From a1a443d9387eed7c0b761bb7d5901d57484ddd88 Mon Sep 17 00:00:00 2001 From: Zhenhao Liu <176368005+LikC1606@users.noreply.github.com> Date: Sat, 28 Nov 2026 13:04:42 +0800 Subject: [PATCH 1/3] Ship the pinned Code Mode host with the native worker --- apps/web/Dockerfile | 3 +- scripts/build-codex-backend.sh | 60 +++++++++--- scripts/codex-backend/README.md | 27 +++--- scripts/codex-backend/check-capabilities.py | 100 ++++++++++++++++++-- scripts/codex-backend/git-fetch-pinned.py | 11 ++- scripts/test-codex-backend-delivery.ts | 8 +- scripts/test-codex-backend.ts | 8 +- 7 files changed, 176 insertions(+), 41 deletions(-) diff --git a/apps/web/Dockerfile b/apps/web/Dockerfile index af113e7b..a4167bf0 100644 --- a/apps/web/Dockerfile +++ b/apps/web/Dockerfile @@ -5,7 +5,7 @@ FROM docker:29-cli AS docker-cli # require a newer glibc even when the Codex source and architecture match. FROM rust:1.99.1-bookworm AS codex-backend RUN apt-get update && apt-get install -y --no-install-recommends \ - python3 cmake pkg-config libssl-dev libcap-dev libasound2-dev \ + python3 curl cmake pkg-config libssl-dev libcap-dev libasound2-dev \ && rm -rf /var/lib/apt/lists/* WORKDIR /build COPY scripts/build-codex-backend.sh scripts/build-codex-backend.sh @@ -105,6 +105,7 @@ ARG THEOREMOS_SOURCE_COMMIT=unknown LABEL org.opencontainers.image.revision=$THEOREMOS_SOURCE_COMMIT ENV THEOREMOS_SOURCE_COMMIT=$THEOREMOS_SOURCE_COMMIT COPY --from=codex-backend /build/artifacts/bin/codex /opt/theoremos-codex-backend/codex +COPY --from=codex-backend /build/artifacts/bin/codex-code-mode-host /opt/theoremos-codex-backend/codex-code-mode-host ENV THEOREMOS_CODEX_BACKEND_EXECUTABLE=/opt/theoremos-codex-backend/codex USER 10001:10001 RUN timeout 30s python3 scripts/codex-backend/check-capabilities.py "$THEOREMOS_CODEX_BACKEND_EXECUTABLE" diff --git a/scripts/build-codex-backend.sh b/scripts/build-codex-backend.sh index 2c008c90..df84cf99 100755 --- a/scripts/build-codex-backend.sh +++ b/scripts/build-codex-backend.sh @@ -10,8 +10,8 @@ usage() { Usage: scripts/build-codex-backend.sh --source DIR --downloads DIR --output DIR [--jobs N] [--host-tools DIR] [--prepare-only] Fetch the pinned official Codex release, apply the checked-in build patches, -and build codex-cli with its locked dependencies and an explicitly selected Rust. -All target files, logs, the executable and its provenance stay under --output. +and build Codex and its Code Mode host with locked dependencies and pinned Rust. +All target files, logs, both executables and their provenance stay under --output. --prepare-only verifies the upstream identity without applying the patch. --host-tools uses an extracted Debian sysroot for build-only native dependencies. No global Codex profile or default Rust toolchain is changed. @@ -61,6 +61,7 @@ lock_patch_digest=$(pin lockPatchSha256) patch_file=$script_dir/codex-backend/$(pin patch) package=$(pin package) binary=$(pin binary) +code_mode_host=codex-code-mode-host profile=$(pin profile) mkdir -p -- "$downloads_dir" "$output_dir" "$(dirname -- "$source_dir")" @@ -108,14 +109,15 @@ if ! git -C "$source_dir" apply --reverse --check "$patch_file" 2>/dev/null; the fi # Build precisely the reviewable patch. Extra edits are preserved and rejected, # so re-running this script never resets a developer's source worktree. -git -C "$source_dir" diff --binary --no-ext-diff HEAD -- . ':(exclude)codex-rs/Cargo.lock' > "$output_dir/agent-control-source.patch" -git -C "$source_dir" diff --binary --no-ext-diff HEAD -- codex-rs/Cargo.lock > "$output_dir/derived-lock-source.patch" +# Match the checked-in index width even when a shallow clone uses shorter IDs. +git -C "$source_dir" diff --binary --abbrev=8 --no-ext-diff HEAD -- . ':(exclude)codex-rs/Cargo.lock' > "$output_dir/agent-control-source.patch" +git -C "$source_dir" diff --binary --abbrev=8 --no-ext-diff HEAD -- codex-rs/Cargo.lock > "$output_dir/derived-lock-source.patch" if ! cmp -s "$patch_file" "$output_dir/agent-control-source.patch" || ! cmp -s "$lock_patch_file" "$output_dir/derived-lock-source.patch" || [[ -n $(git -C "$source_dir" ls-files --others --exclude-standard) ]]; then echo 'Source worktree differs from the checked-in build patches.' >&2; exit 1 fi -git -C "$source_dir" diff --binary --no-ext-diff HEAD > "$output_dir/source.patch" +git -C "$source_dir" diff --binary --abbrev=8 --no-ext-diff HEAD > "$output_dir/source.patch" export CARGO_TARGET_DIR=$output_dir/target export CARGO_PROFILE_DEV_DEBUG=$(pin devDebug) @@ -169,24 +171,59 @@ export THEOREMOS_BUILD_SUBMODULE_PINS=$output_dir/submodule-pins.json ln -sfn -- "$script_dir/codex-backend/git-fetch-pinned.py" "$build_tools/git" export PATH="$build_tools:$PATH" export CARGO_NET_GIT_FETCH_WITH_CLI=true + +# Build the Code Mode host with the same V8 release pair as upstream Cargo CI. +# The crate's default download site does not publish this pair. +v8_version=$(python3 "$source_dir/.github/scripts/rusty_v8_bazel.py" resolved-v8-crate-version) +rust_target=$(rustup run "$toolchain" rustc -vV | awk '$1 == "host:" {print $2}') +v8_dir=$downloads_dir/codex-rusty-v8-$v8_version +v8_checksums=$source_dir/third_party/v8/rusty_v8_${v8_version//./_}.sha256 +v8_archive=librusty_v8_ptrcomp_sandbox_release_$rust_target.a.gz +v8_binding=src_binding_ptrcomp_sandbox_release_$rust_target.rs +mkdir -p -- "$v8_dir" +for artifact in "$v8_archive" "$v8_binding"; do + expected=$(awk -v name="$artifact" '$2 == name {print $1}' "$v8_checksums") + if [[ ! $expected =~ ^[0-9a-f]{64}$ ]]; then + echo "No pinned V8 asset: $artifact" >&2; exit 1 + fi + if [[ ! -f $v8_dir/$artifact ]] || ! sha256sum --check --status <<< "$expected $v8_dir/$artifact"; then + download_file=$(mktemp "$v8_dir/$artifact.XXXXXX") + if ! curl --fail --silent --show-error --location --retry 3 \ + "https://github.com/openai/codex/releases/download/rusty-v8-v$v8_version/$artifact" --output "$download_file" || + ! sha256sum --check --status <<< "$expected $download_file"; then + rm -f -- "$download_file" + echo "Could not fetch the pinned V8 asset: $artifact" >&2; exit 1 + fi + mv -f -- "$download_file" "$v8_dir/$artifact" + fi +done +export RUSTY_V8_ARCHIVE=$v8_dir/$v8_archive +export RUSTY_V8_SRC_BINDING_PATH=$v8_dir/$v8_binding + build_log=$output_dir/build.log -echo "Building $package/$binary; log: $build_log" +echo "Building $package/$binary and $code_mode_host; log: $build_log" if ! (cd -- "$source_dir/codex-rs" && rustup run "$toolchain" cargo build --locked \ - --profile "$profile" -p "$package" --bin "$binary" --jobs "$jobs") > "$build_log" 2>&1; then + --profile "$profile" -p "$package" --bin "$binary" \ + -p "$code_mode_host" --bin "$code_mode_host" --jobs "$jobs") > "$build_log" 2>&1; then tail -n 60 "$build_log" >&2 exit 1 fi mkdir -p -- "$output_dir/bin" -install -m 755 "$CARGO_TARGET_DIR/debug/$binary" "$output_dir/bin/$binary.new" -mv -f -- "$output_dir/bin/$binary.new" "$output_dir/bin/$binary" +# Codex resolves its companion next to the real executable, including when +# started through the runtime symlink. +for artifact in "$code_mode_host" "$binary"; do + install -m 755 "$CARGO_TARGET_DIR/debug/$artifact" "$output_dir/bin/$artifact.new" + mv -f -- "$output_dir/bin/$artifact.new" "$output_dir/bin/$artifact" +done runtime_link=$script_dir/../out/codex-backend/codex mkdir -p -- "$(dirname -- "$runtime_link")" ln -sfn -- "$output_dir/bin/$binary" "$runtime_link" -python3 - "$pin_file" "$source_dir" "$output_dir" "$patch_file" "$jobs" "$runtime_link" "$host_tools" <<'PY' +python3 - "$pin_file" "$source_dir" "$output_dir" "$patch_file" "$jobs" "$runtime_link" "$host_tools" "$code_mode_host" <<'PY' import datetime, hashlib, json, pathlib, subprocess, sys -pin_file, source, output, patch_file, jobs, runtime_link, host_tools = sys.argv[1:] +pin_file, source, output, patch_file, jobs, runtime_link, host_tools, code_mode_host = sys.argv[1:] pin = json.loads(pathlib.Path(pin_file).read_text()) artifact = pathlib.Path(output, "bin", pin["binary"]) +companion = artifact.with_name(code_mode_host) digest = lambda file: hashlib.file_digest(pathlib.Path(file).open("rb"), "sha256").hexdigest() version = lambda command: subprocess.check_output(["rustup", "run", pin["toolchain"], *command], text=True).strip() record = { @@ -198,6 +235,7 @@ record = { "lockPatchSha256": digest(pathlib.Path(pin_file).parent / pin["lockPatch"]), "sourcePatchSha256": digest(pathlib.Path(output, "source.patch")), "executable": str(artifact), "executableSha256": digest(artifact), + "codeModeHost": str(companion), "codeModeHostSha256": digest(companion), "rustc": version(["rustc", "--version", "--verbose"]), "cargo": version(["cargo", "--version"]), "jobs": int(jobs), "targetDirectory": str(pathlib.Path(output, "target")), "log": str(pathlib.Path(output, "build.log")), diff --git a/scripts/codex-backend/README.md b/scripts/codex-backend/README.md index 3de6bf12..17b47018 100644 --- a/scripts/codex-backend/README.md +++ b/scripts/codex-backend/README.md @@ -45,11 +45,12 @@ and `libssl3t64` version `3.0.13-0ubuntu3.16`. Large asynchronous core tests require `RUST_MIN_STACK=8388608`, matching the upstream Bazel test configuration. Set it only on the test subprocess. -All Cargo targets, logs and binaries stay under `--output`. On success, -`backend-build.json` records the source, patch, lockfile and executable digests; -`out/codex-backend/codex` points to the built executable. Existing sessions are -not restarted. Source edits beyond the checked-in patches are preserved and -rejected, so freeze the adapter patch before running a final build. +All Cargo targets, logs and binaries stay under `--output`. The build installs +`codex` and `codex-code-mode-host` together in `bin/` and records both digests in +`backend-build.json`. Keep the pair together when moving the backend. The local +`out/codex-backend/codex` link points to the built CLI. Existing sessions are not +restarted. Source edits beyond the checked-in patches are preserved and rejected, +so freeze the adapter patch before running a final build. New team runs pin the executable's real path and digest and record `agentTeam.transport: native-agent-control`. Startup failures are reported @@ -80,19 +81,19 @@ returns a tool error and Lead can retry with `fork_turns: "none"`. Pass profile, including metered requests before and after Lead cold resume. The built runtime link installs this backend for new local CLI team runs. -The Web worker Dockerfile builds the same pinned source on Debian Bookworm -and installs a separate binary at `/opt/theoremos-codex-backend/codex`. -Ordinary runs keep the stock Codex binary. The worker build probes the native -app-server's capabilities as the worker user before labeling the image +The Web worker Dockerfile builds the same pinned source on Debian Bookworm and +installs both executables in `/opt/theoremos-codex-backend/`. Ordinary runs keep +the stock Codex binary. The worker build probes AgentControl and executes a Code +Mode call as the worker user with fixed loopback responses before labeling the image `org.theoremos.native-agent-control=v1`. The Web service also checks `org.theoremos.native-team-workflow=v1`, which identifies support for native team scheduling and initial route approval. It launches the image by its verified ID. Rebuild both Web and worker images to roll out this workflow. -Cargo resolves V8 host manifests even though the CLI does not link that runtime. -The build-local Git helper fetches the exact locked submodule commits without -downloading unrelated Chromium branch histories. Their official gitlink pins -are recorded in `submodule-pins.json`. +The Code Mode host uses the V8 archive and Rust bindings from the matching Codex +release. The build verifies them against the pinned checkout's checksums. The +build-local Git helper fetches the exact locked submodule commits and records +their official gitlink pins in `submodule-pins.json`. If downloads fail with `Proxy CONNECT aborted`, check the configured proxy. A confirmed direct connection can be used for this build by invoking the script diff --git a/scripts/codex-backend/check-capabilities.py b/scripts/codex-backend/check-capabilities.py index 9c4f20db..86e83043 100644 --- a/scripts/codex-backend/check-capabilities.py +++ b/scripts/codex-backend/check-capabilities.py @@ -1,18 +1,63 @@ -"""Probe the installed app-server without opening a thread or using a provider.""" +"""Probe AgentControl and Code Mode against a fixed loopback Responses fixture.""" +from http.server import BaseHTTPRequestHandler, HTTPServer import json import os +from pathlib import Path import subprocess import sys import tempfile +from threading import Thread -def check(executable, profile): +class ProbeResponses(BaseHTTPRequestHandler): + calls = 0 + tool_output = None + + def do_POST(self): + if self.path != "/v1/responses": + self.send_error(404) + return + body = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) + fixture = type(self) + fixture.calls += 1 + if fixture.calls == 1: + item = {"type": "custom_tool_call", "call_id": "probe-exec", "name": "exec", + "input": "text('theoremos-' + (17 + 25));"} + elif fixture.calls == 2: + fixture.tool_output = next( + (item["output"] for item in body["input"] + if item["type"] == "custom_tool_call_output" and item["call_id"] == "probe-exec"), + None, + ) + item = {"type": "message", "id": "probe-done", "role": "assistant", + "content": [{"type": "output_text", "text": "Probe completed."}]} + else: + self.send_error(500, "unexpected additional Responses request") + return + response = {"id": f"probe-{fixture.calls}"} + events = [ + {"type": "response.created", "response": response}, + {"type": "response.output_item.done", "item": item}, + {"type": "response.completed", "response": response}, + ] + payload = "".join(f"event: {event['type']}\ndata: {json.dumps(event)}\n\n" + for event in events).encode() + self.send_response(200) + self.send_header("Content-Type", "text/event-stream") + self.send_header("Content-Length", str(len(payload))) + self.end_headers() + self.wfile.write(payload) + + def log_message(self, *_): + pass + + +def check_agent_control(executable, profile, environment): with subprocess.Popen( [executable, "app-server", "--listen", "stdio://"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True, - cwd=profile, env={"HOME": profile, "CODEX_HOME": profile, "PATH": os.environ["PATH"], - "THEOREMOS_HOST_AGENT_CONTROL": "1"}, + cwd=profile, env={**environment, "THEOREMOS_HOST_AGENT_CONTROL": "1"}, ) as server: def send(message): server.stdin.write(json.dumps(message) + "\n") @@ -36,11 +81,52 @@ def request(request_id, method, params): if (result.get("version") != 1 or result.get("backend") != "theoremos-host" or result.get("nativeTools") is not True or result.get("isolatedChildBootstrap") is not True): raise RuntimeError(f"incompatible AgentControl backend: {result}") - print(json.dumps(result)) + return result finally: server.terminate() +def check_code_mode(executable, profile, environment): + with HTTPServer(("127.0.0.1", 0), ProbeResponses) as responses: + base_url = f"http://127.0.0.1:{responses.server_port}" + Path(profile, "config.toml").write_text(f"""model = "theoremos-probe" +model_provider = "fixture" +approval_policy = "never" +sandbox_mode = "read-only" +chatgpt_base_url = "{base_url}" +[analytics] +enabled = false +[features] +code_mode_only = true +code_mode_host = true +[model_providers.fixture] +name = "Code Mode probe" +base_url = "{base_url}/v1" +wire_api = "responses" +supports_websockets = false +request_max_retries = 0 +stream_max_retries = 0 +""", encoding="utf-8") + serving = Thread(target=responses.serve_forever, daemon=True) + serving.start() + try: + run = subprocess.run( + [executable, "exec", "--ephemeral", "--skip-git-repo-check", "Run the Code Mode probe."], + cwd=profile, env=environment, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=15, + ) + if run.returncode != 0: + raise RuntimeError(f"Code Mode probe failed: {run.stderr.strip()}") + if "theoremos-42" not in json.dumps(ProbeResponses.tool_output): + raise RuntimeError(f"Code Mode probe returned: {ProbeResponses.tool_output}") + finally: + responses.shutdown() + serving.join() + + if __name__ == "__main__": - with tempfile.TemporaryDirectory() as temporary: - check(sys.argv[1], temporary) + executable = str(Path(sys.argv[1]).resolve()) + with tempfile.TemporaryDirectory() as profile: + environment = {"HOME": profile, "CODEX_HOME": profile, "PATH": os.environ["PATH"]} + capabilities = check_agent_control(executable, profile, environment) + check_code_mode(executable, profile, environment) + print(json.dumps({**capabilities, "codeModeProbe": "passed"})) diff --git a/scripts/codex-backend/git-fetch-pinned.py b/scripts/codex-backend/git-fetch-pinned.py index 575566fd..4b0ab858 100755 --- a/scripts/codex-backend/git-fetch-pinned.py +++ b/scripts/codex-backend/git-fetch-pinned.py @@ -6,12 +6,17 @@ git = os.environ["THEOREMOS_BUILD_REAL_GIT"] arguments = sys.argv[1:] -if arguments and arguments[0] == "fetch": +command = 0 +# Cargo passes Git configuration options before the fetch subcommand. +while command + 1 < len(arguments) and arguments[command] == "-c": + command += 2 +if arguments[command:command + 1] == ["fetch"]: with open(os.environ["THEOREMOS_BUILD_SUBMODULE_PINS"], encoding="utf-8") as stream: pins = json.load(stream) - for argument in arguments[1:]: + for argument in arguments[command + 1:]: if argument in pins: revision = pins[argument] print(f"Fetching pinned submodule {argument} at {revision}", file=sys.stderr) - os.execv(git, [git, "fetch", "--force", "--update-head-ok", "--depth", "1", argument, revision]) + os.execv(git, [git, *arguments[:command], "fetch", "--force", "--update-head-ok", + "--depth", "1", argument, revision]) os.execv(git, [git, *arguments]) diff --git a/scripts/test-codex-backend-delivery.ts b/scripts/test-codex-backend-delivery.ts index e791ea52..e2397aeb 100644 --- a/scripts/test-codex-backend-delivery.ts +++ b/scripts/test-codex-backend-delivery.ts @@ -261,10 +261,12 @@ export async function verifyNativeProofDelivery(input: { repository: string; exe const profile = path.join(directory, 'profile'); if (input.webProvider) prepareWebProviderProfile(profile, webRequest); else prepareSub2apiProfile(profile, state.model, state.effort); - const toolchain = path.join(os.homedir(), '.elan/toolchains/leanprover--lean4---v4.33.0'); + const userHome = os.homedir(); + const elanHome = process.env.ELAN_HOME || path.join(userHome, '.elan'); + const toolchain = path.join(elanHome, 'toolchains/leanprover--lean4---v4.33.0'); assert.ok(fs.existsSync(path.join(toolchain, 'bin/lean')), 'Native delivery acceptance requires Lean 4.33.0.'); - const environment = { PATH: `${toolchain}/bin:${path.dirname(process.execPath)}:/usr/bin:/bin`, - ELAN_HOME: path.join(os.homedir(), '.elan'), LEAN_PATH: '', LEAN_SYSROOT: '', NO_PROXY: '127.0.0.1,localhost', + const environment = { HOME: userHome, PATH: `${toolchain}/bin:${path.dirname(process.execPath)}:/usr/bin:/bin`, + ELAN_HOME: elanHome, LEAN_PATH: '', LEAN_SYSROOT: '', NO_PROXY: '127.0.0.1,localhost', ...(!input.webProvider && { SUB2API_WESTLAKE_API_KEY: apiKey }), DEEPSCIENTIST_MATH_SANDBOX_BACKEND: 'bwrap', DEEPSCIENTIST_MATH_ENV_FILE: path.join(directory, 'missing.env') }; const modules = input.webProvider ? webSolverModules(webRequest, { sink: action => webActions.push(action), diff --git a/scripts/test-codex-backend.ts b/scripts/test-codex-backend.ts index 1ddc128c..b3102edd 100644 --- a/scripts/test-codex-backend.ts +++ b/scripts/test-codex-backend.ts @@ -341,9 +341,11 @@ try { fs.writeFileSync(catalogFile, JSON.stringify(catalog)); } fs.chmodSync(configFile, 0o600); fs.writeFileSync(configFile, stringify(config)); - const toolchain = path.join(os.homedir(), '.elan/toolchains/leanprover--lean4---v4.33.0'); - const environment = { PATH: `${toolchain}/bin:${path.dirname(process.execPath)}:/usr/bin:/bin`, - ELAN_HOME: path.join(os.homedir(), '.elan'), LEAN_PATH: '', LEAN_SYSROOT: '', NO_PROXY: '127.0.0.1,localhost', + const userHome = os.homedir(); + const elanHome = process.env.ELAN_HOME || path.join(userHome, '.elan'); + const toolchain = path.join(elanHome, 'toolchains/leanprover--lean4---v4.33.0'); + const environment = { HOME: userHome, PATH: `${toolchain}/bin:${path.dirname(process.execPath)}:/usr/bin:/bin`, + ELAN_HOME: elanHome, LEAN_PATH: '', LEAN_SYSROOT: '', NO_PROXY: '127.0.0.1,localhost', OFFLINE_NATIVE_BACKEND_KEY: 'synthetic-offline-key', DEEPSCIENTIST_MATH_SANDBOX_BACKEND: 'bwrap', DEEPSCIENTIST_MATH_ENV_FILE: path.join(directory, 'missing.env') }; const save = () => { From 7cfdc202008624681adfe74df06d1787343a9793 Mon Sep 17 00:00:00 2001 From: Zhenhao Liu <176368005+LikC1606@users.noreply.github.com> Date: Sat, 28 Nov 2026 13:04:42 +0800 Subject: [PATCH 2/3] Reuse frozen proof sources across continuation helper checks --- src/solver/declarationArtifacts.ts | 27 +++++++++++++++------------ src/solver/singleContinuationSeed.ts | 7 ++++--- tests/singleContinuationSeed.test.ts | 27 ++++++++++++++++++++------- 3 files changed, 39 insertions(+), 22 deletions(-) diff --git a/src/solver/declarationArtifacts.ts b/src/solver/declarationArtifacts.ts index a2787a63..c8d9e42b 100644 --- a/src/solver/declarationArtifacts.ts +++ b/src/solver/declarationArtifacts.ts @@ -256,20 +256,26 @@ type TeamDeclarationCheckInput = DeclarationCheckInput & { /** Only for host-selected declarations whose signature comes from independently checked source. */ inferredExpectedTypes?: ReadonlySet; }; +type StoppedDeclarationCheckInput = DeclarationCheckInput & { assertWriterStopped: () => void }; +type DeclarationCheckSnapshot = { project?: ReturnType; sourceDigest?: string }; -/** The caller must hold its writer-stop guarantee until this operation and persistence finish. */ -export async function checkDeclarationArtifacts(input: DeclarationCheckInput & { - assertWriterStopped: () => void; -}): Promise { +export async function checkDeclarationArtifacts(input: StoppedDeclarationCheckInput): Promise { + return createDeclarationArtifactChecker(input)(input.declarations); +} + +/** Reuse source preparation for sequential checks of one stopped writer's fixed commit. */ +export function createDeclarationArtifactChecker(input: Omit) { const { state, worktree, commit, signal } = input, { problem } = state; const identity = canonicalMathJson(identityOf(state)); + const snapshot: DeclarationCheckSnapshot = {}; const assertFrozenSource = () => { signal.throwIfAborted(); input.assertWriterStopped(); assertSolverSources(problem, worktree); if (canonicalMathJson(identityOf(state)) !== identity) return fail('run_identity_changed'); if (git(worktree, ['rev-parse', 'HEAD']) !== commit || git(worktree, ['status', '--porcelain', '--', ...problem.ownedFiles.map(file => path.join(problem.projectRelative, file))])) return fail('source_changed'); }; - return checkArtifacts({ ...input, assertFrozenSource }, declarationSubmissionSchema, false); + return (declarations: DeclarationSubmission['declarations']) => + checkArtifacts({ ...input, declarations, assertFrozenSource }, declarationSubmissionSchema, false, snapshot); } /** Host deliveries can include checked peer declarations in addition to a bounded member submission. */ @@ -277,7 +283,8 @@ export async function checkTeamDeclarationArtifacts(input: TeamDeclarationCheckI return checkArtifacts(input, teamDeclarationSubmissionSchema, true); } -async function checkArtifacts(input: TeamDeclarationCheckInput, schema: typeof declarationSubmissionSchema, allowAuxiliaryDefinitions: boolean) { +async function checkArtifacts(input: TeamDeclarationCheckInput, schema: typeof declarationSubmissionSchema, + allowAuxiliaryDefinitions: boolean, snapshot: DeclarationCheckSnapshot = {}) { const declarations = parseDeclarationSubmission({ declarations: input.declarations }, schema).declarations; const { state, worktree, commit, signal, assertFrozenSource } = input, { problem } = state; commitHash.parse(commit); @@ -285,10 +292,6 @@ async function checkArtifacts(input: TeamDeclarationCheckInput, schema: typeof d if (new Set(declarations.map(item => `${item.file}\0${item.name}`)).size !== declarations.length) return submissionFail('duplicate_declaration'); const environment = proofReuseEnvironment(path.join(worktree, problem.projectRelative), input.env); const records: DeclarationArtifact[] = []; - // Share the frozen snapshot across declarations. Each projection is still - // written to its own checkout and checked independently. - let project: ReturnType | undefined; - let sourceDigest: string | undefined; for (const declaration of declarations) { assertFrozenSource(); if (!problem.ownedFiles.includes(declaration.file)) return submissionFail('outside_ownership'); @@ -314,7 +317,7 @@ async function checkArtifacts(input: TeamDeclarationCheckInput, schema: typeof d theoremName: declaration.name, type, dependsOn: [], revision: 0 }; let checkedCommit = commit; if (!checkHelperInDraft) { - const projector = project ??= createTaskSourceProjector(problem, worktree, commit, { compact: true }); + const projector = snapshot.project ??= createTaskSourceProjector(problem, worktree, commit, { compact: true }); const sources = submissionContent(() => projector(task, []), ['math_task_type_invalid', 'math_task_missing_declaration', 'math_task_ambiguous_declaration', 'math_task_requires_theorem', 'math_task_requires_definition', 'math_task_helper_is_original_declaration']); for (const [file, text] of sources) fs.writeFileSync(path.join(checkout, problem.projectRelative, file), text); @@ -335,7 +338,7 @@ async function checkArtifacts(input: TeamDeclarationCheckInput, schema: typeof d const references = result.verification.results[0]?.declarationReferences; const record: DeclarationArtifact = { schema: 'theorem-os.declaration-artifact.v1', id: '', ...identityOf(state), declaration, declarationHash, declarationDigest, - proof: { commit, sourceDigest: sourceDigest ??= ownedSourceDigest(problem, worktree, commit), + proof: { commit, sourceDigest: snapshot.sourceDigest ??= ownedSourceDigest(problem, worktree, commit), passed: true, verification: result.verification }, ...(references ? { references: captureProofReferences(problem, checkout, commit, { file: declaration.file, name: declaration.name }, references, state.environmentDigest) } : {}) }; diff --git a/src/solver/singleContinuationSeed.ts b/src/solver/singleContinuationSeed.ts index 03af849d..a0856a22 100644 --- a/src/solver/singleContinuationSeed.ts +++ b/src/solver/singleContinuationSeed.ts @@ -15,7 +15,7 @@ import { readAgentTeamContinuationNote, type AgentTeamResearchArtifactReference, import { freezeContinuationInput, MAX_CONTINUATION_ATTACHMENT_BYTES, readContinuationContents, type ContinuationManifest } from './continuationInput'; import { captureContinuationTaskDrafts, continuationOwnershipExtension, continuationSourcePolicyDigest, type ContinuationSeedReport, type ContinuationSeedOptions } from './continuationSeed'; -import { checkDeclarationArtifacts, readDeclarationArtifacts, writeDeclarationArtifacts } from './declarationArtifacts'; +import { createDeclarationArtifactChecker, readDeclarationArtifacts, writeDeclarationArtifacts } from './declarationArtifacts'; import { readRunInspection } from './inspection'; import { assertSolverSources, committedSource, commitSolverSources, git, pinSolverResearchSkill, readSolverProblem, withSolverWorktree } from './problem'; import { isDefinitionTask, type TaskRecord } from './tasks'; @@ -317,12 +317,13 @@ export async function seedSingleSolverContinuation(options: ContinuationSeedOpti const env = proofEnvironment ? { ...staticEnv, [MATH_PROOF_ENVIRONMENT_ENV]: proofEnvironment.environmentValue } : staticEnv; report.stage = 'checking'; saveReport(); const assertWriterStopped = () => { lease.assertHeld(); assertPrepared(state, stateFile, true); }; + const checkDeclarations = createDeclarationArtifactChecker({ state, worktree: state.worktree, + commit: canonical, env, signal: lease.signal, timeoutMs, assertWriterStopped }); for (const declaration of source.declarations) { lease.signal.throwIfAborted(); const { id, ...submission } = declaration; try { - const artifacts = await checkDeclarationArtifacts({ state, worktree: state.worktree, commit: canonical, - declarations: [submission], env, signal: lease.signal, timeoutMs, assertWriterStopped }); + const artifacts = await checkDeclarations([submission]); assertWriterStopped(); writeDeclarationArtifacts(directory, state, artifacts); report.checked.push(id); report.evidence = 'fresh-helper-receipts'; emit('continuation_seed_declaration_checked', { id, name: declaration.name, passed: true }); diff --git a/tests/singleContinuationSeed.test.ts b/tests/singleContinuationSeed.test.ts index 7e96d8a9..92e2b02d 100644 --- a/tests/singleContinuationSeed.test.ts +++ b/tests/singleContinuationSeed.test.ts @@ -106,16 +106,29 @@ describe('single researcher continuation', () => { expect(fs.readFileSync(path.join(f.peer, 'RESEARCH.md'))).toEqual(oldNotes); }); - it('keeps a rejected helper advisory with its exact diagnostic, without discarding the source', async () => { + it('keeps a rejected helper advisory and checks the next helper against the same frozen source', async () => { const f = fixture(); - host.verify.mockImplementation((request: MathematicsVerifierBatchRequest) => failedBatch(receiptBatch(request, + const file = path.join(f.sourceWorktree, f.problem.projectRelative, 'Submission.lean'); + const source = f.sources.replace('lemma saved_helper', 'lemma rejected_helper : True := by trivial\nlemma saved_helper'); + fs.writeFileSync(file, source); + const canonical = commitSolverSources(f.problem, f.sourceWorktree); + const cooperation = f.archived.cooperation!; + cooperation.canonicalCommit = canonical; + const rejected = { ...f.helper, id: 'rejected', theoremName: 'Tutorial.rejected_helper' }; + cooperation.tasks.unshift({ ...cooperation.tasks[0], task: rejected, + integratedCheck: { ...cooperation.tasks[0].integratedCheck!, commit: canonical, taskDigest: taskVersion(rejected) } }); + writeSolverRunState(f.sourceStateFile, f.archived); + host.verify.mockImplementationOnce((request: MathematicsVerifierBatchRequest) => failedBatch(receiptBatch(request, { sessionId: 'failed-check', receiptId: () => 'failed-receipt' }), { stdoutPreview: () => 'not proved' })); const report = await f.seed(); - expect(report).toMatchObject({ stage: 'complete', checked: [], failed: ['saved'], - evidence: 'advisory-sources-require-recheck', declarationFailures: [{ id: 'saved', name: 'Tutorial.saved_helper', - error: expect.stringContaining('math_declaration_artifact_check_failed') }] }); - expect(readDeclarationArtifacts(f.directory, readSolverRunState(f.stateFile))).toEqual([]); - expect(fs.readFileSync(path.join(f.worktree, f.problem.projectRelative, 'Submission.lean'), 'utf8')).toBe(f.sources); + expect(report).toMatchObject({ stage: 'complete', checked: ['saved'], failed: ['rejected'], + evidence: 'fresh-helper-receipts', declarationFailures: [{ id: 'rejected', name: 'Tutorial.rejected_helper', + error: expect.stringContaining('not proved') }] }); + const artifacts = readDeclarationArtifacts(f.directory, readSolverRunState(f.stateFile)); + expect(artifacts.map(item => item.proof.verification.results[0].receiptId)).toEqual(['fresh-Tutorial.saved_helper']); + expect(host.verify.mock.calls.map(([request]) => request.items.map(item => item.theoremName))) + .toEqual([['Tutorial.rejected_helper'], ['Tutorial.saved_helper']]); + expect(fs.readFileSync(path.join(f.worktree, f.problem.projectRelative, 'Submission.lean'), 'utf8')).toBe(source); }); it('does not reinterpret a historical conditional helper as an unconditional candidate', async () => { From 16f289f765cb035a59bf669ebae46b804029cdcf Mon Sep 17 00:00:00 2001 From: Zhenhao Liu <176368005+LikC1606@users.noreply.github.com> Date: Sat, 28 Nov 2026 13:04:42 +0800 Subject: [PATCH 3/3] Reserve extended browser checks for manual runs and releases --- .github/workflows/images.yml | 2 ++ .github/workflows/verify.yml | 35 ++++++++++++++++++++++++++++------- docs/web-operations.md | 4 ++-- 3 files changed, 32 insertions(+), 9 deletions(-) diff --git a/.github/workflows/images.yml b/.github/workflows/images.yml index d52d2840..557113b5 100644 --- a/.github/workflows/images.yml +++ b/.github/workflows/images.yml @@ -17,6 +17,8 @@ jobs: verify: if: (github.event_name == 'push' && !github.event.deleted) || (github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main') uses: ./.github/workflows/verify.yml + with: + full: true publish: needs: verify diff --git a/.github/workflows/verify.yml b/.github/workflows/verify.yml index 582f295b..a693bcda 100644 --- a/.github/workflows/verify.yml +++ b/.github/workflows/verify.yml @@ -7,6 +7,11 @@ on: branches: [main] workflow_dispatch: workflow_call: + inputs: + full: + description: Run the extended browser suites + type: boolean + default: false permissions: contents: read @@ -35,31 +40,45 @@ jobs: run: bunx vitest run --maxWorkers=4 tests/webRunSnapshot.test.ts tests/webResearchProjects.test.ts tests/webResearchApi.test.ts tests/webResearchAssets.test.ts tests/webResearchMathematics.test.ts tests/libraryPacks.test.ts tests/leanSource.test.ts - name: Verify direct formalization and independent background review without models run: bunx vitest run --maxWorkers=4 tests/directFormalizationEvidence.test.ts tests/directFormalizationWorkflow.test.ts tests/formalizationCoverage.test.ts tests/formalizationAudit.test.ts tests/formalizationContext.test.ts tests/formalizationPackagesWarmup.test.ts tests/mathProofEnvironmentSeed.test.ts tests/webFormalizationAuditWorker.test.ts tests/webFormalizationBackgroundReview.test.ts tests/webBackgroundReview.test.ts tests/webFormalizationProgress.test.ts tests/webThinkingProcess.test.ts tests/codexSessionInstructions.test.ts + - name: Verify session, draft, budget and archive recovery without models + run: bunx vitest run --maxWorkers=4 tests/webSessionCookies.test.ts tests/webResearchSession.test.ts tests/webDraft.test.ts tests/webLongRun.test.ts tests/researchPlanApproval.test.ts tests/archiveRecordNavigation.test.ts tests/globalTrajectory.test.ts tests/webChatDraft.test.ts tests/archiveSourceLocation.test.ts tests/taskPlanEditorAccess.test.ts - run: bun run build && bun run build:web - run: bunx playwright install --with-deps chromium - name: Verify proof progress in the default simple reading timeout-minutes: 5 run: bun scripts/test-web-proof-thinking.ts --simple-reading - - name: Verify the browser's login and research flows with local fixtures - run: bun run test:web-login && bun run test:web-natural-first && bun run test:web-chat-session && bun run test:web-chat-cancel-recovery && bun run test:web-key-memory && bun run test:web-saved-key && bun run test:web-solve-process && bun run test:web-review-regressions && bun run test:web-explain && bun run test:web-explain-recovery + - name: Verify login and the first research flow with local fixtures + run: bun run test:web-login && bun run test:web-natural-first - name: Verify native team creation, approval and library continuation with local fixtures run: bun scripts/test-web-native-team.ts && bun run test:web-plan-approval && bunx vitest run tests/webLibraryResearch.test.ts - name: Verify paper drafting and download with local fixtures run: bun scripts/test-web-paper.ts + - name: Verify formalization progress and background review in the browser + run: bun scripts/test-web-formalization-progress.ts && bunx vitest run tests/webBackgroundReviewWorkflow.test.ts + - name: Verify chat, saved keys, proof runs and explanations in the browser + if: github.event_name == 'workflow_dispatch' || inputs.full + run: bun run test:web-chat-session && bun run test:web-chat-cancel-recovery && bun run test:web-key-memory && bun run test:web-saved-key && bun run test:web-solve-process && bun run test:web-review-regressions && bun run test:web-explain && bun run test:web-explain-recovery - name: Verify research account switching and interrupted frontend operations + if: github.event_name == 'workflow_dispatch' || inputs.full run: bun run test:frontend-round5 - name: Verify session renewal, candidate review and route evidence readers + if: github.event_name == 'workflow_dispatch' || inputs.full run: bun run test:frontend-round6 - name: Verify delayed session responses and draft recovery - run: bunx vitest run --maxWorkers=4 tests/webSessionCookies.test.ts tests/webResearchSession.test.ts && bun run test:frontend-round7 + if: github.event_name == 'workflow_dispatch' || inputs.full + run: bun run test:frontend-round7 - name: Verify archive budgets, saved keys, plan approvals and historical record navigation - run: bunx vitest run --maxWorkers=4 tests/webDraft.test.ts tests/webLongRun.test.ts tests/researchPlanApproval.test.ts tests/archiveRecordNavigation.test.ts tests/globalTrajectory.test.ts && bun run test:frontend-round8 + if: github.event_name == 'workflow_dispatch' || inputs.full + run: bun run test:frontend-round8 - name: Verify historical guidance, mobile controls and native route search input + if: github.event_name == 'workflow_dispatch' || inputs.full run: bun run test:frontend-round9 - name: Verify recovered guidance, message receipts, math readers and source links - run: bunx vitest run --maxWorkers=4 tests/webChatDraft.test.ts tests/webConversations.test.ts tests/archiveSourceLocation.test.ts tests/taskPlanEditorAccess.test.ts && bun run test:frontend-round10 - - name: Verify formalization progress and proof thinking in the browser - run: bun scripts/test-web-formalization-progress.ts && bun scripts/test-web-proof-thinking.ts && bunx vitest run tests/webBackgroundReviewWorkflow.test.ts + if: github.event_name == 'workflow_dispatch' || inputs.full + run: bun run test:frontend-round10 + - name: Verify the complete proof thinking workflow in the browser + if: github.event_name == 'workflow_dispatch' || inputs.full + run: bun scripts/test-web-proof-thinking.ts verify-research-workflows: runs-on: ubuntu-24.04 @@ -82,8 +101,10 @@ jobs: - name: Verify single-step proof reading in the website and workbench archives run: bun run test:proof-reading-navigation - name: Verify the problem workspace, collaboration, library trials and public reading with disposable fixtures + if: github.event_name == 'workflow_dispatch' || inputs.full run: bun run test:frontend-product-continuity - name: Verify installed libraries, archived problems, mathematical reading and login returns with disposable fixtures + if: github.event_name == 'workflow_dispatch' || inputs.full run: bun run test:frontend-research-redesign && bun run test:site-research-entry verify-solver: diff --git a/docs/web-operations.md b/docs/web-operations.md index eed27f80..23ef36e3 100644 --- a/docs/web-operations.md +++ b/docs/web-operations.md @@ -8,9 +8,9 @@ ## 发布镜像 -`Verify TheoremOS` 在面向 `main` 的 pull request 和 `main` 推送上运行,也可手动运行。它以只读仓库权限执行 TypeScript 检查、运行时与网页构建、离线浏览器回归,以及 Lean 4.33.0 和 4.34.1 上的求解器回归。验证和镜像发布均使用 Ubuntu 24.04。 +`Verify TheoremOS` 在面向 `main` 的 pull request 和 `main` 推送上运行。日常验证包含 TypeScript 检查、运行时和网页构建、单测、Lean 4.33.0 和 4.34.1 上的求解器回归,以及登录、原生团队、计划审批、形式化和归档阅读的浏览器测试。手动运行 `gh workflow run verify.yml --ref <分支>` 会加跑完整的浏览器回归。验证和镜像发布均使用 Ubuntu 24.04。 -推送 `v*` 标签或运行 `gh workflow run images.yml --ref main` 会触发 `Publish workbench images`。发布流程在同一提交上调用上述验证,通过后分别构建和推送 web、worker、tex。三个镜像都使用完整源码 SHA 作为 GHCR 标签,并写入 OCI revision。Web 和 worker 还设置 `THEOREMOS_SOURCE_COMMIT`,Web 前端的 `build-info.json` 也记录这个 SHA。三张镜像均推送成功后,流程才上传 `image-release-`,其中 `image-release.json` 记录提交及三个 registry digest。 +推送 `v*` 标签或运行 `gh workflow run images.yml --ref main` 会触发 `Publish workbench images`。发布流程在同一提交上运行完整验证,通过后分别构建和推送 web、worker、tex。三个镜像都使用完整源码 SHA 作为 GHCR 标签,并写入 OCI revision。Web 和 worker 还设置 `THEOREMOS_SOURCE_COMMIT`,Web 前端的 `build-info.json` 也记录这个 SHA。三张镜像均推送成功后,流程才上传 `image-release-`,其中 `image-release.json` 记录提交及三个 registry digest。 本地可执行同一组无模型求解器回归。Linux CI 与 Worker 构建使用 `scripts/install-elan.sh` 安装固定的 elan 4.2.4,校验官方发布包 SHA-256,并通过 Lean 的发布 JSON 获取工具链。先安装相应工具链,再显式选择版本。