Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(model-hub): maintain inactive exact-base engine intent patch (#1961)

Call Whiteab8c22867e58
diff --git a/docs/plans/model-hub-engine-intent-policy-assessment.md b/docs/plans/model-hub-engine-intent-policy-assessment.md
new file mode 100644
index 000000000..ed3e3c2ed
--- /dev/null
+++ b/docs/plans/model-hub-engine-intent-policy-assessment.md
@@ -0,0 +1,1247 @@
+# Model Hub engine reasoning-intent assessment
+
+Status: **locally SOURCE-qualified seventh-round inactive source**, unshipped;
+final-byte qualification and a conditional LOCAL commit remain ahead.
+Exact5abe's historical source acceptance and renewed review exposed writable
+host RNG authority. The original four-file construction-only release covered
+finite device subtraction, connected HOST regressions and bounded qualification.
+After independent source inspection and checks, root accepted those dirty bytes
+and released final prose qualification followed by one conditional local commit.
+Remote delivery, clean review, seven-thread closure, OS and merge acceptance
+remain held. The orchestrator accepted the earlier
+configured-storage/preparation and nested private-context functionality only
+for its exact historical snapshot: 1,076 pure tests, one bounded Linux context
+diagnostic and independent native original-file readback. Those results and
+the successful CI on `e2d9c6361350` do not validate the new recipe bytes.
+The orchestrator independently inspected the sixth-head correction and accepted
+its bounded source mechanisms for renewed review. Neither that acceptance nor
+its exact5abe tests validate the seventh-round device subtraction.
+The orchestrator explicitly adjusted its supplementary source-evidence
+criterion; the old Watch's raw outer streams remain unavailable and complete
+original transport accounting remains UNMET. No new recipe Linux/privileged/
+Go/build/wire/fullphase or selected-engine-build execution is claimed.
+The preceding second-round recipe's 361 pure tests and separate complete
+lane/orchestrator Linux arm64 test/build/wire runs remain historical, as do
+the macOS, watcher-only failure and earlier receipt qualifications.
+Fresh exact-head Codex/CI gates and zero unresolved threads remain required.
+Shipping additionally needs separate provenance/publication authority. No Avibe
+runtime code, config, manifest, guard or workflow changed; the installed engine
+behavior is unchanged.
+
+Owner: lane D, Session `sesm5hv4yk5c8`;
+orchestrator: Session `sesvmgbdub2gp`.
+
+Delivery: the owner's independent-PR decision at `752c1def8` supersedes the
+earlier no-lane-push/combined-PR plan. This lane submits one Avibe PR containing
+only its inactive source/test candidate and assessment, plus the shared
+root-owned contract. The orchestrator independently verifies exact-head review,
+CI and source acceptance, and alone executes any gated merge. An Avibe PR merge
+does not ship the engine change or authorize engine publication.
+
+## Recommendation
+
+The pinned engine cannot express the requested policy through its existing
+configuration. A small source change is necessary. For example, a native
+Responses request with `reasoning.effort: none` reaches a mock upstream as
+`low` for the pinned `gpt-5.4` catalog row, or as `high` when the configured
+levels are `[high, low]`. A custom model without metadata loses the entire
+reasoning object. These are actual HTTP observations, not adapter simulations.
+
+Keep Avibe's Source/model registration and identity intact. Change the engine's
+shared thinking boundary to distinguish native wire intent from conversion:
+preserve native controls independently of catalog metadata, preserve explicit
+disable through conversion, and use capability-free conversion when the
+selected model has no thinking metadata. Continue using known metadata for
+genuine cross-protocol positive-intent conversion.
+
+Maintain the candidate source/test patch against the exact upstream commit,
+with a reproducible local build and HTTP fixture. Do not ship an Avibe manifest
+change until an authorized, truthful source/release route exists and all
+required assets are published and verified.
+
+## Seventh reviewed-head correction — finite device subtraction; OS gates UNMET
+
+Terminal review `5162069141` binds exact5abe and original `3974966709`.
+The complete circuit contains seven findings-bearing heads/nineteen originals,
+twelve resolved/seven unresolved; eighteen empty owner envelopes and the
+Completed summary are not passes. Sole exact5abe lint `34429289014`, attempt1,
+and all seventeen jobs succeeded, but OPEN/non-draft/CLEAN does not override
+the repeated external-resource-authority family or unresolved review gates.
+
+The existing finite system owner subtracts `/dev/random` and `/dev/urandom`;
+only null/zero retain their original type, exact major/minor, root ownership,
+O_PATH/no-follow admission and FD custody. Identity admission and O_PATH
+acquisition alone do not constrain a later writable device bind, and a readonly
+label is not substituted for removing RNG authority. No replacement device,
+descriptor, provider, service, syscall filter or fallback is introduced.
+Syscall randomness remains unchanged; consumers needing an absent RNG path
+must fail startup closed. Pinned Go/Python source references do not establish
+compatibility of every unexecuted diagnostic consumer.
+
+Connected regressions pass actual pin output through the existing parent,
+fixed handoff and private mount owner, covering the full positive device/
+directory/alias set, non-ASCII input/output labels, exact bind/remount flags,
+NODEV on non-device resources, state/output-only writable directories and
+received-FD closure after success or partial failure. Admission rejects wrong
+device identities/types and unexpected aliases. Only task-owned regular
+backing and intercepted host metadata/effects are used; no real RNG device,
+mount, unshare, keyring or chroot operation runs. Existing private-rootfs,
+NODEV, descriptor-closure and capability-drop premises remain source-level
+companions against alternate paths/handles, not kernel enforcement.
+
+The preceding final bytes passed the lane's 1,457-case pure run in 18.32
+seconds, Ruff 0.4.9 and syntax/whitespace checks before the local5abe commit.
+Root then independently passed 1,457 cases in 17.34 seconds on exact5abe
+before source acceptance and bounded delivery.
+Those results and all earlier failures remain bound to their original bytes.
+The seventh-round construction handoff returned unstaged/uncommitted source:
+lane checks passed 279 focused cases in 3.13 seconds and 1,482 complete cases
+in 19.20 seconds, with Ruff 0.4.9 and static/whitespace checks. Root inspected
+that exact candidate and independently passed 1,482 cases in 18.62 seconds
+before accepting its inactive source. These checks precede this final prose
+freeze, not the separately released final-byte qualification and conditional
+local commit. New outcomes belong only in the external return; no maintained
+prose changes follow validation. Root must independently accept any resulting
+committed bytes before later delivery. All OS/startup and publication gates,
+content-custody prerequisites and OLD Watch transport UNMET persist.
+
+## Historical sixth reviewed-head correction — source inspected; OS gates UNMET
+
+The September 10, 2026 Asia/Shanghai root circuit decision first released a
+bounded local source correction and finite HOST qualification, then independent
+source inspection accepted that candidate for final prose qualification and
+a conditional local-only commit. Reviewed head
+`90cfc9b3dc99d54607561eb91783c69690c4888e` has terminal findings review
+`5160886376`: macOS service IPC (`3973908442`) and multiply-linked source
+closure (`3973908447`). The complete history contains six findings-bearing
+heads and eighteen originals: twelve resolved, six unresolved. The four
+preceding findings remain open. All seventeen exact90 CI jobs succeeded;
+there is no clean Codex verdict, closure, merge or OS acceptance.
+
+The existing macOS policy owner now starts from default-deny. Its only
+positive non-file operations are process-exec and process-fork; no Mach/XPC,
+POSIX/System V IPC, IOKit, job, signal or sysctl grants are introduced.
+Explicit network/file denies and finite task/input file grants retain the
+same original StorageContext and home/protected/alias exclusions. Process
+grants do not grant file paths. Missing startup operations fail closed:
+constructed policy and intercepted argv do not demonstrate kernel enforcement,
+inherited-port confinement or a supported startup closure.
+
+The existing execution-input regular-file owner admits a single-link regular
+inode via no-follow/nonblocking descriptor, reads those bytes and checks
+observed pathname/descriptor and metadata continuity on entry and completion,
+closing partial acquisitions and failed reads. Source/fixture/recipe digests
+and verify's actual input/candidate reads reuse it; public apply also admits
+the complete source closure before a patch write. Sorted relative names,
+kind tags, length-prefixed encoding and supported internal symlink rules are
+unchanged; normal single-link trees keep their original digests and pins.
+Preexisting writable hardlink aliases and observed drift are refused, not
+repaired. This is not an atomic snapshot or protection against an unconstrained
+outside writer creating a later alias or changing bytes. Trusted preparation
+and content custody throughout the interval, and the intended readonly mount
+boundary, remain explicit independent prerequisites.
+
+New consuming regressions cover policy grants/argv/refusals, real task-only
+hardlinks, direct source/candidate reads, complete apply admission, phase
+pre-command and wire pre-import refusal, observed replacement/link-count/type
+changes, nonblocking FIFO rejection and descriptor closure. Before this final
+prose update, the lane passed 1,001 focused cases in 24.27 seconds and 1,457
+complete pure cases in 17.63 seconds; the orchestrator independently passed
+1,457 in 17.54 seconds. Each run exited zero without skips, warnings or
+deselections. Lane Ruff 0.4.9 checked all fifteen Python files; fifteen ASTs,
+all ten fenced blocks, nine shell and six embedded Python syntax checks
+reconciled. Precisely scoped whitespace checks had empty diagnostic streams;
+their raw content-difference exits remain one, not rewritten zero.
+These are overlapping source checks on the inspected pre-final-prose bytes,
+using the CURRENT readonly 23-file layout described below, not OS evidence.
+The later exact5abe final-prose qualification, local commit and bounded
+delivery have separate external records, summarized above; thread closure
+and OS acceptance were never established by those source results.
+The namespace/filter/bootstrap/ownership-fixture contracts and native patch
+remain unchanged.
+
+The preceding final exact90 source separately passed lane/root 1,420-case
+pure runs (17.16/16.15 seconds), Ruff 0.4.9 and static/whitespace checks before
+inactive-source acceptance and renewed review. These and the earlier
+pre-document 1,420/335 results below remain historical, not validation of
+this correction. Both failed macOS routes, all Linux execution gates,
+provenance/four-platform limits and OLD Watch raw transport UNMET persist.
+
+## Historical fifth reviewed-head candidate — pure HOST evidence; OS gates UNMET
+
+The September 10, 2026 Asia/Shanghai circuit decision permits one local
+candidate directly after `10b1bdd80e20eea300c97baeda9fb120522e9a33`, not
+delivery or execution acceptance. The complete pre-edit nine-collection
+inventory equals the independently consumed root snapshot
+`root-1961-snapshot-10b1bdd80e20-20260909T191307308457Z.json` (SHA256
+`3140fa9a88e8eef0dc6fc7d0e8fa1af1290d35a8877105df33291e26f681dfdd`).
+There are five findings-bearing heads, sixteen original findings, seventeen
+review envelopes, twenty-eight inline objects, four issue comments and sixteen
+complete threads: twelve resolved, four unresolved. Twelve empty owner
+envelopes are not findings or clean passes. Review `5158126460` is terminal
+with findings on `10b1`; no pending review or genuine exact-head clean verdict
+exists. Sole lint `34380925809`, attempt 1, and all seventeen expected jobs
+succeeded. OPEN/non-draft/CLEAN does not establish readiness.
+
+| Fifth-head original | Thread | Boundary |
+| --- | --- | --- |
+| 3971583274 | PRRT_kwDOPbFPYs6gxv_t | Invoking UID's kernel keyrings |
+| 3971583287 | PRRT_kwDOPbFPYs6gxv_2 | Shared host IPC namespace |
+| 3971583298 | PRRT_kwDOPbFPYs6gxv_6 | Child bind-source and last privileged-effect custody |
+| 3971583305 | PRRT_kwDOPbFPYs6gxwAA | Complete captured-home macOS read isolation |
+
+These are namespace/storage owner corrections, not changes to prepared native
+intent, explicit disable, source-aware unknown conversion, xAI catalog-filter
+removal, Kimi native-object distinction or routing/auth/registration authority.
+The native patch, exact engine base, pins, fixture/apply implementations,
+budgets and execution-input/wire consumers remain frozen.
+
+The candidate uses the exact inspected native Linux AArch64 little-endian64
+11-instruction/88-byte BPF program (SHA256
+`196f5affb55a9d30299561255adb1027f9a985aba9762b9c66624ed5cded604d`).
+It rejects foreign architecture/high-number compatibility paths, denies only
+add_key/request_key/keyctl with EPERM and allows other native low syscalls.
+A typed stdlib ctypes/prctl adapter retains the actual program/array through
+NNP installation, filter installation and ordered NNP1/Seccomp2 readback.
+Success alone supplies the immutable marker's exact ABI/program identity.
+The marker precedes readonly-remount/chroot and both dropped preflight and
+candidate; all actual evidence consumers require live zero capabilities,
+NNP1/Seccomp2 and complete mnt/net/pid/ipc identities bound to that marker.
+An anonymous session keyring or Seccomp2 by itself is not accepted proof.
+
+One parent ExitStack, the existing unnamed handoff and private supervisor
+retain custody through reaping. Names after admission are diagnostic/mount
+labels, not resource reselection:
+
+| Resource | Admission and retained consumer |
+| --- | --- |
+| Caller root | Canonical original-storage admission, caller UID/directory/exact0700, one no-follow descriptor; rechecked before parent allocations/launch |
+| Source, frozen fixture, inspected recipe, toolchain, Python environment | Component-relative no-follow/nonblocking/close-on-exec directory pins, admitted dev/ino/type/uid/mode; direct libc bind from source FD, readonly/nosuid/nodev |
+| Go archive | Same component walk, regular-file pin, readonly FD bind; never treat a directory/device as an archive |
+| Writable state | Caller-UID directory pin and original-storage admission; writable/nosuid/nodev bind |
+| Exclusive output | Actual allocate_output descriptor retained; caller ownership/mode and parent receipt output identity; writable bind |
+| Selected prior build | Pinned beneath parent-owned runs; exact identity matches the successful prior parent-owned receipt; readonly bind |
+| Rootfs/control | Exclusive rootfs child of retained root-owned receipts/control FD; after tmpfs, reopen that protected child as the distinct overmount view |
+| Target topology/metadata/marker | Create and retain protected target-parent FDs and metadata files before any caller bind; remount via parent/component; marker written only after filter success |
+| Bootstrap modules | Authenticate bounded unnamed root-owned control first; pread only pinned budgets/isolation/namespace, verify all actual bytes against inspected digests before any module execution |
+| System trees and four devices (historical) | Explicit installed-system trust; finite pinned system directories/aliases; null/zero/random/urandom used Linux O_PATH/no-follow and exact character-device identities. The current seventh correction removes both RNG devices. |
+| Chroot/closure/cleanup | fchdir(new overmount view), chroot("."), chdir("/"); close host/input/setup FDs before preflight, unnamed proof before candidate; parent removes only original empty rootfs identity relative to retained control FD |
+
+Pinning a directory does not freeze mutable contents. Fixture/toolchain and
+inspected recipe/interpreter/standard-library/system content prerequisites
+remain separate. The candidate uses an explicitly typed direct libc mount
+adapter, not mount(8) configuration/helpers. HOST target strings and fake view
+replacement are not evidence of actual Linux proc-FD bind or remount semantics.
+
+The macOS helper remains a finite pure-source diagnostic API. It requires
+explicit staged task/recipe/source/interpreter/system inputs, rejects every
+home/protected/alias overlap and broad home/project/system ancestor, and
+applies the same StorageContext admission to EVERY grant, including tools and
+system inputs. Its policy denies network, global reads and production writes;
+only admitted finite reads and task writes are granted. There is no global
+metadata permission, credential-name denylist, arbitrary fragment or
+unsandboxed fallback. The exact startup input closure is still unmeasured.
+
+After the fixture's per-inode synthetic ownership correction, the lane passed
+335 focused HOST cases (926 deselected). The orchestrator independently passed
+the complete seven-file pure suite: 1,420 passed in 25.07 seconds, exit 0,
+empty stderr and no skips, warnings or deselections. All 2,410 maintained
+entries and all 23 input-view files were unchanged before/after that run.
+It consumed hash-admitted CURRENT bytes in a readonly relative layout outside
+real homes: files 0444, directories 0555, separate task-writable execution and
+fresh HOME/XDG/product/temp roots. The independent outer HOST policy denied
+network, production writes and all real-home reads/metadata, without home-input
+exceptions. This admitted layout let strict README resolution reach its
+intended storage-refusal assertions without changing production or test code.
+
+These tests consume emitted bytes, intercepted typed libc adapters,
+component/ancestor replacement, old/new overmount ordering, verified bootstrap
+bytes, finite unprivileged HOST FD/import children, marker/probe/parent
+receipts and synthetic macOS policy refusal. The emitted-program case's
+5,140 decode assertions are internal to ONE test, not separate result rows
+or Linux execution. Pure passes are not lint/static qualification, independent
+source acceptance, OS enforcement or delivery.
+
+Earlier lane originals remain failures: the complete run exited 1 with
+1,071 passed/one failed when README strict resolution hit denied home ancestors
+before the intended refusal; the prior focused run exited 1 with 120 passed/
+one failed/1,027 deselected on inconsistent synthetic GID metadata; the initial
+collection attempt exited 2 with zero tests. Their commands and streams remain
+unmodified. No Linux syscall, proc, mount, namespace, keyring, IPC, sudo/chroot,
+engine, network listener or candidate macOS sandbox execution is claimed.
+
+Historical fourth-round `10b1` source acceptance included 1,190 HOST cases,
+pinned Ruff 0.4.9 and static/whitespace checks; root independently ran the same
+1,190 without skips/warnings. Historical scratch mechanism evidence is 51
+passing HOST tests and 5,140 executed decode assertions. Its original stdout
+contains program hex/digest, the count and 51-test summary, NOT 5,140 individual
+result records. Neither result validates this candidate's new bytes.
+
+Both macOS mechanism attempts remain failures. The lane's nested command
+returned inner 71, empty stdout and `sandbox-exec: sandbox_apply: Operation
+not permitted`, outer 1; only five synthetic admission refusals ran. Root's
+separate single-profile child returned -6 with empty stdout/stderr and outer 1.
+All positive/negative child read/write assertions are UNMET. Root's earlier
+extra non-group-writable interpreter assumption failed preparation; the later
+identity correction retained the same root-owned0775 Python and access ceiling,
+without changing installed modes. No failure is relabeled or rerun here.
+
+Remaining execution gates are native ABI/kernel filter support, actual
+fork/exec inheritance and harmless task-owned-key denial, IPC identity/resource
+separation, proc-FD mount/overmount/remount/chroot/cleanup continuity, and the
+macOS startup closure plus enforced synthetic positive/negative access.
+No new driver, synthetic kernel object, dependency or installed-state change
+was prepared by that candidate. At that checkpoint, independent root source
+inspection was still required; root alone can release later OS work or delivery.
+
+All historical Linux/fullphase/Go/338/macOS/uv/watcher, raw-versus-tracked/cache,
+observer-versus-verifier and publication/four-platform qualifications below
+remain attached to their original bytes. OLD Watch raw outer transport remains
+permanently UNMET. The stale twelve-original root gate is not invoked or
+updated here. Original lane/root forever Watches and distinct cursor lineages
+remain enabled until a later explicit post-merge removal decision.
+
+## Historical fourth reviewed-head pre-envelope authority correction
+
+The complete review inventory at the recorded scope decision contains four
+findings-bearing heads and twelve original findings: eight resolved historical
+threads and four unresolved threads. Review `5155993490` on
+`e2d9c6361350c65929039338bc23a05ac720f8b7` is terminal with three real findings,
+not a clean pass. They concern caller root custody at the privileged writer
+(`3969819318`), ambient Python executable/import startup (`3969819326`), and
+ambient Git configuration/templates/hooks (`3969819339`). The older configured-
+storage finding `3965522776` remains unresolved/outdated. All seventeen matching
+CI jobs succeeded on that reviewed head; green CI does not override this
+repeated pre-effect authority circuit.
+
+The same orchestrator independently diagnosed the complete inventory and
+authorized correction at the existing owners, without another lifecycle owner
+or engine-intent change. Directory topology and an earlier preparation check
+cannot grant custody to a later privileged writer. Body-only Python tests
+cannot validate interpreter startup, and a sanitized test environment cannot
+establish the real documented Git boundary.
+
+The privileged parent now binds its admitted canonical root to one no-follow
+descriptor, verifies caller UID, directory type and exact mode 0700 before any
+receipt/run/rootfs allocation, and rechecks that identity at the actual
+allocation consumers. Rootfs creation and removal use the same held descriptor;
+pathname replacement refuses without repairing a supplied root or discarding
+prior evidence. Existing original-storage admission, parent receipt/private
+handoff ownership and finite phase budgets remain controlling.
+
+Every pre-envelope README Python entry selects trusted absolute Python with
+isolated startup before explicitly importing the inspected canonical recipe.
+Original HOME/XDG/Avibe/Codex/Claude storage variables remain available for the
+shared original-context capture. The public direct-sudo parent and phase caller
+use the same bootstrap shape; failed context/export command substitutions stop
+their shell rather than continuing with an invalid value.
+
+One command-local Git boundary is reused by preparation, fixture export and
+verify/apply. It uses the trusted executable and an empty init template,
+disables ambient/global/system configuration, hooks and executable helpers,
+and refuses non-bookkeeping local configuration before operational commands.
+This includes local includes, filters, fsmonitor, external diff, worktree
+redirection and alternate transport settings. Source/fixture pins and
+dirty/untracked/identity refusals remain unchanged. No installed Git setting
+is modified; prerequisite networking remains separately authorized future work.
+
+The existing pure consumers retain the earlier assertions and add actual
+mocked-parent allocation/descriptor failures, real shell/isolated-interpreter
+startup with task-only shadows, and real task-only Git repositories exercising
+the maintained callers. Linux privilege/process/kernel seams remain mocked;
+the startup tests explicitly adapt only the trusted HOST Python path and omit
+sudo when invoking a finite fake parent import. No live guest or engine test
+is implied. New measured HOST results belong to the exact returned local
+proposal and its retained commands, not to the historical recipe below.
+
+The README is intentionally changed by this separately authorized fourth-round
+repair. The earlier recipe tree `e024eb07cff6df2db9caea0b400e171317b380d4`
+is historical. Its accepted then-unexecuted README notice and later bounded
+diagnostic remain distinct evidence; neither is silently relabeled as this
+recipe. The native patch, pinned source/fixture/toolchain declarations and
+wire/routing/auth/registration ownership remain unchanged. No push, thread
+mutation, new review trigger, merge or engine publication is authorized by
+this local correction.
+
+## Historical third reviewed-head configured-storage correction — source accepted, local only
+
+The independent review inventory at that checkpoint contained three findings-bearing
+heads, eight resolved historical threads and one current unresolved finding,
+`3965522776`, on reviewed head `79a47b8217463e49e06a80368718ed83068e6dcd`.
+The repeated class is incomplete protection before setup writes, not a new
+engine-intent defect. The same orchestrator recorded a bounded scope decision
+before further changes. Successful CI and prior source runs do not waive it.
+
+One original-user storage model now serves every existing public write-root
+consumer and the macOS deny-read policy. It includes passwd/effective HOME,
+the four fixed product directories, five XDG authorities and existing
+AVIBE_HOME/CODEX_HOME/CLAUDE_CONFIG_DIR overrides. Empty/unset values use standard
+defaults beneath effective HOME; XDG runtime has no invented fallback. Invalid
+relative/parent-traversing paths fail closed without logging their values.
+Lexical/canonical aliases, protected descendants and writable ancestors use
+the same admission policy. The narrow privileged temporary-root rule is retained.
+
+Independent inspection of local commit `1844a14fd` confirmed 733 passing pure
+consumers, but also reproduced a missing preparation consumer: the README
+checked only the allocated ancestor before source initialization and state
+mkdir. A preexisting `source` alias into configured XDG config or a `state`
+alias into XDG data reached a real fake-directory write before later admission.
+Both reproductions and all earlier evidence remain intact. This is the same
+pre-write class under the recorded circuit decision, not a fourth GitHub
+findings-bearing head or an engine-policy change.
+
+The corrected README entry now consumes one complete preparation directory
+plan from `isolation.py`, reusing the shared storage validator and generated
+environment planner. Before its first mkdir, copy or Git subprocess it admits
+source, recipe, state/environment/shared cache, downloads, Go/uv extraction,
+venv, exclusive fixture-export parent and setup-only uv cache. It requires an
+empty, caller-owned canonical mode-0700 allocation, rejects all preexisting
+children/aliases/evidence, and exits the setup shell on refusal. Fresh children
+prevent hidden download/extraction/venv descendants from reusing old aliases;
+there is no reset/reseed or permission to change destinations after admission.
+No new executor, storage policy or privileged lifecycle owner is introduced.
+
+The documented ordinary caller binds its original context before sudo. The
+same privileged parent independently checks that digest against its live
+`/usr/bin/sudo` parent's bounded Linux proc exec-time environment, using the
+invoking passwd identity rather than root's sanitized HOME. Unavailable,
+scrubbed, changed or non-sudo context fails closed. This is a deliberately
+narrow direct-sudo caller contract, not support for arbitrary privilege
+wrappers or reconstruction of already-discarded variables.
+
+The admitted context travels through the existing unnamed parent control and
+root-owned private namespace proof. Only verified private namespace, privilege,
+context and exclusive invocation/output identities permit child consumers to
+reuse it instead of misclassifying generated task HOME/XDG/cache as production.
+There is no public safe-root dictionary, skip/allow flag or ambient marker.
+Public preflight/terminal evidence exposes the context digest, not original
+storage paths. Existing lifecycle, deadlines, terminal custody, readonly
+selected build and output semantics are unchanged.
+
+New pure consumers use only fake passwd homes, configured storage and proc
+metadata. They exercise actual setup/export/verifier/wire/process/namespace
+admission, the maintained documented caller with sudo mocked, lost/forged
+context, canonical aliases, shared caches and valid nested private task state.
+The added preparation tests execute the maintained README body, including both
+exact source/state alias reproductions, every planned destination and relevant
+archive/compiler/venv/fixture descendant, configured/default authorities,
+containing paths and preexisting evidence. Negative cases preserve the complete
+fake task trees and reach no mkdir/copy/export/Git or privileged subprocess.
+A legitimate fresh task exercises actual directory creation, metadata-free
+recipe copying and local Git initialization; it performs no fetch, export,
+download, extraction or installation. Shell refusal stops later instructions.
+No real configured values, production contents or guest operations are used.
+At the preparation-repair checkpoint, the complete maintained pure suite passed
+1,076 tests (the prior 733 plus 343 preparation consumers). The orchestrator
+independently inspected the exact source and repeated all 1,076 tests, with no
+skips, under the deny-network/deny-production-write envelope; pinned Ruff 0.4.9
+and document/AST/whitespace checks passed. These are existing measured results,
+not new test invocations during this assessment-only finalization. Pure
+consumers alone are not live sudo/namespace or engine-execution evidence.
+
+The historical recipe README retained its then-unexecuted context-handoff
+acceptance notice as part of the exact accepted pre-execution snapshot; the
+assessment-only finalization did not update it. The later bounded diagnostic and acceptance below
+supersede that historical status, not its input bytes or failure predicates.
+Unavailable original context still fails closed. The original native Go patch
+and frozen source/fixture/toolchain declarations remain unchanged.
+
+### Incremental context evidence and acceptance limits
+
+The frozen once Watch `0b07a0286efb` actually executed configured-root rejection
+then the private-loopback parent/direct-child diagnostic, retired with exit 0
+and was not retried. Rejection reached the exact
+`ValueError: Task writes must not target protected user state.` before receipt/
+run allocation or state writes, rather than a sudo-layout, digest or argument error.
+Positive execution carried the original context through the existing
+privileged parent, including its additive root identity. Distinct, unambiguous
+outer PID/start/NSpid identities bind both candidate roles to their private
+PIDs and direct parent/child relationships in both views; equal ticks alone
+are not identity. Generated task HOME/XDG/cache remained usable without
+replacing the admitted original-storage context.
+
+After inspecting the source and complete originals, the orchestrator performed
+one separately scoped native unprivileged readback, not a diagnostic replay.
+Its 57,176,009 output bytes matched the lane's readback byte for byte: all 42
+original text captures and seven hash-only inventory roots, including complete
+per-case merged stdout/stderr logs. Original root-owned mode-0640/single-link
+parent and dedicated preflight custody remained separate from supplementary
+observations. Native readback reconsumed both role bindings, full unchanged
+inputs, finite outputs and state, and bounded process/mount/boot cleanup.
+
+All twelve outside-sentinel negatives, both private-loopback positives and
+outside receives `[0, 0]` matched, with UID 501/GID 1000, five zero capability
+sets, `NoNewPrivs=1`, separated mount/network/PID namespaces, readonly inputs
+and exclusive output. Candidate/namespace/driver budgets remained 10/130/160
+seconds. No observed PID/start survivor, including zombies, private PID member,
+task executor or rootfs remained in terminal/native readback checks.
+These are bounded observations, not universal claims about unobservable state.
+
+| Incremental source/evidence artifact | Exact identity |
+| --- | --- |
+| Maintained source commit at execution | `3a74406e0bf6fc466821c1cc43011fb1627b44ce` |
+| Complete 21-file recipe Git tree | `e024eb07cff6df2db9caea0b400e171317b380d4` |
+| Metadata-free tracked recipe SHA-256 | `1c57e02045d48b70b6e0429a877744492db7614cdc9f11bf1319528e56051690` |
+| `root-d-round3-context-source-acceptance.md` SHA-256 | `aa71fc3f8600c009d1a1686628068dda524beb8aac1cb74d3f4ededf520ed8bf` |
+| `root-original-readback.stdout` SHA-256 | `4d18800cd6169f745f3cd87c9983658e2a53c83acaf7696ec6eba11a621b8110` |
+| `root-native-readback-result.json` SHA-256 | `412f3b7be8372740768e2bb77eabd871b784c8bce20400b65549630db4621df0` |
+| Original positive parent receipt SHA-256 | `d0ac5b61a27c8d8b491fb2edbb8c93c64244129b632360d4e6903a9dd9302182` |
+| Dedicated original preflight SHA-256 | `0ec8924144e5393af47228361d5c92b79aeb3a587d8cec4a987d31ffe7fa583b` |
+
+The old Watch's raw outer stdout/stderr was not persisted. Its normalized
+notification survives, but exact trailing stdout whitespace and empty original
+stderr cannot be certified. Complete original transport accounting remains
+**unmet**. The orchestrator explicitly changed its supplementary source-
+acceptance criterion to complete original command/per-case merged logs and
+parent evidence plus independent native readback. This is a recorded criterion
+change, not recovered old streams, acceptance from exit 0, or a waiver of
+storage, custody, identity, cleanup, review or CI checks. Failed host inspection
+evidence remains failed; the native reader's new streams do not replace the
+lost Watch streams.
+
+Acceptance covers only the incremental source/context functionality above,
+not arbitrary privilege wrappers. There was no new `e024eb07` Go/build/wire/
+fullphase or selected-engine-build test; `selected_build=null` is a probe fact.
+The `7ac2386d1` / `5b6d733` fullphase evidence below, setup-only uv,
+observer-versus-verifier identities and historical macOS/Watch limitations
+remain qualified. The tracked recipe digest excludes preserved ignored caches;
+raw worktree identities are not interchangeable with it. This local acceptance
+does not resolve the remote finding or establish fresh exact-head PR gates,
+engine publication authority or shipped behavior.
+
+## Historical second reviewed-head recipe correction
+
+The same orchestrator independently diagnosed the full history before
+authorizing repair: two findings-bearing heads, with repeated
+execution-input provenance and isolation-ownership classes. The circuit
+breaker paused edits/pushes; the recorded scope decision released only this
+one coherent recipe/test/documentation correction and deny-network pure tests.
+No engine thinking, registration, auth, payload, normalizer or suffix policy
+change is part of this round.
+
+The existing owners remain:
+
+| Boundary | Owning correction |
+| --- | --- |
+| Execution inputs | Verify the actual full Go extraction against the pinned archive before Go runs; bind archive/tree/selected executable, source, fixture and recipe identities before/after. Measure the existing venv/lock and explicitly label guest Python/OS/util-linux and setup-only uv trust, not unverified provenance claims. |
+| Invocation outputs | Parent reserves one new output directory using its existing receipt identity. Verifier owns exclusive logs/binary/candidate records there; wire explicitly selects and verifies a prior build mounted readonly. Shared caches are not a mutable latest-artifact pointer. |
+| Writable roots | One canonical pre-write validator protects broad/home/protected paths across environment, exporter, verifier and wire consumers, including sudo's invoking user. The privileged CLI supports only narrow canonical `/tmp` or `/var/tmp` children and keeps hidden-home probes strict. |
+| Privileged entry | Public CLI always runs `unshare`; no internal flags select re-entry. A fixed child trampoline receives an unlinked parent-owned control descriptor and checks all actual kernel namespace identities before the first mutation. Original preflight/terminal custody remains separate and closes before candidate launch. |
+| Deadlines | One derived phase budget is consumed by command executor, parent and caller. Three permitted sequential Go commands fit the complete test envelope, with bounded input/preflight/setup/cleanup allowances and failure/timeout evidence. |
+
+The detailed verified/measured/trusted/setup-only inventory is maintained in
+`patches/cliproxyapi/README.md`. In particular, a frozen lock plus a measured
+venv is not archive attestation of Python distributions, and shared Go caches
+retain the existing Go trust model rather than a new production provenance
+contract. Candidate artifacts remain supplementary evidence; only the
+parent-owned receipt records trusted preflight and cleanup.
+
+Pure consumers cover the original entry points, substituted compiler and
+runtime/tool files, canonical path aliases, repeat test/build/wire runs,
+output collisions, partial failures, stale build selection and fake-clock
+deadline propagation. Kernel probes, complete source execution and independent
+rerun passed for the exact second-round recipe below. The configured-storage
+correction was not present in those runs and does not inherit their execution
+acceptance. Publication remains separately blocked.
+
+## Historical second-round Linux source acceptance
+
+On 2026-09-09 the lane completed `fullphase-sequence-2m05b_t9`. After reading
+all original evidence independently, the orchestrator ran the same inspected
+driver once more as `fullphase-sequence-lhboam7u`, from
+06:21:31.223856Z to 06:22:52.369652Z. Both executions were sequential
+test -> build -> wire, with no retry or cache reset. The orchestrator then
+read all 66 original text files, including every parent/preflight/invocation
+and phase log, the complete 456-line/58,205-byte engine log, full before/after
+inputs, hashed output inventories, selected build and lifecycle evidence.
+Exit codes or summary counts alone were not the acceptance criterion.
+
+| Accepted second-round input, before configured-storage correction | Identity |
+| --- | --- |
+| Maintained commit at execution | `7ac2386d1bc9c413ff02a4fe70778efa3d465d47` |
+| Complete 21-file recipe Git tree | `5b6d733fa51d14489bc8889be4bab9bad248a643` |
+| Tracked recipe source SHA-256 | `7cceaf71c292b525eaab3df38cff68184967da8ed797f989cc93a47f3c0db2fa` |
+| Inspected sequential driver SHA-256 | `79fca450bdde28be11958d8c53c2a9b1066f020c261d4fb83e3d639303b45670` |
+| Engine base commit | `2a6b87aca083a5bf498ac1f68a1b636c500d7aaa` |
+| Complete patched engine source SHA-256 | `c49da0017dc015030cd8f460e3288381765bf1283fc49478af657f389c265fb2` |
+| Unchanged native patch SHA-256 | `f55a3731e82837ed92d8943e97ef6d6521d21a78d3026a65c97b0950c3c494be` |
+| Frozen Avibe fixture commit / tree | `76e269c9a9dfd3a6286ce0da81b77316ca4be38a` / `27f32c68b3b9c6b1d40fcde3a034838b58ca0636` |
+| Frozen fixture archive SHA-256 | `3352c66c7b88c35ce7851a4bcfbeb3ac2e6d842199ef7dcf7c93534c0233c4cc` |
+| Complete frozen fixture source SHA-256 | `61c9616c760f9bbe4750c507073deea183064ec7f55dbacc2174eac9c474031e` |
+| Observed Go version / build target | `go version go1.26.4 linux/arm64`; `linux/arm64`, `CGO_ENABLED=0` |
+| Verified Go archive SHA-256 | `ef758ae7c6cf9267c9c0ef080b8965f453d89ab2d25d9eb22de4405925238768` |
+| Complete extracted Go tree SHA-256 | `494cfe7e2731c4125a75ddc194acfd3902657e1da9c5e846d63960aa78081f4a` |
+| Actually selected Go executable SHA-256 | `299613d26b2fc429f9b1a8dbbc6f8952f7e0fb7b5b624c63ff0442a15233eaad` |
+| Measured frozen-lock venv tree SHA-256 | `690bc736ecde2f7129dd1da41893b8ed31d287265e7cfd670084be369442df3b` |
+| Actual verifier normalized input SHA-256 | `e65b6372725d6a2dc98ac4de8cef65eacacfcc792f97f7930734fb14911ef53b` |
+| Complete observer normalized input SHA-256 | `9b9163a9f7d224893da522dd3ef1eff3782df510740687dcb2b305d23d4000a3` |
+
+The verifier object excludes only the observer-only
+`setup_only.verified_existing_uv_archive_sha256` fact. Both objects are
+preserved: the observer object is not emitted candidate provenance, and
+neither an execution nor extraction of uv is claimed. All six observer
+before/after files share raw SHA-256
+`3d393e7d6b1ee2ae96a959356f9d9c8f07627a9ed7db19e7a48597669c268fb2`;
+all six candidate files share
+`45a70b0d0a11425bbdfa894da77a4d99838392fe8b126fcb30c4c80b583f161e`.
+The committed catalogs and engine `go.sum` retain the identities in the
+historical input table below.
+
+| Independent root-run evidence | SHA-256 |
+| --- | --- |
+| Original test parent receipt | `dda6346209fefd8e1d9c5d1de88bf752328d0f60505bfa4a32c6d8d18104ee24` |
+| Original build parent receipt | `85abcee12ab40b801178d006707172c72fec2863013589a6e4b21cee3c60a077` |
+| Original wire parent receipt | `71bcb0ce7a54bd4c1abebee601acab3de969916fa84db2497432902274a7caf0` |
+| Linux diagnostic binary, 79,233,112 bytes | `638de6ce30cfb1c0c7f36a29ff60c41361ac4dad8f86d134076cbe84f7667ea4` |
+| Selected build's candidate receipt | `e32e0133269819cd03c42e7c6c4702d24a743cc22cb740b682ac59aa93ce4f55` |
+| Selected build artifact inventory | `9c774681d31b69988b6fd8743458af068edcee9a4f745c13564e13400843e432` |
+| Complete selected build tree | `6adc585281f813ad85f87c1160d39d8a291f292790a68e94ad6a989301f7ae5a` |
+| Wire candidate receipt | `8c25dcd7e6f7cc139cf4cff2c1fd8bd1cf5ec4ab8e9005fd05a185b5ad8cf4e5` |
+| Complete 380-row policy matrix | `71b15e16af5cde8f022bb51dc41507506f6a9d93e8e75830cd927f6e8f26fa15` |
+| Complete long-identity / image records | `cb807fd737c5294cc52c101a5a2805c96b661e0e45f9c8e458b8ef15c25a0ccb` |
+| Actual frozen lifecycle records | `92ac48c264657d7de8bdb9881a9879db6161a4934baa4c1849963fc2df8cdfb0` |
+| Complete engine log | `568445ac60dc48a428b7a202c3737746b4d27daae24a132527da06690d70d278` |
+| Supplementary complete root readback bundle | `223850d5f86ff7ab93e25175062f76c3afce37f57e7d38a02cdb3c837e5ffb15` |
+
+Wire selected only its own sequence's successful build, binding the original
+parent receipt, invocation, full input identity, binary and complete artifact
+tree before and after consumption. Parent receipts remain original root-owned
+mode-0640 single-link regular files. Supplementary artifacts were read
+unprivileged through anchored, no-follow, regular, single-link, bounded reads;
+binary contents were hashed without export. They do not replace parent custody.
+
+Every phase recorded actual UID 501/GID 1000, all five capability sets zero,
+`NoNewPrivs=1`, distinct mount/network/PID namespaces, readonly original
+inputs and exclusive invocation output. Wire's selected build was readonly.
+Each preflight recorded all twelve blocked sentinel attempts: test/wire had
+both private-loopback positives and errno 111 negatives; network-none build
+had IPv4 errno 101/IPv6 errno 99 and no positives. Outside receives were
+`[0, 0]`. Full inputs, outer mounts and boot ID were unchanged. Original and
+fresh cleanup found no surviving observed process identity, private PID
+namespace member or rootfs; unavailable privileged namespace links were not
+invented from unprivileged observations.
+
+Actual records reconcile 380 unique policy cases and 378 successful captures.
+The two HTTP 400 cases are only Chat -> Responses, narrow profile, absent
+intent, stream off/on, with zero upstream requests. All 24 complete Unicode
+identities pass, including distinct long shared-prefix tails. Three sequential
+image requests of 44,051,709 / 44,051,604 / 44,051,581 bytes preserve four
+distinct images and non-ASCII text. All five frozen lifecycle assertions pass:
+invalid Source/no restart, failed replacement rollback/recovery, committed
+stream/nonstream replacement, cancellation/reuse and failed-startup cleanup.
+Child outcomes are exactly `[0, 23, 0, 0, 23]`; the two injected exit-23 failures
+are required rollback/cleanup evidence, not successful starts.
+
+Remaining trust limits are explicit. Existing guest OS/kernel/Python/util-linux
+are trusted prerequisites; a measured venv and frozen lock are not an
+archive-attested Python distribution. Copied Go caches remain mutable trusted
+setup under the locked-module/offline model; the root reused their expected
+post-lane state without resetting or claiming seed equality. Three optional
+Antigravity updater attempts were refused at private proxy `127.0.0.1:1`,
+not successful external requests. The engine-only empty-object profile remains
+a test supplement, not generated product capability. Identical diagnostic
+binary hashes across these two runs do not establish cold-cache or
+four-platform production-release reproducibility.
+
+The separate 338-product-consumer private-loopback run belongs to historical
+head `7e4412c94c54b2fc7855b9b29f9a317d1bc94f82`, not an executed final-head
+test. Its runtime Python, four runtime/release-guard/catalog/live-resolution
+test files and dependency locks remain unchanged. Finalization integrates only
+landed master and updates this assessment; it does not repoint the frozen
+fixture. The landed presentation row `MH-SRC-DELETE-002` is checked by the
+pure catalog consumer, with no peer UI edits or new scenario allocation.
+That finalization was subsequently reviewed with the configured-storage finding
+above. Fresh exact-head CI and a clean Codex review remain mandatory.
+
+## Completed source-only implementation
+
+The source-only decision was recorded at integration `a3065a7d1`; the later
+xAI and Kimi clarifications were read from integration heads
+`3d0cba9e622fe3e4af706bb9073684e0b3d9b038` and
+`871ce9d94f9f9c02e9cf6c8d8b5e205949bf8727`. The lane does not author edits to
+the shared plan; the independent-delivery directive authorizes replaying the
+six specified root-owned documentation commits into this Avibe branch.
+
+The maintained home is `patches/cliproxyapi/`. Its patch includes the Go tests;
+the small apply/test recipe validates the exact base, frozen catalogs, locked
+modules, Go version, changed-file inventory and file hashes. The revised recipe
+also binds the complete immutable Avibe fixture and imported recipe identity.
+The fixture is an exact tracked commit export, not mutable current-worktree
+imports; dirty exports fail before and after execution. A build receipt
+binds the wire-tested binary to those inputs and the patch digest. It refuses
+dirty source on apply, unrelated candidate edits, stale binaries, and hosts
+without the verified egress-isolation mechanism.
+
+Implemented ownership:
+
+- Shared native-representation passthrough preserves the prepared target,
+ without suffix, for Messages, Chat and verified Responses aliases.
+- Kimi native fields inside a Chat envelope are detected from original
+ `thinking.type`/`thinking.effort`; only the legacy effort alias is removed.
+ Future values, type-only input and prepared-target normalization survive.
+ Keep-only/legacy-only input still uses conversion, and suffix wins.
+- Explicit disable is applied before capability gating/summary activation.
+ Unknown/user-defined and configured missing-metadata conversions receive
+ the original source payload. Known positive conversions still validate.
+- xAI's post-translation catalog-only effort deletion is removed, along with
+ its single-use helper. `stop` removal, payload overrides/filters, tool choice,
+ schemas, replay and image handling remain. A focused final-egress scan of
+ Claude/Codex/OpenAI-compatible/Kimi found no equivalent additional catalog
+ gate; Claude's forced-tool-choice removal remains a tested protocol rule.
+- Exact selected-credential model snapshots and every registration producer
+ are unchanged, including the existing Chat conversion hint. No capability
+ or `UserDefined` claim is fabricated.
+
+### Patched three-protocol positive-intent matrix
+
+The K/KN/U/L/E profiles and notation are defined in the baseline section
+below. Both stream modes agree in all cells. E is a supplementary engine-only
+empty-object registration, not a shape fabricated by Avibe's writer.
+
+| Ingress -> upstream | K | KN | U | L | E |
+| --- | --- | --- | --- | --- | --- |
+| Messages -> Messages | A(max) | A(max) | A(max) | A(max) | A(max) |
+| Responses -> Responses | R(xhigh) | R(xhigh) | R(xhigh) | R(xhigh) | R(xhigh) |
+| Chat -> Chat | C(xhigh) | C(xhigh) | C(xhigh) | C(xhigh) | C(xhigh) |
+| Messages -> Responses | R(xhigh) | R(max) | R(max) | R(high) | R(max) |
+| Messages -> Chat | C(high) | C(high) | C(high) | C(high) | C(max) |
+| Responses -> Messages | A(max) | A(xhigh) | A(xhigh) | A(high) | B(31999) |
+| Responses -> Chat | C(high) | C(high) | C(high) | C(high) | C(xhigh) |
+| Chat -> Messages | A(max) | A(xhigh) | A(xhigh) | A(high) | B(31999) |
+| Chat -> Responses | R(xhigh) | R(xhigh) | R(xhigh) | R(high) | R(xhigh) |
+
+Explicit disable now reaches D, R(none), or C(none), respectively, in every
+cell of all nine directions and five profiles. Native absent reasoning
+remains absent; native future levels, auto, summaries and budgets preserve
+their prepared representation. Cross-protocol defaults remain conversion
+ownership: Messages/Chat -> Responses inject `medium`; the narrow profile
+maps Messages-origin default to `low` and still rejects the Chat-origin
+default. Missing catalog metadata no longer strips the translated default.
+There is no new native default or upstream capability promise.
+
+Unresolved model info and actual `UserDefined=true` also preserve native
+prepared payloads, as directly asserted in policy tests. Their genuine
+conversions retain capability-free conversion, now source-aware. Configured
+unknown rows remain `UserDefined=false`: the missing-metadata branch is an
+explicit boundary policy, not a changed registration claim.
+
+### Historical macOS and earlier-recipe evidence
+
+This section preserves superseded validation stages; the exact second-round
+Linux recipe acceptance is recorded separately above.
+The initial results came from the earlier macOS wildcard-loopback envelope.
+They are source behavior observations, not sufficient evidence of test-owned
+listener isolation or the newly enforced fixture receipt closure. The Linux
+Go/build rerun passed. Wire passed all 380 policy, 24 identity and three image
+cases before its watcher-only replacement failed; cancellation/reuse did not
+execute. These partial results are not complete wire acceptance.
+The corrected lifecycle rerun subsequently passed all three phases, including
+all original matrix/identity/image cases, real child replacement and failed
+replacement rollback/recovery, invalid Source refusal, cancellation/reuse and
+failed-startup cleanup. Each phase's original parent receipt has twelve blocked
+outside attempts, zero sentinel connections, unchanged complete inputs/outer
+mounts, and reaped processes/removed rootfs. Three normal children exited zero;
+the two deliberately failing children exited 23 as asserted by the consumer.
+The policy and integration artifacts retain their original complete hashes.
+The revised fixture/parent/probe/connection pure suite passes 225 cases under deny-all
+network. Actual no-network and private-loopback probes pass with zero outside
+sentinel connections; a deliberate nonzero command retains a failed terminal
+receipt. Original failed probe evidence remains preserved. These probes are
+not full engine acceptance or a shipped repair.
+
+- The maintained Go recipe passes shared thinking/provider tests,
+ `internal/modelconfig`, selected-model helpers, `sdk/cliproxy/auth`, existing
+ thinking/summary conversion cases, and the full executor package.
+ Superseded strip/clamp/native-rejection assertions were replaced explicitly;
+ genuine positive conversions, Gemini-family constraints and suffix tests
+ remain. No tests were skipped to get this result.
+- The real HTTP matrix has 380 cases: 378 successful one-capture requests and
+ two expected conversion-only 400s with zero upstream requests. Full endpoint,
+ upstream model, selected fake key, non-ASCII content, reasoning fields and
+ cross-Source exclusion are checked. Generated Avibe registration, origin/key
+ replacement via the former config-watcher fixture, streaming, cancellation
+ and reuse passed only in that historical envelope.
+- Actual manager + Claude HTTP tests distinguish two Sources with the same
+ alias/upstream name but different metadata, then replace one key/snapshot.
+ Fake subscription tests cover Claude/Codex HTTP, Codex WebSocket, Kimi
+ Messages delegation, Kimi native/legacy Chat and xAI Responses. xAI's final
+ egress matrix has 80 cases; Kimi's native/legacy matrix has 40. They use
+ rejecting transports, not provider accounts; the old OS loopback wildcard
+ is not evidence of test-owned listener enforcement.
+- 24 additional actual-engine requests preserve full long UTF-8 identities
+ beyond 16 KiB, including identical long heads with distinct tails and a
+ route-only model, on all three API-key protocols and both stream modes.
+ Registration and egress assertions compare the full strings/UTF-8 bytes.
+- Three sequential ~42 MiB native requests, each containing four distinct
+ valid synthetic RGB PNGs, preserve every base64 image and the non-ASCII
+ text. Only the existing mock's receive budget is raised to 48 MiB during
+ these tests. Normal envelope/cache transformations remain allowed; exact
+ image/text data is compared independently. This closes the engine seam,
+ not a duplicate gateway-framing test.
+- The patch applies cleanly to a second exact-base local checkout. A second
+ diagnostic build there produces the same binary digest; both builds use the
+ same isolated caches, so this is not a cold-cache or production release proof.
+ All test
+ engines and mock threads are stopped/reaped; no installed engine or backend
+ was started. The source-only PR/CI/review delivery gates and production
+ release builds are not claimed here.
+
+Maintained commands are the `apply`, `test`, `build`, and `wire` phases in
+`patches/cliproxyapi/README.md`. Evidence stays in task-owned scratch, not
+committed developer-machine paths. A successful mock capture proves
+preservation/routing, not that a real provider accepts a future effort value.
+
+## Historical macOS diagnostic inputs and evidence limits
+
+The Darwin binary hashes in this table belong only to the initial macOS
+diagnosis and candidate. They are not Linux build identities.
+The frozen engine base, patch, fixture and catalog declarations remain inputs
+to the separately recorded second-round acceptance. Neither table attests
+execution of the newer configured-storage correction.
+
+| Input | Identity |
+| --- | --- |
+| Avibe task base, config writer, guard, and mock inspected | `76e269c9a9dfd3a6286ce0da81b77316ca4be38a` |
+| Engine repository | `router-for-me/CLIProxyAPI` |
+| Packaged engine version | `v7.2.149` |
+| Engine source fetched, read, tested, and compiled | `2a6b87aca083a5bf498ac1f68a1b636c500d7aaa` |
+| Historical Go toolchain | `go1.26.4`, matching the pinned release workflow |
+| Historical local build target | `darwin/arm64`, `CGO_ENABLED=0`; diagnostic binary, not a release reproduction |
+| Historical unpatched Darwin binary SHA-256 | `f8b3a7bfe5f8be7d48a1f60506ae579a9e37877696d9f813bf6143f5ed4b5887` |
+| Inactive candidate patch SHA-256 | `f55a3731e82837ed92d8943e97ef6d6521d21a78d3026a65c97b0950c3c494be` |
+| Historical patched Darwin binary SHA-256 | `54af78bd25e4bd81cf383e91337c5927506d943ddf0f5458b3a98a0789d590df` |
+| Patched 380-record HTTP matrix SHA-256 | `71b15e16af5cde8f022bb51dc41507506f6a9d93e8e75830cd927f6e8f26fa15` |
+| Long-ID and multi-image evidence SHA-256 | `cb807fd737c5294cc52c101a5a2805c96b661e0e45f9c8e458b8ef15c25a0ccb` |
+| Embedded `models.json` SHA-256 | `b19b2655a4f294605d3a347be16e67ef6ea776d70cedbd69c36629f3dbb945d9` |
+| Embedded `codex_client_models.json` SHA-256 | `a044aa222836b32091fdf4c9c34030443cb8717dea65db875cf705406c332fd6` |
+| Engine `go.sum` SHA-256 | `b29392b1f713b238d6232af2f8fd09e28b7f5d221847ddccf0fc35682a9b29bd` |
+
+The initial baseline checkout remained clean after diagnosis; the source-only
+candidate is now maintained as an exact-base patch and tested in task-owned
+checkouts. Existing temporary checkouts were preserved. No installed
+engine, engine-internal user state, account credentials, or user Avibe process
+was used.
+
+Source references below are relative to the exact engine checkout unless
+explicitly labeled Avibe. This assessment does not substitute upstream HEAD,
+downloaded release bytes, or a refreshed online catalog for the fixed source.
+It does not claim that the currently installed binary was exercised.
+
+## Registration and execution ownership
+
+Avibe `vibe/model_hub_runtime/config.py:67-147` writes the union of discovered
+and routed model IDs, preserving `name == alias == upstream model` and each
+Source prefix. Nonempty Source reasoning levels are registered strongest-first.
+An absent entry emits no `thinking`. OAuth bindings use auth files instead of
+YAML API-key values.
+
+The engine has two different model consumers:
+
+1. `sdk/cliproxy/service_models.go:671-790` builds public model registrations.
+ Native configured API-key rows are initially `UserDefined=true`; Chat
+ compatibility rows are `false` and get synthetic `[low, medium, high]`
+ thinking metadata when omitted.
+2. `sdk/cliproxy/auth/api_key_model_capabilities.go:112-279` builds and binds a
+ private snapshot for the selected credential, alias, and actual upstream
+ model. `internal/modelconfig/model_info.go:13-26` resolves the suffix-free
+ upstream name against the static catalog, overlays explicit metadata, and
+ always sets `UserDefined=false`. Chat compatibility also supplies the
+ synthetic level list here. Thus a configured *unknown name* does not take
+ the unknown/user-defined thinking path during ordinary API-key execution.
+
+`internal/runtime/executor/helps/model_capabilities.go:18-27` consumes that
+selected snapshot. The Claude, Codex HTTP/SSE/WebSocket, and OpenAI-compatible
+executors call it after request translation and before final payload rules and
+transport. The selected snapshot must remain attached to the exact credential
+and upstream model; changing the public registry flag alone cannot repair this.
+
+OAuth attempts ordinarily use the registry lookup path instead of the configured
+API-key snapshot. A shared thinking fix therefore needs both paths tested.
+No OAuth lifecycle, credential refresh, prefix, alias, model-selection, fallback,
+or credential-replacement change is required.
+
+## Pinned policy and why configuration cannot solve it
+
+`internal/thinking/apply.go:196-349` does the following:
+
+- Unknown models (`modelInfo == nil`) and actual `UserDefined=true` rows bypass
+ `ValidateConfig` but still go through extraction and a provider applier.
+- Known/non-user-defined rows with `Thinking == nil` lose recognized thinking
+ controls and summary controls through `StripThinkingConfig`. The comment that
+ describes this case as passthrough is inconsistent with the implementation.
+- With metadata, it extracts suffix intent first, then original source intent
+ for configured models, then translated-body intent.
+- `mapConfiguredHighIntent` can map `max`/`xhigh` before validation when the
+ format labels differ or the model type differs from the protocol family.
+- `ValidateConfig` then normalizes, validates, and clamps, and the provider
+ applier can make further representation changes.
+
+`internal/thinking/validate.go:38-195` distinguishes provider *families*, not
+identical wire protocols. OpenAI Chat and Responses are one validation family,
+but require different field shapes. Conversely, Responses ingress is
+`openai-response` and its executor target is `codex`: those label differences
+trigger configured high-intent mapping despite native Responses reasoning.
+Chat compatibility's model type is `openai-compatibility`, which causes
+clamping even on Chat-to-Chat requests.
+
+The validator can reject native out-of-range budgets or unsupported levels;
+convert a budget to the nearest registered level; replace `auto`; and change
+`none` to `support.Levels[0]` when its flags do not allow disabling. Avibe emits
+levels strongest-first, so that last fallback can enable *high* effort.
+
+Empty `thinking: {}` is not a disable policy or a complete bypass. It creates
+a non-nil zero-valued support object: native Claude `auto` became disabled in
+the baseline, and Claude adaptive `max` became a numeric budget. An arbitrarily
+wide list/range would be a capability claim, still change representation, and
+fail for future fields/levels.
+
+There is no configuration-exposed `UserDefined` flag. `is-compat` handles
+history/signatures or Codex multi-agent compatibility, not this validation.
+Payload default/override/filter rules run too late to prevent validation
+errors and cannot generically preserve arbitrary caller values. Suffixes
+encode an explicit override and still undergo capability policy. Plugin
+normalizers cannot reliably bypass the later bound-model check; enabling a
+plugin is not a configuration-only repair.
+
+## Baseline Model Hub protocol matrix
+
+These tables cover all nine combinations of the three Model Hub wire
+protocols. Each cell was measured through both streaming and non-streaming
+HTTP ingress into the compiled, unmodified engine. Both variants agreed for
+the reported reasoning fragments.
+
+Fixture profiles:
+
+| Profile | Actual model registration |
+| --- | --- |
+| K | Known supported upstream name, omitted configured thinking: `claude-opus-4-6` for Messages; `gpt-5.4` for Responses/Chat |
+| KN | Known static row with nil thinking: `claude-3-5-haiku-20241022`; using it on non-Claude mock routes deliberately tests static lookup, not real vendor model support |
+| U | Unknown configured upstream name `lane-d-custom`, omitted thinking |
+| L | Unknown name `lane-d-narrow`, explicit fixture levels `[high, low]` |
+| E | Unknown name `lane-d-empty`, explicit empty `thinking: {}` |
+
+For Chat targets, omitted thinking in K/KN/U becomes the engine's synthetic
+`[low, medium, high]`. These are diagnostic fixtures only, not proposed
+registration claims.
+
+### Positive explicit intent
+
+Messages input uses adaptive `output_config.effort: max`. Responses and Chat
+inputs use their native `xhigh`; Responses also requests `summary: auto`.
+`A(max)` means adaptive Messages thinking and `output_config.effort: max`;
+`R(xhigh)` and `C(xhigh)` mean native Responses/Chat effort fields. `B(n)`
+means Messages `enabled` with `budget_tokens: n`. `S` means thinking controls
+stripped. `400` means no upstream request.
+
+| Ingress -> upstream | K | KN | U | L | E |
+| --- | --- | --- | --- | --- | --- |
+| Messages -> Messages | A(max) | S | S | 400 | B(63999) |
+| Responses -> Responses | R(xhigh) | S | S | R(high) | R(xhigh) |
+| Chat -> Chat | C(high) | C(high) | C(high) | C(high) | C(xhigh) |
+| Messages -> Responses | R(xhigh) | S | S | R(high) | R(max) |
+| Messages -> Chat | C(high) | C(high) | C(high) | C(high) | C(max) |
+| Responses -> Messages | A(max) | S | S | A(high) | B(31999) |
+| Responses -> Chat | C(high) | C(high) | C(high) | C(high) | C(xhigh) |
+| Chat -> Messages | A(max) | S | S | A(high) | B(31999) |
+| Chat -> Responses | R(xhigh) | S | S | R(high) | R(xhigh) |
+
+Cross-protocol requests into Messages carry `thinking.display: summarized`
+when the source summary semantics request it. Responses targets preserve the
+source summary where represented. The numeric budgets above also reflect
+Claude's post-conversion `max_tokens` relation; they are not metadata-neutral
+passthrough.
+
+### Explicit disable
+
+Messages input uses `thinking.type: disabled`; the other inputs use native
+`effort: none`. `D` means Messages disabled; R/C show the actual effort.
+
+| Ingress -> upstream | K | KN | U | L | E |
+| --- | --- | --- | --- | --- | --- |
+| Messages -> Messages | D | S | S | D | D |
+| Responses -> Responses | R(low) | S | S | R(high) | R(none) |
+| Chat -> Chat | C(low) | C(low) | C(low) | C(high) | C(none) |
+| Messages -> Responses | R(low) | S | S | R(high) | R(none) |
+| Messages -> Chat | C(low) | C(low) | C(low) | C(high) | C(none) |
+| Responses -> Messages | D | S | S | D | D |
+| Responses -> Chat | C(low) | C(low) | C(low) | C(high) | C(none) |
+| Chat -> Messages | D | S | S | D | D |
+| Chat -> Responses | R(low) | S | S | R(high) | R(none) |
+
+### Absence and additional native shapes
+
+No native reasoning input remains absent on all three same-protocol routes,
+for every profile. Cross-protocol Messages/Chat -> Responses injects the
+translator's `medium` default before thinking policy. K/E retain it; KN/U
+strip it; L maps the Messages-origin default to `low` but rejects the
+Chat-origin default with 400. All other absent-input cross routes remain
+without reasoning controls. The patched matrix retains conversion defaults
+while removing the missing-catalog stripping step.
+
+Additional measured native cases:
+
+- Messages K accepts budget 4096, rejects budget 256, and changes enabled
+ thinking with no budget to budget 63999. L maps both budgets to adaptive
+ `low`; E changes enabled-without-budget to disabled. KN/U strip all of them.
+- Responses K maps `auto` to `medium`; L maps it to `low`; KN/U strip it.
+ Chat K/KN/U map `auto` to `medium`; L maps it to `low`.
+- Future explicit effort `ultra` produces 400 in K/L for Messages/Responses
+ and K/KN/U/L for Chat. KN/U Messages/Responses strip it. E forwards it.
+- Summary-only Responses is stripped for KN/U and retained for K/L/E.
+ Messages adaptive `display: omitted` is stripped for KN/U and retained for
+ K/L/E. Native Chat `reasoning.exclude: true` survives these fixtures.
+
+### Unknown/user-defined versus configured-unknown source paths
+
+The HTTP matrix intentionally exercises real config registration. The
+following separate source behavior must not be mislabeled HTTP coverage:
+
+| Selected model info | Same-protocol policy | Cross-protocol policy |
+| --- | --- | --- |
+| `nil` model info | No catalog validation; extract/apply native controls, so not guaranteed byte preservation | Translate then apply capability-free representation; original source handling differs from the configured path |
+| Actual `UserDefined=true` | Same as nil, even if metadata exists | Same unvalidated branch; provider appliers still convert and rewrite fields |
+| Configured unknown, `UserDefined=false`, `Thinking=nil` | Strip recognized controls | Strip translated controls |
+| Non-user-defined with levels/range | Validate, map, clamp, or reject | Convert plus validate/map/clamp |
+
+`applyUserDefinedModel` receives the already translated body and does not
+receive `sourceBody`; its extraction also lacks the `openai-response` alias
+handled by `extractSourceThinkingConfig`. Merely redirecting every configured
+row into that branch can therefore lose source intent or rewrite a compatible
+native field. Existing upstream conversion tests use synthetic registered
+user-defined rows; their behavior does not prove configured API-key behavior.
+
+### Subscription executor qualifications
+
+- Claude OAuth reaches the Claude shared request path; Codex OAuth reaches the
+ Codex HTTP/SSE/WebSocket paths. Same-protocol policy must apply to their
+ registry-selected models without changing credential handling.
+- Kimi selects Claude Messages when ingress is Claude, delegating to
+ `ClaudeExecutor`; otherwise it uses Chat transport but its thinking applier
+ converts legacy `reasoning_effort` into native `thinking.type/effort`.
+ Do not equate this Kimi dialect with ordinary Chat reasoning based only on
+ the HTTP endpoint. Its hardcoded origin requires a rejecting test transport
+ mapped to loopback for source tests.
+- xAI uses the Responses representation and embeds the Codex thinking applier,
+ while passing `xai` as its thinking format. Its Responses wire alias must be
+ assessed explicitly, not inferred from the executor identifier.
+- Gemini/Antigravity/Interactions are not Model Hub's three public protocol
+ choices. Keep their existing conversion behavior; run their existing
+ conversion regression tests for shared-code changes.
+
+No subscription/OAuth wire fixture was part of the initial baseline.
+The source-only acceptance above now includes fake-auth actual executor
+HTTP/WebSocket tests; it never exercises real subscription accounts.
+
+## Approved source and registration boundary
+
+The orchestrator approved and the maintained patch implements this boundary:
+
+1. In the shared thinking entry point, distinguish identical reasoning wire
+ representations from provider families. Messages->Messages and Chat->Chat
+ preserve native controls; `openai-response`/`codex` (and the verified xAI
+ Responses target) share the Responses reasoning representation. Chat and
+ Responses do not. Keep Kimi's native conversion explicit.
+2. For same-representation requests without an explicit model suffix, return
+ the current target payload without catalog-driven extraction/reapplication,
+ stripping, level mapping, or budget validation. Preserve normalizers'
+ deliberate changes: do not restore the whole original request or undo
+ model, protocol, credential, payload-rule, or signature handling.
+3. Extract explicit original-source disable before capability gating. Keep
+ suffix precedence. An explicit `ModeNone` must reach the provider's native
+ disable representation without falling back to a catalog level or being
+ stripped. Reuse the existing provider disable writers, moving this case
+ before their capability guards as necessary. Skip summary activation after
+ explicit disable. This addresses all nine disable rows, not only native
+ requests.
+4. For genuine conversion with no thinking metadata, reuse a clearly named
+ unvalidated conversion path and provider-compatible writers. Pass the
+ source payload/format into it so source intent is not re-extracted from the
+ wrong target shape. A nil support pointer is missing knowledge, not an
+ instruction to delete caller fields. Do not forge `UserDefined=true` or a
+ broad `ThinkingSupport` merely to reach this path.
+5. Keep known-metadata positive cross-protocol conversion, summary visibility,
+ protocol constraints (including forced Claude tool choice), and suffix
+ representation logic. A native passthrough does not disable executor
+ protocol checks or imply that an upstream will accept every request.
+
+Engine edit surface: `internal/thinking/apply.go`, the relevant provider
+appliers, source-payload plumbing in executor helpers, the independently
+approved xAI final-egress gate, and tests. `validate.go` is unchanged.
+Actual executor tests cover both later xAI sanitization and Kimi's native
+representation in a Chat envelope; an early return alone was insufficient.
+
+Registration policy: leave Avibe's real `model_reasoning_efforts`, Source
+prefixes, aliases, routed IDs, and persisted shapes unchanged. Do not synthesize
+levels, flags, ranges, or capability claims. Do not remove existing metadata.
+The upstream's existing Chat fallback remains a conversion hint in this
+minimal proposal; removing that fallback from both registration owners is a
+separate scope decision, not necessary to preserve native requests. It must
+not become a native-request allowlist. No new persistent provenance model,
+config toggle, plugin, or custom-model flag is proposed.
+
+## Concrete validation route
+
+Baseline completed on 2026-09-09 +08:
+
+- Existing `internal/thinking/...` and `internal/modelconfig` tests passed.
+- Existing `test` package cases matching `^TestThinking` passed, including
+ body/suffix, user-defined, adaptive Claude, and other provider conversions.
+- The unmodified `cmd/server` compiled with locked modules.
+- 380 requests traversed real engine HTTP ingress, registration/auth selection,
+ translators, executors, and a real loopback mock upstream. 358 returned 200
+ with exactly one capture; 22 returned 400 before upstream admission. These
+ counts describe pinned behavior, not acceptance success.
+- Every captured request had the expected endpoint, exact upstream model,
+ selected Source's fake outbound key, and no inbound gateway bearer. No
+ request reached a different Source mock. Every input included non-ASCII
+ text. Raw reasoning fragments were compared across stream modes.
+
+The task-owned baseline harness and raw results are retained in scratch
+(SHA-256 `8d31f89e6cb9167c7056e9acbc5539efc5c978e02ebbb9d524370e1cc96021ad`).
+The harness SHA-256 is
+`2d9855ac52194e7164ef0541b3bd8001f0d8e094cfd4316569efa7afdbdc64d3`.
+The maintained entry point is now `patches/cliproxyapi/verify.py`, using
+`wire_matrix.py` and the repository's existing mock.
+
+Maintained hermetic construction (revised Linux lane and independent root
+reruns passed):
+
+1. Fetch only the exact engine commit into a new task directory. Give Go its
+ own HOME, TMPDIR, module/build caches, and `GOENV=off`. Use the exact
+ toolchain and `-mod=readonly`; dependency downloads are preparation, not
+ upstream account probes.
+2. Export the complete frozen Avibe commit and verify its tree, archive and
+ path-independent source digest. Reuse that export's stdlib-only
+ `tests/e2e/drivers/mock_llm_upstream.py`, with one ephemeral loopback
+ listener per protocol. Generate fake-key config in a test-owned home.
+ Use frozen `CLIProxyEngineAdapter.sync_sources` and `EngineSupervisor`.
+ The existing constructor seams select only the preverified diagnostic binary,
+ task environment/log and fresh private port, never an installed runtime.
+ Real state validation, routing/idle barrier, transaction, atomic writer,
+ health checks and owned-child stop/start remain the product's responsibility.
+3. Use the approved temporary Linux mount/network/PID/chroot envelope,
+ making mounts private before binding. Keep source, frozen fixture, recipe
+ and toolchain read-only, expose only invocation output and the separate
+ task caches for writes, hide guest/user homes and namespace handles,
+ close inherited descriptors, then drop
+ UID/GID/groups/capabilities and set no-new-privileges. Compile with networking
+ disabled; dynamic Go listeners, engine and replacement mocks run together
+ on the namespace's private loopback. No veth or host network is added.
+4. Require actual IPv4/IPv6 outside-sentinel negatives and private positives,
+ plus failure/process/mount cleanup receipts before the full suite. Parent
+ receipts are exclusively opened outside child mounts before execution;
+ preflight reaches an unlinked supervisor channel closed before candidate
+ launch. Never trust a later child-writable probe file. The earlier macOS
+ localhost wildcard is retired; its remaining pure/compile path denies all
+ egress. Rejecting executor transports and a dead proxy are complementary
+ checks, not OS isolation. `--local-model` alone is insufficient.
+5. Assert native reasoning fragments, required conversion results, explicit
+ negatives, no intent injection on native absence, correct model/prefix/
+ credential replacement, non-ASCII preservation, response streaming, and
+ cancellation. Stop and reap the child and all mock threads in `finally`.
+ Consume each returned supervisor connection, including changed port/token.
+ Actual-child failure regressions verify Source validation before restart,
+ replacement rollback/recovery and failed-startup cleanup. Preserve all
+ generated registrations; the labeled engine-only empty profile is applied
+ only in the process seam before each launch.
+
+The first Linux wire fixture depended on direct-file watcher reload after
+atomic configuration replacement and timed out. The pinned watcher watches
+the file itself; a raw inotify event trace was not recorded. This is a separate
+diagnostic limitation, not an established Avibe Source replacement regression:
+the frozen product explicitly restarts its owned child. The approved fixture
+correction consumes that lifecycle without modifying the watcher, extending
+deadlines, writing in place, or mocking successful restart.
+
+The promoted maintained engine tests cover:
+
+- Shared policy tests for nil model info, user-defined, known nil support,
+ explicit empty/narrow/ranged support, source/target aliases, suffix-vs-body
+ precedence, summary visibility, `none`, `auto`, unknown future levels,
+ budget 256/4096, and missing intent.
+- Actual manager+executor tests with two credentials advertising the same
+ alias/upstream name but different metadata. Require exact selected model
+ info and auth, including API-key replacement. Existing fake executors are
+ supplementary assertions, not wire evidence.
+- HTTP matrix above for both stream modes, plus suffix overrides and truthful
+ configured negative support fixtures. Existing static nil support and an
+ explicit caller disable remain distinct.
+- Subscription tests use fake auth data and injectable loopback transports.
+ Include Claude, Codex HTTP/WebSocket, Kimi dialect selection, and xAI; reject
+ all non-test destinations. Do not execute login, refresh, browser, or cloud
+ account flows.
+- Build `cmd/server`, run conversion/registration/auth/executor tests, and
+ repeat the matrix with actual generated Avibe Source registrations. The
+ empty-object engine-only profile is labeled separately, not claimed as an
+ Avibe-generated capability. Long-ID and ~42 MiB image consumers close the
+ additional engine seams requested during integration.
+
+Resources after candidate and integration checks: approximately 3.5 GiB of
+task-owned source, Go toolchain/modules/cache and locked Python dependencies;
+an approximately 80 MiB unstripped diagnostic binary.
+Build/test concurrency was `GOMAXPROCS=2`, `-p=1`, with a 1536 MiB soft Go
+memory limit. The final wire child uses the same limits; the initial baseline
+used a 512 MiB soft limit.
+The Go limits are not OS memory caps. Build all four release targets
+sequentially or on bounded native runners, not concurrent local full builds.
+
+## Maintained source, reproducible builds, and publication order
+
+There is no authorized public fork or published patched source today. The
+maintained candidate home is the Avibe-owned source/test patch and recipe
+under `patches/cliproxyapi/`, recording the
+exact upstream base, patch digest, dependency lock, and build-input receipt.
+Apply it only to a fresh task-owned upstream checkout. The temporary checkout
+is execution state, not the permanent source of truth. A public upstream
+contribution may later become the maintained source home with authorization.
+Do not silently create or select another organization's repository.
+
+Reproducibility requires more than `source_sha`:
+
+- Pin Go `1.26.4`, `go.sum`, the exact base plus patch, OS/architecture, CGO
+ setting, compiler/SDK or Linux build-image digest, build flags, and metadata.
+- Freeze both model catalogs. The pinned upstream release workflow runs
+ `.github/scripts/refresh-model-catalogs.sh`, which fetches
+ `router-for-me/models` **main** before compilation. Therefore the source
+ SHA alone does not reproduce upstream release catalog bytes. Use the
+ committed catalog bytes for the candidate, or pin a separately recorded
+ catalog commit and hashes. Never silently refresh HEAD during acceptance.
+- Use `-trimpath`, a fixed commit-derived build date, and deterministic archive
+ entry order/owners/mtimes and gzip metadata. Repeat builds in two fresh
+ directories and compare binary/archive hashes before claiming bit-for-bit
+ reproducibility.
+- Match Avibe's four platforms: Darwin arm64/amd64 and Linux amd64/arm64.
+ The existing release uses CGO-enabled hosted builds and GLIBC 2.17-baseline
+ Linux assets. The CGO-disabled diagnostic build does not prove those asset
+ contracts. Preserve the selected production build variant unless a separate
+ platform/packaging decision changes it.
+
+Release dependency order:
+
+| Stage | Required result | Authority |
+| --- | --- | --- |
+| Source/tests | Reviewed local patch, exact build receipt, passing wire matrix | Orchestrator source-scope approval; no publication implied |
+| Source provenance | Either accepted upstream commit/release, or an explicitly authorized maintained-source and provenance contract | External submission/source-home decision; not authorized in this lane |
+| Release assets | All four verified archives, extracted-binary hashes, sizes, sidecars, matching manifest copy | Explicit tag/release/asset publication authority |
+| Availability | Read back published bytes; run manifest-keyed verification and preserve recoverable backup | Authorized release workflow; guard remains enforced |
+| Avibe dependency pin | Update packaged manifest and frozen tests to the actually available, truthful release | Orchestrator integration/normal PR gates after asset availability |
+| Installation/runtime | Existing lifecycle converges installed dependency and later starts/replaces the managed process | Separate owner authorization; not part of source implementation |
+
+Avibe's guard (`scripts/model_hub_engine_release_guard.py:94-185`) requires
+`source == router-for-me/CLIProxyAPI`, the matching upstream source URL, a
+matching `vX.Y.Z` release tag, four exact asset names, and Avibe-owned release
+URLs. `fetch-source` verifies upstream release bytes against the manifest;
+the scheduled workflow backs up and restores only the exact manifest's bytes.
+It is not a local-patch build or source-provenance system.
+
+The compatible delivery route without changing this guard is an authorized
+upstream contribution/release followed by verified mirroring into an
+Avibe-owned release and then an Avibe pin update. If shipping an Avibe-only
+patch becomes necessary, source identity/build provenance and maintenance
+ownership require a separate explicit decision and equally strong guard
+contract. Relabeling patched bytes as upstream, inventing a fork URL, weakening
+verification, or pinning assets before publication is not an option.
+
+This is a real release-authorization/provenance blocker for shipping, not a
+blocker to approved local source/test implementation. This assessment does not
+declare delivery gates passed or claim the Model Hub issue is fixed.
diff --git a/patches/cliproxyapi/README.md b/patches/cliproxyapi/README.md
new file mode 100644
index 000000000..6c21a40e5
--- /dev/null
+++ b/patches/cliproxyapi/README.md
@@ -0,0 +1,651 @@
+# Inactive CLIProxyAPI native-intent candidate
+
+This directory is the maintained source home for a **local, inactive patch**.
+It does not change Avibe's manifest, installed engine, configuration, release
+guard, or runtime lifecycle. A passing test is not a shipped engine repair.
+
+Base: `router-for-me/CLIProxyAPI` `v7.2.149`,
+`2a6b87aca083a5bf498ac1f68a1b636c500d7aaa`. Do not substitute upstream HEAD.
+The patch includes its Go policy and consuming tests; the temporary engine
+checkout is not the maintained source of truth. See the English assessment in
+`docs/plans/model-hub-engine-intent-policy-assessment.md`.
+
+## Contract
+
+- Native Messages, Chat and verified Responses representations keep their
+ prepared reasoning fields without a suffix, independent of catalog metadata.
+- Native Kimi objects carried by Chat are recognized from original
+ `thinking.type`/`thinking.effort`; only the legacy `reasoning_effort` alias is
+ removed. Keep-only/legacy-only input still uses conversion. Suffix wins.
+- Explicit disable precedes capability gating and summary activation.
+ Missing metadata uses source-aware capability-free conversion; known positive
+ conversion constraints remain. No fake `UserDefined` or capability metadata.
+- xAI's duplicate catalog-based final-egress deletion is removed; its actual
+ protocol sanitization, payload rules, replay and tools remain.
+- All Source, prefix, alias, model, exact credential snapshot, OAuth and
+ replacement ownership remains unchanged, including the existing Chat hint.
+
+## Apply and verify
+
+After separate execution acceptance, use an explicitly authorized, already-running
+native AArch64 little-endian 64-bit Linux development guest with Git, Python 3.12,
+util-linux (`unshare`, `setpriv`), iproute2 and
+transient sudo. This recipe does not provision a guest or change packages,
+services, routes or Incus resources. Its macOS `sandbox-exec` path now denies
+all egress and is only for pure-source diagnostics. Executing the pinned
+Linux arm64 Go toolchain, including compilation, requires the Linux envelope;
+there is no macOS engine-build or network-suite fallback.
+
+Current boundary: **locally SOURCE-qualified seventh-round inactive source;
+final-byte qualification and a conditional LOCAL commit remain ahead**. Reviewed
+head `5abebf8375d1301fb8abf254e402ab0217efbcbf` received terminal review
+`5162069141` with writable host RNG finding `3974966709`. The circuit has
+nineteen originals across seven findings-bearing heads: twelve resolved,
+seven unresolved. Successful seventeen-job CI and CLEAN merge state are not
+a clean Codex verdict. The original four-file construction-only release
+produced lane 279-case focused/1,482-case complete checks (3.13/19.20 seconds),
+Ruff 0.4.9 and static/whitespace checks. Root independently inspected those
+bytes and passed 1,482 cases in 18.62 seconds before source acceptance and
+this final prose freeze. The later release permits one local commit only
+after its own final-byte gates; their outcomes belong in the external return,
+not a post-validation prose edit. Remote delivery, clean review, seven-thread
+closure, OS, merge and publication acceptance remain held.
+
+The preceding exact5abe source passed lane/root 1,457-case pure runs
+(18.32/17.34 seconds), Ruff 0.4.9 and static/whitespace checks before
+independent inactive-source acceptance and renewed review. Its earlier
+pre-final-prose checks passed lane 1,001 focused/1,457 complete and root
+1,457 complete cases. These are historical byte-bound results, not validation
+of this device subtraction.
+
+The existing installed-system device owner now admits only `/dev/null` and
+`/dev/zero`, retaining their exact character-device identities and descriptor
+custody. Neither `/dev/random` nor `/dev/urandom` is pinned or bound; a readonly
+label is not used as a claim of character-device confinement. Syscall-based
+randomness is unchanged. A diagnostic consumer requiring an absent RNG
+pathname lacks a startup prerequisite and must fail closed, without a new
+device, provider or fallback. Compatibility of every consumer is unproved.
+System/input NODEV remounts, private-rootfs custody, received-FD closure and
+capability drop remain companion source premises, not kernel evidence.
+Connected HOST regressions consume actual system pins through parent handoff,
+private bind/remount and success/partial-failure closure with task-only
+metadata and effect interception; they do not open real host RNG devices.
+
+The macOS helper now constructs default-deny policy. Only process-exec and
+process-fork are positive non-file operations; no Mach/XPC, POSIX/System V IPC
+or other service exceptions are granted. Finite file grants and explicit
+network/file denies remain; process authority does not grant a file path.
+The existing regular-file owner now binds reads to a no-follow, nonblocking
+single-link descriptor and rejects observed pathname/descriptor or metadata
+drift at admission and completion. Source digests and actual input/candidate
+reads reuse it; apply checks the complete source tree before patch writes.
+Unchanged single-link trees retain the same digest encoding. These checks
+reject preexisting hardlink aliases, not all future concurrent changes:
+trusted preparation/content custody throughout the diagnostic interval and
+the intended read-only mount boundary remain separate prerequisites, not an
+atomic snapshot guarantee.
+
+The candidate extends the existing namespace/storage owners, not the engine
+intent patch. Its Linux libc mount/proc-FD/overmount behavior, native ABI and
+seccomp installation/inheritance/keyring denial have NOT been executed or
+accepted. IPC separation and end-to-end privileged closure still need separate
+Linux evidence. No source-only test can establish those kernel properties.
+The macOS finite input policy's supported interpreter/system startup closure
+and positive/negative enforcement also remain UNMET. Do not execute the
+commands below on these bytes without the orchestrator's later release.
+
+The preceding fifth candidate, including the corrected synthetic ownership
+fixture, passed 335 focused HOST cases. Its pre-final-document input view
+passed the orchestrator's 1,420-case pure run. Final exact90 inputs separately
+passed lane/root 1,420-case runs and Ruff/static/whitespace qualification.
+Those results remain historical, not validation of the sixth correction.
+The proven HOST route used a hash-admitted, readonly 23-file view outside real homes,
+preserving relative layout, with files 0444 and directories 0555. A separate
+task-writable execution subtree, fresh task storage and an independent outer
+HOST policy denied network, production writes and all real-home reads/metadata.
+No home-input exception or installed-state change was needed.
+
+The lane's earlier complete run remains failed: 1,071 passed before documented
+preparation hit denied home-ancestor resolution. The earlier focused failure
+remains 120 passed/one failed on inconsistent synthetic GID metadata; the
+original collection failure exited 2 with zero tests. None is relabeled by
+the later input-layout or fixture correction. Pure passes establish only
+intercepted source consumers; exact90's inactive-source acceptance never
+established OS enforcement or acceptance of these new omissions. The emitted-program
+case contains 5,140 internal decode assertions in ONE test, not result rows
+or Linux execution.
+
+Historical fourth-round source `10b1` passed 1,190 pure cases, pinned Ruff 0.4.9
+and syntax/whitespace gates, including independent root execution. Historical
+scratch mechanism proof passed 51 HOST tests and executed 5,140 assertions
+decoding its actual 88-byte program; its stdout records a digest/count and
+51-test summary, not 5,140 individual result rows. Neither validates these new
+maintained bytes. Preserve both failed macOS attempts: the lane's nested route
+returned inner 71 (`sandbox_apply: Operation not permitted`) and outer 1;
+the root's later single-profile child returned -6 with empty streams and
+outer 1. No child access assertion passed. The root's earlier incorrect 0755
+assumption was corrected to the unchanged trusted Python's actual root-owned
+0775 mode; no installed permission was changed. No new macOS proof is claimed.
+
+Historical third-round boundary: the third reviewed head exposed configured user
+storage missing from pre-write protection. The orchestrator diagnosed the
+repeated isolation class and authorized only a bounded recipe/test/doc correction
+and pure validation. Independent inspection of the first 733-consumer correction
+then reproduced a remaining README preparation gap: source/state child aliases
+were not admitted before Git initialization or mkdir. The entry below now checks
+the complete fresh preparation plan before any write. The corrected local recipe
+passes 1,076 maintained pure consumers, pinned Ruff 0.4.9 and
+document/AST/whitespace gates. That exact snapshot subsequently received one
+bounded direct-sudo/context diagnostic and independent native original readback,
+under the assessment's supplementary source criterion. Its OLD Watch raw outer
+streams remain unavailable and complete original transport accounting is UNMET.
+No new privileged probes or Go/build/wire execution are released. The preceding
+second-round recipe genuinely passed 361 pure consumers and separate lane and
+independent orchestrator Linux test/build/wire runs. Those full source results
+remain acceptance of their exact earlier recipe, not these changed admission
+and caller-context paths. The Go patch and frozen inputs have not changed.
+The earlier watcher-only failure and all historical artifacts remain preserved.
+The still-earlier macOS wildcard-loopback runs are not isolation acceptance.
+No source tests or Avibe PR merge ship an engine repair.
+
+Set `engine_task` to an explicitly allocated, canonical, dedicated child of
+`/tmp` or `/var/tmp`, never either broad root. The privileged CLI rejects home
+layouts and aliases into `/home`, `/root` or `/Users` before setup.
+All writable-root consumers share one original-user storage model: passwd and
+effective HOME, fixed `.avibe`, `.vibe_remote`, `.codex`, `.claude` children,
+XDG config/cache/data/state/runtime, and AVIBE_HOME/CODEX_HOME/CLAUDE_CONFIG_DIR.
+Unset or empty overrides use defaults; XDG defaults are `.config`, `.cache`,
+`.local/share` and `.local/state` beneath effective HOME, with no runtime
+fallback. Relative, parent-traversing or malformed configured paths fail closed
+without printing their values. Home/broad roots and their ancestors remain
+forbidden; storage roots reject equality, ancestors, descendants and lexical
+or canonical aliases, including writable ancestors containing protected targets.
+The macOS diagnostic also excludes complete original passwd/effective homes
+and their lexical/canonical aliases, not merely product/configuration children.
+`sandbox_prefix(task, required_inputs=(...))` requires a finite explicit set of
+staged recipe/source/interpreter/system inputs outside those roots. Every
+grant, including sandbox-exec, `/dev/null` and system/tool inputs, goes through
+the same storage admission. Whole home/project/task ancestors and broad
+`/usr`, `/System` or `/Library` grants refuse. The default-deny policy permits
+only finite admitted reads, task writes and the two named process operations,
+denies network, and has no global
+read/metadata or unsandboxed fallback. Policy-construction tests are not
+sandbox enforcement or inherited-port confinement evidence; the startup
+input/operation closure remains an execution
+gate, not a reason to widen access.
+
+Begin from the invoking user's original environment, not `env -i`, a task HOME,
+or an already-sanitized sudo shell. Set `recipe_source` to this inspected
+maintained directory. The allocated task must be empty, caller-owned and mode
+0700. Run this entire preparation entry: it admits the complete finite write
+plan using the original context before any mkdir, copy, Git initialization or
+export. It refuses existing contents, including empty children, links and
+prior evidence; preserve them and obtain a separately allocated fresh task.
+Do not run the later steps if this entry fails, or share/mutate its destinations
+with another process while preparing them. Every pre-envelope Python command
+below selects the already trusted `/usr/bin/python3` explicitly and uses `-I -B`.
+Isolation ignores cwd, PYTHONPATH, user site and Python startup configuration;
+it does not replace the original HOME/XDG/product variables used by admission.
+Each command explicitly selects the inspected canonical recipe import directory.
+The installed Python and its standard library are trusted prerequisites.
+
+```sh
+if ! /usr/bin/python3 -I -B - "$recipe_source" "$engine_task" <<'PY'
+import shutil, sys
+from pathlib import Path
+recipe = Path(sys.argv[1])
+if not recipe.is_absolute() or recipe.resolve(strict=True) != recipe or not recipe.is_dir():
+ raise ValueError("Select the inspected canonical recipe directory.")
+sys.path.insert(0, sys.argv[1])
+from isolation import preparation_directories, safe_git
+task = Path(sys.argv[2])
+directories = preparation_directories(task)
+for directory in directories:
+ if directory not in (task / "recipe", task / "source"):
+ directory.mkdir(mode=0o700)
+shutil.copytree(sys.argv[1], task / "recipe",
+ ignore=shutil.ignore_patterns("__pycache__", "*.pyc", "._*", ".DS_Store"))
+safe_git(task / "source", "init")
+PY
+then
+ exit 1
+fi
+```
+
+The same plan covers `recipe`, `source`, `state`, `downloads`, `toolchain`,
+`uv-toolchain`, `venv` and `fixtures`, all generated environment/shared Go cache
+children from `environment_directories`, and the setup-only `state/uv-cache`.
+All children start fresh, so download/extraction/venv internals cannot reuse
+preexisting aliases. Never redirect a later setup destination outside this
+plan or reuse the entry to reset an existing task. Do not use a shared checkout.
+Fetching prerequisites remains a separate authorization, not part of admission:
+
+```sh
+/usr/bin/python3 -I -B - "$engine_task" <<'PY'
+import sys
+from pathlib import Path
+task = Path(sys.argv[1])
+recipe = task / "recipe"
+if not recipe.is_absolute() or recipe.resolve(strict=True) != recipe or not recipe.is_dir():
+ raise ValueError("Select the inspected canonical recipe directory.")
+sys.path.insert(0, str(recipe))
+from isolation import safe_git
+safe_git(task / "source", "fetch", "--depth=1",
+ "https://github.com/router-for-me/CLIProxyAPI.git",
+ "2a6b87aca083a5bf498ac1f68a1b636c500d7aaa")
+safe_git(task / "source", "checkout", "--detach", "FETCH_HEAD")
+PY
+```
+
+`safe_git` is the same command-local boundary used by fixture export and
+verify/apply. It selects trusted `/usr/bin/git`, an empty init template, no
+system/global/environment configuration, no pager/credential helper, and only
+HTTPS transport. No installed configuration is changed. Local config is read
+without includes and must contain only ordinary core bookkeeping, user name/
+email, remote URL/fetch and branch remote/merge declarations. Other local
+settings (including includes, extensions, hooks, filters, fsmonitor, redirects
+and external diff commands) refuse before an operational command. Diff also
+disables external/textconv execution. Preserve refused repositories unchanged.
+An unusual local configuration needs independent inspection, not a reset.
+
+Only separately authorized prerequisite preparation may use public networking. `prerequisites.json`
+records exact Linux arm64 Go 1.26.4 and uv 0.9.8 archive URLs and SHA256 values.
+Download only into the admitted `"$engine_task/downloads"` (Go archive
+`go.tar.gz`, uv archive `uv.tar.gz`), verify hashes before extraction, and
+extract Go into `"$engine_task/toolchain"` and uv into
+`"$engine_task/uv-toolchain"`. Do not install system packages or use a moving
+toolchain. Verify the extracted compiler, tools and runtime files against the
+SHA256-verified archive before using Go, not merely its version string:
+
+```sh
+/usr/bin/python3 -I -B - "$engine_task" <<'PY'
+import json, sys
+from pathlib import Path
+task = Path(sys.argv[1])
+recipe = task / "recipe"
+if not recipe.is_absolute() or recipe.resolve(strict=True) != recipe or not recipe.is_dir():
+ raise ValueError("Select the inspected canonical recipe directory.")
+sys.path.insert(0, str(recipe))
+from execution_inputs import verify_go
+pin = json.loads((task / "recipe/prerequisites.json").read_text())["linux_arm64_go"]
+print(json.dumps(verify_go(task / "toolchain", task / "downloads/go.tar.gz",
+ task / "toolchain/bin/go", pin), indent=2))
+PY
+```
+
+The same verifier is mandatory inside every test/build/wire phase. It rejects
+missing, extra or modified files, changed executable modes, escaping links,
+hard-link aliases, wrong architecture and selection of another compiler.
+The normalized archive/tree identity includes all compiler tools and runtime
+sources, not just `bin/go`. Download locked Go modules using that Go; no catalog refresh or
+provider account is involved:
+
+```sh
+env -i PATH="$engine_task/toolchain/bin:/usr/bin:/bin" \
+ HOME="$engine_task/state/home" \
+ TMPDIR="$engine_task/state/tmp" GOENV=off GOTOOLCHAIN=local \
+ GOPATH="$engine_task/state/go" GOMODCACHE="$engine_task/state/mod" \
+ GOCACHE="$engine_task/state/cache" GOMAXPROCS=2 GOMEMLIMIT=1536MiB \
+ go -C "$engine_task/source" mod download
+```
+
+Export the complete tracked Avibe fixture. Set `avibe_checkout` to a repository
+containing the declared base; its dirty, staged and untracked files are ignored.
+The exporter allocates an exclusive child of the admitted `fixtures` directory;
+retain that actual path as `fixture_root`. Any preparation on another machine
+requires its own complete original-caller admission, not this task's authority:
+
+```sh
+fixture_root=$(/usr/bin/python3 -I -B - "$avibe_checkout" "$engine_task" <<'PY'
+import json, sys
+from pathlib import Path
+recipe = Path(sys.argv[2]) / "recipe"
+if not recipe.is_absolute() or recipe.resolve(strict=True) != recipe or not recipe.is_dir():
+ raise ValueError("Select the inspected canonical recipe directory.")
+sys.path.insert(0, str(recipe))
+from fixture import export_fixture
+root, identity = export_fixture(
+ Path(sys.argv[1]), Path(sys.argv[2]) / "fixtures",
+ json.loads((recipe / "inputs.json").read_text()),
+)
+print(root)
+PY
+) || exit 1
+```
+
+The exporter checks exact commit tree, archive and complete path-independent
+source digest. Actual config writer/state/mock imports use only this export,
+never current-worktree `sys.path`. Build the venv from its frozen `uv.lock`,
+without installing Avibe or running a backend. Set `uv_binary` to the uv
+executable extracted during the separately verified setup step:
+
+```sh
+env -i PATH=/usr/bin:/bin HOME="$engine_task/state/home" \
+ XDG_CONFIG_HOME="$engine_task/state/config" \
+ UV_CACHE_DIR="$engine_task/state/uv-cache" \
+ UV_PROJECT_ENVIRONMENT="$engine_task/venv" UV_LINK_MODE=copy \
+ "$uv_binary" --no-config sync --project "$fixture_root" --frozen \
+ --no-install-project --no-editable --no-managed-python --python /usr/bin/python3
+```
+
+Apply once to a clean exact-base checkout. Reapplying to a dirty checkout is
+refused; it never resets, stashes, or overwrites someone else's changes:
+
+```sh
+/usr/bin/python3 -I -B -c \
+ 'import sys; from pathlib import Path; p=Path(sys.argv.pop(1)); assert p.is_absolute() and p.resolve(strict=True)==p and p.is_dir(); sys.path.insert(0,str(p)); import verify; verify.main()' \
+ "$engine_task/recipe" apply \
+ --source "$engine_task/source" --state "$engine_task/state"
+```
+
+The namespace envelope is mandatory. Inspect its exact source, then run
+`/bin/true` in `none` and `loopback` modes plus `/bin/false` to confirm failed
+receipt/cleanup behavior. Also use the bounded `timeout` phase with a harmless
+`/bin/sh -c 'sleep 30 & wait'` to check PID-namespace teardown after the
+one-second candidate deadline. The nonzero/timeout terminal receipts must
+remain **failed**, even when those diagnostic expectations pass.
+Use new receipt names every time; collisions fail
+closed and preserve prior evidence. Example:
+
+```sh
+caller_storage_sha256=$(/usr/bin/python3 -I -B - "$engine_task/recipe" <<'PY'
+import sys
+from pathlib import Path
+recipe = Path(sys.argv[1])
+if not recipe.is_absolute() or recipe.resolve(strict=True) != recipe or not recipe.is_dir():
+ raise ValueError("Select the inspected canonical recipe directory.")
+sys.path.insert(0, sys.argv[1])
+from isolation import storage_context
+print(storage_context().fingerprint())
+PY
+) || exit 1
+/usr/bin/sudo -n /usr/bin/python3 -I -B -c \
+ 'import sys; from pathlib import Path; p=Path(sys.argv.pop(1)); assert p.is_absolute() and p.resolve(strict=True)==p and p.is_dir(); sys.path.insert(0,str(p)); import namespace; namespace.main()' \
+ "$engine_task/recipe" \
+ --root "$engine_task" --source "$engine_task/source" \
+ --fixture "$fixture_root" --state "$engine_task/state" \
+ --recipe "$engine_task/recipe" --toolchain "$engine_task/toolchain" \
+ --python-env "$engine_task/venv" \
+ --go-archive "$engine_task/downloads/go.tar.gz" --phase probe --network none \
+ --receipt probe-none-unique.json --caller-storage-sha256 "$caller_storage_sha256" \
+ -- /bin/true
+```
+
+After independent probe acceptance, the following narrow helper runs the
+maintained phases with the same mounted inputs. Build uses `none`; test/wire
+use the private loopback. The small caller imports the same derived budget
+as the parent and verifier; a managed Watch must have timeout/lifetime 0
+and must not impose a shorter total timeout. Run phases sequentially:
+
+```sh
+run_phase() {
+ /usr/bin/python3 -I -B - \
+ "$engine_task" "$fixture_root" "$1" "$2" "$3" "${4-}" <<'PY'
+import subprocess, sys
+from pathlib import Path
+task, fixture = Path(sys.argv[1]), Path(sys.argv[2])
+phase, network, receipt, build = sys.argv[3:]
+recipe = task / "recipe"
+if not recipe.is_absolute() or recipe.resolve(strict=True) != recipe or not recipe.is_dir():
+ raise ValueError("Select the inspected canonical recipe directory.")
+sys.path.insert(0, str(recipe))
+from budgets import PHASES
+from isolation import storage_context
+storage = storage_context()
+storage.validate(task)
+entry = ("import sys; from pathlib import Path; p=Path(sys.argv.pop(1)); "
+ "assert p.is_absolute() and p.resolve(strict=True)==p and p.is_dir(); "
+ "sys.path.insert(0,str(p)); import namespace; namespace.main()")
+command = ["/usr/bin/sudo", "-n", "/usr/bin/python3", "-I", "-B", "-c", entry, str(recipe)]
+paths = {"root": task, "source": task / "source", "fixture": fixture,
+ "state": task / "state", "recipe": recipe, "toolchain": task / "toolchain",
+ "python-env": task / "venv", "go-archive": task / "downloads/go.tar.gz"}
+for name, path in paths.items():
+ command += ["--" + name, str(path)]
+selection = ["--build", build] if build else []
+command += ["--phase", phase, "--network", network, "--receipt", receipt,
+ "--caller-storage-sha256", storage.fingerprint(), *selection, "--",
+ str(task / "venv/bin/python"), "-B", str(recipe / "verify.py"), phase,
+ "--source", str(task / "source"), "--state", str(task / "state"),
+ "--fixture", str(fixture), *selection]
+subprocess.run(command, check=True, close_fds=True, timeout=PHASES[phase].driver_seconds)
+PY
+}
+run_phase test loopback test-unique.json &&
+run_phase build none build-unique.json &&
+run_phase wire loopback wire-unique.json "$engine_task/runs/build-unique.json"
+```
+
+`budgets.py` is the single deadline owner: test permits three sequential
+600-second commands, plus input/preflight/setup/cleanup allowances. Its
+candidate, namespace and caller limits are 1980, 2100 and 2130 seconds.
+Build/wire have one 600-second command and limits 780/900/930 seconds.
+The parent also checks that the phase uses its required network mode before
+setup. A timeout or early failure retains evidence and never starts a later
+phase automatically.
+
+The public parent requires the original caller's storage digest and independently
+reconstructs it from its live `/usr/bin/sudo` parent's Linux proc exec-time
+environment and the invoking UID's passwd identity. Only selected storage
+variables are retained; no raw environment or protected paths are printed.
+The proc reads are bounded, anchored and checked for process continuity.
+Root's sanitized HOME is never substituted for the user's original context.
+A missing/mismatched digest, non-sudo parent, unavailable/scrubbed environment
+or changed process fails before any receipt, run, listener, subprocess or mount.
+This deliberately supports the documented direct sudo invocation; another sudo
+process layout is not an excuse for a fallback. Deliberately discarded variables
+cannot be recovered: rerunning from a sanitized shell is not supported.
+
+Before the first privileged allocation, the parent opens the canonical task
+root without following a link and admits its actual directory type, caller UID
+and exact0700 mode. That one ExitStack-owned descriptor is reused for receipts
+and runs, with custody/name-identity rechecked at each consumer. A missing,
+replaced, unreadable, foreign or wrong-mode root fails closed; the parent never
+repairs its ownership or permissions. Rootfs is an exclusive child of the
+root-owned receipts/control descriptor, not the caller-writable task directory.
+Cleanup removes only its original empty identity relative to that retained
+protected parent; replacement trees and prior evidence remain untouched.
+
+The parent pins source, fixture, recipe, toolchain, Python environment, regular
+Go archive, state, allocated output and selected build through component-relative
+no-follow/nonblocking/close-on-exec handles. Selected build custody additionally
+matches the exact output identity recorded in its prior parent-owned receipt.
+Installed system trees retain explicit trusted-system prerequisites; the four
+allowed character devices use Linux O_PATH/no-follow with exact device type/
+major/minor. Directory pins preserve identities, not mutable file contents.
+Existing fixture/toolchain/content checks remain necessary.
+
+The fixed stdlib-only trampoline authenticates its bounded unnamed parent
+handoff before recipe imports. Only budgets/isolation/namespace module bytes
+are pread from pinned regular files, checked against parent-inspected digests
+and compiled; there is no privileged pathname import or cwd bootstrap.
+The initial inspected interpreter, standard library, modules and system inputs
+remain trust prerequisites. `close_fds`/`pass_fds` carry the complete actual
+handle set through unshare; malformed handoff/import/setup paths close partial
+child acquisitions.
+
+The direct typed libc mount adapter uses retained source FDs and protected
+target-parent FD/component pairs, never mount(8) helpers. It reopens the
+protected rootfs child AFTER tmpfs mounting to obtain the overmount view.
+All target topology, metadata and marker handles are prepared before binding
+caller-writable contents. Remounts use protected parent/component targets,
+not old underlying placeholder FDs. After marker completion and readonly
+rootfs remount, fchdir(new-view), chroot(".") and chdir("/") precede closure of
+all host/setup/input handles. These are source contracts; proc-FD binds,
+overmount views and installed-kernel behavior remain unexecuted premises.
+
+Root adds its own passwd-home protection, then carries the stable context only
+through the existing unnamed parent control and root-owned private proof.
+Child consumers reuse it only after verifying all four namespaces (mnt/net/pid/ipc), dropped
+privilege, context digest and exclusive invocation/output identity. Generated
+task HOME/XDG/cache does not redefine production. No public skip/allow flag,
+environment marker or caller-supplied safe-root dictionary grants an exception.
+Public preflight/terminal evidence contains only the storage-context digest;
+the private root-owned proof retains the original locations.
+
+The private network has only its own loopback: dynamic Go `httptest`, engine
+and replacement mock listeners share it, while guest/host listeners and
+external networks are unreachable. Mount propagation becomes private before
+any bind. Source, fixture, recipe and toolchain are read-only; task state is
+writable. Guest/user homes and namespace handles are hidden. Child code runs
+without capabilities or supplementary groups, with no-new-privileges and no
+inherited supervisor descriptors. PID 1 exit destroys remaining descendants.
+There are no public internal re-entry flags: the public CLI always invokes
+util-linux `unshare`. A fixed isolated-Python trampoline consumes an unlinked
+root-owned control descriptor, closes it, and compares all four actual
+kernel namespace identities with the parent-captured identities before the
+first mount or interface operation. Caller-supplied dictionaries cannot select
+the private path. This protects the approved CLI, not arbitrary root Python.
+
+The candidate's finite keyring boundary is the inspected 11-instruction,
+88-byte classic-BPF program with SHA256
+`196f5affb55a9d30299561255adb1027f9a985aba9762b9c66624ed5cded604d`.
+It checks native `AUDIT_ARCH_AARCH64=0xc00000b7`, kills foreign architectures
+and unsigned syscall numbers at or above `0x40000000`, returns EPERM for
+add_key/request_key/keyctl (217/218/219), and permits other native low numbers.
+It is not a general kernel sandbox or an anonymous-session-keyring claim.
+The typed ctypes/prctl adapter requires NNP installation, filter installation,
+NNP=1 and filter-mode=2 readback, in order. Only successful installation adds
+the exact ABI/program identity to the immutable marker, before both dropped
+preflight and candidate. Live consumers require four complete distinct
+namespace IDs, zero capabilities, NNP=1, Seccomp=2 AND the trusted exact marker
+binding; Seccomp=2 alone does not identify a filter. Real fork/exec inheritance,
+harmless task-owned-key denial and IPC isolation remain future execution gates.
+
+Each parent receipt name owns exactly one fresh `runs/<receipt-name>/`
+directory for the invocation's logs, HOME/temp, binary and candidate records.
+Only that output is writable; the parent-owned `runs` collection and other
+runs are not mounted. Shared task caches remain separate under `state`.
+Wire must explicitly select a prior successful build output, which is mounted
+read-only. It verifies that build's identity, receipt, binary and complete
+artifact-tree digest and binds the selection into its own `wire.json`.
+There is no fixed `build.json`, binary or hidden latest pointer in shared
+state. Failures, output collisions and later invocations preserve earlier
+files; the recipe never deletes a run directory.
+
+Parent receipts live under `"$engine_task/receipts"`, outside child mounts.
+They are exclusively opened before execution. Original preflight travels
+through an unlinked supervisor descriptor closed before candidate launch;
+mutable child-state artifacts and candidate stdout cannot replace it. Keep
+parent receipts and before/after input/lifecycle evidence outside candidate
+state. Both unrelated outside IPv4/IPv6 sentinels must observe zero connections.
+A failed preflight, command or cleanup is never a passing receipt.
+
+The parent terminal receipt is still the sole trusted preflight/cleanup
+record. Candidate `build.json`/`wire.json` and logs are supplementary artifacts,
+not privileged attestations. Parent build selection reads only its own
+no-follow, regular-file terminal receipt before execution; it never reads or
+chowns child-controlled artifact paths after execution.
+
+### Execution-input inventory
+
+| Input | Owner and actual evidence |
+| --- | --- |
+| Engine base/patch/catalogs/`go.sum` | `verify_inputs` and `verify_candidate` require the exact base, complete changed-file inventory and fixed bytes; the complete source digest is also bound before/after. No source refresh. |
+| Go archive/extraction/selected compiler | `execution_inputs.verify_go` verifies the archive SHA and normalized full extracted tree before any Go invocation, enforces Linux arm64 and the selected executable, then repeats verification after commands. Raw `go version` is separately captured; a version string is not provenance. |
+| Frozen Avibe fixture | Complete tracked commit export, tree/archive/source hashes, checked before/after. The actual writer/state/mock imports use only this readonly export. |
+| Recipe | Complete tree digest includes Python, declarations, patch, tests and documentation, rather than claiming identity for an unmeasured script subset. |
+| Python/venv/lock | Existing guest Python 3.12 and frozen-lock venv setup are a trusted prerequisite. The selected venv/interpreter, complete venv tree and frozen `uv.lock`/`pyproject.toml` digests are measured before/after. This is **not** archive attestation of Python or independent proof that every installed distribution matches the lock. |
+| Guest OS/Python/util-linux | Existing authorized guest trusted base, not newly pinned or provisioned by this recipe. Namespace, privilege, mount and sentinel facts are measured by the parent/probe. |
+| uv | Setup-only declared archive/version. Preparation verifies its archive manually before extraction; execution phases do not invoke uv or claim to attest its extraction. |
+| Module/build caches | Shared task state prepared through Go's locked-module workflow, not a new cryptographically attested dependency distribution. `go.sum`, readonly module mode and offline operation remain enforced; cache contents are not promoted to frozen source or a production reproducibility claim. |
+
+The test/build/wire input records bind every verified or measured field above
+with its stated trust category. Source, Go, fixture, recipe and measured venv
+are rechecked even after a command fails. Wire refuses stale or changed
+selected-build artifacts. Tests/builds use `GOPROXY=off`, checksum
+verification, `-mod=readonly`, `GOMAXPROCS=2`, `-p=1`, isolated HOME/XDG/cache,
+and private-network OS isolation. The Go memory setting is a soft limit, not an
+OS memory cap.
+
+The maintained `test` phase runs:
+
+```text
+go test -mod=readonly -p=1 -count=1 ./internal/thinking/... ./internal/modelconfig ./internal/runtime/executor/helps ./sdk/cliproxy/auth
+go test -mod=readonly -p=1 -count=1 -run '^TestThinking|^TestSummaryIntent' ./test
+go test -mod=readonly -p=1 -count=1 ./internal/runtime/executor
+```
+
+The `build` phase runs `go build -mod=readonly -p=1 -trimpath
+-buildvcs=false ... ./cmd/server` with `CGO_ENABLED=0`. This is a diagnostic
+host binary, not a production release artifact or an upstream-labeled binary.
+
+## What the tests prove
+
+These are supplementary engine-source consumers for `MH-EFFORT-001`.
+The existing registered Avibe scenario still owns gateway/resolver evidence;
+no new shared scenario identifier or shipped-engine claim is introduced.
+
+- Shared policy covers unresolved/user-defined, configured unknown, static
+ nil, supported, narrow and empty metadata; budget/level/future/none/absence;
+ prepared-target authority; source-aware conversion; aliases and suffixes.
+- Actual manager plus Claude HTTP executor tests bind two conflicting model
+ snapshots to the selected credentials and aliases, then replace one key
+ and metadata snapshot without changing routing. Both stream modes run.
+- Fake subscription tests cover Claude and Codex HTTP, Codex WebSocket,
+ Kimi Messages delegation and native/legacy Chat, and xAI Responses.
+ The xAI final-egress matrix has 80 cases; the Kimi native/legacy matrix
+ has 40. Payload override/filter, suffix priority, forced Claude tool choice
+ and actual upstream cancellation remain consuming assertions.
+- `wire_matrix.py` reuses `tests/e2e/drivers/mock_llm_upstream.py`. It creates
+ actual task-owned `SourceRecord`/credential state and uses the frozen
+ `CLIProxyEngineAdapter.sync_sources` and `EngineSupervisor`, with their real
+ validation, transaction, transport barrier, atomic config writer and health
+ checks. Existing installer/process/port constructor seams select only the
+ preverified task binary, task environment and log, and a fresh private port.
+ The 380-case three-protocol matrix asserts exact endpoint,
+ model, selected fake key, non-ASCII text and reasoning fields, with no
+ request sent to another Source. Four profiles use untouched generated
+ registrations; the empty-object profile is explicitly engine-only and
+ does not claim Avibe generates empty capability objects.
+- Further consuming cases compare complete long UTF-8 model identities
+ (including shared heads/distinct tails and route-only models) through
+ registration and HTTP egress. Three sequential ~42 MiB four-image requests
+ compare exact valid PNG/base64 data and text in native protocol shapes.
+ Only the mock's test receive budget increases to 48 MiB for these cases.
+ Allowed envelope/cache normalization is not mistaken for image truncation.
+- Source origin/key replacement stops the prior owned child and starts a new
+ one through the real product transaction. Requests consume the returned
+ connection's port/token; registrations and exact model/Source identity remain.
+ Focused actual-child regressions reject mismatched Source credentials before
+ restart, inject a real exiting child to verify projection rollback and
+ recovery, and verify failed-startup cleanup. `lifecycle.json` records these
+ assertions and reaped child outcomes and is bound into the wire receipt.
+ HTTP cancellation and same-source reuse complement the precise Go
+ upstream-context cancellation test. All test processes and mock threads
+ are stopped and reaped.
+
+The former watcher-only fixture failed on Linux after the atomic config
+replacement. The pinned engine watches the config file itself; no raw inotify
+trace was captured. This is a separate diagnostic limitation, not an
+established Avibe replacement regression: Avibe owns an explicit restart
+transaction. The recipe neither changes the watcher nor writes config in place
+or extends a replacement deadline. The engine-only empty-object profile is
+applied after each real config generation, before each task child launch.
+
+`--local-model` alone does not disable the upstream Antigravity version
+updater. The private network and dead loopback proxy are intentional complementary
+controls. No login, refresh, cloud account, user engine, or installed
+runtime-state probe is part of this recipe.
+
+Keep task evidence outside the repository. Go/package caches require a few
+GiB; run the image fixtures and production builds sequentially. The recipe
+retains per-run wire artifacts for inspection and does not perform cleanup
+outside its explicitly supplied task directory.
+
+## Maintenance and release boundary
+
+Edit only a task-owned exact-base engine checkout, including the consuming
+tests. Regenerate `native-intent.patch` with `git diff --binary` (include new
+test files with intent-to-add), refresh `patched-files.json`, and repeat
+clean-apply, test, build and wire checks. Review the diff for unrelated edits.
+Never refresh catalogs from a moving branch to make a test pass.
+
+Upstream's MIT notice is retained in `UPSTREAM-LICENSE`.
+
+Shipping requires a separate source/provenance decision: authorized upstream
+acceptance and release, or an explicitly approved Avibe-maintained source and
+equally strong provenance contract. Then build/verify all four production
+targets, publish available assets, satisfy the unchanged manifest guard, and
+only then update an Avibe dependency pin. Publication, guard changes, releases,
+installation, or runtime replacement are not authorized by this directory.
diff --git a/patches/cliproxyapi/UPSTREAM-LICENSE b/patches/cliproxyapi/UPSTREAM-LICENSE
new file mode 100644
index 000000000..08f942bcb
--- /dev/null
+++ b/patches/cliproxyapi/UPSTREAM-LICENSE
@@ -0,0 +1,22 @@
+MIT License
+
+Copyright (c) 2025-2005.9 Luis Pater
+Copyright (c) 2025.9-present Router-For.ME
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/patches/cliproxyapi/budgets.py b/patches/cliproxyapi/budgets.py
new file mode 100644
index 000000000..3a2837536
--- /dev/null
+++ b/patches/cliproxyapi/budgets.py
@@ -0,0 +1,59 @@
+"""One bounded allowance for verifier commands, namespace cleanup and its caller."""
+
+from __future__ import annotations
+
+import argparse
+from dataclasses import asdict, dataclass
+import json
+
+
+@dataclass(frozen=True)
+class PhaseBudget:
+ commands: int
+ command_seconds: int
+ input_seconds: int = 180
+ preflight_seconds: int = 30
+ setup_seconds: int = 60
+ cleanup_seconds: int = 30
+
+ @property
+ def candidate_seconds(self) -> int:
+ return self.commands * self.command_seconds + self.input_seconds
+
+ @property
+ def namespace_seconds(self) -> int:
+ return self.candidate_seconds + self.preflight_seconds + self.setup_seconds + self.cleanup_seconds
+
+ @property
+ def driver_seconds(self) -> int:
+ return self.namespace_seconds + self.cleanup_seconds
+
+ def receipt(self) -> dict:
+ return {
+ **asdict(self), "candidate_seconds": self.candidate_seconds,
+ "namespace_seconds": self.namespace_seconds, "driver_seconds": self.driver_seconds,
+ }
+
+
+PHASES = {
+ "test": PhaseBudget(3, 600),
+ "build": PhaseBudget(1, 600),
+ "wire": PhaseBudget(1, 600),
+ "check": PhaseBudget(1, 600),
+ "probe": PhaseBudget(1, 10, input_seconds=0),
+ # Deliberate harmless timeout/teardown diagnostic; never an engine phase.
+ "timeout": PhaseBudget(1, 1, input_seconds=0),
+}
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("phase", choices=PHASES)
+ parser.add_argument("--layer", choices=("driver", "namespace", "candidate"))
+ args = parser.parse_args()
+ budget = PHASES[args.phase]
+ print(getattr(budget, args.layer + "_seconds") if args.layer else json.dumps(budget.receipt()))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/patches/cliproxyapi/execution_inputs.py b/patches/cliproxyapi/execution_inputs.py
new file mode 100644
index 000000000..7bb019407
--- /dev/null
+++ b/patches/cliproxyapi/execution_inputs.py
@@ -0,0 +1,166 @@
+"""Recipe input inventory: archive-verified Go, frozen inputs, measured trusted base."""
+
+from __future__ import annotations
+
+from contextlib import contextmanager
+import hashlib
+import json
+import os
+from pathlib import Path, PurePosixPath
+import platform
+import stat
+import sys
+import tarfile
+
+
+@contextmanager
+def regular_file(path: Path):
+ """Consume one admitted inode; reject observed replacement or metadata drift.
+
+ This is not a snapshot or a lock against concurrent outside writers. Input
+ preparation/content custody and the read-only execution view remain required.
+ """
+ def identity(info):
+ if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:
+ raise ValueError(f"Expected a single-link regular file: {path.name}")
+ return tuple(getattr(info, "st_" + field) for field in (
+ "dev", "ino", "mode", "uid", "gid", "rdev", "nlink", "size", "mtime_ns", "ctime_ns",
+ ))
+
+ admitted = identity(path.lstat())
+ fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC)
+ try:
+ with os.fdopen(fd, "rb", closefd=False) as stream:
+ def check():
+ if identity(os.fstat(fd)) != admitted or identity(path.lstat()) != admitted:
+ raise ValueError(f"Execution input changed during its read: {path.name}")
+ check()
+ try:
+ yield stream
+ finally:
+ check()
+ finally:
+ os.close(fd)
+
+
+def file_sha256(path: Path) -> str:
+ with regular_file(path) as stream:
+ return hashlib.file_digest(stream, "sha256").hexdigest()
+
+
+def tree_records(root: Path, *, python_links: bool = False) -> dict:
+ root = root.resolve(strict=True)
+ records = {}
+ for path in sorted(root.rglob("*")):
+ info = path.lstat()
+ name = path.relative_to(root).as_posix()
+ if stat.S_ISREG(info.st_mode):
+ record = {"kind": "file", "mode": stat.S_IMODE(info.st_mode), "sha256": file_sha256(path)}
+ elif stat.S_ISDIR(info.st_mode):
+ record = {"kind": "dir", "mode": stat.S_IMODE(info.st_mode)}
+ elif stat.S_ISLNK(info.st_mode):
+ target = path.resolve(strict=True)
+ if not target.is_relative_to(root):
+ # uv's system-Python venv links are explicitly a trusted base,
+ # not Go archive content or an archive-verified Python claim.
+ if not (python_links and name in ("bin/python", "bin/python3", "bin/python3.12")
+ and target.parent == Path("/usr/bin") and target.name.startswith("python3")):
+ raise ValueError(f"Input link escapes its tree: {name}")
+ record = {"kind": "link", "target": os.readlink(path)}
+ else:
+ raise ValueError(f"Unsupported execution input: {name}")
+ records[name] = record
+ return records
+
+
+def records_sha256(records: dict) -> str:
+ return hashlib.sha256(json.dumps(records, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
+
+
+def go_archive_records(archive: Path, expected_sha256: str) -> dict:
+ """Hash and inspect the SAME opened archive; never extract unverified content."""
+ with regular_file(archive) as stream:
+ if hashlib.file_digest(stream, "sha256").hexdigest() != expected_sha256:
+ raise RuntimeError("Wrong pinned Go archive SHA256.")
+ stream.seek(0)
+ records = {}
+ with tarfile.open(fileobj=stream, mode="r:gz") as source:
+ for member in source:
+ path = PurePosixPath(member.name)
+ if path.is_absolute() or ".." in path.parts or path.parts[:1] != ("go",):
+ raise ValueError("Go archive path leaves its extraction root.")
+ name = path.relative_to("go").as_posix()
+ if name == ".":
+ if not member.isdir():
+ raise ValueError("Invalid Go archive root.")
+ continue
+ if name in records:
+ raise ValueError("Duplicate Go archive member.")
+ if member.isfile():
+ with source.extractfile(member) as content:
+ record = {"kind": "file", "mode": member.mode & 0o777,
+ "sha256": hashlib.file_digest(content, "sha256").hexdigest()}
+ elif member.isdir():
+ record = {"kind": "dir"}
+ elif member.issym():
+ target = PurePosixPath(member.linkname)
+ if target.is_absolute() or ".." in target.parts:
+ raise ValueError("Go archive link leaves its extraction root.")
+ record = {"kind": "link", "target": member.linkname}
+ else:
+ raise ValueError("Unsupported Go archive member.")
+ records[name] = record
+ # Tar archives may omit directory entries. Normalize structural
+ # ancestors, but do not invent a claim about their archived modes.
+ for name in list(records):
+ for parent in PurePosixPath(name).parents:
+ if parent == PurePosixPath("."):
+ continue
+ previous = records.setdefault(str(parent), {"kind": "dir"})
+ if previous["kind"] != "dir":
+ raise ValueError("Go archive has a non-directory ancestor.")
+ return records
+
+
+def verify_go(toolchain: Path, archive: Path, selected: Path, prerequisite: dict) -> dict:
+ """Bind the actual compiler/tools/runtime tree BEFORE invoking any Go code."""
+ toolchain = toolchain.resolve(strict=True)
+ selected = selected.resolve(strict=True)
+ if sys.platform != "linux" or platform.machine() not in ("aarch64", "arm64"):
+ raise RuntimeError("The pinned diagnostic toolchain is Linux arm64 only.")
+ if selected != toolchain / "bin/go":
+ raise RuntimeError("Selected Go executable is not the pinned extraction's bin/go.")
+ expected = go_archive_records(archive, prerequisite["sha256"])
+ actual = tree_records(toolchain)
+ for record in actual.values():
+ if record["kind"] == "dir":
+ record.pop("mode")
+ if actual != expected:
+ raise RuntimeError("Go extraction differs from its verified archive (missing/extra/changed input).")
+ with regular_file(selected) as stream:
+ elf = stream.read(20)
+ if len(elf) != 20 or elf[:6] != b"\x7fELF\x02\x01" or int.from_bytes(elf[18:20], "little") != 183:
+ raise RuntimeError("Selected compiler is not a Linux arm64 ELF executable.")
+ return {
+ "archive_sha256": prerequisite["sha256"],
+ "extracted_tree_sha256": records_sha256(actual),
+ "selected_executable": str(selected), "selected_relative_path": "bin/go",
+ "selected_sha256": actual["bin/go"]["sha256"],
+ "target": "linux/arm64", "version": prerequisite["version"],
+ }
+
+
+def python_identity(venv: Path, fixture: Path) -> dict:
+ """Measure the trusted task venv; do not mislabel a version/lock as byte proof."""
+ venv = venv.resolve(strict=True)
+ if Path(sys.prefix).resolve() != venv or Path(sys.executable).absolute().parent != venv / "bin":
+ raise RuntimeError("Verifier must use the selected task venv, not an ambient interpreter.")
+ if sys.version_info[:2] != (3, 12):
+ raise RuntimeError("Use the existing guest Python 3.12 trusted base.")
+ return {
+ "trust": "existing guest Python and frozen-lock setup; measured closure, not archive-attested Python",
+ "executable": sys.executable, "resolved_executable": str(Path(sys.executable).resolve(strict=True)),
+ "version": sys.version, "venv_tree_sha256": records_sha256(tree_records(venv, python_links=True)),
+ "lock_sha256": file_sha256(fixture / "uv.lock"),
+ "pyproject_sha256": file_sha256(fixture / "pyproject.toml"),
+ }
diff --git a/patches/cliproxyapi/fixture.py b/patches/cliproxyapi/fixture.py
new file mode 100644
index 000000000..8c8218a41
--- /dev/null
+++ b/patches/cliproxyapi/fixture.py
@@ -0,0 +1,76 @@
+"""Materialize and verify the frozen Avibe fixture, never the mutable worktree."""
+
+from __future__ import annotations
+
+import hashlib
+import io
+import os
+from pathlib import Path
+import stat
+import tarfile
+import tempfile
+
+from isolation import safe_git, validate_state_root
+from execution_inputs import regular_file
+
+
+def source_digest(root: Path) -> str:
+ """Bind every exported file/link and reject links leaving the export."""
+ digest = hashlib.sha256()
+ for path in sorted(root.rglob("*")):
+ mode = path.lstat().st_mode
+ name = path.relative_to(root).as_posix().encode()
+ if stat.S_ISLNK(mode):
+ if not path.resolve().is_relative_to(root.resolve()):
+ raise ValueError(f"Fixture link leaves its source root: {name!r}")
+ kind, content = b"link", os.readlink(path).encode()
+ elif stat.S_ISREG(mode):
+ with regular_file(path) as source:
+ kind, content = b"file", source.read()
+ elif stat.S_ISDIR(mode):
+ kind, content = b"dir", b""
+ else:
+ raise ValueError(f"Unsupported fixture file: {name!r}")
+ for value in (name, kind, content):
+ digest.update(len(value).to_bytes(8, "big"))
+ digest.update(value)
+ return digest.hexdigest()
+
+
+def verify_fixture(root: Path, expected: str) -> None:
+ if source_digest(root) != expected:
+ raise RuntimeError("Frozen Avibe fixture changed; preserve the evidence and use a fresh export.")
+
+
+def export_fixture(repository: Path, state: Path, receipt: dict) -> tuple[Path, dict]:
+ """An exact commit archive ignores staged, dirty and untracked worktree files."""
+ state = validate_state_root(state)
+ base = receipt["avibe_fixture_base"]
+ tree = safe_git(repository, "rev-parse", f"{base}^{{tree}}").decode().strip()
+ if tree != receipt["avibe_fixture_tree"]:
+ raise RuntimeError("Wrong Avibe fixture tree.")
+ archive = safe_git(repository, "archive", "--format=tar", base)
+ archive_sha = hashlib.sha256(archive).hexdigest()
+ if archive_sha != receipt["avibe_fixture_archive_sha256"]:
+ raise RuntimeError("Frozen Avibe archive differs from the receipt.")
+ root = Path(tempfile.mkdtemp(prefix="avibe-fixture-", dir=state))
+ with tarfile.open(fileobj=io.BytesIO(archive)) as source:
+ source.extractall(root, filter="data")
+ identity = {
+ "commit": base, "tree": tree, "archive_sha256": archive_sha,
+ "source_sha256": source_digest(root),
+ }
+ if "avibe_fixture_source_sha256" in receipt:
+ verify_fixture(root, receipt["avibe_fixture_source_sha256"])
+ return root, identity
+
+
+def fixture_identity(root: Path, receipt: dict) -> dict:
+ """Verify a copied export without trusting its working-copy Git metadata."""
+ verify_fixture(root, receipt["avibe_fixture_source_sha256"])
+ return {
+ "commit": receipt["avibe_fixture_base"],
+ "tree": receipt["avibe_fixture_tree"],
+ "archive_sha256": receipt["avibe_fixture_archive_sha256"],
+ "source_sha256": receipt["avibe_fixture_source_sha256"],
+ }
diff --git a/patches/cliproxyapi/inputs.json b/patches/cliproxyapi/inputs.json
new file mode 100644
index 000000000..86cacffbd
--- /dev/null
+++ b/patches/cliproxyapi/inputs.json
@@ -0,0 +1,15 @@
+{
+ "repository": "router-for-me/CLIProxyAPI",
+ "version": "v7.2.149",
+ "source_sha": "2a6b87aca083a5bf498ac1f68a1b636c500d7aaa",
+ "go_version": "go1.26.4",
+ "avibe_fixture_base": "76e269c9a9dfd3a6286ce0da81b77316ca4be38a",
+ "avibe_fixture_tree": "27f32c68b3b9c6b1d40fcde3a034838b58ca0636",
+ "avibe_fixture_archive_sha256": "3352c66c7b88c35ce7851a4bcfbeb3ac2e6d842199ef7dcf7c93534c0233c4cc",
+ "avibe_fixture_source_sha256": "61c9616c760f9bbe4750c507073deea183064ec7f55dbacc2174eac9c474031e",
+ "sha256": {
+ "internal/registry/models/models.json": "b19b2655a4f294605d3a347be16e67ef6ea776d70cedbd69c36629f3dbb945d9",
+ "internal/registry/models/codex_client_models.json": "a044aa222836b32091fdf4c9c34030443cb8717dea65db875cf705406c332fd6",
+ "go.sum": "b29392b1f713b238d6232af2f8fd09e28b7f5d221847ddccf0fc35682a9b29bd"
+ }
+}
diff --git a/patches/cliproxyapi/isolation.py b/patches/cliproxyapi/isolation.py
new file mode 100644
index 000000000..bd80d6566
--- /dev/null
+++ b/patches/cliproxyapi/isolation.py
@@ -0,0 +1,433 @@
+"""Local-only test envelope, not an engine launcher or release integration."""
+
+from __future__ import annotations
+
+import json
+import hashlib
+import os
+from dataclasses import dataclass
+from pathlib import Path
+import pwd
+import re
+import shutil
+import stat
+import subprocess
+import sys
+
+
+STORAGE_ENV = (
+ "HOME", "XDG_CONFIG_HOME", "XDG_CACHE_HOME", "XDG_DATA_HOME",
+ "XDG_STATE_HOME", "XDG_RUNTIME_DIR", "AVIBE_HOME", "CODEX_HOME", "CLAUDE_CONFIG_DIR",
+)
+PRODUCT_DIRS = (".avibe", ".vibe_remote", ".codex", ".claude")
+XDG_DEFAULTS = {
+ "XDG_CONFIG_HOME": ".config", "XDG_CACHE_HOME": ".cache",
+ "XDG_DATA_HOME": ".local/share", "XDG_STATE_HOME": ".local/state",
+}
+PROOF_PATH = Path("/run/avibe-engine-test-isolation.json")
+NAMESPACE_NAMES = ("mnt", "net", "pid", "ipc")
+KEYRING_ABI = "linux-aarch64-le64"
+KEYRING_PROGRAM_SHA256 = "196f5affb55a9d30299561255adb1027f9a985aba9762b9c66624ed5cded604d"
+CAPABILITY_FIELDS = ("CapInh", "CapPrm", "CapEff", "CapBnd", "CapAmb")
+
+
+def keyring_identity() -> dict:
+ """One expected identity; only the successful installer creates its marker."""
+ return {"abi": KEYRING_ABI, "program_sha256": KEYRING_PROGRAM_SHA256}
+
+
+def require_namespace_ids(values: dict) -> None:
+ """One exact capture schema, shared by the outer and every inner consumer."""
+ if not isinstance(values, dict) or set(values) != set(NAMESPACE_NAMES):
+ raise RuntimeError("Refusing setup outside new mount, network, PID and IPC namespaces.")
+ for name in NAMESPACE_NAMES:
+ if not isinstance(values[name], str) or not re.fullmatch(rf"{name}:\[[1-9][0-9]*\]", values[name]):
+ raise RuntimeError("Invalid namespace identity.")
+
+
+def require_namespaces(outer: dict, actual: dict) -> None:
+ """Validate both complete namespace sets before any privileged child effect."""
+ require_namespace_ids(outer)
+ require_namespace_ids(actual)
+ for name in NAMESPACE_NAMES:
+ if outer[name] == actual[name]:
+ raise RuntimeError("Namespace remains shared with its parent.")
+
+
+def require_kernel_evidence(proof: dict) -> None:
+ """Common private/probe/parent consumer, never an ambient success flag."""
+ if not isinstance(proof, dict):
+ raise RuntimeError("Missing kernel evidence.")
+ require_namespaces(proof.get("outer_namespaces"), proof.get("namespaces"))
+ if proof.get("keyring_boundary") != keyring_identity():
+ raise RuntimeError("Missing exact installed keyring-boundary identity.")
+ status = proof.get("process_status")
+ fields = {*CAPABILITY_FIELDS, "NoNewPrivs", "Seccomp"}
+ if not isinstance(status, dict) or set(status) != fields:
+ raise RuntimeError("Incomplete live privilege/filter evidence.")
+ if status["NoNewPrivs"] != "1" or status["Seccomp"] != "2":
+ raise RuntimeError("Candidate lacks no-new-privileges or the installed filter.")
+ for name in CAPABILITY_FIELDS:
+ if not isinstance(status[name], str) or not re.fullmatch(r"0+", status[name]):
+ raise RuntimeError("Candidate process still has Linux capabilities.")
+
+# A finite bootstrap caller, not an arbitrary Git command runner. Configuration
+# that can load code, redirect objects/worktrees or select transports is refused
+# in the local repository, not inherited from the operator's account.
+GIT_COMMANDS = {"init", "fetch", "checkout", "rev-parse", "archive", "status", "diff", "ls-files", "apply"}
+GIT_LOCAL_KEYS = {
+ "core.repositoryformatversion", "core.filemode", "core.bare", "core.logallrefupdates",
+ "core.ignorecase", "core.precomposeunicode", "user.name", "user.email",
+}
+
+
+def safe_git(repository: Path, *arguments: str) -> bytes:
+ """Use the installed Git without ambient config, hooks, filters or helpers.
+
+ Original storage is captured by the caller before this command-local
+ environment is constructed. Never mutate os.environ or an installed config.
+ Local config is listed without includes before any operational command;
+ only ordinary repository bookkeeping/remote declarations are admitted.
+ """
+ if not arguments or arguments[0] not in GIT_COMMANDS:
+ raise ValueError("Unsupported recipe Git operation.")
+ operation = arguments[0]
+ if operation in {"init", "fetch", "checkout", "apply"}:
+ repository = validate_state_root(repository)
+ environment = {
+ "PATH": "/usr/bin:/bin", "LC_ALL": "C", "GIT_CONFIG_NOSYSTEM": "1",
+ "GIT_CONFIG_SYSTEM": "/dev/null", "GIT_CONFIG_GLOBAL": "/dev/null",
+ "GIT_CONFIG_COUNT": "0", "GIT_ATTR_NOSYSTEM": "1",
+ "GIT_TERMINAL_PROMPT": "0", "GIT_OPTIONAL_LOCKS": "0",
+ "GIT_NO_REPLACE_OBJECTS": "1", "GIT_NO_LAZY_FETCH": "1",
+ }
+ executable = Path("/usr/bin/git")
+ info = executable.stat()
+ if not stat.S_ISREG(info.st_mode) or info.st_uid != 0 or info.st_mode & 0o022:
+ raise RuntimeError("The installed /usr/bin/git must be trusted.")
+ command = [
+ str(executable), "--no-pager", "-c", "core.hooksPath=/dev/null",
+ "-c", "core.fsmonitor=false", "-c", "core.untrackedCache=false",
+ "-c", "core.attributesFile=/dev/null", "-c", "core.excludesFile=/dev/null",
+ "-c", "credential.helper=", "-c", "protocol.allow=never",
+ "-c", "protocol.https.allow=always",
+ ]
+ options = {"env": environment, "cwd": "/", "stdin": subprocess.DEVNULL,
+ "close_fds": True, "timeout": 30}
+ if operation == "init":
+ if len(arguments) != 1 or repository.is_symlink() or (
+ repository.exists() and any(repository.iterdir())):
+ raise ValueError("Git initialization requires a fresh empty destination.")
+ return subprocess.check_output([*command, "init", "--template=", str(repository)], **options)
+ prefix = [*command, "-C", str(repository)]
+ configuration = subprocess.check_output(
+ [*prefix, "config", "--local", "--no-includes", "--null", "--list"], **options,
+ )
+ for entry in configuration.split(b"\0"):
+ if not entry:
+ continue
+ key = entry.split(b"\n", 1)[0].decode("utf-8").lower()
+ bookkeeping = ((key.startswith("remote.") and key.endswith((".url", ".fetch")))
+ or (key.startswith("branch.") and key.endswith((".remote", ".merge"))))
+ if key not in GIT_LOCAL_KEYS and not bookkeeping:
+ # Do not print config values (or potentially protected include paths).
+ raise ValueError("Recipe Git refuses non-bookkeeping local configuration.")
+ if operation == "diff":
+ arguments = ("diff", "--no-ext-diff", "--no-textconv", *arguments[1:])
+ elif operation == "fetch":
+ arguments = ("fetch", "--no-recurse-submodules", *arguments[1:])
+ return subprocess.check_output([*prefix, *arguments], **options)
+
+
+def _absolute(value: str, name: str) -> Path:
+ # Never include configured values in exceptions or diagnostic output.
+ if (not isinstance(value, str) or not value or len(value) > 4096
+ or "\0" in value or not Path(value).is_absolute() or ".." in Path(value).parts):
+ raise ValueError(f"{name} must be an absolute storage path without parent traversal.")
+ return Path(value)
+
+
+def _aliases(paths) -> tuple[Path, ...]:
+ try:
+ return tuple(sorted({alias for path in paths for alias in (path, path.resolve())}))
+ except (OSError, RuntimeError):
+ raise ValueError("Configured storage aliases cannot be resolved safely.") from None
+
+
+@dataclass(frozen=True, repr=False)
+class StorageContext:
+ """Original user locations, never inferred from a generated task environment."""
+
+ uid: int
+ homes: tuple[Path, ...]
+ protected: tuple[Path, ...]
+ environment_sha256: str
+
+ @classmethod
+ def capture(cls, *, uid: int | None = None, environment=None):
+ uid = os.getuid() if uid is None else uid
+ environment = os.environ if environment is None else environment
+ selected = {name: environment.get(name) for name in STORAGE_ENV}
+ # Empty/unset values use defaults; runtime has no default. Relative
+ # and malformed configured values fail closed, including overridden HOME.
+ configured = {name: _absolute(value, name) for name, value in selected.items() if value}
+ passwd_home = _absolute(pwd.getpwuid(uid).pw_dir, "passwd home")
+ effective_home = configured.get("HOME", passwd_home)
+ homes = _aliases((passwd_home, effective_home))
+ protected = [home / name for home in homes for name in PRODUCT_DIRS]
+ protected += [configured.get(name, effective_home / default) for name, default in XDG_DEFAULTS.items()]
+ protected += [configured[name] for name in (
+ "XDG_RUNTIME_DIR", "AVIBE_HOME", "CODEX_HOME", "CLAUDE_CONFIG_DIR",
+ ) if name in configured]
+ environment_sha = hashlib.sha256(json.dumps(selected, sort_keys=True).encode()).hexdigest()
+ return cls(uid, homes, _aliases(protected), environment_sha)
+
+ def record(self) -> dict:
+ """Private parent control/proof only: do not print protected locations."""
+ return {"version": 1, "uid": self.uid, "homes": list(map(str, self.homes)),
+ "protected": list(map(str, self.protected)),
+ "environment_sha256": self.environment_sha256}
+
+ @classmethod
+ def from_parent(cls, record: dict):
+ if (not isinstance(record, dict) or set(record) != {
+ "version", "uid", "homes", "protected", "environment_sha256",
+ } or record["version"] != 1 or type(record["uid"]) is not int
+ or not isinstance(record["homes"], list) or not record["homes"]
+ or not isinstance(record["protected"], list) or not record["protected"]
+ or len(record["homes"]) > 16 or len(record["protected"]) > 128
+ or not isinstance(record["environment_sha256"], str)
+ or len(record["environment_sha256"]) != 64):
+ raise RuntimeError("Invalid parent storage context.")
+ # These paths were canonicalized outside the chroot. Resolving them
+ # again here would lose aliases hidden by the private mount namespace.
+ return cls(record["uid"], tuple(_absolute(value, "parent home") for value in record["homes"]),
+ tuple(_absolute(value, "parent storage") for value in record["protected"]),
+ record["environment_sha256"])
+
+ def fingerprint(self) -> str:
+ return hashlib.sha256(json.dumps(self.record(), sort_keys=True).encode()).hexdigest()
+
+ def with_root_identity(self):
+ root = self.capture(uid=0, environment={})
+ return StorageContext(self.uid, tuple(sorted(set(self.homes + root.homes))),
+ tuple(sorted(set(self.protected + root.protected))), self.environment_sha256)
+
+ def validate(self, root: Path) -> Path:
+ lexical = root.absolute()
+ canonical = root.resolve()
+ broad = {Path(name).resolve() for name in ("/", "/tmp", "/var/tmp", "/var/folders", "/home", "/Users", "/root")}
+ for target in (lexical, canonical):
+ if target in broad or any(target == home or home.is_relative_to(target) for home in self.homes):
+ raise ValueError("The evidence root must be a dedicated, narrow task directory.")
+ if any(target == boundary or target.is_relative_to(boundary) or boundary.is_relative_to(target)
+ for boundary in self.protected):
+ raise ValueError("Task writes must not target protected user state.")
+ return canonical
+
+ def read_input(self, path: Path) -> Path:
+ """Admit EVERY finite macOS read grant, including system/tool inputs.
+
+ This constructs source policy only; its actual OS startup closure still
+ requires independent execution evidence. No privileged read occurs here.
+ """
+ lexical = _absolute(str(path), "diagnostic input")
+ canonical = self.validate(lexical)
+ broad = {Path(value) for value in ("/usr", "/System", "/Library", "/dev", "/etc", "/private")}
+ for target in (lexical, canonical):
+ if target in broad or any(
+ target == boundary or target.is_relative_to(boundary) or boundary.is_relative_to(target)
+ for boundary in (*self.homes, *self.protected)
+ ):
+ raise ValueError("Diagnostic inputs must be narrow and outside all original user storage.")
+ return canonical
+
+
+def storage_context() -> StorageContext:
+ """Only actual private namespace proof may replace ambient user identity."""
+ if sys.platform == "linux" and PROOF_PATH.exists():
+ proof = _namespace_proof()
+ return StorageContext.from_parent(proof["storage_context"])
+ if os.geteuid() == 0 or "SUDO_UID" in os.environ:
+ raise RuntimeError("Original caller storage context is required before sudo sanitization.")
+ return StorageContext.capture()
+
+
+def validate_state_root(root: Path, *, owner_uid: int | None = None, context: StorageContext | None = None) -> Path:
+ """Validate every public write root before setup, including canonical aliases."""
+ context = storage_context() if context is None else context
+ if owner_uid is not None and context.uid != owner_uid:
+ raise RuntimeError("Storage context does not belong to the invoking owner.")
+ return context.validate(root)
+
+
+def validate_temporary_root(root: Path, *, owner_uid: int | None = None, context: StorageContext | None = None) -> Path:
+ """The privileged recipe admits only narrow canonical temporary children."""
+ root = validate_state_root(root, owner_uid=owner_uid, context=context)
+ if not any(root != base and root.is_relative_to(base) for base in (Path("/tmp"), Path("/var/tmp"))):
+ raise ValueError("Privileged scratch must be a canonical child of /tmp or /var/tmp.")
+ return root
+
+
+def _namespace_proof() -> dict:
+ """Private proof reader; no ambient marker or caller dictionary grants trust."""
+ if sys.platform != "linux":
+ raise RuntimeError("Network suites require namespace.py's private Linux envelope.")
+ fd = os.open(PROOF_PATH, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
+ with os.fdopen(fd, "rb") as stream:
+ info = os.fstat(stream.fileno())
+ if (not stat.S_ISREG(info.st_mode) or info.st_nlink != 1 or info.st_uid != 0
+ or info.st_mode & 0o022):
+ raise RuntimeError("Network suites require namespace.py's private Linux envelope.")
+ raw = stream.read(65537)
+ if len(raw) > 65536:
+ raise RuntimeError("Oversized namespace proof.")
+ proof = json.loads(raw)
+ require_namespaces(proof.get("outer_namespaces"), proof.get("namespaces"))
+ for name, expected in proof["namespaces"].items():
+ if os.readlink(f"/proc/self/ns/{name}") != expected or expected == proof["outer_namespaces"][name]:
+ raise RuntimeError("Namespace identity does not match the isolated envelope.")
+ status = dict(line.split(":", 1) for line in Path("/proc/self/status").read_text().splitlines() if ":" in line)
+ proof["process_status"] = {
+ name: status[name].strip()
+ for name in (*CAPABILITY_FIELDS, "NoNewPrivs", "Seccomp") if name in status
+ }
+ require_kernel_evidence(proof)
+ if (os.getuid() == 0
+ or os.getuid() != os.geteuid() or os.getuid() != proof["uid"] or os.getgid() != proof["gid"]):
+ raise RuntimeError("Candidate process has not dropped privilege.")
+ context = StorageContext.from_parent(proof["storage_context"])
+ if context.uid != proof["uid"] or context.fingerprint() != proof["storage_sha256"]:
+ raise RuntimeError("Parent storage context identity does not match.")
+ root = _absolute(proof["root"], "parent task root")
+ output = _absolute(proof["output"], "parent output")
+ state = _absolute(proof["state"], "parent cache")
+ receipt = proof["receipt"]
+ if (not isinstance(receipt, str) or Path(receipt).name != receipt or receipt in ("", ".", "..")
+ or output != root / "runs" / receipt or state == root or not state.is_relative_to(root)
+ or state == output or state.is_relative_to(output) or output.is_relative_to(state)
+ or output.is_symlink() or output.stat().st_uid != proof["uid"]
+ or stat.S_IMODE(output.stat().st_mode) != 0o750):
+ raise RuntimeError("Private task ownership does not match the exclusive invocation.")
+ for target in (root, output, state):
+ if context.validate(target) != target:
+ raise RuntimeError("Private task roots must match parent canonical identities.")
+ proof["actual_uid"], proof["actual_gid"] = os.getuid(), os.getgid()
+ return proof
+
+
+def namespace_receipt() -> dict:
+ """Public evidence excludes original user paths; retain only their digest."""
+ proof = _namespace_proof()
+ return {name: value for name, value in proof.items() if name != "storage_context"}
+
+
+def environment_directories(root: Path, cache: Path) -> list[tuple[Path, str]]:
+ directories = [(root, name) for name in ("home", "tmp", "config", "data")]
+ return directories + [(cache, name) for name in ("cache", "go", "mod")]
+
+
+def preparation_directories(root: Path) -> tuple[Path, ...]:
+ """Admit the entire documented setup plan, without creating anything."""
+ context = storage_context()
+ canonical = validate_temporary_root(root, context=context)
+ if root != canonical:
+ raise ValueError("Preparation requires an absolute canonical task directory.")
+ state = root / "state"
+ directories = [root / name for name in (
+ "recipe", "source", "state", "downloads", "toolchain", "uv-toolchain", "venv", "fixtures",
+ )]
+ directories += [owner / name for owner, name in environment_directories(state, state)]
+ directories.append(state / "uv-cache")
+ # Check actual descendants and their aliases before even the first mkdir,
+ # copy, Git invocation or export. An admitted ancestor is not sufficient.
+ for path in directories:
+ if context.validate(path) != path:
+ raise ValueError("Preparation destinations must not use aliases.")
+ info = root.lstat()
+ if (not stat.S_ISDIR(info.st_mode) or info.st_uid != context.uid
+ or stat.S_IMODE(info.st_mode) != 0o700):
+ raise ValueError("Preparation requires a caller-owned mode-0700 task directory.")
+ if any(root.iterdir()):
+ raise ValueError("Preparation requires an empty task; preserve all existing contents.")
+ return tuple(directories)
+
+
+def isolated_environment(root: Path, *, cache: Path | None = None, go: Path | None = None) -> dict[str, str]:
+ context = storage_context()
+ root = context.validate(root)
+ cache = context.validate(cache) if cache is not None else root
+ directories = environment_directories(root, cache)
+ # Validate all aliases before the FIRST write, not while creating folders.
+ for owner, name in directories:
+ target = context.validate(owner / name)
+ if not target.is_relative_to(owner):
+ raise ValueError("Environment directory escapes its task root.")
+ root.mkdir(parents=True, exist_ok=True)
+ cache.mkdir(parents=True, exist_ok=True)
+ for owner, name in directories:
+ (owner / name).mkdir(exist_ok=True)
+ return {
+ "PATH": str((go or Path(shutil.which("go") or "/usr/bin/go")).parent) + os.pathsep + os.defpath,
+ "HOME": str(root / "home"),
+ "TMPDIR": str(root / "tmp"),
+ "AVIBE_HOME": str(root / "home" / ".avibe"),
+ "XDG_CONFIG_HOME": str(root / "config"),
+ "XDG_CACHE_HOME": str(cache / "cache"),
+ "XDG_DATA_HOME": str(root / "data"),
+ "GOPATH": str(cache / "go"),
+ "GOMODCACHE": str(cache / "mod"),
+ "GOCACHE": str(cache / "cache"),
+ "GOENV": "off",
+ "GOTOOLCHAIN": "local",
+ "GOMAXPROCS": "2",
+ "GOMEMLIMIT": "1536MiB",
+ "CGO_ENABLED": "0",
+ "GOPROXY": "off",
+ "GOSUMDB": "sum.golang.org",
+ "HTTP_PROXY": "http://127.0.0.1:1",
+ "HTTPS_PROXY": "http://127.0.0.1:1",
+ "NO_PROXY": "127.0.0.1,localhost",
+ "PYTHONDONTWRITEBYTECODE": "1",
+ }
+
+
+def sandbox_prefix(root: Path, *, required_inputs: tuple[Path, ...] | None = None) -> list[str]:
+ """Finite macOS diagnostic inputs; OS enforcement/startup remain unqualified."""
+ context = storage_context()
+ lexical_root = root
+ root = context.validate(root)
+ if sys.platform == "linux":
+ proof = namespace_receipt()
+ if Path(proof["state"]) != root.resolve():
+ raise RuntimeError("State does not belong to this isolated envelope.")
+ return []
+ if sys.platform != "darwin" or not Path("/usr/bin/sandbox-exec").is_file():
+ raise RuntimeError("This recipe requires macOS sandbox-exec; no unsandboxed fallback.")
+ if not isinstance(required_inputs, tuple) or not 1 <= len(required_inputs) <= 32:
+ raise ValueError("Declare the finite inspected recipe/source/interpreter/system inputs.")
+ root = context.read_input(lexical_root)
+ inputs = [root]
+ for path in (*required_inputs, Path("/usr/bin/sandbox-exec"), Path("/dev/null")):
+ admitted = context.read_input(path)
+ if admitted != root and root.is_relative_to(admitted):
+ raise ValueError("Do not grant a whole task/project ancestor as a diagnostic input.")
+ inputs.append(admitted)
+
+ def quote(value: Path) -> str:
+ return json.dumps(str(value))
+
+ boundaries = sorted(set((*context.homes, *context.protected)))
+ exclusions = " ".join(f"(require-not (subpath {quote(path)}))" for path in boundaries)
+ # No Mach/XPC/POSIX/System V service is required by this diagnostic.
+ # Missing startup authority must fail closed, never inherit allow-default.
+ policy = ('(version 1) (deny default) (deny network*) (deny file-write*) (deny file-read*) '
+ '(allow process-exec) (allow process-fork) ')
+ for path in sorted(set(inputs)):
+ matcher = "literal" if path == Path("/dev/null") else "subpath"
+ policy += f"(allow file-read* (require-all ({matcher} {quote(path)}) {exclusions})) "
+ policy += f"(allow file-write* (require-all (subpath {quote(root)}) {exclusions})) "
+ policy += f'(allow file-write* (require-all (literal "/dev/null") {exclusions})) '
+ for boundary in boundaries:
+ policy += f'(deny file-read* (subpath {quote(boundary)})) '
+ return ["/usr/bin/sandbox-exec", "-p", policy]
diff --git a/patches/cliproxyapi/isolation_probe.py b/patches/cliproxyapi/isolation_probe.py
new file mode 100644
index 000000000..03eba4ebc
--- /dev/null
+++ b/patches/cliproxyapi/isolation_probe.py
@@ -0,0 +1,133 @@
+"""Consuming namespace checks before any Go suite or actual engine starts."""
+
+from __future__ import annotations
+
+import http.client
+import errno
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+import json
+import os
+from pathlib import Path
+import socket
+import subprocess
+import sys
+import threading
+
+from isolation import namespace_receipt, require_kernel_evidence
+
+
+def probe_blocked_connection(network: str, host: str, port: int, kind: str) -> dict:
+ """Accept only an observed connection error, never a successful connection."""
+ if kind == "subprocess":
+ child = subprocess.run(
+ [sys.executable, "-I", "-B", "-c",
+ "import socket,sys\ntry:\n s=socket.create_connection((sys.argv[1],int(sys.argv[2])),timeout=1)\nexcept OSError as exc:\n print(exc.errno)\nelse:\n s.sendall(b'forbidden'); s.close(); sys.exit(3)",
+ host, str(port)], capture_output=True, close_fds=True, timeout=3,
+ )
+ assert child.returncode == 0, child.stderr
+ observed_errno = int(child.stdout)
+ else:
+ try:
+ if kind == "direct-ip":
+ with socket.create_connection((host, port), timeout=1) as connection:
+ connection.sendall(b"forbidden")
+ raise AssertionError("Direct socket reached outside sentinel.")
+ connection = http.client.HTTPConnection(host, port, timeout=1)
+ try:
+ method = "CONNECT" if kind == "connect-proxy" else "GET"
+ target = "example.invalid:443" if kind == "connect-proxy" else (
+ "http://example.invalid/" if kind == "http-proxy" else "/"
+ )
+ headers = {"Connection": "Upgrade", "Upgrade": "websocket"} if kind == "websocket" else {}
+ connection.request(method, target, headers=headers)
+ raise AssertionError(f"{kind} reached outside sentinel.")
+ finally:
+ connection.close()
+ except OSError as exc:
+ observed_errno = exc.errno
+ allowed = (errno.ECONNREFUSED, errno.ENETUNREACH, errno.EHOSTUNREACH, errno.EACCES, errno.EPERM)
+ # With loopback down, IPv6 has no usable local address in the empty netns.
+ if network == "none" and host == "::1":
+ allowed += (errno.EADDRNOTAVAIL,)
+ assert observed_errno in allowed, (network, host, kind, observed_errno)
+ return {"host": host, "kind": kind, "blocked": True, "errno": observed_errno}
+
+
+def main() -> None:
+ proof = namespace_receipt()
+ # Consume the same exact four-namespace/filter schema before any probe
+ # socket or filesystem effect. A Seccomp=2 string alone is not its identity.
+ require_kernel_evidence(proof)
+ attempts = [
+ probe_blocked_connection(proof["network"], host, port, kind)
+ for host, port in zip(("127.0.0.1", "::1"), proof["sentinel_ports"])
+ for kind in ("http", "websocket", "http-proxy", "connect-proxy", "direct-ip", "subprocess")
+ ]
+ for name in ("source", "fixture", "recipe", "toolchain", "python_env"):
+ target = Path(proof[name]) / ".isolation-write-probe"
+ try:
+ target.write_bytes(b"must-not-write")
+ except OSError:
+ pass
+ else:
+ raise AssertionError(f"{name} is writable.")
+ for path in ("/Users", "/home", "/root", "/sys", "/run/netns"):
+ assert not Path(path).exists(), f"Guest/user namespace surface exposed: {path}"
+ assert not any("shared:" in line for line in Path("/proc/self/mountinfo").read_text().splitlines())
+ assert os.getuid() == proof["uid"] != 0 and os.getgid() == proof["gid"] != 0
+ state = Path(proof["state"])
+ representative_write = state / "writable-state-probe"
+ representative_write.write_bytes(b"test-owned")
+ representative_write.unlink()
+ output = Path(proof["output"])
+ representative_write = output / "writable-output-probe"
+ representative_write.write_bytes(b"this-invocation-only")
+ representative_write.unlink()
+ if proof["selected_build"] is not None:
+ target = Path(proof["selected_build"]["output"]) / ".isolation-write-probe"
+ try:
+ target.write_bytes(b"must-not-write")
+ except OSError:
+ pass
+ else:
+ raise AssertionError("Previous build output is writable.")
+
+ positive = []
+ if proof["network"] == "loopback":
+ class Handler(BaseHTTPRequestHandler):
+ def do_GET(self):
+ self.send_response(200)
+ self.end_headers()
+ self.wfile.write(b"private-listener")
+
+ def log_message(self, *_args):
+ pass
+
+ for family, host in ((socket.AF_INET, "127.0.0.1"), (socket.AF_INET6, "::1")):
+ class Server(ThreadingHTTPServer):
+ address_family = family
+
+ with Server((host, 0), Handler) as server:
+ thread = threading.Thread(target=server.serve_forever)
+ thread.start()
+ connection = http.client.HTTPConnection(host, server.server_address[1], timeout=2)
+ try:
+ connection.request("GET", "/")
+ assert connection.getresponse().read() == b"private-listener"
+ positive.append(host)
+ finally:
+ connection.close()
+ server.shutdown()
+ thread.join(timeout=2)
+ assert not thread.is_alive()
+ result = {**proof, "isolation_probe": "pass", "blocked_attempts": attempts, "positive_listeners": positive,
+ "readonly_source_fixture_recipe": True, "readonly_toolchain_python": True,
+ "previous_build_readonly": proof["selected_build"] is not None,
+ "task_state_write": True, "exclusive_output_write": True}
+ # The privileged supervisor captures this dedicated preflight stdout before
+ # candidate execution. No proof is published into mutable candidate state.
+ print(json.dumps(result), flush=True)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/patches/cliproxyapi/namespace.py b/patches/cliproxyapi/namespace.py
new file mode 100644
index 000000000..0112d979a
--- /dev/null
+++ b/patches/cliproxyapi/namespace.py
@@ -0,0 +1,932 @@
+"""Temporary Linux test envelope; no VM, host network, package or service setup.
+
+Run with sudo only in an explicitly allocated task directory. Privileged setup
+finishes before any candidate/test code runs. Every mount lives in the child
+mount namespace, and its PID 1 exit destroys all remaining child processes.
+"""
+
+from __future__ import annotations
+
+import argparse
+from contextlib import ExitStack
+import ctypes
+import hashlib
+import json
+import os
+from pathlib import Path
+import platform
+import resource
+import secrets
+import socket
+import stat
+import struct
+import subprocess
+import sys
+import threading
+
+from budgets import PHASES
+from isolation import (
+ NAMESPACE_NAMES, STORAGE_ENV, StorageContext, environment_directories,
+ keyring_identity, require_kernel_evidence, require_namespace_ids, require_namespaces,
+ validate_state_root, validate_temporary_root,
+)
+
+
+# No public re-entry option. Only the parent constructs this fixed invocation,
+# with an unnamed control descriptor in pass_fds, after parsing the public CLI.
+# Arbitrary root Python is outside this approved CLI's threat boundary.
+CHILD_TRAMPOLINE = """
+import hashlib, json, os, resource, stat, sys, types
+def bootstrap():
+ with os.fdopen(int(sys.argv[1]), "rb") as control:
+ info = os.fstat(control.fileno())
+ if (not stat.S_ISREG(info.st_mode) or info.st_uid != 0 or info.st_nlink != 0
+ or stat.S_IMODE(info.st_mode) != 0o600):
+ raise RuntimeError("Missing unnamed root-owned parent handoff.")
+ raw = control.read(65537)
+ if len(raw) > 65536:
+ raise RuntimeError("Oversized parent handoff.")
+ values = json.loads(raw)
+ sources = values.pop("bootstrap")
+ if not isinstance(sources, dict) or set(sources) != {"budgets", "isolation", "namespace"}:
+ raise RuntimeError("Incomplete fixed bootstrap.")
+ verified = {}
+ fds = [record.get("fd") for record in sources.values() if isinstance(record, dict)]
+ if len(fds) != 3 or any(type(fd) is not int or fd < 3 for fd in fds) or len(set(fds)) != 3:
+ raise RuntimeError("Invalid bootstrap descriptor.")
+ try:
+ for name in ("budgets", "isolation", "namespace"):
+ record = sources[name]
+ fd = record["fd"]
+ info = os.fstat(fd)
+ identity = {field: getattr(info, "st_" + field) for field in
+ ("dev", "ino", "mode", "uid", "gid", "rdev")}
+ if not stat.S_ISREG(info.st_mode) or identity != record["identity"] or info.st_size > 65536:
+ raise RuntimeError("Bootstrap source identity changed.")
+ data = os.pread(fd, 65537, 0)
+ if len(data) > 65536 or hashlib.sha256(data).hexdigest() != record["sha256"]:
+ raise RuntimeError("Bootstrap source contents changed.")
+ verified[name] = data
+ finally:
+ for fd in fds:
+ os.close(fd)
+ # All source bytes are verified before the first non-stdlib import/effect.
+ for name in ("budgets", "isolation", "namespace"):
+ module = types.ModuleType(name)
+ module.__file__ = values["recipe"] + "/" + name + ".py"
+ sys.modules[name] = module
+ exec(compile(verified[name], module.__file__, "exec"), module.__dict__)
+ sys.modules["namespace"].child_from_control(values)
+try:
+ bootstrap()
+except Exception:
+ # Fresh, single-purpose child: close every inherited/partial acquisition on
+ # malformed handoff/import/setup failure, without inspecting Linux proc.
+ os.closerange(3, int(resource.getrlimit(resource.RLIMIT_NOFILE)[0]))
+ raise
+"""
+
+INPUT_NAMES = ("source", "fixture", "state", "recipe", "toolchain", "python_env", "go_archive")
+MS_RDONLY, MS_NOSUID, MS_NODEV, MS_NOEXEC = 1, 2, 4, 8
+MS_REMOUNT, MS_BIND, MS_REC, MS_PRIVATE = 32, 4096, 16384, 1 << 18
+
+
+def require_native_abi() -> None:
+ """Only the inspected native ABI; this does not measure guest support."""
+ if (sys.platform != "linux" or platform.machine() != "aarch64"
+ or sys.byteorder != "little" or ctypes.sizeof(ctypes.c_void_p) != 8):
+ raise RuntimeError("Unsupported Linux syscall ABI; require native AArch64 little-endian64.")
+
+
+def keyring_program() -> bytes:
+ """The finite inspected classic-BPF program, not a general syscall policy."""
+ instructions = (
+ (0x20, 0, 0, 4), (0x15, 1, 0, 0xC00000B7), (0x06, 0, 0, 0x80000000),
+ (0x20, 0, 0, 0), (0x35, 0, 1, 0x40000000), (0x06, 0, 0, 0x80000000),
+ (0x15, 3, 0, 217), (0x15, 2, 0, 218), (0x15, 1, 0, 219),
+ (0x06, 0, 0, 0x7FFF0000), (0x06, 0, 0, 0x00050001),
+ )
+ return b"".join(struct.pack("<HBBI", *item) for item in instructions)
+
+
+class SockFilter(ctypes.Structure):
+ _fields_ = [("code", ctypes.c_ushort), ("jt", ctypes.c_ubyte),
+ ("jf", ctypes.c_ubyte), ("k", ctypes.c_uint32)]
+
+
+class SockFprog(ctypes.Structure):
+ _fields_ = [("len", ctypes.c_ushort), ("filter", ctypes.POINTER(SockFilter))]
+
+
+def linux_prctl(option: int, a2: int = 0, a3: int = 0, a4: int = 0, a5: int = 0) -> int:
+ require_native_abi()
+ call = ctypes.CDLL(None, use_errno=True).prctl
+ # prctl is variadic: every trailing argument is explicitly native unsigned
+ # long, including the sock_fprog pointer value. Never truncate it to int.
+ call.argtypes = [ctypes.c_int, *([ctypes.c_ulong] * 4)]
+ call.restype = ctypes.c_int
+ ctypes.set_errno(0)
+ result = call(option, a2, a3, a4, a5)
+ if result == -1:
+ raise OSError(ctypes.get_errno(), "Linux prctl failed.")
+ return result
+
+
+def install_keyring_boundary() -> dict:
+ require_native_abi()
+ raw = keyring_program()
+ expected = keyring_identity()
+ if len(raw) != 88 or hashlib.sha256(raw).hexdigest() != expected["program_sha256"]:
+ raise RuntimeError("Unexpected keyring filter program.")
+ array = (SockFilter * (len(raw) // 8)).from_buffer_copy(raw)
+ program = SockFprog(len(array), array)
+ address = ctypes.cast(ctypes.pointer(program), ctypes.c_void_p).value
+ # Keep array/program alive through installation and every readback.
+ for option, argument, pointer, result in ((38, 1, 0, 0), (22, 2, address, 0),
+ (39, 0, 0, 1), (21, 0, 0, 2)):
+ actual = linux_prctl(option, argument, pointer, 0, 0)
+ if type(actual) is not int or actual != result:
+ raise RuntimeError("Keyring filter/no-new-privileges installation or readback failed.")
+ return expected
+
+
+def linux_mount(source: str | None, target: str, filesystem: str | None,
+ flags: int, data: str | None = None) -> None:
+ """Direct native mount(2), never mount(8) helpers or config.
+
+ HOST consumers intercept this adapter. Actual proc-FD bind/overmount
+ semantics and the installed Linux kernel remain execution prerequisites.
+ """
+ require_native_abi()
+ if (not isinstance(target, str) or not target.startswith("/") or "\0" in target
+ or type(flags) is not int or not 0 <= flags < 2**64):
+ raise ValueError("Invalid native mount target or flags.")
+
+ def encoded(value):
+ if value is None:
+ return None
+ if not isinstance(value, str) or "\0" in value:
+ raise ValueError("Invalid mount argument.")
+ return os.fsencode(value)
+ source_bytes, target_bytes, type_bytes, data_bytes = map(encoded, (source, target, filesystem, data))
+ call = ctypes.CDLL(None, use_errno=True).mount
+ call.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_ulong, ctypes.c_void_p]
+ call.restype = ctypes.c_int
+ data_pointer = ctypes.cast(ctypes.c_char_p(data_bytes), ctypes.c_void_p) if data_bytes is not None else None
+ ctypes.set_errno(0)
+ if call(source_bytes, target_bytes, type_bytes, flags, data_pointer) != 0:
+ raise OSError(ctypes.get_errno(), "Linux mount failed.")
+
+
+def descriptor_identity(info) -> dict:
+ return {field: getattr(info, "st_" + field) for field in ("dev", "ino", "mode", "uid", "gid", "rdev")}
+
+
+def retained_handle(fd: int, kind: str) -> dict:
+ info = os.fstat(fd)
+ predicate = {"directory": stat.S_ISDIR, "file": stat.S_ISREG, "device": stat.S_ISCHR}[kind]
+ if not predicate(info.st_mode):
+ raise ValueError("Pinned resource has the wrong type.")
+ return {"fd": fd, "kind": kind, "identity": descriptor_identity(info)}
+
+
+def check_handle(record: dict) -> int:
+ if (not isinstance(record, dict) or type(record.get("fd")) is not int or record["fd"] < 3
+ or record.get("kind") not in ("directory", "file", "device")):
+ raise RuntimeError("Invalid pinned resource.")
+ if retained_handle(record["fd"], record["kind"]) != record:
+ raise RuntimeError("Pinned resource identity changed.")
+ return record["fd"]
+
+
+def pin_beneath(stack: ExitStack, root_fd: int, relative: Path, *, kind: str,
+ expected: dict | None = None) -> dict:
+ if relative.is_absolute() or not relative.parts or any(part in (".", "..") for part in relative.parts):
+ raise ValueError("Pinned input must be a nonempty relative path.")
+ current = root_fd
+ for index, part in enumerate(relative.parts):
+ selected_kind = kind if index == len(relative.parts) - 1 else "directory"
+ flags = os.O_RDONLY | os.O_NOFOLLOW | os.O_CLOEXEC | os.O_NONBLOCK
+ if selected_kind == "directory":
+ flags |= os.O_DIRECTORY
+ elif selected_kind == "device":
+ require_native_abi()
+ # Linux asm-generic/fcntl.h. O_PATH opens no device for I/O.
+ flags = 0o10000000 | os.O_NOFOLLOW | os.O_CLOEXEC
+ current = os.open(part, flags, dir_fd=current)
+ stack.callback(os.close, current)
+ record = retained_handle(current, selected_kind)
+ if expected is not None and record["identity"] != expected:
+ raise ValueError("Pinned resource changed after admission.")
+ return record
+
+
+def pin_system_resources(stack: ExitStack) -> tuple[list[dict], dict]:
+ """Finite trusted-system prerequisite, not caller-supplied input policy."""
+ require_native_abi()
+ fd = os.open("/", os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC | os.O_NONBLOCK)
+ stack.callback(os.close, fd)
+ mounts, aliases = [], {}
+
+ def pin(path: str, kind: str, *, writable: bool = False):
+ record = pin_beneath(stack, fd, Path(path).relative_to("/"), kind=kind)
+ info = record["identity"]
+ if info["uid"] != 0 or (kind != "device" and info["mode"] & 0o002):
+ raise RuntimeError("Installed system inputs must retain their inspected trusted ownership.")
+ mounts.append({"path": path, "resource": record, "writable": writable})
+
+ for name in ("/usr/bin", "/usr/sbin", "/usr/lib", "/usr/share"):
+ pin(name, "directory")
+ for name in ("bin", "sbin", "lib", "lib64"):
+ try:
+ info = os.stat(name, dir_fd=fd, follow_symlinks=False)
+ except FileNotFoundError:
+ continue
+ if stat.S_ISLNK(info.st_mode):
+ if info.st_uid != 0:
+ raise RuntimeError("Untrusted installed system alias.")
+ value = os.readlink(name, dir_fd=fd)
+ if value not in ("usr/" + name, "/usr/" + name):
+ raise RuntimeError("Unexpected installed system alias; no inferred target.")
+ aliases[name] = value
+ else:
+ pin("/" + name, "directory")
+ # No host RNG device authority: syscall randomness is unchanged. A consumer
+ # requiring an RNG pathname lacks a startup prerequisite; do not add a fallback.
+ for name, minor in (("null", 3), ("zero", 5)):
+ pin("/dev/" + name, "device", writable=True)
+ device = mounts[-1]["resource"]["identity"]["rdev"]
+ if (os.major(device), os.minor(device)) != (1, minor):
+ raise RuntimeError("Unexpected installed device identity.")
+ return mounts, aliases
+
+
+def pin_bootstrap(stack: ExitStack, recipe: dict) -> dict:
+ result = {}
+ for name in ("budgets", "isolation", "namespace"):
+ record = pin_beneath(stack, check_handle(recipe), Path(name + ".py"), kind="file")
+ fd = record["fd"]
+ raw = os.pread(fd, 65537, 0)
+ if len(raw) > 65536:
+ raise RuntimeError("Oversized inspected bootstrap source.")
+ result[name] = {"fd": fd, "identity": record["identity"], "sha256": hashlib.sha256(raw).hexdigest()}
+ return result
+
+
+def _proc_field(directory: int, name: str, limit: int) -> bytes:
+ fd = os.open(name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=directory)
+ with os.fdopen(fd, "rb") as stream:
+ info = os.fstat(stream.fileno())
+ if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:
+ raise RuntimeError("Original sudo process metadata is unavailable.")
+ value = stream.read(limit + 1)
+ if len(value) > limit:
+ raise RuntimeError("Original sudo process metadata exceeds its bound.")
+ return value
+
+
+def sudo_storage_context(uid: int, expected: str) -> StorageContext:
+ """Bind pre-sudo caller identity to the live sudo process, never root's HOME.
+
+ Linux proc environ exposes the process's exec-time environment. If sudo
+ scrubs it, execs away, or otherwise makes it unavailable, the caller's
+ independently captured digest will not match and setup fails closed.
+ No caller-authored list of allegedly safe roots is accepted.
+ """
+ if len(expected) != 64 or any(character not in "0123456789abcdef" for character in expected):
+ raise ValueError("An exact original-caller storage digest is required.")
+ parent = os.getppid()
+ fd = os.open(f"/proc/{parent}", os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
+ try:
+ sudo = os.stat("/usr/bin/sudo", follow_symlinks=False)
+ executable = os.stat("exe", dir_fd=fd)
+ if (not stat.S_ISREG(sudo.st_mode) or sudo.st_uid != 0 or sudo.st_mode & 0o022
+ or (executable.st_dev, executable.st_ino) != (sudo.st_dev, sudo.st_ino)):
+ raise RuntimeError("Original context requires the live /usr/bin/sudo parent.")
+ before = _proc_field(fd, "stat", 8192).rsplit(b")", 1)[1].split()[19]
+ raw = _proc_field(fd, "environ", 1024 * 1024)
+ selected = {}
+ names = {name.encode(): name for name in STORAGE_ENV}
+ for entry in raw.split(b"\0"):
+ name, separator, value = entry.partition(b"=")
+ if separator and name in names:
+ key = names[name]
+ if key in selected:
+ raise RuntimeError("Ambiguous original storage environment.")
+ try:
+ selected[key] = value.decode("utf-8")
+ except UnicodeError:
+ raise ValueError("Invalid original storage path encoding.") from None
+ context = StorageContext.capture(uid=uid, environment=selected)
+ after = _proc_field(fd, "stat", 8192).rsplit(b")", 1)[1].split()[19]
+ if (os.getppid() != parent or before != after
+ or _proc_field(fd, "environ", 1024 * 1024) != raw
+ or context.fingerprint() != expected):
+ raise RuntimeError("Original caller storage context was lost or changed before sudo.")
+ finally:
+ os.close(fd)
+ # Root's own passwd-home protection is additive, never a replacement for
+ # the invoking user's effective HOME and configured storage authorities.
+ return context.with_root_identity()
+
+
+def namespace_ids() -> dict[str, str]:
+ return {name: os.readlink(f"/proc/self/ns/{name}") for name in NAMESPACE_NAMES}
+
+
+class Sentinel:
+ """Task-owned outside-namespace listener; even one accepted connection fails."""
+
+ def __init__(self, family: int):
+ self.socket = socket.socket(family)
+ if family == socket.AF_INET6:
+ self.socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
+ self.socket.bind(("::1" if family == socket.AF_INET6 else "127.0.0.1", 0))
+ self.socket.listen()
+ self.socket.settimeout(0.1)
+ self.port = self.socket.getsockname()[1]
+ self.connections = 0
+ self.stopping = threading.Event()
+ self.thread = threading.Thread(target=self.run)
+ self.thread.start()
+
+ def run(self) -> None:
+ while not self.stopping.is_set():
+ try:
+ connection, _ = self.socket.accept()
+ except TimeoutError:
+ continue
+ self.connections += 1
+ connection.close()
+
+ def close(self) -> None:
+ self.stopping.set()
+ self.thread.join(timeout=2)
+ self.socket.close()
+ if self.thread.is_alive():
+ raise RuntimeError("Sentinel thread did not stop.")
+
+
+def run(*command: str) -> None:
+ subprocess.run(command, check=True, stdin=subprocess.DEVNULL, close_fds=True)
+
+
+def run_candidate(args: argparse.Namespace, drop: list[str], env: dict[str, str]) -> int:
+ """Capture the read-only probe before candidate code, then close its channel."""
+ # This unlinked, parent-opened file has no name in the child's filesystem.
+ # Neither subprocess inherits its descriptor; it closes before the candidate.
+ with os.fdopen(args.proof_fd, "wb") as channel:
+ probe = [str(args.python_env / "bin/python"), "-B", str(args.recipe / "isolation_probe.py")]
+ result = subprocess.run(
+ [*drop, *probe], env=env, cwd=args.state, close_fds=True,
+ stdout=subprocess.PIPE, timeout=PHASES[args.phase].preflight_seconds,
+ )
+ if result.returncode:
+ return result.returncode
+ if len(result.stdout) > 65536:
+ raise RuntimeError("Preflight result exceeds the receipt limit.")
+ proof = json.loads(result.stdout)
+ if proof.get("isolation_probe") != "pass":
+ raise RuntimeError("Preflight did not return a passing result.")
+ require_kernel_evidence(proof)
+ if proof["outer_namespaces"] != args.outer_namespaces:
+ raise RuntimeError("Preflight belongs to another parent namespace epoch.")
+ channel.write(result.stdout)
+ channel.flush()
+ os.fsync(channel.fileno())
+ try:
+ result = subprocess.run(
+ [*drop, *args.command], env=env, cwd=args.source, close_fds=True,
+ timeout=PHASES[args.phase].candidate_seconds,
+ )
+ except subprocess.TimeoutExpired:
+ # subprocess.run killed/waited for the direct child. PID 1 then exits
+ # so the kernel tears down any remaining descendants in this PID view.
+ print("Candidate exceeded the derived phase allowance.", file=sys.stderr, flush=True)
+ return 124
+ return result.returncode
+
+
+def check_root_descriptor(args: argparse.Namespace, root_fd: int) -> None:
+ """Recheck actual custody and pathname identity, never repair a supplied root."""
+ info = os.fstat(root_fd)
+ named = args.root.lstat()
+ if (args.root.resolve(strict=True) != args.root
+ or not stat.S_ISDIR(info.st_mode) or not stat.S_ISDIR(named.st_mode)
+ or info.st_uid != args.uid or stat.S_IMODE(info.st_mode) != 0o700
+ or (info.st_dev, info.st_ino, info.st_mode, info.st_uid)
+ != (named.st_dev, named.st_ino, named.st_mode, named.st_uid)):
+ raise ValueError("Privileged scratch must remain the caller-owned mode-0700 admitted directory.")
+
+
+def open_receipts(args: argparse.Namespace, stack: ExitStack, root_fd: int):
+ """Reserve root-owned output and an unnamed probe channel before execution."""
+ control = args.root / "receipts"
+ for name in ("source", "fixture", "state", "recipe", "toolchain", "python_env", "go_archive", "output"):
+ path = getattr(args, name)
+ if control == path or control.is_relative_to(path) or path.is_relative_to(control):
+ raise ValueError("Parent receipts must be outside every child bind mount.")
+ check_root_descriptor(args, root_fd)
+ created = False
+ try:
+ os.mkdir("receipts", mode=0o750, dir_fd=root_fd)
+ created = True
+ except FileExistsError:
+ pass
+ control_fd = os.open("receipts", os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW |
+ os.O_NONBLOCK | os.O_CLOEXEC, dir_fd=root_fd)
+ stack.callback(os.close, control_fd)
+ if created:
+ os.fchown(control_fd, -1, args.gid)
+ os.fchmod(control_fd, 0o750)
+ info = os.fstat(control_fd)
+ if info.st_uid != os.getuid() or info.st_gid != args.gid or stat.S_IMODE(info.st_mode) != 0o750:
+ raise RuntimeError("Refusing a preexisting receipt directory with different ownership or permissions.")
+ flags = os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_CLOEXEC
+ terminal_fd = os.open(args.receipt, os.O_WRONLY | flags, 0o640, dir_fd=control_fd)
+ terminal = stack.enter_context(os.fdopen(terminal_fd, "w"))
+ os.fchown(terminal.fileno(), -1, args.gid)
+ os.fchmod(terminal.fileno(), 0o640)
+ probe_name = args.receipt + ".preflight"
+ probe_fd = os.open(probe_name, os.O_RDWR | flags, 0o600, dir_fd=control_fd)
+ probe = stack.enter_context(os.fdopen(probe_fd, "r+b"))
+ # Unlink while still in setup. There are no path-based reads, writes,
+ # chowns or unlinks of receipt/probe artifacts after candidate execution.
+ os.unlink(probe_name, dir_fd=control_fd)
+ handoff_name = args.receipt + ".control"
+ handoff_fd = os.open(handoff_name, os.O_RDWR | flags, 0o600, dir_fd=control_fd)
+ handoff = stack.enter_context(os.fdopen(handoff_fd, "w+b"))
+ os.unlink(handoff_name, dir_fd=control_fd)
+ return terminal, probe, handoff, control_fd
+
+
+def allocate_output(args: argparse.Namespace, stack: ExitStack, root_fd: int) -> tuple[dict, dict]:
+ """One new child-writable output, beneath a parent-owned unmounted directory."""
+ check_root_descriptor(args, root_fd)
+ try:
+ os.mkdir("runs", mode=0o750, dir_fd=root_fd)
+ created = True
+ except FileExistsError:
+ created = False
+ runs_fd = os.open("runs", os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW |
+ os.O_NONBLOCK | os.O_CLOEXEC, dir_fd=root_fd)
+ stack.callback(os.close, runs_fd)
+ if created:
+ os.fchown(runs_fd, -1, args.gid)
+ os.fchmod(runs_fd, 0o750)
+ info = os.fstat(runs_fd)
+ if info.st_uid != os.getuid() or info.st_gid != args.gid or stat.S_IMODE(info.st_mode) != 0o750:
+ raise RuntimeError("Run collection must be parent-owned, not child-writable.")
+ os.mkdir(args.receipt, mode=0o750, dir_fd=runs_fd)
+ output_fd = os.open(args.receipt, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW |
+ os.O_NONBLOCK | os.O_CLOEXEC, dir_fd=runs_fd)
+ stack.callback(os.close, output_fd)
+ os.fchown(output_fd, args.uid, args.gid)
+ os.fchmod(output_fd, 0o750)
+ return retained_handle(runs_fd, "directory"), retained_handle(output_fd, "directory")
+
+
+def selected_build_receipt(args: argparse.Namespace, control_fd: int, build: dict | None = None) -> dict | None:
+ """Read only a prior PARENT-owned terminal receipt before candidate launch."""
+ if args.build is None:
+ return None
+ fd = os.open(args.build.name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=control_fd)
+ with os.fdopen(fd, "rb") as stream:
+ info = os.fstat(stream.fileno())
+ if (not stat.S_ISREG(info.st_mode) or info.st_nlink != 1
+ or info.st_uid != os.getuid() or stat.S_IMODE(info.st_mode) != 0o640):
+ raise RuntimeError("Selected build lacks an exclusive parent-owned receipt.")
+ raw = stream.read(65537)
+ if len(raw) > 65536:
+ raise RuntimeError("Selected build parent receipt is oversized.")
+ previous = json.loads(raw)
+ if previous.get("status") != "passed" or previous.get("phase") != "build" or previous.get("output") != str(args.build):
+ raise RuntimeError("Selected build does not have a successful matching parent receipt.")
+ if build is None or previous.get("output_identity") != build["identity"]:
+ raise RuntimeError("Selected build directory does not match its parent-owned receipt.")
+ check_handle(build)
+ return {"output": str(args.build), "receipt": args.build.name,
+ "parent_receipt_sha256": hashlib.sha256(raw).hexdigest(),
+ "output_identity": build["identity"]}
+
+
+def child_from_control(values: dict) -> None:
+ """Only the fixed trampoline supplies its already-authenticated bounded body."""
+ outer = values.pop("outer_namespaces")
+ for name in ("root", "rootfs", "source", "fixture", "state", "recipe", "toolchain",
+ "python_env", "go_archive", "output", "build"):
+ values[name] = Path(values[name]) if values[name] is not None else None
+ inside(argparse.Namespace(**values), outer)
+
+
+def protected_directory(stack: ExitStack, root_fd: int, relative: Path) -> int:
+ """Create only fresh-rootfs topology; never traverse an already-bound input."""
+ if relative.is_absolute() or ".." in relative.parts:
+ raise ValueError("Rootfs target must be relative.")
+ current = root_fd
+ for component in relative.parts:
+ try:
+ os.mkdir(component, mode=0o755, dir_fd=current)
+ except FileExistsError:
+ pass
+ current = os.open(component, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW |
+ os.O_CLOEXEC | os.O_NONBLOCK, dir_fd=current)
+ stack.callback(os.close, current)
+ info = os.fstat(current)
+ if info.st_uid != os.getuid() or info.st_mode & 0o022:
+ raise RuntimeError("Rootfs target parent lost privileged custody.")
+ return current
+
+
+def prepare_bind_target(stack: ExitStack, root_fd: int, path: Path, kind: str) -> tuple[int, str]:
+ relative = path.relative_to("/")
+ if not relative.parts or ".." in relative.parts:
+ raise ValueError("Invalid rootfs bind target.")
+ parent = protected_directory(stack, root_fd, relative.parent)
+ if kind == "directory":
+ os.mkdir(relative.name, mode=0o755, dir_fd=parent)
+ else:
+ fd = os.open(relative.name, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW |
+ os.O_CLOEXEC | os.O_NONBLOCK, 0o600, dir_fd=parent)
+ os.close(fd)
+ return parent, relative.name
+
+
+def fd_path(fd: int, component: str | None = None) -> str:
+ if type(fd) is not int or fd < 3:
+ raise ValueError("Invalid retained descriptor.")
+ path = f"/proc/self/fd/{fd}"
+ if component is not None:
+ if not component or Path(component).name != component or component in (".", "..") or "\0" in component:
+ raise ValueError("Expected one protected target component.")
+ path += "/" + component
+ return path
+
+
+def reopen_rootfs(stack: ExitStack, control: dict, rootfs: dict, name: str) -> int:
+ """Open the OVERMOUNT view, not the pre-mount descriptor's underlying inode."""
+ fd = os.open(name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW |
+ os.O_CLOEXEC | os.O_NONBLOCK, dir_fd=check_handle(control))
+ stack.callback(os.close, fd)
+ info = os.fstat(fd)
+ if (info.st_uid != os.getuid() or stat.S_IMODE(info.st_mode) != 0o755
+ or (info.st_dev, info.st_ino) == (rootfs["identity"]["dev"], rootfs["identity"]["ino"])):
+ raise RuntimeError("Rootfs did not become a distinct protected mounted view.")
+ return fd
+
+
+def remove_rootfs(control: dict, rootfs: dict, name: str) -> None:
+ """After namespace teardown, remove only our original empty mountpoint."""
+ fd = check_handle(control)
+ named = os.stat(name, dir_fd=fd, follow_symlinks=False)
+ if descriptor_identity(named) != rootfs["identity"]:
+ raise RuntimeError("Rootfs cleanup identity changed; preserve the replacement.")
+ os.rmdir(name, dir_fd=fd)
+
+
+def inside(args: argparse.Namespace, outer: dict) -> None:
+ records = [*getattr(args, "handles", {}).values(),
+ *(item["resource"] for item in getattr(args, "system_mounts", []))]
+ descriptors = [record.get("fd") for record in records if isinstance(record, dict)]
+ owned = {fd for fd in descriptors if type(fd) is int and fd >= 3}
+ try:
+ with ExitStack() as stack:
+ for fd in owned:
+ stack.callback(os.close, fd)
+ actual = namespace_ids()
+ require_namespaces(outer, actual)
+ context = StorageContext.from_parent(args.storage_context)
+ if context.uid != args.uid:
+ raise RuntimeError("Private handoff lost its invoking storage owner.")
+ required = {"root", "control", "runs", "output", "rootfs", *INPUT_NAMES}
+ if args.build is not None:
+ required.add("build")
+ if set(args.handles) != required:
+ raise RuntimeError("Incomplete parent resource custody.")
+ if (len(owned) != len(records) or args.proof_fd in owned
+ or type(args.proof_fd) is not int or args.proof_fd < 3):
+ raise RuntimeError("Aliased or invalid private descriptor ownership.")
+ args.outer_namespaces = outer
+ for record in records:
+ check_handle(record)
+ root_info = args.handles["root"]["identity"]
+ if root_info["uid"] != args.uid or stat.S_IMODE(root_info["mode"]) != 0o700:
+ raise RuntimeError("Parent task root lost caller custody.")
+ for name in ("control", "runs", "rootfs"):
+ info = args.handles[name]["identity"]
+ if info["uid"] != os.getuid() or stat.S_IMODE(info["mode"]) != (0o700 if name == "rootfs" else 0o750):
+ raise RuntimeError("Parent control directory lost privileged custody.")
+ for name in ("state", "output"):
+ info = args.handles[name]["identity"]
+ if info["uid"] != args.uid or (name == "output" and stat.S_IMODE(info["mode"]) != 0o750):
+ raise RuntimeError("Writable resource lost invoking-user custody.")
+ # The original canonical paths remain labels for the private view.
+ # Do not resolve them again in a mutable outside pathname namespace.
+ for target in (args.root, args.state, args.output):
+ for boundary in context.protected:
+ if target == boundary or target.is_relative_to(boundary) or boundary.is_relative_to(target):
+ raise RuntimeError("Private labels overlap original protected storage.")
+ linux_mount(None, "/", None, MS_REC | MS_PRIVATE)
+ interfaces = json.loads(subprocess.check_output(
+ ["/usr/sbin/ip", "-j", "link"], close_fds=True, timeout=10,
+ ))
+ if [item["ifname"] for item in interfaces] != ["lo"]:
+ raise RuntimeError("Private namespace has an unexpected interface.")
+ if args.network == "loopback":
+ run("/usr/sbin/ip", "link", "set", "lo", "up")
+ control = args.handles["control"]
+ rootfs_target = fd_path(check_handle(control), args.rootfs.name)
+ linux_mount("tmpfs", rootfs_target, "tmpfs", MS_NOSUID | MS_NODEV, "mode=0755")
+ rootfs_fd = reopen_rootfs(stack, control, args.handles["rootfs"], args.rootfs.name)
+ mounts = list(args.system_mounts)
+ for name in (*INPUT_NAMES, "output", *(("build",) if args.build is not None else ())):
+ mounts.append({"path": str(getattr(args, name)), "resource": args.handles[name],
+ "writable": name in ("state", "output")})
+ # Every target and metadata file is opened BEFORE binding any
+ # caller-controlled contents. Later privileged work uses retained FDs.
+ targets = [prepare_bind_target(stack, rootfs_fd, Path(item["path"]), item["resource"]["kind"])
+ for item in mounts]
+ for name, value in args.system_aliases.items():
+ if name not in ("bin", "sbin", "lib", "lib64") or value not in ("usr/" + name, "/usr/" + name):
+ raise RuntimeError("Invalid trusted system alias.")
+ os.symlink(value, name, dir_fd=rootfs_fd)
+ dev = protected_directory(stack, rootfs_fd, Path("dev"))
+ os.symlink("/proc/self/fd", "fd", dir_fd=dev)
+ etc = protected_directory(stack, rootfs_fd, Path("etc"))
+ metadata = {
+ "passwd": f"root:x:0:0:root:/nonexistent:/bin/false\nsandbox:x:{args.uid}:{args.gid}:sandbox:/nonexistent:/bin/false\n",
+ "group": f"root:x:0:\nsandbox:x:{args.gid}:\n",
+ "hosts": "127.0.0.1 localhost\n::1 localhost\n",
+ "nsswitch.conf": "passwd: files\ngroup: files\nhosts: files\n", "resolv.conf": "",
+ }
+ for name, contents in metadata.items():
+ fd = os.open(name, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_CLOEXEC,
+ 0o644, dir_fd=etc)
+ with os.fdopen(fd, "w") as stream:
+ stream.write(contents)
+ proc_parent, proc_name = prepare_bind_target(stack, rootfs_fd, Path("/proc"), "directory")
+ run_fd = protected_directory(stack, rootfs_fd, Path("run"))
+ marker_fd = os.open("avibe-engine-test-isolation.json", os.O_WRONLY | os.O_CREAT | os.O_EXCL |
+ os.O_NOFOLLOW | os.O_CLOEXEC, 0o644, dir_fd=run_fd)
+ marker_stream = stack.enter_context(os.fdopen(marker_fd, "w"))
+ for item, (parent, name) in zip(mounts, targets):
+ source = check_handle(item["resource"])
+ target = fd_path(parent, name)
+ linux_mount(fd_path(source), target, None, MS_BIND)
+ flags = MS_BIND | MS_REMOUNT | MS_NOSUID
+ if item["resource"]["kind"] != "device":
+ flags |= MS_NODEV
+ if not item["writable"]:
+ flags |= MS_RDONLY
+ linux_mount(None, target, None, flags)
+ linux_mount("proc", fd_path(proc_parent, proc_name), "proc",
+ MS_RDONLY | MS_NOSUID | MS_NODEV | MS_NOEXEC, "hidepid=2")
+ boundary = install_keyring_boundary()
+ marker = {
+ "outer_namespaces": outer, "namespaces": actual, "network": args.network,
+ "uid": args.uid, "gid": args.gid, "sentinel_ports": args.sentinel_ports,
+ **{name: str(getattr(args, name)) for name in (*INPUT_NAMES, "root", "output")},
+ "receipt": args.receipt, "phase": args.phase, "budget": PHASES[args.phase].receipt(),
+ "selected_build": args.selected_build, "storage_context": context.record(),
+ "storage_sha256": context.fingerprint(), "keyring_boundary": boundary,
+ }
+ encoded = json.dumps(marker)
+ if len(encoded.encode()) > 65536:
+ raise RuntimeError("Oversized private marker.")
+ marker_stream.write(encoded)
+ marker_stream.flush()
+ marker_stream.close()
+ linux_mount(None, rootfs_target, None, MS_REMOUNT | MS_RDONLY | MS_NOSUID | MS_NODEV)
+ os.fchdir(rootfs_fd)
+ os.chroot(".")
+ os.chdir("/")
+ # Every specifically inherited/setup FD has closed before preflight.
+ except BaseException:
+ proof_fd = getattr(args, "proof_fd", None)
+ if type(proof_fd) is int and proof_fd >= 3 and proof_fd not in owned:
+ os.close(proof_fd)
+ raise
+ # No guest namespace/root directory handles survive into candidate code.
+ resource_limit = resource.getrlimit(resource.RLIMIT_NOFILE)[0]
+ # Keep only the supervisor's result channel. No candidate receives it.
+ os.closerange(3, args.proof_fd)
+ os.closerange(args.proof_fd + 1, int(resource_limit))
+ os.set_inheritable(args.proof_fd, False)
+ drop = [
+ "/usr/bin/setpriv", "--reuid", str(args.uid), "--regid", str(args.gid),
+ "--clear-groups", "--bounding-set=-all", "--inh-caps=-all",
+ "--ambient-caps=-all", "--no-new-privs",
+ ]
+ env = {
+ "PATH": f"{args.toolchain}/bin:/usr/bin:/bin:/usr/sbin",
+ "HOME": str(args.output / "home"), "PYTHONDONTWRITEBYTECODE": "1",
+ }
+ # Exiting this namespace's PID 1 reaps/kills any descendant left behind.
+ raise SystemExit(run_candidate(args, drop, env))
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ for name in ("root", "source", "fixture", "state", "recipe", "toolchain", "python-env", "go-archive"):
+ parser.add_argument(f"--{name}", required=True, type=Path)
+ parser.add_argument("--phase", required=True, choices=PHASES)
+ parser.add_argument("--build", type=Path, help="Explicit prior build output; required only for wire.")
+ parser.add_argument("--network", required=True, choices=("none", "loopback"))
+ parser.add_argument("--receipt", required=True)
+ parser.add_argument("--caller-storage-sha256", required=True,
+ help="Storage identity captured by the original non-root caller before sudo.")
+ parser.add_argument("command", nargs=argparse.REMAINDER)
+ args = parser.parse_args()
+ if sys.platform != "linux" or os.geteuid() != 0:
+ raise RuntimeError("Use sudo in the explicitly authorized Linux task scratch; no fallback.")
+ args.uid, args.gid = int(os.environ["SUDO_UID"]), int(os.environ["SUDO_GID"])
+ if args.uid <= 0 or args.gid <= 0:
+ raise ValueError("The invoking task owner must be non-root.")
+ context = sudo_storage_context(args.uid, args.caller_storage_sha256)
+ args.storage_context = context.record()
+ admitted_root = validate_temporary_root(args.root, owner_uid=args.uid, context=context).resolve(strict=True)
+ if args.root != admitted_root:
+ raise ValueError("Privileged scratch must use its absolute canonical name.")
+ args.root = admitted_root
+ admitted_info = args.root.lstat()
+ for name in ("source", "fixture", "state", "recipe", "toolchain", "python_env", "go_archive"):
+ path = context.validate(getattr(args, name)).resolve(strict=True)
+ if path == args.root or not path.is_relative_to(args.root):
+ raise ValueError(f"{name} must be a dedicated child of the allocated scratch.")
+ setattr(args, name, path)
+ admitted_inputs = {name: descriptor_identity(getattr(args, name).lstat()) for name in INPUT_NAMES}
+ if args.recipe != Path(__file__).resolve().parent:
+ raise ValueError("Recipe mount must be the directory of this inspected launcher.")
+ validate_state_root(args.state, owner_uid=args.uid, context=context)
+ paths = [args.source, args.fixture, args.state, args.recipe, args.toolchain, args.python_env, args.go_archive]
+ if any(a == b or a.is_relative_to(b) or b.is_relative_to(a) for i, a in enumerate(paths) for b in paths[i + 1:]):
+ raise ValueError("Source, fixture, state, recipe, toolchain and Python directories must be disjoint.")
+ if Path(args.receipt).name != args.receipt or args.receipt in ("", ".", ".."):
+ raise ValueError("Receipt must be one new file name in the parent's receipts directory.")
+ args.output = args.root / "runs" / args.receipt
+ # Check the full public setup and generated environment plan before the
+ # first receipt/output allocation, sentinel, subprocess or mount.
+ for target in (args.root / "receipts", args.root / "runs", args.output):
+ context.validate(target)
+ for owner, name in environment_directories(args.output, args.state):
+ target = context.validate(owner / name)
+ if not target.is_relative_to(owner):
+ raise ValueError("Environment directory escapes its task root.")
+ for path in paths:
+ for reserved in (args.root / "receipts", args.root / "runs"):
+ if path == reserved or path.is_relative_to(reserved) or reserved.is_relative_to(path):
+ raise ValueError("Input/cache directories must not overlap parent receipts or run outputs.")
+ if (args.phase == "wire") != (args.build is not None):
+ raise ValueError("Only wire must select one explicit prior build.")
+ if args.phase == "build" and args.network != "none":
+ raise ValueError("Diagnostic builds require network=none.")
+ if args.phase in ("test", "wire") and args.network != "loopback":
+ raise ValueError("Network suites require the private loopback mode.")
+ if args.build is not None:
+ args.build = args.build.resolve(strict=True)
+ if args.build.parent != args.root / "runs" or args.build == args.output:
+ raise ValueError("Select a different prior build output in this task's runs directory.")
+ admitted_build = descriptor_identity(args.build.lstat())
+ if args.command[:1] == ["--"]:
+ args.command = args.command[1:]
+ if not args.command:
+ raise ValueError("An explicit test/build command is required.")
+ outer_namespaces = namespace_ids()
+ require_namespace_ids(outer_namespaces)
+ with ExitStack() as stack:
+ root_fd = os.open(args.root, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC)
+ stack.callback(os.close, root_fd)
+ opened_info = os.fstat(root_fd)
+ if (opened_info.st_dev, opened_info.st_ino) != (admitted_info.st_dev, admitted_info.st_ino):
+ raise ValueError("Privileged scratch changed after original path admission.")
+ check_root_descriptor(args, root_fd)
+ handles = {"root": retained_handle(root_fd, "directory")}
+ for name in INPUT_NAMES:
+ handles[name] = pin_beneath(
+ stack, root_fd, getattr(args, name).relative_to(args.root),
+ kind="file" if name == "go_archive" else "directory", expected=admitted_inputs[name],
+ )
+ if handles["state"]["identity"]["uid"] != args.uid:
+ raise ValueError("Writable state must belong to the invoking user.")
+ bootstrap = pin_bootstrap(stack, handles["recipe"])
+ system_mounts, system_aliases = pin_system_resources(stack)
+ terminal, probe, handoff, control_fd = open_receipts(args, stack, root_fd)
+ handles["control"] = retained_handle(control_fd, "directory")
+ rootfs = None
+ rootfs_identity = None
+ sentinels = []
+ result = None
+ failure = None
+ cleanup_errors = []
+ rootfs_removed = False
+ values = None
+ try:
+ handles["runs"], handles["output"] = allocate_output(args, stack, root_fd)
+ if args.build is not None:
+ handles["build"] = pin_beneath(
+ stack, check_handle(handles["runs"]), Path(args.build.name),
+ kind="directory", expected=admitted_build,
+ )
+ args.selected_build = selected_build_receipt(args, control_fd, handles.get("build"))
+ check_root_descriptor(args, root_fd)
+ rootfs_name = "rootfs-" + secrets.token_hex(16)
+ os.mkdir(rootfs_name, mode=0o700, dir_fd=check_handle(handles["control"]))
+ rootfs = args.root / "receipts" / rootfs_name
+ rootfs_identity = {"identity": descriptor_identity(os.stat(
+ rootfs_name, dir_fd=control_fd, follow_symlinks=False,
+ ))}
+ handles["rootfs"] = pin_beneath(
+ stack, control_fd, Path(rootfs_name), kind="directory", expected=rootfs_identity["identity"],
+ )
+ for family in (socket.AF_INET, socket.AF_INET6):
+ sentinels.append(Sentinel(family))
+ values = {
+ **vars(args), "rootfs": rootfs, "proof_fd": probe.fileno(),
+ "outer_namespaces": outer_namespaces, "sentinel_ports": [server.port for server in sentinels],
+ "handles": handles, "system_mounts": system_mounts, "system_aliases": system_aliases,
+ "bootstrap": bootstrap,
+ }
+ encoded = json.dumps(values, default=str).encode()
+ if len(encoded) > 65536:
+ raise RuntimeError("Oversized private parent handoff.")
+ handoff.write(encoded)
+ handoff.flush()
+ handoff.seek(0)
+ command = ["/usr/bin/unshare", "--mount", "--net", "--pid", "--ipc", "--fork", "--kill-child=KILL",
+ "/usr/bin/python3", "-I", "-B", "-c", CHILD_TRAMPOLINE,
+ str(handoff.fileno())]
+ passed = {probe.fileno(), handoff.fileno(), *(record["fd"] for record in handles.values()),
+ *(item["resource"]["fd"] for item in system_mounts),
+ *(record["fd"] for record in bootstrap.values())}
+ check_root_descriptor(args, root_fd)
+ # subprocess.run kills and waits for the launcher on timeout.
+ # unshare --kill-child also kills its PID 1 and all its descendants.
+ result = subprocess.run(
+ command, close_fds=True, pass_fds=tuple(sorted(passed)),
+ stdin=subprocess.DEVNULL, timeout=PHASES[args.phase].namespace_seconds,
+ )
+ except Exception as exc:
+ failure = exc
+ finally:
+ for server in sentinels:
+ try:
+ server.close()
+ except Exception as exc:
+ cleanup_errors.append(type(exc).__name__)
+ try:
+ # Only the exact parent-created, empty mount point is removed.
+ if rootfs is not None:
+ if rootfs_identity is None:
+ raise RuntimeError("Rootfs allocation identity unavailable; preserve it.")
+ remove_rootfs(handles["control"], rootfs_identity, rootfs.name)
+ rootfs_removed = True
+ except (OSError, RuntimeError) as exc:
+ cleanup_errors.append(type(exc).__name__)
+ receipt = {
+ "command": args.command, "network": args.network,
+ "exit_code": result.returncode if result is not None else None,
+ "outside_sentinel_connections": [server.connections for server in sentinels],
+ "launcher_reaped": result is not None or isinstance(failure, subprocess.TimeoutExpired),
+ "temporary_rootfs_removed": rootfs_removed, "cleanup_errors": cleanup_errors,
+ "failure": type(failure).__name__ if failure is not None else None,
+ "preflight_custody": "unnamed-supervisor-fd-closed-before-candidate",
+ "entry_custody": "fixed-trampoline-unnamed-parent-control",
+ "phase": args.phase, "budget": PHASES[args.phase].receipt(),
+ "output": str(args.output), "selected_build": getattr(args, "selected_build", None),
+ "storage_sha256": context.fingerprint(),
+ "output_identity": handles["output"]["identity"] if "output" in handles else None,
+ }
+ probe.seek(0)
+ raw = probe.read(65537)
+ try:
+ proof = json.loads(raw)
+ if len(raw) > 65536 or not isinstance(proof, dict) or proof.get("isolation_probe") != "pass":
+ raise ValueError("Invalid preflight.")
+ require_kernel_evidence(proof)
+ if values is None or proof["outer_namespaces"] != values["outer_namespaces"]:
+ raise RuntimeError("Preflight parent epoch changed.")
+ except (ValueError, UnicodeError, RuntimeError):
+ receipt["preflight"] = "missing-or-invalid"
+ else:
+ receipt.update(preflight="passed", probe=proof, probe_sha256=hashlib.sha256(raw).hexdigest())
+ passed = (
+ result is not None and result.returncode == 0 and failure is None
+ and not cleanup_errors and len(sentinels) == 2
+ and not any(server.connections for server in sentinels)
+ and receipt["preflight"] == "passed"
+ )
+ receipt["status"] = "passed" if passed else "failed"
+ # Both files were opened before execution, outside all child mounts.
+ # No child-controlled path is inspected even for supplemental evidence.
+ terminal.write(json.dumps(receipt, indent=2) + "\n")
+ terminal.flush()
+ os.fsync(terminal.fileno())
+ if failure is not None:
+ raise failure
+ if not passed:
+ raise RuntimeError("Namespace execution or preflight/cleanup/sentinel acceptance failed; inspect parent receipt.")
+ raise SystemExit(0)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/patches/cliproxyapi/native-intent.patch b/patches/cliproxyapi/native-intent.patch
new file mode 100644
index 000000000..ec915622f
--- /dev/null
+++ b/patches/cliproxyapi/native-intent.patch
@@ -0,0 +1,1696 @@
+diff --git a/internal/runtime/executor/helps/model_capabilities.go b/internal/runtime/executor/helps/model_capabilities.go
+index fa054fe..e13823b 100644
+--- a/internal/runtime/executor/helps/model_capabilities.go
++++ b/internal/runtime/executor/helps/model_capabilities.go
+@@ -24,5 +24,5 @@ func ApplyRequestThinking(body []byte, req cliproxyexecutor.Request, opts clipro
+ if modelInfo, ok := cliproxyauth.ResolvedModelInfo(req); ok {
+ return thinking.ApplyThinkingWithModelInfoAndSummary(body, originalSource, req.Model, fromFormat, toFormat, provider, modelInfo, summaryConfig)
+ }
+- return thinking.ApplyThinkingWithSummary(body, req.Model, fromFormat, toFormat, provider, summaryConfig)
++ return thinking.ApplyThinkingWithSourceAndSummary(body, originalSource, req.Model, fromFormat, toFormat, provider, summaryConfig)
+ }
+diff --git a/internal/runtime/executor/helps/thinking.go b/internal/runtime/executor/helps/thinking.go
+index 9ad7a2e..7884f50 100644
+--- a/internal/runtime/executor/helps/thinking.go
++++ b/internal/runtime/executor/helps/thinking.go
+@@ -13,7 +13,7 @@ import (
+ // originalSourcePayload retains intent removed by an earlier interceptor.
+ func ApplyThinkingWithSourcePayload(body, currentSourcePayload, originalSourcePayload []byte, model, fromFormat, toFormat, providerKey string) ([]byte, error) {
+ summary := translatedRequestSummaryConfig(body, currentSourcePayload, originalSourcePayload, model, fromFormat, toFormat)
+- return thinking.ApplyThinkingWithSummary(body, model, fromFormat, toFormat, providerKey, summary)
++ return thinking.ApplyThinkingWithSourceAndSummary(body, originalSourcePayload, model, fromFormat, toFormat, providerKey, summary)
+ }
+
+ // translatedRequestSummaryConfig gives the translated target payload precedence
+diff --git a/internal/runtime/executor/native_intent_test.go b/internal/runtime/executor/native_intent_test.go
+new file mode 100644
+index 0000000..cee3712
+--- /dev/null
++++ b/internal/runtime/executor/native_intent_test.go
+@@ -0,0 +1,512 @@
++package executor
++
++import (
++ "bytes"
++ "context"
++ "fmt"
++ "io"
++ "net/http"
++ "net/http/httptest"
++ "net/url"
++ "reflect"
++ "strings"
++ "testing"
++ "time"
++
++ "github.com/gorilla/websocket"
++ claudeauth "github.com/router-for-me/CLIProxyAPI/v7/internal/auth/claude"
++ kimiauth "github.com/router-for-me/CLIProxyAPI/v7/internal/auth/kimi"
++ "github.com/router-for-me/CLIProxyAPI/v7/internal/config"
++ "github.com/router-for-me/CLIProxyAPI/v7/internal/registry"
++ _ "github.com/router-for-me/CLIProxyAPI/v7/internal/translator"
++ cliproxyauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/auth"
++ cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/executor"
++ sdktranslator "github.com/router-for-me/CLIProxyAPI/v7/sdk/translator"
++ "github.com/tidwall/gjson"
++)
++
++type intentCapture struct {
++ path string
++ header http.Header
++ body []byte
++}
++
++const intentClaudeJSON = `{"id":"msg-intent","type":"message","role":"assistant","model":"fixture","content":[{"type":"text","text":"ok"}],"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}`
++const intentResponsesJSON = `{"type":"response.completed","response":{"id":"resp-intent","status":"completed","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"ok"}]}],"usage":{"input_tokens":1,"output_tokens":1,"total_tokens":2}}}`
++
++func intentReply(w http.ResponseWriter, path string, body []byte) {
++ if strings.HasSuffix(path, "/responses") {
++ w.Header().Set("Content-Type", "text/event-stream")
++ _, _ = fmt.Fprintf(w, "data: %s\n\n", intentResponsesJSON)
++ } else if strings.HasSuffix(path, "/messages") {
++ if gjson.GetBytes(body, "stream").Bool() {
++ w.Header().Set("Content-Type", "text/event-stream")
++ _, _ = fmt.Fprintf(w, "event: message_start\ndata: {\"type\":\"message_start\",\"message\":%s}\n\n", intentClaudeJSON)
++ _, _ = io.WriteString(w, "event: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"ok\"}}\n\nevent: message_delta\ndata: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"},\"usage\":{\"output_tokens\":1}}\n\nevent: message_stop\ndata: {\"type\":\"message_stop\"}\n\n")
++ } else {
++ w.Header().Set("Content-Type", "application/json")
++ _, _ = io.WriteString(w, intentClaudeJSON)
++ }
++ } else {
++ if gjson.GetBytes(body, "stream").Bool() {
++ w.Header().Set("Content-Type", "text/event-stream")
++ _, _ = io.WriteString(w, "data: {\"id\":\"chat-intent\",\"object\":\"chat.completion.chunk\",\"model\":\"fixture\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"ok\"},\"finish_reason\":null}]}\n\ndata: {\"id\":\"chat-intent\",\"object\":\"chat.completion.chunk\",\"model\":\"fixture\",\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}]}\n\ndata: [DONE]\n\n")
++ return
++ }
++ w.Header().Set("Content-Type", "application/json")
++ _, _ = io.WriteString(w, `{"id":"chat-intent","object":"chat.completion","model":"fixture","choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}`)
++ }
++}
++
++// Only the fixture listener may receive HTTP. Kimi's fixed production origin is
++// rewritten explicitly, never resolved or dialed. The recipe also rejects
++// non-loopback egress at the OS boundary, including WebSocket dialers.
++func intentContext(t *testing.T, server *httptest.Server, rewriteKimi bool) context.Context {
++ t.Helper()
++ target, _ := url.Parse(server.URL)
++ kimi, _ := url.Parse(kimiauth.KimiAPIBaseURL)
++ transport := server.Client().Transport
++ t.Cleanup(func() { transport.(*http.Transport).CloseIdleConnections() })
++ rt := roundTripperFunc(func(r *http.Request) (*http.Response, error) {
++ req := r.Clone(r.Context())
++ if rewriteKimi && req.URL.Host == kimi.Host {
++ uri := *req.URL
++ uri.Scheme, uri.Host = target.Scheme, target.Host
++ req.URL = &uri
++ req.Host = target.Host
++ }
++ if req.URL.Host != target.Host || req.URL.Scheme != "http" {
++ return nil, fmt.Errorf("fixture rejected outbound host %q", req.URL.Host)
++ }
++ return transport.RoundTrip(req)
++ })
++ return context.WithValue(t.Context(), "cliproxy.roundtripper", http.RoundTripper(rt))
++}
++
++func intentReceive(t *testing.T, captures <-chan intentCapture) intentCapture {
++ t.Helper()
++ select {
++ case capture := <-captures:
++ return capture
++ case <-time.After(5 * time.Second):
++ t.Fatal("fixture upstream was not reached")
++ return intentCapture{}
++ }
++}
++
++func TestNativeIntentManagerExactSnapshotAndReplacement(t *testing.T) {
++ captures := make(chan intentCapture, 8)
++ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
++ body, _ := io.ReadAll(r.Body)
++ captures <- intentCapture{r.URL.Path, r.Header.Clone(), bytes.Clone(body)}
++ intentReply(w, r.URL.Path, body)
++ }))
++ defer server.Close()
++ ctx := intentContext(t, server, false)
++ cfg := &config.Config{SDKConfig: config.SDKConfig{ForceModelPrefix: true}, DisableClaudeCloakMode: true}
++ manager := cliproxyauth.NewManager(nil, nil, nil)
++ manager.RegisterExecutor(NewClaudeExecutor(cfg))
++ auths := make([]*cliproxyauth.Auth, 2)
++ reg := registry.GetGlobalRegistry()
++ for i, level := range []string{"high", "max"} {
++ prefix, key := fmt.Sprintf("intent-source-%d", i), fmt.Sprintf("fake-intent-key-%d", i)
++ cfg.ClaudeKey = append(cfg.ClaudeKey, config.ClaudeKey{
++ APIKey: key, Prefix: prefix, BaseURL: server.URL,
++ Models: []config.ClaudeModel{{Name: "shared-intent-upstream", Alias: "public-alias",
++ Thinking: &registry.ThinkingSupport{Levels: []string{level}}}},
++ })
++ auth := &cliproxyauth.Auth{ID: prefix, Provider: "claude", Prefix: prefix, Attributes: map[string]string{
++ "auth_kind": "api_key", "api_key": key, "base_url": server.URL,
++ "source": fmt.Sprintf("config:claude[%d]", i),
++ }}
++ auths[i] = auth
++ reg.RegisterClient(auth.ID, "claude", []*registry.ModelInfo{{
++ ID: prefix + "/public-alias", Type: "claude",
++ }})
++ t.Cleanup(func() { reg.UnregisterClient(auth.ID) })
++ }
++ manager.SetConfig(cfg)
++ for _, auth := range auths {
++ if _, err := manager.Register(ctx, auth); err != nil {
++ t.Fatal(err)
++ }
++ }
++ // An unrelated aggregate must not replace the selected private snapshot.
++ reg.RegisterClient("intent-unrelated", "claude", []*registry.ModelInfo{{
++ ID: "shared-intent-upstream", Type: "claude", Thinking: &registry.ThinkingSupport{Levels: []string{"low"}},
++ }})
++ t.Cleanup(func() { reg.UnregisterClient("intent-unrelated") })
++ check := func(index int, native, stream bool, want string) {
++ t.Helper()
++ auth := auths[index]
++ model := auth.Prefix + "/public-alias"
++ raw := []byte(`{"model":"` + model + `","input":"hello","reasoning":{"effort":"xhigh"}}`)
++ from := sdktranslator.FormatOpenAIResponse
++ if native {
++ raw = []byte(`{"model":"` + model + `","messages":[{"role":"user","content":"hello"}],"max_tokens":1000,"thinking":{"type":"adaptive"},"output_config":{"effort":"ultra"}}`)
++ from = sdktranslator.FormatClaude
++ }
++ req := cliproxyexecutor.Request{Model: model, Payload: raw, Format: from}
++ opts := cliproxyexecutor.Options{SourceFormat: from, OriginalRequest: raw, Headers: http.Header{"Authorization": {"Bearer fake-inbound"}}}
++ if stream {
++ result, err := manager.ExecuteStream(ctx, []string{"claude"}, req, opts)
++ if err != nil {
++ t.Fatal(err)
++ }
++ for chunk := range result.Chunks {
++ if chunk.Err != nil {
++ t.Fatal(chunk.Err)
++ }
++ }
++ } else if _, err := manager.Execute(ctx, []string{"claude"}, req, opts); err != nil {
++ t.Fatal(err)
++ }
++ capture := intentReceive(t, captures)
++ correctKey := capture.header.Get("X-Api-Key") == auth.Attributes["api_key"] ||
++ capture.header.Get("Authorization") == "Bearer "+auth.Attributes["api_key"]
++ if capture.path != "/v1/messages" || !correctKey ||
++ capture.header.Get("Authorization") == "Bearer fake-inbound" ||
++ gjson.GetBytes(capture.body, "model").String() != "shared-intent-upstream" ||
++ gjson.GetBytes(capture.body, "output_config.effort").String() != want {
++ t.Fatalf("selected snapshot, alias, or credential lost: %+v body=%s", capture, capture.body)
++ }
++ }
++ for _, stream := range []bool{false, true} {
++ check(0, false, stream, "high")
++ check(1, false, stream, "max")
++ check(0, true, stream, "ultra")
++ }
++ replacement := *cfg
++ replacement.ClaudeKey = append([]config.ClaudeKey(nil), cfg.ClaudeKey...)
++ replacement.ClaudeKey[0].APIKey = "fake-intent-replacement"
++ replacement.ClaudeKey[0].Models = []config.ClaudeModel{{
++ Name: "shared-intent-upstream", Alias: "public-alias", Thinking: &registry.ThinkingSupport{Levels: []string{"max"}},
++ }}
++ manager.SetConfig(&replacement)
++ auths[0] = auths[0].Clone()
++ auths[0].Attributes["api_key"] = "fake-intent-replacement"
++ if _, err := manager.Update(ctx, auths[0]); err != nil {
++ t.Fatal(err)
++ }
++ for _, stream := range []bool{false, true} {
++ check(0, false, stream, "max")
++ check(1, false, stream, "max")
++ }
++}
++
++func TestNativeIntentOAuthHTTPAndDialects(t *testing.T) {
++ for _, tc := range []struct {
++ name, provider, from, model, controls, path, field, want string
++ }{
++ {"claude-oauth", "claude", "claude", "claude-3-5-haiku-20241022", `"thinking":{"type":"adaptive"},"output_config":{"effort":"max"}`, "/v1/messages", "output_config.effort", "max"},
++ {"codex-oauth", "codex", "openai-response", "gpt-5.4", `"reasoning":{"effort":"none","summary":"auto"}`, "/responses", "reasoning.effort", "none"},
++ {"codex-oauth-unknown-conversion", "codex", "claude", "unknown-oauth", `"thinking":{"type":"adaptive"},"output_config":{"effort":"max"}`, "/responses", "reasoning.effort", "max"},
++ {"kimi-messages", "kimi", "claude", "kimi-k2.5", `"thinking":{"type":"adaptive"},"output_config":{"effort":"max"}`, "/coding/v1/messages", "output_config.effort", "max"},
++ {"kimi-chat-negative", "kimi", "openai", "kimi-k2.5", `"thinking":{"type":"disabled"},"reasoning_effort":"high"`, "/coding/v1/chat/completions", "thinking.type", "disabled"},
++ {"kimi-chat-conversion", "kimi", "openai", "kimi-k2.5", `"reasoning_effort":"high"`, "/coding/v1/chat/completions", "thinking.effort", "high"},
++ {"kimi-native-positive", "kimi", "openai", "kimi-k2.5", `"thinking":{"type":"enabled","effort":"ultra","keep":"all"},"reasoning_effort":"high"`, "/coding/v1/chat/completions", "thinking.effort", "ultra"},
++ {"xai-responses", "xai", "openai-response", "grok-4", `"reasoning":{"effort":"ultra"}`, "/responses", "reasoning.effort", "ultra"},
++ } {
++ t.Run(tc.name, func(t *testing.T) {
++ captures := make(chan intentCapture, 1)
++ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
++ body, _ := io.ReadAll(r.Body)
++ captures <- intentCapture{r.URL.Path, r.Header.Clone(), bytes.Clone(body)}
++ intentReply(w, r.URL.Path, body)
++ }))
++ defer server.Close()
++ cfg := &config.Config{DisableClaudeCloakMode: true, SDKConfig: config.SDKConfig{DisableImageGeneration: config.DisableImageGenerationAll}}
++ var executor cliproxyauth.ProviderExecutor
++ switch tc.provider {
++ case "claude":
++ executor = NewClaudeExecutor(cfg)
++ case "codex":
++ executor = NewCodexExecutor(cfg)
++ case "kimi":
++ executor = NewKimiExecutor(cfg)
++ case "xai":
++ executor = NewXAIExecutor(cfg)
++ }
++ token := "fake-oauth-intent"
++ auth := &cliproxyauth.Auth{ID: tc.name, Provider: tc.provider,
++ Attributes: map[string]string{"auth_kind": "oauth", "base_url": server.URL},
++ Metadata: map[string]any{"access_token": token, "account_id": "fake-account"}}
++ if tc.provider == "claude" {
++ token = "sk-ant-oat-fake-intent"
++ auth.Attributes["api_key"] = token
++ auth.Metadata["account_uuid"] = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"
++ auth.Metadata[claudeauth.ClaudeDeviceIDsMetadataKey] = []string{strings.Repeat("0", 64)}
++ }
++ if tc.provider == "xai" || tc.provider == "kimi" {
++ auth.Attributes["api_key"] = token
++ }
++ raw := []byte(`{"model":"` + tc.model + `","max_tokens":1000,"messages":[{"role":"user","content":"hello"}],"input":"hello",` + tc.controls + `}`)
++ from := sdktranslator.FromString(tc.from)
++ ctx := intentContext(t, server, tc.provider == "kimi")
++ if _, err := executor.Execute(ctx, auth, cliproxyexecutor.Request{Model: tc.model, Payload: raw},
++ cliproxyexecutor.Options{SourceFormat: from, OriginalRequest: raw}); err != nil {
++ t.Fatal(err)
++ }
++ capture := intentReceive(t, captures)
++ if capture.path != tc.path || gjson.GetBytes(capture.body, tc.field).String() != tc.want {
++ t.Fatalf("dialect changed: path=%s body=%s", capture.path, capture.body)
++ }
++ if capture.header.Get("Authorization") != "Bearer "+token && capture.header.Get("X-Api-Key") != token {
++ t.Fatal("selected fake subscription credential was not used")
++ }
++ if tc.provider == "codex" && capture.header.Get("Chatgpt-Account-Id") != "fake-account" {
++ t.Fatal("Codex OAuth account identity lost")
++ }
++ if tc.from == "openai" && tc.provider == "kimi" && gjson.GetBytes(capture.body, "reasoning_effort").Exists() {
++ t.Fatal("Kimi dialect was conflated with Chat reasoning_effort")
++ }
++ })
++ }
++}
++
++func TestNativeIntentCodexOAuthWebSocket(t *testing.T) {
++ captures := make(chan intentCapture, 2)
++ upgrader := websocket.Upgrader{}
++ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
++ conn, err := upgrader.Upgrade(w, r, nil)
++ if err != nil {
++ t.Error(err)
++ return
++ }
++ defer conn.Close()
++ _, body, err := conn.ReadMessage()
++ if err != nil {
++ t.Error(err)
++ return
++ }
++ captures <- intentCapture{r.URL.Path, r.Header.Clone(), bytes.Clone(body)}
++ _ = conn.WriteMessage(websocket.TextMessage, []byte(intentResponsesJSON))
++ }))
++ defer server.Close()
++ for _, stream := range []bool{false, true} {
++ executor := NewCodexWebsocketsExecutor(&config.Config{SDKConfig: config.SDKConfig{DisableImageGeneration: config.DisableImageGenerationAll}})
++ auth := &cliproxyauth.Auth{ID: "intent-ws", Provider: "codex",
++ Attributes: map[string]string{"auth_kind": "oauth", "base_url": server.URL},
++ Metadata: map[string]any{"access_token": "fake-ws-subscription", "account_id": "fake-ws-account"}}
++ raw := []byte(`{"model":"gpt-5.4","input":"hello","reasoning":{"effort":"none","summary":"auto"}}`)
++ req := cliproxyexecutor.Request{Model: "gpt-5.4", Payload: raw}
++ opts := cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatOpenAIResponse, OriginalRequest: raw}
++ ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
++ if stream {
++ result, err := executor.ExecuteStream(ctx, auth, req, opts)
++ if err != nil {
++ cancel()
++ t.Fatal(err)
++ }
++ for chunk := range result.Chunks {
++ if chunk.Err != nil {
++ cancel()
++ t.Fatal(chunk.Err)
++ }
++ }
++ } else if _, err := executor.Execute(ctx, auth, req, opts); err != nil {
++ cancel()
++ t.Fatal(err)
++ }
++ cancel()
++ capture := intentReceive(t, captures)
++ if capture.header.Get("Authorization") != "Bearer fake-ws-subscription" ||
++ capture.header.Get("Chatgpt-Account-Id") != "fake-ws-account" ||
++ capture.path != "/responses" ||
++ gjson.GetBytes(capture.body, "type").String() != "response.create" ||
++ gjson.GetBytes(capture.body, "reasoning.effort").String() != "none" {
++ t.Fatalf("WebSocket native intent or OAuth identity changed: body=%s", capture.body)
++ }
++ }
++}
++
++func TestNativeIntentXAIFinalEgressMatrix(t *testing.T) {
++ reg := registry.GetGlobalRegistry()
++ for _, profile := range []struct {
++ name, model string
++ info *registry.ModelInfo
++ }{
++ {"unknown", "intent-unknown-xai", nil},
++ {"known-nil", "grok-4", nil},
++ {"supported", "grok-4.5", nil},
++ {"empty", "intent-empty-xai", &registry.ModelInfo{ID: "intent-empty-xai", Type: "xai", Thinking: &registry.ThinkingSupport{}}},
++ {"narrow", "intent-narrow-xai", &registry.ModelInfo{ID: "intent-narrow-xai", Type: "xai", Thinking: &registry.ThinkingSupport{Levels: []string{"high", "low"}}}},
++ } {
++ t.Run(profile.name, func(t *testing.T) {
++ if profile.info != nil {
++ reg.RegisterClient(profile.name+"-intent", "xai", []*registry.ModelInfo{profile.info})
++ t.Cleanup(func() { reg.UnregisterClient(profile.name + "-intent") })
++ }
++ captures := make(chan intentCapture, 1)
++ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
++ body, _ := io.ReadAll(r.Body)
++ captures <- intentCapture{r.URL.Path, r.Header.Clone(), bytes.Clone(body)}
++ intentReply(w, r.URL.Path, body)
++ }))
++ defer server.Close()
++ ctx := intentContext(t, server, false)
++ for _, stream := range []bool{false, true} {
++ for _, intent := range []string{"ultra", "none", "absent", "cross-high", "cross-none", "suffix", "override", "filter"} {
++ cfg := &config.Config{}
++ model, from := profile.model, sdktranslator.FormatOpenAIResponse
++ controls, want := `"reasoning":{"effort":"`+intent+`"}`, intent
++ switch intent {
++ case "absent":
++ controls, want = `"metadata":{"fixture":true}`, ""
++ case "cross-high", "cross-none":
++ from = sdktranslator.FormatClaude
++ controls, want = `"thinking":{"type":"adaptive"},"output_config":{"effort":"high"}`, "high"
++ if intent == "cross-none" {
++ controls, want = `"thinking":{"type":"disabled"}`, "none"
++ }
++ case "suffix":
++ model += "(none)"
++ controls, want = `"reasoning":{"effort":"high","summary":"auto"}`, "none"
++ case "override":
++ controls, want = `"reasoning":{"effort":"ultra"}`, "low"
++ cfg.Payload.Override = []config.PayloadRule{{Models: []config.PayloadModelRule{{Name: profile.model}}, Params: map[string]any{"reasoning.effort": "low"}}}
++ case "filter":
++ controls, want = `"reasoning":{"effort":"ultra"}`, ""
++ cfg.Payload.Filter = []config.PayloadFilterRule{{Models: []config.PayloadModelRule{{Name: profile.model}}, Params: []string{"reasoning"}}}
++ }
++ raw := []byte(`{"model":"` + model + `","stop":["stop"],"max_tokens":1000,"input":[{"role":"user","content":"hello"}],"messages":[{"role":"user","content":"hello"}],` + controls + `}`)
++ auth := &cliproxyauth.Auth{Provider: "xai", Attributes: map[string]string{"auth_kind": "oauth", "base_url": server.URL},
++ Metadata: map[string]any{"access_token": "fake-xai-intent"}}
++ executor := NewXAIExecutor(cfg)
++ req := cliproxyexecutor.Request{Model: model, Payload: raw}
++ opts := cliproxyexecutor.Options{SourceFormat: from, OriginalRequest: raw}
++ if stream {
++ result, err := executor.ExecuteStream(ctx, auth, req, opts)
++ if err != nil {
++ t.Fatal(err)
++ }
++ for chunk := range result.Chunks {
++ if chunk.Err != nil {
++ t.Fatal(chunk.Err)
++ }
++ }
++ } else if _, err := executor.Execute(ctx, auth, req, opts); err != nil {
++ t.Fatal(err)
++ }
++ capture := intentReceive(t, captures)
++ if got := gjson.GetBytes(capture.body, "reasoning.effort"); got.String() != want || (want == "" && got.Exists()) {
++ t.Fatalf("intent=%s stream=%v want=%q body=%s", intent, stream, want, capture.body)
++ }
++ if gjson.GetBytes(capture.body, "stop").Exists() || gjson.GetBytes(capture.body, "model").String() != profile.model ||
++ capture.path != "/responses" || capture.header.Get("Authorization") != "Bearer fake-xai-intent" {
++ t.Fatalf("protocol constraint or identity changed: %s", capture.body)
++ }
++ }
++ }
++ })
++ }
++}
++
++func TestNativeIntentKimiNativeAndLegacyWireMatrix(t *testing.T) {
++ for _, model := range []string{"kimi-k2.5", "intent-unknown-kimi"} {
++ for _, stream := range []bool{false, true} {
++ for _, tc := range []struct {
++ name, object, legacy, suffix, want string
++ }{
++ {"future", `{"type":"enabled","effort":"ULTRA","keep":"all"}`, "high", "", `{"type":"enabled","effort":"ULTRA","keep":"all"}`},
++ {"future-type", `{"type":"future-native","other":7}`, "high", "", `{"type":"future-native","other":7}`},
++ {"effort-only", `{"effort":"ultra"}`, "high", "", `{"effort":"ultra"}`},
++ {"type-only", `{"type":"enabled"}`, "high", "", `{"type":"enabled"}`},
++ {"disable", `{"type":"disabled"}`, "high", "", `{"type":"disabled"}`},
++ {"keep-conversion", `{"keep":"all"}`, "high", "", `{"keep":"all","type":"enabled","effort":"high"}`},
++ {"keep-only", `{"keep":"all"}`, "", "", `{"keep":"all"}`},
++ {"suffix", `{"type":"enabled","effort":"ultra"}`, "high", "(none)", `{"type":"disabled"}`},
++ {"override", `{"type":"enabled","effort":"ultra"}`, "high", "", `{"type":"disabled"}`},
++ {"filter", `{"type":"enabled","effort":"ultra"}`, "high", "", ""},
++ } {
++ t.Run(fmt.Sprintf("%s/%v/%s", model, stream, tc.name), func(t *testing.T) {
++ captures := make(chan intentCapture, 1)
++ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
++ body, _ := io.ReadAll(r.Body)
++ captures <- intentCapture{r.URL.Path, r.Header.Clone(), bytes.Clone(body)}
++ intentReply(w, r.URL.Path, body)
++ }))
++ defer server.Close()
++ cfg := &config.Config{}
++ if tc.name == "override" {
++ cfg.Payload.Override = []config.PayloadRule{{Models: []config.PayloadModelRule{{Name: model}}, Params: map[string]any{"thinking": map[string]any{"type": "disabled"}}}}
++ }
++ if tc.name == "filter" {
++ cfg.Payload.Filter = []config.PayloadFilterRule{{Models: []config.PayloadModelRule{{Name: model}}, Params: []string{"thinking"}}}
++ }
++ legacy := ""
++ if tc.legacy != "" {
++ legacy = `,"reasoning_effort":"` + tc.legacy + `"`
++ }
++ raw := []byte(fmt.Sprintf(`{"model":%q,"stream":%v,"messages":[{"role":"user","content":"hello"}],"thinking":%s%s}`, model+tc.suffix, stream, tc.object, legacy))
++ auth := &cliproxyauth.Auth{Provider: "kimi", Attributes: map[string]string{"auth_kind": "oauth"},
++ Metadata: map[string]any{"access_token": "fake-kimi-native"}}
++ executor := NewKimiExecutor(cfg)
++ req := cliproxyexecutor.Request{Model: model + tc.suffix, Payload: raw}
++ opts := cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatOpenAI, OriginalRequest: raw}
++ ctx := intentContext(t, server, true)
++ if stream {
++ result, err := executor.ExecuteStream(ctx, auth, req, opts)
++ if err != nil {
++ t.Fatal(err)
++ }
++ for chunk := range result.Chunks {
++ if chunk.Err != nil {
++ t.Fatal(chunk.Err)
++ }
++ }
++ } else if _, err := executor.Execute(ctx, auth, req, opts); err != nil {
++ t.Fatal(err)
++ }
++ capture := intentReceive(t, captures)
++ got := gjson.GetBytes(capture.body, "thinking")
++ if !reflect.DeepEqual(got.Value(), gjson.Parse(tc.want).Value()) {
++ t.Fatalf("native/legacy boundary changed: want=%s body=%s", tc.want, capture.body)
++ }
++ if gjson.GetBytes(capture.body, "reasoning_effort").Exists() || capture.path != "/coding/v1/chat/completions" ||
++ capture.header.Get("Authorization") != "Bearer fake-kimi-native" ||
++ gjson.GetBytes(capture.body, "model").String() != normalizeKimiUpstreamModel(model) {
++ t.Fatalf("Kimi wire or identity changed: %s", capture.body)
++ }
++ })
++ }
++ }
++ }
++}
++
++func TestNativeIntentCancellationAndForcedToolChoice(t *testing.T) {
++ captures := make(chan intentCapture, 1)
++ canceled := make(chan struct{})
++ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
++ body, _ := io.ReadAll(r.Body)
++ captures <- intentCapture{r.URL.Path, r.Header.Clone(), body}
++ w.Header().Set("Content-Type", "text/event-stream")
++ _, _ = fmt.Fprintf(w, "event: message_start\ndata: {\"type\":\"message_start\",\"message\":%s}\n\n", intentClaudeJSON)
++ w.(http.Flusher).Flush()
++ <-r.Context().Done()
++ close(canceled)
++ }))
++ defer server.Close()
++ ctx, cancel := context.WithTimeout(intentContext(t, server, false), 5*time.Second)
++ defer cancel()
++ raw := []byte(`{"model":"intent-custom","max_tokens":1000,"messages":[{"role":"user","content":"hello"}],"thinking":{"type":"adaptive"},"output_config":{"effort":"max"},"tools":[{"name":"lookup","input_schema":{"type":"object"}}],"tool_choice":{"type":"tool","name":"lookup"}}`)
++ executor := NewClaudeExecutor(&config.Config{DisableClaudeCloakMode: true})
++ result, err := executor.ExecuteStream(ctx, &cliproxyauth.Auth{Attributes: map[string]string{"api_key": "fake-intent", "base_url": server.URL}},
++ cliproxyexecutor.Request{Model: "intent-custom", Payload: raw},
++ cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatClaude, OriginalRequest: raw})
++ if err != nil {
++ t.Fatal(err)
++ }
++ capture := intentReceive(t, captures)
++ if gjson.GetBytes(capture.body, "thinking").Exists() || gjson.GetBytes(capture.body, "output_config.effort").Exists() {
++ t.Fatalf("forced tool-choice protocol constraint lost: %s", capture.body)
++ }
++ cancel()
++ select {
++ case <-canceled:
++ case <-time.After(2 * time.Second):
++ t.Fatal("upstream cancellation did not propagate")
++ }
++ for range result.Chunks {
++ }
++}
+diff --git a/internal/runtime/executor/xai_executor_request.go b/internal/runtime/executor/xai_executor_request.go
+index e884728..9ae594c 100644
+--- a/internal/runtime/executor/xai_executor_request.go
++++ b/internal/runtime/executor/xai_executor_request.go
+@@ -123,7 +123,7 @@ func (e *XAIExecutor) prepareResponsesRequestTo(ctx context.Context, req cliprox
+ body = normalizeXAIInputReasoningItems(body)
+ body = sanitizeXAIInputEncryptedContent(body)
+ body = normalizeCodexInstructions(body)
+- body = sanitizeXAIResponsesBody(body, baseModel)
++ body = sanitizeXAIResponsesBody(body)
+ body = normalizeXAIImageRefs(body)
+
+ sessionID, errSession := xaiResolveComposerSessionID(ctx, req, opts, baseModel)
+@@ -625,18 +625,9 @@ func xaiCompareGrokVersion(a, b xaiGrokVersion) int {
+ return 0
+ }
+
+-func sanitizeXAIResponsesBody(body []byte, model string) []byte {
++func sanitizeXAIResponsesBody(body []byte) []byte {
+ // stop is supported by Chat Completions but not by xAI's Responses API.
+ body, _ = sjson.DeleteBytes(body, "stop")
+- if !xaiSupportsReasoningEffort(model) {
+- if gjson.GetBytes(body, "reasoning.effort").Exists() {
+- log.Debugf("xai: stripping reasoning.effort for model %s (no thinking levels in model registry)", model)
+- }
+- body, _ = sjson.DeleteBytes(body, "reasoning.effort")
+- if reasoning := gjson.GetBytes(body, "reasoning"); reasoning.Exists() && reasoning.IsObject() && len(reasoning.Map()) == 0 {
+- body, _ = sjson.DeleteBytes(body, "reasoning")
+- }
+- }
+ return body
+ }
+
+diff --git a/internal/runtime/executor/xai_executor_response.go b/internal/runtime/executor/xai_executor_response.go
+index 96cfdfe..60e1ffd 100644
+--- a/internal/runtime/executor/xai_executor_response.go
++++ b/internal/runtime/executor/xai_executor_response.go
+@@ -9,10 +9,8 @@ import (
+ "strings"
+ "time"
+
+- "github.com/router-for-me/CLIProxyAPI/v7/internal/registry"
+ "github.com/router-for-me/CLIProxyAPI/v7/internal/runtime/executor/helps"
+ "github.com/router-for-me/CLIProxyAPI/v7/internal/signature"
+- "github.com/router-for-me/CLIProxyAPI/v7/internal/thinking"
+ log "github.com/sirupsen/logrus"
+ "github.com/tidwall/gjson"
+ "github.com/tidwall/sjson"
+@@ -798,24 +796,6 @@ func appendXAIReasoningSummary(previous json.RawMessage, currentSummary []gjson.
+ return updated, true
+ }
+
+-// xaiSupportsReasoningEffort reports whether the model accepts Responses API
+-// reasoning.effort. Capability comes from model registry thinking metadata
+-// (static models.json and dynamic registrations), not a hard-coded name allowlist.
+-func xaiSupportsReasoningEffort(model string) bool {
+- name := strings.ToLower(strings.TrimSpace(thinking.ParseSuffix(model).ModelName))
+- if idx := strings.LastIndex(name, "/"); idx >= 0 {
+- name = name[idx+1:]
+- }
+- if name == "" {
+- return false
+- }
+- info := registry.LookupModelInfo(name, "xai")
+- if info == nil || info.Thinking == nil {
+- return false
+- }
+- return len(info.Thinking.Levels) > 0
+-}
+-
+ func xaiNormalizeReasoningSummaryEventLine(line []byte, eventName string) []byte {
+ if eventName == "" && bytes.HasPrefix(line, xaiEventTag) {
+ eventName = strings.TrimSpace(string(line[len(xaiEventTag):]))
+diff --git a/internal/runtime/executor/xai_executor_test.go b/internal/runtime/executor/xai_executor_test.go
+index 711dcee..6e61fe0 100644
+--- a/internal/runtime/executor/xai_executor_test.go
++++ b/internal/runtime/executor/xai_executor_test.go
+@@ -2791,7 +2791,7 @@ func TestXAIExecutorExecuteStreamCompactionTriggerUsesCompactEndpoint(t *testing
+ }
+ }
+
+-func TestXAIExecutorOmitsUnsupportedReasoningEffort(t *testing.T) {
++func TestXAIExecutorKeepsNativeReasoningWithoutCatalogSupport(t *testing.T) {
+ var gotBody []byte
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ var errRead error
+@@ -2825,36 +2825,8 @@ func TestXAIExecutorOmitsUnsupportedReasoningEffort(t *testing.T) {
+ t.Fatalf("Execute() error = %v", err)
+ }
+
+- if gjson.GetBytes(gotBody, "reasoning").Exists() {
+- t.Fatalf("unsupported xAI model must omit reasoning key: %s", string(gotBody))
+- }
+-}
+-
+-func TestXAISupportsReasoningEffortUsesModelRegistry(t *testing.T) {
+- tests := []struct {
+- name string
+- model string
+- want bool
+- }{
+- {name: "grok-4.5", model: "grok-4.5", want: true},
+- {name: "grok-4.5 with suffix", model: "grok-4.5(high)", want: true},
+- {name: "grok-4.3", model: "grok-4.3", want: true},
+- {name: "grok-3-mini", model: "grok-3-mini", want: true},
+- {name: "grok-3-mini-fast", model: "grok-3-mini-fast", want: true},
+- {name: "grok-4.20-multi-agent", model: "grok-4.20-multi-agent-0309", want: true},
+- {name: "provider-prefixed grok-4.5", model: "xai/grok-4.5", want: true},
+- {name: "legacy grok-4", model: "grok-4", want: false},
+- {name: "composer without thinking metadata", model: "grok-composer-2.5-fast", want: false},
+- {name: "non-reasoning 4.20", model: "grok-4.20-0309-non-reasoning", want: false},
+- {name: "unknown model", model: "unknown-xai-model", want: false},
+- {name: "empty model", model: "", want: false},
+- }
+- for _, tt := range tests {
+- t.Run(tt.name, func(t *testing.T) {
+- if got := xaiSupportsReasoningEffort(tt.model); got != tt.want {
+- t.Fatalf("xaiSupportsReasoningEffort(%q) = %v, want %v", tt.model, got, tt.want)
+- }
+- })
++ if gjson.GetBytes(gotBody, "reasoning.effort").String() != "high" {
++ t.Fatalf("catalog absence must not erase native intent: %s", string(gotBody))
+ }
+ }
+
+diff --git a/internal/thinking/apply.go b/internal/thinking/apply.go
+index 92e6161..745de37 100644
+--- a/internal/thinking/apply.go
++++ b/internal/thinking/apply.go
+@@ -8,6 +8,7 @@ import (
+ "github.com/router-for-me/CLIProxyAPI/v7/internal/registry"
+ log "github.com/sirupsen/logrus"
+ "github.com/tidwall/gjson"
++ "github.com/tidwall/sjson"
+ )
+
+ type pluginProviderApplier struct {
+@@ -126,9 +127,9 @@ func IsUserDefinedModel(modelInfo *registry.ModelInfo) bool {
+
+ // ApplyThinking applies thinking configuration to a request body.
+ //
+-// This is the unified entry point for all providers. It follows the processing
+-// order defined in FR25: route check → model capability query → config extraction
+-// → validation → application.
++// Native reasoning representations without a suffix retain the prepared target
++// payload. Conversion resolves explicit disable before capability policy, then
++// validates known positive intent or converts without incomplete metadata.
+ //
+ // Suffix Priority: When the model name includes a thinking suffix (e.g., "gemini-2.5-pro(8192)"),
+ // the suffix configuration takes priority over any thinking parameters in the request body.
+@@ -149,7 +150,7 @@ func IsUserDefinedModel(modelInfo *registry.ModelInfo) bool {
+ //
+ // Passthrough behavior (returns original body without error):
+ // - Unknown provider (not in providerAppliers map)
+-// - modelInfo.Thinking is nil (model doesn't support thinking)
++// - Native reasoning representation with no model suffix
+ //
+ // Note: Unknown models (modelInfo is nil) are treated as user-defined models: we skip
+ // validation and still apply the thinking config so the upstream can validate it.
+@@ -175,6 +176,12 @@ func ApplyThinkingWithSummary(body []byte, model string, fromFormat string, toFo
+ return applyThinking(body, nil, model, fromFormat, toFormat, providerKey, nil, false, summaryConfig)
+ }
+
++// ApplyThinkingWithSourceAndSummary retains source intent while using the
++// provider registry for model lookup, including OAuth execution attempts.
++func ApplyThinkingWithSourceAndSummary(body, sourceBody []byte, model, fromFormat, toFormat, providerKey string, summaryConfig SummaryConfig) ([]byte, error) {
++ return applyThinking(body, sourceBody, model, fromFormat, toFormat, providerKey, nil, false, summaryConfig)
++}
++
+ // ApplyThinkingWithModelInfo applies thinking with the exact configured model
+ // definition selected for an API-key execution attempt while preserving summary
+ // visibility from the original source body.
+@@ -195,7 +202,7 @@ func ApplyThinkingWithModelInfoAndSummary(body, sourceBody []byte, model string,
+
+ func applyThinking(body, sourceBody []byte, model string, fromFormat string, toFormat string, providerKey string, resolvedModelInfo *registry.ModelInfo, modelInfoResolved bool, summaryConfig SummaryConfig) ([]byte, error) {
+ providerFormat := strings.ToLower(strings.TrimSpace(toFormat))
+- if modelInfoResolved && providerFormat == "openai-response" {
++ if providerFormat == "openai-response" {
+ providerFormat = "codex"
+ }
+ providerKey = strings.ToLower(strings.TrimSpace(providerKey))
+@@ -222,17 +229,52 @@ func applyThinking(body, sourceBody []byte, model string, fromFormat string, toF
+ // 2. Parse suffix and get modelInfo
+ suffixResult := ParseSuffix(model)
+ baseModel := suffixResult.ModelName
++ nativeFormat := nativeReasoningFormat(providerFormat)
++ if !suffixResult.HasSuffix && providerFormat == "kimi" && fromFormat == "openai" {
++ original := sourceBody
++ if len(original) == 0 {
++ original = body
++ }
++ if gjson.GetBytes(original, "thinking.type").Exists() || gjson.GetBytes(original, "thinking.effort").Exists() {
++ // A Chat envelope may already carry Kimi's native representation.
++ // Keep prepared fields (including future values and absence) while
++ // dropping only the legacy input alias required by the Kimi wire.
++ return sjson.DeleteBytes(body, "reasoning_effort")
++ }
++ }
++ if !suffixResult.HasSuffix && nativeFormat != "" && nativeFormat == nativeReasoningFormat(fromFormat) {
++ // The target payload is already prepared by translators/normalizers.
++ // Catalog knowledge must not reinterpret explicit native controls, nor
++ // should restoring the source undo deliberate target normalization.
++ return body, nil
++ }
+ // Use provider-specific lookup to handle capability differences across providers.
+ modelInfo := resolvedModelInfo
+ if !modelInfoResolved {
+ modelInfo = registry.LookupModelInfo(baseModel, providerKey)
+ }
+
++ if nativeFormat != "" {
++ // A user's disable is an instruction, not a model capability claim.
++ // Resolve it before support checks; summary activation must not undo it.
++ var explicit ThinkingConfig
++ if suffixResult.HasSuffix {
++ explicit = parseSuffixToConfig(suffixResult.RawSuffix, providerFormat, model)
++ } else if len(sourceBody) > 0 {
++ explicit = extractConversionSourceConfig(sourceBody, fromFormat, providerFormat)
++ } else {
++ explicit = extractThinkingConfig(body, providerFormat)
++ }
++ if thinkingIsFullyDisabled(explicit) {
++ return applier.Apply(body, explicit, modelInfo)
++ }
++ }
++
+ // 3. Model capability check
+ // Unknown models are treated as user-defined so thinking config can still be applied.
+ // The upstream service is responsible for validating the configuration.
+- if IsUserDefinedModel(modelInfo) {
+- return applyUserDefinedModel(body, modelInfo, fromFormat, providerFormat, providerKey, suffixResult, summaryConfig)
++ if IsUserDefinedModel(modelInfo) || (nativeFormat != "" && modelInfo.Thinking == nil) {
++ return applyUnvalidatedThinking(body, sourceBody, modelInfo, fromFormat, providerFormat, providerKey, suffixResult, summaryConfig)
+ }
+ if modelInfo.Thinking == nil {
+ config := extractThinkingConfig(body, providerFormat)
+@@ -263,7 +305,7 @@ func applyThinking(body, sourceBody []byte, model string, fromFormat string, toF
+ }).Debug("thinking: config from model suffix |")
+ } else {
+ if modelInfoResolved && len(sourceBody) > 0 {
+- config = extractSourceThinkingConfig(sourceBody, fromFormat)
++ config = extractConversionSourceConfig(sourceBody, fromFormat, providerFormat)
+ }
+ if !hasThinkingConfig(config) {
+ config = extractThinkingConfig(body, providerFormat)
+@@ -351,6 +393,20 @@ func thinkingIsFullyDisabled(config ThinkingConfig) bool {
+ return config.Mode == ModeNone && config.Budget == 0 && config.Level == ""
+ }
+
++// nativeReasoningFormat identifies identical reasoning representations, not
++// provider families. Kimi's thinking object is distinct from Chat effort.
++// Gemini-family conversion policy remains unchanged.
++func nativeReasoningFormat(format string) string {
++ switch format {
++ case "claude", "openai", "kimi":
++ return format
++ case "openai-response", "codex", "xai":
++ return "responses"
++ default:
++ return ""
++ }
++}
++
+ func shouldMapConfiguredHighIntent(fromFormat, toFormat string, modelInfo *registry.ModelInfo) bool {
+ fromFormat = strings.ToLower(strings.TrimSpace(fromFormat))
+ toFormat = strings.ToLower(strings.TrimSpace(toFormat))
+@@ -394,6 +450,15 @@ func extractSourceThinkingConfig(body []byte, provider string) ThinkingConfig {
+ return extractThinkingConfig(body, provider)
+ }
+
++func extractConversionSourceConfig(body []byte, fromFormat, toFormat string) ThinkingConfig {
++ // Kimi accepts its native thinking object on a Chat transport. It owns
++ // precedence over the legacy reasoning_effort input, including disable.
++ if toFormat == "kimi" && fromFormat == "openai" {
++ return extractKimiConfig(body)
++ }
++ return extractSourceThinkingConfig(body, fromFormat)
++}
++
+ // parseSuffixToConfig converts a raw suffix string to ThinkingConfig.
+ //
+ // Parsing priority:
+@@ -435,9 +500,10 @@ func parseSuffixToConfig(rawSuffix, provider, model string) ThinkingConfig {
+ return ThinkingConfig{}
+ }
+
+-// applyUserDefinedModel applies thinking configuration for user-defined models
+-// without ThinkingSupport validation.
+-func applyUserDefinedModel(body []byte, modelInfo *registry.ModelInfo, fromFormat, toFormat, providerKey string, suffixResult SuffixResult, summaryConfig SummaryConfig) ([]byte, error) {
++// applyUnvalidatedThinking converts thinking when capability metadata is
++// unavailable or the model is explicitly user-defined. It never fabricates
++// registry capabilities or changes the selected model snapshot.
++func applyUnvalidatedThinking(body, sourceBody []byte, modelInfo *registry.ModelInfo, fromFormat, toFormat, providerKey string, suffixResult SuffixResult, summaryConfig SummaryConfig) ([]byte, error) {
+ // Get model ID for logging
+ modelID := ""
+ if modelInfo != nil {
+@@ -458,7 +524,11 @@ func applyUserDefinedModel(body []byte, modelInfo *registry.ModelInfo, fromForma
+ "level": config.Level,
+ }).Debug("thinking: config from model suffix |")
+ } else {
+- config = extractThinkingConfig(body, fromFormat)
++ if len(sourceBody) > 0 {
++ config = extractConversionSourceConfig(sourceBody, fromFormat, toFormat)
++ } else {
++ config = extractSourceThinkingConfig(body, fromFormat)
++ }
+ if !hasThinkingConfig(config) && fromFormat != toFormat {
+ config = extractThinkingConfig(body, toFormat)
+ }
+@@ -477,7 +547,7 @@ func applyUserDefinedModel(body []byte, modelInfo *registry.ModelInfo, fromForma
+ log.WithFields(log.Fields{
+ "model": modelID,
+ "provider": toFormat,
+- }).Debug("thinking: user-defined model, passthrough (no config) |")
++ }).Debug("thinking: unvalidated conversion, passthrough (no config) |")
+ return applySummaryConfigForProvider(body, toFormat, modelID, providerKey, modelInfo, summaryConfig), nil
+ }
+
+@@ -486,7 +556,7 @@ func applyUserDefinedModel(body []byte, modelInfo *registry.ModelInfo, fromForma
+ log.WithFields(log.Fields{
+ "model": modelID,
+ "provider": toFormat,
+- }).Debug("thinking: user-defined model, passthrough (unknown provider) |")
++ }).Debug("thinking: unvalidated conversion, passthrough (unknown provider) |")
+ return body, nil
+ }
+
+diff --git a/internal/thinking/apply_configured_api_key_test.go b/internal/thinking/apply_configured_api_key_test.go
+index 9c48c36..71b76bc 100644
+--- a/internal/thinking/apply_configured_api_key_test.go
++++ b/internal/thinking/apply_configured_api_key_test.go
+@@ -45,7 +45,7 @@ func TestApplyThinkingWithModelInfoMapsCrossFamilyHighIntent(t *testing.T) {
+ }
+ }
+
+-func TestApplyThinkingWithModelInfoMapsOpenAICompatibilityHighIntent(t *testing.T) {
++func TestApplyThinkingWithModelInfoPreservesPreparedOpenAICompatibilityIntent(t *testing.T) {
+ modelInfo := &registry.ModelInfo{
+ ID: "compat-upstream",
+ Type: "openai-compatibility",
+@@ -57,12 +57,12 @@ func TestApplyThinkingWithModelInfoMapsOpenAICompatibilityHighIntent(t *testing.
+ if err != nil {
+ t.Fatalf("ApplyThinkingWithModelInfo() error = %v", err)
+ }
+- if got := gjson.GetBytes(out, "reasoning_effort").String(); got != "max" {
+- t.Fatalf("reasoning_effort = %q, want max; body=%s", got, out)
++ if got := gjson.GetBytes(out, "reasoning_effort").String(); got != "high" {
++ t.Fatalf("reasoning_effort = %q, want prepared high; body=%s", got, out)
+ }
+ }
+
+-func TestApplyThinkingWithModelInfoMapsResponsesToCodexHighIntent(t *testing.T) {
++func TestApplyThinkingWithModelInfoPreservesPreparedResponsesIntent(t *testing.T) {
+ modelInfo := &registry.ModelInfo{
+ ID: "codex-upstream",
+ Type: "codex",
+@@ -74,12 +74,12 @@ func TestApplyThinkingWithModelInfoMapsResponsesToCodexHighIntent(t *testing.T)
+ if err != nil {
+ t.Fatalf("ApplyThinkingWithModelInfo() error = %v", err)
+ }
+- if got := gjson.GetBytes(out, "reasoning.effort").String(); got != "xhigh" {
+- t.Fatalf("reasoning.effort = %q, want xhigh; body=%s", got, out)
++ if got := gjson.GetBytes(out, "reasoning.effort").String(); got != "high" {
++ t.Fatalf("reasoning.effort = %q, want prepared high; body=%s", got, out)
+ }
+ }
+
+-func TestApplyThinkingWithModelInfoKeepsSameFamilyValidationStrict(t *testing.T) {
++func TestApplyThinkingWithModelInfoLeavesNativeValidationToUpstream(t *testing.T) {
+ modelInfo := &registry.ModelInfo{
+ ID: "openai-upstream",
+ Type: "openai",
+@@ -87,8 +87,8 @@ func TestApplyThinkingWithModelInfoKeepsSameFamilyValidationStrict(t *testing.T)
+ }
+ body := []byte(`{"reasoning_effort":"xhigh"}`)
+ out, err := thinking.ApplyThinkingWithModelInfo(body, body, "openai-upstream", "openai", "openai", "openai", modelInfo)
+- if err == nil {
+- t.Fatalf("ApplyThinkingWithModelInfo() error = nil, want unsupported xhigh error; body=%s", out)
++ if err != nil || string(out) != string(body) {
++ t.Fatalf("native payload changed: error=%v; body=%s", err, out)
+ }
+ }
+
+diff --git a/internal/thinking/kimi_max_clamp_repro_test.go b/internal/thinking/kimi_max_clamp_repro_test.go
+index d5d3ff6..7ce9267 100644
+--- a/internal/thinking/kimi_max_clamp_repro_test.go
++++ b/internal/thinking/kimi_max_clamp_repro_test.go
+@@ -12,7 +12,7 @@ import (
+
+ // Reproduces Claude Code -> Kimi /v1/messages with effort=max.
+ // KimiExecutor delegates to ClaudeExecutor, so ApplyThinking sees claude/claude.
+-func TestKimiClaudeMessagesMaxClampsToHigh(t *testing.T) {
++func TestKimiClaudeMessagesPreservesNativeMax(t *testing.T) {
+ models := registry.GetKimiModels()
+ reg := registry.GetGlobalRegistry()
+ clientID := "test-kimi-max-clamp"
+@@ -27,7 +27,7 @@ func TestKimiClaudeMessagesMaxClampsToHigh(t *testing.T) {
+ if got := gjson.GetBytes(out, "thinking.type").String(); got != "adaptive" {
+ t.Fatalf("thinking.type = %q, want adaptive", got)
+ }
+- if got := gjson.GetBytes(out, "output_config.effort").String(); got != "high" {
+- t.Fatalf("output_config.effort = %q, want high", got)
++ if got := gjson.GetBytes(out, "output_config.effort").String(); got != "max" {
++ t.Fatalf("output_config.effort = %q, want max", got)
+ }
+ }
+diff --git a/internal/thinking/native_intent_test.go b/internal/thinking/native_intent_test.go
+new file mode 100644
+index 0000000..ed8c7d2
+--- /dev/null
++++ b/internal/thinking/native_intent_test.go
+@@ -0,0 +1,191 @@
++package thinking_test
++
++import (
++ "bytes"
++ "reflect"
++ "strings"
++ "testing"
++
++ "github.com/router-for-me/CLIProxyAPI/v7/internal/modelconfig"
++ "github.com/router-for-me/CLIProxyAPI/v7/internal/registry"
++ "github.com/router-for-me/CLIProxyAPI/v7/internal/thinking"
++ _ "github.com/router-for-me/CLIProxyAPI/v7/internal/thinking/provider/claude"
++ _ "github.com/router-for-me/CLIProxyAPI/v7/internal/thinking/provider/codex"
++ _ "github.com/router-for-me/CLIProxyAPI/v7/internal/thinking/provider/kimi"
++ _ "github.com/router-for-me/CLIProxyAPI/v7/internal/thinking/provider/openai"
++ _ "github.com/router-for-me/CLIProxyAPI/v7/internal/thinking/provider/xai"
++ "github.com/tidwall/gjson"
++)
++
++func TestNativeIntentPreservesPreparedPayloadWithoutCapabilityClaims(t *testing.T) {
++ models := map[string]*registry.ModelInfo{
++ "unresolved": nil,
++ "user-defined": {ID: "custom", UserDefined: true},
++ "configured-unknown": modelconfig.ResolveModelInfo("native-intent-custom", "codex", nil),
++ "known-without-thinking": modelconfig.ResolveModelInfo("claude-3-5-haiku-20241022", "claude", nil),
++ "known": modelconfig.ResolveModelInfo("gpt-5.4", "codex", nil),
++ "narrow": modelconfig.ResolveModelInfo("custom", "codex", &registry.ThinkingSupport{Levels: []string{"high", "low"}}),
++ "empty": modelconfig.ResolveModelInfo("custom", "claude", &registry.ThinkingSupport{}),
++ }
++ for _, route := range [][2]string{
++ {"claude", "claude"}, {"openai", "openai"},
++ {"openai-response", "codex"}, {"codex", "openai-response"},
++ {"openai-response", "xai"}, {"codex", "codex"},
++ } {
++ for name, model := range models {
++ t.Run(route[0]+"/"+route[1]+"/"+name, func(t *testing.T) {
++ // Source differs deliberately: a normalizer already owns target.
++ source := []byte(`{"reasoning":{"effort":"high","summary":"auto"}}`)
++ for _, raw := range []string{
++ `{"model":"resolved","messages":[{"role":"user","content":"中文"}]}`,
++ `{"reasoning":{"effort":"xhigh","summary":"auto","future_option":true}}`,
++ `{"reasoning":{"effort":"none","summary":null}}`,
++ `{"reasoning_effort":"ultra","reasoning":{"exclude":true}}`,
++ `{"thinking":{"type":"adaptive","display":"omitted"},"output_config":{"effort":"max","other":7}}`,
++ `{"thinking":{"type":"enabled","budget_tokens":256},"max_tokens":8192}`,
++ `{"thinking":{"type":"enabled"},"max_tokens":8192}`,
++ `{"thinking":{"type":"disabled"}}`,
++ } {
++ body := []byte(raw)
++ before := cloneIntentModel(model)
++ out, err := thinking.ApplyThinkingWithModelInfo(body, source, "resolved", route[0], route[1], route[1], model)
++ if err != nil || !bytes.Equal(out, body) {
++ t.Fatalf("native intent changed: err=%v input=%s output=%s", err, body, out)
++ }
++ if !reflect.DeepEqual(model, before) {
++ t.Fatal("selected model snapshot was changed")
++ }
++ }
++ })
++ }
++ }
++}
++
++func cloneIntentModel(model *registry.ModelInfo) *registry.ModelInfo {
++ if model == nil {
++ return nil
++ }
++ out := *model
++ if model.Thinking != nil {
++ support := *model.Thinking
++ support.Levels = append([]string(nil), support.Levels...)
++ out.Thinking = &support
++ }
++ return &out
++}
++
++func TestNativeIntentDisablePrecedesCapabilitiesAndSummary(t *testing.T) {
++ for _, target := range []string{"claude", "codex", "openai", "xai", "kimi"} {
++ for _, support := range []*registry.ThinkingSupport{nil, {}, {Levels: []string{"high", "low"}}} {
++ model := modelconfig.ResolveModelInfo("intent-disable-custom", target, support)
++ for _, suffix := range []string{"", "(none)", "(0)"} {
++ t.Run(target+"/"+suffix, func(t *testing.T) {
++ body := []byte(`{"thinking":{"type":"adaptive","display":"summarized"},"output_config":{"effort":"high"},"reasoning":{"effort":"high","summary":"auto"},"reasoning_effort":"high"}`)
++ source := []byte(`{"reasoning_effort":"none"}`)
++ out, err := thinking.ApplyThinkingWithModelInfoAndSummary(body, source, "intent-disable-custom"+suffix,
++ "openai", target, target, model, thinking.SummaryConfig{Mode: thinking.SummaryEnabled})
++ if target == "openai" && suffix == "" {
++ // Native target normalization is authoritative; tested above.
++ if err != nil || !bytes.Equal(out, body) {
++ t.Fatalf("native prepared target changed: err=%v body=%s", err, out)
++ }
++ return
++ }
++ if err != nil {
++ t.Fatal(err)
++ }
++ field, want := "reasoning.effort", "none"
++ if target == "claude" || target == "kimi" {
++ field, want = "thinking.type", "disabled"
++ } else if target == "openai" {
++ field = "reasoning_effort"
++ }
++ if got := gjson.GetBytes(out, field).String(); got != want {
++ t.Fatalf("%s=%q, want %q; body=%s", field, got, want, out)
++ }
++ if target == "claude" && (gjson.GetBytes(out, "thinking.display").Exists() || gjson.GetBytes(out, "output_config.effort").Exists()) {
++ t.Fatalf("disabled Claude retained activation fields: %s", out)
++ }
++ })
++ }
++ }
++ }
++}
++
++func TestNativeIntentMissingMetadataUsesOriginalSource(t *testing.T) {
++ for _, model := range []*registry.ModelInfo{
++ nil, {ID: "user", UserDefined: true}, modelconfig.ResolveModelInfo("unknown", "claude", nil),
++ } {
++ out, err := thinking.ApplyThinkingWithModelInfo(
++ []byte(`{"thinking":{"type":"enabled","budget_tokens":1024}}`),
++ []byte(`{"reasoning":{"effort":"xhigh"}}`),
++ "unknown", "openai-response", "claude", "claude", model,
++ )
++ if err != nil || gjson.GetBytes(out, "output_config.effort").String() != "xhigh" {
++ t.Fatalf("original source intent lost: err=%v body=%s", err, out)
++ }
++ if gjson.GetBytes(out, "thinking.budget_tokens").Exists() {
++ t.Fatalf("inferred translated budget retained: %s", out)
++ }
++ }
++}
++
++func TestNativeIntentKeepsConversionAndSuffixAuthority(t *testing.T) {
++ model := modelconfig.ResolveModelInfo("claude-opus-4-6", "claude", nil)
++ body := []byte(`{"thinking":{"type":"enabled","budget_tokens":1024}}`)
++ source := []byte(`{"reasoning":{"effort":"xhigh"}}`)
++ out, err := thinking.ApplyThinkingWithModelInfo(body, source, model.ID, "openai-response", "claude", "claude", model)
++ if err != nil || gjson.GetBytes(out, "output_config.effort").String() != "max" {
++ t.Fatalf("known cross-protocol conversion changed: err=%v body=%s", err, out)
++ }
++ out, err = thinking.ApplyThinkingWithModelInfo(body, source, model.ID+"(low)", "claude", "claude", "claude", model)
++ if err != nil || gjson.GetBytes(out, "output_config.effort").String() != "low" {
++ t.Fatalf("suffix precedence lost: err=%v body=%s", err, out)
++ }
++}
++
++func TestNativeIntentKimiNativeDisableWinsOverLegacyChatEffort(t *testing.T) {
++ body := []byte(`{"thinking":{"type":"disabled"},"reasoning_effort":"high"}`)
++ model := modelconfig.ResolveModelInfo("kimi-intent-custom", "kimi", &registry.ThinkingSupport{Levels: []string{"high", "low"}})
++ out, err := thinking.ApplyThinkingWithModelInfo(body, body, model.ID, "openai", "kimi", "kimi", model)
++ if err != nil || gjson.GetBytes(out, "thinking.type").String() != "disabled" || gjson.GetBytes(out, "reasoning_effort").Exists() {
++ t.Fatalf("Kimi disable lost: err=%v body=%s", err, out)
++ }
++}
++
++func TestNativeIntentKimiRepresentationUsesOriginalAndKeepsPreparedTarget(t *testing.T) {
++ model := modelconfig.ResolveModelInfo("kimi-k2.5", "kimi", nil)
++ for _, original := range []string{
++ `{"thinking":{"type":"enabled"}}`,
++ `{"thinking":{"type":"future-type","effort":"ULTRA","keep":"all"}}`,
++ `{"thinking":{"type":"disabled"},"reasoning_effort":"high"}`,
++ `{"thinking":{"effort":"ultra"}}`,
++ } {
++ // Target normalization may replace/remove the native object. Native
++ // detection uses original source, preservation uses prepared target.
++ for _, prepared := range []string{
++ `{"model":"resolved","thinking":{"type":"future","effort":"target-only","keep":"all"},"reasoning_effort":"high"}`,
++ `{"model":"resolved","reasoning_effort":"high"}`,
++ } {
++ out, err := thinking.ApplyThinkingWithModelInfo([]byte(prepared), []byte(original), model.ID, "openai", "kimi", "kimi", model)
++ want := strings.Replace(prepared, `,"reasoning_effort":"high"`, "", 1)
++ if err != nil || string(out) != want {
++ t.Fatalf("Kimi original/prepared authority lost: err=%v body=%s want=%s", err, out, want)
++ }
++ }
++ }
++ for _, source := range []string{
++ `{"reasoning_effort":"high"}`,
++ `{"thinking":{"keep":"all"},"reasoning_effort":"high"}`,
++ } {
++ out, err := thinking.ApplyThinkingWithModelInfo([]byte(source), []byte(source), model.ID, "openai", "kimi", "kimi", model)
++ if err != nil || gjson.GetBytes(out, "thinking.type").String() != "enabled" || gjson.GetBytes(out, "thinking.effort").String() != "high" {
++ t.Fatalf("Kimi legacy conversion lost: err=%v body=%s", err, out)
++ }
++ }
++ source := []byte(`{"thinking":{"type":"enabled","effort":"ultra"},"reasoning_effort":"high"}`)
++ out, err := thinking.ApplyThinkingWithModelInfo(source, source, model.ID+"(none)", "openai", "kimi", "kimi", model)
++ if err != nil || gjson.GetBytes(out, "thinking.type").String() != "disabled" || gjson.GetBytes(out, "thinking.effort").Exists() {
++ t.Fatalf("Kimi suffix did not override native object: err=%v body=%s", err, out)
++ }
++}
+diff --git a/internal/thinking/provider/claude/apply.go b/internal/thinking/provider/claude/apply.go
+index 97f0284..3d2d248 100644
+--- a/internal/thinking/provider/claude/apply.go
++++ b/internal/thinking/provider/claude/apply.go
+@@ -70,11 +70,11 @@ func init() {
+ // }
+ // }
+ func (a *Applier) Apply(body []byte, config thinking.ThinkingConfig, modelInfo *registry.ModelInfo) ([]byte, error) {
+- if thinking.IsUserDefinedModel(modelInfo) {
++ if config.Mode == thinking.ModeNone && config.Budget == 0 && config.Level == "" {
+ return applyCompatibleClaude(body, config)
+ }
+- if modelInfo.Thinking == nil {
+- return body, nil
++ if thinking.IsUserDefinedModel(modelInfo) || modelInfo.Thinking == nil {
++ return applyCompatibleClaude(body, config)
+ }
+
+ if len(body) == 0 || !gjson.ValidBytes(body) {
+diff --git a/internal/thinking/provider/codex/apply.go b/internal/thinking/provider/codex/apply.go
+index 83f5ae8..37f160a 100644
+--- a/internal/thinking/provider/codex/apply.go
++++ b/internal/thinking/provider/codex/apply.go
+@@ -42,11 +42,11 @@ func init() {
+ // }
+ // }
+ func (a *Applier) Apply(body []byte, config thinking.ThinkingConfig, modelInfo *registry.ModelInfo) ([]byte, error) {
+- if thinking.IsUserDefinedModel(modelInfo) {
++ if config.Mode == thinking.ModeNone && config.Budget == 0 && config.Level == "" {
+ return applyCompatibleCodex(body, config)
+ }
+- if modelInfo.Thinking == nil {
+- return body, nil
++ if thinking.IsUserDefinedModel(modelInfo) || modelInfo.Thinking == nil {
++ return applyCompatibleCodex(body, config)
+ }
+
+ // Only handle ModeLevel and ModeNone; other modes pass through unchanged.
+diff --git a/internal/thinking/provider/kimi/apply.go b/internal/thinking/provider/kimi/apply.go
+index 6ed8504..c645c6b 100644
+--- a/internal/thinking/provider/kimi/apply.go
++++ b/internal/thinking/provider/kimi/apply.go
+@@ -53,11 +53,11 @@ func init() {
+ // }
+ // }
+ func (a *Applier) Apply(body []byte, config thinking.ThinkingConfig, modelInfo *registry.ModelInfo) ([]byte, error) {
+- if thinking.IsUserDefinedModel(modelInfo) {
++ if config.Mode == thinking.ModeNone && config.Budget == 0 && config.Level == "" {
+ return applyCompatibleKimi(body, config)
+ }
+- if modelInfo.Thinking == nil {
+- return body, nil
++ if thinking.IsUserDefinedModel(modelInfo) || modelInfo.Thinking == nil {
++ return applyCompatibleKimi(body, config)
+ }
+
+ if len(body) == 0 || !gjson.ValidBytes(body) {
+diff --git a/internal/thinking/provider/openai/apply.go b/internal/thinking/provider/openai/apply.go
+index 1e87b72..096f1a7 100644
+--- a/internal/thinking/provider/openai/apply.go
++++ b/internal/thinking/provider/openai/apply.go
+@@ -39,11 +39,11 @@ func init() {
+ // "reasoning_effort": "high"
+ // }
+ func (a *Applier) Apply(body []byte, config thinking.ThinkingConfig, modelInfo *registry.ModelInfo) ([]byte, error) {
+- if thinking.IsUserDefinedModel(modelInfo) {
++ if config.Mode == thinking.ModeNone && config.Budget == 0 && config.Level == "" {
+ return applyCompatibleOpenAI(body, config)
+ }
+- if modelInfo.Thinking == nil {
+- return body, nil
++ if thinking.IsUserDefinedModel(modelInfo) || modelInfo.Thinking == nil {
++ return applyCompatibleOpenAI(body, config)
+ }
+
+ // Only handle ModeLevel and ModeNone; other modes pass through unchanged.
+diff --git a/test/thinking_conversion_test.go b/test/thinking_conversion_test.go
+index 72299d8..18dbbdf 100644
+--- a/test/thinking_conversion_test.go
++++ b/test/thinking_conversion_test.go
+@@ -87,7 +87,7 @@ func TestThinkingE2EMatrix_Suffix(t *testing.T) {
+ expectField: "",
+ expectErr: true,
+ },
+- // Case 4: Level none → clamped to minimal (ZeroAllowed=false)
++ // Case 4: Explicit disable precedes capability flags
+ {
+ name: "4",
+ from: "openai",
+@@ -95,7 +95,7 @@ func TestThinkingE2EMatrix_Suffix(t *testing.T) {
+ model: "level-model(none)",
+ inputJSON: `{"model":"level-model(none)","messages":[{"role":"user","content":"hi"}]}`,
+ expectField: "reasoning.effort",
+- expectValue: "minimal",
++ expectValue: "none",
+ expectErr: false,
+ },
+ // Case 5: Level auto → DynamicAllowed=false → medium (mid-range)
+@@ -142,7 +142,7 @@ func TestThinkingE2EMatrix_Suffix(t *testing.T) {
+ expectValue: "high",
+ expectErr: false,
+ },
+- // Case 9: Budget 0 → clamped to minimal (ZeroAllowed=false)
++ // Case 9: Explicit disable precedes capability flags
+ {
+ name: "9",
+ from: "gemini",
+@@ -150,7 +150,7 @@ func TestThinkingE2EMatrix_Suffix(t *testing.T) {
+ model: "level-model(0)",
+ inputJSON: `{"model":"level-model(0)","contents":[{"role":"user","parts":[{"text":"hi"}]}]}`,
+ expectField: "reasoning.effort",
+- expectValue: "minimal",
++ expectValue: "none",
+ expectErr: false,
+ },
+ // Case 10: Budget -1 → auto → DynamicAllowed=false → medium (mid-range)
+@@ -196,7 +196,7 @@ func TestThinkingE2EMatrix_Suffix(t *testing.T) {
+ expectValue: "high",
+ expectErr: false,
+ },
+- // Case 14: Budget 0 → clamped to minimal (ZeroAllowed=false)
++ // Case 14: Explicit disable precedes capability flags
+ {
+ name: "14",
+ from: "claude",
+@@ -204,7 +204,7 @@ func TestThinkingE2EMatrix_Suffix(t *testing.T) {
+ model: "level-model(0)",
+ inputJSON: `{"model":"level-model(0)","messages":[{"role":"user","content":"hi"}]}`,
+ expectField: "reasoning_effort",
+- expectValue: "minimal",
++ expectValue: "none",
+ expectErr: false,
+ },
+ // Case 15: Budget -1 → auto → DynamicAllowed=false → medium (mid-range)
+@@ -736,34 +736,37 @@ func TestThinkingE2EMatrix_Suffix(t *testing.T) {
+ expectField: "",
+ expectErr: false,
+ },
+- // Case 59: Budget 8192 → no thinking support → suffix stripped → no configuration
++ // Case 59: Missing metadata retains capability-free conversion
+ {
+ name: "59",
+ from: "gemini",
+ to: "openai",
+ model: "no-thinking-model(8192)",
+ inputJSON: `{"model":"no-thinking-model(8192)","contents":[{"role":"user","parts":[{"text":"hi"}]}]}`,
+- expectField: "",
++ expectField: "reasoning_effort",
++ expectValue: "medium",
+ expectErr: false,
+ },
+- // Case 60: Budget 0 → suffix stripped → no configuration
++ // Case 60: Missing metadata retains capability-free conversion
+ {
+ name: "60",
+ from: "gemini",
+ to: "openai",
+ model: "no-thinking-model(0)",
+ inputJSON: `{"model":"no-thinking-model(0)","contents":[{"role":"user","parts":[{"text":"hi"}]}]}`,
+- expectField: "",
++ expectField: "reasoning_effort",
++ expectValue: "none",
+ expectErr: false,
+ },
+- // Case 61: Budget -1 → suffix stripped → no configuration
++ // Case 61: Missing metadata retains capability-free conversion
+ {
+ name: "61",
+ from: "gemini",
+ to: "openai",
+ model: "no-thinking-model(-1)",
+ inputJSON: `{"model":"no-thinking-model(-1)","contents":[{"role":"user","parts":[{"text":"hi"}]}]}`,
+- expectField: "",
++ expectField: "reasoning_effort",
++ expectValue: "auto",
+ expectErr: false,
+ },
+ // Case 62: Claude source no suffix → no configuration
+@@ -776,34 +779,37 @@ func TestThinkingE2EMatrix_Suffix(t *testing.T) {
+ expectField: "",
+ expectErr: false,
+ },
+- // Case 63: Budget 8192 → suffix stripped → no configuration
++ // Case 63: Missing metadata retains capability-free conversion
+ {
+ name: "63",
+ from: "claude",
+ to: "openai",
+ model: "no-thinking-model(8192)",
+ inputJSON: `{"model":"no-thinking-model(8192)","messages":[{"role":"user","content":"hi"}]}`,
+- expectField: "",
++ expectField: "reasoning_effort",
++ expectValue: "medium",
+ expectErr: false,
+ },
+- // Case 64: Budget 0 → suffix stripped → no configuration
++ // Case 64: Missing metadata retains capability-free conversion
+ {
+ name: "64",
+ from: "claude",
+ to: "openai",
+ model: "no-thinking-model(0)",
+ inputJSON: `{"model":"no-thinking-model(0)","messages":[{"role":"user","content":"hi"}]}`,
+- expectField: "",
++ expectField: "reasoning_effort",
++ expectValue: "none",
+ expectErr: false,
+ },
+- // Case 65: Budget -1 → suffix stripped → no configuration
++ // Case 65: Missing metadata retains capability-free conversion
+ {
+ name: "65",
+ from: "claude",
+ to: "openai",
+ model: "no-thinking-model(-1)",
+ inputJSON: `{"model":"no-thinking-model(-1)","messages":[{"role":"user","content":"hi"}]}`,
+- expectField: "",
++ expectField: "reasoning_effort",
++ expectValue: "auto",
+ expectErr: false,
+ },
+
+@@ -1131,7 +1137,7 @@ func TestThinkingE2EMatrix_Body(t *testing.T) {
+ expectField: "",
+ expectErr: true,
+ },
+- // Case 4: reasoning_effort=none → clamped to minimal
++ // Case 4: Explicit disable precedes capability flags
+ {
+ name: "4",
+ from: "openai",
+@@ -1139,7 +1145,7 @@ func TestThinkingE2EMatrix_Body(t *testing.T) {
+ model: "level-model",
+ inputJSON: `{"model":"level-model","messages":[{"role":"user","content":"hi"}],"reasoning_effort":"none"}`,
+ expectField: "reasoning.effort",
+- expectValue: "minimal",
++ expectValue: "none",
+ expectErr: false,
+ },
+ // Case 5: reasoning_effort=auto → medium (DynamicAllowed=false)
+@@ -1186,7 +1192,7 @@ func TestThinkingE2EMatrix_Body(t *testing.T) {
+ expectValue: "high",
+ expectErr: false,
+ },
+- // Case 9: thinkingBudget=0 → clamped to minimal
++ // Case 9: Explicit disable precedes capability flags
+ {
+ name: "9",
+ from: "gemini",
+@@ -1194,7 +1200,7 @@ func TestThinkingE2EMatrix_Body(t *testing.T) {
+ model: "level-model",
+ inputJSON: `{"model":"level-model","contents":[{"role":"user","parts":[{"text":"hi"}]}],"generationConfig":{"thinkingConfig":{"thinkingBudget":0}}}`,
+ expectField: "reasoning.effort",
+- expectValue: "minimal",
++ expectValue: "none",
+ expectErr: false,
+ },
+ // Case 10: thinkingBudget=-1 → medium (DynamicAllowed=false)
+@@ -1240,7 +1246,7 @@ func TestThinkingE2EMatrix_Body(t *testing.T) {
+ expectValue: "high",
+ expectErr: false,
+ },
+- // Case 14: thinking.budget_tokens=0 → clamped to minimal
++ // Case 14: Explicit disable precedes capability flags
+ {
+ name: "14",
+ from: "claude",
+@@ -1248,7 +1254,7 @@ func TestThinkingE2EMatrix_Body(t *testing.T) {
+ model: "level-model",
+ inputJSON: `{"model":"level-model","messages":[{"role":"user","content":"hi"}],"thinking":{"type":"enabled","budget_tokens":0}}`,
+ expectField: "reasoning_effort",
+- expectValue: "minimal",
++ expectValue: "none",
+ expectErr: false,
+ },
+ // Case 15: thinking.budget_tokens=-1 → medium (DynamicAllowed=false)
+@@ -1810,34 +1816,37 @@ func TestThinkingE2EMatrix_Body(t *testing.T) {
+ expectField: "",
+ expectErr: false,
+ },
+- // Case 59: thinkingBudget=8192 → stripped
++ // Case 59: Missing metadata retains capability-free conversion
+ {
+ name: "59",
+ from: "gemini",
+ to: "openai",
+ model: "no-thinking-model",
+ inputJSON: `{"model":"no-thinking-model","contents":[{"role":"user","parts":[{"text":"hi"}]}],"generationConfig":{"thinkingConfig":{"thinkingBudget":8192}}}`,
+- expectField: "",
++ expectField: "reasoning_effort",
++ expectValue: "medium",
+ expectErr: false,
+ },
+- // Case 60: thinkingBudget=0 → stripped
++ // Case 60: Missing metadata retains capability-free conversion
+ {
+ name: "60",
+ from: "gemini",
+ to: "openai",
+ model: "no-thinking-model",
+ inputJSON: `{"model":"no-thinking-model","contents":[{"role":"user","parts":[{"text":"hi"}]}],"generationConfig":{"thinkingConfig":{"thinkingBudget":0}}}`,
+- expectField: "",
++ expectField: "reasoning_effort",
++ expectValue: "none",
+ expectErr: false,
+ },
+- // Case 61: thinkingBudget=-1 → stripped
++ // Case 61: Missing metadata retains capability-free conversion
+ {
+ name: "61",
+ from: "gemini",
+ to: "openai",
+ model: "no-thinking-model",
+ inputJSON: `{"model":"no-thinking-model","contents":[{"role":"user","parts":[{"text":"hi"}]}],"generationConfig":{"thinkingConfig":{"thinkingBudget":-1}}}`,
+- expectField: "",
++ expectField: "reasoning_effort",
++ expectValue: "auto",
+ expectErr: false,
+ },
+ // Case 62: Claude no param → passthrough
+@@ -1850,34 +1859,37 @@ func TestThinkingE2EMatrix_Body(t *testing.T) {
+ expectField: "",
+ expectErr: false,
+ },
+- // Case 63: thinking.budget_tokens=8192 → stripped
++ // Case 63: Missing metadata retains capability-free conversion
+ {
+ name: "63",
+ from: "claude",
+ to: "openai",
+ model: "no-thinking-model",
+ inputJSON: `{"model":"no-thinking-model","messages":[{"role":"user","content":"hi"}],"thinking":{"type":"enabled","budget_tokens":8192}}`,
+- expectField: "",
++ expectField: "reasoning_effort",
++ expectValue: "medium",
+ expectErr: false,
+ },
+- // Case 64: thinking.budget_tokens=0 → stripped
++ // Case 64: Missing metadata retains capability-free conversion
+ {
+ name: "64",
+ from: "claude",
+ to: "openai",
+ model: "no-thinking-model",
+ inputJSON: `{"model":"no-thinking-model","messages":[{"role":"user","content":"hi"}],"thinking":{"type":"enabled","budget_tokens":0}}`,
+- expectField: "",
++ expectField: "reasoning_effort",
++ expectValue: "none",
+ expectErr: false,
+ },
+- // Case 65: thinking.budget_tokens=-1 → stripped
++ // Case 65: Missing metadata retains capability-free conversion
+ {
+ name: "65",
+ from: "claude",
+ to: "openai",
+ model: "no-thinking-model",
+ inputJSON: `{"model":"no-thinking-model","messages":[{"role":"user","content":"hi"}],"thinking":{"type":"enabled","budget_tokens":-1}}`,
+- expectField: "",
++ expectField: "reasoning_effort",
++ expectValue: "auto",
+ expectErr: false,
+ },
+
+@@ -2052,15 +2064,16 @@ func TestThinkingE2EMatrix_Body(t *testing.T) {
+ expectValue: "high",
+ expectErr: false,
+ },
+- // Case 81: OpenAI to OpenAI, reasoning_effort=xhigh → out of range error
++ // Case 81: Native intent is validated by upstream, not the catalog
+ {
+ name: "81",
+ from: "openai",
+ to: "openai",
+ model: "level-model",
+ inputJSON: `{"model":"level-model","messages":[{"role":"user","content":"hi"}],"reasoning_effort":"xhigh"}`,
+- expectField: "",
+- expectErr: true,
++ expectField: "reasoning_effort",
++ expectValue: "xhigh",
++ expectErr: false,
+ },
+ // Case 82: OpenAI-Response to Codex, reasoning.effort=high → passthrough
+ {
+@@ -2073,15 +2086,16 @@ func TestThinkingE2EMatrix_Body(t *testing.T) {
+ expectValue: "high",
+ expectErr: false,
+ },
+- // Case 83: OpenAI-Response to Codex, reasoning.effort=xhigh → out of range error
++ // Case 83: Native intent is validated by upstream, not the catalog
+ {
+ name: "83",
+ from: "openai-response",
+ to: "codex",
+ model: "level-model",
+ inputJSON: `{"model":"level-model","input":[{"role":"user","content":"hi"}],"reasoning":{"effort":"xhigh"}}`,
+- expectField: "",
+- expectErr: true,
++ expectField: "reasoning.effort",
++ expectValue: "xhigh",
++ expectErr: false,
+ },
+ // Case 84: Gemini to Gemini, thinkingBudget=8192 → passthrough
+ {
+@@ -2116,15 +2130,16 @@ func TestThinkingE2EMatrix_Body(t *testing.T) {
+ expectValue: "8192",
+ expectErr: false,
+ },
+- // Case 87: Claude to Claude, thinking.budget_tokens=200000 → exceeds Max error
++ // Case 87: Native intent is validated by upstream, not the catalog
+ {
+ name: "87",
+ from: "claude",
+ to: "claude",
+ model: "claude-budget-model",
+ inputJSON: `{"model":"claude-budget-model","messages":[{"role":"user","content":"hi"}],"thinking":{"type":"enabled","budget_tokens":200000}}`,
+- expectField: "",
+- expectErr: true,
++ expectField: "thinking.budget_tokens",
++ expectValue: "200000",
++ expectErr: false,
+ },
+ // Gemini Family Cross-Channel Consistency (Cases 88-89)
+ // Tests that gemini/antigravity as same API family should have consistent validation behavior
+@@ -2219,10 +2234,8 @@ func TestThinkingE2EProviderTargets(t *testing.T) {
+ model: "kimi-tiered-thinking-model(none)",
+ inputJSON: `{"model":"kimi-tiered-thinking-model(none)","messages":[{"role":"user","content":"hi"}]}`,
+ expectField: "thinking.type",
+- expectValue: "enabled",
+- expectField2: "thinking.effort",
+- expectValue2: "low",
+- expectAbsent: []string{"reasoning_effort"},
++ expectValue: "disabled",
++ expectAbsent: []string{"thinking.effort", "reasoning_effort"},
+ },
+ {
+ name: "K6",
+@@ -2287,10 +2300,8 @@ func TestThinkingE2EProviderTargets(t *testing.T) {
+ model: "kimi-tiered-thinking-model",
+ inputJSON: `{"model":"kimi-tiered-thinking-model","messages":[{"role":"user","content":"hi"}],"thinking":{"type":"enabled","budget_tokens":0}}`,
+ expectField: "thinking.type",
+- expectValue: "enabled",
+- expectField2: "thinking.effort",
+- expectValue2: "low",
+- expectAbsent: []string{"reasoning_effort"},
++ expectValue: "disabled",
++ expectAbsent: []string{"thinking.effort", "reasoning_effort"},
+ },
+ {
+ name: "K12",
+@@ -2338,11 +2349,9 @@ func TestThinkingE2EProviderTargets(t *testing.T) {
+ to: "kimi",
+ model: "kimi-toggle-thinking-model",
+ inputJSON: `{"model":"kimi-toggle-thinking-model","messages":[{"role":"user","content":"hi"}],"thinking":{"effort":"high"},"reasoning_effort":"low"}`,
+- expectField: "thinking.type",
+- expectValue: "enabled",
+- expectField2: "thinking.effort",
+- expectValue2: "high",
+- expectAbsent: []string{"reasoning_effort"},
++ expectField: "thinking.effort",
++ expectValue: "high",
++ expectAbsent: []string{"thinking.type", "reasoning_effort"},
+ },
+ {
+ name: "K16",
+@@ -2419,7 +2428,7 @@ func TestThinkingE2EProviderTargets(t *testing.T) {
+ model: "xai-level-model",
+ inputJSON: `{"model":"xai-level-model","input":[{"role":"user","content":"hi"}],"reasoning":{"effort":"minimal"}}`,
+ expectField: "reasoning.effort",
+- expectValue: "low",
++ expectValue: "minimal",
+ },
+ {
+ name: "X8",
+@@ -2489,7 +2498,7 @@ func TestThinkingE2EProviderTargets(t *testing.T) {
+ model: "level-model",
+ inputJSON: `{"model":"level-model","input":"hi","reasoning":{"effort":"none"}}`,
+ expectField: "reasoning_effort",
+- expectValue: "minimal",
++ expectValue: "none",
+ },
+ {
+ name: "R3",
+@@ -3072,7 +3081,8 @@ func TestThinkingE2EClaudeAdaptive_Body(t *testing.T) {
+ to: "openai",
+ model: "no-thinking-model",
+ inputJSON: `{"model":"no-thinking-model","messages":[{"role":"user","content":"hi"}],"thinking":{"type":"adaptive"},"output_config":{"effort":"high"}}`,
+- expectField: "",
++ expectField: "reasoning_effort",
++ expectValue: "high",
+ expectErr: false,
+ },
+
+@@ -3230,12 +3240,14 @@ func TestThinkingE2EClaudeAdaptive_Body(t *testing.T) {
+ expectErr: false,
+ },
+ {
+- name: "C22",
+- from: "claude",
+- to: "claude",
+- model: "claude-opus-4-6-model",
+- inputJSON: `{"model":"claude-opus-4-6-model","messages":[{"role":"user","content":"hi"}],"thinking":{"type":"adaptive"},"output_config":{"effort":"xhigh"}}`,
+- expectErr: true,
++ name: "C22",
++ from: "claude",
++ to: "claude",
++ model: "claude-opus-4-6-model",
++ inputJSON: `{"model":"claude-opus-4-6-model","messages":[{"role":"user","content":"hi"}],"thinking":{"type":"adaptive"},"output_config":{"effort":"xhigh"}}`,
++ expectField: "output_config.effort",
++ expectValue: "xhigh",
++ expectErr: false,
+ },
+ {
+ name: "C23",
+@@ -3250,20 +3262,24 @@ func TestThinkingE2EClaudeAdaptive_Body(t *testing.T) {
+ expectErr: false,
+ },
+ {
+- name: "C24",
+- from: "claude",
+- to: "claude",
+- model: "claude-sonnet-4-6-model",
+- inputJSON: `{"model":"claude-sonnet-4-6-model","messages":[{"role":"user","content":"hi"}],"thinking":{"type":"adaptive"},"output_config":{"effort":"max"}}`,
+- expectErr: true,
++ name: "C24",
++ from: "claude",
++ to: "claude",
++ model: "claude-sonnet-4-6-model",
++ inputJSON: `{"model":"claude-sonnet-4-6-model","messages":[{"role":"user","content":"hi"}],"thinking":{"type":"adaptive"},"output_config":{"effort":"max"}}`,
++ expectField: "output_config.effort",
++ expectValue: "max",
++ expectErr: false,
+ },
+ {
+- name: "C25",
+- from: "claude",
+- to: "claude",
+- model: "claude-sonnet-4-6-model",
+- inputJSON: `{"model":"claude-sonnet-4-6-model","messages":[{"role":"user","content":"hi"}],"thinking":{"type":"adaptive"},"output_config":{"effort":"xhigh"}}`,
+- expectErr: true,
++ name: "C25",
++ from: "claude",
++ to: "claude",
++ model: "claude-sonnet-4-6-model",
++ inputJSON: `{"model":"claude-sonnet-4-6-model","messages":[{"role":"user","content":"hi"}],"thinking":{"type":"adaptive"},"output_config":{"effort":"xhigh"}}`,
++ expectField: "output_config.effort",
++ expectValue: "xhigh",
++ expectErr: false,
+ },
+ }
+
diff --git a/patches/cliproxyapi/patched-files.json b/patches/cliproxyapi/patched-files.json
new file mode 100644
index 000000000..d01e2dd7d
--- /dev/null
+++ b/patches/cliproxyapi/patched-files.json
@@ -0,0 +1,17 @@
+{
+ "internal/runtime/executor/helps/model_capabilities.go": "f7fa213a5abad5612fdfb1e74e081f184d2f6e2a36b930c3af8281b6f1b572cb",
+ "internal/runtime/executor/helps/thinking.go": "f20d0276d83ada0970f0e128a10ccc747e7e5a95c2c4a6a243d9ee1e47474917",
+ "internal/runtime/executor/native_intent_test.go": "9c499039cfbdae871126a44418db651c11ca110de10fee1c51da50431a56f470",
+ "internal/runtime/executor/xai_executor_request.go": "04970082bc305c620386cf7098c04336eb939a2f029d65fb5de813df2ed2af4f",
+ "internal/runtime/executor/xai_executor_response.go": "d5c0667254b06a811377073257903c7d37fa9b17bb1fd3aee3525e19a1d375b1",
+ "internal/runtime/executor/xai_executor_test.go": "1b4956e0e5810611fd7232ec48e4e8ab37c78f8a4ead4f21b9e8f48213550394",
+ "internal/thinking/apply.go": "0bfbb1cf2678de98620f12489059c0acd73835e326e6a506e4593cd3b334ed3b",
+ "internal/thinking/apply_configured_api_key_test.go": "c24f05f8412ae07501a6ce16268a70013fce0481c9893ab72368e2a1a00d843b",
+ "internal/thinking/kimi_max_clamp_repro_test.go": "5cac7a075d13fcbbc605cdb35163b58cdf6a870268719af17fb995f25333cde5",
+ "internal/thinking/native_intent_test.go": "15970e6065a97ca8291995365822835cdd56e67a08b60a473b91856b84e07b9d",
+ "internal/thinking/provider/claude/apply.go": "5fa5f404f71dd6b484b59d55ba62ad5cda9a2c59186149768dab174b20725d19",
+ "internal/thinking/provider/codex/apply.go": "8a1a42bcbfca731fab2ba827c59fa31fd4a8c320a0300d9e25e15c7b5e0e5400",
+ "internal/thinking/provider/kimi/apply.go": "8f031dc04f5915a3f5e347bbc195d076ac36987fb3a9740781c45b7f3cd9969d",
+ "internal/thinking/provider/openai/apply.go": "d532b8f4c06d8f48be3454a44ad1811b9010e7d14a3934b89d369f0a54a2c572",
+ "test/thinking_conversion_test.go": "73c3eee316082aacc1f5de537aac5e8f00f2884b0b2dbcf6c618869f35e522ad"
+}
diff --git a/patches/cliproxyapi/prerequisites.json b/patches/cliproxyapi/prerequisites.json
new file mode 100644
index 000000000..278a1ffe6
--- /dev/null
+++ b/patches/cliproxyapi/prerequisites.json
@@ -0,0 +1,12 @@
+{
+ "linux_arm64_go": {
+ "version": "go1.26.4",
+ "url": "https://go.dev/dl/go1.26.4.linux-arm64.tar.gz",
+ "sha256": "ef758ae7c6cf9267c9c0ef080b8965f453d89ab2d25d9eb22de4405925238768"
+ },
+ "linux_arm64_uv": {
+ "version": "0.9.8",
+ "url": "https://github.com/astral-sh/uv/releases/download/0.9.8/uv-aarch64-unknown-linux-gnu.tar.gz",
+ "sha256": "8dc203a27c99f721545adc531279f0486ea3deb77c951a051e6bb9ea1d588a71"
+ }
+}
diff --git a/patches/cliproxyapi/test_execution_inputs.py b/patches/cliproxyapi/test_execution_inputs.py
new file mode 100644
index 000000000..b7f4099d2
--- /dev/null
+++ b/patches/cliproxyapi/test_execution_inputs.py
@@ -0,0 +1,234 @@
+"""Archive/extraction/selected-executable consumers; no real compiler is run."""
+
+import hashlib
+import io
+import os
+import shutil
+import sys
+import tarfile
+from pathlib import Path
+
+import pytest
+
+import execution_inputs
+
+
[email protected]("kind", ["directory", "fifo", "symlink", "hardlink"])
+def test_regular_file_rejects_unadmitted_types_without_opening(tmp_path, monkeypatch, kind):
+ target = tmp_path / "input"
+ if kind == "directory":
+ target.mkdir()
+ elif kind == "fifo":
+ os.mkfifo(target)
+ else:
+ original = tmp_path / "original"
+ original.write_bytes(b"task-only input")
+ if kind == "symlink":
+ target.symlink_to(original)
+ else:
+ os.link(original, target)
+ monkeypatch.setattr(os, "open", lambda *_a, **_kw: pytest.fail("Rejected input must not be opened."))
+ with pytest.raises(ValueError, match="single-link regular"):
+ execution_inputs.file_sha256(target)
+
+
[email protected]("when", ["admission", "completion"])
[email protected]("mutation", ["replacement", "symlink", "fifo", "hardlink", "mode", "content"])
+def test_regular_file_binds_actual_descriptor_and_closes_on_observed_drift(tmp_path, monkeypatch, when, mutation):
+ target = tmp_path / "input"
+ target.write_bytes(b"original task-only bytes")
+ target.chmod(0o644)
+ original_open, original_fstat = os.open, os.fstat
+ opened = []
+
+ def mutate():
+ if mutation in ("replacement", "symlink", "fifo"):
+ preserved = tmp_path / "preserved"
+ target.rename(preserved)
+ if mutation == "replacement":
+ target.write_bytes(preserved.read_bytes())
+ elif mutation == "symlink":
+ target.symlink_to(preserved)
+ else:
+ os.mkfifo(target)
+ elif mutation == "hardlink":
+ os.link(target, tmp_path / "writable-alias")
+ elif mutation == "mode":
+ target.chmod(0o600)
+ else:
+ target.write_bytes(b"modified task-only bytes")
+
+ def opening(path, flags, *args, **kwargs):
+ assert Path(path) == target
+ assert all(flags & flag for flag in (os.O_NOFOLLOW, os.O_NONBLOCK, os.O_CLOEXEC))
+ if when == "admission":
+ mutate()
+ fd = original_open(path, flags, *args, **kwargs)
+ opened.append(fd)
+ return fd
+
+ monkeypatch.setattr(os, "open", opening)
+ with pytest.raises((ValueError, OSError)):
+ with execution_inputs.regular_file(target) as stream:
+ assert when == "completion", "Admission drift reached the consuming body."
+ assert stream.read() == b"original task-only bytes"
+ mutate()
+ for fd in opened:
+ with pytest.raises(OSError):
+ original_fstat(fd)
+
+
[email protected]("failure", ["fdopen", "consumer", "none"])
+def test_regular_file_closes_partial_and_successful_acquisitions(tmp_path, monkeypatch, failure):
+ target = tmp_path / "input"
+ target.write_bytes(b"stable task-only bytes")
+ original_open, original_fstat = os.open, os.fstat
+ opened = []
+
+ def opening(*args, **kwargs):
+ fd = original_open(*args, **kwargs)
+ opened.append(fd)
+ return fd
+
+ monkeypatch.setattr(os, "open", opening)
+ if failure == "fdopen":
+ def refused(*_args, **_kwargs):
+ raise RuntimeError("finite fdopen failure")
+ monkeypatch.setattr(os, "fdopen", refused)
+ if failure == "none":
+ assert execution_inputs.file_sha256(target) == hashlib.sha256(b"stable task-only bytes").hexdigest()
+ else:
+ with pytest.raises(RuntimeError, match="finite"):
+ with execution_inputs.regular_file(target) as stream:
+ assert stream.read() == b"stable task-only bytes"
+ raise RuntimeError("finite consumer failure")
+ assert len(opened) == 1
+ with pytest.raises(OSError):
+ original_fstat(opened[0])
+
+
+def fake_go(tmp_path, monkeypatch):
+ root = tmp_path / "go"
+ (root / "bin").mkdir(parents=True)
+ (root / "pkg/tool/linux_arm64").mkdir(parents=True)
+ (root / "src/runtime").mkdir(parents=True)
+ elf = b"\x7fELF\x02\x01" + bytes(12) + (183).to_bytes(2, "little") + b"fake-only"
+ for name, content in (
+ ("bin/go", elf), ("pkg/tool/linux_arm64/compile", b"fake-compiler"),
+ ("src/runtime/runtime.go", b"package runtime\n"),
+ ):
+ path = root / name
+ path.write_bytes(content)
+ path.chmod(0o755 if name != "src/runtime/runtime.go" else 0o644)
+ archive = tmp_path / "go.tar.gz"
+ with tarfile.open(archive, "w:gz") as output:
+ for path in sorted(root.rglob("*")):
+ if path.is_file():
+ # Exercise official-style archives with implicit directories.
+ output.add(path, arcname="go/" + path.relative_to(root).as_posix())
+ prerequisite = {"version": "go1.26.4", "sha256": hashlib.sha256(archive.read_bytes()).hexdigest()}
+ monkeypatch.setattr(sys, "platform", "linux")
+ monkeypatch.setattr(execution_inputs.platform, "machine", lambda: "aarch64")
+ return root, archive, prerequisite
+
+
+def test_actual_go_tree_matches_one_verified_archive(tmp_path, monkeypatch):
+ root, archive, pin = fake_go(tmp_path, monkeypatch)
+ identity = execution_inputs.verify_go(root, archive, root / "bin/go", pin)
+ assert identity["archive_sha256"] == pin["sha256"]
+ assert identity["selected_relative_path"] == "bin/go"
+ assert identity["selected_sha256"] == hashlib.sha256((root / "bin/go").read_bytes()).hexdigest()
+ another = tmp_path / "another-path"
+ shutil.copytree(root, another)
+ second = execution_inputs.verify_go(another, archive, another / "bin/go", pin)
+ assert second["extracted_tree_sha256"] == identity["extracted_tree_sha256"]
+ assert second["selected_executable"] != identity["selected_executable"]
+
+
[email protected]("mutation", [
+ "compiler", "runtime", "tool", "extra", "extra-directory", "missing", "mode", "escape", "hardlink",
+])
+def test_valid_archive_does_not_authorize_changed_extraction(tmp_path, monkeypatch, mutation):
+ root, archive, pin = fake_go(tmp_path, monkeypatch)
+ target = root / "src/runtime/runtime.go"
+ if mutation in ("compiler", "runtime", "tool"):
+ name = {"compiler": "bin/go", "runtime": "src/runtime/runtime.go",
+ "tool": "pkg/tool/linux_arm64/compile"}[mutation]
+ (root / name).write_bytes(b"substitute claiming go1.26.4")
+ elif mutation == "extra":
+ (root / "extra").write_bytes(b"extra")
+ elif mutation == "extra-directory":
+ (root / "extra-dir").mkdir()
+ elif mutation == "missing":
+ target.unlink()
+ elif mutation == "mode":
+ (root / "bin/go").chmod(0o644)
+ elif mutation == "escape":
+ target.unlink()
+ target.symlink_to(archive)
+ else:
+ os.link(target, tmp_path / "alias")
+ with pytest.raises((RuntimeError, ValueError)):
+ execution_inputs.verify_go(root, archive, root / "bin/go", pin)
+
+
[email protected]("mutation", ["selected", "archive", "architecture"])
+def test_go_selection_archive_and_host_are_independent_checks(tmp_path, monkeypatch, mutation):
+ root, archive, pin = fake_go(tmp_path, monkeypatch)
+ selected = root / "bin/go"
+ if mutation == "selected":
+ selected = tmp_path / "same-version-go"
+ shutil.copyfile(root / "bin/go", selected)
+ elif mutation == "archive":
+ archive.write_bytes(b"another archive")
+ else:
+ monkeypatch.setattr(execution_inputs.platform, "machine", lambda: "x86_64")
+ with pytest.raises(RuntimeError):
+ execution_inputs.verify_go(root, archive, selected, pin)
+
+
+def test_wrong_elf_architecture_refuses_even_with_a_matching_test_archive(tmp_path, monkeypatch):
+ root, archive, pin = fake_go(tmp_path, monkeypatch)
+ wrong = bytearray((root / "bin/go").read_bytes())
+ wrong[18:20] = (62).to_bytes(2, "little")
+ (root / "bin/go").write_bytes(wrong)
+ with tarfile.open(archive, "w:gz") as output:
+ for path in sorted(root.rglob("*")):
+ if path.is_file():
+ output.add(path, arcname="go/" + path.relative_to(root).as_posix())
+ pin["sha256"] = hashlib.sha256(archive.read_bytes()).hexdigest()
+ with pytest.raises(RuntimeError, match="ELF"):
+ execution_inputs.verify_go(root, archive, root / "bin/go", pin)
+
+
[email protected]("name", ["/go/escape", "go/../escape", "../escape", "wrong-root/file"])
+def test_bad_archive_members_refuse_without_extraction(tmp_path, name):
+ archive = tmp_path / "archive.tar.gz"
+ with tarfile.open(archive, "w:gz") as output:
+ member = tarfile.TarInfo(name)
+ member.size = 1
+ output.addfile(member, io.BytesIO(b"x"))
+ with pytest.raises(ValueError):
+ execution_inputs.go_archive_records(archive, execution_inputs.file_sha256(archive))
+ assert list(tmp_path.iterdir()) == [archive]
+
+
+def test_python_receipt_measures_venv_and_lock_without_archive_claim(tmp_path, monkeypatch):
+ venv, fixture = tmp_path / "venv", tmp_path / "fixture"
+ (venv / "bin").mkdir(parents=True)
+ fixture.mkdir()
+ (venv / "bin/python").write_bytes(b"fake trusted Python, never executed")
+ (fixture / "uv.lock").write_bytes(b"frozen lock")
+ (fixture / "pyproject.toml").write_bytes(b"frozen project")
+ monkeypatch.setattr(sys, "prefix", str(venv))
+ monkeypatch.setattr(sys, "executable", str(venv / "bin/python"))
+ monkeypatch.setattr(sys, "version_info", (3, 12, 3))
+ before = execution_inputs.python_identity(venv, fixture)
+ assert "not archive-attested" in before["trust"]
+ (venv / "package.py").write_bytes(b"mutated")
+ after = execution_inputs.python_identity(venv, fixture)
+ assert before["venv_tree_sha256"] != after["venv_tree_sha256"]
+ assert before["lock_sha256"] == after["lock_sha256"]
+ monkeypatch.setattr(sys, "prefix", str(tmp_path / "ambient"))
+ with pytest.raises(RuntimeError, match="task venv"):
+ execution_inputs.python_identity(venv, fixture)
diff --git a/patches/cliproxyapi/test_isolation_probe.py b/patches/cliproxyapi/test_isolation_probe.py
new file mode 100644
index 000000000..54e5bd377
--- /dev/null
+++ b/patches/cliproxyapi/test_isolation_probe.py
@@ -0,0 +1,143 @@
+"""Consume all negative probe transports without processes, sockets or privileges."""
+
+from __future__ import annotations
+
+import errno
+import json
+from pathlib import Path
+import subprocess
+
+import pytest
+
+import isolation_probe
+from isolation import CAPABILITY_FIELDS, NAMESPACE_NAMES, keyring_identity
+
+
+def valid_kernel_proof():
+ return {
+ "outer_namespaces": {name: f"{name}:[{index + 1}]" for index, name in enumerate(NAMESPACE_NAMES)},
+ "namespaces": {name: f"{name}:[{index + 11}]" for index, name in enumerate(NAMESPACE_NAMES)},
+ "keyring_boundary": keyring_identity(),
+ "process_status": {**dict.fromkeys(CAPABILITY_FIELDS, "0"), "NoNewPrivs": "1", "Seccomp": "2"},
+ }
+
+
+def connection_outcome(monkeypatch):
+ outcome = {"errno": errno.ECONNREFUSED, "calls": []}
+
+ def connect(*_args, **_kwargs):
+ outcome["calls"].append("connection")
+ if outcome["errno"] is not None:
+ raise OSError(outcome["errno"], "mock connection error")
+ return Connection()
+
+ class Connection:
+ def request(self, *_args, **_kwargs):
+ connect()
+
+ def close(self):
+ pass
+
+ def sendall(self, _value):
+ pass
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_args):
+ pass
+
+ def child(command, **kwargs):
+ assert kwargs["close_fds"] and kwargs["capture_output"] and kwargs["timeout"] == 3
+ outcome["calls"].append("subprocess")
+ number = outcome["errno"]
+ return subprocess.CompletedProcess(
+ command, 3 if number is None else 0,
+ stdout=b"" if number is None else str(number).encode(), stderr=b"",
+ )
+
+ monkeypatch.setattr(isolation_probe.socket, "create_connection", connect)
+ monkeypatch.setattr(isolation_probe.http.client, "HTTPConnection", lambda *_args, **_kwargs: Connection())
+ monkeypatch.setattr(isolation_probe.subprocess, "run", child)
+ return outcome
+
+
[email protected]("network", ["none", "loopback"])
[email protected]("host", ["127.0.0.1", "::1"])
[email protected]("kind", ["http", "websocket", "http-proxy", "connect-proxy", "direct-ip", "subprocess"])
[email protected]("number", [
+ errno.ECONNREFUSED, errno.ENETUNREACH, errno.EHOSTUNREACH, errno.EACCES,
+ errno.EPERM, errno.EADDRNOTAVAIL, errno.ETIMEDOUT, None,
+])
+def test_actual_negative_probe_classification(connection_outcome, network, host, kind, number):
+ connection_outcome["errno"] = number
+ permitted = (
+ number in (errno.ECONNREFUSED, errno.ENETUNREACH, errno.EHOSTUNREACH, errno.EACCES, errno.EPERM)
+ or (number == errno.EADDRNOTAVAIL and network == "none" and host == "::1")
+ )
+ if permitted:
+ assert isolation_probe.probe_blocked_connection(network, host, 12345, kind) == {
+ "host": host, "kind": kind, "blocked": True, "errno": number,
+ }
+ else:
+ with pytest.raises(AssertionError):
+ isolation_probe.probe_blocked_connection(network, host, 12345, kind)
+ assert connection_outcome["calls"] == ["subprocess" if kind == "subprocess" else "connection"]
+
+
[email protected]("failure", ["missing-ipc", "same-ipc", "extra-ipc", "bad-ipc", "missing-filter",
+ "wrong-filter", "seccomp-off", "nnp-off", "capability"])
+def test_actual_preflight_main_refuses_kernel_evidence_before_probe_effect(monkeypatch, failure):
+ proof = valid_kernel_proof()
+ if failure == "missing-ipc":
+ proof["namespaces"].pop("ipc")
+ elif failure == "same-ipc":
+ proof["namespaces"]["ipc"] = proof["outer_namespaces"]["ipc"]
+ elif failure == "extra-ipc":
+ proof["namespaces"]["user"] = "user:[4]"
+ elif failure == "bad-ipc":
+ proof["namespaces"]["ipc"] = 4
+ elif failure == "missing-filter":
+ proof.pop("keyring_boundary")
+ elif failure == "wrong-filter":
+ proof["keyring_boundary"]["program_sha256"] = "0" * 64
+ else:
+ key, value = {"seccomp-off": ("Seccomp", "0"), "nnp-off": ("NoNewPrivs", "0"),
+ "capability": ("CapEff", "1")}[failure]
+ proof["process_status"][key] = value
+ monkeypatch.setattr(isolation_probe, "namespace_receipt", lambda: proof)
+ monkeypatch.setattr(isolation_probe, "probe_blocked_connection", lambda *_: pytest.fail("Socket probe reached."))
+ monkeypatch.setattr(Path, "write_bytes", lambda *_: pytest.fail("File probe reached."))
+ with pytest.raises(RuntimeError):
+ isolation_probe.main()
+
+
+def test_actual_preflight_main_emits_complete_kernel_evidence_with_all_effects_intercepted(monkeypatch, capsys):
+ proof = valid_kernel_proof()
+ proof.update(network="none", sentinel_ports=[17000, 17001], uid=501, gid=20, selected_build=None,
+ **{name: "/synthetic/" + name for name in
+ ("source", "fixture", "recipe", "toolchain", "python_env", "state", "output")})
+ effects = []
+ def write(path, contents):
+ effects.append(("write", str(path), contents))
+ if path.name == ".isolation-write-probe":
+ raise PermissionError("finite readonly mount seam")
+ assert path.name in ("writable-state-probe", "writable-output-probe")
+ return len(contents)
+ monkeypatch.setattr(isolation_probe, "namespace_receipt", lambda: proof)
+ monkeypatch.setattr(isolation_probe, "probe_blocked_connection", lambda network, host, port, kind: {
+ "network": network, "host": host, "port": port, "kind": kind, "blocked": True,
+ })
+ monkeypatch.setattr(Path, "write_bytes", write)
+ monkeypatch.setattr(Path, "unlink", lambda path: effects.append(("unlink", str(path))))
+ monkeypatch.setattr(Path, "exists", lambda _path: False)
+ monkeypatch.setattr(Path, "read_text", lambda path: "" if str(path) == "/proc/self/mountinfo" else pytest.fail("Unexpected read."))
+ monkeypatch.setattr(isolation_probe.os, "getuid", lambda: 501)
+ monkeypatch.setattr(isolation_probe.os, "getgid", lambda: 20)
+ isolation_probe.main()
+ result = json.loads(capsys.readouterr().out)
+ assert all(result[name] == proof[name] for name in valid_kernel_proof())
+ assert result["isolation_probe"] == "pass" and len(result["blocked_attempts"]) == 12
+ assert result["positive_listeners"] == [] and result["task_state_write"] and result["exclusive_output_write"]
+ assert len(effects) == 9
diff --git a/patches/cliproxyapi/test_namespace_receipts.py b/patches/cliproxyapi/test_namespace_receipts.py
new file mode 100644
index 000000000..8d7c2849d
--- /dev/null
+++ b/patches/cliproxyapi/test_namespace_receipts.py
@@ -0,0 +1,2020 @@
+"""Actual parent/supervisor consumers with all privileged/process/socket work mocked."""
+
+from __future__ import annotations
+
+import argparse
+from contextlib import ExitStack
+import ctypes
+import errno
+import hashlib
+import json
+import os
+from pathlib import Path
+import socket
+import stat
+import struct
+import subprocess
+import sys
+import tempfile
+from types import SimpleNamespace
+
+import pytest
+
+import namespace
+from budgets import PHASES
+from isolation import (
+ CAPABILITY_FIELDS, NAMESPACE_NAMES, STORAGE_ENV, StorageContext,
+ keyring_identity, require_namespaces, validate_state_root,
+)
+
+
+def kernel_proof():
+ return {
+ "outer_namespaces": {name: f"{name}:[{index + 1}]" for index, name in enumerate(NAMESPACE_NAMES)},
+ "namespaces": {name: f"{name}:[{index + 11}]" for index, name in enumerate(NAMESPACE_NAMES)},
+ "keyring_boundary": keyring_identity(),
+ "process_status": {**dict.fromkeys(CAPABILITY_FIELDS, "0000000000000000"),
+ "NoNewPrivs": "1", "Seccomp": "2"},
+ }
+
+
+def stat_fields(info, **changes):
+ """Preserve extended fields (especially st_rdev), unlike stat_result(tuple)."""
+ return SimpleNamespace(**{**{name: getattr(info, name) for name in dir(info) if name.startswith("st_")},
+ **changes})
+
+
+def envelope(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
+ storage = StorageContext.capture()
+ root = tmp_path / "allocated-task"
+ root.mkdir(mode=0o700)
+ paths = {}
+ for name in ("source", "fixture", "state", "recipe", "toolchain", "python_env"):
+ paths[name] = root / name
+ paths[name].mkdir()
+ paths["go_archive"] = root / "go.tar.gz"
+ paths["go_archive"].write_bytes(b"test-archive-not-executed")
+ for name in ("budgets", "isolation", "namespace"):
+ (paths["recipe"] / (name + ".py")).write_bytes(
+ (Path(namespace.__file__).parent / (name + ".py")).read_bytes(),
+ )
+ sentinel = tmp_path / "outside-child-state"
+ sentinel.write_bytes(b"outside-task-sentinel-private-bytes")
+ context = argparse.Namespace(
+ root=root, sentinel=sentinel, paths=paths, servers=[], candidate=None,
+ candidate_calls=0, launched=False, candidate_started=False,
+ probe_result={"isolation_probe": "pass", "original_preflight": True, **kernel_proof()},
+ probe_exit=0, probe_bytes=None, closed_channel=False, receipt="envelope.json",
+ storage_reader=namespace.sudo_storage_context,
+ system_pin=namespace.pin_system_resources,
+ )
+ monkeypatch.setattr(sys, "platform", "linux")
+ # The macOS pure runner's actual tmp_path is not a Linux /tmp path. Test
+ # the real domain validator separately; only this receipt fixture adapts it.
+ monkeypatch.setattr(namespace, "validate_temporary_root", lambda path, **kwargs: validate_state_root(path, **kwargs))
+ monkeypatch.setattr(namespace, "__file__", str(paths["recipe"] / "namespace.py"))
+ monkeypatch.setattr(os, "geteuid", lambda: 0)
+ monkeypatch.setenv("SUDO_UID", str(os.getuid() or 1000))
+ monkeypatch.setenv("SUDO_GID", str(os.getgid() or 1000))
+ # Caller provenance has dedicated consuming tests with fake proc metadata.
+ # Receipt/lifecycle cases receive the already-admitted immutable context.
+ monkeypatch.setattr(namespace, "sudo_storage_context", lambda uid, expected: storage)
+ # No sudo, mount, actual process, socket, privilege or ownership change.
+ real_stat, real_lstat, real_fstat = os.stat, os.lstat, os.fstat
+ ownership, ownership_effects, admitted_inodes = {}, [], set()
+
+ def admit_ownership_target(path):
+ assert path.is_relative_to(tmp_path) and path == path.resolve(strict=True)
+ info = real_lstat(path)
+ assert stat.S_ISDIR(info.st_mode) or stat.S_ISREG(info.st_mode)
+ admitted_inodes.add((info.st_dev, info.st_ino))
+
+ for path in (root, *paths.values(), sentinel):
+ admit_ownership_target(path)
+
+ def project(info):
+ changed = ownership.get((info.st_dev, info.st_ino))
+ return stat_fields(info, **changed) if changed is not None else info
+
+ def modeled_fchown(fd, uid, gid):
+ assert not context.candidate_started, "Ownership change after candidate execution."
+ info = real_fstat(fd)
+ key = info.st_dev, info.st_ino
+ # The four production allocation targets are the only implicit
+ # additions. Preexisting test prerequisites are admitted explicitly.
+ # No recursive scan, proc-FD lookup, or real ownership change.
+ if key not in admitted_inodes:
+ for path in (root / "receipts", root / "runs",
+ root / "receipts" / context.receipt, root / "runs" / context.receipt):
+ try:
+ target = real_lstat(path)
+ except FileNotFoundError:
+ continue
+ if (target.st_dev, target.st_ino) == key:
+ admit_ownership_target(path)
+ assert key in admitted_inodes, "Ownership effect outside task fixture."
+ current = project(info)
+ ownership[key] = {
+ "st_uid": current.st_uid if uid == -1 else uid,
+ "st_gid": current.st_gid if gid == -1 else gid,
+ }
+ ownership_effects.append((key, uid, gid))
+
+ def parent_owned(path):
+ """Explicit already-valid prerequisite, never repair by actual main."""
+ admit_ownership_target(path)
+ fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
+ try:
+ os.fchown(fd, -1, int(os.environ["SUDO_GID"]))
+ finally:
+ os.close(fd)
+
+ context.ownership = ownership
+ context.ownership_effects = ownership_effects
+ context.parent_owned = parent_owned
+ context.raw_stat, context.raw_lstat, context.raw_fstat = real_stat, real_lstat, real_fstat
+ monkeypatch.setattr(os, "stat", lambda *a, **kw: project(real_stat(*a, **kw)))
+ monkeypatch.setattr(os, "lstat", lambda *a, **kw: project(real_lstat(*a, **kw)))
+ monkeypatch.setattr(os, "fstat", lambda fd: project(real_fstat(fd)))
+ monkeypatch.setattr(os, "fchown", modeled_fchown)
+ monkeypatch.setattr(os, "chown", lambda *_args: pytest.fail("Path-based chown is forbidden."))
+ monkeypatch.setattr(namespace, "namespace_ids", lambda: kernel_proof()["outer_namespaces"])
+ monkeypatch.setattr(namespace, "pin_system_resources", lambda _stack: ([], {}))
+
+ class FakeSentinel:
+ def __init__(self, family):
+ self.port = 17000 + len(context.servers)
+ self.connections = 0
+ self.closed = False
+ self.family = family
+ context.servers.append(self)
+
+ def close(self):
+ self.closed = True
+
+ monkeypatch.setattr(namespace, "Sentinel", FakeSentinel)
+
+ def fake_run(command, **kwargs):
+ assert kwargs["close_fds"] is True
+ if command[0] == "/usr/bin/unshare":
+ context.launched = True
+ assert "--kill-child=KILL" in command and kwargs["timeout"] == PHASES[getattr(context, "phase", "test")].namespace_seconds
+ assert "-I" in command and command[command.index("-c") + 1] == namespace.CHILD_TRAMPOLINE
+ assert "--parent-namespaces" not in command and "--proof-fd" not in command
+ assert "--ipc" in command
+ control_fd = int(command[-1])
+ control = json.loads(os.pread(control_fd, 65536, 0))
+ parent_fd = control["proof_fd"]
+ expected = {parent_fd, control_fd, *(record["fd"] for record in control["handles"].values()),
+ *(item["resource"]["fd"] for item in control["system_mounts"]),
+ *(record["fd"] for record in control["bootstrap"].values())}
+ assert set(kwargs["pass_fds"]) == expected
+ assert os.fstat(parent_fd).st_nlink == 0
+ assert os.fstat(control_fd).st_nlink == 0
+ assert control["outer_namespaces"] == namespace.namespace_ids()
+ assert control["output"] == str(root / "runs" / context.receipt)
+ if getattr(context, "launch", None):
+ return context.launch(command, control, kwargs)
+ child_fd = os.dup(parent_fd)
+ context.child_fd = child_fd
+ inner = argparse.Namespace(
+ **paths, proof_fd=child_fd, command=["candidate-test"], receipt=context.receipt, phase="test",
+ outer_namespaces=control["outer_namespaces"],
+ )
+ result = namespace.run_candidate(inner, ["mock-setpriv"], {})
+ return subprocess.CompletedProcess(command, result)
+ assert "pass_fds" not in kwargs, "Candidate/probe must not inherit the supervisor channel."
+ if command[-1].endswith("isolation_probe.py"):
+ assert not context.candidate_started
+ assert kwargs["stdout"] == subprocess.PIPE and kwargs["timeout"] == 30
+ proof = context.probe_bytes if context.probe_bytes is not None else json.dumps(context.probe_result).encode()
+ return subprocess.CompletedProcess(command, context.probe_exit, stdout=proof)
+ assert command == ["mock-setpriv", "candidate-test"]
+ assert kwargs["timeout"] == PHASES["test"].candidate_seconds
+ context.candidate_calls += 1
+ context.candidate_started = True
+ with pytest.raises(OSError) as closed:
+ os.fstat(context.child_fd)
+ assert closed.value.errno == errno.EBADF
+ context.closed_channel = True
+ if context.candidate:
+ context.candidate()
+ return subprocess.CompletedProcess(command, getattr(context, "candidate_exit", 0))
+
+ monkeypatch.setattr(namespace.subprocess, "run", fake_run)
+ argv = ["namespace.py", "--root", str(root)]
+ for name, path in paths.items():
+ argv += ["--" + name.replace("_", "-"), str(path)]
+ argv += ["--phase", "test", "--network", "loopback", "--receipt", context.receipt,
+ "--caller-storage-sha256", storage.fingerprint(), "--", "candidate-test"]
+ monkeypatch.setattr(sys, "argv", argv)
+ return context
+
+
+def installed_system(envelope, tmp_path, monkeypatch):
+ """Actual finite pin owner over task files; only host metadata/open effects modeled."""
+ root = tmp_path / "installed-system-系统"
+ root.mkdir()
+ directories = [root]
+ for relative in ("usr", "usr/bin", "usr/sbin", "usr/lib", "usr/share", "usr/lib64", "dev"):
+ path = root / relative
+ path.mkdir()
+ directories.append(path)
+ devices = {}
+ for name, minor in (("null", 3), ("zero", 5)):
+ path = root / "dev" / name
+ path.write_bytes(b"regular task backing; no host device I/O")
+ info = envelope.raw_lstat(path)
+ devices[(info.st_dev, info.st_ino)] = (name, minor)
+ trusted = {(info.st_dev, info.st_ino) for info in map(envelope.raw_lstat, directories)}
+ original_open, original_stat, original_fstat = os.open, os.stat, os.fstat
+ context = SimpleNamespace(root=root, opened=[], device_opens=[], mounts=None, aliases=None,
+ fault=None, pinning=False, calls=0)
+
+ def layout(shape, overrides=None):
+ assert shape in ("directories", "relative-aliases", "absolute-aliases")
+ for name in ("bin", "sbin", "lib", "lib64"):
+ path = root / name
+ if shape == "directories":
+ path.mkdir()
+ else:
+ target = (overrides or {}).get(name, ("/" if shape == "absolute-aliases" else "") + "usr/" + name)
+ path.symlink_to(target)
+ info = envelope.raw_lstat(path)
+ trusted.add((info.st_dev, info.st_ino))
+
+ def project(info):
+ key = info.st_dev, info.st_ino
+ if key in devices:
+ name, minor = devices[key]
+ changes = {"st_mode": stat.S_IFCHR | 0o666, "st_rdev": os.makedev(1, minor), "st_uid": 0}
+ if context.fault and context.fault[0] == name:
+ changes.update(context.fault[1])
+ return stat_fields(info, **changes)
+ if key in trusted:
+ return stat_fields(info, st_uid=0)
+ return info
+
+ def opening(path, flags, *args, **kwargs):
+ is_device = bool(flags & 0o10000000)
+ if context.pinning:
+ if path == "/":
+ assert flags == os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC | os.O_NONBLOCK
+ path = root
+ if is_device:
+ assert path in ("null", "zero"), "RNG or another host device must not be acquired."
+ assert flags == 0o10000000 | os.O_NOFOLLOW | os.O_CLOEXEC
+ parent = envelope.raw_fstat(kwargs["dir_fd"])
+ actual_dev = envelope.raw_lstat(root / "dev")
+ assert (parent.st_dev, parent.st_ino) == (actual_dev.st_dev, actual_dev.st_ino)
+ context.device_opens.append(path)
+ # O_PATH is modeled only for the exact regular task backing.
+ flags = os.O_RDONLY | os.O_NOFOLLOW | os.O_CLOEXEC | os.O_NONBLOCK
+ fd = original_open(path, flags, *args, **kwargs)
+ context.opened.append(fd)
+ return fd
+ assert not is_device, "No unmodeled device acquisition."
+ return original_open(path, flags, *args, **kwargs)
+
+ def pin(stack):
+ context.calls += 1
+ context.pinning = True
+ try:
+ result = envelope.system_pin(stack)
+ finally:
+ context.pinning = False
+ context.mounts, context.aliases = result
+ return result
+
+ context.layout = layout
+ monkeypatch.setattr(namespace, "require_native_abi", lambda: None)
+ monkeypatch.setattr(namespace, "pin_system_resources", pin)
+ monkeypatch.setattr(os, "open", opening)
+ monkeypatch.setattr(os, "stat", lambda *a, **kw: project(original_stat(*a, **kw)))
+ monkeypatch.setattr(os, "fstat", lambda fd: project(original_fstat(fd)))
+ return context
+
+
[email protected]("device", ["null", "zero"])
[email protected]("failure", ["type", "major", "minor", "owner"])
+def test_actual_system_device_admission_refuses_before_parent_effects(envelope, installed_system, device, failure):
+ installed_system.layout("relative-aliases")
+ changes = {
+ "type": {"st_mode": stat.S_IFREG | 0o600},
+ "major": {"st_rdev": os.makedev(2, 3 if device == "null" else 5)},
+ "minor": {"st_rdev": os.makedev(1, 8 if device == "null" else 9)},
+ "owner": {"st_uid": os.getuid() or 1000},
+ }
+ installed_system.fault = device, changes[failure]
+ with pytest.raises((ValueError, RuntimeError), match="wrong type|device identity|trusted ownership"):
+ namespace.main()
+ assert installed_system.calls == 1 and installed_system.mounts is None
+ assert installed_system.device_opens == (["null"] if device == "null" else ["null", "zero"])
+ for fd in installed_system.opened:
+ with pytest.raises(OSError) as closed:
+ envelope.raw_fstat(fd)
+ assert closed.value.errno == errno.EBADF
+ assert not envelope.launched and not envelope.servers and envelope.candidate_calls == 0
+ assert not (envelope.root / "receipts").exists() and not (envelope.root / "runs").exists()
+
+
[email protected]("alias", ["bin", "sbin", "lib", "lib64"])
[email protected]("target", ["../outside", "/dev/urandom", "usr/lib/../lib"])
+def test_actual_system_alias_admission_refuses_before_parent_effects(envelope, installed_system, alias, target):
+ installed_system.layout("relative-aliases", {alias: target})
+ with pytest.raises(RuntimeError, match="Unexpected installed system alias"):
+ namespace.main()
+ assert installed_system.calls == 1 and installed_system.mounts is None
+ assert not installed_system.device_opens and not envelope.launched and not envelope.servers
+ for fd in installed_system.opened:
+ with pytest.raises(OSError) as closed:
+ envelope.raw_fstat(fd)
+ assert closed.value.errno == errno.EBADF
+ assert not (envelope.root / "receipts").exists() and not (envelope.root / "runs").exists()
+
+
+def read_receipt(envelope) -> dict:
+ return json.loads((envelope.root / "receipts" / envelope.receipt).read_text())
+
+
+def assert_cleanup(envelope) -> None:
+ assert envelope.servers and all(server.closed for server in envelope.servers)
+ assert not list((envelope.root / "receipts").glob("rootfs-*"))
+ assert not list((envelope.root / "receipts").glob("*.preflight"))
+ assert not list((envelope.root / "receipts").glob("*.control"))
+ assert envelope.sentinel.read_bytes() == b"outside-task-sentinel-private-bytes"
+
+
+def test_envelope_ownership_effect_is_consistent_and_preserves_raw_metadata(envelope):
+ source = envelope.paths["source"]
+ raw = envelope.raw_lstat(source)
+ gid = raw.st_gid + 1
+ assert gid > 0 and gid != raw.st_gid
+ source_fd = os.open(source, os.O_RDONLY | os.O_DIRECTORY)
+ root_fd = os.open(envelope.root, os.O_RDONLY | os.O_DIRECTORY)
+ try:
+ assert source.stat() == source.lstat() == os.fstat(source_fd) == raw
+ assert envelope.ownership == {}
+ os.fchown(source_fd, -1, gid)
+ for info in (source.stat(), source.lstat(), os.stat(source_fd),
+ os.stat("source", dir_fd=root_fd), os.lstat("source", dir_fd=root_fd),
+ os.stat("source", dir_fd=root_fd, follow_symlinks=False), os.fstat(source_fd)):
+ assert info.st_uid == raw.st_uid and info.st_gid == gid
+ for name in (name for name in dir(raw) if name.startswith("st_") and name != "st_gid"):
+ assert getattr(info, name) == getattr(raw, name)
+ assert envelope.raw_stat(source) == envelope.raw_lstat(source) == envelope.raw_fstat(source_fd) == raw
+ os.fchown(source_fd, raw.st_uid + 10000, -1)
+ assert source.stat().st_uid == raw.st_uid + 10000 and os.fstat(source_fd).st_gid == gid
+ previous = namespace.descriptor_identity(source.stat())
+ os.fchown(source_fd, -1, -1)
+ assert namespace.descriptor_identity(os.fstat(source_fd)) == previous
+ assert envelope.raw_lstat(source) == raw
+ before = dict(envelope.ownership)
+ envelope.candidate_started = True
+ with pytest.raises(AssertionError, match="after candidate"):
+ os.fchown(source_fd, -1, gid + 1)
+ assert envelope.ownership == before
+ envelope.candidate_started = False
+ finally:
+ os.close(source_fd)
+ os.close(root_fd)
+ with pytest.raises(OSError) as closed:
+ os.fstat(source_fd)
+ assert closed.value.errno == errno.EBADF
+ with pytest.raises(OSError) as closed:
+ os.fchown(source_fd, -1, gid)
+ assert closed.value.errno == errno.EBADF
+
+
+def test_envelope_ownership_follows_inode_not_names_aliases_or_reused_fds(envelope, tmp_path):
+ source = envelope.paths["source"]
+ saved = source.with_name("preserved-source")
+ raw = envelope.raw_lstat(source)
+ source_fd = os.open(source, os.O_RDONLY | os.O_DIRECTORY)
+ root_fd = os.open(envelope.root, os.O_RDONLY | os.O_DIRECTORY)
+ try:
+ os.fchown(source_fd, -1, raw.st_gid + 1)
+ source.rename(saved)
+ source.mkdir()
+ replacement = envelope.raw_lstat(source)
+ assert replacement.st_ino != raw.st_ino
+ assert source.stat() == replacement
+ assert saved.stat().st_gid == os.fstat(source_fd).st_gid == raw.st_gid + 1
+ alias = envelope.root / "source-alias"
+ alias.symlink_to(saved)
+ alias_raw = envelope.raw_lstat(alias)
+ assert alias.lstat() == os.lstat(alias) == alias_raw
+ assert os.stat(alias, follow_symlinks=False) == alias_raw
+ assert os.stat("source-alias", dir_fd=root_fd, follow_symlinks=False) == alias_raw
+ assert alias.stat().st_gid == os.stat("source-alias", dir_fd=root_fd).st_gid == raw.st_gid + 1
+ assert envelope.raw_lstat(saved).st_gid == raw.st_gid
+ with pytest.raises(FileNotFoundError):
+ os.stat("absent", dir_fd=root_fd, follow_symlinks=False)
+ with pytest.raises(FileNotFoundError):
+ os.lstat("absent", dir_fd=root_fd)
+ replacement_fd = os.open(source, os.O_RDONLY | os.O_DIRECTORY)
+ try:
+ os.dup2(replacement_fd, source_fd)
+ assert os.fstat(source_fd) == replacement
+ assert saved.stat().st_gid == raw.st_gid + 1
+ finally:
+ os.close(replacement_fd)
+ # An unnamed file is not an admitted linked fixture object, even when
+ # its numeric FD happens to be one that previously carried an effect.
+ with tempfile.TemporaryFile(dir=tmp_path) as unnamed:
+ before = dict(envelope.ownership)
+ with pytest.raises(AssertionError, match="outside task fixture"):
+ os.fchown(unnamed.fileno(), -1, raw.st_gid + 2)
+ assert envelope.ownership == before
+ finally:
+ os.close(source_fd)
+ os.close(root_fd)
+
+
[email protected]("field", ["dev", "ino", "mode", "uid", "gid", "rdev"])
+def test_actual_parent_rejects_single_input_identity_drift_before_allocation(envelope, monkeypatch, field):
+ source = envelope.paths["source"]
+ before = namespace.descriptor_identity(source.lstat())
+ raw = envelope.raw_lstat(source)
+ original_open, original_fstat = os.open, os.fstat
+ reached = []
+
+ def opening(path, *args, **kwargs):
+ fd = original_open(path, *args, **kwargs)
+ if path == "source":
+ reached.append(fd)
+ if field in ("uid", "gid"):
+ os.fchown(fd, before["uid"] + 1 if field == "uid" else -1,
+ before["gid"] + 1 if field == "gid" else -1)
+ return fd
+
+ def changed(fd):
+ info = original_fstat(fd)
+ if fd in reached and field not in ("uid", "gid"):
+ return stat_fields(info, **{"st_" + field: before[field] + (0o010 if field == "mode" else 1)})
+ return info
+
+ monkeypatch.setattr(os, "open", opening)
+ monkeypatch.setattr(os, "fstat", changed)
+ monkeypatch.setattr(namespace, "open_receipts", lambda *_: pytest.fail("Allocation after input identity drift."))
+ with pytest.raises(ValueError, match="Pinned resource changed after admission"):
+ namespace.main()
+ assert len(reached) == 1 and not envelope.launched and not envelope.servers
+ assert not (envelope.root / "receipts").exists() and not (envelope.root / "runs").exists()
+ assert envelope.raw_lstat(source) == raw
+ for fd in reached:
+ with pytest.raises(OSError):
+ os.fstat(fd)
+ if field in ("uid", "gid"):
+ after = namespace.descriptor_identity(source.lstat())
+ assert {name for name in before if after[name] != before[name]} == {field}
+
+
[email protected]("artifact", ["symlinks", "hardlinks", "directories", "fifos", "forged-files"])
+def test_parent_never_consumes_child_receipt_or_probe_paths(envelope, artifact: str) -> None:
+ def candidate():
+ for name in (envelope.receipt, envelope.receipt + ".probe.json"):
+ path = envelope.paths["state"] / name
+ if artifact == "symlinks":
+ path.symlink_to(envelope.sentinel)
+ elif artifact == "hardlinks":
+ os.link(envelope.sentinel, path)
+ elif artifact == "directories":
+ path.mkdir()
+ elif artifact == "fifos":
+ os.mkfifo(path)
+ else:
+ path.write_text('{"isolation_probe":"pass","forged":true}')
+
+ envelope.candidate = candidate
+ with pytest.raises(SystemExit) as completed:
+ namespace.main()
+ assert completed.value.code == 0
+ receipt = read_receipt(envelope)
+ assert receipt["status"] == "passed" and receipt["probe"] == envelope.probe_result
+ assert envelope.closed_channel
+ assert "outside-task-sentinel-private-bytes" not in json.dumps(receipt)
+ assert "forged" not in json.dumps(receipt)
+ assert_cleanup(envelope)
+
+
+def test_later_probe_tampering_cannot_replace_preflight(envelope) -> None:
+ def candidate():
+ envelope.probe_result["original_preflight"] = False
+ envelope.probe_result["forged"] = True
+ (envelope.paths["state"] / (envelope.receipt + ".probe.json")).write_text(
+ json.dumps(envelope.probe_result),
+ )
+ # Candidate stdout is not the preflight channel.
+ print('{"isolation_probe":"pass","forged":true}')
+
+ envelope.candidate = candidate
+ with pytest.raises(SystemExit):
+ namespace.main()
+ receipt = read_receipt(envelope)
+ assert receipt["probe"] == {"isolation_probe": "pass", "original_preflight": True, **kernel_proof()}
+ assert receipt["preflight_custody"] == "unnamed-supervisor-fd-closed-before-candidate"
+ assert_cleanup(envelope)
+
+
[email protected]("kind", ["regular", "symlink", "hardlink", "directory", "fifo"])
+def test_preexisting_terminal_receipt_collision_preserves_evidence(envelope, kind: str) -> None:
+ directory = envelope.root / "receipts"
+ directory.mkdir(mode=0o750)
+ directory.chmod(0o750)
+ envelope.parent_owned(directory)
+ path = directory / envelope.receipt
+ if kind == "regular":
+ path.write_bytes(b"previous evidence")
+ elif kind == "symlink":
+ path.symlink_to(envelope.sentinel)
+ elif kind == "hardlink":
+ os.link(envelope.sentinel, path)
+ elif kind == "directory":
+ path.mkdir()
+ else:
+ os.mkfifo(path)
+ before = path.lstat()
+ with pytest.raises(FileExistsError):
+ namespace.main()
+ assert path.lstat() == before
+ assert not envelope.launched and not envelope.servers
+ if kind == "regular":
+ assert path.read_bytes() == b"previous evidence"
+ assert envelope.sentinel.read_bytes() == b"outside-task-sentinel-private-bytes"
+
+
+def test_preexisting_receipt_directory_symlink_is_not_followed(envelope) -> None:
+ (envelope.root / "receipts").symlink_to(envelope.paths["state"], target_is_directory=True)
+ with pytest.raises(OSError):
+ namespace.main()
+ assert not envelope.launched
+ assert list(envelope.paths["state"].iterdir()) == []
+
+
+def test_preexisting_probe_channel_collision_is_not_unlinked(envelope) -> None:
+ directory = envelope.root / "receipts"
+ directory.mkdir(mode=0o750)
+ directory.chmod(0o750)
+ envelope.parent_owned(directory)
+ path = directory / (envelope.receipt + ".preflight")
+ path.symlink_to(envelope.sentinel)
+ before = path.lstat()
+ with pytest.raises(FileExistsError):
+ namespace.main()
+ assert path.lstat() == before and not envelope.launched
+ assert envelope.sentinel.read_bytes() == b"outside-task-sentinel-private-bytes"
+
+
+def test_preexisting_writable_receipt_directory_is_rejected(envelope) -> None:
+ directory = envelope.root / "receipts"
+ directory.mkdir()
+ directory.chmod(0o770)
+ envelope.parent_owned(directory)
+ with pytest.raises(RuntimeError, match="ownership or permissions"):
+ namespace.main()
+ assert not envelope.launched and list(directory.iterdir()) == []
+ assert directory.stat().st_mode & 0o777 == 0o770
+
+
[email protected]("collection", ["receipts", "runs"])
[email protected]("failure", ["uid", "gid", "mode", "alias"])
+def test_preexisting_collection_refuses_its_own_defect_without_ownership_repair(envelope, collection, failure):
+ directory = envelope.root / collection
+ directory.mkdir(mode=0o750)
+ directory.chmod(0o750)
+ envelope.parent_owned(directory)
+ fd = os.open(directory, os.O_RDONLY | os.O_DIRECTORY)
+ try:
+ if failure in ("uid", "gid"):
+ info = os.fstat(fd)
+ os.fchown(fd, info.st_uid + 10000 if failure == "uid" else -1,
+ info.st_gid + 1 if failure == "gid" else -1)
+ elif failure == "mode":
+ directory.chmod(0o770)
+ else:
+ preserved = directory.with_name(collection + "-preserved")
+ directory.rename(preserved)
+ directory.symlink_to(preserved, target_is_directory=True)
+ key = envelope.raw_fstat(fd).st_dev, envelope.raw_fstat(fd).st_ino
+ before = namespace.descriptor_identity(os.fstat(fd))
+ effects = list(envelope.ownership_effects)
+ if failure == "alias" and collection == "runs":
+ with pytest.raises(ValueError, match="Environment directory escapes"):
+ namespace.main()
+ assert not (envelope.root / "receipts").exists()
+ elif failure == "alias":
+ with pytest.raises(OSError):
+ namespace.main()
+ else:
+ message = "ownership or permissions" if collection == "receipts" else "Run collection"
+ with pytest.raises(RuntimeError, match=message):
+ namespace.main()
+ assert namespace.descriptor_identity(os.fstat(fd)) == before
+ assert [effect for effect in envelope.ownership_effects if effect[0] == key] == [
+ effect for effect in effects if effect[0] == key
+ ]
+ assert not envelope.launched and not envelope.servers
+ if collection == "runs" and failure != "alias":
+ assert read_receipt(envelope)["status"] == "failed"
+ finally:
+ os.close(fd)
+
+
[email protected]("failure", ["candidate-exit", "timeout", "probe-exit", "malformed-probe"])
+def test_parent_failure_and_timeout_keep_receipt_and_cleanup(envelope, failure: str) -> None:
+ if failure == "candidate-exit":
+ envelope.candidate_exit = 7
+ elif failure == "timeout":
+ def timeout():
+ raise subprocess.TimeoutExpired("mock-candidate-already-killed-and-waited", PHASES["test"].candidate_seconds)
+ envelope.candidate = timeout
+ elif failure == "probe-exit":
+ envelope.probe_exit = 2
+ else:
+ envelope.probe_bytes = b"not a preflight JSON"
+ with pytest.raises((RuntimeError, subprocess.TimeoutExpired, ValueError)):
+ namespace.main()
+ receipt = read_receipt(envelope)
+ assert receipt["status"] == "failed" and receipt["temporary_rootfs_removed"]
+ assert receipt["cleanup_errors"] == []
+ if failure in ("probe-exit", "malformed-probe"):
+ assert envelope.candidate_calls == 0 and receipt["preflight"] == "missing-or-invalid"
+ else:
+ assert receipt["preflight"] == "passed" and receipt["launcher_reaped"]
+ assert envelope.closed_channel
+ if failure == "timeout":
+ assert receipt["exit_code"] == 124 and receipt["failure"] is None
+ assert_cleanup(envelope)
+
+
+def test_partial_sentinel_setup_failure_cleans_first_listener(envelope, monkeypatch) -> None:
+ original = namespace.Sentinel
+
+ def second_fails(family):
+ if family == socket.AF_INET6:
+ raise OSError("mock setup failure")
+ return original(family)
+
+ monkeypatch.setattr(namespace, "Sentinel", second_fails)
+ with pytest.raises(OSError, match="mock setup failure"):
+ namespace.main()
+ assert read_receipt(envelope)["status"] == "failed"
+ assert not envelope.launched
+ assert_cleanup(envelope)
+
+
+def test_cleanup_failure_is_never_reported_as_pass(envelope, monkeypatch) -> None:
+ original = namespace.Sentinel.close
+
+ def fails_after_close(server):
+ original(server)
+ if server.family == socket.AF_INET:
+ raise RuntimeError("mock cleanup failure")
+
+ monkeypatch.setattr(namespace.Sentinel, "close", fails_after_close)
+ with pytest.raises(RuntimeError, match="acceptance failed"):
+ namespace.main()
+ receipt = read_receipt(envelope)
+ assert receipt["status"] == "failed" and receipt["cleanup_errors"] == ["RuntimeError"]
+ assert_cleanup(envelope)
+
+
[email protected]("mapping", ["{}", '{"mnt":"fake"}',
+ '{"mnt":"mnt:[1]","net":"net:[2]","pid":"pid:[3]"}'])
+def test_public_cli_cannot_select_private_reentry(envelope, monkeypatch, mapping):
+ argv = list(sys.argv)
+ index = argv.index("--")
+ argv[index:index] = ["--parent-namespaces", mapping, "--proof-fd", "7"]
+ monkeypatch.setattr(sys, "argv", argv)
+ with pytest.raises(SystemExit) as refused:
+ namespace.main()
+ assert refused.value.code == 2
+ assert not envelope.launched and not envelope.servers
+ assert not (envelope.root / "receipts").exists()
+ assert not list(envelope.root.glob("rootfs-*"))
+
+
+ {}, {"net": "net:[1]"}, {"net": "net:[1]", "mnt": "mnt:[2]"},
+ {"net": "net:[1]", "mnt": "mnt:[2]", "pid": "pid:[3]"},
+])
+def test_all_kernel_identities_required_before_first_mutation(monkeypatch, outer):
+ monkeypatch.setattr(namespace, "namespace_ids", lambda: {"net": "net:[1]", "mnt": "mnt:[2]", "pid": "pid:[3]"})
+ monkeypatch.setattr(namespace, "run", lambda *_: pytest.fail("Kernel mutation reached before namespace proof."))
+ with pytest.raises(RuntimeError, match="outside new"):
+ namespace.inside(SimpleNamespace(), outer)
+
+
+def test_private_handoff_is_closed_before_inside(tmp_path, monkeypatch):
+ import builtins
+
+ with tempfile.TemporaryFile(dir=tmp_path) as control:
+ values = {name: str(tmp_path / name) for name in (
+ "root", "rootfs", "source", "fixture", "state", "recipe", "toolchain",
+ "python_env", "go_archive", "output",
+ )}
+ outer = kernel_proof()["outer_namespaces"]
+ values.update(build=None, outer_namespaces=outer)
+ fd = os.dup(control.fileno())
+ original = os.fstat
+
+ def root_owned(number):
+ return stat_fields(original(number), st_uid=0) if number == fd else original(number)
+
+ monkeypatch.setattr(os, "fstat", root_owned)
+
+ def consume(body):
+ with pytest.raises(OSError):
+ os.fstat(fd)
+ for record in values["bootstrap"].values():
+ with pytest.raises(OSError):
+ os.fstat(record["fd"])
+ namespace.child_from_control(body)
+
+ observed = []
+ monkeypatch.setattr(namespace, "inside", lambda args, ids: observed.append((args.root, ids)))
+ monkeypatch.setattr(builtins, "_bootstrap_consumer", consume, raising=False)
+ with ExitStack() as stack:
+ bootstrap = {}
+ for name in ("budgets", "isolation", "namespace"):
+ path = tmp_path / (name + ".py")
+ path.write_text("from builtins import _bootstrap_consumer as child_from_control\n"
+ if name == "namespace" else "# finite inspected test module\n")
+ record = namespace.pin_beneath(
+ stack, _directory_fd(stack, tmp_path), Path(path.name), kind="file",
+ )
+ bootstrap[name] = {"fd": os.dup(record["fd"]), "identity": record["identity"],
+ "sha256": hashlib.sha256(path.read_bytes()).hexdigest()}
+ values["bootstrap"] = bootstrap
+ control.write(json.dumps(values).encode())
+ control.flush()
+ control.seek(0)
+ monkeypatch.setattr(sys, "argv", ["-c", str(fd)])
+ for name in bootstrap:
+ monkeypatch.setitem(sys.modules, name, sys.modules[name])
+ exec(compile(namespace.CHILD_TRAMPOLINE, "<actual fixed trampoline>", "exec"), {})
+ assert observed == [(Path(values["root"]), outer)]
+
+
+def test_named_handoff_is_rejected_before_inside(tmp_path, monkeypatch):
+ path = tmp_path / "caller-controlled"
+ path.write_bytes(b"{}")
+ monkeypatch.setattr(namespace, "inside", lambda *_: pytest.fail("Untrusted handoff reached setup."))
+ fd = os.open(path, os.O_RDONLY)
+ monkeypatch.setattr(sys, "argv", ["-c", str(fd)])
+ closures = []
+ monkeypatch.setattr(os, "closerange", lambda start, end: closures.append((start, end)))
+ with pytest.raises(RuntimeError, match="parent handoff"):
+ exec(compile(namespace.CHILD_TRAMPOLINE, "<actual fixed trampoline>", "exec"), {})
+ with pytest.raises(OSError):
+ os.fstat(fd)
+ assert path.read_bytes() == b"{}"
+ assert closures and closures[0][0] == 3
+
+
+def test_parent_deadline_failure_has_receipt_and_cleanup(envelope, monkeypatch):
+ def deadline(command, **kwargs):
+ assert command[0] == "/usr/bin/unshare"
+ assert kwargs["timeout"] == PHASES["test"].namespace_seconds
+ raise subprocess.TimeoutExpired(command, kwargs["timeout"])
+
+ monkeypatch.setattr(namespace.subprocess, "run", deadline)
+ with pytest.raises(subprocess.TimeoutExpired):
+ namespace.main()
+ receipt = read_receipt(envelope)
+ assert receipt["status"] == "failed" and receipt["failure"] == "TimeoutExpired"
+ assert receipt["launcher_reaped"] and receipt["budget"] == PHASES["test"].receipt()
+ assert_cleanup(envelope)
+
+
+def test_orphan_output_collision_preserves_all_previous_files(envelope):
+ runs = envelope.root / "runs"
+ runs.mkdir(mode=0o750)
+ runs.chmod(0o750)
+ envelope.parent_owned(runs)
+ output = runs / envelope.receipt
+ output.mkdir()
+ prior = output / "prior-evidence"
+ prior.write_bytes(b"do not overwrite")
+ with pytest.raises(FileExistsError):
+ namespace.main()
+ assert not envelope.launched and not envelope.servers
+ assert prior.read_bytes() == b"do not overwrite"
+ assert read_receipt(envelope)["status"] == "failed"
+
+
[email protected]("kind", ["symlink", "hardlink", "fifo", "failed", "wrong-phase", "wrong-output"])
+def test_prior_build_requires_real_matching_parent_receipt(envelope, kind):
+ directory = envelope.root / "receipts"
+ directory.mkdir(mode=0o750)
+ directory.chmod(0o750)
+ envelope.parent_owned(directory)
+ root = envelope.root / "runs" / "build-old.json"
+ root.mkdir(parents=True)
+ path = directory / root.name
+ if kind == "symlink":
+ path.symlink_to(envelope.sentinel)
+ elif kind == "hardlink":
+ os.link(envelope.sentinel, path)
+ elif kind == "fifo":
+ os.mkfifo(path)
+ else:
+ value = {"status": "failed" if kind == "failed" else "passed",
+ "phase": "test" if kind == "wrong-phase" else "build",
+ "output": str(envelope.paths["state"] if kind == "wrong-output" else root)}
+ path.write_text(json.dumps(value))
+ path.chmod(0o640)
+ if kind in ("failed", "wrong-phase", "wrong-output"):
+ envelope.parent_owned(path)
+ # Only the task-owned parent receipt directory is opened; no candidate
+ # artifact consumer or privileged operation is involved.
+ fd = os.open(directory, os.O_RDONLY | os.O_DIRECTORY)
+ try:
+ with pytest.raises((RuntimeError, OSError)):
+ namespace.selected_build_receipt(SimpleNamespace(build=root), fd)
+ finally:
+ os.close(fd)
+ assert envelope.sentinel.read_bytes() == b"outside-task-sentinel-private-bytes"
+
+
+def test_phase_network_mismatch_refuses_before_parent_setup(envelope, monkeypatch):
+ argv = list(sys.argv)
+ argv[argv.index("--phase") + 1] = "build"
+ monkeypatch.setattr(sys, "argv", argv)
+ with pytest.raises(ValueError, match="network=none"):
+ namespace.main()
+ assert not envelope.servers and not (envelope.root / "receipts").exists()
+
+
+def _directory_fd(stack, path):
+ fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY)
+ stack.callback(os.close, fd)
+ return fd
+
+
+def private_setup(tmp_path, monkeypatch):
+ """Task-only directory replacement models views; it is NOT a mount proof."""
+ root = tmp_path / "task"
+ root.mkdir(mode=0o700)
+ paths = {}
+ for name in ("source", "fixture", "state", "recipe", "toolchain", "python_env", "output", "build",
+ "control", "runs"):
+ paths[name] = root / name
+ paths[name].mkdir(mode=0o750)
+ paths[name].chmod(0o750)
+ paths["rootfs"] = paths["control"] / "rootfs-test"
+ paths["rootfs"].mkdir(mode=0o700)
+ paths["go_archive"] = root / "go.tar.gz"
+ paths["go_archive"].write_bytes(b"not a compiler")
+ outer, inner = kernel_proof()["outer_namespaces"], kernel_proof()["namespaces"]
+ calls, closed = [], []
+ descriptors = []
+ for name, path in {"root": root, **paths}.items():
+ fd = os.open(path, os.O_RDONLY | (0 if name == "go_archive" else os.O_DIRECTORY))
+ descriptors.append((name, namespace.retained_handle(fd, "file" if name == "go_archive" else "directory")))
+ with tempfile.TemporaryFile(dir=tmp_path) as proof:
+ args = argparse.Namespace(
+ **paths, root=root, network="loopback", phase="wire", receipt="test-wire.json",
+ selected_build={"output": str(paths["build"])}, uid=os.getuid(), gid=os.getgid(), proof_fd=os.dup(proof.fileno()),
+ sentinel_ports=[17000, 17001], command=["never-executed"],
+ storage_context=StorageContext.capture().record(), handles=dict(descriptors),
+ system_mounts=[], system_aliases={},
+ )
+ saved = paths["rootfs"].with_name("preserved-underlay")
+ context = SimpleNamespace(args=args, paths=paths, calls=calls, closed=closed, outer=outer, inner=inner,
+ saved=saved, descriptors=descriptors, bind_observer=None)
+
+ def mount(source, target, filesystem, flags, data=None):
+ calls.append(("mount", source, target, filesystem, flags, data))
+ if filesystem == "tmpfs":
+ paths["rootfs"].rename(saved)
+ paths["rootfs"].mkdir(mode=0o755)
+ paths["rootfs"].chmod(0o755)
+ if flags == namespace.MS_BIND:
+ marker = paths["rootfs"] / "run/avibe-engine-test-isolation.json"
+ assert marker.exists() and marker.read_bytes() == b""
+ if context.bind_observer:
+ context.bind_observer(source, target)
+
+ monkeypatch.setattr(namespace, "namespace_ids", lambda: inner)
+ monkeypatch.setattr(namespace, "run", lambda *command: calls.append(command))
+ monkeypatch.setattr(namespace, "linux_mount", mount)
+ monkeypatch.setattr(namespace, "install_keyring_boundary", lambda: calls.append(("filter",)) or keyring_identity())
+ monkeypatch.setattr(namespace.subprocess, "check_output", lambda _command, **_kw: b'[{"ifname":"lo"}]')
+ monkeypatch.setattr(os, "fchdir", lambda fd: calls.append(("fchdir", namespace.descriptor_identity(os.fstat(fd)))))
+ monkeypatch.setattr(os, "chroot", lambda path: calls.append(("mock-chroot", str(path))))
+ monkeypatch.setattr(os, "chdir", lambda path: calls.append(("chdir", path)))
+ monkeypatch.setattr(os, "closerange", lambda first, last: closed.append((first, last)))
+ monkeypatch.setattr(os, "set_inheritable", lambda fd, value: calls.append(("inherit", fd, value)))
+ monkeypatch.setattr(namespace.resource, "getrlimit", lambda _name: (4096, 4096))
+ yield context
+ for fd in {args.proof_fd, *(record["fd"] for _, record in descriptors)}:
+ try:
+ os.close(fd)
+ except OSError as exc:
+ assert exc.errno == errno.EBADF
+
+
+def test_actual_private_setup_keeps_prior_build_readonly_and_only_current_output_writable(private_setup, monkeypatch):
+ state = private_setup
+ args, paths, calls, closed = state.args, state.paths, state.calls, state.closed
+
+ def candidate(actual_args, drop, env):
+ assert actual_args is args and closed == [(3, args.proof_fd), (args.proof_fd + 1, 4096)]
+ assert "--clear-groups" in drop and "--no-new-privs" in drop
+ assert all(flag in drop for flag in ("--bounding-set=-all", "--inh-caps=-all", "--ambient-caps=-all"))
+ assert env["HOME"] == str(paths["output"] / "home")
+ marker = json.loads((paths["rootfs"] / "run/avibe-engine-test-isolation.json").read_text())
+ assert marker["outer_namespaces"] == state.outer and marker["namespaces"] == state.inner
+ assert marker["keyring_boundary"] == keyring_identity()
+ assert marker["selected_build"] == args.selected_build and marker["phase"] == "wire"
+ assert marker["budget"] == PHASES["wire"].receipt()
+ for _, record in state.descriptors:
+ with pytest.raises(OSError):
+ os.fstat(record["fd"])
+ os.close(args.proof_fd)
+ return 0
+
+ monkeypatch.setattr(namespace, "run_candidate", candidate)
+ with pytest.raises(SystemExit) as finished:
+ namespace.inside(args, state.outer)
+ assert finished.value.code == 0
+ assert calls[0] == ("mount", None, "/", None, namespace.MS_REC | namespace.MS_PRIVATE, None)
+ for name in ("source", "fixture", "recipe", "toolchain", "python_env", "go_archive", "build"):
+ bind = next(call for call in calls if call[:2] == ("mount", namespace.fd_path(args.handles[name]["fd"])))
+ assert ("mount", None, bind[2], None, namespace.MS_BIND | namespace.MS_REMOUNT |
+ namespace.MS_NOSUID | namespace.MS_NODEV | namespace.MS_RDONLY, None) in calls
+ for name in ("state", "output"):
+ bind = next(call for call in calls if call[:2] == ("mount", namespace.fd_path(args.handles[name]["fd"])))
+ assert ("mount", None, bind[2], None, namespace.MS_BIND | namespace.MS_REMOUNT |
+ namespace.MS_NOSUID | namespace.MS_NODEV, None) in calls
+ assert calls.index(("filter",)) < next(i for i, call in enumerate(calls)
+ if call[0] == "mount" and call[4] == 39)
+ view = next(call[1] for call in calls if call[0] == "fchdir")
+ assert view["ino"] == paths["rootfs"].stat().st_ino != state.saved.stat().st_ino
+ assert ("mock-chroot", ".") in calls and ("chdir", "/") in calls
+
+
[email protected]("variable", STORAGE_ENV)
[email protected]("role", ["root", "state", "output", "generated-cache"])
+def test_namespace_configured_storage_refuses_before_first_parent_write(envelope, monkeypatch, variable, role):
+ boundary = {
+ "root": envelope.root, "state": envelope.paths["state"],
+ "output": envelope.root / "runs" / envelope.receipt,
+ "generated-cache": envelope.paths["state"] / "cache",
+ }[role]
+ context = StorageContext.capture(environment={variable: str(boundary)})
+ monkeypatch.setattr(namespace, "sudo_storage_context", lambda *_: context)
+ monkeypatch.setattr(namespace, "open_receipts", lambda *_: pytest.fail("First parent write reached."))
+ with pytest.raises(ValueError):
+ namespace.main()
+ assert not envelope.launched and not envelope.servers
+ assert not (envelope.root / "receipts").exists()
+ assert not (envelope.root / "runs").exists()
+
+
+def sudo_process(tmp_path, monkeypatch):
+ """Real bounded proc-file reader, but every proc/identity surface is fake."""
+ import isolation
+
+ caller_home, root_home = tmp_path / "caller-home", tmp_path / "root-home"
+ caller_home.mkdir()
+ root_home.mkdir()
+ uid = os.getuid()
+ monkeypatch.setattr(isolation.pwd, "getpwuid", lambda number: SimpleNamespace(
+ pw_dir=str(caller_home if number == uid else root_home),
+ ))
+ selected = {name: str(tmp_path / ("original-" + name)) for name in STORAGE_ENV}
+ for name, value in selected.items():
+ monkeypatch.setenv(name, value)
+ monkeypatch.delenv("SUDO_UID", raising=False)
+ monkeypatch.delenv("SUDO_GID", raising=False)
+ context = StorageContext.capture()
+ proc = tmp_path / "fake-proc"
+ proc.mkdir()
+ executable = tmp_path / "fake-sudo"
+ executable.write_bytes(b"never executed")
+ (proc / "exe").symlink_to(executable)
+ values = ["S", *(["0"] * 18), "123456"]
+ (proc / "stat").write_text("765432 (sudo) " + " ".join(values))
+ raw = b"\0".join(name.encode() + b"=" + value.encode() for name, value in selected.items()) + b"\0"
+ (proc / "environ").write_bytes(raw)
+ real_open, real_stat = os.open, os.stat
+ sudo_info = list(executable.stat())
+ sudo_info[4] = 0
+
+ def open_proc(path, flags, *args, **kwargs):
+ return real_open(proc if path == "/proc/765432" else path, flags, *args, **kwargs)
+
+ def stat_sudo(path, *args, **kwargs):
+ return os.stat_result(sudo_info) if path == "/usr/bin/sudo" else real_stat(path, *args, **kwargs)
+
+ monkeypatch.setattr(os, "getppid", lambda: 765432)
+ monkeypatch.setattr(os, "open", open_proc)
+ monkeypatch.setattr(os, "stat", stat_sudo)
+ return SimpleNamespace(uid=uid, proc=proc, context=context, selected=selected, raw=raw,
+ sudo_info=sudo_info, root_home=root_home)
+
+
+def test_parent_uses_original_sudo_environment_not_its_own_sanitized_home(sudo_process, monkeypatch):
+ original = sudo_process
+ for name in STORAGE_ENV:
+ monkeypatch.delenv(name, raising=False)
+ monkeypatch.setenv("HOME", str(original.root_home))
+ context = namespace.sudo_storage_context(original.uid, original.context.fingerprint())
+ assert context.uid == original.uid
+ for name, path in original.selected.items():
+ target = Path(path) / (".avibe" if name == "HOME" else "task")
+ with pytest.raises(ValueError):
+ context.validate(target)
+ with pytest.raises(ValueError):
+ context.validate(original.root_home / ".codex")
+
+
[email protected]("failure", [
+ "missing-environment", "sanitized-environment", "forged-digest", "invalid-digest",
+ "different-executable", "writable-executable", "oversized-environment",
+ "changed-parent", "duplicate-storage-key", "invalid-encoding",
+])
+def test_sudo_context_loss_or_forgery_fails_closed(sudo_process, monkeypatch, failure):
+ original = sudo_process
+ expected = original.context.fingerprint()
+ if failure == "missing-environment":
+ (original.proc / "environ").unlink()
+ elif failure == "sanitized-environment":
+ (original.proc / "environ").write_bytes(b"HOME=/root\0")
+ elif failure == "forged-digest":
+ expected = "0" * 64
+ elif failure == "invalid-digest":
+ expected = '{"protected":[]}'
+ elif failure == "different-executable":
+ original.sudo_info[1] += 1
+ elif failure == "writable-executable":
+ original.sudo_info[0] |= 0o002
+ elif failure == "oversized-environment":
+ (original.proc / "environ").write_bytes(b"x" * (1024 * 1024 + 1))
+ elif failure == "changed-parent":
+ parents = iter((765432, 765433))
+ monkeypatch.setattr(os, "getppid", lambda: next(parents))
+ elif failure == "duplicate-storage-key":
+ (original.proc / "environ").write_bytes(original.raw + b"HOME=/different\0")
+ else:
+ (original.proc / "environ").write_bytes(b"HOME=/invalid-\xff\0")
+ with pytest.raises((ValueError, RuntimeError, OSError)):
+ namespace.sudo_storage_context(original.uid, expected)
+
+
+def test_changed_sudo_environment_during_read_fails(sudo_process, monkeypatch):
+ read = namespace._proc_field
+ reads = 0
+
+ def changing(fd, name, limit):
+ nonlocal reads
+ value = read(fd, name, limit)
+ if name == "environ":
+ reads += 1
+ if reads == 2:
+ return b"HOME=/changed\0"
+ return value
+
+ monkeypatch.setattr(namespace, "_proc_field", changing)
+ with pytest.raises(RuntimeError, match="lost or changed"):
+ namespace.sudo_storage_context(sudo_process.uid, sudo_process.context.fingerprint())
+
+
[email protected]("mutation", ["missing-digest", "claimed-root-map", "allow-flag"])
+def test_public_cli_has_no_protection_bypass(envelope, monkeypatch, mutation):
+ argv = list(sys.argv)
+ if mutation == "missing-digest":
+ index = argv.index("--caller-storage-sha256")
+ del argv[index:index + 2]
+ else:
+ index = argv.index("--")
+ argv[index:index] = (["--storage-context", '{"protected":[]}'] if mutation == "claimed-root-map"
+ else ["--allow-task-root", str(envelope.root)])
+ monkeypatch.setattr(sys, "argv", argv)
+ with pytest.raises(SystemExit) as refused:
+ namespace.main()
+ assert refused.value.code == 2
+ assert not envelope.launched and not (envelope.root / "receipts").exists()
+
+
+def test_documented_caller_binds_original_context_and_actual_parent_admission(
+ envelope, sudo_process, monkeypatch):
+ # Execute the maintained caller itself. Only sudo/process/privilege metadata
+ # are simulated; the parent's storage and path admission remain real.
+ readme = (Path(__file__).parent / "README.md").read_text()
+ caller = readme.split("run_phase() {", 1)[1].split("<<'PY'\n", 1)[1].split("\nPY\n}", 1)[0]
+ monkeypatch.setattr(namespace, "sudo_storage_context", envelope.storage_reader)
+ monkeypatch.setattr(sys, "argv", [
+ "-", str(envelope.root), str(envelope.paths["fixture"]), "test", "loopback", envelope.receipt, "",
+ ])
+ # The README uses this documented archive layout.
+ (envelope.root / "downloads").mkdir()
+ (envelope.root / "downloads/go.tar.gz").write_bytes(b"not executed")
+ (envelope.root / "venv").mkdir()
+ reached = []
+
+ class BeforeFirstWrite(Exception):
+ pass
+
+ def first_write(args, _stack, root_fd):
+ context = StorageContext.from_parent(args.storage_context)
+ assert set(sudo_process.context.protected).issubset(context.protected)
+ assert args.root == envelope.root
+ assert os.fstat(root_fd).st_ino == envelope.root.stat().st_ino
+ reached.append(context.fingerprint())
+ raise BeforeFirstWrite
+
+ def sudo(command, **kwargs):
+ assert command[:6] == ["/usr/bin/sudo", "-n", "/usr/bin/python3", "-I", "-B", "-c"]
+ assert command[7] == str(envelope.paths["recipe"])
+ assert kwargs["timeout"] == PHASES["test"].driver_seconds and kwargs["close_fds"]
+ assert command[command.index("--caller-storage-sha256") + 1] == sudo_process.context.fingerprint()
+ # Mimic sudo env_reset after the original executable's environment was
+ # captured in fake proc. No actual sudo or subordinate process runs.
+ for name in STORAGE_ENV:
+ monkeypatch.delenv(name, raising=False)
+ monkeypatch.setenv("HOME", str(sudo_process.root_home))
+ monkeypatch.setenv("SUDO_UID", str(sudo_process.uid))
+ monkeypatch.setenv("SUDO_GID", str(os.getgid() or 1000))
+ monkeypatch.setattr(sys, "argv", ["-c", *command[7:]])
+ with pytest.raises(BeforeFirstWrite):
+ exec(compile(command[6], "<maintained privileged entry>", "exec"), {})
+ return subprocess.CompletedProcess(command, 0)
+
+ # The outer caller is genuinely non-root; simulate root only inside sudo.
+ monkeypatch.setattr(os, "geteuid", lambda: sudo_process.uid)
+ monkeypatch.setattr(sys, "path", list(sys.path))
+ def call_sudo(command, **kwargs):
+ monkeypatch.setattr(os, "geteuid", lambda: 0)
+ return sudo(command, **kwargs)
+
+ monkeypatch.setattr(namespace, "open_receipts", first_write)
+ monkeypatch.setattr(subprocess, "run", call_sudo)
+ exec(compile(caller, "<maintained original-context caller>", "exec"), {})
+ assert len(reached) == 1 and not (envelope.root / "receipts").exists()
+ assert not envelope.launched and not envelope.servers
+
+
[email protected]("failure", ["missing", "file", "alias", "foreign", "unreadable", "0755", "0777", "1700"])
+def test_actual_parent_refuses_root_custody_before_first_effect(envelope, monkeypatch, failure):
+ root = envelope.root
+ previous = root / "previous-evidence"
+ previous.write_bytes(b"preserve original evidence")
+ preserved = root
+ if failure in ("missing", "file"):
+ preserved = root.with_name("preserved-root")
+ root.rename(preserved)
+ if failure == "file":
+ root.write_bytes(b"not a directory")
+ elif failure == "alias":
+ alias = root.with_name("alias")
+ alias.symlink_to(root, target_is_directory=True)
+ argv = list(sys.argv)
+ argv[argv.index("--root") + 1] = str(alias)
+ monkeypatch.setattr(sys, "argv", argv)
+ elif failure == "foreign":
+ original = StorageContext.capture()
+ caller = original.uid + 10000
+ context = StorageContext(caller, original.homes, original.protected, original.environment_sha256)
+ monkeypatch.setenv("SUDO_UID", str(caller))
+ monkeypatch.setattr(namespace, "sudo_storage_context", lambda *_: context)
+ elif failure[0].isdigit():
+ root.chmod(int(failure, 8))
+ before = preserved.stat()
+ opened = []
+ real_open = os.open
+
+ def opening(path, *args, **kwargs):
+ if path == root and failure == "unreadable":
+ raise PermissionError("finite root-open denial")
+ fd = real_open(path, *args, **kwargs)
+ opened.append(fd)
+ return fd
+
+ monkeypatch.setattr(os, "open", opening)
+ monkeypatch.setattr(os, "mkdir", lambda *_a, **_kw: pytest.fail("First allocation reached."))
+ monkeypatch.setattr(os, "fchmod", lambda *_: pytest.fail("Supplied root repaired."))
+ with pytest.raises((ValueError, OSError)):
+ namespace.main()
+ for fd in opened:
+ with pytest.raises(OSError) as closed:
+ os.fstat(fd)
+ assert closed.value.errno == errno.EBADF
+ after = preserved.stat()
+ assert (before.st_ino, before.st_uid, before.st_mode) == (after.st_ino, after.st_uid, after.st_mode)
+ assert (preserved / "previous-evidence").read_bytes() == b"preserve original evidence"
+ assert not (preserved / "receipts").exists() and not (preserved / "runs").exists()
+ assert not envelope.launched and not envelope.servers
+
+
[email protected]("seam", ["root-open", "after-receipts", "after-output", "before-launch"])
+def test_root_replacement_never_redirects_allocation_or_cleanup(envelope, monkeypatch, seam):
+ root = envelope.root
+ preserved = root.with_name("preserved-root")
+ (root / "previous-evidence").write_bytes(b"original")
+ opened = []
+ real_open = os.open
+
+ def replace():
+ root.rename(preserved)
+ root.mkdir(mode=0o700)
+ (root / "replacement-evidence").write_bytes(b"replacement untouched")
+
+ def opening(path, *args, **kwargs):
+ if path == root and seam == "root-open":
+ replace()
+ fd = real_open(path, *args, **kwargs)
+ opened.append(fd)
+ return fd
+
+ monkeypatch.setattr(os, "open", opening)
+ receipts, output, sentinel = namespace.open_receipts, namespace.allocate_output, namespace.Sentinel
+
+ def receive(args, stack, fd):
+ result = receipts(args, stack, fd)
+ if seam == "after-receipts":
+ replace()
+ return result
+
+ def allocate(args, stack, fd):
+ result = output(args, stack, fd)
+ if seam == "after-output":
+ replace()
+ return result
+
+ def listener(family):
+ result = sentinel(family)
+ if seam == "before-launch" and family == socket.AF_INET6:
+ replace()
+ return result
+
+ monkeypatch.setattr(namespace, "open_receipts", receive)
+ monkeypatch.setattr(namespace, "allocate_output", allocate)
+ monkeypatch.setattr(namespace, "Sentinel", listener)
+ with pytest.raises(ValueError, match="scratch"):
+ namespace.main()
+ for fd in opened:
+ with pytest.raises(OSError) as closed:
+ os.fstat(fd)
+ assert closed.value.errno == errno.EBADF
+ assert list(root.iterdir()) == [root / "replacement-evidence"]
+ assert (root / "replacement-evidence").read_bytes() == b"replacement untouched"
+ assert (preserved / "previous-evidence").read_bytes() == b"original"
+ assert not list(preserved.glob("rootfs-*"))
+ assert not envelope.launched and all(server.closed for server in envelope.servers)
+ if seam == "root-open":
+ assert not (preserved / "receipts").exists()
+ else:
+ result = json.loads((preserved / "receipts" / envelope.receipt).read_text())
+ assert result["status"] == "failed" and result["failure"] == "ValueError"
+ assert result["temporary_rootfs_removed"] and not result["cleanup_errors"]
+ assert not list((preserved / "receipts").glob("*.control"))
+ assert not list((preserved / "receipts").glob("*.preflight"))
+ if seam in ("root-open", "after-receipts"):
+ assert not (preserved / "runs").exists()
+
+
+def test_successful_parent_holds_one_caller_root_descriptor_for_all_allocations(envelope, monkeypatch):
+ real_open, real_mkdir = os.open, os.mkdir
+ root_fds, effects = [], []
+ identity = envelope.root.stat()
+
+ def opening(path, *args, **kwargs):
+ fd = real_open(path, *args, **kwargs)
+ if path == envelope.root:
+ root_fds.append(fd)
+ return fd
+
+ def mkdir(path, *args, **kwargs):
+ if path in ("receipts", "runs") or str(path).startswith("rootfs-"):
+ fd = kwargs["dir_fd"]
+ info = os.fstat(fd)
+ if str(path).startswith("rootfs-"):
+ assert fd != root_fds[0]
+ control = (envelope.root / "receipts").stat()
+ assert (info.st_dev, info.st_ino) == (control.st_dev, control.st_ino)
+ assert info.st_uid == os.getuid() and stat.S_IMODE(info.st_mode) == 0o750
+ else:
+ assert root_fds == [fd]
+ assert (info.st_dev, info.st_ino, info.st_uid, info.st_mode) == (
+ identity.st_dev, identity.st_ino, identity.st_uid, identity.st_mode,
+ )
+ effects.append(str(path).split("-")[0])
+ return real_mkdir(path, *args, **kwargs)
+
+ monkeypatch.setattr(os, "open", opening)
+ monkeypatch.setattr(os, "mkdir", mkdir)
+ with pytest.raises(SystemExit) as result:
+ namespace.main()
+ assert result.value.code == 0 and effects == ["receipts", "runs", "rootfs"]
+ with pytest.raises(OSError) as closed:
+ os.fstat(root_fds[0])
+ assert closed.value.errno == errno.EBADF
+ assert read_receipt(envelope)["status"] == "passed"
+ assert_cleanup(envelope)
+
+
+def test_actual_emitted_filter_decode_excludes_foreign_abi_and_three_keyring_syscalls():
+ """Decode the actual bytes, not an independent production policy predicate."""
+ raw = namespace.keyring_program()
+ assert len(raw) == 88 and hashlib.sha256(raw).hexdigest() == keyring_identity()["program_sha256"]
+ instructions = tuple(struct.iter_unpack("<HBBI", raw))
+
+ def evaluate(arch, number):
+ pc, accumulator = 0, 0
+ for _ in range(len(instructions)):
+ code, yes, no, value = instructions[pc]
+ if code == 0x20:
+ accumulator = {0: number & 0xFFFFFFFF, 4: arch}[value]
+ pc += 1
+ elif code in (0x15, 0x35):
+ condition = accumulator == value if code == 0x15 else accumulator >= value
+ pc += 1 + (yes if condition else no)
+ elif code == 0x06:
+ return value
+ else:
+ pytest.fail("Unexpected emitted opcode.")
+ pytest.fail("Emitted filter did not terminate.")
+
+ count = 0
+ for arch in (0xC00000B7, 0x40000028, 0xC000003E, 0, 0xFFFFFFFF):
+ for number in (*range(1024), 0x3FFFFFFF, 0x40000000, 0xFFFFFFFF, -1):
+ expected = (0x80000000 if arch != 0xC00000B7 or (number & 0xFFFFFFFF) >= 0x40000000
+ else 0x00050001 if number in (217, 218, 219) else 0x7FFF0000)
+ assert evaluate(arch, number) == expected
+ count += 1
+ assert count == 5140
+
+
[email protected]("stage", ["success", "nnp-error", "filter-error", "nnp-readback", "filter-readback",
+ "bool-result", "bad-program"])
+def test_actual_typed_filter_adapter_and_order(monkeypatch, stage):
+ calls = []
+ monkeypatch.setattr(namespace, "require_native_abi", lambda: None)
+
+ class Prctl:
+ def __call__(self, option, a2, a3, a4, a5):
+ assert self.argtypes == [ctypes.c_int, *([ctypes.c_ulong] * 4)]
+ assert self.restype is ctypes.c_int and (a4, a5) == (0, 0)
+ calls.append(option)
+ if option == 22:
+ program = ctypes.cast(a3, ctypes.POINTER(namespace.SockFprog)).contents
+ assert a2 == 2 and program.len == 11
+ assert ctypes.string_at(program.filter, 88) == namespace.keyring_program()
+ if (stage == "nnp-error" and option == 38) or (stage == "filter-error" and option == 22):
+ ctypes.set_errno(errno.EPERM)
+ return -1
+ if stage == "nnp-readback" and option == 39:
+ return 0
+ if stage == "filter-readback" and option == 21:
+ return 1
+ if stage == "bool-result":
+ return False
+ return {38: 0, 22: 0, 39: 1, 21: 2}[option]
+
+ adapter = Prctl()
+ monkeypatch.setattr(ctypes, "CDLL", lambda path, **kwargs: (
+ pytest.fail("Unexpected library selection.") if path is not None or kwargs != {"use_errno": True}
+ else SimpleNamespace(prctl=adapter)
+ ))
+ if stage == "bad-program":
+ monkeypatch.setattr(namespace, "keyring_program", lambda: b"\0" * 88)
+ if stage == "success":
+ assert namespace.install_keyring_boundary() == keyring_identity()
+ assert calls == [38, 22, 39, 21]
+ else:
+ with pytest.raises((RuntimeError, OSError)):
+ namespace.install_keyring_boundary()
+ assert calls == {"nnp-error": [38], "filter-error": [38, 22], "nnp-readback": [38, 22, 39],
+ "filter-readback": [38, 22, 39, 21], "bool-result": [38], "bad-program": []}[stage]
+
+
[email protected]("platform_name,machine,byteorder,width", [
+ ("darwin", "arm64", "little", 8), ("linux", "x86_64", "little", 8),
+ ("linux", "aarch64", "big", 8), ("linux", "aarch64", "little", 4),
+])
+def test_unsupported_abi_refuses_before_any_adapter(monkeypatch, platform_name, machine, byteorder, width):
+ monkeypatch.setattr(sys, "platform", platform_name)
+ monkeypatch.setattr(namespace.platform, "machine", lambda: machine)
+ monkeypatch.setattr(sys, "byteorder", byteorder)
+ monkeypatch.setattr(ctypes, "sizeof", lambda _: width)
+ monkeypatch.setattr(ctypes, "CDLL", lambda *_a, **_kw: pytest.fail("Unsupported ABI reached libc."))
+ with pytest.raises(RuntimeError, match="Unsupported"):
+ namespace.install_keyring_boundary()
+ with pytest.raises(RuntimeError, match="Unsupported"):
+ namespace.linux_mount(None, "/", None, 0)
+
+
[email protected]("failure", [False, True])
+def test_actual_direct_mount_adapter_signature_and_errno(monkeypatch, failure):
+ monkeypatch.setattr(namespace, "require_native_abi", lambda: None)
+ calls = []
+
+ class Mount:
+ def __call__(self, source, target, filesystem, flags, data):
+ assert self.argtypes == [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p,
+ ctypes.c_ulong, ctypes.c_void_p]
+ assert self.restype is ctypes.c_int
+ calls.append((source, target, filesystem, flags, ctypes.string_at(data)))
+ ctypes.set_errno(errno.EACCES if failure else 0)
+ return -1 if failure else 0
+
+ monkeypatch.setattr(ctypes, "CDLL", lambda *_a, **_kw: SimpleNamespace(mount=Mount()))
+ if failure:
+ with pytest.raises(OSError) as error:
+ namespace.linux_mount("tmpfs", "/proc/self/fd/7/唯一", "tmpfs", 6, "mode=0755")
+ assert error.value.errno == errno.EACCES
+ else:
+ namespace.linux_mount("tmpfs", "/proc/self/fd/7/唯一", "tmpfs", 6, "mode=0755")
+ assert calls == [(b"tmpfs", "/proc/self/fd/7/唯一".encode(), b"tmpfs", 6, b"mode=0755")]
+
+
[email protected]("name", NAMESPACE_NAMES)
[email protected]("side", ["outer_namespaces", "namespaces"])
[email protected]("failure", ["missing", "extra", "same", "integer", "wrong-prefix", "empty", "zero", "suffix"])
+def test_complete_namespace_identity_schema_at_actual_consumer(name, side, failure):
+ proof = kernel_proof()
+ values = proof[side]
+ if failure == "missing":
+ values.pop(name)
+ elif failure == "extra":
+ values["user"] = "user:[22]"
+ elif failure == "same":
+ values[name] = proof["namespaces" if side == "outer_namespaces" else "outer_namespaces"][name]
+ else:
+ values[name] = {"integer": 2, "wrong-prefix": "user:[2]", "empty": "", "zero": f"{name}:[0]",
+ "suffix": f"{name}:[12]oops"}[failure]
+ with pytest.raises(RuntimeError):
+ require_namespaces(proof["outer_namespaces"], proof["namespaces"])
+
+
[email protected]("failure", ["missing", "extra", "prefix", "type"])
+def test_parent_bad_outer_capture_refuses_before_allocations(envelope, monkeypatch, failure):
+ outer = kernel_proof()["outer_namespaces"]
+ if failure == "missing":
+ outer.pop("ipc")
+ elif failure == "extra":
+ outer["user"] = "user:[99]"
+ else:
+ outer["ipc"] = "net:[4]" if failure == "prefix" else 4
+ monkeypatch.setattr(namespace, "namespace_ids", lambda: outer)
+ monkeypatch.setattr(namespace, "open_receipts", lambda *_: pytest.fail("Allocation before outer validation."))
+ with pytest.raises(RuntimeError):
+ namespace.main()
+ assert not envelope.servers and not (envelope.root / "receipts").exists()
+
+
[email protected]("name", [*namespace.INPUT_NAMES, "output", "build"])
+def test_actual_bind_consumes_pin_after_child_and_ancestor_replacement(private_setup, monkeypatch, name):
+ state = private_setup
+ path = state.paths[name]
+ original = state.args.handles[name]["identity"]
+ path.rename(path.with_name(path.name + "-preserved"))
+ if name == "go_archive":
+ path.write_bytes(b"replacement archive")
+ else:
+ path.mkdir()
+ (path / "replacement").write_bytes(b"untouched")
+ ancestor = state.args.root
+ preserved = ancestor.with_name("preserved-task")
+ ancestor.rename(preserved)
+ ancestor.mkdir()
+ (ancestor / "replacement-evidence").write_bytes(b"untouched ancestor")
+ # The HOST view simulator must follow its own task-only preserved directory.
+ state.paths["rootfs"] = preserved / "control/rootfs-test"
+ state.saved = preserved / "control/preserved-underlay"
+ # This test stops at the exact source-consuming bind, before any real mount.
+ def mount(source, target, filesystem, flags, data=None):
+ if filesystem == "tmpfs":
+ state.paths["rootfs"].rename(state.saved)
+ state.paths["rootfs"].mkdir(mode=0o755)
+ state.paths["rootfs"].chmod(0o755)
+ if source == namespace.fd_path(state.args.handles[name]["fd"]) and flags == namespace.MS_BIND:
+ assert namespace.descriptor_identity(os.fstat(state.args.handles[name]["fd"])) == original
+ assert target.startswith("/proc/self/fd/") and target.endswith("/" + path.name)
+ raise LookupError("finite stop at actual retained bind source")
+ monkeypatch.setattr(namespace, "linux_mount", mount)
+ with pytest.raises(LookupError, match="retained bind source"):
+ namespace.inside(state.args, state.outer)
+ assert (ancestor / "replacement-evidence").read_bytes() == b"untouched ancestor"
+ replaced = preserved / path.name
+ assert (replaced.read_bytes() if name == "go_archive" else (replaced / "replacement").read_bytes()) == (
+ b"replacement archive" if name == "go_archive" else b"untouched"
+ )
+ for _, record in state.descriptors:
+ with pytest.raises(OSError):
+ os.fstat(record["fd"])
+ with pytest.raises(OSError):
+ os.fstat(state.args.proof_fd)
+
+
[email protected]("stage", ["namespace", "context", "missing-handle", "aliased-handle", "identity",
+ "mount", "overmount", "filter"])
+def test_actual_inside_partial_failure_closes_all_received_handles(private_setup, monkeypatch, stage):
+ state = private_setup
+ if stage == "namespace":
+ state.outer.pop("ipc")
+ elif stage == "context":
+ state.args.storage_context["uid"] += 10000
+ elif stage == "missing-handle":
+ # Preserve the FD in another received record so closure remains observable.
+ state.args.handles["unexpected"] = state.args.handles.pop("state")
+ elif stage == "aliased-handle":
+ state.args.system_mounts = [{"resource": state.args.handles["state"]}]
+ elif stage == "identity":
+ state.args.handles["source"]["identity"]["ino"] += 1
+ elif stage == "mount":
+ monkeypatch.setattr(namespace, "linux_mount", lambda *_a, **_kw: (_ for _ in ()).throw(OSError("finite mount failure")))
+ elif stage == "overmount":
+ monkeypatch.setattr(namespace, "linux_mount", lambda *_a, **_kw: None)
+ else:
+ monkeypatch.setattr(namespace, "install_keyring_boundary",
+ lambda: (_ for _ in ()).throw(RuntimeError("finite filter failure")))
+ monkeypatch.setattr(namespace, "run_candidate", lambda *_: pytest.fail("Candidate after setup failure."))
+ with pytest.raises((RuntimeError, ValueError, OSError)):
+ namespace.inside(state.args, state.outer)
+ for _, record in state.descriptors:
+ with pytest.raises(OSError):
+ os.fstat(record["fd"])
+ with pytest.raises(OSError):
+ os.fstat(state.args.proof_fd)
+ marker = state.paths["rootfs"] / "run/avibe-engine-test-isolation.json"
+ if marker.exists():
+ assert marker.read_bytes() == b""
+
+
[email protected]("kind", ["directory", "file", "device"])
[email protected]("failure", ["none", "wrong-type", "symlink", "missing", "unreadable", "ancestor-alias"])
+def test_actual_component_pins_type_flags_and_partial_closure(tmp_path, monkeypatch, kind, failure):
+ root = tmp_path / "root"
+ parent = root / "a"
+ parent.mkdir(parents=True)
+ target = parent / "resource"
+ if kind == "directory" and failure != "wrong-type":
+ target.mkdir()
+ else:
+ target.write_bytes(b"synthetic regular backing, never a device")
+ if failure == "symlink":
+ original = target.with_name("preserved")
+ target.rename(original)
+ target.symlink_to(original)
+ elif failure == "missing":
+ target.rename(target.with_name("preserved"))
+ elif failure == "ancestor-alias":
+ parent.rename(root / "preserved")
+ parent.symlink_to(root / "preserved")
+ real_open, real_fstat = os.open, os.fstat
+ opened, devices = [], set()
+ def opening(path, flags, *args, **kwargs):
+ assert flags & os.O_NOFOLLOW and flags & os.O_CLOEXEC
+ if path == "resource" and failure == "unreadable":
+ raise PermissionError("finite consuming open failure")
+ is_device = bool(flags & 0o10000000)
+ if is_device:
+ assert kind == "device"
+ flags = os.O_RDONLY | os.O_NOFOLLOW | os.O_CLOEXEC | os.O_NONBLOCK
+ fd = real_open(path, flags, *args, **kwargs)
+ opened.append(fd)
+ if is_device and failure != "wrong-type":
+ devices.add(fd)
+ return fd
+ def info(fd):
+ value = real_fstat(fd)
+ return stat_fields(value, st_mode=stat.S_IFCHR | 0o600, st_rdev=os.makedev(1, 3)) if fd in devices else value
+ with ExitStack() as stack:
+ root_fd = _directory_fd(stack, root)
+ monkeypatch.setattr(namespace, "require_native_abi", lambda: None)
+ monkeypatch.setattr(os, "open", opening)
+ monkeypatch.setattr(os, "fstat", info)
+ if failure == "none":
+ record = namespace.pin_beneath(stack, root_fd, Path("a/resource"), kind=kind)
+ assert namespace.check_handle(record) == record["fd"]
+ else:
+ # A regular directory supplies the wrong type for a regular-file pin.
+ if kind == "file" and failure == "wrong-type":
+ target.unlink()
+ target.mkdir()
+ with pytest.raises((OSError, ValueError)):
+ namespace.pin_beneath(stack, root_fd, Path("a/resource"), kind=kind)
+ for fd in opened:
+ with pytest.raises(OSError):
+ os.fstat(fd)
+
+
[email protected]("different_inherited_gid", [False, True])
+def test_rootfs_pin_failure_cleans_only_the_original_empty_control_child(envelope, monkeypatch, different_inherited_gid):
+ raw = envelope.raw_lstat(envelope.paths["source"])
+ if different_inherited_gid:
+ monkeypatch.setenv("SUDO_GID", str(raw.st_gid + 1))
+ assert int(os.environ["SUDO_GID"]) > 0 and int(os.environ["SUDO_GID"]) != raw.st_gid
+ reached = []
+ original = namespace.pin_beneath
+ def pin(stack, fd, path, **kwargs):
+ if path.name.startswith("rootfs-"):
+ reached.append(path.name)
+ raise PermissionError("finite rootfs pin denial")
+ return original(stack, fd, path, **kwargs)
+ monkeypatch.setattr(namespace, "pin_beneath", pin)
+ with pytest.raises(PermissionError, match="rootfs pin denial"):
+ namespace.main()
+ result = read_receipt(envelope)
+ assert result["status"] == "failed" and result["temporary_rootfs_removed"] and not result["cleanup_errors"]
+ assert len(reached) == 1 and result["failure"] == "PermissionError"
+ assert envelope.paths["source"].lstat() == raw
+ assert envelope.raw_lstat(envelope.paths["source"]) == raw
+ assert not list((envelope.root / "receipts").glob("rootfs-*"))
+ assert not envelope.servers and not envelope.launched
+
+
[email protected]("failure", ["none", "wrong-identity", "replacement", "nonempty"])
+def test_exact_rootfs_cleanup_preserves_replacements_and_nonempty_evidence(tmp_path, failure):
+ root = tmp_path / "control"
+ root.mkdir()
+ target = root / "rootfs-test"
+ target.mkdir(mode=0o700)
+ with ExitStack() as stack:
+ fd = _directory_fd(stack, root)
+ record = namespace.pin_beneath(stack, fd, Path(target.name), kind="directory")
+ if failure == "wrong-identity":
+ record["identity"]["ino"] += 1
+ elif failure == "replacement":
+ target.rename(root / "preserved")
+ target.mkdir()
+ if failure in ("replacement", "nonempty"):
+ (target / "evidence").write_bytes(b"preserve")
+ if failure == "none":
+ namespace.remove_rootfs(namespace.retained_handle(fd, "directory"), record, target.name)
+ assert not target.exists()
+ else:
+ with pytest.raises((RuntimeError, OSError)):
+ namespace.remove_rootfs(namespace.retained_handle(fd, "directory"), record, target.name)
+ assert target.exists()
+ if failure in ("replacement", "nonempty"):
+ assert (target / "evidence").read_bytes() == b"preserve"
+
+
[email protected]("failure", [False, True])
+def test_selected_build_consumes_exact_output_identity_from_parent_receipt(envelope, failure):
+ control = envelope.root / "receipts"
+ control.mkdir(mode=0o750)
+ envelope.parent_owned(control)
+ build = envelope.root / "runs" / "old-build.json"
+ build.mkdir(parents=True)
+ with ExitStack() as stack:
+ fd = _directory_fd(stack, control)
+ build_fd = _directory_fd(stack, build)
+ record = namespace.retained_handle(build_fd, "directory")
+ value = {"status": "passed", "phase": "build", "output": str(build),
+ "output_identity": {**record["identity"], "ino": record["identity"]["ino"] + int(failure)}}
+ receipt = control / build.name
+ receipt.write_text(json.dumps(value))
+ receipt.chmod(0o640)
+ envelope.parent_owned(receipt)
+ if failure:
+ with pytest.raises(RuntimeError, match="directory does not match"):
+ namespace.selected_build_receipt(SimpleNamespace(build=build), fd, record)
+ else:
+ assert namespace.selected_build_receipt(SimpleNamespace(build=build), fd, record)["output_identity"] == record["identity"]
+
+
[email protected]("case", ["success", "pathname-replacement", "same-inode-write", "wrong-hash",
+ "missing-fd", "missing-module", "named-control", "oversized-control"])
+def test_actual_host_exec_inheritance_and_fixed_trampoline_bytes(tmp_path, case):
+ """Real unprivileged HOST exec only; finite control-UID metadata adaptation."""
+ recipe = tmp_path / "recipe"
+ recipe.mkdir()
+ source = {
+ "budgets": "VALUE = 'trusted-budget'\n",
+ "isolation": "from budgets import VALUE\n",
+ }
+ source["namespace"] = (
+ "import json, os\nfrom isolation import VALUE\n"
+ "def child_from_control(value):\n"
+ " for fd in value['closed_sources']:\n"
+ " try: os.fstat(fd)\n"
+ " except OSError: pass\n"
+ " else: raise RuntimeError('bootstrap descriptor survived import')\n"
+ " print(json.dumps({'value': VALUE, 'fixed_import': True}))\n"
+ )
+ for name, text in source.items():
+ (recipe / (name + ".py")).write_text(text)
+ with ExitStack() as stack:
+ recipe_fd = _directory_fd(stack, recipe)
+ pinned = namespace.pin_bootstrap(stack, namespace.retained_handle(recipe_fd, "directory"))
+ control = stack.enter_context(
+ (tmp_path / "named-control").open("w+b") if case == "named-control"
+ else tempfile.TemporaryFile(dir=tmp_path),
+ )
+ os.fchmod(control.fileno(), 0o600)
+ values = {"recipe": str(recipe), "bootstrap": pinned, "closed_sources": [item["fd"] for item in pinned.values()]}
+ if case == "pathname-replacement":
+ (recipe / "budgets.py").rename(recipe / "preserved.py")
+ (recipe / "budgets.py").write_text("raise RuntimeError('replacement must not import')\n")
+ elif case == "same-inode-write":
+ (recipe / "budgets.py").write_text("raise RuntimeError('changed content must not import')\n")
+ elif case == "wrong-hash":
+ pinned["isolation"]["sha256"] = "0" * 64
+ elif case == "missing-module":
+ pinned.pop("isolation")
+ data = json.dumps(values).encode() if case != "oversized-control" else b"x" * 65537
+ control.write(data)
+ control.flush()
+ control.seek(0)
+ # No privilege change: the trusted HOST test shim changes only the
+ # returned UID metadata for this one task-owned unnamed control file.
+ adaptation = (
+ "import os, sys, types\n"
+ "original_fstat=os.fstat\n"
+ "def host_fstat(fd):\n"
+ " info=original_fstat(fd)\n"
+ " if fd!=int(sys.argv[1]): return info\n"
+ " fields={key:getattr(info,key) for key in dir(info) if key.startswith('st_')}\n"
+ " fields['st_uid']=0\n"
+ " return types.SimpleNamespace(**fields)\n"
+ "os.fstat=host_fstat\n"
+ )
+ passed = [control.fileno(), *(item["fd"] for item in pinned.values())]
+ if case == "missing-fd":
+ passed.remove(pinned["isolation"]["fd"])
+ command = [sys.executable, "-I", "-B", "-c", adaptation + namespace.CHILD_TRAMPOLINE, str(control.fileno())]
+ environment = {name: str(tmp_path / ("child-" + name)) for name in (*STORAGE_ENV, "TMPDIR")}
+ for value in environment.values():
+ Path(value).mkdir()
+ environment.update(PATH="/usr/bin:/bin", PYTHONDONTWRITEBYTECODE="1")
+ result = subprocess.run(command, cwd=tmp_path, env=environment, close_fds=True,
+ pass_fds=tuple(passed), capture_output=True, timeout=10)
+ (tmp_path / "child-command.json").write_text(json.dumps({
+ "argv": command, "cwd": str(tmp_path), "environment": environment, "pass_fds": passed,
+ "timeout": 10, "close_fds": True, "qualification": "HOST-only control UID metadata seam; no Linux effect",
+ }, indent=2))
+ (tmp_path / "child.stdout").write_bytes(result.stdout)
+ (tmp_path / "child.stderr").write_bytes(result.stderr)
+ (tmp_path / "child.exit").write_text(str(result.returncode) + "\n")
+ if case in ("success", "pathname-replacement"):
+ assert result.returncode == 0 and result.stderr == b""
+ assert json.loads(result.stdout) == {"value": "trusted-budget", "fixed_import": True}
+ else:
+ assert result.returncode != 0 and result.stdout == b""
+ assert b"replacement must not import" not in result.stderr
+ assert b"changed content must not import" not in result.stderr
+
+
[email protected]("shape", ["directories", "relative-aliases", "absolute-aliases"])
[email protected]("failure", [None, "zero-bind"])
+def test_connected_parent_fixed_bootstrap_inside_probe_and_public_receipt(
+ envelope, installed_system, monkeypatch, shape, failure):
+ """Actual producer/consumers, task-only FD/view adapters; no OS acceptance."""
+ import builtins
+ from contextlib import redirect_stdout
+ import io
+ import isolation_probe
+
+ installed_system.layout(shape)
+ envelope.phase = "build"
+ argv = list(sys.argv)
+ argv[argv.index("--phase") + 1] = "build"
+ argv[argv.index("--network") + 1] = "none"
+ if shape == "absolute-aliases":
+ # Non-ASCII input and output labels reach the same parent/private seam.
+ source = envelope.paths["source"].with_name("source-输入")
+ envelope.paths["source"].rename(source)
+ envelope.paths["source"] = source
+ argv[argv.index("--source") + 1] = str(source)
+ envelope.receipt = "运行-envelope.json"
+ argv[argv.index("--receipt") + 1] = envelope.receipt
+ monkeypatch.setattr(sys, "argv", argv)
+ events, child_fds = [], []
+ real_exec, real_fstat = builtins.exec, os.fstat
+ real_exists, real_read_text, real_write = Path.exists, Path.read_text, Path.write_bytes
+ actual_uid = os.getuid()
+
+ def launch(command, control, kwargs):
+ assert installed_system.calls == 1
+ assert control["system_mounts"] == installed_system.mounts
+ assert control["system_aliases"] == installed_system.aliases
+ expected_directories = ["/usr/bin", "/usr/sbin", "/usr/lib", "/usr/share"]
+ expected_aliases = {}
+ if shape == "directories":
+ expected_directories += ["/bin", "/sbin", "/lib", "/lib64"]
+ else:
+ expected_aliases = {name: ("/" if shape == "absolute-aliases" else "") + "usr/" + name
+ for name in ("bin", "sbin", "lib", "lib64")}
+ assert control["system_aliases"] == expected_aliases
+ assert [item["path"] for item in control["system_mounts"]] == [*expected_directories, "/dev/null", "/dev/zero"]
+ assert installed_system.device_opens == ["null", "zero"]
+ for item in control["system_mounts"]:
+ resource = item["resource"]
+ assert resource["identity"]["uid"] == 0
+ if item["path"] in ("/dev/null", "/dev/zero"):
+ assert resource["kind"] == "device" and item["writable"] is True
+ assert stat.S_ISCHR(resource["identity"]["mode"])
+ assert (os.major(resource["identity"]["rdev"]), os.minor(resource["identity"]["rdev"])) == (
+ 1, 3 if item["path"] == "/dev/null" else 5,
+ )
+ else:
+ assert resource["kind"] == "directory" and item["writable"] is False
+ assert stat.S_ISDIR(resource["identity"]["mode"])
+ # In-process HOST simulation duplicates the exact passed handles to
+ # preserve the real parent's ownership. Numeric-FD translation is the
+ # only handoff adaptation; real exec inheritance is tested separately.
+ translated = json.loads(json.dumps(control))
+ mapping = {fd: os.dup(fd) for fd in kwargs["pass_fds"] if fd != int(command[-1])}
+ child_fds.extend(mapping.values())
+ for record in (*translated["handles"].values(), *translated["bootstrap"].values(),
+ *(item["resource"] for item in translated["system_mounts"])):
+ record["fd"] = mapping[record["fd"]]
+ translated["proof_fd"] = mapping[translated["proof_fd"]]
+ rootfs = Path(control["rootfs"])
+ underlay = rootfs.with_name(rootfs.name + "-underlay")
+ marker = rootfs / "run/avibe-engine-test-isolation.json"
+ expected_mounts = [*translated["system_mounts"], *(
+ {"path": control[name], "resource": translated["handles"][name],
+ "writable": name in ("state", "output")}
+ for name in (*namespace.INPUT_NAMES, "output")
+ )]
+ bound, remounted = [], []
+ with tempfile.TemporaryFile(dir=envelope.root) as handoff, monkeypatch.context() as child:
+ handoff.write(json.dumps(translated).encode())
+ handoff.flush()
+ handoff.seek(0)
+ control_fd = os.dup(handoff.fileno())
+ control_identity = real_fstat(control_fd).st_ino
+ child.setattr(sys, "argv", ["-c", str(control_fd)])
+ for name in ("budgets", "isolation", "namespace"):
+ child.setitem(sys.modules, name, sys.modules[name])
+
+ def fstat(fd):
+ info = real_fstat(fd)
+ if info.st_ino == control_identity or (marker.exists() and info.st_ino == marker.stat().st_ino):
+ return stat_fields(info, st_uid=0)
+ return info
+
+ def mount(source, target, filesystem, flags, data=None):
+ events.append(("mount", source, target, flags))
+ if filesystem == "tmpfs":
+ rootfs.rename(underlay)
+ rootfs.mkdir(mode=0o755)
+ rootfs.chmod(0o755)
+ if flags == namespace.MS_BIND:
+ assert marker.exists() and marker.read_bytes() == b""
+ source_fd = int(source.rsplit("/", 1)[1])
+ assert source_fd in mapping.values()
+ os.fstat(source_fd)
+ item = expected_mounts[len(bound)]
+ assert source_fd == item["resource"]["fd"]
+ relative = Path(item["path"]).relative_to("/")
+ parent_fd = int(target.split("/")[-2])
+ parent_info = os.fstat(parent_fd)
+ expected_parent = (rootfs / relative.parent).stat()
+ assert (parent_info.st_dev, parent_info.st_ino) == (expected_parent.st_dev, expected_parent.st_ino)
+ assert target.endswith("/" + relative.name)
+ bound.append((item, target))
+ if failure == "zero-bind" and item["path"] == "/dev/zero":
+ raise OSError(errno.EPERM, "finite task-only zero bind refusal")
+ elif flags & namespace.MS_BIND and flags & namespace.MS_REMOUNT:
+ item, expected_target = bound[len(remounted)]
+ expected_flags = namespace.MS_BIND | namespace.MS_REMOUNT | namespace.MS_NOSUID
+ if item["resource"]["kind"] != "device":
+ expected_flags |= namespace.MS_NODEV
+ if not item["writable"]:
+ expected_flags |= namespace.MS_RDONLY
+ assert source is None and filesystem is None and target == expected_target
+ assert flags == expected_flags
+ remounted.append(item)
+ if flags == namespace.MS_REMOUNT | namespace.MS_RDONLY | namespace.MS_NOSUID | namespace.MS_NODEV:
+ assert json.loads(marker.read_text())["keyring_boundary"] == keyring_identity()
+ events.append(("immutable-marker",))
+
+ def execute(code, globals=None, locals=None, **options):
+ result = real_exec(code, globals, locals, **options)
+ if globals is not None and globals.get("__name__") == "namespace":
+ module = sys.modules["namespace"]
+ child.setattr(module, "namespace_ids", lambda: kernel_proof()["namespaces"])
+ child.setattr(module, "linux_mount", mount)
+ child.setattr(module, "install_keyring_boundary",
+ lambda: events.append(("filter",)) or keyring_identity())
+ child.setattr(sys.modules["isolation"], "PROOF_PATH", marker)
+ return result
+
+ def read_text(path, *args, **kwargs):
+ if str(path) == "/proc/self/status":
+ return "\n".join(f"{name}: {value}" for name, value in kernel_proof()["process_status"].items())
+ if str(path) == "/proc/self/mountinfo":
+ return ""
+ return real_read_text(path, *args, **kwargs)
+
+ def exists(path):
+ if str(path) in ("/Users", "/home", "/root", "/sys", "/run/netns"):
+ return False
+ return real_exists(path)
+
+ def write(path, value):
+ if path.name == ".isolation-write-probe":
+ raise PermissionError("finite readonly bind seam")
+ return real_write(path, value)
+
+ def run(command, **options):
+ assert options["close_fds"] and "pass_fds" not in options
+ assert command[0] == "/usr/bin/setpriv"
+ assert "--clear-groups" in command and "--bounding-set=-all" in command
+ for fd in mapping.values():
+ if fd != translated["proof_fd"]:
+ with pytest.raises(OSError):
+ os.fstat(fd)
+ if command[-1].endswith("isolation_probe.py"):
+ events.append(("preflight",))
+ child.setattr(isolation_probe, "namespace_receipt", sys.modules["isolation"].namespace_receipt)
+ output = io.StringIO()
+ with redirect_stdout(output):
+ isolation_probe.main()
+ return subprocess.CompletedProcess(command, 0, stdout=output.getvalue().encode())
+ assert command[-1] == "candidate-test"
+ with pytest.raises(OSError):
+ os.fstat(translated["proof_fd"])
+ events.append(("candidate",))
+ return subprocess.CompletedProcess(command, 0)
+
+ child.setattr(os, "fstat", fstat)
+ child.setattr(builtins, "exec", execute)
+ child.setattr(Path, "read_text", read_text)
+ child.setattr(Path, "exists", exists)
+ child.setattr(Path, "write_bytes", write)
+ original_readlink = os.readlink
+ child.setattr(os, "readlink", lambda path, *a, **kw: (
+ kernel_proof()["namespaces"][Path(path).name] if str(path).startswith("/proc/self/ns/")
+ else original_readlink(path, *a, **kw)
+ ))
+ child.setattr(namespace.subprocess, "check_output", lambda *_a, **_kw: b'[{"ifname":"lo"}]')
+ child.setattr(namespace.subprocess, "run", run)
+ child.setattr(os, "fchdir", lambda fd: events.append(("new-view", os.fstat(fd).st_ino)))
+ child.setattr(os, "chroot", lambda path: (events.append(("chroot", path)),
+ child.setattr(os, "geteuid", lambda: actual_uid)))
+ child.setattr(os, "chdir", lambda path: events.append(("chdir", path)))
+ child.setattr(os, "closerange", lambda *_: None)
+ child.setattr(isolation_probe, "probe_blocked_connection", lambda network, host, port, kind: {
+ "host": host, "kind": kind, "blocked": True, "errno": errno.ECONNREFUSED,
+ })
+ if failure is None:
+ with pytest.raises(SystemExit) as result:
+ real_exec(compile(namespace.CHILD_TRAMPOLINE, "<actual connected trampoline>", "exec"), {})
+ assert result.value.code == 0
+ assert events.index(("filter",)) < events.index(("immutable-marker",)) < events.index(("preflight",))
+ assert events.index(("preflight",)) < events.index(("candidate",))
+ assert next(event[1] for event in events if event[0] == "new-view") != underlay.stat().st_ino
+ assert remounted == expected_mounts
+ assert [item["path"] for item in remounted if item["writable"] and item["resource"]["kind"] == "directory"] == [
+ control["state"], control["output"],
+ ]
+ else:
+ with pytest.raises(OSError, match="finite task-only zero bind refusal") as refused:
+ real_exec(compile(namespace.CHILD_TRAMPOLINE, "<actual connected trampoline>", "exec"), {})
+ assert refused.value.errno == errno.EPERM
+ assert [item["path"] for item, _ in bound] == [*expected_directories, "/dev/null", "/dev/zero"]
+ assert [item["path"] for item in remounted] == [*expected_directories, "/dev/null"]
+ assert not any(event[0] in ("filter", "immutable-marker", "preflight", "candidate") for event in events)
+ for fd in mapping.values():
+ with pytest.raises(OSError) as closed:
+ os.fstat(fd)
+ assert closed.value.errno == errno.EBADF
+ for name, target in expected_aliases.items():
+ assert os.readlink(rootfs / name) == target
+ assert not (rootfs / "dev/random").exists() and not (rootfs / "dev/urandom").exists()
+ rootfs.rename(rootfs.with_name(rootfs.name + "-preserved-view"))
+ underlay.rename(rootfs)
+ return subprocess.CompletedProcess(command, 0 if failure is None else 1)
+
+ envelope.launch = launch
+ if failure is None:
+ with pytest.raises(SystemExit) as result:
+ namespace.main()
+ assert result.value.code == 0
+ else:
+ with pytest.raises(RuntimeError, match="Namespace execution or preflight/cleanup/sentinel acceptance failed"):
+ namespace.main()
+ receipt = read_receipt(envelope)
+ assert receipt["status"] == ("passed" if failure is None else "failed")
+ assert receipt["temporary_rootfs_removed"] and not receipt["cleanup_errors"]
+ if failure is None:
+ assert receipt["probe"]["keyring_boundary"] == keyring_identity()
+ assert receipt["probe"]["namespaces"] == kernel_proof()["namespaces"]
+ assert receipt["probe"]["outer_namespaces"] == kernel_proof()["outer_namespaces"]
+ assert receipt["probe"]["isolation_probe"] == "pass"
+ assert "storage_context" not in receipt["probe"]
+ else:
+ assert receipt["failure"] is None and receipt["exit_code"] == 1
+ assert receipt["preflight"] == "missing-or-invalid" and "probe" not in receipt
+ assert receipt["output_identity"]["ino"] == (envelope.root / "runs" / envelope.receipt).stat().st_ino
+ for fd in child_fds:
+ with pytest.raises(OSError):
+ os.fstat(fd)
+ for fd in installed_system.opened:
+ with pytest.raises(OSError) as closed:
+ envelope.raw_fstat(fd)
+ assert closed.value.errno == errno.EBADF
diff --git a/patches/cliproxyapi/test_phase_outputs.py b/patches/cliproxyapi/test_phase_outputs.py
new file mode 100644
index 000000000..69d9a2af0
--- /dev/null
+++ b/patches/cliproxyapi/test_phase_outputs.py
@@ -0,0 +1,275 @@
+"""Real verifier phase/output consumers with only compiler/wire processes faked."""
+
+import json
+import os
+from pathlib import Path
+import subprocess
+import sys
+from types import SimpleNamespace
+
+import pytest
+
+from budgets import PHASES
+from fixture import source_digest
+from test_execution_inputs import fake_go
+import verify
+
+
+def phases(tmp_path, monkeypatch):
+ toolchain, archive, pin = fake_go(tmp_path, monkeypatch)
+ context = SimpleNamespace(
+ root=tmp_path, state=tmp_path / "cache-state", source=tmp_path / "source",
+ fixture=tmp_path / "fixture", recipe=tmp_path / "recipe", calls=[],
+ fail_at=None, timeout_at=None, elapsed=0, before_execution=None, after_execution=None,
+ )
+ for path in (context.source, context.state, context.fixture, context.recipe, tmp_path / "runs"):
+ path.mkdir()
+ (context.fixture / "uv.lock").write_text("test-frozen-lock")
+ (context.fixture / "pyproject.toml").write_text("test-frozen-project")
+ (context.recipe / "prerequisites.json").write_text(json.dumps({
+ "linux_arm64_go": pin, "linux_arm64_uv": {"version": "setup-only", "sha256": "test-only"},
+ }))
+ (context.source / "main.go").write_text("fake engine source; no Go process runs")
+ receipt = {
+ "source_sha": "test-base", "sha256": {"catalog": "test-catalog"},
+ "avibe_fixture_base": "test-fixture", "avibe_fixture_tree": "test-tree",
+ "avibe_fixture_archive_sha256": "test-archive",
+ "avibe_fixture_source_sha256": source_digest(context.fixture),
+ }
+ monkeypatch.setattr(verify, "HERE", context.recipe)
+ monkeypatch.setattr(verify, "verify_inputs", lambda source: receipt)
+ monkeypatch.setattr(verify, "verify_candidate", lambda source: "test-patch")
+ monkeypatch.setattr(verify, "python_identity", lambda *_: {"trust": "test-only trusted base"})
+ monkeypatch.setattr(verify.shutil, "which", lambda _name: str(toolchain / "bin/go"))
+
+ def version(command, **kwargs):
+ assert command == [str(toolchain / "bin/go"), "version"]
+ assert kwargs["env"]["GOTOOLCHAIN"] == "local"
+ assert kwargs["timeout"] == PHASES[context.phase].input_seconds
+ return "go version go1.26.4 linux/arm64\n"
+
+ monkeypatch.setattr(verify.subprocess, "check_output", version)
+
+ def git(source, *arguments):
+ assert source == context.source
+ assert arguments == ("apply", "--reverse", "--check", str(context.recipe / "native-intent.patch"))
+ return b""
+
+ monkeypatch.setattr(verify, "safe_git", git)
+
+ def command(command, **kwargs):
+ assert kwargs["close_fds"] and kwargs["stdin"] == subprocess.DEVNULL
+ assert kwargs["timeout"] == PHASES[context.phase].command_seconds
+ context.calls.append([str(part) for part in command])
+ context.elapsed += kwargs["timeout"] - 0.01
+ if context.before_execution:
+ context.before_execution()
+ kwargs["stdout"].write(b"exclusive fake command diagnostics\n")
+ if str(command[0]) == str(toolchain / "bin/go") and command[1] == "build":
+ Path(command[command.index("-o") + 1]).write_bytes(b"fake exact diagnostic binary")
+ elif len(command) > 1 and str(command[1]).endswith("wire_matrix.py"):
+ wire = Path(command[command.index("--state") + 1])
+ wire.mkdir()
+ for name in ("matrix", "integration", "lifecycle"):
+ (wire / (name + ".json")).write_text(json.dumps({"fake": name}))
+ if context.after_execution:
+ context.after_execution()
+ if context.timeout_at == len(context.calls):
+ raise subprocess.TimeoutExpired(command, kwargs["timeout"])
+ return subprocess.CompletedProcess(command, 9 if context.fail_at == len(context.calls) else 0)
+
+ monkeypatch.setattr(verify.subprocess, "run", command)
+
+ def invoke(phase, name, *, build=None, existing=False):
+ context.phase = phase
+ output = tmp_path / "runs" / name
+ if not existing:
+ output.mkdir()
+ proof = {
+ "phase": phase, "budget": PHASES[phase].receipt(),
+ "receipt": name, "source": str(context.source), "state": str(context.state),
+ "fixture": str(context.fixture), "recipe": str(context.recipe), "output": str(output),
+ "toolchain": str(toolchain), "go_archive": str(archive), "python_env": "test-venv",
+ "network": "none" if phase == "build" else "loopback",
+ "selected_build": None if build is None else {
+ "output": str(build), "receipt": build.name, "parent_receipt_sha256": "test-parent-receipt",
+ },
+ }
+ monkeypatch.setattr(verify, "namespace_receipt", lambda: proof)
+ argv = ["verify.py", phase, "--source", str(context.source), "--state", str(context.state),
+ "--fixture", str(context.fixture)]
+ if build is not None:
+ argv += ["--build", str(build)]
+ monkeypatch.setattr(sys, "argv", argv)
+ context.output, context.proof = output, proof
+ verify.main()
+ return output
+
+ context.invoke, context.toolchain, context.archive = invoke, toolchain, archive
+ return context
+
+
[email protected]("phase", ["test", "build", "wire"])
+def test_repeat_actual_phase_never_replaces_previous_evidence(phases, phase):
+ build = phases.invoke("build", "selected-build.json") if phase == "wire" else None
+ first = phases.invoke(phase, "first-" + phase + ".json", build=build)
+ before = source_digest(first)
+ build_before = source_digest(build) if build else None
+ second = phases.invoke(phase, "second-" + phase + ".json", build=build)
+ assert first != second and source_digest(first) == before
+ if build:
+ assert source_digest(build) == build_before
+ result = json.loads((second / "wire.json").read_text())
+ assert result["selected_build"]["receipt"] == build.name
+ assert result["selected_build"]["parent_receipt_sha256"] == "test-parent-receipt"
+ for output in (first, second):
+ assert json.loads((output / "inputs-before.json").read_text()) == json.loads((output / "inputs-after.json").read_text())
+ assert not (phases.state / "build.json").exists()
+ assert not (phases.state / "bin").exists()
+
+
[email protected]("phase", ["test", "build", "wire"])
+def test_same_invocation_refuses_before_overwriting_any_file(phases, phase):
+ build = phases.invoke("build", "selected-build.json") if phase == "wire" else None
+ output = phases.invoke(phase, "one-only.json", build=build)
+ before, calls = source_digest(output), len(phases.calls)
+ with pytest.raises(FileExistsError):
+ phases.invoke(phase, "one-only.json", build=build, existing=True)
+ assert source_digest(output) == before and len(phases.calls) == calls
+
+
[email protected]("phase", ["test", "build", "wire"])
[email protected]("failure", ["nonzero", "timeout"])
+def test_partial_failure_preserves_prior_run_and_current_diagnostics(phases, phase, failure):
+ build = phases.invoke("build", "selected-build.json") if phase == "wire" else None
+ previous = phases.invoke(phase, "previous.json", build=build)
+ before = source_digest(previous)
+ if failure == "nonzero":
+ phases.fail_at = len(phases.calls) + 1
+ else:
+ phases.timeout_at = len(phases.calls) + 1
+ with pytest.raises((SystemExit, subprocess.TimeoutExpired)):
+ phases.invoke(phase, "failed.json", build=build)
+ assert source_digest(previous) == before
+ assert (phases.output / (phase + "-0.log")).read_bytes() == b"exclusive fake command diagnostics\n"
+ assert (phases.output / "inputs-after.json").is_file()
+ assert not (phases.output / "build.json").exists()
+ assert not (phases.output / "wire.json").exists()
+
+
[email protected]("mutation", ["binary", "log", "receipt", "stale-recipe", "bin-link"])
+def test_wire_rejects_stale_or_substituted_selected_build(phases, mutation):
+ build = phases.invoke("build", "selected-build.json")
+ if mutation == "binary":
+ (build / "bin/cli-proxy-api").write_bytes(b"substituted")
+ elif mutation == "log":
+ (build / "build-0.log").write_bytes(b"lost old evidence")
+ elif mutation == "receipt":
+ value = json.loads((build / "build.json").read_text())
+ value["invocation"] = "another-parent.json"
+ (build / "build.json").write_text(json.dumps(value))
+ elif mutation == "stale-recipe":
+ (phases.recipe / "changed.py").write_text("changed recipe")
+ else:
+ (build / "bin").rename(build / "old-bin")
+ (build / "bin").symlink_to(build / "old-bin")
+ before, calls = source_digest(build), len(phases.calls)
+ with pytest.raises(RuntimeError):
+ phases.invoke("wire", "refused-wire.json", build=build)
+ assert len(phases.calls) == calls and source_digest(build) == before
+
+
+def test_substituted_same_version_compiler_refuses_before_any_go_execution(phases):
+ (phases.toolchain / "bin/go").write_bytes(b"substitute that claims go1.26.4")
+ with pytest.raises(RuntimeError, match="extraction"):
+ phases.invoke("build", "refused-compiler.json")
+ assert not phases.calls and not (phases.output / "bin").exists()
+
+
[email protected]("resource", ["source", "fixture", "recipe"])
+def test_actual_phase_identity_refuses_hardlink_closure_before_command(phases, monkeypatch, resource):
+ root = getattr(phases, resource)
+ target = root / {"source": "main.go", "fixture": "uv.lock", "recipe": "prerequisites.json"}[resource]
+ os.link(target, phases.state / "writable-alias")
+ monkeypatch.setattr(verify.subprocess, "check_output",
+ lambda *_a, **_kw: pytest.fail("Rejected closure reached compiler version."))
+ with pytest.raises(ValueError, match="single-link regular"):
+ phases.invoke("build", "refused-hardlink.json")
+ assert not phases.calls and not (phases.output / "bin").exists()
+ assert not (phases.output / "inputs-before.json").exists()
+ assert not (phases.output / "build.json").exists()
+
+
+def test_inputs_are_rechecked_after_failed_command(phases):
+ phases.fail_at = 1
+ phases.after_execution = lambda: (phases.toolchain / "src/runtime/runtime.go").write_bytes(b"changed runtime")
+ with pytest.raises(RuntimeError, match="extraction"):
+ phases.invoke("build", "changed-inputs.json")
+ assert (phases.output / "build-0.log").is_file()
+ assert not (phases.output / "build.json").exists()
+
+
+def test_near_limit_sequential_commands_fit_parent_and_driver_budget(phases):
+ phases.invoke("test", "three-near-deadlines.json")
+ budget = PHASES["test"]
+ assert len(phases.calls) == budget.commands == 3
+ assert phases.elapsed > 1799
+ assert phases.elapsed < budget.candidate_seconds < budget.namespace_seconds < budget.driver_seconds
+ assert budget.namespace_seconds - budget.candidate_seconds >= budget.preflight_seconds + budget.cleanup_seconds
+
+
+def test_later_command_log_collision_is_not_truncated(phases):
+ def collision():
+ if len(phases.calls) == 1:
+ (phases.output / "test-1.log").write_bytes(b"preexisting collision")
+
+ phases.after_execution = collision
+ with pytest.raises(FileExistsError):
+ phases.invoke("test", "log-collision.json")
+ assert len(phases.calls) == 1
+ assert (phases.output / "test-1.log").read_bytes() == b"preexisting collision"
+
+
[email protected]("phase,network", [("test", "loopback"), ("build", "none"), ("wire", "loopback")])
+def test_documented_outer_caller_uses_the_same_complete_budget(tmp_path, monkeypatch, phase, network):
+ # The maintained README is an executable caller, not another timeout owner.
+ readme = (Path(__file__).parent / "README.md").read_text()
+ caller = readme.split("run_phase() {", 1)[1].split("<<'PY'\n", 1)[1].split("\nPY\n}", 1)[0]
+ (tmp_path / "recipe").mkdir()
+ build = str(tmp_path / "runs/prior-build.json") if phase == "wire" else ""
+ monkeypatch.setattr(sys, "argv", ["-", str(tmp_path), str(tmp_path / "fixture"),
+ phase, network, "one-phase.json", build])
+ monkeypatch.setattr(sys, "path", list(sys.path))
+ calls = []
+
+ def observed(command, **kwargs):
+ calls.append(command)
+ assert kwargs == {"check": True, "close_fds": True, "timeout": PHASES[phase].driver_seconds}
+ assert command[command.index("--phase") + 1] == phase
+ assert command[command.index("--network") + 1] == network
+ if build:
+ assert command.count("--build") == 2
+ assert command[command.index("--build") + 1] == build
+ else:
+ assert "--build" not in command
+ return subprocess.CompletedProcess(command, 0)
+
+ monkeypatch.setattr(subprocess, "run", observed)
+ exec(compile(caller, "<maintained README caller>", "exec"), {})
+ assert len(calls) == 1
+
+
[email protected]("failure", ["test", "build"])
+def test_documented_phase_sequence_stops_at_first_failure(failure):
+ readme = (Path(__file__).parent / "README.md").read_text()
+ sequence = readme.split("run_phase test loopback test-unique.json", 1)[1].split("\n```", 1)[0]
+ sequence = "run_phase test loopback test-unique.json" + sequence
+ # Only the harmless function below runs; no recipe/Go/sudo process exists.
+ command = "run_phase() { printf '%s\\n' \"$1\"; test \"$1\" != \"$failure\"; }\n" + sequence
+ result = subprocess.run(
+ ["/bin/bash", "-c", command], env={"PATH": "/usr/bin:/bin", "failure": failure},
+ stdin=subprocess.DEVNULL, capture_output=True, text=True, close_fds=True, timeout=3,
+ )
+ assert result.returncode != 0
+ assert result.stdout.splitlines() == (["test"] if failure == "test" else ["test", "build"])
diff --git a/patches/cliproxyapi/test_recipe.py b/patches/cliproxyapi/test_recipe.py
new file mode 100644
index 000000000..3f3089830
--- /dev/null
+++ b/patches/cliproxyapi/test_recipe.py
@@ -0,0 +1,486 @@
+"""Pure-source receipt regressions; no engine process or network access."""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import os
+from pathlib import Path
+import re
+import shlex
+import subprocess
+import sys
+
+import pytest
+
+from fixture import export_fixture, source_digest, verify_fixture
+from isolation import STORAGE_ENV, isolated_environment, safe_git
+import verify
+
+
+def frozen_repository(tmp_path: Path) -> tuple[Path, dict]:
+ repository = tmp_path / "repository"
+ repository.mkdir()
+ env = isolated_environment(tmp_path / "state")
+ env["GIT_CONFIG_NOSYSTEM"] = "1"
+ env["GIT_CONFIG_GLOBAL"] = "/dev/null"
+
+ def git(*args: str) -> str:
+ return subprocess.check_output(
+ ["/usr/bin/git", "-C", str(repository), *args], env=env, text=True,
+ ).strip()
+
+ safe_git(repository, "init")
+ (repository / "fixture_model.py").write_text("MODEL = 'frozen-模型'\n")
+ (repository / "unchanged.go").write_text("package unchanged\n")
+ (repository / "facts").mkdir()
+ (repository / "facts/config.json").write_text('{"model":"frozen-模型"}')
+ git("add", ".")
+ git("-c", "user.name=Fixture", "-c", "[email protected]",
+ "commit", "--quiet", "-m", "fixture")
+ base = git("rev-parse", "HEAD")
+ archive = subprocess.check_output(["/usr/bin/git", "-C", str(repository), "archive", "--format=tar", base], env=env)
+ return repository, {
+ "avibe_fixture_base": base,
+ "avibe_fixture_tree": git("rev-parse", f"{base}^{{tree}}"),
+ "avibe_fixture_archive_sha256": hashlib.sha256(archive).hexdigest(),
+ }
+
+
+def test_frozen_export_never_imports_dirty_or_untracked_checkout(tmp_path: Path) -> None:
+ repository, receipt = frozen_repository(tmp_path)
+ (repository / "fixture_model.py").write_text("raise RuntimeError('dirty source executed')\n")
+ (repository / "untracked.py").write_text("raise RuntimeError('untracked source executed')\n")
+ exported, identity = export_fixture(repository, tmp_path, receipt)
+ assert not (exported / "untracked.py").exists()
+ assert identity["commit"] == receipt["avibe_fixture_base"]
+ # A clean interpreter imports from the frozen export even with dirty cwd.
+ result = subprocess.check_output(
+ [sys.executable, "-I", "-B", "-c",
+ "import sys; sys.path.insert(0,sys.argv[1]); import fixture_model; print(fixture_model.MODEL)",
+ str(exported)], cwd=repository, env=isolated_environment(tmp_path / "child"), text=True,
+ )
+ assert result.strip() == "frozen-模型"
+ verify_fixture(exported, identity["source_sha256"])
+
+
[email protected]("mutation", ["content", "extra", "missing", "escape"])
+def test_fixture_digest_rejects_changed_closure(tmp_path: Path, mutation: str) -> None:
+ repository, receipt = frozen_repository(tmp_path)
+ exported, identity = export_fixture(repository, tmp_path, receipt)
+ if mutation == "content":
+ (exported / "facts/config.json").write_text('{"model":"changed"}')
+ elif mutation == "extra":
+ (exported / "extra.py").write_text("VALUE = 1")
+ elif mutation == "missing":
+ (exported / "fixture_model.py").unlink()
+ else:
+ (exported / "outside.py").symlink_to(repository / "fixture_model.py")
+ with pytest.raises((RuntimeError, ValueError)):
+ verify_fixture(exported, identity["source_sha256"])
+
+
+def test_wrong_archive_refuses_before_materializing_fixture(tmp_path: Path) -> None:
+ repository, receipt = frozen_repository(tmp_path)
+ receipt["avibe_fixture_archive_sha256"] = "0" * 64
+ with pytest.raises(RuntimeError, match="archive"):
+ export_fixture(repository, tmp_path, receipt)
+ assert not list(tmp_path.glob("avibe-fixture-*"))
+
+
+def test_fixture_source_digest_is_path_independent(tmp_path: Path) -> None:
+ repository, receipt = frozen_repository(tmp_path)
+ first, identity = export_fixture(repository, tmp_path, receipt)
+ second, second_identity = export_fixture(repository, tmp_path, receipt)
+ assert first != second
+ assert second_identity == identity
+ assert source_digest(first) == source_digest(second)
+
+
+def test_single_link_digest_keeps_independent_encoding_and_internal_symlinks(tmp_path):
+ root = tmp_path / "source"
+ (root / "facts").mkdir(parents=True)
+ (root / "facts/模型.txt").write_bytes(b"exact task-only bytes")
+ (root / "internal-link").symlink_to("facts/模型.txt")
+ expected = hashlib.sha256()
+ # Independent named records preserve the preexisting sorted/length encoding.
+ for record in ((b"facts", b"dir", b""),
+ ("facts/模型.txt".encode(), b"file", b"exact task-only bytes"),
+ (b"internal-link", b"link", "facts/模型.txt".encode())):
+ for field in record:
+ expected.update(len(field).to_bytes(8, "big"))
+ expected.update(field)
+ assert source_digest(root) == expected.hexdigest()
+ verify_fixture(root, expected.hexdigest())
+
+
[email protected]("alias_location", ["inside", "outside", "writable-state"])
+def test_complete_source_digest_rejects_real_hardlink_aliases(tmp_path, alias_location):
+ root = tmp_path / "source"
+ root.mkdir()
+ target = root / "unchanged.go"
+ target.write_bytes(b"normal unpatched source")
+ expected = source_digest(root)
+ parent = root if alias_location == "inside" else tmp_path / alias_location
+ if parent != root:
+ parent.mkdir()
+ alias = parent / "alias"
+ os.link(target, alias)
+ with pytest.raises(ValueError, match="single-link regular"):
+ verify_fixture(root, expected)
+ assert target.read_bytes() == alias.read_bytes() == b"normal unpatched source"
+
+
[email protected]("mutation", ["replacement", "hardlink", "fifo"])
+def test_actual_digest_refuses_leaf_drift_at_consumed_open(tmp_path, monkeypatch, mutation):
+ root = tmp_path / "source"
+ root.mkdir()
+ target = root / "file"
+ target.write_bytes(b"unchanged content")
+ original_open, original_fstat = os.open, os.fstat
+ opened = []
+
+ def opening(path, flags, *args, **kwargs):
+ assert path == target and flags & os.O_NONBLOCK
+ if mutation == "hardlink":
+ os.link(target, tmp_path / "alias")
+ else:
+ target.rename(tmp_path / "preserved")
+ if mutation == "replacement":
+ target.write_bytes(b"unchanged content")
+ else:
+ os.mkfifo(target)
+ fd = original_open(path, flags, *args, **kwargs)
+ opened.append(fd)
+ return fd
+
+ monkeypatch.setattr(os, "open", opening)
+ with pytest.raises(ValueError):
+ source_digest(root)
+ assert len(opened) == 1
+ with pytest.raises(OSError):
+ original_fstat(opened[0])
+
+
+def apply_fixture(repository, receipt, tmp_path, monkeypatch):
+ """Actual apply/status/candidate consumers, with a harmless exact-base patch."""
+ recipe = tmp_path / "apply-recipe"
+ recipe.mkdir()
+ before = (repository / "fixture_model.py").read_bytes()
+ after = b"MODEL = 'patched task-only text'\n"
+ patch = ("diff --git a/fixture_model.py b/fixture_model.py\n"
+ "--- a/fixture_model.py\n+++ b/fixture_model.py\n@@ -1 +1 @@\n"
+ "-" + before.decode() + "+" + after.decode())
+ (recipe / "native-intent.patch").write_text(patch)
+ (recipe / "inputs.json").write_text(json.dumps({
+ "source_sha": receipt["avibe_fixture_base"],
+ "sha256": {"facts/config.json": hashlib.sha256((repository / "facts/config.json").read_bytes()).hexdigest()},
+ }))
+ (recipe / "patched-files.json").write_text(json.dumps({
+ "fixture_model.py": hashlib.sha256(after).hexdigest(),
+ }))
+ monkeypatch.setattr(verify, "HERE", recipe)
+ monkeypatch.setattr(sys, "argv", [
+ "verify.py", "apply", "--source", str(repository), "--state", str(tmp_path / "apply-state"),
+ ])
+ return after
+
+
[email protected]("name", ["facts/config.json", "fixture_model.py"])
+def test_actual_verify_input_and_candidate_reads_reject_hardlinks(tmp_path, monkeypatch, name):
+ repository, receipt = frozen_repository(tmp_path)
+ expected = apply_fixture(repository, receipt, tmp_path, monkeypatch)
+ verify.main() # Actual task-only Git apply, before installing the alias.
+ target = repository / name
+ os.link(target, tmp_path / "state-alias")
+ consumer = verify.verify_inputs if name == "facts/config.json" else verify.verify_candidate
+ with pytest.raises(ValueError, match="single-link regular"):
+ consumer(repository)
+ assert (repository / "fixture_model.py").read_bytes() == expected
+
+
[email protected]("name", ["facts/config.json", "fixture_model.py", "unchanged.go"])
+def test_actual_apply_refuses_complete_hardlinked_source_before_patch_write(tmp_path, monkeypatch, name):
+ repository, receipt = frozen_repository(tmp_path)
+ apply_fixture(repository, receipt, tmp_path, monkeypatch)
+ before = (repository / "fixture_model.py").read_bytes()
+ os.link(repository / name, tmp_path / "writable-state-alias")
+ original_git = verify.safe_git
+ calls = []
+
+ def git(source, *arguments):
+ calls.append(arguments)
+ assert arguments[0] != "apply", "Rejected closure reached patch effect."
+ return original_git(source, *arguments)
+
+ monkeypatch.setattr(verify, "safe_git", git)
+ with pytest.raises(ValueError, match="single-link regular"):
+ verify.main()
+ assert (repository / "fixture_model.py").read_bytes() == before
+ assert not (tmp_path / "apply-state").exists()
+ assert not any(command[0] == "apply" for command in calls)
+
+
+def git_poison(tmp_path, monkeypatch, source):
+ """All poison destinations and marker scripts are task-owned, never user config."""
+ marker = tmp_path / "unwanted-execution"
+ helper = tmp_path / "unwanted-helper"
+ helper.write_text("#!/bin/sh\nprintf unwanted >> " + shlex.quote(str(marker)) + "\nexit 73\n")
+ helper.chmod(0o700)
+ template = tmp_path / "hostile-template"
+ (template / "hooks").mkdir(parents=True)
+ for name in ("post-checkout", "post-index-change"):
+ (template / "hooks" / name).write_bytes(helper.read_bytes())
+ (template / "hooks" / name).chmod(0o700)
+ configuration = tmp_path / "hostile-config"
+ configuration.write_text(
+ f'[init]\n\ttemplateDir = "{template}"\n[core]\n\thooksPath = "{template / "hooks"}"\n'
+ f'\tfsmonitor = "{helper}"\n[filter "hostile"]\n\tclean = "{helper}"\n'
+ f'\tsmudge = "{helper}"\n[diff "hostile"]\n\tcommand = "{helper}"\n\ttextconv = "{helper}"\n'
+ f'[credential]\n\thelper = "!{helper}"\n',
+ )
+ if source in ("global", "system"):
+ monkeypatch.setenv("GIT_CONFIG_" + source.upper(), str(configuration))
+ if source == "system":
+ monkeypatch.setenv("GIT_CONFIG_NOSYSTEM", "0")
+ elif source == "count":
+ monkeypatch.setenv("GIT_CONFIG_COUNT", "3")
+ for index, (key, value) in enumerate((
+ ("init.templateDir", str(template)), ("core.fsmonitor", str(helper)),
+ ("filter.hostile.clean", str(helper)))):
+ monkeypatch.setenv(f"GIT_CONFIG_KEY_{index}", key)
+ monkeypatch.setenv(f"GIT_CONFIG_VALUE_{index}", value)
+ elif source == "parameters":
+ monkeypatch.setenv("GIT_CONFIG_PARAMETERS", " ".join(shlex.quote(value) for value in (
+ f"init.templateDir={template}", f"core.hooksPath={template / 'hooks'}",
+ f"filter.hostile.clean={helper}", f"core.fsmonitor={helper}",
+ )))
+ else:
+ assert source == "environment"
+ for name, value in {
+ "GIT_TEMPLATE_DIR": str(template), "GIT_EXEC_PATH": str(tmp_path),
+ "GIT_EXTERNAL_DIFF": str(helper), "GIT_SSH_COMMAND": str(helper),
+ "GIT_ASKPASS": str(helper), "SSH_ASKPASS": str(helper),
+ "GIT_DIR": str(tmp_path / "wrong-git-dir"), "GIT_WORK_TREE": str(tmp_path / "wrong-worktree"),
+ "GIT_CONFIG": str(configuration), "GIT_CONFIG_SYSTEM": str(configuration),
+ "GIT_OBJECT_DIRECTORY": str(tmp_path / "wrong-objects"), "GIT_INDEX_FILE": str(tmp_path / "wrong-index"),
+ "GIT_ALTERNATE_OBJECT_DIRECTORIES": str(tmp_path / "wrong-alternates"),
+ }.items():
+ monkeypatch.setenv(name, value)
+ return marker, helper, template
+
+
[email protected]("source", ["global", "system", "count", "parameters", "environment"])
[email protected]("consumer", ["checkout", "export", "apply"])
+def test_actual_git_consumers_ignore_ambient_execution_authority(tmp_path, monkeypatch, source, consumer):
+ repository, receipt = frozen_repository(tmp_path)
+ expected = apply_fixture(repository, receipt, tmp_path, monkeypatch) if consumer == "apply" else None
+ marker, helper, template = git_poison(tmp_path, monkeypatch, source)
+ environment_before = dict(os.environ)
+ fresh = tmp_path / "fresh-init"
+ safe_git(fresh, "init")
+ assert not (fresh / ".git/hooks").exists()
+ # Even manually placed local hooks are disabled at their actual consumer.
+ hooks = repository / ".git/hooks"
+ hooks.mkdir()
+ for name in ("post-checkout", "post-index-change"):
+ (hooks / name).write_bytes(helper.read_bytes())
+ (hooks / name).chmod(0o700)
+ (repository / ".git/info").mkdir(exist_ok=True)
+ (repository / ".git/info/attributes").write_text("fixture_model.py filter=hostile diff=hostile\n")
+ template_before = source_digest(template)
+ if consumer == "checkout":
+ (repository / "fixture_model.py").unlink()
+ safe_git(repository, "checkout", "--", "fixture_model.py")
+ safe_git(repository, "checkout", "--detach", receipt["avibe_fixture_base"])
+ assert (repository / "fixture_model.py").is_file()
+ elif consumer == "export":
+ (repository / "fixture_model.py").write_text("dirty, not archived\n")
+ exported, identity = export_fixture(repository, tmp_path, receipt)
+ assert identity["commit"] == receipt["avibe_fixture_base"]
+ assert "frozen" in (exported / "fixture_model.py").read_text()
+ else:
+ verify.main()
+ assert (repository / "fixture_model.py").read_bytes() == expected
+ assert not marker.exists() and source_digest(template) == template_before
+ assert dict(os.environ) == environment_before
+
+
+ "init.templateDir", "include.path", "includeIf.gitdir:/.path", "core.hooksPath",
+ "core.fsmonitor", "core.worktree", "core.gitProxy", "core.sshCommand",
+ "core.attributesFile", "core.excludesFile", "diff.external", "diff.hostile.command",
+ "diff.hostile.textconv", "filter.hostile.clean", "filter.hostile.smudge", "filter.hostile.process",
+ "credential.helper", "url.hostile.insteadOf", "remote.origin.uploadpack",
+ "remote.origin.vcs", "remote.origin.proxy", "http.proxy", "submodule.recurse",
+ "extensions.worktreeConfig",
+])
[email protected]("consumer", ["export", "apply"])
+def test_actual_git_consumers_refuse_local_executable_or_redirecting_config(
+ tmp_path, monkeypatch, key, consumer):
+ repository, receipt = frozen_repository(tmp_path)
+ if consumer == "apply":
+ apply_fixture(repository, receipt, tmp_path, monkeypatch)
+ marker, helper, _ = git_poison(tmp_path, monkeypatch, "global")
+ # Fixture construction itself has a finite clean environment.
+ env = {"PATH": "/usr/bin:/bin", "GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": "/dev/null"}
+ value = "true" if key in ("extensions.worktreeConfig", "submodule.recurse") else str(helper)
+ subprocess.run(
+ ["/usr/bin/git", "config", "--file", str(repository / ".git/config"), key, value],
+ env=env, check=True, stdin=subprocess.DEVNULL, capture_output=True, timeout=5,
+ )
+ before = source_digest(repository)
+ with pytest.raises((ValueError, subprocess.CalledProcessError)):
+ if consumer == "export":
+ export_fixture(repository, tmp_path, receipt)
+ else:
+ verify.main()
+ assert not marker.exists() and source_digest(repository) == before
+ assert not list(tmp_path.glob("avibe-fixture-*"))
+
+
[email protected]("failure", ["dirty", "untracked", "base", "input", "candidate"])
+def test_shared_git_boundary_preserves_actual_apply_identity_refusals(tmp_path, monkeypatch, failure):
+ repository, receipt = frozen_repository(tmp_path)
+ apply_fixture(repository, receipt, tmp_path, monkeypatch)
+ if failure == "dirty":
+ (repository / "fixture_model.py").write_text("preserve a peer edit\n")
+ elif failure == "untracked":
+ (repository / "peer").write_text("preserve unrelated work\n")
+ elif failure == "input":
+ (repository / "facts/config.json").write_text("changed input")
+ elif failure == "base":
+ record = json.loads((verify.HERE / "inputs.json").read_text())
+ record["source_sha"] = "0" * 40
+ (verify.HERE / "inputs.json").write_text(json.dumps(record))
+ else:
+ verify.main()
+ (repository / "fixture_model.py").write_text("not the maintained candidate\n")
+ before = source_digest(repository)
+ with pytest.raises(RuntimeError):
+ verify.verify_candidate(repository) if failure == "candidate" else verify.main()
+ assert source_digest(repository) == before
+
+
+def test_documented_fetch_uses_shared_command_local_boundary_without_network(tmp_path, monkeypatch):
+ task = tmp_path / "task"
+ (task / "recipe").mkdir(parents=True)
+ repository = task / "source"
+ safe_git(repository, "init")
+ readme = (Path(__file__).parent / "README.md").read_text()
+ block = next(block for block in re.findall(r"```sh\n(.*?)\n```", readme, re.S)
+ if '"fetch", "--depth=1"' in block)
+ code = block.split("<<'PY'\n", 1)[1].split("\nPY", 1)[0]
+ check_output = subprocess.check_output
+ calls = []
+
+ def command(argv, **kwargs):
+ assert argv[0] == "/usr/bin/git" and kwargs["env"]["GIT_CONFIG_COUNT"] == "0"
+ if "config" in argv:
+ return check_output(argv, **kwargs)
+ assert kwargs["env"]["GIT_CONFIG_GLOBAL"] == "/dev/null"
+ assert "protocol.allow=never" in argv and "protocol.https.allow=always" in argv
+ calls.append(argv[argv.index(str(repository)) + 1:])
+ return b"" # Sole finite process seam: never execute fetch/transport.
+
+ monkeypatch.setattr(subprocess, "check_output", command)
+ monkeypatch.setattr(sys, "argv", ["-", str(task)])
+ monkeypatch.setattr(sys, "path", list(sys.path))
+ exec(compile(code, "<maintained fetch caller; transport forbidden>", "exec"), {})
+ assert calls == [
+ ["fetch", "--no-recurse-submodules", "--depth=1",
+ "https://github.com/router-for-me/CLIProxyAPI.git", "2a6b87aca083a5bf498ac1f68a1b636c500d7aaa"],
+ ["checkout", "--detach", "FETCH_HEAD"],
+ ]
+
+
[email protected]("entry", ["preparation", "fetch", "archive", "export", "apply", "storage", "parent", "phase"])
[email protected]("shadow", ["cwd", "pythonpath", "user-site", "path"])
+def test_documented_python_starts_isolated_before_recipe_import(tmp_path, entry, shadow):
+ """Actual shell/interpreter startup; fake recipe stops before all work/sudo.
+
+ HOST-only adaptation: the documented absolute Linux interpreter is replaced
+ by this installed base interpreter; the public sudo prefix is not executed.
+ Neither this test nor the body-consuming tests claim Linux custody evidence.
+ """
+ readme = (Path(__file__).parent / "README.md").read_text()
+ blocks = re.findall(r"```sh\n(.*?)\n```", readme, re.S)
+ task = tmp_path / "task"
+ recipe = task / "recipe"
+ recipe.mkdir(parents=True)
+ cwd, pythonpath, home, binary = [tmp_path / name for name in ("cwd", "pythonpath", "home", "bin")]
+ for path in (cwd, pythonpath, home, binary):
+ path.mkdir()
+ marker = tmp_path / "shadow-executed"
+ poison = f"from pathlib import Path; Path({str(marker)!r}).write_text('shadow'); raise SystemExit(73)\n"
+ env = {name: str(tmp_path / ("original-" + name)) for name in STORAGE_ENV}
+ env.update(HOME=str(home), PATH="/usr/bin:/bin", TMPDIR=str(tmp_path),
+ engine_task=str(task), recipe_source=str(recipe), fixture_root=str(task / "fixtures"),
+ avibe_checkout=str(tmp_path / "never-opened-repository"), caller_storage_sha256="not-used")
+ if shadow in ("cwd", "pythonpath"):
+ directory = cwd if shadow == "cwd" else pythonpath
+ for name in ("subprocess", "pathlib", "sitecustomize"):
+ (directory / (name + ".py")).write_text(poison)
+ if shadow == "pythonpath":
+ env["PYTHONPATH"] = str(directory)
+ elif shadow == "user-site":
+ userbase = tmp_path / "usersite"
+ env["PYTHONUSERBASE"] = str(userbase)
+ # Ask the same trusted HOST interpreter only for its task-local site
+ # location. -I prevents activation during this read-only calculation.
+ result = subprocess.run(
+ [sys._base_executable, "-I", "-B", "-c", "import site; print(site.getusersitepackages())"],
+ env=env, capture_output=True, text=True, check=True, timeout=5,
+ )
+ user_site = Path(result.stdout.strip())
+ assert user_site.is_relative_to(userbase)
+ user_site.mkdir(parents=True)
+ (user_site / "usercustomize.py").write_text(poison)
+ (user_site / "startup.pth").write_text("import pathlib; pathlib.Path(" + repr(str(marker)) + ").touch()\n")
+ else:
+ fake = binary / "python3"
+ fake.write_text("#!/bin/sh\nprintf shadow > " + shlex.quote(str(marker)) + "\nexit 74\n")
+ fake.chmod(0o700)
+ env["PATH"] = str(binary) + ":/usr/bin:/bin"
+ # These finite fake import consumers record the unmodified original storage
+ # and flags, then stop. The actual admission/Git/parent consumers are tested
+ # separately above and in the state/namespace suites.
+ fake_module = (
+ "import json, os, sys\n"
+ f"names = {STORAGE_ENV!r}\n"
+ "def stop(*args, **kwargs):\n"
+ " print('STARTUP=' + json.dumps({'storage': {k: os.environ.get(k) for k in names},\n"
+ " 'isolated': sys.flags.isolated, 'user_site': sys.flags.no_user_site,\n"
+ " 'bytecode': sys.dont_write_bytecode}), file=sys.stderr, flush=True)\n"
+ " raise SystemExit(41)\n"
+ "preparation_directories = safe_git = verify_go = export_fixture = storage_context = main = stop\n"
+ "PHASES = {}\n"
+ )
+ for name in ("isolation", "execution_inputs", "fixture", "verify", "namespace", "budgets"):
+ (recipe / (name + ".py")).write_text(fake_module)
+ (recipe / "inputs.json").write_text("{}")
+ (recipe / "prerequisites.json").write_text('{"linux_arm64_go": {}}')
+ selected = {
+ "preparation": blocks[0], "fetch": blocks[1], "archive": blocks[2],
+ "export": next(block for block in blocks if "fixture_root=$(" in block),
+ "apply": next(block for block in blocks if "import verify; verify.main()" in block),
+ "storage": next(block for block in blocks if "caller_storage_sha256=$(" in block),
+ "phase": next(block for block in blocks if "run_phase() {" in block),
+ }
+ parent = selected["storage"].split("/usr/bin/sudo -n ", 1)[1]
+ selected["parent"] = parent
+ block = selected[entry].replace("/usr/bin/python3", shlex.quote(sys._base_executable))
+ # Every selected body must stop before sudo. The one parent startup case
+ # omits only the privilege prefix and invokes a task-only fake namespace.
+ result = subprocess.run(
+ ["/bin/sh", "-c", block], cwd=cwd, env=env, stdin=subprocess.DEVNULL,
+ capture_output=True, text=True, close_fds=True, timeout=10,
+ )
+ assert result.returncode == (1 if entry in ("preparation", "export", "storage") else 41), result.stderr
+ records = [json.loads(line.removeprefix("STARTUP=")) for line in result.stderr.splitlines()
+ if line.startswith("STARTUP=")]
+ assert records == [{"storage": {name: env[name] for name in STORAGE_ENV},
+ "isolated": 1, "user_site": 1, "bytecode": True}]
+ assert not marker.exists()
+ assert sorted(path.name for path in task.iterdir()) == ["recipe"]
+ assert not list(recipe.glob("*.pyc")) and not (recipe / "__pycache__").exists()
diff --git a/patches/cliproxyapi/test_state_boundaries.py b/patches/cliproxyapi/test_state_boundaries.py
new file mode 100644
index 000000000..741bc429a
--- /dev/null
+++ b/patches/cliproxyapi/test_state_boundaries.py
@@ -0,0 +1,860 @@
+"""Actual pre-write consumers with fake homes and task-only sentinels."""
+
+import json
+import os
+from pathlib import Path
+import re
+import shutil
+import stat
+import subprocess
+import sys
+from types import SimpleNamespace
+
+import pytest
+
+import fixture
+import isolation
+import verify
+import wire_matrix
+
+
+def fake_home(tmp_path, monkeypatch):
+ home = tmp_path / "fake-home"
+ home.mkdir()
+ monkeypatch.setattr(isolation.pwd, "getpwuid", lambda _uid: SimpleNamespace(pw_dir=str(home)))
+ for name in (".avibe", ".vibe_remote", ".codex", ".claude"):
+ (home / name).mkdir()
+ (home / name / "sentinel").write_bytes(b"unchanged test-only user state")
+ return home
+
+
[email protected]("name", [".avibe", ".vibe_remote", ".codex", ".claude"])
[email protected]("consumer", ["environment", "sandbox", "export", "verify", "wire", "engine-seam"])
[email protected]("alias", [False, True])
+def test_actual_callers_refuse_before_any_protected_setup_write(tmp_path, fake_home, monkeypatch, name, consumer, alias):
+ root = fake_home / name / "must-not-create"
+ if alias:
+ root = tmp_path / "task-alias"
+ root.symlink_to(fake_home / name / "must-not-create")
+ before = fixture.source_digest(fake_home)
+ if consumer == "environment":
+ action = lambda: isolation.isolated_environment(root)
+ elif consumer == "sandbox":
+ action = lambda: isolation.sandbox_prefix(root)
+ elif consumer == "export":
+ action = lambda: fixture.export_fixture(tmp_path / "not-a-repository", root, {})
+ elif consumer == "engine-seam":
+ action = lambda: wire_matrix.FrozenEngine(None, root, None, None)
+ elif consumer == "verify":
+ monkeypatch.setattr(sys, "argv", ["verify.py", "build", "--state", str(root),
+ "--source", str(tmp_path / "not-a-source")])
+ action = verify.main
+ else:
+ monkeypatch.setattr(sys, "argv", ["wire_matrix.py", "--state", str(root), "--binary", "/absent",
+ "--fixture", "/absent", "--fixture-sha256", "0" * 64])
+ action = wire_matrix.main
+ with pytest.raises(ValueError, match="protected user state"):
+ action()
+ assert fixture.source_digest(fake_home) == before
+ assert not (fake_home / name / "must-not-create").exists()
+
+
+def test_protected_apply_source_refuses_before_git_or_patch(tmp_path, fake_home, monkeypatch):
+ monkeypatch.setattr(sys, "argv", [
+ "verify.py", "apply", "--state", str(tmp_path / "task-state"),
+ "--source", str(fake_home / ".avibe" / "source"),
+ ])
+ with pytest.raises(ValueError, match="protected user state"):
+ verify.main()
+ assert not (tmp_path / "task-state").exists()
+
+
+def test_environment_aliases_are_all_validated_before_first_mkdir(tmp_path, fake_home):
+ root = tmp_path / "task-state"
+ root.mkdir()
+ (root / "tmp").symlink_to(fake_home / ".codex")
+ with pytest.raises(ValueError, match="protected user state"):
+ isolation.isolated_environment(root)
+ assert sorted(path.name for path in root.iterdir()) == ["tmp"]
+ assert (fake_home / ".codex/sentinel").read_bytes() == b"unchanged test-only user state"
+
+
[email protected]("which", ["home", "ancestor", "root", "tmp", "users"])
+def test_broad_write_roots_refuse(tmp_path, fake_home, which):
+ root = {"home": fake_home, "ancestor": tmp_path, "root": Path("/"),
+ "tmp": Path("/tmp"), "users": Path("/Users")}[which]
+ with pytest.raises(ValueError, match="dedicated, narrow"):
+ isolation.isolated_environment(root)
+
+
+def test_ordinary_dedicated_temporary_state_still_works(tmp_path, fake_home):
+ root = tmp_path / "allowed-task"
+ cache = tmp_path / "allowed-cache"
+ environment = isolation.isolated_environment(root, cache=cache)
+ assert Path(environment["HOME"]) == root / "home"
+ assert Path(environment["GOCACHE"]) == cache / "cache"
+ assert environment["GOTOOLCHAIN"] == "local"
+ assert set(path.name for path in root.iterdir()) == {"home", "tmp", "config", "data"}
+
+
[email protected]("root", ["/home/user/task", "/root/task", "/Users/user/task", "/tmp", "/var/tmp", "/"])
+def test_privileged_domain_rejects_non_temporary_or_broad_roots(monkeypatch, root):
+ # Pure virtual Linux path classification; never create/read those surfaces.
+ monkeypatch.setattr(Path, "resolve", lambda path, **_kw: path)
+ monkeypatch.setattr(isolation.pwd, "getpwuid", lambda _uid: SimpleNamespace(pw_dir="/home/user"))
+ with pytest.raises(ValueError):
+ isolation.validate_temporary_root(Path(root))
+
+
[email protected]("root", ["/tmp/allocated-task", "/var/tmp/allocated/task"])
+def test_privileged_domain_accepts_narrow_linux_temporary_roots(monkeypatch, root):
+ monkeypatch.setattr(Path, "resolve", lambda path, **_kw: path)
+ monkeypatch.setattr(isolation.pwd, "getpwuid", lambda _uid: SimpleNamespace(pw_dir="/home/user"))
+ assert isolation.validate_temporary_root(Path(root)) == Path(root)
+
+
[email protected]("target", ["/home/absent-task", "/root/absent-task", "/Users/absent-task"])
+def test_symlinked_privileged_root_cannot_admit_a_hidden_surface(tmp_path, target):
+ link = tmp_path / "looks-temporary"
+ link.symlink_to(target)
+ with pytest.raises(ValueError):
+ isolation.validate_temporary_root(link)
+ assert link.is_symlink()
+
+
+def test_privileged_validation_also_protects_invoking_users_aliased_state(tmp_path, monkeypatch):
+ invoking_home, root_home = tmp_path / "invoking-home", tmp_path / "root-home"
+ invoking_home.mkdir()
+ root_home.mkdir()
+ actual_data = tmp_path / "looks-like-temporary-data"
+ actual_data.mkdir()
+ (actual_data / "sentinel").write_bytes(b"invoking user's fake protected data")
+ (invoking_home / ".avibe").symlink_to(actual_data)
+ monkeypatch.setattr(isolation.os, "getuid", lambda: 0)
+ monkeypatch.setattr(isolation.pwd, "getpwuid", lambda uid: SimpleNamespace(
+ pw_dir=str(invoking_home if uid == 501 else root_home),
+ ))
+ context = isolation.StorageContext.capture(uid=501, environment={}).with_root_identity()
+ with pytest.raises(ValueError, match="protected user state"):
+ isolation.validate_state_root(actual_data / "evidence", owner_uid=501, context=context)
+ assert list(actual_data.iterdir()) == [actual_data / "sentinel"]
+
+
[email protected]("name", [".avibe", ".vibe_remote", ".codex", ".claude"])
+def test_write_root_cannot_contain_protected_symlink_target(tmp_path, fake_home, name):
+ root = tmp_path / "apparently-task-owned"
+ target = root / "protected-target"
+ target.mkdir(parents=True)
+ (target / "sentinel").write_bytes(b"fake protected state must remain unchanged")
+ protected = fake_home / name
+ # Preserve the original fake home fixture while substituting only its alias.
+ protected.rename(fake_home / (name + "-preserved"))
+ protected.symlink_to(target)
+ before = fixture.source_digest(root)
+ with pytest.raises(ValueError, match="protected user state"):
+ isolation.isolated_environment(root)
+ assert fixture.source_digest(root) == before
+
+
+def original_storage(tmp_path, fake_home, monkeypatch):
+ for name in (*isolation.STORAGE_ENV, "SUDO_UID", "SUDO_GID"):
+ monkeypatch.delenv(name, raising=False)
+ return SimpleNamespace(home=fake_home, parent=tmp_path / "configured-storage")
+
+
[email protected]("variable", isolation.STORAGE_ENV)
[email protected]("shape", ["equal", "descendant", "alias", "containing"])
[email protected]("consumer", ["environment", "sandbox", "export", "verify", "wire", "engine-seam"])
+def test_configured_storage_is_rejected_by_every_public_prewrite_consumer(
+ tmp_path, original_storage, monkeypatch, variable, shape, consumer):
+ boundary = original_storage.parent / variable
+ boundary.mkdir(parents=True)
+ (boundary / "sentinel").write_bytes(b"fake production storage")
+ monkeypatch.setenv(variable, str(boundary))
+ descendant = boundary / (".codex/evidence" if variable == "HOME" else "evidence")
+ root = boundary if shape == "equal" else descendant
+ if shape == "containing":
+ root = original_storage.parent
+ elif shape == "alias":
+ root = tmp_path / "looks-like-task"
+ root.symlink_to(descendant)
+ before = fixture.source_digest(original_storage.parent)
+ monkeypatch.setattr(fixture, "safe_git", lambda *_a, **_kw: pytest.fail("Git reached."))
+ if consumer == "environment":
+ action = lambda: isolation.isolated_environment(root)
+ elif consumer == "sandbox":
+ action = lambda: isolation.sandbox_prefix(root)
+ elif consumer == "export":
+ action = lambda: fixture.export_fixture(tmp_path / "absent-repository", root, {})
+ elif consumer == "engine-seam":
+ action = lambda: wire_matrix.FrozenEngine(None, root, None, None)
+ elif consumer == "verify":
+ monkeypatch.setattr(sys, "argv", ["verify.py", "build", "--state", str(root), "--source", "/absent"])
+ action = verify.main
+ else:
+ monkeypatch.setattr(sys, "argv", [
+ "wire_matrix.py", "--state", str(root), "--binary", "/absent",
+ "--fixture", "/absent", "--fixture-sha256", "0" * 64,
+ ])
+ action = wire_matrix.main
+ with pytest.raises(ValueError):
+ action()
+ assert fixture.source_digest(original_storage.parent) == before
+
+
[email protected]("variable", isolation.STORAGE_ENV)
[email protected]("shape", ["equal", "descendant", "alias", "containing"])
+def test_configured_shared_cache_refuses_before_even_output_creation(
+ tmp_path, original_storage, monkeypatch, variable, shape):
+ boundary = original_storage.parent / variable
+ boundary.mkdir(parents=True)
+ monkeypatch.setenv(variable, str(boundary))
+ cache = boundary if shape == "equal" else boundary / (".avibe/cache" if variable == "HOME" else "cache")
+ if shape == "containing":
+ cache = boundary.parent
+ elif shape == "alias":
+ alias = tmp_path / "cache-alias"
+ alias.symlink_to(cache)
+ cache = alias
+ output = tmp_path / "exclusive-output"
+ with pytest.raises(ValueError):
+ isolation.isolated_environment(output, cache=cache)
+ assert not output.exists()
+ assert list(boundary.iterdir()) == []
+
+
[email protected]("variable", isolation.STORAGE_ENV)
+def test_configured_alias_target_cannot_be_enclosed_by_a_write_root(tmp_path, original_storage, monkeypatch, variable):
+ output = tmp_path / "apparently-owned"
+ target = output / "protected-target"
+ target.mkdir(parents=True)
+ alias = tmp_path / "configured-alias"
+ alias.symlink_to(target)
+ monkeypatch.setenv(variable, str(alias))
+ with pytest.raises(ValueError):
+ isolation.isolated_environment(output)
+ assert list(output.iterdir()) == [target]
+
+
[email protected]("variable", isolation.STORAGE_ENV)
[email protected]("invalid", ["relative", "~/not-expanded", "/tmp/../other"])
+def test_invalid_configuration_refuses_before_any_setup(tmp_path, original_storage, monkeypatch, variable, invalid):
+ monkeypatch.setenv(variable, invalid)
+ root = tmp_path / "never-created"
+ with pytest.raises(ValueError) as refused:
+ isolation.isolated_environment(root)
+ assert invalid not in str(refused.value)
+ assert not root.exists()
+
+
[email protected]("override_home", [False, True])
[email protected]("empty", [False, True])
+def test_unset_empty_defaults_and_both_home_identities(tmp_path, original_storage, monkeypatch, override_home, empty):
+ home = tmp_path / "effective-home" if override_home else original_storage.home
+ if override_home:
+ monkeypatch.setenv("HOME", str(home))
+ if empty:
+ for name in isolation.STORAGE_ENV[1:]:
+ monkeypatch.setenv(name, "")
+ context = isolation.storage_context()
+ for protected_home in (original_storage.home, home):
+ with pytest.raises(ValueError):
+ context.validate(protected_home)
+ for name in isolation.PRODUCT_DIRS:
+ with pytest.raises(ValueError):
+ context.validate(protected_home / name / "task")
+ for default in isolation.XDG_DEFAULTS.values():
+ with pytest.raises(ValueError):
+ context.validate(home / default / "task")
+ assert not any(str(path).startswith("/run/user/") for path in context.protected)
+ # An ordinary dedicated directory outside protected locations still works.
+ assert isolation.isolated_environment(tmp_path / "task")["GOENV"] == "off"
+
+
+def test_invalid_path_values_do_not_leak_and_empty_home_uses_passwd(original_storage):
+ for invalid in ("\0private", "/" + "x" * 4097):
+ with pytest.raises(ValueError) as refused:
+ isolation.StorageContext.capture(environment={"HOME": invalid})
+ assert invalid not in str(refused.value)
+ empty = isolation.StorageContext.capture(environment={"HOME": ""})
+ unset = isolation.StorageContext.capture(environment={})
+ assert empty.homes == unset.homes and empty.protected == unset.protected
+ assert empty.fingerprint() != unset.fingerprint() # Detect environment loss in transit.
+
+
+def test_macos_read_policy_uses_all_original_configured_and_canonical_locations(tmp_path, original_storage, monkeypatch):
+ for name in isolation.STORAGE_ENV:
+ target = original_storage.parent / name
+ target.mkdir(parents=True)
+ alias = tmp_path / ("alias-" + name)
+ alias.symlink_to(target)
+ monkeypatch.setenv(name, str(alias))
+ monkeypatch.setattr(sys, "platform", "darwin")
+ original_is_file = Path.is_file
+ monkeypatch.setattr(Path, "is_file", lambda path: True if str(path) == "/usr/bin/sandbox-exec" else original_is_file(path))
+ context = isolation.storage_context()
+ prefix = isolation.sandbox_prefix(tmp_path / "task", required_inputs=(tmp_path / "staged-input",))
+ assert prefix[:2] == ["/usr/bin/sandbox-exec", "-p"]
+ assert "(deny default)" in prefix[2] and "(allow default)" not in prefix[2]
+ assert set(re.findall(r"\(allow ([^\s()]+)", prefix[2])) == {
+ "file-read*", "file-write*", "process-exec", "process-fork",
+ }
+ for boundary in (*context.homes, *context.protected):
+ assert f"(deny file-read* (subpath {json.dumps(str(boundary))}))" in prefix[2]
+
+
[email protected]("variable", isolation.STORAGE_ENV)
+def test_actual_process_seam_refuses_protected_config_before_write_or_launch(
+ tmp_path, original_storage, monkeypatch, variable):
+ boundary = original_storage.parent / variable
+ boundary.mkdir(parents=True)
+ monkeypatch.setenv(variable, str(boundary))
+ protected = boundary / (".avibe" if variable == "HOME" else "engine")
+ engine = object.__new__(wire_matrix.FrozenEngine)
+ engine.binary = tmp_path / "not-executed"
+ engine.state = tmp_path / "safe-state"
+ engine.store = SimpleNamespace(root=protected)
+ monkeypatch.setitem(sys.modules, "config.atomic_io", SimpleNamespace(
+ write_atomic=lambda *_a, **_kw: pytest.fail("Atomic config write reached."),
+ ))
+ monkeypatch.setattr(wire_matrix.subprocess, "Popen", lambda *_a, **_kw: pytest.fail("Process reached."))
+ with pytest.raises(ValueError):
+ engine.launch([str(engine.binary), "-config", str(protected / "config.yaml")], env={})
+ assert not engine.state.exists() and list(boundary.iterdir()) == []
+
+
+def private_storage(tmp_path, original_storage, monkeypatch):
+ original = original_storage.parent / "original-xdg"
+ original.mkdir(parents=True)
+ context = isolation.StorageContext.capture(environment={"XDG_CONFIG_HOME": str(original)})
+ root = tmp_path / "task"
+ output, cache = root / "runs/one.json", root / "shared-cache"
+ output.mkdir(parents=True, mode=0o750)
+ output.chmod(0o750)
+ cache.mkdir()
+ uid, gid = os.getuid(), os.getgid()
+ inner = {"mnt": "mnt:[11]", "net": "net:[12]", "pid": "pid:[13]", "ipc": "ipc:[14]"}
+ proof = {
+ "uid": uid, "gid": gid, "root": str(root), "output": str(output), "state": str(cache),
+ "receipt": "one.json", "namespaces": inner,
+ "outer_namespaces": {"mnt": "mnt:[1]", "net": "net:[2]", "pid": "pid:[3]", "ipc": "ipc:[4]"},
+ "keyring_boundary": isolation.keyring_identity(),
+ "storage_context": context.record(), "storage_sha256": context.fingerprint(),
+ }
+ marker = tmp_path / "parent-proof.json"
+ marker.write_text(json.dumps(proof))
+ marker.chmod(0o644)
+ marker_inode = marker.stat().st_ino
+ real_fstat, real_readlink, real_read_text = os.fstat, os.readlink, Path.read_text
+ status = {**{name: "0" * 16 for name in ("CapInh", "CapPrm", "CapEff", "CapBnd", "CapAmb")},
+ "NoNewPrivs": "1", "Seccomp": "2"}
+ state = SimpleNamespace(root=root, output=output, cache=cache, original=original,
+ proof=proof, marker=marker, status=status, root_owned=True)
+
+ def parent_owned(fd):
+ info = real_fstat(fd)
+ if info.st_ino == marker_inode and state.root_owned:
+ values = list(info)
+ values[4] = 0
+ return os.stat_result(values)
+ return info
+
+ def read_status(path, *args, **kwargs):
+ if str(path) == "/proc/self/status":
+ return "\n".join(f"{name}: {value}" for name, value in status.items())
+ return real_read_text(path, *args, **kwargs)
+
+ def namespace_link(path, *args, **kwargs):
+ if str(path).startswith("/proc/self/ns/"):
+ return inner[Path(path).name]
+ return real_readlink(path, *args, **kwargs)
+
+ monkeypatch.setattr(isolation, "PROOF_PATH", marker)
+ monkeypatch.setattr(sys, "platform", "linux")
+ monkeypatch.setattr(os, "fstat", parent_owned)
+ monkeypatch.setattr(os, "readlink", namespace_link)
+ monkeypatch.setattr(Path, "read_text", read_status)
+ # These are task-generated values, not the original invoking user's roots.
+ monkeypatch.setenv("HOME", str(output / "home"))
+ for name in isolation.STORAGE_ENV[1:]:
+ monkeypatch.setenv(name, str(cache / name))
+ return state
+
+
+def test_valid_private_proof_keeps_generated_home_xdg_cache_usable(private_storage):
+ state = private_storage
+ environment = isolation.isolated_environment(state.output, cache=state.cache)
+ assert environment["HOME"] == str(state.output / "home")
+ assert environment["GOCACHE"] == str(state.cache / "cache")
+ assert isolation.validate_state_root(state.output / "wire") == state.output / "wire"
+ with pytest.raises(ValueError):
+ isolation.validate_state_root(state.original / "must-not-create")
+ public = json.dumps(isolation.namespace_receipt())
+ assert str(state.original) not in public and "storage_context" not in public
+ assert state.proof["storage_sha256"] in public
+
+
[email protected]("failure", [
+ "missing", "caller-owned", "symlink", "writable-proof", "linked-proof",
+ "same-namespace", "missing-namespace", "wrong-uid", "capability", "privilege",
+ "wrong-output", "output-mode", "cache-overlap", "context-hash", "empty-context",
+])
+def test_forged_or_incomplete_task_context_never_waives_production_admission(
+ private_storage, failure):
+ state = private_storage
+ if failure == "missing":
+ state.marker.unlink()
+ elif failure == "caller-owned":
+ state.root_owned = False
+ elif failure == "symlink":
+ real = state.marker.with_suffix(".original")
+ state.marker.rename(real)
+ state.marker.symlink_to(real)
+ elif failure == "writable-proof":
+ state.marker.chmod(0o666)
+ elif failure == "linked-proof":
+ os.link(state.marker, state.marker.with_suffix(".other"))
+ elif failure == "same-namespace":
+ state.proof["outer_namespaces"]["net"] = state.proof["namespaces"]["net"]
+ elif failure == "missing-namespace":
+ state.proof["outer_namespaces"].pop("pid")
+ elif failure == "wrong-uid":
+ state.proof["uid"] += 1
+ elif failure == "capability":
+ state.status["CapBnd"] = "1"
+ elif failure == "privilege":
+ state.status["NoNewPrivs"] = "0"
+ elif failure == "wrong-output":
+ state.proof["output"] = str(state.cache)
+ elif failure == "output-mode":
+ state.output.chmod(0o770)
+ elif failure == "cache-overlap":
+ state.proof["state"] = str(state.output)
+ elif failure == "context-hash":
+ state.proof["storage_sha256"] = "0" * 64
+ else:
+ state.proof["storage_context"] = {}
+ if failure not in ("missing", "symlink"):
+ state.marker.write_text(json.dumps(state.proof))
+ before = fixture.source_digest(state.root)
+ with pytest.raises((OSError, RuntimeError, ValueError)):
+ isolation.isolated_environment(state.output, cache=state.cache)
+ assert fixture.source_digest(state.root) == before
+
+
+def test_ambient_safe_root_claim_does_not_waive_real_storage(tmp_path, original_storage, monkeypatch):
+ protected = original_storage.parent
+ monkeypatch.setenv("XDG_CONFIG_HOME", str(protected))
+ monkeypatch.setenv("AVIBE_STORAGE_CONTEXT", '{"protected": [], "task": "/tmp"}')
+ with pytest.raises(ValueError):
+ isolation.isolated_environment(protected / "output")
+ assert not protected.exists()
+
+
[email protected]("failure", [
+ "missing-ipc", "same-ipc", "extra-namespace", "invalid-prefix", "missing-filter", "wrong-program",
+ "wrong-abi", "extra-filter-field", "missing-seccomp", "seccomp-disabled", "seccomp-strict",
+ "missing-capability", "invalid-capability",
+])
+def test_live_private_proof_requires_exact_ipc_filter_and_privilege_binding(private_storage, failure):
+ state = private_storage
+ if failure == "missing-ipc":
+ state.proof["namespaces"].pop("ipc")
+ elif failure == "same-ipc":
+ state.proof["outer_namespaces"]["ipc"] = state.proof["namespaces"]["ipc"]
+ elif failure == "extra-namespace":
+ state.proof["namespaces"]["user"] = "user:[15]"
+ elif failure == "invalid-prefix":
+ state.proof["outer_namespaces"]["ipc"] = "mnt:[4]"
+ elif failure == "missing-filter":
+ state.proof.pop("keyring_boundary")
+ elif failure in ("wrong-program", "wrong-abi", "extra-filter-field"):
+ field = {"wrong-program": "program_sha256", "wrong-abi": "abi", "extra-filter-field": "installed"}[failure]
+ state.proof["keyring_boundary"][field] = "untrusted"
+ elif failure == "missing-seccomp":
+ state.status.pop("Seccomp")
+ elif failure in ("seccomp-disabled", "seccomp-strict"):
+ state.status["Seccomp"] = "0" if failure == "seccomp-disabled" else "1"
+ elif failure == "missing-capability":
+ state.status.pop("CapEff")
+ else:
+ state.status["CapEff"] = "not-hex"
+ state.marker.write_text(json.dumps(state.proof))
+ before = fixture.source_digest(state.root)
+ with pytest.raises(RuntimeError):
+ isolation.namespace_receipt()
+ assert fixture.source_digest(state.root) == before
+
+
[email protected]("variable", isolation.STORAGE_ENV)
[email protected]("grant", ["/usr/bin/sandbox-exec", "/dev/null", "/usr/lib/diagnostic",
+ "/System/Library/Frameworks/Python.framework", "/Library/Frameworks/Python.framework"])
+def test_macos_every_system_and_tool_grant_uses_same_storage_admission(
+ tmp_path, original_storage, monkeypatch, variable, grant):
+ """Synthetic path identities only; never read system configuration contents."""
+ monkeypatch.setattr(sys, "platform", "darwin")
+ monkeypatch.setattr(Path, "resolve", lambda path, **_kw: path)
+ monkeypatch.setattr(Path, "is_file", lambda _path: True)
+ # Even a protected subtree strictly inside a system input must refuse.
+ monkeypatch.setenv(variable, grant + "/configured-state")
+ monkeypatch.setattr(subprocess, "run", lambda *_a, **_kw: pytest.fail("Policy refusal must precede execution."))
+ with pytest.raises(ValueError):
+ isolation.sandbox_prefix(tmp_path / "task", required_inputs=(Path(grant),))
+ assert not (tmp_path / "task").exists()
+
+
[email protected]("shape", ["home", "home-child", "parent", "protected", "alias", "home-alias",
+ "broad-usr", "broad-system", "broad-library", "missing-inputs", "empty-inputs"])
+def test_macos_finite_input_refusals_are_before_effects(tmp_path, original_storage, monkeypatch, shape):
+ monkeypatch.setattr(sys, "platform", "darwin")
+ context = isolation.StorageContext.capture()
+ task = tmp_path / "task"
+ inputs = (tmp_path / "staged",)
+ if shape == "home":
+ inputs = (original_storage.home,)
+ elif shape == "home-child":
+ inputs = (original_storage.home / ".ssh",)
+ elif shape == "parent":
+ inputs = (tmp_path,)
+ elif shape == "protected":
+ inputs = (context.protected[0],)
+ elif shape == "alias":
+ alias = tmp_path / "alias"
+ alias.symlink_to(original_storage.home / "Library/Application Support/Browser")
+ inputs = (alias,)
+ elif shape == "home-alias":
+ task = original_storage.home / "looks-outside"
+ task.symlink_to(tmp_path / "task")
+ elif shape.startswith("broad-"):
+ inputs = (Path({"broad-usr": "/usr", "broad-system": "/System", "broad-library": "/Library"}[shape]),)
+ elif shape == "missing-inputs":
+ inputs = None
+ else:
+ inputs = ()
+ monkeypatch.setattr(subprocess, "run", lambda *_a, **_kw: pytest.fail("Refused policy executed."))
+ with pytest.raises(ValueError):
+ isolation.sandbox_prefix(task, required_inputs=inputs)
+ assert not (tmp_path / "task").exists()
+
+
[email protected]("name", ["normal", "task-唯一", 'staged-"quoted"'])
+def test_macos_disjoint_unicode_inputs_reach_actual_argv_without_policy_widening(
+ tmp_path, original_storage, monkeypatch, name):
+ monkeypatch.setattr(sys, "platform", "darwin")
+ task, inputs = tmp_path / ("task-" + name), tmp_path / ("inputs-" + name)
+ inputs.mkdir()
+ sentinel = inputs / "approved.txt"
+ sentinel.write_bytes(b"synthetic approved input")
+ for relative in (".ssh/key", ".aws/config", "Library/Application Support/Browser/profile"):
+ path = original_storage.home / relative
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes(b"synthetic private sentinel")
+ before = fixture.source_digest(original_storage.home)
+ context = isolation.storage_context()
+ calls = []
+ def consume(command, **kwargs):
+ assert command[:2] == ["/usr/bin/sandbox-exec", "-p"]
+ policy = command[2]
+ assert policy.startswith("(version 1) (deny default)")
+ assert "(allow default)" not in policy and "(import " not in policy
+ # Inspect the actual entire positive operation set, not an SBPL emulator.
+ assert set(re.findall(r"\(allow ([^\s()]+)", policy)) == {
+ "file-read*", "file-write*", "process-exec", "process-fork",
+ }
+ assert policy.count("(allow process-exec)") == policy.count("(allow process-fork)") == 1
+ assert not any(token in policy for token in (
+ "mach", "ipc", "iokit", "sysctl", "signal", "job-creation", "process*",
+ ))
+ assert "(deny network*)" in policy and "(deny file-read*)" in policy and "(deny file-write*)" in policy
+ assert "(allow file-read*)" not in policy and "(allow file-read-metadata)" not in policy
+ for boundary in (*context.homes, *context.protected):
+ assert f"(deny file-read* (subpath {json.dumps(str(boundary))}))" in policy
+ assert f"(require-not (subpath {json.dumps(str(boundary))}))" in policy
+ assert json.dumps(str(inputs)) in policy and json.dumps(str(task)) in policy
+ assert command[3:] == ["/usr/bin/false"] and kwargs["close_fds"]
+ calls.append(command)
+ return subprocess.CompletedProcess(command, 0)
+ monkeypatch.setattr(subprocess, "run", consume)
+ subprocess.run([*isolation.sandbox_prefix(task, required_inputs=(inputs,)), "/usr/bin/false"], close_fds=True)
+ assert len(calls) == 1 and not task.exists()
+ assert fixture.source_digest(original_storage.home) == before
+ assert sentinel.read_bytes() == b"synthetic approved input"
+
+
+# Independent expected plan: changing only the planner cannot shrink coverage.
+PREPARATION_PATHS = (
+ "recipe", "source", "state", "downloads", "toolchain", "uv-toolchain", "venv", "fixtures",
+ "state/home", "state/tmp", "state/config", "state/data", "state/cache",
+ "state/go", "state/mod", "state/uv-cache",
+)
+PREPARATION_INTERNALS = (
+ "downloads/go.tar.gz", "downloads/uv.tar.gz", "toolchain/bin/go", "uv-toolchain/uv",
+ "venv/bin/python", "fixtures/avibe-fixture-existing/config", "state/home/.avibe",
+)
+
+
+def preparation_entry():
+ readme = (Path(__file__).parent / "README.md").read_text()
+ block = readme.split("```sh\n", 1)[1].split("\n```", 1)[0]
+ body = block.split("<<'PY'\n", 1)[1].split("\nPY\n", 1)[0]
+ return block, compile(body, "<maintained README preparation entry>", "exec")
+
+
+def setup_snapshot(root):
+ """Record fake task paths without following links into any other tree."""
+ result = {}
+ for directory, dirs, files in os.walk(root, followlinks=False):
+ for path in [Path(directory), *(Path(directory) / name for name in dirs + files)]:
+ info = path.lstat()
+ content = os.readlink(path) if stat.S_ISLNK(info.st_mode) else (
+ path.read_bytes() if stat.S_ISREG(info.st_mode) else None
+ )
+ result[str(path.relative_to(root))] = (info.st_mode, info.st_ino, info.st_mtime_ns, content)
+ return result
+
+
+def run_preparation(task, monkeypatch):
+ _, body = preparation_entry()
+ monkeypatch.setattr(sys, "argv", ["-", str(Path(__file__).parent), str(task)])
+ # Adapt only the temporary-path domain for a macOS pure run. The original
+ # caller context, complete shared storage validator and README body are real.
+ monkeypatch.setattr(isolation, "validate_temporary_root", isolation.validate_state_root)
+ exec(body, {})
+
+
+def assert_preparation_refuses_without_side_effects(task, all_fake_state, monkeypatch):
+ before = setup_snapshot(all_fake_state)
+ with monkeypatch.context() as guard:
+ def forbidden(*_args, **_kwargs):
+ pytest.fail("Preparation reached a write/copy/export/subprocess before complete admission.")
+ guard.setattr(Path, "mkdir", forbidden)
+ guard.setattr(shutil, "copytree", forbidden)
+ guard.setattr(fixture, "export_fixture", forbidden)
+ for name in ("run", "Popen", "check_output"):
+ guard.setattr(subprocess, name, forbidden)
+ with pytest.raises((ValueError, FileNotFoundError)):
+ run_preparation(task, guard)
+ assert setup_snapshot(all_fake_state) == before
+
+
[email protected]("destination", (*PREPARATION_PATHS, *PREPARATION_INTERNALS))
[email protected]("authority", ["configured", "default"])
+def test_documented_preparation_checks_every_destination_before_first_write(
+ tmp_path, original_storage, monkeypatch, destination, authority):
+ task = tmp_path / "allocated-task"
+ task.mkdir(mode=0o700)
+ protected = (original_storage.parent / "xdg" if authority == "configured"
+ else original_storage.home / ".config")
+ protected.mkdir(parents=True)
+ (protected / "sentinel").write_bytes(b"preserved fake configuration")
+ if authority == "configured":
+ monkeypatch.setenv("XDG_CONFIG_HOME", str(protected))
+ target = task / destination
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.symlink_to(protected)
+ assert_preparation_refuses_without_side_effects(task, tmp_path, monkeypatch)
+
+
[email protected]("destination,variable", [
+ ("source", "XDG_CONFIG_HOME"), ("state", "XDG_DATA_HOME"),
+])
+def test_documented_preparation_closes_both_exact_root_reproductions(
+ tmp_path, original_storage, monkeypatch, destination, variable):
+ task = tmp_path / "allocated-task"
+ task.mkdir(mode=0o700)
+ protected = original_storage.parent
+ protected.mkdir()
+ (protected / "sentinel").write_bytes(b"fake production data; never real user data")
+ monkeypatch.setenv(variable, str(protected))
+ (task / destination).symlink_to(protected)
+ # The original root diagnosis reached actual Git init or mkdir through
+ # precisely these layouts. The maintained entry now reaches neither.
+ assert_preparation_refuses_without_side_effects(task, tmp_path, monkeypatch)
+ assert not (protected / ".git").exists()
+ assert not (protected / "home").exists() and not (protected / "tmp").exists()
+
+
[email protected]("variable", isolation.STORAGE_ENV)
[email protected]("destination", ["root", "source", "state", "state/cache"])
[email protected]("shape", ["equal", "descendant", "containing", "configured-alias"])
+def test_documented_preparation_retains_all_original_storage_authorities(
+ tmp_path, original_storage, monkeypatch, variable, destination, shape):
+ protected = original_storage.parent / "storage"
+ protected.mkdir(parents=True)
+ (protected / "sentinel").write_bytes(b"fake protected storage")
+ configured = protected
+ if shape == "configured-alias":
+ configured = tmp_path / "configured-alias"
+ configured.symlink_to(protected)
+ monkeypatch.setenv(variable, str(configured))
+ target = protected
+ if shape == "descendant":
+ target /= ".avibe/never-created" if variable == "HOME" else "never-created"
+ elif shape == "containing":
+ target = protected.parent
+ if destination == "root":
+ task = target
+ else:
+ task = tmp_path / "allocated-task"
+ task.mkdir(mode=0o700)
+ link = task / destination
+ link.parent.mkdir(parents=True, exist_ok=True)
+ link.symlink_to(target)
+ assert_preparation_refuses_without_side_effects(task, tmp_path, monkeypatch)
+
+
[email protected]("home_override", [False, True])
[email protected]("default", (*isolation.PRODUCT_DIRS, *isolation.XDG_DEFAULTS.values()))
+def test_documented_preparation_default_product_and_xdg_locations(
+ tmp_path, original_storage, monkeypatch, home_override, default):
+ home = tmp_path / "effective-home" if home_override else original_storage.home
+ if home_override:
+ monkeypatch.setenv("HOME", str(home))
+ protected = home / default
+ protected.mkdir(parents=True, exist_ok=True)
+ (protected / "setup-sentinel").write_bytes(b"preserved default storage")
+ task = tmp_path / "allocated-task"
+ task.mkdir(mode=0o700)
+ (task / "source").symlink_to(protected)
+ assert_preparation_refuses_without_side_effects(task, tmp_path, monkeypatch)
+
+
[email protected]("destination", (*PREPARATION_PATHS, *PREPARATION_INTERNALS))
[email protected]("existing", ["directory", "file", "internal-alias", "dangling-alias"])
+def test_documented_preparation_preserves_all_preexisting_destinations(
+ tmp_path, original_storage, monkeypatch, destination, existing):
+ task = tmp_path / "allocated-task"
+ task.mkdir(mode=0o700)
+ path = task / destination
+ path.parent.mkdir(parents=True, exist_ok=True)
+ if existing == "directory":
+ path.mkdir()
+ elif existing == "file":
+ path.write_bytes(b"earlier evidence")
+ else:
+ target = task / "preserved"
+ if existing == "internal-alias":
+ target.mkdir()
+ (target / "sentinel").write_bytes(b"earlier evidence")
+ path.symlink_to(target)
+ assert_preparation_refuses_without_side_effects(task, tmp_path, monkeypatch)
+
+
[email protected]("variable", isolation.STORAGE_ENV)
[email protected]("existing", [False, True])
+def test_documented_preparation_never_ignores_protected_storage_inside_proposed_task(
+ tmp_path, original_storage, monkeypatch, variable, existing):
+ task = tmp_path / "allocated-task"
+ task.mkdir(mode=0o700)
+ protected = task / "downloads/live-user-storage"
+ if existing:
+ protected.mkdir(parents=True)
+ (protected / "sentinel").write_bytes(b"fake user storage is not task output")
+ monkeypatch.setenv(variable, str(protected))
+ assert_preparation_refuses_without_side_effects(task, tmp_path, monkeypatch)
+
+
[email protected]("variable", isolation.STORAGE_ENV)
[email protected]("invalid", ["relative/storage", "/tmp/../storage"])
+def test_documented_preparation_invalid_context_never_reaches_setup(
+ tmp_path, original_storage, monkeypatch, variable, invalid):
+ task = tmp_path / "allocated-task"
+ task.mkdir(mode=0o700)
+ monkeypatch.setenv(variable, invalid)
+ assert_preparation_refuses_without_side_effects(task, tmp_path, monkeypatch)
+
+
[email protected]("failure", ["mode", "owner", "root-alias", "missing", "unknown-evidence"])
+def test_documented_preparation_requires_exclusive_canonical_allocation(
+ tmp_path, original_storage, monkeypatch, failure):
+ task = tmp_path / "allocated-task"
+ if failure != "missing":
+ task.mkdir(mode=0o700)
+ if failure == "mode":
+ task.chmod(0o755)
+ elif failure == "owner":
+ real_lstat = Path.lstat
+
+ def wrong_owner(path, *args, **kwargs):
+ info = real_lstat(path, *args, **kwargs)
+ if path == task:
+ values = list(info)
+ values[4] += 1
+ return os.stat_result(values)
+ return info
+ monkeypatch.setattr(Path, "lstat", wrong_owner)
+ elif failure == "root-alias":
+ alias = tmp_path / "root-alias"
+ alias.symlink_to(task)
+ task = alias
+ elif failure == "unknown-evidence":
+ (task / "unlisted-earlier-result").write_bytes(b"preserve even unrelated evidence")
+ assert_preparation_refuses_without_side_effects(task, tmp_path, monkeypatch)
+
+
+def test_documented_preparation_fresh_task_runs_actual_copy_git_and_directory_consumers(
+ tmp_path, original_storage, monkeypatch):
+ task = tmp_path / "allocated-task"
+ task.mkdir(mode=0o700)
+ events = []
+ planner = isolation.preparation_directories
+ mkdir, copytree, run = Path.mkdir, shutil.copytree, subprocess.run
+
+ def plan(root):
+ result = planner(root)
+ assert tuple(str(path.relative_to(task)) for path in result) == PREPARATION_PATHS
+ assert list(task.iterdir()) == []
+ events.append("complete-admission")
+ return result
+
+ def make(path, *args, **kwargs):
+ events.append("mkdir")
+ return mkdir(path, *args, **kwargs)
+
+ def copy(*args, **kwargs):
+ events.append("copy")
+ return copytree(*args, **kwargs)
+
+ def execute(command, **kwargs):
+ assert command[0] == "/usr/bin/git"
+ assert command[-3:] == ["init", "--template=", str(task / "source")]
+ assert kwargs["env"]["GIT_CONFIG_GLOBAL"] == "/dev/null"
+ events.append("git-init")
+ return run(command, **kwargs)
+
+ monkeypatch.setattr(isolation, "preparation_directories", plan)
+ monkeypatch.setattr(Path, "mkdir", make)
+ monkeypatch.setattr(shutil, "copytree", copy)
+ monkeypatch.setattr(subprocess, "run", execute)
+ monkeypatch.setenv("GIT_CONFIG_NOSYSTEM", "1")
+ monkeypatch.setenv("GIT_CONFIG_GLOBAL", "/dev/null")
+ monkeypatch.setenv("HOME", str(original_storage.home))
+ run_preparation(task, monkeypatch)
+ assert events[0] == "complete-admission"
+ assert set(events) == {"complete-admission", "mkdir", "copy", "git-init"}
+ assert (task / "source/.git").is_dir()
+ assert all((task / name).is_dir() for name in PREPARATION_PATHS)
+ assert not list((task / "recipe").rglob("*.pyc"))
+ assert (task / "recipe/isolation.py").read_bytes() == Path(isolation.__file__).read_bytes()
+ assert all(not list((task / name).iterdir()) for name in (
+ "downloads", "toolchain", "uv-toolchain", "venv", "fixtures", "state/uv-cache",
+ )) # No downloads, extraction, dependency installation or fixture export ran.
+ assert_preparation_refuses_without_side_effects(task, tmp_path, monkeypatch)
+
+
+def test_documented_preparation_shell_stops_before_any_later_instruction_on_refusal(tmp_path):
+ block, _ = preparation_entry()
+ # Actual isolated interpreter startup; an absent inspected recipe refuses
+ # before the preparation import. HOST Python path adaptation only.
+ block = block.replace("/usr/bin/python3", sys.executable)
+ result = subprocess.run(
+ ["/bin/sh", "-c", block + "\nexit 99\n"],
+ env={"PATH": "/usr/bin:/bin", "recipe_source": str(tmp_path / "absent-recipe"),
+ "engine_task": str(tmp_path / "absent-task")},
+ stdin=subprocess.DEVNULL, capture_output=True, close_fds=True, timeout=5,
+ )
+ assert result.returncode == 1
+ assert not (tmp_path / "absent-task").exists()
diff --git a/patches/cliproxyapi/test_wire_fixture.py b/patches/cliproxyapi/test_wire_fixture.py
new file mode 100644
index 000000000..a6e9990a0
--- /dev/null
+++ b/patches/cliproxyapi/test_wire_fixture.py
@@ -0,0 +1,121 @@
+"""Pure recipe consumers; actual lifecycle regressions run in isolated wire."""
+
+import copy
+import builtins
+import json
+import os
+from pathlib import Path
+import sys
+from types import SimpleNamespace
+
+import pytest
+
+import wire_matrix
+from fixture import source_digest
+
+
+def test_actual_wire_refuses_hardlinked_fixture_before_import_or_effect(tmp_path, monkeypatch):
+ fixture = tmp_path / "fixture"
+ fixture.mkdir()
+ target = fixture / "unpatched.py"
+ target.write_bytes(b"raise RuntimeError('must never import')\n")
+ expected = source_digest(fixture)
+ build = tmp_path / "prior-build"
+ (build / "bin").mkdir(parents=True)
+ binary = build / "bin/cli-proxy-api"
+ binary.write_bytes(b"task-only binary sentinel; never executed")
+ output = tmp_path / "output"
+ output.mkdir()
+ state = output / "wire"
+ os.link(target, output / "writable-alias")
+ proof = {"network": "loopback", "fixture": str(fixture), "output": str(output),
+ "selected_build": {"output": str(build)}}
+ monkeypatch.setattr(wire_matrix, "namespace_receipt", lambda: proof)
+ monkeypatch.setattr(sys, "argv", ["wire_matrix.py", "--binary", str(binary),
+ "--state", str(state), "--fixture", str(fixture), "--fixture-sha256", expected])
+ original_import = builtins.__import__
+ imports = []
+
+ def importing(name, *args, **kwargs):
+ if name.startswith("vibe."):
+ imports.append(name)
+ pytest.fail("Rejected fixture reached Avibe import.")
+ return original_import(name, *args, **kwargs)
+
+ monkeypatch.setattr(builtins, "__import__", importing)
+ monkeypatch.setattr(wire_matrix.importlib.util, "spec_from_file_location",
+ lambda *_a, **_kw: pytest.fail("Rejected fixture reached dynamic import."))
+ monkeypatch.setattr(wire_matrix.subprocess, "run",
+ lambda *_a, **_kw: pytest.fail("Rejected fixture reached process effect."))
+ original_path = list(sys.path)
+ with pytest.raises(ValueError, match="single-link regular"):
+ wire_matrix.main()
+ assert sys.path == original_path and not imports and not state.exists()
+ assert target.read_bytes() == b"raise RuntimeError('must never import')\n"
+
+
[email protected]("section", ["claude-api-key", "codex-api-key", "openai-compatibility"])
+def test_engine_only_empty_profile_preserves_all_generated_fields(section):
+ config = {name: [] for name in ("claude-api-key", "codex-api-key", "openai-compatibility")}
+ config[section] = [
+ {"prefix": "intent-protocol-" + profile, "api-key": "fake-only-key",
+ "base-url": "http://127.0.0.1:1234", "headers": {"api-mode": "chat"},
+ "models": [{"name": "模型完整", "alias": "模型完整", "context-window": 123,
+ **({"thinking": {"levels": ["high", "low"]}} if profile == "narrow" else {})}]}
+ for profile in ("known", "unknown", "narrow", "empty")
+ ]
+ expected = copy.deepcopy(config)
+ expected[section][-1]["models"][0]["thinking"] = {}
+ wire_matrix.supplement_empty_profile(config)
+ assert config == expected
+
+
+def test_generated_metadata_must_not_be_silently_overwritten():
+ config = {name: [] for name in ("claude-api-key", "codex-api-key", "openai-compatibility")}
+ config["openai-compatibility"] = [
+ {"prefix": "intent-chat-empty", "models": [
+ {"name": "model", "alias": "model", "thinking": {"levels": ["future"]}},
+ ]},
+ ]
+ previous = copy.deepcopy(config)
+ with pytest.raises(AssertionError):
+ wire_matrix.supplement_empty_profile(config)
+ assert config == previous
+
+
+def test_requests_follow_returned_connection_and_never_a_cached_token(monkeypatch):
+ observed = []
+
+ class Response:
+ status = 200
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_):
+ pass
+
+ def read(self):
+ return b"mock response"
+
+ def open_request(request, timeout):
+ observed.append((request.full_url, request.get_header("Authorization"),
+ json.loads(request.data), timeout))
+ return Response()
+
+ monkeypatch.setattr(wire_matrix, "opener", SimpleNamespace(open=open_request))
+ for port, token in ((1234, "fake-initial"), (5678, "fake-replacement")):
+ connection = SimpleNamespace(base_url=f"http://127.0.0.1:{port}", gateway_token=token)
+ assert wire_matrix.request(connection, "/v1/responses", {"model": "完整模型"}) == (200, b"mock response")
+ assert observed == [
+ ("http://127.0.0.1:1234/v1/responses", "Bearer fake-initial", {"model": "完整模型"}, 12),
+ ("http://127.0.0.1:5678/v1/responses", "Bearer fake-replacement", {"model": "完整模型"}, 12),
+ ]
+
+
+def test_installer_seam_only_selects_the_preverified_task_binary():
+ binary = Path("/test-owned/diagnostic/cli-proxy-api")
+ installer = wire_matrix.DiagnosticInstaller(binary)
+ assert installer.resolve_engine_path() == binary
+ assert installer.status()["install_dir"] == str(binary.parent)
+ assert not hasattr(installer, "install")
diff --git a/patches/cliproxyapi/verify.py b/patches/cliproxyapi/verify.py
new file mode 100644
index 000000000..87967361a
--- /dev/null
+++ b/patches/cliproxyapi/verify.py
@@ -0,0 +1,223 @@
+"""Verify exact source inputs and run only the inactive candidate's local checks."""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+from pathlib import Path
+import shutil
+import subprocess
+import sys
+
+from budgets import PHASES
+from execution_inputs import file_sha256, python_identity, records_sha256, regular_file, tree_records, verify_go
+from isolation import isolated_environment, namespace_receipt, safe_git, validate_state_root
+from fixture import fixture_identity, source_digest
+
+
+HERE = Path(__file__).resolve().parent
+
+
+def verify_inputs(source: Path) -> dict:
+ receipt = json.loads((HERE / "inputs.json").read_text())
+ head = safe_git(source, "rev-parse", "HEAD").decode().strip()
+ if head != receipt["source_sha"]:
+ raise RuntimeError(f"Wrong engine base: {head}")
+ for name, expected in receipt["sha256"].items():
+ if file_sha256(source / name) != expected:
+ raise RuntimeError(f"Frozen input changed: {name}")
+ return receipt
+
+
+def verify_candidate(source: Path) -> str:
+ receipt = json.loads((HERE / "patched-files.json").read_text())
+ changed = set()
+ for arguments in (["diff", "HEAD", "--name-only", "-z"], ["ls-files", "--others", "-z"]):
+ raw = safe_git(source, *arguments)
+ changed.update(name.decode() for name in raw.split(b"\0") if name)
+ if changed != set(receipt):
+ raise RuntimeError("Candidate has missing/extra edits or untracked files; preserve and inspect it.")
+ for name, expected in receipt.items():
+ if file_sha256(source / name) != expected:
+ raise RuntimeError(f"Candidate file differs from the maintained patch: {name}")
+ return hashlib.sha256((HERE / "native-intent.patch").read_bytes()).hexdigest()
+
+
+def write_json(path: Path, value: dict) -> None:
+ """Candidate evidence is exclusive; the parent terminal receipt stays separate."""
+ with path.open("x") as output:
+ output.write(json.dumps(value, indent=2) + "\n")
+
+
+def input_identity(source: Path, fixture: Path, proof: dict, go: Path) -> dict:
+ receipt = verify_inputs(source)
+ patch_sha = verify_candidate(source)
+ prerequisites = json.loads((HERE / "prerequisites.json").read_text())
+ toolchain = verify_go(
+ Path(proof["toolchain"]), Path(proof["go_archive"]), go, prerequisites["linux_arm64_go"],
+ )
+ return {
+ "source_sha": receipt["source_sha"], "patch_sha256": patch_sha,
+ "frozen_inputs": receipt["sha256"], "source_full_sha256": source_digest(source),
+ "go": toolchain, "avibe_fixture": fixture_identity(fixture, receipt),
+ "recipe_tree_sha256": source_digest(HERE),
+ "python_trusted_setup": python_identity(Path(proof["python_env"]), fixture),
+ "setup_only": {"uv": prerequisites["linux_arm64_uv"],
+ "scope": "declared setup prerequisite, not executed or archive-attested by this phase"},
+ }
+
+
+def build_artifacts(root: Path) -> dict:
+ records = tree_records(root)
+ records.pop("build.json", None)
+ return records
+
+
+def select_build(root: Path, proof: dict, identity: dict) -> dict:
+ selection = proof["selected_build"]
+ if selection is None or root != Path(selection["output"]):
+ raise RuntimeError("Wire must select the envelope's explicit read-only prior build.")
+ if (root / "bin").is_symlink() or not (root / "bin").is_dir():
+ raise RuntimeError("Build binary directory must be a real directory.")
+ with regular_file(root / "build.json") as source:
+ raw = source.read()
+ previous = json.loads(raw)
+ if previous["invocation"] != selection["receipt"] or previous["inputs"] != identity:
+ raise RuntimeError("Selected build is stale or belongs to different verified inputs.")
+ if previous["artifacts_sha256"] != records_sha256(build_artifacts(root)):
+ raise RuntimeError("Selected build output was substituted or changed.")
+ binary_sha = file_sha256(root / "bin/cli-proxy-api")
+ if previous["binary_sha256"] != binary_sha:
+ raise RuntimeError("Selected diagnostic binary changed.")
+ return {
+ **selection, "build_receipt_sha256": hashlib.sha256(raw).hexdigest(),
+ "binary_sha256": binary_sha, "artifacts_sha256": previous["artifacts_sha256"],
+ }
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("phase", choices=("apply", "test", "build", "wire"))
+ parser.add_argument("--source", required=True, type=Path)
+ parser.add_argument("--state", required=True, type=Path)
+ parser.add_argument("--fixture", type=Path, help="Complete verified Avibe commit export; required for execution.")
+ parser.add_argument("--build", type=Path, help="Explicit previous build output, required only for wire.")
+ args = parser.parse_args()
+ # Public consumers refuse protected aliases BEFORE any setup/output write.
+ state = validate_state_root(args.state)
+ source = validate_state_root(args.source).resolve(strict=True)
+ if source == state or state.is_relative_to(source):
+ raise ValueError("Evidence/cache state must be outside the source checkout.")
+ proof = namespace_receipt() if args.phase != "apply" else None
+ verify_inputs(source)
+ if args.phase == "apply":
+ # Apply has no input_identity call: admit the COMPLETE original tree
+ # before Git can write, including unchanged/nonpatched source files.
+ source_digest(source)
+ status = safe_git(source, "status", "--porcelain")
+ if status:
+ raise RuntimeError("Checkout is dirty; preserve it and use a fresh exact-base checkout.")
+ patch = HERE / "native-intent.patch"
+ for options in (["--check"], []):
+ safe_git(source, "apply", *options, str(patch))
+ verify_candidate(source)
+ return
+ # Confirm that the maintained candidate, including its Go tests, is applied.
+ safe_git(source, "apply", "--reverse", "--check", str(HERE / "native-intent.patch"))
+ verify_candidate(source)
+ budget = PHASES[args.phase]
+ expected_network = "none" if args.phase == "build" else "loopback"
+ if (proof["phase"] != args.phase or proof["budget"] != budget.receipt()
+ or Path(proof["source"]) != source or Path(proof["state"]) != state
+ or Path(proof["recipe"]) != HERE
+ or proof["network"] != expected_network):
+ raise RuntimeError("Phase/source/state/network/budget does not match the parent envelope.")
+ output = validate_state_root(Path(proof["output"])).resolve(strict=True)
+ if output == state or output.is_relative_to(state) or state.is_relative_to(output):
+ raise RuntimeError("Per-invocation output and shared cache must be disjoint.")
+ if args.fixture is None or args.fixture.resolve(strict=True) != Path(proof["fixture"]):
+ raise ValueError("Select the complete frozen read-only Avibe fixture.")
+ fixture = args.fixture.resolve(strict=True)
+ if (args.phase == "wire") != (args.build is not None):
+ raise ValueError("Only wire must select an explicit prior build.")
+ go_name = shutil.which("go")
+ if not go_name:
+ raise RuntimeError("The exact pinned Go extraction is required.")
+ go = Path(go_name).resolve(strict=True)
+ write_json(output / "invocation.json", {"parent_receipt": proof["receipt"], "phase": args.phase,
+ "budget": budget.receipt()})
+ identity = input_identity(source, fixture, proof, go)
+ write_json(output / "inputs-before.json", identity)
+ env = isolated_environment(output, cache=state, go=go)
+ version = subprocess.check_output(
+ [str(go), "version"], cwd=source, env=env, text=True, timeout=budget.input_seconds,
+ )
+ if version.strip() != f"go version {identity['go']['version']} linux/arm64":
+ raise RuntimeError(f"Wrong Go version: {version.strip()}")
+ with (output / "go-version.txt").open("x") as stream:
+ stream.write(version)
+ selected = None
+ if args.phase == "test":
+ commands = [
+ [go, "test", "-mod=readonly", "-p=1", "-count=1",
+ "./internal/thinking/...", "./internal/modelconfig",
+ "./internal/runtime/executor/helps", "./sdk/cliproxy/auth"],
+ [go, "test", "-mod=readonly", "-p=1", "-count=1",
+ "-run", "^TestThinking|^TestSummaryIntent", "./test"],
+ [go, "test", "-mod=readonly", "-p=1", "-count=1",
+ "./internal/runtime/executor"],
+ ]
+ elif args.phase == "build":
+ (output / "bin").mkdir()
+ commands = [[go, "build", "-mod=readonly", "-p=1", "-trimpath", "-buildvcs=false",
+ "-o", str(output / "bin/cli-proxy-api"), "./cmd/server"]]
+ else:
+ build_root = args.build.resolve(strict=True)
+ selected = select_build(build_root, proof, identity)
+ wire_state = output / "wire"
+ commands = [[sys.executable, str(HERE / "wire_matrix.py"),
+ "--binary", str(build_root / "bin/cli-proxy-api"), "--state", str(wire_state),
+ "--fixture", str(fixture), "--fixture-sha256", identity["avibe_fixture"]["source_sha256"]]]
+ if len(commands) != budget.commands:
+ raise RuntimeError("Command plan does not match its complete phase allowance.")
+ try:
+ for index, command in enumerate(commands):
+ log = output / f"{args.phase}-{index}.log"
+ with log.open("xb") as stream:
+ result = subprocess.run(
+ command, cwd=source, env=env, stdin=subprocess.DEVNULL, close_fds=True,
+ stdout=stream, stderr=subprocess.STDOUT, timeout=budget.command_seconds,
+ )
+ print(f"{args.phase}-{index}: exit {result.returncode}; evidence: {log}", flush=True)
+ if result.returncode:
+ raise SystemExit(result.returncode)
+ finally:
+ # Failure evidence and all prior runs remain in place. The parent owns
+ # the terminal verdict; these files do not impersonate that receipt.
+ after = input_identity(source, fixture, proof, go)
+ write_json(output / "inputs-after.json", after)
+ if after != identity:
+ raise RuntimeError("Execution inputs changed during the phase.")
+ if selected is not None and select_build(build_root, proof, identity) != selected:
+ raise RuntimeError("Selected build changed during wire execution.")
+ if args.phase == "build":
+ write_json(output / "build.json", {
+ "invocation": proof["receipt"], "inputs": identity,
+ "binary_sha256": file_sha256(output / "bin/cli-proxy-api"),
+ "artifacts_sha256": records_sha256(build_artifacts(output)),
+ "command": [str(part) for part in commands[0][1:]],
+ })
+ elif args.phase == "wire":
+ wire_identity = {
+ "invocation": proof["receipt"], "inputs": identity, "selected_build": selected,
+ "artifacts": {
+ name: file_sha256(wire_state / name)
+ for name in ("matrix.json", "integration.json", "lifecycle.json")
+ },
+ }
+ write_json(output / "wire.json", wire_identity)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/patches/cliproxyapi/wire_matrix.py b/patches/cliproxyapi/wire_matrix.py
new file mode 100644
index 000000000..1d7d5ed85
--- /dev/null
+++ b/patches/cliproxyapi/wire_matrix.py
@@ -0,0 +1,637 @@
+"""Patched engine HTTP -> existing loopback mock, with actual Avibe registrations.
+
+MH-EFFORT-001 supplementary engine acceptance: the registered Avibe scenario
+still owns gateway/resolver evidence; these inactive-source consumers close
+its downstream engine seam without claiming shipped behavior.
+
+Run through verify.py. All credentials, Source records, processes and writes
+belong to the explicit evidence directory; this never launches an installed
+engine or reads an installed engine's state.
+"""
+
+from __future__ import annotations
+
+import argparse
+import asyncio
+import base64
+import binascii
+import copy
+from contextlib import ExitStack
+from dataclasses import replace
+import http.client
+import hashlib
+import importlib.util
+import json
+from pathlib import Path
+import socket
+import struct
+import subprocess
+import sys
+import time
+import zlib
+from urllib.error import HTTPError, URLError
+from urllib.request import ProxyHandler, Request, build_opener
+
+import yaml
+
+from fixture import verify_fixture
+from isolation import isolated_environment, namespace_receipt, validate_state_root
+
+
+opener = build_opener(ProxyHandler({}))
+PROTOCOLS = ("anthropic", "openai_responses", "openai_chat")
+PATHS = dict(zip(PROTOCOLS, ("/v1/messages", "/v1/responses", "/v1/chat/completions")))
+PROFILES = ("known", "known_nil", "unknown", "narrow", "empty")
+TEXT = "中文 fixture — reasoning intent"
+
+
+def request(connection, path, body=None):
+ headers = {"Authorization": f"Bearer {connection.gateway_token}", "Content-Type": "application/json"}
+ raw = None if body is None else json.dumps(body, ensure_ascii=False).encode()
+ try:
+ response = opener.open(Request(connection.base_url + path, data=raw, headers=headers), timeout=12)
+ except HTTPError as exc:
+ response = exc
+ with response:
+ return response.status, response.read()
+
+
+def supplement_empty_profile(config):
+ """Assert generated registrations; add only the labeled ENGINE-only case."""
+ for section in ("claude-api-key", "codex-api-key", "openai-compatibility"):
+ for entry in config[section]:
+ for model in entry["models"]:
+ assert model["name"] == model["alias"]
+ if entry["prefix"].endswith("-narrow"):
+ assert model["thinking"] == {"levels": ["high", "low"]}
+ else:
+ assert "thinking" not in model
+ if entry["prefix"].endswith("-empty"):
+ # The frozen product deliberately does not generate this.
+ model["thinking"] = {}
+
+
+class DiagnosticInstaller:
+ """Only the preverified task binary; no installed-state or download lookup."""
+
+ def __init__(self, binary):
+ self.binary = binary
+
+ def status(self):
+ return {"installed": True, "version": "inactive-source-diagnostic",
+ "install_dir": str(self.binary.parent)}
+
+ def resolve_engine_path(self):
+ return self.binary
+
+
+class FrozenEngine:
+ """Constructor seams only; frozen Avibe owns validation, health and lifecycle."""
+
+ def __init__(self, binary, state, store, log):
+ state = validate_state_root(state)
+ from core.handlers.model_hub.adapter import SourceBinding
+ from vibe.model_hub_runtime.adapter import CLIProxyEngineAdapter
+ from vibe.model_hub_runtime.supervisor import EngineSupervisor
+
+ self.binding_type = SourceBinding
+ self.binary, self.state, self.store, self.log = binary, state, store, log
+ self.processes, self.ports, self.launches = [], [], []
+ self.fail_next = False
+ self.loop = asyncio.Runner()
+ self.supervisor = EngineSupervisor(
+ installer=DiagnosticInstaller(binary), state_store=store,
+ process_factory=self.launch, port_allocator=self.allocate_port,
+ )
+ self.adapter = CLIProxyEngineAdapter(supervisor=self.supervisor, state_store=store)
+
+ def allocate_port(self):
+ # Force a changed connection to catch stale-port consumers on restart.
+ while True:
+ with socket.socket() as reservation:
+ reservation.bind(("127.0.0.1", 0))
+ port = reservation.getsockname()[1]
+ if port not in self.ports:
+ self.ports.append(port)
+ return port
+
+ def launch(self, command, **kwargs):
+ from config.atomic_io import write_atomic
+
+ assert command[0] == str(self.binary) and command[1] == "-config"
+ config_path = validate_state_root(Path(command[2])).resolve(strict=True)
+ assert config_path.is_relative_to(self.store.root)
+ config = yaml.safe_load(config_path.read_text())
+ supplement_empty_profile(config)
+ environment = isolated_environment(self.state)
+ write_atomic(config_path, yaml.safe_dump(config, sort_keys=False))
+ # Preserve the product's cwd/stdin/umask/process-group ownership. Only
+ # task-local environment, output and local-catalog selection differ.
+ kwargs["env"] = {**kwargs["env"], **environment}
+ kwargs["stdout"], kwargs["stderr"] = self.log, subprocess.STDOUT
+ failure = self.fail_next
+ self.fail_next = False
+ actual = [sys.executable, "-B", "-c", "raise SystemExit(23)"] if failure else [*command, "--local-model"]
+ process = subprocess.Popen(actual, **kwargs)
+ self.processes.append(process)
+ self.launches.append({"pid": process.pid, "injected_exit": 23 if failure else None,
+ "config_sha256": hashlib.sha256(config_path.read_bytes()).hexdigest()})
+ return process
+
+ def sync(self, sources):
+ bindings = [
+ self.binding_type(**{name: getattr(source, name) for name in (
+ "source_id", "vendor", "protocol", "base_url", "credential_ref",
+ "allowed_origins", "model_ids", "model_reasoning_efforts", "route_model_ids",
+ )})
+ for source in sources
+ ]
+ self.loop.run(self.adapter.sync_sources(bindings))
+
+ def connection(self):
+ client = self.supervisor.client_if_running()
+ assert client is not None
+ return client.connection
+
+ def close(self):
+ try:
+ self.supervisor.stop()
+ finally:
+ self.loop.close()
+ assert all(process.poll() is not None for process in self.processes)
+
+
+def wait_registered(engine, expected_routes):
+ connection = engine.connection()
+ deadline = time.monotonic() + 20
+ while True:
+ assert engine.processes[-1].poll() is None
+ try:
+ status, raw = request(connection, "/v1/models")
+ registered = {model["id"] for model in json.loads(raw).get("data", [])}
+ if status == 200 and expected_routes <= registered:
+ return connection
+ except (URLError, TimeoutError):
+ pass
+ assert time.monotonic() < deadline, "fixture registration deadline"
+ time.sleep(0.1)
+
+
+def payload(protocol, model, intent, stream):
+ if protocol == "openai_responses":
+ result = {
+ "model": model,
+ "input": [{"type": "message", "role": "user", "content": [{"type": "input_text", "text": TEXT}]}],
+ "stream": stream,
+ }
+ else:
+ result = {"model": model, "messages": [{"role": "user", "content": TEXT}], "stream": stream}
+ if protocol == "anthropic":
+ result["max_tokens"] = 64000
+ if protocol == "anthropic":
+ if intent in ("strong", "future"):
+ result["thinking"] = {"type": "adaptive"}
+ result["output_config"] = {"effort": "max" if intent == "strong" else "ultra"}
+ elif intent == "none":
+ result["thinking"] = {"type": "disabled"}
+ elif intent in ("budget", "budget_outside"):
+ result["thinking"] = {"type": "enabled", "budget_tokens": 4096 if intent == "budget" else 256}
+ elif intent == "auto":
+ result["thinking"] = {"type": "enabled"}
+ elif intent == "summary":
+ result["thinking"] = {"type": "adaptive", "display": "omitted"}
+ elif protocol == "openai_responses":
+ if intent in ("strong", "none", "future", "auto"):
+ effort = {"strong": "xhigh", "none": "none", "future": "ultra", "auto": "auto"}[intent]
+ result["reasoning"] = {"effort": effort, "summary": "auto"}
+ elif intent == "summary":
+ result["reasoning"] = {"summary": "auto"}
+ elif intent in ("strong", "none", "future", "auto"):
+ result["reasoning_effort"] = {"strong": "xhigh", "none": "none", "future": "ultra", "auto": "auto"}[intent]
+ elif intent == "summary":
+ result["reasoning"] = {"exclude": True}
+ return result
+
+
+def fragment(body):
+ return {key: copy.deepcopy(body[key]) for key in ("reasoning", "reasoning_effort", "thinking", "output_config") if key in body}
+
+
+def assert_policy(row):
+ source, target, profile, intent = (row[key] for key in ("frontend", "upstream", "profile", "intent"))
+ expected_error = source == "openai_chat" and target == "openai_responses" and profile == "narrow" and intent == "absent"
+ assert row["status"] == (400 if expected_error else 200), row
+ assert row["upstream_count"] == (0 if expected_error else 1), row
+ if expected_error:
+ return
+ body = row["out"]
+ if source == target:
+ assert body == row["in"], row
+ return
+ if intent == "none":
+ if target == "anthropic":
+ assert body == {"thinking": {"type": "disabled"}}, row
+ else:
+ effort = body.get("reasoning_effort") if target == "openai_chat" else body.get("reasoning", {}).get("effort")
+ assert effort == "none", row
+ return
+ if intent == "strong":
+ if target == "anthropic":
+ if profile == "empty":
+ assert body["thinking"]["budget_tokens"] == 31999, row
+ else:
+ effort = {"known": "max", "known_nil": "xhigh", "unknown": "xhigh", "narrow": "high"}[profile]
+ assert body["thinking"]["type"] == "adaptive" and body["output_config"]["effort"] == effort, row
+ else:
+ field = body.get("reasoning_effort") if target == "openai_chat" else body.get("reasoning", {}).get("effort")
+ original = "max" if source == "anthropic" else "xhigh"
+ if profile == "narrow" or (target == "openai_chat" and profile != "empty"):
+ expected = "high"
+ elif target == "openai_responses" and profile == "known":
+ expected = "xhigh"
+ else:
+ expected = original
+ assert field == expected, row
+ elif target == "openai_responses":
+ # Preserve translator defaults and known positive conversion constraints.
+ expected = "low" if profile == "narrow" else "medium"
+ assert body.get("reasoning", {}).get("effort") == expected, row
+ else:
+ assert not body, row
+
+
+def synthetic_images():
+ """Four valid, distinct RGB PNGs; uncompressed IDAT yields ~42 MiB JSON."""
+ def chunk(kind, data):
+ return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", binascii.crc32(kind + data) & 0xFFFFFFFF)
+
+ images = []
+ for index in range(4):
+ width, height = 2048, 1344
+ scanline = b"\0" + bytes((index * 60, 80, 160)) * width
+ png = (
+ b"\x89PNG\r\n\x1a\n"
+ + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0))
+ + chunk(b"IDAT", zlib.compress(scanline * height, level=0))
+ + chunk(b"IEND", b"")
+ )
+ images.append(base64.b64encode(png).decode("ascii"))
+ return images
+
+
+def add_images(body, protocol, images):
+ text = {"type": "text" if protocol != "openai_responses" else "input_text", "text": TEXT}
+ if protocol == "anthropic":
+ parts = [text, *({"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": image}} for image in images)]
+ elif protocol == "openai_chat":
+ parts = [text, *({"type": "image_url", "image_url": {"url": "data:image/png;base64," + image}} for image in images)]
+ else:
+ parts = [text, *({"type": "input_image", "image_url": "data:image/png;base64," + image} for image in images)]
+ key = "input" if protocol == "openai_responses" else "messages"
+ body[key][0]["content"] = parts
+
+
+def image_and_text(body, protocol):
+ key = "input" if protocol == "openai_responses" else "messages"
+ parts = body[key][0]["content"]
+ text, images = [], []
+ for part in parts:
+ if part["type"] in ("text", "input_text"):
+ text.append(part["text"])
+ elif part["type"] == "image":
+ assert part["source"]["type"] == "base64" and part["source"]["media_type"] == "image/png"
+ images.append(part["source"]["data"])
+ else:
+ url = part["image_url"]
+ if isinstance(url, dict):
+ url = url["url"]
+ assert url.startswith("data:image/png;base64,")
+ images.append(url.removeprefix("data:image/png;base64,"))
+ return text, images
+
+
+def integration_consumers(connection, targets, long_targets, mocks, mock_module):
+ results = []
+ for protocol in PROTOCOLS:
+ for route, model, key in long_targets[protocol]:
+ for stream in (False, True):
+ for mock in mocks.values():
+ mock.reset_requests()
+ status, response = request(
+ connection, PATHS[protocol],
+ payload(protocol, route, "strong", stream),
+ )
+ assert status == 200 and b"mock response" in response
+ captured = mocks[protocol].requests()
+ assert len(captured) == 1
+ assert not any(mock.requests() for other, mock in mocks.items() if other != protocol)
+ outbound = captured[0]
+ # Compare FULL identities, never display labels, heads, or hashes.
+ assert outbound["body"]["model"] == model
+ assert outbound["body"]["model"].encode("utf-8") == model.encode("utf-8")
+ assert outbound["path"] == PATHS[protocol]
+ values = set(outbound["headers"].values())
+ assert key in values or f"Bearer {key}" in values
+ assert f"Bearer {connection.gateway_token}" not in values
+ results.append({"kind": "long-id", "protocol": protocol, "stream": stream,
+ "utf8_bytes": len(model.encode()), "identity": model})
+
+ # Only this reused MOCK's receive budget changes. No gateway, engine,
+ # product constant, or production configuration is changed.
+ previous_limit = mock_module.MAX_REQUEST_BODY_BYTES
+ mock_module.MAX_REQUEST_BODY_BYTES = 48 * 1024 * 1024
+ try:
+ images = synthetic_images()
+ for protocol in PROTOCOLS:
+ for mock in mocks.values():
+ mock.reset_requests()
+ route, model, key = targets[protocol, "unknown"]
+ body = payload(protocol, route, "strong", False)
+ add_images(body, protocol, images)
+ size = len(json.dumps(body, ensure_ascii=False).encode())
+ assert 42 * 1024 * 1024 <= size < 43 * 1024 * 1024
+ status, response = request(connection, PATHS[protocol], body)
+ assert status == 200 and b"mock response" in response, f"{protocol} large request returned {status}"
+ captured = mocks[protocol].requests()
+ assert len(captured) == 1
+ assert not any(mock.requests() for other, mock in mocks.items() if other != protocol)
+ outbound = captured[0]
+ assert outbound["path"] == PATHS[protocol] and outbound["body"]["model"] == model
+ values = set(outbound["headers"].values())
+ assert key in values or f"Bearer {key}" in values
+ assert f"Bearer {connection.gateway_token}" not in values
+ text, actual_images = image_and_text(outbound["body"], protocol)
+ # Compare exact data independently of allowed envelope/cache changes.
+ assert text == [TEXT] and actual_images == images
+ assert fragment(outbound["body"]) == fragment(body)
+ results.append({"kind": "multi-image", "protocol": protocol, "request_bytes": size,
+ "image_sha256": [hashlib.sha256(value.encode()).hexdigest() for value in actual_images],
+ "text": text})
+ mocks[protocol].reset_requests()
+ finally:
+ mock_module.MAX_REQUEST_BODY_BYTES = previous_limit
+ return results
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--binary", required=True, type=Path)
+ parser.add_argument("--state", required=True, type=Path)
+ parser.add_argument("--fixture", required=True, type=Path)
+ parser.add_argument("--fixture-sha256", required=True)
+ args = parser.parse_args()
+ state = validate_state_root(args.state)
+ binary = args.binary.resolve(strict=True)
+ fixture = args.fixture.resolve(strict=True)
+ envelope = namespace_receipt()
+ if (envelope["network"] != "loopback" or Path(envelope["fixture"]) != fixture
+ or not state.is_relative_to(Path(envelope["output"]))
+ or envelope["selected_build"] is None
+ or binary != Path(envelope["selected_build"]["output"]) / "bin/cli-proxy-api"):
+ raise RuntimeError("Wire fixture must run within its private loopback and read-only source envelope.")
+ verify_fixture(fixture, args.fixture_sha256)
+ # All Avibe imports resolve from the verified commit export, not this
+ # recipe's checkout or caller cwd. The clean child has no PYTHONPATH.
+ sys.path.insert(0, str(fixture))
+ from vibe.model_hub_runtime.state import EngineStateError, EngineStateStore, SourceRecord
+ from vibe.model_hub_runtime.supervisor import EngineUnavailableError
+
+ spec = importlib.util.spec_from_file_location(
+ "mock_upstream", fixture / "tests/e2e/drivers/mock_llm_upstream.py",
+ )
+ mock_module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(mock_module)
+ # An existing evidence run is preserved, never overwritten.
+ state.mkdir(parents=True, exist_ok=False)
+ store = EngineStateStore(state / "engine-state")
+ rows, sources, targets, long_targets = [], [], {}, {}
+ lifecycle = {}
+
+ with ExitStack() as stack:
+ mocks = {protocol: stack.enter_context(mock_module.MockLLMUpstream()) for protocol in PROTOCOLS}
+ for protocol, mock in mocks.items():
+ mock.configure(protocol=protocol)
+ for profile in PROFILES:
+ prefix = f"intent-{protocol.replace('_', '-')}-{profile}"
+ model = {
+ "known": "claude-opus-4-6" if protocol == "anthropic" else "gpt-5.4",
+ "known_nil": "claude-3-5-haiku-20241022",
+ "unknown": "intent-custom", "narrow": "intent-narrow", "empty": "intent-empty",
+ }[profile]
+ base = mock.url + ("/v1" if protocol != "anthropic" else "")
+ key = f"fake-outbound-{prefix}"
+ credential = store.store_api_key(key, protocol=protocol, base_url=base)
+ sources.append(SourceRecord(
+ source_id=f"src_{len(sources):08x}", vendor="custom", protocol=protocol,
+ base_url=base, credential_ref=credential, allowed_origins=(mock.url,),
+ model_ids=() if profile == "unknown" else (model,),
+ route_model_ids=(model,) if profile == "unknown" else (),
+ prefix=prefix,
+ model_reasoning_efforts=((model, ("low", "high")),) if profile == "narrow" else (),
+ ))
+ targets[protocol, profile] = (f"{prefix}/{model}", model, key)
+ long_head = "模型-" * 4000
+ long_models = ("单独-" + "🌙" * 5000, long_head + "尾甲", long_head + "尾乙", "路由-" + "🎛️" * 3000)
+ assert all(len(model.encode()) > 16384 for model in long_models)
+ for protocol, mock in mocks.items():
+ prefix, key = f"intent-long-{protocol}", f"fake-long-{protocol}"
+ base = mock.url + ("/v1" if protocol != "anthropic" else "")
+ sources.append(SourceRecord(
+ source_id=f"src_{len(sources):08x}", vendor="custom", protocol=protocol,
+ base_url=base, credential_ref=store.store_api_key(key, protocol=protocol, base_url=base),
+ allowed_origins=(mock.url,), model_ids=long_models[:3],
+ route_model_ids=(long_models[3],), prefix=prefix,
+ ))
+ long_targets[protocol] = [(f"{prefix}/{model}", model, key) for model in long_models]
+ # Seed deterministic test prefixes, then validate the entire projection
+ # through the real adapter/state owner before the initial child launch.
+ store.replace_sources(sources)
+ expected_routes = {target[0] for target in targets.values()}
+ expected_routes.update(target[0] for values in long_targets.values() for target in values)
+ with (state / "engine.log").open("wb") as log:
+ engine = FrozenEngine(binary, state, store, log)
+ try:
+ engine.sync(sources)
+ assert store.list_sources() == sources and not engine.processes
+ initial = engine.supervisor.ensure_running()
+ connection = wait_registered(engine, expected_routes)
+ assert connection == initial
+ for target in PROTOCOLS:
+ for frontend in PROTOCOLS:
+ intents = ["strong", "none", "absent"]
+ if frontend == target:
+ intents += ["summary", "auto", "future"]
+ if frontend == "anthropic":
+ intents += ["budget", "budget_outside"]
+ for profile in PROFILES:
+ route, model, key = targets[target, profile]
+ for intent in intents:
+ for stream in (False, True):
+ for mock in mocks.values():
+ mock.reset_requests()
+ body = payload(frontend, route, intent, stream)
+ status, response = request(connection, PATHS[frontend], body)
+ captured = mocks[target].requests()
+ assert not any(mock.requests() for protocol, mock in mocks.items() if protocol != target)
+ assert len(captured) <= 1
+ outbound = captured[0] if captured else None
+ if outbound:
+ assert outbound["path"] == PATHS[target]
+ assert outbound["body"]["model"] == model
+ assert TEXT in json.dumps(outbound["body"], ensure_ascii=False)
+ values = set(outbound["headers"].values())
+ assert key in values or f"Bearer {key}" in values
+ assert f"Bearer {connection.gateway_token}" not in values
+ assert b"mock response" in response
+ row = {
+ "frontend": frontend, "upstream": target, "profile": profile,
+ "intent": intent, "stream": stream, "status": status,
+ "upstream_count": len(captured), "in": fragment(body),
+ "out": fragment(outbound["body"]) if outbound else None,
+ }
+ rows.append(row)
+ assert_policy(row)
+
+ integration = integration_consumers(connection, targets, long_targets, mocks, mock_module)
+ (state / "integration.json").write_text(json.dumps(integration, ensure_ascii=False, indent=2))
+
+ # Consume the real frozen adapter transaction, barrier, config
+ # writer and supervisor stop/start. No watcher-only contract.
+ replacement_mock = stack.enter_context(mock_module.MockLLMUpstream())
+ replacement_mock.configure(protocol="openai_responses")
+ index = next(i for i, source in enumerate(sources) if source.prefix == "intent-openai-responses-unknown")
+ previous = sources[index]
+ base = replacement_mock.url + "/v1"
+ key = "fake-replaced-source-key"
+ candidate = replace(previous, base_url=base, allowed_origins=(replacement_mock.url,),
+ credential_ref=store.store_api_key(key, protocol=previous.protocol, base_url=base))
+ next_sources = [candidate if i == index else source for i, source in enumerate(sources)]
+ route, model, old_key = targets["openai_responses", "unknown"]
+
+ # Focused real consumer: invalid credentials fail validation
+ # before any child is stopped or projection is committed.
+ original_child = engine.processes[-1]
+ invalid = [replace(candidate, credential_ref=previous.credential_ref)
+ if i == index else source for i, source in enumerate(sources)]
+ try:
+ engine.sync(invalid)
+ except EngineStateError as exc:
+ assert "credential does not match" in str(exc)
+ else:
+ raise AssertionError("source validation was bypassed")
+ assert store.list_sources() == sources
+ assert len(engine.processes) == 1 and original_child.poll() is None
+ lifecycle["invalid_source_no_restart"] = "pass"
+
+ # A genuinely exiting child exercises the product's rollback,
+ # recovery health check, and failure cleanup, not a restart mock.
+ engine.fail_next = True
+ try:
+ engine.sync(next_sources)
+ except EngineUnavailableError as exc:
+ assert exc.error_key == "models.engine.health_failed"
+ else:
+ raise AssertionError("failed replacement did not surface")
+ assert store.list_sources() == sources
+ assert len(engine.processes) == 3
+ assert original_child.poll() is not None and engine.processes[1].poll() == 23
+ connection = wait_registered(engine, expected_routes)
+ assert connection.base_url != initial.base_url
+ for mock in [*mocks.values(), replacement_mock]:
+ mock.reset_requests()
+ status, _ = request(connection, "/v1/responses", payload("openai_responses", route, "future", False))
+ assert status == 200 and not replacement_mock.requests()
+ captured = mocks["openai_responses"].requests()
+ assert len(captured) == 1 and captured[0]["body"]["model"] == model
+ assert captured[0]["headers"]["authorization"] == f"Bearer {old_key}"
+ lifecycle["failed_replacement_rollback_and_recovery"] = "pass"
+
+ previous_connection, previous_child = connection, engine.processes[-1]
+ engine.sync(next_sources)
+ assert store.list_sources() == next_sources
+ assert len(engine.processes) == 4 and previous_child.poll() is not None
+ assert engine.processes[-1].poll() is None
+ connection = wait_registered(engine, expected_routes)
+ assert connection.base_url != previous_connection.base_url
+ assert store.get_source(previous.source_id).prefix == previous.prefix
+ assert store.get_source(previous.source_id).route_model_ids == previous.route_model_ids
+ for stream in (False, True):
+ for mock in [*mocks.values(), replacement_mock]:
+ mock.reset_requests()
+ status, _ = request(connection, "/v1/responses",
+ payload("openai_responses", route, "none", stream))
+ assert status == 200 and not any(mock.requests() for mock in mocks.values())
+ captured = replacement_mock.requests()
+ assert len(captured) == 1
+ assert captured[0]["body"]["model"] == model
+ assert captured[0]["body"]["reasoning"]["effort"] == "none"
+ assert captured[0]["headers"]["authorization"] == f"Bearer {key}"
+ values = set(captured[0]["headers"].values())
+ assert not {old_key, f"Bearer {old_key}", f"Bearer {connection.gateway_token}"} & values
+ lifecycle["committed_replacement_stream_and_nonstream"] = "pass"
+
+ # HTTP client cancellation plus immediate reuse of the same
+ # source. Precise upstream context cancellation is also covered
+ # by the Go executor test (this reused mock pauses deliberately).
+ mock = mocks["anthropic"]
+ mock.configure(stream="pause_after_first_output")
+ route, _, _ = targets["anthropic", "unknown"]
+ http_connection = http.client.HTTPConnection("127.0.0.1", int(connection.base_url.rsplit(":", 1)[1]), timeout=5)
+ http_connection.request("POST", "/v1/messages",
+ json.dumps(payload("anthropic", route, "strong", True)).encode(),
+ {"Authorization": f"Bearer {connection.gateway_token}", "Content-Type": "application/json"})
+ response = http_connection.getresponse()
+ assert response.status == 200
+ while True:
+ line = response.readline()
+ assert line, "stream ended before first output"
+ if b"mock response" in line:
+ break
+ if http_connection.sock is not None:
+ http_connection.sock.shutdown(socket.SHUT_RDWR)
+ response.close()
+ http_connection.close()
+ mock.configure(stream="healthy")
+ status, _ = request(connection, "/v1/messages",
+ payload("anthropic", route, "future", False))
+ assert status == 200
+ lifecycle["cancellation_and_reuse"] = "pass"
+
+ # Failed startup with no prior child cannot leave an owned
+ # listener/process behind. Product stop/health failure owns it.
+ engine.supervisor.stop()
+ engine.fail_next = True
+ try:
+ engine.supervisor.ensure_running()
+ except EngineUnavailableError as exc:
+ assert exc.error_key == "models.engine.health_failed"
+ else:
+ raise AssertionError("failed startup did not surface")
+ assert engine.supervisor.client_if_running() is None
+ assert len(engine.processes) == 5 and engine.processes[-1].poll() == 23
+ lifecycle["failed_startup_cleanup"] = "pass"
+ finally:
+ (state / "matrix.json").write_text(json.dumps(rows, ensure_ascii=False, indent=2))
+ try:
+ engine.close()
+ finally:
+ lifecycle["children"] = [
+ {**launch, "returncode": process.poll()}
+ for launch, process in zip(engine.launches, engine.processes)
+ ]
+ (state / "lifecycle.json").write_text(json.dumps(lifecycle, indent=2))
+ assert len(rows) == 380
+ for row in rows:
+ if row["stream"]:
+ peer = next(item for item in rows if all(item[key] == row[key] for key in ("frontend", "upstream", "profile", "intent")) and not item["stream"])
+ assert row["out"] == peer["out"]
+ verify_fixture(fixture, args.fixture_sha256)
+ print(json.dumps({"matrix_cases": len(rows), "successful": sum(row["status"] == 200 for row in rows),
+ "replacement": "pass", "cancellation_and_reuse": "pass", "processes_reaped": True,
+ "lifecycle_regressions": lifecycle,
+ "long_identity_cases": 24, "multi_image_cases": 3,
+ "matrix_file": str(state / "matrix.json"), "integration_file": str(state / "integration.json")}))
+
+
+if __name__ == "__main__":
+ main()