# Native adapters and spawned agents

Scope: the Codex, ACP and Pi adapters and the Pi extension (turn `generation` and `activity` events), peer turn state, approvals, and the agent processes the hub spawns and stops. Read before editing `src/adapters/`, `src/pi/`, `src/hub/peers.ts`, `src/hub/permission-mode.ts`, `src/hub/tool-refusal.ts`, `src/hub/action-enforce.ts`, `src/hub/permission-payload.ts`, `src/hub/claude-shell-wrapper.ts`, `src/hub/task-shell-command.ts`, `src/hub/task-shell-default.ts`, `src/hub/task-shell-proof.ts`, `src/hub/task-shell-sandbox.ts`, `src/cli/claude-shell-wrapper.ts`, `src/hub/child-process.ts`, `src/hub/lifecycle.ts` (shutdown deadline), `src/hub/start-mode.ts`, `src/hub/terminal-open.ts`, `src/memory/capture.ts` (session end), `src/hub/native-hook-launch.ts`, `src/hub/peer-catalog.ts`, the launcher-managed MCP entries (`src/cli/agy-mcp.ts`, `src/cli/kimi-mcp.ts`, `src/cli/jcode-mcp.ts`), `src/cli/configured-acp-entry.ts`, the version policy (`src/adapters/compat.ts`, `src/cli/agents.ts`) or the process-tree stop in `scripts/benchmarks/teardown.ts`, or before adding a native peer.

- For conceptual architecture, definition fields, generic ACP config and the new-adapter review checklist, see [Adding an AI Tool](../adding-an-ai-tool.md). For definition interfaces, see [registry-types.ts](../../src/adapters/registry-types.ts).

## Adapter definitions, the registry and external modules (#451)

- Optional live model selection must preserve ordinary no-override delivery when its native surface is unsupported or unverified. A retained desired override must instead refuse before any prompt. Test both paths through the actual daemon factory; capability metadata alone cannot prove runtime readiness.

- Keep per-kind native policy in `src/adapters/definitions/` and consume it through the registry. Private CLI implementations accept only fixed host-bound ports; keep identity, audit, lifecycle admission and effect ordering in the host. Except for the verified person-owned A4 startup-module contract, do not add config-selected callbacks or runtime imports from registry leaves into eagerly initialized hub/CLI modules; use type-only ports for existing host planners.
- Adapter registry (#451): kind-specific policy lives in that peer's `AdapterDefinition` under `src/adapters/definitions/` (runtime definitions `NATIVE_BUILTIN_DEFINITIONS_WITHOUT_QWEN` in `builtin-metadata.ts` plus `qwen.ts`; the daemon constructs every native driver through `start.create` and `DAEMON_PORTS`). Outside `src/adapters/`, read a semantic field of `definitionOf(id)`: never a raw peer-id comparison, a resolved kind (`kindOf`, `definitionOf(...).kind`) or a constant alias compared with a native name, a vendor-keyed object, a peer-name array, or a closed-list import from `peer-catalog.ts`, `start-mode.ts` or `permission-mode.ts`; the guard resolves aliases and import/re-export bindings. `test/registry-guard.baseline.json` is `[]` and stays empty: a new site moves into a definition, never into the baseline. The only exceptions are the cross-release literals `KNOWN_PEERS`, `OPTIONAL_PEERS` and `START_MODE_PEERS`, which `test/registry-guard.test.ts` holds equal to the derived lists. `LaunchContext.nativeCommand` carries only validated config argv (or its redacted preview), never model input; a definition's `permission.grants` text is what `permissionGrant` shows, ahead of the built-in wording. Keep native mode-id maps in `definitions/*-native.ts`, free of registry factories (`test/adapter-import-order.test.ts`).
- Registry load runs `assertDaemonEngine` and `assertNativeCapabilityScope` before publication. A definition that is not a fixed builtin (object identity in `fixedBuiltinDefinitions`, never a kind name) may not declare `start.acpCommand`, `start.upStart`, `attach.admission`, `budget.resetSoftTokensOnResume`, `session.crashIdentity`, `session.nativeRevert`, a `pi-rpc` or `claude-implementer` daemon port, `identity.currentChild`, `routing`, `projection`, `reviewerVariant`, `headlessVariant`, `reviewer`, `hooks.factsHook`, `cli.entry`, `cli.preview`, `cli.usage` or `instances.modelSelect`. Only `definitionOf(id, instances)` picks a kind's `reviewerVariant`, for a declared extra with `start_mode: "headless"`, roles exactly `["reviewer"]`, and either a variant whose `reviewer.declaration` is `"automatic"` (Claude, agy) or `review_mode: "fresh"` (Codex, Kimi); without that opt-in a reviewer-only Codex or Kimi instance keeps its native adapter. It picks a kind's `headlessVariant` (Claude, #525-4) for a declared headless extra whose roles include `implementer` and hold only `implementer` and `verifier`. Metadata-only reviewer variants never establish native peer support; `isSupportedPeer` shares the registry runtime/validated-instance predicate with the catalog and daemon. A new field that depends on fixed-builtin assumptions or host-global native state joins that list (`test/adapter-capability-scope.test.ts`). `trust.onPrem` admits PII work (rule: `tasks.md`).
- Native branch ratchet (#625): `test/daemon-native-branches.test.ts` counts every call of a native class predicate (an `is*Peer` imported from an adapter module other than `registry.ts`) per enclosing function in `src/hub/daemon.ts` and `src/hub/claude-launch-proof.ts`, and the counts must equal `test/daemon-native-branches.json` (`predicate`, `function`, `count`, `reason`). A PR that adds, moves or removes such a call edits its row by hand with a concrete reason; never regenerate the table from a test. Bind a predicate alias with `const` only and never call one through a computed namespace key: the scan refuses both.
- Native proof state (`frontendProxy`, builtin `statusNotice`, `revertTurn` with `session.nativeRevert`, the Claude launch proof and terminal execution root) is read in the daemon only after `isFixedBuiltinDefinition(definitionOf(peer))`: a same-name foreign definition gets none of it. A product of a definition that is not a fixed builtin may not have a `frontendProxy`, `statusNotice` or `revertTurn` member at all, even undefined (`assertNativeProofPorts`, run by `createFromDefinition` and the conformance kit). Use `frontendProxyState` for the daemon proxy reads: absence keeps the generic path, present undefined refuses with `frontend proxy state unknown`. Keep approval policies and restoration debt inside CodexPeer. The remaining Codex `actionEnforcement`/`actionGated` predicate is intentional until a separately specified action-policy port; never add it to `FrontendProxyPort`.
- Adding a native peer: declare its `AdapterDefinition` under `src/adapters/definitions/` (or its own directory, as agy) and list it in `ADAPTERS` (`src/adapters/registry.ts`). `KNOWN_PEERS`, `OPTIONAL_PEERS`, `SUPPORTED_PEERS`, `START_MODE_PEERS` (a kind with both a TUI and a headless form), `ROLE_ORDER`, `HELP_ORDER` and `PLANNER_PEERS` are derived from it by `deriveAdapterLists`: set `optional`, `projection` (`roleRank`, `startRank`, `helpRank`, `plannerEligible`, `conductorEligible`, `reviewerEligible`; absent eligibility is false; a configured or external definition cannot) and, for an `ahub <kind>` launcher, `cli.entry`, `cli.usage`, `cli.preview` and `cli.startWords`, never a list edit (`builtinCliEntries(definitions)` projects the entries). The literal cross-release copies `KNOWN_PEERS` and `OPTIONAL_PEERS` in `src/hub/peer-catalog.ts` and `START_MODE_PEERS` in `src/hub/start-mode.ts` stay hand-kept for older coordinators: `test/registry-guard.test.ts` fails when one differs from the derived list. Adding a peer is the one change that updates their probe counts and `VENDORS` in `test/helpers/registry-inventory.ts` (`REGISTRY_COMPATIBILITY_PROBES`), the probe literal in `test/adapter-registry-a2.test.ts`, the `ADAPTERS` order in `test/adapter-registry.test.ts` and the literal in `test/adapter-catalog-a2.test.ts`; say so in the PR as an expected test change. `isSupportedPeer` answers from `ADAPTERS`, and for a declared instance from its kind's runtime definition unless the instance resolves to an unavailable reviewer variant; `isKnownPeer` and `defaultPeerRoles` answer from `definitionOf`; `STARTABLE_PEERS` reuses `SUPPORTED_PEERS`. Role eligibility (#1408) is read only through `roleEligibility` / `applyRoleCeiling` (`src/adapters/role-eligibility.ts`): a new kind changes the generated table in `docs/roles.md` (`renderEligibilityTable`; `test/roles-doc.test.ts` fails until the doc matches) and, when `conductorEligible`, the pinned conductor set in `test/conformance/conductor.test.ts`, and the conductor-start wording comes from `conductorStartText()` (`src/adapters/registry.ts`), never a text edit. It also adds the kind's `kinds` entry and its rows to `templates/presets/confirmation-matrix.json` (#999 T0): `test/confirmation-matrix.test.ts` fails without a tool-approval and a classed-action row per environment, and when the entry's forms, pull-only forms, conductor start or hub-mode fact differ from the definition. Add the same kind to `kinds` in `templates/presets/autonomous.json`, with a permission per form (`null` where the hub mode is `unmanaged`, or for `tui` under `unmanaged-in-tui`) and a start per environment: `test/autonomy.test.ts` fails when the preset and matrix kinds differ or a mode is unsupported. A builtin kind that reads a user skill directory joins `SKILL_HOSTS` and `hostSkillDir` (`src/adapters/definitions/native-cli-skills.ts`); one that reads none joins the exclusions in `test/skills-install.test.ts`.
- When an adapter lands, add its project config directories to `AGENT_CONFIG_SEGMENTS` (`src/hub/permission-mode.ts`); scoped automatic writes must ask there, while explicit approval and `never-ask` keep their existing behavior.
- Load external modules only at daemon startup from trusted untracked local declarations: verify the self-contained bundle and content pin before importing captured bytes. Keep CLI/reload paths metadata-only, modules restart-bound and never settings-editable, builtin capabilities restricted, and external-kind instances admitted only under the accepted #754 headless opt-in, live captured catalog, separate worktree and host-managed current-owner proof; preserve the live-module controlled-recovery refusal. Export conformance registrations and fake assets without starting them on import.
- Bind scanned external runtime SDK imports to this daemon's own `/adapter` entry; never resolve them against project packages. Refuse `/conformance`, `bun:ffi`, `bun:test` and CommonJS loading at runtime. Isolate module refusals from hub startup and retain unknown module roster rows as inert when metadata is unavailable.
- Require the immutable captured project catalog at instance, roster, execution and permission resolver boundaries; choose a builtin catalog explicitly only for builtin-only callers; accept `adapters` only as wholly machine-local trusted data and require restart for changes. Refuse missing/mismatched pins, non-echoed load sessions, leader/attach argv and unknown owned-group evidence; require an explicit standalone `--no-leader` before argv termination for Grok (kind, executable or pinned native name); signal only the original verified group. Keep unmapped policy unmanaged, absent budgets exempt and read-only instances non-raisable through native acknowledgement plus host/MCP mutation gates. Claim native support only with its isolated T0 receipt.
- Consume quota/context through the resolved definition's declared readers; absence stays unknown. Use explicit `attach.externalHello` and `instances` policy for admission, never `identity.mcp`; keep runtime owner/root and reviewer isolation proof in the host. Never let configured `roles` include `conductor`. Keep native stderr, prompt-failure, permission-mode and transport error text out of configured-kind logs and turn-failure reasons. A configured CLI start (`src/cli/configured-acp-entry.ts`) accepts only `--mode headless`, `--as`, `--session-id` and one preview flag, and its preview never shows argv or session values.
- Validate coherence and conformance enrollment for reviewer and headless variants too. Construct driven conformance peers through `start.create`; name dedicated coverage and concrete reasons for unsupported legs. Every fixed builtin identity, variants included, has a concrete `<id>:native-proof-ports` reason in `UNSUPPORTED_LEGS`, and only a fixed builtin may have one; every ACP factory product must report `deliveryOnly === true`, `hubOwned === true` and `form === "headless"` at runtime admission and in the conformance kit; never mark the mandatory `restrictive-ports` leg unsupported. Do not restore removed placeholder launch, lifecycle, init or permission metadata.

## Permissions, modes and approvals

- Approval titles are agent-written text shown to a person: the daemon escapes control characters, and write/edit/bash show what will be written or run.
- An ACP permission request may carry no `rawInput` (Kimi 2.0.1): the arguments were on the earlier `tool_call` update, which `acp.ts` remembers by `toolCallId`. Kimi 2.1.1 sends no `rawInput` before the answer at all: the argument JSON streams as `content` text on `tool_call_update`, and only complete JSON counts. A payload that still cannot be resolved, or is too long to show whole (marked `[cut, N chars]`), withholds its `allow_always` option - never render a bare tool name as if it described the call.
- Auto-approval covers the hub's own tools by exact `mcp__agent-hub__<name>` title and only ever picks `allow_once`. Identity comes from the permission request title or, when an agent titles the request with the argument JSON (Qwen), from the announced `tool_call` title bound to the call id and resolved against the session's configured MCP servers, never from payload text, a prefix or an unrelated display title. Never widen it to a prefix or replace it with an agent-selected session mode. Configured ACP kinds (`nativePolicy` or `requireOwnedGroup` set) never auto-approve from a request or tool-call title, even an exact hub tool name; under a locked read-only mode, reject any request whose ACP `kind` is not read, search or think, and never offer `allow_always`. Set Kimi `yolo`/`auto` only for its verified native identity and an operator mode; config never-ask waits for a console y unless retained autonomy consent matches it, and other ACP agents stay unmanaged on fresh/resumed starts without setting/resetting modes or failing over their reported mode; refuse runtime changes until their map exists; await the advertised mode change after session new/load and before a prompt, and fail startup on refusal. Use the shared `KIMI_MODE_IDS` mapping (`src/adapters/definitions/kimi-native.ts`, re-exported by `src/hub/permission-mode.ts`).
- Permission modes (#242) are a person's and live in the daemon's memory only: `permission` and `permission_default` are console-role control messages, `ahub permission` is `console` in `classifyPeerCommand`, and no hub tool or conductor tool sets one. The dashboard and `ahub settings` set one only through `settingsSet` (`src/hub/daemon.ts`, #269), which calls `changePermission` inside `permissionChange` as the console does: never add another path that writes a runtime choice to `permissionModes`; a reloaded project default (#439) is applied only by `applyPendingPermissionDefault`, and only while that peer is absent or offline. Never write a runtime choice to a restart snapshot.
- Proven read-only shell grants (#816, `src/hub/read-only-shell.ts`, `read-only-shell-proof.ts`) apply to Pi/local and the #845 headless Claude host wrapper under `ask-when-needed`, at the host permit boundary: parsing grants nothing, and a grant needs the closed program and flag table, trusted executable lookup and the path guard. For Pi/local, between the grant and the spawn the host calls `shellExecutionCheck` synchronously; `ask` re-asks once with `forceAsk` and a second unstable proof refuses without running, and an aborted or superseded turn (`executionGeneration`) never spawns. Never widen the table or skip the recheck to make a command pass.
- Agent shell authority (#812, `classifyPeerCommand` in `src/cli/identity.ts`, `src/hub/operational-authority.ts`): the Allowed read forms live in `peerReadForms` and are admitted only when the daemon also admits the same form for an ordinary tools connection; the conductor family is the closed `conductorOperation` list, each admitted by `admitOperational` (role recheck, closed audit label, no argument text; `queue show`, a settings preview and the authorize handshake recheck through `operationalCurrent` without an audit record). Throw `OperationalAuthorityError` only from an authority fence: only it is audited as refused and gets the conductor or person guidance, and an ordinary operation failure keeps its own error (#839). A new CLI form is `console` until it is added to one of those tables with a test in `test/identity.test.ts`. #933: `console` is only trust, money, attribution and interactive terminals; a conductor form joins `CONDUCTOR_DAEMON_OPERATIONS` (its own daemon request calls `admitOperational`) or `CONDUCTOR_LOCAL_OPERATIONS` (its effect runs in the CLI, so the `admit` handshake is its one audit row, sent only after its `LOCAL_OPERATION_ARGS` check in `src/cli/main.ts` passed), never both; a form whose write records the person as actor (amem's `user`) or whose runner inherits the agent markers stays `console`, except the recovery-bearing daemon forms (`restart --yes`, `upgrade --yes --to <version>`, `recovery resume|abort`, #900), which also require their source-issued continuation proof (rule: `daemon.md`), and every reclassified form changes its daemon check in the same PR.
- A headless ACP Kimi or Codex whose mode lives in the native agent joins the bus only through `reconcileNativeStart` (`src/hub/daemon.ts`): after `start()` the daemon's current mode is applied, then `bus.add` (it can drain at once), then the state `start()` reached is replayed. Every mode change runs inside `permissionChange`, one per peer at a time.
- Generic permission and generation dispatch in the daemon reads the optional `PeerAdapter` ports (`src/hub/peers.ts`, #667): `permissionModeState`, `setPermissionMode` (resolves only after native acknowledgement; changes approval frequency, never the sandbox), `sessionGeneration` and `checkpointUsesSessionGeneration`; never add a native-class predicate (`isAcpPeer`, `isCodexPeer`) for it. An absent `sessionGeneration` keeps the recovery-session/owner-token fallback; a present but undefined one is unknown and refuses. `BasePeer` installs no default generation, and only an explicit `checkpointUsesSessionGeneration = false` (Pi) skips the checkpoint generation fence. A `permissionModeState` of `unknown` or `unmanaged` refuses a change.
- Delivery, lifecycle and session dispatch in the daemon reads the same optional ports (#625 slices 2b-2c): `deliveryOnly` (absent or `false` permits `hub_delivery_retry`; `true` or a present `undefined` refuses), `hubOwned` (only `true` lets `peer_stop` stop the runtime), `pendingOwnedProcess`, `form` (a present `undefined` is unknown: `peer_stop` refuses, and a definition with `permission.unmanagedForms` treats it as a TUI), `captureResume`, `detachForRoster`/`resumeFromRoster`, `pullOnly`, `recoveryReady` and `nativeSession` (rules: `daemon.md`). An adapter the hub owns and may stop sets `hubOwned = true`, a delivery-only transport sets `deliveryOnly = true`, and only a live push channel (`WsPeer`) sets `acceptedSettlement = "explicit"`, the one port that lets a peer settle or discard its own `accepted` row (`Bus`, #1172: `accepted` is transport acceptance only, and an unconfirmed row moves to `needs_review` after `bus.accepted_settle_ms`, never replayed); never add an `is*Peer` call for any of them (ratchet above).
- Codex takes a mode as an `approvalPolicy` override on `turn/start`, and the override persists on the thread: pass the hub's and the TUI's `turn/start` alike through `applyPermissionPolicy`, and return to `ask` only by sending the captured native policy once. With none captured, refuse while the TUI is attached; never just stop sending the override. Keep the captured native policy and the restoration debt per thread (`nativeApprovalPolicies`, `overriddenApprovals`) across detach and `thread/start` or `thread/resume`; clear a debt only on a successful response to its restoring `turn/start` while the mode is `ask` (`settlePermissionRestore`), so a rejected turn keeps it. While a thread owes a restoration with a known baseline, in any mode, never replace that baseline: a `thread/resume` response and the TUI's own `turn/start` can both echo the sticky override, and the restoring turn sends the kept baseline whatever the TUI supplied. That protection is one turn: after the restoration succeeded, a policy the TUI sends is taken as the person's choice, captured and passed through, because the proxy cannot tell a repeated echo from one. A detached proxy's `clearPermissionMode` is never refused; if the native policy is unknown, return a CLI-visible note that the thread keeps its last policy. Attached refusal directs the person to close the TUI, then run `ahub permission codex ask`.
- Codex planner threads (#525-6, `threadSandbox` in `codex-appserver.ts`, live from `isPlannerOnly` for a declared instance): every `thread/start`/`thread/resume` goes up with `sandbox: "read-only"` and is adopted only when its response positively confirms the `readOnly` policy (`confirmsReadOnlySandbox`). An unconfirmed or malformed reply, a reused RPC id, an `unavailable` policy (a planner with a declared worktree) or a throwing reader refuses that RPC and closes the TUI link before adoption or delivery, and `deliver`, `steer` and `steerText` recheck `threadSandboxReady` right before they send. Never count missing evidence as read-only, and never let a role change promote an unconfirmed thread.
- An unanswered `session/set_mode` leaves the native mode unknown, not unchanged: `AcpPeer` invalidates the turn, goes offline, stops its process group and refuses further changes until restarted. Never report the old or the requested mode after a timeout.
- A mode grant in `piPermit` or the local worker's `permit` (`src/hub/daemon.ts`) answers as the prompt path does: allowed only while that owner is still the attached one and the call was not aborted. `ask-when-needed` covers `PI_EDIT_TOOLS` on a `grantablePath` only (path rule: `local-worker.md`).
- Pi and local approvals (#253): `permit` answers a `ToolApproval` (contract: `local-worker.md`) and `requestPermission` (`src/hub/daemon.ts`) tells the adapter's `ApprovalObserver` what settled it. An expiry counts toward the stop only as `source: "expired"` with `eligibleExpiry` not false (no person answered a request of that peer while it was pending); `person` resets the count, `automatic` (a mode grant, Pi's `always`) never does, and a new turn starts it over. The second one ends the turn, never the peer: local throws `ApprovalWaitStop`, Pi sends `abort_budget` with `cause: "approval"`, and both settle the delivery `completed` with the reason; a Pi whose extension did not announce `approvalTurnAbort` goes offline with the delivery held. `requestPermission` deletes a request from `permissions` before it runs an observer, resolves or reports, and an aborted signal closes it as `cancelled`: a late answer must find nothing to grant, and a failed event, notice or console push never strands the caller.
- Pi's `always` grant (#209) is keyed by `executeTool`'s tool name, never parsed from the approval title, and lives only in that Pi start's closure. Never persist it, share it with the local worker, or let the dashboard give it.
- Refuse ACP permissions while offline or waiting for watchdog cancellation before consulting automatic or human approvers. Abort pending permission signals on watchdog, offline transition and stop; the daemon withdraws their registered console approvals before any late person answer. Restart creates new requests without reviving withdrawn ones (#311).
- Apply QWEN_MODE_IDS only to a production qwen025 adapter with a qwen-code native identity admitted by compat and advertised ids; legacy benchmark ACP stays unmanaged. Await the native acknowledgement before bus admission, preserve existing approval fences, and never map auto or plan. No Qwen quota classification exists until a pinned native refusal is observed.

## Turns, watchdogs and hub tools

- Delivery failure diagnostics (#1178): carry the optional typed `failureCause` from `src/hub/delivery-failure.ts` through `DeliveryReceipt` and legacy `onFailed`, including pending RPC, steer and watchdog paths. Classify from structured host facts, never error, reason or body text. Channel receipt causes are assigned by the host, never trusted from the caller. A known cause never downgrades an uncertain delivery to `failed_safe` or changes settlement.
- A peer must set `busy` synchronously inside `deliver()`, otherwise the bus drains the next envelope into a running turn (Kimi answers `turn.agent_busy`). Outside a turn the adapter accepts an occupancy diagnostic (a `context-used` `usage_update` naming its current session) and nothing else: no token total, no chunk, nothing unnamed or for an offline peer (#285).
- A watchdog-cancelled turn still reports later. Anything a turn does on completion must check it is still the current turn (`turn` generation in `acp.ts`, `activeTurns` in `codex-appserver.ts`). A rejected prompt other than a recognised quota refusal, or an abnormal prompt end, reports through the adapter's `onTurnFailure` (same shape in `acp.ts` and `pi.ts`), even when ACP streamed partial text; a stale cancelled turn never reports it; a rejected watchdog-cancelled ACP prompt during its journal-less wait is discarded with one log line, not requeued as on the earlier adapter.
- After an ACP watchdog cancels a prompt on a bus without a journal, keep the peer busy with its inactivity watchdog cleared until that prompt settles; suppress its turn-scoped updates and permissions while still accepting session-bound occupancy diagnostics. Bound the wait by the existing 30 s ACP handshake deadline, go offline, never idle, with queued work retained if it expires, and revoke the wait on stop or transport loss; a durable delivery keeps its existing offline/needs_review path.
- ACP tool ceiling (#542): a tool call announced (`tool_call`) and not yet `completed` or `failed` in the current turn keeps a silent busy turn alive past the watchdog, up to `AcpOptions.toolCeilingMs` (never below the watchdog) counted from the last protocol message. Re-arm with `touch(<remaining ceiling, at most the watchdog>)`, never a full extra watchdog, and clear the open calls at each `deliver()`. Past the ceiling, cancel as an ordinary watchdog; its log line names the open tools only on a turn that is not private (latch `isPrivateTurn`, fail closed when it throws), each title as one sanitized, quoted, cut line. Fire `onToolCeiling({ ceilingMs })` before that line and the cancel; it carries the number only, and the daemon turns it into the host sentence for a kind whose adapter log is withheld (Jcode, `jcodeToolCeilingCause(ceilingMs, peer)`, #1601), so never add a title or native text to it. The daemon passes `toolCeilingMs`, `activityBatchMs` and Jcode's `steerTimeoutMs` from `adapterOperationalReaders` (`adapter_timing.*`, #982) only when it constructs an adapter; an adapter never reads config itself, and an accepted edit never retimes a running launch.
- Native capability listings (#445 C1, #985): keep vendor identities and listing shapes in `src/adapters/native-capabilities.ts`, never in `src/hub/capabilities.ts`. `capabilityManifest` lists only on a `NATIVE_PINS` version; any other version returns an empty manifest, never a guess, and a transport failure rejects rather than showing a stale list. Codex `skills/list` uses a negative hub id, and only `enabled: true` skills are listed. ACP keeps `available_commands_update` lists that arrive during `binding` keyed by session (`earlyCommands`, at most `EARLY_COMMANDS_MAX`), and the bind adopts only the bound session's list (#567).
- Retire a cancelled Codex native turn until its exact completion or session teardown. Late start acceptance, answer frames and completion must not revive its audience or relabel uncertainty as `failed_safe`. If cancellation has no provable native id, keep the peer offline until verified reattachment.
- Codex: the adapter never sends its own `initialize`. It is a proxy; hub requests use negative ids and their responses must not reach the TUI.
- A durable Codex steer stays pending while its native turn runs. Its RPC may answer after `turn/completed`: bound unanswered replies from that turn's end, requeue a definitive late refusal, and hold a late acceptance as uncertain without attaching it to a later turn's audience (#296).
- Codex reports each thread it adopts, started or resumed (`onThread`, the `native_thread` event), before any turn on it starts: the upgrade planner (Codex's `session.zeroTurn` in `src/adapters/definitions/native-recovery.ts`, read through `nativeZeroTurn` in `src/cli/upgrade-runtime.ts`, #215) gives each codex `turn_start` to the thread adopted last before it and plans a thread it saw start with no turn (and no rollout) as a fresh start.
- Peer DOING (#878): an adapter reports a native session title or its plan's in-progress item only through `onDoing` (set by `Bus.add`), with `reset` when it binds a new session or thread; never put that text in a log line, event, message, status notice or memory capture. Codex reads only `thread/name/updated` and `turn/plan/updated` of the bound thread, ACP only a `plan` update inside the current turn; never guess a value for a peer without such a source.
- Session titles (#1055, spec `docs/design/adapters.md` "Session title slots"): only a fixed builtin may declare `title` or `titlePersistence` (`assertNativeCapabilityScope`), and only a `title: "hub"` definition (Pi, local) is offered `hub_set_title` (`sessionTitleTools`); keep it off Claude, Codex, Kimi and ACP tool lists and native auto-approval names. Write a title only through `setSessionTitle` (unnamed-only for an agent, `current()` rechecked right before the effect) and report it only through `onDoing("title", ...)`; never pass a title call to `observeTool` or capture, and never store a derived unnamed label.
- Final answers (#1320): a driven adapter publishes a model's final turn answer through `BasePeer.finalAnswer` (the bus's `onFinalAnswer`), never `onMessage`, and passes `complete` only for a normal completion. `onMessage` skips Record capture and lets `amem:` Record lines reach peers unstripped. Decorate a turn's fixed prompt with `turnRecordPrompt`, never native client configuration.
- Observed turn model (#1402, spec `docs/design/adapters.md` "Observed turn model"): report a turn's model only through `PeerAdapter.observedModel()`, cleared on read and read once at `turn_end`. `served` only when the native surface names what it served (Claude print `result` `modelUsage`, Codex `model/rerouted`), `session` for the agent's own current model (ACP session model at prompt send, headless Pi `get_state`, Codex thread model, agy hook `modelName`), `configured` for a model the hub set and the agent acknowledged. Pass ids through `safeModelLabel`; never invent, expand an alias or truncate, and a refused, `unknown` or absent value records nothing. A failed model read never fails the delivery.
- Codex 0.154.0 `agentMessage` items carry `text` and `phase` (not `content[]`); only the last non-`commentary` message of a turn is shared.
- Hide `hub_delivery_retry` from delivery-only ACP/local tool lists and omit its retry hint. Treat `AGENTHUB_DELIVERY_ONLY` only as an exposure hint; the daemon must refuse by the actual attached adapter, and native children must not inherit the marker. A Claude push that cannot reach its model reports `failed_safe`; if the daemon refuses that optional receipt state, try `needs_review` and retain uncertainty when neither receipt is confirmed. Keep `hub_delivery_resolve` on every list, delivery-only included: settling one's own `needs_review` row is not a retry (#1112).
- ACP `onActivity` is a closed, transient person-only projection. Never publish it through the bus, log/event writers, UI, tools or memory. Emit only for an active turn; latch private envelopes and associated PII work, including unreadable privacy state, and discard pending chunks on turn teardown. Native terminal references do not authorize filesystem/terminal RPC reads.
- ACP quota refusals use the pinned agent contract in `src/adapters/acp-quota.ts`, fenced by native identity and current turn generation. Report hard quota and require the hub's explicit pause confirmation before settling a pre-acceptance refusal as `failed_safe`; retain `needs_review` when work already started, and keep unknown refusals on the ordinary failure path. Sanitize agent refusal text before hub-written output.

## Spawned processes and teardown

- Every agent the hub spawns (the Codex app-server, ACP agents such as Kimi, Pi) runs in its own process group and is stopped as one (`stopOwnedProcess(proc, { group: true })`, `trackGroup` after spawn): `codex` is a node launcher, and mid-turn its native app-server does not exit on SIGTERM within the grace period, so a SIGKILL to the launcher alone left the app-server running under init and holding the daemon alive (#113, #115). A new builtin adapter that spawns an agent does the same. A configured ACP kind stops only through `AcpOwnedGroup` (`src/adapters/acp-owned-group.ts`): capture the direct child and its original group after spawn, verify before admission and again before stop, SIGSTOP, re-verify, then SIGKILL only that group; never discover or signal descendants outside it, and with unproven ownership send no signal, close stdin and keep the owner until it is confirmed gone.
- To stop a process tree, freeze it (SIGSTOP) before reading what it contains, then SIGKILL, and call it done only when the table shows none of it (with no table at all, the stop can only ask the group itself, which cannot see groups below it). A process a read after the freeze shows for the first time is frozen and read again before anything is killed.
- Work that must survive `ahub kill` (amem capture session end) is awaited in `stop()`; fire-and-forget dies with the process.
- Native owner teardown must handle a lost shutdown acknowledgement using verified process identity. Pending launches must be revocable, and active tools/streaming output must count as watchdog activity. A reloaded `watchdog_ms` reaches a peer only through `configureWatchdog` (`src/hub/peers.ts`, #439) and applies from its next busy turn, never to the running one.
- `stop(reason?)` (`src/hub/peers.ts`): a reason marks a person's requested stop (`peer_stop`, rule: `daemon.md`). Fence before the first await (the adapter's stopping flag, or `offline`) so `deliver()` and buffered native callbacks do nothing more, hold the in-flight delivery as `needs_review` with that reason, and end `offline`. For ACP without a journal, return ordinary in-flight envelopes once through `onFailed` before a requested stop invalidates the turn; never return the watchdog-cancelled original prompt. A requested stop never completes, escalates or invokes failure handoff for the turn it cut (`AcpPeer` bumps `turn`; `PiPeer.fail` skips the failure message and `onTurnFailure` while `requestedStopReason` is set). `PiPeer.stop()` waits for aborted tools only up to `stopGraceMs`: a tool past it never blocks the teardown, and the stop throws `PiToolSettlementFailure` once the owner is down.
- A terminal the hub opens for a person (`src/hub/terminal-open.ts`, #269) gets `personEnv`, which strips every agent marker; never `peerChildEnv`, which sets one.
- Spawn a native peer with `peerChildEnv(peer, source)` so its own `AGENTHUB_PEER_ID` replaces inherited agent markers. Sandbox tool environments carry their executing peer too. Preserve the native shell environment policy; Codex's `CODEX_THREAD_ID` supplies the fallback after filtering. Before changing marker detection or launcher environments, read `docs/verification/2026-10-09-agent-shell-t0.md` for pinned source and live-probe limits.
- `peerChildEnv` drops every `ORCA_*` variable by default (#1094). Only a native that runs in the person's own pane passes `{ preserveOrca: true }`: `src/cli/launch.ts` and the Qwen CLI entry. A version probe, the process table or another helper the hub spawns uses `withoutOrcaEnv(childEnv(...))`, never `{ ...process.env }`.
- Launch ids and peer ids (agent-hub#1036): `peerChildEnv` gives a spawned peer `AGENTHUB_PEER_ID`; a Claude session's launcher also puts `AGENTHUB_LAUNCH_ID` into the environment every shell and MCP helper it spawns inherits, and a tools hello that names a Claude channel peer is a distinct session `<peer>~<origin>` only when it PRESENTS a launch id that is not the current launch record's (`sessionHello`). A hello with NO id stays the peer: the native facts hook, a helper and a person's shell connect that way and must keep working (#636, #525-5), so `ControlClient` never injects an inherited id. Nothing is refused: a new adapter that gives its tools socket a peer id keeps its marker admission, and adds its own launch id and `sessionHello` branch only when it wants the same distinction. The daemon labels an envelope an adapter publishes itself with the launch read by shape from `managedLaunchId` (channel) or `ownedLaunchId` (Jcode) (rule: `daemon.md` "Sender provenance"): keep those names, and never admit or authorize anything by them. This makes sessions distinguishable, it does not authenticate them: a same-user process can always act as the user.
- Spawn with `peerChildEnv(<instance id>)`, not the kind name. An ACP `kind` comes only from the host declaration, never from the id suffix or agent text.

## Pi

- Tag a Pi hub-tool refusal only at a proven pre-effect guard with `PreEffectToolRefusal`; return its exact error and settle its receipt. Never classify a generic/post-effect/storage failure or a legacy pending receipt from error text or current board state. After durable `markStale`, cancellation or output consumption, retain ordinary failure classification; a later binding/privacy rejection cannot prove that no effect occurred. Recheck task revision, owner/session generation and privacy across awaited bounded spec/check operations; never turn those tools into arbitrary host execution.
- Version gate (#843): `PiPeer.startImpl` first awaits the preflight the production factory `createPi` passes as a separate constructor argument (keep it out of `PiOptions`: transport option identity), which runs `piVersionAsync` on the exact configured `pi.cmd` plus `--version` (owned group, 64 KiB, 10 s) against compat `pi`. Only a `PiVersionRefusal` reaches the caller as is (sanitized, 1000 characters); never wrap another start error in it. A fake Pi in a daemon fixture answers `--version` with a verified version.
- Report each Pi owner exit once, with code/signal (unknown for an unobserved TUI exit), turn/tool activity and only the last tool name. Auto-restart only a current, started, unexpectedly idle headless owner on its verified persisted session, once per 60 s; preserve shutdown/requested-stop/recovery/startup/active-tool fences and never fall back fresh.
- Keep Pi owner identity on the shared `processSignature`/`processLiveness` contract exported by the first-party package's Node-safe `@staix/agent-mem/platform` entry, re-exported unchanged by `src/pi/process-signature.ts` for the startup claim, extension claim, TUI owner monitor, `recoveryReady` and verified teardown. Memory's `sync.lock` uses the same implementation. Preserve the Node-safe process-entry regression in `test/memory-parity.test.ts`, the existing Pi process behavior tests, the LC_ALL=C/TZ=UTC `ps` read and strict pid + start + command identity; never accept PID-only or a fuzzy command match.
- Return the shared `toolResultFailed` verdict as `/tool`'s `failed`; map only `failed === true` to Pi's `isError`. Preserve text and the older bridge's absent-flag behavior. The one exception is a person's `!command` whose process exit was observed: its `failed` is `exitCode !== 0` and the reply carries `exitCode`, from `onProcessExit` through `packPiShellResult`, never parsed from the output (#253).
- Pi's bridge executes `/tool` only for the verified owner (`verifiedOwner()`: the claimed pid with its `processSignature`; a headless owner is pinned from the spawned process once `get_state` proved its session) with the current `sessionId` and turn `generation`, and admits `/budget` only for that owner and generation, checked again after the awaited admission. Refuse anything else before execution. `tool_abort` aborts that pending call, or fences its id when it arrives before the call (64 ids a turn, then every further call of that turn). A person's `!command` (`purpose: "idle_user_bash"`) is taken only in TUI mode from an idle owner on its one-use reservation, and it alone skips `piPermit`: never widen that to a model's bash call (#253).
- Emit Pi's ceiling event at the pre-effect rejection boundary (`src/pi/ceiling.ts`), before `agent_end`. Accept only a valid current-session/current-generation signal during a running turn; retain the first signal and attach it to that turn's failure. Never classify a ceiling from free text. At `agent_settled`, mark a ceiling delivery completed with `ceiling steps <count>/<limit>` and pass `settledCeiling: true` only when that turn failed without cancellation, withdrawal or an execution/approval budget stop, and no managed tool was pending when the ceiling arrived or remains pending. Latch tool uncertainty at the ceiling even if tools settle later. Keep every other failed delivery held; never replay it. Observe explicit stop/recovery, roster or personal withdrawal and cancelled settlement once per logical turn through `onTurnAborted`, without failure handoff; internal model-failure teardown suppresses that observation. Call `onTurnSuccess` only for an actual nonerror, noncancelled settlement, never a ceiling.
- Known limit (#1447 T4): host `turn_start` is adapter busy, before Pi model selection/readback. Workflow items after that boundary stay queued for the following host turn; do not fold them into an unsent provider prompt. Closing this gap needs an explicit preparation/commit or deferred-fold contract preserving durable ACKs and private input fences. Former-owner done/checkpoint refusals still apply in that window. Its duration was not measured.
- Pi dependencies (#1447 T5): register preparation only from the Pi factory. Use the trusted worktree record's reviewed Git base and protected global hub state outside every peer root; never execute mutable task install inputs. Keep the fixed frozen-install command, scrubbed environment, deadline, lifecycle/config refusals and CWD-pinned rename publication. Preparation failures stay advisory; accept/self-claim replies recheck ownership, acceptance/session and privacy after waiting and carry fixed readiness guidance. Never copy dependency trees or skip install scripts to make preparation succeed.
- Pi TUI hub prompts (#379; an idle snapshot ACK arriving before a personal start inserted a hub prompt into the person's turn): attribute a start, end or settle to a hub turn only by the command's `promptId`, which lasts until the logical `agent_settled`; treat any other start while a hub prompt is pending or running as personal activity that detaches Pi. Settle `failed_safe` only on a `prompt_not_started` refusal bound to the verified owner, session, command id and generation; everything else stays `needs_review`. Refuse roster return without `fencedPrompt`.
- `validatePiSession` (`src/pi/session.ts`) throws `PiSessionUnresumable` only on positive evidence (ENOENT, a file outside the managed session directory, an unparsable or mismatched header) and `PiSessionBookmarkMismatch` only when a valid header names another session id; every other read failure is rethrown unchanged, because the daemon retires a Pi continuity bookmark only on those two classes (#463). `PiPeer` rethrows a mismatch with the neutral header-id message and never claims a bookmark exists (`test/pi-session-validation.test.ts`).
- Pi terminal ownership reads only the existing monitor's current pid/signature/session/file/token observation, expiring after 1 s; unknown verification withdraws proof. Keep fresh shared process-signature checks at tool/effect admission and teardown, and never revive terminal proof across detach, offline, stop or a changed owner/session (#576).

## Qwen's dual-output TUI (#286 Part 3)

- Before qualifying another dual-output version, read the required Q2 normal-path contract in `docs/specs/2026-09-19-agent-hub-design.md` (Qwen dual-output TUI amendment) and use `scripts/compat-receipts/proofs/qwen-dual-bus-q2.ts`. Keep direct-native-busy-submit characterization separate; do not change automation admission from this manual proof. Do not infer native quiescence from adoption, event-file reattachment or hub deny settlement; preserve their separate ceilings when reporting qualification. Background for changing this rule: `README.md` in this directory.

- `src/adapters/qwen-dual.ts` drives Qwen's own TUI through `--input-file` and `--json-file`; it is started only by `ahub qwen --mode tui`, through the definition's `start.createTui` and the `qwen-dual` daemon port, both fixed-builtin capabilities (`assertNativeCapabilityScope`). Qwen's `start.forms` stays `["headless"]`: never add `tui` to it (that would make Qwen a start-mode peer the hub opens by itself, and would change `START_MODE_PEERS`, a cross-release probe). The launcher needs a terminal and the base `qwen` id; the daemon refuses a TUI start for a declared instance, off roster or while a headless Qwen runs.
- Judge a Qwen TUI by `holdsTerminal()` (its bound owner verified alive, or a session seen with no owner bound), never by peer state: a detached TUI reads offline while Qwen keeps running. A headless start over a held terminal is refused and a TUI start answers `already`.
- Gate the TUI on `COMPAT["qwen-dual"]` (verified 0.26.1, 0.27.0, 0.27.1 and 0.28.3, no `line`), both before the start (`qwenDualVersionAsync`) and from the TUI's own `session_start` (version, `protocol_version` 2, the events read). Never widen the headless `qwen` entry for it, or the other way round: their receipts are separate.
- `deliver()` sets `busy` synchronously and appends one `submit`; a prompt that is not the hub's own (matched by its text) is the person typing: the peer stays busy, nothing is shared, no approval is asked of the console. A submit that starts with `/`, `!`, `@` or `?` gets an `[agent-hub]` first line: Qwen reads a submit as typed input (slash command, shell line, file include). A turn ends at an `assistant` whose `stop_reason` is not `tool_use` followed by `message_stop` (or a `result`); a `tool_use` message never ends it.
- A Qwen background-task notice is not the person typing (#517): when a background shell finishes Qwen writes a `user` event of its own, which can land in the middle of a running hub turn, and several finished shells fold into one event. `isQwenTaskNotification` accepts exactly one or more whole `<task-notification>` envelopes (task id, kind, status header, blank line between envelopes) and nothing else; `onUser` judges the raw event, not `promptText` (which joins every text block and drops the rest): the content must be exactly one text block that is wholly the envelope, so a split or mixed-block event is a person's prompt. Such an event changes nothing: a running hub turn keeps its owner and is not failed, and an idle peer stays idle (never mark it busy for a notice nobody may answer). Read nothing inside an envelope beyond its header, and never loosen the shape: a prompt that only contains or resembles one is still a person's prompt and still settles a hub turn as uncertain. The old reading held 7 of 7 recorded `needs_review` queues; when a new Qwen event type shows up inside a turn, check the live `events.jsonl` against `onUser` before widening anything.
- After appending a Qwen deny, retain a durable input fence and settle only the delivery as known `completed`; never report idle from the deny, a denied-turn assistant/Stop, a control response, file readability or elapsed time. Check the fence write before appending the deny. Release it only after a newly observed same-session personal USER and that personal turn's normal final assistant/message_stop under the same verified owner, or a verified fresh native generation. Expire the named 30 s wait to offline with an actionable notice, retain queued input and the fence, and keep observing those recovery proofs after expiry. Persist the fence across detach, stop and adoption; an adopted fence needs a new personal USER, never buffered history. The watchdog never cancels: keep stalled turns busy; never type into the terminal, signal a turn or invent an input/ACK schema.
- Only an exact hub tool name is auto-approved (`autoApprove`, the daemon's `HUB_TOOL_TITLES`), and an always-ask class call never is. A `control_response` for a request the hub has not answered means the person answered in the TUI: abort the hub's pending request so a late console answer finds nothing. A request other than a hub tool that names the hub state dir (`qwenDualNamesStateDir` against `guardDir`) is refused before anyone is asked: the input file is a prompt channel (`docs/security.md`).
- Write each Qwen input record as one full UTF8 Buffer and require its full byte count, never retry a remainder. A short/throwing write settles uncertainty as `needs_review` and offline; a non-newline tail before append or attachment also blocks input. Only a verified fresh generation may reopen that file, never personal completion. Preserve the documented torn-prefix-ending-newline ceiling; add durable write intents only if that failure is observed.
- The event file is read from the saved offset in `state.json`. Qwen opens an existing event file at byte 0 without truncating it (measured on 0.26.1), so a fresh or resumed launch starts from empty files (the old event file is kept as `events.prev.jsonl`) and a hub restart adopts a still-running Qwen from the saved offset instead. The owner is bound from the host's process table (the root of the tree of processes whose argv names this adapter's input file; two separate roots is no owner), never from anything the launcher sends. An unreadable event file is `detached` (offline, the `qwen-detached` status notice), never idle, and reattaches when it reads again; a stall shows `qwen-stalled`. An event line over 1 MiB is dropped through its newline and the saved offset moves past it.
- Recovery never restores this terminal as a headless worker (`QWEN_RECOVERY_SESSION.recoveryRefusal`), and `stopPeer` refuses a Qwen TUI: the hub never signals a person's Qwen.

## TUI launchers, native facts and Antigravity

- Kimi TUI is a pull-only WsPeer under the one kimi id, with no hub busy/watchdog/permission/quota machinery. Only the person's launcher merges or removes its project MCP entry; a daemon headless start refuses a stale entry and never edits the file. Scrub mode/channel markers from the native child; managed AGENTS instructions and tool descriptions carry the pull rules, not MCP initialize instructions. Completion facts (#1282) do not change that pull-only transport: no push, steer, watchdog, permission or automatic quota handoff.
- Kimi TUI completion facts are admitted only on compat `kimi-tui` (2.5.2) through `native_hook_launch`, a launch-scoped plugin under the native home, and `KIMI_TUI_FACTS_HOOK`. The launcher uses async spawn so its control socket stays live, previews plugin writes, and cleans only that launch's files. A different launch's plugin is replaced only after a new begin succeeds and its recorded owner pid+signature is proven gone; an active or unknown owner is never replaced, including another project's launch sharing the native home. Replacement and cleanup share one fail-closed lock per native home; a stale lock is never removed automatically. Begin or setup failure prints the cause and next step and launches the plain TUI without completion receipts. Quiet background/final-turn re-reads back off from 250 ms to 1 s and the Stop deadline also arms them. `turn.prompt` proves origin, `turn.ended` proves the outcome; `prompt.completed`/`aborted` are optional consistency rows, and notification turns may omit prompt ids. Never treat Stop, a final message chunk, a heartbeat or an empty observed task list as proof. Background inventory is read from every agent's task files and stays unknown on any malformed or unreadable row. Final-turn and inventory re-reads must not emit prompt, response, error, task command or title text. Native-person results are private. StopFailure is failed only after final-state readback, Interrupt is quiet, and launcher end/socket loss creates at most one interrupted result.
- Empty-inbox polling advice (#681, `InboxPolling` in `src/hub/inbox-polling.ts`) is advisory: never refuse or delay an inbox read for it. The daemon computes it only for a pull-only peer after the pull completed, so a throw drops the advice, never the pulled envelopes; it counts only empty reads with no open, non-backlog task as owner or reviewer, and an assignment resets it. The plugin shows `[polling detected]` only for a well-formed `pollingAdvice` (count >= 3, minutes 0 to 10).
- TUI launchers (Kimi, Jcode, agy) write the plugin bundle the hub reports in `status` into their MCP entry, and the CLI's own copy only when the hub reports none (#502). Only the Jcode start path checks the entry against the daemon's own `SERVER_JS` (`jcodeMcpReady`); Kimi TUI admission does not compare it.
- Native CLI versions (#691): every version gate asks `assessVersion` in `src/adapters/compat.ts`; no other file holds a version constant. Add a version to `verified` only with a receipt in `docs/verification/`, and point the entry's `receipt` at the receipt a later version should repeat (the daily `scripts/agent-compat-watch.ts` names it, #849); a `line` is for contract gates only (an isolation gate never assumes a newer version compatible); the person's `ahub agents trust` admits one exact version on this machine and never skips a runtime proof; `ahub agents` with anything but `--json` stays `console` in `classifyPeerCommand` and refused in `liveTestRefusal` (`src/cli/identity.ts`). A version refusal starts with `VERSION_REFUSAL` and names only versions and the trust command; keep it that way so the daemon may show it.
- Jcode (#529): accept the native version only through `jcodeVersionSupported` (compat `jcode` line, 0.98.0 up to 1.1.0), in the daemon preflight (`jcodeVersionAsync`: off the event loop, owning its process group, output capped at 64 KiB), the doctor probe (`jcodeVersion`) and ACP `expectedAgent`; never pin the minor, and lower `line.below` when a release breaks the contract. Every owned jcode process (probe, serve, ACP and TUI) gets `JCODE_OWNED_ENV`, and the private socket name ends in `.sock`.
- Jcode TUI (#464): use only the current owned launch's top-level `--socket`/`--resume` tuple after native saved-session proof. Prove the save only through `savedSession` (no-follow, single-link regular file, size-bounded, unchanged across the read, its `id` and `messages` matching) and refuse a requested model, provider profile or session that differs from the running launch with `JcodeOptionMismatch`, which names the flag, never its value (#559); both the launcher and `--print-command` report it through `refuseNamedOption` (#574). Hand the tuple only to a person's launcher through `native_tui_launch` (admission: `daemon.md`); a refused tuple throws `JcodeTuiRefusal` with one closed `JcodeTuiRefusalCode` per check, never a path, socket, session or launch id. The launcher turns a returned code into words only through `jcodeTuiCauseMessage` (#1093). The headless-after-recovery hint is `JcodePeer.statusNotice` (fixed `JCODE_HEADLESS_AFTER_RECOVERY`), shown only after a crash report or a resumed session and gone once a ready TUI launch was served (`tuiServed`); previews (`--dry-run`, or `--print-command` from anyone but a person) start nothing and never resolve it. Never synthesize a save or prompt to induce one. Ctrl-C during the save wait and frontend close retain ACP; preserve session/load identity refusal and headless owned recovery metadata, and never record the TUI as a managed terminal (`recordTerminalLaunch`): Jcode has no terminal recovery adapter (#564).
- Jcode steer (#572): reach a busy owned jcode only through `nativeSteer` on its private server socket, never by cancelling its turn: `ping` must list `soft_interrupt_ids`, `subscribe` uses `target_session_id` (the ACP session id) and `continue_on_disconnect`, `state` must report `is_processing` (a soft interrupt sent while idle starts a turn by itself), then `soft_interrupt {content, urgent: false, client_id}`. `canSend` rechecks the captured turn, busy state, owned server process, socket identity and session immediately before the write. Every refusal before the send is `failed_safe` with nothing sent; a sent message that is not acknowledged, or whose turn cannot be confirmed, is `needs_review`, never `failed_safe` or `completed`. Read `currentTurn()` before sending and adopt only through `AcpPeer.adoptIntoTurn(turn, ...)`, which refuses a different or ended turn; adopted senders join the turn answer's audience (`replyParent` and `replyAudience` over the turn envelopes, so the hop cap holds), and each steer receipt is `accepted` at once and settles with the turn (`completed` on a normal end, `needs_review` on a cancel, failure, stop or watchdog). Headless Kimi and Qwen have no steer: status reports their waiting important messages only through `importantWaitingStatus` (`src/hub/daemon.ts`) past `budget.stale_min`. A turn that ends and restarts between jcode's `state` reply and the write still receives the message, held `needs_review` and adopted into nobody: keep that ceiling until upstream offers an atomic per-turn steer, and never add a cancel-to-deliver path.
- Jcode MCP set (#572): `jcode acp` and `jcode serve` start every server named in `<JCODE_HOME>/mcp.json` and the project's `.jcode/mcp.json`, `.mcp.json` and `.claude/mcp.json`, and no flag or variable selects them (`--mcp-tools`, `JCODE_MCP_TOOLS`, `JCODE_DISABLED_TOOLS` and `JCODE_DISABLE_CLAUDE_MCP` do not). Do not paper over it: `ahub doctor` lists the extra names through `jcodeExtraMcpServers` (`src/adapters/definitions/native-cli-jcode-mcp.ts`), names only, those four paths only, no home search, no link followed. Below the project root or home, `.jcode` and `.claude` must be real directories and the file a regular file (per-component `lstat`, an `O_NOFOLLOW` open and an `fstat` identity recheck); a system alias at or above the configured root stays allowed. Revisit if upstream adds a server selector. The person's machine-local `jcode_mcp_allow` (#1621; top level, or per instance, tier 3, never settings-editable) only changes what doctor accepts, through `splitJcodeMcpServers`: matching is by name, so a different server under an allowed name also passes (`ponytail:` comment). Never widen it to read a server's command or args, and never use it to change what jcode loads.
- Extra Jcode instances (#685, #368): one `JcodePeer` per declared id (at most 8), each with its own `jcode_home`, socket and state. The person authenticates inside Jcode; the hub passes `-p`, `--model` and `--provider-profile` exactly as declared, handles no model credential or URL, and only checks that the home is a directory the person owns (`jcodeHomeRefusal`: no read or write under it). Never put `AGENTHUB_PEER_ID` in the shared `.jcode/mcp.json` entry (`jcodeMcpEntry`): every owned launch supplies it through `peerChildEnv(<id>)` or the TUI launch env, together with its `AGENTHUB_LAUNCH_ID`. The MCP server with no `AGENTHUB_PEER_ID` in tools mode refuses every tool and never defaults to a peer id. The daemon admits a `tools` hello for a peer whose definition is `owned-acp` only when it carries the launch id of that peer's current owned launch (`JcodePeer.ownsLaunch`, from `jcodeLaunches`); never trust the env alone. `jcode --as <id>` never opens a TUI. Declare the semantic `instances.nativeHome` on a definition, never compare the kind name (`registry-guard`); it is a fixed-builtin capability that `assertNativeCapabilityScope` refuses elsewhere. `checkJcodeInstanceHomes` (`src/hub/instances.ts`, run once at daemon startup) refuses a home equal to or nested in the base Jcode's or another instance's; compare homes only through its `canonicalHome` (`realPath`, case-folded on a volume that folds case, inode), never `resolve()` text. The preview of `--as <id>` passes the instance to `previewJcode` so it shows the daemon's real flags.
- Hub-owned Jcode home (#1627, `src/adapters/definitions/native-cli-jcode-home*.ts`): `ahub init` reads only the allowed entries of the person's own `mcp.json` and never writes it. It never copies or links auth. It writes the new home's files 0600, and sets `jcode_home` only after that home holds a login.
- Jcode defers MCP tools (#912, `JCODE_DEFERRED_TOOLS_INSTRUCTION` in `src/hub/envelope.ts`): a Jcode peer lists only its built-in tools until the model searches for an MCP tool, so without a hint it reports the hub tools missing and answers in its final message. The guidance is written in exactly one place, that constant, and `JcodePeer` sends it through `jcodePreamble` (`src/adapters/jcode.ts`) ahead of the role contract, once with a session's first prompt, for the base peer and every extra instance. Never copy it into `STANDING_INSTRUCTION`, `templates/AGENTS.block.md` or a profile template (the Jcode bullet there is the same text in every template, and `test/jcode-deferred-tools.test.ts` pins both), and never change Jcode's own deferral or cache settings from the hub. The tools it names must exist, and the server name must be `JCODE_MCP_NAME`.
- Antigravity P1 (`src/adapters/agy/`): keep it optional, cloud, off roster by default, implementer/verifier only and pull-only. Until per-mode native prompt behavior is verified, reject hub permission/unattended mappings, headless starts and resume selectors; do not infer a quota source. The launcher refuses extra instances, any `agy --version` not admitted by `assessVersion("agy", ...)` (`COMPAT.agy` in `src/adapters/compat.ts` is the verified-set/warning-line source of truth; exact person trust is separate, #691), and a hub without the `native_hook_launch` feature.
- A project MCP entry the hub wrote is its own after the project directory moved (#1423): the directory fields are compared by real path (`sameDirectory`, `src/adapters/same-directory.ts`), not by text: `AGENTHUB_PROJECT_DIR` in the Jcode entry (`foreignField`), and `AGENTHUB_PROJECT_DIR` and `AGENTHUB_STATE_DIR` in agy's MCP entry and hook commands; a refusal names the differing field and the remedy. `jcodeMcpReady` still requires the exact current entry, so the launcher rewrites a moved one. Never loosen the rest of the shape (command, args, mode, peer id): only the directory fields follow a symlink. Kimi's entry is rewritten from the current paths and has no ownership check.
- Only the person's `ahub agy` launcher manages `.agents/plugins/agent-hub/{plugin.json,mcp_config.json,hooks.json}`. Refuse linked/foreign entries before any write; cleanup only the matching launch. Never write project-level `.agents/hooks.json` or personal Gemini settings. The plugin MCP server is named `agent-hub_agent-hub` by the pinned native client.
- Managed native facts use the definition's typed `NativeFactsPort` and the daemon's ephemeral `native_hook_launch` authority. Bind every observation to the daemon, launch, native session, project and current socket generation, and bind `WsPeer`'s live `nativeSession` (`bindNativeSession`) from `case "native_facts"` while keeping new `WsPeer` instances free of `nativeSession` until observed. Normal `Stop` (`NO_TOOL_CALL`) requires `fullyIdle` and a fresh validated completion row (a missing readback keeps the peer busy); terminal non-normal `Stop` reasons (`USER_CANCELED`, `ERROR`, `MAX_INVOCATIONS`, `MAX_FORCED_INVOCATIONS`, `MAX_TOKEN_BUDGET_EXCEEDED`, `TERMINAL_STEP_TYPE`, `TERMINAL_CUSTOM_HOOK`) with `fullyIdle` acknowledge any pending transcript facts/usage, clear the active turn, end any waiting cohort turn, record a closed-reason `native_turn_end` event (`reason` without `id`), settle any open #1054 run by its closed reason (pull-only `agy` opens none), and return the peer to `idle` (#1280). Native fact acknowledgement accepts only `SYSTEM_SDK` rows (`EPHEMERAL_MESSAGE` in 1.4.x, `SYSTEM_MESSAGE` in 1.5.x) in the exact session transcript path, extracts completed `PLANNER_RESPONSE` token counters (`input_tokens` excludes `cache_read_tokens`: cache reads exceeded input on 2947 of 3021 real 1.5.x rows, so `totalTokens` is their sum, not a double count) into `source: "agy_transcript"` usage events (deduped by hashed `(session, step_index)` across restarts), and advances the per-launch transcript cursor only after a scan that reached the previous cursor (or the 4 MiB lookback ceiling). `decodeAgyHook` normalizes `Read` (`view_file` `AbsolutePath`, `read_file` `Path`, with `StartLine`/`EndLine`/`ByteOffset` carried as `offset`/`limit` so partial reads never count as a whole-file view), `Write` (`write_to_file` `TargetFile`/`CodeContent`, `write_file` `Path`/`Content` when not `Append`), and `Edit` (`replace_all` only when `AllowMultiple` is true: a missing flag reads as a single replacement because no native receipt shows the default) (`replace_file_content` `TargetFile`/`TargetContent`/`ReplacementContent`, `edit_file` `Path`/`Target`/`Replacement`). The daemon records Pre/PostToolUse through `Facts.preTool`/`postTool` and offers nothing on them (#555, #1280). `INSTRUCTION_FILES` (`src/hub/permission-mode.ts`) includes `gemini.md` alongside `agents.md`, `claude.md` and `qwen.md`. Pull-only `agy` has no push, so on `SessionStart`/`PreInvocation` the daemon appends a count-only line (`[agent-hub: N message(s) waiting (M important); call hub_inbox]`, never a body or sender) to the injected message when `bus.queued(peer) > 0`, with or without a fact offer (#1280 P2). `agy acp` was probed model-free (`docs/verification/2026-11-08-agy-acp-t0.md`); its `AcpPeer` wiring waits for one authorized model-backed receipt.
- `terminalOwner(launchId)` (`src/hub/peers.ts`, #482) answers only for the adapter's current native TUI owner bound to that launch (Codex: the claimed link with that `launchId`, both sockets open; the launcher sends the id as the upgrade's bearer token through `--remote-auth-token-env`, because `codex --remote` refuses any path or query (#586); Pi: a started, verified TUI owner on its requested session); a start acknowledgement is never ownership. A Codex link that is not the claimed one or has a closed socket never adopts a thread.

## Reviewers

- Keep the default reviewer kind order Claude, Codex, Kimi (selection rules: `tasks.md`).
- Keep the retained agy reviewer slot unavailable with exact reason `agy is an implementer peer (#485)`, including explicit reviewer-pool requests. The slot is data only: the running-review fence (`runningReviewAuthority` in `src/hub/daemon.ts`) binds only a definition with `reviewer.backend`, so it never fences agy's own task reads (#792). Do not add agy reviewer launch/admission or personal configuration writes to #234; implementer work belongs to #485.
- For fresh Kimi reviewers and task-bound MCP (#533), retain the common per-child task/head/review-revision/generation verdict fences, privacy screening and cleanup-before-settlement. Expose only a host in-process two-tool MCP capability for `hub_review` and `hub_task_show`; never give the native child the full hub control token. Supply source evidence only through the screened review brief/read result and host facts; exclude native Read/file/shell tools. Admit only compat-covered Kimi versions when current runtime preparation passes; otherwise keep it unavailable with the refusal reason. Keep actual interactive-TUI/usage ceilings separate from completed live/fake receipts; do not reuse historical Seatbelt/dummy-provider probes as revised-contract passes.
- Start fresh Kimi reviewers without Seatbelt, with private `KIMI_CODE_HOME`, managed-provider-only configuration, clean temporary cwd, explicit empty skills directory and exactly `mcp__agent-hub__hub_review` plus `mcp__agent-hub__hub_task_show` in its agent tools. Use directory symlinks for the person's native `credentials/` and `oauth/`, and link `device_id` to the native identity; do not copy token files, select static-API-key mode or set `KIMI_DISABLE_OAUTH_LOCK`. Let native OAuth share refresh/atomic rename/`proper-lockfile` coordination and the existing Kimi account budget. Revoke verdict authority before shutdown; allow bounded TERM grace while the OAuth lock is held, then use verified owned-group teardown. Report a forced-kill/re-login requirement without attempting host auth repair.
- Bind every running print review to its immutable envelope head and review revision. Recheck `Tasks.reviewBindingCurrent` for task-MCP operations, legacy print reads and the verdict authority after awaits; an old child never gains a replacement request. A committed verdict acknowledgement does not authorize subsequent reads or verdicts.
- `ReviewerPrintPeer` (`src/adapters/reviewer-print.ts`, #223, #519; `ClaudePrintPeer` is its Claude wrapper) runs one fresh child per review and clears `reviewing` at the leader's exit and first in `kill()`. A stop or watchdog settles `needs_review` at once, before the kill; `completed`, `idle` and `offline` come only after the whole process group is confirmed gone, and a failed cleanup keeps the child handle and stays `busy`. The daemon's `reviewAuthority` compares `reviewToken`: never widen it.
- Every print child (reviewer and Claude implementer) is spawned, bounded and stopped only through `OwnedPrintChild` (`src/adapters/claude-print-child.ts`): its `done` settles only after the whole group is confirmed gone, and a failed stop rejects with `PrintChildCleanupError` while the owning peer keeps the handle. Never add a second spawn path to an adapter.
- Owned input observers (#1056): `beforeInput`/`inputReleased` (`OwnedInputObserver` in `src/adapters/claude-print-child.ts`) carry review-observer provenance only. `observerSessionId` (Claude implementer, reviewer print, local) is never `nativeSession` and never grants budget, resume, permission or task authority. `beforeInput` runs with the final target session before any prompt reaches the child or model, and a throw releases no prompt; `onInputReleased` fires only after stdin flushed for the current generation, and an observer throw never changes settlement. A fresh reviewer calls `inputFinished` only after its group is confirmed gone, its task MCP is closed and launch cleanup succeeded.
- Retained standby (#1174, `WsPeer` in `src/adapters/channel-peer.ts`): an opt-in (`retainStandby`) hello while another session holds the peer is kept as one of at most `MAX_STANDBY_SESSIONS` (8) standbys; `standbySessions` ids and PIDs are display only, never native-session provenance or authority. Ownership changes only through `takeover` (the person's `peer_takeover`, or the oldest standby when the owner leaves), guarded by the host's `channelTakeoverAdmission` and `claim.isCurrent()` across the async preface; the old socket closes 4405 (opt-in) or 4403 "detached by the person" and its native process is not stopped. A standby socket runs no peer operation until `ownsSocket` confirms it. A hello without the opt-in keeps newest-hello replacement.
- A reviewer backend is a fixed builtin `ReviewerBackend` in a definition's `reviewer`, never config. Its `prepare` must return a complete isolation receipt (matching backend id, binary, version, profile, evidence and `readOnly` true, plus `strictMcp` and `ephemeral` true, or for a `nativePolicy` backend `enforcement: "native-policy"`, `freshSession` and `hubToolsOnly` true) before every child. A `taskMcp` backend refuses without the host's `taskMcp` port and gets only that task's MCP config, never the hub-wide one. `admit(env)` and the complete synchronous `launch.current()` are rechecked right before spawn; keep that complete fence in `reviewToken()` at every verdict/task-MCP authority boundary. A `watchCurrent` launch supplies `startPolicyWatch()` with a review-owned full-policy probe; run its serialized asynchronous checks on absolute 100 ms due times, coalescing missed ticks without overlap or an extra post-check delay. Pass only expected paths/fingerprints to its worker, never task text or inherited environment. Fence the exact child/review sequence on failure as `review policy changed`, and terminate/join the worker before private cleanup even when native stop fails; retain an unconfirmed owner for explicit stop retry; a missing or failed proof refuses, never a weaker launch or a continuing native session. The daemon puts the reviewer on the bus only after `start()` proved isolation; a failed start or a `start_failed` report marks it in `reviewerUnavailable`, which routing reads as `failing`. An unavailable reviewer variant has no reviewer backend or launch code; `startPeerBody` refuses it before preflight, independently of any native TUI launcher.
- Report reviewer failures (`onUnavailable`: `start_failed`, `quota`, `no_verdict`, the last also for a `review.max_minutes` wall-clock cap with reason `review time cap`) only after the child's group is confirmed gone and only while its generation is current: a person's stop owns its hold and never reroutes. Complete a normal no-verdict delivery only after the host confirms a current re-offer; an uncertain or failed fallback stays `needs_review`, with its `REVIEWER_FALLBACK_UNCONFIRMED` reason excluded from automatic moved-review settlement; ordinary superseded holds keep their existing rule. Log one bounded no-verdict line from exit code and allowlisted hub-tool metadata only, with full refusal privacy/secret screening before sanitization and truncation; retain the first full host refusal across native echoes, and withhold differing later host refusals rather than replacing or accumulating them; stale/private context is withheld. Record only allowlisted tool names and refusal text; never retain argument objects, task/diff fields or model-message events as trace data. `quota` comes only from the backend's structured `failure(event)` (the pinned native frames in `src/adapters/definitions/native-quota.ts`, revalidated by `nativeReviewerQuota`) or Kimi's `failureOnExit` (a nonzero exit with the complete owned stderr read after group settlement, `kimiReviewerQuotaOnExit`), never from assistant, tool or model text (quota rules: `budget.md`). An NDJSON frame over 256 KiB or more than 4 MiB of output aborts the review as `needs_review`.
- Codex reviewer isolation (`src/adapters/codex-review-isolation.ts`): accept only a `codex-cli` version that compat `codex-review` admits (verified or the person's trust, #691), and still run every proof below after trust; pass `-c notify=[]` (legacy notify off) on every launch; prove model-free that Apps, plugins and hooks are disabled (`features list`), ambient MCP servers are replaced by disabled stubs, and the hub server alone is enabled with exactly `hub_review` and `hub_task_show`; approve exactly those two MCP tools per tool, never with a server-wide approval default; before marking a reviewer backend/version verified, record a successful model-backed hub tool call as well as the model-free inventory (inventory alone is not verdict-delivery proof); run the native sandbox fixture probe before every launch; hash the binary once and fence binary and config files by metadata. Credential denies come only from the bounded `HOST_CREDENTIAL_PATHS` and `HOST_CREDENTIAL_ENV` lists, denied at the lexical and canonical path; refuse glob syntax or a root inside the checkout. A root that is dangling or unreadable refuses too; the reason names only its path class (`~/.docker`, `$DOCKER_CONFIG`), never a path or contents. Never pass the control token in a reviewer child's argv, env or MCP config: keep the hub state dir in its `privatePaths`. A refused `prepare` carries a `causeClass` from the closed `REVIEWER_CAUSE_CLASSES` (`version`, `binary`, `mcp_inventory`, `plugins_hooks_apps`, `sandbox_proof`, `credential_root`, `fixture_root_denied`, `timeout`, `unknown`; `reviewer-print.ts`, #722): `prepare` tracks the proof leg it is on, `fixture_root_denied` (#1493) means a deny entry covers the system temp directory and the hub's own `reviewer-proof` directory, so the proof has no place for its public canary (the fixture root moves to the hub directory when only the temp directory is covered; the reason names no entry), and `timeout` means a metadata command ran out of its 2 s or the 12 s budget, never an abort. The host builds the reason only through `reviewerUnavailableReason(cause, detail)`: a fixed sentence per class, plus a credential-root path class (`~/.docker: a dangling link`) as the only detail. The one exception is a failed `start()` whose error is a version refusal (`VERSION_REFUSAL`) or comes from a `nativePolicy` backend: the daemon shows that sanitized message, capped at 1000 characters (#691). `ReviewerPrintPeer` classes a missing or invalid receipt as `unknown`, a `launch.current()` change before spawn as `binary`, and any other start error as `unknown`. Keep admission refusals separate from start failures: skip only a stale-bound request with one task-id log and no reroute; reroute a still-current request whose policy changed as `no_verdict`, without marking the reviewer unavailable. The daemon writes that reason to the `reviewerUnavailable` map (read by routing and shown as the `reviewer` line of `ahub status`), and a `hub.log` line names the class. Never add native CLI text, a path, a version output or a token to the class, the reason or the log.

## Headless Claude implementer (#525-4)

- `ClaudeImplementerPeer` (`src/adapters/claude-implementer.ts`) runs one owned print child per turn in its verified worktree and none while idle. Keep the native argv of `claudeImplementerArgs`: `--permission-mode default`, `--strict-mcp-config` and `--permission-prompt-tool mcp__agent-hub__hub_permission_request`; never `acceptEdits`, `dontAsk`, `bypassPermissions` or `--bare`. `--model` is added only from the instance's validated declared `model` (#844, `instances.modelSelect` on the headless variant; one `NATIVE_WORD`, headless implementer only, untracked config only) or, ahead of it, the person's runtime override sampled at each turn boundary (`getModelOverride`, `ahub model`, #1317, rechecked with `isNativeModelToken`), on every turn, resumed ones included; never from task, chat or tool text. `never-ask` and `--unattended` are refused at every layer (factory, `setPermissionMode`, daemon start, `validateInstances`); a mode change only changes what the host facts gate allows. A start needs a version compat `claude-implementer` admits, and each turn rechecks the binary fingerprint from `proveClaudeImplementer`.
- Per-task native sessions live only in `ClaudeTaskSessions` (`src/adapters/claude-task-sessions.ts`, file `claudeStateFile("claude-task-sessions", id)`, ids only). A reserved UUID becomes `--resume` only after `markStarted` saw a stream-json frame naming that session; forget it only when `transcriptPersisted` answers false (unknown keeps it); an unreadable or invalid state file throws, never resets. Chat without a task ref goes to the instance's single `in_progress` task (`chatTask`), else to a `--no-session-persistence` one-off child.
- A private envelope refuses the delivery before spawn; an item `admit` refuses is dropped without vetoing the others. Settle `failed_safe` until the child's stdin was released (`inputReleased`), `needs_review` after; a failed group cleanup keeps the handle and stays `busy`.
- The child's tools-mode server (`AGENTHUB_PERMISSION_TOOL=1`) lists only `IMPLEMENTER_HUB_TOOL_NAMES`. `hub_permission_request` returns the original input only for the person's allow-once. Automatic Bash grants require the #845 host wrapper, a current owned public task/root/branch, existing read-only or closed task-command proof, and wrapper protocol 1 on request and reply; never return an automatic allow for the original native command. Consume the expiring single-use ticket before rechecking and executing with the fixed host environment, absolute executable and proven cwd; changed proof/task/child/root/branch runs nothing. Require the local-worker mutating Seatbelt profile for check/test/build with an additive deny for all project Git metadata and the canonical hub state. Only closed host Git add/commit/push and gh stay outside it; refuse configured filter/external drivers/textconv for add/commit only (global Git LFS must not disable push/gh), retain the config-include/partial-clone refusal for privileged Git/gh, and disable signing/automatic maintenance. Pin default-branch authority from the remote, never mutable local origin/HEAD. Unknown or unavailable confinement asks. Enabled action classes and `ask` still ask; malformed requests, no hub, expiry or a changed child deny. The original arguments stay in the child's request; the person sees only `permissionPayload` (`src/hub/permission-payload.ts`): the whole value withheld on any screen match, cut with `[cut, N chars]` inside 600 characters. Daemon admission of that child: `daemon.md`.
- Failure stages (#950): a failed turn's reason comes only from the launch-bound `ClaudeFailureTrace` (`src/hub/claude-failure-stage.ts`), sealed at leader exit and rendered by `formatClaudeFailure`; it is `details withheld` unless `failurePrivate` answers `false` (absent, unknown or a throw is private), and a trace error never changes cleanup or settlement. The tools-mode server denies an invalid `hub_permission_request` locally whatever the hub answers: `acceptsNativePermissionRequest` keeps the approval path's checks, and the strict `validateNativePermissionRequest` only classifies a diagnostic probe (at most `NATIVE_PERMISSION_PROBE_MAX_PER_LAUNCH` per launch); never use it to narrow or widen approval.

## Always-ask (#636)

- Class calls in `src/hub/action-enforce.ts`: the Claude PreToolUse hook returns `actionClasses` (`ask` beats `allow`), `AcpPeer.answerPermission` consults `actionGate` before `autoApprove`, and the daemon's `classedToolPermission` runs before `never-ask`, `ask-when-needed` and `piAlways` in local `permit` and `piPermit`. Keep Pi's gate inside its persisted tool receipt so a replay never spends twice. Classify a local/Pi call with `cwd` and `workdir` set to the host execution root, never the model's fields. Unknown, unparsable or absent payload follows the native mode; a classed request is never answered by `--unattended`. A gate that throws asks deny-only (`command withheld`, `denyOnly`), never allows.
- Local/Pi approvals supply the host's complete tool title only through the optional `onPremToolTitle` port; match it against the exact bash/git input before showing it with the class line. The person's on-prem console gets that full title even on a PII turn. Keep it out of logs, public status, other peers and dashboard projections. Public/native cut or withheld views set `denyOnly`: drop every grant and budget choice, and reject forged allow/budget answers. Never infer completeness from the presence of a marker string.
- Codex (`interceptActionApproval` in `codex-appserver.ts`) intercepts only `item/commandExecution/requestApproval` and legacy `execCommandApproval` with a well-formed command; any other request, or no `actionGate` verdict, keeps native handling. Classed command approvals need the current link, thread and observed active turn; without that binding deny, including legacy exec approvals. A pending classed wait is aborted, and answered deny, on stop, watchdog, detach, thread adoption, its turn's completion or interrupt. Keep `approvalIds` tombstones for the socket lifetime and suppress late/duplicate TUI replies. At 1024 ids close both sides rather than evict a fence; reattachment is the upgrade path. Native calls that emit no request remain not enforceable.
- Action allowances use their own host `actionSession` port; do not widen `contextSession` for Local and thereby change checkpoint, telemetry or supervision behavior. Managed headless Claude enforceability needs a current child generation in busy state, never a truthy method reference.
- The class-budget choice is the hub's own option (`ACTION_BUDGET_OPTION`), answered to the agent as its own `allow_once`; only that choice calls `ActionBudgets.approve`, and a refusal answers cancelled. Never let an ordinary allow seed the ledger. Claude never consults the ledger. `ActionBudgets.approve` consumes a slot when another approval landed since its challenge was issued (requests are concurrent; a reset would let N+1 calls through), and the daemon revokes a peer's entry on its `offline` transition and before creating a new owned adapter, so a resumed session id never revives an allowance.
- Do not claim enforcement a native mode bypasses: Kimi's `yolo` and `auto` send no request for a call they allow, so `ahub status` lists that peer as not enforceable until it is back in `ask`.
- The floor (#999 T3, `action_policy.floor`) is the only place the classifier is told a push or pull request is ordinary: `classifyAction(..., floor?: FloorFacts)` runs `floorPush` and `floorPullRequest` only for a bare command (an `unwrapped` wrapper, `-c`, `--git-dir`, `--work-tree`, an expansion or a `cd` it cannot place keeps the class), and without a `FloorFacts` argument it is byte-identical to before. The flag is read only through `ActionBudgets.floorOn()`; the daemon's `floorFacts(peer)` supplies the facts per execution root (the default branch from the same authoritative remote read as the task shell, cached and refreshed at every `action_policy` reload; `inOwnRepository` only when git proves the top level is that root and its origin is the project's repository). A fact that is missing or unproven is the strict case; never add an allowed form to `floorRefspec` or `floorPullRequest` without a test that pushes the matching unforced and forced, default-branch, tag and opaque variants. A new allowed class change belongs there and in `test/action-floor.test.ts`, never in the shared `classify` branches.
- Floor facts hold only until the first earlier segment on the line that could change them. In `floorInert` (`src/hub/action-class.ts`), `FLOOR_INERT_PROGRAMS` and `FLOOR_INERT_GIT` are allowlists: any other program or git subcommand, a `FIND_WRITERS` primary, `rg --pre` or a glob argument ends the facts for the rest of the line. Before adding a program or git subcommand to either allowlist, show that no form of it can write a file, git config or a ref, or run another command, and add a test in `test/action-floor.test.ts` where its writing form still asks. Adding to `FIND_WRITERS` only makes the floor stricter. Revisit if the facts are ever re-read per segment. A redirect to a device file is not an output for the destroy rule (#725, #1193): `DEVICE_OUTPUTS` in `src/hub/action-class.ts` lists exactly `/dev/null` and `/dev/tty`, matched as written and never resolved, prefix-matched or normalized. `/dev/stdout`, `/dev/stderr` and every `/dev/fd/<n>` (1 and 2 included) stay destroys, because on Linux they reopen the file fd 1 or 2 already points at and a `>` truncates it (`sh -c 'echo x >/dev/stdout' >>/tmp/log`; the person's ruling after review of PR #1202); so do `/dev/sda`, `/dev//null` and `/dev/null/x`, and a device target never hides a real one beside it. The redirect is still recorded (`redirected`), so the read-only fast path in `floorInert` stays closed. Add a device to the list only with proof that opening it for writing cannot change a file and that no descriptor stands behind it, and a test in `test/action-class.test.ts` beside the lookalike rows.
- 2026-11-02 (#1089): a terminal the hub opens for a start through Orca (`src/hub/terminal-open.ts`, #269) is opened in the worktree `resolveStartTerminalWorktree` finds by asking `orca worktree list` for the one whose path equals this project's root, never in `ORCA_WORKTREE_ID`: that variable names the terminal this process was started from, which is another project's when `ahub --project`, the dashboard manager or an upgrade brought the project up. `startTerminalCandidate` (the environment or a recorded launch) only answers the synchronous "could Orca be used" question in `available()`. The match is exact because `ahub <peer>` compares the terminal's worktree root with the project root by equality; a parent, a child and an archived entry are not matches, two matches and a cut-off list that lacks the root are refusals, and each refusal names the cause and the next step and carries no path. Verified against Orca 1.4.245: `worktree list --json` rows carry `id` and `path`, with `truncated` and `totalCount` beside them. A change to that shape is found by the fake-Orca test in `test/start-modes.test.ts` only if its fixture is updated with it, so recheck the real output when Orca moves (the read-only probe is `orca worktree list --json`; never create or write to a live pane).

## Other hosts' user skill directories (#1622)

`ahub setup` installs the hub's skills (`plugins/agent-hub/skills/`) into each other host's user skill directory.
Established from each host's own source or help output, not from a shared convention:

- Codex `@openai/codex`: `_codex_home()/skills`, so `$CODEX_HOME/skills` (default `~/.codex/skills`).
- Kimi Code: `$KIMI_CODE_HOME/skills` or `~/.kimi-code/skills`; project skills sit in `.kimi-code/skills/`.
- Qwen Code: `getGlobalQwenDir()/skills`, so `$QWEN_HOME/skills` or `~/.qwen/skills` (it also reads `~/.agents/skills`).
- Jcode: the global `~/.jcode/skills/<name>/SKILL.md` under `$JCODE_HOME`; it also reads `.claude/skills` and `.codex/skills`.
- Pi: the global agent dir's `skills`, so `$PI_CODING_AGENT_DIR/skills` or `~/.pi/agent/skills`.
- agy: `~/.gemini/config/skills/<name>/` (its global config directory).

The directories are `hostSkillDir` and `SKILL_HOSTS` in `src/adapters/definitions/native-cli-skills.ts`, with the other
native facts, so no host name appears in the installer engine (`src/cli/skills-install.ts`) and the #451 registry
inventory stays empty outside `src/adapters/`. It writes a `.ahub-skill.json` marker (`tool`, `version`, `sha256` of the
tree) with each copy and replaces a tree only while that digest still matches; the check is repeated at the write, so a
tree that changed while the confirmation question was open is kept. A host with no config directory gets no install and
an `absent` state; setup never creates a host home. Never follow a link: a linked skills directory, a linked skill
directory, or a link inside the tree, is reported and left alone, while a symlinked host config home is the host's own
choice and is resolved with `realPath` (`src/hub/project.ts`), never `realpathSync`. The file count and size are bounded
before anything is written, and `ahub setup --undo` removes only the hub's own unmodified trees. Tests use fixture homes
only and never read or write a real agent home.

- Exact instructed CLI (#1622): derive argv only from the confirmed native transcript receipt; admit only the explicit classified form list, refuse private turns and PII tasks, and close the receipt before execution. Use the daemon-captured installed runtime outside project and peer write roots; the child uses inherited Bun IPC and never a WebSocket. Preserve the current managed-session and launcher checks through the effect, and never log prompt arguments.
- Intent instructed CLI (#1622): admit agent-selected argv only through its closed list of id, peer and enum forms, a current confirmed receipt and the existing inherited IPC boundary. Person verdicts are the exception to reversibility: match the literal item id, and both task id and slot for a claim, against the confirmed prompt. Reserve each of at most ten operations, and recheck the session and privacy until the effect. Spending settings, free-text forms and other closed classes remain refused. Record the person's instructed provenance, never the prompt text.
- Screened exact forms (`screen: true`) pass each input (the receipt args, the argv, plus the study contract or the previous title) through `publicMetadataText` and `screenPii` with `SCREEN_TIMEOUT_MS`. Reconfirm the receipt after each screen and before consuming it. A screen is not declassification. `INSTRUCTION_CONTROL_TIMEOUT_MS` budgets three screens: adding a fourth input raises that bound in the same change.
- `plugins/agent-hub/skills/ahub/SKILL.md` lists the admitted exact and intent forms. Change it in the same PR as `exactForm`/`intentForm`, because no test binds the two. Keep `disable-model-invocation: true` on the `ahub` skill.
