Skip to content

feat(backend): add mojo (@byted/mojo) as a per-turn remote backend - #803

Merged
deepcoldy merged 154 commits into
deepcoldy:masterfrom
swtxbling:xx_develop/mojo_botmux
Aug 18, 2026
Merged

deepcoldy merged 154 commits into
deepcoldy:masterfrom
swtxbling:xx_develop/mojo_botmux

Conversation

@swtxbling

Copy link
Copy Markdown
Contributor

Adds mojo (@byted/mojo) as a botmux backend, alongside the existing remote
backend riff.

mojo is unlike the PTY-style CLIs: it is headless and invoked once per turn,
its agent runs off-box, and it has no local per-session transcript. Most of this
diff is therefore not the adapter itself but making botmux's session lifecycle,
credential handling and isolation gates correct for a backend with those
properties.

What this gives you

Configure a bot with backendType: "mojo" (or cliId: "mojo") and an optional
mojo block in bots.json:

{
  "larkAppId": "...",
  "cliId": "mojo",
  "backendType": "mojo",
  "mojo": {
    "cloud": true,            // run tools in the cloud sandbox, not on the bot host
    "workspaceId": "ws_...",
    "agentId": "ag_...",
    "jwtEnv": "X_JWT_TOKEN",  // or `jwt` for a literal
    "systemPrompt": "...",
    "idleTimeoutSec": 300
  }
}

Everything botmux already resolves generically — binary, working dir, model,
approval bypass, launch prefix — stays on the top-level bot config. The
mojo block deliberately has no second entry point for those (see below).

Turn streaming, tool-call summaries, session resume, /close cancellation,
orphan cleanup, device isolation and the Lark card all work as they do for other
backends.

Design points worth reviewing

Public vs internal config. MojoConfig is what a user may set;
EffectiveMojoConfig is what the backend actually launches with. The split
exists because a live edit to the mojo block must not be able to override
launch identity that was frozen onto the session at creation.

The control plane is frozen per session. cloud, localDaemon, baseUrl,
ppeEnv, workspaceId and agentId are snapshotted onto Session.mojoIdentity
at first fork. Without this, editing the bot between two messages could resume or
cancel a live session against a different tenant, endpoint or workspace than
the one holding its remote session. buildEnv() also unconditionally deletes
every control-plane env var before re-deriving it from the frozen snapshot, so
mojo.env cannot reintroduce one through the environment.

Credentials stay live, but never persist. A rotated or cleared JWT must take
effect without a refork, so the live patch is applied per turn — narrowed to the
JWT only, with tri-state semantics (undefined = no new snapshot, string = use
this, null = explicit tombstone). MOJO_IDENTITY_KEYS excludes jwt/jwtEnv/
env, and the snapshot is a whitelist copy rather than a spread, so credentials
cannot leak into the session store.

Remote-execution proof fails closed. isMojoFullyRemote() requires
cloud === true, localDaemon !== true, and no wrapper at all — a wrapper
runs after the environment is built and could flip AGENT_LOCAL_DAEMON back on
after the sandbox decision was already made. Boolean checks are strict
(=== true), because localDaemon: "false" used to satisfy a !== true sandbox
check while being truthy where the child env is built: isolation skipped and
host execution enabled at once.

Unverifiable lineages are quarantined, not deleted. A row created before the
frozen identity existed cannot be safely resumed or cancelled against current
config. It is parked (mojoQuarantinedLineage) and the user is told through the
normal managed-output policy rather than a direct sessionReply, so a VC
receiver / silent scheduled turn / durable replay cannot be lit up by it.

Review history

This branch went through two rounds of adversarial review plus continuous
self-audit. Notable findings, all fixed with a regression test that fails when the
fix is reverted:

Sev Finding Fix
P0 Control-plane freeze was a guaranteed no-op for every new session — the guard read session.backendType, which createSession() never writes and forkWorker stamps only after worker.send(initMsg), i.e. after the freeze it calls. Left the "control plane edited after creation" window fully open, and made the next restart quarantine a lineage whose control plane was fully known. isMojoSessionRow(): a stamped backendType is authoritative, otherwise fall back through cliId to live bot config
P1 mojo.env bypassed the reserved-key block (BOTMUX_SESSION_ID, SESSION_DATA_DIR, LARK_APP_SECRET, CLAUDE_CONFIG_DIR) — and as the highest-precedence layer it won the merge delegates to isReservedPerBotEnvKey + env-name validation
P1 spawn() silently dropped a mandatory device-credential isolation wrapper and fed its argv to mojo as extra CLI args fails closed on an unexpected launch prefix
P1 destroySession() raced the lineage: a /close before the first init event skipped the cancel and never published the id, so the daemon's orphan fallback had nothing either — the remote session leaked while still holding the injected credential bounded wait for an in-flight turn to publish its id
P1 Wrapper resolution used a PATH the child never ran with (omitted mojo.env), so a wrapper carrying auth could resolve to the wrong binary single shared buildEffectiveChildEnv: child → bot → mojo.env
P2 Passthrough turns (/compact, /model) arrive as raw_input and carried no credential snapshot, yet become real mojo turns — a cleared JWT did not apply both daemon-side sends attach it; worker applies at write time
P2 The Lark card still rendered 11 PTY quick-action buttons for mojo (all silently inert) gate asks isRemoteCliId() via a new dependency-free core/remote-cli-ids leaf

Several rounds were spent on my own tests that passed while the code was
broken
— fences satisfied by the init handshake, source-locks whose region
spanned the wrong return, fixtures that hard-wrote post-first-fork state. Those
are now behaviour tests against real worker processes, a fake mojo binary
recording argv/env/cwd per invocation, and real session-store round trips.
Verification is organised per change point: every individual edit was reverted
in isolation to confirm at least one test goes red.

Testing

  • npx tsc --noEmit clean; pnpm build passes; git diff --check clean
  • mojo suites + touched files: 14 files / 410 tests green
  • Every change point reverted individually → a test fails in each case
  • 5 consecutive full-suite runs: 0 mojo failures

The full suite has ~31 pre-existing failures on this branch. They are identical to
the master baseline (97395d45) and none are in the 44 files touched here —
verified by comparing the failing file set, not just the count.

Known limitation

RESUME_DEAD_RE — the pattern deciding that a remote session is gone — has not
been validated against a real internal @byted/mojo binary. The public npm
package 404s, so neither I nor the reviewers could cover it. Everything around it
is tested; this specific pattern needs one E2E pass in an environment with the
internal registry and a real JWT.

liaoxiao.333 added 30 commits August 5, 2026 13:13
reconcileRiffBackendType and shutdownBackendDisposition both hardcoded a
single `=== 'riff'` comparison. Every additional remote CLI (empty
resolvedBin, backend translates write() into remote calls) would need
another shotgun edit across the same helpers.

Introduce REMOTE_CLI_IDS + isRemoteBackendType() and route both helpers
through them. The set still contains only 'riff', so this commit is
behaviour-preserving by construction.

The function keeps its historical name: it is imported by name in several
modules and renaming it would turn a contained refactor into a
cross-cutting rename.
Adds @byted/mojo as a remote CLI, following the riff pattern: an empty
resolvedBin plus a SessionBackend that translates write() into headless
CLI invocations.

Why headless-per-turn instead of a TUI adapter
  - --yolo / -r / -c / --output-format / --timeout / --idle-timeout are all
    "-p only". Passing them without -p does not launch a TUI; the process
    blocks on stdin until EOF.
  - mojo keeps NO local per-session transcript (~/.mojo holds only
    credentials/ memory/ skills/; session state is server-side), so the
    grok-style "tail the transcript for turn end" bridge is impossible and
    only unreliable screen-scraping would remain.

Why foreground streaming instead of --background + polling
  --background is CREATE-ONLY (verified: "--background 不支持:--resume"
  and "--background 不支持:--continue"). A chat bot is multi-turn, so a
  create-only submit path would start a fresh context-less session on
  every message. Foreground `-p -r <sid>` resumes correctly and also gives
  token-level streaming plus an exact turn boundary from the result event.

Behaviours worth calling out in review
  - ask-user is auto-skipped in headless mode and CANCELS the turn. We
    detect that warning and tell the user what to supply, instead of
    leaving them with a silently empty reply.
  - A session stays RUNNING briefly after the foreground process exits.
    botmux flushes queued follow-ups exactly at the turn boundary, so this
    race is hit reliably; retried with backoff rather than surfaced.
  - A dead resume lineage (expired/GC'd session) drops the stored id and
    broadcasts null, so the next message starts fresh instead of re-sending
    the same doomed `-r <sid>` forever. NOTE: the detection regex is not
    empirically verified (mojo was not installable in this environment) and
    is deliberately broad + gated on `-r` actually being passed. Needs
    calibration against real output.
  - onExit is NOT fired per-turn (the binary exits every turn; forwarding
    that would tear the session down after the first reply) but IS fired
    from kill(), mirroring RiffBackend so the worker learns of teardown.
  - Blast radius is bounded by --cloud, NOT by per-tool approval: verified
    that without --yolo a cloud-sandbox `rm -rf` still succeeded, contrary
    to what --help implies.

Wiring beyond the union types: remote-backend pairing (a mojo cliId must
not spawn pty/tmux against an empty bin), device-isolation safe_remote,
local sandbox bypass, no local reproduce command, no native rename, the
bots.json `mojo` config block, and the remote settle delay.
Completes the remaining steps of the official "添加新 CLI 适配器" checklist
in src/adapters/cli/CLAUDE.md.

CLI_ID_CHOICES gets mojo APPENDED as 25 rather than inserted: the numbering
is the stable interface for scripted (non-TTY) setup, so inserting would
make existing scripts silently select the wrong CLI.

Note that worker.ts's CLI_DISPLAY_NAMES is Record<string, string> — unlike
card-builder's and bot-config-editor's Record<CliId, string>, tsc does NOT
catch a missing entry there, so it has to be added by hand.
Two unit files, no real mojo binary and no JWT required.

mojo-backend.test.ts drives a fake `mojo` shell script emitting canned
NDJSON: session-id adoption from the first event, delta streaming without
duplicating the trailing whole-segment text, both tool_result shapes, the
ask-user cancellation, error-object formatting, the RUNNING-race backoff,
invalid-model stderr, and dead-lineage recovery (including the negative
case: no resume attempted must NOT clear the lineage).

Framing cases call the incremental parser directly instead of going
through a subprocess — that is the only reliable way to control chunk
boundaries, and it covers the half-line-across-chunks case a canned
subprocess cannot reproduce.

mojo-wiring.test.ts locks the cross-cutting invariants that compile fine
but break at runtime: the pairing rule that keeps a mojo cliId off
pty/tmux (its resolvedBin is empty, so the failure lands at spawn, not at
config time), the local-sandbox bypass, and the absence of a local
reproduce command. It also pins riff's existing pairing behaviour so the
generalization in the first commit cannot regress unnoticed.
… riff check

Rebasing onto master surfaced a wiring point added upstream (deepcoldy#619's
fastToggleUnsupportedBackend), which prompted auditing ALL 23 files that
reference 'riff' instead of fixing them one crash at a time. None of these
are caught by tsc.

Applies to mojo for the same reason it applies to riff — one write() becomes
one remote turn, and there is no local terminal:
  - daemon.ts        /fast toggle: fail closed instead of silently no-op
  - worker.ts        generic startupCommands are PTY semantics (text, then
                     Enter 200ms later) and would split into two turns
  - worker.ts        term_action would post an ANSI escape sequence as a turn
  - worker.ts        native session rename (worker-side counterpart of the
                     daemon-side guard already added)
  - dashboard        cliId→backendType auto-pairing, otherwise picking mojo in
                     the dashboard leaves backendType unset and spawn goes to
                     pty against an empty resolvedBin
  - config store     'mojo' was missing from backendType's enumValues, so
                     `/config set backendType mojo` was rejected outright, and
                     there was no `mojo` field spec to set the config block with

SECURITY: the config store's secret-redaction branch was riff-only, so a mojo
block fell through to the generic json branch and JSON.stringify'd the whole
object — posting `jwt` in cleartext to `/config get`, the config card and the
change log. Verified by reverting the fix and watching the new test catch the
literal token. Comment added so the next backend config block does not repeat
it.

Also corrects an earlier mistake of mine: RAW_CLI_EXECUTABLES.mojo was
undefined, copying riff. But riff/mira are pure HTTP and genuinely need no
local command, whereas MojoBackend spawns the binary EVERY turn. Declaring it
lets `botmux setup` fail fast on a missing install instead of letting the first
IM message die with ENOENT.

Deliberately NOT wired (riff-specific, cloning user repos into the remote
sandbox — mojo has no such concept): default-worktree.ts, command-handler.ts's
worktree push, card-handler.ts's nextSessionUsesRiffBackend, and cli.ts's
in-sandbox api-only bootstrap.

Generalizes the pairing helpers further with isRemoteCliId() so the dashboard
path shares one definition instead of hardcoding a third comparison chain.
mojo-config-surface.test.ts pins the JWT redaction: it was verified to FAIL
(rendering `{"jwt":"super-secret-token-value",...}`) with the fix reverted, so
it guards a real leak rather than restating the implementation. Also pins that
'mojo' is a settable backendType and that an absent block renders as ∅ instead
of leaking `undefined`.

mojo-wiring.test.ts gains isRemoteCliId coverage and locks the deliberate
asymmetry against riff: rawCliExecutable('mojo') === 'mojo' (spawned per turn,
setup must check it) while rawCliExecutable('riff') stays undefined (pure HTTP).
Review found that the previous commits wired mojo into every config/type
surface but left the actual daemon → worker → backend runtime path on the
riff-only branches. Each of these is invisible to tsc.

1. ready/idle. The IdleDetector gate and the post-spawn markPromptReady()
   both tested `=== 'riff'`, so a mojo session got neither: the first
   message waited for the ~15s first-prompt fallback, and the generic
   detector — which infers "done" from ~2s of output quiescence — could
   fire mid-turn while a tool was running. That would re-arm prompt-ready
   before the real `result` event, flushing queued messages into a session
   that is still RUNNING and attributing the reply to the wrong turn/card,
   defeating the exact boundary MojoBackend already provides. Both gates now
   use isRemoteBackendType(); the rationale lives on MojoBackend.settleTurn,
   which is the authority being protected.

2. resume lineage. The daemon already persisted mojo's session id (the
   generic backend.onTaskId → riff_task_id IPC path is shared by both remote
   backends), but only riff translated it back on spawn. So a daemon
   restart, /relay or worker rebuild silently started a fresh context-less
   session. Now mapped: cfg.riffParentTaskId → resumeCliSessionId.

3. host-owned settings were dropped. MojoBackend.spawn ignored SpawnOpts
   entirely and the config was never merged with the generic session config,
   so workingDir (repo selection), per-bot env, the dashboard/setup `model`,
   `disableCliBypass` and `cliPathOverride` all had no effect — with
   cliPathOverride the install check could validate /custom/mojo while the
   runtime still spawned a bare `mojo`. There is now one effectiveMojoConfig
   built in the worker (mojo block wins, session value is the fallback), and
   spawn() keeps cwd/env/injectEnv for buildEnv().

4. SECURITY, sandbox/isolation fail-open. localSandboxApplies() and the
   device-isolation `safe_remote` disposition treated mojo as unconditionally
   remote. But `cloud` is OPTIONAL and `localDaemon` can be explicitly
   enabled — MojoBackend spawns the binary locally every turn. So a bot with
   `sandbox: true` silently ran unisolated, and credential activation could
   proceed while a local mojo child was mid-turn. A bypass now requires proof
   (`cloud === true && localDaemon !== true`); anything else keeps the local
   sandbox engaged, and because MojoBackend cannot launch its per-turn child
   under the sandbox wrapper, that combination now fails CLOSED with an
   actionable message instead of pretending to be sandboxed.

5. close/suspend lifecycle. The 24s close backstop, the workerless orphan
   cancel and the non-destructive suspend were all riff-only. mojo's
   destroySession runs `mojo session cancel` (CLI timeout 60s), so a 2s
   SIGTERM killed it before the cancel left the box; a workerless /close
   never cancelled the remote session at all; and suspend called
   destroySession, cancelling a session that is supposed to resume. Adds
   cancelMojoSessionById() for the workerless path, mirroring
   cancelRiffTaskById.

Also: backendType validation in bot-config-editor still rejected "mojo"
outright, and the lexical-repair path in worker-pool keyed off riff alone.
Supporting changes for the runtime wiring commit, kept separate because they
change SHARED helpers rather than mojo-only paths:

- sandbox.ts: localSandboxApplies() takes the remote-execution inputs and
  gains isMojoFullyRemote() as the single definition of "provably off-box"
  (cloud on, localDaemon off). Undefined config counts as local — the safe
  direction.
- session-backend-selector.ts: an unproven mojo session that requested
  sandbox now returns an actionable error instead of undefined.
- device-isolation-daemon.ts: `safe_remote` requires remoteExecutionProven.
  Resolved from the worker's frozen backendConfig, falling back to bot
  config, defaulting to false if the bot is deregistered.
- worker-pool.ts: remote close grace + workerless orphan cancel now cover
  both remote backends; lexical output repair keys off isRemoteBackendType.
- bot-config-editor.ts: accept "mojo" in the explicit backendType validator.
mojo-worker-wiring.integration.test.ts boots a REAL worker against a fake
`mojo` binary that records its argv/cwd/env, so the assertions are about what
would actually have been executed. This is the layer the previous tests were
missing: every bug it covers passed the backend unit tests, because the
backend was correct in isolation and the defect was in the worker handoff.

Covers first-prompt promptness (1.1s, vs the ~15s fallback it used to wait
for), workingDir/per-bot env/model/disableCliBypass propagation, resume from
the persisted lineage, and the fail-closed sandbox refusal.

Reverse-verified: reverting the lineage and model/bypass merges makes exactly
3 of these fail, so they guard real behaviour rather than restating the
implementation.

mojo-wiring.test.ts's sandbox expectations are REWRITTEN, not extended — they
previously asserted the fail-open behaviour (localSandboxApplies('mojo')
always false) that review flagged.

worker-durable-expiry-order.test.ts asserts on a source literal that this
branch changed (riff-only → isRemoteBackendType); updated with a note on why.
The raw-input-followup-atomicity scan needed no change: its fixed 2300-char
window was overrun by added comments, so the mojo rationale moved to
MojoBackend.settleTurn — where the invariant actually lives.
Three findings from the second review round. All three reproduced exactly as
reported.

1. SECURITY, per-bot JWT was overridden by the daemon's ambient one.
   buildEnv() layered worker env → per-bot env → mojo.env correctly, then read
   the JWT back from process.env and overwrote the merged value. So a bot with
   env.X_JWT_TOKEN=per-bot-jwt running under a daemon with
   X_JWT_TOKEN=ambient-jwt executed as the HOST identity. This line survived
   verbatim from the pre-SpawnOpts version and was never updated when the env
   layering was introduced. Now read from the merged env, which yields the
   intended precedence for free: mojo.jwt > mojo.env > per-bot env > ambient.

2. workerless /close dropped every generic setting. The daemon passed a bare
   `botCfg.mojo`, which carries neither the pinned binary (cliPathOverride) nor
   the per-bot env holding the JWT — and since that path has no worker, it never
   calls spawn() and cannot recover them from SpawnOpts. A bot running fine on a
   custom path/identity therefore could not be cancelled once its worker died,
   leaving the remote session consuming cloud sandbox time while still holding
   injected credentials. Extracted buildEffectiveMojoConfig() as the single
   builder both sides use.

3. wrapperCli was silently ignored. The worker resolved the prefix, logged
   "Launch prefix: …", then MojoBackend discarded bin/args and ran
   `config.bin ?? 'mojo'`. Now supported rather than refused: the prefix is
   re-applied to EVERY per-turn invocation, since unlike a PTY CLI there is no
   single long-lived process to wrap once. The daemon's cancel path resolves the
   prefix from config (no spawn() there), so teardown reaches a
   wrapper-dependent setup too. If a wrapper is configured but the worker
   supplied no launch binary — sandbox takes precedence, for instance — that is
   logged as a warning instead of quietly running unwrapped.

A launch prefix can only ever reach this backend from wrapperCli: the mojo
adapter's resolvedBin is '' with empty buildArgs, and the sandbox wrappers that
also rewrite spawnBin are unreachable here (a fully-remote session never
requests the local sandbox; a locally-executing one that does is refused before
spawn). Noted at the call site so a future sandbox change is not mistaken for a
wrapper.
Fixes a test of mine that review correctly called out as not doing what its
name claimed: "…and cliPathOverride through" never set that field and never
asserted which executable ran. The fake mojo now records its own $0, so the
new test actually proves the pinned binary is the one executed — and the old
test name no longer overclaims.

mojo-worker-wiring gains the JWT precedence matrix (ambient-only, per-bot wins
over ambient, mojo.jwt wins over both) and a wrapperCli probe asserting
WRAPPER_MARK reaches the child while the prompt still arrives.

mojo-orphan-cancel.test.ts is new and covers the daemon side with a real fake
binary: the pinned path runs, the per-bot JWT is carried, the wrapper prefix is
applied, and a missing binary reports failure instead of throwing (teardown
must not crash). It also pins buildEffectiveMojoConfig's precedence rules,
including two easy-to-regress ones — a blank override must not become
`spawn('')`, and an explicit `disableCliBypass: false` must survive (`??`, not
`||`).

Two notes on honesty of coverage:
  - The daemon call site is inline in destroyOrphanedBackingSession and needs a
    full DaemonSession + registry to exercise, so it is pinned with a source
    assertion in the repo's existing style. Verified by reverting to
    `botCfg.mojo ?? {}`, which fails exactly that assertion.
  - The wrapper test must put the fake binary on PATH, because a wrapperCli
    names its own target (`… mojo`) and that name resolves on PATH rather than
    inheriting cliPathOverride. That is pre-existing wrapperCli semantics shared
    with the other CLIs, not something this branch changes; called out in the
    test so it is not read as a bug.

Reverse-verified: reverting the JWT merge and the launch-prefix capture fails
exactly the two corresponding tests.
…I args

Fourth review round. All four findings reproduced.

1. [P1] workerless /close read the LIVE bot config for the launch identity.
   Session semantics freeze cliId/cliPathOverride/wrapperCli/model at creation
   so later bot edits never retroactively change a live session. The remote
   session was created through the FROZEN wrapper/binary, so cancelling through
   whatever the bot has now can reach the wrong gateway or tenant. Worse, the
   `agentFrozen` contract states verbatim that a session frozen with no wrapper
   must never inherit one the bot gains later — my code did exactly that.
   Adds frozenSessionLaunchIdentity(), a READ-ONLY reader: sessionAgentConfig()
   cannot be reused here because it freezes and writes to the session store,
   which a teardown path must not do. Only a never-frozen legacy session falls
   back to live bot config, mirroring that function's back-fill.

2. [P1] `mojo.wrapperCli` was publicly accepted but the two paths disagreed.
   The worker builds its prefix from the TOP-LEVEL wrapperCli only, while the
   cancel path resolves it from config — so a block-only wrapper meant "run
   bare, cancel wrapped". Review offered two options; taking the narrower one:
   wrapperCli stays a single top-level field. buildEffectiveMojoConfig drops any
   block value, and `/config set mojo` now REJECTS it
   (reason: mojo_wrapper_cli_top_level_only) rather than dropping it silently,
   because a silent drop reads to the operator as "applied". Making the worker
   honour a block wrapper instead would have meant reimplementing its whole
   wrapper pipeline (ttadk gateway injection, sandbox-takes-precedence, cjadk
   special-casing) against a second source of truth. The field stays on the type
   as documented INTERNAL plumbing so the cancel path can reconstruct the launch.

3. [P2] CLI_EXTRA_ARGS was dropped when no wrapper was configured. The mojo
   adapter's buildArgs() returns [], so anything arriving at spawn() came from
   the worker's shared arg pipeline. With a wrapper it survived (buildWrappedLaunch
   folds spawnArgs into the prefix) and without one it vanished — a
   config-dependent inconsistency. Now retained and re-applied per turn, inserted
   after our own flags (so an operator can override them) and before the
   positional prompt (which must stay last).

   Deliberately NOT applied to runCli(): `session cancel` / `auth status` are
   subcommands, and the flags people put in CLI_EXTRA_ARGS (e.g. --timeout) are
   "-p only" and would break them.
…bility

Adds real-worker / real-fake-binary coverage for all four round-4 findings, plus
the macOS portability fix.

New behaviour tests:
  - CLI_EXTRA_ARGS reaches argv with no wrapper configured, and the positional
    prompt still ends up last.
  - A wrapper declared only inside the mojo block takes effect on NEITHER path:
    the run path (worker probe) and the cancel path (fake-binary probe) now agree,
    where review found run-bare / cancel-wrapped.
  - `/config set mojo` rejects a block wrapperCli with a self-describing reason,
    while the same block without it is accepted.

Frozen launch identity is pinned with source assertions in the repo's existing
style: exercising it for real needs a full DaemonSession plus a registry, and the
value being protected is precisely that the live bot fields are NOT read. The
second assertion checks the frozen branch contains no `botCfg.` fallback at all,
since a stray `??` there is what would resurrect a later-added wrapper.

macOS portability: temp roots are now realpathSync()'d, matching
test/claude-code-cwd.test.ts. os.tmpdir() is a symlink there (/var →
/private/var), so a child process reports the resolved path and the raw cwd
comparison failed. Applied to every temp root in both files, not just the one
assertion that happened to fail, so future cwd assertions stay portable.

Also renamed a test that overclaimed: it asserts the run path does not launch a
block-only wrapper, which is not the same as proving the block value is ignored
everywhere — the cancel-path test in mojo-orphan-cancel.test.ts covers that half.

Reverse-verified: reverting the frozen-identity read, the block-wrapper drop and
the extra-args retention fails exactly the three corresponding tests.
…3 findings

Fifth review round found three problems that were all the same shape: after
making `wrapperCli` top-level-only I left the OTHER launch-identity fields with
two entry points, and only closed one of the two config doors. Taking review's
structural suggestion instead of patching each field.

MojoConfig (public, bots.json / `/config set mojo` / dashboard) now contains
ONLY settings with no platform-wide equivalent: workspaceId, agentId, cloud,
idleTimeoutSec, stream, systemPrompt, jwt, jwtEnv, baseUrl, localDaemon, ppeEnv,
env.

EffectiveMojoConfig (internal, what MojoBackend runs on) adds the platform-owned
launch identity — bin, cwd, model, disableCliBypass, wrapperCli,
resumeCliSessionId, extraCliArgs — resolved by the worker or reconstructed by the
daemon from the session's FROZEN values. Built only via
buildEffectiveMojoConfig(); there is no longer a precedence question to answer,
because each of those keys has exactly one source.

1. [P1] live `mojo.bin` / `mojo.model` could override the frozen identity.
   The builder took `block.X ?? generic.X`, and generic is now the frozen value,
   so adding `mojo.bin` after session creation made the workerless cancel run a
   different binary than the one that created the remote session — wrong gateway
   or no cancel at all. `mojo.model` could likewise override the frozen session
   model on a cold resume. Both keys are now stripped and rejected.

2. [P1] bots.json was not fail-closed. Only coerceConfigValue() rejected
   wrapperCli, while parseBotConfigsFromText() accepted `entry.mojo` wholesale —
   so a hand-edited file parsed fine, kept the wrapper in memory, and the builder
   dropped it later, leaving the worker running bare. That is precisely the
   dangerous case when the wrapper carries auth. Now rejected at parse time with
   the owning top-level field named, sharing one key list
   (MOJO_INTERNAL_CONFIG_KEYS) with the config-command path so the two doors
   cannot drift.

3. [P2] CLI_EXTRA_ARGS precedence inverted with a wrapper configured.
   buildWrappedLaunch folds whatever it is given into the prefix, i.e. BEFORE the
   backend's per-turn flags, so `CLI_EXTRA_ARGS=--idle-timeout 77` plus
   `mojo.idleTimeoutSec=12` yielded `--idle-timeout 77 … --idle-timeout 12` and
   last-value-wins picked 12 — the opposite of the documented behaviour, and
   inconsistent with the no-wrapper path. The worker now hands the generic args to
   the backend through the config and resolves the prefix with `[]`, so the prefix
   holds the wrapper alone and the extras are appended after our own flags on
   every turn.

The `/config set mojo` rejection reason now carries the offending keys
(mojo_internal_key_top_level_only:bin,model) since it is surfaced verbatim to the
user.
Two of the rewritten assertions were pinning the WRONG behaviour and review was
right to cite them as evidence:
  - "folds generic session settings in, with the mojo block winning" asserted
    block.bin beats the frozen path — the bug itself. Replaced with a test that
    the launch identity comes only from the generic (frozen) source, plus one
    proving an internal key in the block yields `undefined` rather than the live
    value (i.e. the block is not a fallback source either).
  - "does not launch a wrapper declared only inside the mojo block" documented
    the silent bare-run. bots.json now rejects that outright, so the run-path
    probe was narrowed to a stale/forged init payload and a new test asserts
    loadBotConfigs() throws, naming the owning top-level field.

New coverage:
  - Every internal key is rejected by `/config set mojo`, while a block of
    genuinely mojo-specific settings is still accepted.
  - CLI_EXTRA_ARGS overrides a built-in flag BOTH with and without a wrapper
    (loops over the two configurations): two `--idle-timeout` occurrences with
    the operator's value last, and the wrapper still applied when configured.
  - disableCliBypass:false survives from the generic source (`!== undefined`,
    not `||` — false is meaningful here).

The JWT-redaction fixture used `mojo.model`, which the new parse-time validation
now rejects; switched to `workspaceId`, which is genuinely mojo-specific, so the
test still proves non-secret fields stay visible.

Reverse-verified: reverting all three fixes fails exactly 5 of these tests,
covering each finding.
…he IPC type

Sixth review round. All three findings reproduced.

1. [P1] SECURITY — wrong types produced a sandbox fail-open.
   Both config doors rejected unknown/internal KEYS but never checked types, and
   `localDaemon: "false"` then meant two contradictory things: isMojoFullyRemote()
   compares strictly, so `"false" !== true` read as "not local, safe to bypass the
   local sandbox", while buildEnv used a truthy check and emitted
   AGENT_LOCAL_DAEMON=1. Isolation skipped AND host execution enabled. A typo like
   `cluod: true` was equally dangerous: cloud silently unset, tools on the host.

   Adds normalizeMojoConfig() as the ONE validator: unknown keys, internal
   launch-identity keys and wrong types are all rejected, with every problem
   reported at once. Wired into bots.json parsing, `/config set mojo`, and
   defensively at the worker boundary (which the two config doors cannot cover —
   a stale IPC payload from an older daemon reaches neither).

   Also aligned the comparisons themselves: `cloud`, `localDaemon` and
   `disableCliBypass` now use `=== true` / `!== true` everywhere, so the sandbox
   decision and the argv/env construction cannot diverge again even if something
   slips past validation. Defence in depth, not a substitute for it.

2. [P1] control-plane config was still live, so a session could be re-identified.
   Cold resume and workerless cancel both read the CURRENT `botCfg.mojo`, so
   editing the bot between two messages could move an existing session from cloud
   to host execution, resume it against a different tenant (baseUrl) or workspace,
   or switch its PPE profile — and `/close` would cancel against an endpoint that
   never created the remote session.

   Freezes the control-plane identity (cloud / localDaemon / baseUrl / ppeEnv /
   workspaceId / agentId) onto the session as `Session.mojoIdentity`, mirroring
   how cliId/wrapperCli are frozen. Credentials (jwt / jwtEnv / env) and
   behaviour knobs (stream / systemPrompt / idleTimeoutSec) stay LIVE, so a
   rotated token takes effect and — per review's caution — no plaintext JWT is
   persisted into session state.

   Applying the snapshot DELETES an identity key that was absent at creation
   rather than leaving the live value, otherwise a newly-added baseUrl/workspaceId
   would leak into an existing session. A drift is logged as a warning: quietly
   ignoring an operator's config change would be its own surprise. Teardown passes
   freeze:false so it never mutates session state, and a session predating the
   field keeps running on live config exactly as before.

3. [P2] the IPC declared EffectiveMojoConfig but carries MojoConfig.
   EffectiveMojoConfig only exists after buildEffectiveMojoConfig() runs in the
   worker; structural typing let the subset assignment through, hiding the
   boundary error. Corrected to `RiffBackendConfig | MojoConfig`.

   Also rewrote the worker comment that still claimed "an explicit value in the
   `mojo` block wins" — the opposite of the current design — with an explicit
   note not to reintroduce a `block ?? generic` merge, since that was the
   double-entry-point bug.
…l plane

mojo-config-validation.test.ts (new, 18 cases) pins the validator, with the
security case stated explicitly: `localDaemon: "false"` must be rejected, because
it satisfied the sandbox check's strict `!== true` while being truthy where the
child env is built. It also asserts the two decisions now agree for real booleans,
so a future change to either cannot silently re-open the gap.

Identity-freeze coverage asserts what must NOT be captured as much as what must:
credentials never enter the frozen snapshot (no plaintext JWT in session state),
absent keys are omitted rather than stored as undefined, and a rotated JWT is not
reported as identity drift.

Real-worker probes:
  - a stringified boolean in the init payload makes the worker refuse to launch
    (this is the path the two config doors cannot cover)
  - baseUrl/workspaceId reach the child, so a tenant switch is observable end to
    end — the baseline the freeze protects

Two existing tests were UPDATED because the behaviour is now stronger, not
because they broke:
  - "does not launch a wrapper smuggled in through the mojo block" asserted a
    silent bare run; the worker now refuses outright, naming the top-level field
    that owns wrapperCli.
  - the workerless-cancel source assertion now requires sessionMojoConfig BEFORE
    buildEffectiveMojoConfig, and that neither the bare block nor the live config
    reaches the cancel helper.

The freeze logic itself is pinned with source assertions: exercising it needs a
full DaemonSession plus registry, and the property being protected is precisely
that the live config is NOT read.

Reverse-verified: reverting strictBoolean and the two sessionMojoConfig call
sites fails exactly 7 of these tests, including the end-to-end worker refusal.
Seventh review round. All five findings reproduced.

1. [P1] live `env` bypassed the freeze entirely.
   `baseUrl` and `ppeEnv` are frozen, but the mojo CLI reads them from env — and
   buildEnv() only overwrote AGENT_BASE_URL / MOJO_PPE_ENV *conditionally*
   (`if (config.baseUrl)`). So a session whose frozen snapshot had no baseUrl
   silently inherited whatever the live per-bot `env` provided, moving it to
   another tenant. Worse, a bot configured through `env` from the start never had
   its control plane captured in the snapshot at all.

   Introduces MOJO_CONTROL_ENV_KEYS and DELETES all of them after merging, then
   re-derives from the (frozen) config alone. AGENT_LOCAL_DAEMON is now written
   unconditionally too, so an ambient `AGENT_LOCAL_DAEMON=1` cannot enable host
   execution. `X_JWT_TOKEN` stays live, per review — a rotated credential must
   keep working. Setting a control-plane var inside `mojo.env` is REJECTED at
   config time (naming the real setting) rather than silently stripped, which
   would read as "applied".

2. [P1] legacy sessions were migrated lazily, so they could bind to a new tenant.
   sessionMojoConfig() only froze at the next worker fork, while
   restoreActiveSessions() neither migrated nor persisted. After a restart but
   before a session's next wake, a config edit was therefore adopted as that
   session's "original" identity — pairing a lineage created on tenant A with
   tenant B.

   Adds migrateMojoSessionIdentities(), run right after restoreActiveSessions()
   (which completes before the dispatcher can deliver a message). Empty snapshots
   are persisted so `{}` ("frozen with nothing set") stays distinguishable from
   `undefined` ("predates the field").

   A legacy row that ALREADY holds a remote lineage cannot be migrated safely —
   nothing records which control plane created it. Rather than guess, the lineage
   is dropped so the next message starts fresh on a known control plane. Losing
   context beats resuming, or cancelling, against the wrong tenant.

3. [P2] device isolation read live bot config for a workerless session, so one
   frozen as local (since switched to cloud) was classified safe_remote, and vice
   versa. Now prefers session.mojoIdentity; live config is an explicit legacy
   branch for rows the migration could not reach (bot deregistered at restore).

4. [P2] the drift warning logged old and new values verbatim. The URL validator
   accepts userinfo and query strings because they are legitimate endpoints, so
   `https://user:password@host/api?sig=secret` went straight into the daemon log.
   Now logs KEY NAMES only. Booleans are still shown, since cloud→host execution
   is the transition the warning exists to surface and is not a secret.

5. [P3] the `/config set mojo` hint still advertised `model`, which is now
   rejected. Replaced with the actual accepted field list plus a pointer to the
   top-level `model` / `cliPathOverride`.
…nd trip

mojo-identity-persistence.test.ts is new and is the test review asked for
specifically: a REAL session-store write + module reload, not an in-memory
assertion. It proves the snapshot survives a restart (the exact window where a
config edit could re-identify a session), that a reloaded `{}` stays
distinguishable from `undefined`, that drift is still detected against the
reloaded value, and that no plaintext credential reaches disk.

Real-worker probes for the env back door:
  - per-bot env supplying AGENT_BASE_URL / MOJO_PPE_ENV does not reach the child
  - an ambient AGENT_LOCAL_DAEMON=1 cannot enable host execution
  - a configured baseUrl/ppeEnv DOES reach it, overriding any inherited value
    (the strip must not break the legitimate path)

Redaction coverage asserts the absence of secrets rather than the presence of a
format: the URL case checks the password, both signed tokens and both hostnames
are all missing from the log line, while the boolean case checks cloud→host IS
shown.

The migration and isolation-precedence changes are pinned with source assertions
(ordering: restore → migrate; frozen identity read before live config; lineage
dropped for an unverifiable legacy row) — exercising them needs a full daemon
boot plus registry, and the property being protected is that live config is NOT
consulted.

Reverse-verified: reverting all five fixes fails exactly 6 of these tests,
including the end-to-end env probe.
…ineages

Eighth review round. All five findings reproduced.

1. [P1] SECURITY — wrapperCli could re-enable local execution AFTER the
   isolation decision. buildEnv() strips the control-plane env vars, but the
   launch prefix runs later and rewrites the very input the decision depended on:
   `wrapperCli = "env AGENT_LOCAL_DAEMON=1 mojo"` restored host execution while
   the local sandbox had already been skipped on the strength of "provably
   remote". Inspecting the wrapper string is not sufficient — a wrapper can be a
   script that sets it internally — so ANY wrapper now voids the proof and the
   local sandbox stays engaged. isMojoFullyRemote moved to mojo-types as the
   single definition; sandbox.ts re-exports it.

2. [P1] CLI_EXTRA_ARGS could override the frozen control plane. Extra args are
   appended after the backend's own flags (the documented override contract), but
   last-value-wins meant `--workspace-id workspace-b` also beat the frozen
   workspace, and likewise --agent-id / --cloud / --model / --yolo / -r. Reserved
   flags are now refused at the worker boundary and, defensively, dropped in the
   backend (which the daemon's cancel path also constructs). Matching covers
   `--flag value`, `--flag=value`, bare booleans and negated forms.

3. [P1] a cancel could still fire on an unverifiable lineage. The caller captured
   `remoteId` BEFORE calling sessionMojoConfig(), so clearing the field inside did
   not stop it. Per review, sessionMojoConfig now returns an explicit
   `usable | quarantined | none` state and the cancel is gated on it, rather than
   relying on a side effect the caller had already read past.

   The window itself is also closed: freezing now happens BEFORE a row is
   registered into the active map (restoreActiveSessions runs with the dispatcher
   already live), and resumeSession — the second path that re-registers a legacy
   row — is covered too.

4. [P2] dropping the lineage was not a complete fail-closed. The id was deleted,
   so the user silently lost context and the remote session became
   unreachable for manual cleanup. It is now PARKED as
   `Session.mojoQuarantinedLineage`: preserved for inspection, removed from the
   active slot so nothing auto-resumes it, and never cancelled automatically.

5. [P2] "credentials stay live" was not true for a running worker. The mojo block
   was read once at init, so every later per-turn invocation kept the ORIGINAL
   JWT. Adds MojoBackend.applyLivePatch() plus a validated credential/behaviour
   patch that rides along with each turn, sent only when it differs from what the
   worker was given. The patch is restricted to MOJO_LIVE_PATCH_KEYS and passed
   through normalizeMojoConfig, so it can never widen into the control plane.

freezeMojoIdentityForSession lives in its own leaf module rather than
worker-pool: session-manager needs it, and many tests mock worker-pool
wholesale — importing it from there made every such mock incomplete and broke ~40
unrelated tests (caught by the full run, fixed by the extraction).
Review's criticism was correct and is the reason this round's runtime problems
survived 104 passing tests: the migration and cancel wiring were pinned with
source-string assertions, which cannot observe a cancel firing on a quarantined
lineage or a row becoming visible before it was frozen.

DELETED all five source-assertion blocks from mojo-orphan-cancel.test.ts.

mojo-identity-freeze.test.ts (new) calls the real freezeMojoIdentityForSession /
migrateMojoSessionIdentities against a real session store and a real bots.json:
freezing, empty-snapshot persistence, idempotence, quarantine (preserved id,
cleared active slot, surviving a reload), non-mojo rows, and the deregistered-bot
path. The "no plaintext credential" assertion now reads the RAW STORE FILE — review
noted the previous one only checked the reloaded object.

MojoBackend.applyLivePatch is tested through actual invocations: a fake mojo
appends its X_JWT_TOKEN on every call, so turn 1 vs turn 2 proves a rotated
credential reaches the next turn without a refork. Also that a patch carrying
control-plane keys is ignored.

Worker probe loops over all seven spellings of a reserved flag
(`--workspace-id value`, `--workspace-id=value`, bare `--cloud`, `-r`, …) and
asserts each is refused, plus one asserting a legitimate `--idle-timeout`
override still works — the refusal must not break the documented contract.

Wrapper-voids-the-proof and the live-patch key split are covered as unit cases,
including that a control-plane change is NOT reported as a live change.

Reverse-verified: reverting each fix independently fails exactly the
corresponding tests (wrapper proof 2, extra-arg refusal 1, credential rotation 2,
quarantine 2).
Ninth review round. All six findings reproduced. Four were state-transition
errors introduced by the previous round's own fixes.

1. [P1] SECURITY — a live `env` patch could replace the executable. With no
   cliPathOverride the backend spawns the bare name `mojo`, so a validated
   `env: { PATH: … }` patch ran a different binary on the next turn; NODE_OPTIONS
   / LD_PRELOAD / DYLD_* are comparable. Enumerating dangerous variables cannot be
   made complete, so MOJO_LIVE_PATCH_KEYS is now just `['jwt']` and `env` is not
   patchable at all. jwtEnv is resolved DAEMON-side across the same layers
   buildEnv uses, so rotation still works while the worker never receives a map.
   The binary is also pinned once per session, removing the class of problem
   rather than one instance.

   Review's framing was right: "a compromised daemon" is not the boundary that
   mattered here — the problem was that a completely legitimate, validated patch
   could change what gets executed.

2. [P1] the JWT could be neither cleared nor rolled back. pickMojoLivePatch
   omitted `undefined` and applyLivePatch skipped it, so deleting `mojo.jwt` left
   the old token live for the worker's lifetime. And diffing the live config
   against the INIT snapshot meant `init A → patch B → rollback to A` compared A
   with A and sent nothing, leaving the backend on B. Now a COMPLETE snapshot with
   `null` as a tombstone, sent every turn and de-duplicated by the backend against
   its own value — the only authoritative source. (Clearing falls back to the host
   login, which is the intent, and is asserted separately so it is not misread.)

3. [P1] an old quarantine poisoned every later lineage. Once an identity is
   frozen, anything created afterwards was created on that known control plane —
   but the session was reported quarantined forever, so a NEW session could never
   be cancelled after its worker died and kept consuming cloud sandbox time.
   Quarantine is now bound to the specific id; the parked one is an audit record.

4. [P1] device isolation still classified a wrapped mojo session as safe_remote.
   wrapperCli lives on the top-level session, not in the mojo block or the frozen
   identity, so it has to be folded in explicitly — the worker's own gate was
   fixed last round while this classifier was not.

5. [P2] `mojo.env` no longer overwrites the merged env, because env is not
   patchable at all.

6. [P2] quarantine is now user-visible: a pending-notice flag is persisted with
   the parked id and delivered on the next turn (restore/resume have no reply
   context), telling the user the context was parked, that the next message starts
   fresh, and which id needs manual cleanup.

Also collapses the duplicated freeze/quarantine logic in sessionMojoConfig onto
the shared helper — the two copies had already begun to drift.
…ation

Fills in the matrix review asked for, all as real behaviour tests.

Credential state transitions, driven through actual CLI invocations (the fake
mojo appends its X_JWT_TOKEN on every call, so turns are directly comparable):
  A → B          rotation
  A → B → A      rollback, which diffing against the init snapshot missed
  A → cleared    the tombstone case, which a sparse patch could not express
  undefined      no-op when the daemon has nothing to say
Plus: clearing falls back to the host login (asserted explicitly so the clear case
is not misread as "auth disabled"), a patch cannot change the control plane / bin
/ env, and the binary stays pinned across a PATH change.

mojo-device-isolation.test.ts (new) calls resolveRemoteExecutionProven directly:
a wrapper voids the proof whether it arrives via initConfig or the frozen session
field, any wrapper counts (not just an obviously hostile one), and the
deregistered-bot path fails closed.

Quarantine is now asserted on the real lineage state rather than the row shape:
usable when the active id post-dates the freeze, quarantined when it IS the parked
id, none when there is no lineage. Plus the notice flag being set, persisted, and
not set when nothing was parked.

Live-patch unit cases were REWRITTEN, not extended — they previously pinned the
wide `env`-carrying patch that this round removed, including a
"compares env by value" case that no longer has a subject.

Two test-infrastructure notes:
  - worker-pool is imported lazily and the file timeout widened. Importing it
    eagerly pushed this file past 30s under full-suite load (the same reason
    restart-worker-null-reattach times out there); the leaf module keeps the rest
    of the cases cheap.
  - The clear-case fixture passes an explicit spawn env, because this host has an
    ambient X_JWT_TOKEN that buildEnv legitimately falls back to.

Reverse-verified: reverting each fix independently fails exactly the
corresponding tests (wrapper proof 3, quarantine binding 2, notice 1,
tombstone/state 3).
…olicy

Tenth review round. All six findings reproduced.

1+2. [P1] SECURITY — clearing a credential never worked in production, for two
   reasons on the same chain:
   - The worker validated the live patch with the CONFIG validator, which requires
     a non-empty `jwt` string, so every `null` tombstone was rejected with
     "Ignoring invalid mojo live patch" and the backend never saw it. Adds a
     dedicated normalizeMojoLivePatch() accepting exactly `{ jwt: string | null }`.
   - Even past that gate, `null` only unset `config.jwt`, and buildEnv then re-read
     `jwtEnv` out of the init-time `config.env` / `injectEnv`, reviving a stale
     token. The live JWT is now a THREE-state field: undefined (no snapshot yet),
     string (use it), null (explicitly cleared → delete the resolved
     X_JWT_TOKEN, no config-layer fallback). The daemon already folds the ambient
     fallback into the snapshot, so `null` genuinely means "nothing anywhere".

   The previous clear test called applyLivePatch() directly and so proved nothing
   about the IPC boundary. The new test drives a real worker process across two
   turns; reverting either half of this fix fails it.

3. [P1] the quarantine notice bypassed the managed-output policy. It called
   sessionReply() directly, so a dedicated VC receiver got an aux Lark message, a
   silent scheduled turn could be lit up, a no-transport bot dialled Feishu with
   nowhere to render, and no sourceSessionId was passed on a shared anchor. It also
   used a stale `currentReplyTarget.turnId` instead of the turn actually carrying
   the delivery. Now gated on mojoAuxNoticeAllowed(), which mirrors the first three
   checks of setupWorkerHandlers' closure; suppressed sessions keep the persisted
   state for dashboard/audit.

4. [P2] three cells of the notice matrix were missing:
   - rows quarantined by an EARLIER build already have an identity, so both
     migration entry points returned before flagging the notice → added as an
     independent backfill step ahead of the early return;
   - a cold-resumed session goes straight to forkWorker and never passes through
     sendWorkerInput, so "notice on the next message" never happened for exactly
     the sessions most likely to need it → delivered from both;
   - the flag was cleared BEFORE the async send, so a transient failure lost the
     notice permanently → now cleared only after success (a suppressed channel
     clears immediately, since the state is already persisted).

5. [P2] binary pinning resolved against the daemon's own PATH, ignoring a per-bot
   PATH — the child then ran a different install than the one pinned. Now resolved
   on the effective child PATH, layered exactly like buildEnv.

6. Removed dead code: mojoLivePatchDiffers() and livePatchState() had only test
   consumers, and worker→daemon state reporting does not exist as a protocol. The
   comments claiming it were worse than the missing feature.

Self-audit (not from review) found two more of the same shape:
   - buildWrappedLaunch still resolved the wrapper binary on the ambient PATH,
     disagreeing with resolveBin about which install is in use.
   - freezeMojoIdentityForSession used `active ?? parked`, which would overwrite an
     existing parked id when both are present and differ, silently losing the only
     handle to a remote session still running somewhere. Both are now parked.
… policy

The clear case is now tested where it actually broke. The previous version called
backend.applyLivePatch() directly, which is why a worker validator that rejected
every tombstone passed 140 tests: the test never crossed the boundary that was
broken. This one spawns a real worker, runs two turns in one process, and asserts
the recorded X_JWT_TOKEN per turn. Reverting EITHER the validator split or the
tri-state buildEnv change fails it — one test, both halves of the chain.

New coverage:
  - normalizeMojoLivePatch accepts `null`, rejects anything beyond `jwt`, and is
    contrasted directly against normalizeMojoConfig rejecting the same payload
    (the split is the fix, so the contrast is the assertion).
  - mojo-quarantine-notice-policy.test.ts: VC receiver / silent turn / apiOnly /
    http_async / http_wait / deregistered bot all suppress the notice, ordinary IM
    allows it.
  - Notice state matrix: backfill onto an earlier-build row, no re-queue once
    delivered, and both ids parked when two unverifiable lineages collide.
  - Binary resolution uses the effective child PATH, with mojo.env winning over
    the per-bot layer (same order buildEnv uses).

Two existing tests were rewritten because the SEMANTICS tightened, not because
they broke: a cleared credential no longer falls back to an inherited one (that
fallback was the bug), and the patch now lands in a dedicated `liveJwt` field so
the frozen launch identity is structurally out of reach rather than merely
unmodified.
…oss respawn

(Retitled from `test(mojo): ...` — this commit carries ~200 lines of product
code alongside its tests, so the `test` type was wrong.)

The previous restart test could not fail: its precondition grepped for
'Spawning fresh CLI', which is also logged at init, so it never proved a
respawn happened, and it asserted on a fixed dump index even though a
restart re-queues the original prompt.

Rewritten to the ordering from review (the clear queues *during* the
rebuild) and made index-free, asserting that no turn from the clear
onwards shows a revived token. Verified by reverting: each fix alone
leaves one case failing, and reverting both fails cases 1 and 2.
… child

The launcher resolved wrapperCli against ambient + bot env only, omitting the
highest-precedence mojo.env. A wrapper pinned via mojo.env.PATH therefore lost
to a same-named binary on the bot-level PATH, and since a wrapper can carry
auth or act as a gateway, that means running under the wrong identity.

The two sites layered the env independently, which is how they drifted. They
now share buildEffectiveChildEnv with one precedence: child -> bot -> mojo.env.

Also corrects two comments that contradicted the code: the quarantine notice
STAYS pending on a suppressed channel (it does not clear the flag), and
managedAuxUiSuppressed now delegates to auxUiSuppressedFor rather than
mirroring its first three checks.
…ree env layers

Adds 2b, the guard review asked for: the clear SETTLES first, then the backend
is rebuilt, then a no-patch turn and a /close both run on the replacement. This
is the only test that fails when restoreMojoLivePatchAfterRespawn() is removed
(test 2's clear rides the queue, so fix 1 alone saves it).

Two vacuous versions were discarded before this one: /close on a fresh backend
never cancels (no session id yet), and counting the restart's own teardown as
progress let the assertion pass while nothing was exercised.

Extends the wrapper probe to three PATH layers so mojo.env is actually covered.

Revert matrix, each fix pinned by exactly one test:
  drop the mojo.env layer  -> only 3 fails
  drop the respawn restore -> only 2b fails
Self-found while diffing the full-suite failure SET against master instead of
only comparing counts — the count alone (31 vs 31) had hidden it.

Extracting auxUiSuppressedFor() moved the no-transport gate out of the
managedAuxUiSuppressed closure this lock was reading, so the lock broke while
the invariant itself was intact. It now pins both the delegation and the gate in
its new home, plus the fail-closed branch for a deregistered bot.
… IPC

Two cleanups from review, neither behavioural:

Inserting buildEffectiveChildEnv() left MOJO_CONTROL_ENV_KEYS' JSDoc dangling
in front of the helper. Each block now sits above what it documents.

2b's unused `settled` is gone: the harness now records WorkerToDaemon messages
and the test fences on the readiness handshake a fresh backend re-emits
(local_process_attestation, counted, then prompt_ready) instead of grepping
stdout. A bare `restart` emits no restart_result — that is only sent for an
attemptId-carrying restart — which the first attempt at this fence proved.

Revert matrix re-confirmed after the fence change: dropping the respawn restore
fails only 2b; dropping the mojo.env layer fails only 3.
@swtxbling

Copy link
Copy Markdown
Contributor Author

正式提请最终复核 @deepcoldy。 head = ed6e9c8d,Linux CI 全绿(run 32050122939,完整 ~16.3k 用例通过)。

自六审 CHANGES_REQUESTED 起,P0/P1 与七审、八审复审发现已逐轮闭环:

六审 P0/P1:P0 spawn→入组窗口(exec 前入组 shim,post-spawn 迁移在 API 层移除);P1-A/B residual 全链路 durable(journal/重启重放/workerless 三路都发 closed_with_residual)。

七审:P0-1 cgroup 递归子树证明(堵 nested 逃逸、读不了 fail-closed)+ 边界建到 daemon 委派 cgroup 下(挡上迁)+ 诚实收敛 strong-proof 声明;P1-1 release 先复查内核 membership、空了才删 durable store;finding-2 write() 检查未登记闩+登记失败重试落 durable;finding-3 本地 residual 落行、幂等 re-close 仍报;finding-4 本地/远端分文案。

八审:finding-4 补两处批量弹窗(Dashboard 批量关闭/idle 清理/bot-defaults 汇总/mismatch 日志),本地 residual 不再被标成远端或打成 (undefined);P2 release 的 rmdir 返回值不再丢弃——membership 复查与 rmdir 间亚毫秒窗成员迁入→内核拒删→rmdir 现在是最终闸,非 zombie 证明下失败即 VETO 保留 handle+blocker(zombie-only 仍容忍)。

测试:递归证明 nested 逃逸、release 三态(membership 否决/rmdir 否决/zombie 容忍)、write() 闩、幂等 re-close residual、本地 vs 远端文案,均在 CI 跑;Linux 真 cgroup 委派下 layer-3 逃逸探针自动执行。

遗留(follow-up 级、非 blocker):zombie-only 释放的 rmdir tail、latch 成功 re-record 后不清、各 review 列的 P2。

mergeable=MERGEABLE、无冲突;等这条 CHANGES_REQUESTED 转 approve。请你和 codex 终审过一遍 ed6e9c8 这两轮增量。

🤖 Generated with Claude Code

@deepcoldy deepcoldy left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

复审 head ed6e9c8d:上一轮的 spawn→入组时间窗口、以及 P1-A/P1-B(residual 进 durable journal + workerless 传播)都已确认修好。但 cgroup strong boundary proof 仍有一个设计级 P0(含一个 release 子缝),暂不能合。

🔴 P0 — 同 UID 可迁出 leaf,strong proof 仍可假绿

pre-exec enrollment shim 只解决了「进程出生在哪个 cgroup」,没有阻止它之后自迁移:

  1. resolveSliceParent() 建出的布局是 D/botmux.slice/mojo-<sid>-g<n>-<rand>,D 是 daemon 获委派的 cgroup;mojo 子进程与 daemon 同 UID。
  2. cgroup v2 delegation 明确允许 delegatee 在其 delegated subtree 内自由迁移进程——迁移只要求 destination 与 source/destination 的 common ancestor 的 cgroup.procs 可写。从 mojo-* 上迁到 botmux.slice、或迁到 sibling mojo-*,全在同一委派域、同 UID 可写;root 运行时更无边界。(内核依据:cgroup-v2 admin-guide, Delegation Containment。)
  3. 关闭证明 cgroupSubtreePids(handle.cgroupPath) 只向 leaf 下方递归,迁出的进程不再可见 → 返回 cgroup-empty → releaseContainmentHandle 删除 handle → classifySession 随即失去 mojo_containment_unproven blocker,而带凭证进程仍在同委派域另一处存活。
  4. 源码注释(mojo-containment.ts:76-83)称 sibling/ancestor 盲区「由 device-isolation fail-closed 兜底」,但这是循环论证:device blocker 正是被这个假 proof + handle release 清掉的。

最小结构反例(leaf 的 cgroup.procs 空、同委派 parent 下的 sibling 里放一个存活 PID):生产函数返回 {verdict:true, evidence:'cgroup-empty', release:true, siblingStillAlive:true}。

🔴 P0 子缝 — cgroup-zombie-only release 跳过复查且容忍 rmdir 失败,且 zombie 模型与内核相反

releaseContainmentHandle:if (!zombieOnly) 才做 membership recheck,末尾 if (!reclaimed && !zombieOnly) 才 VETO —— 所以 zombie-only 时 rmdir 失败被容忍、handle 仍被 release。而代码的 zombie 模型是反的:注释(:346-347)称「zombie REMAINS a member of its cgroup until reaped, and rmdir keeps failing」,但真实 cgroup v2 语义是退出的进程在成为 zombie 前已从 cgroup.procs 移除,仅含 zombie 的 cgroup 可直接 rmdir。因此 cgroup-zombie-only(cgroup.procs 非空却全判 zombie)在真 cgroup v2 里不该合法出现,能出现的多半是读不到 state 的真实成员或迁移竞态;这条路径既跳复查又容忍 rmdir 失败,等于对竞态迁回/逃逸成员放行。现有 synthetic 测试用「普通目录残留文件导致不可删」模拟 zombie,与真实语义相反。

必修方向

  • 最小可靠:在有真正不可逃逸的权限边界前,所有 cgroup empty/zombie verdict 都不得铸造 boundaryProof:true;cgroup 仅用于 kill/诊断,close 保留 local residual + durable handle(即降到 weak 那一档,blocker 不被清)。
  • 若要保留 strong proof:必须让目标进程无法写 parent/sibling —— 独立 per-session UID + 特权 broker,或 cgroup namespace 连同 mount/权限隔离。CLONE_INTO_CGROUP / pre-exec shim 只解决「出生在哪」,挡不住后续自迁移。
  • 回归:在真实 delegated cgroup 中让目标 exec 后主动迁到 parent/sibling,再 setsid + scrub env + reparent,断言 close 不得 release handle;另把 zombie-only 的 rmdir 失败改为 VETO。

验证

  • pnpm build / tsc --noEmit / git diff --check 通过;origin/master 已包含在 head,git merge-tree 无冲突(本轮 MERGEABLE,无需 rebase)。
  • containment/mojo/device-isolation/close 相关约 44 文件 738/741 通过;1 skip 是宿主无可委派 cgroup v2;2 fail 是 root 环境 chmod 0500 写失败失效(CAP_DAC_OVERRIDE 绕过),代码本身正确,非 root 全绿。
  • fork PR 无 CI checks 上报。

结论:不合,打回修这个 P0(含 zombie release 子缝)。residual 三条链路本轮已确认修好,无新增阻断。

codex 终审在 cgroup 强证明上挖出设计级 P0,我对照内核 cgroup v2 delegation 语义
坐实:mojo 与 daemon 同 uid,委派域内同 uid 进程可把自己从 mojo-<sid> leaf 上迁
到父 slice 或迁到 sibling;关闭证明只递归 leaf 向下、看不到迁出去的进程 → 读空 →
判 release → 设备隔离 blocker 被清、带凭证进程仍活。我七审「device-isolation
fail-closed 兜底」是循环论证:blocker 正是被这条假 proof 清的。zombie 子缝同理
(cgroup v2 里 zombie 不在 cgroup.procs、只含 zombie 的组可直接 rmdir,原 zombie
模型反了)。

修法(codex 主张、review lead 认同):per-session uid/namespace 隔离到位前,
cgroup empty/zombie 一律不铸造 boundary proof——降级到与 weak scan-clean 同级:
- containmentReleaseDecision:唯一 boundaryProof=true 只剩 boot-id-changed(重启,
  真正杀掉一切)。cgroup-empty / cgroup-zombie-only 均 → releaseAuthorised=false +
  deviceIsolation residual(close 照常进行、signals 停、blocker 保留);
- releaseContainmentHandle:cgroup handle 永不经证据释放(早返回 residual),
  故不再 rmdir 回收目录(原 veto/rmdir 块随之删除,成了死代码);
- revokeContainmentHandles(operator 逃生阀):改为 cgroup.kill + 回收目录,
  承接「blocker 保留后目录/句柄的清理」;
- 更新模块头/真值表/STRONG 定义注释,明确 cgroup 只作 kill+诊断、非安全边界。

后果(已同步 review lead,接受为 fail-closed 代价、解耦列 follow-up):cgroup
handle 不再因「空」释放 → 每会话 per-turn 目录/句柄 close 后也保留,靠重启或
`mojo-containment revoke` 清。

测试改契约:strong cgroup verdict → diagnostic-clean(非 contained-proven);
release 对 empty/populated/zombie 三态 cgroup 一律保留 handle+blocker;仅 weak
boot-id-changed 释放;strong-cgroup-gone 也不再释放。boot-id-changed → contained
-proven 正路径补测。

Co-Authored-By: Claude Fable 5 <[email protected]>
@swtxbling

Copy link
Copy Markdown
Contributor Author

九审 P0 已修 @deepcoldy。 head = 1bd1759a,Linux CI 全绿(run 32089475607)。

codex 终审的设计级 P0(同 UID cgroup 逃逸)已按 codex 主张修复:

根因:mojo 与 daemon 同 UID,cgroup v2 委派域内同 UID 进程可把自己从 mojo-<sid> leaf 迁到父 slice 或 sibling;关闭证明只递归 leaf 向下、看不到迁出的进程 → 读空判 release → device-isolation blocker 被清、带凭证进程仍活。上一轮「device-isolation fail-closed 兜底」是循环论证(blocker 正是被假 proof 清的)。zombie 子缝同理(cgroup v2 里 zombie 不在 cgroup.procs、只含 zombie 的组可 rmdir)。

修法:per-session UID/namespace 隔离到位前,cgroup empty/zombie 一律不铸造 boundary proof,降级到与 weak scan-clean 同级:

  • containmentReleaseDecision:唯一 boundaryProof=true 只剩 boot-id-changed(重启);cgroup-empty/zombie-only → releaseAuthorised=false + deviceIsolation residual(close 照常、signals 停、blocker 保留);
  • releaseContainmentHandle:cgroup handle 永不经证据释放(原 veto/rmdir 死代码已删);
  • revokeContainmentHandles(operator 逃生阀):cgroup.kill + 回收目录,承接 blocker 保留后的目录/句柄清理;
  • 模块头/真值表/STRONG 注释改为「cgroup 只作 kill+诊断、非安全边界」。

codex 的最小反例现被中和在 RELEASE 闸:leaf 空 + sibling 存活 → proveContainmentQuiescent 仍读 leaf 空判 proven,但 release → 不释放、residual、blocker 保留。

已知代价(fail-closed 优先):cgroup handle 不再因空释放 → per-turn 目录/句柄 close 后保留,靠重启或 mojo-containment revoke 清;「回收目录/句柄」与「blocker 保留」解耦列为 follow-up。

测试改契约:strong cgroup verdict → diagnostic-clean;release 对 empty/populated/zombie 三态一律保留 handle+blocker;仅 weak boot-id-changed 释放;补 boot-id-changed→contained-proven 正路径 + 空 cgroup 保留(模拟 sibling 逃逸)revert-red。本机全量 16208 passed(仅 4 条无关环境失败)。

请 codex 复核这条 P0。

🤖 Generated with Claude Code

…闸(P2-2)+ 修 4 处反话注释(P1-doc)

九审 P0 修死后,十审五方一致「可合入」,顺手清掉全部剩余项:

P1-doc(安全模块命门上的反话注释,留着=照注释改回 P0 的地雷):
- mojo-containment.ts evidence 说明:cgroup-empty/zombie-only 明确标为「诊断信号、
  非 boundary proof」,只 boot-id-changed 是真证据;
- containedProvenQuiescence 头注释:改成「唯一 boundaryProof 证据是 boot-id-changed」,
  删「空 cgroup.procs 是真 boundary proof」的反话;grep 声明改准(两处构造点+类型定义);
- mojo-backend.ts 注释:boundaryProof 只对「重启」为真,对空 cgroup 为假。

P2-1(bootId:让「重启」这个逃生阀对 cgroup handle 生效):
- StrongContainmentHandle 加可选 bootId(legacy 无此字段仍解析);
  strongHandleFromPreparedBoundary mint 时盖 readBootId();
- proveContainmentQuiescent 的 cgroup 分支先查 boot-id:变了 → boot-id-changed proof
  → cgroup handle 重启后能释放。运维代价从「每会话永久 revoke」降到「本 boot 内」。
- parseHandle 容忍/校验 bootId(present 则须非空串)。

P2-2(revoke 对 cgroup handle 的 ops-safety):
- 加 cgroup 成员存活闸(cgroupHandleLiveMembers):路径有执行成员 → 默认拒绝,
  --force 越过并写审计;不可读则告警不硬拦(与弱 handle 一致);
- revoke 移除后由 CLI await killPreparedBoundary 并记录结果(回收目录 / 未证清空则
  显式告警),不再 fire-and-forget;revokeContainmentHandles 回归纯 store 变更。

commit-message nit(九审):源码注释本就正确,仅九审 message 的 zombie 描述有误,
本 message 不再复述。

测试:bootId 两态(同 boot 不释放 / 跨 boot 释放)+ legacy 无 bootId 不获证据 +
mint 盖章;revoke cgroup 存活闸(默认拒 / --force 越过)。tsc/build 通过,
10 个 containment/close/device-isolation 套件本机全绿。

Co-Authored-By: Claude Fable 5 <[email protected]>
@swtxbling

Copy link
Copy Markdown
Contributor Author

@deepcoldy 请复核合入。 head 现为 2cec0d2a(十审收口,含九审 P0 修复 + 十审 P1-doc/P2-1/P2-2 全部落地)。fork CI 正在对该 sha 重跑,绿了我在本条回补 run 链接。

自你上次 CHANGES_REQUESTED 以来的完整闭环(六→十审):

  • 六审 P0(spawn→入组窗口)/ P1(residual 全链路):exec 前入组 shim + residual durable journal / 重启重放 / workerless 三路。
  • 七审 P0-1(cgroup 递归子树证明堵 nested 逃逸)+ P1-1(release 先证后忘)+ finding-2/3/4 + P2。
  • 八审 finding-4 补两处批量弹窗 + P2(release 的 rmdir 返回值作最终闸)。
  • 九审 P0(设计级,同 uid cgroup 逃逸):cgroup 空/僵尸不再铸造 boundary proof——mojo 与 daemon 同 uid,委派域内可自迁出 leaf,leaf-down 读空看不到迁出者;唯一能清 blocker 的证据只剩重启(boot-id-changed)或 operator revoke。上一轮「device-isolation 兜底」是循环论证,已纠正。
  • 十审收口:
    • P1-doc:4 处和实现相反的安全注释全部改正(否则是「照注释改回 P0」的地雷);
    • P2-1(bootId):StrongContainmentHandle 盖 bootId,cgroup 分支先查 boot-id → 重启后 cgroup handle 也能释放,运维代价从「每会话永久 revoke」降到「本 boot 内」;
    • P2-2:mojo-containment revoke 对 cgroup handle 加成员存活闸(默认拒、--force 越过写审计)+ await killPreparedBoundary 并记录结果(不再 fire-and-forget)。

已知运维代价(fail-closed 正确方向):cgroup host 上每个 mojo 会话 close 后留 residual + blocker,靠重启或 mojo-containment revoke 清(bootId 让重启这条逃生阀对 cgroup 生效)。

验证:本机全量门 16209 passed(余下失败均为与本 PR 无关的环境/并发 flake:riff-keychain 真 keychain、cost-calculator 满载 flake、real-process /proc 套件在满载并行下的时序 flake——隔离全绿、复跑 3/3 绿)。mergeable、无冲突。

请 owner 复核,之前那条 CHANGES_REQUESTED 清掉即可合。

🤖 Generated with Claude Code

@swtxbling

Copy link
Copy Markdown
Contributor Author

✅ CI green for 2cec0d2a: https://github.com/swtxbling/botmux/actions/runs/32104534325 — full suite passed on Linux. Ready for @deepcoldy's re-review.

@deepcoldy deepcoldy left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

复审 head 2cec0d2a:上一轮的 cgroup P0(同 UID 空间逃逸 + zombie 子缝)已按最小安全方案真正修好——containmentReleaseDecision 的自动授权现在只认 boot-id-changed,cgroup-empty/cgroup-zombie-only 只停 signals、保留 handle 与 device-isolation blocker;原 sibling-alive 反例现返回 boundaryProof:false / releaseAuthorised:false,全仓仅 releaseContainmentHandle 一条删除入口、无从 cgroup-empty 绕开的旁路。但这轮新增的两处仍需修复,暂不能合。

🔴 P1-1 — bootId 能产出证明,但 closed residual 没有生产消费者

proveContainmentQuiescent() 现在能在 boot 变化时返回 boot-id-changed,但全仓生产调用只有两类:live backend teardown(mojo-backend.ts:1057)和 workerless close(:2363)。一个已 closed_with_residual、只剩 ledger handle 的会话,重启后不会恢复 worker:

  • device-isolation 侧只走 hasUnprovenContainment()(mojo-containment.ts),其实现是 containmentHandles(sessionId).length > 0 —— 只数 handle,从不调用 proof、不看 bootId;safeContainmentSessionIds / appendResidualContainmentSessions(device-isolation-daemon.ts:527-574)据此把 handle 重新合成 blocker。
  • 再次 /close 在 prepareMojoExplicitClose() 的 already-closed 分支(worker-pool.ts:3987-3998)直接返回 parked/ok,也不走 workerless proof。

因此真实链路:close 留 cgroup handle → 主机 reboot(旧树确实全死)→ daemon restart → 旧 handle 仍被 inventory 合成 mojo_containment_unproven → device-isolation 持续 409,新增 bootId 分支永不被消费。清理实际仍只有 operator revoke —— 本轮宣称的「重启或 revoke 清理」闭环不成立(全机 device-isolation 会被旧 handle 持续卡住)。

修复要求:加一个 production reconciliation(daemon 启动或 activation inventory 之前),枚举 durable handles,逐个 proveContainmentQuiescent,仅在 boot-id-changed 时 release;账本或 /proc 不可读必须 fail closed。端到端测试至少覆盖:closed row / 无 row + old-boot handle 会清、same-boot 保留、legacy 无 bootId 保留。

🔴 P1-2 — local residual 被 5 个消费点误报成「远端会话未取消」

新策略下 cgroup close 正常返回 {reason:'local_subtree_boundary_unproven'},没有 taskId。但以下 5 处仍直接拼 residual.taskId 并宣称远端未取消:

  • background cleanup:worker-pool.ts:4888-4893
  • 文本 /close:command-handler.ts:1403-1413
  • 卡片 close:card-handler.ts:2539-2546
  • 文本 /repo switch:command-handler.ts:1968-1976
  • 卡片 /repo switch:card-handler.ts:789-796

结果把「本机可能残留带凭证子进程未确认终止」显示成「远端会话 undefined 未取消」,并给出相反的人工处置方向(应查本机进程,却引导去清远端)。仓库已有正确的 kind-aware helper(close-residual.ts:63-98:closeResidualIsLocal / describeCloseResidual / closeResidualClause,local 分支文案为「本地可能残留带凭证的子进程未确认终止…需人工核查该主机进程」),但这 5 个 typed consumer 未复用;现有测试只喂 mojo_lineage_quarantined + taskId,所以全绿是假覆盖。

修复要求:5 处统一走 kind-aware helper(按 residual 类型分别渲染 local / remote 文案与处置方向),并为每个入口补 local residual 的行为测试。

非阻断(建议顺手)

  • mojo-containment.ts:120-124 仍保留「same-uid child 不能向上迁」的旧反话注释;:1115-1122/:1148 又称 cgroup handle 永不经 proof release、只有 weak boot-id 能到达,与新增的 cgroup boot-id 分支矛盾。
  • revoke 是显式 operator override,当前告警足够;但它先删 ledger 再 kill,empty leaf 对已迁出的 sibling 也可能报「已证实清空」,建议后续收紧措辞/顺序。

验证

  • pnpm build / tsc --noEmit / git diff --check 通过;对当前 origin/master 的 git merge-tree 无冲突,但 master 已不是 head 祖先,合前需 rebase。
  • containment/mojo/device-isolation/close 相关约 47 文件 1158 passed / 1 skipped / 2 failed;1 skip 是宿主无可委派 cgroup v2;2 fail 是 root 环境 chmod 0500 写失败失效(CAP_DAC_OVERRIDE 绕过),代码本身正确,非 root 全绿。
  • fork PR 无 CI checks 上报。

结论:P0 修复认可,但 P1-1 / P1-2 未闭环,2cec0d2a 暂不可合。

liaoxiao.333 and others added 5 commits August 18, 2026 18:01
十审 P0 修死后,双审又坐实两条 P1,均已闭环:

P1-1(bootId 有证明无消费者,隔离被旧 handle 卡死):
proveContainmentQuiescent 的 boot-id-changed 分支只被 live teardown / workerless
close 调用,二者对「已 closed、只剩 durable handle」的会话都不触发;device-isolation
侧只 hasUnprovenContainment(length>0),从不跑证明。于是主机重启后旧 cgroup
handle 仍被 inventory 合成 activation_blocked,永远不消费新 bootId。
- 新增 reconcileContainmentHandlesOnBoot():枚举 durable handles 逐个
  proveContainmentQuiescent,仅 boot-id-changed 才 release;账本//proc 不可读或
  单 handle 证明抛错一律 fail-closed(保留)。
- 接进生产链:buildDeviceIsolationInventory() 首次构建前跑一次(每 boot 一次,
  guard 复位于 resetForTest)——正好对应「daemon 重启」,且在合成 blocker 之前。
- 作为可注入依赖 reconcileContainmentOnBoot,便于 wiring 测试。

P1-2(本地 residual 无 taskId 被 5 处误报成「远端会话 undefined 未取消」):
background(worker-pool)/文本 close/卡片 close/文本 repo 切换/卡片 repo 切换 5 个
typed consumer 统一改走已有 kind-aware helper(closeResidualIsLocal /
describeCloseResidual / closeResidualClause):本地 residual 现指向「本机残留子进程、
请人工核查该主机进程」,不再拼 undefined、不再把处置方向指向远端。

非阻断:resolveSliceParent 头注释纠正(同 uid 可迁移、cgroup 非安全边界)。

测试:
- 重启 reconciliation 五态(old-boot cgroup 清 / same-boot 留 / legacy 无 bootId
  留 / old-boot weak 清 / store 不可读 fail-closed)+ inventory 只触发一次 + 抛错
  被吞不阻断构建;
- 5 消费点各补 local residual 行为测试(断言含「本机」、不含 undefined、不含
  「远端会话未取消」),补上此前只喂 quarantine+taskId 的假覆盖。

tsc/build 通过,device-isolation + containment + 消费点相关套件本机全绿。

Co-Authored-By: Claude Fable 5 <[email protected]>
P1-1 的 reconciliation 上一版挂在 buildDeviceIsolationInventory() 里,导致每个
构建 inventory 的测试都会对其 fixture handle 跑一次证明——Linux CI 上 readBootId
返回真实 boot_id,与 fixture 里硬编码的 bootId 不同 → 被判 boot-id-changed 释放,
mojo-containment-inventory 的「应 blocked」用例变成 safe_remote(macOS readBootId
为 null 不触发,故本机漏测)。

改为在 daemon 启动序列里调用一次(紧邻 reconcileIdempotencyLeasesOnBoot),
daemon-global + guard 保证每 boot 一次、与 bot 数量无关;在 device-isolation
activation inventory 之前,仍满足「合成 blocker 前清理」。移除注入依赖/guard/
inventory 钩子与对应 wiring 测试;reconcile 行为仍由 reconcileContainmentHandlesOnBoot
的五态单测覆盖。

Co-Authored-By: Claude Fable 5 <[email protected]>
十一审把 reconcileContainmentHandlesOnBoot 接进 buildDeviceIsolationInventory
首建之前后,夹具里写死的 bootId('boot-abc')在 Linux 上会被对账判定为「上一次
boot 遗留、重启已证明死亡」而合法 release,两条 blocked 断言于是拿不到 entry
(CI 红;macOS 无 /proc boot_id、对账 fail-closed 保留,故本机绿)。

夹具改为 readBootId() 取当前真实 bootId(Darwin 无 /proc 时回退固定串,对账
同样 fail-closed 保留),语义回到用例本意:「本次 boot 内未证明的 handle 必须
阻断」。生产代码不动——对账只在 boot-id-changed 时 release、其余一律保留的
方向经复核正确。

验证:tsc 通过;mojo-containment-inventory / mojo-containment /
mojo-weak-handle-residual 共 98 条全绿(Linux 容器)。

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01XP3faqVPKXZoQdrV137KDt
假 mojo 用 writeFileSync 写 invocation dump:open() 即建文件、内容随后才落盘。
runWorker 原来只等 existsSync 就立刻 JSON.parse,负载高的 runner 上 100ms 轮询
恰好落在两者之间就读到空/半截文件(CI 报 Unexpected end of JSON input,全量 run
32127071266 独此一条红)。等待谓词改为「文件可完整 JSON.parse」才放行并复用解析
结果,超时报错文案同步说明两种可能。

验证:tsc 通过;mojo-worker-wiring.integration 26 条全绿。

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01XP3faqVPKXZoQdrV137KDt

@deepcoldy deepcoldy left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

复审 head 423cc615:上轮两条 P1 的方向修对了——boot reconcile 已接到 IPC bind 之前且各分支 fail-closed;5 个 local residual 消费点已 kind-aware(taskId 仅在 remote 分支)。但 P1-1 还剩一个 durable-state 子缺口,cleanup 成功后会永久留下假 residual 并进入控制流,暂不能合。

🔴 P1 — handle 已 release,但 Session.mojoLocalResidual 从无清除路径,两者永久分叉

  • types.ts:589-596 约定 mojoLocalResidual 在 containment handle released 后清除;
  • 但全仓 mojoLocalResidual 只有一个写入点(session-store.ts:902 park + :928 失败回滚),没有任何清除路径(无 = undefined / delete);
  • 唯一读取点 mojoCloseResidualForRow()(worker-pool.ts:4373)无条件读 session.mojoLocalResidual,不校验对应 handle 是否仍在;
  • 新增的 reconcileContainmentHandlesOnBoot() 只删全局 mojo-containment-handles.json,不碰 session row;reactivateClosedSession()(session-store.ts:990+)清了 codexApp / queued / status 等字段,唯独不清 mojoLocalResidual;operator revoke 同样只删 handle。
  • 且 prepared-close journal 的 localResidual 在 worker-pool.ts:4022-4026 无条件重放,而 reconcile 早于 restore,所以「崩在 prepared → 主机重启」会在 handle 已释放后重新 park 一个假 residual。

后果:主机重启已证明树死、device-isolation blocker 已解除,但 dashboard / re-close 仍谎报「本机可能残留带凭证子进程」;恢复该 closed session 后再 close / repo-switch,旧 residual 被当成当前事实,repo-switch 据此中止。mojo-containment revoke 后同样复现。不是凭证 fail-open(blocker 始终挡着),所以非 P0;但这是永久 durable 假状态 + 真实流程阻断 → P1。

修复方向(建议以 handle 存在性为授权真源,而非 session row):containment ledger 是全局单文件、session row 按 bot 分文件,release 时机清 row 不可靠(第一个 daemon 可能先释放别的 bot 的 handle,owner daemon 启动时 released 信息已不在)。更稳的是让消费端以「该 session 仍有 containment handle」为准:

  • mojoCloseResidualForRow() 读取 parked local residual 前先查 hasUnprovenContainment(sessionId);账本不可读仍视为 outstanding(fail-closed);
  • prepared journal 的 localResidual 重放走同一判断;
  • 可再顺手清 row 字段,但不要把 row 本身当授权真源。

回归至少覆盖:① closed row + old-boot handle → reconcile 后 re-close 不再报 residual;② prepared journal + old-boot handle → boot reconcile/restore 后不重新 park;③ same-boot 与账本不可读仍保留 residual;④ revoke 后 re-close/resume 不继承旧 residual;⑤ resume → repo-switch 不被已释放 handle 的旧字段中止。

非阻断(建议与本轮一起清)

mojo-containment.ts 真值表(:1105-1113)漏了 cgroup, boot-id-changed → true / release yes 一行(reconcile 里 boundaryProof 是 kind 无关的,带 bootId 的 cgroup handle 重启后确会 release,有单测证);:1191 / :1290 附近仍有「cgroup handle never released by proof」的旧反话注释。纯文档。

验证

  • pnpm build / tsc --noEmit 通过;containment/mojo/close 相关约 19 文件 742/745(1 skip = 宿主无可委派 cgroup v2;2 fail = root chmod 0500 写失败失效,CAP_DAC_OVERRIDE 绕过,代码本身正确,非 root 全绿)。
  • 上述 stale-row 反例、release 写失败、/proc 不可读的 fail-closed 均以生产函数实跑确认。
  • git diff --check / merge-tree 干净,但 master 已领先 head,合前需 rebase。

结论:两条 P1 实现方向正确,但 cleanup 只清 handle、不清/不失效 durable residual,423cc615 仍不可合。

claude and others added 4 commits August 18, 2026 12:31
行字段 mojoLocalResidual 只有写入、没有任何清除路径:重启对账与 operator revoke
都只清全局 containment 台账、不碰 per-bot session 行;reactivateClosedSession 也
不清。于是主机重启已证明进程树死亡、隔离已解锁后,行字段永久残留——dashboard/
二次 close 持续误报「本机可能残留凭证进程」,恢复会话后的 repo 切换也被旧字段
卡住;类型注释里写的「handle 释放时清除」实际不存在。

修复方向(与复审共识一致):handle 台账是授权真源,行字段只是派生展示态。
- 新增 liveLocalResidual:消费 residual 前先查 hasUnprovenContainment——handle
  已释放 → 不再报告;台账不可读 → 照旧报告(fail-closed,与台账「读不了就抛」
  的方向一致)。
- 接入全部四个存量 residual 消费口:mojoCloseResidualForRow(行字段,覆盖
  dashboard 已关闭复读/最终发布/repo 切换)、prepared journal 重放、活 worker
  与 workerless 的运行时重试响应。当次 close 刚算出的鲜活证明不受门控;journal
  重放照原样重发 durable 证明(证据等级不因重放改变),只有对外响应被派生。
- 不加清除路径是有意的:台账全局单文件、session 行按 bot 分文件,让全局清理
  路径去改行文件会依赖当时加载了哪些 bot;读时派生天然对全部 bot 正确。
- 修正 Session.mojoLocalResidual 注释(原注释声称的清除路径不存在)。

回归测试(mojo-explicit-close):
- handle 已释放(台账为空,等价重启对账后的状态)→ 二次 close 报纯 closed;
- journal 重放且 handle 已释放 → 发布纯 closed;
- 台账损坏不可读 → 仍报 closed_with_residual(fail-closed);
- 原 round-6/7 四条 residual 存续用例补录 outstanding handle(生产里产生本地
  residual 的 close 定义上保留了 handle),断言不变,防过度抑制回归。

验证:tsc + pnpm build 通过;mojo-explicit-close 57 条全绿。

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01XP3faqVPKXZoQdrV137KDt
补上一笔派生修复(liveLocalResidual)尚缺的复审回归面与两处非阻塞文档债:

回归(mojo-explicit-close,走生产函数而非手清台账):
- old-boot handle + reconcileContainmentHandlesOnBoot() 释放后,二次 close 报纯
  closed(Linux 有真 boot id 才有意义,runIf 门控);
- operator revoke 后二次 close 同样不再继承旧 residual;
- prepared journal 重放提交后行上不重新 park residual(堵「prepared 期崩溃→
  主机重启」重铸假状态的路径)。

注释(mojo-containment):
- containmentReleaseDecision 真值表补 proven,cgroup/boot-id-changed 行——十审起
  strong handle 盖 bootId 后该行真实存在,表却仍写着 cgroup 永不 release;
- releaseContainmentHandle 头注释与释放路径注释同步改为「boot-id-changed 对两种
  handle 都放行;重启已重置 cgroupfs,故释放路径无目录可回收」,删除「cgroup
  verdict 恒 releaseAuthorised:false」的过时断言。

验证:tsc + pnpm build 通过;mojo-explicit-close + mojo-containment 141 条全绿。

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01XP3faqVPKXZoQdrV137KDt
十二审补了 release-decision 区两处,但 revokeContainmentHandles 里还留一处:cgroup
handle 现在会经 boot-id-changed(重启)释放,故前提「never released by proof」不准。
结论仍对(proof 释放只发生在重启、cgroupfs 已被清,无目录可回收;revoke 才是同 boot
下唯一可能带活目录丢 handle 的地方),仅纠正措辞。纯注释、无行为改动。

Co-Authored-By: Claude Fable 5 <[email protected]>
EOF
@swtxbling

Copy link
Copy Markdown
Contributor Author

正式提请最终复核合入 @deepcoldy。 head = c2dad3de,fork CI 全绿(run 32145800885),mergeable、无冲突、master 已并。

自你上次 CHANGES_REQUESTED 起,六→十二审的全部 P0/P1/P2 已逐轮闭环,最后一轮独立严格安审(四条安全命门对抗性核验)零发现:

核心设计(最深 P0 的最终形态):cgroup 空/僵尸不再铸造 boundary proof——mojo 与 daemon 同 uid,cgroup v2 委派域内可自迁出 leaf、leaf-down 读空看不到迁出者,所以"空"不是证明。能清 device-isolation blocker 的证据只剩**重启(boot-id-changed,不可伪造)**或 operator revoke(显式人类动作)。这从根上消除了"假释放"这一 bug 类。

逐条闭环:

  • P0(cgroup 同 uid 逃逸):release 闸只认 boot-id-changed;git grep "boundaryProof: true" 仅 2 处构造点,无旁路;递归子树证明 + pre-exec 入组 shim 堵 spawn 窗口。
  • P1-1(重启清理):reconcileContainmentHandlesOnBoot() 接在 daemon 启动、IPC bind 之前;仅 boot-id-changed 才 release,store//proc 不可读 fail-closed。
  • P1-2 + 派生 residual:Session.mojoLocalResidual 为读时派生态,liveLocalResidual gate 于 handle 台账(source of truth)——handle 没了不报、台账不可读照报(fail-closed);本地 residual 5 处 UI 全走 kind-aware helper,不再"远端会话 undefined"。
  • revoke ops-safety:cgroup 成员存活闸(默认拒、--force 写审计)+ await killPreparedBoundary。

已知运维代价(fail-closed 正确方向,已文档化):cgroup 主机上每个 mojo 会话 close 后留 residual + blocker,靠重启或 mojo-containment revoke 清。

门禁证据:tsc 0;fork CI run 32145800885 = success(build/test/workflow-core:test);mergeable=MERGEABLE、BLOCKED 仅因本条 review gate。

独立严审已通过。就等 owner 复核把这条 CHANGES_REQUESTED 转 approve(+ codex 终审两条 P1 delta)即可合入。

🤖 Generated with Claude Code

@deepcoldy
deepcoldy dismissed their stale review August 18, 2026 15:50

双审收敛:P0/P1 全部闭环并复核通过,撤下本条 changes-requested 以合入(合前 rebase 无冲突)。

@deepcoldy
deepcoldy merged commit df5ed5a into deepcoldy:master Aug 18, 2026
deepcoldy pushed a commit that referenced this pull request Aug 20, 2026
`/api/sessions/:sessionId/wake` 里的 `isRiffBackendSession(ds)` 守卫(#912)引用了
一个未导入的符号:该 import 在 #803 把 riff 判定扩成 `isRemoteBackendSession` 时被
移除,两处改动各自都对,合在一起后 `src/core/dashboard-ipc-server.ts` 少了一行 import。

结果是 master 自 #912 起 `tsc` 直接报错、`pnpm build` 退出码 2:

```
src/core/dashboard-ipc-server.ts(1277,9): error TS2552:
  Cannot find name 'isRiffBackendSession'. Did you mean 'isRemoteBackendSession'?
```

按调用点的原意补 import,不改行为:该守卫返回的错误码是 `riff_wake_unsupported`,
针对的就是 riff 这一种远端后端;`isRemoteBackendSession`(riff + mojo 全家)语义更宽,
是否要把 mojo 会话也挡在本地 wake 之外属于产品判断,不在本修复范围内。

验证:`npx tsc --noEmit` 干净、`pnpm build` 通过(改动前两者均失败)。
deepcoldy pushed a commit that referenced this pull request Aug 20, 2026
#958 已用「补回 isRiffBackendSession import」修好了 build 编译红,但那是最小改法:
它让 /wake 继续用 riff-only 守卫,与 #803 引入的结构不变量冲突——
worker-remote-retirement-protocol.test.ts 断言 dashboard-ipc-server 里
isRiffBackendSession( 调用数为 0(远程退役守卫必须泛化到 riff+mojo,不能各自 riff-only)。
所以 master 现在 build 绿、但两个测试红:

1. worker-remote-retirement-protocol.test.ts —「still calls isRiffBackendSession: expected 1 to be 0」
2. session-picker-responsive.test.ts —「q 中止 wake」用例(见下 #3)

本提交把 /wake 守卫对齐旁边 /restart 的既有约定,从根上消掉冲突:

- /wake 改用 isRemoteBackendSession,错误码 riff_wake_unsupported→remote_wake_unsupported,
  并删掉 #958 补回、现已无引用的 isRiffBackendSession import。语义同步收紧:mojo 与 riff
  一样持有远程血缘,本地 forkWorker 冷启动会切断/替换它,绝不能被 picker 唤醒拉起。
- 补 /wake 的 riff + mojo 拒绝回归测(此前 /wake describe 完全没覆盖远程分支,
  正是守卫会从 isRemoteBackendSession 悄悄退回 riff-only 的原因)。
- 修 session-picker-responsive「q 中止 wake」用例:其 .dashboard-secret fixture 未设 0600,
  被 secure-host-file 的凭证权限收紧挡在鉴权层,wake 请求发不出。显式 chmod 0600。
- 补 sessionWakeAcquireTimeoutMs clamp 单测(#912 双审记的非阻断 follow-up)。

验证:pnpm build 绿;相关 5 文件 189 测过(含两处原 master 红转绿);反向变异 3 处有牙。

Co-Authored-By: Claude <[email protected]>
@github-actions

Copy link
Copy Markdown

🚀 Released in v3.16.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants