From 39137f93c8c399d728201c7e31c97468bfccafbc Mon Sep 17 00:00:00 2001 From: Zhenhao Liu <176368005+LikC1606@users.noreply.github.com> Date: Thu, 3 Dec 2026 23:41:24 +0800 Subject: [PATCH 01/30] Migrate the TheoremOS CLI runtime to Rust --- .dockerignore | 1 + .github/workflows/verify.yml | 107 +- .gitignore | 1 + .prettierignore | 2 +- Cargo.lock | 2424 +++ Cargo.toml | 3 + README.md | 16 +- README.zh-CN.md | 16 +- apps/web/Dockerfile | 33 +- apps/web/agentActions.ts | 2 +- apps/web/auth.ts | 51 +- apps/web/client/CommunityBoard.tsx | 30 +- apps/web/community.ts | 502 +- apps/web/communityTypes.ts | 1 + apps/web/explain.ts | 9 +- apps/web/explanation.ts | 12 + apps/web/explanations.ts | 23 +- apps/web/formalizations.ts | 36 +- apps/web/jobs.ts | 189 +- apps/web/keyVault.ts | 13 + apps/web/nativeDockerOperation.ts | 56 + apps/web/nativeWeb.ts | 82 + apps/web/operations.ts | 2 + apps/web/paperDrafts.ts | 13 +- apps/web/precheck.ts | 16 +- apps/web/queueCounts.ts | 4 + apps/web/runner.ts | 460 +- apps/web/server.ts | 855 +- apps/web/staticFiles.ts | 58 +- apps/web/storage.ts | 8 + apps/web/trajectory.ts | 59 +- apps/web/verification-readme.json | 7 + apps/web/verificationKit.ts | 32 +- apps/web/workbench-assets.json | 70 + apps/web/worker-entrypoint.sh | 18 +- apps/web/worker.ts | 13 +- bin/formalize-help.txt | 26 + bin/math-help.txt | 40 + bin/math.ts | 44 +- bin/theorem-os | 14 + docs/rust-migration.md | 246 + examples/components/README.md | 28 +- package.json | 6 +- resources/auto-library-replay.json | 134 + resources/formalization-replay/preset.json | 321 + resources/lean/ConditionalProjection.lean | 257 + resources/workflow-output.json | 3 + rust/cli/Cargo.toml | 38 + rust/cli/src/auto_library.rs | 145 + rust/cli/src/auto_library/replay.rs | 311 + rust/cli/src/batch.rs | 552 + rust/cli/src/bin/theorem-os-agent.rs | 39 + rust/cli/src/bin/web-funnel.rs | 323 + rust/cli/src/bootstrap.rs | 45 + rust/cli/src/build.rs | 555 + rust/cli/src/check_lean.rs | 422 + rust/cli/src/checkpoint.rs | 176 + rust/cli/src/comparison/experiment.rs | 176 + rust/cli/src/comparison/freshness.rs | 84 + rust/cli/src/comparison/funnel.rs | 327 + rust/cli/src/comparison/knowledge.rs | 70 + rust/cli/src/comparison/mod.rs | 246 + rust/cli/src/comparison/ordinary.rs | 478 + rust/cli/src/comparison/policy.rs | 322 + rust/cli/src/comparison/providers.json | 39 + rust/cli/src/comparison/sample.rs | 112 + rust/cli/src/comparison/sample/manifest.rs | 157 + rust/cli/src/component/contract.rs | 131 + rust/cli/src/component/mod.rs | 134 + rust/cli/src/component/template.rs | 10 + rust/cli/src/continuation/mod.rs | 155 + rust/cli/src/continuation/search.rs | 394 + rust/cli/src/declarations.rs | 352 + rust/cli/src/doctor/mod.rs | 413 + rust/cli/src/doctor/project.rs | 164 + rust/cli/src/doctor/provider.rs | 174 + rust/cli/src/edit/mod.rs | 330 + rust/cli/src/edit/schema.rs | 1 + rust/cli/src/example.rs | 433 + rust/cli/src/finite.rs | 335 + rust/cli/src/first_proof/case.rs | 207 + rust/cli/src/first_proof/form.rs | 415 + rust/cli/src/first_proof/help.txt | 11 + rust/cli/src/first_proof/mod.rs | 294 + rust/cli/src/first_proof/report.rs | 164 + rust/cli/src/formal_eval/help.txt | 22 + rust/cli/src/formal_eval/mod.rs | 145 + rust/cli/src/formal_eval/review.rs | 286 + rust/cli/src/formal_eval/review/legacy.json | 1 + rust/cli/src/formal_eval/review/legacy.rs | 226 + rust/cli/src/formal_eval/review/model.rs | 273 + .../src/formal_eval/review/structured.json | 1 + rust/cli/src/formal_eval/review/structured.rs | 513 + .../formal_eval/review/structured/fidelity.rs | 105 + .../formal_eval/review/structured/stage.rs | 160 + rust/cli/src/formalize/inputs.rs | 169 + rust/cli/src/formalize/mod.rs | 296 + rust/cli/src/formalize/prepare.rs | 329 + rust/cli/src/formalize/replay/compiler.rs | 137 + rust/cli/src/formalize/replay/mod.rs | 348 + .../src/formalize/replay/role-contracts.json | 729 + rust/cli/src/formalize/replay/roles.rs | 148 + rust/cli/src/formalize/resume.rs | 299 + rust/cli/src/informalize/help.txt | 17 + rust/cli/src/informalize/mod.rs | 367 + rust/cli/src/informalize/resume.rs | 115 + rust/cli/src/inspect.rs | 104 + rust/cli/src/kernel_certificate.rs | 805 + rust/cli/src/lean_eval/binding.rs | 189 + rust/cli/src/lean_eval/mod.rs | 434 + rust/cli/src/lean_eval/workspace.rs | 300 + rust/cli/src/lib.rs | 48 + rust/cli/src/list_lean_eval.rs | 712 + rust/cli/src/main.rs | 240 + rust/cli/src/plan_validate.rs | 169 + rust/cli/src/recover.rs | 66 + rust/cli/src/report_flags.rs | 41 + rust/cli/src/research_owner.rs | 199 + rust/cli/src/role_launcher/mod.rs | 83 + rust/cli/src/role_launcher/relay.rs | 158 + rust/cli/src/run.rs | 226 + rust/cli/src/search_lean.rs | 111 + rust/cli/src/seed.rs | 317 + rust/cli/src/startup/direct.rs | 966 ++ rust/cli/src/startup/direct/team_runtime.rs | 875 + rust/cli/src/startup/direct/team_state.rs | 849 + rust/cli/src/startup/lean_task.rs | 89 + rust/cli/src/startup/method.json | 13 + rust/cli/src/startup/mod.rs | 1231 ++ rust/cli/src/startup/replay.rs | 124 + rust/cli/src/startup/request_ledger.rs | 192 + rust/cli/src/startup/responses_relay.rs | 361 + rust/cli/src/startup/tutorial.json | 127 + rust/cli/src/summarize.rs | 617 + rust/cli/src/workflow_host.rs | 59 + rust/cli/tests/checkpoint.rs | 85 + rust/cli/tests/component.rs | 112 + rust/cli/tests/declarations.rs | 172 + rust/cli/tests/finite.rs | 87 + rust/cli/tests/kernel_certificate.rs | 106 + rust/cli/tests/package.rs | 96 + rust/cli/tests/sealed_image.rs | 115 + rust/cli/tests/statement.rs | 237 + rust/cli/tests/summarize-receipts.json | 12 + rust/cli/tests/web_funnel.rs | 115 + rust/lean/Cargo.toml | 19 + .../resources/type-query-application.lean.in | 12 + rust/lean/resources/type-query.lean.in | 13 + rust/lean/resources/unshare-lean.sh | 68 + rust/lean/src/advisory.rs | 398 + rust/lean/src/artifacts.rs | 140 + rust/lean/src/configuration.rs | 216 + rust/lean/src/constraints.rs | 434 + rust/lean/src/declaration_type.rs | 86 + rust/lean/src/declarations.rs | 582 + rust/lean/src/diagnostics.rs | 125 + rust/lean/src/environment.rs | 221 + rust/lean/src/formalization_source.rs | 357 + rust/lean/src/header.rs | 156 + rust/lean/src/health.rs | 270 + rust/lean/src/host_compile.rs | 230 + rust/lean/src/image/custodian.rs | 392 + rust/lean/src/image/custodian/leases.rs | 273 + rust/lean/src/image/holder.rs | 291 + rust/lean/src/image/mod.rs | 89 + rust/lean/src/image/prepare.rs | 491 + rust/lean/src/image/seed.rs | 81 + rust/lean/src/image_cache.rs | 205 + rust/lean/src/lean_eval/history.rs | 50 + rust/lean/src/lean_eval/mod.rs | 238 + rust/lean/src/lease.rs | 37 + rust/lean/src/lib.rs | 349 + rust/lean/src/module_store.rs | 330 + rust/lean/src/offsets.rs | 32 + rust/lean/src/packages.rs | 123 + rust/lean/src/projection_notation.rs | 283 + rust/lean/src/projection_scope.rs | 142 + rust/lean/src/sandbox.rs | 487 + rust/lean/src/sealed.rs | 94 + rust/lean/src/snapshot.rs | 273 + rust/lean/src/sources.rs | 286 + rust/lean/src/tools.rs | 162 + rust/lean/src/type_query.rs | 225 + rust/lean/src/type_worker.rs | 340 + rust/lean/src/verification.rs | 154 + rust/lean/src/worker.rs | 438 + rust/library/Cargo.toml | 28 + rust/library/src/author/interfaces.rs | 196 + rust/library/src/author/mod.rs | 301 + rust/library/src/author/pack.rs | 277 + rust/library/src/author/select.rs | 281 + rust/library/src/auto/build.rs | 253 + rust/library/src/auto/cli.rs | 263 + rust/library/src/auto/cli_profile.rs | 186 + rust/library/src/auto/harness.rs | 260 + rust/library/src/auto/inspect.rs | 177 + rust/library/src/auto/mod.rs | 144 + rust/library/src/auto/pack.rs | 264 + rust/library/src/auto/planner.rs | 96 + rust/library/src/auto/pool.rs | 133 + rust/library/src/auto/prepare.rs | 231 + rust/library/src/auto/replay.rs | 120 + rust/library/src/auto/usage.rs | 256 + rust/library/src/catalog.rs | 448 + rust/library/src/continuation.rs | 479 + .../src/continuation/capture/drafts.rs | 115 + .../src/continuation/capture/guide.txt | 2 + rust/library/src/continuation/capture/mod.rs | 356 + .../library/src/continuation/capture/notes.rs | 140 + rust/library/src/continuation/freeze.rs | 72 + rust/library/src/continuation/history.rs | 219 + rust/library/src/continuation/seed.rs | 205 + .../library/src/continuation/seed_checkout.rs | 267 + .../src/continuation/seed_documents.rs | 134 + rust/library/src/display.rs | 173 + rust/library/src/first_proof.rs | 78 + rust/library/src/formal_eval/cases.rs | 183 + rust/library/src/formal_eval/isolation.rs | 96 + rust/library/src/formal_eval/mod.rs | 216 + rust/library/src/formal_eval/review_state.rs | 213 + .../library/src/formal_eval/role_workspace.rs | 74 + rust/library/src/formal_eval/score.rs | 183 + rust/library/src/formal_eval/structured.rs | 89 + .../src/formal_eval/structured/observation.rs | 100 + .../src/formal_eval/structured/output.rs | 154 + .../library/src/formalization/archive_json.rs | 55 + rust/library/src/formalization/artifact.rs | 121 + rust/library/src/formalization/compilation.rs | 226 + rust/library/src/formalization/context.rs | 211 + rust/library/src/formalization/elaboration.rs | 240 + rust/library/src/formalization/fidelity.rs | 97 + rust/library/src/formalization/mod.rs | 112 + rust/library/src/formalization/plan.rs | 185 + rust/library/src/formalization/queries.json | 1 + .../src/formalization/reference/compare.rs | 279 + .../src/formalization/reference/files.rs | 208 + .../src/formalization/reference/mod.rs | 249 + .../src/formalization/reference/programs.json | 1 + .../src/formalization/reference/report.rs | 247 + .../formalization/report/correspondences.rs | 237 + rust/library/src/formalization/report/mod.rs | 188 + rust/library/src/formalization/report/page.rs | 190 + rust/library/src/formalization/request.rs | 114 + rust/library/src/formalization/retrieval.rs | 261 + rust/library/src/formalization/reviewed.rs | 328 + rust/library/src/formalization/role.rs | 93 + rust/library/src/formalization/run.rs | 171 + rust/library/src/formalization/seed.rs | 143 + rust/library/src/formalization/semantic.rs | 189 + rust/library/src/goal.rs | 620 + rust/library/src/host_release/auto_source.rs | 186 + rust/library/src/host_release/config.rs | 176 + rust/library/src/host_release/coverage.rs | 116 + rust/library/src/host_release/json.rs | 69 + rust/library/src/host_release/legacy.rs | 129 + rust/library/src/host_release/mod.rs | 258 + rust/library/src/host_release/policy.rs | 91 + rust/library/src/host_release/registry.rs | 223 + rust/library/src/hub/archive.rs | 127 + rust/library/src/hub/client.rs | 296 + rust/library/src/hub/export.rs | 400 + rust/library/src/hub/help.txt | 28 + rust/library/src/hub/imports.rs | 302 + rust/library/src/hub/manifest.rs | 273 + rust/library/src/hub/mod.rs | 202 + rust/library/src/hub/sources.rs | 263 + rust/library/src/imo/lakefile.toml.in | 17 + rust/library/src/imo/mod.rs | 389 + rust/library/src/imo/receipt.rs | 124 + rust/library/src/informalization/alignment.rs | 305 + rust/library/src/informalization/evidence.rs | 395 + .../src/informalization/evidence/publish.rs | 122 + rust/library/src/informalization/markdown.rs | 269 + rust/library/src/informalization/mod.rs | 297 + .../src/informalization/report/locations.rs | 147 + .../library/src/informalization/report/mod.rs | 293 + rust/library/src/informalization/roles.rs | 155 + rust/library/src/inspection/artifacts.rs | 245 + rust/library/src/inspection/category.rs | 51 + rust/library/src/inspection/events.rs | 158 + .../src/inspection/markdown/contributions.rs | 335 + .../src/inspection/markdown/cooperative.rs | 391 + rust/library/src/inspection/markdown/mod.rs | 272 + .../library/src/inspection/markdown/report.rs | 206 + .../src/inspection/markdown/scheduling.rs | 182 + rust/library/src/inspection/markdown/team.rs | 322 + rust/library/src/inspection/mod.rs | 120 + .../src/inspection/report/flow/attempts.rs | 188 + .../src/inspection/report/flow/checks.rs | 232 + .../library/src/inspection/report/flow/mod.rs | 352 + rust/library/src/inspection/report/mod.rs | 199 + .../src/inspection/report/progress/mod.rs | 387 + .../src/inspection/report/progress/routes.rs | 222 + .../inspection/report/progress/snapshot.rs | 271 + rust/library/src/inspection/report/tasks.rs | 200 + .../library/src/inspection/report/team/mod.rs | 195 + .../src/inspection/report/team/overview.rs | 405 + rust/library/src/inspection/report/usage.rs | 160 + rust/library/src/inspection/report/workers.rs | 118 + rust/library/src/io.rs | 130 + rust/library/src/knowledge/accepted.rs | 353 + rust/library/src/knowledge/archive.rs | 463 + rust/library/src/knowledge/authorized.rs | 110 + rust/library/src/knowledge/build.rs | 226 + rust/library/src/knowledge/cli.rs | 219 + .../src/knowledge/enrichment/binding.rs | 226 + .../src/knowledge/enrichment/collect.rs | 517 + .../src/knowledge/enrichment/collectors.json | 1 + .../src/knowledge/enrichment/discovery.rs | 124 + .../src/knowledge/enrichment/exports.rs | 192 + rust/library/src/knowledge/enrichment/mod.rs | 103 + .../src/knowledge/enrichment/operation.rs | 152 + .../library/src/knowledge/enrichment/query.rs | 182 + .../enrichment/query/dependencies.lean.in | 19 + .../knowledge/enrichment/query/direct.lean.in | 10 + .../enrichment/query/expected.lean.in | 13 + .../src/knowledge/enrichment/reports.rs | 319 + .../src/knowledge/enrichment/source.rs | 136 + .../src/knowledge/enrichment/validate.rs | 356 + rust/library/src/knowledge/findings.rs | 98 + rust/library/src/knowledge/help.txt | 50 + rust/library/src/knowledge/installed.rs | 63 + rust/library/src/knowledge/mod.rs | 151 + rust/library/src/knowledge/pages.rs | 370 + rust/library/src/knowledge/pages/relations.rs | 275 + rust/library/src/knowledge/runs/admission.rs | 294 + rust/library/src/knowledge/runs/artifacts.rs | 331 + rust/library/src/knowledge/runs/demand.rs | 169 + rust/library/src/knowledge/runs/findings.rs | 299 + rust/library/src/knowledge/runs/mod.rs | 299 + rust/library/src/knowledge/runs/routes.rs | 318 + rust/library/src/knowledge/runs/tasks.rs | 138 + rust/library/src/knowledge/runs/team.rs | 285 + .../src/knowledge/runs/team/contributions.rs | 351 + rust/library/src/knowledge/schema.json | 1 + rust/library/src/knowledge/schema.rs | 271 + rust/library/src/lean_eval/contract.rs | 126 + rust/library/src/lean_eval/installed.rs | 213 + rust/library/src/lean_eval/mod.rs | 205 + rust/library/src/lean_task/environments.json | 157 + rust/library/src/lean_task/mod.rs | 408 + rust/library/src/lean_task/prepare.rs | 316 + rust/library/src/lib.rs | 289 + rust/library/src/module_plan.rs | 138 + rust/library/src/packing/cli.rs | 125 + rust/library/src/packing/mod.rs | 434 + rust/library/src/packing/prune.rs | 177 + rust/library/src/problem.rs | 30 + rust/library/src/recovery/checkout.rs | 253 + rust/library/src/recovery/history.rs | 98 + rust/library/src/recovery/mod.rs | 304 + rust/library/src/recovery/recheck.rs | 526 + .../src/recovery/recheck/declarations.rs | 116 + rust/library/src/recovery/recheck/execute.rs | 852 + .../src/recovery/recheck/execute/isolated.rs | 134 + .../src/recovery/recheck/execute/seed.rs | 508 + .../recovery/recheck/execute/seed/publish.rs | 105 + rust/library/src/recovery/snapshot.rs | 130 + rust/library/src/search.rs | 614 + rust/library/src/search/history.rs | 441 + rust/library/src/stored_zip.rs | 54 + rust/library/src/team_research.rs | 150 + rust/library/src/terms.rs | 247 + rust/library/src/tutorial.rs | 43 + rust/library/src/vocabulary.rs | 2 + rust/process/Cargo.toml | 24 + rust/process/src/archive.rs | 192 + rust/process/src/budgets.rs | 119 + rust/process/src/codex_stdio.rs | 237 + rust/process/src/continuation_seed.rs | 163 + rust/process/src/diagnostic_session.rs | 46 + rust/process/src/environment.rs | 26 + rust/process/src/evaluation.rs | 284 + rust/process/src/evidence.rs | 66 + rust/process/src/formalization_audit.rs | 304 + .../src/formalization_audit/isolation.rs | 35 + rust/process/src/formalization_compiler.rs | 100 + rust/process/src/git.rs | 45 + rust/process/src/image_cache.rs | 58 + rust/process/src/informalization.rs | 69 + rust/process/src/lean_diagnostics.rs | 5 + rust/process/src/lean_sources.rs | 333 + rust/process/src/lease.rs | 86 + rust/process/src/lib.rs | 196 + rust/process/src/library.rs | 630 + rust/process/src/proof_projection.rs | 358 + rust/process/src/research.rs | 61 + rust/process/src/response_usage.rs | 38 + rust/process/src/resume.rs | 128 + rust/process/src/retrieval.rs | 63 + rust/process/src/retry.rs | 142 + rust/process/src/rpc.rs | 177 + rust/process/src/run_options.rs | 80 + rust/process/src/sub2api_auth.rs | 48 + rust/process/src/sub2api_http.rs | 86 + rust/process/src/team_control.rs | 90 + rust/process/src/turn.rs | 155 + rust/retrieval/Cargo.toml | 20 + rust/retrieval/src/additive.rs | 72 + rust/retrieval/src/aliases.rs | 76 + rust/retrieval/src/cache.rs | 172 + rust/retrieval/src/concepts.rs | 356 + rust/retrieval/src/declarations.rs | 185 + rust/retrieval/src/files.rs | 118 + rust/retrieval/src/goal.rs | 266 + rust/retrieval/src/headers.rs | 8 + rust/retrieval/src/installed.rs | 274 + rust/retrieval/src/lib.rs | 464 + rust/retrieval/src/notation.rs | 344 + rust/retrieval/src/packet.rs | 138 + rust/retrieval/src/premises.rs | 213 + rust/retrieval/src/query.rs | 137 + rust/retrieval/src/search.rs | 342 + rust/retrieval/src/shape.rs | 362 + rust/retrieval/src/specialization.rs | 128 + rust/retrieval/src/syntax.rs | 102 + rust/solver/Cargo.toml | 20 + rust/solver/src/archive/diagnostic.rs | 56 + rust/solver/src/archive/mod.rs | 312 + rust/solver/src/archive/schema.json | 1 + rust/solver/src/budget.rs | 132 + rust/solver/src/codex_child.rs | 248 + rust/solver/src/codex_child/namespace.rs | 103 + rust/solver/src/codex_dispatch.rs | 249 + rust/solver/src/codex_frames.rs | 60 + rust/solver/src/codex_session.rs | 380 + rust/solver/src/codex_session/team.rs | 549 + rust/solver/src/codex_stdio.rs | 146 + rust/solver/src/direct-instructions.txt | 14 + rust/solver/src/direct_context.rs | 305 + rust/solver/src/direct_context/permissions.rs | 367 + rust/solver/src/evaluation.rs | 37 + rust/solver/src/git.rs | 138 + rust/solver/src/lib.rs | 435 + rust/solver/src/plan/decisions.rs | 310 + rust/solver/src/plan/families.rs | 137 + rust/solver/src/plan/goal_path.rs | 410 + rust/solver/src/plan/graph.rs | 507 + rust/solver/src/plan/mod.rs | 228 + rust/solver/src/plan/patch.rs | 176 + rust/solver/src/plan/routes.rs | 124 + rust/solver/src/problem.rs | 417 + rust/solver/src/projection/assignment.rs | 142 + rust/solver/src/projection/changes.rs | 188 + rust/solver/src/projection/closure.rs | 61 + rust/solver/src/projection/fingerprints.rs | 115 + rust/solver/src/projection/lookup.rs | 238 + rust/solver/src/projection/lookup/graph.rs | 437 + .../solver/src/projection/lookup/instances.rs | 160 + rust/solver/src/projection/lookup/snapshot.rs | 448 + .../src/projection/lookup/snapshot/files.rs | 158 + rust/solver/src/projection/merge.rs | 488 + rust/solver/src/projection/mod.rs | 196 + rust/solver/src/projection/opens.rs | 249 + rust/solver/src/projection/render.rs | 152 + rust/solver/src/projection/syntax.rs | 139 + rust/solver/src/projection/target.rs | 105 + rust/solver/src/proof.rs | 527 + rust/solver/src/proof/checkpoint.rs | 343 + rust/solver/src/proof/export.lean | 26 + rust/solver/src/proof/external.rs | 124 + rust/solver/src/proof/imports.rs | 113 + rust/solver/src/proof/kernel.rs | 374 + rust/solver/src/proof/layout.lean | 31 + rust/solver/src/proof/packages.rs | 417 + rust/solver/src/proof/packages/layout.rs | 139 + rust/solver/src/proof/replay.lean | 61 + rust/solver/src/receipts.rs | 314 + rust/solver/src/research.rs | 138 + rust/solver/src/response_usage.rs | 280 + rust/solver/src/responses_admission.rs | 518 + rust/solver/src/statement.rs | 377 + rust/solver/src/statement/packages.rs | 401 + rust/solver/src/sub2api_auth.rs | 126 + rust/solver/src/sub2api_http.rs | 113 + rust/solver/src/team.rs | 291 + rust/solver/src/team_control.rs | 426 + rust/solver/tests/codex_session.rs | 384 + rust/solver/tests/codex_stdio.rs | 90 + rust/solver/tests/direct_context.rs | 82 + rust/solver/tests/git.rs | 109 + rust/solver/tests/proof.rs | 558 + rust/supervision/Cargo.toml | 12 + rust/supervision/src/capture.rs | 309 + rust/supervision/src/group.rs | 203 + rust/supervision/src/lib.rs | 5 + rust/supervision/src/namespace.rs | 301 + rust/supervision/src/session.rs | 214 + rust/web/Cargo.toml | 40 + rust/web/community-limits.json | 11 + rust/web/src/bin/theoremos-web-assets.rs | 359 + rust/web/src/bin/theoremos-web-check.rs | 140 + .../src/bin/theoremos-web-docker/language.rs | 168 + rust/web/src/bin/theoremos-web-docker/main.rs | 472 + .../web/src/bin/theoremos-web-docker/paper.rs | 110 + .../src/bin/theoremos-web-docker/precheck.rs | 171 + .../src/bin/theoremos-web/admin_accounts.rs | 346 + .../src/bin/theoremos-web/admin_allowlist.rs | 141 + .../src/bin/theoremos-web/auth_challenges.rs | 462 + rust/web/src/bin/theoremos-web/auth_mail.rs | 71 + rust/web/src/bin/theoremos-web/auth_routes.rs | 635 + .../bin/theoremos-web/community_account.rs | 317 + .../src/bin/theoremos-web/community_routes.rs | 294 + .../src/bin/theoremos-web/community_worker.rs | 187 + rust/web/src/bin/theoremos-web/identity.rs | 547 + .../src/bin/theoremos-web/knowledge_reads.rs | 240 + .../web/src/bin/theoremos-web/login_return.rs | 234 + rust/web/src/bin/theoremos-web/main.rs | 1233 ++ .../web/src/bin/theoremos-web/module_plans.rs | 228 + rust/web/src/bin/theoremos-web/operations.rs | 114 + rust/web/src/bin/theoremos-web/product.rs | 112 + .../src/bin/theoremos-web/proof_download.rs | 316 + rust/web/src/bin/theoremos-web/run_archive.rs | 214 + rust/web/src/bin/theoremos-web/run_list.rs | 261 + .../src/bin/theoremos-web/run_observations.rs | 166 + rust/web/src/bin/theoremos-web/run_reads.rs | 364 + rust/web/src/bin/theoremos-web/run_write.rs | 117 + .../src/bin/theoremos-web/session_handlers.rs | 549 + .../web/src/bin/theoremos-web/session_http.rs | 92 + rust/web/src/bin/theoremos-web/trajectory.rs | 298 + .../src/bin/theoremos-web/trajectory_index.rs | 510 + rust/web/src/bin/theoremos-web/vault.rs | 125 + .../bin/theoremos-web/workspace_catalog.rs | 89 + rust/web/src/community.rs | 436 + rust/web/src/community_admission.rs | 382 + rust/web/src/community_admission_addon.rs | 63 + rust/web/src/community_check.rs | 18 + rust/web/src/community_lock.rs | 9 + rust/web/src/lib.rs | 171 + rust/web/src/record_file.rs | 36 + rust/web/src/run_lifecycle.rs | 238 + rust/web/src/static_files.rs | 283 + rust/web/src/worker_image.rs | 72 + rust/web/trajectory.json | 57 + scripts/build-agent-tools.ts | 35 +- scripts/build-web.ts | 240 +- scripts/build.ts | 17 +- scripts/generate-native-archive-schema.ts | 117 + .../generate-native-direct-instructions.ts | 40 + ...rate-native-evaluation-review-contracts.ts | 56 + .../generate-native-formalization-queries.ts | 36 + .../generate-native-knowledge-collectors.ts | 16 + scripts/generate-native-knowledge-schema.ts | 422 + scripts/generate-native-reference-queries.ts | 89 + scripts/generate-native-task-environments.ts | 26 + scripts/generate-native-tutorial-contract.ts | 62 + scripts/generate-web-library-search.ts | 9 +- scripts/mathematics/agentTools.ts | 14 +- scripts/mathematics/autoLibrary.ts | 40 +- scripts/mathematics/autoLibraryReplay.ts | 369 +- scripts/mathematics/component.ts | 76 +- .../mathematics/continuationSeedCommand.ts | 35 + scripts/mathematics/formalize.ts | 29 +- scripts/mathematics/runExample.ts | 2 +- scripts/mathematics/runMathProof.ts | 39 +- scripts/mathematics/seedContinuation.ts | 36 +- scripts/test-native-archive.ts | 46 + scripts/test-native-auto-library.ts | 213 + scripts/test-native-build.ts | 287 + scripts/test-native-check-lean.ts | 118 + scripts/test-native-continuation.ts | 173 + scripts/test-native-doctor.ts | 141 + scripts/test-native-edit.ts | 160 + scripts/test-native-eval-bootstrap.ts | 188 + scripts/test-native-health.ts | 156 + scripts/test-native-imo.ts | 77 + scripts/test-native-informalize.ts | 80 + scripts/test-native-knowledge-pages.ts | 219 + scripts/test-native-knowledge.ts | 255 + scripts/test-native-lean-eval.ts | 90 + scripts/test-native-lean-source.ts | 96 + scripts/test-native-library-catalog.ts | 286 + scripts/test-native-library-pack.ts | 188 + scripts/test-native-library.ts | 192 + scripts/test-native-plan.ts | 152 + scripts/test-native-process.ts | 201 + scripts/test-native-retrieval.ts | 274 + scripts/test-native-run-options.ts | 181 + scripts/test-native-solver.ts | 172 + scripts/test-native-startup.ts | 1193 ++ scripts/test-native-sub2api.ts | 281 + scripts/test-native-task-bootstrap.ts | 81 + scripts/test-native-team.ts | 267 + scripts/test-native-web.ts | 1557 ++ src/math/autoLibrary.ts | 93 +- src/math/autoLibraryPlanner.ts | 12 +- src/math/formalization.ts | 22 +- src/math/formalizationEvaluation.ts | 25 +- src/math/formalizationReference.ts | 22 +- src/math/formalizationReferenceV3.ts | 2 +- src/math/formalizationReferenceV4.ts | 2 +- src/math/formalizationReview.ts | 10 + src/math/formalizationReviewV2.ts | 43 +- src/math/formalizationRoleWorkspace.ts | 63 + src/math/formalizationSemanticReview.ts | 12 + src/math/formalizationSource.ts | 4 + src/math/frozenLibrarySearchData.json | 14018 +++++++++++++++ src/math/frozenLibrarySearchData.ts | 14021 +--------------- src/math/informalization.ts | 106 +- src/math/informalizationLabels.json | 62 + src/math/leanDeclarationType.ts | 51 + src/math/leanDiagnosticMessages.ts | 2 + src/math/leanDiagnostics.ts | 192 +- src/math/leanEvalAdapter.ts | 76 +- src/math/leanEvalBenchmark.ts | 2 + src/math/leanEvalBootstrap.ts | 8 + src/math/leanKnowledgeEnrichment.ts | 3 + src/math/leanModuleBuild.ts | 8 + src/math/leanProbeSnapshot.ts | 7 +- src/math/leanReferences.ts | 4 + src/math/leanSource.ts | 15 +- src/math/leanStatementContext.ts | 5 + src/math/leanSyntax.ts | 52 +- src/math/leanTask.ts | 27 +- src/math/leanTaskEnvironment.ts | 6 +- src/math/leanToolchainReadiness.ts | 17 +- src/math/leanTypeDiagnostics.ts | 3 + src/math/libraryEffectivePack.ts | 3 + src/math/libraryHostConfig.ts | 46 +- src/math/libraryLegacyBinding.ts | 29 +- src/math/libraryPacks.ts | 5 + src/math/libraryRelease.ts | 40 +- src/math/mathConstructionSources.ts | 5 + src/math/mathGit.ts | 32 +- src/math/mathProcess.ts | 61 +- src/math/mathProcessIdentity.ts | 3 + src/math/mathProofEnvironment.ts | 43 +- src/math/mathProofEnvironmentCache.ts | 11 + src/math/mathProofEnvironmentSeed.ts | 8 + src/math/mathProofSourcePolicy.ts | 3 + src/math/mathRetrievalCorpus.ts | 37 +- src/math/mathRuntimeEnvironment.ts | 46 +- src/math/mathRuntimeIo.ts | 46 +- src/math/mathSearchConceptData.json | 138 + src/math/mathSearchConcepts.ts | 42 +- src/math/mathlibTheoremAliasData.json | 259 + src/math/mathlibTheoremAliases.ts | 164 +- src/math/nativeProcess.ts | 986 ++ src/math/runtimeEnvironmentKeys.json | 39 + src/math/verifier.ts | 389 +- src/runtime/cliConfiguration.ts | 26 +- src/runtime/codexSession.ts | 546 +- src/runtime/codexTurnEvidence.ts | 31 + src/runtime/formalizationRelay.ts | 305 +- src/runtime/formalizationSandbox.ts | 28 +- src/runtime/nativeAgentControl.ts | 74 +- src/runtime/responsesAdmissionReference.ts | 245 + src/runtime/sub2apiHttp.ts | 62 + src/solver/agentTeam.ts | 53 +- src/solver/agentTeamBudget.ts | 36 + src/solver/agentTeamNative.ts | 295 +- src/solver/agentTeamProof.ts | 2 +- src/solver/agentTeamResearch.ts | 5 + src/solver/agentTeamWorkspace.ts | 4 + src/solver/archive.ts | 33 +- src/solver/autoLibrary.ts | 234 +- src/solver/autoLibraryControl.ts | 69 + src/solver/componentTemplate.ts | 91 +- src/solver/conditionalProjection.ts | 264 +- src/solver/continuationInput.ts | 10 + src/solver/continuationSeed.ts | 3 +- src/solver/contributionFlow.ts | 19 +- src/solver/cooperativeProof.ts | 619 +- src/solver/declarationArtifacts.ts | 41 +- src/solver/evaluation.ts | 101 +- src/solver/formalization.ts | 231 +- src/solver/formalizationAudit.ts | 135 +- src/solver/formalizationElaboration.ts | 317 +- src/solver/formalizationReview.ts | 69 +- src/solver/formalizationReviewIsolation.ts | 15 + src/solver/formalizationReviewV2.ts | 151 +- src/solver/informalization.ts | 2 +- src/solver/inspection.ts | 201 +- src/solver/libraryCatalog.ts | 9 + src/solver/modules/context.ts | 6 +- src/solver/modules/evidence.ts | 72 +- src/solver/modules/index.ts | 11 + src/solver/modules/search.ts | 46 +- src/solver/problem.ts | 24 + src/solver/projectionNotation.ts | 6 + src/solver/proofReferences.ts | 133 +- src/solver/proofReuse.ts | 34 + src/solver/recovery.ts | 86 +- src/solver/research.ts | 653 +- src/solver/researchLoop.ts | 57 + src/solver/researchOwner.ts | 41 + src/solver/researchToolGuide.ts | 4 +- src/solver/run.ts | 276 +- src/solver/runOptions.ts | 326 + src/solver/singleContinuationSeed.ts | 190 +- src/solver/skillProofLifecycle.ts | 82 +- src/solver/storedRunInspection.ts | 46 +- src/solver/taskConnections.ts | 2 + src/solver/taskDeclarationStart.ts | 82 + src/solver/taskOpenBindings.ts | 132 + src/solver/taskProjection.ts | 11 + src/solver/taskProjectionFile.ts | 66 + src/solver/taskSourceSnapshot.ts | 81 + src/solver/taskTypeContract.ts | 2 + src/solver/teamMemberSchedule.ts | 26 + src/solver/theoremKnowledgeAccepted.ts | 4 +- src/solver/theoremKnowledgeAuthorization.ts | 93 +- src/solver/theoremKnowledgeEnrichment.ts | 44 +- src/solver/theoremKnowledgeRuns.ts | 3 +- src/solver/theoremKnowledgeSearch.ts | 15 +- src/solver/theoremKnowledgeStore.ts | 31 +- src/solver/usageBudget.ts | 25 + src/solver/workerProject.ts | 11 + src/solver/workflowOutput.ts | 4 +- tests/agentTeamNativeControl.test.ts | 54 + tests/agentTeamNativeLifecycle.test.ts | 8 + tests/agentTeamProof.test.ts | 26 +- tests/agentTeamResearch.test.ts | 26 +- tests/agentTeamSourceRecovery.test.ts | 8 + tests/agentTeamWorkspace.test.ts | 36 +- tests/agentTools.test.ts | 91 +- tests/autoLibrary.test.ts | 69 +- tests/autoLibraryDemand.test.ts | 32 + tests/autoLibraryHost.test.ts | 188 +- tests/autoLibraryUsage.test.ts | 37 +- tests/codexIsolatedChild.test.ts | 114 + tests/codexSessionAgentControl.test.ts | 48 +- tests/codexSessionLifecycle.test.ts | 1 + tests/comparisonHarness.test.ts | 9 +- tests/comparisonLeanTask.test.ts | 2 + tests/comparisonReportSnapshot.test.ts | 49 +- tests/comparisonSkillBaseline.test.ts | 3 + tests/componentTemplate.test.ts | 105 +- tests/conditionalProjectionElaborator.test.ts | 10 +- tests/consumerConnections.test.ts | 1 + tests/contributionFlow.test.ts | 35 +- tests/declarationArtifacts.test.ts | 2 +- tests/directFormalizationEvidence.test.ts | 12 +- tests/directFormalizationWorkflow.test.ts | 149 +- tests/evaluatorExecution.test.ts | 60 +- tests/exactSourceIntegration.test.ts | 8 + tests/firstProof.test.ts | 69 +- tests/firstProofAutomation.test.ts | 167 +- tests/firstProofCli.test.ts | 32 +- tests/fixtures/native-team-peer.py | 161 + tests/formalization.test.ts | 10 +- tests/formalizationAdjudication.test.ts | 30 + tests/formalizationAudit.test.ts | 39 +- tests/formalizationCompiledCandidate.test.ts | 10 +- tests/formalizationElaboration.test.ts | 10 +- tests/formalizationEvaluation.test.ts | 87 +- tests/formalizationFidelityReference.test.ts | 1 + tests/formalizationFidelityWorkflow.test.ts | 10 + tests/formalizationIdentityReference.test.ts | 1 + ...ormalizationLibrarySymbolsWorkflow.test.ts | 13 +- tests/formalizationRecovery.test.ts | 28 + tests/formalizationReference.test.ts | 1 + tests/formalizationReferenceLibrary.test.ts | 1 + ...malizationReferenceV4Compatibility.test.ts | 46 + tests/formalizationRelay.test.ts | 272 +- tests/formalizationRetrievalWorkflow.test.ts | 12 +- tests/formalizationReview.test.ts | 47 + tests/formalizationReviewCli.test.ts | 122 +- tests/formalizationReviewIsolation.test.ts | 33 +- tests/formalizationReviewV2.test.ts | 1 + tests/formalizationReviewV2Runner.test.ts | 283 +- tests/formalizationSandbox.test.ts | 114 +- tests/formalizationSource.test.ts | 19 +- tests/formalizationWorkflow.test.ts | 24 +- tests/formalizeCli.test.ts | 120 + tests/helpers/firstProofNative.ts | 59 + tests/helpers/historicalReportNative.ts | 24 + tests/helpers/inspectionMarkdownNative.ts | 61 + tests/helpers/nativeArchiveParity.cjs | 66 + tests/helpers/nativeDirectContext.ts | 86 + tests/helpers/nativeKnowledgeImport.ts | 44 + tests/helpers/nativeReferenceAddon.ts | 10 + tests/helpers/semanticReviewIsolation.ts | 34 + tests/huggingMathBundle.test.ts | 125 +- tests/huggingMathClient.test.ts | 37 +- tests/huggingMathImports.test.ts | 39 +- tests/informalization.test.ts | 107 + tests/informalizationLean.test.ts | 10 +- tests/informalizeCli.test.ts | 8 + tests/inspection.test.ts | 52 +- tests/leanDeclarationIdentity.test.ts | 10 +- tests/leanDiagnosticCapture.test.ts | 10 +- tests/leanDiagnostics.test.ts | 7 + tests/leanEvalBenchmark.test.ts | 10 +- tests/leanEvalBootstrap.test.ts | 8 + tests/leanKnowledgeEnrichment.test.ts | 8 + tests/leanLocalDependencies.test.ts | 7 + tests/leanModuleBuild.test.ts | 39 +- tests/leanProbeSnapshot.test.ts | 10 +- tests/leanReferences.test.ts | 1 + tests/leanSource.test.ts | 10 +- tests/leanSyntax.test.ts | 1 + tests/leanTask.test.ts | 10 +- tests/leanToolchainNative.test.ts | 66 + tests/leanTypeDiagnostics.test.ts | 18 + tests/leanTypeDiagnosticsEnvironment.test.ts | 8 + tests/leanTypeDiagnosticsSealed.test.ts | 165 +- tests/libraryEffectivePack.test.ts | 10 +- tests/libraryHostConfig.test.ts | 8 + tests/libraryLegacyBinding.test.ts | 8 + tests/libraryPacks.test.ts | 10 +- tests/mathBatch.test.ts | 19 +- tests/mathProofEnvironment.test.ts | 8 + tests/mathProofEnvironmentSeed.test.ts | 8 + tests/mathProofLease.test.ts | 18 + tests/mathRetrievalCorpus.test.ts | 78 +- tests/mathRuntimeEnvironment.test.ts | 10 +- tests/moduleExperiment.test.ts | 15 +- tests/nativeFormalizationCompiler.test.ts | 92 + tests/obligationProgress.test.ts | 8 +- tests/projectionDependencyReview.test.ts | 10 +- tests/projectionNotation.test.ts | 22 +- tests/proofReuseEnvironment.test.ts | 10 +- tests/putnamSample.test.ts | 80 +- tests/recovery.test.ts | 182 +- tests/responseUsageObserver.test.ts | 65 + tests/singleContinuationSeed.test.ts | 295 +- tests/skillProcessRecovery.test.ts | 19 +- tests/solver.test.ts | 32 +- tests/solverBatchAttribution.test.ts | 7 + tests/solverCompactProjection.test.ts | 8 + tests/solverContext.test.ts | 1 + tests/solverProgress.test.ts | 16 +- tests/solverSourceRecovery.test.ts | 8 + tests/sourceContextComments.test.ts | 10 +- tests/storedRunInspection.test.ts | 57 +- tests/taskConditionalUniverses.test.ts | 10 +- tests/taskSourceConditionalContext.test.ts | 10 +- tests/taskSourceImplicitInstances.test.ts | 10 +- tests/taskSourceMacroProjection.test.ts | 10 +- tests/taskSourceNotationContext.test.ts | 10 +- tests/taskSourceNotationHints.test.ts | 10 +- tests/taskSourceProjection.test.ts | 34 +- tests/theoremKnowledgeAuthorization.test.ts | 14 +- tests/theoremKnowledgeEnrichment.test.ts | 25 +- tests/theoremKnowledgeEnrichmentCli.test.ts | 71 +- tests/theoremKnowledgeFindings.test.ts | 2 +- tests/theoremKnowledgeRuns.test.ts | 2 +- tests/verifierLeaseTimeout.test.ts | 1 + tests/verifierModuleBuild.test.ts | 1 + tests/verifierSealedEnvironmentCache.test.ts | 8 + tests/verifierToolIdentity.test.ts | 10 +- tests/webAgentActions.test.ts | 119 +- tests/webAuthPolicy.test.ts | 25 + tests/webCommunity.test.ts | 192 + tests/webExplanation.test.ts | 3 +- tests/webFonts.test.ts | 5 +- tests/webPaperRunner.test.ts | 63 + tests/webRunner.test.ts | 221 +- tests/webStaticFiles.test.ts | 60 +- 850 files changed, 148106 insertions(+), 19589 deletions(-) create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 apps/web/nativeDockerOperation.ts create mode 100644 apps/web/nativeWeb.ts create mode 100644 apps/web/queueCounts.ts create mode 100644 apps/web/verification-readme.json create mode 100644 apps/web/workbench-assets.json create mode 100644 bin/formalize-help.txt create mode 100644 bin/math-help.txt create mode 100755 bin/theorem-os create mode 100644 docs/rust-migration.md create mode 100644 resources/auto-library-replay.json create mode 100644 resources/formalization-replay/preset.json create mode 100644 resources/lean/ConditionalProjection.lean create mode 100644 resources/workflow-output.json create mode 100644 rust/cli/Cargo.toml create mode 100644 rust/cli/src/auto_library.rs create mode 100644 rust/cli/src/auto_library/replay.rs create mode 100644 rust/cli/src/batch.rs create mode 100644 rust/cli/src/bin/theorem-os-agent.rs create mode 100644 rust/cli/src/bin/web-funnel.rs create mode 100644 rust/cli/src/bootstrap.rs create mode 100644 rust/cli/src/build.rs create mode 100644 rust/cli/src/check_lean.rs create mode 100644 rust/cli/src/checkpoint.rs create mode 100644 rust/cli/src/comparison/experiment.rs create mode 100644 rust/cli/src/comparison/freshness.rs create mode 100644 rust/cli/src/comparison/funnel.rs create mode 100644 rust/cli/src/comparison/knowledge.rs create mode 100644 rust/cli/src/comparison/mod.rs create mode 100644 rust/cli/src/comparison/ordinary.rs create mode 100644 rust/cli/src/comparison/policy.rs create mode 100644 rust/cli/src/comparison/providers.json create mode 100644 rust/cli/src/comparison/sample.rs create mode 100644 rust/cli/src/comparison/sample/manifest.rs create mode 100644 rust/cli/src/component/contract.rs create mode 100644 rust/cli/src/component/mod.rs create mode 100644 rust/cli/src/component/template.rs create mode 100644 rust/cli/src/continuation/mod.rs create mode 100644 rust/cli/src/continuation/search.rs create mode 100644 rust/cli/src/declarations.rs create mode 100644 rust/cli/src/doctor/mod.rs create mode 100644 rust/cli/src/doctor/project.rs create mode 100644 rust/cli/src/doctor/provider.rs create mode 100644 rust/cli/src/edit/mod.rs create mode 100644 rust/cli/src/edit/schema.rs create mode 100644 rust/cli/src/example.rs create mode 100644 rust/cli/src/finite.rs create mode 100644 rust/cli/src/first_proof/case.rs create mode 100644 rust/cli/src/first_proof/form.rs create mode 100644 rust/cli/src/first_proof/help.txt create mode 100644 rust/cli/src/first_proof/mod.rs create mode 100644 rust/cli/src/first_proof/report.rs create mode 100644 rust/cli/src/formal_eval/help.txt create mode 100644 rust/cli/src/formal_eval/mod.rs create mode 100644 rust/cli/src/formal_eval/review.rs create mode 100644 rust/cli/src/formal_eval/review/legacy.json create mode 100644 rust/cli/src/formal_eval/review/legacy.rs create mode 100644 rust/cli/src/formal_eval/review/model.rs create mode 100644 rust/cli/src/formal_eval/review/structured.json create mode 100644 rust/cli/src/formal_eval/review/structured.rs create mode 100644 rust/cli/src/formal_eval/review/structured/fidelity.rs create mode 100644 rust/cli/src/formal_eval/review/structured/stage.rs create mode 100644 rust/cli/src/formalize/inputs.rs create mode 100644 rust/cli/src/formalize/mod.rs create mode 100644 rust/cli/src/formalize/prepare.rs create mode 100644 rust/cli/src/formalize/replay/compiler.rs create mode 100644 rust/cli/src/formalize/replay/mod.rs create mode 100644 rust/cli/src/formalize/replay/role-contracts.json create mode 100644 rust/cli/src/formalize/replay/roles.rs create mode 100644 rust/cli/src/formalize/resume.rs create mode 100644 rust/cli/src/informalize/help.txt create mode 100644 rust/cli/src/informalize/mod.rs create mode 100644 rust/cli/src/informalize/resume.rs create mode 100644 rust/cli/src/inspect.rs create mode 100644 rust/cli/src/kernel_certificate.rs create mode 100644 rust/cli/src/lean_eval/binding.rs create mode 100644 rust/cli/src/lean_eval/mod.rs create mode 100644 rust/cli/src/lean_eval/workspace.rs create mode 100644 rust/cli/src/lib.rs create mode 100644 rust/cli/src/list_lean_eval.rs create mode 100644 rust/cli/src/main.rs create mode 100644 rust/cli/src/plan_validate.rs create mode 100644 rust/cli/src/recover.rs create mode 100644 rust/cli/src/report_flags.rs create mode 100644 rust/cli/src/research_owner.rs create mode 100644 rust/cli/src/role_launcher/mod.rs create mode 100644 rust/cli/src/role_launcher/relay.rs create mode 100644 rust/cli/src/run.rs create mode 100644 rust/cli/src/search_lean.rs create mode 100644 rust/cli/src/seed.rs create mode 100644 rust/cli/src/startup/direct.rs create mode 100644 rust/cli/src/startup/direct/team_runtime.rs create mode 100644 rust/cli/src/startup/direct/team_state.rs create mode 100644 rust/cli/src/startup/lean_task.rs create mode 100644 rust/cli/src/startup/method.json create mode 100644 rust/cli/src/startup/mod.rs create mode 100644 rust/cli/src/startup/replay.rs create mode 100644 rust/cli/src/startup/request_ledger.rs create mode 100644 rust/cli/src/startup/responses_relay.rs create mode 100644 rust/cli/src/startup/tutorial.json create mode 100644 rust/cli/src/summarize.rs create mode 100644 rust/cli/src/workflow_host.rs create mode 100644 rust/cli/tests/checkpoint.rs create mode 100644 rust/cli/tests/component.rs create mode 100644 rust/cli/tests/declarations.rs create mode 100644 rust/cli/tests/finite.rs create mode 100644 rust/cli/tests/kernel_certificate.rs create mode 100644 rust/cli/tests/package.rs create mode 100644 rust/cli/tests/sealed_image.rs create mode 100644 rust/cli/tests/statement.rs create mode 100644 rust/cli/tests/summarize-receipts.json create mode 100644 rust/cli/tests/web_funnel.rs create mode 100644 rust/lean/Cargo.toml create mode 100644 rust/lean/resources/type-query-application.lean.in create mode 100644 rust/lean/resources/type-query.lean.in create mode 100644 rust/lean/resources/unshare-lean.sh create mode 100644 rust/lean/src/advisory.rs create mode 100644 rust/lean/src/artifacts.rs create mode 100644 rust/lean/src/configuration.rs create mode 100644 rust/lean/src/constraints.rs create mode 100644 rust/lean/src/declaration_type.rs create mode 100644 rust/lean/src/declarations.rs create mode 100644 rust/lean/src/diagnostics.rs create mode 100644 rust/lean/src/environment.rs create mode 100644 rust/lean/src/formalization_source.rs create mode 100644 rust/lean/src/header.rs create mode 100644 rust/lean/src/health.rs create mode 100644 rust/lean/src/host_compile.rs create mode 100644 rust/lean/src/image/custodian.rs create mode 100644 rust/lean/src/image/custodian/leases.rs create mode 100644 rust/lean/src/image/holder.rs create mode 100644 rust/lean/src/image/mod.rs create mode 100644 rust/lean/src/image/prepare.rs create mode 100644 rust/lean/src/image/seed.rs create mode 100644 rust/lean/src/image_cache.rs create mode 100644 rust/lean/src/lean_eval/history.rs create mode 100644 rust/lean/src/lean_eval/mod.rs create mode 100644 rust/lean/src/lease.rs create mode 100644 rust/lean/src/lib.rs create mode 100644 rust/lean/src/module_store.rs create mode 100644 rust/lean/src/offsets.rs create mode 100644 rust/lean/src/packages.rs create mode 100644 rust/lean/src/projection_notation.rs create mode 100644 rust/lean/src/projection_scope.rs create mode 100644 rust/lean/src/sandbox.rs create mode 100644 rust/lean/src/sealed.rs create mode 100644 rust/lean/src/snapshot.rs create mode 100644 rust/lean/src/sources.rs create mode 100644 rust/lean/src/tools.rs create mode 100644 rust/lean/src/type_query.rs create mode 100644 rust/lean/src/type_worker.rs create mode 100644 rust/lean/src/verification.rs create mode 100644 rust/lean/src/worker.rs create mode 100644 rust/library/Cargo.toml create mode 100644 rust/library/src/author/interfaces.rs create mode 100644 rust/library/src/author/mod.rs create mode 100644 rust/library/src/author/pack.rs create mode 100644 rust/library/src/author/select.rs create mode 100644 rust/library/src/auto/build.rs create mode 100644 rust/library/src/auto/cli.rs create mode 100644 rust/library/src/auto/cli_profile.rs create mode 100644 rust/library/src/auto/harness.rs create mode 100644 rust/library/src/auto/inspect.rs create mode 100644 rust/library/src/auto/mod.rs create mode 100644 rust/library/src/auto/pack.rs create mode 100644 rust/library/src/auto/planner.rs create mode 100644 rust/library/src/auto/pool.rs create mode 100644 rust/library/src/auto/prepare.rs create mode 100644 rust/library/src/auto/replay.rs create mode 100644 rust/library/src/auto/usage.rs create mode 100644 rust/library/src/catalog.rs create mode 100644 rust/library/src/continuation.rs create mode 100644 rust/library/src/continuation/capture/drafts.rs create mode 100644 rust/library/src/continuation/capture/guide.txt create mode 100644 rust/library/src/continuation/capture/mod.rs create mode 100644 rust/library/src/continuation/capture/notes.rs create mode 100644 rust/library/src/continuation/freeze.rs create mode 100644 rust/library/src/continuation/history.rs create mode 100644 rust/library/src/continuation/seed.rs create mode 100644 rust/library/src/continuation/seed_checkout.rs create mode 100644 rust/library/src/continuation/seed_documents.rs create mode 100644 rust/library/src/display.rs create mode 100644 rust/library/src/first_proof.rs create mode 100644 rust/library/src/formal_eval/cases.rs create mode 100644 rust/library/src/formal_eval/isolation.rs create mode 100644 rust/library/src/formal_eval/mod.rs create mode 100644 rust/library/src/formal_eval/review_state.rs create mode 100644 rust/library/src/formal_eval/role_workspace.rs create mode 100644 rust/library/src/formal_eval/score.rs create mode 100644 rust/library/src/formal_eval/structured.rs create mode 100644 rust/library/src/formal_eval/structured/observation.rs create mode 100644 rust/library/src/formal_eval/structured/output.rs create mode 100644 rust/library/src/formalization/archive_json.rs create mode 100644 rust/library/src/formalization/artifact.rs create mode 100644 rust/library/src/formalization/compilation.rs create mode 100644 rust/library/src/formalization/context.rs create mode 100644 rust/library/src/formalization/elaboration.rs create mode 100644 rust/library/src/formalization/fidelity.rs create mode 100644 rust/library/src/formalization/mod.rs create mode 100644 rust/library/src/formalization/plan.rs create mode 100644 rust/library/src/formalization/queries.json create mode 100644 rust/library/src/formalization/reference/compare.rs create mode 100644 rust/library/src/formalization/reference/files.rs create mode 100644 rust/library/src/formalization/reference/mod.rs create mode 100644 rust/library/src/formalization/reference/programs.json create mode 100644 rust/library/src/formalization/reference/report.rs create mode 100644 rust/library/src/formalization/report/correspondences.rs create mode 100644 rust/library/src/formalization/report/mod.rs create mode 100644 rust/library/src/formalization/report/page.rs create mode 100644 rust/library/src/formalization/request.rs create mode 100644 rust/library/src/formalization/retrieval.rs create mode 100644 rust/library/src/formalization/reviewed.rs create mode 100644 rust/library/src/formalization/role.rs create mode 100644 rust/library/src/formalization/run.rs create mode 100644 rust/library/src/formalization/seed.rs create mode 100644 rust/library/src/formalization/semantic.rs create mode 100644 rust/library/src/goal.rs create mode 100644 rust/library/src/host_release/auto_source.rs create mode 100644 rust/library/src/host_release/config.rs create mode 100644 rust/library/src/host_release/coverage.rs create mode 100644 rust/library/src/host_release/json.rs create mode 100644 rust/library/src/host_release/legacy.rs create mode 100644 rust/library/src/host_release/mod.rs create mode 100644 rust/library/src/host_release/policy.rs create mode 100644 rust/library/src/host_release/registry.rs create mode 100644 rust/library/src/hub/archive.rs create mode 100644 rust/library/src/hub/client.rs create mode 100644 rust/library/src/hub/export.rs create mode 100644 rust/library/src/hub/help.txt create mode 100644 rust/library/src/hub/imports.rs create mode 100644 rust/library/src/hub/manifest.rs create mode 100644 rust/library/src/hub/mod.rs create mode 100644 rust/library/src/hub/sources.rs create mode 100644 rust/library/src/imo/lakefile.toml.in create mode 100644 rust/library/src/imo/mod.rs create mode 100644 rust/library/src/imo/receipt.rs create mode 100644 rust/library/src/informalization/alignment.rs create mode 100644 rust/library/src/informalization/evidence.rs create mode 100644 rust/library/src/informalization/evidence/publish.rs create mode 100644 rust/library/src/informalization/markdown.rs create mode 100644 rust/library/src/informalization/mod.rs create mode 100644 rust/library/src/informalization/report/locations.rs create mode 100644 rust/library/src/informalization/report/mod.rs create mode 100644 rust/library/src/informalization/roles.rs create mode 100644 rust/library/src/inspection/artifacts.rs create mode 100644 rust/library/src/inspection/category.rs create mode 100644 rust/library/src/inspection/events.rs create mode 100644 rust/library/src/inspection/markdown/contributions.rs create mode 100644 rust/library/src/inspection/markdown/cooperative.rs create mode 100644 rust/library/src/inspection/markdown/mod.rs create mode 100644 rust/library/src/inspection/markdown/report.rs create mode 100644 rust/library/src/inspection/markdown/scheduling.rs create mode 100644 rust/library/src/inspection/markdown/team.rs create mode 100644 rust/library/src/inspection/mod.rs create mode 100644 rust/library/src/inspection/report/flow/attempts.rs create mode 100644 rust/library/src/inspection/report/flow/checks.rs create mode 100644 rust/library/src/inspection/report/flow/mod.rs create mode 100644 rust/library/src/inspection/report/mod.rs create mode 100644 rust/library/src/inspection/report/progress/mod.rs create mode 100644 rust/library/src/inspection/report/progress/routes.rs create mode 100644 rust/library/src/inspection/report/progress/snapshot.rs create mode 100644 rust/library/src/inspection/report/tasks.rs create mode 100644 rust/library/src/inspection/report/team/mod.rs create mode 100644 rust/library/src/inspection/report/team/overview.rs create mode 100644 rust/library/src/inspection/report/usage.rs create mode 100644 rust/library/src/inspection/report/workers.rs create mode 100644 rust/library/src/io.rs create mode 100644 rust/library/src/knowledge/accepted.rs create mode 100644 rust/library/src/knowledge/archive.rs create mode 100644 rust/library/src/knowledge/authorized.rs create mode 100644 rust/library/src/knowledge/build.rs create mode 100644 rust/library/src/knowledge/cli.rs create mode 100644 rust/library/src/knowledge/enrichment/binding.rs create mode 100644 rust/library/src/knowledge/enrichment/collect.rs create mode 100644 rust/library/src/knowledge/enrichment/collectors.json create mode 100644 rust/library/src/knowledge/enrichment/discovery.rs create mode 100644 rust/library/src/knowledge/enrichment/exports.rs create mode 100644 rust/library/src/knowledge/enrichment/mod.rs create mode 100644 rust/library/src/knowledge/enrichment/operation.rs create mode 100644 rust/library/src/knowledge/enrichment/query.rs create mode 100644 rust/library/src/knowledge/enrichment/query/dependencies.lean.in create mode 100644 rust/library/src/knowledge/enrichment/query/direct.lean.in create mode 100644 rust/library/src/knowledge/enrichment/query/expected.lean.in create mode 100644 rust/library/src/knowledge/enrichment/reports.rs create mode 100644 rust/library/src/knowledge/enrichment/source.rs create mode 100644 rust/library/src/knowledge/enrichment/validate.rs create mode 100644 rust/library/src/knowledge/findings.rs create mode 100644 rust/library/src/knowledge/help.txt create mode 100644 rust/library/src/knowledge/installed.rs create mode 100644 rust/library/src/knowledge/mod.rs create mode 100644 rust/library/src/knowledge/pages.rs create mode 100644 rust/library/src/knowledge/pages/relations.rs create mode 100644 rust/library/src/knowledge/runs/admission.rs create mode 100644 rust/library/src/knowledge/runs/artifacts.rs create mode 100644 rust/library/src/knowledge/runs/demand.rs create mode 100644 rust/library/src/knowledge/runs/findings.rs create mode 100644 rust/library/src/knowledge/runs/mod.rs create mode 100644 rust/library/src/knowledge/runs/routes.rs create mode 100644 rust/library/src/knowledge/runs/tasks.rs create mode 100644 rust/library/src/knowledge/runs/team.rs create mode 100644 rust/library/src/knowledge/runs/team/contributions.rs create mode 100644 rust/library/src/knowledge/schema.json create mode 100644 rust/library/src/knowledge/schema.rs create mode 100644 rust/library/src/lean_eval/contract.rs create mode 100644 rust/library/src/lean_eval/installed.rs create mode 100644 rust/library/src/lean_eval/mod.rs create mode 100644 rust/library/src/lean_task/environments.json create mode 100644 rust/library/src/lean_task/mod.rs create mode 100644 rust/library/src/lean_task/prepare.rs create mode 100644 rust/library/src/lib.rs create mode 100644 rust/library/src/module_plan.rs create mode 100644 rust/library/src/packing/cli.rs create mode 100644 rust/library/src/packing/mod.rs create mode 100644 rust/library/src/packing/prune.rs create mode 100644 rust/library/src/problem.rs create mode 100644 rust/library/src/recovery/checkout.rs create mode 100644 rust/library/src/recovery/history.rs create mode 100644 rust/library/src/recovery/mod.rs create mode 100644 rust/library/src/recovery/recheck.rs create mode 100644 rust/library/src/recovery/recheck/declarations.rs create mode 100644 rust/library/src/recovery/recheck/execute.rs create mode 100644 rust/library/src/recovery/recheck/execute/isolated.rs create mode 100644 rust/library/src/recovery/recheck/execute/seed.rs create mode 100644 rust/library/src/recovery/recheck/execute/seed/publish.rs create mode 100644 rust/library/src/recovery/snapshot.rs create mode 100644 rust/library/src/search.rs create mode 100644 rust/library/src/search/history.rs create mode 100644 rust/library/src/stored_zip.rs create mode 100644 rust/library/src/team_research.rs create mode 100644 rust/library/src/terms.rs create mode 100644 rust/library/src/tutorial.rs create mode 100644 rust/library/src/vocabulary.rs create mode 100644 rust/process/Cargo.toml create mode 100644 rust/process/src/archive.rs create mode 100644 rust/process/src/budgets.rs create mode 100644 rust/process/src/codex_stdio.rs create mode 100644 rust/process/src/continuation_seed.rs create mode 100644 rust/process/src/diagnostic_session.rs create mode 100644 rust/process/src/environment.rs create mode 100644 rust/process/src/evaluation.rs create mode 100644 rust/process/src/evidence.rs create mode 100644 rust/process/src/formalization_audit.rs create mode 100644 rust/process/src/formalization_audit/isolation.rs create mode 100644 rust/process/src/formalization_compiler.rs create mode 100644 rust/process/src/git.rs create mode 100644 rust/process/src/image_cache.rs create mode 100644 rust/process/src/informalization.rs create mode 100644 rust/process/src/lean_diagnostics.rs create mode 100644 rust/process/src/lean_sources.rs create mode 100644 rust/process/src/lease.rs create mode 100644 rust/process/src/lib.rs create mode 100644 rust/process/src/library.rs create mode 100644 rust/process/src/proof_projection.rs create mode 100644 rust/process/src/research.rs create mode 100644 rust/process/src/response_usage.rs create mode 100644 rust/process/src/resume.rs create mode 100644 rust/process/src/retrieval.rs create mode 100644 rust/process/src/retry.rs create mode 100644 rust/process/src/rpc.rs create mode 100644 rust/process/src/run_options.rs create mode 100644 rust/process/src/sub2api_auth.rs create mode 100644 rust/process/src/sub2api_http.rs create mode 100644 rust/process/src/team_control.rs create mode 100644 rust/process/src/turn.rs create mode 100644 rust/retrieval/Cargo.toml create mode 100644 rust/retrieval/src/additive.rs create mode 100644 rust/retrieval/src/aliases.rs create mode 100644 rust/retrieval/src/cache.rs create mode 100644 rust/retrieval/src/concepts.rs create mode 100644 rust/retrieval/src/declarations.rs create mode 100644 rust/retrieval/src/files.rs create mode 100644 rust/retrieval/src/goal.rs create mode 100644 rust/retrieval/src/headers.rs create mode 100644 rust/retrieval/src/installed.rs create mode 100644 rust/retrieval/src/lib.rs create mode 100644 rust/retrieval/src/notation.rs create mode 100644 rust/retrieval/src/packet.rs create mode 100644 rust/retrieval/src/premises.rs create mode 100644 rust/retrieval/src/query.rs create mode 100644 rust/retrieval/src/search.rs create mode 100644 rust/retrieval/src/shape.rs create mode 100644 rust/retrieval/src/specialization.rs create mode 100644 rust/retrieval/src/syntax.rs create mode 100644 rust/solver/Cargo.toml create mode 100644 rust/solver/src/archive/diagnostic.rs create mode 100644 rust/solver/src/archive/mod.rs create mode 100644 rust/solver/src/archive/schema.json create mode 100644 rust/solver/src/budget.rs create mode 100644 rust/solver/src/codex_child.rs create mode 100644 rust/solver/src/codex_child/namespace.rs create mode 100644 rust/solver/src/codex_dispatch.rs create mode 100644 rust/solver/src/codex_frames.rs create mode 100644 rust/solver/src/codex_session.rs create mode 100644 rust/solver/src/codex_session/team.rs create mode 100644 rust/solver/src/codex_stdio.rs create mode 100644 rust/solver/src/direct-instructions.txt create mode 100644 rust/solver/src/direct_context.rs create mode 100644 rust/solver/src/direct_context/permissions.rs create mode 100644 rust/solver/src/evaluation.rs create mode 100644 rust/solver/src/git.rs create mode 100644 rust/solver/src/lib.rs create mode 100644 rust/solver/src/plan/decisions.rs create mode 100644 rust/solver/src/plan/families.rs create mode 100644 rust/solver/src/plan/goal_path.rs create mode 100644 rust/solver/src/plan/graph.rs create mode 100644 rust/solver/src/plan/mod.rs create mode 100644 rust/solver/src/plan/patch.rs create mode 100644 rust/solver/src/plan/routes.rs create mode 100644 rust/solver/src/problem.rs create mode 100644 rust/solver/src/projection/assignment.rs create mode 100644 rust/solver/src/projection/changes.rs create mode 100644 rust/solver/src/projection/closure.rs create mode 100644 rust/solver/src/projection/fingerprints.rs create mode 100644 rust/solver/src/projection/lookup.rs create mode 100644 rust/solver/src/projection/lookup/graph.rs create mode 100644 rust/solver/src/projection/lookup/instances.rs create mode 100644 rust/solver/src/projection/lookup/snapshot.rs create mode 100644 rust/solver/src/projection/lookup/snapshot/files.rs create mode 100644 rust/solver/src/projection/merge.rs create mode 100644 rust/solver/src/projection/mod.rs create mode 100644 rust/solver/src/projection/opens.rs create mode 100644 rust/solver/src/projection/render.rs create mode 100644 rust/solver/src/projection/syntax.rs create mode 100644 rust/solver/src/projection/target.rs create mode 100644 rust/solver/src/proof.rs create mode 100644 rust/solver/src/proof/checkpoint.rs create mode 100644 rust/solver/src/proof/export.lean create mode 100644 rust/solver/src/proof/external.rs create mode 100644 rust/solver/src/proof/imports.rs create mode 100644 rust/solver/src/proof/kernel.rs create mode 100644 rust/solver/src/proof/layout.lean create mode 100644 rust/solver/src/proof/packages.rs create mode 100644 rust/solver/src/proof/packages/layout.rs create mode 100644 rust/solver/src/proof/replay.lean create mode 100644 rust/solver/src/receipts.rs create mode 100644 rust/solver/src/research.rs create mode 100644 rust/solver/src/response_usage.rs create mode 100644 rust/solver/src/responses_admission.rs create mode 100644 rust/solver/src/statement.rs create mode 100644 rust/solver/src/statement/packages.rs create mode 100644 rust/solver/src/sub2api_auth.rs create mode 100644 rust/solver/src/sub2api_http.rs create mode 100644 rust/solver/src/team.rs create mode 100644 rust/solver/src/team_control.rs create mode 100644 rust/solver/tests/codex_session.rs create mode 100644 rust/solver/tests/codex_stdio.rs create mode 100644 rust/solver/tests/direct_context.rs create mode 100644 rust/solver/tests/git.rs create mode 100644 rust/solver/tests/proof.rs create mode 100644 rust/supervision/Cargo.toml create mode 100644 rust/supervision/src/capture.rs create mode 100644 rust/supervision/src/group.rs create mode 100644 rust/supervision/src/lib.rs create mode 100644 rust/supervision/src/namespace.rs create mode 100644 rust/supervision/src/session.rs create mode 100644 rust/web/Cargo.toml create mode 100644 rust/web/community-limits.json create mode 100644 rust/web/src/bin/theoremos-web-assets.rs create mode 100644 rust/web/src/bin/theoremos-web-check.rs create mode 100644 rust/web/src/bin/theoremos-web-docker/language.rs create mode 100644 rust/web/src/bin/theoremos-web-docker/main.rs create mode 100644 rust/web/src/bin/theoremos-web-docker/paper.rs create mode 100644 rust/web/src/bin/theoremos-web-docker/precheck.rs create mode 100644 rust/web/src/bin/theoremos-web/admin_accounts.rs create mode 100644 rust/web/src/bin/theoremos-web/admin_allowlist.rs create mode 100644 rust/web/src/bin/theoremos-web/auth_challenges.rs create mode 100644 rust/web/src/bin/theoremos-web/auth_mail.rs create mode 100644 rust/web/src/bin/theoremos-web/auth_routes.rs create mode 100644 rust/web/src/bin/theoremos-web/community_account.rs create mode 100644 rust/web/src/bin/theoremos-web/community_routes.rs create mode 100644 rust/web/src/bin/theoremos-web/community_worker.rs create mode 100644 rust/web/src/bin/theoremos-web/identity.rs create mode 100644 rust/web/src/bin/theoremos-web/knowledge_reads.rs create mode 100644 rust/web/src/bin/theoremos-web/login_return.rs create mode 100644 rust/web/src/bin/theoremos-web/main.rs create mode 100644 rust/web/src/bin/theoremos-web/module_plans.rs create mode 100644 rust/web/src/bin/theoremos-web/operations.rs create mode 100644 rust/web/src/bin/theoremos-web/product.rs create mode 100644 rust/web/src/bin/theoremos-web/proof_download.rs create mode 100644 rust/web/src/bin/theoremos-web/run_archive.rs create mode 100644 rust/web/src/bin/theoremos-web/run_list.rs create mode 100644 rust/web/src/bin/theoremos-web/run_observations.rs create mode 100644 rust/web/src/bin/theoremos-web/run_reads.rs create mode 100644 rust/web/src/bin/theoremos-web/run_write.rs create mode 100644 rust/web/src/bin/theoremos-web/session_handlers.rs create mode 100644 rust/web/src/bin/theoremos-web/session_http.rs create mode 100644 rust/web/src/bin/theoremos-web/trajectory.rs create mode 100644 rust/web/src/bin/theoremos-web/trajectory_index.rs create mode 100644 rust/web/src/bin/theoremos-web/vault.rs create mode 100644 rust/web/src/bin/theoremos-web/workspace_catalog.rs create mode 100644 rust/web/src/community.rs create mode 100644 rust/web/src/community_admission.rs create mode 100644 rust/web/src/community_admission_addon.rs create mode 100644 rust/web/src/community_check.rs create mode 100644 rust/web/src/community_lock.rs create mode 100644 rust/web/src/lib.rs create mode 100644 rust/web/src/record_file.rs create mode 100644 rust/web/src/run_lifecycle.rs create mode 100644 rust/web/src/static_files.rs create mode 100644 rust/web/src/worker_image.rs create mode 100644 rust/web/trajectory.json create mode 100644 scripts/generate-native-archive-schema.ts create mode 100644 scripts/generate-native-direct-instructions.ts create mode 100644 scripts/generate-native-evaluation-review-contracts.ts create mode 100644 scripts/generate-native-formalization-queries.ts create mode 100644 scripts/generate-native-knowledge-collectors.ts create mode 100644 scripts/generate-native-knowledge-schema.ts create mode 100644 scripts/generate-native-reference-queries.ts create mode 100644 scripts/generate-native-task-environments.ts create mode 100644 scripts/generate-native-tutorial-contract.ts create mode 100644 scripts/mathematics/continuationSeedCommand.ts create mode 100644 scripts/test-native-archive.ts create mode 100644 scripts/test-native-auto-library.ts create mode 100644 scripts/test-native-build.ts create mode 100644 scripts/test-native-check-lean.ts create mode 100644 scripts/test-native-continuation.ts create mode 100644 scripts/test-native-doctor.ts create mode 100644 scripts/test-native-edit.ts create mode 100644 scripts/test-native-eval-bootstrap.ts create mode 100644 scripts/test-native-health.ts create mode 100644 scripts/test-native-imo.ts create mode 100644 scripts/test-native-informalize.ts create mode 100644 scripts/test-native-knowledge-pages.ts create mode 100644 scripts/test-native-knowledge.ts create mode 100644 scripts/test-native-lean-eval.ts create mode 100644 scripts/test-native-lean-source.ts create mode 100644 scripts/test-native-library-catalog.ts create mode 100644 scripts/test-native-library-pack.ts create mode 100644 scripts/test-native-library.ts create mode 100644 scripts/test-native-plan.ts create mode 100644 scripts/test-native-process.ts create mode 100644 scripts/test-native-retrieval.ts create mode 100644 scripts/test-native-run-options.ts create mode 100644 scripts/test-native-solver.ts create mode 100644 scripts/test-native-startup.ts create mode 100644 scripts/test-native-sub2api.ts create mode 100644 scripts/test-native-task-bootstrap.ts create mode 100644 scripts/test-native-team.ts create mode 100644 scripts/test-native-web.ts create mode 100644 src/math/formalizationRoleWorkspace.ts create mode 100644 src/math/frozenLibrarySearchData.json create mode 100644 src/math/informalizationLabels.json create mode 100644 src/math/leanDeclarationType.ts create mode 100644 src/math/mathSearchConceptData.json create mode 100644 src/math/mathlibTheoremAliasData.json create mode 100644 src/math/nativeProcess.ts create mode 100644 src/math/runtimeEnvironmentKeys.json create mode 100644 src/runtime/codexTurnEvidence.ts create mode 100644 src/runtime/responsesAdmissionReference.ts create mode 100644 src/runtime/sub2apiHttp.ts create mode 100644 src/solver/autoLibraryControl.ts create mode 100644 src/solver/researchLoop.ts create mode 100644 src/solver/researchOwner.ts create mode 100644 src/solver/runOptions.ts create mode 100644 src/solver/taskDeclarationStart.ts create mode 100644 src/solver/taskOpenBindings.ts create mode 100644 src/solver/taskProjectionFile.ts create mode 100644 src/solver/taskSourceSnapshot.ts create mode 100644 src/solver/teamMemberSchedule.ts create mode 100644 tests/codexIsolatedChild.test.ts create mode 100644 tests/fixtures/native-team-peer.py create mode 100644 tests/helpers/firstProofNative.ts create mode 100644 tests/helpers/historicalReportNative.ts create mode 100644 tests/helpers/inspectionMarkdownNative.ts create mode 100644 tests/helpers/nativeArchiveParity.cjs create mode 100644 tests/helpers/nativeDirectContext.ts create mode 100644 tests/helpers/nativeKnowledgeImport.ts create mode 100644 tests/helpers/nativeReferenceAddon.ts create mode 100644 tests/helpers/semanticReviewIsolation.ts create mode 100644 tests/leanToolchainNative.test.ts create mode 100644 tests/nativeFormalizationCompiler.test.ts create mode 100644 tests/responseUsageObserver.test.ts create mode 100644 tests/webPaperRunner.test.ts diff --git a/.dockerignore b/.dockerignore index dd1a3218..e94e7d51 100644 --- a/.dockerignore +++ b/.dockerignore @@ -4,6 +4,7 @@ out runtime .state coverage +target *.log **/*.runtime accepted diff --git a/.github/workflows/verify.yml b/.github/workflows/verify.yml index 1c620435..b353eb73 100644 --- a/.github/workflows/verify.yml +++ b/.github/workflows/verify.yml @@ -17,6 +17,80 @@ permissions: contents: read jobs: + verify-rust: + runs-on: ubuntu-24.04 + timeout-minutes: 15 + 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 + - 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: 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: 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 @@ -167,11 +241,42 @@ 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 + 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 + 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 + 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 - 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: 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: 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 - name: Verify projected proof contracts and retained source contexts run: bunx vitest run --maxWorkers=4 tests/taskTypeContract.test.ts tests/projectionNotation.test.ts tests/taskSourceImplicitInstances.test.ts tests/taskSourceMacroProjection.test.ts tests/taskSourceNotationHints.test.ts tests/taskSourceNotationContext.test.ts - name: Verify search tools, failure reuse and completed research delivery diff --git a/.gitignore b/.gitignore index b5325896..aba3a12a 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,4 @@ coverage/ .state/ *.runtime/ .taste-skill/ +/target/ diff --git a/.prettierignore b/.prettierignore index be307cfb..8b4661a5 100644 --- a/.prettierignore +++ b/.prettierignore @@ -18,7 +18,7 @@ bun.lock *.lean # Generated by scripts/generate-web-library-search.ts. -src/math/frozenLibrarySearchData.ts +src/math/frozenLibrarySearchData.json # Font faces are generated and matched byte-for-byte by tests/webFonts.test.ts. apps/web/client/app.css diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 00000000..a8250909 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,2424 @@ +# 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", +] + +[[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 = "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-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 = "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", + "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", + "libc", + "wasi", +] + +[[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", + "libc", + "r-efi 6.0.0", +] + +[[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-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 = "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 = "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", + "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 = "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", +] + +[[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", +] + +[[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 = "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-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "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 = "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-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "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 = "scrypt" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0516a385866c09368f0b5bcd1caff3366aace790fcd46e2bb032697bb172fd1f" +dependencies = [ + "pbkdf2", + "salsa20", + "sha2", +] + +[[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", + "digest", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "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", + "regex", + "scrypt", + "serde", + "serde_json", + "sha2", + "subtle", + "tempfile", + "theoremos-lean", + "theoremos-library", + "tokio", + "url", +] + +[[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-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 = "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 new file mode 100644 index 00000000..bbaed01e --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,3 @@ +[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 ee0df961..cd63d57e 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,7 @@ # 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). + English · [简体中文](README.zh-CN.md) TheoremOS is a Lean 4 research workbench from [WestlakeNLP, Westlake University](https://westlakenlp.com/). Start with a mathematical statement, review its formalization, then let a single agent or a team work on the proof. Each run preserves the source, attempts and Lean diagnostics. The host checks the complete original goal before it records a proof as accepted. @@ -16,22 +18,20 @@ TheoremOS is a Lean 4 research workbench from [WestlakeNLP, Westlake University] ## Quick start -Run a proof check on your own machine without a model key or Mathlib. The example needs Linux, Git, Bun (1.4.0 in CI), Node.js 22+, Python 3, util-linux, Bubblewrap with user namespaces enabled, and Elan. See the [setup and replay guide](examples/getting-started/README.md) for details. +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. ```bash -git clone https://github.com/HuggingMath/theorem-os.git -cd theorem-os -bun install --frozen-lockfile +cargo build --locked --release -p theorem-os --bins elan toolchain install leanprover/lean4:v4.36.0 -bun run math doctor --lean-only +./target/release/theorem-os doctor --lean-only # Choose a new directory outside the checkout. export THEOREMOS_REPLAY="$PWD/../theorem-os-runs/first-replay" -bun run math example replay --dir "$THEOREMOS_REPLAY" -bun run math inspect --run "$THEOREMOS_REPLAY/result.json" +./target/release/theorem-os example replay --dir "$THEOREMOS_REPLAY" +./target/release/theorem-os 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 candidates are supplied by the example (`modelInvoked: false`). To have a model write a proof, follow the [agent run instructions](examples/getting-started/README.md#再让-agent-自己证明). +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). ## Find your way around diff --git a/README.zh-CN.md b/README.zh-CN.md index 2af0a224..e6f5ec3f 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -1,5 +1,7 @@ # TheoremOS +Rust 首版面向 Linux 命令行,支持单人求解、在线组队、Lean 独立验收、续跑和手动选用库包。浏览器工作台后置。参见 [Rust CLI 快速开始](docs/rust-migration.md)。 + [English](README.md) · 简体中文 TheoremOS 是[西湖大学 WestlakeNLP 实验室](https://westlakenlp.com/)开发的 Lean 4 数学研究工作台。你可以输入一道数学题,核对形式化后的题意,再交给单个 Agent 或研究团队写证明。每次运行保留源码、尝试记录和 Lean 诊断;宿主重新检查完整原题后,才把证明记为通过。 @@ -14,22 +16,20 @@ TheoremOS 是[西湖大学 WestlakeNLP 实验室](https://westlakenlp.com/)开 ## 快速开始 -先在本机验证一个小证明。这个例子不需要模型密钥,也不下载 Mathlib。需要 Linux、Git、Bun(CI 使用 1.4.0)、Node.js 22+、Python 3、util-linux、能创建用户命名空间的 Bubblewrap,以及 Elan。环境配置见[入门指南](examples/getting-started/README.md)。 +先在本机验证一个小证明。这个例子不需要模型密钥,也不下载 Mathlib。需要 Linux、Rust 1.95 或更新版本、Git、能创建用户命名空间的 Bubblewrap,以及 Elan。 ```bash -git clone https://github.com/HuggingMath/theorem-os.git -cd theorem-os -bun install --frozen-lockfile +cargo build --locked --release -p theorem-os --bins elan toolchain install leanprover/lean4:v4.36.0 -bun run math doctor --lean-only +./target/release/theorem-os doctor --lean-only # 选择仓库外尚未使用的目录。 export THEOREMOS_REPLAY="$PWD/../theorem-os-runs/first-replay" -bun run math example replay --dir "$THEOREMOS_REPLAY" -bun run math inspect --run "$THEOREMOS_REPLAY/result.json" +./target/release/theorem-os example replay --dir "$THEOREMOS_REPLAY" +./target/release/theorem-os inspect --run "$THEOREMOS_REPLAY/result.json" ``` -第一次尝试在 `0 + n = n` 处被 Lean 拒绝;第二次用 `Nat.zero_add` 修复,两个目标都通过。成功时状态为 `evaluated_passed`,本地验收标为 `official: false`。两次候选都由示例提供(`modelInvoked: false`)。要让模型自己写证明,接着看[运行第一个 Agent](examples/getting-started/README.md#再让-agent-自己证明)。 +第一次尝试在 `0 + n = n` 处被 Lean 拒绝。第二次用 `Nat.zero_add` 修复,两个目标都通过。成功时状态为 `evaluated_passed`,本地验收标为 `official: false`。两次候选都由示例提供(`modelInvoked: false`)。要把自己的题交给单个 Agent 或研究团队,接着看 [Rust CLI 指南](docs/rust-migration.md)。 ## 按任务找入口 diff --git a/apps/web/Dockerfile b/apps/web/Dockerfile index 5bfe8fef..2d1edbf3 100644 --- a/apps/web/Dockerfile +++ b/apps/web/Dockerfile @@ -1,6 +1,18 @@ 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/frozenLibrarySearchData.json src/math/frozenLibrarySearchData.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 @@ -33,6 +45,7 @@ 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 docs/assets ./docs/assets COPY LICENSE NOTICE CITATION.cff ./ COPY LICENSES ./LICENSES @@ -82,6 +95,9 @@ 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 \ @@ -91,8 +107,9 @@ 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 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 \ +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 \ && 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 \ @@ -117,7 +134,17 @@ 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 docs/web ./docs/web COPY docs/archive.html docs/site.css docs/process.css docs/replay.css ./docs/ @@ -128,4 +155,4 @@ RUN bun scripts/build-web.ts 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 ["bun", "apps/web/server.ts"] +CMD ["theoremos-web"] diff --git a/apps/web/agentActions.ts b/apps/web/agentActions.ts index e6787266..02271204 100644 --- a/apps/web/agentActions.ts +++ b/apps/web/agentActions.ts @@ -63,7 +63,7 @@ export function unwrapShell(command: string) { export function createAgentPathMask(context: AgentActionContext) { const rules: RegExp[] = []; const tool = context.tool - ? new RegExp(String.raw`\bbun\s+'?${escape(path.resolve(context.tool))}'?`, 'gu') + ? new RegExp(String.raw`(?:\bbun\s+)?'?${escape(path.resolve(context.tool))}'?`, 'gu') : undefined; const own = new RegExp(escape(path.resolve(context.worktree)) + notName, 'gu'); for (const root of [...new Set(context.hidden.map(item => path.resolve(item)))].sort((a, b) => b.length - a.length)) diff --git a/apps/web/auth.ts b/apps/web/auth.ts index 6e81f858..0fc68be3 100644 --- a/apps/web/auth.ts +++ b/apps/web/auth.ts @@ -136,6 +136,7 @@ type Limit = { times: number[] }; export class WebAuth { private readonly secret = crypto.randomBytes(32); private readonly captchas = new Map(); + private readonly sending = new Set<{ email: string }>(); private readonly codes = new Map(); private readonly limits = new Map(); @@ -144,6 +145,7 @@ export class WebAuth { private readonly storage: WebStorage, private readonly mailer: WebMailer = smtpMailer(config), private readonly answer: () => string = () => String(crypto.randomInt(0, 100_000)).padStart(5, '0'), + private readonly writer?: (message: object) => WebAccount, ) {} /** Sliding-window counter; returns false once `max` events already fall inside `windowMs`. */ @@ -213,16 +215,24 @@ export class WebAuth { const version = this.checkTerms(body, account); return this.recordTerms(account, version); } + invalidateLoginCode(login: string) { + this.codes.delete(login); + for (const delivery of this.sending) if (delivery.email === login) this.sending.delete(delivery); + } /** Suspension keeps records for restoration, blocks both login methods and invalidates admission on the next request. */ setSuspended(value: unknown, suspended: boolean): WebAccount { - const login = normalizeLogin(value), - account = this.getAccount(login); + const login = normalizeLogin(value); + if (this.writer) { + if (suspended) this.invalidateLoginCode(login); + return this.writer({ op: 'account', action: 'suspend', login, data: { suspended } }); + } + const account = this.getAccount(login); if (!account) throw new WebAuthError(404, '账号不存在。'); if (this.isAdmin(login) && suspended) throw new WebAuthError(400, '管理员账号不能暂停。'); const { suspendedAt: _previous, ...rest } = account; const updated = suspended ? { ...rest, suspendedAt: account.suspendedAt ?? new Date().toISOString() } : rest; this.storage.saveRecord(this.accountPath(login), updated); - if (suspended) this.codes.delete(login); + if (suspended) this.invalidateLoginCode(login); return updated; } private fileLines(): string[] { @@ -264,7 +274,8 @@ export class WebAuth { file, this.fileLines().filter(line => line.replace(/#.*/u, '').trim().toLowerCase() !== email), ); - this.codes.delete(email); + this.invalidateLoginCode(email); + this.writer?.({ op: 'invalidateCode', login: email }); } allowlistWritable(): boolean { return Boolean(this.config.allowlistFile); @@ -310,15 +321,15 @@ export class WebAuth { if (!this.allow(`code-email:${email}`, 5, 60 * 60_000)) throw new WebAuthError(429, '这个邮箱的验证码请求过多,请一小时后再试。'); const code = String(crypto.randomInt(0, 1_000_000)).padStart(6, '0'); + const delivery = { email }; + this.sending.add(delivery); try { - await this.mailer({ - to: email, - subject: `TheoremOS 登录验证码 ${code}`, - text: `你的 TheoremOS 登录验证码是 ${code},10 分钟内有效。\n如果不是你本人操作,请忽略这封邮件。\n\nYour TheoremOS login code is ${code}. It expires in 10 minutes.\n`, - }); + await this.sendLoginCode(email, code); } catch { + this.sending.delete(delivery); throw new WebAuthError(502, '验证码邮件发送失败,请稍后重试。'); } + if (!this.sending.delete(delivery)) throw new WebAuthError(403, '这个账号目前无法使用,请联系支持。'); this.codes.set(email, { digest: this.digest(email, code), expiresAt: Date.now() + codeTtlMs, @@ -328,6 +339,14 @@ export class WebAuth { return { email, expiresInSeconds: codeTtlMs / 1000, resendAfterSeconds: resendAfterMs / 1000 }; } + sendLoginCode(email: string, code: string) { + return this.mailer({ + to: email, + subject: `TheoremOS 登录验证码 ${code}`, + text: `你的 TheoremOS 登录验证码是 ${code},10 分钟内有效。\n如果不是你本人操作,请忽略这封邮件。\n\nYour TheoremOS login code is ${code}. It expires in 10 minutes.\n`, + }); + } + /** `terms` is the signup form's checkbox; an open signup requires it before the account exists. */ verifyCode(body: { email?: unknown; code?: unknown; terms?: unknown; termsVersion?: unknown }): WebAccount { const email = normalizeEmail(body.email), @@ -508,6 +527,15 @@ export class WebAuth { /** Stamps a milestone the first time it happens; later runs leave the first time unchanged. */ markMilestone(accountId: string, milestone: WebMilestone, at = new Date().toISOString()) { const account = this.listAccounts().find(item => item.id === accountId); + if (account && this.writer) { + this.writer({ + op: 'account', + action: 'milestone', + login: accountLogin(account), + data: { id: accountId, field: milestone, at }, + }); + return; + } if (account && !account[milestone]) this.storage.saveRecord(this.accountPath(accountLogin(account)), { ...account, [milestone]: at }); } @@ -529,6 +557,11 @@ export class WebAuth { await this.mailer({ to, ...message }); } deleteAccount(login: string) { + if (this.writer) { + this.writer({ op: 'account', action: 'delete', login, data: {} }); + this.codes.delete(login); + return; + } // Keep the account retryable if credential deletion fails; a recreated account must never inherit its password. this.storage.deleteRecord(this.passwordPath(login)); this.storage.deleteRecord(this.accountPath(login)); diff --git a/apps/web/client/CommunityBoard.tsx b/apps/web/client/CommunityBoard.tsx index 76ca8369..e66778c7 100644 --- a/apps/web/client/CommunityBoard.tsx +++ b/apps/web/client/CommunityBoard.tsx @@ -68,7 +68,9 @@ export function CommunityBoard({ language }: { language: 'zh' | 'en' }) { const [overview, setOverview] = useState(); const [session, setSession] = useState(); const [me, setMe] = useState(); - const [{ tab, open }, setRoute] = useState(route); + const [selected, setRoute] = useState(route); + const { open } = selected; + const tab = overview?.readOnly && selected.tab === 'join' ? 'tasks' : selected.tab; const [filter, setFilter] = useState('open'); const tabs = useRef(null), came = useRef(), @@ -76,14 +78,12 @@ export function CommunityBoard({ language }: { language: 'zh' | 'en' }) { const [error, setError] = useState(''); const refresh = async () => { try { - const [board, current] = await Promise.all([ - call('/api/community/overview'), - call('/api/session'), - ]); - csrf = current.csrfToken; + const board = await call('/api/community/overview'); + const current = board.readOnly ? undefined : await call('/api/session'); + csrf = current?.csrfToken ?? ''; setOverview(board); setSession(current); - setMe(current.account ? await call('/api/community/me') : undefined); + setMe(current?.account ? await call('/api/community/me') : undefined); setError(''); } catch (failure) { setError(localizeMessage((failure as Error).message)); @@ -126,8 +126,8 @@ export function CommunityBoard({ language }: { language: 'zh' | 'en' }) { ['tasks', tx('题目', 'Problems')], ['boards', tx('排行榜', 'Leaderboards')], ['activity', tx('动态', 'Activity')], - ['join', tx('参与', 'Join')], ]; + if (!overview?.readOnly) names.push(['join', tx('参与', 'Join')]); const keys = (event: KeyboardEvent) => { const buttons = [...(tabs.current?.querySelectorAll('[role=tab]') ?? [])], last = buttons.length - 1; @@ -212,8 +212,13 @@ export function CommunityBoard({ language }: { language: 'zh' | 'en' }) { )} - - {!overview.checker && ( + {!overview.readOnly && } + {overview.readOnly && ( +

+ {tx('这里只能浏览公开题目和证明。', 'You can browse public problems and proofs here.')} +

+ )} + {!overview.readOnly && !overview.checker && (

{tx('证明校验服务当前不可用,暂不接收提交。', 'The proof checker is unavailable; submissions are paused.')}

@@ -256,6 +261,7 @@ export function CommunityBoard({ language }: { language: 'zh' | 'en' }) { me={me} signedIn={signedIn} checker={overview.checker} + readOnly={Boolean(overview.readOnly)} back={() => show()} changed={refresh} /> @@ -389,6 +395,7 @@ function TaskDetail({ me, signedIn, checker, + readOnly, back, changed, }: { @@ -399,6 +406,7 @@ function TaskDetail({ me?: Me; signedIn: boolean; checker: boolean; + readOnly: boolean; back: () => void; changed: () => Promise; }) { @@ -513,7 +521,7 @@ function TaskDetail({
{detail.solution.source}
)} - {task.status === 'open' && ( + {!readOnly && task.status === 'open' && (

{tx('认领与提交', 'Claim and submit')}

diff --git a/apps/web/community.ts b/apps/web/community.ts index f88aa400..bca80cdf 100644 --- a/apps/web/community.ts +++ b/apps/web/community.ts @@ -6,6 +6,7 @@ import { inspectScopedLeanDeclarations } from '../../src/math/leanSource'; import { mathConstructionImports } from '../../src/math/mathConstructionSources'; import { leanDiagnostics, type WebPrecheckRunner } from './precheck'; import { WebStorage, WebStorageError } from './storage'; +import { nativeWeb } from './nativeWeb'; import type { WebEnvironment } from './shared'; /** @@ -35,17 +36,8 @@ type Activity = CommunityActivity; type Profile = { handle: string; createdAt: string; tokenDigest?: string; tokenCreatedAt?: string }; type Claim = { owner: string; claimedAt: string; expiresAt: string }; -export const communityLimits = { - claimsPerPerson: 3, - claimHours: 48, - pendingPerPerson: 2, - submissionsPerHour: 20, - sourceBytes: 64 * 1024, - statementBytes: 16 * 1024, - activityKept: 500, - activityShown: 200, - pointsIntervalSeconds: 3_600, -}; +export { default as communityLimits } from '../../rust/web/community-limits.json'; +import communityLimits from '../../rust/web/community-limits.json'; export const communityTokenPattern = /^tosc_[a-f0-9]{64}$/u; const fail = (status: number, text: string): never => { throw new WebStorageError(status, text); @@ -156,23 +148,72 @@ const submitInput = z export class WebCommunity { private readonly queue: string[] = []; - private running = 0; + private readonly checking = new Set(); private sequence = 0; private readonly controller = new AbortController(); private readonly idle = new Set<() => void>(); constructor( private readonly storage: WebStorage, private readonly runner?: WebPrecheckRunner, - private readonly options: { concurrency?: number; now?: () => number } = {}, + private readonly options: { concurrency?: number; now?: () => number; externalWorker?: boolean } = {}, ) { + if (options.externalWorker) return; // A restart re-checks what was waiting; a check cut off mid-run is simply run again. - for (const file of this.storage.listRecords(['community', 'submissions'])) { - const item = this.storage.getRecord(['community', 'submissions', file]); - if (item && (item.status === 'queued' || item.status === 'checking')) this.queue.push(item.id); - } - this.queue.sort(); + this.write(() => { + const root = this.storage.root, + backend = root && nativeWeb(); + if (root && backend) { + this.queue.length = 0; + for (const id of backend.pendingCommunitySubmissions(root)) this.queue.push(id); + } else { + for (const file of this.storage.listRecords(['community', 'submissions'])) { + const item = this.storage.getRecord(['community', 'submissions', file]); + if (item && (item.status === 'queued' || item.status === 'checking')) this.queue.push(item.id); + } + this.queue.sort(); + } + }); this.pump(); } + /** Read the current records after the HTTP layer has authenticated the actor. */ + readPersistedRoute(path: string, actor?: CommunityActor) { + if (!this.storage.root) return; + return nativeWeb()?.readCommunity({ + root: this.storage.root, + path, + now: this.now(), + ...(actor && { actor: actor.key }), + admin: Boolean(actor?.admin), + checker: Boolean(this.runner), + locale: Intl.Collator().resolvedOptions().locale, + limits: communityLimits, + }); + } + private writing = false; + /** Hold the same record lock as the Rust listener only during synchronous commits. */ + private write(commit: () => T): T { + if (!this.storage.root || this.writing) return commit(); + const backend = nativeWeb(); + if (!backend) return commit(); + const guard = new backend.CommunityWriteLock(this.storage.root); + this.writing = true; + try { + const recovered = backend.recoverCommunityAdmission(this.storage.root); + if ( + !this.options.externalWorker && + recovered && + !this.checking.has(recovered) && + !this.queue.includes(recovered) + ) { + this.queue.push(recovered); + queueMicrotask(() => this.pump()); + } + return commit(); + } finally { + this.writing = false; + guard.release(); + } + } private now() { return this.options.now?.() ?? Date.now(); } @@ -223,10 +264,14 @@ export class WebCommunity { .filter((item): item is CommunitySubmission => Boolean(item)) .sort((a, b) => b.id.localeCompare(a.id)); } + private activityFile() { + return `${String(this.now()).padStart(15, '0')}-${String(this.sequence++).padStart(8, '0')}-${crypto.randomBytes(4).toString('hex')}.json`; + } private log(entry: Omit) { - const at = this.iso(), - name = `${String(this.now()).padStart(15, '0')}-${String(this.sequence++).padStart(8, '0')}-${crypto.randomBytes(4).toString('hex')}.json`; - this.storage.saveRecord(['community', 'activity', name], { at, ...entry } satisfies Activity); + this.storage.saveRecord(['community', 'activity', this.activityFile()], { + at: this.iso(), + ...entry, + } satisfies Activity); const files = this.storage.listRecords(['community', 'activity']); for (const file of files.slice(0, Math.max(0, files.length - communityLimits.activityKept))) this.storage.deleteRecord(['community', 'activity', file]); @@ -369,41 +414,47 @@ export class WebCommunity { }; } setProfile(actor: CommunityActor, raw: unknown) { - const name = parse(z.object({ handle }).strict(), raw, '名称需为 2–24 个字母、数字、下划线或连字符。').handle; - const previous = this.profile(actor.key), - slot = (value: string) => ['community', 'handles', `${mathDigest(value.normalize('NFKC').toLowerCase())}.json`]; - if (previous?.handle === name) return this.me(actor); - if (!this.storage.createRecord(slot(name), { owner: actor.key })) { - if (this.storage.getRecord<{ owner: string }>(slot(name))?.owner !== actor.key) fail(409, '这个名称已被使用。'); - } - if (previous) this.storage.deleteRecord(slot(previous.handle)); - this.storage.saveRecord(['community', 'profiles', `${actor.key}.json`], { - ...previous, - handle: name, - createdAt: previous?.createdAt ?? this.iso(), - } satisfies Profile); - return this.me(actor); + return this.write(() => { + const name = parse(z.object({ handle }).strict(), raw, '名称需为 2–24 个字母、数字、下划线或连字符。').handle; + const previous = this.profile(actor.key), + slot = (value: string) => ['community', 'handles', `${mathDigest(value.normalize('NFKC').toLowerCase())}.json`]; + if (previous?.handle === name) return this.me(actor); + if (!this.storage.createRecord(slot(name), { owner: actor.key })) { + if (this.storage.getRecord<{ owner: string }>(slot(name))?.owner !== actor.key) fail(409, '这个名称已被使用。'); + } + if (previous && slot(previous.handle)[2] !== slot(name)[2]) this.storage.deleteRecord(slot(previous.handle)); + this.storage.saveRecord(['community', 'profiles', `${actor.key}.json`], { + ...previous, + handle: name, + createdAt: previous?.createdAt ?? this.iso(), + } satisfies Profile); + return this.me(actor); + }); } /** A personal agent token, shown once. Only its digest is stored; issuing a new one revokes the previous. */ issueToken(actor: CommunityActor) { - const profile = this.requireProfile(actor), - token = `tosc_${crypto.randomBytes(32).toString('hex')}`, - digest = mathDigest(token); - if (profile.tokenDigest) this.storage.deleteRecord(['community', 'tokens', `${profile.tokenDigest}.json`]); - this.storage.saveRecord(['community', 'tokens', `${digest}.json`], { owner: actor.key }); - this.storage.saveRecord(['community', 'profiles', `${actor.key}.json`], { - ...profile, - tokenDigest: digest, - tokenCreatedAt: this.iso(), - } satisfies Profile); - return { token }; + return this.write(() => { + const profile = this.requireProfile(actor), + token = `tosc_${crypto.randomBytes(32).toString('hex')}`, + digest = mathDigest(token); + if (profile.tokenDigest) this.storage.deleteRecord(['community', 'tokens', `${profile.tokenDigest}.json`]); + this.storage.saveRecord(['community', 'tokens', `${digest}.json`], { owner: actor.key }); + this.storage.saveRecord(['community', 'profiles', `${actor.key}.json`], { + ...profile, + tokenDigest: digest, + tokenCreatedAt: this.iso(), + } satisfies Profile); + return { token }; + }); } revokeToken(actor: CommunityActor) { - const profile = this.requireProfile(actor); - if (profile.tokenDigest) this.storage.deleteRecord(['community', 'tokens', `${profile.tokenDigest}.json`]); - const { tokenDigest: _digest, tokenCreatedAt: _created, ...rest } = profile; - this.storage.saveRecord(['community', 'profiles', `${actor.key}.json`], rest satisfies Profile); - return this.me(actor); + return this.write(() => { + const profile = this.requireProfile(actor); + if (profile.tokenDigest) this.storage.deleteRecord(['community', 'tokens', `${profile.tokenDigest}.json`]); + const { tokenDigest: _digest, tokenCreatedAt: _created, ...rest } = profile; + this.storage.saveRecord(['community', 'profiles', `${actor.key}.json`], rest satisfies Profile); + return this.me(actor); + }); } actorForToken(token: string): CommunityActor | undefined { if (!communityTokenPattern.test(token)) return undefined; @@ -411,11 +462,9 @@ export class WebCommunity { saved = this.storage.getRecord<{ owner: string }>(['community', 'tokens', `${digest}.json`]); return saved && this.profile(saved.owner)?.tokenDigest === digest ? { key: saved.owner } : undefined; } - /** Publishing compiles the frozen module once, so a task that cannot even state its goal never opens. */ - async createTask(actor: CommunityActor, raw: unknown) { - if (!actor.admin) fail(403, '只有管理员可以发布社区题目。'); - const input = parse(createTaskInput, raw, '题目字段无效。'); - for (const part of [input.prelude, input.statement]) { + /** The checker only sees the frozen task source. Publication and account state belong to the caller. */ + async reviewTask(id: string, environment: WebEnvironment, prelude: string, statement: string) { + for (const part of [prelude, statement]) { const reason = communityLeanGuard(part, { allowedImports: () => false, allowNamespace: 'task' }) ?? (mathConstructionImports(part).length || @@ -424,17 +473,10 @@ export class WebCommunity { : undefined); if (reason) fail(400, reason); } - const numbers = this.storage - .listRecords(['community', 'tasks']) - .filter(id => taskId.safeParse(id).success) - .map(id => Number(id.slice(1))); - let next = Math.max(0, ...numbers) + 1; - while (this.storage.getRecord(this.taskPath(`T${next}`))) next++; - const id = `T${next}`, - built = communityTaskModule(id, input.environment, input.prelude, input.statement); + const built = communityTaskModule(id, environment, prelude, statement); if (this.runner) { const result = await this.runner( - { environment: input.environment, source: built.source, sourceFile: built.file }, + { environment, source: built.source, sourceFile: built.file }, this.controller.signal, ); const diagnostics = leanDiagnostics(result.output); @@ -444,6 +486,28 @@ export class WebCommunity { `题目模块没有通过编译:${diagnostics.diagnostics.find(item => item.severity === 'error')?.message ?? (result.timedOut ? '编译超时。' : '含 sorry 或编译失败。')}`, ); } + return built; + } + reviewSubmission(task: Pick, source: string) { + if (!this.runner) fail(503, '证明校验服务暂不可用。'); + const reason = communitySubmissionReason(task, source); + if (reason) fail(400, reason); + } + /** Publishing compiles the frozen module once, so a task that cannot even state its goal never opens. */ + async createTask(actor: CommunityActor, raw: unknown) { + if (!actor.admin) fail(403, '只有管理员可以发布社区题目。'); + const input = parse(createTaskInput, raw, '题目字段无效。'); + const root = this.storage.root, + backend = root && nativeWeb(); + const id = + root && backend + ? this.write(() => backend.nextCommunityTask(root)) + : `T${ + this.storage + .listRecords(['community', 'tasks']) + .reduce((max, id) => (taskId.safeParse(id).success ? Math.max(max, Number(id.slice(1))) : max), 0) + 1 + }`; + const built = await this.reviewTask(id, input.environment, input.prelude, input.statement); const task: CommunityTask = { id, title: input.title, @@ -458,131 +522,170 @@ export class WebCommunity { tags: input.tags, submissions: 0, }; - if (!this.storage.createRecord(this.taskPath(id), task)) fail(409, '题目编号冲突,请重试。'); - this.log({ kind: 'published', taskId: id }); - return { task: this.publicTask(task) }; + return this.write(() => { + if (root && backend) { + const result = backend.publishCommunityTask(root, Boolean(actor.admin), task, this.activityFile()); + if ('error' in result) fail(result.status, result.error); + } else { + if (!this.storage.createRecord(this.taskPath(id), task)) fail(409, '题目编号冲突,请重试。'); + this.log({ kind: 'published', taskId: id }); + } + return { task: this.publicTask(task) }; + }); } withdrawTask(actor: CommunityActor, id: string) { - if (!actor.admin) fail(403, '只有管理员可以撤下社区题目。'); - const task = this.readTask(id); - if (task.status !== 'open') fail(409, '只能撤下仍在开放的题目。'); - this.storage.saveRecord(this.taskPath(id), { ...task, status: 'withdrawn' } satisfies CommunityTask); - return { ok: true }; + return this.write(() => { + if (!actor.admin) fail(403, '只有管理员可以撤下社区题目。'); + const task = this.readTask(id); + if (task.status !== 'open') fail(409, '只能撤下仍在开放的题目。'); + this.storage.saveRecord(this.taskPath(id), { ...task, status: 'withdrawn' } satisfies CommunityTask); + return { ok: true }; + }); } /** Claims are not exclusive: they tell others who is working, expire on their own and can be renewed. */ claim(actor: CommunityActor, id: string) { - this.requireProfile(actor); - const task = this.readTask(id); - if (task.status !== 'open') fail(409, '这道题已经关闭。'); - const held = this.tasks().filter( - item => item.id !== id && this.claims(item.id).some(claim => claim.owner === actor.key), - ).length; - if (held >= communityLimits.claimsPerPerson) - fail(429, `最多同时认领 ${communityLimits.claimsPerPerson} 道题,请先放弃或完成一道。`); - const path = ['community', 'tasks', id, 'claims', `${actor.key}.json`], - renewed = this.storage.getRecord(path); - const claim: Claim = { - owner: actor.key, - claimedAt: renewed && Date.parse(renewed.expiresAt) > this.now() ? renewed.claimedAt : this.iso(), - expiresAt: new Date(this.now() + communityLimits.claimHours * 3_600_000).toISOString(), - }; - this.storage.saveRecord(path, claim); - if (!renewed || Date.parse(renewed.expiresAt) <= this.now()) - this.log({ kind: 'claimed', owner: actor.key, taskId: id }); - return this.task(id); + return this.write(() => { + this.requireProfile(actor); + const task = this.readTask(id); + if (task.status !== 'open') fail(409, '这道题已经关闭。'); + const held = this.tasks().filter( + item => item.id !== id && this.claims(item.id).some(claim => claim.owner === actor.key), + ).length; + if (held >= communityLimits.claimsPerPerson) + fail(429, `最多同时认领 ${communityLimits.claimsPerPerson} 道题,请先放弃或完成一道。`); + const path = ['community', 'tasks', id, 'claims', `${actor.key}.json`], + renewed = this.storage.getRecord(path); + const claim: Claim = { + owner: actor.key, + claimedAt: renewed && Date.parse(renewed.expiresAt) > this.now() ? renewed.claimedAt : this.iso(), + expiresAt: new Date(this.now() + communityLimits.claimHours * 3_600_000).toISOString(), + }; + this.storage.saveRecord(path, claim); + if (!renewed || Date.parse(renewed.expiresAt) <= this.now()) + this.log({ kind: 'claimed', owner: actor.key, taskId: id }); + return this.task(id); + }); } release(actor: CommunityActor, id: string) { - this.readTask(id); - const path = ['community', 'tasks', id, 'claims', `${actor.key}.json`]; - if (this.storage.getRecord(path)) { - this.storage.deleteRecord(path); - this.log({ kind: 'released', owner: actor.key, taskId: id }); - } - return this.task(id); + return this.write(() => { + this.readTask(id); + const path = ['community', 'tasks', id, 'claims', `${actor.key}.json`]; + if (this.storage.getRecord(path)) { + this.storage.deleteRecord(path); + this.log({ kind: 'released', owner: actor.key, taskId: id }); + } + return this.task(id); + }); } submit(actor: CommunityActor, raw: unknown) { - this.requireProfile(actor); - if (!this.runner) fail(503, '证明校验服务暂不可用。'); - const input = parse(submitInput, raw, '提交字段无效。'), - task = this.readTask(input.taskId); - if (task.status !== 'open') fail(409, task.status === 'solved' ? '这道题已经有人先解出。' : '这道题已经关闭。'); - const mine = this.ownSubmissions(actor.key), - now = this.now(); - if ( - mine.filter(item => item.status === 'queued' || item.status === 'checking').length >= - communityLimits.pendingPerPerson - ) - fail(429, `你已有 ${communityLimits.pendingPerPerson} 份提交在等待校验,请等它们出结果。`); - if ( - mine.filter(item => Date.parse(item.submittedAt) > now - 3_600_000).length >= communityLimits.submissionsPerHour - ) - fail(429, `每小时最多提交 ${communityLimits.submissionsPerHour} 次。`); - const reason = communitySubmissionReason(task, input.source); - if (reason) fail(400, reason); - const id = `s${now.toString(36).padStart(9, '0')}${crypto.randomBytes(6).toString('hex')}`; - const item: CommunitySubmission = { - id, - taskId: task.id, - owner: actor.key, - model: input.model, - harness: input.harness, - source: input.source, - submittedAt: this.iso(), - points: this.points(task, now), - status: 'queued', - }; - this.storage.saveRecord(['community', 'submissions', `${id}.json`], item); - this.storage.saveRecord(['community', 'tasks', task.id, 'submissions', `${id}.json`], { id }); - this.storage.saveRecord(['community', 'people', actor.key, 'submissions', `${id}.json`], { id }); - this.storage.saveRecord(this.taskPath(task.id), { - ...task, - submissions: task.submissions + 1, - } satisfies CommunityTask); - this.log({ - kind: 'submitted', - owner: actor.key, - taskId: task.id, - submissionId: id, - model: item.model || undefined, - harness: item.harness || undefined, + const id = this.write(() => { + this.requireProfile(actor); + if (!this.runner) fail(503, '证明校验服务暂不可用。'); + const input = parse(submitInput, raw, '提交字段无效。'), + task = this.readTask(input.taskId); + if (task.status !== 'open') fail(409, task.status === 'solved' ? '这道题已经有人先解出。' : '这道题已经关闭。'); + const now = this.now(), + root = this.storage.root, + backend = root && nativeWeb(); + if (root && backend) { + const result = backend.enqueueCommunitySubmission( + root, + actor.key, + input, + now, + this.activityFile(), + () => communitySubmissionReason(task, input.source) ?? '', + ); + return 'error' in result ? fail(result.status, result.error) : result.id; + } + const mine = this.ownSubmissions(actor.key); + if ( + mine.filter(item => item.status === 'queued' || item.status === 'checking').length >= + communityLimits.pendingPerPerson + ) + fail(429, `你已有 ${communityLimits.pendingPerPerson} 份提交在等待校验,请等它们出结果。`); + if ( + mine.filter(item => Date.parse(item.submittedAt) > now - 3_600_000).length >= communityLimits.submissionsPerHour + ) + fail(429, `每小时最多提交 ${communityLimits.submissionsPerHour} 次。`); + const reason = communitySubmissionReason(task, input.source); + if (reason) fail(400, reason); + const id = `s${now.toString(36).padStart(9, '0')}${crypto.randomBytes(6).toString('hex')}`; + const item: CommunitySubmission = { + id, + taskId: task.id, + owner: actor.key, + model: input.model, + harness: input.harness, + source: input.source, + submittedAt: this.iso(), + points: this.points(task, now), + status: 'queued', + }; + this.storage.saveRecord(['community', 'submissions', `${id}.json`], item); + this.storage.saveRecord(['community', 'tasks', task.id, 'submissions', `${id}.json`], { id }); + this.storage.saveRecord(['community', 'people', actor.key, 'submissions', `${id}.json`], { id }); + this.storage.saveRecord(this.taskPath(task.id), { + ...task, + submissions: task.submissions + 1, + } satisfies CommunityTask); + this.log({ + kind: 'submitted', + owner: actor.key, + taskId: task.id, + submissionId: id, + model: item.model || undefined, + harness: item.harness || undefined, + }); + return id; }); + this.wakeSubmission(id); + return this.submission(actor, id); + } + wakeSubmission(id: string) { + if (this.checking.has(id) || this.queue.includes(id)) return; this.queue.push(id); this.pump(); - return this.submission(actor, id); } private pump() { while ( this.runner && + !this.options.externalWorker && !this.controller.signal.aborted && - this.running < Math.max(1, this.options.concurrency ?? 1) && + this.checking.size < Math.max(1, this.options.concurrency ?? 1) && this.queue.length ) { const id = this.queue.shift()!; - this.running++; + this.checking.add(id); void this.verify(id) .catch(error => console.error('[community_check_failed]', id, error instanceof Error ? error.message : error)) .finally(() => { - this.running--; + this.checking.delete(id); this.pump(); - if (!this.running && !this.queue.length) for (const done of this.idle) done(); + if (!this.checking.size && !this.queue.length) for (const done of this.idle) done(); }); } } private save(item: CommunitySubmission) { this.storage.saveRecord(['community', 'submissions', `${item.id}.json`], item); } - private async verify(id: string) { - let item = this.submissionRecord(id); - if (item.status !== 'queued' && item.status !== 'checking') return; - const before = this.readTask(item.taskId); - if (before.status !== 'open') { - this.save({ ...item, status: 'late', reason: '校验前这道题已被先解出或关闭。', checkedAt: this.iso() }); - this.log({ kind: 'late', owner: item.owner, taskId: item.taskId, submissionId: id }); - return; - } + private nativeVerdict(id: string, passed: boolean, reason?: string) { + const backend = this.storage.root && nativeWeb(); + if (!backend || !this.storage.root) return false; + const root = this.storage.root; + this.write(() => { + backend.finishCommunitySubmission(root, id, passed, reason?.slice(0, 1500), this.iso(), this.activityFile()); + }); + return true; + } + /** Read the frozen inputs. The native worker owns scheduling and every receipt write. */ + async checkPersisted(id: string) { + const item = this.submissionRecord(id); + return this.checkProof(this.readTask(item.taskId), item); + } + private async checkProof(before: CommunityTask, item: CommunitySubmission) { // The static rules are re-applied so a rule tightened after submission still holds for queued work. let reason = communitySubmissionReason(before, item.source); - this.save((item = { ...item, status: 'checking' })); const result = reason ? undefined : await this.runner!( @@ -615,44 +718,61 @@ export class WebCommunity { ? '校验超时。' : (diagnostics?.diagnostics.find(entry => entry.severity === 'error')?.message ?? (diagnostics?.sorries ? '证明仍含 sorry。' : '证明没有通过独立校验(类型不符或依赖了不允许的公理)。')); - const task = this.readTask(item.taskId), - checkedAt = this.iso(); - if (!passed) { - this.save({ ...item, status: 'rejected', reason: reason!.slice(0, 1_500), checkedAt }); - this.log({ kind: 'rejected', owner: item.owner, taskId: item.taskId, submissionId: id }); - return; - } - if (task.status !== 'open') { - this.save({ ...item, status: 'late', reason: '证明通过,但这道题已被先解出。', checkedAt }); + return { passed, reason: reason?.slice(0, 1500) }; + } + private async verify(id: string) { + const item = this.submissionRecord(id); + if (item.status !== 'queued' && item.status !== 'checking') return; + const before = this.readTask(item.taskId); + if (before.status !== 'open') { + if (this.nativeVerdict(id, false)) return; + this.save({ ...item, status: 'late', reason: '校验前这道题已被先解出或关闭。', checkedAt: this.iso() }); this.log({ kind: 'late', owner: item.owner, taskId: item.taskId, submissionId: id }); return; } - this.save({ ...item, status: 'accepted', checkedAt }); - this.storage.saveRecord(this.taskPath(task.id), { - ...task, - status: 'solved', - solvedBy: item.owner, - solvedAt: checkedAt, - solution: id, - points: item.points, - ...(item.model ? { model: item.model } : {}), - ...(item.harness ? { harness: item.harness } : {}), - } satisfies CommunityTask); - for (const file of this.storage.listRecords(['community', 'tasks', task.id, 'claims'])) - this.storage.deleteRecord(['community', 'tasks', task.id, 'claims', file]); - this.log({ - kind: 'accepted', - owner: item.owner, - taskId: item.taskId, - submissionId: id, - points: item.points, - model: item.model || undefined, - harness: item.harness || undefined, + this.save({ ...item, status: 'checking' }); + const { passed, reason } = await this.checkProof(before, item); + if (this.nativeVerdict(id, passed, reason)) return; + this.write(() => { + const task = this.readTask(item.taskId), + checkedAt = this.iso(); + if (!passed) { + this.save({ ...item, status: 'rejected', reason: reason!.slice(0, 1_500), checkedAt }); + this.log({ kind: 'rejected', owner: item.owner, taskId: item.taskId, submissionId: id }); + return; + } + if (task.status !== 'open') { + this.save({ ...item, status: 'late', reason: '证明通过,但这道题已被先解出。', checkedAt }); + this.log({ kind: 'late', owner: item.owner, taskId: item.taskId, submissionId: id }); + return; + } + this.save({ ...item, status: 'accepted', checkedAt }); + this.storage.saveRecord(this.taskPath(task.id), { + ...task, + status: 'solved', + solvedBy: item.owner, + solvedAt: checkedAt, + solution: id, + points: item.points, + ...(item.model ? { model: item.model } : {}), + ...(item.harness ? { harness: item.harness } : {}), + } satisfies CommunityTask); + for (const file of this.storage.listRecords(['community', 'tasks', task.id, 'claims'])) + this.storage.deleteRecord(['community', 'tasks', task.id, 'claims', file]); + this.log({ + kind: 'accepted', + owner: item.owner, + taskId: item.taskId, + submissionId: id, + points: item.points, + model: item.model || undefined, + harness: item.harness || undefined, + }); }); } /** Resolves once nothing is queued or running; tests and shutdown use it. */ settled(): Promise { - if (!this.running && !this.queue.length) return Promise.resolve(); + if (!this.checking.size && !this.queue.length) return Promise.resolve(); return new Promise(resolve => { const done = () => { this.idle.delete(done); @@ -693,6 +813,10 @@ export async function handleCommunityRequest( return write(); }; let found: RegExpExecArray | null; + if (method === 'GET') { + const result = community.readPersistedRoute(path, actor); + if (result) return result; + } if (method === 'GET' && path === '/api/community/overview') return { status: 200, body: community.overview() }; if (method === 'GET' && (found = match(/^\/api\/community\/tasks\/([^/]+)$/u))) return { status: 200, body: community.task(found[1]!) }; diff --git a/apps/web/communityTypes.ts b/apps/web/communityTypes.ts index a4b85ea8..f832a78f 100644 --- a/apps/web/communityTypes.ts +++ b/apps/web/communityTypes.ts @@ -68,4 +68,5 @@ export type CommunityOverview = CommunityBoards & { tasks: CommunityPublicTask[]; totals: { tasks: number; open: number; solved: number; submissions: number; people: number; working: number }; checker: boolean; + readOnly?: true; }; diff --git a/apps/web/explain.ts b/apps/web/explain.ts index 1be4a884..41caad4c 100644 --- a/apps/web/explain.ts +++ b/apps/web/explain.ts @@ -1,3 +1,4 @@ +import { queueCounts } from './queueCounts'; import type { TrajectoryVersionDetail } from './trajectory'; import type { WebCheckReceipt } from './collaboration'; import type { WebEffort, WebRun } from './shared'; @@ -259,8 +260,12 @@ export class WebExplainer { private readonly busy = new Set(); private readonly asked = new Map(); constructor(private readonly timeoutMs = 0) {} + onQueueChange?: () => void; + queueState() { + return { running: this.busy.size, waiting: [] }; + } counts() { - return { running: this.busy.size, queued: 0 }; + return queueCounts(this.queueState()); } async ask(owner: string, call: Omit, signal?: AbortSignal): Promise { @@ -269,11 +274,13 @@ export class WebExplainer { if (this.busy.has(owner)) throw new WebExplainError(429, '上一个问题还在回答,请等它结束或先停止。'); if (recent.length >= pace.questions) throw new WebExplainError(429, '提问太频繁,请过几分钟再问。'); this.busy.add(owner); + this.onQueueChange?.(); this.asked.set(owner, [...recent, now]); try { return await askProvider({ ...call, timeoutMs: this.timeoutMs }, signal); } finally { this.busy.delete(owner); + this.onQueueChange?.(); } } prune() { diff --git a/apps/web/explanation.ts b/apps/web/explanation.ts index 9b5ec63f..cb8b979e 100644 --- a/apps/web/explanation.ts +++ b/apps/web/explanation.ts @@ -1,3 +1,4 @@ +import { nativeProcess } from '../../src/math/nativeProcess'; import { getLeanTaskEnvironment } from '../../src/math/leanTaskEnvironment'; import { assertInformalizationEvidence, @@ -381,6 +382,17 @@ export function explanationDocument( }; } +/** The workbench reads saved explanations through its packaged native process library. */ +export function savedExplanationDocument( + evidence: InformalizationEvidence, + proof: string, + formalization?: FormalizationEvidence, +): WebExplanationDocument { + return nativeProcess + ? nativeProcess.informalizationDocument(evidence, proof, formalization) + : explanationDocument(evidence, proof, formalization); +} + export function explanationMarkdownFilename(runId: string, target: string, language: WebExplanationLanguage): string { const name = target diff --git a/apps/web/explanations.ts b/apps/web/explanations.ts index d3cddd8b..f9e315e1 100644 --- a/apps/web/explanations.ts +++ b/apps/web/explanations.ts @@ -1,8 +1,9 @@ +import { queueCounts } from './queueCounts'; import crypto from 'node:crypto'; import { mathDigest } from '../../src/math/mathRuntimeIo'; import { informalizationRetryLimit } from '../../src/solver/informalization'; import { webExplanationLimits } from './config'; -import { explanationDocument, verifyExplanationEvidence } from './explanation'; +import { savedExplanationDocument, verifyExplanationEvidence } from './explanation'; import { explanationCheckpointBinding } from './explanationCheckpoint'; import type { WebRunner } from './runner'; import type { @@ -74,10 +75,15 @@ export class WebExplanations { } } + onQueueChange?: () => void; + queueState() { + const waiting = [...this.jobs.values()] + .filter(job => job.explanation.status === 'queued') + .map(job => job.explanation.createdAt); + return { running: this.running, waiting }; + } counts() { - const queued = [...this.jobs.values()].filter(job => job.explanation.status === 'queued'); - const oldestQueuedAt = queued.map(job => job.explanation.createdAt).sort()[0]; - return { running: this.running, queued: queued.length, ...(oldestQueuedAt ? { oldestQueuedAt } : {}) }; + return queueCounts(this.queueState()); } /** The run's explanations without their documents, newest state first from memory. */ list(owner: string, runId: string): WebExplanation[] { @@ -112,7 +118,7 @@ export class WebExplanations { this.storage.getExplanationEvidence(owner, run.id, explanationKey(target, language)), binding, ); - return { ...explanation, document: explanationDocument(evidence, binding.proof) }; + return { ...explanation, document: savedExplanationDocument(evidence, binding.proof) }; } catch (error) { return { ...explanation, reason: reasonOf(error) }; } @@ -168,6 +174,7 @@ export class WebExplanations { } } } + this.onQueueChange?.(); queueMicrotask(() => this.pump()); } private capacity(owner: string) { @@ -250,6 +257,7 @@ export class WebExplanations { this.release(job); throw error; } + this.onQueueChange?.(); queueMicrotask(() => this.pump()); return this.view(job); } @@ -309,6 +317,7 @@ export class WebExplanations { return this.jobs.get(this.id(job.owner, job.run.id, job.key)) === job; } private release(job: Job) { + this.onQueueChange?.(); if (this.current(job)) this.jobs.delete(this.id(job.owner, job.run.id, job.key)); job.input.apiKey = ''; delete job.input.checkpoint; @@ -345,6 +354,7 @@ export class WebExplanations { ); if (!job) break; this.running++; + this.onQueueChange?.(); const now = new Date().toISOString(); Object.assign(job.explanation, { status: 'running', @@ -353,6 +363,7 @@ export class WebExplanations { }); void this.execute(job).finally(() => { this.running--; + this.onQueueChange?.(); this.pump(); }); } @@ -420,7 +431,7 @@ export class WebExplanations { }; const { evidence } = verifyExplanationEvidence(result.evidence, binding); // The projection must work before approval; its document is not stored, read() projects it again. - explanationDocument(evidence, binding.proof); + savedExplanationDocument(evidence, binding.proof); this.storage.saveExplanationEvidence(job.owner, job.run.id, job.key, evidence); this.finish(job, { status: 'approved' }); if (job.input.checkpoint) this.storage.deleteExplanationCheckpoint(job.owner, job.run.id, job.key); diff --git a/apps/web/formalizations.ts b/apps/web/formalizations.ts index 8c35ba43..81319bb0 100644 --- a/apps/web/formalizations.ts +++ b/apps/web/formalizations.ts @@ -1,3 +1,4 @@ +import { queueCounts } from './queueCounts'; import type { WorkerFormalizationAuditInput } from './formalizationAuditTypes'; import crypto from 'node:crypto'; import { @@ -237,20 +238,21 @@ export class WebFormalizations { }) .sort((a, b) => b.createdAt.localeCompare(a.createdAt)); } + onQueueChange?: () => void; + queueState() { + const waiting = [ + ...[...this.jobs.values()] + .filter(job => job.record.formalization.status === 'queued') + .map(job => job.record.formalization.createdAt), + ...[...this.auditJobs.values()].flatMap(job => { + const review = job.record.formalization.backgroundReview; + return review?.status === 'queued' ? [review.queuedAt] : []; + }), + ]; + return { running: this.running + this.auditsRunning, waiting }; + } counts() { - const queued = [...this.jobs.values()].filter(job => job.record.formalization.status === 'queued'); - const auditQueued = [...this.auditJobs.values()].filter( - job => job.record.formalization.backgroundReview?.status === 'queued', - ); - const oldestQueuedAt = [ - ...queued.map(job => job.record.formalization.createdAt), - ...auditQueued.map(job => job.record.formalization.backgroundReview!.queuedAt), - ].sort()[0]; - return { - running: this.running + this.auditsRunning, - queued: queued.length + auditQueued.length, - ...(oldestQueuedAt ? { oldestQueuedAt } : {}), - }; + return queueCounts(this.queueState()); } private view(value: WebFormalization): WebFormalization { if (value.status !== 'queued') return value; @@ -535,6 +537,7 @@ export class WebFormalizations { this.release(job); throw error; } + this.onQueueChange?.(); queueMicrotask(() => this.pump()); return this.view(formalization); } @@ -678,6 +681,7 @@ export class WebFormalizations { this.storage.saveRecord([...recordPath(record.owner, record.formalization.id), 'record.json'], record); } private release(job: Job) { + this.onQueueChange?.(); if (this.current(job)) this.jobs.delete(this.key(job.record.owner, job.record.formalization.id)); job.input.apiKey = ''; } @@ -749,6 +753,7 @@ export class WebFormalizations { maxTotalTokens, maxRunSeconds: 0, }; + this.onQueueChange?.(); this.auditJobs.set(this.key(job.record.owner, value.id), { record: job.record, input, @@ -762,6 +767,7 @@ export class WebFormalizations { return this.auditJobs.get(this.key(job.record.owner, job.record.formalization.id)) === job; } private releaseAudit(job: AuditJob) { + this.onQueueChange?.(); if (this.currentAudit(job)) this.auditJobs.delete(this.key(job.record.owner, job.record.formalization.id)); job.input.apiKey = ''; } @@ -798,8 +804,10 @@ export class WebFormalizations { job.record.formalization.updatedAt = now; this.save(job.record); this.auditsRunning++; + this.onQueueChange?.(); void this.executeAudit(job).finally(() => { this.auditsRunning--; + this.onQueueChange?.(); this.pumpAudits(); }); } @@ -865,12 +873,14 @@ export class WebFormalizations { const job = [...this.jobs.values()].find(item => item.record.formalization.status === 'queued'); if (!job) break; this.running++; + this.onQueueChange?.(); Object.assign(job.record.formalization, { status: 'running', progress: { phase: 'preparing', updatedAt: new Date().toISOString() }, }); void this.execute(job).finally(() => { this.running--; + this.onQueueChange?.(); this.pump(); }); } diff --git a/apps/web/jobs.ts b/apps/web/jobs.ts index 929318a9..cac0023d 100644 --- a/apps/web/jobs.ts +++ b/apps/web/jobs.ts @@ -1,3 +1,5 @@ +import { queueCounts } from './queueCounts'; +import { nativeWeb } from './nativeWeb'; import { webProviderExecutionDigest, webProviderHarness, webHarnessResearchError } from './harness'; import crypto from 'node:crypto'; import type { WebConfig } from './config'; @@ -118,10 +120,13 @@ export class WebJobs { } } + onQueueChange?: () => void; + queueState() { + const waiting = [...this.jobs.values()].filter(job => job.run.status === 'queued').map(job => job.run.createdAt); + return { running: this.running, waiting }; + } counts() { - const queued = [...this.jobs.values()].filter(job => job.run.status === 'queued'); - const oldestQueuedAt = queued.map(job => job.run.createdAt).sort()[0]; - return { running: this.running, queued: queued.length, ...(oldestQueuedAt ? { oldestQueuedAt } : {}) }; + return queueCounts(this.queueState()); } list(owner: string): WebRun[] { return [...this.jobs.values()] @@ -133,6 +138,17 @@ export class WebJobs { const job = this.jobs.get(id); return job?.owner === owner ? job.run : undefined; } + private sessionLists?: (owner: string, runs: WebRun[], version: string) => void; + private actionTallies?: (owner: string, runId: string, actions: NonNullable) => void; + sessionVersionId() { + return this.versionId; + } + publishSessionLists(callback: NonNullable, tallies?: NonNullable) { + this.actionTallies = tallies; + this.sessionLists = callback; + for (const owner of new Set([...this.jobs.values()].map(job => job.owner))) + callback(owner, this.list(owner), this.version(owner)); + } version(owner: string): string { const identity = `${this.versionId}/${owner}/${this.revisions.get(owner) ?? 0}`; return `"${crypto.createHash('sha256').update(identity).digest('hex')}"`; @@ -152,6 +168,13 @@ export class WebJobs { ? input : { ...input, researchMode: input.researchMode ?? 'skill', skillLoading: input.skillLoading ?? 'file' }; const { apiKey: _key, ...visible } = normalized; + const providerIdentity = { + id: provider.id, + baseUrl: provider.baseUrl, + ...(provider.harness || provider.execution ? { executionDigest: webProviderExecutionDigest(provider) } : {}), + }; + const native = nativeWeb(); + if (native) return native.runCreationIdentity(visible, providerIdentity, requestId); return { schema: 'theorem-os.web-creation.v1', requestId, @@ -160,13 +183,7 @@ export class WebJobs { .update( canonicalMathJson({ input: { ...visible, environment: input.environment ?? 'standard' }, - provider: { - id: provider.id, - baseUrl: provider.baseUrl, - ...(provider.harness || provider.execution - ? { executionDigest: webProviderExecutionDigest(provider) } - : {}), - }, + provider: providerIdentity, }), ) .digest('hex'), @@ -219,14 +236,28 @@ export class WebJobs { if (modeError) throw new WebStorageError(400, modeError); const previous = this.replay(owner, creationInput, provider, requestId); if (previous) return previous; - if (this.closing) throw new Error('服务正在停止,请稍后重试。'); - const count = (status: string) => [...this.jobs.values()].filter(job => job.run.status === status).length; - const active = count('running'), - waiting = count('queued'); - if (active + waiting >= this.config.queueLimit) - throw new Error(`运行队列已满:${active} 个任务正在运行,${waiting} 个在排队。草稿已保留,请等几分钟后再提交。`); - if (this.list(owner).length >= webLimits.maxRuns) - throw new Error(`已达到 ${webLimits.maxRuns} 条运行记录的上限。请先下载需要的档案,删除已结束的记录后重试。`); + const native = nativeWeb(); + if (native) { + const error = native.queueAdmission( + this.closing, + [...this.jobs.values()].map(j => j.run.status), + this.list(owner).length, + this.config.queueLimit, + webLimits.maxRuns, + ); + if (error) throw new Error(error); + } else { + if (this.closing) throw new Error('服务正在停止,请稍后重试。'); + const count = (status: string) => [...this.jobs.values()].filter(job => job.run.status === status).length; + const active = count('running'), + waiting = count('queued'); + if (active + waiting >= this.config.queueLimit) + throw new Error( + `运行队列已满:${active} 个任务正在运行,${waiting} 个在排队。草稿已保留,请等几分钟后再提交。`, + ); + if (this.list(owner).length >= webLimits.maxRuns) + throw new Error(`已达到 ${webLimits.maxRuns} 条运行记录的上限。请先下载需要的档案,删除已结束的记录后重试。`); + } const now = new Date().toISOString(); const knowledgeDigest = input.knowledgeDigest === undefined @@ -249,20 +280,26 @@ export class WebJobs { else delete pinnedInput.knowledgeDigest; const { apiKey, knowledgeDigest: _selectedKnowledgeDigest, ...visible } = pinnedInput; const environment = input.environment ?? 'standard'; - const run: WebRun = { + const fields = { ...clean(visible, apiKey), ...(knowledgeDigest !== undefined ? { knowledgeDigest } : {}), + ...(formalization ? { formalization: formalization.provenance } : {}), environment, - id: crypto.randomUUID(), - title: '', - status: 'queued', - phase: 'queued', - createdAt: now, - updatedAt: now, - timings: {}, - events: [], - modules: {}, }; + const run: WebRun = native + ? native.initialRun(fields, now) + : { + ...fields, + id: crypto.randomUUID(), + title: (formalization?.provenance.original.trim() || fields.task).split('\n')[0].slice(0, 60) || 'Lean 研究', + status: 'queued', + phase: 'queued', + createdAt: now, + updatedAt: now, + timings: {}, + events: [], + modules: {}, + }; if (input.continueFrom && continuation) run.continueFrom = clean( { @@ -274,9 +311,7 @@ export class WebJobs { }, apiKey, ); - if (formalization) run.formalization = formalization.provenance; if (researchConfiguration) run.researchConfiguration = structuredClone(researchConfiguration); - run.title = (formalization?.provenance.original.trim() || run.task).split('\n')[0].slice(0, 60) || 'Lean 研究'; if (provider.harness || provider.execution) { run.harness = webProviderHarness(provider); run.harnessConfigurationDigest = webProviderExecutionDigest(provider); @@ -291,7 +326,7 @@ export class WebJobs { const creation = requestId ? this.creation(normalizeWebTeamPreferences(creationInput), provider, requestId) : undefined; - this.event(run, 'queued', '任务已进入队列'); + if (!native) this.event(run, 'queued', '任务已进入队列'); // Persist the identity and initial run atomically before a worker can be queued. this.storage.saveRun(owner, run, creation); if (creation) this.creations.set(JSON.stringify([owner, requestId]), { ...creation, runId: run.id }); @@ -364,23 +399,31 @@ export class WebJobs { cancel(owner: string, id: string): WebRun | undefined { const job = this.jobs.get(id); if (!job || job.owner !== owner) return undefined; - // The worker reports Lean acceptance before the runner finishes Docker cleanup. - if (!terminal(job.run) && job.run.result?.status !== 'evaluated_passed') { - const queued = job.run.status === 'queued'; - job.run.status = 'cancelled'; - job.run.phase = 'cancelled'; - job.run.finishedAt = new Date().toISOString(); - delete job.run.queue; - try { + const native = nativeWeb(); + const queued = job.run.status === 'queued'; + const now = new Date().toISOString(); + const cancelled = native?.cancelRun(job.run, now, webRunEventLimit); + if (native ? !cancelled : terminal(job.run) || job.run.result?.status === 'evaluated_passed') return job.run; + try { + if (cancelled) { + Object.assign(job.run, cancelled); + delete job.run.queue; + if (!job.run.modules) recordWebModuleEvent(job.run, job.run.events.at(-1)!); + this.persist(job.run); + } else { + job.run.status = 'cancelled'; + job.run.phase = 'cancelled'; + job.run.finishedAt = now; + delete job.run.queue; this.event(job.run, 'cancelled', '运行已取消'); - } finally { - job.controller.abort(); - job.input.apiKey = ''; - delete job.continuation; - delete job.formalization; - delete job.compiledFormalization; - if (queued) this.reindex(); } + } finally { + job.controller.abort(); + job.input.apiKey = ''; + delete job.continuation; + delete job.formalization; + delete job.compiledFormalization; + if (queued) this.reindex(); } return job.run; } @@ -474,11 +517,12 @@ export class WebJobs { } private changed(owner: string) { this.revisions.set(owner, (this.revisions.get(owner) ?? 0) + 1); - if (!this.listeners.has(owner) || this.pendingNotifications.has(owner)) return; + if ((!this.listeners.has(owner) && !this.sessionLists) || this.pendingNotifications.has(owner)) return; this.pendingNotifications.add(owner); queueMicrotask(() => { this.pendingNotifications.delete(owner); const version = this.version(owner); + this.sessionLists?.(owner, this.list(owner), version); for (const listener of this.listeners.get(owner) ?? []) listener(version); }); } @@ -731,25 +775,51 @@ export class WebJobs { this.persist(run); } private pump() { - while (!this.closing && this.running < this.config.concurrency) { - const job = [...this.jobs.values()].find(item => item.run.status === 'queued'); - if (!job) break; - this.running++; - job.run.status = 'running'; - job.run.phase = 'preparing'; - delete job.run.queue; - void this.execute(job).finally(() => { - this.running--; - this.pump(); - }); + if (this.closing) return; + const native = nativeWeb(); + if (native) { + const waiting = [...this.jobs.values()].filter(j => j.run.status === 'queued').map(j => j.run.id); + for (const id of native.planWebQueue(waiting, this.running, this.config.concurrency, true).start) { + const job = this.jobs.get(id); + if (job?.run.status === 'queued') this.startWorker(job); + } + } else { + while (!this.closing && this.running < this.config.concurrency) { + const job = [...this.jobs.values()].find(j => j.run.status === 'queued'); + if (!job) break; + this.startWorker(job); + } } this.reindex(); } + private startWorker(job: Job) { + this.running++; + job.run.status = 'running'; + job.run.phase = 'preparing'; + delete job.run.queue; + void this.execute(job).finally(() => { + this.running--; + this.onQueueChange?.(); + this.pump(); + }); + } /** Queue positions are global and first-in first-out; only counts are shown, never other owners' runs. */ private reindex() { + this.onQueueChange?.(); const queued = [...this.jobs.values()].filter(job => job.run.status === 'queued'); + const positions = nativeWeb()?.planWebQueue( + queued.map(j => j.run.id), + this.running, + this.config.concurrency, + false, + ).waiting; queued.forEach((job, index) => { - const queue = { position: index + 1, ahead: index, running: this.running, slots: this.config.concurrency }; + const queue = positions?.[index]?.queue ?? { + position: index + 1, + ahead: index, + running: this.running, + slots: this.config.concurrency, + }; const previous = job.run.queue; if (previous && Object.entries(queue).every(([key, value]) => previous[key as keyof typeof queue] === value)) return; @@ -816,6 +886,7 @@ export class WebJobs { }); tally.count = sequence; } + this.actionTallies?.(job.owner, job.run.id, tally); this.actionsChanged(job.run); } else if (message.type === 'artifact') { if (job.run.result) return; diff --git a/apps/web/keyVault.ts b/apps/web/keyVault.ts index f8a02b4b..a7f0db16 100644 --- a/apps/web/keyVault.ts +++ b/apps/web/keyVault.ts @@ -15,6 +15,7 @@ export class WebKeyVault { constructor( private readonly secret: Buffer, private readonly storage: WebStorage, + private readonly writer?: (message: object) => unknown, ) {} private path(accountId: string) { @@ -49,6 +50,10 @@ export class WebKeyVault { }); } save(accountId: string, providerId: string, baseUrl: string, key: string) { + if (this.writer) { + this.writer({ op: 'vault', account: accountId, provider: providerId, url: baseUrl, key }); + return; + } const iv = crypto.randomBytes(12), cipher = crypto.createCipheriv('aes-256-gcm', this.secret, iv); cipher.setAAD(this.aad(accountId, providerId, baseUrl)); @@ -63,6 +68,10 @@ export class WebKeyVault { this.storage.saveRecord(this.path(accountId), record); } forget(accountId: string, providerId: string) { + if (this.writer) { + this.writer({ op: 'vault', account: accountId, provider: providerId }); + return; + } const record = this.read(accountId); if (!record.providers[providerId]) return; delete record.providers[providerId]; @@ -70,6 +79,10 @@ export class WebKeyVault { else this.storage.deleteRecord(this.path(accountId)); } forgetAccount(accountId: string) { + if (this.writer) { + this.writer({ op: 'vault', account: accountId }); + return; + } this.storage.deleteRecord(this.path(accountId)); } } diff --git a/apps/web/nativeDockerOperation.ts b/apps/web/nativeDockerOperation.ts new file mode 100644 index 00000000..2ac7b974 --- /dev/null +++ b/apps/web/nativeDockerOperation.ts @@ -0,0 +1,56 @@ +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/nativeWeb.ts b/apps/web/nativeWeb.ts new file mode 100644 index 00000000..65d32f57 --- /dev/null +++ b/apps/web/nativeWeb.ts @@ -0,0 +1,82 @@ +import type { WebCreation } from './storage'; +import type { WebRun } from './shared'; +type StaticFiles = { + serve( + root: string, + relative: string, + acceptEncoding: string, + ifNoneMatch: string, + head: boolean, + ): { status: number; headers: Record; body?: Buffer; error?: string }; +}; + +type AdmissionError = { status: number; error: string }; +type WebBackend = { + persistRun(root: string, owner: string, summary: unknown, observation?: number, creation?: WebCreation): void; + planWebQueue( + queued: string[], + running: number, + slots: number, + dispatch: boolean, + ): { start: string[]; waiting: { id: string; queue: NonNullable }[] }; + runCreationIdentity(input: unknown, provider: unknown, requestId: string): WebCreation; + queueAdmission( + closing: boolean, + statuses: string[], + owned: number, + queueLimit: number, + ownerLimit: number, + ): string | undefined; + initialRun(fields: unknown, at: string): WebRun; + cancelRun(run: WebRun, at: string, eventLimit: number): WebRun | undefined; + recoverCommunityAdmission(root: string): string | undefined; + pendingCommunitySubmissions(root: string): string[]; + nextCommunityTask(root: string): string; + publishCommunityTask( + root: string, + admin: boolean, + task: unknown, + activityFile: string, + ): { status: 201 } | AdmissionError; + enqueueCommunitySubmission( + root: string, + owner: string, + input: unknown, + now: number, + activityFile: string, + checkSource: () => string, + ): { status: 202; id: string } | AdmissionError; + finishCommunitySubmission( + root: string, + id: string, + passed: boolean, + reason: string | undefined, + checkedAt: string, + activityFile: string, + ): unknown; + CommunityWriteLock: new (root: string) => { release(): void }; + WebSessionWriter: new (socket: string) => { update(message: string): string }; + WorkbenchStatic: new () => StaticFiles; + readCommunity(request: { + root: string; + path: string; + now: number; + actor?: string; + admin: boolean; + checker: boolean; + locale: string; + limits: Record; + }): { status: number; body: unknown }; +}; + +let loaded: WebBackend | undefined; +export function nativeWeb(): WebBackend | undefined { + const library = process.env.THEOREMOS_WEB_STATIC_ADDON; + if (!library) return; + if (!loaded) { + const handle = { exports: {} as WebBackend }; + process.dlopen(handle, library); + loaded = handle.exports; + } + return loaded; +} diff --git a/apps/web/operations.ts b/apps/web/operations.ts index 0b4f6865..8669fa1b 100644 --- a/apps/web/operations.ts +++ b/apps/web/operations.ts @@ -4,6 +4,7 @@ import type { WebStorage } from './storage'; const maintenanceFile = ['operations', 'maintenance.json']; /** Shared with the host operations CLI so maintenance does not require impersonating a user's login. */ export class WebOperations { + onMailFailure?: () => void; private smtp = 0; private lastSmtpFailureAt?: string; constructor( @@ -19,6 +20,7 @@ export class WebOperations { mailFailed() { this.smtp++; this.lastSmtpFailureAt = new Date().toISOString(); + this.onMailFailure?.(); } failures() { return { smtp: this.smtp, ...(this.lastSmtpFailureAt ? { lastSmtpFailureAt: this.lastSmtpFailureAt } : {}) }; diff --git a/apps/web/paperDrafts.ts b/apps/web/paperDrafts.ts index 13062948..4d51ffdc 100644 --- a/apps/web/paperDrafts.ts +++ b/apps/web/paperDrafts.ts @@ -1,3 +1,4 @@ +import { queueCounts } from './queueCounts'; import crypto from 'node:crypto'; import { mathDigest } from '../../src/math/mathRuntimeIo'; import { paperTemplate, type PaperLanguage } from '../../src/math/paperDraft'; @@ -17,8 +18,12 @@ export class WebPaperDrafts { this.storage.interruptPaperDrafts(); } + onQueueChange?: () => void; + queueState() { + return { running: this.active.size, waiting: [] }; + } counts() { - return { running: this.active.size, queued: 0 }; + return queueCounts(this.queueState()); } isGenerating(owner: string, runId: string) { @@ -120,8 +125,12 @@ export class WebPaperDrafts { .catch(() => { /* A storage outage leaves the last durable checkpoint available for a retry. */ }) - .finally(() => this.active.delete(owner)); + .finally(() => { + this.active.delete(owner); + this.onQueueChange?.(); + }); this.active.set(owner, { id: job.id, runId: run.id, done, controller }); + this.onQueueChange?.(); return job; } diff --git a/apps/web/precheck.ts b/apps/web/precheck.ts index 256a45fd..1bc26936 100644 --- a/apps/web/precheck.ts +++ b/apps/web/precheck.ts @@ -1,3 +1,4 @@ +import { queueCounts } from './queueCounts'; import crypto from 'node:crypto'; import { inspectScopedLeanDeclarations } from '../../src/math/leanSource'; import { LEAN_TASK_DECLARATIONS_MAX } from '../../src/math/leanTask'; @@ -161,9 +162,12 @@ export class WebPrechecker { private readonly limits = { concurrency: 2, queue: 6, perMinute: 20, cache: 200 }, ) {} + onQueueChange?: () => void; + queueState() { + return { running: this.running, waiting: this.waiting.map(item => item.createdAt) }; + } counts() { - const oldestQueuedAt = this.waiting[0]?.createdAt; - return { running: this.running, queued: this.waiting.length, ...(oldestQueuedAt ? { oldestQueuedAt } : {}) }; + return queueCounts(this.queueState(), true); } async check( owner: string, @@ -222,12 +226,17 @@ export class WebPrechecker { }; const leave = () => { this.waiting.splice(this.waiting.indexOf(turn), 1); + this.onQueueChange?.(); reject(controller.signal.reason); }; this.waiting.push(turn); + this.onQueueChange?.(); controller.signal.addEventListener('abort', leave, { once: true }); }); - } else this.running++; + } else { + this.running++; + this.onQueueChange?.(); + } try { controller.signal.throwIfAborted(); let output: WebPrecheckOutput | undefined; @@ -250,6 +259,7 @@ export class WebPrechecker { const next = this.waiting.shift(); if (next) next.start(); else this.running--; + this.onQueueChange?.(); } } finally { signal.removeEventListener('abort', stop); diff --git a/apps/web/queueCounts.ts b/apps/web/queueCounts.ts new file mode 100644 index 00000000..11f1c2ea --- /dev/null +++ b/apps/web/queueCounts.ts @@ -0,0 +1,4 @@ +export function queueCounts(state: { running: number; waiting: string[] }, fifo = false) { + const oldestQueuedAt = fifo ? state.waiting[0] : state.waiting.toSorted()[0]; + return { running: state.running, queued: state.waiting.length, ...(oldestQueuedAt ? { oldestQueuedAt } : {}) }; +} diff --git a/apps/web/runner.ts b/apps/web/runner.ts index aecd1d83..04d77048 100644 --- a/apps/web/runner.ts +++ b/apps/web/runner.ts @@ -7,6 +7,8 @@ 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'; @@ -414,6 +416,116 @@ export function parseFormalizationMessage( } } +function decodeCommandResult(value: unknown, id: string, command: WebCommand): WebCommandResult { + if (!object(value) || typeof value.id !== 'string' || typeof value.status !== 'string') throw new Error(); + const { observation, sourceBlobs, libraryRestart: transition, ...receipt } = value; + const observed = + observation === undefined + ? undefined + : readWorkerObservation(observation, sourceBlobs, { runId: id, sources: new Map() }); + if (observation !== undefined && !observed) throw new Error(); + const libraryRestart = transition === undefined ? undefined : libraryRestartSchema.parse(transition); + if (libraryRestart && (command.type !== 'capture' || observed?.solverRunId !== libraryRestart.solverRunId)) + throw new Error(); + if (receipt.catalog) validateTheoremKnowledge(receipt.catalog); + return { + ...receipt, + ...(observed ? { observation: observed } : {}), + ...(libraryRestart ? { libraryRestart } : {}), + } as WebCommandResult; +} + +/** Both live output and recovered receipts pass through the same validation and ordering. */ +function proofMessages(input: WorkerInput, onMessage: (message: WorkerMessage) => void, watchdog: ExecutionDeadline) { + let observedSequence = 0, + libraryRound = 0, + artifactAt = ''; + let receivedResult = false, + workerError: Error | undefined; + const observationStream = { runId: input.id, sources: new Map() }; + const forward = (message: WorkerMessage) => { + if (input.input.planApproval && message.type === 'progress') { + if (message.event === 'plan_approval_wait_started') watchdog.setWaiting(true); + else if (message.event === 'plan_approval_wait_ended') watchdog.setWaiting(false); + } + if (message.type === 'result') receivedResult = true; + if (message.type === 'error') workerError = new Error(message.message); + if (message.type === 'library_restart') { + if (message.round <= libraryRound) return; + libraryRound = message.round; + } + if (message.type === 'observation') { + if (message.observation.webRunId !== input.id || message.observation.sequence <= observedSequence) return; + observedSequence = message.observation.sequence; + } + if (message.type === 'artifact') { + if (message.artifact.capturedAt <= artifactAt) return; + artifactAt = message.artifact.capturedAt; + } + onMessage(message); + }; + return { + forward, + get result() { + return receivedResult; + }, + get error() { + return workerError; + }, + read(line: string, journal = false) { + const message = parseWorkerMessage(line, journal ? { runId: input.id, sources: new Map() } : observationStream); + if (message) forward(message); + }, + capture(receipt: WebCommandResult) { + if (receipt.libraryRestart) forward({ type: 'library_restart', ...receipt.libraryRestart }); + if (receipt.observation) forward({ type: 'observation', observation: receipt.observation }); + if (receipt.catalog) forward({ type: 'catalog', catalog: receipt.catalog }); + }, + }; +} + +function proofDeadline(input: WorkerInput, abort: () => void) { + return new ExecutionDeadline( + input.input.maxRunSeconds === 0 + ? Number.POSITIVE_INFINITY + : (input.input.maxRunSeconds + (input.input.environment === 'mathlib' ? 600 : 0) + 240) * 1_000, + abort, + ); +} + +function readPaperPdf(output: string): WebPaperCompileOutput { + let packet: unknown; + try { + packet = JSON.parse(output.trim()); + } catch { + throw new WebPaperCompileError('paper_pdf_invalid_output'); + } + if (!packet || typeof packet !== 'object' || Array.isArray(packet)) + throw new WebPaperCompileError('paper_pdf_invalid_output'); + const result = packet as { ok?: unknown; pdf?: unknown; log?: unknown }; + if (result.ok !== true || typeof result.pdf !== 'string') { + const log = + typeof result.log === 'string' ? result.log.slice(-webPaperLimits.maxLogBytes).replaceAll('\r', '') : undefined; + const match = log?.match(/(?:^|\n)([^\n:]{1,256}):(\d+):/u); + const detail = log?.match(/(?:^|\n)(?:!\s*|(?:LaTeX|Package)[^\n]*Error:\s*)([^\n]{1,240})/u)?.[1]?.trim(); + throw new WebPaperCompileError( + 'paper_pdf_compile_failed', + detail, + match?.[1], + match ? Number(match[2]) : undefined, + ); + } + let pdf: Buffer; + try { + pdf = Buffer.from(result.pdf, 'base64'); + } catch { + throw new WebPaperCompileError('paper_pdf_invalid_output'); + } + if (!pdf.length || pdf.length > webPaperLimits.maxPdfBytes || pdf.subarray(0, 5).toString() !== '%PDF-') + throw new WebPaperCompileError('paper_pdf_missing_output'); + return { pdf }; +} + export class DockerWebRunner implements WebRunner { private cached?: { at: number; @@ -433,7 +545,8 @@ export class DockerWebRunner implements WebRunner { if (Buffer.byteLength(template) + Buffer.byteLength(main) > webPaperLimits.maxSourceBytes) throw new WebPaperCompileError('paper_pdf_source_too_large'); const image = this.config.texImage || 'theorem-os-tex:local'; - const name = `theoremos-paper-${crypto.randomUUID()}`; + const id = crypto.randomUUID(); + const name = `theoremos-paper-${id}`; const script = [ 'set -eu', 'python3 -c \'import json,pathlib,sys; p=json.load(sys.stdin); pathlib.Path("/work/template.tex").write_text(p["template"],encoding="utf-8"); pathlib.Path("/work/main.tex").write_text(p["main"],encoding="utf-8")\'', @@ -443,6 +556,36 @@ export class DockerWebRunner implements WebRunner { 'python3 -c \'import json,pathlib; p=pathlib.Path("/work/latexmk.log"); print(json.dumps({"ok":False,"log":p.read_text(encoding="utf-8",errors="replace")[-65536:]}))\'', '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( () => {}, @@ -521,40 +664,9 @@ export class DockerWebRunner implements WebRunner { child.stdin.on('error', () => {}); child.once('error', () => finish(new WebPaperCompileError('paper_pdf_container_failed'))); child.once('close', code => finish(code ? new WebPaperCompileError('paper_pdf_compile_failed') : undefined)); - child.stdin.end(JSON.stringify({ template, main })); + child.stdin.end(payload); }); - let packet: unknown; - try { - packet = JSON.parse(output.trim()); - } catch { - throw new WebPaperCompileError('paper_pdf_invalid_output'); - } - if (!packet || typeof packet !== 'object' || Array.isArray(packet)) - throw new WebPaperCompileError('paper_pdf_invalid_output'); - const result = packet as { ok?: unknown; pdf?: unknown; log?: unknown }; - if (result.ok !== true || typeof result.pdf !== 'string') { - const log = - typeof result.log === 'string' - ? result.log.slice(-webPaperLimits.maxLogBytes).replaceAll('\r', '') - : undefined; - const match = log?.match(/(?:^|\n)([^\n:]{1,256}):(\d+):/u); - const detail = log?.match(/(?:^|\n)(?:!\s*|(?:LaTeX|Package)[^\n]*Error:\s*)([^\n]{1,240})/u)?.[1]?.trim(); - throw new WebPaperCompileError( - 'paper_pdf_compile_failed', - detail, - match?.[1], - match ? Number(match[2]) : undefined, - ); - } - let pdf: Buffer; - try { - pdf = Buffer.from(result.pdf, 'base64'); - } catch { - throw new WebPaperCompileError('paper_pdf_invalid_output'); - } - if (!pdf.length || pdf.length > webPaperLimits.maxPdfBytes || pdf.subarray(0, 5).toString() !== '%PDF-') - throw new WebPaperCompileError('paper_pdf_missing_output'); - return { pdf }; + return readPaperPdf(output); } finally { await remove(); } @@ -564,6 +676,15 @@ 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', @@ -589,23 +710,7 @@ export class DockerWebRunner implements WebRunner { return; } try { - const value: unknown = JSON.parse(output); - if (!object(value) || typeof value.id !== 'string' || typeof value.status !== 'string') throw new Error(); - const { observation, sourceBlobs, libraryRestart: transition, ...receipt } = value; - const observed = - observation === undefined - ? undefined - : readWorkerObservation(observation, sourceBlobs, { runId: id, sources: new Map() }); - if (observation !== undefined && !observed) throw new Error(); - const libraryRestart = transition === undefined ? undefined : libraryRestartSchema.parse(transition); - if (libraryRestart && (command.type !== 'capture' || observed?.solverRunId !== libraryRestart.solverRunId)) - throw new Error(); - if (receipt.catalog) validateTheoremKnowledge(receipt.catalog); - resolve({ - ...receipt, - ...(observed ? { observation: observed } : {}), - ...(libraryRestart ? { libraryRestart } : {}), - } as WebCommandResult); + resolve(decodeCommandResult(JSON.parse(output), id, command)); } catch { reject(new Error('运行环境未返回有效命令回执。')); } @@ -632,7 +737,8 @@ export class DockerWebRunner implements WebRunner { signal, ) => { signal.throwIfAborted(); - const name = `theoremos-check-${crypto.randomUUID()}`; + const checkId = crypto.randomUUID(); + const name = `theoremos-check-${checkId}`; const mathlib = environment === 'mathlib'; const memory = mathlib ? '6g' : '2g'; // A pack is validated before any of its paths reach the container. Compile dependencies first, @@ -688,6 +794,40 @@ export class DockerWebRunner implements WebRunner { candidateTargetQuery(sourceFile.slice(0, -5).replaceAll('/', '.'), source, candidateTarget, marker!); const queryFile = query && `TheoremOSCandidateCheck${crypto.randomBytes(16).toString('hex')}.lean`; const withFiles = Boolean(pack || dependencySources.length || sourceFile !== 'Submission.lean' || candidateTarget); + const payload = withFiles + ? JSON.stringify({ source, sourceFile, modules: ordered, ...(query ? { query, queryFile } : {}) }) + : source; + const result = (output: string, exitCode: number | null, timedOut: boolean): WebPrecheckOutput => ({ + output, + exitCode, + timedOut, + ...(candidateTarget && exitCode === 0 && !timedOut && candidateTargetWasChecked(output, marker!) + ? { 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); @@ -786,21 +926,8 @@ export class DockerWebRunner implements WebRunner { }); child.stdin.on('error', () => {}); child.once('error', error => finish(undefined, error)); - child.once('close', code => - finish({ - output, - exitCode: code, - timedOut, - ...(candidateTarget && code === 0 && !timedOut && candidateTargetWasChecked(output, marker!) - ? { checkedTarget: candidateTarget.name } - : {}), - }), - ); - child.stdin.end( - withFiles - ? JSON.stringify({ source, sourceFile, modules: ordered, ...(query ? { query, queryFile } : {}) }) - : source, - ); + child.once('close', code => finish(result(output, code, timedOut))); + child.stdin.end(payload); }); } finally { await remove(); @@ -809,6 +936,25 @@ export class DockerWebRunner implements WebRunner { async readiness() { if (this.cached && Date.now() - this.cached.at < 10_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', [ @@ -835,6 +981,96 @@ 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); @@ -848,6 +1084,8 @@ 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'; @@ -914,13 +1152,7 @@ export class DockerWebRunner implements WebRunner { }); this.active.add(input.id); let buffer = '', - finished = false, - receivedResult = false; - let workerError: Error | undefined; - let observedSequence = 0, - libraryRound = 0, - artifactAt = ''; - const observationStream = { runId: input.id, sources: new Map() }; + finished = false; let recovery: AbortController | undefined; let stopping: Promise | undefined; let heartbeat: ReturnType | undefined; @@ -931,9 +1163,7 @@ export class DockerWebRunner implements WebRunner { // Capture the actual saved checkpoint and source evidence before deleting the container. try { const captured = await this.command(input.id, { type: 'capture' }); - if (captured.libraryRestart) forward({ type: 'library_restart', ...captured.libraryRestart }); - if (captured.observation) forward({ type: 'observation', observation: captured.observation }); - if (captured.catalog) forward({ type: 'catalog', catalog: captured.catalog }); + messages.capture(captured); } catch { /* A run cancelled during bootstrap may not have a checkpoint yet. */ } @@ -943,12 +1173,8 @@ export class DockerWebRunner implements WebRunner { const abort = () => { void stop(); }; - const watchdog = new ExecutionDeadline( - input.input.maxRunSeconds === 0 - ? Number.POSITIVE_INFINITY - : (input.input.maxRunSeconds + (mathlib ? 600 : 0) + 240) * 1_000, - abort, - ); + const watchdog = proofDeadline(input, abort); + const messages = proofMessages(input, onMessage, watchdog); signal.addEventListener('abort', abort, { once: true }); const finish = async (error?: Error) => { if (finished) return; @@ -961,27 +1187,6 @@ export class DockerWebRunner implements WebRunner { if (error) reject(error); else resolve(); }; - const forward = (message: WorkerMessage) => { - if (input.input.planApproval && message.type === 'progress') { - if (message.event === 'plan_approval_wait_started') watchdog.setWaiting(true); - else if (message.event === 'plan_approval_wait_ended') watchdog.setWaiting(false); - } - if (message.type === 'result') receivedResult = true; - if (message.type === 'error') workerError = new Error(message.message); - if (message.type === 'library_restart') { - if (message.round <= libraryRound) return; - libraryRound = message.round; - } - if (message.type === 'observation') { - if (message.observation.webRunId !== input.id || message.observation.sequence <= observedSequence) return; - observedSequence = message.observation.sequence; - } - if (message.type === 'artifact') { - if (message.artifact.capturedAt <= artifactAt) return; - artifactAt = message.artifact.capturedAt; - } - onMessage(message); - }; child.stdout.setEncoding('utf8'); child.stdout.on('data', chunk => { buffer += chunk; @@ -994,8 +1199,7 @@ export class DockerWebRunner implements WebRunner { if (newline < 0) break; const line = buffer.slice(0, newline); buffer = buffer.slice(newline + 1); - const message = parseWorkerMessage(line, observationStream); - if (message) forward(message); + messages.read(line); } }); child.stdin.on('error', () => {}); @@ -1005,12 +1209,12 @@ export class DockerWebRunner implements WebRunner { child.once('close', () => { clearInterval(heartbeat); if (finished) return; - if (signal.aborted || receivedResult) { + if (signal.aborted || messages.result) { void finish(); return; } - if (workerError) { - void finish(workerError); + if (messages.error) { + void finish(messages.error); return; } const missingResult = new Error('运行环境已退出,未返回验收结果。'); @@ -1030,9 +1234,9 @@ export class DockerWebRunner implements WebRunner { }); for (const message of await readProofJournal(name, input.id, recoverySignal)) { if (signal.aborted || stopping) break; - forward(message); + messages.forward(message); } - await finish(signal.aborted || receivedResult ? undefined : (workerError ?? missingResult)); + await finish(signal.aborted || messages.result ? undefined : (messages.error ?? missingResult)); } catch { await finish(signal.aborted ? undefined : missingResult); } @@ -1064,6 +1268,20 @@ 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'; @@ -1200,6 +1418,26 @@ 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 a721552f..0716ee96 100644 --- a/apps/web/server.ts +++ b/apps/web/server.ts @@ -1,3 +1,4 @@ +import { nativeWeb } from './nativeWeb'; import { publicWebProvider, webProviderHarness, webHarnessResearchError } from './harness'; import { nativeTeamCapacitySchema, @@ -10,7 +11,6 @@ import { } from './researchMode'; import { webTeamProfiles } from './nativeTeamProfiles'; import http, { type IncomingMessage, type ServerResponse } from 'node:http'; -import fs from 'node:fs'; import path from 'node:path'; import crypto from 'node:crypto'; import { pathToFileURL } from 'node:url'; @@ -51,7 +51,7 @@ import { WebStorage, WebStorageError } from './storage'; import { WebKnowledgeService, type WebKnowledgeDetailOptions } from './knowledgeService'; import { WebModuleRegistry } from './moduleRegistry'; import { webPlanApprovalSchema } from './collaborationValidation'; -import { WebAuth, WebAuthError, type WebMailer, type WebMilestone } from './auth'; +import { normalizeEmail, WebAuth, WebAuthError, type WebAccount, type WebMailer, type WebMilestone } from './auth'; import { WebSessionAdmission, WebAdmissionError } from './admission'; import { WebOperations } from './operations'; import { checkWebProvider, WebProviderCheckError } from './providerCheck'; @@ -64,7 +64,7 @@ import { WebPaperDrafts } from './paperDrafts'; import { WebPaperPdf, WebPaperPdfError } from './paperPdf'; import type { WebPaperOverview } from './paperTypes'; import { paperTemplate } from '../../src/math/paperDraft'; -import { acceptedEncoding, sendStatic } from './staticFiles'; +import { acceptedEncoding, createStaticResponder } from './staticFiles'; import { webFunnel } from './funnel'; import { completionMail, mailsCompletion, planApprovalMail } from './completionMail'; import { WebKeyVault } from './keyVault'; @@ -407,7 +407,7 @@ function json(response: ServerResponse, status: number, body: unknown, revalidat }); response.end(compressed); } -function readJson(request: IncomingMessage): Promise { +function readJson(request: IncomingMessage, maxBytes = 160 * 1024): Promise { if (!/^application\/json(?:\s*;|$)/i.test(request.headers['content-type'] || '')) throw new HttpError(415, '请求必须使用 JSON。'); return new Promise((resolve, reject) => { @@ -417,7 +417,7 @@ function readJson(request: IncomingMessage): Promise { request.on('data', chunk => { if (rejected) return; bytes += chunk.length; - if (bytes > 160 * 1024) { + if (bytes > maxBytes) { rejected = true; chunks.length = 0; reject(new HttpError(413, '请求内容过大。')); @@ -498,6 +498,7 @@ export function createWebService( const storage = new WebStorage(config.dataRoot); const operations = new WebOperations(storage, config.dataRoot); const productBuild = readProductBuild(config.staticRoot); + const serveStatic = createStaticResponder(config.staticRoot); const admission = new WebSessionAdmission(Boolean(config.auth)); // null disables the sample; omitted loads the one shipped with the image. const sample = options.sample === undefined ? loadWebSample() : (options.sample ?? undefined); @@ -506,7 +507,40 @@ export function createWebService( const knowledge = new WebKnowledgeService(storage); const registry = new WebModuleRegistry(storage); const sessions = new Map(storage.listSessions().map(session => [session.id, session])); - const auth = config.auth ? new WebAuth(config.auth, storage, options.mailer, options.captchaAnswer) : undefined; + const writerSocket = process.env.THEOREMOS_WEB_SESSION_SOCKET; + const Writer = writerSocket && nativeWeb()?.WebSessionWriter; + const identityWriter = Writer ? new Writer(writerSocket!) : undefined; + const identity = (message: object): T => { + const result = JSON.parse(identityWriter!.update(JSON.stringify(message))); + if (result?.failed === true) throw new Error('Session storage operation failed'); + return result; + }; + const persistSession = (session: Session) => { + if (!identityWriter) { + storage.saveSession(session); + return; + } + if (!identity({ op: 'save', session })) throw new HttpError(401, '会话已过期,请刷新页面。'); + }; + const touchSession = (s: Session) => { + s.touchedAt = Date.now(); + if (identityWriter && !identity({ op: 'touch', session: s })) throw new HttpError(401, '会话已过期,请刷新页面。'); + }; + const auth = config.auth + ? new WebAuth( + config.auth, + storage, + options.mailer, + options.captchaAnswer, + identityWriter + ? message => { + const reply = identity(message); + if (reply?.status && reply.error) throw new WebAuthError(reply.status, reply.error); + return reply; + } + : undefined, + ) + : undefined; const quota = auth && config.quota ? new WebQuota(storage, config.quota) : undefined; const providersFor = (session: Session) => webProvidersForAccount(config, session.account?.id); // With login enabled, records belong to the account; otherwise to the anonymous browser session. @@ -523,7 +557,10 @@ export function createWebService( return ids.length ? ids : undefined; }; // Each account reads and replaces only its own saved keys. - const vault = auth && config.keySecret ? new WebKeyVault(config.keySecret, storage) : undefined; + const vault = + auth && config.keySecret + ? new WebKeyVault(config.keySecret, storage, identityWriter ? identity : undefined) + : undefined; const savedKeysFor = (session: Session) => vault && session.account ? vault.list(session.account.id, providersFor(session)) : []; // What an empty key field stands for: the account's saved key, then the server's key for admins. @@ -756,7 +793,47 @@ export function createWebService( }, ); const prechecker = runner.check ? new WebPrechecker(runner.check.bind(runner)) : undefined; - const community = new WebCommunity(storage, runner.check?.bind(runner)); + const checkerSocket = process.env.THEOREMOS_WEB_CHECKER_SOCKET; + const community = new WebCommunity(storage, runner.check?.bind(runner), { externalWorker: Boolean(checkerSocket) }); + // Only the Rust listener can reach this Unix socket. It carries Lean source review and isolated proof checks, + // never an account, permission, or public request forwarded for publication. + const checkerServer = checkerSocket + ? http + .createServer(async (req, res) => { + try { + const raw = await readJson(req); + if (req.method === 'POST' && req.url === '/task') { + const spec = z + .object({ + id: z.string().regex(/^T[1-9][0-9]{0,5}$/u), + environment: z.enum(['standard', 'mathlib']), + prelude: z.string(), + statement: z.string(), + }) + .strict() + .parse(raw); + json(res, 200, await community.reviewTask(spec.id, spec.environment, spec.prelude, spec.statement)); + } else if (req.method === 'POST' && req.url === '/submission') { + const spec = z + .object({ module: z.string(), environment: z.enum(['standard', 'mathlib']), source: z.string() }) + .strict() + .parse(raw); + community.reviewSubmission({ module: spec.module, environment: spec.environment }, spec.source); + json(res, 200, { ok: true }); + } else if (req.method === 'POST' && req.url === '/check') { + const { id } = z + .object({ id: z.string().regex(/^s[0-9a-z]{8,40}$/u) }) + .strict() + .parse(raw); + json(res, 200, await community.checkPersisted(id)); + } else json(res, 404, { error: '接口不存在。' }); + } catch (e) { + if (e instanceof WebStorageError || e instanceof HttpError) json(res, e.status, { error: e.message }); + else json(res, 503, { error: '证明校验服务暂不可用。' }); + } + }) + .listen(checkerSocket) + : undefined; const communityActor = (session?: Session): CommunityActor | undefined => { const owner = session && ownerOf(session); return owner @@ -784,6 +861,82 @@ export function createWebService( }, (owner, call, signal) => explainer.ask(owner, call, signal), ); + if (identityWriter) + identity({ + op: 'start', + settings: { + ...(sample && { sample }), + ttl: config.sessionTtlMs, + locale: Intl.Collator().resolvedOptions().locale, + ...(config.auth + ? { + auth: { + admins: config.auth.admins || [], + smtpUrl: config.auth.smtpUrl, + from: config.auth.from, + allowlist: config.auth.allowlist, + allowlistFile: config.auth.allowlistFile, + signup: config.auth.signup || 'allowlist', + }, + } + : {}), + context: { + base: { + providers: config.providers.map(publicWebProvider), + environments: getWebEnvironments(), + templates: webTemplates, + defaults: webDefaults, + limits: webLimits, + ...(sample ? { sample: { id: sample.run.id, title: sample.run.title } } : {}), + ...(prechecker ? { precheck: true } : {}), + ...(auth?.termsVersion ? { termsVersion: auth.termsVersion } : {}), + ...(auth?.signup() === 'open' ? { signup: 'open' } : {}), + }, + accountUrls: config.accountProviderUrls, + adminKeyIds: Object.keys(config.adminKeys || {}), + quota: config.quota, + dataRoot: config.dataRoot, + workerImage: config.workerImage, + runVersionId: jobs.sessionVersionId(), + vault: Boolean(vault), + }, + }, + sessions: [...sessions.values()], + }); + if (identityWriter) + jobs.publishSessionLists( + (owner, runs, version) => identity({ op: 'runs', owner, runs, version }), + (owner, id, actions) => identity({ op: 'runActions', owner, id, actions }), + ); + if (identityWriter) { + // The schedulers own their live slots. Send only counts and waiting timestamps after each transition. + const publish = () => + identity({ + op: 'operations', + queues: { + research: jobs.queueState(), + formalization: formalizations.queueState(), + explanation: explanations.queueState(), + precheck: prechecker?.queueState() ?? { running: 0, waiting: [] }, + conversation: explainer.queueState(), + paper: papers.queueState(), + }, + failures: operations.failures(), + }); + let pending = false; + const changed = () => { + if (pending) return; + pending = true; + queueMicrotask(() => { + pending = false; + publish(); + }); + }; + for (const source of [jobs, formalizations, explanations, prechecker, explainer, papers]) + if (source) source.onQueueChange = changed; + operations.onMailFailure = changed; + publish(); + } const rates = new Map(); const runStreams = new Map void>>(); const origin = new URL(config.publicUrl); @@ -808,13 +961,15 @@ export function createWebService( response.setHeader('Set-Cookie', auth ? [value, cookieValue(bootstrapCookie, '', 0)] : value); }; const startSession = (account?: Session['account'], verifiedByEmail = false) => { - const session: Session = { - id: crypto.randomBytes(32).toString('hex'), - csrf: crypto.randomBytes(32).toString('hex'), - touchedAt: Date.now(), - ...(account ? { account } : {}), - ...(verifiedByEmail ? { passwordResetUntil: Date.now() + 10 * 60_000 } : {}), - }; + const session: Session = identityWriter + ? identity({ op: 'create', account, verified: verifiedByEmail }) + : { + id: crypto.randomBytes(32).toString('hex'), + csrf: crypto.randomBytes(32).toString('hex'), + touchedAt: Date.now(), + ...(account ? { account } : {}), + ...(verifiedByEmail ? { passwordResetUntil: Date.now() + 10 * 60_000 } : {}), + }; sessions.set(session.id, session); return session; }; @@ -822,8 +977,15 @@ export function createWebService( const endSession = (id: string) => { // Revocation must take effect even when deleting persisted records fails. sessions.delete(id); - for (const stop of runStreams.get(id) ?? []) stop(); let failure: unknown; + if (identityWriter) { + try { + identity({ op: 'remove', id }); + } catch (e) { + failure = e; + } + } + for (const stop of runStreams.get(id) ?? []) stop(); if (!auth) { conversations.forget(id); formalizations.forget(id); @@ -843,7 +1005,7 @@ export function createWebService( trajectories.forgetOwner(id); } try { - storage.deleteSession(id); + if (!identityWriter) storage.deleteSession(id); } catch (error) { failure ??= error; } @@ -851,8 +1013,9 @@ export function createWebService( }; const endSessions = (matches: (session: Session) => boolean) => { let failure: unknown; - for (const [id, session] of sessions) + for (const session of identityWriter ? identity({ op: 'list' }) : sessions.values()) if (matches(session)) { + const id = session.id; try { endSession(id); } catch (error) { @@ -866,11 +1029,14 @@ export function createWebService( quota?.prune(); let failure: unknown; try { - endSessions(session => { - // Login-page sessions without an account only need to outlive one sign-in attempt. - const ttl = auth && !session.account ? Math.min(config.sessionTtlMs, 60 * 60_000) : config.sessionTtlMs; - return Date.now() - session.touchedAt > ttl; - }); + if (identityWriter) { + for (const id of identity({ op: 'expired', now: Date.now() })) endSession(id); + } else + endSessions(session => { + // Login-page sessions without an account only need to outlive one sign-in attempt. + const ttl = auth && !session.account ? Math.min(config.sessionTtlMs, 60 * 60_000) : config.sessionTtlMs; + return Date.now() - session.touchedAt > ttl; + }); } catch (error) { failure = error; } @@ -883,16 +1049,36 @@ export function createWebService( const maintenance = setInterval(() => { try { prune(); + if (identityWriter && sessions.size) { + // Drop backend object references for sessions logged out directly at the Rust listener. + const active = new Set(identity({ op: 'ids' })); + for (const id of sessions.keys()) if (!active.has(id)) sessions.delete(id); + } } catch { console.error('[web_cleanup_failed] background cleanup failed'); } }, 60_000).unref(); /** The browser session named by the cookie. An address removed from the allowlist, or a deleted account, loses its signed-in sessions. */ - const cookieSession = (request: IncomingMessage) => { - const cookies = request.headers.cookie?.split(';').map(value => value.trim()) ?? []; + const fromCookies = (header: string | undefined) => { + const cookies = header?.split(';').map(value => value.trim()) ?? []; const read = (name: string) => { const value = cookies.find(value => value.startsWith(`${name}=`))?.slice(name.length + 1); - return value ? sessions.get(value) : undefined; + if (!value) return; + const prior = sessions.get(value); + if (!identityWriter) return prior; + const live = identity({ op: 'get', id: value }); + if (!live) { + sessions.delete(value); + return; + } + // Other requests can revoke a session while an upload is in flight. + if (prior) { + if (live.passwordResetUntil === undefined) delete prior.passwordResetUntil; + Object.assign(prior, live); + return prior; + } + sessions.set(value, live); + return live; }; let session = read(sessionCookie); if (!auth) return session; @@ -911,6 +1097,298 @@ export function createWebService( // Accept legacy anonymous cookies until their normal expiry; bootstrap cookies never authenticate. return bootstrap && !bootstrap.account ? bootstrap : session; }; + const cookieSession = (request: IncomingMessage) => fromCookies(request.headers.cookie); + const checkWork = (session: Session) => { + if (auth && session.account && auth.needsTerms(accountLogin(session.account))) + throw new HttpError(428, '使用条款已更新,请先确认后继续。'); + if (operations.maintenance) + throw new HttpError(503, '服务正在维护,暂不接收新任务;已有任务会继续,历史与下载仍可使用。'); + if (!operations.writable()) throw new HttpError(503, '存储空间暂时不足,请稍后重试。'); + }; + const createRun = async ( + session: Session, + owner: string, + raw: unknown, + headerId: string | string[] | undefined, + admitWork: () => void, + ) => { + const parsed = inputSchema.safeParse(raw); + if (!parsed.success) throw new HttpError(400, '请检查题目、API Key、模型、模块方案及运行预算。'); + const provider = providersFor(session).find(item => item.id === parsed.data.providerId); + if (!provider) throw new HttpError(400, '该模型服务尚未配置。'); + const { saveKey, requestId: bodyRequestId, ...submitted } = parsed.data; + const legacyEnvironmentOmitted = submitted.environment === undefined; + submitted.environment ??= webDefaults.environment; + if ( + headerId !== undefined && + (typeof headerId !== 'string' || + !/^[A-Za-z0-9_-]{1,128}$/u.test(headerId) || + (bodyRequestId && bodyRequestId !== headerId)) + ) + throw new HttpError(400, '提交请求标识无效或不一致。'); + const requestId = bodyRequestId ?? (typeof headerId === 'string' ? headerId : undefined); + // Confirmed statements retain their exact artifact bytes; ordinary Lean drafts keep the existing normalization. + if (!submitted.formalizationId) submitted.source = submitted.source.trim(); + if (webProviderHarness(provider) !== 'codex') { + submitted.researchMode ??= 'skill'; + submitted.skillLoading ??= 'file'; + } + if (submitted.researchMode === 'skill') submitted.skillLoading ??= webDefaultSkillLoading(provider); + if (!submitted.planApproval) delete submitted.planApproval; + // Retry the exact submitted identity before considering migration defaults or runtime capabilities. + const creationInput = submitted as WebRunInput; + const typed = submitted.apiKey; + const submissionKeys = (failed = false) => + vault + ? { + savedKeys: savedKeysFor(session), + ...(failed || + (saveKey && + typed && + session.account && + vault.get(session.account.id, provider.id, provider.baseUrl) !== typed) + ? { keySaveFailed: true } + : {}), + } + : {}; + const previous = jobs.replay(owner, creationInput, provider, requestId, legacyEnvironmentOmitted); + if (previous) { + return { status: 200, body: { run: previous, ...submissionKeys() } }; + } + const retiredInput = retiredWebRunInputError(submitted); + if (retiredInput) throw new HttpError(400, retiredInput, retiredResearchCoordinationCode); + const harnessError = webHarnessResearchError(provider, creationInput); + if (harnessError) throw new HttpError(400, harnessError); + const researchModeError = webResearchModeError(creationInput, provider); + if (researchModeError) throw new HttpError(400, researchModeError); + if (submitted.planApproval && webProviderHarness(provider) !== 'codex') + throw new HttpError(400, '先审计划需要 Codex 原生团队。'); + // A typed key wins; an empty one uses the account's saved key, then the server's key for admins. + const apiKey = typed || heldKey(session, provider); + if (!apiKey) throw new HttpError(400, '请填写 API Key。'); + const readiness = await runner.readiness(); + const raced = jobs.replay(owner, creationInput, provider, requestId, legacyEnvironmentOmitted); + if (raced) { + return { status: 200, body: { run: raced, ...submissionKeys() } }; + } + if (!readiness.ready) throw new HttpError(503, '运行环境尚未就绪,请先构建 worker 镜像。'); + if ((submitted.nativeTeamCapacity || submitted.planApproval) && !readiness.nativeTeam) + throw new HttpError(503, '当前运行镜像未安装原生团队后端。'); + const input = { + ...submitted, + apiKey, + environment: submitted.environment ?? webDefaults.environment, + coordination: 'independent' as const, + ...(webProviderHarness(provider) === 'codex' && readiness.nativeTeam + ? webAgentTeamPreset(submitted.nativeTeamCapacity) + : {}), + }; + if (input.nativeTeamCapacity && input.modulePlan) throw new HttpError(400, '原生团队不使用自定义模块方案。'); + if (input.libraryProposalOrigin) research.validateLibraryProposalOrigin(owner, input.libraryProposalOrigin); + if (input.budgetOrigin) { + const origin = research.projects.resolveBinding(owner, input.budgetOrigin.projectId, input.budgetOrigin.runId); + if (origin.run.source !== input.source || origin.run.environment !== input.environment) + throw new HttpError(409, '运行的原题或环境与陈述版本不一致。'); + } + const frozenResearch = !input.researchSelection + ? undefined + : input.nativeTeamCapacity + ? research.assets.freezeNativeTeam( + owner, + input.researchSelection as ResearchConfigurationSelection, + input.environment, + ) + : research.assets.freeze( + owner, + input.researchSelection as ResearchConfigurationSelection, + input.environment, + input.researchSelection.agent ? undefined : (input.modulePlan as ResearchModulePlan | undefined), + ); + if ( + frozenResearch && + input.researchSelection?.agent && + input.modulePlan && + JSON.stringify(input.modulePlan) !== JSON.stringify(frozenResearch.modulePlan) + ) + throw new HttpError(409, '所选 Agent 的方案与当前自定义方案不同,请清除自定义方案后重新提交。'); + if (frozenResearch) { + // Freeze the exact combined source pack once. The worker and future evidence reads use this copy. + const libraryPack = combineWebLibraryPacks( + selectWebLibraryPack(input as WebRunInput), + frozenResearch.libraryPack, + ); + if (libraryPack) frozenResearch.libraryPack = libraryPack as ResearchLibraryPack; + const { digest: _digest, ...configuration } = frozenResearch; + frozenResearch.digest = mathDigest(canonicalMathJson(configuration)); + } + if (frozenResearch?.personalExperts?.length && !readiness.nativeTeamExpertCards) + throw new HttpError(503, '当前运行镜像不支持个人专家资料。请移除专家资产或更新运行镜像。'); + if (input.nativeTeamPreferredProfiles?.length && !readiness.nativeTeamPreferences) + throw new HttpError(503, '当前运行镜像不支持角色偏好。清空偏好后仍可使用原生团队。'); + const from = input.continueFrom as WebContinuation | undefined; + const previousRun = from ? jobs.get(owner, from.runId) : undefined; + const saved = + from && previousRun + ? from.taskVersion + ? storage.getTaskSource(owner, from.runId, from.taskId, from.taskVersion, from.commit) + : trajectories.version(owner, from.runId, from.taskId, from.commit)?.source + : undefined; + if (from && !saved) { + if (previousRun && from.taskVersion && trajectories.version(owner, from.runId, from.taskId, from.commit)?.source) + throw new HttpError(409, '续跑来源的固定版本与保存记录不一致,请重新选择。'); + throw new HttpError(404, '这个版本的代码没有记录或已超出保留范围。'); + } + if ( + from && + saved && + (['sourceDigest', 'environmentDigest', 'file'] as const).some( + field => from[field] !== undefined && from[field] !== saved[field], + ) + ) + throw new HttpError(409, '续跑来源的固定版本与保存记录不一致,请重新选择。'); + const approved = input.formalizationId ? formalizations.confirmed(owner, input.formalizationId) : undefined; + if ( + approved && + (input.source !== approved.evidence.candidate.source || + input.environment !== approved.evidence.request.environment) + ) + throw new HttpError(409, 'Lean 原题或环境已改变,请重新形式化确认,或作为普通 Lean 题目创建。'); + if (from && previousRun?.formalizationId !== input.formalizationId) + throw new HttpError(409, '继续研究必须保留原运行的形式化来源。'); + // Only a new run costs allowance; a replayed request above already returned the run it created. + admitWork(); + const refund = spend(session, 'runs'); + let run: WebRun; + try { + run = jobs.create( + owner, + input as WebRunInput, + provider, + from && saved + ? { + ...from, + taskVersion: saved.taskVersion, + sourceDigest: saved.sourceDigest, + environmentDigest: saved.environmentDigest, + file: saved.file, + source: saved.source, + } + : undefined, + requestId, + approved + ? { + evidence: approved.evidence, + provenance: { + id: approved.formalization.id, + evidenceSha256: approved.formalization.report!.evidenceSha256, + original: approved.formalization.original, + confirmedAt: approved.formalization.confirmedAt!, + confirmation: approved.formalization.confirmation ?? 'manual', + }, + } + : undefined, + frozenResearch, + creationInput, + ); + } catch (error) { + // A submit that never became a run gives the allowance back. + refund(); + if (error instanceof WebStorageError) throw error; + throw new HttpError(429, error instanceof Error ? error.message : '运行队列已满。'); + } + milestone(owner, 'firstRunAt'); + let keySaveFailed = false; + if (saveKey && typed && vault && session.account) { + try { + vault.save(session.account.id, provider.id, provider.baseUrl, typed); + } catch { + keySaveFailed = true; + } + } + // The run has been accepted. An optional key save must not reject or refund its work. + return { status: 201, body: { run, ...submissionKeys(keySaveFailed) } }; + }; + const cancelAccountWork = (accountId: string) => { + const owner = `account:${accountId}`; + for (const run of jobs.list(owner)) { + jobs.cancel(owner, run.id); + for (const item of explanations.list(owner, run.id)) + explanations.cancel(owner, run.id, item.target, item.language); + } + for (const item of formalizations.list(owner)) formalizations.cancel(owner, item.id); + for (const item of conversations.list(owner)) conversations.stop(owner, item.id); + }; + const jobSocket = process.env.THEOREMOS_WEB_JOBS_SOCKET; + const jobServer = jobSocket + ? http + .createServer(async (request, response) => { + try { + const input = objectBody(await readJson(request, 192 * 1024)); + if (request.method === 'POST' && request.url === '/mail/code') { + if (!auth || typeof input.code !== 'string' || !/^\d{6}$/u.test(input.code)) + throw new HttpError(400, '验证码格式无效。'); + await auth.sendLoginCode(normalizeEmail(input.email), input.code); + json(response, 200, { delivered: true }); + return; + } + if (request.method === 'POST' && request.url === '/suspend') { + const { login, accountId } = input; + const account = typeof login === 'string' ? auth?.getAccount(login) : undefined; + if (!auth || !account || account.id !== accountId || !account.suspendedAt) + throw new HttpError(409, '账号状态已变更,请重新读取。'); + auth.invalidateLoginCode(accountLogin(account)); + cancelAccountWork(account.id); + for (const cached of sessions.values()) { + if (cached.account?.id !== account.id) continue; + sessions.delete(cached.id); + for (const stop of runStreams.get(cached.id) ?? []) stop(); + } + json(response, 200, { stopped: true }); + return; + } + if (request.method !== 'POST' || !['/create', '/cancel'].includes(request.url || '')) + throw new HttpError(404, '页面或运行不存在。'); + const sessionId = input.session; + if (typeof sessionId !== 'string' || !/^[a-f0-9]{64}$/u.test(sessionId)) + throw new HttpError(401, '会话已过期,请刷新页面。'); + const cookie = sessionCookie + '=' + sessionId; + const session = fromCookies(cookie); + const owner = session && ownerOf(session); + if (!session || session.id !== sessionId || !owner) throw new HttpError(401, '会话已过期,请刷新页面。'); + const admitWork = () => { + if (fromCookies(cookie) !== session) throw new HttpError(401, '会话已过期,请刷新页面。'); + checkWork(session); + }; + if (auth && session.account && auth.needsTerms(accountLogin(session.account))) + throw new HttpError(428, '使用条款已更新,请先确认后继续。'); + if (request.url === '/cancel') { + const id = input.id; + if (typeof id !== 'string' || !/^[a-f0-9-]{36}$/u.test(id)) + throw new HttpError(404, '页面或运行不存在。'); + const run = jobs.cancel(owner, id); + if (!run) throw new HttpError(404, '运行不存在或不属于当前会话。'); + json(response, 200, { run }); + } else { + admitWork(); + const result = await createRun( + session, + owner, + input.body, + typeof input.requestId === 'string' ? input.requestId : undefined, + admitWork, + ); + json(response, result.status, result.body); + } + } catch (e) { + const known = e instanceof WebStorageError || e instanceof HttpError || e instanceof WebAuthError; + json(response, known ? e.status : 500, { + error: known ? e.message : '服务暂时不可用。', + ...(e instanceof HttpError && e.code ? { code: e.code } : {}), + }); + } + }) + .listen(jobSocket) + : undefined; const server = http.createServer(async (request, response) => { const encoding = acceptedEncoding(request.headers['accept-encoding']); if (encoding) jsonEncodings.set(response, encoding); @@ -959,16 +1437,22 @@ export function createWebService( // Behind a tunnel every request comes from the proxy, so the configured proxy header names the visitor. const forwarded = config.clientIpHeader ? request.headers[config.clientIpHeader] : undefined; const ip = - (typeof forwarded === 'string' && forwarded.trim().slice(0, 64)) || request.socket.remoteAddress || ''; - let rate = rates.get(ip); - if (!rate) { - if (rates.size >= 2_000) throw new HttpError(429, '请求较多,请稍后重试。'); - rates.set(ip, (rate = { count: 0, expiresAt: Date.now() + 60_000 })); - } - if (++rate.count > 600) { - response.setHeader('Retry-After', Math.max(1, Math.ceil((rate.expiresAt - Date.now()) / 1000))); - response.setHeader('X-Theoremos-Rate-Limit-Scope', 'api'); - throw new HttpError(429, '请求过于频繁,请稍后重试。'); + (typeof forwarded === 'string' && forwarded.trim().slice(0, 64)) || + (process.env.THEOREMOS_WEB_BACKEND_SOCKET ? String(request.headers['x-theoremos-socket-peer'] || '') : '') || + request.socket.remoteAddress || + ''; + // The production listener counts native reads and forwarded routes in the same window. + if (!process.env.THEOREMOS_WEB_BACKEND_SOCKET) { + let rate = rates.get(ip); + if (!rate) { + if (rates.size >= 2_000) throw new HttpError(429, '请求较多,请稍后重试。'); + rates.set(ip, (rate = { count: 0, expiresAt: Date.now() + 60_000 })); + } + if (++rate.count > 600) { + response.setHeader('Retry-After', Math.max(1, Math.ceil((rate.expiresAt - Date.now()) / 1000))); + response.setHeader('X-Theoremos-Rate-Limit-Scope', 'api'); + throw new HttpError(429, '请求过于频繁,请稍后重试。'); + } } // Share links are public read-only snapshots: no session, no cookie, nothing beyond the stored whitelist. const shared = /^\/api\/share\/([^/]+)$/u.exec(url.pathname); @@ -1020,8 +1504,8 @@ export function createWebService( session = startSession(); setSessionCookie(response, session); } else if (!auth) setSessionCookie(response, session); - session.touchedAt = Date.now(); - storage.saveSession(session); + touchSession(session); + persistSession(session); const usage = usageOf(session); const body: WebSession = { draftOwner: crypto @@ -1095,12 +1579,12 @@ export function createWebService( .digest('hex'), ); if (!session) throw new HttpError(401, '会话已过期,请刷新页面。'); - session.touchedAt = Date.now(); + touchSession(session); if (request.method !== 'GET' && !equal(String(request.headers['x-csrf-token'] || ''), session.csrf)) throw new HttpError(403, '会话校验失败,请刷新页面。'); // An earlier response may arrive after another tab logs in. It must not replace the new identity cookie. if (!auth) setSessionCookie(response, session); - storage.saveSession(session); + persistSession(session); const requireSession = () => { if (cookieSession(request) !== session) throw new HttpError(401, '会话已过期,请刷新页面。'); }; @@ -1145,7 +1629,7 @@ export function createWebService( // A fresh identifier and CSRF token after login; the pre-login cookie stops working. endSession(session.id); const next = startSession({ id: account.id, ...accountIdentity(account) }, true); - storage.saveSession(next); + persistSession(next); setSessionCookie(response, next); json(response, 200, { account: accountIdentity(account), csrfToken: next.csrf }); return; @@ -1155,7 +1639,7 @@ export function createWebService( quota?.restore(account.id, accountLogin(account)); endSession(session.id); const next = startSession({ id: account.id, ...accountIdentity(account) }); - storage.saveSession(next); + persistSession(next); setSessionCookie(response, next); json(response, 200, { account: accountIdentity(account), csrfToken: next.csrf }); return; @@ -1191,9 +1675,10 @@ export function createWebService( requireSession, ); session.passwordResetUntil = undefined; + if (identityWriter) identity({ op: 'consumeReset', id: session.id }); let failure: unknown; try { - storage.saveSession(session); + persistSession(session); } catch (error) { failure = error; } @@ -1279,7 +1764,13 @@ export function createWebService( maintenance: operations.maintenance, ready, ...(disk ? { disk } : {}), - failures: operations.failures(), + failures: (() => { + const hosted = operations.failures(); + if (!identityWriter) return hosted; + const native = identity<{ smtp: number; lastSmtpFailureAt?: string }>({ op: 'mailFailures' }); + const last = [hosted.lastSmtpFailureAt, native.lastSmtpFailureAt].filter(Boolean).sort().at(-1); + return { smtp: hosted.smtp + native.smtp, ...(last ? { lastSmtpFailureAt: last } : {}) }; + })(), queues: { research: jobs.counts(), formalization: formalizations.counts(), @@ -1305,14 +1796,7 @@ export function createWebService( throw new HttpError(400, '请检查账号与暂停状态。'); const account = auth.setSuspended(login, body.suspended); if (body.suspended) { - const owner = `account:${account.id}`; - for (const run of jobs.list(owner)) { - jobs.cancel(owner, run.id); - for (const item of explanations.list(owner, run.id)) - explanations.cancel(owner, run.id, item.target, item.language); - } - for (const item of formalizations.list(owner)) formalizations.cancel(owner, item.id); - for (const item of conversations.list(owner)) conversations.stop(owner, item.id); + cancelAccountWork(account.id); endSessions(other => other.account?.id === account.id); } json(response, 200, adminOverview(auth, quota)); @@ -1360,11 +1844,7 @@ export function createWebService( // submission cannot start work after logout, suspension, account deletion or maintenance activation. const admitWork = () => { requireSession(); - if (auth && session.account && auth.needsTerms(accountLogin(session.account))) - throw new HttpError(428, '使用条款已更新,请先确认后继续。'); - if (operations.maintenance) - throw new HttpError(503, '服务正在维护,暂不接收新任务;已有任务会继续,历史与下载仍可使用。'); - if (!operations.writable()) throw new HttpError(503, '存储空间暂时不足,请稍后重试。'); + checkWork(session); }; if (newWork) admitWork(); const connection = /^\/api\/providers\/([a-z][a-z0-9-]{0,39})\/check$/u.exec(url.pathname); @@ -1806,212 +2286,14 @@ export function createWebService( return; } if (url.pathname === '/api/runs' && request.method === 'POST') { - const parsed = inputSchema.safeParse(await readBody()); - if (!parsed.success) throw new HttpError(400, '请检查题目、API Key、模型、模块方案及运行预算。'); - const provider = providersFor(session).find(item => item.id === parsed.data.providerId); - if (!provider) throw new HttpError(400, '该模型服务尚未配置。'); - const { saveKey, requestId: bodyRequestId, ...submitted } = parsed.data; - const legacyEnvironmentOmitted = submitted.environment === undefined; - submitted.environment ??= webDefaults.environment; - const headerId = request.headers['idempotency-key']; - if ( - headerId !== undefined && - (typeof headerId !== 'string' || - !/^[A-Za-z0-9_-]{1,128}$/u.test(headerId) || - (bodyRequestId && bodyRequestId !== headerId)) - ) - throw new HttpError(400, '提交请求标识无效或不一致。'); - const requestId = bodyRequestId ?? (typeof headerId === 'string' ? headerId : undefined); - // Confirmed statements retain their exact artifact bytes; ordinary Lean drafts keep the existing normalization. - if (!submitted.formalizationId) submitted.source = submitted.source.trim(); - if (webProviderHarness(provider) !== 'codex') { - submitted.researchMode ??= 'skill'; - submitted.skillLoading ??= 'file'; - } - if (submitted.researchMode === 'skill') submitted.skillLoading ??= webDefaultSkillLoading(provider); - if (!submitted.planApproval) delete submitted.planApproval; - // Retry the exact submitted identity before considering migration defaults or runtime capabilities. - const creationInput = submitted as WebRunInput; - const typed = submitted.apiKey; - const submissionKeys = (failed = false) => - vault - ? { - savedKeys: savedKeysFor(session), - ...(failed || - (saveKey && - typed && - session.account && - vault.get(session.account.id, provider.id, provider.baseUrl) !== typed) - ? { keySaveFailed: true } - : {}), - } - : {}; - const previous = jobs.replay(owner, creationInput, provider, requestId, legacyEnvironmentOmitted); - if (previous) { - json(response, 200, { run: previous, ...submissionKeys() }); - return; - } - const retiredInput = retiredWebRunInputError(submitted); - if (retiredInput) throw new HttpError(400, retiredInput, retiredResearchCoordinationCode); - const harnessError = webHarnessResearchError(provider, creationInput); - if (harnessError) throw new HttpError(400, harnessError); - const researchModeError = webResearchModeError(creationInput, provider); - if (researchModeError) throw new HttpError(400, researchModeError); - if (submitted.planApproval && webProviderHarness(provider) !== 'codex') - throw new HttpError(400, '先审计划需要 Codex 原生团队。'); - // A typed key wins; an empty one uses the account's saved key, then the server's key for admins. - const apiKey = typed || heldKey(session, provider); - if (!apiKey) throw new HttpError(400, '请填写 API Key。'); - const readiness = await runner.readiness(); - const raced = jobs.replay(owner, creationInput, provider, requestId, legacyEnvironmentOmitted); - if (raced) { - json(response, 200, { run: raced, ...submissionKeys() }); - return; - } - if (!readiness.ready) throw new HttpError(503, '运行环境尚未就绪,请先构建 worker 镜像。'); - if ((submitted.nativeTeamCapacity || submitted.planApproval) && !readiness.nativeTeam) - throw new HttpError(503, '当前运行镜像未安装原生团队后端。'); - const input = { - ...submitted, - apiKey, - environment: submitted.environment ?? webDefaults.environment, - coordination: 'independent' as const, - ...(webProviderHarness(provider) === 'codex' && readiness.nativeTeam - ? webAgentTeamPreset(submitted.nativeTeamCapacity) - : {}), - }; - if (input.nativeTeamCapacity && input.modulePlan) throw new HttpError(400, '原生团队不使用自定义模块方案。'); - if (input.libraryProposalOrigin) research.validateLibraryProposalOrigin(owner, input.libraryProposalOrigin); - if (input.budgetOrigin) { - const origin = research.projects.resolveBinding( - owner, - input.budgetOrigin.projectId, - input.budgetOrigin.runId, - ); - if (origin.run.source !== input.source || origin.run.environment !== input.environment) - throw new HttpError(409, '运行的原题或环境与陈述版本不一致。'); - } - const frozenResearch = !input.researchSelection - ? undefined - : input.nativeTeamCapacity - ? research.assets.freezeNativeTeam( - owner, - input.researchSelection as ResearchConfigurationSelection, - input.environment, - ) - : research.assets.freeze( - owner, - input.researchSelection as ResearchConfigurationSelection, - input.environment, - input.researchSelection.agent ? undefined : (input.modulePlan as ResearchModulePlan | undefined), - ); - if ( - frozenResearch && - input.researchSelection?.agent && - input.modulePlan && - JSON.stringify(input.modulePlan) !== JSON.stringify(frozenResearch.modulePlan) - ) - throw new HttpError(409, '所选 Agent 的方案与当前自定义方案不同,请清除自定义方案后重新提交。'); - if (frozenResearch) { - // Freeze the exact combined source pack once. The worker and future evidence reads use this copy. - const libraryPack = combineWebLibraryPacks( - selectWebLibraryPack(input as WebRunInput), - frozenResearch.libraryPack, - ); - if (libraryPack) frozenResearch.libraryPack = libraryPack as ResearchLibraryPack; - const { digest: _digest, ...configuration } = frozenResearch; - frozenResearch.digest = mathDigest(canonicalMathJson(configuration)); - } - if (frozenResearch?.personalExperts?.length && !readiness.nativeTeamExpertCards) - throw new HttpError(503, '当前运行镜像不支持个人专家资料。请移除专家资产或更新运行镜像。'); - if (input.nativeTeamPreferredProfiles?.length && !readiness.nativeTeamPreferences) - throw new HttpError(503, '当前运行镜像不支持角色偏好。清空偏好后仍可使用原生团队。'); - const from = input.continueFrom as WebContinuation | undefined; - const previousRun = from ? jobs.get(owner, from.runId) : undefined; - const saved = - from && previousRun - ? from.taskVersion - ? storage.getTaskSource(owner, from.runId, from.taskId, from.taskVersion, from.commit) - : trajectories.version(owner, from.runId, from.taskId, from.commit)?.source - : undefined; - if (from && !saved) { - if ( - previousRun && - from.taskVersion && - trajectories.version(owner, from.runId, from.taskId, from.commit)?.source - ) - throw new HttpError(409, '续跑来源的固定版本与保存记录不一致,请重新选择。'); - throw new HttpError(404, '这个版本的代码没有记录或已超出保留范围。'); - } - if ( - from && - saved && - (['sourceDigest', 'environmentDigest', 'file'] as const).some( - field => from[field] !== undefined && from[field] !== saved[field], - ) - ) - throw new HttpError(409, '续跑来源的固定版本与保存记录不一致,请重新选择。'); - const approved = input.formalizationId ? formalizations.confirmed(owner, input.formalizationId) : undefined; - if ( - approved && - (input.source !== approved.evidence.candidate.source || - input.environment !== approved.evidence.request.environment) - ) - throw new HttpError(409, 'Lean 原题或环境已改变,请重新形式化确认,或作为普通 Lean 题目创建。'); - if (from && previousRun?.formalizationId !== input.formalizationId) - throw new HttpError(409, '继续研究必须保留原运行的形式化来源。'); - // Only a new run costs allowance; a replayed request above already returned the run it created. - admitWork(); - const refund = spend(session, 'runs'); - let run: WebRun; - try { - run = jobs.create( - owner, - input as WebRunInput, - provider, - from && saved - ? { - ...from, - taskVersion: saved.taskVersion, - sourceDigest: saved.sourceDigest, - environmentDigest: saved.environmentDigest, - file: saved.file, - source: saved.source, - } - : undefined, - requestId, - approved - ? { - evidence: approved.evidence, - provenance: { - id: approved.formalization.id, - evidenceSha256: approved.formalization.report!.evidenceSha256, - original: approved.formalization.original, - confirmedAt: approved.formalization.confirmedAt!, - confirmation: approved.formalization.confirmation ?? 'manual', - }, - } - : undefined, - frozenResearch, - creationInput, - ); - } catch (error) { - // A submit that never became a run gives the allowance back. - refund(); - if (error instanceof WebStorageError) throw error; - throw new HttpError(429, error instanceof Error ? error.message : '运行队列已满。'); - } - milestone(owner, 'firstRunAt'); - let keySaveFailed = false; - if (saveKey && typed && vault && session.account) { - try { - vault.save(session.account.id, provider.id, provider.baseUrl, typed); - } catch { - keySaveFailed = true; - } - } - // The run has been accepted. An optional key save must not reject or refund its work. - json(response, 201, { run, ...submissionKeys(keySaveFailed) }); + const result = await createRun( + session, + owner, + await readBody(), + request.headers['idempotency-key'], + admitWork, + ); + json(response, result.status, result.body); return; } const match = /^\/api\/runs\/([a-f0-9-]{36})(?:\/(.*))?$/.exec(url.pathname); @@ -2541,44 +2823,8 @@ export function createWebService( return; } const relative = decodeURIComponent(url.pathname).replace(/^\/+/, '') || 'index.html'; - const file = path.resolve(config.staticRoot, relative); - if ( - !file.startsWith(config.staticRoot + path.sep) || - !fs.existsSync(file) || - !fs.lstatSync(file).isFile() || - fs.lstatSync(file).isSymbolicLink() - ) - throw new HttpError(404, '页面不存在,请先运行 bun run build:web。'); - if (!fs.realpathSync(file).startsWith(fs.realpathSync(config.staticRoot) + path.sep)) - throw new HttpError(404, '文件不存在。'); - const allowed: Record = { - '.html': 'text/html; charset=utf-8', - '.js': 'text/javascript; charset=utf-8', - '.css': 'text/css; charset=utf-8', - '.svg': 'image/svg+xml', - '.png': 'image/png', - '.woff2': 'font/woff2', - '.txt': 'text/plain; charset=utf-8', - }; - // Only the checked, shared proof archive adds JSON/Lean downloads; account-owned records remain behind /api/runs. - const extension = path.extname(file); - const archiveType = file.startsWith(path.join(config.staticRoot, 'classics') + path.sep) - ? extension === '.json' - ? 'application/json; charset=utf-8' - : extension === '.lean' - ? 'text/plain; charset=utf-8' - : undefined - : undefined; - const contentType = allowed[extension] ?? archiveType; - if (!contentType) throw new HttpError(404, '文件不存在。'); - sendStatic( - request, - response, - file, - extension, - contentType, - path.relative(config.staticRoot, file).split(path.sep).join('/'), - ); + const missing = serveStatic(request, response, relative); + if (missing) throw new HttpError(404, missing); } catch (error) { const invalidKnowledgeInput = error instanceof Error && @@ -2624,6 +2870,8 @@ export function createWebService( formalizations.close(), conversations.close(), communityClosed, + jobServer && new Promise(resolve => jobServer.close(() => resolve())), + checkerServer && new Promise(resolve => checkerServer.close(() => resolve())), new Promise(resolve => server.close(() => resolve())), ]); for (const result of closed) if (result.status === 'rejected') throw result.reason; @@ -2649,7 +2897,10 @@ if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.ar THEOREMOS_WEB_DATA_ROOT: process.env.THEOREMOS_WEB_DATA_ROOT || 'out/web-data', }); const service = createWebService(config); - service.server.listen(config.port, config.host, () => console.log(`TheoremOS workbench: ${config.publicUrl}`)); + const listening = () => console.log(`TheoremOS workbench: ${config.publicUrl}`); + if (process.env.THEOREMOS_WEB_BACKEND_SOCKET) + service.server.listen(process.env.THEOREMOS_WEB_BACKEND_SOCKET, listening); + else service.server.listen(config.port, config.host, listening); let stopping = false; const stop = () => { if (!stopping) { diff --git a/apps/web/staticFiles.ts b/apps/web/staticFiles.ts index 02f87975..3deeda87 100644 --- a/apps/web/staticFiles.ts +++ b/apps/web/staticFiles.ts @@ -1,7 +1,9 @@ import crypto from 'node:crypto'; import fs from 'node:fs'; +import path from 'node:path'; import type http from 'node:http'; import zlib from 'node:zlib'; +import { nativeWeb } from './nativeWeb'; /** * Built workbench files, read once per change and kept in memory with their compressed forms. Text is sent as Brotli or @@ -9,13 +11,11 @@ import zlib from 'node:zlib'; * Other files carry an ETag so the next request can pick up a rebuilt file without a restart. */ type Entry = { mtimeMs: number; size: number; etag: string; identity: Buffer; br?: Buffer; gzip?: Buffer }; -export const compressible = new Set(['.html', '.js', '.css', '.svg', '.txt']); -export const versionedEntryFile = /^[a-z][a-z0-9-]*\.[a-f0-9]{16}\.(?:js|css)$/u; +const compressible = new Set(['.html', '.js', '.css', '.svg', '.txt']); +const versionedEntryFile = /^[a-z][a-z0-9-]*\.[a-f0-9]{16}\.(?:js|css)$/u; const bundledChunk = /^chunks\/[\w-]+-[A-Z0-9]{8}\.js$/u; // Quality 9 is within 10% of the maximum here at a fraction of its time; the first request after a rebuild pays it once. const brotli = { params: { [zlib.constants.BROTLI_PARAM_QUALITY]: 9 } }; -/** The build writes `.br` at the maximum quality, about 8% smaller than quality 9, which is too slow to run per request. */ -export const precompressed = { params: { [zlib.constants.BROTLI_PARAM_QUALITY]: zlib.constants.BROTLI_MAX_QUALITY } }; const cache = new Map(); /** The build's `.br`, only when it still decodes to this file; a stale or broken one is ignored. */ @@ -107,3 +107,53 @@ export function sendStatic( response.writeHead(200, headers); response.end(request.method === 'HEAD' ? undefined : body); } + +export function createStaticResponder(root: string) { + const native = nativeWeb(); + if (native) { + const files = new native.WorkbenchStatic(); + return (request: http.IncomingMessage, response: http.ServerResponse, relative: string) => { + const reply = files.serve( + root, + relative, + request.headers['accept-encoding'] ?? '', + String(request.headers['if-none-match'] ?? ''), + request.method === 'HEAD', + ); + if (reply.error) return reply.error; + response.writeHead(reply.status, reply.headers); + response.end(reply.body); + }; + } + return (request: http.IncomingMessage, response: http.ServerResponse, relative: string) => { + const file = path.resolve(root, relative); + if (!file.startsWith(root + path.sep) || !fs.existsSync(file) || !fs.lstatSync(file).isFile()) + return '页面不存在,请先运行 bun run build:web。'; + const actual = fs.realpathSync(file); + const realRoot = fs.realpathSync(root); + if (!actual.startsWith(realRoot + path.sep)) return '文件不存在。'; + const allowed: Record = { + '.html': 'text/html; charset=utf-8', + '.js': 'text/javascript; charset=utf-8', + '.css': 'text/css; charset=utf-8', + '.svg': 'image/svg+xml', + '.png': 'image/png', + '.woff2': 'font/woff2', + '.txt': 'text/plain; charset=utf-8', + }; + const extension = path.extname(file); + const classic = + file.startsWith(path.join(root, 'classics') + path.sep) && + actual.startsWith(path.join(realRoot, 'classics') + path.sep); + const archiveType = + classic && + (extension === '.json' + ? 'application/json; charset=utf-8' + : extension === '.lean' + ? 'text/plain; charset=utf-8' + : undefined); + const contentType = allowed[extension] || archiveType; + if (!contentType) return '文件不存在。'; + sendStatic(request, response, file, extension, contentType, path.relative(root, file).split(path.sep).join('/')); + }; +} diff --git a/apps/web/storage.ts b/apps/web/storage.ts index 54a29a2e..2c20507f 100644 --- a/apps/web/storage.ts +++ b/apps/web/storage.ts @@ -1,4 +1,5 @@ import fs from 'node:fs'; +import { nativeWeb } from './nativeWeb'; import path from 'node:path'; import crypto from 'node:crypto'; import { canonicalMathJson, mathDigest, syncMathDirectory, writeMathFrozen } from '../../src/math/mathRuntimeIo'; @@ -307,6 +308,13 @@ export class WebStorage { saveRun(owner: string, run: WebRun, creation?: WebCreation): void { const directory = this.runPath(owner, run.id); + const native = this.root && nativeWeb(); + if (native && this.root) { + const { observation, ...summary } = run; + if (observation) this.saveObservation(owner, observation); + native.persistRun(this.root, owner, summary, observation?.sequence, creation); + return; + } this.saveRecord([...this.ownerPath(owner), 'owner.json'], { owner }, true); if (run.observation) this.saveObservation(owner, run.observation); for (const event of run.events) this.saveRecord([...directory, 'events', `${event.sequence}.json`], event, true); diff --git a/apps/web/trajectory.ts b/apps/web/trajectory.ts index 9c741e6d..020876f9 100644 --- a/apps/web/trajectory.ts +++ b/apps/web/trajectory.ts @@ -18,62 +18,9 @@ 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. */ -export const trajectoryEventTypes = new Set([ - 'ready', - 'solve_started', - 'preparation_failed', - 'source_rejected', - 'plan_updated', - 'plan_published', - 'initial_plan_published', - 'initial_plan_fallback', - 'plan_rejected', - 'initial_plan_rejected', - 'plan_publication_rejected', - 'plan_approval_requested', - 'plan_approved', - 'plan_approval_unanswered', - 'task_assigned', - 'task_checked', - 'task_check_reused', - 'task_failure_check_reused', - 'task_integrated', - 'task_recheck_finished', - 'task_conditional_recheck_finished', - 'task_recheck_dependency_invalidated', - 'assembly_started', - 'proof_checked', - 'evaluation_started', - 'evaluation_finished', - 'review_assigned', - 'review_completed', - 'route_parked', - 'routes_idle', - 'plan_stalled', - 'goal_path_stalled', - 'task_mathematical_gap_blocked', - 'task_repeated_input_blocked', - 'worker_failed', - 'model_budget_stopped', - 'planning_budget_stopped', - 'error', - 'cancelled', - 'interrupted', -]); - -export const trajectoryLimits = { - events: 10_000, - versions: 4_000, - checks: 100, - receipts: 200, - plans: 300, - planItems: 200, - deliveries: 1_000, - guidance: 300, - edits: 300, - workers: 64, - targets: 200, -} as const; +import trajectoryConfig from '../../rust/web/trajectory.json'; +export const trajectoryEventTypes = new Set(trajectoryConfig.events); +export const trajectoryLimits = trajectoryConfig.limits; const textLimits = { guidance: 2_000, headline: 160 } as const; const readLimits = { events: 5_000, observations: 40 } as const; diff --git a/apps/web/verification-readme.json b/apps/web/verification-readme.json new file mode 100644 index 00000000..38e31b39 --- /dev/null +++ b/apps/web/verification-readme.json @@ -0,0 +1,7 @@ +{ + "template": "TheoremOS local verification · run {run}\nLean {toolchain} · {dependency}\n\n中文\n1. 安装 elan(Lean 版本管理器):https://github.com/leanprover/elan ;lean-toolchain 会自动选用上面的 Lean 版本。\n{stepZh}\n3. 运行 `lake build Submission`:没有 error 即 Lean 内核接受了 Submission.lean 中的全部证明。\n4. 运行 `lake env lean Check.lean`:每个目标只应依赖 propext、Classical.choice、Quot.sound;出现 sorryAx 表示证明不完整,其他公理需逐一核对。\n5. 比较 Original.lean 与 Submission.lean(如 `diff Original.lean Submission.lean`):目标定理的陈述应保持不变,只有证明和新增的辅助声明不同。\nreport.json 是平台的验收记录,供对照,不参与上述检查。\n\nEnglish\n1. Install elan (the Lean version manager): https://github.com/leanprover/elan . lean-toolchain selects the Lean version above.\n{stepEn}\n3. Run `lake build Submission`. No errors means the Lean kernel accepted every proof in Submission.lean.\n4. Run `lake env lean Check.lean`. Each target should depend only on propext, Classical.choice and Quot.sound; sorryAx means an incomplete proof, and any other axiom needs review.\n5. Compare Original.lean with Submission.lean (for example `diff Original.lean Submission.lean`). Target statements should be unchanged; only proofs and added helper declarations differ.\nreport.json is the platform's acceptance record, kept for comparison; the steps above do not use it.\n", + "mathlibZh": "2. 在本目录运行 `lake exe cache get` 下载预编译的 Mathlib(首次约数 GB)。", + "coreZh": "2. 标准库环境无需下载依赖。", + "mathlibEn": "2. Run `lake exe cache get` here to download prebuilt Mathlib (several GB the first time).", + "coreEn": "2. The core-library environment needs no downloads." +} diff --git a/apps/web/verificationKit.ts b/apps/web/verificationKit.ts index 5713abdd..5a378ed9 100644 --- a/apps/web/verificationKit.ts +++ b/apps/web/verificationKit.ts @@ -1,3 +1,4 @@ +import instructions from './verification-readme.json'; import { inspectScopedLeanDeclarations } from '../../src/math/leanSource'; import { getLeanTaskEnvironment } from '../../src/math/leanTaskEnvironment'; import type { WebProofOutline, WebProofOutlineDeclaration, WebRun } from './shared'; @@ -159,31 +160,12 @@ export function verificationKit(run: WebRun, now = new Date()): { filename: stri const directory = `theoremos-${run.id.slice(0, 8)}`; const mathlib = Boolean(environment.mathlibRevision); const check = ['import Submission', '', ...targets.map(name => `#print axioms ${identifier(name)}`), ''].join('\n'); - const readme = [ - `TheoremOS local verification · run ${run.id}`, - `Lean ${environment.toolchain}${mathlib ? ` · Mathlib ${environment.mathlibRevision}` : ' · core library only'}`, - '', - '中文', - '1. 安装 elan(Lean 版本管理器):https://github.com/leanprover/elan ;lean-toolchain 会自动选用上面的 Lean 版本。', - ...(mathlib - ? ['2. 在本目录运行 `lake exe cache get` 下载预编译的 Mathlib(首次约数 GB)。'] - : ['2. 标准库环境无需下载依赖。']), - '3. 运行 `lake build Submission`:没有 error 即 Lean 内核接受了 Submission.lean 中的全部证明。', - '4. 运行 `lake env lean Check.lean`:每个目标只应依赖 propext、Classical.choice、Quot.sound;出现 sorryAx 表示证明不完整,其他公理需逐一核对。', - '5. 比较 Original.lean 与 Submission.lean(如 `diff Original.lean Submission.lean`):目标定理的陈述应保持不变,只有证明和新增的辅助声明不同。', - 'report.json 是平台的验收记录,供对照,不参与上述检查。', - '', - 'English', - '1. Install elan (the Lean version manager): https://github.com/leanprover/elan . lean-toolchain selects the Lean version above.', - ...(mathlib - ? ['2. Run `lake exe cache get` here to download prebuilt Mathlib (several GB the first time).'] - : ['2. The core-library environment needs no downloads.']), - '3. Run `lake build Submission`. No errors means the Lean kernel accepted every proof in Submission.lean.', - '4. Run `lake env lean Check.lean`. Each target should depend only on propext, Classical.choice and Quot.sound; sorryAx means an incomplete proof, and any other axiom needs review.', - '5. Compare Original.lean with Submission.lean (for example `diff Original.lean Submission.lean`). Target statements should be unchanged; only proofs and added helper declarations differ.', - "report.json is the platform's acceptance record, kept for comparison; the steps above do not use it.", - '', - ].join('\n'); + const readme = instructions.template + .replace('{run}', run.id) + .replace('{toolchain}', environment.toolchain) + .replace('{dependency}', mathlib ? `Mathlib ${environment.mathlibRevision}` : 'core library only') + .replace('{stepZh}', mathlib ? instructions.mathlibZh : instructions.coreZh) + .replace('{stepEn}', mathlib ? instructions.mathlibEn : instructions.coreEn); const files = [ ...Object.entries(environment.files).map(([name, content]) => ({ name, content })), { name: 'Submission.lean', content: run.result!.proof }, diff --git a/apps/web/workbench-assets.json b/apps/web/workbench-assets.json new file mode 100644 index 00000000..2b070eae --- /dev/null +++ b/apps/web/workbench-assets.json @@ -0,0 +1,70 @@ +{ + "publicClientFiles": [ + "index.html", + "login.html", + "share.html", + "guide.html", + "terms.html", + "privacy.html", + "explain.html", + "formalize.html", + "formalize.css", + "research-conversation.css", + "people.html", + "theorems.html", + "library.html", + "workspace.html", + "problem.html", + "invite.html", + "practice.html", + "researchPractice.css", + "community.html", + "community.css", + "paper.html", + "paper.css" + ], + "reportPages": ["formalization.html", "explain.html"], + "fonts": [ + "Geist-latin.woff2", + "Geist-OFL.txt", + "TheoremOSSerif-latin.woff2", + "Lora-OFL.txt", + "JetBrainsMono.woff2", + "JetBrainsMono-OFL.txt", + "TheoremOSWorkbenchHeading.woff2", + "NotoSerifSC-ui.woff2", + "NotoSerifSC-ui-extra.woff2", + "NotoSerifSC-common.woff2", + "NotoSerifSC-OFL.txt", + "NotoSansSC-ui.woff2", + "NotoSansSC-ui-extra.woff2", + "NotoSansSC-common.woff2", + "NotoSansSC-OFL.txt" + ], + "stylesheets": { + "app.css": [ + "client/app.css", + "solutionRoute.css", + "client/productFlow.css", + "client/research-overview.css", + "client/decisionFlow.css", + "client/researchBudget.css", + "client/researchPersonal.css", + "client/proofMap.css", + "math.css" + ], + "research.css": [ + "client/research.css", + "client/collaborationFlow.css", + "client/researchCollections.css", + "client/researchWorkspace.css", + "client/researchProblem.css", + "client/researchLibraryTrials.css", + "client/researchCandidateContinuity.css", + "client/researchJourney.css", + "client/researchInlineActions.css", + "client/researchPersonal.css", + "client/researchBudget.css" + ] + } +} diff --git a/apps/web/worker-entrypoint.sh b/apps/web/worker-entrypoint.sh index 9112c742..72a274fa 100644 --- a/apps/web/worker-entrypoint.sh +++ b/apps/web/worker-entrypoint.sh @@ -1,5 +1,7 @@ #!/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) @@ -10,13 +12,23 @@ case "${2:-run}" in ;; *) exit 2 ;; esac -case "${1:-standard}" in +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 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 bun "$script" ;; + standard) exec "$@" ;; *) exit 2 ;; esac diff --git a/apps/web/worker.ts b/apps/web/worker.ts index d58eed6e..f0d6aa1d 100644 --- a/apps/web/worker.ts +++ b/apps/web/worker.ts @@ -2,6 +2,7 @@ import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { stringify as stringifyToml } from 'smol-toml'; +import { isNativeToolBundle } from '../../src/solver/researchToolGuide'; import { prepareWebProblem } from './formalizationSeed'; import { classifyWebError, classifyWebResult } from './failure'; import { getLeanTaskEnvironment, type LeanTaskEnvironment } from '../../src/math/leanTaskEnvironment'; @@ -266,7 +267,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.mjs'; +export const webAgentToolsDefault = '/opt/theoremos-agent-tools/math.native'; export const webPantographManifest = '/opt/theoremos-pantograph/manifest.json'; /** Pass only the frozen knowledge projection to the solver, outside all member worktrees. */ @@ -365,8 +366,14 @@ export function webSolverModules( ...(isolation && options.leanHealthCheck ? { leanHealthCheck: { - ...options.leanHealthCheck, - arguments: [isolation.tools, 'check-lean', ...options.leanHealthCheck.arguments.slice(1)], + executable: isNativeToolBundle(isolation.tools) + ? isolation.tools + : options.leanHealthCheck.executable, + arguments: [ + ...(isNativeToolBundle(isolation.tools) ? [] : [isolation.tools]), + 'check-lean', + ...options.leanHealthCheck.arguments.slice(1), + ], }, } : {}), diff --git a/bin/formalize-help.txt b/bin/formalize-help.txt new file mode 100644 index 00000000..8580d598 --- /dev/null +++ b/bin/formalize-help.txt @@ -0,0 +1,26 @@ +Usage: theorem-os formalize --phase prepare|run|inspect|replay|report --directory DIR [options] +prepare (offline): --problem ID --task-file FILE --build-manifest FILE + or --first-proof-problem first_proof_batch3_01 [--source-root DIR] --build-manifest FILE + [--environment mathlib|standard] [--model deepseek-flash] [--effort high] [--profile DIR] [--codex FILE] [--harness codex|claude-code|opencode|cli --harness-profile DIR --harness-executable FILE] + [--max-rounds 0] [--max-run-seconds 0] [--max-turn-seconds 0] [--max-compile-seconds 0] [--max-total-tokens 0] + [--review-mode direct|independent] (default: direct generation and Lean compilation, without model review) + [--statement-only] (direct mode: compile an open question to a Lean proposition) + [--review-config FILE] [--max-planning-rounds 0] (opt in to independent planning, backtranslation and review) + [--retrieval-workspace DIR --retrieval-corpus FILE] (offline opt-in: frozen matching Mathlib declarations for generation) + [--retrieval-symbols lean-exact-names-v1] (with retrieval: query exact Lean types and direct structure fields) + [--retrieval-queries lean-resolved-objects-v1] (with symbols: search resolved object names and all explicit plan mappings) + [--context-protocol kernel-v2|kernel-v3] (kernel-v3 records imported-library overflow instead of failing the round) + [--exemplar-corpus FILE] [--exemplar-count 8] [--exemplar-exclude ID,...] (frozen nearest NL/Lean pairs for planning and generation) + [--compatibility-names FILE --compatibility-provenance TEXT] (frozen declaration list of an older evaluation library; written names it lacks are compile feedback) + Execution limits default to 0 (unlimited); a positive safe integer sets an explicit limit. + [--reference-file FILE --reference-pairs FILE --reference-provenance TEXT] [--max-reference-seconds 0] +run: use the frozen request; starts or resumes generation and Lean elaboration, plus review only when configured. +inspect (offline): read a bounded summary and validate the approved artifact; never starts or resumes a run. +replay (no model): --build-manifest FILE; new directory only, preset tutorial candidate checked by real Lean. +report (offline): --output FILE.html; the approved statement beside the original problem and what its reviewers matched, + as one self-contained page (needs bun run build:web). +All directories must be outside the source repository. Existing requests are never overwritten. +Direct requests produce compiler-checked v4 artifacts marked semanticReview=not-performed. Legacy reviewed requests remain readable. +New requests freeze kernel-v3 complete local semantics with bounded imported-library expansion; saved requests retain their context protocol. +Independent mode retains task-preserving fidelity checks and parallel reviewers; review/retrieval/First Proof options select it explicitly. +Statement compilation is distinct from semantic review and proof acceptance. See docs/formalization.md. diff --git a/bin/math-help.txt b/bin/math-help.txt new file mode 100644 index 00000000..ccff187a --- /dev/null +++ b/bin/math-help.txt @@ -0,0 +1,40 @@ +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) + 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 + bootstrap-lean-eval Prepare a public Lean-Eval workspace + list-lean-eval List V1 obligations and public formalization gap warnings + freeze-retrieval Freeze allowed local Lean declaration sources + search-lean Find declarations in verified local Lean packages + declarations Search saved owned declarations with bounded type previews + knowledge Build and query previously checked theorem sources + hub Export frozen results and import private HuggingMath drafts + check-lean Check changed Lean files with bounded diagnostics + checkpoint Save the acknowledgment requested by the active host + plan-validate Check a cooperative Lead plan and report field-level issues + check-finite Replay finite Boolean constraints and return witnesses + kernel-certificate Generate chunked decide +kernel certificate modules + library-pack Extract checked run modules or backport upstream files as a frozen library + library-catalog Index versioned library releases and select only the modules a task needs + library Search the pinned release, inspect sources and request host installation + auto-library Plan, prove and publish the library modules a problem needs, before solving it + continuation Read or search frozen continuation attachments in bounded pages + continuation-seed Initialize a new prepared run from advisory sources and fresh helper checks + inspect Read a research report or export a versioned task plan + recover Restore a research snapshot and recheck saved helpers + edit Approve the exact version of a native team's initial route + compare Read and check saved comparison reports + sample-putnam Read and check saved PutnamBench sample reports + first-proof Audit and prepare the First Proof Batch 3 Lean adaptation offline + formalize Formalize an informal problem and review its Lean statement + informalize Explain a checked Lean proof in natural language, step by step with audits + evaluate-formalization Prepare, review and score blind formalization candidates + summarize Summarize saved proof-run receipts + +Use theorem-os --help for command arguments. diff --git a/bin/math.ts b/bin/math.ts index 1e3a6e13..62e3fcf9 100644 --- a/bin/math.ts +++ b/bin/math.ts @@ -50,45 +50,7 @@ if (args.length === 1 && args[0] === '-h') args[0] = '--help'; const runHelp = command === 'run' && args.length === 1 && args[0] === '--help'; const missingBundle = command === 'run' && !fs.existsSync(path.join(root, commands.run)); if (!command || ['help', '--help', '-h'].includes(command)) { - console.log(`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 replaceable search component - run Run or resume an isolated mathematics proof (optional --portfolio-exploration) - batch Run prepared problems concurrently in separate processes - bootstrap-imo Prepare an IMO2026 proof workspace - bootstrap-lean-eval Prepare a public Lean-Eval workspace - list-lean-eval List V1 obligations and public formalization gap warnings - freeze-retrieval Freeze allowed local Lean declaration sources - search-lean Find declarations in verified local Lean packages - declarations Search saved owned declarations with bounded type previews - knowledge Build and query previously checked theorem sources - hub Export frozen results and import private HuggingMath drafts - check-lean Check changed Lean files with bounded diagnostics - checkpoint Save the acknowledgment requested by the active host - plan-validate Check a cooperative Lead plan and report field-level issues - check-finite Replay finite Boolean constraints and return witnesses - kernel-certificate Generate chunked decide +kernel certificate modules - library-pack Extract checked run modules or backport upstream files as a frozen library - library-catalog Index versioned library releases and select only the modules a task needs - library Search the pinned release, inspect sources and request host installation - auto-library Plan, prove and publish the library modules a problem needs, before solving it - continuation Read or search frozen continuation attachments in bounded pages - continuation-seed Initialize a new prepared run from advisory sources and fresh helper checks - inspect Read a research report or export a versioned task plan - recover Restore a research snapshot and recheck saved helpers - edit Approve the exact version of a native team's initial route - compare Read and check saved comparison reports - sample-putnam Read and check saved PutnamBench sample reports - first-proof Audit and prepare the First Proof Batch 3 Lean adaptation offline - formalize Formalize an informal problem and review its Lean statement - informalize Explain a checked Lean proof in natural language, step by step with audits - evaluate-formalization Prepare, review and score blind formalization candidates - summarize Summarize saved proof-run receipts - -Use theorem-os --help for command arguments.`); + process.stdout.write(fs.readFileSync(path.join(root, 'bin/math-help.txt'))); } else if (!Object.hasOwn(commands, command)) { console.error(`Unknown command: ${command}. Run theorem-os --help to list commands.`); process.exitCode = 1; @@ -97,7 +59,9 @@ Use theorem-os --help for command arguments.`); process.exitCode = 1; } else { // Only help may use the source entry; proof runs require the frozen bundle. - const entry = missingBundle ? 'scripts/mathematics/runMathProof.ts' : commands[command]!; + const bundledSeed = command === 'continuation-seed' && fs.existsSync(path.join(root, commands.run)); + const entry = bundledSeed ? commands.run : missingBundle ? 'scripts/mathematics/runMathProof.ts' : commands[command]!; + if (bundledSeed) args.unshift('--theoremos-continuation-seed'); const env = { ...process.env, CODEX_HOME: process.env.CODEX_HOME || path.join(os.homedir(), '.config', 'deepscientist', 'math-sol-codex'), diff --git a/bin/theorem-os b/bin/theorem-os new file mode 100755 index 00000000..6d5604d3 --- /dev/null +++ b/bin/theorem-os @@ -0,0 +1,14 @@ +#!/bin/sh +# Package managers may link this file into a separate bin directory. +entry=$0 +case $entry in /*) ;; *) entry=$PWD/$entry ;; esac +while [ -L "$entry" ]; do + target=$(command -p readlink "$entry") || exit 1 + 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/rust-migration.md b/docs/rust-migration.md new file mode 100644 index 00000000..6e5f5801 --- /dev/null +++ b/docs/rust-migration.md @@ -0,0 +1,246 @@ +# Running the Rust migration branch + +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 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 +``` + +To run outside the checkout, copy `target/release/theorem-os` to an installation +directory on the Linux host. 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. + +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 the Sub2API profile or a Responses profile whose model supports Codex +multi-agent v2. + +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`. + +| 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 at a frozen Git commit using Bubblewrap and Lean. It supports TOML projects with local modules and Git dependencies already installed under `.lake/packages` at the revisions in the committed Lake manifest. Rust checks the tracked package files and seals the package tree before the offline check. The advisory report records the digest of the image, including any precompiled package files. Statement checking allows `sorry` in proof bodies. + +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 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, definition targets, 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 report research through the collaboration tools. The Lead integrates their findings into the complete candidate for independent Lean acceptance. Structured lemma delivery, adoption and route approval remain available through the full solver bundle. + +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. The replay still runs the frozen TypeScript bundle with Node.js for build orchestration and planner callbacks. It requires Node.js 22 or newer and the pinned Lean toolchain. The active online build still opens its sessions with Bun. 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 using the built Web assets. 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. Active model sessions use the Bun host. Both the native build and the 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` prepare and score phases run in Rust. They freeze blind reviewer inputs separately from labels and references, reconstruct the source-family split when reopening a bundle, and score saved decisions against the original labels. The Rust CLI can replay direct v1 and structured v2 presets, resume independent roles across hosts, and revalidate the frozen inputs, observations and receipts before publishing decisions. Structured review keeps missing observations pending and records a completed unavailable observation as unknown. For historical task-preserving reviews, Rust verifies saved Lean comparison receipts and runs missing comparisons in the pinned sandbox. It tests strict identity first for v2 and checks the recorded fallback rules when identity fails. Once every v1 or v2 model review case has a saved receipt, the standalone Rust CLI revalidates the build, harness, provider profile and role sandbox receipts, then reconstructs the final state and decisions. This covers interruptions after the last receipt is published. The Bun host opens isolated model sessions. In an installed build, those sessions use Rust to check outputs, persist corrections, record cumulative token usage and authenticate completed roles. + +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. Runs bound to these manifests skip automatic explanations. 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 active writer and auditor sessions still use the Bun host. + +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. + +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. diff --git a/examples/components/README.md b/examples/components/README.md index e38905be..27f876a9 100644 --- a/examples/components/README.md +++ b/examples/components/README.md @@ -1,26 +1,20 @@ -# 替换一个研究组件 +# 检查研究组件的排序策略 -TheoremOS 的扩展单位是带版本的 `SolverModules` 组件。 -Agent 数量和角色由运行时组织;替换研究策略无需新增 Agent。 -目前通过 TypeScript 源码组合组件,尚未提供动态插件加载或稳定 SDK。 - -## 生成自己的组件 - -从仓库根目录执行: +从仓库根目录执行下面的命令。首次构建需要 Cargo,此后 `check` 使用本机的 `rustc` 和链接器编译组件,只依赖 Rust 标准库。 ```bash -bun run math component init --name my-search -bun run math component check --name my-search +cargo build --locked --release --bin theorem-os +bin/theorem-os component init --name my-search +bin/theorem-os component check --name my-search ``` -第一条命令生成 `src/components/my-search.ts` 和 `scripts/components/my-search.ts`。 -在第一个文件中修改 `ready` 函数,就能改变就绪任务的顺序;其余四个组件继续使用默认实现。 -已有同名文件会被保留,命令会提示换一个名字。 +`init` 生成 `rust/components/my-search.rs`。文件中的 `ready(tasks, routes)` 接受只读任务和路线,返回按优先级排列的任务引用。默认模板用 `ready_tasks` 筛选就绪任务,再把目标排在研究任务前面。修改排序策略后,在同一文件更新 `ID`。已有同名 Rust 文件、旧 TypeScript 组件或旧运行入口都会阻止创建。 + +`check` 在临时目录编译并执行该组件。它检查每个就绪任务恰好返回一次,覆盖依赖完成前后、暂停任务、停止路线和预算耗尽的路线,并输出排序和组件 ID。这个本地合同只用合成任务。新组件的类型和测试数据见[检查合同](../../rust/cli/src/component/contract.rs)。 + +## 使用历史版本复现调度实验 -`check` 不调用模型或 Lean,用几个本地任务检查排序是否保留了依赖、暂停、路线和预算约束。 -它只检查这个排序模板的基本约定,策略是否有效仍需要实验。 -改变策略后,更新 `id` 和 M3 的 `version`,再运行检查。 -当前版本生成的组件运行脚本用于恢复已有运行。 +旧 TypeScript 组件及其求解入口使用实验固定的 TheoremOS 版本。保留原来的源码、构建清单和工作区。当前 Rust 组件的范围是本地排序检查。 以下运行命令用于复现历史调度器中的组件实验。在实验固定的 TheoremOS 版本中,先配置 Codex 和 Lean 环境,再使用一个仓库外的新目录。 diff --git a/package.json b/package.json index dfafcf71..7f6deb88 100644 --- a/package.json +++ b/package.json @@ -10,11 +10,11 @@ }, "packageManager": "bun@1.4.0", "bin": { - "theorem-os": "bin/math.ts", - "deepscientist-math": "bin/math.ts" + "theorem-os": "bin/theorem-os", + "deepscientist-math": "bin/theorem-os" }, "scripts": { - "math": "bun bin/math.ts", + "math": "./bin/theorem-os", "build": "bun scripts/build.ts", "build:site": "bun scripts/build-site.ts", "import:math-results": "bun scripts/import-math-campaign.ts", diff --git a/resources/auto-library-replay.json b/resources/auto-library-replay.json new file mode 100644 index 00000000..6f06b702 --- /dev/null +++ b/resources/auto-library-replay.json @@ -0,0 +1,134 @@ +{ + "source": "theorem replay_target (n : Nat) : n + n + (n + n) = 4 * n := by\n sorry\n", + "task": "Prove replay_target.", + "base": { + "schema": "theorem-os.library-pack.v1", + "modules": [ + { + "file": "Submission/Library/Fixture/Double.lean", + "source": "namespace Fixture\n\ndef double (n : Nat) : Nat := n + n\n\ntheorem double_eq_two_mul (n : Nat) : double n = 2 * n := by\n unfold double; omega\n\nend Fixture\n", + "origin": { + "kind": "upstream", + "repository": "theorem-os-auto-library-replay", + "commit": "0000000000000000000000000000000000000000", + "file": "Fixture/Double.lean" + } + } + ] + }, + "plans": { + "0/1": { + "decision": "module", + "reason": "global notation (host rejects it)", + "name": "Quadruple", + "summary": "Quadrupling natural numbers as two doublings, with its closed form and additivity.", + "sources": [ + "Peano arithmetic (standard)" + ], + "lean": "import Submission.Library.Fixture.Double\n\nopen Fixture\n\nnotation \"𝟜\" => 4\n\nnamespace TheoremOS.Auto.Quadruple\n\n/-- Four times a number, as two doublings. -/\ndef quadruple (n : Nat) : Nat := double (double n)\n\ntheorem quadruple_eq (n : Nat) : quadruple n = 4 * n := by\n sorry\n\ntheorem quadruple_add (m n : Nat) : quadruple (m + n) = quadruple m + quadruple n := by\n sorry\n\nend TheoremOS.Auto.Quadruple\n", + "target": "replay_target", + "application": "Apply TheoremOS.Auto.Quadruple.quadruple_eq to the consumer parameter n.", + "remaining": [], + "consumerApplication": { + "declaration": "TheoremOS.Auto.Quadruple.quadruple_eq", + "application": { + "expression": "TheoremOS.Auto.Quadruple.quadruple_eq", + "expectedType": "∀ n : Nat, n + n + (n + n) = 4 * n", + "context": { + "file": "Submission.lean", + "declaration": "replay_target" + }, + "remainingGoals": [] + } + } + }, + "0/2": { + "decision": "module", + "reason": "misspelled definition (Lean rejects it)", + "name": "Quadruple", + "summary": "Quadrupling natural numbers as two doublings, with its closed form and additivity.", + "sources": [ + "Peano arithmetic (standard)" + ], + "lean": "import Submission.Library.Fixture.Double\n\nopen Fixture\n\nnamespace TheoremOS.Auto.Quadruple\n\n/-- Four times a number, as two doublings. -/\ndef quadruple (n : Nat) : Nat := doubel (double n)\n\ntheorem quadruple_eq (n : Nat) : quadruple n = 4 * n := by\n sorry\n\ntheorem quadruple_add (m n : Nat) : quadruple (m + n) = quadruple m + quadruple n := by\n sorry\n\nend TheoremOS.Auto.Quadruple\n", + "target": "replay_target", + "application": "Apply TheoremOS.Auto.Quadruple.quadruple_eq to the consumer parameter n.", + "remaining": [], + "consumerApplication": { + "declaration": "TheoremOS.Auto.Quadruple.quadruple_eq", + "application": { + "expression": "TheoremOS.Auto.Quadruple.quadruple_eq", + "expectedType": "∀ n : Nat, n + n + (n + n) = 4 * n", + "context": { + "file": "Submission.lean", + "declaration": "replay_target" + }, + "remainingGoals": [] + } + } + }, + "0/3": { + "decision": "module", + "reason": "the replay solver proves nothing in this round", + "name": "Quadruple", + "summary": "Quadrupling natural numbers as two doublings, with its closed form and additivity.", + "sources": [ + "Peano arithmetic (standard)" + ], + "lean": "import Submission.Library.Fixture.Double\n\nopen Fixture\n\nnamespace TheoremOS.Auto.Quadruple\n\n/-- Four times a number, as two doublings. -/\ndef quadruple (n : Nat) : Nat := double (double n)\n\ntheorem quadruple_eq (n : Nat) : quadruple n = 4 * n := by\n sorry\n\ntheorem quadruple_add (m n : Nat) : quadruple (m + n) = quadruple m + quadruple n := by\n sorry\n\nend TheoremOS.Auto.Quadruple\n", + "target": "replay_target", + "application": "Apply TheoremOS.Auto.Quadruple.quadruple_eq to the consumer parameter n.", + "remaining": [], + "consumerApplication": { + "declaration": "TheoremOS.Auto.Quadruple.quadruple_eq", + "application": { + "expression": "TheoremOS.Auto.Quadruple.quadruple_eq", + "expectedType": "∀ n : Nat, n + n + (n + n) = 4 * n", + "context": { + "file": "Submission.lean", + "declaration": "replay_target" + }, + "remainingGoals": [] + } + } + }, + "0/4": { + "decision": "module", + "reason": "the replay solver proves both theorems", + "name": "Quadruple", + "summary": "Quadrupling natural numbers as two doublings, with its closed form and additivity.", + "sources": [ + "Peano arithmetic (standard)" + ], + "lean": "import Submission.Library.Fixture.Double\n\nopen Fixture\n\nnamespace TheoremOS.Auto.Quadruple\n\n/-- Four times a number, as two doublings. -/\ndef quadruple (n : Nat) : Nat := double (double n)\n\ntheorem quadruple_eq (n : Nat) : quadruple n = 4 * n := by\n sorry\n\ntheorem quadruple_add (m n : Nat) : quadruple (m + n) = quadruple m + quadruple n := by\n sorry\n\nend TheoremOS.Auto.Quadruple\n", + "target": "replay_target", + "application": "Apply TheoremOS.Auto.Quadruple.quadruple_eq to the consumer parameter n.", + "remaining": [], + "consumerApplication": { + "declaration": "TheoremOS.Auto.Quadruple.quadruple_eq", + "application": { + "expression": "TheoremOS.Auto.Quadruple.quadruple_eq", + "expectedType": "∀ n : Nat, n + n + (n + n) = 4 * n", + "context": { + "file": "Submission.lean", + "declaration": "replay_target" + }, + "remainingGoals": [] + } + } + }, + "1/1": { + "decision": "none", + "reason": "the published module is enough", + "name": null, + "summary": null, + "sources": null, + "lean": null, + "target": null, + "application": null, + "remaining": null + } + }, + "solution": "import Submission.Library.Auto.Quadruple\n\ntheorem replay_target (n : Nat) : n + n + (n + n) = 4 * n := by\n exact TheoremOS.Auto.Quadruple.quadruple_eq n\n", + "proofCandidate": "import Submission.Library.Fixture.Double\n\nopen Fixture\n\nnamespace TheoremOS.Auto.Quadruple\n\n/-- Four times a number, as two doublings. -/\ndef quadruple (n : Nat) : Nat := double (double n)\n\ntheorem quadruple_eq (n : Nat) : quadruple n = 4 * n := by\n unfold quadruple double; omega\n\ntheorem quadruple_add (m n : Nat) : quadruple (m + n) = quadruple m + quadruple n := by\n simp only [quadruple, double]; omega\n\nend TheoremOS.Auto.Quadruple\n" +} diff --git a/resources/formalization-replay/preset.json b/resources/formalization-replay/preset.json new file mode 100644 index 00000000..88a6c840 --- /dev/null +++ b/resources/formalization-replay/preset.json @@ -0,0 +1,321 @@ +{ + "request": { + "contextProtocol": "kernel-v3", + "effort": "none", + "environment": "standard", + "executable": "/no-model", + "execution": "replay", + "maxCompileSeconds": 120, + "maxRounds": 3, + "maxRunSeconds": 300, + "maxTotalTokens": 0, + "maxTurnSeconds": 30, + "model": "preset-replay", + "outputDelivery": "native-schema", + "problemId": "formalization_replay_addition", + "profile": "/preset-replay", + "schema": "theorem-os.formalization-request.v3", + "statement": "For every natural number n, prove both n + 0 = n and 0 + n = n.", + "workflow": { + "backtranslator": { + "effort": "none", + "executable": "/no-model", + "model": "preset-replay", + "profile": "/preset-replay" + }, + "candidateSelection": "first-unanimously-approved", + "maxPlanningRounds": 0, + "planner": { + "effort": "none", + "executable": "/no-model", + "model": "preset-replay", + "profile": "/preset-replay" + }, + "reviewPolicy": "all-approve", + "reviewers": [ + { + "effort": "none", + "executable": "/no-model", + "id": "reviewer-1", + "model": "preset-replay", + "profile": "/preset-replay" + }, + { + "effort": "none", + "executable": "/no-model", + "id": "reviewer-2", + "model": "preset-replay", + "profile": "/preset-replay" + } + ], + "schema": "theorem-os.formalization-workflow.v2" + } + }, + "plan": { + "assumptions": [], + "conclusions": [ + { + "assumptionIds": [], + "id": "conclusion-left", + "mathematics": "For all n : Nat, n + 0 = n.", + "spanIds": [ + "original" + ], + "targetNames": [ + "left" + ] + }, + { + "assumptionIds": [], + "id": "conclusion-right", + "mathematics": "For all n : Nat, 0 + n = n.", + "spanIds": [ + "original" + ], + "targetNames": [ + "right" + ] + } + ], + "definitions": [], + "objects": [ + { + "description": "An arbitrary natural number n.", + "id": "natural-number", + "leanType": "Nat", + "spanIds": [ + "original" + ] + } + ], + "schema": "theorem-os.formalization-plan.v1", + "spans": [ + { + "end": 63, + "id": "original", + "start": 0, + "text": "For every natural number n, prove both n + 0 = n and 0 + n = n." + } + ], + "taskKind": "prove", + "unresolved": [] + }, + "candidates": [ + { + "assumptions": [ + "n is a natural number" + ], + "assumptionsExplanation": "Natural-number domain; no additional hypotheses.", + "coverage": [ + { + "explanation": "Preset fixture only; translate both addition targets.", + "originalText": "For every natural number n, prove both n + 0 = n and 0 + n = n.", + "targetNames": [ + "left", + "right" + ] + } + ], + "definitionsExplanation": "Uses standard natural-number addition.", + "source": "theorem left (n : MissingNat) : n + 0 = n := by sorry\ntheorem right (n : Nat) : 0 + n = n := by sorry\n" + }, + { + "assumptions": [ + "n is a natural number" + ], + "assumptionsExplanation": "Natural-number domain; no additional hypotheses.", + "coverage": [ + { + "explanation": "Preset fixture only; translate both addition targets.", + "originalText": "For every natural number n, prove both n + 0 = n and 0 + n = n.", + "targetNames": [ + "left", + "right" + ] + } + ], + "definitionsExplanation": "Uses standard natural-number addition.", + "source": "theorem left (n : Nat) : n + 0 = 0 := by sorry\ntheorem right (n : Nat) : 0 + n = n := by sorry\n" + }, + { + "assumptions": [ + "n is a natural number" + ], + "assumptionsExplanation": "Natural-number domain; no additional hypotheses.", + "coverage": [ + { + "explanation": "Preset fixture only; translate both addition targets.", + "originalText": "For every natural number n, prove both n + 0 = n and 0 + n = n.", + "targetNames": [ + "left", + "right" + ] + } + ], + "definitionsExplanation": "Uses standard natural-number addition.", + "source": "theorem left (n : Nat) : n + 0 = n := by sorry\ntheorem right (n : Nat) : 0 + n = n := by sorry\n" + } + ], + "reviews": { + "revision": { + "checks": { + "assumptions": "faithful", + "conclusions": "mismatch", + "definitions": "faithful", + "domains": "faithful", + "instanceCoherence": "faithful", + "quantifierScope": "faithful" + }, + "correspondences": [ + { + "aspect": "domains", + "explanation": "Preset fixture compares the natural-number zero identities.", + "forwardArgument": "", + "mismatchEvidence": null, + "relation": "direct", + "reverseArgument": "", + "sourceReadings": [] + }, + { + "aspect": "assumptions", + "explanation": "Preset fixture compares the natural-number zero identities.", + "forwardArgument": "", + "mismatchEvidence": null, + "relation": "direct", + "reverseArgument": "", + "sourceReadings": [] + }, + { + "aspect": "conclusions", + "explanation": "Restore n as the first target right hand side.", + "forwardArgument": "", + "mismatchEvidence": { + "candidateClaim": "For every natural n, n + 0 = 0 and 0 + n = n.", + "separationArgument": "At n = 1, the first candidate equality fails while both source equalities hold.", + "sourceClaim": "For every natural n, n + 0 = n and 0 + n = n." + }, + "relation": "mismatch", + "reverseArgument": "", + "sourceReadings": [] + }, + { + "aspect": "definitions", + "explanation": "Preset fixture compares the natural-number zero identities.", + "forwardArgument": "", + "mismatchEvidence": null, + "relation": "direct", + "reverseArgument": "", + "sourceReadings": [] + }, + { + "aspect": "quantifierScope", + "explanation": "Preset fixture compares the natural-number zero identities.", + "forwardArgument": "", + "mismatchEvidence": null, + "relation": "direct", + "reverseArgument": "", + "sourceReadings": [] + }, + { + "aspect": "instanceCoherence", + "explanation": "Preset fixture compares the natural-number zero identities.", + "forwardArgument": "", + "mismatchEvidence": null, + "relation": "direct", + "reverseArgument": "", + "sourceReadings": [] + } + ], + "evidenceVersion": "source-readings-v1", + "schema": "theorem-os.formalization-semantic-review.v2", + "summary": "The first target changed the conclusion.", + "verdict": "changes_requested" + }, + "repair": { + "checks": { + "assumptions": "faithful", + "conclusions": "faithful", + "definitions": "faithful", + "domains": "faithful", + "instanceCoherence": "faithful", + "quantifierScope": "faithful" + }, + "correspondences": [ + { + "aspect": "domains", + "explanation": "Preset fixture compares the natural-number zero identities.", + "forwardArgument": "", + "mismatchEvidence": null, + "relation": "direct", + "reverseArgument": "", + "sourceReadings": [] + }, + { + "aspect": "assumptions", + "explanation": "Preset fixture compares the natural-number zero identities.", + "forwardArgument": "", + "mismatchEvidence": null, + "relation": "direct", + "reverseArgument": "", + "sourceReadings": [] + }, + { + "aspect": "conclusions", + "explanation": "Preset fixture compares the natural-number zero identities.", + "forwardArgument": "", + "mismatchEvidence": null, + "relation": "direct", + "reverseArgument": "", + "sourceReadings": [] + }, + { + "aspect": "definitions", + "explanation": "Preset fixture compares the natural-number zero identities.", + "forwardArgument": "", + "mismatchEvidence": null, + "relation": "direct", + "reverseArgument": "", + "sourceReadings": [] + }, + { + "aspect": "quantifierScope", + "explanation": "Preset fixture compares the natural-number zero identities.", + "forwardArgument": "", + "mismatchEvidence": null, + "relation": "direct", + "reverseArgument": "", + "sourceReadings": [] + }, + { + "aspect": "instanceCoherence", + "explanation": "Preset fixture compares the natural-number zero identities.", + "forwardArgument": "", + "mismatchEvidence": null, + "relation": "direct", + "reverseArgument": "", + "sourceReadings": [] + } + ], + "evidenceVersion": "source-readings-v1", + "schema": "theorem-os.formalization-semantic-review.v2", + "summary": "Both original zero identities are faithfully represented.", + "verdict": "approved" + } + }, + "translations": { + "revision": { + "assumptions": [], + "definitions": [ + "Standard natural-number addition." + ], + "mathematics": "The first target incorrectly states n + 0 = 0." + }, + "repair": { + "assumptions": [], + "definitions": [ + "Standard natural-number addition." + ], + "mathematics": "Both natural-number zero identities." + } + } +} diff --git a/resources/lean/ConditionalProjection.lean b/resources/lean/ConditionalProjection.lean new file mode 100644 index 00000000..7002ceb8 --- /dev/null +++ b/resources/lean/ConditionalProjection.lean @@ -0,0 +1,257 @@ +namespace TheoremOS.Host.ConditionalProjection +open Lean Meta Elab Term + +structure Dependency where + theoremName : String + type : String + deriving FromJson, Inhabited + +structure Payload where + declaration : String + dependencies : Array Dependency + deriving FromJson, Inhabited + +private def parsePayload (text : String) : TermElabM Payload := do + match Json.parse text >>= fromJson? with + | .ok value => pure value + | .error message => throwError "Invalid host conditional projection: {message}" + +private def parseTerm (text : String) : TermElabM Syntax := do + match Parser.runParserCategory (← getEnv) `term text with + | .ok stx => pure stx + | .error message => throwError "Invalid conditional type: {message}" + +private def addDependency (dependency : Dependency) : TermElabM Unit := do + let name := dependency.theoremName.toName + if (← getEnv).contains name then throwError "Conditional declaration already exists: {name}" + let type ← withoutErrToSorry <| elabType (← parseTerm dependency.type) + synthesizeSyntheticMVarsNoPostponing + let type ← levelMVarToParam (← instantiateMVars type) + if type.hasFVar || type.hasMVar || type.hasLevelMVar then + throwError "Conditional dependency type must be closed" + let params := (collectLevelParams {} type).params.toList + addDecl <| .axiomDecl { name, levelParams := params, type, isUnsafe := false } + +private def addDependencies (dependencies : Array Dependency) : TermElabM Unit := do + let mut pending := dependencies + while !pending.isEmpty do + let mut next := #[] + let mut lastError : Option Exception := none + for dependency in pending do + let saved ← Term.saveState + try addDependency dependency + catch error => + saved.restore + next := next.push dependency + lastError := some error + if next.size == pending.size then + match lastError with + | some error => throw error + | none => throwError "Conditional dependency types contain a cycle" + pending := next + +private def declarationTerm (text : String) : TermElabM Syntax := do + let parsed ← match Parser.runParserCategory (← getEnv) `command text with + | .ok stx => pure stx + | .error message => throwError "Invalid conditional declaration: {message}" + -- Mathlib's lemma is a command macro, not a child of Command.declaration. + -- Expand only this supported alias, then apply the same named-declaration checks. + let parsed ← if parsed.getKind == `lemma then do + let some expanded ← liftMacroM <| expandMacro? parsed + | throwError "Conditional projection requires a named declaration" + unless expanded.getKind == ``Lean.Parser.Command.declaration && + expanded[1].getKind == ``Lean.Parser.Command.theorem && + expanded[1][1] == parsed[1][1] do + throwError "Conditional lemma macro changed its declaration identity" + pure expanded + else pure parsed + unless parsed.getKind == ``Lean.Parser.Command.declaration do + throwError "Conditional projection requires a named declaration" + let sectionVars := (← read).sectionVars + let parsed ← parsed.replaceM fun stx => do + match stx with + | .ident info raw name resolved => + let localInputs := Quotation.resolveSectionVariable sectionVars name + if localInputs.isEmpty then pure none else + pure (some (.ident info raw name (localInputs.map (fun (name, fields) => .decl name fields) ++ resolved))) + | _ => pure none + let declaration := parsed[1] + unless [``Lean.Parser.Command.theorem, ``Lean.Parser.Command.definition, ``Lean.Parser.Command.abbrev].contains declaration.getKind do + throwError "Conditional projection requires a named declaration" + unless declaration[3].getKind == ``Lean.Parser.Command.declValSimple do + throwError "Conditional projection requires a proof term" + let (rawBinders, result?) := if declaration[2].getKind == ``Lean.Parser.Command.declSig then + let (binders, result) := expandDeclSig declaration[2] + (binders, some result) + else expandOptDeclSig declaration[2] + let binders : TSyntaxArray ``Lean.Parser.Term.funBinder := rawBinders.getArgs.map (fun stx => ⟨stx⟩) + let proof : TSyntax `term := ⟨declaration[3][1]⟩ + let value ← match result? with + | some result => do + let result : TSyntax `term := ⟨result⟩ + `(show $result from $proof) + | none => pure proof + if binders.isEmpty then pure value else `(fun $binders* => $value) + +private partial def inlineTemporary (base : Environment) (dependencies : Array Dependency) + (expression : Expr) (stack : List Name := []) : TermElabM Expr := do + match expression with + | .const name levels => + if base.contains name || dependencies.any (fun dep => dep.theoremName.toName == name) then return expression + if stack.contains name then throwError "Recursive temporary declaration in conditional proof: {name}" + let info ← getConstInfo name + let some value := (match info with + | .defnInfo value => some value.value + | .thmInfo value => some value.value + | .opaqueInfo value => some value.value + | _ => none) + | throwError "Unsupported temporary declaration in conditional proof: {name}" + inlineTemporary base dependencies (value.instantiateLevelParams info.levelParams levels) (name :: stack) + | .app f a => return .app (← inlineTemporary base dependencies f stack) (← inlineTemporary base dependencies a stack) + | .lam n t b bi => return .lam n (← inlineTemporary base dependencies t stack) (← inlineTemporary base dependencies b stack) bi + | .forallE n t b bi => return .forallE n (← inlineTemporary base dependencies t stack) (← inlineTemporary base dependencies b stack) bi + | .letE n t v b nondep => return .letE n (← inlineTemporary base dependencies t stack) (← inlineTemporary base dependencies v stack) (← inlineTemporary base dependencies b stack) nondep + | .mdata data body => return .mdata data (← inlineTemporary base dependencies body stack) + | .proj name index body => return .proj name index (← inlineTemporary base dependencies body stack) + | _ => return expression + +private partial def collectUses (dependencies : Array Dependency) (expression : Expr) + (uses : Array Expr := #[]) : Array Expr := Id.run do + let mut uses := uses + match expression with + | .const name _ => + if dependencies.any (fun dep => dep.theoremName.toName == name) && !uses.contains expression then + uses := uses.push expression + | .app f a => uses := collectUses dependencies a (collectUses dependencies f uses) + | .lam _ t b _ | .forallE _ t b _ => uses := collectUses dependencies b (collectUses dependencies t uses) + | .letE _ t v b _ => uses := collectUses dependencies b (collectUses dependencies v (collectUses dependencies t uses)) + | .mdata _ b | .proj _ _ b => uses := collectUses dependencies b uses + | _ => pure () + return uses + +private def orderUses (dependencies : Array Dependency) (uses : Array Expr) : TermElabM (Array Expr) := do + let mut pending := uses + let mut ordered := #[] + while !pending.isEmpty do + let mut next := #[] + for use in pending do + let required := collectUses dependencies (← inferType use) + if required.all (fun input => ordered.contains input) then + ordered := ordered.push use + else + next := next.push use + if next.size == pending.size then throwError "Conditional dependency instances contain a cycle" + pending := next + return ordered + +private def replaceUses (expression : Expr) (uses localInputs : Array Expr) : Expr := + expression.replace fun current => + (uses.findIdx? (fun use => use == current)).map (fun index => localInputs[index]!) + +private partial def abstractUses (dependencies : Array Dependency) (uses : Array Expr) (proof : Expr) + (index : Nat := 0) (localInputs : Array Expr := #[]) : TermElabM Expr := do + if index == uses.size then + return ← mkLambdaFVars localInputs (replaceUses proof uses localInputs) + let use := uses[index]! + let dependencyIndex := dependencies.findIdx? (fun dep => dep.theoremName.toName == use.constName!) |>.getD 0 + let type := replaceUses (← inferType use) (uses.extract 0 index) localInputs + withLocalDeclD (Name.mkSimple s!"_theoremOS_condition_{dependencyIndex}_{index}") type fun input => + abstractUses dependencies uses proof (index + 1) (localInputs.push input) + +private def generate (text : String) : TermElabM (List Name × Expr × Expr) := do + let initialLevels ← getLevelNames + withLevelNames initialLevels do + let payload ← parsePayload text + let base ← getEnv + withoutModifyingEnv do + addDependencies payload.dependencies + setLevelNames initialLevels + let value ← withoutErrToSorry <| elabTerm (← declarationTerm payload.declaration) none + synthesizeSyntheticMVarsNoPostponing + let value ← instantiateMVars value + let value ← inlineTemporary base payload.dependencies value + let value ← mkLambdaFVars (← getLCtx).getFVars value (usedOnly := true) + let mut uses := collectUses payload.dependencies (← inferType value) (collectUses payload.dependencies value) + let mut cursor := 0 + while cursor < uses.size do + uses := collectUses payload.dependencies (← inferType uses[cursor]!) uses + cursor := cursor + 1 + let ordered ← orderUses payload.dependencies uses + let value ← abstractUses payload.dependencies ordered value + let value ← levelMVarToParam value + let type ← inferType value + if value.hasFVar || value.hasMVar || value.hasLevelMVar || type.hasFVar || type.hasMVar || type.hasLevelMVar then + throwError "Conditional projection did not close its proof" + unless (collectUses payload.dependencies value).isEmpty && (collectUses payload.dependencies type).isEmpty do + throwError "Conditional placeholder escaped abstraction" + let params := (collectLevelParams (collectLevelParams {} type) value).params.toList.filter (fun p => !initialLevels.contains p) + return (params, type, value) + +private def cacheKey (text : String) : TermElabM Name := do + pure <| Name.str (← getCurrNamespace) ("_theoremOS_conditional_cache_" ++ toString (hash text)) + +private def obtain (text : String) : TermElabM (List Name × Expr × Expr) := do + let key ← cacheKey text + if let some info := (← getEnv).find? key then + let some proof := (match info with + | .defnInfo value => some value.value + | _ => none) | throwError "Invalid conditional projection cache declaration" + let scope ← getLevelNames + return (info.levelParams.filter (fun name => !scope.contains name), info.type, proof) + let (params, type, proof) ← generate text + let allParams := (collectLevelParams (collectLevelParams {} type) proof).params.toList + addDecl <| .defnDecl { name := key, levelParams := allParams, type := type, value := proof, hints := .opaque, safety := .safe } + return (params, type, proof) + +elab "theorem_os_conditional_type% " payload:str : term => do + let (params, type, _) ← obtain payload.getString + let levels ← params.mapM fun _ => mkFreshLevelMVar + pure (type.instantiateLevelParams params levels) + +elab "theorem_os_conditional_proof% " payload:str : term => do + let (params, _, proof) ← obtain payload.getString + let levels ← params.mapM fun _ => mkFreshLevelMVar + pure (proof.instantiateLevelParams params levels) + +private def inputIndex (name : Name) : Option (Nat × Nat) := do + match name.toString.splitOn "_" with + | ["", "theoremOS", "condition", dependency, occurrence] => + return (← dependency.toNat?, ← occurrence.toNat?) + | _ => none + +private partial def validateExpected (dependencies : Array Dependency) (taskType : Syntax) + (actual : Expr) (index : Nat := 0) : TermElabM Unit := do + match actual with + | .forallE name domain body info => + if let some (dependency, occurrence) := inputIndex name then + unless occurrence == index && dependency < dependencies.size && info == .default do + throwError "Invalid host conditional premise identity" + let premise ← mkConstWithFreshMVarLevels dependencies[dependency]!.theoremName.toName + unless ← isDefEq domain (← inferType premise) do + throwError "Host conditional premise has a different dependency type" + withLocalDecl name info domain fun input => + validateExpected dependencies taskType (body.instantiate1 input) (index + 1) + else + let expected ← withoutErrToSorry <| elabType taskType + synthesizeSyntheticMVarsNoPostponing + unless ← isDefEq actual (← instantiateMVars expected) do + throwError "Helper declaration has a different type or additional assumptions" + | _ => + let expected ← withoutErrToSorry <| elabType taskType + synthesizeSyntheticMVarsNoPostponing + unless ← isDefEq actual (← instantiateMVars expected) do + throwError "Helper declaration has a different type or additional assumptions" + +elab "theorem_os_conditional_expected% " theoremName:str taskType:str dependencies:str : term => do + let dependencies : Array Dependency ← match Json.parse dependencies.getString >>= fromJson? with + | .ok value => pure value + | .error message => throwError "Invalid host conditional dependency contracts: {message}" + let actual ← inferType (← mkConstWithFreshMVarLevels theoremName.getString.toName) + let levels ← getLevelNames + withLevelNames levels <| withoutModifyingEnv do + addDependencies dependencies + setLevelNames levels + validateExpected dependencies (← parseTerm taskType.getString) actual + levelMVarToParam (← instantiateMVars actual) + +end TheoremOS.Host.ConditionalProjection diff --git a/resources/workflow-output.json b/resources/workflow-output.json new file mode 100644 index 00000000..24edb174 --- /dev/null +++ b/resources/workflow-output.json @@ -0,0 +1,3 @@ +{ + "nativeDelivery": "Codex native JSON delivery: return only the complete JSON in your final response, matching the native output schema. In the role contract below, requirements to write or submit OUTPUT.json mean returning that complete final JSON response; file-writing, temporary-file and rename instructions do not apply to this session. Do not write OUTPUT.json or use a shell call to submit it. Other role requirements are unchanged. The host closes this session, validates the final response and saves OUTPUT.json; this response does not establish a proof." +} diff --git a/rust/cli/Cargo.toml b/rust/cli/Cargo.toml new file mode 100644 index 00000000..8b341f8f --- /dev/null +++ b/rust/cli/Cargo.toml @@ -0,0 +1,38 @@ +[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 new file mode 100644 index 00000000..38b14e3d --- /dev/null +++ b/rust/cli/src/auto_library.rs @@ -0,0 +1,145 @@ +//! Run native Auto build transitions and hand active sessions to the package's Bun host. +mod replay; +use crate::{build, edit}; +use serde_json::{Value, json}; +use std::{os::unix::process::CommandExt, path::Path, process::Command}; +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(&[ + "--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_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(()) +} + +pub fn run(args: &[String]) -> Result { + let root = build::root(None).map_err(|e| e.to_string())?; + if let Some(directory) = auto::cli::replay_directory(args, &root)? { + return replay::run(&root, &directory); + } + if let Some(directory) = auto::cli::session_directory(args, &root)? + && directory + .join("state.json") + .try_exists() + .map_err(|e| e.to_string())? + { + let lock = edit::Lease::acquire(&directory, "run.lock").map_err(|e| e.to_string())?; + if let Some(summary) = auto::build::terminal(&directory, &|file| { + build::verify_manifest(file, &root).map_err(|e| e.to_string()) + })? { + lock.held().map_err(|e| e.to_string())?; + println!("{}", serde_json::to_string_pretty(&summary).unwrap()); + return Ok(if summary["status"] == "exhausted" { + 2 + } else { + 0 + }); + } + } + let exe = std::env::current_exe().map_err(|e| e.to_string())?; + let mut cmd = Command::new("bun"); + if std::env::var_os("CODEX_HOME").is_none_or(|p| p.is_empty()) + && let Some(home) = std::env::home_dir() + { + cmd.env( + "CODEX_HOME", + home.join(".config/deepscientist/math-sol-codex"), + ); + } + let error = cmd + .arg(root.join("scripts/mathematics/autoLibrary.ts")) + .arg("__native") + .arg(exe) + .args(args) + .exec(); + Err(format!("Cannot start Auto library session host: {error}")) +} diff --git a/rust/cli/src/auto_library/replay.rs b/rust/cli/src/auto_library/replay.rs new file mode 100644 index 00000000..eeb3a239 --- /dev/null +++ b/rust/cli/src/auto_library/replay.rs @@ -0,0 +1,311 @@ +//! Run preset proof rounds in Rust and verify the archived Auto Library build. +use super::*; +use std::{path::PathBuf, 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 + }) + }; + 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, + observations: PathBuf, +} +impl Driver<'_> { + fn build(&self) -> Result<()> { + let status = Command::new("node") + .arg(self.root.join("out/main/math-solver.js")) + .arg("--theoremos-auto-replay") + .arg("build") + .arg(self.directory) + .arg(std::env::current_exe().map_err(|e| e.to_string())?) + .arg(&self.observations) + .stdout(std::io::stderr()) + .status() + .map_err(|e| format!("Cannot run the Auto library solver bundle with Node.js: {e}"))?; + if !status.success() { + return fail(&format!("build solver exited with {status}")); + } + Ok(()) + } + + 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) -> Result { + let build = self.directory.join("build"); + let observations = load(&self.observations)?; + 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_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 temp = tempfile::Builder::new() + .prefix(".preset-") + .tempdir_in(directory) + .map_err(|e| e.to_string())?; + let driver = Driver { + root, + directory, + manifest, + observations: temp.path().join("observations.json"), + }; + driver.build()?; + let report = driver.report()?; + println!("{}", serde_json::to_string_pretty(&report).unwrap()); + Ok(0) +} diff --git a/rust/cli/src/batch.rs b/rust/cli/src/batch.rs new file mode 100644 index 00000000..a3b134c9 --- /dev/null +++ b/rust/cli/src/batch.rs @@ -0,0 +1,552 @@ +//! 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 new file mode 100644 index 00000000..d15e94ed --- /dev/null +++ b/rust/cli/src/bin/theorem-os-agent.rs @@ -0,0 +1,39 @@ +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 new file mode 100644 index 00000000..aef0251d --- /dev/null +++ b/rust/cli/src/bin/web-funnel.rs @@ -0,0 +1,323 @@ +//! 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 new file mode 100644 index 00000000..f2001a6e --- /dev/null +++ b/rust/cli/src/bootstrap.rs @@ -0,0 +1,45 @@ +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] + +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. +Print the preparation receipt as JSON."; + +pub fn run(args: &[String]) -> Result<(), String> { + let flags = flags( + args, + &[ + "source", + "task-file", + "workspace", + "environment", + "library-pack", + ], + )?; + 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("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 new file mode 100644 index 00000000..cbdd27ce --- /dev/null +++ b/rust/cli/src/build.rs @@ -0,0 +1,555 @@ +//! 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 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}")); + } + 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 new file mode 100644 index 00000000..3650e9a2 --- /dev/null +++ b/rust/cli/src/check_lean.rs @@ -0,0 +1,422 @@ +//! 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 new file mode 100644 index 00000000..0a122aac --- /dev/null +++ b/rust/cli/src/checkpoint.rs @@ -0,0 +1,176 @@ +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 new file mode 100644 index 00000000..9ef8ce8a --- /dev/null +++ b/rust/cli/src/comparison/experiment.rs @@ -0,0 +1,176 @@ +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 new file mode 100644 index 00000000..8c360f73 --- /dev/null +++ b/rust/cli/src/comparison/freshness.rs @@ -0,0 +1,84 @@ +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 new file mode 100644 index 00000000..f1d9d896 --- /dev/null +++ b/rust/cli/src/comparison/funnel.rs @@ -0,0 +1,327 @@ +//! 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 new file mode 100644 index 00000000..a4b25dfb --- /dev/null +++ b/rust/cli/src/comparison/knowledge.rs @@ -0,0 +1,70 @@ +//! 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 new file mode 100644 index 00000000..7e3a62db --- /dev/null +++ b/rust/cli/src/comparison/mod.rs @@ -0,0 +1,246 @@ +//! 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 new file mode 100644 index 00000000..cda12931 --- /dev/null +++ b/rust/cli/src/comparison/ordinary.rs @@ -0,0 +1,478 @@ +//! 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 new file mode 100644 index 00000000..b566c090 --- /dev/null +++ b/rust/cli/src/comparison/policy.rs @@ -0,0 +1,322 @@ +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 new file mode 100644 index 00000000..62fd0f28 --- /dev/null +++ b/rust/cli/src/comparison/providers.json @@ -0,0 +1,39 @@ +{ + "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 new file mode 100644 index 00000000..e42e29f6 --- /dev/null +++ b/rust/cli/src/comparison/sample.rs @@ -0,0 +1,112 @@ +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 new file mode 100644 index 00000000..95dbb383 --- /dev/null +++ b/rust/cli/src/comparison/sample/manifest.rs @@ -0,0 +1,157 @@ +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 new file mode 100644 index 00000000..9069c81c --- /dev/null +++ b/rust/cli/src/component/contract.rs @@ -0,0 +1,131 @@ +// 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 new file mode 100644 index 00000000..bf3ef62e --- /dev/null +++ b/rust/cli/src/component/mod.rs @@ -0,0 +1,134 @@ +//! 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 new file mode 100644 index 00000000..03638479 --- /dev/null +++ b/rust/cli/src/component/template.rs @@ -0,0 +1,10 @@ +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 new file mode 100644 index 00000000..98a41052 --- /dev/null +++ b/rust/cli/src/continuation/mod.rs @@ -0,0 +1,155 @@ +//! 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 new file mode 100644 index 00000000..805f901d --- /dev/null +++ b/rust/cli/src/continuation/search.rs @@ -0,0 +1,394 @@ +//! 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::