From bd74f714addc7b3ff134e0f4bc68e7a5b4e5b0ac Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 15:49:37 -0500 Subject: [PATCH 001/129] chore(plan): complete planning for PAN-5754 Plan-Finalized: 4bc96701b264c44addc3b284a940ec06706bd414bfc5cf9f8a60e68a8ea5da2d --- .pan/drafts/PAN-5754-critique-2.md | 13 + .pan/drafts/PAN-5754-critique.md | 25 + .pan/drafts/PAN-5754.md | 501 ++++ ...s-from-the-operator-credential.xbrief.json | 2182 +++++++++++++++++ 4 files changed, 2721 insertions(+) create mode 100644 .pan/drafts/PAN-5754-critique-2.md create mode 100644 .pan/drafts/PAN-5754-critique.md create mode 100644 .pan/drafts/PAN-5754.md create mode 100644 .pan/specs/2026-12-03-PAN-5754-design-isolate-agents-from-the-operator-credential.xbrief.json diff --git a/.pan/drafts/PAN-5754-critique-2.md b/.pan/drafts/PAN-5754-critique-2.md new file mode 100644 index 00000000000..054688f974e --- /dev/null +++ b/.pan/drafts/PAN-5754-critique-2.md @@ -0,0 +1,13 @@ +plan-digest: cd5f51cba77f8b6ffaf5d13a700be55daf5b16acaec452804b4f409af3b43cfc + +## blocks-the-design: forwarded handoff can create an operator conversation + +The draft grants a work token the `handoff` self-job verb without binding its source conversation (`.pan/drafts/PAN-5754.md`, lines 280–294). The existing CLI accepts an explicit conversation name or ID and sends the caller's focus to the fork route (`src/cli/commands/handoff.ts`, lines 100–107, 200–218). The fork handler defaults an omitted role to `conversation` (`src/lib/overdeck/conversation-forks.ts`, lines 774–778). Under FR-11, that successor has the operator credential and no sandbox. Thus an isolated work agent can forward `pan handoff ` and cause a privileged successor to run. Remove `handoff` from the generic forwarded table, or replace it with a self-only action that binds the source and successor to the caller's issue and isolated token role. Add a test that an agent cannot hand off an operator conversation or create a `conversation`-role successor. + +## blocks-the-design: root registration fails open + +The peer rule trusts loopback whenever the root registry is empty (`.pan/drafts/PAN-5754.md`, lines 111–113, 313–319), and the existing mint accepts an uncredentialed trusted loopback peer (`src/dashboard/server/routes/dashboard-auth.ts`, lines 454, 476–482, 509–519). The launcher plan creates only the policy's masked directories before writing `/isolation/roots/.json`; it never creates `isolation/roots` or requires that write to succeed (`.pan/drafts/PAN-5754.md`, lines 204–213, 309–312). The first launch therefore has no registry entry if that directory is absent, and a later write failure has the same effect. Probe P10 already establishes that sandboxed Bash can reach host loopback through its proxy. Create the roots directory before launch, require an atomic registration and verified readback, and refuse the launch on any failure. Test a fresh home and an unwritable roots directory. + +## blocks-the-design: validated file flags can be swapped before the self job reads them + +D-7 validates a `workspacePath` flag with `realpath`, then passes the path to a self job outside the sandbox (`.pan/drafts/PAN-5754.md`, line 103). WI-19 explicitly enables `worker run --brief` this way (line 306). The existing worker command reads `options.brief` when the child runs (`src/cli/commands/worker.ts`, lines 228–235). An agent can replace a validated workspace file with a symlink to `internal-token` between the check and that read, causing the operator-rights child to consume the secret as a worker prompt. Exclude file-reading flags from self jobs. For `--brief`, have the isolated CLI read the file inside its sandbox and forward bounded prompt text; apply the same rule to any later file flag. Add a symlink-swap regression test. diff --git a/.pan/drafts/PAN-5754-critique.md b/.pan/drafts/PAN-5754-critique.md new file mode 100644 index 00000000000..4b8e7957421 --- /dev/null +++ b/.pan/drafts/PAN-5754-critique.md @@ -0,0 +1,25 @@ +plan-digest: 9b53f7de14313c03619205faff1f5a4e187f464173d900216017977417463c02 + +## blocks-the-design: fail-open leaves the credential readable on this host + +The PRD's probe notes say `socat` is absent here and Claude Code runs commands unsandboxed without it (`.pan/drafts/PAN-5754.md`, lines 35 and 64). D-12 and WI-4 deliberately set `failIfUnavailable: false` (lines 117 and 182-190). In that state, D-8's read deny and socket masks never apply, so a newly launched Claude agent can read `~/.overdeck/internal-token` and connect to the terminal sockets. A doctor error after launch does not enforce isolation. Make the isolated launch fail when the sandbox is unavailable, or make the switch explicitly opt-in until the prerequisites are present; require a launch test with `socat` missing. + +## blocks-the-design: forwarded file flags read operator secrets + +D-7 says each forwarded row allows the command's Commander flags except a list that omits file inputs (`.pan/drafts/PAN-5754.md`, line 103); WI-16 forwards `worker report` and WI-19 forwards `worker run` (lines 291 and 304). `worker report --file ` reads that path through `deps.readFile` (`src/cli/commands/worker.ts`, lines 366-399), and `worker run --brief ` does the same (lines 225-233). Self jobs run outside the sandbox with the dashboard user's filesystem rights (`src/dashboard/server/services/self-jobs.ts`, lines 125-133, 231-239). A worker can therefore forward `worker report --file ~/.overdeck/internal-token`, then retrieve the report, bypassing D-8. Exclude file-reading flags from these rows, use the bounded stdin path for reports, and validate any indispensable path against the caller's workspace with realpath before starting a job. Test the protected-file case. + +## blocks-the-design: hook payloads have no subject agent ID + +WI-14 says the five hook routes can compare the token with “the body's agent id field each handler already parses” (`.pan/drafts/PAN-5754.md`, lines 263-274). The actual `user-prompt-submit` payload contains only `session_id` and `prompt` (`sync-sources/hooks/user-prompt-submit-hook`, lines 43-45); `turn-complete` contains only `session_id` (`sync-sources/hooks/stop-hook`, lines 85-92); and `permission-event` posts Claude's raw payload (`sync-sources/hooks/permission-event-hook`, lines 12-21). Their handlers resolve a conversation from `session_id` (`src/dashboard/server/routes/hooks.ts`, lines 617-627, 669-681, 572-585). As written, the new equality check either rejects legitimate isolated hooks or accepts a caller-supplied ID unrelated to the session being mutated. Resolve the session's owner on the server and compare it with the token before handling each route; specify what to do when a session has no owner. Test a token for A with B's `session_id`. + +## blocks-the-design: alternate runtime launches bypass isolation + +WI-7 and WI-8 list only the agent spawn, recovery, messaging, planning and conversation launch sites (`.pan/drafts/PAN-5754.md`, lines 217-230). The runtime registry also launches agents directly: crash recovery calls `runtime.spawnAgent` (`src/lib/cloister/service-crash.ts`, lines 429-441) and session rotation does likewise (`src/lib/cloister/session-rotation.ts`, lines 245-257). The Codex runtime builds its own tmux command and environment, without `generateLauncherScript` (`src/lib/runtimes/codex.ts`, lines 674-699); Muse, Kimi, Prime Agent and ohmypi each call `generateLauncherScript` in their own runtime modules. Those paths will not receive `prepareAgentIsolation`, the token env, root registration or the Codex clamp. Inventory every production `spawnAgent`/`generateLauncherScript` path and make the runtime entry points prepare isolation too; test a crash restart and a rotation through a direct runtime. + +## blocks-the-design: worker run cannot pass its required issue + +D-7 excludes `--issue` from every forwarded row, and WI-19 forwards `worker run` without specifying a server-injected replacement (`.pan/drafts/PAN-5754.md`, lines 103 and 304). But `worker run` takes the issue only through `--issue` (`src/cli/commands/worker.ts`, lines 514-519) and returns a usage error when it is absent (lines 196-203). This breaks the planned delegated worker flow. For this row, validate any supplied `--issue` against `caller.issueId`, remove it from caller argv, and inject the caller's issue on the server; test the normal `pan worker run --issue ` command. + +## blocks-the-design: generic self jobs truncate and time out long commands + +WI-16 promises that forwarded verbs print their stdout/stderr and exit with their code (`.pan/drafts/PAN-5754.md`, lines 282-292). Existing self jobs keep only the last 16 KiB of stdout except for `task-done` and kill a command after 15 minutes (`src/dashboard/server/services/self-jobs.ts`, lines 29-36, 125-143, 231-239). `worker run` and `worker wait` can wait without a deadline (`src/cli/commands/worker.ts`, lines 215-216 and 267-272), while a valid worker report can be 1 MiB (`src/lib/agents/worker/report.ts`, lines 22-23). Forwarding these commands through the current runner silently cuts a valid report and kills a still-waiting command. Give long waits a bounded, resumable job protocol and preserve the full result for report-producing verbs; test a report over 16 KiB and a wait that exceeds the job timeout. diff --git a/.pan/drafts/PAN-5754.md b/.pan/drafts/PAN-5754.md new file mode 100644 index 00000000000..348fa173512 --- /dev/null +++ b/.pan/drafts/PAN-5754.md @@ -0,0 +1,501 @@ +# PAN-5754 — Isolate agents from the operator credential + +**Issue:** [PAN-5754](https://github.com/eltmon/overdeck/issues/5754) (follow-up to the PAN-5687 audit, findings F-4 and F-9; tracks #5699, relates to #5696). +**Operator direction (issue comment, 2026-12-03):** use the harness sandbox and per-agent tokens, not a separate uid. Hooks and the CLI inside an agent use the agent's per-agent token, never `~/.overdeck/internal-token`. Claude Code agents get deny-read on the operator credential files and deny-write on the terminal-backend socket directories. Every other harness gets the closest equivalent its sandbox offers; where a harness has no sandbox, the docs and `pan doctor` say so. Operator conversations keep the operator credential. Plan and implement it as one issue. + +## Summary + +Today every managed agent runs as the operator's user and can act as the operator on the dashboard in one command. It can `cat ~/.overdeck/internal-token`, or `curl -X POST http://127.0.0.1:3011/api/dashboard/session` to mint a root session cookie (a loopback caller always mints), or drive another agent's pane through the Herdr or tmux socket. This plan closes those paths for pipeline agents: + +1. Isolated agents authenticate to the dashboard only with their own agent token, from hooks and from the CLI. +2. Claude Code agents run every Bash command inside Claude Code's OS sandbox, under an Overdeck-generated policy. The policy hides the operator's secret files, masks the terminal-backend socket directories, limits writes, and blocks the files Claude Code or Overdeck later execute outside the sandbox. +3. The dashboard stops treating connections from an isolated agent's process tree as a trusted local caller, and stops trusting uncredentialed Traefik-forwarded requests while isolation is on. +4. CLI verbs that need the operator's rights or a terminal socket run as dashboard self jobs, bound to the calling agent's identity and role. +5. Codex gets the closest equivalent (its write sandbox). Every harness without a sandbox is named in the docs and in `pan doctor`. + +## Glossary + +- **Operator credential.** The dashboard root secret `~/.overdeck/internal-token` (`src/lib/internal-token.ts`), the session cookie derived from it, and the Overdeck-held secrets that mint or impersonate dashboard access. The full list is the **operator secret set** in D-8. +- **Agent token.** A managed agent's or conversation's own `odk_<64 hex>` access token (PAN-4927, `src/lib/mcp/agent-token.ts`). Its scopes come from `AGENT_TOKEN_SCOPES` and never include `admin`. +- **Token role.** The `AgentTokenRole` an owner's token carries: `work`, `worker`, `plan`, `strike`, `sequencer`, `knowledge`, `flywheel`, `review`, `test`, `ship`, or `conversation` (`agent-token.ts` `AGENT_TOKEN_SCOPES`; conversations get theirs from `conversationTokenRole`, `src/lib/mcp/agent-injection.ts`). +- **Isolated agent.** A launch whose token role is neither `conversation` nor `flywheel` (D-1). +- **Isolated context.** A process whose environment has `OVERDECK_AGENT_TOKEN_FILE` set. The launcher sets it only for isolated agents. +- **Isolation policy.** The pure data structure (D-8) that lists the paths an isolated agent may read and write, and the socket directories it may not reach. One policy feeds the Claude Code settings file, the write guard hook and `pan doctor`. +- **Isolation settings file.** The Claude Code settings JSON rendered from the isolation policy and passed with `--settings `. +- **Write guard hook.** `sync-sources/hooks/agent-isolation-guard`, a PreToolUse hook that denies Edit, Write, MultiEdit and NotebookEdit calls outside the policy's writable paths. The sandbox covers Bash only; this hook covers the file tools. +- **Sandbox proxy.** The HTTP and SOCKS proxy Claude Code runs for sandboxed commands. On Linux a sandboxed command has its own network namespace and reaches the network only through it. +- **Isolated process tree.** Every process descended from an isolated agent's launcher root pid, recorded in the root registry (D-10). +- **Trusted local caller.** Rule 4 of the remote request gate: `isTrustedLocalCaller` in `src/dashboard/server/routes/dashboard-auth.ts`. A trusted local caller passes the gate with no credential and mints the root session. +- **Agent socket.** A new Unix socket, `/agent-api/dashboard.sock`. The dashboard serves its normal HTTP app on it, and a request on it is never a trusted local caller (D-6). +- **Self job / self route.** A `pan` verb the dashboard runs for the calling agent with its own rights, in the agent's workspace and with the agent's identity variables (`src/dashboard/server/services/self-jobs.ts`, closed verb table in `services/self-job-argv.ts`). +- **Forwarded verb.** A `pan` verb that an isolated-context CLI sends to `POST /api/self/cli` instead of running locally (D-7). + +## Verified facts (probes run during planning, 2026-12-03) + +All probes ran Claude Code 2.1.335 on this Linux host (bubblewrap 0.9.0), in scratch directories, with `--settings `. `socat` is **not installed** on this host, so the probes put a copy from `apt-get download socat` on `PATH` for the probe process only. Every row below is an observed result. + +| # | Setting under test | Observed | +|---|---|---| +| P1 | `sandbox.filesystem.denyRead` on a directory | `cat` and Python `open()` get `ENOENT`: the directory is masked | +| P2 | `denyWrite` on a path inside an `allowWrite` path | `Read-only file system`: deny inside allow holds | +| P3 | Default write policy | Writes outside the cwd and `$TMPDIR` fail (`Read-only file system`) | +| P4 | Default Unix sockets | Every `connect()` fails `EPERM`: the Herdr socket, a test socket, `/var/run/docker.sock` | +| P5 | `sandbox.network.allowUnixSockets: [path]` on Linux | No effect: still `EPERM` | +| P6 | `allowAllUnixSockets: true` + `denyWrite` on the socket's directory | `connect()` **succeeds**. Deny-write does not stop a socket connect | +| P7 | `allowAllUnixSockets: true` + `denyRead` on the socket's directory (or file) | `ENOENT` (directory) or `ECONNREFUSED` (file masked with `/dev/null`): blocked | +| P8 | `allowRead` on a subdirectory of a `denyRead` directory | The subdirectory is readable; its siblings stay hidden | +| P9 | Direct TCP to `127.0.0.1:3011` from the sandbox | Fails: default `NO_PROXY` sends it direct, and the namespace has no route | +| P10 | `curl --noproxy '' --proxy "$HTTP_PROXY" http://127.0.0.1:3011/api/health` | **HTTP 200**: the sandbox proxy forwards to host loopback | +| P11 | `deniedDomains: ["127.0.0.1","localhost","*.localhost","::1"]` | Refused, including `127.0.0.1.nip.io` ("resolved to a deny-listed address") and `127.1` | +| P12 | `deniedDomains` with CIDR (`127.0.0.0/8`, `172.16.0.0/12`, …) | **Ignored**: `127.0.0.1`, `172.17.0.1:3011`, `172.31.0.1:80` (Traefik via a bridge gateway) and the LAN address all answered | +| P13 | Process view | 5 processes visible: the sandbox has its own PID namespace | +| P14 | Node `fetch` to the internet | `ENOTFOUND`; with `NODE_USE_ENV_PROXY=1` (Node 22.22) it returns 200 and prints an `EnvHttpProxyAgent is experimental` warning | +| P15 | git in a worktree with `allowWrite: []`, `denyWrite: [/hooks, /config]` | `git commit` works; `.git/hooks` write fails; `git config --local` fails (`could not lock config file`) | +| P16 | `git ls-remote` over https and ssh, `gh api` | All work through the proxy | +| P17 | `permissions.deny` with `Read(/abs/path)` | Does **not** match: a single leading `/` is relative to the settings file | +| P18 | `permissions.deny` with `Read(//abs/path)` and `Edit(//abs/dir/**)` | Blocks the Read and Write tools in `bypassPermissions` mode, **and** when a PreToolUse hook answers `allow` | +| P19 | A PreToolUse hook answering `deny` for `Write|Edit` | Blocks the Write tool in `bypassPermissions` mode | +| P20 | Sandbox `denyRead` vs the Read tool | The Read tool still reads a sandbox-`denyRead` file: the file tools need their own rules | +| P21 | A project `.claude/settings.local.json` adding `allowRead`, `excludedCommands: ["cat"]`, `allowAllUnixSockets` | None of them widened the `--settings` sandbox | +| P22 | `sandbox.network.allowedDomains: ["*"]` in `default` permission mode | Internet hosts reachable with no prompt | +| P23 | Codex 0.173 `codex sandbox -c sandbox_mode=workspace-write` | Reads the secret file; HOME write blocked; cwd write allowed; reaches `127.0.0.1:3011` directly | +| P24 | The composed D-8 profile (`allowAllUnixSockets`, `allowedDomains: ["*"]`; `denyRead` on a sockets dir, the Herdr sessions dir, `/tmp/tmux-`, `/run/user/`, `/tmp/.X11-unix`, `docker.sock`) | Internet and git over https work. A socket in a non-masked directory (the agent-socket stand-in) connects. The PTY-style socket, Herdr, D-Bus (`/run/user//bus`) and Docker are all blocked. `/tmp/.X11-unix` lists empty. Masking `XDG_RUNTIME_DIR` does not break Claude Code's own proxy bridge (its temp dir is `/tmp/claude-`) | + +Docs facts (code.claude.com, read 2026-12-03): hooks, stdio MCP servers and the status line run **outside** the sandbox. Without bubblewrap or socat, Claude Code runs commands **unsandboxed** unless `sandbox.failIfUnavailable: true`. Settings arrays merge across scopes, and a deny at any scope wins. + +Harness sandbox matrix, from the installed binaries' `--help` (2026-12-03): + +| Harness | Sandbox offered | Class | +|---|---|---| +| claude-code | OS sandbox (bubblewrap/Seatbelt), read deny, write allowlist, socket block, network namespace | `os-sandbox` | +| codex 0.173 | `workspace-write` OS sandbox (writes only); `--permission-profile` exists | `write-sandbox` | +| muse | Own OS sandbox, on by default (`muse sandbox`, `--permission-profile`) | `harness-default` | +| grok, opencode | Tool permission rules only (`--deny`, permission config) | `none` | +| pi, ohmypi (omp), kimi-code, prime-agent, antigravity, acp | None | `none` | + +## Threat model + +**Claim.** An isolated agent whose harness is Claude Code with a working sandbox cannot, from any tool: +1. read the operator secret set or another owner's agent token; +2. get a dashboard credential with `admin` scope or a root session, whether by an uncredentialed loopback request, the session mint, or the managed Traefik; +3. connect to the Herdr, tmux, PTY-supervisor or ACP-host sockets, so it cannot type into another pane; +4. write the files that Claude Code or Overdeck later run outside the sandbox with the operator's rights (D-8 lists them). + +**Residual risks** (stated in the docs, `pan doctor` and NonGoals; each needs its own issue): +- R-1. The verification gate and the post-merge deploy run workspace code (`npm run …`) outside any sandbox. An agent that edits `package.json` scripts reaches the operator's rights there. +- R-2. A harness with no sandbox (class `none`) can still read the secret files. It can also reach the dashboard as a trusted local caller by detaching from its process tree (`setsid`). For those harnesses the token change alone holds. +- R-3. `agents.isolation.allow_docker: true` gives the agent the Docker socket, which is root-equivalent. +- R-4. Isolated agents can still write `~/.overdeck/overdeck.db` and other non-secret Overdeck state (pipeline integrity, not the credential). +- R-5. Non-Bash tools that run outside the sandbox: an operator- or project-configured MCP server (for example Playwright) does whatever the agent asks of it. +- R-6. On macOS the peer rule (D-10) is off, and `pan doctor` says so. +- R-7. Other harness credentials the agent needs, such as `~/.claude/.credentials.json` and the `gh` token, stay readable. +- R-8. `~/.overdeck/config.yaml` stays readable, because the CLI reads it on every call. Audit F-5 notes it holds provider API keys and tracker tokens. +- R-9. Per-agent files under `~/.overdeck/agents//` (the PTY supervisor token, delivered `secrets/`) of *other* agents stay readable. An agent could forge another agent's lifecycle events or read its delivered secrets (lateral, not the operator credential). + +## Decisions + +- **D-1 Who is isolated.** An isolated agent is a launch whose token role is not `conversation` and not `flywheel`. Operator conversations (token role `conversation`) and the Flywheel (token role `flywheel`, whether an agent or the Flywheel conversation) keep the operator credential and get no sandbox. Lane and worker conversations (`laneRole !== null` → token role `worker`) are isolated. `isIsolatedTokenRole(role)` in `src/lib/agent-isolation/config.ts` is the one predicate. +- **D-2 Master switch.** `agents.isolation.enabled` (global `config.yaml` only, default `true`, secure by default). `false` restores today's behaviour for every launch. `.pan.yaml` cannot set it. Today `stripProjectSecurity` (`src/lib/config-yaml/load.ts`) does **not** strip `agents`, and an agent can commit a `.pan.yaml`, so WI-1 adds `agents.isolation` to the stripped keys. +- **D-3 Credential selection.** In an isolated context, hooks and the CLI read only `OVERDECK_AGENT_TOKEN_FILE` and send `Authorization: Bearer `. They never call `getInternalToken`, `ensureInternalToken` or read the internal-token file, and never fall back to them. The launcher unsets `OVERDECK_INTERNAL_TOKEN` for isolated launches (a long-lived Herdr or tmux server may carry a stale one, PAN-4628). +- **D-4 Token location.** Agent tokens move from `/mcp-token` to `/agent-tokens/agent//mcp-token` and `/agent-tokens/conversation//mcp-token`. The sandbox then denies `agent-tokens/` and re-allows the owner's own directory (P8). A per-file list would go stale as other agents launch. Revoke removes both the new file and any legacy `/mcp-token`. +- **D-5 Mint for isolation.** An isolated launch mints its token with `ensureAgentMcpToken` whatever `overdeckMcpEnabledFor(harness)` says. If the mint fails, the launch fails with an error naming the agent (fail closed). The MCP injection keeps its own fail-open behaviour. +- **D-6 CLI transport: the agent socket.** In the sandbox, loopback TCP needs the proxy and a future Claude Code could block it, while `allowAllUnixSockets` is documented. So the dashboard listens on `/agent-api/dashboard.sock` (directory 0700, socket 0600) and hands each connection to the HTTP server with the existing `deliverHttpSocket` (`src/dashboard/server/channel-listener.ts`). A Unix-socket request has no peer address, so `localPeerKind` returns `null` and only a credential passes the gate. The isolated CLI connects with `node:http` `socketPath`. It falls back to TCP only when the socket fails with `ENOENT`, `ECONNREFUSED` or `EPERM`, which is the Codex case. It never falls back to the internal token. +- **D-7 Forwarded verbs.** Verbs that need `admin` routes or terminal sockets run as self jobs. One route, `POST /api/self/cli` with body `{ "argv": string[] }`, matches argv against a closed table of forwarded verbs. Each row declares: the argv prefix, the token roles allowed, which positional (if any) is the issue (it must equal the caller's issue, case-insensitive), and the allowed flags. The flags are exactly the verb's commander options, minus any flag that selects another agent, issue, session, model or harness, or that forces (`--agent`, `--issue`, `--session`, `--model`, `--harness`, `--force`, `--yes` and any flag whose name ends in `-agent` or `-issue`). The server builds argv only through the existing `buildSelfJobArgv` piece types. The isolated CLI forwards a verb that matches a row, prints the job's stdout and stderr, and exits with the job's exit code. A row may also declare a **text tail**: trailing free-text positionals (a message), passed as one `rest` piece after `--`, so spaces and any text survive. A `ref` piece cannot carry spaces (`SELF_JOB_REF_PATTERN`). A row may declare **stdin**: the body's `stdin` string (at most 1 MiB) is written to the job's stdin, for `worker report` and `lane report`. **Path and issue flags.** A flag whose value the verb reads as a file (`--file`, `--brief`, any `--*-file`, `--path`, `--from`) is excluded unless the row marks it `workspacePath`. Then the server resolves it with `realpath` and requires it to lie inside the caller's workspace and outside the D-8 read-deny set; anything else gets 400 `path-outside-workspace`. A self job runs outside the sandbox, so a forwarded file flag would otherwise read operator secrets (critique round 1). `worker report` takes its report only on stdin. A row may name an **issue flag** (`issueFlag: 'issue'`): a supplied value must equal the caller's issue, the server strips it and injects `--issue=`. That is how `worker run`, which requires `--issue`, is forwarded. **Long and large jobs.** Self-cli jobs keep their whole stdout and stderr up to `SELF_JOB_MAX_BUFFER` (4 MiB), not the 16 KiB tail. A row marked `longRunning` gets a job timeout of `SELF_CLI_LONG_JOB_TIMEOUT_MS` (24 h) instead of 15 min. The CLI forwarder follows `next` wait chunks until the job ends. If the job is gone (404 `unknown-job`, for example after a dashboard restart), it exits 75 with `forwarded job lost (dashboard restarted?); re-run the command`. A verb that matches no row runs locally with the agent token. +- **D-8 The isolation policy (Claude Code).** + - **Read deny (sandbox `denyRead` + `Read(//…)` deny rules).** Inside ``: `internal-token`, `access-tokens.json`, `account.json`, `machine-key.json`, `machine-links.json`, `ssh-machines.json`, `credentials/`, `github-app/`, `cliproxy/`, `kimi-cliproxy-home/`, `secrets/`, `vault/`, `certs/`, `browser-profiles/` (browser profiles can hold a signed-in dashboard session cookie) and `agent-tokens/`, with `allowRead` for the owner's own token directory. + - **Socket masks (sandbox `denyRead` + `denyWrite`).** The Herdr sessions directory (`dirname(dirname(herdrSocketPath()))`), the tmux socket directory for the operator's uid (`$TMUX_TMPDIR` or `/tmp`, then `tmux-`), `/sockets`, `$XDG_RUNTIME_DIR` (or `/run/user/`), `/tmp/.X11-unix`, and `/var/run/docker.sock` plus `/run/docker.sock` unless `allow_docker`. With `allowAllUnixSockets: true` these masks are what blocks the sockets (P6, P7). The launcher creates each masked directory that is missing (`mkdir -p`, mode 0700) before launch, so a server that starts later still lands under the mask. + - **Write allow (sandbox `allowWrite`).** The default cwd and `$TMPDIR`. Also `/tmp`, the git common directory of the workspace and of each child repo in a polyrepo workspace (`git rev-parse --git-common-dir`), inside `` **only** `overdeck.db`, `panopticon.db` and `cache.db` with their `-wal`/`-shm` files, `logs/`, `tmp/` and `verification-workers/admission/` (an allowlist: every other entry in ``, classified or not, stays read-only; mutating verbs are forwarded, D-7), the package caches that exist at launch (`~/.npm`, `~/.bun`, `~/.cache`, `~/.local/share/pnpm`, `~/.yarn`, `~/.gradle`, `~/.m2`, `~/.cargo`, `~/go`, `~/.pub-cache`), and `agents.isolation.allow_write`. + - **Write deny (sandbox `denyWrite` + write guard hook + `Edit(//…)` deny rules).** In the workspace: `.git` (the file), `.claude/` and `.mcp.json`. For each git common dir: `hooks/` and `config`. `` needs no deny list beyond the read-deny set, because only the allowlisted entries are writable. `agent-api/` must stay out of the allowlist: an agent that could write it could unlink and rebind the socket and capture other agents' tokens. In the caches: `~/.bun/bin`, `~/.cargo/bin`, `~/go/bin`, `~/.npm/_npx` and `~/.cache/ms-playwright`, because MCP servers and browsers run from them outside the sandbox. Writes anywhere else in the home directory (rc files, `~/.claude`, `~/.config`, `~/.local/bin`) fall outside the allowlist and fail. + - **Sandbox switches.** `enabled: true`, `failIfUnavailable: true` (D-12), `allowUnsandboxedCommands: false` (no retry outside the sandbox, which also narrows F-4's auto-approval), `autoAllowBashIfSandboxed: true`, `network.allowAllUnixSockets: true`, `network.allowedDomains: ["*"]` (no network prompt in any permission mode, P22). +- **D-9 Socket wording.** The issue says "deny-write on the terminal-backend socket directories". P6 shows deny-write does not stop `connect()`, so the policy applies both `denyRead` (which blocks) and `denyWrite` (as worded) to those directories. This deviation is recorded in `autoDecisions`. +- **D-10 Peer rule.** The sandbox proxy forwards to host loopback (P10), and CIDR denies do not work (P12), so the network layer cannot keep an agent off the dashboard port. On Linux, the dashboard decides whether a loopback request's TCP connection is owned by a process in an isolated process tree. If it is, `localPeerKind` returns `null` for that request: no trusted local caller, no session mint, and a credential is required. The decision is made once per connection and cached on the socket. It runs only for a loopback peer that sent no credential, and only when the root registry is non-empty. + - **Root registry.** Before it starts the harness, each isolated launcher writes `/isolation/roots/.json` holding `{ "pid": $$, "startTime": }`. That directory is write-denied to the agent (D-8). The dashboard ignores and deletes an entry whose pid is gone or whose start time differs. + - **Lookup.** Read `/proc/net/tcp` and `/proc/net/tcp6` for the row whose local address is the client's address and port and whose remote address is the server's: that gives the inode. Collect the descendants of each live root through `/proc//task//children`. Then test whether any descendant's `/proc//fd` links to `socket:[]`. + - **Other platforms.** When `/proc/net/tcp` is absent (macOS), the rule is off and `pan doctor` warns (R-6). + - **Self-authenticated routes.** The rule does not apply to `POST /api/agents/:id/lifecycle` when the request carries `x-overdeck-pty-token`. The PTY supervisor runs inside the isolated tree, posts there with its own per-session token (not a dashboard credential), and today passes the gate only as an uncredentialed loopback caller. Its handler verifies that token. This exception list, `ISOLATED_PEER_SELF_AUTH_ROUTES` in `isolated-peer.ts`, holds only routes whose handler checks a non-dashboard secret. +- **D-11 Traefik.** A sandboxed process reaches the managed Traefik through the proxy at a bridge gateway (P12), and an in-tree browser reaches it directly. Traefik then forwards with a gateway client address, which `peerIsManagedTraefikForLocalClient` trusts. So while `agents.isolation.enabled` is true, a Traefik-forwarded request without a credential is **not** a trusted local caller. Browsers that already hold the 30-day `overdeck_session` cookie are unaffected. A new browser profile on `overdeck.localhost` signs in through the existing `#overdeck_token=` link or uses `http://localhost:`. The 401 body for that case names both. +- **D-12 Missing sandbox prerequisites: fail closed.** On Linux, an isolated Claude Code launch first checks that `bwrap` and `socat` are on `PATH`. If either is missing, the launch is **refused** before any pane starts, with the error `agent isolation: Claude Code sandbox unavailable (missing: socat). Install with: sudo apt-get install bubblewrap socat, or set agents.isolation.enabled: false to run agents unisolated`. The settings file also sets `failIfUnavailable: true`, so Claude Code itself refuses to run unsandboxed if the check is ever bypassed. `pan doctor` reports the same condition as an **error**. Overdeck never installs system packages. A fail-open launch would leave the credential readable with only a doctor message (critique round 1), so a missing prerequisite stops the launch instead. **Rollout hazard:** this host lacks `socat` today, so the work agent must state in the PR description, and in a `pan tell conv-flywheel` before `pan done`, that `sudo apt-get install socat` is required before this merges. +- **D-13 Codex.** An isolated Codex launch clamps `codex.permissionMode: full-access` to `workspace` (`workspace-write`). Conversations keep the configured mode. Reads of the secret set stay possible (P23); that is checkpoint CP-5. +- **D-14 Other harnesses.** Muse keeps its own default sandbox. Overdeck does not configure it beyond the token change, and the docs and doctor class it `harness-default`. grok, opencode, pi, ohmypi, kimi-code, prime-agent, antigravity and acp are class `none`, and `pan doctor` prints a warn row per configured harness of that class: `: no sandbox — the agent token is used, but the agent can read operator secrets`. +- **D-15 Launcher's own calls.** Commands the launcher script runs after the harness exits (review sub-role `pan tell`, `pan admin agents exited`) are Overdeck code the agent cannot change (`launcher.sh` sits under `agents/`, which is write-denied). They run with `env -u OVERDECK_AGENT_TOKEN_FILE`, so they keep the operator credential. +- **D-16 Hook routes.** Routes that only hooks and in-pane helpers call accept either the internal token or an agent token whose `agentId` equals the route's subject agent. The subject is the path `:id` where the route has one. For the session-keyed hook routes (`user-prompt-submit`, `turn-complete`, `permission-event`, the memory routes), the payload carries only `session_id` (`sync-sources/hooks/user-prompt-submit-hook` lines ~43-45, `stop-hook` ~85-92, `permission-event-hook` ~12-21). There the server resolves the session's owner (the agent or conversation whose recorded Claude session id is `session_id`, through the same lookup the handlers already use, `routes/hooks.ts` lines ~572-585, ~617-627, ~669-681) and compares that owner with the token's `agentId`. A session with no owner is refused for agent tokens (403 `not-self`); the internal token still passes. A mismatch gets 403 `{ "code": "not-self" }`. These routes get the `tell` scope row, which every agent role holds. +- **D-17 Admission queue.** Gate admission records stamp each pid with its PID namespace (`readlink /proc/self/ns/pid`). An owner from another namespace counts as alive until `staleMs`, because a sandboxed gate run sees every outside pid as dead (P13). Today that would steal live slots. +- **D-19 pi extension.** `packages/pi-extension/src/index.ts` reads `/internal-token` and posts heartbeat, work-complete, stuck, plan-checklist, classify-completion, conversation control-ack and specialists auto-complete. With `OVERDECK_AGENT_TOKEN_FILE` set, it sends the agent token instead. Those routes accept a self agent token (D-16). +- **D-18 F-4 narrowing.** The auto-approve hook is unchanged. For isolated Claude Code agents the boundary is the sandbox with `allowUnsandboxedCommands: false`, plus the deny rules, which hold even when the hook answers allow (P18). + +## Requirements + +- **FR-1** `isIsolatedTokenRole` returns true for `work`, `worker`, `plan`, `strike`, `sequencer`, `knowledge`, `review`, `test` and `ship`, and false for `conversation` and `flywheel`. Isolation applies only when `agents.isolation.enabled` is not `false`. +- **FR-2** In an isolated context the CLI and every hook authenticate with the agent token from `OVERDECK_AGENT_TOKEN_FILE`. They never read, create or send the internal token. +- **FR-3** Agent tokens live under `/agent-tokens/{agent,conversation}//mcp-token`. An isolated Claude Code sandbox can read only its own. +- **FR-4** An isolated Claude Code launch passes `--settings `. The file holds the D-8 sandbox, the deny rules and the write guard hook. +- **FR-5** From an isolated Claude Code sandbox, the Herdr, tmux, `~/.overdeck/sockets` and Docker sockets cannot be connected to (Docker only when `allow_docker` is false). +- **FR-6** The dashboard serves its HTTP app on the agent socket. A request there passes the gate only with a credential. +- **FR-7** `POST /api/self/cli` runs a forwarded verb as a self job for an agent token whose role the verb's row allows. It refuses any other issue, any disallowed flag, and any token role the row does not list. +- **FR-8** The hook and self-report routes (heartbeat, the hooks routes, the memory hook routes, the permission request, permission-event) accept an agent token that speaks only for itself (D-16). +- **FR-9** On Linux, a loopback connection owned by an isolated process tree is never a trusted local caller and never mints a session. +- **FR-10** While isolation is enabled, an uncredentialed Traefik-forwarded request is not a trusted local caller. +- **FR-11** Operator conversations and the Flywheel launch exactly as before: no `--settings` isolation file, no agent-token env, and the internal token available. +- **FR-12** An isolated Codex launch never runs `danger-full-access`. +- **FR-13** `pan doctor` reports the isolation state: the switch, the Claude Code sandbox prerequisites, and one row per configured harness class. +- **FR-14** `agents.isolation.{enabled, allow_docker, allow_write}` are parsed and validated (`enabled` and `allow_docker` booleans; `allow_write` absolute or `~`-prefixed paths). +- **FR-15** Gate admission does not reap a live owner from another PID namespace. +- **FR-17** In-pane processes keep working under the peer rule: the PTY supervisor's lifecycle post (own token) passes, and the pi extension authenticates with the agent token. +- **FR-16** The user and developer docs describe the model, the per-harness matrix, the residual risks and the config keys. +- **NFR-1** The peer rule does async file I/O only, runs only for uncredentialed loopback requests, and caches its answer per connection. No `execSync` and no blocking calls in server code. +- **NFR-2** An isolated launch whose token mint fails does not start. +- **NFR-3** No item raises a `scripts/file-size-allowlist.txt` cap. A growing god file gets an extraction instead. +- **NFR-4** New tests never read source files to assert content (the lint gate rejects source-grep tests) and add no `skipIf` or `.only`. + +## Work items + +Each item lands as its own commit with an `Item: ` trailer. File references were verified on `36e20af8c66`; search for the quoted anchor if a line has moved. + +### WI-1 `iso-config` — isolation config and paths (FR-1, FR-14) +- **New** `src/lib/config-yaml/schema-agent-isolation.ts`: `export interface AgentIsolationConfig { enabled?: boolean; allow_docker?: boolean; allow_write?: string[] }`. +- `src/lib/config-yaml/schema.ts`: inside `agents?: {` (anchor `/** RTK Bash output compression configuration */`) add one line, `isolation?: import('./schema-agent-isolation.js').AgentIsolationConfig;`. +- **New** `src/lib/agent-isolation/config.ts`: + - `readAgentIsolationConfig(config = loadYamlConfig().config): { enabled: boolean; allowDocker: boolean; allowWrite: string[] }`, defaulting to `{ enabled: true, allowDocker: false, allowWrite: [] }`, expanding `~`, and dropping relative paths with one warning each. + - `isIsolatedTokenRole(role: AgentTokenRole): boolean`. + - `isAgentIsolationActive(role)`, which is the config switch AND the role check. +- **New** `src/lib/agent-isolation/paths.ts` (no imports beyond `node:path` and `../paths.js`): `agentTokensDir()`, `agentTokenDir(kind, id)`, `isolationDir()`, `isolationOwnerDir(kind, id)`, `isolationRootsDir()`, `agentApiSocketPath()` (`/agent-api/dashboard.sock`), and the env var names `OVERDECK_AGENT_TOKEN_FILE`, `OVERDECK_DASHBOARD_SOCKET`, `OVERDECK_ISOLATED`. +- `src/lib/config-yaml/load.ts` `stripProjectSecurity` (anchor `const { security: _security, harnesses: _harnesses, computer_use: _computerUse, ...rest } = config;`): also drop `agents.isolation`, keeping the other `agents` keys (`caveman`, `rtk`). +- Tests: `src/lib/agent-isolation/__tests__/config.test.ts` covers each role, the switch off, `~` expansion, a relative path being dropped, and `stripProjectSecurity` removing `agents.isolation` while keeping `agents.rtk`. + +### WI-2 `token-location` — move agent tokens and decouple the mint (FR-3, NFR-2) +- `src/lib/mcp/agent-token.ts`: `agentMcpTokenPath(dir)` (anchor `export function agentMcpTokenPath`) becomes `agentMcpTokenPathFor(owner: { agentId; agentKind })`, which returns `agentTokenDir(kind, normalizedId)/mcp-token`. `ensureAgentMcpToken` writes there, creating the directory 0700. `revokeAgentMcpTokens` unlinks the new path and also the legacy `/mcp-token` when `dir` is known. +- `src/lib/mcp/agent-injection.ts`: `mintOverdeckTokenFile` uses the new path. The written `overdeck-mcp.json` keeps its location. +- **New** export `ensureIsolationToken(owner)` in `agent-token.ts`. It calls `ensureAgentMcpToken` without the `overdeckMcpEnabledFor` gate and rethrows any failure as `Error('agent isolation: token mint failed for : ')`. +- Tests: extend `tests/unit/lib/mcp/agent-token.test.ts` for the new path, legacy unlink, and `ensureIsolationToken` throwing. + +### WI-3 `iso-policy` — the pure isolation policy (FR-4, FR-5) — requiresInspection +- **New** `src/lib/agent-isolation/policy.ts`: + - `buildIsolationPolicy(input: IsolationPolicyInput): IsolationPolicy`, pure. The input is `{ overdeckHome, homeDir, workspace, gitCommonDirs, owner: { kind, id }, uid, herdrSessionsDir, tmuxSocketDir, xdgRuntimeDir, allowDocker, extraAllowWrite, existingCacheDirs }`. + - The output is `{ denyRead, allowRead, allowWrite, denyWrite, maskedSocketDirs, mkdirBeforeLaunch }`: arrays of absolute paths exactly as D-8 lists them. + - `serializePolicy(policy)` returns the JSON the guard hook reads (`{ version: 1, allowWrite, denyWrite }`). +- **New** `src/lib/agent-isolation/policy-input.ts`: `resolveIsolationPolicyInput(owner, workspace)` gathers the real values asynchronously (`execFile('git', ['rev-parse','--git-common-dir'])` for the workspace and each child directory holding a `.git` file; `herdrSocketPath()`; `process.getuid()`; `existsSync` checks for caches). +- Tests: `src/lib/agent-isolation/__tests__/policy.test.ts`. Assert every D-8 path class: the internal token is in `denyRead` and `denyWrite`; the own token dir is in `allowRead`; another owner's is covered only by `agent-tokens/`; `.git/hooks` and `.git/config` are in `denyWrite`; docker.sock is masked unless `allowDocker`; `extraAllowWrite` lands in `allowWrite`. + +### WI-4 `claude-settings` — render the isolation settings file (FR-4) +- **New** `src/lib/agent-isolation/claude-settings.ts`: + - `renderIsolationClaudeSettings(policy, guardHookPath, policyFile): object` returns: + ```json + { "sandbox": { "enabled": true, "failIfUnavailable": true, "allowUnsandboxedCommands": false, + "autoAllowBashIfSandboxed": true, + "network": { "allowAllUnixSockets": true, "allowedDomains": ["*"] }, + "filesystem": { "denyRead": [...], "allowRead": [...], "allowWrite": [...], "denyWrite": [...] } }, + "permissions": { "deny": ["Read(//)", "Read(///**)", "Edit(//)", "Edit(///**)"] }, + "hooks": { "PreToolUse": [{ "matcher": "Edit|Write|MultiEdit|NotebookEdit", + "hooks": [{ "type": "command", "command": "OVERDECK_ISOLATION_POLICY= " }] }] } } + ``` + - Permission paths use the `//` absolute form (P17). A directory gets `/**`; a file gets the bare path. + - `writeIsolationFiles(owner, policy)` writes `isolationOwnerDir(kind,id)/claude-settings.json` and `policy.json` (0600, directory 0700, temp file then rename) and returns both paths. +- Tests: `src/lib/agent-isolation/__tests__/claude-settings.test.ts`. Every `denyRead` path appears as a `Read(//…)` rule; no rule starts with a single `/`; the hook command names the policy file. + +### WI-5 `write-guard-hook` — the PreToolUse write guard (FR-4) +- **New** `sync-sources/hooks/agent-isolation-guard` (bash, `set -u`, needs `jq`, mode 0755). It reads the hook JSON from stdin and takes the target from `.tool_input.file_path` (Edit, Write, MultiEdit) or `.tool_input.notebook_path` (NotebookEdit). + - It resolves the target with `realpath -m`, or, when the target exists and is a symlink, with `realpath` so the link's destination is judged. + - It allows when the resolved path is under an `allowWrite` root and under no `denyWrite` root, and prints nothing (exit 0). + - Otherwise it prints `{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"agent isolation: is outside this agent's writable paths"}}`. + - It denies when the policy file is missing or unreadable (fail closed). +- `pan sync` already ships it: `src/lib/sync-hooks.ts` copies every file in `sync-sources/hooks/` to `~/.overdeck/bin/` (`readdirSync`), so there is no list to edit. The settings file names it as `join(BIN_DIR, 'agent-isolation-guard')`. `bin/` is write-denied to isolated agents (D-8), so an agent cannot replace it. +- Tests: `tests/scripts/agent-isolation-guard.test.ts` runs the script with `spawnSync` against a fixture policy. Cases: allowed path; denied path; a symlink in the cwd pointing to a denied file; a missing policy denies. + +### WI-6 `launch-isolation` — launcher wiring (FR-2, FR-4, FR-11, NFR-2) +- **New** `src/lib/agent-isolation/launch.ts`: `prepareAgentIsolation(owner: OverdeckMcpLaunchOwner): Promise<{ isolation?: LaunchIsolation }>`. It returns `{}` when `isAgentIsolationActive(owner.role)` is false. Otherwise it: + 1. for a claude-code launch on Linux, checks `bwrap` and `socat` on `PATH` and throws the D-12 error when either is missing (the check is an injected dependency so tests run without them); + 2. calls `ensureIsolationToken` (throws, so the launch fails, NFR-2); + 2. resolves the policy input and builds the policy; + 3. when the harness's `launchCommandKind` is `claude-code`, writes the settings and policy files; + 4. returns `LaunchIsolation = { settingsFile?: string; env: Record; unsetEnv: string[]; mkdirs: string[]; rootFile: string }`. `env` is `OVERDECK_AGENT_TOKEN_FILE`, `OVERDECK_DASHBOARD_SOCKET` (`agentApiSocketPath()`), `OVERDECK_ISOLATED=1` and `NODE_USE_ENV_PROXY=1`. `unsetEnv` is `['OVERDECK_INTERNAL_TOKEN']`. +- `src/lib/launcher-generator.ts`. Keep the file at or below its `origin/main` count plus its allowlist cap (938); put any helper in `src/lib/agent-isolation/launcher-lines.ts`. + - Add `isolation?: LaunchIsolation` to `LauncherConfig`. + - In `generateLauncherScript`, emit `mkdir -p -m 700 `, the `export` lines, the `unset` line, and the root-registry line from WI-13's `rootRegistrationLauncherLine(rootFile)`, after the env block and before `cd`. + - In `buildCommand`'s conversation branch and in `buildNonConversationCommand`, append ` --settings ` for the claude-code command when `settingsFile` is set. + - In `buildReviewSubRoleCommand`, prefix the post-exit `pan tell` and `pan admin agents exited` lines with `env -u OVERDECK_AGENT_TOKEN_FILE` (D-15). +- Tests: extend `src/lib/__tests__/launcher-generator*.test.ts`. An isolated claude-code launch contains `--settings`, the exports and the `unset`; a launch with `isolation` undefined is byte-identical to today; the review sub-role post-exit lines carry `env -u OVERDECK_AGENT_TOKEN_FILE`. + +### WI-7 `launch-sites-agents` — wire agent launch sites (FR-1, FR-4, FR-11) +Spread `...(await prepareAgentIsolation({...same owner as the MCP call...}))` next to each `prepareClaudeOverdeckMcp` / `prepareCodexOverdeckMcp` call: +- `src/lib/agents/spawn.ts` (anchors `await prepareClaudeOverdeckMcp({ agentId, agentKind: 'agent', role, harness: resolvedHarness` and the codex call above it); +- `src/lib/agents/spawn-prep.ts` (`const overdeckMcp = await prepareClaudeOverdeckMcp(`); +- `src/lib/agents/recovery.ts` (`...(await prepareClaudeOverdeckMcp({ agentId: normalizedId`); +- `src/lib/agents/messaging.ts` (`...(await prepareClaudeOverdeckMcp({ agentId: normalizedId, agentKind: 'agent', role: resumeRole`). + +A thrown isolation error must fail the spawn the same way a missing binary does. Tests: one spawn test per file asserts that the launcher config carries `isolation` for role `work` and no `isolation` for role `flywheel`. + +### WI-8 `launch-sites-planning-conv` — wire planning and conversation launch sites (FR-1, FR-11) +- `src/lib/planning/spawn-planning-session.ts` (`...(await prepareClaudeOverdeckMcp({ agentId: sessionName`) and `src/dashboard/server/routes/misc/planning.ts` (same anchor): role `plan` is isolated. +- `src/lib/overdeck/conversation-runtime.ts` (anchors `? await prepareClaudeOverdeckMcp({ agentId: tokenRow.name` and the codex call): pass `role: conversationTokenRole(tokenRow, role, tmuxSession)`. A plain conversation resolves to `conversation`, so it is not isolated (FR-11); a lane conversation resolves to `worker`, so it is. +- Tests: a conversation launch test asserts that no `--settings` appears for a plain conversation and that it does appear for a lane conversation. + +### WI-9 `agent-socket` — the agent socket listener (FR-6) +- **New** `src/dashboard/server/agent-api-socket.ts`: `installAgentApiSocket(): Promise<() => Promise>`. + - Create the directory 0700 and unlink a stale socket. + - `net.createServer((socket) => { if (!deliverHttpSocket(socket)) socket.destroy(); })`, then `listen(agentApiSocketPath())` and `chmod 0600`. + - Return a closer that closes the server and unlinks the socket. +- `src/dashboard/server/server.ts`: right after `installChannelListener(nodeServer, {` (primary dashboard only), call it and register the closer with the server's shutdown. +- Tests: `src/dashboard/server/__tests__/agent-api-socket.test.ts` drives a real request over the socket against a test server. Without a credential, `GET /api/agents` gets 401; with an agent token it gets 200; the socket file mode is 0600. + +### WI-10 `cli-credential` — CLI credential and transport helper (FR-2) +- **New** `src/lib/dashboard-client/agent-credential.ts`: + - `isIsolatedAgentContext(env = process.env): boolean` (`OVERDECK_AGENT_TOKEN_FILE` set and non-empty). + - `readAgentToken(env)`: reads the file each call; must match `/^odk_[0-9a-f]{64}$/`; throws `AgentCredentialError` otherwise. + - `dashboardAuthHeaders(env)`: `{ authorization: 'Bearer ' }` in an isolated context, else `{ [INTERNAL_TOKEN_HEADER]: ensureInternalToken() }`. + - `dashboardFetch(path, init, env)`: in an isolated context with `OVERDECK_DASHBOARD_SOCKET` set, use `node:http` `request({ socketPath, path, method, headers })` and return a WHATWG `Response`. On `ENOENT`/`ECONNREFUSED`/`EPERM` from the socket, retry once over TCP at `getDashboardApiUrl()`. Otherwise use `fetch(getDashboardApiUrl() + path)`. It always adds `dashboardAuthHeaders` and removes any `x-overdeck-internal-token` header the caller set. +- Tests: `src/lib/dashboard-client/__tests__/agent-credential.test.ts` uses a temp `OVERDECK_HOME` and a real Unix-socket test server. It asserts that an isolated context sends Bearer and never creates `internal-token`, and that a non-isolated context sends the internal header. + +### WI-11 `cli-callers` — route CLI-side dashboard calls through the helper (FR-2) +Replace every `ensureInternalToken()`/`getInternalToken()` header construction on the CLI paths with `dashboardFetch` or `dashboardAuthHeaders`. Files: `src/cli/commands/dashboard-call.ts` (anchor `[INTERNAL_TOKEN_HEADER]: ensureInternalToken()`), `src/lib/agent-runtime.ts`, `src/lib/pipeline-notifier.ts`, `src/lib/cloister/deacon-event-client.ts`, `src/cli/commands/plan.ts`, `src/cli/commands/start.ts`. + +Behaviour outside an isolated context stays identical. `pipeline-notifier.ts` keeps its "skip when no credential" rule, but in an isolated context it posts with the agent token. Tests: extend each module's existing test to cover the isolated context sending Bearer, and confirm that `ensureInternalToken` is not called (spy on the module export). + +### WI-12 `in-pane-callers` — in-pane helpers use the agent token (FR-2) +- `src/lib/caveman/workspace.ts`: the memory hook script it writes (anchors near `internal-token` at lines ~183-223) reads `$OVERDECK_AGENT_TOKEN_FILE` when set and sends `Authorization: Bearer`, else today's internal token. +- `src/lib/codex/prompt-memory.ts`: use `dashboardAuthHeaders()`. +- `src/lib/channels/overdeck-bridge.ts`: the permission-request post uses `dashboardAuthHeaders()`. +- Tests: extend `src/lib/caveman/__tests__/workspace.test.ts` (asserting on the generated script text is fine: it is output, not source) and `src/lib/codex/__tests__/prompt-memory.test.ts`. + +### WI-13 `hooks-token` — hook scripts use the agent token (FR-2) +- `sync-sources/hooks/pan-hook-lib.sh` (anchor `_pan_token_path="${OVERDECK_HOME:-$HOME/.overdeck}/internal-token"`): when `OVERDECK_AGENT_TOKEN_FILE` is set, read it into `PAN_AGENT_TOKEN`, set an auth header variable to `Authorization: Bearer $PAN_AGENT_TOKEN`, and do not read `internal-token`. Otherwise keep today's behaviour. Both curl call sites (lines ~366 and ~417) use the header variable. +- `sync-sources/hooks/session-start-hook` (anchor `TOKEN_PATH="${OVERDECK_HOME:-$HOME/.overdeck}/internal-token"`), `stop-hook` (same anchor; also add the header to the planning `complete-planning` curl, anchor `/api/issues/$ISSUE_ID/complete-planning`), `user-prompt-submit-hook` (same anchor), and `permission-event-hook` get the same rule. +- Tests: `tests/scripts/hooks-agent-token.test.ts` runs `pan-hook-lib.sh`'s auth-header function and the session-start hook against a stub dashboard (a local HTTP server) with `OVERDECK_AGENT_TOKEN_FILE` set. It asserts the Bearer header, and that no `internal-token` read happens: give it an `OVERDECK_HOME` with no internal-token file and assert no file appears. + +### WI-14 `self-auth-routes` — hook and self-report routes accept a self agent token (FR-8) +- **New** `src/dashboard/server/routes/self-or-internal.ts`: `authorizeInternalOrSelfAgent(request, subjectAgentId: string | null): { ok: true } | { ok: false; response }`. It passes the internal token (header or Bearer). It passes an agent token (`resolveRequestCredential` → `kind: 'token'` with `agentId`) whose normalized `agentId` equals the normalized subject. Anything else gets 401, or 403 `{ "code": "not-self" }` for a token speaking for someone else. +- Use it in: + - `routes/agents/shared.ts` `validateAgentRuntimeEventAuth` (anchor `const provided = getHeaderFromMap(request.headers as Record, INTERNAL_TOKEN_HEADER);`). It gains a `subjectAgentId` parameter, and every caller in `routes/agents/runtime-events.ts` (heartbeat line ~117, work-complete ~138, stuck ~155, plan-checklist ~191) passes the route `:id`; + - `routes/hooks.ts` at the five `if (!hasDashboardInternalToken(request)) return jsonResponse({ error: 'unauthorized' }, { status: 401 });` sites (lines ~429, ~454, ~495, ~654, ~697; subject = the body's agent id field each handler already parses); + - `routes/agents/permissions.ts` internal permission request (lines ~291-303; subject = `:id`); + - `routes/hooks.ts` `POST /api/hooks/permission-event` (subject = body agent id). +- `src/dashboard/server/routes/issues.ts` complete-planning (anchor `'/api/issues/:id/complete-planning',`, line ~360; reached from the planning stop-hook). The WI-15 `operate` row lets agent tokens through the gate, so the handler must keep other credentials from widening: + - an agent token passes only when its role is `plan` and its agent's issue equals `:id` (`selfCallerFromCredential` resolves the issue); + - any other credential must hold `admin` (`credentialScopes(credential).includes('admin')`), so a phone, machine or connector token with `operate` gets 403; + - an uncredentialed trusted local caller passes as today. +- Tests: one route test per file covers the internal token, the own agent token, another agent's token (403 `not-self`), a token for agent A carrying agent B's `session_id` (403 `not-self`), a `session_id` with no owner (403 for an agent token), and no credential. + +### WI-15 `route-scope-rows` — route-scope rows for agent-callable routes (FR-8) +`src/dashboard/server/route-scopes.ts`: add `tell` rows for `POST /api/agents/:id/heartbeat`, `POST /api/hooks/turn-complete`, `POST /api/hooks/user-prompt-submit`, `POST /api/hooks/permission-event`, `POST /api/memory/inject`, `POST /api/memory/session/start`, `POST /api/memory/turn` and `POST /api/internal/agents/:id/permissions/request`. Add `operate` for `POST /api/issues/:id/complete-planning`, `read:state` for `GET /api/agents/:id/runtime`, `read:conversations` for `GET /api/agents/:id/conversation`, and `read:state` for `POST /api/self/cli` (the route enforces the role itself). For the pi extension (D-19), add `tell` rows for `POST /api/agents/:id/work-complete`, `/stuck`, `/plan-checklist`, `/classify-completion`, `POST /api/conversations/:name/control-ack` and `POST /api/specialists/:name/auto-complete`. This item is the only one that edits `route-scopes.ts`. Add the `POST /api/self/cli` row to the no-loss matrix, `tests/unit/lib/overdeck/no-loss-matrix.ts` (memory: a new HTTP route without one fails CI). Tests: extend the route-scopes table test to assert each row. + +### WI-16 `self-cli-route` — the forwarded-verb route and CLI forwarder (FR-7) — requiresInspection +- **New** `src/dashboard/server/services/self-cli-verbs/index.ts`: `SELF_CLI_VERBS: readonly SelfCliVerb[]`, concatenated from the family files `core.ts`, `messaging.ts`, `planning.ts`, `review.ts`, `swarm.ts` and `misc.ts` (each `export const VERBS: SelfCliVerb[] = []` at first). + - `SelfCliVerb = { prefix: string[]; roles: AgentTokenRole[]; issuePositional?: number; positionals: number; flags: Record; stdin?: boolean }`. + - `matchSelfCliVerb(argv)` returns the longest-prefix row or null. +- **New** `src/dashboard/server/services/self-cli-argv.ts`: `buildSelfCliArgv(row, argv, caller)` validates every token against the row (flags only from `row.flags`; values as `{flag,value}` pieces; positionals as `{ref}` pieces; the issue positional must equal `caller.issueId` case-insensitively, else `SelfJobArgError('issue-mismatch')`). It returns argv built only through `buildSelfJobArgv`'s piece types (extend `self-job-argv.ts` with an exported `buildArgvFromPieces(prefix, pieces)` if needed, keeping the H-6 ref rule). +- Argument kinds (D-7): a row may set `textTail: true`, meaning trailing positionals after the fixed ones are joined into one `rest` piece placed after `--`; and `stdin: true`, meaning the body's `stdin` string (at most 1 MiB) goes to the job's stdin. Extend `SelfJobRunInput` in `services/self-jobs.ts` with `stdin?: string`; when it is set, the runner writes it to the child's stdin and closes it (keep the injected-runner design). +- **New** `src/dashboard/server/routes/self-cli.ts`: `POST /api/self/cli` with body `{ argv: string[], stdin?: string }` (argv at most 64 elements, each at most 8 KiB). + - Caller from `selfCallerFromCredential`. A role not in the row gets 403 `{ code: "role-not-allowed" }`; no row gets 404 `{ code: "verb-not-forwarded" }`; a validation error gets 400. + - It starts the job with `selfJobs` (extend `SelfJobRunInput` to take a prebuilt argv) and answers `selfJobAnswer`. + - Register it with the existing self routes. +- Rows may set `issueFlag`, `workspacePath` flags and `longRunning` (D-7). In `services/self-jobs.ts`, a self-cli job keeps full stdout/stderr up to `SELF_JOB_MAX_BUFFER` and uses `SELF_CLI_LONG_JOB_TIMEOUT_MS` when its row is `longRunning`. The timeout is injected, so tests use fake timers. +- **New** `src/cli/isolated-forward.ts`: `maybeForwardIsolatedVerb(argv = process.argv.slice(2)): Promise`. It returns null outside an isolated context. Otherwise it posts to `/api/self/cli` through `dashboardFetch`, follows `next` with `GET /api/self/jobs/:id/wait` until done, writes stdout and stderr, and returns the exit code. On 404 `verb-not-forwarded` it returns null so the verb runs locally. +- `src/cli/index.ts`: before `await runCliWithTelemetry(() => program.parseAsync(`, add `const forwarded = await maybeForwardIsolatedVerb(); if (forwarded !== null) process.exit(forwarded);`. +- Rows in `core.ts` (this item): `task claim|done|block|unblock|next|cancel`, `memory edit|retire|pin|unpin` (every isolated role), `done`, `handoff`, `worker report`, `lane report`, `memory add|search`. Roles: every isolated role for `memory`; `work`, `strike`, `knowledge` for `done`; `work`, `strike` for `task`; `work` for `handoff`; `worker` for `worker report` and `lane report` (both `stdin: true`). A `worker` token never gets `done` or `task` (`roles/worker.md`: "Never run `pan done`, `pan review`, or `pan task done`"). +- Tests: `src/dashboard/server/__tests__/self-cli-route.test.ts` (role refusal, issue mismatch, disallowed flag, unknown verb 404, a valid `task done` job, a `worker report` with stdin reaching the job, `worker report --file ~/.overdeck/internal-token` refused with 400 `path-outside-workspace`, a stdout over 16 KiB returned whole, and a `longRunning` job still running after 15 minutes of fake time), and `src/cli/__tests__/isolated-forward.test.ts` (forwards when isolated, returns null otherwise, honours the exit code). + +### WI-17 `forward-messaging` — forward tell, ask, sync-main (FR-7) +Add rows in `self-cli-verbs/messaging.ts`: `tell` (all isolated roles; positional 0 is the target and not the issue; `textTail: true` for the message), `ask` (`work`, `strike`; `textTail: true`), `sync-main` (`work`, `strike`; issue positional 0), `review request` (`work`, `strike`; issue positional 0). Test: forwarding `['tell','conv-flywheel','three word message']` runs `pan tell conv-flywheel -- three word message`, and the message arrives intact. Flags follow the D-7 rule, read from each verb's commander definition (`src/cli/index.ts` / its command module). Tests: row-level cases in `self-cli-route.test.ts`. + +### WI-18 `forward-planning-review` — forward plan finalize and the review/test verbs (FR-7) +- `self-cli-verbs/planning.ts`: `plan finalize` and `plan done` (role `plan`; issue positional 0 when given; with no positional the server injects the caller's issue). +- `self-cli-verbs/review.ts`: `admin specialists done` (roles `review`, `test`), `review spawn-reviewer` (role `review`) and `admin seed-uat-fixtures` (role `test`). The issue positional must match. +- Tests: rows reject a `work` token for `admin specialists done` (a work agent must never record its own review verdict). + +### WI-19 `forward-swarm-misc` — forward swarm, worker, backlog, knowledge (FR-7) +- `self-cli-verbs/swarm.ts`: `swarm dispatch|merge|status|wait|resume|recover|freeze`, `foreman` and `spawn` (role `work`; issue positional when the subcommand takes one), and `workspace add-repo` (role `work`, issue positional; the cloister prompt builders tell polyrepo work agents to run it, and it writes another repository's git dir, which the sandbox denies). +- `self-cli-verbs/misc.ts`: `worker run` (roles `work`, `plan`; `issueFlag: 'issue'`; `--brief` marked `workspacePath`; `--prompt` text allowed; `longRunning`), `worker wait` (roles `work`, `plan`; `longRunning`), `worker stop` (roles `work`, `plan`). Test: `pan worker run --issue --prompt 'x y'` forwards with the server-injected issue; `--issue ` gets 400. `backlog write-sequence` (role `sequencer`), `knowledge` (role `knowledge`). +- Tests: row cases. + +### WI-20 `peer-rule` — isolated process trees are not trusted local callers (FR-9, NFR-1) — requiresInspection +- **New** `src/lib/agent-isolation/roots.ts`: + - `rootRegistrationLauncherLine(rootFile)` returns the bash line that writes `{"pid":$$,"startTime":}` to `rootFile` (temp file, then `mv`), guarded by `[ -r /proc/$$/stat ]`. + - `readLiveRoots(deps)` lists the root files and drops and deletes stale entries. +- **New** `src/dashboard/server/isolated-peer.ts`: + - `resolveIsolatedPeer(socket: { remoteAddress, remotePort, localAddress, localPort }, deps = realProcFs): Promise`, implementing D-10 with `fs/promises` only. + - A `WeakMap>` caches per socket. + - Returns false immediately when there are no live roots or `/proc/net/tcp` is absent. +- `src/dashboard/server/routes/dashboard-auth.ts`. Keep the file at or below its count; move logic into `isolated-peer.ts`. + - `ensurePeerIdentityFresh(request)` (anchor `export function ensurePeerIdentityFresh`) also awaits `resolveIsolatedPeer` for a literal-loopback peer that carries no credential, and stores the result on the request's socket. + - `localPeerKind` (anchor `if (addr === '127.0.0.1' || addr === '::1') return 'loopback';`) returns `null` when the socket is marked isolated. + - `isTrustedLocalNodeRequest` awaits the same resolution: make its callers await an async variant, `isTrustedLocalNodeRequestAsync`, at `routes/workspace-wake.ts:95`. +- `ISOLATED_PEER_SELF_AUTH_ROUTES` (D-10): for `POST /api/agents/:id/lifecycle` carrying `x-overdeck-pty-token`, the rule is skipped and `localPeerKind` answers as today. +- Tests: `src/dashboard/server/__tests__/isolated-peer.test.ts` with an injected fake `/proc` (tcp table, children, fd links). A connection owned by a descendant is isolated; an unrelated pid is not; a stale root is ignored and deleted; no roots means no fs reads. A gate test asserts that a marked socket gets 401 on `POST /api/dashboard/session`, and that a marked socket's `POST /api/agents/x/lifecycle` with `x-overdeck-pty-token` still reaches the handler. + +### WI-21 `traefik-trust` — no uncredentialed Traefik trust under isolation (FR-10) +- `src/dashboard/server/routes/dashboard-auth.ts` `localPeerKind`: when `readAgentIsolationConfig().enabled` is true, the `traefik` branch returns `null` (the cookie path still authenticates through `resolveDashboardCredential`). +- The session mint's 401 for a Traefik-forwarded request answers `{ "error": "sign in: open http://localhost: on this machine, or use a #overdeck_token= link from `pan serve`", "code": "isolation-sign-in" }`. +- Tests: extend the dashboard-auth tests. A Traefik-forwarded uncredentialed mint gets 401 `isolation-sign-in` with isolation on and 200 with it off. + +### WI-22 `admission-pidns` — PID-namespace-aware gate admission (FR-15) +- `src/lib/cloister/quality-gate-admission.ts`: + - Add `pidNs?: string` to the ticket, owner and breaker records written by `publishExclusive` (anchor `await publishExclusive(path, { pid: process.pid, acquiredAt: now() })`), read from `readlinkSync('/proc/self/ns/pid')` once per process (or `undefined` off Linux). + - `ownerIsStale` (anchor `return now - owner.acquiredAt > staleMs || !isProcessAlive(owner.pid)`) and the breaker check treat a record whose `pidNs` differs from ours as alive until `staleMs`. + - Put the helper in a new `quality-gate-admission-pidns.ts` if the file would grow past its count. +- Tests: extend `tests/unit/lib/cloister/quality-gate-admission.test.ts` with injected `isProcessAlive` and `pidNs`. A foreign-namespace owner within `staleMs` is kept; past `staleMs` it is cleared. + +### WI-23 `codex-clamp` — isolated Codex never runs full access (FR-12) +- `src/lib/agents/runtime-command.ts` `getCodexLauncherFields` (anchor `const codexPermMode = codexConfig?.permissionMode ?? 'workspace';`): add a parameter `isolated: boolean`. When it is true and the mode is `full-access`, use `workspace`. Callers pass `isAgentIsolationActive(role)`. Conversations use `src/lib/overdeck/conversation-runtime.ts`'s own path and are unchanged. +- **Implementation checkpoint CP-5:** run `codex sandbox --help` and the Codex config docs for a permission profile that denies reads of given paths. If one exists, add the D-8 read-deny set through it in `initCodexHome`. If not, leave a code comment citing CP-5 and keep the class `write-sandbox`. +- Tests: `getCodexLauncherFields` with `isolated: true` and `full-access` yields `danger-full-access` never; `isolated: false` is unchanged. + +### WI-24 `capability-doctor` — harness isolation class and `pan doctor` (FR-13) +- `packages/contracts/src/harness-capabilities.ts`: add `readonly agentIsolation: 'os-sandbox' | 'write-sandbox' | 'harness-default' | 'none'` to `HarnessCapabilities`, and set it in every capabilities constant per the matrix above. +- **New** `src/cli/commands/doctor-agent-isolation.ts`: `checkAgentIsolation(deps): Promise` (local `CheckResult` re-declaration as `doctor-permission-mode.ts` does). Rows: + - `Agent isolation`: ok, `on`, or warn, `off (agents.isolation.enabled: false)`. + - On Linux with Claude Code configured: `Claude Code sandbox`: ok when `bwrap` and `socat` are on PATH, else **error** naming the missing ones, with the fix `sudo apt-get install bubblewrap socat`. + - `Dashboard peer rule`: warn on non-Linux. + - One row per configured harness of class `write-sandbox`, `harness-default` or `none`, with the D-14 message. + - `Docker access`: warn when `allow_docker` is true. +- `src/cli/commands/doctor.ts`: one line `for (const c of await checkAgentIsolation()) checks.push(c); // PAN-5754` after the `checkClaudeCode()` line. +- Tests: `src/cli/commands/__tests__/doctor-agent-isolation.test.ts` with injected PATH lookups, platform and config. + +### WI-25 `docs` — documentation (FR-16) +- **New** `configuration/agent-isolation.mdx`, and add `"configuration/agent-isolation"` to `docs.json` next to `"configuration/permissions"`. Sections: + - Who is isolated (D-1). + - What an isolated Claude Code agent can and cannot reach (D-8 lists). + - The per-harness table (classes and messages). + - The config keys with defaults. + - Prerequisites (`bubblewrap`, `socat`) and the fail-closed behaviour: a launch without them is refused with the install command. + - Signing in on `overdeck.localhost` (D-11). + - Docker opt-in (R-3). + - Residual risks R-1 to R-9. +- **New** `docs/AGENT-ISOLATION.md` (developer): architecture (policy → settings file, guard hook, agent socket, forwarded verbs table, peer rule, root registry), the probe table, and how to add a forwarded verb row. +- `docs/DASHBOARD-AUTH.md`: the agent socket; the peer rule under "Remote request gate" rule 4; the Traefik change; `POST /api/self/cli` under "`/api/self/*`". +- `docs/SECURITY-AUDIT-2026-11-29.md`: the F-9 and F-4 rows and the F-9 paragraph record "Fixed by PAN-5754 for Claude Code agents", with the residual risks. +- `configuration/harnesses.mdx`: an "Agent isolation" column or subsection with each harness's class. +- `CLAUDE.md`: one Key Invariants line ("Isolated agents (token role not conversation/flywheel) use their agent token only; Claude Code agents run Bash in the sandbox; see docs/AGENT-ISOLATION.md") and a Topic Index row. +- `.overdeck/context/codebase/concerns.md`: update the "Claude Code Auto permission mode filters nothing" entry with the isolation boundary. Leave its `last-verified` line unchanged. +- **New** `changelog.d/pan-5754.md` under `#### New`. +- Verify: `npm run lint:docs`. + +### WI-26 `pi-extension-token` — the pi extension uses the agent token (FR-2, FR-17) +- `packages/pi-extension/src/index.ts`: the token read (anchor `const token = (await readFile(join(overdeckHome, 'internal-token'), 'utf8')).trim()`) first checks `process.env.OVERDECK_AGENT_TOKEN_FILE`. When it is set, the extension reads that file, sends `Authorization: Bearer ` on every dashboard post (`postWithTimeout`, `postJsonWithTimeout`, `postDashboard`), and never reads `internal-token`. Otherwise it behaves as today. +- Tests: extend `packages/pi-extension/src/__tests__/index.test.ts`. Assert the Bearer header with the env var set, and the internal-token header without it. + +### WI-27 `pi-routes-self-auth` — routes the pi extension calls accept a self agent token (FR-8, FR-17) +- `src/dashboard/server/routes/conversations.ts` control-ack (anchor `'/api/conversations/:name/control-ack',`, line ~741). Use `authorizeInternalOrSelfAgent` with subject = `:name` for an agent id, or the conversation's tmux session for a conversation. +- `src/dashboard/server/routes/specialists/legacy-routes.ts` auto-complete (anchor `'/api/specialists/:name/auto-complete',`, line ~601). An agent token passes only with role `review` or `test` and when the body's issue equals the token agent's issue; other credentials keep today's check. +- `routes/agents/runtime-events.ts` classify-completion (line ~173) has no handler auth today. Leave it, but note in `docs/DASHBOARD-AUTH.md` that the WI-15 `tell` row now admits any `tell`-scoped token. +- Tests: one route test per file: own token passes, another agent's token gets 403 `not-self`, and a `work` token on auto-complete gets 403. + +### WI-28 `verb-coverage` — every agent-facing verb is forwarded or known-local (FR-7, H1) +- **New** `src/dashboard/server/__tests__/self-cli-coverage.test.ts`. A data table lists every `pan` verb that isolated roles are told to run, taken from `roles/*.md`, the cloister prompt builders (`src/lib/cloister/*prompt*.ts`) and the agent skills `pan-task`, `pan-done`, `pan-tell`, `pan-worker`, `pan-foreman`, `pan-memory`, `pan-handoff`, `pan-sync-main` and `pan-plan` (`sync-sources/skills//SKILL.md`). Each verb carries its disposition: `forwarded:`, or `local-read`. + - `local-read` is allowed only for read-only verbs: `task show`, `task next`, `show`, `status`, `memory search|show|list|read`, `conv pending|current|list|show|whoami`, `worker list` and `lane` reads. + - For each `forwarded` verb, the test asserts that `matchSelfCliVerb(argv)` finds a row whose `roles` include the listed roles. +- The table is test data, not a scan of source files (NFR-4). + +### WI-29 `launch-sites-runtimes` — isolation at the runtime entry points (FR-1, FR-4, FR-12) +Crash recovery (`src/lib/cloister/service-crash.ts` line ~433, `runtime.spawnAgent({`) and session rotation (`src/lib/cloister/session-rotation.ts` line ~249) launch through the runtime registry, not the WI-7 sites. Each runtime also builds its own launch: the Codex runtime builds its own command without `generateLauncherScript` (`src/lib/runtimes/codex.ts` lines ~674-699); ohmypi, Muse, Kimi and Prime Agent call `generateLauncherScript` from their runtime modules. +- In every runtime `spawnAgent` implementation (`src/lib/runtimes/claude-code.ts`, `codex.ts`, `ohmypi.ts`, `pi.ts`, `muse.ts`, `kimi-code.ts`, `prime-agent.ts`, `acp.ts`), call `prepareAgentIsolation` for the spawn's owner. When the caller already passed an `isolation` value (the WI-7 sites), reuse it and do not mint twice. + - Generator-based runtimes pass it to `generateLauncherScript`. + - The Codex runtime emits the same `export`/`unset`/root-registration lines into its own command and applies the D-13 clamp. +- `src/lib/remote/remote-agents.ts` (Fly VMs) is out of scope. **Checkpoint CP-7:** confirm the Fly VM holds no copy of this host's `internal-token`. If it does, file a follow-up issue and link it from `docs/AGENT-ISOLATION.md`. +- Tests: `src/lib/cloister/__tests__/isolation-runtime-launch.test.ts`. A crash restart through `service-crash.ts` and a rotation through `session-rotation.ts` of a `work` agent each produce a launch with the token export; a Codex runtime spawn of an isolated agent writes `workspace-write`. + +## Acceptance criteria (map to items) + +- WI-1: `isIsolatedTokenRole('work')` returns true and `isIsolatedTokenRole('flywheel')` returns false; `readAgentIsolationConfig({})` returns `{ enabled: true, allowDocker: false, allowWrite: [] }`. +- WI-2: after `ensureAgentMcpToken`, the token file exists at `/agent-tokens/agent//mcp-token` with mode 0600; `ensureIsolationToken` rejects when the registry write fails. +- WI-3: `buildIsolationPolicy` output lists `/internal-token` in `denyRead` and `denyWrite`, the owner's token dir in `allowRead`, and `/hooks` in `denyWrite`; docker.sock is in `maskedSocketDirs` only when `allowDocker` is false. +- WI-4: the rendered settings contain `"allowUnsandboxedCommands": false` and only `Read(//…)`/`Edit(//…)` rules; the PreToolUse matcher is `Edit|Write|MultiEdit|NotebookEdit`. +- WI-5: the guard prints a deny decision for a target under `/config.yaml`, including through a symlink in the cwd, and prints nothing for a file in the workspace. +- WI-6: an isolated claude-code launcher script contains `--settings` and `unset OVERDECK_INTERNAL_TOKEN`; a non-isolated launcher is unchanged byte for byte. +- WI-7 and WI-8: a `work` spawn carries `isolation`; a plain conversation does not; a lane conversation does. +- WI-9: over the agent socket, an uncredentialed `GET /api/agents` gets 401 and an agent-token request gets 200. +- WI-10 and WI-11: in an isolated context, no `internal-token` file is created and requests carry `Authorization: Bearer odk_…`. +- WI-12: the generated caveman memory hook script sends the Bearer header when `OVERDECK_AGENT_TOKEN_FILE` is set. +- WI-13: hook scripts send the Bearer header with `OVERDECK_AGENT_TOKEN_FILE` set and never read `internal-token`. +- WI-14: a heartbeat from agent A's token for agent B returns 403 `not-self`; A's own heartbeat returns 2xx; a connector token with `operate` on complete-planning returns 403. +- WI-15: the route-scope table maps each listed route to the stated scope. +- WI-16: a `worker` token forwarding `done` returns 403 `role-not-allowed`; a `work` token forwarding `task done ` returns 400 `issue-mismatch`; a `review` token forwarding `task done` returns 403 `role-not-allowed`; an unknown verb returns 404 and the CLI runs it locally. +- WI-17 to WI-19: each listed verb has a row with the stated roles; a `work` token cannot forward `admin specialists done`. +- WI-20: a loopback connection owned by a descendant of a registered root gets 401 on `POST /api/dashboard/session`; with no roots registered, the mint is unchanged. +- WI-21: an uncredentialed Traefik-forwarded mint returns 401 `isolation-sign-in` with isolation enabled. +- WI-22: a foreign-PID-namespace owner younger than `staleMs` keeps its slot. +- WI-23: an isolated Codex launch with `codex.permissionMode: full-access` writes `sandbox_mode = "workspace-write"`. +- WI-24: `pan doctor` prints an error row naming `socat` when it is missing on Linux, and a warn row for each configured `none`-class harness. +- WI-26: with `OVERDECK_AGENT_TOKEN_FILE` set, the pi extension's heartbeat post carries `Authorization: Bearer odk_…` and no internal-token header. +- WI-27: agent A's token on agent B's control-ack gets 403 `not-self`; a `work` token on specialists auto-complete gets 403. +- WI-28: every verb in the coverage table with disposition `forwarded` resolves to a row that allows the listed roles. +- WI-29: a crash restart and a session rotation of an isolated agent each launch with `OVERDECK_AGENT_TOKEN_FILE` exported. +- D-12 (WI-6): an isolated claude-code launch with `socat` missing is refused with the D-12 error, and no pane starts. +- WI-25: `configuration/agent-isolation.mdx` exists, is linked from `docs.json`, and names `agents.isolation.enabled`, `allow_docker` and `allow_write`; `npm run lint:docs` passes. + +**Live verification (review/test).** On a host with `bwrap` and `socat` (or a scratch socat on PATH for the test process only), start one isolated Claude Code work agent on a throwaway issue. From its Bash, all of these must hold: +- `cat ~/.overdeck/internal-token` fails; +- `curl --noproxy '' --proxy "$HTTP_PROXY" -X POST http://127.0.0.1:3011/api/dashboard/session` gets 401; +- connecting to the Herdr socket fails; +- `pan task done` for its own item succeeds; +- `pan task done` naming another issue fails; +- `echo x >> ~/.bashrc` fails. + +Use an isolated browser profile for any Playwright step. + +## Implementation checkpoints + +- **CP-1 Live probes need socat.** When `socat` is missing, run live checks with a scratch copy on `PATH` for the probe process only (`apt-get download socat && dpkg -x`). Never install system packages. If neither is possible, record the live verification as not run in the PR and rely on unit tests. +- **CP-2 Own agent directory writes.** D-8 denies writes to all of `agents/`. If a local (non-forwarded) verb an isolated role runs fails with `EROFS` writing its own agent directory, add `allowWrite` for that directory and keep `denyWrite` on its `launcher.sh`, `overdeck-mcp.json` and `git-guard/` (deny inside allow holds, P2). +- **CP-3 `git push -u`.** `.git/config` is write-denied, so `git push -u` cannot record the upstream. Verify what work agents run. If `-u` is used, set the branch upstream at workspace creation (outside the sandbox), and make the agent git guard (`src/lib/launcher-git-guard.ts`) drop `-u`/`--set-upstream` when the upstream is already set. +- **CP-4 macOS.** Not probed. The settings file is the same and the peer rule is off. Doctor warns. +- **CP-5 Codex read deny.** See WI-23. +- **CP-6 Muse.** If `muse sandbox --help` documents read-deny paths, record them in the docs as a follow-up issue; do not configure it in this issue. + +## Intersecting repo rules (restated) + +- No `execSync` in dashboard server code or anything it imports. The peer rule uses `fs/promises`. +- Retry, backoff and delay tests use `vi.useFakeTimers()`, never real `setTimeout` waits. The self-cli wait loop tests inject the wait. +- One variant per operation in `src/lib`: no Effect wrapper around a Promise helper, and no sync twin without a documented sync caller. +- New tests must not read source files to assert content, and must add no `skipIf` or `.only`. +- File-size ratchet: no allowlist raise; extract into a new module instead. +- A new HTTP route needs a `no-loss-matrix.ts` row. +- Never `git stash`. Commit per item with an `Item: ` trailer. +- Quality gates: `npm run typecheck`, `npm run lint`, `npx vitest run `. Never the full `npm test` on the host. + +## Non-goals + +- A separate uid or root setup per machine. +- Sandboxing the verification gate or the post-merge deploy (R-1). It needs its own issue. +- Isolating agents launched on remote Fly VMs (`src/lib/remote/remote-agents.ts`): they run on a separate machine (CP-7). +- Configuring Muse's, grok's or opencode's own permission systems. +- Making the session mint require a credential for the local browser. +- Moving `overdeck.db` writes behind the dashboard (R-4). +- Hiding harness login credentials (Claude OAuth, `gh`) from agents (R-7). +- A Settings UI for the isolation keys. Config is `config.yaml` only. +- Changing the auto-approve hook. + +## Planning Q&A + +Auto mode (`pan plan --auto`): no questions were asked. Every default is recorded in `plan.autoDecisions` in the xBRIEF. The main ones: +1. The comment's "plan and implement it as one issue" supersedes "Design only". +2. The socket deny is applied as `denyRead` + `denyWrite` (D-9). +3. Fail closed when sandbox prerequisites are missing (D-12; changed from fail-open after plan critique round 1). +4. Traefik trust is off under isolation (D-11). +5. Docker is blocked by default (R-3). +6. The Flywheel keeps the operator credential (D-1). + +## Critique response + +### fail-open leaves the credential readable on this host +Accepted. D-12 now fails closed. An isolated Claude Code launch on Linux checks `bwrap` and `socat` and is refused with an actionable error when either is missing. The settings file sets `failIfUnavailable: true` as a second guard. A WI-6 acceptance criterion covers the refused launch with `socat` missing. The work agent flags the `socat` install requirement to the operator before merge. + +### forwarded file flags read operator secrets +Accepted. D-7 now excludes file-reading flags unless a row marks them `workspacePath`; such a value must `realpath` inside the caller's workspace and outside the read-deny set (400 `path-outside-workspace`). `worker report` takes its report only on stdin. WI-16 tests `worker report --file ~/.overdeck/internal-token`. + +### hook payloads have no subject agent ID +Accepted. D-16 now resolves the subject of the session-keyed hook routes on the server, from `session_id` to its owning agent or conversation. A token is accepted only when that owner matches. A session with no owner is refused for agent tokens. WI-14 tests token A with B's `session_id`. + +### alternate runtime launches bypass isolation +Accepted. New WI-29 prepares isolation inside every runtime's `spawnAgent`, which covers crash recovery, session rotation, the Codex runtime's own command, ohmypi, Muse, Kimi, Prime Agent, pi and ACP. Tests cover a crash restart and a rotation. Remote Fly launches are a NonGoal with checkpoint CP-7. + +### worker run cannot pass its required issue +Accepted. D-7 adds an `issueFlag` row option: a supplied `--issue` must equal the caller's issue, and the server strips it and injects the caller's own. WI-19 forwards `worker run` with it and tests `pan worker run --issue `. + +### generic self jobs truncate and time out long commands +Accepted. Self-cli jobs keep full output up to 4 MiB. `longRunning` rows (`worker run`, `worker wait`, `swarm wait`) get a 24 h job timeout, and the forwarder follows wait chunks until the job ends. A lost job exits 75 with a re-run message. WI-16 tests a report over 16 KiB and a job that outlives 15 minutes. + +### Unresolved after two critic rounds + +- forwarded handoff can create an operator conversation +- root registration fails open +- validated file flags can be swapped before the self job reads them + diff --git a/.pan/specs/2026-12-03-PAN-5754-design-isolate-agents-from-the-operator-credential.xbrief.json b/.pan/specs/2026-12-03-PAN-5754-design-isolate-agents-from-the-operator-credential.xbrief.json new file mode 100644 index 00000000000..44f699a097a --- /dev/null +++ b/.pan/specs/2026-12-03-PAN-5754-design-isolate-agents-from-the-operator-credential.xbrief.json @@ -0,0 +1,2182 @@ +{ + "xBRIEFInfo": { + "version": "0.8", + "created": "2026-12-03T20:19:30Z", + "author": "overdeck/0.0.0", + "description": "Plan for PAN-5754: Design: isolate agents from the operator credential", + "updated": "2026-12-03T20:49:17.841Z" + }, + "plan": { + "id": "pan-5754", + "title": "Design: isolate agents from the operator credential", + "status": "proposed", + "uid": "6bde0b77-c4ed-4d9d-bee0-71eec7f8a969", + "author": "agent:claude-opus-5-5", + "sequence": 2, + "created": "2026-12-03T20:19:30Z", + "updated": "2026-12-03T20:49:17.841Z", + "references": [ + { + "uri": "https://github.com/eltmon/overdeck/issues/5754", + "label": "PAN-5754", + "type": "issue" + }, + { + "uri": "https://github.com/eltmon/overdeck/issues/5696", + "label": "PAN-5696", + "type": "issue" + }, + { + "uri": "https://github.com/eltmon/overdeck/issues/5699", + "label": "PAN-5699", + "type": "issue" + } + ], + "tags": [ + "security", + "agent-isolation", + "sandbox", + "auth", + "pan-5687-followup" + ], + "narratives": { + "Problem": "Every managed agent runs as the operator's user and can act as the operator on the dashboard in one command. It can read ~/.overdeck/internal-token, mint a root session from loopback (a loopback caller always mints), or drive another agent's pane through the Herdr or tmux socket. This is audit finding F-9, and it is the root of F-4's auto-approval risk. Planning probes also showed that Claude Code's sandbox proxy forwards to host loopback and the managed Traefik, and that CIDR deny rules are ignored, so a sandbox alone does not close the mint.", + "Proposal": "Isolated agents (token role not conversation/flywheel) authenticate only with their own agent token from hooks and the CLI. Claude Code agents launch with an Overdeck-generated --settings file: sandboxed Bash with read-deny on the operator secret set (own token re-allowed), masked terminal-backend socket directories, a write allowlist with denies on files executed outside the sandbox, and a PreToolUse write guard for the file tools. The dashboard serves an agent Unix socket that only accepts credentials, refuses local trust to connections owned by an isolated process tree (Linux /proc lookup against a root registry), and stops trusting uncredentialed Traefik-forwarded requests while isolation is on. CLI verbs that need admin routes or terminal sockets are forwarded to POST /api/self/cli and run as role- and issue-bound self jobs. Codex is clamped to workspace-write. Every other harness is classified, and pan doctor and the docs name the gaps. Gate admission becomes PID-namespace aware.", + "NonGoals": "- No separate uid or root setup per machine.\n- No sandboxing of the verification gate or post-merge deploy (residual R-1, separate issue).\n- No configuration of Muse, grok or opencode permission systems beyond the token change.\n- No change that makes the local browser's session mint require a credential (only Traefik-forwarded trust changes under isolation).\n- No moving overdeck.db writes behind the dashboard (R-4).\n- No hiding of harness login credentials such as Claude OAuth or the gh token (R-7).\n- No Settings UI for agents.isolation keys.\n- No change to the auto-approve hook.\n- Overdeck never installs bubblewrap or socat itself.\n- Operator conversations and the Flywheel must not gain a sandbox, an isolation settings file or an agent-token-only credential." + }, + "autoDecisions": [ + { + "summary": "Plan and implement in this issue despite the title's 'Design only'.", + "rationale": "The operator's 2026-12-03 comment says #5696 is closed and to plan and implement it as one issue; that supersedes the original body." + }, + { + "summary": "Implement the 'deny-write on terminal-backend socket directories' intent as denyRead + denyWrite on those directories.", + "rationale": "Probe P6 showed deny-write does not stop connect() once Unix sockets are allowed; denyRead masking (P7) does. Both are applied so the wording and the effect both hold." + }, + { + "summary": "When bubblewrap or socat is missing, isolated Claude Code launches are refused (fail closed) with an actionable error; pan doctor reports an error too.", + "rationale": "Plan critique round 1: failing open leaves the credential readable with only a doctor message. The operator chose secure by default; the error names the one-line install and the opt-out key. The work agent must flag the socat install to the operator before merge." + }, + { + "summary": "The Flywheel keeps the operator credential like operator conversations.", + "rationale": "The Flywheel merges, deploys and approves restarts with operator authority by standing operator decision; it is the operator's delegate, not a pipeline agent." + }, + { + "summary": "Uncredentialed Traefik-forwarded requests are not trusted while isolation is on.", + "rationale": "Probe P12 showed the sandbox proxy reaches Traefik through a bridge gateway that the dashboard trusts as local, and an in-tree browser reaches it directly; the original client cannot be identified. Existing cookies keep working and the #overdeck_token= link covers new browsers." + }, + { + "summary": "Docker is blocked for isolated Claude Code agents unless agents.isolation.allow_docker is true.", + "rationale": "The Docker socket is root-equivalent and would void the isolation; secure by default per the operator's direction." + }, + { + "summary": "The CLI reaches the dashboard through a new credential-only Unix socket, and privileged or socket-touching verbs are forwarded as self jobs.", + "rationale": "Inside the sandbox loopback TCP works only through an undocumented proxy path, while allowAllUnixSockets is documented; PAN-4927 self jobs already run closed verbs with identity bound to the token." + }, + { + "summary": "Codex isolated launches are clamped to workspace-write; other harnesses get the token change plus doctor/docs disclosure.", + "rationale": "Built from the installed binaries' --help: Codex offers a write sandbox, Muse its own default sandbox, the rest none. That is the closest equivalent each offers." + }, + { + "summary": "Plan as one large xBRIEF instead of sibling issues.", + "rationale": "The operator explicitly asked for one issue; items are decomposed into small independently testable slices with a parallel-friendly DAG." + } + ], + "metadata": { + "sizeJustification": "The operator's 2026-12-03 comment on PAN-5754 says 'Plan and implement it as one issue.' The pieces are also interlocked: the CLI token switch breaks agents unless the forwarded-verb route and route-scope rows ship with it, and the sandbox breaks socket-touching verbs unless they are forwarded. Each item is still a small, independently testable slice, and the DAG lets most run in parallel.", + "canonicalFilename": "2026-12-03-PAN-5754-design-isolate-agents-from-the-operator-credential.xbrief.json", + "promotionIntent": "automatic" + }, + "items": [ + { + "id": "iso-config", + "title": "Add agents.isolation config and the isolated-role predicate", + "status": "pending", + "priority": "high", + "created": "2026-12-03T20:19:30Z", + "metadata": { + "difficulty": "simple", + "kind": "backend", + "issueLabel": "pan-5754", + "requiresInspection": false, + "inspectionDepth": "fast", + "files_scope": [ + "src/lib/config-yaml/schema-agent-isolation.ts", + "src/lib/config-yaml/schema.ts", + "src/lib/config-yaml/load.ts", + "src/lib/agent-isolation/config.ts", + "src/lib/agent-isolation/paths.ts", + "src/lib/agent-isolation/__tests__/config.test.ts" + ], + "files_scope_confidence": "high", + "verify_commands": [ + "npx vitest run src/lib/agent-isolation/__tests__/config.test.ts", + "npm run typecheck" + ], + "expected_outputs": [ + "src/lib/agent-isolation/__tests__/config.test.ts passes", + "typecheck completes without errors" + ], + "readiness": "ready", + "traces": [ + "FR-1", + "FR-14" + ] + }, + "narrative": { + "Action": "PRD WI-1. Create schema-agent-isolation.ts with AgentIsolationConfig {enabled?, allow_docker?, allow_write?}; add one line `isolation?: import('./schema-agent-isolation.js').AgentIsolationConfig;` inside `agents?: {` in schema.ts. Create src/lib/agent-isolation/config.ts with readAgentIsolationConfig (defaults enabled true, allowDocker false, allowWrite []; expands ~; drops relative paths with one warning), isIsolatedTokenRole(role) (false only for 'conversation' and 'flywheel'), isAgentIsolationActive(role). Create src/lib/agent-isolation/paths.ts with agentTokensDir, agentTokenDir(kind,id), isolationDir, isolationOwnerDir(kind,id), isolationRootsDir, agentApiSocketPath (/agent-api/dashboard.sock) and the env var name constants OVERDECK_AGENT_TOKEN_FILE, OVERDECK_DASHBOARD_SOCKET, OVERDECK_ISOLATED. In src/lib/config-yaml/load.ts stripProjectSecurity, also drop agents.isolation (keep agents.caveman and agents.rtk) so a committed .pan.yaml cannot turn isolation off." + }, + "items": [ + { + "id": "iso-config.ac1", + "title": "Given role 'work', 'review' or 'worker', when isIsolatedTokenRole is called, then it returns true; given 'conversation' or 'flywheel' it returns false", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "iso-config.ac2", + "title": "Given an empty config, when readAgentIsolationConfig runs, then it returns { enabled: true, allowDocker: false, allowWrite: [] }", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "iso-config.ac3", + "title": "Given agents.isolation.enabled: false, when isAgentIsolationActive('work') is called, then it returns false", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "iso-config.ac4", + "title": "Given allow_write ['~/x', 'rel/y'], when readAgentIsolationConfig runs, then it returns ['/x'] and emits exactly one warning naming 'rel/y'", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "iso-config.ac5", + "title": "Given a project config with agents.isolation.enabled false and agents.rtk set, when stripProjectSecurity runs, then the result has no agents.isolation and keeps agents.rtk", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + } + ] + }, + { + "id": "token-location", + "title": "Move agent tokens under agent-tokens/ and add a fail-closed isolation mint", + "status": "pending", + "priority": "high", + "created": "2026-12-03T20:19:30Z", + "metadata": { + "difficulty": "medium", + "kind": "backend", + "issueLabel": "pan-5754", + "requiresInspection": false, + "inspectionDepth": "fast", + "files_scope": [ + "src/lib/mcp/agent-token.ts", + "src/lib/mcp/agent-injection.ts", + "tests/unit/lib/mcp/agent-token.test.ts" + ], + "files_scope_confidence": "medium", + "verify_commands": [ + "npx vitest run tests/unit/lib/mcp/agent-token.test.ts", + "npm run typecheck" + ], + "expected_outputs": [ + "tests/unit/lib/mcp/agent-token.test.ts passes", + "typecheck completes without errors" + ], + "readiness": "ready", + "traces": [ + "FR-3", + "NFR-2" + ] + }, + "narrative": { + "Action": "PRD WI-2 / D-4 / D-5. Replace agentMcpTokenPath(dir) with agentMcpTokenPathFor({agentId, agentKind}) returning agentTokenDir(kind, normalizedId)/mcp-token; ensureAgentMcpToken writes there (dir 0700, file 0600); revokeAgentMcpTokens unlinks the new file and the legacy /mcp-token when dir is known. mintOverdeckTokenFile in agent-injection.ts uses the new path. Add ensureIsolationToken(owner) that calls ensureAgentMcpToken without the overdeckMcpEnabledFor gate and rethrows failures as Error('agent isolation: token mint failed for : '). If the token test file has another name, extend the existing agent-token test file instead." + }, + "items": [ + { + "id": "token-location.ac1", + "title": "Given a fresh OVERDECK_HOME, when ensureAgentMcpToken runs for agent-pan-1, then /agent-tokens/agent/agent-pan-1/mcp-token exists with mode 0600", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "token-location.ac2", + "title": "Given a legacy /mcp-token, when revokeAgentMcpTokens runs with that dir, then both the legacy file and the new file are removed", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "token-location.ac3", + "title": "Given a registry write that does not persist, when ensureIsolationToken runs, then it rejects with a message starting 'agent isolation: token mint failed for'", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + } + ] + }, + { + "id": "iso-policy", + "title": "Build the pure isolation policy and its input resolver", + "status": "pending", + "priority": "high", + "created": "2026-12-03T20:19:30Z", + "metadata": { + "difficulty": "complex", + "kind": "backend", + "issueLabel": "pan-5754", + "requiresInspection": true, + "inspectionDepth": "deep", + "files_scope": [ + "src/lib/agent-isolation/policy.ts", + "src/lib/agent-isolation/policy-input.ts", + "src/lib/agent-isolation/__tests__/policy.test.ts" + ], + "files_scope_confidence": "high", + "verify_commands": [ + "npx vitest run src/lib/agent-isolation/__tests__/policy.test.ts", + "npm run typecheck" + ], + "expected_outputs": [ + "src/lib/agent-isolation/__tests__/policy.test.ts passes", + "typecheck completes without errors" + ], + "readiness": "ready", + "traces": [ + "FR-4", + "FR-5" + ], + "foundationFor": [ + "claude-settings", + "write-guard-hook", + "launch-isolation" + ], + "acJustification": "Five ACs: the policy is the security foundation; read, write, socket, extras and the allowlist each need a check.", + "parallelSafeReason": "Creates new files only (policy.ts, policy-input.ts and its test); no other item edits them." + }, + "narrative": { + "Action": "PRD WI-3 / D-8. buildIsolationPolicy(input) is pure and returns {denyRead, allowRead, allowWrite, denyWrite, maskedSocketDirs, mkdirBeforeLaunch} with exactly the D-8 path lists (read-deny operator secret set incl. agent-tokens/ with allowRead for the owner's token dir; socket masks for Herdr sessions dir, tmux- dir, /sockets, XDG_RUNTIME_DIR, /tmp/.X11-unix, docker sockets unless allowDocker; write allowlist where contributes ONLY overdeck.db/panopticon.db/cache.db with -wal/-shm, logs/, tmp/ and verification-workers/admission/ (every other entry, incl. agent-api/, stays read-only); browser-profiles/ in read-deny; write denylist incl. workspace .git/.claude/.mcp.json, /hooks and /config, cache bin dirs). serializePolicy returns {version:1, allowWrite, denyWrite} for the guard hook. policy-input.ts resolves real inputs asynchronously (execFile git rev-parse --git-common-dir for the workspace and each child dir with a .git file; herdrSocketPath(); process.getuid(); existing cache dirs)." + }, + "items": [ + { + "id": "iso-policy.ac1", + "title": "Given a standard input, when buildIsolationPolicy runs, then /internal-token appears in both denyRead and denyWrite and /agent-tokens/agent/ appears in allowRead", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "iso-policy.ac2", + "title": "Given a workspace whose git common dir is /r/.git, when buildIsolationPolicy runs, then /r/.git is in allowWrite and /r/.git/hooks and /r/.git/config are in denyWrite", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "iso-policy.ac3", + "title": "Given allowDocker false, when buildIsolationPolicy runs, then /var/run/docker.sock is in maskedSocketDirs; given allowDocker true it is absent", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "iso-policy.ac4", + "title": "Given extraAllowWrite ['/data/x'], when buildIsolationPolicy runs, then '/data/x' is in allowWrite and the tmux socket dir is in mkdirBeforeLaunch", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "iso-policy.ac5", + "title": "Given a standard input, when buildIsolationPolicy runs, then the allowWrite entries under are exactly the DB files, logs/, tmp/ and verification-workers/admission/, and /agent-api is not writable", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + } + ] + }, + { + "id": "claude-settings", + "title": "Render the Claude Code isolation settings file", + "status": "pending", + "priority": "high", + "created": "2026-12-03T20:19:30Z", + "metadata": { + "difficulty": "medium", + "kind": "backend", + "issueLabel": "pan-5754", + "requiresInspection": false, + "inspectionDepth": "fast", + "files_scope": [ + "src/lib/agent-isolation/claude-settings.ts", + "src/lib/agent-isolation/__tests__/claude-settings.test.ts" + ], + "files_scope_confidence": "high", + "verify_commands": [ + "npx vitest run src/lib/agent-isolation/__tests__/claude-settings.test.ts", + "npm run typecheck" + ], + "expected_outputs": [ + "src/lib/agent-isolation/__tests__/claude-settings.test.ts passes", + "typecheck completes without errors" + ], + "readiness": "ready", + "traces": [ + "FR-4" + ] + }, + "narrative": { + "Action": "PRD WI-4. renderIsolationClaudeSettings(policy, guardHookPath, policyFile) returns the JSON in the PRD: sandbox {enabled true, failIfUnavailable true, allowUnsandboxedCommands false, autoAllowBashIfSandboxed true, network {allowAllUnixSockets true, allowedDomains ['*']}, filesystem {denyRead (incl. masked socket dirs), allowRead, allowWrite, denyWrite (incl. masked socket dirs)}}, permissions.deny with Read(//abs) and Edit(//abs) rules (directories get /**), hooks.PreToolUse matcher 'Edit|Write|MultiEdit|NotebookEdit' running 'OVERDECK_ISOLATION_POLICY= '. writeIsolationFiles(owner, policy) writes claude-settings.json and policy.json under isolationOwnerDir (0600, dir 0700, temp+rename)." + }, + "items": [ + { + "id": "claude-settings.ac1", + "title": "Given a policy, when renderIsolationClaudeSettings runs, then every denyRead path appears as a Read(//...) deny rule and no permission rule starts with a single '/' followed by a non-slash", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "claude-settings.ac2", + "title": "Given a policy, when renderIsolationClaudeSettings runs, then sandbox.allowUnsandboxedCommands is false, sandbox.failIfUnavailable is true and sandbox.network.allowAllUnixSockets is true", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "claude-settings.ac3", + "title": "Given an owner, when writeIsolationFiles runs, then claude-settings.json and policy.json exist under /isolation/// with mode 0600", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + } + ] + }, + { + "id": "write-guard-hook", + "title": "Add the agent-isolation-guard PreToolUse hook", + "status": "pending", + "priority": "high", + "created": "2026-12-03T20:19:30Z", + "metadata": { + "difficulty": "medium", + "kind": "backend", + "issueLabel": "pan-5754", + "requiresInspection": false, + "inspectionDepth": "fast", + "files_scope": [ + "sync-sources/hooks/agent-isolation-guard*", + "tests/scripts/agent-isolation-guard.test.ts" + ], + "files_scope_confidence": "high", + "verify_commands": [ + "npx vitest run tests/scripts/agent-isolation-guard.test.ts", + "npm run typecheck" + ], + "expected_outputs": [ + "tests/scripts/agent-isolation-guard.test.ts passes", + "typecheck completes without errors" + ], + "readiness": "ready", + "traces": [ + "FR-4", + "NFR-4" + ] + }, + "narrative": { + "Action": "PRD WI-5. Bash script (set -u, jq) reading hook JSON from stdin; target = .tool_input.file_path or .tool_input.notebook_path; resolve with realpath -m (realpath for an existing symlink); allow (print nothing, exit 0) when under an allowWrite root and no denyWrite root from $OVERDECK_ISOLATION_POLICY; otherwise print the PreToolUse deny JSON with reason 'agent isolation: is outside this agent's writable paths'; deny when the policy file is missing or unreadable. Mode 0755. sync-hooks.ts already copies every hook file to ~/.overdeck/bin." + }, + "items": [ + { + "id": "write-guard-hook.ac1", + "title": "Given a policy allowing the workspace, when the hook gets a Write to a workspace file, then it prints nothing and exits 0", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "write-guard-hook.ac2", + "title": "Given a policy denying /config.yaml, when the hook gets an Edit to a cwd symlink pointing at that file, then it prints a permissionDecision 'deny' JSON", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "write-guard-hook.ac3", + "title": "Given OVERDECK_ISOLATION_POLICY naming a missing file, when the hook runs, then it prints a permissionDecision 'deny' JSON", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + } + ] + }, + { + "id": "launch-isolation", + "title": "Wire isolation into the launcher (settings flag, env, root registration)", + "status": "pending", + "priority": "high", + "created": "2026-12-03T20:19:30Z", + "metadata": { + "difficulty": "complex", + "kind": "backend", + "issueLabel": "pan-5754", + "requiresInspection": false, + "inspectionDepth": "fast", + "files_scope": [ + "src/lib/agent-isolation/launch.ts", + "src/lib/agent-isolation/launcher-lines.ts", + "src/lib/launcher-generator.ts", + "src/lib/__tests__/launcher-generator.test.ts" + ], + "files_scope_confidence": "medium", + "verify_commands": [ + "npx vitest run src/lib/__tests__/launcher-generator.test.ts", + "npm run typecheck" + ], + "expected_outputs": [ + "src/lib/__tests__/launcher-generator.test.ts passes", + "typecheck completes without errors" + ], + "readiness": "ready", + "traces": [ + "FR-2", + "FR-4", + "FR-11", + "NFR-2", + "NFR-3" + ], + "acJustification": "Five ACs: the launcher is where the fail-closed rule, the token env, the settings flag and the unchanged non-isolated path each need a check.", + "parallelSafeReason": "Owns launcher-generator.ts and the new launch.ts/launcher-lines.ts; the launch-site items that call it are ordered after it by edges." + }, + "narrative": { + "Action": "PRD WI-6 / D-3 / D-15. prepareAgentIsolation(owner) returns {} unless isAgentIsolationActive(owner.role); otherwise, for a claude-code launch on Linux, check bwrap and socat on PATH (injected dependency) and throw the D-12 error 'agent isolation: Claude Code sandbox unavailable (missing: ). Install with: sudo apt-get install bubblewrap socat, or set agents.isolation.enabled: false to run agents unisolated' when either is missing (fail closed); then ensureIsolationToken (throws => launch fails), resolve+build the policy, write settings+policy files for claude-code launches, and return {isolation: {settingsFile?, env: {OVERDECK_AGENT_TOKEN_FILE, OVERDECK_DASHBOARD_SOCKET, OVERDECK_ISOLATED:'1', NODE_USE_ENV_PROXY:'1'}, unsetEnv:['OVERDECK_INTERNAL_TOKEN'], mkdirs, rootFile}}. In launcher-generator.ts add LauncherConfig.isolation; emit mkdir -p -m 700, exports, unset and rootRegistrationLauncherLine(rootFile) (from peer-rule) after the env block and before cd; append --settings to the claude command in buildCommand's conversation branch and buildNonConversationCommand; prefix the review sub-role post-exit pan tell / pan admin agents exited lines with 'env -u OVERDECK_AGENT_TOKEN_FILE'. Keep launcher-generator.ts within its file-size cap by putting helpers in launcher-lines.ts. If the existing launcher test file has another name, extend that file." + }, + "items": [ + { + "id": "launch-isolation.ac1", + "title": "Given an isolated claude-code LauncherConfig, when generateLauncherScript runs, then the script contains '--settings', 'export OVERDECK_AGENT_TOKEN_FILE=' and 'unset OVERDECK_INTERNAL_TOKEN'", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "launch-isolation.ac2", + "title": "Given a LauncherConfig without isolation, when generateLauncherScript runs, then the output is byte-identical to the output before this change for the same config", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "launch-isolation.ac3", + "title": "Given an isolated review sub-role launch, when generateLauncherScript runs, then the post-exit pan tell and pan admin agents exited lines start with 'env -u OVERDECK_AGENT_TOKEN_FILE'", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "launch-isolation.ac4", + "title": "Given ensureIsolationToken rejects, when prepareAgentIsolation runs for role 'work', then it rejects and no launcher script is written", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "launch-isolation.ac5", + "title": "Given a Linux claude-code launch for role 'work' with socat missing from PATH, when prepareAgentIsolation runs, then it rejects with a message naming socat and 'sudo apt-get install bubblewrap socat'", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + } + ] + }, + { + "id": "launch-sites-agents", + "title": "Spread prepareAgentIsolation at the agent spawn, recovery and resume sites", + "status": "pending", + "priority": "high", + "created": "2026-12-03T20:19:30Z", + "metadata": { + "difficulty": "medium", + "kind": "backend", + "issueLabel": "pan-5754", + "requiresInspection": false, + "inspectionDepth": "fast", + "files_scope": [ + "src/lib/agents/spawn.ts", + "src/lib/agents/spawn-prep.ts", + "src/lib/agents/recovery.ts", + "src/lib/agents/messaging.ts", + "src/lib/agents/__tests__/spawn-isolation.test.ts" + ], + "files_scope_confidence": "medium", + "verify_commands": [ + "npx vitest run src/lib/agents/__tests__/spawn-isolation.test.ts", + "npm run typecheck" + ], + "expected_outputs": [ + "src/lib/agents/__tests__/spawn-isolation.test.ts passes", + "typecheck completes without errors" + ], + "readiness": "ready", + "traces": [ + "FR-1", + "FR-4", + "FR-11" + ] + }, + "narrative": { + "Action": "PRD WI-7. Next to each prepareClaudeOverdeckMcp / prepareCodexOverdeckMcp call in spawn.ts, spawn-prep.ts, recovery.ts and messaging.ts, spread `...(await prepareAgentIsolation({ same owner }))` into the launcher config, and pass `isolated: isAgentIsolationActive(role)` to getCodexLauncherFields (added by codex-clamp). An isolation error fails the spawn like a missing binary." + }, + "items": [ + { + "id": "launch-sites-agents.ac1", + "title": "Given a spawn for role 'work', when the launcher config is built, then it carries an isolation field with OVERDECK_AGENT_TOKEN_FILE in env", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "launch-sites-agents.ac2", + "title": "Given a spawn for role 'flywheel', when the launcher config is built, then it has no isolation field", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "launch-sites-agents.ac3", + "title": "Given a resume through messaging.ts for a work agent, when the launcher config is built, then it carries an isolation field", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + } + ] + }, + { + "id": "launch-sites-planning-conv", + "title": "Spread prepareAgentIsolation at the planning and conversation launch sites", + "status": "pending", + "priority": "high", + "created": "2026-12-03T20:19:30Z", + "metadata": { + "difficulty": "medium", + "kind": "backend", + "issueLabel": "pan-5754", + "requiresInspection": false, + "inspectionDepth": "fast", + "files_scope": [ + "src/lib/planning/spawn-planning-session.ts", + "src/dashboard/server/routes/misc/planning.ts", + "src/lib/overdeck/conversation-runtime.ts", + "src/lib/overdeck/__tests__/conversation-isolation.test.ts" + ], + "files_scope_confidence": "medium", + "verify_commands": [ + "npx vitest run src/lib/overdeck/__tests__/conversation-isolation.test.ts", + "npm run typecheck" + ], + "expected_outputs": [ + "src/lib/overdeck/__tests__/conversation-isolation.test.ts passes", + "typecheck completes without errors" + ], + "readiness": "ready", + "traces": [ + "FR-1", + "FR-11" + ] + }, + "narrative": { + "Action": "PRD WI-8. Planning launches (role 'plan') in spawn-planning-session.ts and routes/misc/planning.ts get the isolation spread. conversation-runtime.ts passes role conversationTokenRole(tokenRow, role, tmuxSession): a plain conversation resolves to 'conversation' (not isolated, FR-11), a lane conversation to 'worker' (isolated), the Flywheel conversation to 'flywheel' (not isolated)." + }, + "items": [ + { + "id": "launch-sites-planning-conv.ac1", + "title": "Given a plain operator conversation launch, when the launch command is built, then it contains no '--settings' isolation flag and no OVERDECK_AGENT_TOKEN_FILE export", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "launch-sites-planning-conv.ac2", + "title": "Given a lane conversation launch, when the launch command is built, then it contains the '--settings' isolation flag", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "launch-sites-planning-conv.ac3", + "title": "Given a planning session launch, when the launcher config is built, then it carries an isolation field", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + } + ] + }, + { + "id": "agent-socket", + "title": "Serve the dashboard HTTP app on the agent Unix socket", + "status": "pending", + "priority": "high", + "created": "2026-12-03T20:19:30Z", + "metadata": { + "difficulty": "medium", + "kind": "backend", + "issueLabel": "pan-5754", + "requiresInspection": false, + "inspectionDepth": "fast", + "files_scope": [ + "src/dashboard/server/agent-api-socket.ts", + "src/dashboard/server/server.ts", + "src/dashboard/server/__tests__/agent-api-socket.test.ts" + ], + "files_scope_confidence": "high", + "verify_commands": [ + "npx vitest run src/dashboard/server/__tests__/agent-api-socket.test.ts", + "npm run typecheck" + ], + "expected_outputs": [ + "src/dashboard/server/__tests__/agent-api-socket.test.ts passes", + "typecheck completes without errors" + ], + "readiness": "ready", + "traces": [ + "FR-6" + ] + }, + "narrative": { + "Action": "PRD WI-9 / D-6. installAgentApiSocket(): mkdir 0700, unlink stale socket, net.createServer(socket => deliverHttpSocket(socket) || socket.destroy()), listen(agentApiSocketPath()), chmod 0600; return a closer that closes and unlinks. Call it in server.ts right after installChannelListener on the primary dashboard and register the closer with shutdown. A request on the socket has no peer address, so it is never a trusted local caller." + }, + "items": [ + { + "id": "agent-socket.ac1", + "title": "Given the socket is installed, when an uncredentialed GET /api/agents arrives over it, then the response status is 401", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "agent-socket.ac2", + "title": "Given the socket is installed, when GET /api/agents arrives over it with a valid agent token, then the response status is 200", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "agent-socket.ac3", + "title": "Given the socket is installed, when its file mode is read, then it is 0600", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + } + ] + }, + { + "id": "cli-credential", + "title": "Add the isolated-context credential and transport helper", + "status": "pending", + "priority": "high", + "created": "2026-12-03T20:19:30Z", + "metadata": { + "difficulty": "medium", + "kind": "backend", + "issueLabel": "pan-5754", + "requiresInspection": false, + "inspectionDepth": "fast", + "files_scope": [ + "src/lib/dashboard-client/agent-credential.ts", + "src/lib/dashboard-client/__tests__/agent-credential.test.ts" + ], + "files_scope_confidence": "high", + "verify_commands": [ + "npx vitest run src/lib/dashboard-client/__tests__/agent-credential.test.ts", + "npm run typecheck" + ], + "expected_outputs": [ + "src/lib/dashboard-client/__tests__/agent-credential.test.ts passes", + "typecheck completes without errors" + ], + "readiness": "ready", + "traces": [ + "FR-2" + ] + }, + "narrative": { + "Action": "PRD WI-10 / D-3 / D-6. isIsolatedAgentContext(env), readAgentToken(env) (re-read each call; must match ^odk_[0-9a-f]{64}$ else AgentCredentialError), dashboardAuthHeaders(env) (Bearer in isolated context, else the internal-token header via ensureInternalToken), dashboardFetch(path, init, env): in isolated context with OVERDECK_DASHBOARD_SOCKET use node:http request({socketPath}) and return a WHATWG Response; on ENOENT/ECONNREFUSED/EPERM retry once over TCP at getDashboardApiUrl(); never fall back to the internal token; always strip a caller-set x-overdeck-internal-token header." + }, + "items": [ + { + "id": "cli-credential.ac1", + "title": "Given OVERDECK_AGENT_TOKEN_FILE pointing at a valid token, when dashboardFetch runs against a Unix-socket test server, then the request carries 'Authorization: Bearer odk_' and no internal-token file is created in OVERDECK_HOME", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "cli-credential.ac2", + "title": "Given no OVERDECK_AGENT_TOKEN_FILE, when dashboardAuthHeaders runs, then it returns the x-overdeck-internal-token header", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "cli-credential.ac3", + "title": "Given the socket path does not exist, when dashboardFetch runs in an isolated context, then it falls back to TCP with the Bearer header", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + } + ] + }, + { + "id": "cli-callers", + "title": "Route CLI-side dashboard calls through the credential helper", + "status": "pending", + "priority": "high", + "created": "2026-12-03T20:19:30Z", + "metadata": { + "difficulty": "medium", + "kind": "backend", + "issueLabel": "pan-5754", + "requiresInspection": false, + "inspectionDepth": "fast", + "files_scope": [ + "src/cli/commands/dashboard-call.ts", + "src/lib/agent-runtime.ts", + "src/lib/pipeline-notifier.ts", + "src/lib/cloister/deacon-event-client.ts", + "src/cli/commands/plan.ts", + "src/cli/commands/start.ts", + "src/lib/__tests__/pipeline-notifier.test.ts", + "src/lib/dashboard-client/__tests__/cli-callers-isolated.test.ts" + ], + "files_scope_confidence": "medium", + "verify_commands": [ + "npx vitest run src/lib/__tests__/pipeline-notifier.test.ts src/lib/dashboard-client/__tests__/cli-callers-isolated.test.ts", + "npm run typecheck" + ], + "expected_outputs": [ + "the named test files pass", + "typecheck completes without errors" + ], + "readiness": "ready", + "traces": [ + "FR-2" + ] + }, + "narrative": { + "Action": "PRD WI-11. Replace every ensureInternalToken()/getInternalToken() header construction in these files with dashboardFetch or dashboardAuthHeaders. Behaviour outside an isolated context is unchanged. pipeline-notifier keeps its skip-without-credential rule but posts with the agent token in an isolated context. Extend src/lib/__tests__/pipeline-notifier.test.ts and add src/lib/dashboard-client/__tests__/cli-callers-isolated.test.ts for the other callers." + }, + "items": [ + { + "id": "cli-callers.ac1", + "title": "Given an isolated context, when pipeline-notifier forwards an event, then the request carries the Bearer agent token and ensureInternalToken is not called", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "cli-callers.ac2", + "title": "Given an isolated context, when dashboard-call's helper runs, then no internal-token file is created in OVERDECK_HOME", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "cli-callers.ac3", + "title": "Given a non-isolated context, when the same calls run, then they send the x-overdeck-internal-token header as before", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + } + ] + }, + { + "id": "in-pane-callers", + "title": "Use the agent token in the in-pane memory hook, Codex prompt memory and Channels bridge", + "status": "pending", + "priority": "high", + "created": "2026-12-03T20:19:30Z", + "metadata": { + "difficulty": "simple", + "kind": "backend", + "issueLabel": "pan-5754", + "requiresInspection": false, + "inspectionDepth": "fast", + "files_scope": [ + "src/lib/caveman/workspace.ts", + "src/lib/codex/prompt-memory.ts", + "src/lib/channels/overdeck-bridge.ts", + "src/lib/caveman/__tests__/workspace.test.ts", + "src/lib/codex/__tests__/prompt-memory.test.ts" + ], + "files_scope_confidence": "medium", + "verify_commands": [ + "npx vitest run src/lib/caveman/__tests__/workspace.test.ts src/lib/codex/__tests__/prompt-memory.test.ts", + "npm run typecheck" + ], + "expected_outputs": [ + "the caveman and prompt-memory tests pass", + "typecheck completes without errors" + ], + "readiness": "ready", + "traces": [ + "FR-2" + ] + }, + "narrative": { + "Action": "PRD WI-12. The memory hook script caveman/workspace.ts generates reads $OVERDECK_AGENT_TOKEN_FILE when set and sends Authorization: Bearer, otherwise today's internal token. codex/prompt-memory.ts and channels/overdeck-bridge.ts use dashboardAuthHeaders(). Extend the existing tests (asserting on the generated script output is allowed; it is output, not source)." + }, + "items": [ + { + "id": "in-pane-callers.ac1", + "title": "Given OVERDECK_AGENT_TOKEN_FILE is referenced, when the caveman memory hook script is generated, then it contains an Authorization: Bearer branch that does not read internal-token", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "in-pane-callers.ac2", + "title": "Given an isolated context, when prompt-memory posts /api/memory/inject, then the request carries the Bearer agent token", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + } + ] + }, + { + "id": "hooks-token", + "title": "Make the Claude Code hook scripts use the agent token", + "status": "pending", + "priority": "high", + "created": "2026-12-03T20:19:30Z", + "metadata": { + "difficulty": "medium", + "kind": "backend", + "issueLabel": "pan-5754", + "requiresInspection": false, + "inspectionDepth": "fast", + "files_scope": [ + "sync-sources/hooks/pan-hook-lib.sh", + "sync-sources/hooks/session-start-hook*", + "sync-sources/hooks/stop-hook*", + "sync-sources/hooks/user-prompt-submit-hook*", + "sync-sources/hooks/permission-event-hook*", + "tests/scripts/hooks-agent-token.test.ts" + ], + "files_scope_confidence": "high", + "verify_commands": [ + "npx vitest run tests/scripts/hooks-agent-token.test.ts", + "npm run typecheck" + ], + "expected_outputs": [ + "tests/scripts/hooks-agent-token.test.ts passes", + "typecheck completes without errors" + ], + "readiness": "ready", + "traces": [ + "FR-2", + "NFR-4" + ] + }, + "narrative": { + "Action": "PRD WI-13. When OVERDECK_AGENT_TOKEN_FILE is set, each hook reads it and sends 'Authorization: Bearer ' and does not read /internal-token; otherwise behaviour is unchanged. Covers pan-hook-lib.sh (both curl sites), session-start-hook, stop-hook (incl. the planning complete-planning curl), user-prompt-submit-hook and permission-event-hook. Test with a local stub HTTP server." + }, + "items": [ + { + "id": "hooks-token.ac1", + "title": "Given OVERDECK_AGENT_TOKEN_FILE set and a stub dashboard, when session-start-hook runs, then the stub receives 'Authorization: Bearer odk_' and no x-overdeck-internal-token header", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "hooks-token.ac2", + "title": "Given OVERDECK_AGENT_TOKEN_FILE set and an OVERDECK_HOME without internal-token, when pan-hook-lib.sh's event emit runs, then no internal-token file is created", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "hooks-token.ac3", + "title": "Given OVERDECK_AGENT_TOKEN_FILE unset, when session-start-hook runs, then the stub receives the x-overdeck-internal-token header as before", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + } + ] + }, + { + "id": "self-auth-routes", + "title": "Let hook and self-report routes accept an agent token that speaks for itself", + "status": "pending", + "priority": "high", + "created": "2026-12-03T20:19:30Z", + "metadata": { + "difficulty": "complex", + "kind": "api", + "issueLabel": "pan-5754", + "requiresInspection": false, + "inspectionDepth": "fast", + "files_scope": [ + "src/dashboard/server/routes/self-or-internal.ts", + "src/dashboard/server/routes/agents/shared.ts", + "src/dashboard/server/routes/agents/runtime-events.ts", + "src/dashboard/server/routes/hooks.ts", + "src/dashboard/server/routes/agents/permissions.ts", + "src/dashboard/server/routes/issues.ts", + "src/dashboard/server/__tests__/self-or-internal.test.ts" + ], + "files_scope_confidence": "medium", + "verify_commands": [ + "npx vitest run src/dashboard/server/__tests__/self-or-internal.test.ts", + "npm run typecheck" + ], + "expected_outputs": [ + "src/dashboard/server/__tests__/self-or-internal.test.ts passes", + "typecheck completes without errors" + ], + "readiness": "ready", + "traces": [ + "FR-8" + ], + "parallelSafeReason": "Edits only the hook and runtime route handlers plus a new helper; route-scopes.ts belongs to route-scope-rows and the pi routes to pi-routes-self-auth." + }, + "narrative": { + "Action": "PRD WI-14 / D-16. authorizeInternalOrSelfAgent(request, subjectAgentId) passes the internal token or an agent token whose normalized agentId equals the subject; another agent's token gets 403 {code:'not-self'}; none gets 401. Use it in validateAgentRuntimeEventAuth, which gains a subjectAgentId parameter passed from every caller in routes/agents/runtime-events.ts (heartbeat, work-complete, stuck, plan-checklist; subject = :id), the five hasDashboardInternalToken sites in hooks.ts (session-keyed routes: resolve the owner of the payload's session_id on the server with the lookup the handlers already use, compare it with the token agentId; a session with no owner is refused for agent tokens), the internal permission request in agents/permissions.ts (subject = :id) and POST /api/hooks/permission-event. complete-planning in src/dashboard/server/routes/issues.ts (anchor '/api/issues/:id/complete-planning', line ~360) accepts an agent token only when its role is 'plan' and its agent's issue equals :id; any other credential must hold admin (so a phone/machine/connector token with operate gets 403); an uncredentialed trusted local caller passes as today." + }, + "items": [ + { + "id": "self-auth-routes.ac1", + "title": "Given agent A's token, when A posts its own heartbeat to /api/agents/A/heartbeat, then the response is 2xx", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "self-auth-routes.ac2", + "title": "Given agent A's token, when A posts a heartbeat for agent B, then the response is 403 with code 'not-self'", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "self-auth-routes.ac3", + "title": "Given agent A's token and a user-prompt-submit payload carrying agent B's session_id, when it is posted, then the response is 403 with code 'not-self'", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "self-auth-routes.ac4", + "title": "Given a work-role token or a connector token with operate, when it posts /api/issues//complete-planning, then the response is 403; given a plan-role token for its own issue, it is accepted", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + } + ] + }, + { + "id": "route-scope-rows", + "title": "Add route-scope rows for agent-callable routes", + "status": "pending", + "priority": "high", + "created": "2026-12-03T20:19:30Z", + "metadata": { + "difficulty": "simple", + "kind": "api", + "issueLabel": "pan-5754", + "requiresInspection": false, + "inspectionDepth": "fast", + "files_scope": [ + "src/dashboard/server/route-scopes.ts", + "tests/unit/lib/overdeck/no-loss-matrix.ts", + "src/dashboard/server/__tests__/route-scopes.test.ts" + ], + "files_scope_confidence": "medium", + "verify_commands": [ + "npx vitest run src/dashboard/server/__tests__/route-scopes.test.ts", + "npm run typecheck" + ], + "expected_outputs": [ + "src/dashboard/server/__tests__/route-scopes.test.ts passes", + "typecheck completes without errors" + ], + "readiness": "ready", + "traces": [ + "FR-8" + ] + }, + "narrative": { + "Action": "PRD WI-15. In route-scopes.ts add 'tell' rows for POST /api/agents/:id/heartbeat, /api/hooks/turn-complete, /api/hooks/user-prompt-submit, /api/hooks/permission-event, /api/memory/inject, /api/memory/session/start, /api/memory/turn, /api/internal/agents/:id/permissions/request; 'operate' for POST /api/issues/:id/complete-planning; 'read:state' for GET /api/agents/:id/runtime and POST /api/self/cli; 'read:conversations' for GET /api/agents/:id/conversation; for the pi extension also 'tell' for POST /api/agents/:id/work-complete, /stuck, /plan-checklist, /classify-completion, POST /api/conversations/:name/control-ack and POST /api/specialists/:name/auto-complete. Add the no-loss-matrix row for the new POST /api/self/cli route in tests/unit/lib/overdeck/no-loss-matrix.ts. This item is the only one that edits route-scopes.ts. Use the existing route-scopes test file name." + }, + "items": [ + { + "id": "route-scope-rows.ac1", + "title": "Given the route-scope table, when requiredScopeFor('POST', '/api/agents/x/heartbeat') is called, then it returns 'tell'", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "route-scope-rows.ac2", + "title": "Given the route-scope table, when requiredScopeFor('POST', '/api/issues/PAN-1/complete-planning') is called, then it returns 'operate'", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "route-scope-rows.ac3", + "title": "Given the route-scope table, when requiredScopeFor('POST', '/api/self/cli') is called, then it returns 'read:state'", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + } + ] + }, + { + "id": "self-cli-route", + "title": "Add POST /api/self/cli, the forwarded-verb table and the CLI forwarder", + "status": "pending", + "priority": "high", + "created": "2026-12-03T20:19:30Z", + "metadata": { + "difficulty": "expert", + "kind": "api", + "issueLabel": "pan-5754", + "requiresInspection": true, + "inspectionDepth": "deep", + "files_scope": [ + "src/dashboard/server/services/self-cli-verbs/index.ts", + "src/dashboard/server/services/self-cli-verbs/core.ts", + "src/dashboard/server/services/self-cli-verbs/messaging.ts", + "src/dashboard/server/services/self-cli-verbs/planning.ts", + "src/dashboard/server/services/self-cli-verbs/review.ts", + "src/dashboard/server/services/self-cli-verbs/swarm.ts", + "src/dashboard/server/services/self-cli-verbs/misc.ts", + "src/dashboard/server/services/self-cli-argv.ts", + "src/dashboard/server/services/self-job-argv.ts", + "src/dashboard/server/services/self-jobs.ts", + "src/dashboard/server/routes/self-cli.ts", + "src/cli/isolated-forward.ts", + "src/cli/index.ts", + "src/dashboard/server/__tests__/self-cli-route.test.ts", + "src/cli/__tests__/isolated-forward.test.ts" + ], + "files_scope_confidence": "medium", + "verify_commands": [ + "npx vitest run src/dashboard/server/__tests__/self-cli-route.test.ts src/cli/__tests__/isolated-forward.test.ts", + "npm run typecheck" + ], + "expected_outputs": [ + "src/dashboard/server/__tests__/self-cli-route.test.ts passes", + "src/cli/__tests__/isolated-forward.test.ts passes", + "typecheck completes without errors" + ], + "readiness": "ready", + "traces": [ + "FR-7" + ], + "foundationFor": [ + "forward-messaging", + "forward-planning-review", + "forward-swarm-misc" + ], + "acJustification": "Five ACs: the route is the security boundary (role, issue, flag, unknown-verb and stdin handling each need their own check).", + "parallelSafeReason": "Creates the self-cli files; the forward-* items that add rows to its family files are ordered after it by edges." + }, + "narrative": { + "Action": "PRD WI-16 / D-7. SELF_CLI_VERBS concatenated from family files (messaging, planning, review, swarm, misc start as empty arrays; core holds this item's rows: task claim|done|block|unblock|next|cancel (roles work, strike), done (work, strike, knowledge), handoff (work), worker report and lane report (worker; stdin only, no --file), memory add|search|edit|retire|pin|unpin (every isolated role); a worker token never gets done or task, per roles/worker.md). matchSelfCliVerb picks the longest prefix. Rows may set issueFlag (a supplied --issue must equal the caller's issue; the server strips it and injects --issue=), workspacePath flags (file-reading flags such as --file/--brief/--*-file/--path/--from are excluded unless marked; a marked value must realpath inside the caller's workspace and outside the D-8 read-deny set, else 400 path-outside-workspace), longRunning (job timeout SELF_CLI_LONG_JOB_TIMEOUT_MS = 24 h, injected for fake-timer tests), textTail (trailing free text joined into one rest piece after '--') and stdin (body stdin string <= 1 MiB written to the job's stdin; extend SelfJobRunInput with stdin?: string and have the injected runner write and close it). buildSelfCliArgv validates flags only from row.flags (D-7 exclusion rule), positionals as ref pieces, issue positional equal to caller.issueId (case-insensitive) else SelfJobArgError('issue-mismatch'), built only through buildSelfJobArgv piece types. POST /api/self/cli body {argv, stdin?} (argv <=64 elements, each <=8 KiB): role not allowed -> 403 role-not-allowed; no row -> 404 verb-not-forwarded; validation -> 400; else start a self job with the prebuilt argv (self-cli jobs keep full stdout/stderr up to SELF_JOB_MAX_BUFFER) and answer selfJobAnswer. The forwarder exits 75 with 'forwarded job lost (dashboard restarted?); re-run the command' on 404 unknown-job. maybeForwardIsolatedVerb() in src/cli/isolated-forward.ts returns null outside an isolated context or on 404, otherwise posts via dashboardFetch, follows next via GET /api/self/jobs/:id/wait, writes stdout/stderr and returns the exit code; index.ts calls it before program.parseAsync. Register the route with the other self routes." + }, + "items": [ + { + "id": "self-cli-route.ac1", + "title": "Given a work token, when it forwards ['task','done','x','--issue','PAN-9'] or names another issue positional, then the route returns 400 (disallowed flag or issue-mismatch)", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "self-cli-route.ac2", + "title": "Given a review token forwarding ['task','done','item-1'] or a worker token forwarding ['done'], when the route runs, then it returns 403 with code 'role-not-allowed'", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "self-cli-route.ac3", + "title": "Given any token, when it forwards an argv matching no row, then the route returns 404 'verb-not-forwarded' and maybeForwardIsolatedVerb returns null", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "self-cli-route.ac4", + "title": "Given a work token and a valid ['task','done','item-1'], when forwarded, then a self job runs 'pan task done item-1' with the caller's identity env and the CLI exits with the job's exit code", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "self-cli-route.ac5", + "title": "Given a worker token forwarding ['worker','report','--file','~/.overdeck/internal-token'], when the route runs, then it returns 400 and no job starts; a two-line stdin report instead reaches the child exactly, and job stdout over 16 KiB is returned whole", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + } + ] + }, + { + "id": "forward-messaging", + "title": "Forward tell, ask and sync-main for isolated agents", + "status": "pending", + "priority": "high", + "created": "2026-12-03T20:19:30Z", + "metadata": { + "difficulty": "medium", + "kind": "api", + "issueLabel": "pan-5754", + "requiresInspection": false, + "inspectionDepth": "fast", + "files_scope": [ + "src/dashboard/server/services/self-cli-verbs/messaging.ts", + "src/dashboard/server/__tests__/self-cli-messaging.test.ts" + ], + "files_scope_confidence": "medium", + "verify_commands": [ + "npx vitest run src/dashboard/server/__tests__/self-cli-messaging.test.ts", + "npm run typecheck" + ], + "expected_outputs": [ + "src/dashboard/server/__tests__/self-cli-messaging.test.ts passes", + "typecheck completes without errors" + ], + "readiness": "ready", + "traces": [ + "FR-7" + ] + }, + "narrative": { + "Action": "PRD WI-17. Rows: tell (all isolated roles; positional 0 is the target, not the issue; textTail for the message), ask (work, strike; textTail), sync-main (work, strike; issue positional 0), review request (work, strike; issue positional 0). Flags per the D-7 rule, read from each verb's commander definition in src/cli/index.ts or its command module." + }, + "items": [ + { + "id": "forward-messaging.ac1", + "title": "Given a test token, when it forwards ['tell','conv-flywheel','three word message'], then the self job argv is ['tell','conv-flywheel','--','three word message'] and the message reaches the target intact", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "forward-messaging.ac2", + "title": "Given a work token for PAN-5, when it forwards ['sync-main','PAN-6'], then the route returns 400 issue-mismatch", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "forward-messaging.ac3", + "title": "Given a review token, when it forwards ['ask', ...], then the route returns 403 role-not-allowed", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + } + ] + }, + { + "id": "forward-planning-review", + "title": "Forward plan finalize and the review/test verdict verbs", + "status": "pending", + "priority": "high", + "created": "2026-12-03T20:19:30Z", + "metadata": { + "difficulty": "medium", + "kind": "api", + "issueLabel": "pan-5754", + "requiresInspection": false, + "inspectionDepth": "fast", + "files_scope": [ + "src/dashboard/server/services/self-cli-verbs/planning.ts", + "src/dashboard/server/services/self-cli-verbs/review.ts", + "src/dashboard/server/__tests__/self-cli-planning-review.test.ts" + ], + "files_scope_confidence": "medium", + "verify_commands": [ + "npx vitest run src/dashboard/server/__tests__/self-cli-planning-review.test.ts", + "npm run typecheck" + ], + "expected_outputs": [ + "src/dashboard/server/__tests__/self-cli-planning-review.test.ts passes", + "typecheck completes without errors" + ], + "readiness": "ready", + "traces": [ + "FR-7" + ] + }, + "narrative": { + "Action": "PRD WI-18. planning.ts: 'plan finalize' and 'plan done' (role plan; issue positional 0 when given, otherwise the server injects the caller's issue). review.ts: 'admin specialists done' (roles review, test), 'review spawn-reviewer' (role review), 'admin seed-uat-fixtures' (role test); the issue positional must match. Flags per D-7." + }, + "items": [ + { + "id": "forward-planning-review.ac1", + "title": "Given a work token, when it forwards ['admin','specialists','done', ...], then the route returns 403 role-not-allowed", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "forward-planning-review.ac2", + "title": "Given a plan token for PAN-5, when it forwards ['plan','finalize'], then the self job argv is 'plan finalize PAN-5'", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "forward-planning-review.ac3", + "title": "Given a review token for PAN-5, when it forwards ['review','spawn-reviewer', ...] naming PAN-5, then a self job starts", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + } + ] + }, + { + "id": "forward-swarm-misc", + "title": "Forward swarm, worker, backlog and knowledge verbs", + "status": "pending", + "priority": "high", + "created": "2026-12-03T20:19:30Z", + "metadata": { + "difficulty": "medium", + "kind": "api", + "issueLabel": "pan-5754", + "requiresInspection": false, + "inspectionDepth": "fast", + "files_scope": [ + "src/dashboard/server/services/self-cli-verbs/swarm.ts", + "src/dashboard/server/services/self-cli-verbs/misc.ts", + "src/dashboard/server/__tests__/self-cli-swarm-misc.test.ts" + ], + "files_scope_confidence": "medium", + "verify_commands": [ + "npx vitest run src/dashboard/server/__tests__/self-cli-swarm-misc.test.ts", + "npm run typecheck" + ], + "expected_outputs": [ + "src/dashboard/server/__tests__/self-cli-swarm-misc.test.ts passes", + "typecheck completes without errors" + ], + "readiness": "ready", + "traces": [ + "FR-7" + ] + }, + "narrative": { + "Action": "PRD WI-19. swarm.ts: 'swarm dispatch|merge|status|wait|resume|recover|freeze', 'foreman' and 'spawn' (role work; issue positional when the subcommand takes one) and 'workspace add-repo' (role work; issue positional; polyrepo work agents run it per the cloister prompt builders). misc.ts: 'worker run' (roles work, plan; issueFlag 'issue'; --brief marked workspacePath; longRunning), 'worker wait' (work, plan; longRunning), 'worker stop' (work, plan); 'swarm wait' in swarm.ts is longRunning; 'backlog write-sequence' (role sequencer), 'knowledge' (role knowledge). Flags per D-7." + }, + "items": [ + { + "id": "forward-swarm-misc.ac1", + "title": "Given a work token for PAN-5, when it forwards ['swarm','dispatch','PAN-5'], then a self job starts running 'pan swarm dispatch PAN-5'", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "forward-swarm-misc.ac2", + "title": "Given a test token, when it forwards ['swarm','merge', ...], then the route returns 403 role-not-allowed", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "forward-swarm-misc.ac3", + "title": "Given a sequencer token, when it forwards ['backlog','write-sequence'], then a self job starts", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "forward-swarm-misc.ac4", + "title": "Given a work token for PAN-5, when it forwards ['worker','run','--issue','PAN-5','--prompt','x y'], then the job argv carries --issue=PAN-5 injected by the server; with --issue PAN-6 the route returns 400", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + } + ] + }, + { + "id": "peer-rule", + "title": "Refuse local trust to connections owned by an isolated process tree", + "status": "pending", + "priority": "high", + "created": "2026-12-03T20:19:30Z", + "metadata": { + "difficulty": "expert", + "kind": "backend", + "issueLabel": "pan-5754", + "requiresInspection": true, + "inspectionDepth": "deep", + "files_scope": [ + "src/lib/agent-isolation/roots.ts", + "src/dashboard/server/isolated-peer.ts", + "src/dashboard/server/routes/dashboard-auth.ts", + "src/dashboard/server/routes/workspace-wake.ts", + "src/dashboard/server/__tests__/isolated-peer.test.ts" + ], + "files_scope_confidence": "medium", + "verify_commands": [ + "npx vitest run src/dashboard/server/__tests__/isolated-peer.test.ts", + "npm run typecheck" + ], + "expected_outputs": [ + "src/dashboard/server/__tests__/isolated-peer.test.ts passes", + "typecheck completes without errors" + ], + "readiness": "ready", + "traces": [ + "FR-9", + "NFR-1", + "NFR-3" + ], + "foundationFor": [ + "traefik-trust", + "launch-isolation" + ], + "acJustification": "Five ACs: the peer rule is a security boundary with a required exception for the PTY supervisor.", + "parallelSafeReason": "Creates isolated-peer.ts and roots.ts and edits dashboard-auth.ts; traefik-trust, which also edits dashboard-auth.ts, is ordered after it by an edge." + }, + "narrative": { + "Action": "PRD WI-20 / D-10. roots.ts: rootRegistrationLauncherLine(rootFile) (bash writing {pid:$$,startTime:} via temp+mv, guarded by [ -r /proc/$$/stat ]) and readLiveRoots (drops+deletes stale). isolated-peer.ts: resolveIsolatedPeer(socket, deps) using fs/promises only: /proc/net/tcp{,6} row -> inode; descendants of live roots via /proc//task//children; match /proc//fd -> socket:[inode]; WeakMap cache per socket; return false fast with no roots or no /proc/net/tcp. dashboard-auth.ts: ensurePeerIdentityFresh also awaits it for an uncredentialed literal-loopback peer and marks the socket; localPeerKind returns null for a marked socket; add isTrustedLocalNodeRequestAsync and use it at workspace-wake.ts. ISOLATED_PEER_SELF_AUTH_ROUTES: POST /api/agents/:id/lifecycle carrying x-overdeck-pty-token skips the rule (the PTY supervisor sits in the isolated tree and its handler checks its own pty-token). Keep dashboard-auth.ts within its file-size count (logic lives in isolated-peer.ts). No execSync." + }, + "items": [ + { + "id": "peer-rule.ac1", + "title": "Given a fake /proc where the connection's inode belongs to a descendant of a live registered root, when resolveIsolatedPeer runs, then it returns true", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "peer-rule.ac2", + "title": "Given a fake /proc where the inode belongs to an unrelated pid, when resolveIsolatedPeer runs, then it returns false", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "peer-rule.ac3", + "title": "Given a root file whose pid start time differs, when readLiveRoots runs, then the entry is ignored and the file is deleted", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "peer-rule.ac4", + "title": "Given a socket marked isolated, when an uncredentialed POST /api/dashboard/session arrives, then the response is 401; given no registered roots, the mint behaves as before and no /proc reads happen", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "peer-rule.ac5", + "title": "Given a socket marked isolated, when POST /api/agents/x/lifecycle arrives with x-overdeck-pty-token, then the gate passes it to the handler (the PTY supervisor keeps recording lifecycle)", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + } + ] + }, + { + "id": "traefik-trust", + "title": "Stop trusting uncredentialed Traefik-forwarded requests while isolation is on", + "status": "pending", + "priority": "high", + "created": "2026-12-03T20:19:30Z", + "metadata": { + "difficulty": "simple", + "kind": "backend", + "issueLabel": "pan-5754", + "requiresInspection": false, + "inspectionDepth": "fast", + "files_scope": [ + "src/dashboard/server/routes/dashboard-auth.ts", + "src/dashboard/server/routes/dashboard-session.ts", + "src/dashboard/server/__tests__/dashboard-auth-isolation.test.ts" + ], + "files_scope_confidence": "high", + "verify_commands": [ + "npx vitest run src/dashboard/server/__tests__/dashboard-auth-isolation.test.ts", + "npm run typecheck" + ], + "expected_outputs": [ + "src/dashboard/server/__tests__/dashboard-auth-isolation.test.ts passes", + "typecheck completes without errors" + ], + "readiness": "ready", + "traces": [ + "FR-10" + ] + }, + "narrative": { + "Action": "PRD WI-21 / D-11. In localPeerKind, when readAgentIsolationConfig().enabled, the traefik branch returns null (cookies still authenticate through resolveDashboardCredential). The session mint answers a Traefik-forwarded uncredentialed request with 401 {error naming http://localhost: and the #overdeck_token= link from pan serve, code:'isolation-sign-in'}." + }, + "items": [ + { + "id": "traefik-trust.ac1", + "title": "Given isolation enabled and a managed-Traefik peer forwarding a local client with no credential, when POST /api/dashboard/session arrives, then the response is 401 with code 'isolation-sign-in'", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "traefik-trust.ac2", + "title": "Given isolation disabled, when the same request arrives, then the session is minted as before", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "traefik-trust.ac3", + "title": "Given isolation enabled and a valid overdeck_session cookie through Traefik, when a GET /api/agents arrives, then it is authorized", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + } + ] + }, + { + "id": "admission-pidns", + "title": "Make gate admission tolerant of PID namespaces", + "status": "pending", + "priority": "high", + "created": "2026-12-03T20:19:30Z", + "metadata": { + "difficulty": "medium", + "kind": "backend", + "issueLabel": "pan-5754", + "requiresInspection": false, + "inspectionDepth": "fast", + "files_scope": [ + "src/lib/cloister/quality-gate-admission.ts", + "src/lib/cloister/quality-gate-admission-pidns.ts", + "tests/unit/lib/cloister/quality-gate-admission.test.ts" + ], + "files_scope_confidence": "medium", + "verify_commands": [ + "npx vitest run tests/unit/lib/cloister/quality-gate-admission.test.ts", + "npm run typecheck" + ], + "expected_outputs": [ + "tests/unit/lib/cloister/quality-gate-admission.test.ts passes", + "typecheck completes without errors" + ], + "readiness": "ready", + "traces": [ + "FR-15" + ] + }, + "narrative": { + "Action": "PRD WI-22 / D-17. Stamp ticket, owner and breaker records with pidNs (readlink /proc/self/ns/pid once per process; undefined off Linux). ownerIsStale and the breaker check treat a record whose pidNs differs from ours as alive until staleMs. Put helpers in quality-gate-admission-pidns.ts if the main file would grow past its count. Use the existing admission test file name; inject isProcessAlive and pidNs, no real timers." + }, + "items": [ + { + "id": "admission-pidns.ac1", + "title": "Given an owner record from another PID namespace younger than staleMs whose pid looks dead locally, when the queue checks staleness, then the owner keeps its slot", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "admission-pidns.ac2", + "title": "Given the same owner older than staleMs, when the queue checks staleness, then the slot is cleared", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "admission-pidns.ac3", + "title": "Given an owner from our own namespace whose pid is dead, when the queue checks staleness, then the slot is cleared as before", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + } + ] + }, + { + "id": "codex-clamp", + "title": "Clamp isolated Codex launches to workspace-write", + "status": "pending", + "priority": "high", + "created": "2026-12-03T20:19:30Z", + "metadata": { + "difficulty": "simple", + "kind": "backend", + "issueLabel": "pan-5754", + "requiresInspection": false, + "inspectionDepth": "fast", + "files_scope": [ + "src/lib/agents/runtime-command.ts", + "src/lib/agents/__tests__/runtime-command-codex.test.ts" + ], + "files_scope_confidence": "medium", + "verify_commands": [ + "npx vitest run src/lib/agents/__tests__/runtime-command-codex.test.ts", + "npm run typecheck" + ], + "expected_outputs": [ + "src/lib/agents/__tests__/runtime-command-codex.test.ts passes", + "typecheck completes without errors" + ], + "readiness": "ready", + "traces": [ + "FR-12" + ] + }, + "narrative": { + "Action": "PRD WI-23 / D-13. Add an optional `isolated = false` parameter to getCodexLauncherFields; when true and codex.permissionMode is 'full-access', use 'workspace' (workspace-write, on-request). Checkpoint CP-5: check `codex sandbox --help` and Codex config docs for a permission profile that denies reads; if one exists, add the D-8 read-deny set through it in initCodexHome, otherwise leave a comment citing CP-5. Use the existing runtime-command test file if one covers getCodexLauncherFields." + }, + "items": [ + { + "id": "codex-clamp.ac1", + "title": "Given isolated true and codex.permissionMode 'full-access', when getCodexLauncherFields runs, then the written config.toml has sandbox_mode = \"workspace-write\"", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "codex-clamp.ac2", + "title": "Given isolated false and 'full-access', when getCodexLauncherFields runs, then sandbox_mode is \"danger-full-access\" as before", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + } + ] + }, + { + "id": "capability-doctor", + "title": "Declare each harness's isolation class and report it in pan doctor", + "status": "pending", + "priority": "high", + "created": "2026-12-03T20:19:30Z", + "metadata": { + "difficulty": "medium", + "kind": "backend", + "issueLabel": "pan-5754", + "requiresInspection": false, + "inspectionDepth": "fast", + "files_scope": [ + "packages/contracts/src/harness-capabilities.ts", + "src/cli/commands/doctor-agent-isolation.ts", + "src/cli/commands/doctor.ts", + "src/cli/commands/__tests__/doctor-agent-isolation.test.ts" + ], + "files_scope_confidence": "high", + "verify_commands": [ + "npx vitest run src/cli/commands/__tests__/doctor-agent-isolation.test.ts", + "npm run typecheck" + ], + "expected_outputs": [ + "src/cli/commands/__tests__/doctor-agent-isolation.test.ts passes", + "typecheck completes without errors" + ], + "readiness": "ready", + "traces": [ + "FR-13" + ] + }, + "narrative": { + "Action": "PRD WI-24 / D-12 / D-14. Add agentIsolation: 'os-sandbox'|'write-sandbox'|'harness-default'|'none' to HarnessCapabilities and set it per the PRD matrix in every capabilities constant. checkAgentIsolation(deps) returns rows: switch on/off; on Linux with Claude Code configured, 'Claude Code sandbox' error naming missing bwrap/socat with fix 'sudo apt-get install bubblewrap socat'; 'Dashboard peer rule' warn on non-Linux; one row per configured harness of class write-sandbox/harness-default/none with the D-14 message; 'Docker access' warn when allow_docker. Add one line in doctor.ts after the checkClaudeCode() line." + }, + "items": [ + { + "id": "capability-doctor.ac1", + "title": "Given Linux with bwrap present and socat missing, when checkAgentIsolation runs, then it returns an 'error' row whose message names socat", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "capability-doctor.ac2", + "title": "Given pi configured as a harness, when checkAgentIsolation runs, then it returns a 'warn' row saying pi has no sandbox", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "capability-doctor.ac3", + "title": "Given agents.isolation.enabled false, when checkAgentIsolation runs, then the first row is 'warn' with message containing 'off'", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "capability-doctor.ac4", + "title": "Given every harness capabilities constant, when typecheck runs, then each declares agentIsolation", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + } + ] + }, + { + "id": "docs", + "title": "Document agent isolation for users and developers", + "status": "pending", + "priority": "high", + "created": "2026-12-03T20:19:30Z", + "metadata": { + "difficulty": "medium", + "kind": "docs", + "issueLabel": "pan-5754", + "requiresInspection": false, + "inspectionDepth": "fast", + "files_scope": [ + "configuration/agent-isolation.mdx", + "docs.json", + "docs/AGENT-ISOLATION.md", + "docs/DASHBOARD-AUTH.md", + "docs/SECURITY-AUDIT-2026-11-29.md", + "configuration/harnesses.mdx", + "CLAUDE.md", + ".overdeck/context/codebase/concerns.md", + "changelog.d/pan-5754.md" + ], + "files_scope_confidence": "high", + "verify_commands": [ + "npm run lint:docs" + ], + "expected_outputs": [ + "lint:docs completes without errors" + ], + "readiness": "ready", + "traces": [ + "FR-16" + ] + }, + "narrative": { + "Action": "PRD WI-25. New configuration/agent-isolation.mdx (linked in docs.json next to configuration/permissions) covering who is isolated, the D-8 reach lists, the per-harness class table, config keys with defaults, bubblewrap/socat prerequisites and the fail-closed launch refusal, signing in on overdeck.localhost (D-11), the Docker opt-in, and residual risks R-1..R-9. New docs/AGENT-ISOLATION.md (architecture, probe table, how to add a forwarded-verb row). Update docs/DASHBOARD-AUTH.md (agent socket, peer rule under rule 4, Traefik change, POST /api/self/cli), docs/SECURITY-AUDIT-2026-11-29.md (F-9/F-4 rows and paragraph), configuration/harnesses.mdx (isolation class), CLAUDE.md (one Key Invariants line + Topic Index row), codebase concerns.md (auto-approve entry; keep its last-verified line), and add changelog.d/pan-5754.md under '#### New'." + }, + "items": [ + { + "id": "docs.ac1", + "title": "Given the docs site config, when docs.json is read, then it lists 'configuration/agent-isolation' and that page names agents.isolation.enabled, allow_docker and allow_write with their defaults", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "docs.ac2", + "title": "Given configuration/agent-isolation.mdx, when read, then it contains a table naming every harness with its class (os-sandbox, write-sandbox, harness-default, none) and lists residual risks R-1 to R-9", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "docs.ac3", + "title": "Given docs/SECURITY-AUDIT-2026-11-29.md, when read, then the F-9 row states it is fixed by PAN-5754 for Claude Code agents and names the residual risks", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "docs.ac4", + "title": "Given changelog.d/pan-5754.md, when npm run lint:docs runs, then it exits 0", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + } + ] + }, + { + "id": "pi-extension-token", + "title": "Make the pi extension authenticate with the agent token", + "status": "pending", + "priority": "high", + "created": "2026-12-03T20:19:30Z", + "metadata": { + "difficulty": "simple", + "kind": "backend", + "issueLabel": "pan-5754", + "requiresInspection": false, + "inspectionDepth": "fast", + "files_scope": [ + "packages/pi-extension/src/index.ts", + "packages/pi-extension/src/__tests__/index.test.ts" + ], + "files_scope_confidence": "high", + "verify_commands": [ + "npx vitest run --config packages/pi-extension/vitest.config.ts packages/pi-extension/src/__tests__/index.test.ts", + "npm run typecheck" + ], + "expected_outputs": [ + "the pi-extension index test passes", + "typecheck completes without errors" + ], + "readiness": "ready", + "traces": [ + "FR-2", + "FR-17" + ] + }, + "narrative": { + "Action": "PRD WI-26 / D-19. In packages/pi-extension/src/index.ts the token read (anchor `const token = (await readFile(join(overdeckHome, 'internal-token'), 'utf8')).trim()`) first checks process.env.OVERDECK_AGENT_TOKEN_FILE; when set it reads that file, sends Authorization: Bearer on every dashboard post (postWithTimeout, postJsonWithTimeout, postDashboard) and never reads internal-token; otherwise unchanged." + }, + "items": [ + { + "id": "pi-extension-token.ac1", + "title": "Given OVERDECK_AGENT_TOKEN_FILE set, when the extension posts a heartbeat, then the request carries 'Authorization: Bearer odk_' and no x-overdeck-internal-token header", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "pi-extension-token.ac2", + "title": "Given OVERDECK_AGENT_TOKEN_FILE unset, when the extension posts a heartbeat, then it sends the x-overdeck-internal-token header as before", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + } + ] + }, + { + "id": "pi-routes-self-auth", + "title": "Let the pi extension's control-ack and auto-complete routes accept a self agent token", + "status": "pending", + "priority": "high", + "created": "2026-12-03T20:19:30Z", + "metadata": { + "difficulty": "medium", + "kind": "api", + "issueLabel": "pan-5754", + "requiresInspection": false, + "inspectionDepth": "fast", + "files_scope": [ + "src/dashboard/server/routes/conversations.ts", + "src/dashboard/server/routes/specialists/legacy-routes.ts", + "src/dashboard/server/__tests__/pi-routes-self-auth.test.ts" + ], + "files_scope_confidence": "medium", + "verify_commands": [ + "npx vitest run src/dashboard/server/__tests__/pi-routes-self-auth.test.ts", + "npm run typecheck" + ], + "expected_outputs": [ + "src/dashboard/server/__tests__/pi-routes-self-auth.test.ts passes", + "typecheck completes without errors" + ], + "readiness": "ready", + "traces": [ + "FR-8", + "FR-17" + ] + }, + "narrative": { + "Action": "PRD WI-27. conversations.ts control-ack (anchor '/api/conversations/:name/control-ack', line ~741): authorizeInternalOrSelfAgent with subject :name (agent id, or the conversation's tmux session). specialists/legacy-routes.ts auto-complete (anchor '/api/specialists/:name/auto-complete', line ~601): an agent token passes only with role review or test and when the body issue equals the token agent's issue; other credentials keep today's check. Note in the docs item that classify-completion (runtime-events.ts ~173, no handler auth) is admitted by its new 'tell' row." + }, + "items": [ + { + "id": "pi-routes-self-auth.ac1", + "title": "Given agent A's token, when it posts control-ack for agent B, then the response is 403 with code 'not-self'", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "pi-routes-self-auth.ac2", + "title": "Given a work-role token, when it posts /api/specialists/review-agent/auto-complete, then the response is 403", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "pi-routes-self-auth.ac3", + "title": "Given a review-role token for its own issue, when it posts auto-complete for that issue, then the request is accepted", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + } + ] + }, + { + "id": "verb-coverage", + "title": "Prove every agent-facing pan verb is forwarded or known-local", + "status": "pending", + "priority": "high", + "created": "2026-12-03T20:19:30Z", + "metadata": { + "difficulty": "medium", + "kind": "test", + "issueLabel": "pan-5754", + "requiresInspection": false, + "inspectionDepth": "fast", + "files_scope": [ + "src/dashboard/server/__tests__/self-cli-coverage.test.ts" + ], + "files_scope_confidence": "high", + "verify_commands": [ + "npx vitest run src/dashboard/server/__tests__/self-cli-coverage.test.ts", + "npm run typecheck" + ], + "expected_outputs": [ + "src/dashboard/server/__tests__/self-cli-coverage.test.ts passes", + "typecheck completes without errors" + ], + "readiness": "ready", + "traces": [ + "FR-7", + "NFR-4" + ] + }, + "narrative": { + "Action": "PRD WI-28. A data table lists every pan verb isolated roles are told to run (roles/*.md, src/lib/cloister/*prompt*.ts, and the skills pan-task, pan-done, pan-tell, pan-worker, pan-foreman, pan-memory, pan-handoff, pan-sync-main, pan-plan) with disposition forwarded: or local-read. local-read is allowed only for read-only verbs (task show/next, show, status, memory search/show/list/read, conv pending/current/list/show/whoami, worker list, lane reads). For each forwarded verb assert matchSelfCliVerb finds a row allowing the listed roles. The table is test data, not a source scan (NFR-4)." + }, + "items": [ + { + "id": "verb-coverage.ac1", + "title": "Given the coverage table, when the test runs, then every 'forwarded' verb (incl. tell, ask, sync-main, review request, plan finalize, admin specialists done, review spawn-reviewer, swarm dispatch, spawn, foreman, workspace add-repo, worker run, backlog write-sequence) resolves to a row allowing its listed roles", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "verb-coverage.ac2", + "title": "Given the coverage table, when the test runs, then no verb with a mutating effect is marked local-read", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + } + ] + }, + { + "id": "launch-sites-runtimes", + "title": "Prepare isolation inside every runtime spawnAgent (crash recovery, rotation, Codex and the other runtimes)", + "status": "pending", + "priority": "high", + "created": "2026-12-03T20:19:30Z", + "metadata": { + "difficulty": "complex", + "kind": "backend", + "issueLabel": "pan-5754", + "requiresInspection": false, + "inspectionDepth": "fast", + "files_scope": [ + "src/lib/runtimes/claude-code.ts", + "src/lib/runtimes/codex.ts", + "src/lib/runtimes/ohmypi.ts", + "src/lib/runtimes/pi.ts", + "src/lib/runtimes/muse.ts", + "src/lib/runtimes/kimi-code.ts", + "src/lib/runtimes/prime-agent.ts", + "src/lib/runtimes/acp.ts", + "src/lib/cloister/__tests__/isolation-runtime-launch.test.ts" + ], + "files_scope_confidence": "medium", + "verify_commands": [ + "npx vitest run src/lib/cloister/__tests__/isolation-runtime-launch.test.ts", + "npm run typecheck" + ], + "expected_outputs": [ + "src/lib/cloister/__tests__/isolation-runtime-launch.test.ts passes", + "typecheck completes without errors" + ], + "readiness": "ready", + "traces": [ + "FR-1", + "FR-4", + "FR-12" + ], + "parallelSafeReason": "Edits only src/lib/runtimes/* spawn implementations, which no other item touches; it runs after launch-isolation and codex-clamp by edges." + }, + "narrative": { + "Action": "PRD WI-29. Crash recovery (src/lib/cloister/service-crash.ts ~433) and session rotation (src/lib/cloister/session-rotation.ts ~249) call runtime.spawnAgent directly. In every runtime spawnAgent implementation call prepareAgentIsolation for the spawn owner, reusing an isolation value the caller already passed (no double mint). Generator-based runtimes pass it to generateLauncherScript; the Codex runtime (runtimes/codex.ts ~674-699, own command) emits the same export/unset/root-registration lines and applies the D-13 clamp. remote-agents.ts (Fly VMs) is out of scope; checkpoint CP-7: confirm the Fly VM holds no copy of the host internal-token, else file a follow-up issue linked from docs/AGENT-ISOLATION.md." + }, + "items": [ + { + "id": "launch-sites-runtimes.ac1", + "title": "Given an isolated work agent restarted through service-crash.ts, when the runtime launches it, then the launch exports OVERDECK_AGENT_TOKEN_FILE", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "launch-sites-runtimes.ac2", + "title": "Given an isolated work agent rotated through session-rotation.ts, when the runtime launches it, then the launch exports OVERDECK_AGENT_TOKEN_FILE", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + }, + { + "id": "launch-sites-runtimes.ac3", + "title": "Given an isolated agent spawned through the Codex runtime with codex.permissionMode full-access, when it launches, then the Codex config has sandbox_mode = \"workspace-write\" and the command unsets OVERDECK_INTERNAL_TOKEN", + "status": "pending", + "metadata": { + "kind": "acceptance_criterion" + } + } + ] + } + ], + "edges": [ + { + "from": "iso-config", + "to": "token-location", + "type": "blocks" + }, + { + "from": "iso-config", + "to": "iso-policy", + "type": "blocks" + }, + { + "from": "iso-config", + "to": "launch-isolation", + "type": "blocks" + }, + { + "from": "iso-config", + "to": "agent-socket", + "type": "blocks" + }, + { + "from": "iso-config", + "to": "cli-credential", + "type": "blocks" + }, + { + "from": "iso-config", + "to": "peer-rule", + "type": "blocks" + }, + { + "from": "iso-config", + "to": "traefik-trust", + "type": "blocks" + }, + { + "from": "iso-config", + "to": "codex-clamp", + "type": "blocks" + }, + { + "from": "iso-config", + "to": "capability-doctor", + "type": "blocks" + }, + { + "from": "token-location", + "to": "launch-isolation", + "type": "blocks" + }, + { + "from": "iso-policy", + "to": "claude-settings", + "type": "blocks" + }, + { + "from": "iso-policy", + "to": "write-guard-hook", + "type": "blocks" + }, + { + "from": "iso-policy", + "to": "launch-isolation", + "type": "blocks" + }, + { + "from": "claude-settings", + "to": "launch-isolation", + "type": "blocks" + }, + { + "from": "peer-rule", + "to": "launch-isolation", + "type": "blocks" + }, + { + "from": "peer-rule", + "to": "traefik-trust", + "type": "blocks" + }, + { + "from": "launch-isolation", + "to": "launch-sites-runtimes", + "type": "blocks" + }, + { + "from": "codex-clamp", + "to": "launch-sites-runtimes", + "type": "blocks" + }, + { + "from": "launch-isolation", + "to": "launch-sites-agents", + "type": "blocks" + }, + { + "from": "launch-isolation", + "to": "launch-sites-planning-conv", + "type": "blocks" + }, + { + "from": "codex-clamp", + "to": "launch-sites-agents", + "type": "blocks" + }, + { + "from": "cli-credential", + "to": "cli-callers", + "type": "blocks" + }, + { + "from": "cli-credential", + "to": "in-pane-callers", + "type": "blocks" + }, + { + "from": "cli-credential", + "to": "self-cli-route", + "type": "blocks" + }, + { + "from": "self-auth-routes", + "to": "pi-routes-self-auth", + "type": "blocks" + }, + { + "from": "forward-messaging", + "to": "verb-coverage", + "type": "blocks" + }, + { + "from": "forward-planning-review", + "to": "verb-coverage", + "type": "blocks" + }, + { + "from": "forward-swarm-misc", + "to": "verb-coverage", + "type": "blocks" + }, + { + "from": "self-cli-route", + "to": "forward-messaging", + "type": "blocks" + }, + { + "from": "self-cli-route", + "to": "forward-planning-review", + "type": "blocks" + }, + { + "from": "self-cli-route", + "to": "forward-swarm-misc", + "type": "blocks" + } + ] + }, + "status": "proposed" +} \ No newline at end of file From 8548111fea574ac3d1de0f626ffd6662b42c29f9 Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 16:28:28 -0500 Subject: [PATCH 002/129] chore(workspace): plan artifacts for PAN-5754 Overdeck-Agent: agent-pan-5754 --- .pan/continues/PAN-5754.xbrief.json | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 .pan/continues/PAN-5754.xbrief.json diff --git a/.pan/continues/PAN-5754.xbrief.json b/.pan/continues/PAN-5754.xbrief.json new file mode 100644 index 00000000000..1d52bcea7aa --- /dev/null +++ b/.pan/continues/PAN-5754.xbrief.json @@ -0,0 +1,18 @@ +{ + "version": "1", + "issueId": "PAN-5754", + "created": "2026-12-03T21:28:28.525Z", + "updated": "2026-12-03T21:28:28.525Z", + "gitState": {}, + "decisions": [], + "hazards": [], + "resumePoint": null, + "sessionHistory": [], + "items": { + "iso-config": { + "status": "in_progress", + "claimedBy": "agent-pan-5754", + "claimedAt": "2026-12-03T21:28:28.525Z" + } + } +} From 2501084555c0ae43599eababa65958499d658b9e Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 16:35:23 -0500 Subject: [PATCH 003/129] feat(infra): add agents.isolation config and the isolated-role predicate PAN-5754 WI-1. agents.isolation.{enabled, allow_docker, allow_write} is read from the global config.yaml only (loadGlobalConfig is now exported for that); stripProjectSecurity drops agents.isolation from .pan.yaml and keeps the other agents keys. isIsolatedTokenRole is false only for conversation and flywheel. paths.ts holds the agent-tokens, isolation and agent-socket locations and the isolation env var names. Item: iso-config Item: iso-config.ac1 Item: iso-config.ac2 Item: iso-config.ac3 Item: iso-config.ac4 Item: iso-config.ac5 Co-Authored-By: Claude Opus 5.5 Overdeck-Agent: agent-pan-5754 --- .../agent-isolation/__tests__/config.test.ts | 86 +++++++++++++++++++ src/lib/agent-isolation/config.ts | 79 +++++++++++++++++ src/lib/agent-isolation/paths.ts | 45 ++++++++++ src/lib/config-yaml/load.ts | 12 ++- src/lib/config-yaml/schema-agent-isolation.ts | 12 +++ src/lib/config-yaml/schema.ts | 1 + 6 files changed, 233 insertions(+), 2 deletions(-) create mode 100644 src/lib/agent-isolation/__tests__/config.test.ts create mode 100644 src/lib/agent-isolation/config.ts create mode 100644 src/lib/agent-isolation/paths.ts create mode 100644 src/lib/config-yaml/schema-agent-isolation.ts diff --git a/src/lib/agent-isolation/__tests__/config.test.ts b/src/lib/agent-isolation/__tests__/config.test.ts new file mode 100644 index 00000000000..7628f36b68c --- /dev/null +++ b/src/lib/agent-isolation/__tests__/config.test.ts @@ -0,0 +1,86 @@ +import { homedir } from 'node:os'; +import { join } from 'node:path'; +import { describe, expect, it, vi } from 'vitest'; + +import { stripProjectSecurity } from '../../config-yaml/load.js'; +import type { AgentTokenRole } from '../../mcp/agent-token.js'; +import { isAgentIsolationActive, isIsolatedTokenRole, readAgentIsolationConfig } from '../config.js'; + +describe('isIsolatedTokenRole (PAN-5754 D-1)', () => { + const isolated: AgentTokenRole[] = ['work', 'worker', 'plan', 'strike', 'sequencer', 'knowledge', 'review', 'test', 'ship']; + + it.each(isolated)('isolates token role %s', (role) => { + expect(isIsolatedTokenRole(role)).toBe(true); + }); + + it.each(['conversation', 'flywheel'] as AgentTokenRole[])('does not isolate token role %s', (role) => { + expect(isIsolatedTokenRole(role)).toBe(false); + }); +}); + +describe('readAgentIsolationConfig (PAN-5754 D-2, FR-14)', () => { + it('defaults to enabled with no docker and no extra writes', () => { + expect(readAgentIsolationConfig({})).toEqual({ enabled: true, allowDocker: false, allowWrite: [] }); + expect(readAgentIsolationConfig(null)).toEqual({ enabled: true, allowDocker: false, allowWrite: [] }); + }); + + it('reads enabled and allow_docker', () => { + expect(readAgentIsolationConfig({ agents: { isolation: { enabled: false, allow_docker: true } } })).toEqual({ + enabled: false, + allowDocker: true, + allowWrite: [], + }); + }); + + it('expands ~ and drops a relative allow_write path with exactly one warning', () => { + const warn = vi.fn(); + const result = readAgentIsolationConfig({ agents: { isolation: { allow_write: ['~/x', 'rel/y'] } } }, warn); + expect(result.allowWrite).toEqual([join(homedir(), 'x')]); + expect(warn).toHaveBeenCalledTimes(1); + expect(warn.mock.calls[0]![0]).toContain('rel/y'); + }); + + it('keeps an absolute allow_write path', () => { + const warn = vi.fn(); + expect(readAgentIsolationConfig({ agents: { isolation: { allow_write: ['/srv/data'] } } }, warn).allowWrite).toEqual(['/srv/data']); + expect(warn).not.toHaveBeenCalled(); + }); + + it('throws on a non-boolean enabled value', () => { + // @ts-expect-error — exercising runtime validation of bad input + expect(() => readAgentIsolationConfig({ agents: { isolation: { enabled: 'no' } } })).toThrow( + /agents\.isolation\.enabled must be true or false/, + ); + }); + + it('throws when allow_write is not a list of strings', () => { + // @ts-expect-error — exercising runtime validation of bad input + expect(() => readAgentIsolationConfig({ agents: { isolation: { allow_write: '/srv' } } })).toThrow( + /allow_write must be a list/, + ); + }); +}); + +describe('isAgentIsolationActive', () => { + it('is false for an isolated role when the switch is off', () => { + expect(isAgentIsolationActive('work', { agents: { isolation: { enabled: false } } })).toBe(false); + }); + + it('is true for an isolated role by default and false for a conversation', () => { + expect(isAgentIsolationActive('work', {})).toBe(true); + expect(isAgentIsolationActive('conversation', {})).toBe(false); + }); +}); + +describe('stripProjectSecurity drops agents.isolation (PAN-5754 D-2)', () => { + it('removes agents.isolation and keeps agents.rtk', () => { + const stripped = stripProjectSecurity({ agents: { isolation: { enabled: false }, rtk: { enabled: true } } }); + expect(stripped?.agents).toEqual({ rtk: { enabled: true } }); + expect(stripped?.agents && 'isolation' in stripped.agents).toBe(false); + }); + + it('leaves a config without agents.isolation untouched', () => { + const config = { agents: { caveman: { enabled: true } } }; + expect(stripProjectSecurity(config)).toEqual(config); + }); +}); diff --git a/src/lib/agent-isolation/config.ts b/src/lib/agent-isolation/config.ts new file mode 100644 index 00000000000..8ca4b05c03b --- /dev/null +++ b/src/lib/agent-isolation/config.ts @@ -0,0 +1,79 @@ +/** + * PAN-5754: the `agents.isolation` switch and the one isolated-role predicate. + * + * D-1: an isolated agent is a launch whose token role is neither `conversation` + * nor `flywheel`. D-2: `agents.isolation.enabled` is read from the global + * config.yaml only and defaults to true. + */ +import { homedir } from 'node:os'; +import { isAbsolute, join } from 'node:path'; +import { loadGlobalConfig } from '../config-yaml/load.js'; +import type { YamlConfig } from '../config-yaml/schema.js'; +import type { AgentTokenRole } from '../mcp/agent-token.js'; + +export interface ResolvedAgentIsolationConfig { + enabled: boolean; + allowDocker: boolean; + allowWrite: string[]; +} + +function readBoolean(value: unknown, key: string, fallback: boolean): boolean { + if (value === undefined) return fallback; + if (typeof value !== 'boolean') { + throw new Error(`config.yaml: agents.isolation.${key} must be true or false (got: ${String(value)})`); + } + return value; +} + +function expandHome(path: string): string { + if (path === '~') return homedir(); + return path.startsWith('~/') ? join(homedir(), path.slice(2)) : path; +} + +/** + * Resolve `agents.isolation` from a raw config layer (the global config.yaml by default). + * A non-boolean switch or a non-list `allow_write` throws: a malformed security switch + * never silently turns isolation off. A relative `allow_write` entry is dropped with a warning. + */ +export function readAgentIsolationConfig( + config: YamlConfig | null = loadGlobalConfig(), + warn: (message: string) => void = (message) => console.warn(message), +): ResolvedAgentIsolationConfig { + const raw: unknown = config?.agents?.isolation; + if (raw === undefined || raw === null) return { enabled: true, allowDocker: false, allowWrite: [] }; + if (typeof raw !== 'object' || Array.isArray(raw)) { + throw new Error('config.yaml: agents.isolation must be a mapping'); + } + const block = raw as Record; + const allowWriteRaw = block.allow_write ?? []; + if (!Array.isArray(allowWriteRaw) || allowWriteRaw.some((entry) => typeof entry !== 'string')) { + throw new Error('config.yaml: agents.isolation.allow_write must be a list of paths'); + } + const allowWrite: string[] = []; + for (const entry of allowWriteRaw as string[]) { + const expanded = expandHome(entry); + if (isAbsolute(expanded)) { + allowWrite.push(expanded); + } else { + warn(`[overdeck] agents.isolation.allow_write: ignoring relative path '${entry}' (use an absolute or ~/ path)`); + } + } + return { + enabled: readBoolean(block.enabled, 'enabled', true), + allowDocker: readBoolean(block.allow_docker, 'allow_docker', false), + allowWrite, + }; +} + +/** D-1: the one predicate. Operator conversations and the Flywheel keep the operator credential. */ +export function isIsolatedTokenRole(role: AgentTokenRole): boolean { + return role !== 'conversation' && role !== 'flywheel'; +} + +/** The config switch AND the role check. */ +export function isAgentIsolationActive( + role: AgentTokenRole, + config: YamlConfig | null = loadGlobalConfig(), +): boolean { + return isIsolatedTokenRole(role) && readAgentIsolationConfig(config).enabled; +} diff --git a/src/lib/agent-isolation/paths.ts b/src/lib/agent-isolation/paths.ts new file mode 100644 index 00000000000..3700c9de3da --- /dev/null +++ b/src/lib/agent-isolation/paths.ts @@ -0,0 +1,45 @@ +/** + * PAN-5754: filesystem locations and env var names for agent isolation. + * A dependency leaf: it imports only `node:path` and `../paths.js`. + */ +import { join } from 'node:path'; +import { getOverdeckHome } from '../paths.js'; + +/** Path of the calling agent's own token file; set only for isolated launches (D-3). */ +export const OVERDECK_AGENT_TOKEN_FILE = 'OVERDECK_AGENT_TOKEN_FILE'; +/** Path of the agent socket the isolated CLI connects to (D-6). */ +export const OVERDECK_DASHBOARD_SOCKET = 'OVERDECK_DASHBOARD_SOCKET'; +/** `1` in an isolated launch's environment. */ +export const OVERDECK_ISOLATED = 'OVERDECK_ISOLATED'; + +export type AgentIsolationOwnerKind = 'agent' | 'conversation'; + +/** `/agent-tokens`: every agent token lives below it (D-4). */ +export function agentTokensDir(): string { + return join(getOverdeckHome(), 'agent-tokens'); +} + +/** `/agent-tokens//`: one owner's token directory. */ +export function agentTokenDir(kind: AgentIsolationOwnerKind, id: string): string { + return join(agentTokensDir(), kind, id); +} + +/** `/isolation`: rendered policies, settings files and the root registry. */ +export function isolationDir(): string { + return join(getOverdeckHome(), 'isolation'); +} + +/** `/isolation//`: one owner's rendered isolation files. */ +export function isolationOwnerDir(kind: AgentIsolationOwnerKind, id: string): string { + return join(isolationDir(), kind, id); +} + +/** `/isolation/roots`: one `.json` per live isolated launcher (D-10). */ +export function isolationRootsDir(): string { + return join(isolationDir(), 'roots'); +} + +/** `/agent-api/dashboard.sock`: the dashboard's credential-only Unix socket (D-6). */ +export function agentApiSocketPath(): string { + return join(getOverdeckHome(), 'agent-api', 'dashboard.sock'); +} diff --git a/src/lib/config-yaml/load.ts b/src/lib/config-yaml/load.ts index 7f38b3588d6..4045fbaff9d 100644 --- a/src/lib/config-yaml/load.ts +++ b/src/lib/config-yaml/load.ts @@ -84,13 +84,21 @@ export function stripProjectTtsEndpoint(config: YamlConfig | null): YamlConfig | export function stripProjectSecurity(config: YamlConfig | null): YamlConfig | null { if (!config) return config; // PAN-5108: harness CLI auto-update is machine-wide; a project file never sets it. - const { security: _security, harnesses: _harnesses, computer_use: _computerUse, ...rest } = config; + const { security: _security, harnesses: _harnesses, computer_use: _computerUse, ...stripped } = config; + // PAN-5754 D-2: agent isolation is the operator's switch; an agent can commit a .pan.yaml. + const rest = stripAgentIsolation(stripped); // PAN-4947 D-2: public MCP (Tailscale Funnel) is operator-only too. if (rest.mcp?.public === undefined) return rest; const { public: _public, ...mcp } = rest.mcp; return { ...rest, mcp }; } +function stripAgentIsolation(config: YamlConfig): YamlConfig { + if (config.agents?.isolation === undefined) return config; + const { isolation: _isolation, ...agents } = config.agents; + return { ...config, agents }; +} + /** * Load per-project config (.pan.yaml in project root, with fallback to .overdeck.yaml) */ @@ -119,7 +127,7 @@ function loadProjectConfig(): YamlConfig | null { /** * Load global config (~/.overdeck/config.yaml) */ -function loadGlobalConfig(): YamlConfig | null { +export function loadGlobalConfig(): YamlConfig | null { return loadYamlFile(GLOBAL_CONFIG_PATH); } diff --git a/src/lib/config-yaml/schema-agent-isolation.ts b/src/lib/config-yaml/schema-agent-isolation.ts new file mode 100644 index 00000000000..7bca9d6aa08 --- /dev/null +++ b/src/lib/config-yaml/schema-agent-isolation.ts @@ -0,0 +1,12 @@ +/** + * Raw `agents.isolation:` block in ~/.overdeck/config.yaml (PAN-5754 D-2). + * Global layer only: `stripProjectSecurity` drops it from `.pan.yaml`. + */ +export interface AgentIsolationConfig { + /** Master switch. Default true; false launches every agent unisolated, as before PAN-5754. */ + enabled?: boolean; + /** Leave the Docker socket reachable from an isolated agent's sandbox. Default false. */ + allow_docker?: boolean; + /** Extra writable paths for isolated agents. Absolute or `~`-prefixed; relative paths are dropped. */ + allow_write?: string[]; +} diff --git a/src/lib/config-yaml/schema.ts b/src/lib/config-yaml/schema.ts index 8b909aae6d9..e4303dde221 100644 --- a/src/lib/config-yaml/schema.ts +++ b/src/lib/config-yaml/schema.ts @@ -620,6 +620,7 @@ export interface YamlConfig { caveman?: CavemanConfig; /** RTK Bash output compression configuration */ rtk?: RtkConfig; + isolation?: import('./schema-agent-isolation.js').AgentIsolationConfig; }; /** TTS configuration */ From a3f0ea9d851eee9790fc1bac080e7765e17e57d9 Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 16:36:05 -0500 Subject: [PATCH 004/129] chore(workspace): plan artifacts for PAN-5754 Overdeck-Agent: agent-pan-5754 --- .pan/continues/PAN-5754.xbrief.json | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/.pan/continues/PAN-5754.xbrief.json b/.pan/continues/PAN-5754.xbrief.json index 1d52bcea7aa..23aa1b1090f 100644 --- a/.pan/continues/PAN-5754.xbrief.json +++ b/.pan/continues/PAN-5754.xbrief.json @@ -2,7 +2,7 @@ "version": "1", "issueId": "PAN-5754", "created": "2026-12-03T21:28:28.525Z", - "updated": "2026-12-03T21:28:28.525Z", + "updated": "2026-12-03T21:36:05.380Z", "gitState": {}, "decisions": [], "hazards": [], @@ -10,9 +10,30 @@ "sessionHistory": [], "items": { "iso-config": { - "status": "in_progress", + "status": "completed", "claimedBy": "agent-pan-5754", - "claimedAt": "2026-12-03T21:28:28.525Z" + "claimedAt": "2026-12-03T21:28:28.525Z", + "doneAt": "2026-12-03T21:36:05.380Z" + }, + "iso-config.ac1": { + "status": "completed", + "doneAt": "2026-12-03T21:36:05.380Z" + }, + "iso-config.ac2": { + "status": "completed", + "doneAt": "2026-12-03T21:36:05.380Z" + }, + "iso-config.ac3": { + "status": "completed", + "doneAt": "2026-12-03T21:36:05.380Z" + }, + "iso-config.ac4": { + "status": "completed", + "doneAt": "2026-12-03T21:36:05.380Z" + }, + "iso-config.ac5": { + "status": "completed", + "doneAt": "2026-12-03T21:36:05.380Z" } } } From 9d659dada77be49e8dc4ba16e1a36fa16c5b3ce8 Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 16:36:26 -0500 Subject: [PATCH 005/129] chore(workspace): plan artifacts for PAN-5754 Overdeck-Agent: agent-pan-5754 --- .pan/continues/PAN-5754.xbrief.json | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/.pan/continues/PAN-5754.xbrief.json b/.pan/continues/PAN-5754.xbrief.json index 23aa1b1090f..28403895819 100644 --- a/.pan/continues/PAN-5754.xbrief.json +++ b/.pan/continues/PAN-5754.xbrief.json @@ -2,7 +2,7 @@ "version": "1", "issueId": "PAN-5754", "created": "2026-12-03T21:28:28.525Z", - "updated": "2026-12-03T21:36:05.380Z", + "updated": "2026-12-03T21:36:26.225Z", "gitState": {}, "decisions": [], "hazards": [], @@ -34,6 +34,11 @@ "iso-config.ac5": { "status": "completed", "doneAt": "2026-12-03T21:36:05.380Z" + }, + "token-location": { + "status": "in_progress", + "claimedBy": "agent-pan-5754", + "claimedAt": "2026-12-03T21:36:26.224Z" } } } From ff7ae46cd581a4ad617a8445b1b60868033e0274 Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 16:48:36 -0500 Subject: [PATCH 006/129] feat(infra): move agent tokens under agent-tokens/ and add a fail-closed isolation mint PAN-5754 WI-2. An owner's token now lives at /agent-tokens///mcp-token (directory 0700, file 0600), so the sandbox can deny agent-tokens/ and re-allow only the owner's own directory. agentMcpTokenPath(dir) becomes agentMcpTokenPathFor({ agentId, agentKind }), which refuses an owner id that is not one path segment. Revoke unlinks the new file and the legacy /mcp-token. ensureIsolationToken mints regardless of the MCP switch and rethrows a failure as 'agent isolation: token mint failed for : ...'. Tests that asserted the old /mcp-token location now assert the new one. Item: token-location Item: token-location.ac1 Item: token-location.ac2 Item: token-location.ac3 Co-Authored-By: Claude Opus 5.5 Overdeck-Agent: agent-pan-5754 --- .../__tests__/agents-spawn-supervisor.test.ts | 4 +- src/lib/mcp/agent-injection.ts | 6 +- src/lib/mcp/agent-token.ts | 66 ++++++++++++----- .../conversation-runtime-launch.test.ts | 2 +- .../spawn-planning-session-backend.test.ts | 2 +- .../lib/mcp/agent-injection-launch.test.ts | 4 +- tests/unit/lib/mcp/agent-injection.test.ts | 8 +-- tests/unit/lib/mcp/agent-token.test.ts | 70 ++++++++++++++----- 8 files changed, 112 insertions(+), 50 deletions(-) diff --git a/src/lib/__tests__/agents-spawn-supervisor.test.ts b/src/lib/__tests__/agents-spawn-supervisor.test.ts index debce02a575..07ce8531f80 100644 --- a/src/lib/__tests__/agents-spawn-supervisor.test.ts +++ b/src/lib/__tests__/agents-spawn-supervisor.test.ts @@ -651,7 +651,7 @@ describe('spawnAgent PTY supervisor wiring', () => { const call = initCodexHomeMock.mock.calls.find(([, opts]) => (opts as { mcpServers?: Record })?.mcpServers?.overdeck); expect(call).toBeDefined(); const overdeck = (call![1] as { mcpServers: Record; defaultToolsApprovalMode: string }> }).mcpServers.overdeck; - expect(overdeck.env.OVERDECK_MCP_TOKEN_FILE).toBe(join(tmpHome, 'agents', state.id, 'mcp-token')); + expect(overdeck.env.OVERDECK_MCP_TOKEN_FILE).toBe(join(tmpHome, 'agent-tokens', 'agent', state.id, 'mcp-token')); expect(overdeck.defaultToolsApprovalMode).toBe('approve'); const tokens = await listAccessTokens(); @@ -667,7 +667,7 @@ describe('spawnAgent PTY supervisor wiring', () => { const call = initCodexHomeMock.mock.calls.find(([, opts]) => (opts as { mcpServers?: Record })?.mcpServers?.overdeck); expect(call).toBeDefined(); const overdeck = (call![1] as { mcpServers: Record }> }).mcpServers.overdeck; - expect(overdeck.env.OVERDECK_MCP_TOKEN_FILE).toBe(join(tmpHome, 'agents', state.id, 'mcp-token')); + expect(overdeck.env.OVERDECK_MCP_TOKEN_FILE).toBe(join(tmpHome, 'agent-tokens', 'agent', state.id, 'mcp-token')); const tokens = await listAccessTokens(); expect(tokens.filter((t) => t.agentId === state.id && t.role === 'review' && !t.revokedAt)).toHaveLength(1); diff --git a/src/lib/mcp/agent-injection.ts b/src/lib/mcp/agent-injection.ts index 71c708bcda4..4990e1a8844 100644 --- a/src/lib/mcp/agent-injection.ts +++ b/src/lib/mcp/agent-injection.ts @@ -4,8 +4,8 @@ * * Every launch site spreads `await prepareClaudeOverdeckMcp(owner)` into its * `generateLauncherScript` config. The helper mints (or reuses) the owner's agent - * token, writes `/overdeck-mcp.json` next to `/mcp-token`, and returns - * its path. The config names only the token file; the token never leaves `mcp-token`. + * token (in `/agent-tokens///mcp-token`, PAN-5754 D-4), writes + * `/overdeck-mcp.json`, and returns its path. The config names only the token file; the token never leaves `mcp-token`. * It returns `{}` when injection is off and never throws: a failed mint starts the * agent without the server and logs one warning. * The file is Claude Code's `--mcp-config` format; the ACP host reads the same file and converts it (PAN-4934). @@ -141,7 +141,7 @@ async function mintOverdeckTokenFile(owner: OverdeckMcpLaunchOwner): Promise<{ d if (!(await overdeckMcpEnabledFor(owner.harness))) return null; const dir = launchDir(owner); if (dir === undefined) throw new Error('a conversation launch needs its state dir'); - const { tokenFile } = await ensureAgentMcpToken({ agentId: owner.agentId, agentKind: owner.agentKind, role: owner.role, dir }); + const { tokenFile } = await ensureAgentMcpToken({ agentId: owner.agentId, agentKind: owner.agentKind, role: owner.role }); return { dir, tokenFile }; } diff --git a/src/lib/mcp/agent-token.ts b/src/lib/mcp/agent-token.ts index 7535155fa9f..d68c27852b6 100644 --- a/src/lib/mcp/agent-token.ts +++ b/src/lib/mcp/agent-token.ts @@ -4,18 +4,22 @@ * * Each managed agent or conversation (the owner) holds at most one active * `kind: 'token'` record that names it through `agentId`, `agentKind` and - * `role`. Its plaintext lives only in `/mcp-token` (mode 0600). The + * `role`. Its plaintext lives only in + * `/agent-tokens///mcp-token` (mode 0600, PAN-5754 D-4), + * outside the owner's state dir, so an isolated agent's sandbox can hide every + * other owner's token by denying `agent-tokens/` and re-allowing its own. The * scopes come from `AGENT_TOKEN_SCOPES` and never include `admin`, `forward`, * `read:settings` or `read:costs`. * - * `ensureAgentMcpToken` is the only helper that throws. The revoke helpers run + * `ensureAgentMcpToken` and `ensureIsolationToken` are the only helpers that throw. The revoke helpers run * on stop paths, so they log one warning and resolve on any failure. Log lines * name the agent id and token id, never the token. */ import { randomUUID } from 'node:crypto'; import { mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises'; -import { join } from 'node:path'; +import { dirname, join } from 'node:path'; +import { agentTokenDir } from '../agent-isolation/paths.js'; import { createAccessToken, listAccessTokens, @@ -57,12 +61,6 @@ export interface AgentTokenOwner { agentId: string; agentKind: 'agent' | 'conversation'; role: AgentTokenRole; - dir: string; -} - -/** `/mcp-token`. W-INJ1 uses this to name the file in MCP configs. */ -export function agentMcpTokenPath(dir: string): string { - return join(dir, AGENT_TOKEN_FILE); } /** D-2: an agent owner's id is normalized (`PAN-1` → `agent-pan-1`); a conversation name is kept as is. */ @@ -70,6 +68,23 @@ function ownerId(agentId: string, agentKind: 'agent' | 'conversation'): string { return agentKind === 'agent' ? normalizeAgentId(agentId) : agentId; } +/** PAN-5754 D-4: the owner id names one directory under `agent-tokens//`; refuse anything else. */ +function tokenDirSegment(id: string): string { + if (!id || id === '.' || id === '..' || /[/\\\0]/.test(id)) throw new Error(`Invalid token owner id: ${JSON.stringify(id)}`); + return id; +} + +/** PAN-5754 D-4: `/agent-tokens///mcp-token`. W-INJ1 uses this to name the file in MCP configs. */ +export function agentMcpTokenPathFor(owner: { agentId: string; agentKind: 'agent' | 'conversation' }): string { + return join(agentTokenDir(owner.agentKind, tokenDirSegment(ownerId(owner.agentId, owner.agentKind))), AGENT_TOKEN_FILE); +} + +async function unlinkIfPresent(path: string): Promise { + await unlink(path).catch((error: NodeJS.ErrnoException) => { + if (error.code !== 'ENOENT') throw error; + }); +} + async function readTokenFile(tokenFile: string): Promise { try { const content = (await readFile(tokenFile, 'utf8')).trim(); @@ -85,8 +100,8 @@ function sameScopes(granted: readonly string[], expected: readonly AccessTokenSc return set.size === expected.length && expected.every((scope) => set.has(scope)); } -async function writeTokenFile(dir: string, tokenFile: string, token: string): Promise { - await mkdir(dir, { recursive: true, mode: 0o700 }); +async function writeTokenFile(tokenFile: string, token: string): Promise { + await mkdir(dirname(tokenFile), { recursive: true, mode: 0o700 }); const temp = `${tokenFile}.${randomUUID()}.tmp`; try { await writeFile(temp, `${token}\n`, { mode: 0o600 }); @@ -97,12 +112,12 @@ async function writeTokenFile(dir: string, tokenFile: string, token: string): Pr } } -/** D-4/D-5: reuse or mint; writes `/mcp-token` 0600. Throws on a corrupt registry or a mint that does not persist. */ +/** D-4/D-5: reuse or mint; writes the owner's `mcp-token` 0600. Throws on a corrupt registry or a mint that does not persist. */ export async function ensureAgentMcpToken(owner: AgentTokenOwner): Promise<{ tokenFile: string; tokenId: string }> { const agentId = ownerId(owner.agentId, owner.agentKind); - const { agentKind, role, dir } = owner; + const { agentKind, role } = owner; const scopes = AGENT_TOKEN_SCOPES[role]; - const tokenFile = agentMcpTokenPath(dir); + const tokenFile = agentMcpTokenPathFor({ agentId, agentKind }); const existing = await readTokenFile(tokenFile); if (existing) { @@ -124,25 +139,38 @@ export async function ensureAgentMcpToken(owner: AgentTokenOwner): Promise<{ tok agentKind, role, }); - await writeTokenFile(dir, tokenFile, token); + await writeTokenFile(tokenFile, token); if (await readActiveAccessTokenRecord(token)) return { tokenFile, tokenId: record.id }; console.warn(`[agent-token] token ${record.id} for ${agentId} is missing from the registry after mint`); } throw new Error(`agent token for ${agentId} did not persist in the access-token registry`); } -/** Revoke every active token of the owner, unlink its token file, delete its `secrets/` directory (PAN-4941) and remove its PR watches (PAN-4943). Never throws; returns the count revoked. */ +/** + * PAN-5754 D-5: an isolated launch's token. Minted whatever the MCP switch says, because + * hooks and the CLI authenticate with it. Any failure rethrows naming the agent, so the + * launch fails closed (NFR-2) instead of starting with no credential of its own. + */ +export async function ensureIsolationToken(owner: AgentTokenOwner): Promise<{ tokenFile: string; tokenId: string }> { + try { + return await ensureAgentMcpToken(owner); + } catch (error) { + throw new Error(`agent isolation: token mint failed for ${owner.agentId}: ${(error as Error).message}`); + } +} + +/** Revoke every active token of the owner, unlink its token file (and the legacy `/mcp-token`), delete its `secrets/` directory (PAN-4941) and remove its PR watches (PAN-4943). Never throws; returns the count revoked. */ export async function revokeAgentMcpTokens(agentId: string, opts: { agentKind?: 'agent' | 'conversation'; dir?: string } = {}): Promise { const agentKind = opts.agentKind ?? 'agent'; const id = ownerId(agentId, agentKind); try { const revoked = await revokeAccessTokensMatching((record) => record.kind === 'token' && record.agentId === id && record.agentKind === agentKind); + await unlinkIfPresent(agentMcpTokenPathFor({ agentId: id, agentKind })); // C-1: a conversation's directory is never guessed; only the caller knows it. const dir = opts.dir ?? (agentKind === 'agent' ? getAgentDir(id) : undefined); if (dir !== undefined) { - await unlink(agentMcpTokenPath(dir)).catch((error: NodeJS.ErrnoException) => { - if (error.code !== 'ENOENT') throw error; - }); + // PAN-5754 D-4: tokens minted before the move lived in the owner's state dir. + await unlinkIfPresent(join(dir, AGENT_TOKEN_FILE)); await removeAgentSecretsDir(dir); } // PAN-4943: a stopped agent watches nothing. Its own try/catch, so a diff --git a/src/lib/overdeck/__tests__/conversation-runtime-launch.test.ts b/src/lib/overdeck/__tests__/conversation-runtime-launch.test.ts index a136009b543..11c1352afbd 100644 --- a/src/lib/overdeck/__tests__/conversation-runtime-launch.test.ts +++ b/src/lib/overdeck/__tests__/conversation-runtime-launch.test.ts @@ -370,7 +370,7 @@ describe('conversations get the overdeck MCP server (PAN-4932)', () => { const opts = initCodexHomeMock.mock.calls[0]![1] as { mcpServers?: Record; defaultToolsApprovalMode?: string }>; }; - expect(opts.mcpServers?.overdeck?.env.OVERDECK_MCP_TOKEN_FILE).toBe(join(overdeckHome, 'conversations', 'conv-cx', 'mcp-token')); + expect(opts.mcpServers?.overdeck?.env.OVERDECK_MCP_TOKEN_FILE).toBe(join(overdeckHome, 'agent-tokens', 'conversation', 'cx', 'mcp-token')); expect(opts.mcpServers?.overdeck?.defaultToolsApprovalMode).toBe('approve'); expect(await tokenFor('cx')).toEqual([expect.objectContaining({ agentKind: 'conversation', role: 'conversation' })]); diff --git a/src/lib/planning/__tests__/spawn-planning-session-backend.test.ts b/src/lib/planning/__tests__/spawn-planning-session-backend.test.ts index bd3a6373ec7..07fcd81bd3d 100644 --- a/src/lib/planning/__tests__/spawn-planning-session-backend.test.ts +++ b/src/lib/planning/__tests__/spawn-planning-session-backend.test.ts @@ -175,7 +175,7 @@ describe('spawnPlanningSession launches through the host backend (PAN-3960)', () // PAN-4932: the planner gets the overdeck MCP server with its own token file. expect(launcher).toContain(`--mcp-config='${join(tempHome, '.overdeck', 'agents', sessionName, 'overdeck-mcp.json')}'`); expect(launcher).not.toContain('odk_'); - expect(statSync(join(tempHome, '.overdeck', 'agents', sessionName, 'mcp-token')).mode & 0o777).toBe(0o600); + expect(statSync(join(tempHome, '.overdeck', 'agent-tokens', 'agent', sessionName, 'mcp-token')).mode & 0o777).toBe(0o600); }); it('keeps the tmux-only server hygiene on tmux and skips it on Herdr', async () => { diff --git a/tests/unit/lib/mcp/agent-injection-launch.test.ts b/tests/unit/lib/mcp/agent-injection-launch.test.ts index 9a9b805bc67..d1e3763a680 100644 --- a/tests/unit/lib/mcp/agent-injection-launch.test.ts +++ b/tests/unit/lib/mcp/agent-injection-launch.test.ts @@ -43,7 +43,7 @@ function expectOverdeckMcp(launcherContent: string, agentId: string) { expect(launcherContent).toContain(`--mcp-config='${join(dir, 'overdeck-mcp.json')}'`); expect(launcherContent).toContain('--allowedTools=mcp__overdeck'); expect(launcherContent).not.toContain('odk_'); - expect(statSync(join(dir, 'mcp-token')).mode & 0o777).toBe(0o600); + expect(statSync(join(home, 'agent-tokens', 'agent', agentId, 'mcp-token')).mode & 0o777).toBe(0o600); } describe('buildAgentLaunchConfig overdeck MCP (PAN-4932)', () => { @@ -88,6 +88,6 @@ describe('buildAgentLaunchConfig overdeck MCP (PAN-4932)', () => { expect(launcherContent).toContain(`--mcp-config '${join(dir, 'overdeck-mcp.json')}'`); expect(launcherContent).not.toContain('odk_'); expect(launcherContent).not.toContain('--allowedTools'); - expect(statSync(join(dir, 'mcp-token')).mode & 0o777).toBe(0o600); + expect(statSync(join(home, 'agent-tokens', 'agent', agentId, 'mcp-token')).mode & 0o777).toBe(0o600); }); }); diff --git a/tests/unit/lib/mcp/agent-injection.test.ts b/tests/unit/lib/mcp/agent-injection.test.ts index ce7395c6ce6..2ca3b83e4cd 100644 --- a/tests/unit/lib/mcp/agent-injection.test.ts +++ b/tests/unit/lib/mcp/agent-injection.test.ts @@ -139,7 +139,7 @@ describe('overdeck MCP injection (PAN-4932 W-4)', () => { const result = await prepareClaudeOverdeckMcp({ agentId: 'agent-pan-1', agentKind: 'agent', role: 'work', harness: 'claude-code' }); const dir = join(home, 'agents', 'agent-pan-1'); const configPath = join(dir, 'overdeck-mcp.json'); - const tokenFile = join(dir, 'mcp-token'); + const tokenFile = join(home, 'agent-tokens', 'agent', 'agent-pan-1', 'mcp-token'); expect(result).toEqual({ overdeckMcpConfig: configPath }); expect((await stat(configPath)).mode & 0o777).toBe(0o600); @@ -158,8 +158,8 @@ describe('overdeck MCP injection (PAN-4932 W-4)', () => { .toEqual({ overdeckMcpConfig: join(home, 'agents', 'agent-pan-2', 'overdeck-mcp.json') }); expect(await prepareClaudeOverdeckMcp({ agentId: 'agent-pan-3', agentKind: 'agent', role: 'work', harness: 'acp' })) .toEqual({ overdeckMcpConfig: join(home, 'agents', 'agent-pan-3', 'overdeck-mcp.json') }); - expect((await stat(join(home, 'agents', 'agent-pan-2', 'mcp-token'))).mode & 0o777).toBe(0o600); - expect((await stat(join(home, 'agents', 'agent-pan-3', 'mcp-token'))).mode & 0o777).toBe(0o600); + expect((await stat(join(home, 'agent-tokens', 'agent', 'agent-pan-2', 'mcp-token'))).mode & 0o777).toBe(0o600); + expect((await stat(join(home, 'agent-tokens', 'agent', 'agent-pan-3', 'mcp-token'))).mode & 0o777).toBe(0o600); }); it('returns {} for kimi-code, mcp.agents false, Docker env, and a conversation without a dir', async () => { @@ -214,7 +214,7 @@ describe('overdeck MCP injection (PAN-4932 W-4)', () => { describe('overdeck MCP injection for Codex (PAN-4933 W-INJ2)', () => { it('returns { overdeck } with defaultToolsApprovalMode approve and a 0600 token file for an enabled codex agent', async () => { const result = await prepareCodexOverdeckMcp({ agentId: 'agent-pan-9', agentKind: 'agent', role: 'work', harness: 'codex' }); - const tokenFile = join(home, 'agents', 'agent-pan-9', 'mcp-token'); + const tokenFile = join(home, 'agent-tokens', 'agent', 'agent-pan-9', 'mcp-token'); expect(Object.keys(result)).toEqual(['overdeck']); expect(result.overdeck!.env.OVERDECK_MCP_TOKEN_FILE).toBe(tokenFile); diff --git a/tests/unit/lib/mcp/agent-token.test.ts b/tests/unit/lib/mcp/agent-token.test.ts index 0cf54a1dd8d..399d0a4c415 100644 --- a/tests/unit/lib/mcp/agent-token.test.ts +++ b/tests/unit/lib/mcp/agent-token.test.ts @@ -33,8 +33,9 @@ import { import type { Role } from '../../../../src/lib/agents/role.js'; import { AGENT_TOKEN_SCOPES, - agentMcpTokenPath, + agentMcpTokenPathFor, ensureAgentMcpToken, + ensureIsolationToken, revokeAgentMcpTokens, revokeAgentMcpTokensForIssue, type AgentTokenOwner, @@ -54,12 +55,12 @@ async function activeFor(agentId: string) { return (await listAccessTokens()).filter((record) => !record.revokedAt && record.agentId === agentId); } -async function tokenIn(dir: string): Promise { - return (await readFile(agentMcpTokenPath(dir), 'utf8')).trim(); +async function tokenIn(owner: Pick): Promise { + return (await readFile(agentMcpTokenPathFor(owner), 'utf8')).trim(); } -function workOwner(dir = join(home, 'agents', 'agent-pan-1')): AgentTokenOwner { - return { agentId: 'agent-pan-1', agentKind: 'agent', role: 'work', dir }; +function workOwner(agentId = 'agent-pan-1'): AgentTokenOwner { + return { agentId, agentKind: 'agent', role: 'work' }; } beforeEach(async () => { @@ -95,17 +96,17 @@ describe('agent MCP tokens (PAN-4930 W-4)', () => { it('mints a work agent one active token and a 0600 mcp-token file that verifies to it', async () => { const owner = workOwner(); const { tokenFile, tokenId } = await ensureAgentMcpToken(owner); - expect(tokenFile).toBe(join(owner.dir, 'mcp-token')); + expect(tokenFile).toBe(join(home, 'agent-tokens', 'agent', 'agent-pan-1', 'mcp-token')); expect((await stat(tokenFile)).mode & 0o777).toBe(0o600); - const record = await readActiveAccessTokenRecord(await tokenIn(owner.dir)); + const record = await readActiveAccessTokenRecord(await tokenIn(owner)); expect(record).toMatchObject({ id: tokenId, kind: 'token', agentId: 'agent-pan-1', agentKind: 'agent', role: 'work', name: 'agent:work:agent-pan-1', scopes: OPERATE }); expect(await activeFor('agent-pan-1')).toHaveLength(1); }); it('gives a review run the review scopes and a conversation approve', async () => { - const review = await ensureAgentMcpToken({ agentId: 'review-run-1', agentKind: 'agent', role: 'review', dir: join(home, 'agents', 'review-run-1') }); - const conv = await ensureAgentMcpToken({ agentId: 'my-conv', agentKind: 'conversation', role: 'conversation', dir: join(home, 'conversations', 'conv-my-conv') }); + const review = await ensureAgentMcpToken({ agentId: 'review-run-1', agentKind: 'agent', role: 'review' }); + const conv = await ensureAgentMcpToken({ agentId: 'my-conv', agentKind: 'conversation', role: 'conversation' }); const records = await listAccessTokens(); expect(records.find((record) => record.id === review.tokenId)?.scopes).toEqual(REVIEW); expect(records.find((record) => record.id === conv.tokenId)).toMatchObject({ agentKind: 'conversation', role: 'conversation', scopes: [...OPERATE, 'approve'] }); @@ -122,7 +123,7 @@ describe('agent MCP tokens (PAN-4930 W-4)', () => { const owner = workOwner(); const first = await ensureAgentMcpToken(owner); - await rm(agentMcpTokenPath(owner.dir)); + await rm(agentMcpTokenPathFor(owner)); const afterDelete = await ensureAgentMcpToken(owner); expect(afterDelete.tokenId).not.toBe(first.tokenId); @@ -143,7 +144,7 @@ describe('agent MCP tokens (PAN-4930 W-4)', () => { await ensureAgentMcpToken(owner); expect(await revokeAgentMcpTokens('agent-pan-1')).toBe(1); expect(await activeFor('agent-pan-1')).toEqual([]); - await expect(stat(agentMcpTokenPath(owner.dir))).rejects.toMatchObject({ code: 'ENOENT' }); + await expect(stat(agentMcpTokenPathFor(owner))).rejects.toMatchObject({ code: 'ENOENT' }); await writeFile(join(home, 'access-tokens.json'), 'not json', { mode: 0o600 }); const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); @@ -171,7 +172,7 @@ describe('agent MCP tokens (PAN-4930 W-4)', () => { // cleanup (unlike a corrupt access-token registry, which does both). await expect(revokeAgentMcpTokens('agent-pan-1')).resolves.toBe(1); expect(await activeFor('agent-pan-1')).toEqual([]); - await expect(stat(agentMcpTokenPath(owner.dir))).rejects.toMatchObject({ code: 'ENOENT' }); + await expect(stat(agentMcpTokenPathFor(owner))).rejects.toMatchObject({ code: 'ENOENT' }); expect(warn).toHaveBeenCalledWith(expect.stringContaining('[agent-token] PR watch cleanup failed for agent-pan-1')); }); @@ -206,18 +207,18 @@ describe('agent MCP tokens (PAN-4930 W-4)', () => { it('a conversation revoke never touches an agent token with the same id', async () => { // A qualified id, so normalizeAgentId leaves the agent owner's id equal to the conversation name. - const dir = join(home, 'agents', 'agent-x'); - await ensureAgentMcpToken({ agentId: 'agent-x', agentKind: 'agent', role: 'work', dir }); + const owner = workOwner('agent-x'); + await ensureAgentMcpToken(owner); expect(await revokeAgentMcpTokens('agent-x', { agentKind: 'conversation', dir: join(home, 'conversations', 'conv-agent-x') })).toBe(0); expect(await activeFor('agent-x')).toHaveLength(1); - expect(await tokenIn(dir)).toMatch(/^odk_/); + expect(await tokenIn(owner)).toMatch(/^odk_/); }); it('revokeAgentMcpTokensForIssue revokes only the agents of that issue', async () => { agentStates.set('agent-pan-1', { issueId: 'pan-1' }); agentStates.set('agent-pan-2', { issueId: 'PAN-2' }); await ensureAgentMcpToken(workOwner()); - await ensureAgentMcpToken({ agentId: 'agent-pan-2', agentKind: 'agent', role: 'work', dir: join(home, 'agents', 'agent-pan-2') }); + await ensureAgentMcpToken(workOwner('agent-pan-2')); expect(await revokeAgentMcpTokensForIssue('PAN-1')).toBe(1); expect(await activeFor('agent-pan-1')).toEqual([]); @@ -232,9 +233,42 @@ describe('agent MCP tokens (PAN-4930 W-4)', () => { expect(active.map((record) => record.id)).toEqual([tokenId]); expect((await listAccessTokens()).filter((record) => record.agentId === 'agent-pan-1')).toHaveLength(2); - const other = workOwner(join(home, 'agents', 'agent-pan-9')); vi.mocked(readActiveAccessTokenRecord).mockResolvedValueOnce(null).mockResolvedValueOnce(null); - await expect(ensureAgentMcpToken({ ...other, agentId: 'agent-pan-9' })).rejects.toThrow('agent token for agent-pan-9 did not persist in the access-token registry'); + await expect(ensureAgentMcpToken(workOwner('agent-pan-9'))).rejects.toThrow('agent token for agent-pan-9 did not persist in the access-token registry'); expect(warn).toHaveBeenCalled(); }); + it('PAN-5754 D-4: keeps each owner token under agent-tokens//, never in the owner state dir', async () => { + const agent = await ensureAgentMcpToken(workOwner()); + const conv = await ensureAgentMcpToken({ agentId: 'my-conv', agentKind: 'conversation', role: 'conversation' }); + expect(agent.tokenFile).toBe(join(home, 'agent-tokens', 'agent', 'agent-pan-1', 'mcp-token')); + expect(conv.tokenFile).toBe(join(home, 'agent-tokens', 'conversation', 'my-conv', 'mcp-token')); + expect((await stat(join(home, 'agent-tokens', 'agent', 'agent-pan-1'))).mode & 0o777).toBe(0o700); + await expect(stat(join(home, 'agents', 'agent-pan-1', 'mcp-token'))).rejects.toMatchObject({ code: 'ENOENT' }); + + await expect(ensureAgentMcpToken({ agentId: '../escape', agentKind: 'conversation', role: 'conversation' })).rejects.toThrow('Invalid token owner id'); + }); + + it('PAN-5754 D-4: revoke unlinks both the new token file and a legacy /mcp-token', async () => { + const owner = workOwner(); + await ensureAgentMcpToken(owner); + const legacyDir = join(home, 'agents', 'agent-pan-1'); + await mkdir(legacyDir, { recursive: true }); + await writeFile(join(legacyDir, 'mcp-token'), 'odk_legacy\n', { mode: 0o600 }); + + expect(await revokeAgentMcpTokens('agent-pan-1')).toBe(1); + await expect(stat(agentMcpTokenPathFor(owner))).rejects.toMatchObject({ code: 'ENOENT' }); + await expect(stat(join(legacyDir, 'mcp-token'))).rejects.toMatchObject({ code: 'ENOENT' }); + }); + + it('PAN-5754 D-5: ensureIsolationToken mints a token and rethrows a failed mint naming the agent', async () => { + const minted = await ensureIsolationToken(workOwner()); + expect(await tokenIn(workOwner())).toMatch(/^odk_/); + expect(minted.tokenFile).toBe(agentMcpTokenPathFor(workOwner())); + + vi.spyOn(console, 'warn').mockImplementation(() => undefined); + vi.mocked(readActiveAccessTokenRecord).mockResolvedValueOnce(null).mockResolvedValueOnce(null); + await expect(ensureIsolationToken(workOwner('agent-pan-7'))).rejects.toThrow( + /^agent isolation: token mint failed for agent-pan-7: agent token for agent-pan-7 did not persist/, + ); + }); }); From effc75057a48e93a71b4d6e6450b0bfdc36d3eb1 Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 16:49:04 -0500 Subject: [PATCH 007/129] chore(workspace): plan artifacts for PAN-5754 Overdeck-Agent: agent-pan-5754 --- .pan/continues/PAN-5754.xbrief.json | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/.pan/continues/PAN-5754.xbrief.json b/.pan/continues/PAN-5754.xbrief.json index 28403895819..4058a08091b 100644 --- a/.pan/continues/PAN-5754.xbrief.json +++ b/.pan/continues/PAN-5754.xbrief.json @@ -2,7 +2,7 @@ "version": "1", "issueId": "PAN-5754", "created": "2026-12-03T21:28:28.525Z", - "updated": "2026-12-03T21:36:26.225Z", + "updated": "2026-12-03T21:49:04.900Z", "gitState": {}, "decisions": [], "hazards": [], @@ -36,9 +36,22 @@ "doneAt": "2026-12-03T21:36:05.380Z" }, "token-location": { - "status": "in_progress", + "status": "completed", "claimedBy": "agent-pan-5754", - "claimedAt": "2026-12-03T21:36:26.224Z" + "claimedAt": "2026-12-03T21:36:26.224Z", + "doneAt": "2026-12-03T21:49:04.899Z" + }, + "token-location.ac1": { + "status": "completed", + "doneAt": "2026-12-03T21:49:04.899Z" + }, + "token-location.ac2": { + "status": "completed", + "doneAt": "2026-12-03T21:49:04.899Z" + }, + "token-location.ac3": { + "status": "completed", + "doneAt": "2026-12-03T21:49:04.899Z" } } } From 43a5ddccdc0e302216d90e4b7b04ae65790220cc Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 16:49:07 -0500 Subject: [PATCH 008/129] chore(workspace): plan artifacts for PAN-5754 Overdeck-Agent: agent-pan-5754 --- .pan/continues/PAN-5754.xbrief.json | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/.pan/continues/PAN-5754.xbrief.json b/.pan/continues/PAN-5754.xbrief.json index 4058a08091b..ab36e820c66 100644 --- a/.pan/continues/PAN-5754.xbrief.json +++ b/.pan/continues/PAN-5754.xbrief.json @@ -2,7 +2,7 @@ "version": "1", "issueId": "PAN-5754", "created": "2026-12-03T21:28:28.525Z", - "updated": "2026-12-03T21:49:04.900Z", + "updated": "2026-12-03T21:49:07.519Z", "gitState": {}, "decisions": [], "hazards": [], @@ -52,6 +52,11 @@ "token-location.ac3": { "status": "completed", "doneAt": "2026-12-03T21:49:04.899Z" + }, + "iso-policy": { + "status": "in_progress", + "claimedBy": "agent-pan-5754", + "claimedAt": "2026-12-03T21:49:07.518Z" } } } From 86fe329e4616461dc8370207c7d5d1d9e780458a Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 16:52:37 -0500 Subject: [PATCH 009/129] feat(infra): build the pure agent isolation policy and its input resolver PAN-5754 WI-3. buildIsolationPolicy turns one launch's paths into the D-8 policy: the operator secret set and the masked socket dirs (Herdr, tmux, ~/.overdeck/sockets, the user runtime dir, X11, Docker unless allow_docker) are denied for read and write; the owner's own token dir is re-allowed; writes are allowed only to the workspace, /tmp, the git common dirs, the DB files, logs/, tmp/ and the admission queue inside OVERDECK_HOME, the caches present at launch and allow_write. Workspace .git files, .claude/, .mcp.json, git hooks/config and cache executable dirs are write-denied. Deviation: the input carries repoRoots (workspace plus polyrepo child repos) so each child's .git file is write-denied too, and drops the unused uid (the resolver uses it to find the tmux socket dir). Item: iso-policy Item: iso-policy.ac1 Item: iso-policy.ac2 Item: iso-policy.ac3 Item: iso-policy.ac4 Item: iso-policy.ac5 Co-Authored-By: Claude Opus 5.5 Overdeck-Agent: agent-pan-5754 --- .../agent-isolation/__tests__/policy.test.ts | 119 ++++++++++++++ src/lib/agent-isolation/policy-input.ts | 90 +++++++++++ src/lib/agent-isolation/policy.ts | 145 ++++++++++++++++++ 3 files changed, 354 insertions(+) create mode 100644 src/lib/agent-isolation/__tests__/policy.test.ts create mode 100644 src/lib/agent-isolation/policy-input.ts create mode 100644 src/lib/agent-isolation/policy.ts diff --git a/src/lib/agent-isolation/__tests__/policy.test.ts b/src/lib/agent-isolation/__tests__/policy.test.ts new file mode 100644 index 00000000000..5448fecc6c9 --- /dev/null +++ b/src/lib/agent-isolation/__tests__/policy.test.ts @@ -0,0 +1,119 @@ +import { execFileSync } from 'node:child_process'; +import { mkdir, mkdtemp, realpath, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterEach, describe, expect, it } from 'vitest'; + +import { buildIsolationPolicy, serializePolicy, type IsolationPolicyInput } from '../policy.js'; +import { resolveIsolationPolicyInput } from '../policy-input.js'; + +const HOME = '/home/op'; +const OD = '/home/op/.overdeck'; + +function input(overrides: Partial = {}): IsolationPolicyInput { + return { + overdeckHome: OD, + homeDir: HOME, + workspace: '/r/workspaces/feature-pan-1', + repoRoots: ['/r/workspaces/feature-pan-1'], + gitCommonDirs: ['/r/.git'], + owner: { kind: 'agent', id: 'agent-pan-1' }, + herdrSessionsDir: '/home/op/.config/herdr/sessions', + tmuxSocketDir: '/tmp/tmux-1000', + xdgRuntimeDir: '/run/user/1000', + allowDocker: false, + extraAllowWrite: [], + existingCacheDirs: ['/home/op/.npm', '/home/op/.bun', '/home/op/.cache'], + ...overrides, + }; +} + +describe('buildIsolationPolicy (PAN-5754 D-8)', () => { + it('denies the internal token for read and write and re-allows only the own token dir', () => { + const policy = buildIsolationPolicy(input()); + expect(policy.denyRead).toContain(`${OD}/internal-token`); + expect(policy.denyWrite).toContain(`${OD}/internal-token`); + expect(policy.allowRead).toEqual([`${OD}/agent-tokens/agent/agent-pan-1`]); + expect(policy.denyRead).toContain(`${OD}/agent-tokens`); + expect(policy.denyRead.some((path) => path.includes('agent-pan-2'))).toBe(false); + for (const secret of ['access-tokens.json', 'machine-key.json', 'credentials', 'browser-profiles', 'vault', 'cliproxy']) { + expect(policy.denyRead).toContain(`${OD}/${secret}`); + } + }); + + it('allows the git common dir but denies its hooks and config and the workspace .git, .claude and .mcp.json', () => { + const policy = buildIsolationPolicy(input({ repoRoots: ['/r/workspaces/feature-pan-1', '/r/workspaces/feature-pan-1/api'] })); + expect(policy.allowWrite).toContain('/r/.git'); + expect(policy.denyWrite).toEqual(expect.arrayContaining([ + '/r/.git/hooks', + '/r/.git/config', + '/r/workspaces/feature-pan-1/.git', + '/r/workspaces/feature-pan-1/api/.git', + '/r/workspaces/feature-pan-1/.claude', + '/r/workspaces/feature-pan-1/.mcp.json', + ])); + }); + + it('masks the docker socket unless allowDocker', () => { + expect(buildIsolationPolicy(input()).maskedSocketDirs).toEqual(expect.arrayContaining(['/var/run/docker.sock', '/run/docker.sock'])); + const allowed = buildIsolationPolicy(input({ allowDocker: true })); + expect(allowed.maskedSocketDirs).not.toContain('/var/run/docker.sock'); + expect(allowed.denyRead).not.toContain('/var/run/docker.sock'); + }); + + it('masks every terminal-backend socket dir for read and write and creates the missing ones', () => { + const policy = buildIsolationPolicy(input({ extraAllowWrite: ['/data/x'] })); + expect(policy.allowWrite).toContain('/data/x'); + for (const dir of ['/home/op/.config/herdr/sessions', '/tmp/tmux-1000', `${OD}/sockets`, '/run/user/1000', '/tmp/.X11-unix']) { + expect(policy.maskedSocketDirs).toContain(dir); + expect(policy.denyRead).toContain(dir); + expect(policy.denyWrite).toContain(dir); + } + expect(policy.mkdirBeforeLaunch).toEqual(['/home/op/.config/herdr/sessions', '/tmp/tmux-1000', `${OD}/sockets`]); + }); + + it('allows exactly the DB files, logs/, tmp/ and the admission queue inside OVERDECK_HOME', () => { + const policy = buildIsolationPolicy(input()); + const underHome = policy.allowWrite.filter((path) => path === OD || path.startsWith(`${OD}/`)).sort(); + const dbs = ['overdeck.db', 'panopticon.db', 'cache.db'].flatMap((db) => [db, `${db}-wal`, `${db}-shm`]); + expect(underHome).toEqual([...dbs, 'logs', 'tmp', 'verification-workers/admission'].map((entry) => `${OD}/${entry}`).sort()); + expect(policy.allowWrite.some((path) => path.startsWith(`${OD}/agent-api`))).toBe(false); + expect(policy.allowWrite).not.toContain(`${OD}/bin`); + }); + + it('allows the existing caches but denies their executable subdirectories', () => { + const policy = buildIsolationPolicy(input()); + expect(policy.allowWrite).toEqual(expect.arrayContaining(['/home/op/.npm', '/home/op/.bun', '/home/op/.cache'])); + expect(policy.denyWrite).toEqual(expect.arrayContaining(['/home/op/.bun/bin', '/home/op/.npm/_npx', '/home/op/.cache/ms-playwright'])); + expect(policy.denyWrite).not.toContain('/home/op/.cargo/bin'); + }); + + it('serializes the guard hook view of the policy', () => { + const policy = buildIsolationPolicy(input()); + expect(JSON.parse(serializePolicy(policy))).toEqual({ version: 1, allowWrite: policy.allowWrite, denyWrite: policy.denyWrite }); + }); +}); + +describe('resolveIsolationPolicyInput', () => { + let dir: string | undefined; + afterEach(async () => { + if (dir) await rm(dir, { recursive: true, force: true }); + dir = undefined; + }); + + it('finds the workspace repo, a child repo and their git common dirs', async () => { + dir = await realpath(await mkdtemp(join(tmpdir(), 'pan-5754-policy-'))); + execFileSync('git', ['init', '-q', dir]); + const child = join(dir, 'api'); + await mkdir(child); + execFileSync('git', ['init', '-q', child]); + await mkdir(join(dir, 'docs')); + await writeFile(join(dir, 'docs', 'README.md'), 'x'); + + const resolved = await resolveIsolationPolicyInput({ kind: 'agent', id: 'agent-pan-1' }, dir); + expect(resolved.repoRoots).toEqual([dir, child]); + expect(resolved.gitCommonDirs).toEqual([join(dir, '.git'), join(child, '.git')]); + expect(resolved.tmuxSocketDir).toMatch(/\/tmux-\d+$/); + expect(resolved.owner).toEqual({ kind: 'agent', id: 'agent-pan-1' }); + }); +}); diff --git a/src/lib/agent-isolation/policy-input.ts b/src/lib/agent-isolation/policy-input.ts new file mode 100644 index 00000000000..5ea9b027c24 --- /dev/null +++ b/src/lib/agent-isolation/policy-input.ts @@ -0,0 +1,90 @@ +/** + * PAN-5754 D-8: gather the real values `buildIsolationPolicy` needs for one launch. + * Async only (it runs in the dashboard server): `execFile` for git, `access`/`stat` for files. + */ +import { execFile } from 'node:child_process'; +import { access, readdir, stat } from 'node:fs/promises'; +import { homedir } from 'node:os'; +import { dirname, join, resolve } from 'node:path'; +import { promisify } from 'node:util'; + +import { getOverdeckHome } from '../paths.js'; +import { herdrSocketPath } from '../terminal-backends/select.js'; +import { readAgentIsolationConfig } from './config.js'; +import { PACKAGE_CACHE_DIRS, type IsolationPolicyInput } from './policy.js'; + +const execFileAsync = promisify(execFile); + +async function exists(path: string): Promise { + try { + await access(path); + return true; + } catch { + return false; + } +} + +/** The workspace (when it is a repo) and each direct child directory holding a `.git` entry. */ +async function findRepoRoots(workspace: string): Promise { + const roots: string[] = []; + if (await exists(join(workspace, '.git'))) roots.push(workspace); + let entries: string[] = []; + try { + entries = (await readdir(workspace, { withFileTypes: true })).filter((entry) => entry.isDirectory()).map((entry) => entry.name); + } catch { + return roots; + } + for (const name of entries) { + if (name === '.git' || name === 'node_modules') continue; + const child = join(workspace, name); + if (await exists(join(child, '.git'))) roots.push(child); + } + return roots; +} + +async function gitCommonDir(repoRoot: string): Promise { + try { + const { stdout } = await execFileAsync('git', ['rev-parse', '--git-common-dir'], { cwd: repoRoot, timeout: 10_000 }); + const out = stdout.trim(); + return out ? resolve(repoRoot, out) : null; + } catch { + return null; + } +} + +async function isDirectory(path: string): Promise { + try { + return (await stat(path)).isDirectory(); + } catch { + return false; + } +} + +export async function resolveIsolationPolicyInput( + owner: { kind: 'agent' | 'conversation'; id: string }, + workspace: string, +): Promise { + const homeDir = homedir(); + const uid = process.getuid?.() ?? 0; + const config = readAgentIsolationConfig(); + const repoRoots = await findRepoRoots(workspace); + const gitCommonDirs = [...new Set((await Promise.all(repoRoots.map(gitCommonDir))).filter((dir): dir is string => dir !== null))]; + const cacheCandidates = PACKAGE_CACHE_DIRS.map((dir) => join(homeDir, dir)); + const existingCacheDirs = (await Promise.all(cacheCandidates.map(async (dir) => ((await isDirectory(dir)) ? dir : null)))) + .filter((dir): dir is string => dir !== null); + + return { + overdeckHome: getOverdeckHome(), + homeDir, + workspace, + repoRoots, + gitCommonDirs, + owner, + herdrSessionsDir: dirname(dirname(herdrSocketPath())), + tmuxSocketDir: join(process.env.TMUX_TMPDIR || '/tmp', `tmux-${uid}`), + xdgRuntimeDir: process.env.XDG_RUNTIME_DIR || `/run/user/${uid}`, + allowDocker: config.allowDocker, + extraAllowWrite: config.allowWrite, + existingCacheDirs, + }; +} diff --git a/src/lib/agent-isolation/policy.ts b/src/lib/agent-isolation/policy.ts new file mode 100644 index 00000000000..2433ed1de52 --- /dev/null +++ b/src/lib/agent-isolation/policy.ts @@ -0,0 +1,145 @@ +/** + * PAN-5754 D-8: the isolation policy for an isolated Claude Code agent, as pure data. + * + * One policy feeds the Claude Code settings file (sandbox + permission deny rules), + * the write guard hook (`serializePolicy`) and `pan doctor`. Every path is absolute. + * + * - `denyRead`: the operator secret set plus the masked socket directories. + * - `allowRead`: the owner's own token directory, re-allowed inside `agent-tokens/`. + * - `allowWrite`: the workspace, `/tmp`, the git common dirs, an allowlist inside + * `` (the databases, `logs/`, `tmp/`, the gate admission queue), the + * package caches present at launch, and `agents.isolation.allow_write`. Every other + * entry of `` stays read-only, including `agent-api/` and `isolation/`. + * - `denyWrite`: everything in `denyRead`, the workspace's `.git` files, `.claude/` and + * `.mcp.json`, each git common dir's `hooks/` and `config`, and the cache directories + * whose contents run outside the sandbox (MCP servers, browsers). + * - `maskedSocketDirs`: Herdr, tmux, Overdeck, the user runtime dir, X11 and (unless + * `allowDocker`) the Docker socket. Deny-read is what blocks `connect()` (D-9). + * - `mkdirBeforeLaunch`: masked directories the launcher creates when missing, so a + * server that starts later still lands under the mask. + */ +import { join } from 'node:path'; + +export interface IsolationPolicyInput { + overdeckHome: string; + homeDir: string; + workspace: string; + /** The workspace root and each child repo root (polyrepo); each `/.git` is write-denied. */ + repoRoots: string[]; + /** `git rev-parse --git-common-dir` of every repo root, absolute. */ + gitCommonDirs: string[]; + owner: { kind: 'agent' | 'conversation'; id: string }; + herdrSessionsDir: string; + tmuxSocketDir: string; + xdgRuntimeDir: string; + allowDocker: boolean; + extraAllowWrite: string[]; + /** The package cache directories (from `PACKAGE_CACHE_DIRS`) that exist at launch. */ + existingCacheDirs: string[]; +} + +export interface IsolationPolicy { + denyRead: string[]; + allowRead: string[]; + allowWrite: string[]; + denyWrite: string[]; + maskedSocketDirs: string[]; + mkdirBeforeLaunch: string[]; +} + +/** The operator secret set inside `` (D-8 read deny). */ +export const OVERDECK_HOME_SECRET_ENTRIES: readonly string[] = [ + 'internal-token', + 'access-tokens.json', + 'account.json', + 'machine-key.json', + 'machine-links.json', + 'ssh-machines.json', + 'credentials', + 'github-app', + 'cliproxy', + 'kimi-cliproxy-home', + 'secrets', + 'vault', + 'certs', + 'browser-profiles', + 'agent-tokens', +]; + +/** The only writable entries inside `` (D-8 write allow). */ +export const OVERDECK_HOME_WRITABLE_ENTRIES: readonly string[] = [ + ...['overdeck.db', 'panopticon.db', 'cache.db'].flatMap((db) => [db, `${db}-wal`, `${db}-shm`]), + 'logs', + 'tmp', + join('verification-workers', 'admission'), +]; + +/** Package caches, relative to the home directory. Writable when present at launch. */ +export const PACKAGE_CACHE_DIRS: readonly string[] = [ + '.npm', '.bun', '.cache', join('.local', 'share', 'pnpm'), '.yarn', '.gradle', '.m2', '.cargo', 'go', '.pub-cache', +]; + +/** Cache subdirectories whose contents run outside the sandbox, keyed by their cache dir. */ +const CACHE_EXECUTABLE_DIRS: ReadonlyArray = [ + ['.bun', 'bin'], + ['.cargo', 'bin'], + ['go', 'bin'], + ['.npm', '_npx'], + ['.cache', 'ms-playwright'], +]; + +function unique(paths: string[]): string[] { + return [...new Set(paths)]; +} + +export function buildIsolationPolicy(input: IsolationPolicyInput): IsolationPolicy { + const { overdeckHome, homeDir } = input; + const inHome = (entry: string) => join(overdeckHome, entry); + + const secrets = OVERDECK_HOME_SECRET_ENTRIES.map(inHome); + const maskedSocketDirs = unique([ + input.herdrSessionsDir, + input.tmuxSocketDir, + inHome('sockets'), + input.xdgRuntimeDir, + '/tmp/.X11-unix', + ...(input.allowDocker ? [] : ['/var/run/docker.sock', '/run/docker.sock']), + ]); + const denyRead = unique([...secrets, ...maskedSocketDirs]); + const allowRead = [join(overdeckHome, 'agent-tokens', input.owner.kind, input.owner.id)]; + + const allowWrite = unique([ + input.workspace, + '/tmp', + ...input.gitCommonDirs, + ...OVERDECK_HOME_WRITABLE_ENTRIES.map(inHome), + ...input.existingCacheDirs, + ...input.extraAllowWrite, + ]); + + const existingCaches = new Set(input.existingCacheDirs); + const denyWrite = unique([ + ...denyRead, + ...input.repoRoots.map((root) => join(root, '.git')), + join(input.workspace, '.claude'), + join(input.workspace, '.mcp.json'), + ...input.gitCommonDirs.flatMap((dir) => [join(dir, 'hooks'), join(dir, 'config')]), + ...CACHE_EXECUTABLE_DIRS + .filter(([cache]) => existingCaches.has(join(homeDir, cache))) + .map(([cache, sub]) => join(homeDir, cache, sub)), + ]); + + return { + denyRead, + allowRead, + allowWrite, + denyWrite, + maskedSocketDirs, + mkdirBeforeLaunch: unique([input.herdrSessionsDir, input.tmuxSocketDir, inHome('sockets')]), + }; +} + +/** The JSON the write guard hook reads (`OVERDECK_ISOLATION_POLICY`). */ +export function serializePolicy(policy: IsolationPolicy): string { + return `${JSON.stringify({ version: 1, allowWrite: policy.allowWrite, denyWrite: policy.denyWrite }, null, 2)}\n`; +} From c58319c53c4d6c27691e8e888aeb9a07a56c35b6 Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 16:53:07 -0500 Subject: [PATCH 010/129] chore(workspace): plan artifacts for PAN-5754 Overdeck-Agent: agent-pan-5754 --- .pan/continues/PAN-5754.xbrief.json | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/.pan/continues/PAN-5754.xbrief.json b/.pan/continues/PAN-5754.xbrief.json index ab36e820c66..32238385901 100644 --- a/.pan/continues/PAN-5754.xbrief.json +++ b/.pan/continues/PAN-5754.xbrief.json @@ -2,7 +2,7 @@ "version": "1", "issueId": "PAN-5754", "created": "2026-12-03T21:28:28.525Z", - "updated": "2026-12-03T21:49:07.519Z", + "updated": "2026-12-03T21:53:07.731Z", "gitState": {}, "decisions": [], "hazards": [], @@ -54,9 +54,30 @@ "doneAt": "2026-12-03T21:49:04.899Z" }, "iso-policy": { - "status": "in_progress", + "status": "completed", "claimedBy": "agent-pan-5754", - "claimedAt": "2026-12-03T21:49:07.518Z" + "claimedAt": "2026-12-03T21:49:07.518Z", + "doneAt": "2026-12-03T21:53:07.731Z" + }, + "iso-policy.ac1": { + "status": "completed", + "doneAt": "2026-12-03T21:53:07.731Z" + }, + "iso-policy.ac2": { + "status": "completed", + "doneAt": "2026-12-03T21:53:07.731Z" + }, + "iso-policy.ac3": { + "status": "completed", + "doneAt": "2026-12-03T21:53:07.731Z" + }, + "iso-policy.ac4": { + "status": "completed", + "doneAt": "2026-12-03T21:53:07.731Z" + }, + "iso-policy.ac5": { + "status": "completed", + "doneAt": "2026-12-03T21:53:07.731Z" } } } From eb0b72126f2e62eda70b911a63ece8be0fd36628 Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 16:53:09 -0500 Subject: [PATCH 011/129] chore(workspace): plan artifacts for PAN-5754 Overdeck-Agent: agent-pan-5754 --- .pan/continues/PAN-5754.xbrief.json | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/.pan/continues/PAN-5754.xbrief.json b/.pan/continues/PAN-5754.xbrief.json index 32238385901..f5fce5c9911 100644 --- a/.pan/continues/PAN-5754.xbrief.json +++ b/.pan/continues/PAN-5754.xbrief.json @@ -2,7 +2,7 @@ "version": "1", "issueId": "PAN-5754", "created": "2026-12-03T21:28:28.525Z", - "updated": "2026-12-03T21:53:07.731Z", + "updated": "2026-12-03T21:53:09.165Z", "gitState": {}, "decisions": [], "hazards": [], @@ -78,6 +78,11 @@ "iso-policy.ac5": { "status": "completed", "doneAt": "2026-12-03T21:53:07.731Z" + }, + "claude-settings": { + "status": "in_progress", + "claimedBy": "agent-pan-5754", + "claimedAt": "2026-12-03T21:53:09.165Z" } } } From 75eb4fecec418b1c4622b9c6174a5e77ea48458d Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 16:53:48 -0500 Subject: [PATCH 012/129] feat(infra): render the Claude Code isolation settings file PAN-5754 WI-4. renderIsolationClaudeSettings turns the isolation policy into the --settings file: sandbox enabled with failIfUnavailable, no unsandboxed retry, auto-allowed sandboxed Bash, all Unix sockets (the policy's masks block the terminal-backend ones) and every domain; Read(//...) and Edit(//...) deny rules for each denied path, bare and /** so files and directories both match; and the PreToolUse write guard hook with the policy file. writeIsolationFiles writes claude-settings.json and policy.json (0600) under /isolation/// (0700). Item: claude-settings Item: claude-settings.ac1 Item: claude-settings.ac2 Item: claude-settings.ac3 Co-Authored-By: Claude Opus 5.5 Overdeck-Agent: agent-pan-5754 --- .../__tests__/claude-settings.test.ts | 87 ++++++++++++++++++ src/lib/agent-isolation/claude-settings.ts | 92 +++++++++++++++++++ 2 files changed, 179 insertions(+) create mode 100644 src/lib/agent-isolation/__tests__/claude-settings.test.ts create mode 100644 src/lib/agent-isolation/claude-settings.ts diff --git a/src/lib/agent-isolation/__tests__/claude-settings.test.ts b/src/lib/agent-isolation/__tests__/claude-settings.test.ts new file mode 100644 index 00000000000..c64a63ef24f --- /dev/null +++ b/src/lib/agent-isolation/__tests__/claude-settings.test.ts @@ -0,0 +1,87 @@ +import { mkdtemp, readFile, rm, stat } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; + +import { renderIsolationClaudeSettings, writeIsolationFiles } from '../claude-settings.js'; +import { buildIsolationPolicy, type IsolationPolicy } from '../policy.js'; + +function policy(overdeckHome = '/home/op/.overdeck'): IsolationPolicy { + return buildIsolationPolicy({ + overdeckHome, + homeDir: '/home/op', + workspace: '/r/ws', + repoRoots: ['/r/ws'], + gitCommonDirs: ['/r/.git'], + owner: { kind: 'agent', id: 'agent-pan-1' }, + herdrSessionsDir: '/home/op/.config/herdr/sessions', + tmuxSocketDir: '/tmp/tmux-1000', + xdgRuntimeDir: '/run/user/1000', + allowDocker: false, + extraAllowWrite: [], + existingCacheDirs: [], + }); +} + +type Settings = { + sandbox: { enabled: boolean; failIfUnavailable: boolean; allowUnsandboxedCommands: boolean; network: { allowAllUnixSockets: boolean }; filesystem: Record }; + permissions: { deny: string[] }; + hooks: { PreToolUse: Array<{ matcher: string; hooks: Array<{ command: string }> }> }; +}; + +describe('renderIsolationClaudeSettings (PAN-5754 WI-4)', () => { + it('turns every denyRead path into a Read(//…) rule and never emits a single-slash rule', () => { + const p = policy(); + const settings = renderIsolationClaudeSettings(p, '/home/op/.overdeck/bin/agent-isolation-guard', '/x/policy.json') as unknown as Settings; + for (const path of p.denyRead) expect(settings.permissions.deny).toContain(`Read(/${path})`); + for (const path of p.denyWrite) expect(settings.permissions.deny).toContain(`Edit(/${path}/**)`); + expect(settings.permissions.deny).toContain('Read(//home/op/.overdeck/internal-token)'); + for (const rule of settings.permissions.deny) expect(rule).not.toMatch(/^\w+\(\/[^/]/); + }); + + it('runs every Bash command in the sandbox with no unsandboxed retry', () => { + const settings = renderIsolationClaudeSettings(policy(), '/g', '/p') as unknown as Settings; + expect(settings.sandbox.enabled).toBe(true); + expect(settings.sandbox.allowUnsandboxedCommands).toBe(false); + expect(settings.sandbox.failIfUnavailable).toBe(true); + expect(settings.sandbox.network.allowAllUnixSockets).toBe(true); + expect(settings.sandbox.filesystem.allowRead).toEqual(['/home/op/.overdeck/agent-tokens/agent/agent-pan-1']); + }); + + it('wires the write guard hook with the policy file', () => { + const settings = renderIsolationClaudeSettings(policy(), '/home/op/.overdeck/bin/agent-isolation-guard', "/x/it's/policy.json") as unknown as Settings; + const [entry] = settings.hooks.PreToolUse; + expect(entry!.matcher).toBe('Edit|Write|MultiEdit|NotebookEdit'); + expect(entry!.hooks[0]!.command).toBe(`OVERDECK_ISOLATION_POLICY='/x/it'\\''s/policy.json' '/home/op/.overdeck/bin/agent-isolation-guard'`); + }); +}); + +describe('writeIsolationFiles', () => { + let home: string; + const originalHome = process.env.OVERDECK_HOME; + beforeEach(async () => { + home = await mkdtemp(join(tmpdir(), 'pan-5754-settings-')); + process.env.OVERDECK_HOME = home; + }); + afterEach(async () => { + if (originalHome === undefined) delete process.env.OVERDECK_HOME; + else process.env.OVERDECK_HOME = originalHome; + await rm(home, { recursive: true, force: true }); + }); + + it('writes 0600 claude-settings.json and policy.json under isolation///', async () => { + const { settingsFile, policyFile } = await writeIsolationFiles({ kind: 'agent', id: 'agent-pan-1' }, policy(home)); + expect(settingsFile).toBe(join(home, 'isolation', 'agent', 'agent-pan-1', 'claude-settings.json')); + expect(policyFile).toBe(join(home, 'isolation', 'agent', 'agent-pan-1', 'policy.json')); + expect((await stat(settingsFile)).mode & 0o777).toBe(0o600); + expect((await stat(policyFile)).mode & 0o777).toBe(0o600); + expect((await stat(join(home, 'isolation', 'agent', 'agent-pan-1'))).mode & 0o777).toBe(0o700); + const settings = JSON.parse(await readFile(settingsFile, 'utf8')) as Settings; + expect(settings.hooks.PreToolUse[0]!.hooks[0]!.command).toContain(policyFile); + expect(settings.hooks.PreToolUse[0]!.hooks[0]!.command).toContain(join(home, 'bin', 'agent-isolation-guard')); + }); + + it('refuses an owner id that is not one path segment', async () => { + await expect(writeIsolationFiles({ kind: 'conversation', id: '../x' }, policy(home))).rejects.toThrow('invalid owner id'); + }); +}); diff --git a/src/lib/agent-isolation/claude-settings.ts b/src/lib/agent-isolation/claude-settings.ts new file mode 100644 index 00000000000..9a1e5ed9924 --- /dev/null +++ b/src/lib/agent-isolation/claude-settings.ts @@ -0,0 +1,92 @@ +/** + * PAN-5754 WI-4: render an isolation policy as the Claude Code settings file an isolated + * launch passes with `--settings`, and write it with the guard hook's policy file. + * + * Permission rules use the `//` form: a single leading `/` is relative to the + * settings file and silently matches nothing (P17). Each path gets a bare rule (a file) + * and a `/**` rule (a directory's contents), so the renderer never guesses which it is. + */ +import { randomUUID } from 'node:crypto'; +import { mkdir, rename, unlink, writeFile } from 'node:fs/promises'; +import { join } from 'node:path'; + +import { getOverdeckHome } from '../paths.js'; +import { isolationOwnerDir, type AgentIsolationOwnerKind } from './paths.js'; +import { serializePolicy, type IsolationPolicy } from './policy.js'; + +export const ISOLATION_GUARD_HOOK = 'agent-isolation-guard'; +export const ISOLATION_POLICY_ENV = 'OVERDECK_ISOLATION_POLICY'; + +function shellQuote(value: string): string { + return `'${value.replace(/'/g, `'\\''`)}'`; +} + +function permissionRules(tool: 'Read' | 'Edit', paths: readonly string[]): string[] { + return paths.flatMap((path) => { + const abs = `/${path.replace(/\/+$/, '')}`; + return [`${tool}(${abs})`, `${tool}(${abs}/**)`]; + }); +} + +export function renderIsolationClaudeSettings(policy: IsolationPolicy, guardHookPath: string, policyFile: string): Record { + return { + sandbox: { + enabled: true, + failIfUnavailable: true, + allowUnsandboxedCommands: false, + autoAllowBashIfSandboxed: true, + network: { allowAllUnixSockets: true, allowedDomains: ['*'] }, + filesystem: { + denyRead: policy.denyRead, + allowRead: policy.allowRead, + allowWrite: policy.allowWrite, + denyWrite: policy.denyWrite, + }, + }, + permissions: { + deny: [...permissionRules('Read', policy.denyRead), ...permissionRules('Edit', policy.denyWrite)], + }, + hooks: { + PreToolUse: [ + { + matcher: 'Edit|Write|MultiEdit|NotebookEdit', + hooks: [{ type: 'command', command: `${ISOLATION_POLICY_ENV}=${shellQuote(policyFile)} ${shellQuote(guardHookPath)}` }], + }, + ], + }, + }; +} + +/** `/bin/agent-isolation-guard`, installed by `pan sync` from `sync-sources/hooks/`. */ +export function isolationGuardHookPath(): string { + return join(getOverdeckHome(), 'bin', ISOLATION_GUARD_HOOK); +} + +async function writeAtomic(file: string, content: string): Promise { + const temp = `${file}.${randomUUID()}.tmp`; + try { + await writeFile(temp, content, { mode: 0o600 }); + await rename(temp, file); + } catch (error) { + await unlink(temp).catch(() => undefined); + throw error; + } +} + +/** Write `claude-settings.json` and `policy.json` (0600) under `/isolation///` (0700). */ +export async function writeIsolationFiles( + owner: { kind: AgentIsolationOwnerKind; id: string }, + policy: IsolationPolicy, +): Promise<{ settingsFile: string; policyFile: string }> { + if (!owner.id || owner.id === '.' || owner.id === '..' || /[/\\\0]/.test(owner.id)) { + throw new Error(`agent isolation: invalid owner id ${JSON.stringify(owner.id)}`); + } + const dir = isolationOwnerDir(owner.kind, owner.id); + await mkdir(dir, { recursive: true, mode: 0o700 }); + const policyFile = join(dir, 'policy.json'); + const settingsFile = join(dir, 'claude-settings.json'); + await writeAtomic(policyFile, serializePolicy(policy)); + const settings = renderIsolationClaudeSettings(policy, isolationGuardHookPath(), policyFile); + await writeAtomic(settingsFile, `${JSON.stringify(settings, null, 2)}\n`); + return { settingsFile, policyFile }; +} From 104dc3bcf98b77109c178111527b2f6ca753919d Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 16:54:15 -0500 Subject: [PATCH 013/129] chore(workspace): plan artifacts for PAN-5754 Overdeck-Agent: agent-pan-5754 --- .pan/continues/PAN-5754.xbrief.json | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/.pan/continues/PAN-5754.xbrief.json b/.pan/continues/PAN-5754.xbrief.json index f5fce5c9911..5645a8eeb32 100644 --- a/.pan/continues/PAN-5754.xbrief.json +++ b/.pan/continues/PAN-5754.xbrief.json @@ -2,7 +2,7 @@ "version": "1", "issueId": "PAN-5754", "created": "2026-12-03T21:28:28.525Z", - "updated": "2026-12-03T21:53:09.165Z", + "updated": "2026-12-03T21:54:15.430Z", "gitState": {}, "decisions": [], "hazards": [], @@ -80,9 +80,22 @@ "doneAt": "2026-12-03T21:53:07.731Z" }, "claude-settings": { - "status": "in_progress", + "status": "completed", "claimedBy": "agent-pan-5754", - "claimedAt": "2026-12-03T21:53:09.165Z" + "claimedAt": "2026-12-03T21:53:09.165Z", + "doneAt": "2026-12-03T21:54:15.430Z" + }, + "claude-settings.ac1": { + "status": "completed", + "doneAt": "2026-12-03T21:54:15.430Z" + }, + "claude-settings.ac2": { + "status": "completed", + "doneAt": "2026-12-03T21:54:15.430Z" + }, + "claude-settings.ac3": { + "status": "completed", + "doneAt": "2026-12-03T21:54:15.430Z" } } } From 102a2847c9740ea428a1bfba97e62e5997523d44 Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 16:54:16 -0500 Subject: [PATCH 014/129] chore(workspace): plan artifacts for PAN-5754 Overdeck-Agent: agent-pan-5754 --- .pan/continues/PAN-5754.xbrief.json | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/.pan/continues/PAN-5754.xbrief.json b/.pan/continues/PAN-5754.xbrief.json index 5645a8eeb32..cbb0c168caa 100644 --- a/.pan/continues/PAN-5754.xbrief.json +++ b/.pan/continues/PAN-5754.xbrief.json @@ -2,7 +2,7 @@ "version": "1", "issueId": "PAN-5754", "created": "2026-12-03T21:28:28.525Z", - "updated": "2026-12-03T21:54:15.430Z", + "updated": "2026-12-03T21:54:16.764Z", "gitState": {}, "decisions": [], "hazards": [], @@ -96,6 +96,11 @@ "claude-settings.ac3": { "status": "completed", "doneAt": "2026-12-03T21:54:15.430Z" + }, + "write-guard-hook": { + "status": "in_progress", + "claimedBy": "agent-pan-5754", + "claimedAt": "2026-12-03T21:54:16.764Z" } } } From 3cdfe9794d4c09fb0a8455a7bc5bb78f5b4fff3b Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 16:54:31 -0500 Subject: [PATCH 015/129] feat(infra): add the agent-isolation-guard PreToolUse write guard PAN-5754 WI-5. Claude Code's sandbox covers Bash only, so this hook keeps Edit, Write, MultiEdit and NotebookEdit inside the isolation policy: it resolves the target with realpath -m (a symlink is judged by its destination), allows a path under an allowWrite root and no denyWrite root, and otherwise prints a PreToolUse deny. A missing or invalid policy, a missing jq or a payload with no path all deny. pan sync already installs every file in sync-sources/hooks/ to ~/.overdeck/bin. Item: write-guard-hook Item: write-guard-hook.ac1 Item: write-guard-hook.ac2 Item: write-guard-hook.ac3 Co-Authored-By: Claude Opus 5.5 Overdeck-Agent: agent-pan-5754 --- sync-sources/hooks/agent-isolation-guard | 70 ++++++++++++++++ tests/scripts/agent-isolation-guard.test.ts | 88 +++++++++++++++++++++ 2 files changed, 158 insertions(+) create mode 100755 sync-sources/hooks/agent-isolation-guard create mode 100644 tests/scripts/agent-isolation-guard.test.ts diff --git a/sync-sources/hooks/agent-isolation-guard b/sync-sources/hooks/agent-isolation-guard new file mode 100755 index 00000000000..a58b3666dd8 --- /dev/null +++ b/sync-sources/hooks/agent-isolation-guard @@ -0,0 +1,70 @@ +#!/bin/bash +# ~/.overdeck/bin/agent-isolation-guard (PAN-5754 WI-5) +# +# PreToolUse hook on Edit, Write, MultiEdit and NotebookEdit for isolated agents. +# Claude Code's sandbox covers Bash only; this hook keeps the file tools inside the +# isolation policy's writable paths. The policy file (OVERDECK_ISOLATION_POLICY) +# holds { "version": 1, "allowWrite": [...], "denyWrite": [...] }. +# +# Allow: the resolved target lies under an allowWrite root and under no denyWrite +# root. The hook then prints nothing and exits 0. +# Otherwise it prints a PreToolUse "deny" decision. It fails closed: a missing or +# unreadable policy, a missing jq, or a payload without a target path all deny. + +set -u + +deny() { + local reason="$1" + if command -v jq >/dev/null 2>&1; then + jq -cn --arg reason "agent isolation: $reason" \ + '{hookSpecificOutput: {hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: $reason}}' + else + printf '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"agent isolation: %s"}}\n' "jq is not installed" + fi + exit 0 +} + +INPUT=$(cat 2>/dev/null || true) + +command -v jq >/dev/null 2>&1 || deny "jq is not installed" + +POLICY="${OVERDECK_ISOLATION_POLICY:-}" +[ -n "$POLICY" ] && [ -r "$POLICY" ] || deny "isolation policy file is missing or unreadable" +jq -e '.version == 1 and (.allowWrite | type == "array") and (.denyWrite | type == "array")' "$POLICY" >/dev/null 2>&1 \ + || deny "isolation policy file is invalid" + +TARGET=$(printf '%s' "$INPUT" | jq -r '.tool_input.file_path // .tool_input.notebook_path // empty' 2>/dev/null) +[ -n "$TARGET" ] || deny "the tool call names no file path" + +case "$TARGET" in + /*) ;; + *) + CWD=$(printf '%s' "$INPUT" | jq -r '.cwd // empty' 2>/dev/null) + TARGET="${CWD:-$PWD}/$TARGET" + ;; +esac + +# realpath -m resolves every existing symlink on the way, so a link is judged by +# its destination, and tolerates components that do not exist yet. +RESOLVED=$(realpath -m -- "$TARGET" 2>/dev/null) || deny "$TARGET cannot be resolved" + +under() { + local path="$1" root="$2" + [ "$path" = "$root" ] || case "$path" in "$root"/*) return 0 ;; *) return 1 ;; esac +} + +in_roots() { + local key="$1" root canonical + while IFS= read -r root; do + [ -n "$root" ] || continue + canonical=$(realpath -m -- "$root" 2>/dev/null) || canonical="$root" + if under "$RESOLVED" "$canonical" || under "$RESOLVED" "$root"; then return 0; fi + done < <(jq -r --arg key "$key" '.[$key][]' "$POLICY" 2>/dev/null) + return 1 +} + +if in_roots denyWrite || ! in_roots allowWrite; then + deny "$RESOLVED is outside this agent's writable paths" +fi + +exit 0 diff --git a/tests/scripts/agent-isolation-guard.test.ts b/tests/scripts/agent-isolation-guard.test.ts new file mode 100644 index 00000000000..f85ab009e66 --- /dev/null +++ b/tests/scripts/agent-isolation-guard.test.ts @@ -0,0 +1,88 @@ +/** + * PAN-5754 WI-5: the agent-isolation-guard PreToolUse hook keeps Edit/Write/ + * MultiEdit/NotebookEdit inside the isolation policy and fails closed. + */ +import { spawnSync } from 'node:child_process' +import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' + +const SCRIPT_PATH = join(process.cwd(), 'sync-sources', 'hooks', 'agent-isolation-guard') + +let root: string +let workspace: string +let home: string +let policyFile: string + +function runHook(payload: unknown, policy: string | null = policyFile): { stdout: string; status: number | null } { + const env: NodeJS.ProcessEnv = { ...process.env } + if (policy === null) delete env.OVERDECK_ISOLATION_POLICY + else env.OVERDECK_ISOLATION_POLICY = policy + const result = spawnSync('bash', [SCRIPT_PATH], { input: JSON.stringify(payload), env, encoding: 'utf8' }) + return { stdout: result.stdout, status: result.status } +} + +function decision(stdout: string): string | undefined { + if (!stdout.trim()) return undefined + return (JSON.parse(stdout) as { hookSpecificOutput: { permissionDecision: string } }).hookSpecificOutput.permissionDecision +} + +beforeEach(() => { + root = realpathSync(mkdtempSync(join(tmpdir(), 'pan-5754-guard-'))) + workspace = join(root, 'ws') + home = join(root, 'home', '.overdeck') + mkdirSync(join(workspace, '.claude'), { recursive: true }) + mkdirSync(home, { recursive: true }) + writeFileSync(join(home, 'config.yaml'), 'x: 1\n') + policyFile = join(root, 'policy.json') + writeFileSync(policyFile, JSON.stringify({ + version: 1, + allowWrite: [workspace, join(home, 'logs')], + denyWrite: [join(workspace, '.claude'), join(home, 'config.yaml')], + })) +}) + +afterEach(() => { + rmSync(root, { recursive: true, force: true }) +}) + +describe('agent-isolation-guard', () => { + it('allows a Write to a workspace file silently', () => { + const result = runHook({ tool_name: 'Write', tool_input: { file_path: join(workspace, 'src', 'a.ts') }, cwd: workspace }) + expect(result.status).toBe(0) + expect(result.stdout).toBe('') + }) + + it('allows a NotebookEdit and a relative path resolved against the payload cwd', () => { + expect(runHook({ tool_name: 'NotebookEdit', tool_input: { notebook_path: join(workspace, 'n.ipynb') } }).stdout).toBe('') + expect(runHook({ tool_name: 'Edit', tool_input: { file_path: 'src/b.ts' }, cwd: workspace }).stdout).toBe('') + }) + + it('denies a path outside the writable roots', () => { + const result = runHook({ tool_name: 'Edit', tool_input: { file_path: join(home, 'config.yaml') }, cwd: workspace }) + expect(result.status).toBe(0) + expect(decision(result.stdout)).toBe('deny') + expect(result.stdout).toContain("outside this agent's writable paths") + }) + + it('denies a write-denied path inside an allowed root', () => { + expect(decision(runHook({ tool_name: 'Write', tool_input: { file_path: join(workspace, '.claude', 'settings.json') } }).stdout)).toBe('deny') + }) + + it('judges a cwd symlink by its destination', () => { + symlinkSync(join(home, 'config.yaml'), join(workspace, 'innocent.yaml')) + const result = runHook({ tool_name: 'Edit', tool_input: { file_path: join(workspace, 'innocent.yaml') }, cwd: workspace }) + expect(decision(result.stdout)).toBe('deny') + expect(result.stdout).toContain(join(home, 'config.yaml')) + }) + + it('denies when the policy file is missing or unset', () => { + expect(decision(runHook({ tool_name: 'Write', tool_input: { file_path: join(workspace, 'a') } }, join(root, 'nope.json')).stdout)).toBe('deny') + expect(decision(runHook({ tool_name: 'Write', tool_input: { file_path: join(workspace, 'a') } }, null).stdout)).toBe('deny') + }) + + it('denies a payload without a file path', () => { + expect(decision(runHook({ tool_name: 'Write', tool_input: {} }).stdout)).toBe('deny') + }) +}) From b889175937e6bd993d8176bbff217c19264c4294 Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 16:55:00 -0500 Subject: [PATCH 016/129] chore(workspace): plan artifacts for PAN-5754 Overdeck-Agent: agent-pan-5754 --- .pan/continues/PAN-5754.xbrief.json | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/.pan/continues/PAN-5754.xbrief.json b/.pan/continues/PAN-5754.xbrief.json index cbb0c168caa..97caed7ccd5 100644 --- a/.pan/continues/PAN-5754.xbrief.json +++ b/.pan/continues/PAN-5754.xbrief.json @@ -2,7 +2,7 @@ "version": "1", "issueId": "PAN-5754", "created": "2026-12-03T21:28:28.525Z", - "updated": "2026-12-03T21:54:16.764Z", + "updated": "2026-12-03T21:54:59.964Z", "gitState": {}, "decisions": [], "hazards": [], @@ -98,9 +98,22 @@ "doneAt": "2026-12-03T21:54:15.430Z" }, "write-guard-hook": { - "status": "in_progress", + "status": "completed", "claimedBy": "agent-pan-5754", - "claimedAt": "2026-12-03T21:54:16.764Z" + "claimedAt": "2026-12-03T21:54:16.764Z", + "doneAt": "2026-12-03T21:54:59.963Z" + }, + "write-guard-hook.ac1": { + "status": "completed", + "doneAt": "2026-12-03T21:54:59.963Z" + }, + "write-guard-hook.ac2": { + "status": "completed", + "doneAt": "2026-12-03T21:54:59.963Z" + }, + "write-guard-hook.ac3": { + "status": "completed", + "doneAt": "2026-12-03T21:54:59.963Z" } } } From 7593262e6b76f8f0cb68f66886865f2b9a4511a1 Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 16:55:02 -0500 Subject: [PATCH 017/129] chore(workspace): plan artifacts for PAN-5754 Overdeck-Agent: agent-pan-5754 --- .pan/continues/PAN-5754.xbrief.json | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/.pan/continues/PAN-5754.xbrief.json b/.pan/continues/PAN-5754.xbrief.json index 97caed7ccd5..cafb87b3d8d 100644 --- a/.pan/continues/PAN-5754.xbrief.json +++ b/.pan/continues/PAN-5754.xbrief.json @@ -2,7 +2,7 @@ "version": "1", "issueId": "PAN-5754", "created": "2026-12-03T21:28:28.525Z", - "updated": "2026-12-03T21:54:59.964Z", + "updated": "2026-12-03T21:55:02.104Z", "gitState": {}, "decisions": [], "hazards": [], @@ -114,6 +114,11 @@ "write-guard-hook.ac3": { "status": "completed", "doneAt": "2026-12-03T21:54:59.963Z" + }, + "launch-isolation": { + "status": "in_progress", + "claimedBy": "agent-pan-5754", + "claimedAt": "2026-12-03T21:55:02.104Z" } } } From 41a8cd2b49650c58ab24cebe5038de1959237126 Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:06:18 -0500 Subject: [PATCH 018/129] fix(infra): keep a plain clone's .git writable in the isolation policy PAN-5754 iso-policy follow-up. buildIsolationPolicy write-denied /.git for every repo root, but in a plain clone that path is the git common dir it also allows, and a deny wins, so the agent could not commit. Only a .git that is not a common dir (a worktree pointer file) is denied now; the common dir's hooks/ and config stay denied. resolveIsolationPolicyInput also takes the global config layer, so callers and tests pass their own. Co-Authored-By: Claude Opus 5.5 Overdeck-Agent: agent-pan-5754 --- src/lib/agent-isolation/__tests__/policy.test.ts | 14 +++++++++++++- src/lib/agent-isolation/policy-input.ts | 5 ++++- src/lib/agent-isolation/policy.ts | 8 +++++--- 3 files changed, 22 insertions(+), 5 deletions(-) diff --git a/src/lib/agent-isolation/__tests__/policy.test.ts b/src/lib/agent-isolation/__tests__/policy.test.ts index 5448fecc6c9..f5e3be201b1 100644 --- a/src/lib/agent-isolation/__tests__/policy.test.ts +++ b/src/lib/agent-isolation/__tests__/policy.test.ts @@ -54,6 +54,13 @@ describe('buildIsolationPolicy (PAN-5754 D-8)', () => { ])); }); + it('keeps a plain clone writable: its .git is the common dir, only hooks/ and config are denied', () => { + const policy = buildIsolationPolicy(input({ workspace: '/r', repoRoots: ['/r'], gitCommonDirs: ['/r/.git'] })); + expect(policy.allowWrite).toContain('/r/.git'); + expect(policy.denyWrite).not.toContain('/r/.git'); + expect(policy.denyWrite).toEqual(expect.arrayContaining(['/r/.git/hooks', '/r/.git/config'])); + }); + it('masks the docker socket unless allowDocker', () => { expect(buildIsolationPolicy(input()).maskedSocketDirs).toEqual(expect.arrayContaining(['/var/run/docker.sock', '/run/docker.sock'])); const allowed = buildIsolationPolicy(input({ allowDocker: true })); @@ -110,7 +117,12 @@ describe('resolveIsolationPolicyInput', () => { await mkdir(join(dir, 'docs')); await writeFile(join(dir, 'docs', 'README.md'), 'x'); - const resolved = await resolveIsolationPolicyInput({ kind: 'agent', id: 'agent-pan-1' }, dir); + const resolved = await resolveIsolationPolicyInput({ kind: 'agent', id: 'agent-pan-1' }, dir, { agents: { isolation: { allow_docker: true, allow_write: ['/srv/x'] } } }); + expect(resolved.allowDocker).toBe(true); + expect(resolved.extraAllowWrite).toEqual(['/srv/x']); + const policy = buildIsolationPolicy(resolved); + expect(policy.denyWrite).not.toContain(join(dir, '.git')); + expect(policy.allowWrite).toContain(join(dir, '.git')); expect(resolved.repoRoots).toEqual([dir, child]); expect(resolved.gitCommonDirs).toEqual([join(dir, '.git'), join(child, '.git')]); expect(resolved.tmuxSocketDir).toMatch(/\/tmux-\d+$/); diff --git a/src/lib/agent-isolation/policy-input.ts b/src/lib/agent-isolation/policy-input.ts index 5ea9b027c24..7136f2116c7 100644 --- a/src/lib/agent-isolation/policy-input.ts +++ b/src/lib/agent-isolation/policy-input.ts @@ -8,6 +8,7 @@ import { homedir } from 'node:os'; import { dirname, join, resolve } from 'node:path'; import { promisify } from 'node:util'; +import type { YamlConfig } from '../config-yaml/schema.js'; import { getOverdeckHome } from '../paths.js'; import { herdrSocketPath } from '../terminal-backends/select.js'; import { readAgentIsolationConfig } from './config.js'; @@ -63,10 +64,12 @@ async function isDirectory(path: string): Promise { export async function resolveIsolationPolicyInput( owner: { kind: 'agent' | 'conversation'; id: string }, workspace: string, + /** The global config layer; defaults to ~/.overdeck/config.yaml. */ + globalConfig?: YamlConfig | null, ): Promise { const homeDir = homedir(); const uid = process.getuid?.() ?? 0; - const config = readAgentIsolationConfig(); + const config = readAgentIsolationConfig(globalConfig); const repoRoots = await findRepoRoots(workspace); const gitCommonDirs = [...new Set((await Promise.all(repoRoots.map(gitCommonDir))).filter((dir): dir is string => dir !== null))]; const cacheCandidates = PACKAGE_CACHE_DIRS.map((dir) => join(homeDir, dir)); diff --git a/src/lib/agent-isolation/policy.ts b/src/lib/agent-isolation/policy.ts index 2433ed1de52..9499859a08a 100644 --- a/src/lib/agent-isolation/policy.ts +++ b/src/lib/agent-isolation/policy.ts @@ -10,7 +10,7 @@ * `` (the databases, `logs/`, `tmp/`, the gate admission queue), the * package caches present at launch, and `agents.isolation.allow_write`. Every other * entry of `` stays read-only, including `agent-api/` and `isolation/`. - * - `denyWrite`: everything in `denyRead`, the workspace's `.git` files, `.claude/` and + * - `denyWrite`: everything in `denyRead`, the workspace's `.git` pointer files, `.claude/` and * `.mcp.json`, each git common dir's `hooks/` and `config`, and the cache directories * whose contents run outside the sandbox (MCP servers, browsers). * - `maskedSocketDirs`: Herdr, tmux, Overdeck, the user runtime dir, X11 and (unless @@ -24,7 +24,7 @@ export interface IsolationPolicyInput { overdeckHome: string; homeDir: string; workspace: string; - /** The workspace root and each child repo root (polyrepo); each `/.git` is write-denied. */ + /** The workspace root and each child repo root (polyrepo); each `/.git` file (a worktree pointer) is write-denied. */ repoRoots: string[]; /** `git rev-parse --git-common-dir` of every repo root, absolute. */ gitCommonDirs: string[]; @@ -118,9 +118,11 @@ export function buildIsolationPolicy(input: IsolationPolicyInput): IsolationPoli ]); const existingCaches = new Set(input.existingCacheDirs); + const commonDirs = new Set(input.gitCommonDirs); const denyWrite = unique([ ...denyRead, - ...input.repoRoots.map((root) => join(root, '.git')), + // A plain clone's `.git` is its common dir, which must stay writable (its hooks/ and config are denied below). + ...input.repoRoots.map((root) => join(root, '.git')).filter((gitPath) => !commonDirs.has(gitPath)), join(input.workspace, '.claude'), join(input.workspace, '.mcp.json'), ...input.gitCommonDirs.flatMap((dir) => [join(dir, 'hooks'), join(dir, 'config')]), From c2d79ca34502354f392235f004cad4da3aa77a26 Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:06:19 -0500 Subject: [PATCH 019/129] fix(infra): resolve guard hook paths without GNU realpath -m PAN-5754 write-guard-hook follow-up. BSD realpath (macOS) has no -m, and the guard fails closed, so it would have denied every edit there. It now falls back to a node one-liner that canonicalizes the longest existing prefix and keeps the missing tail. Co-Authored-By: Claude Opus 5.5 Overdeck-Agent: agent-pan-5754 --- sync-sources/hooks/agent-isolation-guard | 14 ++++++++++---- tests/scripts/agent-isolation-guard.test.ts | 17 ++++++++++++++--- 2 files changed, 24 insertions(+), 7 deletions(-) diff --git a/sync-sources/hooks/agent-isolation-guard b/sync-sources/hooks/agent-isolation-guard index a58b3666dd8..4b0e2728f7d 100755 --- a/sync-sources/hooks/agent-isolation-guard +++ b/sync-sources/hooks/agent-isolation-guard @@ -44,9 +44,15 @@ case "$TARGET" in ;; esac -# realpath -m resolves every existing symlink on the way, so a link is judged by -# its destination, and tolerates components that do not exist yet. -RESOLVED=$(realpath -m -- "$TARGET" 2>/dev/null) || deny "$TARGET cannot be resolved" +# Canonicalize a path: every existing symlink on the way is resolved, so a link is +# judged by its destination, and components that do not exist yet are kept. +# GNU realpath -m does this; BSD realpath (macOS) has no -m, so fall back to node. +canonical_path() { + realpath -m -- "$1" 2>/dev/null && return 0 + node -e 'const fs=require("fs"),p=require("path");let x=p.resolve(process.argv[1]);const rest=[];for(;;){try{console.log(p.join(fs.realpathSync(x),...rest));break}catch{const d=p.dirname(x);if(d===x){console.log(p.resolve(process.argv[1]));break}rest.unshift(p.basename(x));x=d}}' "$1" 2>/dev/null +} + +RESOLVED=$(canonical_path "$TARGET") && [ -n "$RESOLVED" ] || deny "$TARGET cannot be resolved" under() { local path="$1" root="$2" @@ -57,7 +63,7 @@ in_roots() { local key="$1" root canonical while IFS= read -r root; do [ -n "$root" ] || continue - canonical=$(realpath -m -- "$root" 2>/dev/null) || canonical="$root" + canonical=$(canonical_path "$root") || canonical="$root" if under "$RESOLVED" "$canonical" || under "$RESOLVED" "$root"; then return 0; fi done < <(jq -r --arg key "$key" '.[$key][]' "$POLICY" 2>/dev/null) return 1 diff --git a/tests/scripts/agent-isolation-guard.test.ts b/tests/scripts/agent-isolation-guard.test.ts index f85ab009e66..8b7010b29f6 100644 --- a/tests/scripts/agent-isolation-guard.test.ts +++ b/tests/scripts/agent-isolation-guard.test.ts @@ -3,7 +3,7 @@ * MultiEdit/NotebookEdit inside the isolation policy and fails closed. */ import { spawnSync } from 'node:child_process' -import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' +import { chmodSync, mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' @@ -15,8 +15,8 @@ let workspace: string let home: string let policyFile: string -function runHook(payload: unknown, policy: string | null = policyFile): { stdout: string; status: number | null } { - const env: NodeJS.ProcessEnv = { ...process.env } +function runHook(payload: unknown, policy: string | null = policyFile, extraEnv: NodeJS.ProcessEnv = {}): { stdout: string; status: number | null } { + const env: NodeJS.ProcessEnv = { ...process.env, ...extraEnv } if (policy === null) delete env.OVERDECK_ISOLATION_POLICY else env.OVERDECK_ISOLATION_POLICY = policy const result = spawnSync('bash', [SCRIPT_PATH], { input: JSON.stringify(payload), env, encoding: 'utf8' }) @@ -77,6 +77,17 @@ describe('agent-isolation-guard', () => { expect(result.stdout).toContain(join(home, 'config.yaml')) }) + it('falls back to node when realpath has no -m (BSD realpath on macOS)', () => { + const bin = join(root, 'bin') + mkdirSync(bin) + writeFileSync(join(bin, 'realpath'), '#!/bin/sh\nexit 1\n') + chmodSync(join(bin, 'realpath'), 0o755) + const env = { PATH: `${bin}:${process.env.PATH ?? ''}` } + symlinkSync(join(home, 'config.yaml'), join(workspace, 'innocent.yaml')) + expect(decision(runHook({ tool_name: 'Edit', tool_input: { file_path: join(workspace, 'innocent.yaml') } }, policyFile, env).stdout)).toBe('deny') + expect(runHook({ tool_name: 'Write', tool_input: { file_path: join(workspace, 'new', 'a.ts') } }, policyFile, env).stdout).toBe('') + }) + it('denies when the policy file is missing or unset', () => { expect(decision(runHook({ tool_name: 'Write', tool_input: { file_path: join(workspace, 'a') } }, join(root, 'nope.json')).stdout)).toBe('deny') expect(decision(runHook({ tool_name: 'Write', tool_input: { file_path: join(workspace, 'a') } }, null).stdout)).toBe('deny') From dda1946a4281c174cad016f158c52f27f11da984 Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:06:19 -0500 Subject: [PATCH 020/129] feat(infra): wire agent isolation into the launcher PAN-5754 WI-6. prepareAgentIsolation returns {} for conversations, the Flywheel and when agents.isolation.enabled is false. Otherwise it fails closed: a Linux claude-code launch without bwrap or socat is refused with the D-12 install hint, then ensureIsolationToken mints (and throws on failure), the policy is built and, for claude-code, the settings and policy files are written. LauncherConfig.isolation adds, before cd: mkdir of the masked socket dirs, the OVERDECK_AGENT_TOKEN_FILE / OVERDECK_DASHBOARD_SOCKET / OVERDECK_ISOLATED / NODE_USE_ENV_PROXY exports, unset OVERDECK_INTERNAL_TOKEN and the root-registry line (pid + /proc start time). Claude commands get --settings "$PAN_ISO_SETTINGS". The review sub-role's post-exit pan tell and pan admin agents exited run under env -u OVERDECK_AGENT_TOKEN_FILE (D-15). Deviation: skill overrides already pass --settings "$PAN_SKILL_SETTINGS", and Claude Code keeps one --settings value. The launcher folds the skill JSON into a per-launch copy of the isolation settings (arrays concatenated, isolation scalars win) and clears PAN_SKILL_SETTINGS; a failed merge keeps the isolation file alone, so the sandbox is never dropped. Helpers live in agent-isolation/launcher-lines.ts to keep launcher-generator.ts under its cap. Item: launch-isolation Item: launch-isolation.ac1 Item: launch-isolation.ac2 Item: launch-isolation.ac3 Item: launch-isolation.ac4 Item: launch-isolation.ac5 Co-Authored-By: Claude Opus 5.5 Overdeck-Agent: agent-pan-5754 --- .../__tests__/launch-isolation.test.ts | 169 ++++++++++++++++++ src/lib/agent-isolation/launch.ts | 93 ++++++++++ src/lib/agent-isolation/launcher-lines.ts | 80 +++++++++ src/lib/launcher-generator.ts | 16 +- 4 files changed, 354 insertions(+), 4 deletions(-) create mode 100644 src/lib/agent-isolation/__tests__/launch-isolation.test.ts create mode 100644 src/lib/agent-isolation/launch.ts create mode 100644 src/lib/agent-isolation/launcher-lines.ts diff --git a/src/lib/agent-isolation/__tests__/launch-isolation.test.ts b/src/lib/agent-isolation/__tests__/launch-isolation.test.ts new file mode 100644 index 00000000000..c5e5a65decf --- /dev/null +++ b/src/lib/agent-isolation/__tests__/launch-isolation.test.ts @@ -0,0 +1,169 @@ +/** + * PAN-5754 WI-6: an isolated launch's launcher script (settings flag, env, unset, root + * registration, D-15 post-exit prefix) and prepareAgentIsolation's fail-closed paths. + */ +import { spawnSync } from 'node:child_process'; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +vi.mock('../../mcp/agent-token.js', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, ensureIsolationToken: vi.fn(actual.ensureIsolationToken) }; +}); + +import { generateLauncherScript, type LauncherConfig } from '../../launcher-generator.js'; +import { ensureIsolationToken } from '../../mcp/agent-token.js'; +import type { OverdeckMcpLaunchOwner } from '../../mcp/agent-injection.js'; +import { prepareAgentIsolation } from '../launch.js'; +import { isolationLauncherLines, isolationSettingsArg, type LaunchIsolation } from '../launcher-lines.js'; + +let home: string; +const originalHome = process.env.OVERDECK_HOME; + +beforeEach(() => { + home = mkdtempSync(join(tmpdir(), 'pan-5754-launch-')); + process.env.OVERDECK_HOME = home; +}); + +afterEach(() => { + vi.mocked(ensureIsolationToken).mockReset(); + if (originalHome === undefined) delete process.env.OVERDECK_HOME; + else process.env.OVERDECK_HOME = originalHome; + rmSync(home, { recursive: true, force: true }); +}); + +const ISOLATION: LaunchIsolation = { + settingsFile: '/h/isolation/agent/agent-pan-1/claude-settings.json', + env: { OVERDECK_AGENT_TOKEN_FILE: '/h/agent-tokens/agent/agent-pan-1/mcp-token', OVERDECK_ISOLATED: '1' }, + unsetEnv: ['OVERDECK_INTERNAL_TOKEN'], + mkdirs: ['/tmp/tmux-1000'], + rootFile: '/h/isolation/roots/agent-pan-1.json', +}; + +const WORK: LauncherConfig = { role: 'work', workingDir: '/workspace/project', baseCommand: 'claude', sessionId: 'sess-1' }; + +describe('generateLauncherScript with isolation (PAN-5754 WI-6)', () => { + it('adds --settings, the exports, the unset and the root registration before cd', () => { + const script = generateLauncherScript({ ...WORK, isolation: ISOLATION }); + expect(script).toContain(`PAN_ISO_SETTINGS='${ISOLATION.settingsFile}'`); + expect(script.split('\n').find((line) => line.includes('--session-id'))).toContain('--settings "$PAN_ISO_SETTINGS"'); + expect(script).toContain(`export OVERDECK_AGENT_TOKEN_FILE='${ISOLATION.env.OVERDECK_AGENT_TOKEN_FILE}'`); + expect(script).toContain('unset OVERDECK_INTERNAL_TOKEN'); + expect(script).toContain("mkdir -p -m 700 '/tmp/tmux-1000'"); + expect(script).toContain(ISOLATION.rootFile); + expect(script.indexOf('unset OVERDECK_INTERNAL_TOKEN')).toBeLessThan(script.indexOf("cd -- '/workspace/project'")); + }); + + it('adds --settings to a conversation-mode claude command too', () => { + const script = generateLauncherScript({ ...WORK, spawnMode: 'conversation', isolation: ISOLATION }); + expect(script).toContain('--settings "$PAN_ISO_SETTINGS"'); + }); + + it('leaves a launch without isolation unchanged', () => { + const plain = generateLauncherScript(WORK); + expect(generateLauncherScript({ ...WORK, isolation: undefined })).toBe(plain); + expect(plain).not.toContain("--settings '"); + expect(plain).not.toContain('OVERDECK_AGENT_TOKEN_FILE'); + expect(plain).not.toContain('isolation/roots'); + }); + + it('keeps the operator credential for the review sub-role post-exit pan calls (D-15)', () => { + const script = generateLauncherScript({ + ...WORK, + role: 'review', + isolation: ISOLATION, + reviewSignal: { + agentId: 'agent-pan-1-review-security', + synthesisAgentId: 'agent-pan-1-review', + subRole: 'security', + outputPath: '/tmp/review.md', + signalMarkerPath: '/tmp/signaled', + launcherPidPath: '/tmp/pid', + timeoutSeconds: 1800, + }, + }); + const tellLines = script.split('\n').filter((line) => line.includes(" tell 'agent-pan-1-review'")); + expect(tellLines).toHaveLength(3); + for (const line of tellLines) expect(line.trimStart().startsWith('env -u OVERDECK_AGENT_TOKEN_FILE pan tell')).toBe(true); + expect(script).toContain('if env -u OVERDECK_AGENT_TOKEN_FILE pan admin agents exited'); + expect(script).not.toMatch(/if pan admin agents exited/); + }); +}); + +describe('skill settings merge (PAN-5754 WI-6)', () => { + function runLines(skillSettings: string): { stdout: string; merged: string } { + const dir = join(home, 'isolation', 'agent', 'agent-pan-1'); + mkdirSync(dir, { recursive: true }); + const settingsFile = join(dir, 'claude-settings.json'); + writeFileSync(settingsFile, JSON.stringify({ sandbox: { enabled: true }, permissions: { deny: ['Read(//h/internal-token)'] } })); + const lines = isolationLauncherLines({ ...ISOLATION, settingsFile, mkdirs: [], rootFile: join(home, 'roots', 'a.json') }); + const script = [...lines, `echo "ARG:${isolationSettingsArg({ ...ISOLATION, settingsFile })}" "SKILL:$PAN_SKILL_SETTINGS"`].join('\n'); + const result = spawnSync('bash', ['-c', script], { env: { ...process.env, PAN_SKILL_SETTINGS: skillSettings }, encoding: 'utf8' }); + const mergedFile = join(dir, 'claude-settings.merged.json'); + return { stdout: result.stdout, merged: existsSync(mergedFile) ? readFileSync(mergedFile, 'utf8') : '' }; + } + + it('folds skill override settings into one settings file and keeps the sandbox', () => { + const { stdout, merged } = runLines(JSON.stringify({ skillOverrides: { x: 'off' }, permissions: { deny: ['Bash(rm:*)'] }, sandbox: { enabled: false } })); + expect(stdout).toContain('claude-settings.merged.json'); + expect(stdout).toContain('SKILL:\n'); + expect(JSON.parse(merged)).toEqual({ + skillOverrides: { x: 'off' }, + permissions: { deny: ['Bash(rm:*)', 'Read(//h/internal-token)'] }, + sandbox: { enabled: true }, + }); + }); + + it('keeps the isolation settings alone when the skill JSON cannot merge', () => { + const { stdout } = runLines('{not json'); + expect(stdout).toContain(`ARG: --settings ${join(home, 'isolation', 'agent', 'agent-pan-1', 'claude-settings.json')}`); + }); +}); + +function owner(overrides: Partial = {}): OverdeckMcpLaunchOwner { + return { agentId: 'agent-pan-1', agentKind: 'agent', role: 'work', harness: 'claude-code', cwd: home, ...overrides }; +} + +const allPresent = { platform: 'linux' as const, which: async (binary: string) => `/usr/bin/${binary}`, config: {} }; + +describe('prepareAgentIsolation (PAN-5754 WI-6)', () => { + it('returns {} for a conversation, the Flywheel, and when the switch is off', async () => { + expect(await prepareAgentIsolation(owner({ role: 'conversation', agentKind: 'conversation', agentId: 'c1' }), allPresent)).toEqual({}); + expect(await prepareAgentIsolation(owner({ role: 'flywheel' }), allPresent)).toEqual({}); + expect(await prepareAgentIsolation(owner(), { ...allPresent, config: { agents: { isolation: { enabled: false } } } })).toEqual({}); + }); + + it('refuses a Linux claude-code launch when socat is missing, before any mint', async () => { + await expect(prepareAgentIsolation(owner(), { ...allPresent, which: async (binary) => (binary === 'socat' ? null : '/usr/bin/bwrap') })) + .rejects.toThrow(/missing: socat\).*sudo apt-get install bubblewrap socat/); + expect(ensureIsolationToken).not.toHaveBeenCalled(); + }); + + it('rejects when the token mint fails and writes no settings file', async () => { + vi.mocked(ensureIsolationToken).mockRejectedValueOnce(new Error('agent isolation: token mint failed for agent-pan-1: boom')); + await expect(prepareAgentIsolation(owner(), allPresent)).rejects.toThrow('agent isolation: token mint failed for agent-pan-1'); + expect(existsSync(join(home, 'isolation', 'agent', 'agent-pan-1', 'claude-settings.json'))).toBe(false); + }); + + it('builds the launch isolation for a work agent', async () => { + const { isolation } = await prepareAgentIsolation(owner(), allPresent); + expect(isolation?.settingsFile).toBe(join(home, 'isolation', 'agent', 'agent-pan-1', 'claude-settings.json')); + expect(existsSync(isolation!.settingsFile!)).toBe(true); + expect(isolation?.env).toEqual({ + OVERDECK_AGENT_TOKEN_FILE: join(home, 'agent-tokens', 'agent', 'agent-pan-1', 'mcp-token'), + OVERDECK_DASHBOARD_SOCKET: join(home, 'agent-api', 'dashboard.sock'), + OVERDECK_ISOLATED: '1', + NODE_USE_ENV_PROXY: '1', + }); + expect(isolation?.unsetEnv).toEqual(['OVERDECK_INTERNAL_TOKEN']); + expect(isolation?.rootFile).toBe(join(home, 'isolation', 'roots', 'agent-pan-1.json')); + }); + + it('writes no settings file for a codex launch and skips the sandbox check', async () => { + const { isolation } = await prepareAgentIsolation(owner({ harness: 'codex' }), { ...allPresent, which: async () => null }); + expect(isolation?.settingsFile).toBeUndefined(); + expect(isolation?.env.OVERDECK_ISOLATED).toBe('1'); + }); +}); diff --git a/src/lib/agent-isolation/launch.ts b/src/lib/agent-isolation/launch.ts new file mode 100644 index 00000000000..332c5c37012 --- /dev/null +++ b/src/lib/agent-isolation/launch.ts @@ -0,0 +1,93 @@ +/** + * PAN-5754 WI-6: everything one isolated launch needs before its launcher script is written. + * + * `prepareAgentIsolation(owner)` returns `{}` for an operator conversation, the Flywheel, or + * when `agents.isolation.enabled` is false. Otherwise it fails closed (D-12, NFR-2): a missing + * sandbox prerequisite or a failed token mint throws, and the caller's spawn fails with it. + */ +import { access, constants } from 'node:fs/promises'; +import { delimiter, join } from 'node:path'; + +import type { YamlConfig } from '../config-yaml/schema.js'; +import { normalizeAgentId } from '../agents/identity.js'; +import { ensureIsolationToken } from '../mcp/agent-token.js'; +import type { OverdeckMcpLaunchOwner } from '../mcp/agent-injection.js'; +import { getHarnessBehavior } from '../runtimes/behavior.js'; +import { writeIsolationFiles } from './claude-settings.js'; +import { isAgentIsolationActive } from './config.js'; +import type { LaunchIsolation } from './launcher-lines.js'; +import { agentApiSocketPath, isolationRootsDir, OVERDECK_AGENT_TOKEN_FILE, OVERDECK_DASHBOARD_SOCKET, OVERDECK_ISOLATED } from './paths.js'; +import { buildIsolationPolicy } from './policy.js'; +import { resolveIsolationPolicyInput } from './policy-input.js'; + +/** Claude Code's sandbox needs both on Linux (D-12). */ +export const CLAUDE_SANDBOX_PREREQUISITES = ['bwrap', 'socat'] as const; + +export interface AgentIsolationDeps { + platform?: NodeJS.Platform; + /** Resolves a binary on PATH, or null. */ + which?: (binary: string) => Promise; + /** The global config layer; defaults to ~/.overdeck/config.yaml. */ + config?: YamlConfig | null; +} + +async function whichOnPath(binary: string): Promise { + for (const dir of (process.env.PATH ?? '').split(delimiter)) { + if (!dir) continue; + const candidate = join(dir, binary); + try { + await access(candidate, constants.X_OK); + return candidate; + } catch { + // not here + } + } + return null; +} + +/** The binaries Claude Code's sandbox needs that are missing (always `[]` off Linux). */ +export async function missingClaudeSandboxPrerequisites(deps: AgentIsolationDeps = {}): Promise { + if ((deps.platform ?? process.platform) !== 'linux') return []; + const which = deps.which ?? whichOnPath; + const found = await Promise.all(CLAUDE_SANDBOX_PREREQUISITES.map(async (binary) => ((await which(binary)) ? null : binary))); + return found.filter((binary): binary is (typeof CLAUDE_SANDBOX_PREREQUISITES)[number] => binary !== null); +} + +export function claudeSandboxUnavailableMessage(missing: readonly string[]): string { + return `agent isolation: Claude Code sandbox unavailable (missing: ${missing.join(', ')}). ` + + 'Install with: sudo apt-get install bubblewrap socat, or set agents.isolation.enabled: false to run agents unisolated'; +} + +export async function prepareAgentIsolation( + owner: OverdeckMcpLaunchOwner, + deps: AgentIsolationDeps = {}, +): Promise<{ isolation?: LaunchIsolation }> { + if (!isAgentIsolationActive(owner.role, deps.config)) return {}; + + const isClaudeCode = getHarnessBehavior(owner.harness).launchCommandKind === 'claude-code'; + if (isClaudeCode) { + const missing = await missingClaudeSandboxPrerequisites(deps); + if (missing.length > 0) throw new Error(claudeSandboxUnavailableMessage(missing)); + } + + const id = owner.agentKind === 'agent' ? normalizeAgentId(owner.agentId) : owner.agentId; + const { tokenFile } = await ensureIsolationToken({ agentId: id, agentKind: owner.agentKind, role: owner.role }); + + const policy = buildIsolationPolicy(await resolveIsolationPolicyInput({ kind: owner.agentKind, id }, owner.cwd, deps.config)); + const settingsFile = isClaudeCode ? (await writeIsolationFiles({ kind: owner.agentKind, id }, policy)).settingsFile : undefined; + + return { + isolation: { + ...(settingsFile ? { settingsFile } : {}), + env: { + [OVERDECK_AGENT_TOKEN_FILE]: tokenFile, + [OVERDECK_DASHBOARD_SOCKET]: agentApiSocketPath(), + [OVERDECK_ISOLATED]: '1', + NODE_USE_ENV_PROXY: '1', + }, + unsetEnv: ['OVERDECK_INTERNAL_TOKEN'], + mkdirs: policy.mkdirBeforeLaunch, + rootFile: join(isolationRootsDir(), `${id}.json`), + }, + }; +} diff --git a/src/lib/agent-isolation/launcher-lines.ts b/src/lib/agent-isolation/launcher-lines.ts new file mode 100644 index 00000000000..051fddcd491 --- /dev/null +++ b/src/lib/agent-isolation/launcher-lines.ts @@ -0,0 +1,80 @@ +/** + * PAN-5754 WI-6: the launcher-script lines an isolated launch adds. Kept out of + * `launcher-generator.ts`, which is at its file-size cap. + */ +import { dirname, join } from 'node:path'; + +import { shellQuote } from '../shell-quote.js'; +import { OVERDECK_AGENT_TOKEN_FILE } from './paths.js'; + +/** What `prepareAgentIsolation` hands the launcher generator for one isolated launch. */ +export interface LaunchIsolation { + /** The Claude Code `--settings` file (claude-code launches only). */ + settingsFile?: string; + /** Exported before the harness starts. */ + env: Record; + /** Unset before the harness starts (a long-lived terminal server may carry a stale value). */ + unsetEnv: string[]; + /** Socket directories to create (0700) so a server started later lands under the mask. */ + mkdirs: string[]; + /** `/isolation/roots/.json`: the launcher records its pid and start time there (D-10). */ + rootFile: string; +} + +/** + * D-10: record this launcher's pid and kernel start time (field 22 of /proc/$$/stat, read after + * the last `)` because the command name may hold spaces). `exec` keeps the pid, so the harness and + * everything it starts descend from it. Skipped where there is no /proc (macOS). + */ +export function rootRegistrationLauncherLine(rootFile: string): string { + const file = shellQuote(rootFile); + return [ + `if [ -r /proc/$$/stat ]; then`, + `PAN_ISO_STAT=$(cat /proc/$$/stat); PAN_ISO_STAT=\${PAN_ISO_STAT##*) };`, + `PAN_ISO_START=$(printf '%s\\n' "$PAN_ISO_STAT" | awk '{print $20}');`, + `mkdir -p -m 700 "$(dirname ${file})" && printf '{"pid":%s,"startTime":%s}\\n' "$$" "$PAN_ISO_START" > ${file}.tmp.$$ && mv -f ${file}.tmp.$$ ${file};`, + `unset PAN_ISO_STAT PAN_ISO_START;`, + `fi`, + ].join(' '); +} + +/** + * Skill overrides (PAN-3942) pass their own `--settings` JSON in `$PAN_SKILL_SETTINGS`, and + * Claude Code keeps one `--settings` value. So the launcher folds the skill JSON into a copy of + * the isolation settings (arrays concatenated, objects merged, isolation scalars win) and clears + * `$PAN_SKILL_SETTINGS`. A failed merge keeps the isolation file alone: the sandbox is never lost. + */ +const MERGE_SETTINGS_SCRIPT = 'const fs=require("fs");const [isoFile,skill,out]=process.argv.slice(1);' + + 'const m=(a,b)=>{if(Array.isArray(a)&&Array.isArray(b))return [...new Set([...a,...b].map(x=>JSON.stringify(x)))].map(x=>JSON.parse(x));' + + 'if(a&&b&&typeof a==="object"&&typeof b==="object"&&!Array.isArray(a)&&!Array.isArray(b)){const r={...a};for(const k of Object.keys(b))r[k]=k in a?m(a[k],b[k]):b[k];return r}return b===undefined?a:b};' + + 'const merged=m(JSON.parse(skill),JSON.parse(fs.readFileSync(isoFile,"utf8")));' + + 'const t=out+".tmp-"+process.pid;fs.writeFileSync(t,JSON.stringify(merged)+"\\n",{mode:384});fs.renameSync(t,out)'; + +function settingsMergeLines(settingsFile: string): string[] { + const merged = join(dirname(settingsFile), 'claude-settings.merged.json'); + return [ + `PAN_ISO_SETTINGS=${shellQuote(settingsFile)}`, + `if [ -n "\${PAN_SKILL_SETTINGS:-}" ]; then if node -e ${shellQuote(MERGE_SETTINGS_SCRIPT)} "$PAN_ISO_SETTINGS" "$PAN_SKILL_SETTINGS" ${shellQuote(merged)}; then PAN_ISO_SETTINGS=${shellQuote(merged)}; else echo "[launcher] WARNING: skill overrides not applied (isolation settings merge failed)" >&2; fi; PAN_SKILL_SETTINGS=''; fi`, + ]; +} + +/** The mkdir, export, unset, settings-merge and root-registration lines, in that order. */ +export function isolationLauncherLines(isolation: LaunchIsolation): string[] { + const lines: string[] = []; + if (isolation.mkdirs.length > 0) lines.push(`mkdir -p -m 700 ${isolation.mkdirs.map(shellQuote).join(' ')} 2>/dev/null || true`); + for (const [key, value] of Object.entries(isolation.env)) lines.push(`export ${key}=${shellQuote(value)}`); + if (isolation.unsetEnv.length > 0) lines.push(`unset ${isolation.unsetEnv.join(' ')}`); + if (isolation.settingsFile) lines.push(...settingsMergeLines(isolation.settingsFile)); + lines.push(rootRegistrationLauncherLine(isolation.rootFile)); + return lines; +} + +/** ` --settings "$PAN_ISO_SETTINGS"` for a claude-code command (set by `isolationLauncherLines`), or `''`. */ +export function isolationSettingsArg(isolation: LaunchIsolation | undefined): string { + return isolation?.settingsFile ? ' --settings "$PAN_ISO_SETTINGS"' : ''; +} + +/** D-15: the launcher's own post-exit `pan` calls keep the operator credential. */ +export function launcherOwnPanPrefix(isolation: LaunchIsolation | undefined): string { + return isolation ? `env -u ${OVERDECK_AGENT_TOKEN_FILE} ` : ''; +} diff --git a/src/lib/launcher-generator.ts b/src/lib/launcher-generator.ts index 5604a313501..9f6df6e1d71 100644 --- a/src/lib/launcher-generator.ts +++ b/src/lib/launcher-generator.ts @@ -18,6 +18,7 @@ import { getClaudeCodeLaunchModel } from './kimi-claude-routing.js'; import { harnessLaunchLines } from './launcher-job-control.js'; import { workspaceEnvLauncherLines } from './workspace-env.js'; import { panCliShimLauncherLines } from './pan-cli-shim.js'; +import { isolationLauncherLines, isolationSettingsArg, launcherOwnPanPrefix, type LaunchIsolation } from './agent-isolation/launcher-lines.js'; export type LauncherSpawnMode = 'conversation' | 'remote' | 'resume'; @@ -263,6 +264,8 @@ export interface LauncherConfig extends CodexNativeEndpointOption { useSupervisor?: boolean; /** Absolute path to dist/pty-supervisor.js. Required when useSupervisor=true. */ supervisorScriptPath?: string; + /** PAN-5754: set for an isolated agent (`prepareAgentIsolation`); undefined leaves the script unchanged. */ + isolation?: LaunchIsolation; } /** @@ -423,6 +426,8 @@ export function generateLauncherScript(config: LauncherConfig): string { lines.push(`export CODEX_HOME=${shellQuote(config.codexHome)}`); } + if (config.isolation) lines.push(...isolationLauncherLines(config.isolation)); // PAN-5754 + // Change directory (after env setup, before command) if (config.changeDir !== false) { lines.push(`cd -- ${shellQuote(config.workingDir)}`); @@ -554,6 +559,7 @@ function buildCommand(config: LauncherConfig): string[] { let cmd = config.baseCommand; cmd += buildChannelsArgs(config); cmd += overdeckMcpArgs(config.overdeckMcpConfig, cmd, { serverNames: config.overdeckMcpServerNames, strict: config.mcpStrict, forceAllow: config.overdeckMcpForceAllow }); + cmd += isolationSettingsArg(config.isolation); for (const file of systemPromptFiles(config)) { cmd += ` --append-system-prompt-file ${shellQuote(file)}`; } @@ -605,6 +611,7 @@ function buildReviewSubRoleCommand(config: LauncherConfig): string[] { const out = sig.outputPath; const role = sig.subRole; const pidFile = shellQuote(sig.launcherPidPath); + const pan = `${launcherOwnPanPrefix(config.isolation)}pan`; return [ // Record this launcher's pid so Deacon's convoy watchdog can check the @@ -614,11 +621,11 @@ function buildReviewSubRoleCommand(config: LauncherConfig): string[] { claudeCmd, 'CLAUDE_EXIT=$?', `if [ "$CLAUDE_EXIT" = "124" ]; then`, - ` pan tell ${synth} "REVIEWER_TIMEOUT ${role} reviewer exceeded ${sig.timeoutSeconds}s deadline" || true`, + ` ${pan} tell ${synth} "REVIEWER_TIMEOUT ${role} reviewer exceeded ${sig.timeoutSeconds}s deadline" || true`, `elif [ -s ${shellQuote(out)} ]; then`, - ` pan tell ${synth} "REVIEWER_READY ${role} ${out}" || true`, + ` ${pan} tell ${synth} "REVIEWER_READY ${role} ${out}" || true`, `else`, - ` pan tell ${synth} "REVIEWER_FAILED ${role} reviewer exited (code $CLAUDE_EXIT) without writing report" || true`, + ` ${pan} tell ${synth} "REVIEWER_FAILED ${role} reviewer exited (code $CLAUDE_EXIT) without writing report" || true`, `fi`, // PAN-3848 (W26, FR-21): the transition writes its own state — the launcher // records the reviewer's exit instead of a patrol inferring it from a @@ -629,7 +636,7 @@ function buildReviewSubRoleCommand(config: LauncherConfig): string[] { // row from session liveness on its next sweep. `PAN_EXIT_RECORDED=false`, `for PAN_EXIT_ATTEMPT in 1 2 3; do`, - ` if pan admin agents exited ${shellQuote(sig.agentId)} --code "$CLAUDE_EXIT"; then`, + ` if ${pan} admin agents exited ${shellQuote(sig.agentId)} --code "$CLAUDE_EXIT"; then`, ` PAN_EXIT_RECORDED=true`, ` break`, ` fi`, @@ -687,6 +694,7 @@ function buildNonConversationCommand(config: LauncherConfig, useExec: boolean): // Append channels bridge args (no-op when channelsBridgeMcpConfig unset) cmd += buildChannelsArgs(config); cmd += overdeckMcpArgs(config.overdeckMcpConfig, cmd, { serverNames: config.overdeckMcpServerNames, strict: config.mcpStrict, forceAllow: config.overdeckMcpForceAllow }); + cmd += isolationSettingsArg(config.isolation); // Append session args if (config.resumeSessionId) { From b3ab387db3b1fee7b4af810bc9d08f92c91d5adb Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:06:44 -0500 Subject: [PATCH 021/129] chore(workspace): plan artifacts for PAN-5754 Overdeck-Agent: agent-pan-5754 --- .pan/continues/PAN-5754.xbrief.json | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/.pan/continues/PAN-5754.xbrief.json b/.pan/continues/PAN-5754.xbrief.json index cafb87b3d8d..49939af4b02 100644 --- a/.pan/continues/PAN-5754.xbrief.json +++ b/.pan/continues/PAN-5754.xbrief.json @@ -2,7 +2,7 @@ "version": "1", "issueId": "PAN-5754", "created": "2026-12-03T21:28:28.525Z", - "updated": "2026-12-03T21:55:02.104Z", + "updated": "2026-12-03T22:06:44.506Z", "gitState": {}, "decisions": [], "hazards": [], @@ -116,9 +116,30 @@ "doneAt": "2026-12-03T21:54:59.963Z" }, "launch-isolation": { - "status": "in_progress", + "status": "completed", "claimedBy": "agent-pan-5754", - "claimedAt": "2026-12-03T21:55:02.104Z" + "claimedAt": "2026-12-03T21:55:02.104Z", + "doneAt": "2026-12-03T22:06:44.505Z" + }, + "launch-isolation.ac1": { + "status": "completed", + "doneAt": "2026-12-03T22:06:44.505Z" + }, + "launch-isolation.ac2": { + "status": "completed", + "doneAt": "2026-12-03T22:06:44.505Z" + }, + "launch-isolation.ac3": { + "status": "completed", + "doneAt": "2026-12-03T22:06:44.505Z" + }, + "launch-isolation.ac4": { + "status": "completed", + "doneAt": "2026-12-03T22:06:44.505Z" + }, + "launch-isolation.ac5": { + "status": "completed", + "doneAt": "2026-12-03T22:06:44.505Z" } } } From 329b7498cd784ac4a601a82cc98b30d4410b2882 Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:08:05 -0500 Subject: [PATCH 022/129] fix(infra): check the sandbox prerequisites through host-tools PAN-5754 launch-isolation follow-up. The bwrap/socat check now uses the cached resolveHostTool lookup (bwrap and socat join HostToolName) instead of its own PATH scan, so it shares the PATH-only, no-spawn lookup and the test convention (OVERDECK_TEST_ASSUME_HOST_TOOLS; setHostToolFinderForTests) with every other host tool probe. Co-Authored-By: Claude Opus 5.5 Overdeck-Agent: agent-pan-5754 --- src/lib/agent-isolation/launch.ts | 27 +++++++-------------------- src/lib/host-tools.ts | 3 ++- 2 files changed, 9 insertions(+), 21 deletions(-) diff --git a/src/lib/agent-isolation/launch.ts b/src/lib/agent-isolation/launch.ts index 332c5c37012..d9627a33cd3 100644 --- a/src/lib/agent-isolation/launch.ts +++ b/src/lib/agent-isolation/launch.ts @@ -5,13 +5,13 @@ * when `agents.isolation.enabled` is false. Otherwise it fails closed (D-12, NFR-2): a missing * sandbox prerequisite or a failed token mint throws, and the caller's spawn fails with it. */ -import { access, constants } from 'node:fs/promises'; -import { delimiter, join } from 'node:path'; +import { join } from 'node:path'; import type { YamlConfig } from '../config-yaml/schema.js'; import { normalizeAgentId } from '../agents/identity.js'; import { ensureIsolationToken } from '../mcp/agent-token.js'; import type { OverdeckMcpLaunchOwner } from '../mcp/agent-injection.js'; +import { resolveHostTool } from '../host-tools.js'; import { getHarnessBehavior } from '../runtimes/behavior.js'; import { writeIsolationFiles } from './claude-settings.js'; import { isAgentIsolationActive } from './config.js'; @@ -22,35 +22,22 @@ import { resolveIsolationPolicyInput } from './policy-input.js'; /** Claude Code's sandbox needs both on Linux (D-12). */ export const CLAUDE_SANDBOX_PREREQUISITES = ['bwrap', 'socat'] as const; +export type SandboxPrerequisite = (typeof CLAUDE_SANDBOX_PREREQUISITES)[number]; export interface AgentIsolationDeps { platform?: NodeJS.Platform; - /** Resolves a binary on PATH, or null. */ - which?: (binary: string) => Promise; + /** Resolves a binary on PATH, or null. Defaults to the cached `resolveHostTool` lookup. */ + which?: (binary: SandboxPrerequisite) => Promise; /** The global config layer; defaults to ~/.overdeck/config.yaml. */ config?: YamlConfig | null; } -async function whichOnPath(binary: string): Promise { - for (const dir of (process.env.PATH ?? '').split(delimiter)) { - if (!dir) continue; - const candidate = join(dir, binary); - try { - await access(candidate, constants.X_OK); - return candidate; - } catch { - // not here - } - } - return null; -} - /** The binaries Claude Code's sandbox needs that are missing (always `[]` off Linux). */ export async function missingClaudeSandboxPrerequisites(deps: AgentIsolationDeps = {}): Promise { if ((deps.platform ?? process.platform) !== 'linux') return []; - const which = deps.which ?? whichOnPath; + const which = deps.which ?? (async (binary: SandboxPrerequisite) => resolveHostTool(binary)); const found = await Promise.all(CLAUDE_SANDBOX_PREREQUISITES.map(async (binary) => ((await which(binary)) ? null : binary))); - return found.filter((binary): binary is (typeof CLAUDE_SANDBOX_PREREQUISITES)[number] => binary !== null); + return found.filter((binary): binary is SandboxPrerequisite => binary !== null); } export function claudeSandboxUnavailableMessage(missing: readonly string[]): string { diff --git a/src/lib/host-tools.ts b/src/lib/host-tools.ts index 1f465871125..c8b3d957c15 100644 --- a/src/lib/host-tools.ts +++ b/src/lib/host-tools.ts @@ -16,7 +16,8 @@ */ import { findExecutableOnPath } from './pan-cli-shim.js'; -export type HostToolName = 'docker' | 'tmux' | 'systemctl' | 'journalctl' | 'brew'; +/** PAN-5754: `bwrap` and `socat` are Claude Code's Linux sandbox prerequisites. */ +export type HostToolName = 'docker' | 'tmux' | 'systemctl' | 'journalctl' | 'brew' | 'bwrap' | 'socat'; export const HOST_TOOL_MISSING_RECHECK_MS = 60_000; From 687c2430d54483da47ddc9ea57f9539e6555dfe1 Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:08:53 -0500 Subject: [PATCH 023/129] chore(workspace): plan artifacts for PAN-5754 Overdeck-Agent: agent-pan-5754 --- .pan/continues/PAN-5754.xbrief.json | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/.pan/continues/PAN-5754.xbrief.json b/.pan/continues/PAN-5754.xbrief.json index 49939af4b02..0344cbca335 100644 --- a/.pan/continues/PAN-5754.xbrief.json +++ b/.pan/continues/PAN-5754.xbrief.json @@ -2,7 +2,7 @@ "version": "1", "issueId": "PAN-5754", "created": "2026-12-03T21:28:28.525Z", - "updated": "2026-12-03T22:06:44.506Z", + "updated": "2026-12-03T22:08:53.442Z", "gitState": {}, "decisions": [], "hazards": [], @@ -140,6 +140,11 @@ "launch-isolation.ac5": { "status": "completed", "doneAt": "2026-12-03T22:06:44.505Z" + }, + "codex-clamp": { + "status": "in_progress", + "claimedBy": "agent-pan-5754", + "claimedAt": "2026-12-03T22:08:53.441Z" } } } From 0353107148e3d90d72cf95aa8963f2e76d4e2286 Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:12:27 -0500 Subject: [PATCH 024/129] feat(infra): clamp isolated Codex launches to workspace-write PAN-5754 WI-23 (D-13). codexLaunchPermissions maps codex.permissionMode to the Codex home's approval policy, sandbox mode and reviewer, and turns full-access into workspace for an isolated launch. getCodexLauncherFields uses it with the role's isolation; conversation-runtime uses it with the conversation's token role, so a lane conversation (token role worker) is clamped too while operator conversations keep their configured mode. The mapping was duplicated in both files; it now lives once. CP-5: codex-cli 0.173 offers named permission profiles and extra readable roots but no setting that denies reads of given paths, so isolated Codex agents can still read the operator secret set (class write-sandbox). Recorded in agent-isolation/codex.ts. Item: codex-clamp Item: codex-clamp.ac1 Item: codex-clamp.ac2 Co-Authored-By: Claude Opus 5.5 Overdeck-Agent: agent-pan-5754 --- .../agent-isolation/__tests__/codex.test.ts | 21 ++++++++++++ src/lib/agent-isolation/codex.ts | 26 +++++++++++++++ .../runtime-command-codex-clamp.test.ts | 32 +++++++++++++++++++ src/lib/agents/runtime-command.ts | 11 +++---- src/lib/overdeck/conversation-runtime.ts | 12 +++---- 5 files changed, 88 insertions(+), 14 deletions(-) create mode 100644 src/lib/agent-isolation/__tests__/codex.test.ts create mode 100644 src/lib/agent-isolation/codex.ts create mode 100644 src/lib/agents/__tests__/runtime-command-codex-clamp.test.ts diff --git a/src/lib/agent-isolation/__tests__/codex.test.ts b/src/lib/agent-isolation/__tests__/codex.test.ts new file mode 100644 index 00000000000..e8ad06ff782 --- /dev/null +++ b/src/lib/agent-isolation/__tests__/codex.test.ts @@ -0,0 +1,21 @@ +import { describe, expect, it } from 'vitest'; + +import { codexLaunchPermissions } from '../codex.js'; + +describe('codexLaunchPermissions (PAN-5754 D-13)', () => { + it('clamps full-access to workspace-write for an isolated launch', () => { + expect(codexLaunchPermissions('full-access', true)).toEqual({ approvalPolicy: 'on-request', sandboxMode: 'workspace-write', approvalsReviewer: undefined }); + }); + + it('keeps full-access for a launch that is not isolated', () => { + expect(codexLaunchPermissions('full-access', false)).toEqual({ approvalPolicy: 'never', sandboxMode: 'danger-full-access', approvalsReviewer: undefined }); + }); + + it('maps the other modes the same way either way', () => { + for (const isolated of [true, false]) { + expect(codexLaunchPermissions(undefined, isolated).sandboxMode).toBe('workspace-write'); + expect(codexLaunchPermissions('read-only', isolated).sandboxMode).toBe('read-only'); + expect(codexLaunchPermissions('auto-review', isolated)).toEqual({ approvalPolicy: 'on-request', sandboxMode: 'workspace-write', approvalsReviewer: 'auto_review' }); + } + }); +}); diff --git a/src/lib/agent-isolation/codex.ts b/src/lib/agent-isolation/codex.ts new file mode 100644 index 00000000000..9460fdda9b0 --- /dev/null +++ b/src/lib/agent-isolation/codex.ts @@ -0,0 +1,26 @@ +/** + * The Codex home permission settings for a launch, from `codex.permissionMode`. + * + * PAN-5754 D-13: an isolated launch never runs `danger-full-access`; `full-access` + * becomes `workspace` (workspace-write). Its reads of the operator secret set stay + * possible: checkpoint CP-5 found no Codex sandbox setting that denies reads of given + * paths (codex-cli 0.173 offers only named permission profiles and extra readable + * roots), so Codex is isolation class `write-sandbox`. + */ +export type CodexPermissionMode = 'read-only' | 'workspace' | 'auto-review' | 'full-access'; + +export interface CodexLaunchPermissions { + approvalPolicy: 'never' | 'on-request'; + sandboxMode: 'danger-full-access' | 'read-only' | 'workspace-write'; + approvalsReviewer: 'auto_review' | undefined; +} + +export function codexLaunchPermissions(configured: CodexPermissionMode | undefined, isolated: boolean): CodexLaunchPermissions { + const requested = configured ?? 'workspace'; + const mode = isolated && requested === 'full-access' ? 'workspace' : requested; + return { + approvalPolicy: mode === 'full-access' ? 'never' : 'on-request', + sandboxMode: mode === 'full-access' ? 'danger-full-access' : mode === 'read-only' ? 'read-only' : 'workspace-write', + approvalsReviewer: mode === 'auto-review' ? 'auto_review' : undefined, + }; +} diff --git a/src/lib/agents/__tests__/runtime-command-codex-clamp.test.ts b/src/lib/agents/__tests__/runtime-command-codex-clamp.test.ts new file mode 100644 index 00000000000..163cb29000d --- /dev/null +++ b/src/lib/agents/__tests__/runtime-command-codex-clamp.test.ts @@ -0,0 +1,32 @@ +/** + * PAN-5754 D-13 (WI-23): getCodexLauncherFields never gives an isolated role + * danger-full-access, and keeps full access for the Flywheel (not isolated). + */ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +vi.mock('../../config-yaml.js', async (importOriginal) => ({ + ...(await importOriginal()), + loadConfigSync: vi.fn(() => ({ config: { codex: { permissionMode: 'full-access' }, roles: {}, tieredExecution: { tiers: {} } } })), +})); + +const initCodexHomeMock = vi.hoisted(() => vi.fn()); +vi.mock('../../runtimes/codex.js', async (importOriginal) => ({ + ...(await importOriginal()), + initCodexHome: initCodexHomeMock, +})); + +import { getCodexLauncherFields } from '../runtime-command.js'; + +describe('getCodexLauncherFields isolation clamp (PAN-5754 D-13)', () => { + beforeEach(() => initCodexHomeMock.mockClear()); + + it('writes workspace-write for an isolated work agent configured for full access', () => { + getCodexLauncherFields('agent-pan-1', 'gpt-5.6', '/tmp/ws', 'work'); + expect(initCodexHomeMock).toHaveBeenCalledWith(expect.any(String), expect.objectContaining({ sandboxMode: 'workspace-write', approvalPolicy: 'on-request' })); + }); + + it('keeps danger-full-access for the Flywheel', () => { + getCodexLauncherFields('flywheel', 'gpt-5.6', '/tmp/ws', 'flywheel'); + expect(initCodexHomeMock).toHaveBeenCalledWith(expect.any(String), expect.objectContaining({ sandboxMode: 'danger-full-access', approvalPolicy: 'never' })); + }); +}); diff --git a/src/lib/agents/runtime-command.ts b/src/lib/agents/runtime-command.ts index 70639b68c79..1863c97bd1c 100644 --- a/src/lib/agents/runtime-command.ts +++ b/src/lib/agents/runtime-command.ts @@ -36,6 +36,8 @@ import { CLI_PROXY_MODEL_ALIASES } from './provider-env.js'; import { getClaudeCodeLaunchModel } from '../kimi-claude-routing.js'; import { codexSessionsRoot } from '../runtimes/storage/codex.js'; import { OVERDECK_MCP_SERVER_NAME } from '../mcp/overdeck-mcp-args.js'; +import { codexLaunchPermissions } from '../agent-isolation/codex.js'; +import { isAgentIsolationActive } from '../agent-isolation/config.js'; const execAsync = promisify(exec); const missingRoleDefinitionWarnings = new Set(); @@ -186,13 +188,8 @@ export function getCodexLauncherFields(agentId: string, model: string, workspace const codexHome = join(homedir(), '.overdeck', 'agents', agentId, 'codex-home-v2'); const codexConfig = loadYamlConfig().config.codex; // Match conversation permissions and pre-trust the workspace to avoid onboarding prompts. - const codexPermMode = codexConfig?.permissionMode ?? 'workspace'; - const approvalPolicy = codexPermMode === 'full-access' ? 'never' : 'on-request'; - const sandboxMode = - codexPermMode === 'full-access' ? 'danger-full-access' - : codexPermMode === 'read-only' ? 'read-only' - : 'workspace-write'; - const approvalsReviewer = codexPermMode === 'auto-review' ? 'auto_review' : undefined; + // PAN-5754 D-13: an isolated role never gets danger-full-access. + const { approvalPolicy, sandboxMode, approvalsReviewer } = codexLaunchPermissions(codexConfig?.permissionMode, role !== undefined && isAgentIsolationActive(role)); const codexEffort = resolveEffort({ explicit: effort, role, model, harness: 'codex' }).effort; initCodexHome(codexHome, { trustedDir: workspacePath, diff --git a/src/lib/overdeck/conversation-runtime.ts b/src/lib/overdeck/conversation-runtime.ts index 8957352b942..5aa1500e978 100644 --- a/src/lib/overdeck/conversation-runtime.ts +++ b/src/lib/overdeck/conversation-runtime.ts @@ -40,6 +40,8 @@ import { normalizeHarnessName, type AgentRole } from '@overdeck/contracts'; import { conversationStateDir, readConversationPaneRole, writeConversationPaneRole } from './conversation-pane-role.js'; import { revokeAgentMcpTokens } from '../mcp/agent-token.js'; import { conversationTokenRole, prepareClaudeOverdeckMcp, prepareCodexOverdeckMcp } from '../mcp/agent-injection.js'; +import { codexLaunchPermissions } from '../agent-isolation/codex.js'; +import { isAgentIsolationActive } from '../agent-isolation/config.js'; import { validateCwdContainment } from './cwd-containment.js'; import { conversationWriteRefusal } from './conversation-release.js'; import { shutdownDrainingRefusal } from '../shutdown/refusal.js'; @@ -720,14 +722,10 @@ export async function spawnConversationSession( } else if (behavior.usesCodexHome) { const codexHome = join(getOverdeckHome(), 'agents', tmuxSession, 'codex-home-v2'); const codexConfig = loadConfigSync().config.codex; - const codexPermMode = codexConfig?.permissionMode ?? 'workspace'; codexTransport = codexConfig?.transport ?? 'app-server'; - const codexApprovalPolicy = codexPermMode === 'full-access' ? 'never' : 'on-request'; - const codexSandboxMode = - codexPermMode === 'full-access' ? 'danger-full-access' - : codexPermMode === 'read-only' ? 'read-only' - : 'workspace-write'; - const codexApprovalsReviewer = codexPermMode === 'auto-review' ? 'auto_review' : undefined; + // PAN-5754 D-13: a lane conversation (token role worker) is isolated and never gets danger-full-access. + const codexIsolated = !!tokenRow && isAgentIsolationActive(conversationTokenRole(tokenRow, role, tmuxSession)); + const { approvalPolicy: codexApprovalPolicy, sandboxMode: codexSandboxMode, approvalsReviewer: codexApprovalsReviewer } = codexLaunchPermissions(codexConfig?.permissionMode, codexIsolated); const { initCodexHome } = await import('../runtimes/codex.js'); initCodexHome(codexHome, { trustedDir: cwd, From 1616198d2683950175b65435968641b857e9e062 Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:12:55 -0500 Subject: [PATCH 025/129] chore(workspace): plan artifacts for PAN-5754 Overdeck-Agent: agent-pan-5754 --- .pan/continues/PAN-5754.xbrief.json | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/.pan/continues/PAN-5754.xbrief.json b/.pan/continues/PAN-5754.xbrief.json index 0344cbca335..34d20685c2a 100644 --- a/.pan/continues/PAN-5754.xbrief.json +++ b/.pan/continues/PAN-5754.xbrief.json @@ -2,7 +2,7 @@ "version": "1", "issueId": "PAN-5754", "created": "2026-12-03T21:28:28.525Z", - "updated": "2026-12-03T22:08:53.442Z", + "updated": "2026-12-03T22:12:55.289Z", "gitState": {}, "decisions": [], "hazards": [], @@ -142,9 +142,18 @@ "doneAt": "2026-12-03T22:06:44.505Z" }, "codex-clamp": { - "status": "in_progress", + "status": "completed", "claimedBy": "agent-pan-5754", - "claimedAt": "2026-12-03T22:08:53.441Z" + "claimedAt": "2026-12-03T22:08:53.441Z", + "doneAt": "2026-12-03T22:12:55.288Z" + }, + "codex-clamp.ac1": { + "status": "completed", + "doneAt": "2026-12-03T22:12:55.288Z" + }, + "codex-clamp.ac2": { + "status": "completed", + "doneAt": "2026-12-03T22:12:55.288Z" } } } From 1b72d5343313a74d10733a4f3f22f76e92f811e5 Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:12:57 -0500 Subject: [PATCH 026/129] chore(workspace): plan artifacts for PAN-5754 Overdeck-Agent: agent-pan-5754 --- .pan/continues/PAN-5754.xbrief.json | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/.pan/continues/PAN-5754.xbrief.json b/.pan/continues/PAN-5754.xbrief.json index 34d20685c2a..30af7a9ec85 100644 --- a/.pan/continues/PAN-5754.xbrief.json +++ b/.pan/continues/PAN-5754.xbrief.json @@ -2,7 +2,7 @@ "version": "1", "issueId": "PAN-5754", "created": "2026-12-03T21:28:28.525Z", - "updated": "2026-12-03T22:12:55.289Z", + "updated": "2026-12-03T22:12:57.127Z", "gitState": {}, "decisions": [], "hazards": [], @@ -154,6 +154,11 @@ "codex-clamp.ac2": { "status": "completed", "doneAt": "2026-12-03T22:12:55.288Z" + }, + "launch-sites-agents": { + "status": "in_progress", + "claimedBy": "agent-pan-5754", + "claimedAt": "2026-12-03T22:12:57.127Z" } } } From 1960f21729ffd3a3480a7b20a854a4cd5b3c4af8 Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:15:55 -0500 Subject: [PATCH 027/129] chore(workspace): plan artifacts for PAN-5754 Overdeck-Agent: agent-pan-5754 --- .pan/continues/PAN-5754.xbrief.json | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/.pan/continues/PAN-5754.xbrief.json b/.pan/continues/PAN-5754.xbrief.json index 30af7a9ec85..b7568bce8a2 100644 --- a/.pan/continues/PAN-5754.xbrief.json +++ b/.pan/continues/PAN-5754.xbrief.json @@ -2,7 +2,7 @@ "version": "1", "issueId": "PAN-5754", "created": "2026-12-03T21:28:28.525Z", - "updated": "2026-12-03T22:12:57.127Z", + "updated": "2026-12-03T22:15:55.430Z", "gitState": {}, "decisions": [], "hazards": [], @@ -159,6 +159,11 @@ "status": "in_progress", "claimedBy": "agent-pan-5754", "claimedAt": "2026-12-03T22:12:57.127Z" + }, + "launch-sites-planning-conv": { + "status": "in_progress", + "claimedBy": "agent-pan-5754", + "claimedAt": "2026-12-03T22:15:55.429Z" } } } From e83fc4369b8cf50e8c0f38f83419cfa81ecf5c95 Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:17:49 -0500 Subject: [PATCH 028/129] feat(infra): isolate agents at the spawn, recovery and resume sites PAN-5754 WI-7. prepareAgentLaunchAccess returns the overdeck MCP launcher fields plus prepareAgentIsolation's, so a site cannot wire one without the other. spawn.ts (spawnRun), spawn-prep.ts (buildAgentLaunchConfig, fresh and resume), recovery.ts and messaging.ts (fresh-launch fallback) call it in place of prepareClaudeOverdeckMcp. An isolation error (missing sandbox prerequisite, failed mint) throws, so the spawn fails like a missing binary. Every spawn-path test file (60) passes with isolation on by default. Item: launch-sites-agents Item: launch-sites-agents.ac1 Item: launch-sites-agents.ac2 Item: launch-sites-agents.ac3 Co-Authored-By: Claude Opus 5.5 Overdeck-Agent: agent-pan-5754 --- src/lib/agent-isolation/launch.ts | 14 ++++- .../__tests__/message-fallback-effort.test.ts | 3 + .../agents/__tests__/spawn-isolation.test.ts | 60 +++++++++++++++++++ src/lib/agents/messaging.ts | 5 +- src/lib/agents/recovery.ts | 5 +- src/lib/agents/spawn-prep.ts | 6 +- src/lib/agents/spawn.ts | 5 +- 7 files changed, 89 insertions(+), 9 deletions(-) create mode 100644 src/lib/agents/__tests__/spawn-isolation.test.ts diff --git a/src/lib/agent-isolation/launch.ts b/src/lib/agent-isolation/launch.ts index d9627a33cd3..c0536e1f67b 100644 --- a/src/lib/agent-isolation/launch.ts +++ b/src/lib/agent-isolation/launch.ts @@ -10,7 +10,7 @@ import { join } from 'node:path'; import type { YamlConfig } from '../config-yaml/schema.js'; import { normalizeAgentId } from '../agents/identity.js'; import { ensureIsolationToken } from '../mcp/agent-token.js'; -import type { OverdeckMcpLaunchOwner } from '../mcp/agent-injection.js'; +import { prepareClaudeOverdeckMcp, type OverdeckMcpLaunchOwner } from '../mcp/agent-injection.js'; import { resolveHostTool } from '../host-tools.js'; import { getHarnessBehavior } from '../runtimes/behavior.js'; import { writeIsolationFiles } from './claude-settings.js'; @@ -78,3 +78,15 @@ export async function prepareAgentIsolation( }, }; } + +/** + * The launcher fields every managed agent launch site spreads: the overdeck MCP config + * (`prepareClaudeOverdeckMcp`, never throws) and the isolation fields (`prepareAgentIsolation`, + * throws to fail the launch closed). One call per site, so no site can wire one without the other. + */ +export async function prepareAgentLaunchAccess( + owner: OverdeckMcpLaunchOwner, +): Promise> & { isolation?: LaunchIsolation }> { + const mcp = await prepareClaudeOverdeckMcp(owner); + return { ...mcp, ...(await prepareAgentIsolation(owner)) }; +} diff --git a/src/lib/agents/__tests__/message-fallback-effort.test.ts b/src/lib/agents/__tests__/message-fallback-effort.test.ts index e36b71fa05b..4b13567f454 100644 --- a/src/lib/agents/__tests__/message-fallback-effort.test.ts +++ b/src/lib/agents/__tests__/message-fallback-effort.test.ts @@ -109,6 +109,9 @@ describe('messageAgent fresh-launch fallback re-applies the persisted effort (PA expect(readLauncher(agentId)).toContain('--effort max'); // PAN-4932 FR-7: the fallback relaunch keeps the overdeck MCP server. expect(readLauncher(agentId)).toContain(`--mcp-config='${join(getAgentDir(agentId), 'overdeck-mcp.json')}'`); + // PAN-5754 WI-7: the fallback relaunch of an isolated work agent keeps its isolation. + expect(readLauncher(agentId)).toContain(`export OVERDECK_AGENT_TOKEN_FILE='${join(tempHome, 'agent-tokens', 'agent', agentId, 'mcp-token')}'`); + expect(readLauncher(agentId)).toContain('--settings "$PAN_ISO_SETTINGS"'); }); it('resolves legacy state (no persisted effort) to the role default', async () => { diff --git a/src/lib/agents/__tests__/spawn-isolation.test.ts b/src/lib/agents/__tests__/spawn-isolation.test.ts new file mode 100644 index 00000000000..d45a64c5b25 --- /dev/null +++ b/src/lib/agents/__tests__/spawn-isolation.test.ts @@ -0,0 +1,60 @@ +/** + * PAN-5754 WI-7: agent launch sites carry the isolation fields for an isolated role + * (here through buildAgentLaunchConfig, the spawn/recovery launcher builder) and leave + * the Flywheel unisolated. + */ +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; + +import { _resetAccessTokensForTests, _settleAccessTokenWritesForTests } from '../../access-tokens.js'; +import { buildAgentLaunchConfig } from '../spawn-prep.js'; + +let home: string; +let workspace: string; +let previousHome: string | undefined; + +beforeEach(() => { + home = mkdtempSync(join(tmpdir(), 'pan-5754-spawn-home-')); + workspace = mkdtempSync(join(tmpdir(), 'pan-5754-spawn-ws-')); + previousHome = process.env.OVERDECK_HOME; + process.env.OVERDECK_HOME = home; + _resetAccessTokensForTests(); +}); + +afterEach(async () => { + await _settleAccessTokenWritesForTests(); + _resetAccessTokensForTests(); + if (previousHome === undefined) delete process.env.OVERDECK_HOME; + else process.env.OVERDECK_HOME = previousHome; + rmSync(home, { recursive: true, force: true }); + rmSync(workspace, { recursive: true, force: true }); +}); + +describe('agent launch sites wire isolation (PAN-5754 WI-7)', () => { + it('a work spawn exports its own token file and runs Claude Code with the isolation settings', async () => { + const agentId = 'agent-pan-5754-work'; + const { launcherContent } = await buildAgentLaunchConfig({ agentId, model: 'claude-sonnet-4-6', workspace, role: 'work' }); + expect(launcherContent).toContain(`export OVERDECK_AGENT_TOKEN_FILE='${join(home, 'agent-tokens', 'agent', agentId, 'mcp-token')}'`); + expect(launcherContent).toContain('unset OVERDECK_INTERNAL_TOKEN'); + expect(launcherContent).toContain('--settings "$PAN_ISO_SETTINGS"'); + expect(launcherContent).toContain(join(home, 'isolation', 'roots', `${agentId}.json`)); + }); + + it('a resumed work launch is isolated too', async () => { + const { launcherContent } = await buildAgentLaunchConfig({ + agentId: 'agent-pan-5754-resume', model: 'claude-sonnet-4-6', workspace, role: 'work', spawnMode: 'resume', resumeSessionId: 'sess-5754', + }); + expect(launcherContent).toContain('export OVERDECK_AGENT_TOKEN_FILE='); + expect(launcherContent).toContain('--settings "$PAN_ISO_SETTINGS"'); + }); + + it('a flywheel spawn has no isolation', async () => { + const { launcherContent } = await buildAgentLaunchConfig({ agentId: 'flywheel', model: 'claude-sonnet-4-6', workspace, role: 'flywheel' }); + expect(launcherContent).not.toContain('OVERDECK_AGENT_TOKEN_FILE'); + expect(launcherContent).not.toContain('PAN_ISO_SETTINGS'); + expect(launcherContent).not.toContain('unset OVERDECK_INTERNAL_TOKEN'); + }); +}); diff --git a/src/lib/agents/messaging.ts b/src/lib/agents/messaging.ts index 703f13e9801..48df4581688 100644 --- a/src/lib/agents/messaging.ts +++ b/src/lib/agents/messaging.ts @@ -5,7 +5,8 @@ import { Effect } from 'effect'; import { emitActivityEntry } from '../activity-logger.js'; import { BLANKED_PROVIDER_ENV } from '../child-env.js'; import { generateLauncherScript } from '../launcher-generator.js'; -import { prepareClaudeOverdeckMcp, prepareCodexOverdeckMcp } from '../mcp/agent-injection.js'; +import { prepareCodexOverdeckMcp } from '../mcp/agent-injection.js'; +import { prepareAgentLaunchAccess } from '../agent-isolation/launch.js'; import { prepareHarnessLaunch } from '../harness-binary.js'; import { appendOperatorInterventionEvent } from '../operator-interventions.js'; import { logAgentLifecycle } from '../persistent-logger.js'; @@ -510,7 +511,7 @@ export async function messageAgent( supervisorScriptPath: fallbackSupervisorLaunch.supervisorScriptPath, ...fallbackPiFields, ...fallbackCodexFields, - ...(await prepareClaudeOverdeckMcp({ agentId: normalizedId, agentKind: 'agent', role: resumeRole, harness: fallbackHarness, cwd: agentState.workspace, issueId: agentState.issueId })), + ...(await prepareAgentLaunchAccess({ agentId: normalizedId, agentKind: 'agent', role: resumeRole, harness: fallbackHarness, cwd: agentState.workspace, issueId: agentState.issueId })), // PAN-5754 }); await writeLauncherScriptAtomic(fallbackLauncher, fallbackContent); // PAN-5720: a fresh 0700 temp file renamed into place; never new content under an old mode. // PAN-3960: relaunch on the backend the host selects now, stamped like a spawn. diff --git a/src/lib/agents/recovery.ts b/src/lib/agents/recovery.ts index f144bb8566a..accdc42fd99 100644 --- a/src/lib/agents/recovery.ts +++ b/src/lib/agents/recovery.ts @@ -9,7 +9,8 @@ import { getLatestSessionId } from './activity.js'; import { sendGracefulRestartWarning } from '../graceful-restart.js'; import { checkHook, generateFixedPointPrompt } from '../hooks.js'; import { generateLauncherScript } from '../launcher-generator.js'; -import { prepareClaudeOverdeckMcp, prepareCodexOverdeckMcp } from '../mcp/agent-injection.js'; +import { prepareCodexOverdeckMcp } from '../mcp/agent-injection.js'; +import { prepareAgentLaunchAccess } from '../agent-isolation/launch.js'; import { resolveHarness } from '../harness-resolve.js'; import { prepareHarnessLaunch } from '../harness-binary.js'; import { normalizeModelOverride, requireModelOverride } from '../model-validation.js'; @@ -831,7 +832,7 @@ export async function recoverAgent( useSupervisor: recoverySupervisorLaunch.useSupervisor, supervisorScriptPath: recoverySupervisorLaunch.supervisorScriptPath, ...recoveryCodexFields, - ...(await prepareClaudeOverdeckMcp({ agentId: normalizedId, agentKind: 'agent', role: recoveryRole, harness: recoveryHarness, cwd: state.workspace, issueId: state.issueId })), + ...(await prepareAgentLaunchAccess({ agentId: normalizedId, agentKind: 'agent', role: recoveryRole, harness: recoveryHarness, cwd: state.workspace, issueId: state.issueId })), // PAN-5754 }); const launcherScript = join(getAgentDir(normalizedId), 'launcher.sh'); await writeLauncherScriptAtomic(launcherScript, recoveryLauncherContent); diff --git a/src/lib/agents/spawn-prep.ts b/src/lib/agents/spawn-prep.ts index e8d610f2b0e..c371ac6c1d3 100644 --- a/src/lib/agents/spawn-prep.ts +++ b/src/lib/agents/spawn-prep.ts @@ -12,7 +12,8 @@ import { transitionJiraIssue } from '../tracker/jira-lifecycle.js'; import { trackerStateToJiraTarget } from '../tracker/jira-status.js'; import { findProjectByPath, getIssuePrefix, resolveProjectFromIssueSync } from '../projects.js'; import { generateLauncherScript } from '../launcher-generator.js'; -import { prepareClaudeOverdeckMcp, prepareCodexOverdeckMcp } from '../mcp/agent-injection.js'; +import { prepareCodexOverdeckMcp } from '../mcp/agent-injection.js'; +import { prepareAgentLaunchAccess } from '../agent-isolation/launch.js'; import { getProviderForModel, setupCredentialFileAuth, clearCredentialFileAuth } from '../providers.js'; import type { ModelId } from '../settings.js'; import { requireModelOverride } from '../model-validation.js'; @@ -731,7 +732,8 @@ export async function buildAgentLaunchConfig(opts: { // A resumed review/test/ship run loads the wrong frontmatter (and wrong // tool permissions) if it always points at roles/work.md. const launchRole: Role = opts.isPlanning ? 'plan' : opts.role; - const overdeckMcp = await prepareClaudeOverdeckMcp({ agentId: opts.agentId, agentKind: 'agent', role: launchRole, harness: opts.harness ?? 'claude-code', cwd: opts.workspace }); + // PAN-5754: the MCP config plus, for an isolated role, the isolation fields (throws to refuse the launch). + const overdeckMcp = await prepareAgentLaunchAccess({ agentId: opts.agentId, agentKind: 'agent', role: launchRole, harness: opts.harness ?? 'claude-code', cwd: opts.workspace }); // PAN-1055: ohmypi harness needs --session-dir + fifo redirect threaded into // the launcher; getOhmypiLauncherFields() resolves them from the agent state diff --git a/src/lib/agents/spawn.ts b/src/lib/agents/spawn.ts index f84cfd28fc8..dc5f10bd12c 100644 --- a/src/lib/agents/spawn.ts +++ b/src/lib/agents/spawn.ts @@ -17,7 +17,8 @@ import { createConversation, getConversationByName, reactivateConversationForSpa import { startWork } from '../cv.js'; import { generateFixedPointPrompt, checkHook, initHook } from '../hooks.js'; import { generateLauncherScript } from '../launcher-generator.js'; -import { prepareClaudeOverdeckMcp, prepareCodexOverdeckMcp } from '../mcp/agent-injection.js'; +import { prepareCodexOverdeckMcp } from '../mcp/agent-injection.js'; +import { prepareAgentLaunchAccess } from '../agent-isolation/launch.js'; import { getProviderForModel, setupCredentialFileAuth, clearCredentialFileAuth } from '../providers.js'; import { resolveHarness } from '../harness-resolve.js'; import { prepareHarnessLaunch } from '../harness-binary.js'; @@ -433,7 +434,7 @@ async function spawnRunWithoutConsentClaim( ...kimiCodeLauncherFields, ...museLauncherFields, ...(primeLaunch?.fields ?? {}), - ...(await prepareClaudeOverdeckMcp({ agentId, agentKind: 'agent', role, harness: resolvedHarness, cwd: workspace, issueId, subRole: options.subRole })), + ...(await prepareAgentLaunchAccess({ agentId, agentKind: 'agent', role, harness: resolvedHarness, cwd: workspace, issueId, subRole: options.subRole })), // PAN-5754 }); const launcherScript = join(getAgentDir(agentId), 'launcher.sh'); From e651f25a14951e654455ff1f405d9e5e43f1e20b Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:18:17 -0500 Subject: [PATCH 029/129] chore(workspace): plan artifacts for PAN-5754 Overdeck-Agent: agent-pan-5754 --- .pan/continues/PAN-5754.xbrief.json | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/.pan/continues/PAN-5754.xbrief.json b/.pan/continues/PAN-5754.xbrief.json index b7568bce8a2..18e954e8543 100644 --- a/.pan/continues/PAN-5754.xbrief.json +++ b/.pan/continues/PAN-5754.xbrief.json @@ -2,7 +2,7 @@ "version": "1", "issueId": "PAN-5754", "created": "2026-12-03T21:28:28.525Z", - "updated": "2026-12-03T22:15:55.430Z", + "updated": "2026-12-03T22:18:17.799Z", "gitState": {}, "decisions": [], "hazards": [], @@ -156,14 +156,27 @@ "doneAt": "2026-12-03T22:12:55.288Z" }, "launch-sites-agents": { - "status": "in_progress", + "status": "completed", "claimedBy": "agent-pan-5754", - "claimedAt": "2026-12-03T22:12:57.127Z" + "claimedAt": "2026-12-03T22:12:57.127Z", + "doneAt": "2026-12-03T22:18:17.798Z" }, "launch-sites-planning-conv": { "status": "in_progress", "claimedBy": "agent-pan-5754", "claimedAt": "2026-12-03T22:15:55.429Z" + }, + "launch-sites-agents.ac1": { + "status": "completed", + "doneAt": "2026-12-03T22:18:17.798Z" + }, + "launch-sites-agents.ac2": { + "status": "completed", + "doneAt": "2026-12-03T22:18:17.798Z" + }, + "launch-sites-agents.ac3": { + "status": "completed", + "doneAt": "2026-12-03T22:18:17.798Z" } } } From c03fee60b77d7e72ad61738f01a5db1ca177c4b3 Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:19:51 -0500 Subject: [PATCH 030/129] feat(infra): isolate planners and lane conversations at their launch sites PAN-5754 WI-8. spawn-planning-session.ts and the planning continuation route (routes/misc/planning.ts) launch the planner (role plan, isolated) through prepareAgentLaunchAccess. conversation-runtime.ts does the same for a conversation with a row, using its token role: a plain operator conversation (token role conversation) gets no isolation fields (FR-11), and a lane conversation (token role worker) gets the --settings file and its own token. Deviation: the conversation cases are asserted in the existing conversation-runtime-launch.test.ts (which already mocks the launch stack) instead of a new conversation-isolation.test.ts. planning-routes.test.ts asserted the pre-WI-2 /mcp-token path; it now asserts the agent-tokens location and the planner's isolation. Item: launch-sites-planning-conv Item: launch-sites-planning-conv.ac1 Item: launch-sites-planning-conv.ac2 Item: launch-sites-planning-conv.ac3 Co-Authored-By: Claude Opus 5.5 Overdeck-Agent: agent-pan-5754 --- src/dashboard/server/routes/misc/planning.ts | 4 ++-- .../overdeck/__tests__/conversation-runtime-launch.test.ts | 6 ++++++ src/lib/overdeck/conversation-runtime.ts | 6 ++++-- .../__tests__/spawn-planning-session-backend.test.ts | 3 +++ src/lib/planning/spawn-planning-session.ts | 5 +++-- tests/unit/dashboard/server/routes/planning-routes.test.ts | 5 ++++- 6 files changed, 22 insertions(+), 7 deletions(-) diff --git a/src/dashboard/server/routes/misc/planning.ts b/src/dashboard/server/routes/misc/planning.ts index e5a2df59280..8e53a5be985 100644 --- a/src/dashboard/server/routes/misc/planning.ts +++ b/src/dashboard/server/routes/misc/planning.ts @@ -13,7 +13,7 @@ import { workspaceContextFile } from '../../../../lib/context-layers/layers.js'; import { extractPrefix } from '../../../../lib/issue-id.js'; import { prepareHarnessLaunch } from '../../../../lib/harness-binary.js'; import { generateLauncherScript } from '../../../../lib/launcher-generator.js'; -import { prepareClaudeOverdeckMcp } from '../../../../lib/mcp/agent-injection.js'; +import { prepareAgentLaunchAccess } from '../../../../lib/agent-isolation/launch.js'; import { PAN_CONTINUE_FILENAME, PAN_DIRNAME } from '../../../../lib/pan-dir/types.js'; import { getOverdeckHome } from '../../../../lib/paths.js'; import { extractTeamPrefix, findProjectByTeam } from '../../../../lib/projects.js'; @@ -355,7 +355,7 @@ Continue the PLANNING session. Do NOT implement anything. extraEnvExports: [harnessLaunch.pathExport], appendSystemPromptFiles: await claudePlanningSystemPromptFiles(agentCwd), promptInline: `Please read the continuation prompt at ${continuationPromptPath} and continue the planning session.`, - ...(await prepareClaudeOverdeckMcp({ agentId: sessionName, agentKind: 'agent', role: 'plan', harness: 'claude-code', cwd: agentCwd, issueId })), + ...(await prepareAgentLaunchAccess({ agentId: sessionName, agentKind: 'agent', role: 'plan', harness: 'claude-code', cwd: agentCwd, issueId })), // PAN-5754 }), ); // PAN-5720: a fresh 0700 temp file renamed into place; never new content under an old mode. diff --git a/src/lib/overdeck/__tests__/conversation-runtime-launch.test.ts b/src/lib/overdeck/__tests__/conversation-runtime-launch.test.ts index 11c1352afbd..51ceab519bc 100644 --- a/src/lib/overdeck/__tests__/conversation-runtime-launch.test.ts +++ b/src/lib/overdeck/__tests__/conversation-runtime-launch.test.ts @@ -320,6 +320,8 @@ describe('conversations get the overdeck MCP server (PAN-4932)', () => { expect(launcherConfigs[0]!['overdeckMcpConfig']).toBe(join(overdeckHome, 'conversations', 'conv-op', 'overdeck-mcp.json')); expect(await tokenFor('op')).toEqual([expect.objectContaining({ agentKind: 'conversation', role: 'conversation' })]); + // PAN-5754 FR-11: an operator conversation is never isolated. + expect(launcherConfigs[0]!['isolation']).toBeUndefined(); }); it('passes no config for a bare conversation', async () => { @@ -355,6 +357,10 @@ describe('conversations get the overdeck MCP server (PAN-4932)', () => { expect(launcherConfigs[0]!['overdeckMcpConfig']).toBe(join(overdeckHome, 'conversations', 'conv-lane-c1', 'overdeck-mcp.json')); expect(await tokenFor('lane-c1')).toEqual([expect.objectContaining({ agentKind: 'conversation', role: 'worker' })]); expect((await tokenFor('lane-c1'))[0]!.scopes).not.toContain('approve'); + // PAN-5754 D-1: a lane conversation (token role worker) is isolated. + const isolation = launcherConfigs[0]!['isolation'] as { settingsFile?: string; env: Record } | undefined; + expect(isolation?.settingsFile).toBe(join(overdeckHome, 'isolation', 'conversation', 'lane-c1', 'claude-settings.json')); + expect(isolation?.env.OVERDECK_AGENT_TOKEN_FILE).toBe(join(overdeckHome, 'agent-tokens', 'conversation', 'lane-c1', 'mcp-token')); }); it('gives a Codex conversation the overdeck MCP server under its own [mcp_servers.overdeck] table (PAN-4933)', async () => { diff --git a/src/lib/overdeck/conversation-runtime.ts b/src/lib/overdeck/conversation-runtime.ts index 5aa1500e978..ec253c51b6c 100644 --- a/src/lib/overdeck/conversation-runtime.ts +++ b/src/lib/overdeck/conversation-runtime.ts @@ -39,7 +39,8 @@ import type { AgentPaneRef, TerminalBackend, TerminalBackendName } from '../term import { normalizeHarnessName, type AgentRole } from '@overdeck/contracts'; import { conversationStateDir, readConversationPaneRole, writeConversationPaneRole } from './conversation-pane-role.js'; import { revokeAgentMcpTokens } from '../mcp/agent-token.js'; -import { conversationTokenRole, prepareClaudeOverdeckMcp, prepareCodexOverdeckMcp } from '../mcp/agent-injection.js'; +import { conversationTokenRole, prepareCodexOverdeckMcp } from '../mcp/agent-injection.js'; +import { prepareAgentLaunchAccess } from '../agent-isolation/launch.js'; import { codexLaunchPermissions } from '../agent-isolation/codex.js'; import { isAgentIsolationActive } from '../agent-isolation/config.js'; import { validateCwdContainment } from './cwd-containment.js'; @@ -802,8 +803,9 @@ export async function spawnConversationSession( writeBridgeToken(tmuxSession); await writeChannelsBridgeMcpConfig(channelsBridgeMcpConfig, tmuxSession); } + // PAN-5754: a lane conversation (token role worker) also gets the isolation fields; a plain one does not. const overdeckMcp = tokenRow - ? await prepareClaudeOverdeckMcp({ agentId: tokenRow.name, agentKind: 'conversation', role: conversationTokenRole(tokenRow, role, tmuxSession), harness, dir: stateDir, cwd, issueId, skillConversation: tmuxSession }) + ? await prepareAgentLaunchAccess({ agentId: tokenRow.name, agentKind: 'conversation', role: conversationTokenRole(tokenRow, role, tmuxSession), harness, dir: stateDir, cwd, issueId, skillConversation: tmuxSession }) : {}; // PAN-1837 review fix: the tmux-create + session-capture sequence below is // wrapped per-bucket (withKimiSessionCaptureLock) for kimi-code conversations diff --git a/src/lib/planning/__tests__/spawn-planning-session-backend.test.ts b/src/lib/planning/__tests__/spawn-planning-session-backend.test.ts index 07fcd81bd3d..53ec82b2105 100644 --- a/src/lib/planning/__tests__/spawn-planning-session-backend.test.ts +++ b/src/lib/planning/__tests__/spawn-planning-session-backend.test.ts @@ -176,6 +176,9 @@ describe('spawnPlanningSession launches through the host backend (PAN-3960)', () expect(launcher).toContain(`--mcp-config='${join(tempHome, '.overdeck', 'agents', sessionName, 'overdeck-mcp.json')}'`); expect(launcher).not.toContain('odk_'); expect(statSync(join(tempHome, '.overdeck', 'agent-tokens', 'agent', sessionName, 'mcp-token')).mode & 0o777).toBe(0o600); + // PAN-5754 WI-8: the planner is an isolated role. + expect(launcher).toContain(`export OVERDECK_AGENT_TOKEN_FILE='${join(tempHome, '.overdeck', 'agent-tokens', 'agent', sessionName, 'mcp-token')}'`); + expect(launcher).toContain('--settings "$PAN_ISO_SETTINGS"'); }); it('keeps the tmux-only server hygiene on tmux and skips it on Herdr', async () => { diff --git a/src/lib/planning/spawn-planning-session.ts b/src/lib/planning/spawn-planning-session.ts index 1a60294c1dc..329f65f5192 100644 --- a/src/lib/planning/spawn-planning-session.ts +++ b/src/lib/planning/spawn-planning-session.ts @@ -44,7 +44,8 @@ import { getHarnessBehavior } from '../runtimes/behavior.js'; import { launchAndCaptureManagedKimiSession } from '../runtimes/kimi-code.js'; import type { RuntimeName } from '../runtimes/types.js'; import { generateLauncherScript } from '../launcher-generator.js'; -import { prepareClaudeOverdeckMcp, prepareCodexOverdeckMcp } from '../mcp/agent-injection.js'; +import { prepareCodexOverdeckMcp } from '../mcp/agent-injection.js'; +import { prepareAgentLaunchAccess } from '../agent-isolation/launch.js'; import { BLANKED_PROVIDER_ENV } from '../child-env.js'; import { ensureWorkspacePanDir, getWorkspacePanPaths, writeWorkspaceContext } from '../pan-dir/index.js'; import { resolvePlanningDraftPath } from '../pan-dir/drafts.js'; @@ -658,7 +659,7 @@ export async function spawnPlanningSession(opts: SpawnPlanningOptions): Promise< ...acpLauncherFields, ...kimiCodeLauncherFields, ...(primeLaunch?.fields ?? {}), - ...(await prepareClaudeOverdeckMcp({ agentId: sessionName, agentKind: 'agent', role: 'plan', harness: effectiveHarness, cwd: workspacePath, issueId: issue.identifier })), + ...(await prepareAgentLaunchAccess({ agentId: sessionName, agentKind: 'agent', role: 'plan', harness: effectiveHarness, cwd: workspacePath, issueId: issue.identifier })), // PAN-5754 ...(effectiveHarness === 'muse' ? { museModel: planningModel, museEffort: resolvedEffort.effort, museContextFile: await materializeMuseContext(sessionName, workspacePath, roleAgentDefinitionPath('plan')) } : {}), }), ); // PAN-5720: a fresh 0700 temp file renamed into place; never new content under an old mode. diff --git a/tests/unit/dashboard/server/routes/planning-routes.test.ts b/tests/unit/dashboard/server/routes/planning-routes.test.ts index d9c75d7cd88..cd4d4b15d0e 100644 --- a/tests/unit/dashboard/server/routes/planning-routes.test.ts +++ b/tests/unit/dashboard/server/routes/planning-routes.test.ts @@ -204,7 +204,10 @@ describe('POST /api/planning/:issueId/message (M1)', () => { expect(JSON.stringify(mocks.launcherConfigs[0])).not.toContain('odk_'); const agentDir = join(mocks.projectPath, 'home', 'agents', PLANNER); expect(await readFile(join(agentDir, 'continuation-launcher.sh'), 'utf8')).not.toContain('odk_'); - expect((await stat(join(agentDir, 'mcp-token'))).mode & 0o777).toBe(0o600); + expect((await stat(join(mocks.projectPath, 'home', 'agent-tokens', 'agent', PLANNER, 'mcp-token'))).mode & 0o777).toBe(0o600); + // PAN-5754 WI-8: the continued planner is an isolated role. + expect((mocks.launcherConfigs[0] as { isolation?: { env: Record } }).isolation?.env.OVERDECK_AGENT_TOKEN_FILE) + .toBe(join(mocks.projectPath, 'home', 'agent-tokens', 'agent', PLANNER, 'mcp-token')); }); it('records the relaunched claude-code harness, so the oracle probes the right process next time', async () => { From d0bc07add32689f7a75cdb8e4c3a5b8410d59eef Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:20:20 -0500 Subject: [PATCH 031/129] chore(workspace): plan artifacts for PAN-5754 Overdeck-Agent: agent-pan-5754 --- .pan/continues/PAN-5754.xbrief.json | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/.pan/continues/PAN-5754.xbrief.json b/.pan/continues/PAN-5754.xbrief.json index 18e954e8543..9bc91fffb40 100644 --- a/.pan/continues/PAN-5754.xbrief.json +++ b/.pan/continues/PAN-5754.xbrief.json @@ -2,7 +2,7 @@ "version": "1", "issueId": "PAN-5754", "created": "2026-12-03T21:28:28.525Z", - "updated": "2026-12-03T22:18:17.799Z", + "updated": "2026-12-03T22:20:20.918Z", "gitState": {}, "decisions": [], "hazards": [], @@ -162,9 +162,10 @@ "doneAt": "2026-12-03T22:18:17.798Z" }, "launch-sites-planning-conv": { - "status": "in_progress", + "status": "completed", "claimedBy": "agent-pan-5754", - "claimedAt": "2026-12-03T22:15:55.429Z" + "claimedAt": "2026-12-03T22:15:55.429Z", + "doneAt": "2026-12-03T22:20:20.918Z" }, "launch-sites-agents.ac1": { "status": "completed", @@ -177,6 +178,18 @@ "launch-sites-agents.ac3": { "status": "completed", "doneAt": "2026-12-03T22:18:17.798Z" + }, + "launch-sites-planning-conv.ac1": { + "status": "completed", + "doneAt": "2026-12-03T22:20:20.918Z" + }, + "launch-sites-planning-conv.ac2": { + "status": "completed", + "doneAt": "2026-12-03T22:20:20.918Z" + }, + "launch-sites-planning-conv.ac3": { + "status": "completed", + "doneAt": "2026-12-03T22:20:20.918Z" } } } From 13de3ccccaec06a0a145c9ce71cf0c368b15fcd2 Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:20:22 -0500 Subject: [PATCH 032/129] chore(workspace): plan artifacts for PAN-5754 Overdeck-Agent: agent-pan-5754 --- .pan/continues/PAN-5754.xbrief.json | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/.pan/continues/PAN-5754.xbrief.json b/.pan/continues/PAN-5754.xbrief.json index 9bc91fffb40..83309f3d618 100644 --- a/.pan/continues/PAN-5754.xbrief.json +++ b/.pan/continues/PAN-5754.xbrief.json @@ -2,7 +2,7 @@ "version": "1", "issueId": "PAN-5754", "created": "2026-12-03T21:28:28.525Z", - "updated": "2026-12-03T22:20:20.918Z", + "updated": "2026-12-03T22:20:22.611Z", "gitState": {}, "decisions": [], "hazards": [], @@ -190,6 +190,11 @@ "launch-sites-planning-conv.ac3": { "status": "completed", "doneAt": "2026-12-03T22:20:20.918Z" + }, + "agent-socket": { + "status": "in_progress", + "claimedBy": "agent-pan-5754", + "claimedAt": "2026-12-03T22:20:22.611Z" } } } From e7f921a20491b6256d3c1434dcddd1ce39efb939 Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:21:19 -0500 Subject: [PATCH 033/129] feat(dashboard): serve the HTTP app on the credential-only agent socket PAN-5754 WI-9 (D-6). installAgentApiSocket binds /agent-api/dashboard.sock (directory 0700, socket 0600) and hands each connection to the HTTP listeners through deliverHttpSocket. A Unix-socket request has no peer address, so localPeerKind returns null and the remote request gate passes it only with a credential. The primary dashboard binds it next to the channel listener and closes it with the HTTP server. A socket another live process already serves is left alone; a stale socket file is replaced. Item: agent-socket Item: agent-socket.ac1 Item: agent-socket.ac2 Item: agent-socket.ac3 Co-Authored-By: Claude Opus 5.5 Overdeck-Agent: agent-pan-5754 --- .../server/__tests__/agent-api-socket.test.ts | 111 ++++++++++++++++++ src/dashboard/server/agent-api-socket.ts | 69 +++++++++++ src/dashboard/server/server.ts | 10 ++ 3 files changed, 190 insertions(+) create mode 100644 src/dashboard/server/__tests__/agent-api-socket.test.ts create mode 100644 src/dashboard/server/agent-api-socket.ts diff --git a/src/dashboard/server/__tests__/agent-api-socket.test.ts b/src/dashboard/server/__tests__/agent-api-socket.test.ts new file mode 100644 index 00000000000..76094232b9d --- /dev/null +++ b/src/dashboard/server/__tests__/agent-api-socket.test.ts @@ -0,0 +1,111 @@ +/** + * PAN-5754 WI-9 (D-6): the agent socket serves the dashboard HTTP app, and a request on it + * passes the remote request gate only with a credential — never as a trusted local caller. + */ +import { request as httpRequest, createServer, type Server } from 'node:http'; +import { mkdtemp, rm, stat } from 'node:fs/promises'; +import { createRequire } from 'node:module'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +import { Context, Effect, Exit, Layer, Scope } from 'effect'; +import { HttpRouter, HttpServer } from 'effect/unstable/http'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; + +import type { MachineKeyPair } from '../../../lib/anywhere/machine-key.js'; + +const _require = createRequire(import.meta.url); +const dh = _require('noise-handshake/dh') as { generateKeyPair(): MachineKeyPair }; + +const originalHome = process.env.OVERDECK_HOME; +const home = await mkdtemp(join(tmpdir(), 'pan-5754-agent-socket-')); +process.env.OVERDECK_HOME = home; + +const { _resetAccessTokensForTests, _settleAccessTokenWritesForTests, createAccessToken } = await import('../../../lib/access-tokens.js'); +const { _resetDashboardSessionTokenForTests } = await import('../routes/dashboard-auth.js'); +const { remoteRequestGateLayer } = await import('../remote-request-gate.js'); +const { _resetChannelListenerForTests, installChannelListener } = await import('../channel-listener.js'); +const { jsonResponse } = await import('../http-helpers.js'); +const { installAgentApiSocket } = await import('../agent-api-socket.js'); + +const socketPath = join(home, 'agent-api', 'dashboard.sock'); +let scope: Scope.Closeable; +let port: number; +let closeSocket: () => Promise; + +function get(target: { socketPath: string } | { port: number }, path: string, headers: Record = {}): Promise<{ status: number; body: string }> { + return new Promise((resolve, reject) => { + const req = httpRequest({ ...target, ...('port' in target ? { host: '127.0.0.1' } : {}), path, method: 'GET', headers }, (res) => { + let body = ''; + res.setEncoding('utf8'); + res.on('data', (chunk: string) => { body += chunk; }); + res.on('end', () => resolve({ status: res.statusCode ?? 0, body })); + }); + req.on('error', reject); + req.end(); + }); +} + +beforeAll(async () => { + _resetDashboardSessionTokenForTests(); + _resetAccessTokensForTests(); + const routes = Layer.mergeAll( + remoteRequestGateLayer, + HttpRouter.add('GET', '/api/agents', Effect.succeed(jsonResponse({ agents: [] }))), + ); + const serverLayer = (await import('@effect/platform-node/NodeHttpServer')).layer(() => { + const nodeServer: Server = createServer(); + installChannelListener(nodeServer, { + primary: true, + localKey: async () => dh.generateKeyPair(), + isPinnedPeer: () => false, + takePairing: () => 'unknown', + onPairingFailure: () => undefined, + }); + return nodeServer; + }, { host: '127.0.0.1', port: 0 }); + scope = await Effect.runPromise(Scope.make()); + const app = HttpRouter.serve(routes, { disableLogger: true }).pipe(Layer.provideMerge(serverLayer)); + const context = await Effect.runPromise(Layer.build(app).pipe(Effect.provideService(Scope.Scope, scope))); + const address = Context.get(context, HttpServer.HttpServer).address; + if (address._tag !== 'TcpAddress') throw new Error('expected a TCP address'); + port = address.port; + closeSocket = await installAgentApiSocket(socketPath); +}); + +afterAll(async () => { + await closeSocket?.(); + await Effect.runPromise(Scope.close(scope, Exit.void)); + _resetChannelListenerForTests(); + await _settleAccessTokenWritesForTests(); + _resetAccessTokensForTests(); + _resetDashboardSessionTokenForTests(); + if (originalHome === undefined) delete process.env.OVERDECK_HOME; + else process.env.OVERDECK_HOME = originalHome; + await rm(home, { recursive: true, force: true }); +}); + +describe('agent socket (PAN-5754 D-6)', () => { + it('creates a 0600 socket in a 0700 directory', async () => { + expect((await stat(socketPath)).mode & 0o777).toBe(0o600); + expect((await stat(join(home, 'agent-api'))).mode & 0o777).toBe(0o700); + }); + + it('refuses an uncredentialed request with 401, where the same request over loopback TCP is trusted', async () => { + expect((await get({ socketPath }, '/api/agents')).status).toBe(401); + expect((await get({ port }, '/api/agents')).status).toBe(200); + }); + + it('serves a request that carries an agent token', async () => { + const { token } = await createAccessToken({ name: 'agent:work:agent-pan-1', kind: 'token', scopes: ['read:state'], agentId: 'agent-pan-1', agentKind: 'agent', role: 'work' }); + const response = await get({ socketPath }, '/api/agents', { authorization: `Bearer ${token}` }); + expect(response.status).toBe(200); + expect(JSON.parse(response.body)).toEqual({ agents: [] }); + }); + + it('does not take over a socket another process already serves', async () => { + const close = await installAgentApiSocket(socketPath); + await close(); + expect((await get({ socketPath }, '/api/agents')).status).toBe(401); + }); +}); diff --git a/src/dashboard/server/agent-api-socket.ts b/src/dashboard/server/agent-api-socket.ts new file mode 100644 index 00000000000..575302c63d4 --- /dev/null +++ b/src/dashboard/server/agent-api-socket.ts @@ -0,0 +1,69 @@ +/** + * PAN-5754 D-6: the agent socket, `/agent-api/dashboard.sock`. + * + * The dashboard serves its normal HTTP app here (each connection goes to the HTTP + * listeners through `deliverHttpSocket`). A Unix-socket request has no peer address, so + * `localPeerKind` returns null and only a credential passes the remote request gate: an + * isolated agent's CLI reaches the dashboard with its own token and never as a trusted + * local caller. The directory is 0700 and the socket 0600; `agent-api/` is outside every + * isolated agent's writable paths, so no agent can unlink and rebind it. + */ +import { connect, createServer, type Server } from 'node:net'; +import { chmod, mkdir, unlink } from 'node:fs/promises'; +import { dirname } from 'node:path'; + +import { agentApiSocketPath } from '../../lib/agent-isolation/paths.js'; +import { deliverHttpSocket } from './channel-listener.js'; + +/** True when something already accepts connections on `path` (another live dashboard). */ +function socketIsLive(path: string): Promise { + return new Promise((resolve) => { + const probe = connect(path); + probe.once('connect', () => { + probe.destroy(); + resolve(true); + }); + probe.once('error', () => resolve(false)); + }); +} + +async function unlinkIfPresent(path: string): Promise { + await unlink(path).catch((error: NodeJS.ErrnoException) => { + if (error.code !== 'ENOENT') throw error; + }); +} + +/** + * Bind the agent socket and return a closer that closes it and removes the socket file. + * Refuses (returns a no-op closer, with a warning) when another process already serves it. + */ +export async function installAgentApiSocket(path: string = agentApiSocketPath()): Promise<() => Promise> { + await mkdir(dirname(path), { recursive: true, mode: 0o700 }); + await chmod(dirname(path), 0o700); + if (await socketIsLive(path)) { + console.warn(`[agent-api] ${path} is served by another process; not binding it`); + return async () => undefined; + } + await unlinkIfPresent(path); + + const server: Server = createServer((socket) => { + if (!deliverHttpSocket(socket)) socket.destroy(); + }); + await new Promise((resolve, reject) => { + server.once('error', reject); + server.listen(path, () => { + server.off('error', reject); + resolve(); + }); + }); + await chmod(path, 0o600); + server.on('error', (error) => console.warn(`[agent-api] socket error: ${error.message}`)); + + let closed = false; + return async () => { + if (closed) return; + closed = true; + await new Promise((resolve) => server.close(() => resolve())); + await unlinkIfPresent(path).catch(() => undefined); + }; +} diff --git a/src/dashboard/server/server.ts b/src/dashboard/server/server.ts index 4f3467006be..713c1bbb6a3 100644 --- a/src/dashboard/server/server.ts +++ b/src/dashboard/server/server.ts @@ -40,6 +40,7 @@ import { knowledgeViewerRouteLayer, setupKnowledgeViewerProxy } from './routes/k import { setupVoiceWebSocket } from './ws-voice.js'; import { setupAutoPresoWebSocket } from './ws-autopreso.js'; import { installChannelListener } from './channel-listener.js'; +import { installAgentApiSocket } from './agent-api-socket.js'; import { plainHttpNavigationGuard } from './plain-http-guard.js'; import { recordPairingExchangeFailure, takePairingById } from './pairing-credentials.js'; import { currentApprovalService } from './services/directory-approval.js'; @@ -236,6 +237,14 @@ export function installRawNodeHandlers(nodeServer: NodeServer): void { }); } +/** PAN-5754 D-6: serve the HTTP app on the agent socket for as long as the dashboard server lives. */ +function bindAgentApiSocket(nodeServer: NodeServer): void { + installAgentApiSocket().then( + (close) => nodeServer.once('close', () => void close()), + (error: unknown) => console.warn(`[agent-api] could not bind the agent socket: ${(error as Error).message}`), + ); +} + // ─── Dual-runtime layers ────────────────────────────────────────────────────── const HttpServerLive = Layer.unwrap( @@ -254,6 +263,7 @@ const HttpServerLive = Layer.unwrap( const nodeServer = NodeHttp.createServer(); holdRequestsUntilServed(nodeServer); installRawNodeHandlers(nodeServer); + if (hostsMachineLinks()) bindAgentApiSocket(nodeServer); // PAN-5754 D-6 return nodeServer; }, { host: config.host, From 3989ed6343ff50b77a6ec4a7e8fc2e04180aac1f Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:21:44 -0500 Subject: [PATCH 034/129] chore(workspace): plan artifacts for PAN-5754 Overdeck-Agent: agent-pan-5754 --- .pan/continues/PAN-5754.xbrief.json | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/.pan/continues/PAN-5754.xbrief.json b/.pan/continues/PAN-5754.xbrief.json index 83309f3d618..37dc8404acc 100644 --- a/.pan/continues/PAN-5754.xbrief.json +++ b/.pan/continues/PAN-5754.xbrief.json @@ -2,7 +2,7 @@ "version": "1", "issueId": "PAN-5754", "created": "2026-12-03T21:28:28.525Z", - "updated": "2026-12-03T22:20:22.611Z", + "updated": "2026-12-03T22:21:44.107Z", "gitState": {}, "decisions": [], "hazards": [], @@ -192,9 +192,22 @@ "doneAt": "2026-12-03T22:20:20.918Z" }, "agent-socket": { - "status": "in_progress", + "status": "completed", "claimedBy": "agent-pan-5754", - "claimedAt": "2026-12-03T22:20:22.611Z" + "claimedAt": "2026-12-03T22:20:22.611Z", + "doneAt": "2026-12-03T22:21:44.107Z" + }, + "agent-socket.ac1": { + "status": "completed", + "doneAt": "2026-12-03T22:21:44.107Z" + }, + "agent-socket.ac2": { + "status": "completed", + "doneAt": "2026-12-03T22:21:44.107Z" + }, + "agent-socket.ac3": { + "status": "completed", + "doneAt": "2026-12-03T22:21:44.107Z" } } } From 95398c0e8f3918d77b272801d74101edc08e3f38 Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:21:45 -0500 Subject: [PATCH 035/129] chore(workspace): plan artifacts for PAN-5754 Overdeck-Agent: agent-pan-5754 --- .pan/continues/PAN-5754.xbrief.json | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/.pan/continues/PAN-5754.xbrief.json b/.pan/continues/PAN-5754.xbrief.json index 37dc8404acc..48c039c9dea 100644 --- a/.pan/continues/PAN-5754.xbrief.json +++ b/.pan/continues/PAN-5754.xbrief.json @@ -2,7 +2,7 @@ "version": "1", "issueId": "PAN-5754", "created": "2026-12-03T21:28:28.525Z", - "updated": "2026-12-03T22:21:44.107Z", + "updated": "2026-12-03T22:21:45.732Z", "gitState": {}, "decisions": [], "hazards": [], @@ -208,6 +208,11 @@ "agent-socket.ac3": { "status": "completed", "doneAt": "2026-12-03T22:21:44.107Z" + }, + "cli-credential": { + "status": "in_progress", + "claimedBy": "agent-pan-5754", + "claimedAt": "2026-12-03T22:21:45.732Z" } } } From 2c1928860b44d7848744fccd84fade3fe9d5795e Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:23:02 -0500 Subject: [PATCH 036/129] feat(cli): add the isolated-context dashboard credential and transport PAN-5754 WI-10. src/lib/dashboard-client/agent-credential.ts: isIsolatedAgentContext (OVERDECK_AGENT_TOKEN_FILE set), readAgentToken (read fresh, must be odk_<64 hex>, else AgentCredentialError), dashboardAuthHeaders (Bearer agent token when isolated, the internal-token header otherwise) and dashboardFetch, which goes over the agent socket in an isolated context and retries once over TCP only on ENOENT, ECONNREFUSED or EPERM. It replaces any caller-set internal-token or authorization header and never falls back to the internal token. Item: cli-credential Item: cli-credential.ac1 Item: cli-credential.ac2 Item: cli-credential.ac3 Co-Authored-By: Claude Opus 5.5 Overdeck-Agent: agent-pan-5754 --- .../__tests__/agent-credential.test.ts | 130 ++++++++++++++++++ src/lib/dashboard-client/agent-credential.ts | 104 ++++++++++++++ 2 files changed, 234 insertions(+) create mode 100644 src/lib/dashboard-client/__tests__/agent-credential.test.ts create mode 100644 src/lib/dashboard-client/agent-credential.ts diff --git a/src/lib/dashboard-client/__tests__/agent-credential.test.ts b/src/lib/dashboard-client/__tests__/agent-credential.test.ts new file mode 100644 index 00000000000..9078388e5a1 --- /dev/null +++ b/src/lib/dashboard-client/__tests__/agent-credential.test.ts @@ -0,0 +1,130 @@ +/** + * PAN-5754 WI-10: the CLI credential and transport helper. Uses a temp OVERDECK_HOME and + * real Unix-socket and TCP test servers. + */ +import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { createServer, type IncomingHttpHeaders, type Server } from 'node:http'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; + +import { _resetInternalTokenCacheForTests } from '../../internal-token.js'; +import { AgentCredentialError, dashboardAuthHeaders, dashboardFetch, isIsolatedAgentContext, readAgentToken } from '../agent-credential.js'; + +const TOKEN = `odk_${'a'.repeat(64)}`; +let home: string; +const servers: Server[] = []; +const seen: Array<{ via: string; method: string; url: string; headers: IncomingHttpHeaders; body: string }> = []; +const originalHome = process.env.OVERDECK_HOME; +const originalUrl = process.env.OVERDECK_DASHBOARD_URL; + +function serve(via: string): Server { + const server = createServer((req, res) => { + let body = ''; + req.setEncoding('utf8'); + req.on('data', (chunk: string) => { body += chunk; }); + req.on('end', () => { + seen.push({ via, method: req.method ?? '', url: req.url ?? '', headers: req.headers, body }); + res.writeHead(201, { 'content-type': 'application/json' }); + res.end(JSON.stringify({ via })); + }); + }); + servers.push(server); + return server; +} + +function listenOnSocket(server: Server, socketPath: string): Promise { + return new Promise((resolve) => server.listen(socketPath, () => resolve())); +} + +async function tcpServer(): Promise { + const server = serve('tcp'); + await new Promise((resolve) => server.listen(0, '127.0.0.1', () => resolve())); + const address = server.address(); + if (address === null || typeof address === 'string') throw new Error('expected a TCP address'); + return address.port; +} + +beforeEach(() => { + home = mkdtempSync(join(tmpdir(), 'pan-5754-cred-')); + process.env.OVERDECK_HOME = home; + delete process.env.OVERDECK_INTERNAL_TOKEN; + _resetInternalTokenCacheForTests(); + seen.length = 0; +}); + +afterEach(async () => { + await Promise.all(servers.splice(0).map((server) => new Promise((resolve) => server.close(() => resolve())))); + _resetInternalTokenCacheForTests(); + if (originalHome === undefined) delete process.env.OVERDECK_HOME; + else process.env.OVERDECK_HOME = originalHome; + if (originalUrl === undefined) delete process.env.OVERDECK_DASHBOARD_URL; + else process.env.OVERDECK_DASHBOARD_URL = originalUrl; + rmSync(home, { recursive: true, force: true }); +}); + +function isolatedEnv(extra: Record = {}): NodeJS.ProcessEnv { + const tokenFile = join(home, 'mcp-token'); + writeFileSync(tokenFile, `${TOKEN}\n`, { mode: 0o600 }); + return { ...process.env, OVERDECK_AGENT_TOKEN_FILE: tokenFile, ...extra }; +} + +describe('agent credential (PAN-5754 D-3)', () => { + it('reads a well-formed agent token and refuses a malformed one', () => { + const env = isolatedEnv(); + expect(isIsolatedAgentContext(env)).toBe(true); + expect(readAgentToken(env)).toBe(TOKEN); + writeFileSync(env.OVERDECK_AGENT_TOKEN_FILE!, 'nope'); + expect(() => readAgentToken(env)).toThrow(AgentCredentialError); + }); + + it('sends the internal-token header outside an isolated context', () => { + const env = { ...process.env, OVERDECK_AGENT_TOKEN_FILE: '' }; + expect(isIsolatedAgentContext(env)).toBe(false); + const headers = dashboardAuthHeaders(env); + expect(Object.keys(headers)).toEqual(['x-overdeck-internal-token']); + expect(headers['x-overdeck-internal-token']).toMatch(/^[0-9a-f]{64}$/); + }); +}); + +describe('dashboardFetch (PAN-5754 D-6)', () => { + it('sends Bearer over the agent socket and never creates the internal token', async () => { + const socketPath = join(home, 'dashboard.sock'); + await listenOnSocket(serve('socket'), socketPath); + const response = await dashboardFetch('/api/x?y=1', { + method: 'POST', + headers: { 'content-type': 'application/json', 'x-overdeck-internal-token': 'leak' }, + body: JSON.stringify({ a: 1 }), + }, isolatedEnv({ OVERDECK_DASHBOARD_SOCKET: socketPath })); + + expect(response.status).toBe(201); + expect(await response.json()).toEqual({ via: 'socket' }); + expect(seen).toHaveLength(1); + expect(seen[0]).toMatchObject({ via: 'socket', method: 'POST', url: '/api/x?y=1', body: '{"a":1}' }); + expect(seen[0]!.headers.authorization).toBe(`Bearer ${TOKEN}`); + expect(seen[0]!.headers['x-overdeck-internal-token']).toBeUndefined(); + expect(existsSync(join(home, 'internal-token'))).toBe(false); + }); + + it('falls back to TCP with Bearer when the socket does not exist', async () => { + const port = await tcpServer(); + process.env.OVERDECK_DASHBOARD_URL = `http://127.0.0.1:${port}`; + const response = await dashboardFetch('/api/x', {}, isolatedEnv({ OVERDECK_DASHBOARD_SOCKET: join(home, 'missing.sock') })); + expect(await response.json()).toEqual({ via: 'tcp' }); + expect(seen[0]!.headers.authorization).toBe(`Bearer ${TOKEN}`); + expect(existsSync(join(home, 'internal-token'))).toBe(false); + }); + + it('uses TCP and the internal-token header outside an isolated context', async () => { + const port = await tcpServer(); + process.env.OVERDECK_DASHBOARD_URL = `http://127.0.0.1:${port}`; + await dashboardFetch('/api/x', { headers: { authorization: 'Bearer odk_spoof' } }, { ...process.env, OVERDECK_AGENT_TOKEN_FILE: '' }); + expect(seen[0]!.headers['x-overdeck-internal-token']).toMatch(/^[0-9a-f]{64}$/); + expect(seen[0]!.headers.authorization).toBeUndefined(); + }); + + it('rejects instead of falling back to the internal token when the agent token is unreadable', async () => { + await expect(dashboardFetch('/api/x', {}, { ...process.env, OVERDECK_AGENT_TOKEN_FILE: join(home, 'nope') })).rejects.toThrow(AgentCredentialError); + expect(existsSync(join(home, 'internal-token'))).toBe(false); + }); +}); diff --git a/src/lib/dashboard-client/agent-credential.ts b/src/lib/dashboard-client/agent-credential.ts new file mode 100644 index 00000000000..6f9e5dc3bba --- /dev/null +++ b/src/lib/dashboard-client/agent-credential.ts @@ -0,0 +1,104 @@ +/** + * PAN-5754 D-3/D-6: how the CLI (and in-pane helpers) authenticate to the dashboard. + * + * In an isolated context (`OVERDECK_AGENT_TOKEN_FILE` set by the launcher) the only + * credential is the agent's own token, sent as `Authorization: Bearer`, and the transport is + * the agent socket (`OVERDECK_DASHBOARD_SOCKET`), falling back to loopback TCP only when the + * socket is missing, refused or blocked (the Codex sandbox). The internal token is never + * read, created or sent there: no fallback to it exists. Outside an isolated context the + * behaviour is unchanged: the internal-token header over TCP. + */ +import { readFileSync } from 'node:fs'; +import { request as httpRequest } from 'node:http'; + +import { OVERDECK_AGENT_TOKEN_FILE, OVERDECK_DASHBOARD_SOCKET } from '../agent-isolation/paths.js'; +import { getDashboardApiUrl } from '../config.js'; +import { ensureInternalToken, INTERNAL_TOKEN_HEADER } from '../internal-token.js'; + +const AGENT_TOKEN_FORMAT = /^odk_[0-9a-f]{64}$/; +/** Socket errors that mean "no agent socket here": retry once over TCP. */ +const SOCKET_FALLBACK_CODES: ReadonlySet = new Set(['ENOENT', 'ECONNREFUSED', 'EPERM']); + +export class AgentCredentialError extends Error { + override readonly name = 'AgentCredentialError'; +} + +export function isIsolatedAgentContext(env: NodeJS.ProcessEnv = process.env): boolean { + return (env[OVERDECK_AGENT_TOKEN_FILE] ?? '') !== ''; +} + +/** The agent token, read fresh on each call. Throws `AgentCredentialError` when unreadable or malformed. */ +export function readAgentToken(env: NodeJS.ProcessEnv = process.env): string { + const file = env[OVERDECK_AGENT_TOKEN_FILE]; + if (!file) throw new AgentCredentialError(`${OVERDECK_AGENT_TOKEN_FILE} is not set`); + let token: string; + try { + token = readFileSync(file, 'utf8').trim(); + } catch (error) { + throw new AgentCredentialError(`cannot read the agent token at ${file}: ${(error as Error).message}`); + } + if (!AGENT_TOKEN_FORMAT.test(token)) throw new AgentCredentialError(`the agent token at ${file} is malformed`); + return token; +} + +/** The auth header for a dashboard call from this process. */ +export function dashboardAuthHeaders(env: NodeJS.ProcessEnv = process.env): Record { + if (isIsolatedAgentContext(env)) return { authorization: `Bearer ${readAgentToken(env)}` }; + return { [INTERNAL_TOKEN_HEADER]: ensureInternalToken() }; +} + +function withAuth(init: RequestInit, env: NodeJS.ProcessEnv): Headers { + const headers = new Headers(init.headers); + headers.delete(INTERNAL_TOKEN_HEADER); + headers.delete('authorization'); + for (const [key, value] of Object.entries(dashboardAuthHeaders(env))) headers.set(key, value); + return headers; +} + +async function requestOverSocket(socketPath: string, path: string, init: RequestInit, headers: Headers): Promise { + const body = init.body == null ? undefined : Buffer.from(await new Response(init.body).arrayBuffer()); + if (body !== undefined) headers.set('content-length', String(body.byteLength)); + return new Promise((resolve, reject) => { + const req = httpRequest({ + socketPath, + path, + method: init.method ?? 'GET', + headers: Object.fromEntries(headers.entries()), + ...(init.signal ? { signal: init.signal } : {}), + }, (res) => { + const chunks: Buffer[] = []; + res.on('data', (chunk: Buffer) => chunks.push(chunk)); + res.on('error', reject); + res.on('end', () => { + const status = res.statusCode ?? 502; + const responseHeaders = new Headers(); + for (const [key, value] of Object.entries(res.headers)) { + if (value === undefined) continue; + for (const item of Array.isArray(value) ? value : [value]) responseHeaders.append(key, item); + } + const nullBody = status === 204 || status === 205 || status === 304; + resolve(new Response(nullBody ? null : Buffer.concat(chunks), { status, statusText: res.statusMessage ?? '', headers: responseHeaders })); + }); + }); + req.on('error', reject); + req.end(body); + }); +} + +/** + * `fetch` against the dashboard with this process's credential. `path` starts with `/api/…`. + * Any caller-set internal-token or authorization header is replaced. + */ +export async function dashboardFetch(path: string, init: RequestInit = {}, env: NodeJS.ProcessEnv = process.env): Promise { + const headers = withAuth(init, env); + const socketPath = isIsolatedAgentContext(env) ? env[OVERDECK_DASHBOARD_SOCKET] : undefined; + if (socketPath) { + try { + return await requestOverSocket(socketPath, path, init, headers); + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + if (code === undefined || !SOCKET_FALLBACK_CODES.has(code)) throw error; + } + } + return fetch(`${getDashboardApiUrl()}${path}`, { ...init, headers }); +} From 42c2335b0864035598f4d808c77a88c8bebd473a Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:23:28 -0500 Subject: [PATCH 037/129] chore(workspace): plan artifacts for PAN-5754 Overdeck-Agent: agent-pan-5754 --- .pan/continues/PAN-5754.xbrief.json | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/.pan/continues/PAN-5754.xbrief.json b/.pan/continues/PAN-5754.xbrief.json index 48c039c9dea..c26e45cab3a 100644 --- a/.pan/continues/PAN-5754.xbrief.json +++ b/.pan/continues/PAN-5754.xbrief.json @@ -2,7 +2,7 @@ "version": "1", "issueId": "PAN-5754", "created": "2026-12-03T21:28:28.525Z", - "updated": "2026-12-03T22:21:45.732Z", + "updated": "2026-12-03T22:23:28.777Z", "gitState": {}, "decisions": [], "hazards": [], @@ -210,9 +210,22 @@ "doneAt": "2026-12-03T22:21:44.107Z" }, "cli-credential": { - "status": "in_progress", + "status": "completed", "claimedBy": "agent-pan-5754", - "claimedAt": "2026-12-03T22:21:45.732Z" + "claimedAt": "2026-12-03T22:21:45.732Z", + "doneAt": "2026-12-03T22:23:28.777Z" + }, + "cli-credential.ac1": { + "status": "completed", + "doneAt": "2026-12-03T22:23:28.777Z" + }, + "cli-credential.ac2": { + "status": "completed", + "doneAt": "2026-12-03T22:23:28.777Z" + }, + "cli-credential.ac3": { + "status": "completed", + "doneAt": "2026-12-03T22:23:28.777Z" } } } From ddd0da7d34b22e3e2338f4194e33c9726771b241 Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:23:38 -0500 Subject: [PATCH 038/129] chore(workspace): plan artifacts for PAN-5754 Overdeck-Agent: agent-pan-5754 --- .pan/continues/PAN-5754.xbrief.json | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/.pan/continues/PAN-5754.xbrief.json b/.pan/continues/PAN-5754.xbrief.json index c26e45cab3a..ecfd188685d 100644 --- a/.pan/continues/PAN-5754.xbrief.json +++ b/.pan/continues/PAN-5754.xbrief.json @@ -2,7 +2,7 @@ "version": "1", "issueId": "PAN-5754", "created": "2026-12-03T21:28:28.525Z", - "updated": "2026-12-03T22:23:28.777Z", + "updated": "2026-12-03T22:23:38.426Z", "gitState": {}, "decisions": [], "hazards": [], @@ -226,6 +226,11 @@ "cli-credential.ac3": { "status": "completed", "doneAt": "2026-12-03T22:23:28.777Z" + }, + "cli-callers": { + "status": "in_progress", + "claimedBy": "agent-pan-5754", + "claimedAt": "2026-12-03T22:23:38.426Z" } } } From 19282e99cd43027d3da585eae8cc4079ba3ae39c Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:28:33 -0500 Subject: [PATCH 039/129] feat(cli): route CLI-side dashboard calls through the agent credential PAN-5754 WI-11. callDashboard, pan plan and pan start's start-planning call use dashboardFetch (agent socket + Bearer in an isolated context, the internal-token header over TCP otherwise; an AgentCredentialError is not reported as an unreachable dashboard). emitAgentEvent and the deacon event client keep their own URLs and take dashboardAuthHeaders (an explicit deacon token still wins). The pipeline notifier keeps its skip-when-no-credential rule and posts with the agent token when isolated, never creating the internal token. dashboardFetch now passes a plain header record with the caller's casing, and loads config lazily so low-level clients gain no import edge to it. Not converted here: callers on operator-only verbs (merge, machines, serve, dev, sharing, admin conversations), the Flywheel watchdog, and the review/planning helpers that WI-17..19 forward as self jobs. Item: cli-callers Co-Authored-By: Claude Opus 5.5 Overdeck-Agent: agent-pan-5754 --- src/cli/commands/dashboard-call.ts | 14 +- src/cli/commands/plan.ts | 7 +- src/cli/commands/start.ts | 10 +- src/lib/agent-runtime.ts | 15 ++- src/lib/cloister/deacon-event-client.ts | 16 +-- .../__tests__/isolated-callers.test.ts | 127 ++++++++++++++++++ src/lib/dashboard-client/agent-credential.ts | 26 ++-- src/lib/pipeline-notifier.ts | 21 ++- 8 files changed, 194 insertions(+), 42 deletions(-) create mode 100644 src/lib/dashboard-client/__tests__/isolated-callers.test.ts diff --git a/src/cli/commands/dashboard-call.ts b/src/cli/commands/dashboard-call.ts index b606aa7770c..17df9962260 100644 --- a/src/cli/commands/dashboard-call.ts +++ b/src/cli/commands/dashboard-call.ts @@ -6,21 +6,25 @@ */ export class DashboardUnreachableError extends Error {} -/** Call the running dashboard with the internal token. Throws DashboardUnreachableError when nothing answers. */ +/** + * Call the running dashboard with this process's credential (the internal token, or in an + * isolated agent the agent token over the agent socket, PAN-5754). Throws + * DashboardUnreachableError when nothing answers; an unreadable agent token is rethrown as is. + */ export async function callDashboard( path: string, init: { method: string; body?: unknown; headers?: Record; signal?: AbortSignal }, ): Promise { - const { getDashboardApiUrl } = await import('../../lib/config.js'); - const { ensureInternalToken, INTERNAL_TOKEN_HEADER } = await import('../../lib/internal-token.js'); + const { AgentCredentialError, dashboardFetch } = await import('../../lib/dashboard-client/agent-credential.js'); try { - return await fetch(`${getDashboardApiUrl()}${path}`, { + return await dashboardFetch(path, { method: init.method, - headers: { 'Content-Type': 'application/json', ...init.headers, [INTERNAL_TOKEN_HEADER]: ensureInternalToken() }, + headers: { 'Content-Type': 'application/json', ...init.headers }, body: init.body === undefined ? undefined : JSON.stringify(init.body), signal: init.signal, }); } catch (error) { + if (error instanceof AgentCredentialError) throw error; throw new DashboardUnreachableError((error as Error).message, { cause: error }); } } diff --git a/src/cli/commands/plan.ts b/src/cli/commands/plan.ts index 93e220aaf3b..9ee4bc35c92 100644 --- a/src/cli/commands/plan.ts +++ b/src/cli/commands/plan.ts @@ -2,9 +2,8 @@ import { exitCli } from '../exit.js'; import chalk from 'chalk'; import ora from 'ora'; import type { EffortLevel } from '@overdeck/contracts'; -import { getDashboardApiUrl } from '../../lib/config.js'; import { resolveCliStartedBy } from '../../lib/agents/provenance.js'; -import { ensureInternalToken, INTERNAL_TOKEN_HEADER } from '../../lib/internal-token.js'; +import { dashboardFetch } from '../../lib/dashboard-client/agent-credential.js'; import { buildStartPlanningBody, printPlanningConnectionError, streamPlanningSession } from './planning-stream.js'; interface PlanOptions { @@ -36,9 +35,9 @@ export async function planCommand(id: string | undefined, options: PlanOptions): const spinner = ora(`${options.auto ? 'Auto-planning' : 'Starting planning for'} ${issueId}...`).start(); try { - const response = await fetch(`${getDashboardApiUrl()}/api/issues/${encodeURIComponent(issueId)}/start-planning`, { + const response = await dashboardFetch(`/api/issues/${encodeURIComponent(issueId)}/start-planning`, { method: 'POST', - headers: { 'Content-Type': 'application/json', [INTERNAL_TOKEN_HEADER]: ensureInternalToken() }, + headers: { 'Content-Type': 'application/json' }, body: buildStartPlanningBody({ auto: options.auto === true, autoStart: options.autoStart === true, diff --git a/src/cli/commands/start.ts b/src/cli/commands/start.ts index 33f5579da3b..9e86e2c754f 100644 --- a/src/cli/commands/start.ts +++ b/src/cli/commands/start.ts @@ -14,7 +14,7 @@ import { appendOperatorInterventionEvent } from '../../lib/operator-intervention import { attachHintLines, resolveAttach } from '../../lib/terminal-backends/attach-hint.js'; import { AgentAlreadyRunningError } from '../../lib/agents/start-claim.js'; import { resolveCliStartedBy } from '../../lib/agents/provenance.js'; -import { ensureInternalToken, INTERNAL_TOKEN_HEADER } from '../../lib/internal-token.js'; +import { dashboardFetch } from '../../lib/dashboard-client/agent-credential.js'; import { describeConflictingWorkAgents } from '../../lib/work-agent-conflicts.js'; import { resolveModel as resolveRoleModel, loadConfigSync as loadYamlConfig, type RoleEffort } from '../../lib/config-yaml.js'; import { resolveEffort, InvalidEffortError } from '../../lib/agents/resolve-effort.js'; @@ -51,7 +51,7 @@ function isLinearIssue(issueId: string): boolean { import { shouldSkipTrackerUpdate } from '../../lib/shadow-mode.js'; import { createShadowState, updateShadowState } from '../../lib/shadow-state.js'; -import { getDashboardApiUrl, loadConfigSync } from '../../lib/config.js'; +import { loadConfigSync } from '../../lib/config.js'; import { loadWorkspaceMetadata, findRemoteWorkspaceMetadata, @@ -690,11 +690,11 @@ export async function issueCommand(id: string, options: IssueOptions): Promise ensureInternalToken(), + // attach this same header; the lib emitter must too. PAN-5754: an isolated + // agent sends its own agent token instead (the route accepts it for itself). + const auth = yield* Effect.try({ + try: (): Record => dashboardAuthHeaders(), catch: (cause) => new AgentRuntimeFetchError({ url, cause }), - }).pipe(Effect.orElseSucceed((): string | null => null)) - if (!token) return false + }).pipe(Effect.orElseSucceed((): Record | null => null)) + if (!auth) return false const res = yield* Effect.tryPromise({ try: () => fetch(url, { method: 'POST', - headers: { 'Content-Type': 'application/json', [INTERNAL_TOKEN_HEADER]: token }, + headers: { 'Content-Type': 'application/json', ...auth }, body: JSON.stringify({ ...body, timestamp: new Date().toISOString() }), signal: abortSignal(DEFAULT_TIMEOUT_MS), }), diff --git a/src/lib/cloister/deacon-event-client.ts b/src/lib/cloister/deacon-event-client.ts index a7d39f5106f..8065a7db1ed 100644 --- a/src/lib/cloister/deacon-event-client.ts +++ b/src/lib/cloister/deacon-event-client.ts @@ -1,5 +1,6 @@ import type { DomainEvent } from '@overdeck/contracts'; -import { ensureInternalToken, INTERNAL_TOKEN_HEADER } from '../internal-token.js'; +import { INTERNAL_TOKEN_HEADER } from '../internal-token.js'; +import { dashboardAuthHeaders } from '../dashboard-client/agent-credential.js'; export interface DeaconEventClientOptions { dashboardUrl?: string; @@ -50,6 +51,8 @@ function internalDashboardOrigin(): string { export function createDeaconEventClient(options: DeaconEventClientOptions = {}): DeaconEventClient { const dashboardUrl = options.dashboardUrl ?? internalDashboardOrigin(); + // PAN-5754: an explicit token wins; otherwise the process credential (the agent token when isolated). + const authHeaders = (): Record => (options.token ? { [INTERNAL_TOKEN_HEADER]: options.token } : dashboardAuthHeaders()); const fetchImpl = options.fetchImpl ?? fetch; const warn = options.warn ?? ((message) => console.warn(message)); const batchSize = options.batchSize ?? DEFAULT_BATCH_SIZE; @@ -94,13 +97,12 @@ export function createDeaconEventClient(options: DeaconEventClientOptions = {}): inFlight = true; const batch = queue.slice(0, batchSize); try { - const token = options.token ?? ensureInternalToken(); const response = await fetchImpl(new URL('/api/internal/events', dashboardUrl), { method: 'POST', headers: { 'content-type': 'application/json', origin: dashboardUrl, - [INTERNAL_TOKEN_HEADER]: token, + ...authHeaders(), }, body: JSON.stringify({ events: batch }), }); @@ -118,11 +120,10 @@ export function createDeaconEventClient(options: DeaconEventClientOptions = {}): } async function fetchJson(url: URL, signal?: AbortSignal): Promise { - const token = options.token ?? ensureInternalToken(); const response = await fetchImpl(url, { signal, headers: { - [INTERNAL_TOKEN_HEADER]: token, + ...authHeaders(), origin: dashboardUrl, }, }); @@ -196,13 +197,12 @@ export function createDeaconEventClient(options: DeaconEventClientOptions = {}): const controller = new AbortController(); const deadline = setTimeout(() => controller.abort(), appendOnceTimeoutMs); try { - const token = options.token ?? ensureInternalToken(); const response = await fetchImpl(new URL('/api/internal/events/append-once', dashboardUrl), { method: 'POST', headers: { 'content-type': 'application/json', origin: dashboardUrl, - [INTERNAL_TOKEN_HEADER]: token, + ...authHeaders(), }, body: JSON.stringify({ event, idempotencyKey }), signal: controller.signal, @@ -253,7 +253,7 @@ export function createDeaconEventClient(options: DeaconEventClientOptions = {}): const response = await fetchImpl(url, { signal: abortController.signal, headers: { - [INTERNAL_TOKEN_HEADER]: options.token ?? ensureInternalToken(), + ...authHeaders(), origin: dashboardUrl, }, }); diff --git a/src/lib/dashboard-client/__tests__/isolated-callers.test.ts b/src/lib/dashboard-client/__tests__/isolated-callers.test.ts new file mode 100644 index 00000000000..55edc64309c --- /dev/null +++ b/src/lib/dashboard-client/__tests__/isolated-callers.test.ts @@ -0,0 +1,127 @@ +/** + * PAN-5754 WI-11: the CLI-side dashboard callers send the agent token in an isolated + * context and never create the internal token; outside it they keep the internal-token + * header. Real stub servers (Unix socket and TCP) under a temp OVERDECK_HOME. + */ +import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { createServer, type IncomingHttpHeaders, type Server } from 'node:http'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { Effect } from 'effect'; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest'; + +const TOKEN = `odk_${'b'.repeat(64)}`; +const seen: Array<{ via: string; url: string; headers: IncomingHttpHeaders }> = []; +const servers: Server[] = []; +const home = mkdtempSync(join(tmpdir(), 'pan-5754-callers-')); +const originalEnv = { ...process.env }; +let port = 0; + +function stub(via: string): Server { + const server = createServer((req, res) => { + req.resume(); + req.on('end', () => { + seen.push({ via, url: req.url ?? '', headers: req.headers }); + res.writeHead(200, { 'content-type': 'application/json' }); + res.end(JSON.stringify({ outcome: 'appended' })); + }); + }); + servers.push(server); + return server; +} + +beforeAll(async () => { + const tcp = stub('tcp'); + await new Promise((resolve) => tcp.listen(0, '127.0.0.1', () => resolve())); + port = (tcp.address() as { port: number }).port; + const socketPath = join(home, 'dashboard.sock'); + const unix = stub('socket'); + await new Promise((resolve) => unix.listen(socketPath, () => resolve())); + writeFileSync(join(home, 'mcp-token'), `${TOKEN}\n`, { mode: 0o600 }); + process.env.OVERDECK_HOME = join(home, 'overdeck'); + process.env.OVERDECK_DASHBOARD_URL = `http://127.0.0.1:${port}`; + delete process.env.OVERDECK_INTERNAL_TOKEN; +}); + +afterAll(async () => { + await Promise.all(servers.map((server) => new Promise((resolve) => server.close(() => resolve())))); + process.env = originalEnv; + rmSync(home, { recursive: true, force: true }); +}); + +beforeEach(async () => { + seen.length = 0; + const { _resetInternalTokenCacheForTests } = await import('../../internal-token.js'); + _resetInternalTokenCacheForTests(); +}); + +afterEach(() => { + delete process.env.OVERDECK_AGENT_TOKEN_FILE; + delete process.env.OVERDECK_DASHBOARD_SOCKET; + rmSync(join(home, 'overdeck'), { recursive: true, force: true }); +}); + +function isolate(withSocket = true): void { + process.env.OVERDECK_AGENT_TOKEN_FILE = join(home, 'mcp-token'); + if (withSocket) process.env.OVERDECK_DASHBOARD_SOCKET = join(home, 'dashboard.sock'); +} + +const internalTokenFile = () => join(home, 'overdeck', 'internal-token'); + +describe('CLI dashboard callers in an isolated context (PAN-5754 WI-11)', () => { + it('callDashboard goes over the agent socket with the agent token', async () => { + isolate(); + const { callDashboard } = await import('../../../cli/commands/dashboard-call.js'); + const response = await callDashboard('/api/x', { method: 'POST', body: { a: 1 }, headers: { 'x-overdeck-internal-token': 'leak' } }); + expect(response.status).toBe(200); + expect(seen).toEqual([expect.objectContaining({ via: 'socket', url: '/api/x' })]); + expect(seen[0]!.headers.authorization).toBe(`Bearer ${TOKEN}`); + expect(seen[0]!.headers['x-overdeck-internal-token']).toBeUndefined(); + expect(existsSync(internalTokenFile())).toBe(false); + }); + + it('emitAgentEvent posts the heartbeat with the agent token', async () => { + isolate(); + const { emitAgentEvent } = await import('../../agent-runtime.js'); + expect(await Effect.runPromise(emitAgentEvent('agent-pan-1', { kind: 'activity', activity: 'idle' } as never))).toBe(true); + expect(seen[0]!.url).toBe('/api/agents/agent-pan-1/heartbeat'); + expect(seen[0]!.headers.authorization).toBe(`Bearer ${TOKEN}`); + expect(seen[0]!.headers['x-overdeck-internal-token']).toBeUndefined(); + expect(existsSync(internalTokenFile())).toBe(false); + }); + + it('the deacon event client sends the agent token when no token is given', async () => { + isolate(false); + const { createDeaconEventClient } = await import('../../cloister/deacon-event-client.js'); + const client = createDeaconEventClient({ dashboardUrl: `http://127.0.0.1:${port}` }); + expect(await client.appendOnce({ type: 'activity.entry', timestamp: '2026-12-03T00:00:00.000Z', payload: {} } as never, 'k1')).toBe('appended'); + expect(seen[0]!.headers.authorization).toBe(`Bearer ${TOKEN}`); + expect(existsSync(internalTokenFile())).toBe(false); + }); + + it('the pipeline notifier forwards with the agent token and never creates the internal token', async () => { + isolate(false); + const previousNodeEnv = process.env.NODE_ENV; + process.env.NODE_ENV = 'development'; + try { + const { notifyPipeline } = await import('../../pipeline-notifier.js'); + notifyPipeline({ type: 'verification.started', issueId: 'PAN-1' } as never); + await expect.poll(() => seen.length).toBe(1); + } finally { + process.env.NODE_ENV = previousNodeEnv; + } + expect(seen[0]!.url).toBe('/api/internal/pipeline/notify'); + expect(seen[0]!.headers.authorization).toBe(`Bearer ${TOKEN}`); + expect(existsSync(internalTokenFile())).toBe(false); + }); +}); + +describe('CLI dashboard callers outside isolation keep the internal token', () => { + it('callDashboard sends the internal-token header over TCP', async () => { + const { callDashboard } = await import('../../../cli/commands/dashboard-call.js'); + await callDashboard('/api/y', { method: 'GET' }); + expect(seen[0]).toEqual(expect.objectContaining({ via: 'tcp', url: '/api/y' })); + expect(seen[0]!.headers['x-overdeck-internal-token']).toMatch(/^[0-9a-f]{64}$/); + expect(seen[0]!.headers.authorization).toBeUndefined(); + }); +}); diff --git a/src/lib/dashboard-client/agent-credential.ts b/src/lib/dashboard-client/agent-credential.ts index 6f9e5dc3bba..7ef3a178df5 100644 --- a/src/lib/dashboard-client/agent-credential.ts +++ b/src/lib/dashboard-client/agent-credential.ts @@ -12,7 +12,6 @@ import { readFileSync } from 'node:fs'; import { request as httpRequest } from 'node:http'; import { OVERDECK_AGENT_TOKEN_FILE, OVERDECK_DASHBOARD_SOCKET } from '../agent-isolation/paths.js'; -import { getDashboardApiUrl } from '../config.js'; import { ensureInternalToken, INTERNAL_TOKEN_HEADER } from '../internal-token.js'; const AGENT_TOKEN_FORMAT = /^odk_[0-9a-f]{64}$/; @@ -47,23 +46,28 @@ export function dashboardAuthHeaders(env: NodeJS.ProcessEnv = process.env): Reco return { [INTERNAL_TOKEN_HEADER]: ensureInternalToken() }; } -function withAuth(init: RequestInit, env: NodeJS.ProcessEnv): Headers { - const headers = new Headers(init.headers); - headers.delete(INTERNAL_TOKEN_HEADER); - headers.delete('authorization'); - for (const [key, value] of Object.entries(dashboardAuthHeaders(env))) headers.set(key, value); - return headers; +/** The caller's headers (casing kept) minus any credential header, plus this process's credential. */ +function withAuth(init: RequestInit, env: NodeJS.ProcessEnv): Record { + const headers: Record = {}; + const add = (key: string, value: string): void => { + const lower = key.toLowerCase(); + if (lower !== INTERNAL_TOKEN_HEADER && lower !== 'authorization') headers[key] = value; + }; + const source = init.headers; + if (source instanceof Headers) source.forEach((value, key) => add(key, value)); + else if (Array.isArray(source)) for (const [key, value] of source) add(key, value); + else if (source) for (const [key, value] of Object.entries(source)) add(key, value); + return { ...headers, ...dashboardAuthHeaders(env) }; } -async function requestOverSocket(socketPath: string, path: string, init: RequestInit, headers: Headers): Promise { +async function requestOverSocket(socketPath: string, path: string, init: RequestInit, headers: Record): Promise { const body = init.body == null ? undefined : Buffer.from(await new Response(init.body).arrayBuffer()); - if (body !== undefined) headers.set('content-length', String(body.byteLength)); return new Promise((resolve, reject) => { const req = httpRequest({ socketPath, path, method: init.method ?? 'GET', - headers: Object.fromEntries(headers.entries()), + headers: body === undefined ? headers : { ...headers, 'content-length': String(body.byteLength) }, ...(init.signal ? { signal: init.signal } : {}), }, (res) => { const chunks: Buffer[] = []; @@ -100,5 +104,7 @@ export async function dashboardFetch(path: string, init: RequestInit = {}, env: if (code === undefined || !SOCKET_FALLBACK_CODES.has(code)) throw error; } } + // Lazy: low-level clients import this module for dashboardAuthHeaders without loading config. + const { getDashboardApiUrl } = await import('../config.js'); return fetch(`${getDashboardApiUrl()}${path}`, { ...init, headers }); } diff --git a/src/lib/pipeline-notifier.ts b/src/lib/pipeline-notifier.ts index 2dfba859b2d..e9e07dbc6ff 100644 --- a/src/lib/pipeline-notifier.ts +++ b/src/lib/pipeline-notifier.ts @@ -14,6 +14,7 @@ */ import { getInternalToken, INTERNAL_TOKEN_HEADER } from './internal-token.js'; +import { dashboardAuthHeaders, isIsolatedAgentContext } from './dashboard-client/agent-credential.js'; export type PipelineEvent = | { type: 'review.approved'; issueId: string } @@ -63,8 +64,9 @@ export function notifyPipeline(event: PipelineEvent): void { // Resolve shared secret (PAN-891). If the dashboard hasn't started in this // home (no token file, no env), skip the forward — DB write is durable. - const token = getInternalToken(); - if (!token) return; + // PAN-5754: an isolated agent posts with its own agent token instead. + const authHeaders = notifyAuthHeaders(); + if (!authHeaders) return; // PAN-915 — forward the full event; each type carries its own payload. const body = event; @@ -76,7 +78,7 @@ export function notifyPipeline(event: PipelineEvent): void { method: 'POST', headers: { 'content-type': 'application/json', - [INTERNAL_TOKEN_HEADER]: token, + ...authHeaders, }, body: JSON.stringify(body), signal: ctrl.signal, @@ -87,3 +89,16 @@ export function notifyPipeline(event: PipelineEvent): void { }) .finally(() => clearTimeout(timer)); } + +/** The forward's credential, or null to skip it. Never creates the internal token. */ +function notifyAuthHeaders(): Record | null { + if (isIsolatedAgentContext()) { + try { + return dashboardAuthHeaders(); + } catch { + return null; + } + } + const token = getInternalToken(); + return token ? { [INTERNAL_TOKEN_HEADER]: token } : null; +} From 2d717c46cc666883b57183a6644fb84c9405d345 Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:29:06 -0500 Subject: [PATCH 040/129] chore(cli): record cli-callers acceptance evidence PAN-5754 WI-11: isolated-callers.test.ts covers the notifier's Bearer forward with no internal-token file, callDashboard creating no internal token, and the non-isolated internal-token header. Item: cli-callers.ac1 Item: cli-callers.ac2 Item: cli-callers.ac3 Co-Authored-By: Claude Opus 5.5 Overdeck-Agent: agent-pan-5754 From 5f830618842690f330cb72d30695daa1edcb0652 Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:29:38 -0500 Subject: [PATCH 041/129] chore(workspace): plan artifacts for PAN-5754 Overdeck-Agent: agent-pan-5754 --- .pan/continues/PAN-5754.xbrief.json | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/.pan/continues/PAN-5754.xbrief.json b/.pan/continues/PAN-5754.xbrief.json index ecfd188685d..1c6c1691194 100644 --- a/.pan/continues/PAN-5754.xbrief.json +++ b/.pan/continues/PAN-5754.xbrief.json @@ -2,7 +2,7 @@ "version": "1", "issueId": "PAN-5754", "created": "2026-12-03T21:28:28.525Z", - "updated": "2026-12-03T22:23:38.426Z", + "updated": "2026-12-03T22:29:38.175Z", "gitState": {}, "decisions": [], "hazards": [], @@ -228,9 +228,22 @@ "doneAt": "2026-12-03T22:23:28.777Z" }, "cli-callers": { - "status": "in_progress", + "status": "completed", "claimedBy": "agent-pan-5754", - "claimedAt": "2026-12-03T22:23:38.426Z" + "claimedAt": "2026-12-03T22:23:38.426Z", + "doneAt": "2026-12-03T22:29:38.175Z" + }, + "cli-callers.ac1": { + "status": "completed", + "doneAt": "2026-12-03T22:29:38.175Z" + }, + "cli-callers.ac2": { + "status": "completed", + "doneAt": "2026-12-03T22:29:38.175Z" + }, + "cli-callers.ac3": { + "status": "completed", + "doneAt": "2026-12-03T22:29:38.175Z" } } } From 0b44ed685c524fd2e8a7149a226581975d1fc4f6 Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:29:39 -0500 Subject: [PATCH 042/129] chore(workspace): plan artifacts for PAN-5754 Overdeck-Agent: agent-pan-5754 --- .pan/continues/PAN-5754.xbrief.json | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/.pan/continues/PAN-5754.xbrief.json b/.pan/continues/PAN-5754.xbrief.json index 1c6c1691194..835f2b5d8c1 100644 --- a/.pan/continues/PAN-5754.xbrief.json +++ b/.pan/continues/PAN-5754.xbrief.json @@ -2,7 +2,7 @@ "version": "1", "issueId": "PAN-5754", "created": "2026-12-03T21:28:28.525Z", - "updated": "2026-12-03T22:29:38.175Z", + "updated": "2026-12-03T22:29:39.381Z", "gitState": {}, "decisions": [], "hazards": [], @@ -244,6 +244,11 @@ "cli-callers.ac3": { "status": "completed", "doneAt": "2026-12-03T22:29:38.175Z" + }, + "hooks-token": { + "status": "in_progress", + "claimedBy": "agent-pan-5754", + "claimedAt": "2026-12-03T22:29:39.381Z" } } } From a58e7e6c704c3a82586d84ab5d9266654e872078 Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:31:44 -0500 Subject: [PATCH 043/129] feat(infra): hook scripts authenticate with the agent token when isolated PAN-5754 WI-13. pan-hook-lib.sh sets PAN_AUTH_HEADER once: with OVERDECK_AGENT_TOKEN_FILE set it is the Bearer agent token and internal-token is never read; otherwise it is today's internal-token header. Both pan_emit_event curls, session-start-hook (memory session start), user-prompt-submit-hook (title, memory inject) and stop-hook (turn-complete) use it instead of their own internal-token blocks. Beyond the plan: stop-hook's complete-planning post and permission-event-hook sent no credential and relied on loopback trust, which the peer rule (WI-20) removes for an isolated agent's hooks. complete-planning now sends PAN_AUTH_HEADER, and permission-event-hook sends the Bearer agent token when isolated (unchanged otherwise). Item: hooks-token Item: hooks-token.ac1 Item: hooks-token.ac2 Item: hooks-token.ac3 Co-Authored-By: Claude Opus 5.5 Overdeck-Agent: agent-pan-5754 --- sync-sources/hooks/pan-hook-lib.sh | 23 +++-- sync-sources/hooks/permission-event-hook | 7 ++ sync-sources/hooks/session-start-hook | 12 +-- sync-sources/hooks/stop-hook | 15 +--- sync-sources/hooks/user-prompt-submit-hook | 14 +--- tests/scripts/hooks-agent-token.test.ts | 97 ++++++++++++++++++++++ 6 files changed, 130 insertions(+), 38 deletions(-) create mode 100644 tests/scripts/hooks-agent-token.test.ts diff --git a/sync-sources/hooks/pan-hook-lib.sh b/sync-sources/hooks/pan-hook-lib.sh index cffdb9af398..638b376b235 100644 --- a/sync-sources/hooks/pan-hook-lib.sh +++ b/sync-sources/hooks/pan-hook-lib.sh @@ -270,11 +270,22 @@ pan_llm_rate_check() { # OVERDECK_INTERNAL_TOKEN from a long-lived terminal-backend server # (PAN-4628); the env value is the fallback for a home with no file. Empty # token => same 403/drop as before (no regression). +# +# PAN-5754: an isolated agent (OVERDECK_AGENT_TOKEN_FILE set by its launcher) +# authenticates with its own agent token and never reads internal-token. +# PAN_AUTH_HEADER is the one header every hook curl sends. PAN_INTERNAL_TOKEN="" -_pan_token_path="${OVERDECK_HOME:-$HOME/.overdeck}/internal-token" -[ -f "$_pan_token_path" ] && PAN_INTERNAL_TOKEN=$(cat "$_pan_token_path" 2>/dev/null || true) -if [ -z "$PAN_INTERNAL_TOKEN" ]; then - PAN_INTERNAL_TOKEN="${OVERDECK_INTERNAL_TOKEN:-}" +PAN_AGENT_TOKEN="" +if [ -n "${OVERDECK_AGENT_TOKEN_FILE:-}" ]; then + PAN_AGENT_TOKEN=$(cat "$OVERDECK_AGENT_TOKEN_FILE" 2>/dev/null || true) + PAN_AUTH_HEADER="Authorization: Bearer $PAN_AGENT_TOKEN" +else + _pan_token_path="${OVERDECK_HOME:-$HOME/.overdeck}/internal-token" + [ -f "$_pan_token_path" ] && PAN_INTERNAL_TOKEN=$(cat "$_pan_token_path" 2>/dev/null || true) + if [ -z "$PAN_INTERNAL_TOKEN" ]; then + PAN_INTERNAL_TOKEN="${OVERDECK_INTERNAL_TOKEN:-}" + fi + PAN_AUTH_HEADER="x-overdeck-internal-token: $PAN_INTERNAL_TOKEN" fi # Resolve the current agent ID without a "main-cli" fallback (PAN-69). @@ -363,7 +374,7 @@ pan_emit_event() { local http_code http_code=$(curl -s -m "$PAN_CURL_TIMEOUT" -o /dev/null -w '%{http_code}' \ -X POST "$url" -H 'Content-Type: application/json' \ - -H "x-overdeck-internal-token: $PAN_INTERNAL_TOKEN" --data "$body" 2>/dev/null || echo '000') + -H "$PAN_AUTH_HEADER" --data "$body" 2>/dev/null || echo '000') if [[ "$http_code" =~ ^2 ]]; then return 0 @@ -414,7 +425,7 @@ pan__drain_pending() { local code code=$(curl -s -m "$PAN_CURL_TIMEOUT" -o /dev/null -w '%{http_code}' \ -X POST "$url" -H 'Content-Type: application/json' \ - -H "x-overdeck-internal-token: $PAN_INTERNAL_TOKEN" --data "$line" 2>/dev/null || echo '000') + -H "$PAN_AUTH_HEADER" --data "$line" 2>/dev/null || echo '000') if [[ "$code" =~ ^2 ]]; then : # drained successfully elif [[ "$code" =~ ^4 ]]; then diff --git a/sync-sources/hooks/permission-event-hook b/sync-sources/hooks/permission-event-hook index 18fa0a7c7d6..49a77c9ffbc 100755 --- a/sync-sources/hooks/permission-event-hook +++ b/sync-sources/hooks/permission-event-hook @@ -13,10 +13,17 @@ set +e PAN_DASHBOARD_URL="${OVERDECK_DASHBOARD_URL:-http://localhost:3011}" PAYLOAD=$(cat 2>/dev/null || echo '{}') +# PAN-5754: an isolated agent's hooks are not trusted local callers; send its own token. +PAN_AUTH_ARGS=() +if [ -n "${OVERDECK_AGENT_TOKEN_FILE:-}" ]; then + PAN_AUTH_ARGS=(-H "Authorization: Bearer $(cat "$OVERDECK_AGENT_TOKEN_FILE" 2>/dev/null)") +fi + curl -sf \ --max-time 1 \ -X POST \ -H "Content-Type: application/json" \ + "${PAN_AUTH_ARGS[@]}" \ -d "$PAYLOAD" \ "${PAN_DASHBOARD_URL}/api/hooks/permission-event" \ >/dev/null 2>&1 || true diff --git a/sync-sources/hooks/session-start-hook b/sync-sources/hooks/session-start-hook index c1f90abd25c..be202822644 100755 --- a/sync-sources/hooks/session-start-hook +++ b/sync-sources/hooks/session-start-hook @@ -77,15 +77,7 @@ if [ "${OVERDECK_BARE_CONTEXT:-}" = "1" ]; then exit 0 fi -INTERNAL_TOKEN="" -TOKEN_PATH="${OVERDECK_HOME:-$HOME/.overdeck}/internal-token" -if [ -f "$TOKEN_PATH" ]; then - INTERNAL_TOKEN=$(cat "$TOKEN_PATH" 2>/dev/null || true) -fi -if [ -z "$INTERNAL_TOKEN" ]; then - INTERNAL_TOKEN="${OVERDECK_INTERNAL_TOKEN:-}" -fi - +# PAN_AUTH_HEADER comes from pan-hook-lib.sh (the agent token when isolated, PAN-5754). MEMORY_BRIEFING="" if command -v jq >/dev/null 2>&1; then SESSION_BODY=$(printf '%s' "$INPUT" | jq -c --arg agentId "$AGENT_ID" '. + {agentId: $agentId}' 2>/dev/null) @@ -95,7 +87,7 @@ if command -v jq >/dev/null 2>&1; then # discarding it. The timeout is a hard ceiling on how long session start can # block on the dashboard; the server side composes from local files only # (no LLM, no FTS) specifically to stay well inside it. - SESSION_RESPONSE=$(curl -s -m 1.5 -X POST -H 'Content-Type: application/json' -H "x-overdeck-internal-token: $INTERNAL_TOKEN" --data "$SESSION_BODY" "$PAN_DASHBOARD_URL/api/memory/session/start" 2>/dev/null || true) + SESSION_RESPONSE=$(curl -s -m 1.5 -X POST -H 'Content-Type: application/json' -H "$PAN_AUTH_HEADER" --data "$SESSION_BODY" "$PAN_DASHBOARD_URL/api/memory/session/start" 2>/dev/null || true) if [ -n "$SESSION_RESPONSE" ]; then MEMORY_BRIEFING=$(printf '%s' "$SESSION_RESPONSE" | jq -r '.briefing // ""' 2>/dev/null || true) fi diff --git a/sync-sources/hooks/stop-hook b/sync-sources/hooks/stop-hook index c1397cc7f8d..c3fa2312772 100755 --- a/sync-sources/hooks/stop-hook +++ b/sync-sources/hooks/stop-hook @@ -72,15 +72,7 @@ fi # Fire-and-forget: the dashboard may be down or busy; the stop-hook must still # exit 0 and chain to downstream hooks. if [ "$API_ERROR_DETECTED" != "true" ]; then - INTERNAL_TOKEN="" - TOKEN_PATH="${OVERDECK_HOME:-$HOME/.overdeck}/internal-token" - if [ -f "$TOKEN_PATH" ]; then - INTERNAL_TOKEN=$(cat "$TOKEN_PATH" 2>/dev/null || true) - fi - if [ -z "$INTERNAL_TOKEN" ]; then - INTERNAL_TOKEN="${OVERDECK_INTERNAL_TOKEN:-}" - fi - + # PAN_AUTH_HEADER comes from pan-hook-lib.sh (the agent token when isolated, PAN-5754). if command -v jq >/dev/null 2>&1; then SESSION_ID=$(printf '%s' "$INPUT" | jq -r '(.session_id // "")' 2>/dev/null) if [ -z "$SESSION_ID" ]; then @@ -89,7 +81,7 @@ if [ "$API_ERROR_DETECTED" != "true" ]; then if [ -n "$SESSION_ID" ]; then TURN_COMPLETE_BODY=$(jq -n --arg session_id "$SESSION_ID" '{session_id: $session_id}' 2>/dev/null) if [ -n "$TURN_COMPLETE_BODY" ]; then - curl -s -m 1 -X POST -H 'Content-Type: application/json' -H "x-overdeck-internal-token: $INTERNAL_TOKEN" --data "$TURN_COMPLETE_BODY" "$PAN_DASHBOARD_URL/api/hooks/turn-complete" >/dev/null 2>&1 || true + curl -s -m 1 -X POST -H 'Content-Type: application/json' -H "$PAN_AUTH_HEADER" --data "$TURN_COMPLETE_BODY" "$PAN_DASHBOARD_URL/api/hooks/turn-complete" >/dev/null 2>&1 || true fi fi fi @@ -129,8 +121,9 @@ fi if [[ "$AGENT_ID" == planning-* ]]; then ISSUE_ID=$(echo "$AGENT_ID" | sed 's/^planning-//' | tr '[:lower:]' '[:upper:]') if [ -n "$ISSUE_ID" ]; then + # PAN-5754: credentialed, so an isolated planner's hook passes without loopback trust. curl -s -m 1.0 -X POST "$PAN_DASHBOARD_URL/api/issues/$ISSUE_ID/complete-planning" \ - -H "Content-Type: application/json" \ + -H "Content-Type: application/json" -H "$PAN_AUTH_HEADER" \ -d '{"skipKill":true}' > /dev/null 2>&1 & fi fi diff --git a/sync-sources/hooks/user-prompt-submit-hook b/sync-sources/hooks/user-prompt-submit-hook index b28528b418c..98a1a984c85 100644 --- a/sync-sources/hooks/user-prompt-submit-hook +++ b/sync-sources/hooks/user-prompt-submit-hook @@ -30,19 +30,11 @@ pan_emit_event "$AGENT_ID" "{\"kind\":\"waiting_clear\",\"clearedBy\":\"user_res pan_emit_event "$AGENT_ID" "{\"kind\":\"message_received\",\"direction\":\"to_agent\",\"source\":\"user\",\"timestamp\":\"$TS\"}" pan_emit_event "$AGENT_ID" "{\"kind\":\"thinking_start\",\"lastToolAt\":\"$TS\",\"timestamp\":\"$TS\"}" -INTERNAL_TOKEN="" -TOKEN_PATH="${OVERDECK_HOME:-$HOME/.overdeck}/internal-token" -if [ -f "$TOKEN_PATH" ]; then - INTERNAL_TOKEN=$(cat "$TOKEN_PATH" 2>/dev/null || true) -fi -if [ -z "$INTERNAL_TOKEN" ]; then - INTERNAL_TOKEN="${OVERDECK_INTERNAL_TOKEN:-}" -fi - +# PAN_AUTH_HEADER comes from pan-hook-lib.sh (the agent token when isolated, PAN-5754). if command -v jq >/dev/null 2>&1; then TITLE_BODY=$(printf '%s' "$INPUT" | jq -c '{session_id: (.session_id // ""), prompt: (.prompt // .message // .input // "")}' 2>/dev/null) if [ -n "$TITLE_BODY" ]; then - curl -s -m 1 -X POST -H 'Content-Type: application/json' -H "x-overdeck-internal-token: $INTERNAL_TOKEN" --data "$TITLE_BODY" "$PAN_DASHBOARD_URL/api/hooks/user-prompt-submit" >/dev/null 2>&1 || true + curl -s -m 1 -X POST -H 'Content-Type: application/json' -H "$PAN_AUTH_HEADER" --data "$TITLE_BODY" "$PAN_DASHBOARD_URL/api/hooks/user-prompt-submit" >/dev/null 2>&1 || true fi # PAN-4185: a bare conversation skips memory retrieval and briefing updates; @@ -52,7 +44,7 @@ if command -v jq >/dev/null 2>&1; then INJECT_BODY=$(printf '%s' "$INPUT" | jq -c --arg agentId "$AGENT_ID" '{prompt: (.prompt // .message // .input // ""), sessionId: (.session_id // ""), agentId: $agentId}' 2>/dev/null) fi if [ -n "$INJECT_BODY" ]; then - INJECT_RESPONSE=$(curl -s -m 1 -X POST -H 'Content-Type: application/json' -H "x-overdeck-internal-token: $INTERNAL_TOKEN" --data "$INJECT_BODY" "$PAN_DASHBOARD_URL/api/memory/inject" 2>/dev/null || true) + INJECT_RESPONSE=$(curl -s -m 1 -X POST -H 'Content-Type: application/json' -H "$PAN_AUTH_HEADER" --data "$INJECT_BODY" "$PAN_DASHBOARD_URL/api/memory/inject" 2>/dev/null || true) INJECT_CONTEXT=$(printf '%s' "$INJECT_RESPONSE" | jq -r 'if .ok == true and (.context // "") != "" then .context else empty end' 2>/dev/null) if [ -n "$INJECT_CONTEXT" ]; then printf '%s\n' "$INJECT_CONTEXT" diff --git a/tests/scripts/hooks-agent-token.test.ts b/tests/scripts/hooks-agent-token.test.ts new file mode 100644 index 00000000000..104c6e2ec2f --- /dev/null +++ b/tests/scripts/hooks-agent-token.test.ts @@ -0,0 +1,97 @@ +/** + * PAN-5754 WI-13: hook scripts authenticate with the agent token when + * OVERDECK_AGENT_TOKEN_FILE is set and never read or create internal-token; + * without it they send the internal-token header as before. A stub curl on PATH + * records the arguments each hook sends. + */ +import { spawnSync } from 'node:child_process' +import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' + +const HOOKS = join(process.cwd(), 'sync-sources', 'hooks') +const AGENT_TOKEN = `odk_${'c'.repeat(64)}` +const INTERNAL = 'f'.repeat(64) + +let dir: string +let bin: string +let home: string +let overdeckHome: string +let curlLog: string +let tokenFile: string + +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'pan-5754-hooks-')) + bin = join(dir, 'bin') + home = join(dir, 'home') + overdeckHome = join(home, '.overdeck') + curlLog = join(dir, 'curl.log') + tokenFile = join(dir, 'mcp-token') + mkdirSync(bin, { recursive: true }) + mkdirSync(overdeckHome, { recursive: true }) + writeFileSync(tokenFile, `${AGENT_TOKEN}\n`, { mode: 0o600 }) + // The stub answers 200 for -w '%{http_code}' callers and records every argument. + writeFileSync(join(bin, 'curl'), `#!/bin/bash\nprintf '%s\\n' "$@" >> '${curlLog}'\nprintf '200'\n`) + chmodSync(join(bin, 'curl'), 0o755) +}) + +afterEach(() => { + rmSync(dir, { recursive: true, force: true }) +}) + +function run(script: string, stdin: string, env: Record): { status: number | null; curl: string } { + const result = spawnSync('bash', ['-c', script], { + input: stdin, + encoding: 'utf8', + env: { + ...process.env, + HOME: home, + OVERDECK_HOME: overdeckHome, + OVERDECK_DASHBOARD_URL: 'http://dashboard.test', + PAN_DASHBOARD_URL: 'http://dashboard.test', + OVERDECK_INTERNAL_TOKEN: '', + OVERDECK_AGENT_TOKEN_FILE: '', + PATH: `${bin}:${process.env.PATH ?? ''}`, + ...env, + }, + }) + return { status: result.status, curl: existsSync(curlLog) ? readFileSync(curlLog, 'utf8') : '' } +} + +const SESSION_START = JSON.stringify({ session_id: 'session-5754', source: 'startup' }) +const sessionStart = `bash ${JSON.stringify(join(HOOKS, 'session-start-hook'))}` + +describe('hook scripts and the agent token (PAN-5754 WI-13)', () => { + it('session-start-hook sends the Bearer agent token and no internal-token header when isolated', () => { + writeFileSync(join(overdeckHome, 'internal-token'), INTERNAL) + const { status, curl } = run(sessionStart, SESSION_START, { OVERDECK_AGENT_ID: 'agent-pan-5754', OVERDECK_AGENT_TOKEN_FILE: tokenFile }) + expect(status).toBe(0) + expect(curl).toContain('http://dashboard.test/api/memory/session/start') + expect(curl).toContain(`Authorization: Bearer ${AGENT_TOKEN}`) + expect(curl).not.toContain('x-overdeck-internal-token') + expect(curl).not.toContain(INTERNAL) + }) + + it('session-start-hook keeps the internal-token header when not isolated', () => { + writeFileSync(join(overdeckHome, 'internal-token'), INTERNAL) + const { curl } = run(sessionStart, SESSION_START, { OVERDECK_AGENT_ID: 'agent-pan-5754' }) + expect(curl).toContain(`x-overdeck-internal-token: ${INTERNAL}`) + expect(curl).not.toContain('Authorization: Bearer') + }) + + it("pan-hook-lib.sh's event emit sends Bearer and never creates internal-token", () => { + const script = `. ${JSON.stringify(join(HOOKS, 'pan-hook-lib.sh'))}; pan_emit_event agent-pan-5754 '{"kind":"activity","activity":"idle"}'` + const { curl } = run(script, '', { OVERDECK_AGENT_TOKEN_FILE: tokenFile }) + expect(curl).toContain('http://dashboard.test/api/agents/agent-pan-5754/heartbeat') + expect(curl).toContain(`Authorization: Bearer ${AGENT_TOKEN}`) + expect(existsSync(join(overdeckHome, 'internal-token'))).toBe(false) + }) + + it('permission-event-hook sends Bearer only when isolated', () => { + const hook = `bash ${JSON.stringify(join(HOOKS, 'permission-event-hook'))}` + expect(run(hook, '{}', { OVERDECK_AGENT_TOKEN_FILE: tokenFile }).curl).toContain(`Authorization: Bearer ${AGENT_TOKEN}`) + rmSync(curlLog, { force: true }) + expect(run(hook, '{}', {}).curl).not.toContain('Authorization') + }) +}) From fdb472c3a91fce3cf979abd1ad1a58aa9778ae49 Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:32:10 -0500 Subject: [PATCH 044/129] chore(workspace): plan artifacts for PAN-5754 Overdeck-Agent: agent-pan-5754 --- .pan/continues/PAN-5754.xbrief.json | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/.pan/continues/PAN-5754.xbrief.json b/.pan/continues/PAN-5754.xbrief.json index 835f2b5d8c1..09270ceaf60 100644 --- a/.pan/continues/PAN-5754.xbrief.json +++ b/.pan/continues/PAN-5754.xbrief.json @@ -2,7 +2,7 @@ "version": "1", "issueId": "PAN-5754", "created": "2026-12-03T21:28:28.525Z", - "updated": "2026-12-03T22:29:39.381Z", + "updated": "2026-12-03T22:32:10.535Z", "gitState": {}, "decisions": [], "hazards": [], @@ -246,9 +246,22 @@ "doneAt": "2026-12-03T22:29:38.175Z" }, "hooks-token": { - "status": "in_progress", + "status": "completed", "claimedBy": "agent-pan-5754", - "claimedAt": "2026-12-03T22:29:39.381Z" + "claimedAt": "2026-12-03T22:29:39.381Z", + "doneAt": "2026-12-03T22:32:10.535Z" + }, + "hooks-token.ac1": { + "status": "completed", + "doneAt": "2026-12-03T22:32:10.535Z" + }, + "hooks-token.ac2": { + "status": "completed", + "doneAt": "2026-12-03T22:32:10.535Z" + }, + "hooks-token.ac3": { + "status": "completed", + "doneAt": "2026-12-03T22:32:10.535Z" } } } From ffa2f3b729da5e76c10d47c4526d9392b6769284 Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:32:16 -0500 Subject: [PATCH 045/129] chore(workspace): plan artifacts for PAN-5754 Overdeck-Agent: agent-pan-5754 --- .pan/continues/PAN-5754.xbrief.json | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/.pan/continues/PAN-5754.xbrief.json b/.pan/continues/PAN-5754.xbrief.json index 09270ceaf60..1fce3a687d5 100644 --- a/.pan/continues/PAN-5754.xbrief.json +++ b/.pan/continues/PAN-5754.xbrief.json @@ -2,7 +2,7 @@ "version": "1", "issueId": "PAN-5754", "created": "2026-12-03T21:28:28.525Z", - "updated": "2026-12-03T22:32:10.535Z", + "updated": "2026-12-03T22:32:16.445Z", "gitState": {}, "decisions": [], "hazards": [], @@ -262,6 +262,11 @@ "hooks-token.ac3": { "status": "completed", "doneAt": "2026-12-03T22:32:10.535Z" + }, + "in-pane-callers": { + "status": "in_progress", + "claimedBy": "agent-pan-5754", + "claimedAt": "2026-12-03T22:32:16.444Z" } } } From d0929d59f9aed6d084dd81ea792e12b2b98473ef Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:34:24 -0500 Subject: [PATCH 046/129] feat(infra): in-pane helpers use the agent token when isolated PAN-5754 WI-12. The caveman memory hook script the workspace writes reads OVERDECK_AGENT_TOKEN_FILE when set and sends Authorization: Bearer, without reading internal-token; otherwise it sends today's internal-token header. Codex prompt memory posts /api/memory/inject with the agent token in an isolated context (an unreadable token skips the inject, as a missing internal token does). The channels bridge relays a permission request with the agent token when isolated. Item: in-pane-callers Item: in-pane-callers.ac1 Item: in-pane-callers.ac2 Co-Authored-By: Claude Opus 5.5 Overdeck-Agent: agent-pan-5754 --- src/lib/caveman/__tests__/workspace.test.ts | 36 +++++++++++++++++++ src/lib/caveman/workspace.ts | 12 ++++++- src/lib/channels/overdeck-bridge.ts | 17 ++++++--- src/lib/codex/__tests__/prompt-memory.test.ts | 19 ++++++++++ src/lib/codex/prompt-memory.ts | 20 +++++++++-- 5 files changed, 95 insertions(+), 9 deletions(-) diff --git a/src/lib/caveman/__tests__/workspace.test.ts b/src/lib/caveman/__tests__/workspace.test.ts index 9ff5fb8dd62..07f57ee194d 100644 --- a/src/lib/caveman/__tests__/workspace.test.ts +++ b/src/lib/caveman/__tests__/workspace.test.ts @@ -155,6 +155,42 @@ describe('injectMemoryHookSettings', () => { const internalTokenFn = scriptContent.slice(scriptContent.indexOf('function internalToken()')); expect(internalTokenFn.indexOf('existsSync(path)')).toBeLessThan(internalTokenFn.indexOf('process.env.OVERDECK_INTERNAL_TOKEN')); }); + + it('PAN-5754: the generated memory hook sends the Bearer agent token when OVERDECK_AGENT_TOKEN_FILE is set', async () => { + const { createServer } = await import('node:http'); + const { spawn } = await import('node:child_process'); + await injectMemoryHookSettings(workspaceDir); + const settings = JSON.parse(readFileSync(join(workspaceDir, '.claude', 'settings.json'), 'utf-8')); + const scriptPath = settings.hooks.UserPromptSubmit[0].hooks[0].command.match(/node "([^"]+)" prompt-inject/)?.[1] as string; + const seen: Array> = []; + const server = createServer((req, res) => { + seen.push(req.headers); + req.resume(); + req.on('end', () => res.end(JSON.stringify({ ok: true, context: '' }))); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', () => resolve())); + try { + const port = (server.address() as { port: number }).port; + const tokenFile = join(testBase, 'mcp-token'); + writeFileSync(tokenFile, `odk_${'e'.repeat(64)}\n`); + writeFileSync(join(testBase, 'internal-token'), 'operator-secret'); + const run = (env: Record) => new Promise((resolve) => { + const child = spawn(process.execPath, [scriptPath, 'prompt-inject'], { + env: { ...process.env, OVERDECK_DASHBOARD_URL: `http://127.0.0.1:${port}`, OVERDECK_HOME: testBase, OVERDECK_INTERNAL_TOKEN: '', ...env }, + }); + child.on('close', () => resolve()); + child.stdin.end(JSON.stringify({ prompt: 'hi', session_id: 's1' })); + }); + await run({ OVERDECK_AGENT_TOKEN_FILE: tokenFile }); + await run({ OVERDECK_AGENT_TOKEN_FILE: '' }); + expect(seen[0]!.authorization).toBe(`Bearer odk_${'e'.repeat(64)}`); + expect(seen[0]!['x-overdeck-internal-token']).toBeUndefined(); + expect(seen[1]!['x-overdeck-internal-token']).toBe('operator-secret'); + expect(seen[1]!.authorization).toBeUndefined(); + } finally { + await new Promise((resolve) => server.close(() => resolve())); + } + }); }); // ─── injectCavemanSettings ──────────────────────────────────────────────────── diff --git a/src/lib/caveman/workspace.ts b/src/lib/caveman/workspace.ts index 48ffbdfe0ff..ada3c40fabf 100644 --- a/src/lib/caveman/workspace.ts +++ b/src/lib/caveman/workspace.ts @@ -208,7 +208,7 @@ async function post(path, body, timeoutMs) { try { return await fetch(baseUrl + path, { method: 'POST', - headers: { 'Content-Type': 'application/json', 'x-overdeck-internal-token': internalToken() }, + headers: { 'Content-Type': 'application/json', ...authHeaders() }, body: JSON.stringify(body), signal: controller.signal, }); @@ -216,6 +216,16 @@ async function post(path, body, timeoutMs) { clearTimeout(timer); } } +// PAN-5754: an isolated agent sends its own token and never reads internal-token. +function authHeaders() { + const tokenFile = process.env.OVERDECK_AGENT_TOKEN_FILE; + if (tokenFile) { + let token = ''; + try { token = readFileSync(tokenFile, 'utf8').trim(); } catch {} + return { Authorization: 'Bearer ' + token }; + } + return { 'x-overdeck-internal-token': internalToken() }; +} function internalToken() { const path = join(process.env.OVERDECK_HOME || join(homedir(), '.overdeck'), 'internal-token'); if (existsSync(path)) { diff --git a/src/lib/channels/overdeck-bridge.ts b/src/lib/channels/overdeck-bridge.ts index 8da67e7a7b2..1bd9e88ea0d 100644 --- a/src/lib/channels/overdeck-bridge.ts +++ b/src/lib/channels/overdeck-bridge.ts @@ -52,6 +52,7 @@ import { type NormalizedChannelPermissionRequestFields, } from './permission-payload.js'; import { getInternalToken, INTERNAL_TOKEN_HEADER } from '../internal-token.js'; +import { dashboardAuthHeaders, isIsolatedAgentContext } from '../dashboard-client/agent-credential.js'; /** * Resolve the per-agent ID from env. Tests import this module to call the @@ -349,14 +350,20 @@ export async function pushPermissionDecisionNotification( return { ok: true, status: 200, body: 'ok' }; } -async function forwardPermissionRequestToDashboard( - agentId: string, - request: ChannelPermissionRequest, -): Promise { +function internalTokenHeader(): Record { const token = getInternalToken(); if (!token) { throw new Error('internal token unavailable; dashboard permission relay not configured'); } + return { [INTERNAL_TOKEN_HEADER]: token }; +} + +async function forwardPermissionRequestToDashboard( + agentId: string, + request: ChannelPermissionRequest, +): Promise { + // PAN-5754: an isolated agent relays with its own agent token (the route accepts it for itself). + const authHeaders = isIsolatedAgentContext() ? dashboardAuthHeaders() : internalTokenHeader(); const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), 2_000); @@ -368,7 +375,7 @@ async function forwardPermissionRequestToDashboard( method: 'POST', headers: { 'content-type': 'application/json', - [INTERNAL_TOKEN_HEADER]: token, + ...authHeaders, }, body: JSON.stringify({ requestId: request.requestId, diff --git a/src/lib/codex/__tests__/prompt-memory.test.ts b/src/lib/codex/__tests__/prompt-memory.test.ts index ec56fa2d5bc..57edeca0f65 100644 --- a/src/lib/codex/__tests__/prompt-memory.test.ts +++ b/src/lib/codex/__tests__/prompt-memory.test.ts @@ -40,6 +40,25 @@ describe('applyCodexPromptMemory (PAN-5359)', () => { }); }); + it('PAN-5754: posts with the Bearer agent token in an isolated context and never reads the internal token', async () => { + const { mkdtempSync, rmSync, writeFileSync } = await import('node:fs'); + const { tmpdir } = await import('node:os'); + const { join } = await import('node:path'); + const dir = mkdtempSync(join(tmpdir(), 'pan-5754-prompt-memory-')); + try { + const tokenFile = join(dir, 'mcp-token'); + writeFileSync(tokenFile, `odk_${'d'.repeat(64)}\n`); + const fetchImpl = vi.fn(async () => new Response(JSON.stringify({ ok: true, context: 'MEM' }), { status: 202 })); + const { token: _token, ...rest } = deps({ fetchImpl: fetchImpl as unknown as typeof fetch, env: { OVERDECK_AGENT_TOKEN_FILE: tokenFile } }); + await applyCodexPromptMemory({ prompt: 'build it', agentId: 'agent-pan-1', sessionId: 's1' }, rest); + const headers = fetchImpl.mock.calls[0]![1]?.headers as Record; + expect(headers.authorization).toBe(`Bearer odk_${'d'.repeat(64)}`); + expect(headers['x-overdeck-internal-token']).toBeUndefined(); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + it('never calls fetch and returns the original prompt when OVERDECK_BARE_CONTEXT=1', async () => { const fetchImpl = vi.fn(); diff --git a/src/lib/codex/prompt-memory.ts b/src/lib/codex/prompt-memory.ts index b981f22ae18..8af7fc68f6c 100644 --- a/src/lib/codex/prompt-memory.ts +++ b/src/lib/codex/prompt-memory.ts @@ -6,6 +6,7 @@ */ import { getDashboardLoopbackApiUrl } from '../config.js'; import { getInternalToken, INTERNAL_TOKEN_HEADER } from '../internal-token.js'; +import { dashboardAuthHeaders, isIsolatedAgentContext } from '../dashboard-client/agent-credential.js'; import { wrapCodexTurnContext } from '../codex-rollout-message.js'; export const CODEX_PROMPT_MEMORY_TIMEOUT_MS = 1500; @@ -30,6 +31,19 @@ export interface CodexPromptMemoryResult { contextChars: number; } +/** PAN-5754: the agent token when isolated (never internal-token there); else the internal token, or null to skip. */ +function promptMemoryAuthHeaders(deps: CodexPromptMemoryDeps, env: NodeJS.ProcessEnv): Record | null { + if (!deps.token && isIsolatedAgentContext(env)) { + try { + return dashboardAuthHeaders(env); + } catch { + return null; + } + } + const token = (deps.token ?? getInternalToken)(); + return token ? { [INTERNAL_TOKEN_HEADER]: token } : null; +} + export async function applyCodexPromptMemory( input: CodexPromptMemoryInput, deps: CodexPromptMemoryDeps = {}, @@ -37,15 +51,15 @@ export async function applyCodexPromptMemory( const unchanged = { text: input.prompt, contextChars: 0 }; const env = deps.env ?? process.env; if (!input.prompt.trim() || env.OVERDECK_BARE_CONTEXT === '1') return unchanged; - const token = (deps.token ?? getInternalToken)(); - if (!token) return unchanged; + const authHeaders = promptMemoryAuthHeaders(deps, env); + if (!authHeaders) return unchanged; const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), deps.timeoutMs ?? CODEX_PROMPT_MEMORY_TIMEOUT_MS); try { const baseUrl = deps.baseUrl ? deps.baseUrl() : (env.OVERDECK_DASHBOARD_URL || getDashboardLoopbackApiUrl()); const response = await (deps.fetchImpl ?? fetch)(`${baseUrl}/api/memory/inject`, { method: 'POST', - headers: { 'Content-Type': 'application/json', [INTERNAL_TOKEN_HEADER]: token }, + headers: { 'Content-Type': 'application/json', ...authHeaders }, body: JSON.stringify({ prompt: input.prompt, sessionId: input.sessionId, From 4ce30edf9c0ecffdf6b670200433571316cab3f2 Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:34:52 -0500 Subject: [PATCH 047/129] chore(workspace): plan artifacts for PAN-5754 Overdeck-Agent: agent-pan-5754 --- .pan/continues/PAN-5754.xbrief.json | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/.pan/continues/PAN-5754.xbrief.json b/.pan/continues/PAN-5754.xbrief.json index 1fce3a687d5..c6f37187721 100644 --- a/.pan/continues/PAN-5754.xbrief.json +++ b/.pan/continues/PAN-5754.xbrief.json @@ -2,7 +2,7 @@ "version": "1", "issueId": "PAN-5754", "created": "2026-12-03T21:28:28.525Z", - "updated": "2026-12-03T22:32:16.445Z", + "updated": "2026-12-03T22:34:52.764Z", "gitState": {}, "decisions": [], "hazards": [], @@ -264,9 +264,18 @@ "doneAt": "2026-12-03T22:32:10.535Z" }, "in-pane-callers": { - "status": "in_progress", + "status": "completed", "claimedBy": "agent-pan-5754", - "claimedAt": "2026-12-03T22:32:16.444Z" + "claimedAt": "2026-12-03T22:32:16.444Z", + "doneAt": "2026-12-03T22:34:52.764Z" + }, + "in-pane-callers.ac1": { + "status": "completed", + "doneAt": "2026-12-03T22:34:52.764Z" + }, + "in-pane-callers.ac2": { + "status": "completed", + "doneAt": "2026-12-03T22:34:52.764Z" } } } From a738f6af553fb440133ac4120238fa5d8202af36 Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:34:54 -0500 Subject: [PATCH 048/129] chore(workspace): plan artifacts for PAN-5754 Overdeck-Agent: agent-pan-5754 --- .pan/continues/PAN-5754.xbrief.json | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/.pan/continues/PAN-5754.xbrief.json b/.pan/continues/PAN-5754.xbrief.json index c6f37187721..6c6beb9108f 100644 --- a/.pan/continues/PAN-5754.xbrief.json +++ b/.pan/continues/PAN-5754.xbrief.json @@ -2,7 +2,7 @@ "version": "1", "issueId": "PAN-5754", "created": "2026-12-03T21:28:28.525Z", - "updated": "2026-12-03T22:34:52.764Z", + "updated": "2026-12-03T22:34:54.245Z", "gitState": {}, "decisions": [], "hazards": [], @@ -276,6 +276,11 @@ "in-pane-callers.ac2": { "status": "completed", "doneAt": "2026-12-03T22:34:52.764Z" + }, + "self-auth-routes": { + "status": "in_progress", + "claimedBy": "agent-pan-5754", + "claimedAt": "2026-12-03T22:34:54.245Z" } } } From f8690fcecdb6ee1bd02698d48e8a1dffab62a12e Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:41:09 -0500 Subject: [PATCH 049/129] feat(dashboard): hook and self-report routes accept a self agent token PAN-5754 WI-14 (D-16). routes/self-or-internal.ts: an agent token passes only for its own agent (path :id, normalized, or a conversation's name or tmux session) or, on session-keyed hook routes, only when its agent or conversation owns the body's session_id; a token speaking for anyone else gets 403 not-self, a session with no owner is refused for agent tokens, and the internal token passes as before. - validateAgentRuntimeEventAuth takes the subject: heartbeat, work-complete, stuck and plan-checklist pass :id; the internal permission request uses it too (its 403 body is now the shared { success: false } shape). - memory inject/session start/turn, user-prompt-submit and turn-complete check the session owner (and the body's agentId, where the hook sets one); permission-event checks it when an agent token is presented. - complete-planning: an agent token passes only as the issue's own plan agent, any other credential needs admin, an uncredentialed request the gate already trusted passes as today. Item: self-auth-routes Item: self-auth-routes.ac1 Item: self-auth-routes.ac2 Item: self-auth-routes.ac3 Item: self-auth-routes.ac4 Co-Authored-By: Claude Opus 5.5 Overdeck-Agent: agent-pan-5754 --- .../routes/__tests__/self-or-internal.test.ts | 142 ++++++++++++++++++ .../server/routes/agents/permissions.ts | 18 +-- .../server/routes/agents/runtime-events.ts | 24 +-- src/dashboard/server/routes/agents/shared.ts | 18 ++- src/dashboard/server/routes/hooks.ts | 57 +++++-- src/dashboard/server/routes/issues.ts | 3 + .../server/routes/self-or-internal.ts | 138 +++++++++++++++++ 7 files changed, 359 insertions(+), 41 deletions(-) create mode 100644 src/dashboard/server/routes/__tests__/self-or-internal.test.ts create mode 100644 src/dashboard/server/routes/self-or-internal.ts diff --git a/src/dashboard/server/routes/__tests__/self-or-internal.test.ts b/src/dashboard/server/routes/__tests__/self-or-internal.test.ts new file mode 100644 index 00000000000..fbdf20a7d46 --- /dev/null +++ b/src/dashboard/server/routes/__tests__/self-or-internal.test.ts @@ -0,0 +1,142 @@ +/** + * PAN-5754 WI-14 (D-16): hook and self-report routes accept the internal token or an + * agent token that speaks only for itself. Real access-token registry and internal + * token under a temporary OVERDECK_HOME. + */ +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +import { HttpServerRequest } from 'effect/unstable/http'; +import { afterAll, afterEach, beforeEach, describe, expect, it } from 'vitest'; + +const originalHome = process.env.OVERDECK_HOME; +const home = mkdtempSync(join(tmpdir(), 'pan-5754-self-auth-')); +process.env.OVERDECK_HOME = home; +const INTERNAL = 'a1'.repeat(32); + +const { _resetAccessTokensForTests, _settleAccessTokenWritesForTests, createAccessToken } = await import('../../../../lib/access-tokens.js'); +const { _resetInternalTokenCacheForTests } = await import('../../../../lib/internal-token.js'); +const { validateAgentRuntimeEventAuth } = await import('../agents/shared.js'); +const { authorizeInternalOrSessionOwner, refuseCompletePlanning } = await import('../self-or-internal.js'); + +function request(headers: Record = {}) { + return HttpServerRequest.fromWeb(new Request('http://dashboard.test/api/x', { method: 'POST', headers })); +} + +async function agentToken(agentId: string, role: string, agentKind: 'agent' | 'conversation' = 'agent', scopes: string[] = ['tell', 'operate']) { + const { token } = await createAccessToken({ name: `agent:${role}:${agentId}`, kind: 'token', scopes: scopes as never, agentId, agentKind, role }); + return { authorization: `Bearer ${token}` }; +} + +async function status(result: { ok: boolean; response?: unknown }): Promise<{ status: number; body: unknown } | 'ok'> { + if (result.ok) return 'ok'; + const raw = result.response as { status: number; body: { body?: Uint8Array } }; + return { status: raw.status, body: raw.body.body ? JSON.parse(new TextDecoder().decode(raw.body.body)) : null }; +} + +beforeEach(() => { + writeFileSync(join(home, 'internal-token'), INTERNAL, { mode: 0o600 }); + _resetInternalTokenCacheForTests(); + _resetAccessTokensForTests(); +}); + +afterEach(async () => { + await _settleAccessTokenWritesForTests(); + _resetAccessTokensForTests(); + rmSync(join(home, 'access-tokens.json'), { force: true }); +}); + +afterAll(() => { + _resetInternalTokenCacheForTests(); + if (originalHome === undefined) delete process.env.OVERDECK_HOME; + else process.env.OVERDECK_HOME = originalHome; + rmSync(home, { recursive: true, force: true }); +}); + +describe('runtime-event routes accept a self agent token (heartbeat, work-complete, stuck, plan-checklist, permission request)', () => { + it("passes agent A's own token for A, also given as a bare issue id", async () => { + const headers = await agentToken('agent-pan-1', 'work'); + expect(await status(await validateAgentRuntimeEventAuth(request(headers), 'agent-pan-1'))).toBe('ok'); + expect(await status(await validateAgentRuntimeEventAuth(request(headers), 'PAN-1'))).toBe('ok'); + }); + + it("refuses agent A's token for agent B with 403 not-self", async () => { + const headers = await agentToken('agent-pan-1', 'work'); + expect(await status(await validateAgentRuntimeEventAuth(request(headers), 'agent-pan-2'))).toEqual({ + status: 403, + body: expect.objectContaining({ code: 'not-self' }), + }); + }); + + it('keeps the internal token and refuses no credential', async () => { + expect(await status(await validateAgentRuntimeEventAuth(request({ 'x-overdeck-internal-token': INTERNAL }), 'agent-pan-2'))).toBe('ok'); + expect(await status(await validateAgentRuntimeEventAuth(request(), 'agent-pan-2'))).toMatchObject({ status: 403 }); + }); + + it('accepts a conversation token for its own tmux session', async () => { + const headers = await agentToken('lane-c1', 'worker', 'conversation'); + // tokenSpeaksFor also accepts the conversation name itself without a lookup. + expect(await status(await validateAgentRuntimeEventAuth(request(headers), 'lane-c1'))).toBe('ok'); + }); +}); + +describe('session-keyed hook routes (user-prompt-submit, turn-complete, memory, permission-event)', () => { + const owners: Record = { 'session-a': 'agent-pan-1', 'session-b': 'agent-pan-2' }; + const resolve = async (sessionId: string) => owners[sessionId] ?? null; + const deps = { conversationTmuxSession: () => null, conversationNameForSession: (s: string) => (s === 'session-c' ? 'lane-c1' : null) }; + + it("passes A's token with A's own session", async () => { + const headers = await agentToken('agent-pan-1', 'work'); + expect(await status(await authorizeInternalOrSessionOwner(request(headers), 'session-a', resolve, null, deps))).toBe('ok'); + }); + + it("refuses A's token carrying B's session_id with 403 not-self", async () => { + const headers = await agentToken('agent-pan-1', 'work'); + expect(await status(await authorizeInternalOrSessionOwner(request(headers), 'session-b', resolve, null, deps))).toMatchObject({ + status: 403, + body: { code: 'not-self' }, + }); + }); + + it('refuses an agent token for a session with no owner, or one claiming another agent', async () => { + const headers = await agentToken('agent-pan-1', 'work'); + expect(await status(await authorizeInternalOrSessionOwner(request(headers), 'session-z', resolve, null, deps))).toMatchObject({ status: 403 }); + expect(await status(await authorizeInternalOrSessionOwner(request(headers), 'session-a', resolve, 'agent-pan-2', deps))).toMatchObject({ status: 403 }); + }); + + it("passes a lane conversation's token for its own session", async () => { + const headers = await agentToken('lane-c1', 'worker', 'conversation'); + expect(await status(await authorizeInternalOrSessionOwner(request(headers), 'session-c', resolve, null, deps))).toBe('ok'); + }); + + it('keeps the internal token for any session and answers 401 with no credential', async () => { + expect(await status(await authorizeInternalOrSessionOwner(request({ 'x-overdeck-internal-token': INTERNAL }), 'session-z', resolve, null, deps))).toBe('ok'); + expect(await status(await authorizeInternalOrSessionOwner(request(), 'session-a', resolve, null, deps))).toMatchObject({ status: 401 }); + }); +}); + +describe('complete-planning credential check (WI-14)', () => { + const callerDeps = { + getAgentState: (id: string) => (id === 'planning-pan-1' || id === 'agent-pan-1' ? { workspace: '/w', issueId: 'PAN-1' } : null), + getConversationByName: () => null, + }; + const refusal = (r: unknown) => (r === null ? null : (r as { status: number }).status); + + it("accepts the issue's own planner token and refuses it for another issue", async () => { + const headers = await agentToken('planning-pan-1', 'plan'); + expect(refuseCompletePlanning(request(headers), 'PAN-1', callerDeps)).toBeNull(); + expect(refusal(refuseCompletePlanning(request(headers), 'PAN-2', callerDeps))).toBe(403); + }); + + it('refuses a work-role token and a connector token with operate', async () => { + expect(refusal(refuseCompletePlanning(request(await agentToken('agent-pan-1', 'work')), 'PAN-1', callerDeps))).toBe(403); + const { token } = await createAccessToken({ name: 'connector', kind: 'token', scopes: ['operate', 'read:state'] }); + expect(refusal(refuseCompletePlanning(request({ authorization: `Bearer ${token}` }), 'PAN-1', callerDeps))).toBe(403); + }); + + it('keeps the internal token and an uncredentialed (gate-trusted local) request', () => { + expect(refuseCompletePlanning(request({ 'x-overdeck-internal-token': INTERNAL }), 'PAN-1', callerDeps)).toBeNull(); + expect(refuseCompletePlanning(request(), 'PAN-1', callerDeps)).toBeNull(); + }); +}); diff --git a/src/dashboard/server/routes/agents/permissions.ts b/src/dashboard/server/routes/agents/permissions.ts index cfb7de51f9d..1f87bbaaa8e 100644 --- a/src/dashboard/server/routes/agents/permissions.ts +++ b/src/dashboard/server/routes/agents/permissions.ts @@ -39,9 +39,9 @@ import { processPermissionResponse, } from '../agent-permissions.js'; import { - constantTimeTokenEqual, getAgentPendingQuestions, readJsonBody, + validateAgentRuntimeEventAuth, } from './shared.js'; interface AgentPaneChoiceDeps { @@ -289,19 +289,9 @@ export const postInternalAgentPermissionRequestRoute = HttpRouter.add( } const request = yield* HttpServerRequest.HttpServerRequest; - const { INTERNAL_TOKEN_HEADER, getInternalToken } = yield* Effect.promise(() => - import('../../../../lib/internal-token.js'), - ); - const expected = getInternalToken(); - if (!expected) { - return jsonResponse({ ok: false, error: 'internal token not configured' }, { status: 503 }); - } - const headers = request.headers as Record; - const rawHeader = headers[INTERNAL_TOKEN_HEADER]; - const provided = Array.isArray(rawHeader) ? rawHeader[0] : rawHeader; - if (!constantTimeTokenEqual(provided, expected)) { - return jsonResponse({ ok: false, error: 'forbidden' }, { status: 403 }); - } + // PAN-5754 D-16: the internal token, or the agent's own agent token (an isolated agent has no internal token). + const auth = yield* Effect.promise(() => validateAgentRuntimeEventAuth(request, id)); + if (!auth.ok) return auth.response; const body = (yield* readJsonBody) as Record; const normalized = normalizePermissionRequestBody(body); diff --git a/src/dashboard/server/routes/agents/runtime-events.ts b/src/dashboard/server/routes/agents/runtime-events.ts index 2ff8f0ecd8c..e3534793038 100644 --- a/src/dashboard/server/routes/agents/runtime-events.ts +++ b/src/dashboard/server/routes/agents/runtime-events.ts @@ -114,11 +114,11 @@ export const postAgentHeartbeatRoute = HttpRouter.add( '/api/agents/:id/heartbeat', httpHandler(Effect.gen(function* () { const request = yield* HttpServerRequest.HttpServerRequest; - const auth = yield* Effect.promise(() => validateAgentRuntimeEventAuth(request)); - if (!auth.ok) return auth.response; - const params = yield* HttpRouter.params; const id = params['id'] ?? ''; + const auth = yield* Effect.promise(() => validateAgentRuntimeEventAuth(request, id)); // PAN-5754: or the agent's own token + if (!auth.ok) return auth.response; + if (!id.trim()) { return jsonResponse({ success: false, error: 'missing agent id' }, { status: 400 }); } @@ -135,11 +135,11 @@ export const postAgentWorkCompleteRoute = HttpRouter.add( '/api/agents/:id/work-complete', httpHandler(Effect.gen(function* () { const request = yield* HttpServerRequest.HttpServerRequest; - const auth = yield* Effect.promise(() => validateAgentRuntimeEventAuth(request)); - if (!auth.ok) return auth.response; - const params = yield* HttpRouter.params; const id = params['id'] ?? ''; + const auth = yield* Effect.promise(() => validateAgentRuntimeEventAuth(request, id)); // PAN-5754: or the agent's own token + if (!auth.ok) return auth.response; + if (!id.trim()) return jsonResponse({ success: false, error: 'missing agent id' }, { status: 400 }); const result = yield* emitAgentRuntimeEvent(id, { kind: 'resolution_set', resolution: 'done', resolutionCount: 1 }, new Date().toISOString()); if (!result.ok) return result.response; @@ -152,11 +152,11 @@ export const postAgentStuckRoute = HttpRouter.add( '/api/agents/:id/stuck', httpHandler(Effect.gen(function* () { const request = yield* HttpServerRequest.HttpServerRequest; - const auth = yield* Effect.promise(() => validateAgentRuntimeEventAuth(request)); - if (!auth.ok) return auth.response; - const params = yield* HttpRouter.params; const id = params['id'] ?? ''; + const auth = yield* Effect.promise(() => validateAgentRuntimeEventAuth(request, id)); // PAN-5754: or the agent's own token + if (!auth.ok) return auth.response; + if (!id.trim()) return jsonResponse({ success: false, error: 'missing agent id' }, { status: 400 }); const result = yield* emitAgentRuntimeEvent(id, { kind: 'resolution_set', resolution: 'stuck', resolutionCount: 1 }, new Date().toISOString()); if (!result.ok) return result.response; @@ -188,11 +188,11 @@ export const postAgentPlanChecklistRoute = HttpRouter.add( '/api/agents/:id/plan-checklist', httpHandler(Effect.gen(function* () { const request = yield* HttpServerRequest.HttpServerRequest; - const auth = yield* Effect.promise(() => validateAgentRuntimeEventAuth(request)); - if (!auth.ok) return auth.response; - const params = yield* HttpRouter.params; const id = params['id'] ?? ''; + const auth = yield* Effect.promise(() => validateAgentRuntimeEventAuth(request, id)); // PAN-5754: or the agent's own token + if (!auth.ok) return auth.response; + const { getAgentState } = yield* Effect.promise(() => import('../../../../lib/agents.js')); const state = getAgentState(id); if (!state?.workspace || !state.issueId) { diff --git a/src/dashboard/server/routes/agents/shared.ts b/src/dashboard/server/routes/agents/shared.ts index d3b38c42fa4..fd7ae8e2ab9 100644 --- a/src/dashboard/server/routes/agents/shared.ts +++ b/src/dashboard/server/routes/agents/shared.ts @@ -12,6 +12,8 @@ import { EFFORT_LEVELS, isEffortLevel, type AgentStatus, type EffortLevel } from import { jsonResponse } from '../../http-helpers.js'; import { getHeaderFromMap } from '../origin-validation.js'; +import { resolveRequestCredential } from '../dashboard-auth.js'; +import { agentTokenIdentity, NOT_SELF, tokenSpeaksFor } from '../self-or-internal.js'; import { getOverdeckHome } from '../../../../lib/paths.js'; import { normalizeModelOverride } from '../../../../lib/model-validation.js'; import { buildHostOverrideConfirmation } from '../../../../lib/agents/host-override.js'; @@ -232,19 +234,29 @@ async function readInternalTokenForRequest(): Promise { return fromEnv && fromEnv.length > 0 ? fromEnv : null; } +/** + * The internal token, or (PAN-5754 D-16) an agent token speaking for `subjectAgentId` itself — + * an isolated agent's hooks hold no internal token. `null` subject: internal token only. + */ export async function validateAgentRuntimeEventAuth( request: HttpServerRequest.HttpServerRequest, + subjectAgentId: string | null = null, ) { const expected = await readInternalTokenForRequest(); + const provided = getHeaderFromMap(request.headers as Record, INTERNAL_TOKEN_HEADER); + if (expected && constantTimeTokenEqual(provided, expected)) return { ok: true as const }; + + const token = agentTokenIdentity(resolveRequestCredential(request)); + if (token !== null) { + if (subjectAgentId !== null && tokenSpeaksFor(token, subjectAgentId)) return { ok: true as const }; + return { ok: false as const, response: jsonResponse({ success: false, ...NOT_SELF }, { status: 403 }) }; + } if (!expected) { return { ok: false as const, response: jsonResponse({ success: false, error: 'internal token not configured' }, { status: 503 }), }; } - - const provided = getHeaderFromMap(request.headers as Record, INTERNAL_TOKEN_HEADER); - if (constantTimeTokenEqual(provided, expected)) return { ok: true as const }; return { ok: false as const, response: jsonResponse({ success: false, error: 'forbidden' }, { status: 403 }), diff --git a/src/dashboard/server/routes/hooks.ts b/src/dashboard/server/routes/hooks.ts index 45bbc59ed01..1386d7cae4f 100644 --- a/src/dashboard/server/routes/hooks.ts +++ b/src/dashboard/server/routes/hooks.ts @@ -22,7 +22,8 @@ import { getEventStore } from '../event-store.js'; import { getAgentRuntimeState, getAgentState, listRunningAgents, type AgentState } from '../../../lib/agents.js'; import { sessionFilePath } from '../../../lib/runtimes/storage/claude-code.js'; import { assertMemorySafeSegment } from '../../../lib/memory/paths.js'; -import { hasDashboardInternalToken } from './dashboard-auth.js'; +import { resolveRequestCredential } from './dashboard-auth.js'; +import { agentTokenIdentity, authorizeInternalOrSessionOwner, bodyString, hasInternalOrAgentToken, type SelfAuthResult } from './self-or-internal.js'; import { ReadModelService } from '../read-model.js'; import { clearConversationFailureState, getConversationByClaudeSessionId, getConversationByTmuxSession, markConversationActive, updateConversationTitle, type LegacyConversation } from '../../../lib/overdeck/conversations.js'; import { memoryIdentityForConversation } from '../../../lib/memory/conversation-identity.js'; @@ -421,12 +422,27 @@ async function resolveWithTimeout( } } +/** PAN-5754 D-16: the internal token, or an agent token whose agent or conversation owns the body's session. */ +function authorizeHookSession( + request: HttpServerRequest.HttpServerRequest, + body: Record, + resolveAgentIdBySessionId: (sessionId: string) => Promise, + bodyNamesAgent: boolean, +): Promise { + return authorizeInternalOrSessionOwner( + request, + bodyString(body, 'session_id', 'sessionId'), + resolveAgentIdBySessionId, + bodyNamesAgent ? bodyString(body, 'agentId') : null, + ); +} + const postMemoryInjectRoute = HttpRouter.add( 'POST', '/api/memory/inject', httpHandler(Effect.gen(function* () { const request = yield* HttpServerRequest.HttpServerRequest; - if (!hasDashboardInternalToken(request)) return jsonResponse({ error: 'unauthorized' }, { status: 401 }); + if (!hasInternalOrAgentToken(request)) return jsonResponse({ error: 'unauthorized' }, { status: 401 }); const rawBody = yield* request.text; let body: Record; @@ -438,6 +454,8 @@ const postMemoryInjectRoute = HttpRouter.add( const readModel = yield* ReadModelService; const resolveAgentIdBySessionId = async (sessionId: string) => Effect.runPromise(readModel.getAgentIdBySessionId(sessionId)); + const auth = yield* Effect.promise(() => authorizeHookSession(request, body, resolveAgentIdBySessionId, true)); // PAN-5754 D-16 + if (!auth.ok) return auth.response; const result = yield* Effect.promise(() => handleMemoryInjectFastPathBody(body, { resolveAgentIdBySessionId, docsConfig: loadConfigSync().config.docs, @@ -451,7 +469,7 @@ const postMemorySessionStartRoute = HttpRouter.add( '/api/memory/session/start', httpHandler(Effect.gen(function* () { const request = yield* HttpServerRequest.HttpServerRequest; - if (!hasDashboardInternalToken(request)) return jsonResponse({ error: 'unauthorized' }, { status: 401 }); + if (!hasInternalOrAgentToken(request)) return jsonResponse({ error: 'unauthorized' }, { status: 401 }); const rawBody = yield* request.text; let body: Record; @@ -462,9 +480,10 @@ const postMemorySessionStartRoute = HttpRouter.add( } const readModel = yield* ReadModelService; - const result = yield* Effect.promise(() => handleMemorySessionStartBody(body, { - resolveAgentIdBySessionId: async (sessionId) => Effect.runPromise(readModel.getAgentIdBySessionId(sessionId)), - })); + const resolveAgentIdBySessionId = async (sessionId: string) => Effect.runPromise(readModel.getAgentIdBySessionId(sessionId)); + const auth = yield* Effect.promise(() => authorizeHookSession(request, body, resolveAgentIdBySessionId, true)); // PAN-5754 D-16 + if (!auth.ok) return auth.response; + const result = yield* Effect.promise(() => handleMemorySessionStartBody(body, { resolveAgentIdBySessionId })); if (result.status === 'subagent' || result.status === 'disabled') { return HttpServerResponse.text('', { status: 204 }); } @@ -492,7 +511,7 @@ const postMemoryTurnRoute = HttpRouter.add( '/api/memory/turn', httpHandler(Effect.gen(function* () { const request = yield* HttpServerRequest.HttpServerRequest; - if (!hasDashboardInternalToken(request)) return jsonResponse({ error: 'unauthorized' }, { status: 401 }); + if (!hasInternalOrAgentToken(request)) return jsonResponse({ error: 'unauthorized' }, { status: 401 }); const rawBody = yield* request.text; let body: Record; @@ -503,9 +522,10 @@ const postMemoryTurnRoute = HttpRouter.add( } const readModel = yield* ReadModelService; - const result = yield* Effect.promise(() => handleMemoryTurnBody(body, { - resolveAgentIdBySessionId: async (sessionId) => Effect.runPromise(readModel.getAgentIdBySessionId(sessionId)), - })); + const resolveAgentIdBySessionId = async (sessionId: string) => Effect.runPromise(readModel.getAgentIdBySessionId(sessionId)); + const auth = yield* Effect.promise(() => authorizeHookSession(request, body, resolveAgentIdBySessionId, true)); // PAN-5754 D-16 + if (!auth.ok) return auth.response; + const result = yield* Effect.promise(() => handleMemoryTurnBody(body, { resolveAgentIdBySessionId })); if (result.status === 'subagent' || result.status === 'disabled') return HttpServerResponse.text('', { status: 204 }); if (result.status === 'error') return jsonResponse({ ok: false, error: result.error }, { status: result.statusCode }); @@ -527,6 +547,13 @@ const postPermissionEventRoute = HttpRouter.add( return jsonResponse({ error: 'invalid JSON' }, { status: 400 }); } + // PAN-5754 D-16: an agent token may report only its own session's permission events. + // Requests with no agent token keep today's behaviour (the gate already admitted them). + if (agentTokenIdentity(resolveRequestCredential(request)) !== null) { + const readModel = yield* ReadModelService; + const auth = yield* Effect.promise(() => authorizeHookSession(request, body, async (sessionId) => Effect.runPromise(readModel.getAgentIdBySessionId(sessionId)), false)); + if (!auth.ok) return auth.response; + } return jsonResponse(yield* Effect.promise(() => handlePermissionEventBody(body))); })), ); @@ -651,7 +678,7 @@ const postUserPromptSubmitRoute = HttpRouter.add( '/api/hooks/user-prompt-submit', httpHandler(Effect.gen(function* () { const request = yield* HttpServerRequest.HttpServerRequest; - if (!hasDashboardInternalToken(request)) return jsonResponse({ error: 'unauthorized' }, { status: 401 }); + if (!hasInternalOrAgentToken(request)) return jsonResponse({ error: 'unauthorized' }, { status: 401 }); const rawBody = yield* request.text; let body: Record; @@ -661,6 +688,9 @@ const postUserPromptSubmitRoute = HttpRouter.add( return jsonResponse({ error: 'invalid JSON' }, { status: 400 }); } + const readModel = yield* ReadModelService; + const auth = yield* Effect.promise(() => authorizeHookSession(request, body, async (sessionId) => Effect.runPromise(readModel.getAgentIdBySessionId(sessionId)), false)); // PAN-5754 D-16 + if (!auth.ok) return auth.response; const result = yield* Effect.promise(() => handleUserPromptSubmitBody(body)); return jsonResponse(result); })), @@ -694,7 +724,7 @@ const postTurnCompleteRoute = HttpRouter.add( '/api/hooks/turn-complete', httpHandler(Effect.gen(function* () { const request = yield* HttpServerRequest.HttpServerRequest; - if (!hasDashboardInternalToken(request)) return jsonResponse({ error: 'unauthorized' }, { status: 401 }); + if (!hasInternalOrAgentToken(request)) return jsonResponse({ error: 'unauthorized' }, { status: 401 }); const rawBody = yield* request.text; let body: Record; @@ -704,6 +734,9 @@ const postTurnCompleteRoute = HttpRouter.add( return jsonResponse({ error: 'invalid JSON' }, { status: 400 }); } + const readModel = yield* ReadModelService; + const auth = yield* Effect.promise(() => authorizeHookSession(request, body, async (sessionId) => Effect.runPromise(readModel.getAgentIdBySessionId(sessionId)), false)); // PAN-5754 D-16 + if (!auth.ok) return auth.response; const result = yield* Effect.promise(() => handleTurnCompleteBody(body)); return jsonResponse(result); })), diff --git a/src/dashboard/server/routes/issues.ts b/src/dashboard/server/routes/issues.ts index 88b6bed0a35..b9d108a452e 100644 --- a/src/dashboard/server/routes/issues.ts +++ b/src/dashboard/server/routes/issues.ts @@ -54,6 +54,7 @@ import { generateTasksForIssue } from '../../../lib/overdeck/task-generation.js' import { loadWorkspaceMetadata as loadWorkspaceMetadataStatic } from '../../../lib/remote/workspace-metadata.js'; import { resolveGitHubIssue, resolveTrackerType } from '../../../lib/tracker-utils.js'; import { rejectUnsafeDashboardMutationRequest } from './dashboard-auth.js'; +import { refuseCompletePlanning } from './self-or-internal.js'; import { validateOrigin } from './origin-validation.js'; import { reopenWorkspaceState } from '../../../lib/reopen.js'; import { getGitHubConfig, getRallyConfig } from '../services/tracker-config.js'; @@ -365,6 +366,8 @@ const postIssueCompletePlanningRoute = HttpRouter.add( if (!parseIssueId(id)) { return jsonResponse({ error: "Invalid issue ID" }, { status: 400 }); } + const refused = refuseCompletePlanning(request, id); // PAN-5754 WI-14 + if (refused) return refused; const body = yield* readJsonBody; const eventStore = yield* EventStoreService; const linear = yield* LinearClient; diff --git a/src/dashboard/server/routes/self-or-internal.ts b/src/dashboard/server/routes/self-or-internal.ts new file mode 100644 index 00000000000..fb9ef163f6c --- /dev/null +++ b/src/dashboard/server/routes/self-or-internal.ts @@ -0,0 +1,138 @@ +/** + * PAN-5754 D-16 (FR-8): the routes hooks and in-pane helpers call accept either the internal + * token or an agent token that speaks only for itself. + * + * An isolated agent holds no internal token, so its hooks send its own agent token. Such a + * token passes only when its agent (or conversation) is the route's subject: + * - path-keyed routes (`/api/agents/:id/...`): the subject is `:id` — an agent id, or a + * conversation's name or tmux session; + * - session-keyed hook routes (`session_id` in the body): the server resolves the session's + * owner and compares it with the token. A session with no owner is refused for agent tokens. + * A token speaking for anyone else gets 403 `{ code: 'not-self' }`; every other credential, + * including none, gets 401. The internal token still passes everywhere it did. + */ +import type { HttpServerRequest, HttpServerResponse } from 'effect/unstable/http'; + +import { normalizeAgentId } from '../../../lib/agents/identity.js'; +import { getConversationByClaudeSessionId, getConversationByName } from '../../../lib/overdeck/conversations.js'; +import { jsonResponse } from '../http-helpers.js'; +import { selfCallerFromCredential, type SelfCallerDeps } from '../self-caller.js'; +import { credentialScopes, hasDashboardInternalToken, resolveRequestCredential, type DashboardCredential } from './dashboard-auth.js'; + +export const NOT_SELF = { error: 'an agent token can act only for its own agent', code: 'not-self' } as const; + +export type SelfAuthResult = { ok: true } | { ok: false; response: HttpServerResponse.HttpServerResponse }; + +export interface AgentTokenIdentity { + agentId: string; + agentKind: 'agent' | 'conversation'; +} + +export interface SelfSubjectDeps { + conversationTmuxSession: (name: string) => string | null; + conversationNameForSession: (sessionId: string) => string | null; +} + +const defaultDeps: SelfSubjectDeps = { + conversationTmuxSession: (name) => getConversationByName(name)?.tmuxSession ?? null, + conversationNameForSession: (sessionId) => getConversationByClaudeSessionId(sessionId)?.name ?? null, +}; + +const ok: SelfAuthResult = { ok: true }; +const unauthorized = (): SelfAuthResult => ({ ok: false, response: jsonResponse({ error: 'unauthorized' }, { status: 401 }) }); +const notSelf = (): SelfAuthResult => ({ ok: false, response: jsonResponse(NOT_SELF, { status: 403 }) }); + +/** The agent or conversation an agent token names, or null for any other credential. */ +export function agentTokenIdentity(credential: DashboardCredential | null): AgentTokenIdentity | null { + if (credential?.kind !== 'token' || typeof credential.agentId !== 'string' || credential.agentId === '') return null; + if (credential.agentKind !== 'agent' && credential.agentKind !== 'conversation') return null; + return { agentId: credential.agentId, agentKind: credential.agentKind }; +} + +function normalizedAgentId(id: string): string | null { + try { + return normalizeAgentId(id); + } catch { + return null; + } +} + +/** True when `subject` (an agent id, or a conversation name or tmux session) is the token's own owner. */ +export function tokenSpeaksFor(token: AgentTokenIdentity, subject: string, deps: SelfSubjectDeps = defaultDeps): boolean { + if (!subject) return false; + if (token.agentKind === 'agent') return normalizedAgentId(subject) === token.agentId; + return subject === token.agentId || subject === deps.conversationTmuxSession(token.agentId); +} + +/** Path-keyed routes: the internal token, or an agent token for `subjectAgentId` itself. */ +export function authorizeInternalOrSelfAgent( + request: HttpServerRequest.HttpServerRequest, + subjectAgentId: string | null, + deps: SelfSubjectDeps = defaultDeps, +): SelfAuthResult { + if (hasDashboardInternalToken(request)) return ok; + const token = agentTokenIdentity(resolveRequestCredential(request)); + if (token === null) return unauthorized(); + return subjectAgentId !== null && tokenSpeaksFor(token, subjectAgentId, deps) ? ok : notSelf(); +} + +/** + * Session-keyed hook routes: the internal token, or an agent token whose agent or conversation + * owns `sessionId`. `claimedAgentId` (a body's own agent id field, when it has one) must also be + * the token's own. + */ +export async function authorizeInternalOrSessionOwner( + request: HttpServerRequest.HttpServerRequest, + sessionId: string | null, + resolveAgentIdBySessionId: (sessionId: string) => Promise, + claimedAgentId: string | null = null, + deps: SelfSubjectDeps = defaultDeps, +): Promise { + if (hasDashboardInternalToken(request)) return ok; + const token = agentTokenIdentity(resolveRequestCredential(request)); + if (token === null) return unauthorized(); + if (!sessionId) return notSelf(); + if (claimedAgentId && !tokenSpeaksFor(token, claimedAgentId, deps)) return notSelf(); + const owner = token.agentKind === 'agent' + ? await resolveAgentIdBySessionId(sessionId) + : deps.conversationNameForSession(sessionId); + if (!owner) return notSelf(); + return (token.agentKind === 'agent' ? normalizedAgentId(owner) : owner) === token.agentId ? ok : notSelf(); +} + +/** A body's string field, or null. */ +export function bodyString(body: Record, ...keys: string[]): string | null { + for (const key of keys) { + const value = body[key]; + if (typeof value === 'string' && value !== '') return value; + } + return null; +} + +/** Cheap pre-check before reading a body: the internal token or some agent token. */ +export function hasInternalOrAgentToken(request: HttpServerRequest.HttpServerRequest): boolean { + return hasDashboardInternalToken(request) || agentTokenIdentity(resolveRequestCredential(request)) !== null; +} + +/** + * PAN-5754 WI-14: `POST /api/issues/:id/complete-planning`. Its `operate` scope row admits agent + * tokens through the gate (an isolated planner's stop hook), so the handler keeps everything else + * from widening: an agent token passes only as the `plan` agent of that issue; any other credential + * must hold `admin`; an uncredentialed request is one the gate already trusted as local, as today. + * Returns a refusal response, or null to proceed. + */ +export function refuseCompletePlanning( + request: HttpServerRequest.HttpServerRequest, + issueId: string, + callerDeps?: SelfCallerDeps, +): HttpServerResponse.HttpServerResponse | null { + const credential = resolveRequestCredential(request); + if (credential === null) return null; + if (agentTokenIdentity(credential) !== null) { + const caller = selfCallerFromCredential(credential, callerDeps); + if (caller.ok && caller.caller.role === 'plan' && caller.caller.issueId?.toLowerCase() === issueId.toLowerCase()) return null; + return jsonResponse({ error: 'only the issue\'s own planner may complete its planning', code: 'not-self' }, { status: 403 }); + } + if (credentialScopes(credential).includes('admin')) return null; + return jsonResponse({ error: 'completing planning needs an admin credential', code: 'admin-required' }, { status: 403 }); +} From 417e53378c192aa4fafdae57616b4a75bc7c174e Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:41:36 -0500 Subject: [PATCH 050/129] chore(workspace): plan artifacts for PAN-5754 Overdeck-Agent: agent-pan-5754 --- .pan/continues/PAN-5754.xbrief.json | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/.pan/continues/PAN-5754.xbrief.json b/.pan/continues/PAN-5754.xbrief.json index 6c6beb9108f..2332f414493 100644 --- a/.pan/continues/PAN-5754.xbrief.json +++ b/.pan/continues/PAN-5754.xbrief.json @@ -2,7 +2,7 @@ "version": "1", "issueId": "PAN-5754", "created": "2026-12-03T21:28:28.525Z", - "updated": "2026-12-03T22:34:54.245Z", + "updated": "2026-12-03T22:41:36.099Z", "gitState": {}, "decisions": [], "hazards": [], @@ -278,9 +278,26 @@ "doneAt": "2026-12-03T22:34:52.764Z" }, "self-auth-routes": { - "status": "in_progress", + "status": "completed", "claimedBy": "agent-pan-5754", - "claimedAt": "2026-12-03T22:34:54.245Z" + "claimedAt": "2026-12-03T22:34:54.245Z", + "doneAt": "2026-12-03T22:41:36.098Z" + }, + "self-auth-routes.ac1": { + "status": "completed", + "doneAt": "2026-12-03T22:41:36.098Z" + }, + "self-auth-routes.ac2": { + "status": "completed", + "doneAt": "2026-12-03T22:41:36.098Z" + }, + "self-auth-routes.ac3": { + "status": "completed", + "doneAt": "2026-12-03T22:41:36.098Z" + }, + "self-auth-routes.ac4": { + "status": "completed", + "doneAt": "2026-12-03T22:41:36.098Z" } } } From a04fe6b530cef465993bb0ec658fb0a9fb1ac54b Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:41:37 -0500 Subject: [PATCH 051/129] chore(workspace): plan artifacts for PAN-5754 Overdeck-Agent: agent-pan-5754 --- .pan/continues/PAN-5754.xbrief.json | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/.pan/continues/PAN-5754.xbrief.json b/.pan/continues/PAN-5754.xbrief.json index 2332f414493..8f06784e5e1 100644 --- a/.pan/continues/PAN-5754.xbrief.json +++ b/.pan/continues/PAN-5754.xbrief.json @@ -2,7 +2,7 @@ "version": "1", "issueId": "PAN-5754", "created": "2026-12-03T21:28:28.525Z", - "updated": "2026-12-03T22:41:36.099Z", + "updated": "2026-12-03T22:41:37.692Z", "gitState": {}, "decisions": [], "hazards": [], @@ -298,6 +298,11 @@ "self-auth-routes.ac4": { "status": "completed", "doneAt": "2026-12-03T22:41:36.098Z" + }, + "route-scope-rows": { + "status": "in_progress", + "claimedBy": "agent-pan-5754", + "claimedAt": "2026-12-03T22:41:37.692Z" } } } From c271cdd28f6792344cba12413d633de7d2e1fbaa Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:44:03 -0500 Subject: [PATCH 052/129] feat(dashboard): route-scope rows for the routes isolated agents call PAN-5754 WI-15. tell rows for the heartbeat, work-complete, stuck, plan-checklist and classify-completion runtime routes, the turn-complete, user-prompt-submit and permission-event hooks, the memory inject, session start and turn routes, the internal permission request, conversation control-ack and specialists auto-complete; operate for complete-planning; read:state for GET /api/agents/:id/runtime and POST /api/self/cli; read:conversations for GET /api/agents/:id/conversation. Without a row an agent token needed admin, so an isolated agent's hooks could not reach them. Each handler keeps its own self check (WI-14, WI-27). The no-loss matrix gains POST /api/self/cli and the missing POST /api/agents/:id/plan-checklist; the telemetry client_route list (every scoped path, sorted) gains the new paths. Item: route-scope-rows Item: route-scope-rows.ac1 Item: route-scope-rows.ac2 Item: route-scope-rows.ac3 Co-Authored-By: Claude Opus 5.5 Overdeck-Agent: agent-pan-5754 --- packages/contracts/src/telemetry.ts | 18 +++++++++++++++ .../server/__tests__/route-scopes.test.ts | 13 +++++++++++ src/dashboard/server/route-scopes.ts | 23 +++++++++++++++++++ tests/unit/lib/overdeck/no-loss-matrix.ts | 2 ++ 4 files changed, 56 insertions(+) diff --git a/packages/contracts/src/telemetry.ts b/packages/contracts/src/telemetry.ts index fd51f193ad9..d9a6b72c092 100644 --- a/packages/contracts/src/telemetry.ts +++ b/packages/contracts/src/telemetry.ts @@ -208,11 +208,18 @@ const TELEMETRY_CLIENT_ROUTES = [ "/api/agent-requests", "/api/agents", "/api/agents/:id/answer-question", + "/api/agents/:id/classify-completion", + "/api/agents/:id/conversation", + "/api/agents/:id/heartbeat", "/api/agents/:id/message", "/api/agents/:id/permissions/:requestId/respond", "/api/agents/:id/plan-action", + "/api/agents/:id/plan-checklist", + "/api/agents/:id/runtime", "/api/agents/:id/send-now", + "/api/agents/:id/stuck", "/api/agents/:id/tell", + "/api/agents/:id/work-complete", "/api/backend-restart-recovery", "/api/backend-restart-recovery/dismiss", "/api/backend-restart-recovery/resume-all", @@ -232,6 +239,7 @@ const TELEMETRY_CLIENT_ROUTES = [ "/api/conversations/:name/changes", "/api/conversations/:name/changes/lines", "/api/conversations/:name/compact", + "/api/conversations/:name/control-ack", "/api/conversations/:name/delete-image", "/api/conversations/:name/diffs", "/api/conversations/:name/diffs/:turnId", @@ -290,9 +298,14 @@ const TELEMETRY_CLIENT_ROUTES = [ "/api/flywheel/status", "/api/github/identities", "/api/harness-auto-update", + "/api/hooks/permission-event", + "/api/hooks/turn-complete", + "/api/hooks/user-prompt-submit", + "/api/internal/agents/:id/permissions/request", "/api/issues", "/api/issues/:id", "/api/issues/:id/check-runs", + "/api/issues/:id/complete-planning", "/api/issues/:id/costs", "/api/issues/resource-allocated", "/api/lanes", @@ -314,6 +327,9 @@ const TELEMETRY_CLIENT_ROUTES = [ "/api/machines/work/projects", "/api/machines/work/projects/:jobId", "/api/machines/work/workers", + "/api/memory/inject", + "/api/memory/session/start", + "/api/memory/turn", "/api/needs-you", "/api/orders", "/api/orders/:id", @@ -333,6 +349,7 @@ const TELEMETRY_CLIENT_ROUTES = [ "/api/registered-projects", "/api/resources/actions/execute", "/api/resources/actions/preview", + "/api/self/cli", "/api/self/done", "/api/self/handoff", "/api/self/jobs/:id", @@ -367,6 +384,7 @@ const TELEMETRY_CLIENT_ROUTES = [ "/api/skills/packs", "/api/skills/packs/available", "/api/skills/packs/preview", + "/api/specialists/:name/auto-complete", "/api/telemetry/client-config", "/api/ui/open", "/api/usage-limit-hold", diff --git a/src/dashboard/server/__tests__/route-scopes.test.ts b/src/dashboard/server/__tests__/route-scopes.test.ts index a42f87363b9..d00209df421 100644 --- a/src/dashboard/server/__tests__/route-scopes.test.ts +++ b/src/dashboard/server/__tests__/route-scopes.test.ts @@ -103,6 +103,19 @@ describe('route-scope table (PAN-2351)', () => { } }); + it('maps the routes isolated agents call with their own token (PAN-5754 WI-15)', () => { + for (const path of ['/api/agents/x/heartbeat', '/api/agents/x/work-complete', '/api/agents/x/stuck', '/api/agents/x/plan-checklist', '/api/agents/x/classify-completion']) { + expect(requiredScopeFor('POST', path), path).toBe('tell'); + } + for (const path of ['/api/hooks/turn-complete', '/api/hooks/user-prompt-submit', '/api/hooks/permission-event', '/api/memory/inject', '/api/memory/session/start', '/api/memory/turn', '/api/internal/agents/x/permissions/request', '/api/conversations/conv-a/control-ack', '/api/specialists/review-agent/auto-complete']) { + expect(requiredScopeFor('POST', path), path).toBe('tell'); + } + expect(requiredScopeFor('POST', '/api/issues/PAN-1/complete-planning')).toBe('operate'); + expect(requiredScopeFor('GET', '/api/agents/x/runtime')).toBe('read:state'); + expect(requiredScopeFor('GET', '/api/agents/x/conversation')).toBe('read:conversations'); + expect(requiredScopeFor('POST', '/api/self/cli')).toBe('read:state'); + }); + it('lets a read:state credential read the telemetry client config', () => { expect(requiredScopeFor('GET', '/api/telemetry/client-config')).toBe('read:state'); }); diff --git a/src/dashboard/server/route-scopes.ts b/src/dashboard/server/route-scopes.ts index 66b1949ebce..d6a9a0d11be 100644 --- a/src/dashboard/server/route-scopes.ts +++ b/src/dashboard/server/route-scopes.ts @@ -182,6 +182,29 @@ export const ROUTE_SCOPES: ReadonlyArray = [ { method: 'POST', path: '/api/self/done', scope: 'operate' }, { method: 'POST', path: '/api/self/handoff', scope: 'tell' }, { method: 'POST', path: '/api/self/worker-report', scope: 'tell' }, + // PAN-5754 WI-15 (D-16): routes an isolated agent's hooks and in-pane helpers call with its own + // agent token. Each handler also requires the internal token or a token speaking for itself + // (routes/self-or-internal.ts); classify-completion has no handler auth (docs/DASHBOARD-AUTH.md). + { method: 'POST', path: '/api/agents/:id/heartbeat', scope: 'tell' }, + { method: 'POST', path: '/api/agents/:id/work-complete', scope: 'tell' }, + { method: 'POST', path: '/api/agents/:id/stuck', scope: 'tell' }, + { method: 'POST', path: '/api/agents/:id/plan-checklist', scope: 'tell' }, + { method: 'POST', path: '/api/agents/:id/classify-completion', scope: 'tell' }, + { method: 'POST', path: '/api/hooks/turn-complete', scope: 'tell' }, + { method: 'POST', path: '/api/hooks/user-prompt-submit', scope: 'tell' }, + { method: 'POST', path: '/api/hooks/permission-event', scope: 'tell' }, + { method: 'POST', path: '/api/memory/inject', scope: 'tell' }, + { method: 'POST', path: '/api/memory/session/start', scope: 'tell' }, + { method: 'POST', path: '/api/memory/turn', scope: 'tell' }, + { method: 'POST', path: '/api/internal/agents/:id/permissions/request', scope: 'tell' }, + { method: 'POST', path: '/api/conversations/:name/control-ack', scope: 'tell' }, + { method: 'POST', path: '/api/specialists/:name/auto-complete', scope: 'tell' }, + // The handler admits an agent token only as the issue's own planner, anything else needs admin. + { method: 'POST', path: '/api/issues/:id/complete-planning', scope: 'operate' }, + { method: 'GET', path: '/api/agents/:id/runtime', scope: 'read:state' }, + { method: 'GET', path: '/api/agents/:id/conversation', scope: 'read:conversations' }, + // PAN-5754 D-7: forwarded CLI verbs; the route enforces each verb's roles and issue itself. + { method: 'POST', path: '/api/self/cli', scope: 'read:state' }, // PAN-4927 W-SEC1: secret requests; the handler also requires an agent token (D-10). { method: 'POST', path: '/api/self/secret-requests', scope: 'tell' }, { method: 'GET', path: '/api/self/secret-requests/:id/wait', scope: 'read:state' }, diff --git a/tests/unit/lib/overdeck/no-loss-matrix.ts b/tests/unit/lib/overdeck/no-loss-matrix.ts index 4178f6c274a..f80d5587c2a 100644 --- a/tests/unit/lib/overdeck/no-loss-matrix.ts +++ b/tests/unit/lib/overdeck/no-loss-matrix.ts @@ -117,6 +117,7 @@ export const NO_LOSS_MATRIX: MatrixEntry[] = [ { surface: 'POST /api/agents/:id/heartbeat', kind: 'http', disposition: 'WRITE', door: 'AgentWriter.recordHealth' }, { surface: 'POST /api/agents/:id/work-complete', kind: 'http', disposition: 'RELOCATE', door: 'IssueWriter.advance("in_review")' }, { surface: 'POST /api/agents/:id/stuck', kind: 'http', disposition: 'RELOCATE', door: 'Orchestration' }, + { surface: 'POST /api/agents/:id/plan-checklist', kind: 'http', disposition: 'READ', door: 'xBRIEF checklist for the agent\'s issue (pi extension); internal token or the agent\'s own token (PAN-5754 D-19)' }, { surface: 'POST /api/agents/:id/classify-completion', kind: 'http', disposition: 'RELOCATE', door: 'Orchestration' }, { surface: 'POST /api/internal/agents/:id/permissions/request', kind: 'http', disposition: 'RELOCATE', door: 'AgentPermissionsWriter.request' }, { surface: 'POST /api/agents/:id/permissions/:requestId/respond', kind: 'http', disposition: 'RELOCATE', door: 'AgentPermissionsWriter.resolve' }, @@ -562,6 +563,7 @@ export const NO_LOSS_MATRIX: MatrixEntry[] = [ { surface: 'POST /api/workers/:id/stop', kind: 'http', disposition: 'WRITE', door: 'agents/termination.stopAgent (operator) (PAN-4651)' }, { surface: 'GET /api/self/jobs/:id', kind: 'http', disposition: 'READ', door: 'services/self-jobs.get, owner-only, agent tokens only (PAN-4927 W-SELF1)' }, { surface: 'GET /api/self/jobs/:id/wait', kind: 'http', disposition: 'READ', door: 'services/self-jobs.wait (at most 50 s), owner-only, agent tokens only (PAN-4927 W-SELF1)' }, + { surface: 'POST /api/self/cli', kind: 'http', disposition: 'WRITE', door: 'services/self-jobs.start for a forwarded pan verb (self-cli-verbs row: roles, own issue, allowed flags), agent tokens only (PAN-5754 D-7)' }, { surface: 'POST /api/self/workers', kind: 'http', disposition: 'WRITE', door: 'fleet-work.handleFleetWorker with issueId and parentId from the agent token, owner-stamped (PAN-4938 W-DEL1)' }, { surface: 'GET /api/self/workers/:id/wait', kind: 'http', disposition: 'READ', door: 'worker/wait-any.waitForAnyWorker (at most 50 s, startup grace from the worker launch time), owner-only, agent tokens only (PAN-4938 W-DEL1)' }, { surface: 'GET /api/self/workers', kind: 'http', disposition: 'READ', door: 'worker/list.listWorkers + remote-standin.listRemoteStandIns + liveness.isAlive, owner-only, agent tokens only (PAN-4938 W-DEL1)' }, From 22855f950f8ecea01fb0bc5f377b8fca0d03642f Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:44:29 -0500 Subject: [PATCH 053/129] chore(workspace): plan artifacts for PAN-5754 Overdeck-Agent: agent-pan-5754 --- .pan/continues/PAN-5754.xbrief.json | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/.pan/continues/PAN-5754.xbrief.json b/.pan/continues/PAN-5754.xbrief.json index 8f06784e5e1..5d0fcf9ca4f 100644 --- a/.pan/continues/PAN-5754.xbrief.json +++ b/.pan/continues/PAN-5754.xbrief.json @@ -2,7 +2,7 @@ "version": "1", "issueId": "PAN-5754", "created": "2026-12-03T21:28:28.525Z", - "updated": "2026-12-03T22:41:37.692Z", + "updated": "2026-12-03T22:44:29.515Z", "gitState": {}, "decisions": [], "hazards": [], @@ -300,9 +300,22 @@ "doneAt": "2026-12-03T22:41:36.098Z" }, "route-scope-rows": { - "status": "in_progress", + "status": "completed", "claimedBy": "agent-pan-5754", - "claimedAt": "2026-12-03T22:41:37.692Z" + "claimedAt": "2026-12-03T22:41:37.692Z", + "doneAt": "2026-12-03T22:44:29.515Z" + }, + "route-scope-rows.ac1": { + "status": "completed", + "doneAt": "2026-12-03T22:44:29.515Z" + }, + "route-scope-rows.ac2": { + "status": "completed", + "doneAt": "2026-12-03T22:44:29.515Z" + }, + "route-scope-rows.ac3": { + "status": "completed", + "doneAt": "2026-12-03T22:44:29.515Z" } } } From 4c49e28bf4cd12e351df19cb53c4bb2380540984 Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:44:41 -0500 Subject: [PATCH 054/129] chore(workspace): plan artifacts for PAN-5754 Overdeck-Agent: agent-pan-5754 --- .pan/continues/PAN-5754.xbrief.json | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/.pan/continues/PAN-5754.xbrief.json b/.pan/continues/PAN-5754.xbrief.json index 5d0fcf9ca4f..e87775e59e4 100644 --- a/.pan/continues/PAN-5754.xbrief.json +++ b/.pan/continues/PAN-5754.xbrief.json @@ -2,7 +2,7 @@ "version": "1", "issueId": "PAN-5754", "created": "2026-12-03T21:28:28.525Z", - "updated": "2026-12-03T22:44:29.515Z", + "updated": "2026-12-03T22:44:41.717Z", "gitState": {}, "decisions": [], "hazards": [], @@ -316,6 +316,11 @@ "route-scope-rows.ac3": { "status": "completed", "doneAt": "2026-12-03T22:44:29.515Z" + }, + "pi-routes-self-auth": { + "status": "in_progress", + "claimedBy": "agent-pan-5754", + "claimedAt": "2026-12-03T22:44:41.717Z" } } } From c06ee7f3b05f13f1f8be913db6493429bfd896ca Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:46:33 -0500 Subject: [PATCH 055/129] feat(dashboard): pi extension routes accept a self agent token PAN-5754 WI-27. control-ack: a request with a credential must be the internal token, an admin credential, or the agent's own token for :name (403 not-self otherwise); an uncredentialed request the gate trusted passes as today. specialists auto-complete: an agent token passes only as a review or test agent of the body's issue (a work token gets 403); other credentials keep the internal-token check. classify-completion keeps no handler auth; the docs item records that its tell row admits any tell-scoped token. Item: pi-routes-self-auth Item: pi-routes-self-auth.ac1 Item: pi-routes-self-auth.ac2 Item: pi-routes-self-auth.ac3 Co-Authored-By: Claude Opus 5.5 Overdeck-Agent: agent-pan-5754 --- .../routes/__tests__/self-or-internal.test.ts | 31 ++++++++++++++++++- src/dashboard/server/routes/conversations.ts | 4 +++ .../server/routes/self-or-internal.ts | 31 +++++++++++++++++++ .../routes/specialists/legacy-routes.ts | 12 +++++-- 4 files changed, 74 insertions(+), 4 deletions(-) diff --git a/src/dashboard/server/routes/__tests__/self-or-internal.test.ts b/src/dashboard/server/routes/__tests__/self-or-internal.test.ts index fbdf20a7d46..c38a03089e0 100644 --- a/src/dashboard/server/routes/__tests__/self-or-internal.test.ts +++ b/src/dashboard/server/routes/__tests__/self-or-internal.test.ts @@ -18,7 +18,7 @@ const INTERNAL = 'a1'.repeat(32); const { _resetAccessTokensForTests, _settleAccessTokenWritesForTests, createAccessToken } = await import('../../../../lib/access-tokens.js'); const { _resetInternalTokenCacheForTests } = await import('../../../../lib/internal-token.js'); const { validateAgentRuntimeEventAuth } = await import('../agents/shared.js'); -const { authorizeInternalOrSessionOwner, refuseCompletePlanning } = await import('../self-or-internal.js'); +const { authorizeControlAck, authorizeInternalOrSessionOwner, refuseAgentAutoComplete, refuseCompletePlanning } = await import('../self-or-internal.js'); function request(headers: Record = {}) { return HttpServerRequest.fromWeb(new Request('http://dashboard.test/api/x', { method: 'POST', headers })); @@ -140,3 +140,32 @@ describe('complete-planning credential check (WI-14)', () => { expect(refuseCompletePlanning(request(), 'PAN-1', callerDeps)).toBeNull(); }); }); + +describe('pi extension routes (WI-27)', () => { + const callerDeps = { + getAgentState: (id: string) => ({ 'agent-pan-1-review': { workspace: '/w', issueId: 'PAN-1' }, 'agent-pan-1': { workspace: '/w', issueId: 'PAN-1' } } as Record)[id] ?? null, + getConversationByName: () => null, + }; + + it("control-ack: the agent's own token passes, another agent's token gets 403 not-self", async () => { + const headers = await agentToken('agent-pan-1', 'work'); + expect(await status(authorizeControlAck(request(headers), 'agent-pan-1'))).toBe('ok'); + expect(await status(authorizeControlAck(request(headers), 'agent-pan-2'))).toMatchObject({ status: 403, body: { code: 'not-self' } }); + }); + + it('control-ack: no credential (gate-trusted local) and the internal token pass; a plain tell token does not', async () => { + expect(await status(authorizeControlAck(request(), 'agent-pan-2'))).toBe('ok'); + expect(await status(authorizeControlAck(request({ 'x-overdeck-internal-token': INTERNAL }), 'agent-pan-2'))).toBe('ok'); + const { token } = await createAccessToken({ name: 'phone-ish', kind: 'token', scopes: ['tell'] }); + expect(await status(authorizeControlAck(request({ authorization: `Bearer ${token}` }), 'agent-pan-2'))).toMatchObject({ status: 401 }); + }); + + it('auto-complete: a work token gets 403; a review token for its own issue passes; non-agent credentials fall through', async () => { + const work = refuseAgentAutoComplete(request(await agentToken('agent-pan-1', 'work')), 'PAN-1', callerDeps); + expect((work as { status: number }).status).toBe(403); + const reviewHeaders = await agentToken('agent-pan-1-review', 'review', 'agent', ['tell']); + expect(refuseAgentAutoComplete(request(reviewHeaders), 'PAN-1', callerDeps)).toBeNull(); + expect((refuseAgentAutoComplete(request(reviewHeaders), 'PAN-2', callerDeps) as { status: number }).status).toBe(403); + expect(refuseAgentAutoComplete(request({ 'x-overdeck-internal-token': INTERNAL }), 'PAN-1', callerDeps)).toBe('not-an-agent-token'); + }); +}); diff --git a/src/dashboard/server/routes/conversations.ts b/src/dashboard/server/routes/conversations.ts index 0fa6798ac84..56f844ffaad 100644 --- a/src/dashboard/server/routes/conversations.ts +++ b/src/dashboard/server/routes/conversations.ts @@ -12,6 +12,7 @@ import { extname, join, resolve } from 'node:path'; import { createInterface } from 'node:readline'; import { promisify } from 'node:util'; import { validateOrigin, validateOriginHeaders, getHeaderFromMap, type HeaderMap } from './origin-validation.js'; +import { authorizeControlAck } from './self-or-internal.js'; import * as self from './conversations.js'; import { crossSiteWriteRefusal } from '../linked-conversation-proxy.js'; import { conversationStartOriginForRequest } from '../conversation-start-origin.js'; @@ -745,6 +746,9 @@ const postConversationControlAckRoute = HttpRouter.add( if (!originCheck.ok) { return jsonResponse({ error: originCheck.error }, { status: 403 }); } + const params = yield* HttpRouter.params; + const selfAuth = authorizeControlAck(request, params['name'] ?? ''); // PAN-5754 WI-27 + if (!selfAuth.ok) return selfAuth.response; const body = yield* readJsonBody; return yield* Effect.promise(async () => { try { diff --git a/src/dashboard/server/routes/self-or-internal.ts b/src/dashboard/server/routes/self-or-internal.ts index fb9ef163f6c..ddec54185ed 100644 --- a/src/dashboard/server/routes/self-or-internal.ts +++ b/src/dashboard/server/routes/self-or-internal.ts @@ -136,3 +136,34 @@ export function refuseCompletePlanning( if (credentialScopes(credential).includes('admin')) return null; return jsonResponse({ error: 'completing planning needs an admin credential', code: 'admin-required' }, { status: 403 }); } + +/** + * PAN-5754 WI-27: `POST /api/conversations/:name/control-ack` (the pi extension acks a control + * message). Its `tell` row admits any tell-scoped token, so a request with a credential must be + * the internal token, an admin credential, or an agent token for `:name` itself. An uncredentialed + * request is one the gate already trusted as local, as today. + */ +export function authorizeControlAck(request: HttpServerRequest.HttpServerRequest, name: string): SelfAuthResult { + const credential = resolveRequestCredential(request); + if (credential === null || credentialScopes(credential).includes('admin')) return ok; + return authorizeInternalOrSelfAgent(request, name); +} + +/** + * PAN-5754 WI-27: `POST /api/specialists/:name/auto-complete`. An agent token passes only as a + * `review` or `test` agent whose own issue is the body's issue; other credentials keep today's + * internal-token check (the caller runs it when this returns null). + */ +export function refuseAgentAutoComplete( + request: HttpServerRequest.HttpServerRequest, + bodyIssueId: unknown, + callerDeps?: SelfCallerDeps, +): HttpServerResponse.HttpServerResponse | 'not-an-agent-token' | null { + const credential = resolveRequestCredential(request); + if (agentTokenIdentity(credential) === null) return 'not-an-agent-token'; + const caller = selfCallerFromCredential(credential, callerDeps); + const role = caller.ok ? caller.caller.role : null; + const issue = caller.ok ? caller.caller.issueId : null; + if ((role === 'review' || role === 'test') && typeof bodyIssueId === 'string' && issue !== null && issue.toLowerCase() === bodyIssueId.toLowerCase()) return null; + return jsonResponse({ error: 'only a review or test agent of this issue may auto-complete it', code: 'not-self' }, { status: 403 }); +} diff --git a/src/dashboard/server/routes/specialists/legacy-routes.ts b/src/dashboard/server/routes/specialists/legacy-routes.ts index 9f217041d1e..061b078b790 100644 --- a/src/dashboard/server/routes/specialists/legacy-routes.ts +++ b/src/dashboard/server/routes/specialists/legacy-routes.ts @@ -14,6 +14,7 @@ import { jsonResponse } from '../../http-helpers.js'; import { getDerivedIssueState } from '../../services/derived-issue-state.js'; import { EventStoreService } from '../../services/domain-services.js'; import { validateAgentRuntimeEventAuth } from '../agents.js'; +import { refuseAgentAutoComplete } from '../self-or-internal.js'; import { httpHandler } from '../http-handler.js'; import { killSession } from '../../../../lib/tmux.js'; import { @@ -601,12 +602,17 @@ const postSpecialistAutoCompleteRoute = HttpRouter.add( '/api/specialists/:name/auto-complete', httpHandler(Effect.gen(function* () { const request = yield* HttpServerRequest.HttpServerRequest; - const auth = yield* Effect.promise(() => validateAgentRuntimeEventAuth(request)); - if (!auth.ok) return auth.response; - const params = yield* HttpRouter.params; const name = params['name'] as string; const body = (yield* readJsonBody) as SpecialistAutoCompleteBody; + // PAN-5754 WI-27: a review/test agent's own token for its own issue, else the internal token. + const agentRefusal = refuseAgentAutoComplete(request, body.issueId); + if (agentRefusal === 'not-an-agent-token') { + const auth = yield* Effect.promise(() => validateAgentRuntimeEventAuth(request)); + if (!auth.ok) return auth.response; + } else if (agentRefusal !== null) { + return agentRefusal; + } const eventStore = yield* EventStoreService; const { issueId: requestIssueId, status: requestStatus, agentId } = body; From 098dead6998529d1a298b8e48796c8172aab8878 Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:46:58 -0500 Subject: [PATCH 056/129] chore(workspace): plan artifacts for PAN-5754 Overdeck-Agent: agent-pan-5754 --- .pan/continues/PAN-5754.xbrief.json | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/.pan/continues/PAN-5754.xbrief.json b/.pan/continues/PAN-5754.xbrief.json index e87775e59e4..4d28614f6bb 100644 --- a/.pan/continues/PAN-5754.xbrief.json +++ b/.pan/continues/PAN-5754.xbrief.json @@ -2,7 +2,7 @@ "version": "1", "issueId": "PAN-5754", "created": "2026-12-03T21:28:28.525Z", - "updated": "2026-12-03T22:44:41.717Z", + "updated": "2026-12-03T22:46:58.296Z", "gitState": {}, "decisions": [], "hazards": [], @@ -318,9 +318,22 @@ "doneAt": "2026-12-03T22:44:29.515Z" }, "pi-routes-self-auth": { - "status": "in_progress", + "status": "completed", "claimedBy": "agent-pan-5754", - "claimedAt": "2026-12-03T22:44:41.717Z" + "claimedAt": "2026-12-03T22:44:41.717Z", + "doneAt": "2026-12-03T22:46:58.295Z" + }, + "pi-routes-self-auth.ac1": { + "status": "completed", + "doneAt": "2026-12-03T22:46:58.295Z" + }, + "pi-routes-self-auth.ac2": { + "status": "completed", + "doneAt": "2026-12-03T22:46:58.295Z" + }, + "pi-routes-self-auth.ac3": { + "status": "completed", + "doneAt": "2026-12-03T22:46:58.295Z" } } } From cf061fb21b147e8e7cfa45d6ef4b45503bb83763 Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:46:59 -0500 Subject: [PATCH 057/129] chore(workspace): plan artifacts for PAN-5754 Overdeck-Agent: agent-pan-5754 --- .pan/continues/PAN-5754.xbrief.json | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/.pan/continues/PAN-5754.xbrief.json b/.pan/continues/PAN-5754.xbrief.json index 4d28614f6bb..45a46f9e194 100644 --- a/.pan/continues/PAN-5754.xbrief.json +++ b/.pan/continues/PAN-5754.xbrief.json @@ -2,7 +2,7 @@ "version": "1", "issueId": "PAN-5754", "created": "2026-12-03T21:28:28.525Z", - "updated": "2026-12-03T22:46:58.296Z", + "updated": "2026-12-03T22:46:59.734Z", "gitState": {}, "decisions": [], "hazards": [], @@ -334,6 +334,11 @@ "pi-routes-self-auth.ac3": { "status": "completed", "doneAt": "2026-12-03T22:46:58.295Z" + }, + "pi-extension-token": { + "status": "in_progress", + "claimedBy": "agent-pan-5754", + "claimedAt": "2026-12-03T22:46:59.733Z" } } } From 8a0bc22e4dc45376665d5afbdc026159d32ee7a4 Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:47:53 -0500 Subject: [PATCH 058/129] feat(infra): the pi extension authenticates with the agent token when isolated PAN-5754 WI-26 (D-19). With OVERDECK_AGENT_TOKEN_FILE set, the pi extension's dashboard posts (heartbeat, work-complete, stuck, plan checklist, classify-completion, control-ack, specialists auto-complete) carry Authorization: Bearer with the agent's own token and never read internal-token; otherwise they send the internal-token header as before. Item: pi-extension-token Item: pi-extension-token.ac1 Item: pi-extension-token.ac2 Co-Authored-By: Claude Opus 5.5 Overdeck-Agent: agent-pan-5754 --- .../pi-extension/src/__tests__/index.test.ts | 20 +++++++++++++++++ packages/pi-extension/src/index.ts | 22 ++++++++++++++----- 2 files changed, 36 insertions(+), 6 deletions(-) diff --git a/packages/pi-extension/src/__tests__/index.test.ts b/packages/pi-extension/src/__tests__/index.test.ts index 48e19313518..aeeb53b912c 100644 --- a/packages/pi-extension/src/__tests__/index.test.ts +++ b/packages/pi-extension/src/__tests__/index.test.ts @@ -204,6 +204,26 @@ describe('handleSessionStart', () => { expect(fetchCalls[0]!.headers['x-overdeck-internal-token']).toBe('test-token') }) + it('PAN-5754: sends the Bearer agent token and no internal-token header when OVERDECK_AGENT_TOKEN_FILE is set', async () => { + mkdirSync(join(h.home, '.overdeck'), { recursive: true }) + writeFileSync(join(h.home, '.overdeck', 'internal-token'), 'test-token\n') + const tokenFile = join(h.home, 'mcp-token') + writeFileSync(tokenFile, `odk_${'9'.repeat(64)}\n`) + const previous = process.env['OVERDECK_AGENT_TOKEN_FILE'] + process.env['OVERDECK_AGENT_TOKEN_FILE'] = tokenFile + try { + await handleSessionStart( + { agentId: 'agent-pan-636', home: h.home, pid: 4242, now }, + { reason: 'new', sessionId: 'sess-abc' }, + ) + } finally { + if (previous === undefined) delete process.env['OVERDECK_AGENT_TOKEN_FILE'] + else process.env['OVERDECK_AGENT_TOKEN_FILE'] = previous + } + expect(fetchCalls[0]!.headers['authorization']).toBe(`Bearer odk_${'9'.repeat(64)}`) + expect(fetchCalls[0]!.headers['x-overdeck-internal-token']).toBeUndefined() + }) + it('buffers to pending-events.jsonl when dashboard returns 503', async () => { fetchResponse = { status: 503 } await handleSessionStart( diff --git a/packages/pi-extension/src/index.ts b/packages/pi-extension/src/index.ts index b6570517558..1532c1e9639 100644 --- a/packages/pi-extension/src/index.ts +++ b/packages/pi-extension/src/index.ts @@ -232,6 +232,20 @@ async function readInternalToken(env: HookEnv): Promise { } } +/** + * PAN-5754 D-19: an isolated agent (OVERDECK_AGENT_TOKEN_FILE set by its launcher) sends its own + * agent token and never reads internal-token; otherwise the internal-token header as before. + */ +async function dashboardAuthHeaders(env: HookEnv): Promise> { + const tokenFile = process.env['OVERDECK_AGENT_TOKEN_FILE'] + if (tokenFile) { + const token = (await readFile(tokenFile, 'utf8').catch(() => '')).trim() + return token ? { authorization: `Bearer ${token}` } : {} + } + const token = await readInternalToken(env) + return token ? { [INTERNAL_TOKEN_HEADER]: token } : {} +} + async function postEvent(env: HookEnv, body: Record): Promise { await postDashboard(env, HEARTBEAT_PATH(env.agentId), body) } @@ -254,9 +268,7 @@ async function postWithTimeout(env: HookEnv, url: string, body: Record controller.abort(), POST_TIMEOUT_MS) try { - const token = await readInternalToken(env) - const headers: Record = { 'Content-Type': 'application/json' } - if (token) headers[INTERNAL_TOKEN_HEADER] = token + const headers: Record = { 'Content-Type': 'application/json', ...(await dashboardAuthHeaders(env)) } const res = await fetch(url, { method: 'POST', headers, @@ -277,9 +289,7 @@ async function postJsonWithTimeout(env: HookEnv, url: string, body: Record controller.abort(), POST_TIMEOUT_MS) try { - const token = await readInternalToken(env) - const headers: Record = { 'Content-Type': 'application/json' } - if (token) headers[INTERNAL_TOKEN_HEADER] = token + const headers: Record = { 'Content-Type': 'application/json', ...(await dashboardAuthHeaders(env)) } const res = await fetch(url, { method: 'POST', headers, From 070c92549cb216d73e4dbc89e83def4b76a44014 Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:48:17 -0500 Subject: [PATCH 059/129] chore(workspace): plan artifacts for PAN-5754 Overdeck-Agent: agent-pan-5754 --- .pan/continues/PAN-5754.xbrief.json | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/.pan/continues/PAN-5754.xbrief.json b/.pan/continues/PAN-5754.xbrief.json index 45a46f9e194..456ab98945e 100644 --- a/.pan/continues/PAN-5754.xbrief.json +++ b/.pan/continues/PAN-5754.xbrief.json @@ -2,7 +2,7 @@ "version": "1", "issueId": "PAN-5754", "created": "2026-12-03T21:28:28.525Z", - "updated": "2026-12-03T22:46:59.734Z", + "updated": "2026-12-03T22:48:17.742Z", "gitState": {}, "decisions": [], "hazards": [], @@ -336,9 +336,18 @@ "doneAt": "2026-12-03T22:46:58.295Z" }, "pi-extension-token": { - "status": "in_progress", + "status": "completed", "claimedBy": "agent-pan-5754", - "claimedAt": "2026-12-03T22:46:59.733Z" + "claimedAt": "2026-12-03T22:46:59.733Z", + "doneAt": "2026-12-03T22:48:17.742Z" + }, + "pi-extension-token.ac1": { + "status": "completed", + "doneAt": "2026-12-03T22:48:17.742Z" + }, + "pi-extension-token.ac2": { + "status": "completed", + "doneAt": "2026-12-03T22:48:17.742Z" } } } From 80cd72b84aaedffca28a962d7801b8e28e14a8a2 Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:48:19 -0500 Subject: [PATCH 060/129] chore(workspace): plan artifacts for PAN-5754 Overdeck-Agent: agent-pan-5754 --- .pan/continues/PAN-5754.xbrief.json | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/.pan/continues/PAN-5754.xbrief.json b/.pan/continues/PAN-5754.xbrief.json index 456ab98945e..f3e532977d0 100644 --- a/.pan/continues/PAN-5754.xbrief.json +++ b/.pan/continues/PAN-5754.xbrief.json @@ -2,7 +2,7 @@ "version": "1", "issueId": "PAN-5754", "created": "2026-12-03T21:28:28.525Z", - "updated": "2026-12-03T22:48:17.742Z", + "updated": "2026-12-03T22:48:19.150Z", "gitState": {}, "decisions": [], "hazards": [], @@ -348,6 +348,11 @@ "pi-extension-token.ac2": { "status": "completed", "doneAt": "2026-12-03T22:48:17.742Z" + }, + "admission-pidns": { + "status": "in_progress", + "claimedBy": "agent-pan-5754", + "claimedAt": "2026-12-03T22:48:19.149Z" } } } From 6ef634be94dfe822423bb6e59f9835d6d271ad40 Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:55:05 -0500 Subject: [PATCH 061/129] fix(cloister): make gate admission liveness PID-namespace aware PAN-5754 WI-22 (D-17). A gate run inside Claude Code's sandbox has its own PID namespace, so kill(pid, 0) makes every outside slot holder look dead and its own pids mean nothing outside. Tickets, owners and breakers now carry the writer's pidNs (readlink /proc/self/ns/pid, once per process), and every liveness check goes through recordLiveness: a record from another namespace counts as alive until staleMs after its timestamp (a waiter ticket from its createdAt) instead of being reaped at once. Records without pidNs (older checkouts) are judged by their pid as before. The helper lives in quality-gate-admission-pidns.ts to keep the admission module under the 1000-line ceiling. Item: admission-pidns Item: admission-pidns.ac1 Item: admission-pidns.ac2 Item: admission-pidns.ac3 Co-Authored-By: Claude Opus 5.5 Overdeck-Agent: agent-pan-5754 --- .../cloister/quality-gate-admission-pidns.ts | 45 +++++++++++++++++++ src/lib/cloister/quality-gate-admission.ts | 30 ++++++++----- .../cloister/quality-gate-admission.test.ts | 32 +++++++++++++ 3 files changed, 96 insertions(+), 11 deletions(-) create mode 100644 src/lib/cloister/quality-gate-admission-pidns.ts diff --git a/src/lib/cloister/quality-gate-admission-pidns.ts b/src/lib/cloister/quality-gate-admission-pidns.ts new file mode 100644 index 00000000000..d11cab4701a --- /dev/null +++ b/src/lib/cloister/quality-gate-admission-pidns.ts @@ -0,0 +1,45 @@ +/** + * PAN-5754 D-17 (FR-15): PID-namespace-aware liveness for gate admission records. + * + * A gate run inside Claude Code's sandbox has its own PID namespace: every pid it reads from + * another namespace looks dead (`kill(pid, 0)` fails), and its own pids mean nothing outside. + * Each ticket, owner and breaker record carries the writer's PID namespace (`pidNs`); a record + * from another namespace counts as alive until `staleMs` after its timestamp, instead of being + * reaped at once. A record without `pidNs` (an older checkout) is judged by its pid, as before. + */ +import { readlinkSync } from 'node:fs'; + +/** `(pid, pidNs?, since?) => alive`: `pidNs` and `since` come from the record being judged. */ +export type RecordLiveness = (pid: number, pidNs?: string, since?: number) => boolean; + +let cachedPidNs: string | null | undefined; + +/** This process's PID namespace (`pid:[4026531836]`), read once; undefined off Linux. */ +export function currentPidNamespace(): string | undefined { + if (cachedPidNs === undefined) { + try { + cachedPidNs = readlinkSync('/proc/self/ns/pid'); + } catch { + cachedPidNs = null; + } + } + return cachedPidNs ?? undefined; +} + +/** + * Wrap a pid probe so a record from another PID namespace is alive while `now() - since` is + * within `staleMs` (or, with no `since`, always: the caller applies its own age bound). + */ +export function recordLiveness( + isProcessAlive: (pid: number) => boolean, + ownPidNs: string | undefined, + now: () => number, + staleMs: number, +): RecordLiveness { + return (pid, pidNs, since) => { + if (pidNs !== undefined && ownPidNs !== undefined && pidNs !== ownPidNs) { + return since === undefined || now() - since <= staleMs; + } + return isProcessAlive(pid); + }; +} diff --git a/src/lib/cloister/quality-gate-admission.ts b/src/lib/cloister/quality-gate-admission.ts index a0c7f46ea3b..d45e752515c 100644 --- a/src/lib/cloister/quality-gate-admission.ts +++ b/src/lib/cloister/quality-gate-admission.ts @@ -6,6 +6,7 @@ import { getOverdeckHome } from '../paths.js' import { readCpuPsi, type CpuPsi } from '../system-health/cpu-psi.js' import { readProcessTreeRssBytes } from '../system-health/process-tree-rss.js' import { fileAgeMs, isErrnoException, publishExclusive, readJson, replaceFile, unlinkIfExists } from './quality-gate-admission-files.js' +import { currentPidNamespace, recordLiveness, type RecordLiveness } from './quality-gate-admission-pidns.js' import { clearQueueCpuBlock, DEFAULT_QUALITY_GATE_PSI_START_AVG10, @@ -159,6 +160,8 @@ export interface QualityGateAdmissionHandle { interface AdmissionTicket extends QualityGateAdmissionRequest { ticketId: string pid: number + /** PAN-5754 D-17: the writer's PID namespace; absent on tickets from older checkouts. */ + pidNs?: string createdAt: number footprintBytes?: number /** PAN-5285: absent on tickets from older checkouts. */ @@ -184,6 +187,7 @@ interface AdmissionOwner extends AdmissionTicket { interface AdmissionBreaker { pid: number acquiredAt: number + pidNs?: string } export interface QualityGateAdmissionDeps { @@ -192,6 +196,8 @@ export interface QualityGateAdmissionDeps { sleep?: (ms: number) => Promise pid?: number isProcessAlive?: (pid: number) => boolean + /** PAN-5754 D-17: this process's PID namespace; defaults to /proc/self/ns/pid. */ + pidNs?: string /** Called with the configured PSI start threshold. */ samplePressure?: (psiStartAvg10: number) => Promise pollMs?: number @@ -316,9 +322,9 @@ function ownerIsStale( owner: AdmissionOwner, now: number, staleMs: number, - isProcessAlive: (pid: number) => boolean, + isProcessAlive: RecordLiveness, ): boolean { - return now - owner.acquiredAt > staleMs || !isProcessAlive(owner.pid) + return now - owner.acquiredAt > staleMs || !isProcessAlive(owner.pid, owner.pidNs) } async function acquireBreaker( @@ -326,12 +332,12 @@ async function acquireBreaker( slot: number, now: () => number, staleMs: number, - isProcessAlive: (pid: number) => boolean, + isProcessAlive: RecordLiveness, ): Promise { const path = slotBreakerPath(root, slot) for (let attempt = 0; attempt < 2; attempt++) { try { - await publishExclusive(path, { pid: process.pid, acquiredAt: now() }) + await publishExclusive(path, { pid: process.pid, acquiredAt: now(), pidNs: currentPidNamespace() }) return true } catch (error) { if (!isErrnoException(error) || error.code !== 'EEXIST') throw error @@ -339,7 +345,7 @@ async function acquireBreaker( if ( existing && now() - existing.acquiredAt <= staleMs - && isProcessAlive(existing.pid) + && isProcessAlive(existing.pid, existing.pidNs) ) return false await unlinkIfExists(path) } @@ -353,7 +359,7 @@ async function clearStaleOwner( observed: AdmissionOwner | null, now: () => number, staleMs: number, - isProcessAlive: (pid: number) => boolean, + isProcessAlive: RecordLiveness, ): Promise { if (!await acquireBreaker(root, slot, now, staleMs, isProcessAlive)) return const path = slotOwnerPath(root, slot) @@ -373,7 +379,7 @@ async function clearStaleOwner( async function listLiveTickets( root: string, - isProcessAlive: (pid: number) => boolean, + isProcessAlive: RecordLiveness, tornGraceMs: number, ): Promise { const entries = await readdir(root) @@ -393,7 +399,7 @@ async function listLiveTickets( if (ageMs != null && ageMs > tornGraceMs) await unlinkIfExists(path) continue } - if (!isProcessAlive(ticket.pid)) { + if (!isProcessAlive(ticket.pid, ticket.pidNs, ticket.createdAt)) { await unlinkIfExists(path) continue } @@ -533,9 +539,9 @@ export async function readQualityGateQueue(deps: { } = {}): Promise { const slots = deps.slots ?? await resolveQualityGateSlots() const empty: QualityGateQueueSnapshot = { slots, owners: [], waiters: [] } - const isProcessAlive = deps.isProcessAlive ?? processIsAlive const now = deps.now ?? Date.now const staleMs = deps.staleMs ?? QUALITY_GATE_ADMISSION_STALE_MS + const isProcessAlive = recordLiveness(deps.isProcessAlive ?? processIsAlive, currentPidNamespace(), now, staleMs) const root = admissionRoot(deps.rootDir) try { const owners: QualityGateQueueEntry[] = [] @@ -549,7 +555,7 @@ export async function readQualityGateQueue(deps: { for (const entry of await readdir(root)) { if (!entry.startsWith('waiter-') || !entry.endsWith('.json')) continue const ticket = await readJson(join(root, entry)) - if (!isTicketShape(ticket) || !isProcessAlive(ticket.pid)) continue + if (!isTicketShape(ticket) || !isProcessAlive(ticket.pid, ticket.pidNs, ticket.createdAt)) continue waiters.push(ticket) } waiters.sort((left, right) => left.createdAt - right.createdAt @@ -597,11 +603,12 @@ export async function acquireQualityGateAdmission( const now = deps.now ?? Date.now const sleep = deps.sleep ?? delay const pid = deps.pid ?? process.pid - const isProcessAlive = deps.isProcessAlive ?? processIsAlive const samplePressure = deps.samplePressure ?? ((psi: number) => sampleQualityGatePressure(sleep, readCpuPsi, psi)) const pollMs = deps.pollMs ?? QUALITY_GATE_ADMISSION_POLL_MS const settleMs = deps.settleMs ?? QUALITY_GATE_ADMISSION_SETTLE_MS const staleMs = deps.staleMs ?? QUALITY_GATE_ADMISSION_STALE_MS + const pidNs = 'pidNs' in deps ? deps.pidNs : currentPidNamespace() // PAN-5754 D-17 + const isProcessAlive = recordLiveness(deps.isProcessAlive ?? processIsAlive, pidNs, now, staleMs) const tornGraceMs = deps.tornGraceMs ?? QUALITY_GATE_ADMISSION_TORN_GRACE_MS const headBypassMs = deps.headBypassMs ?? QUALITY_GATE_HEAD_BYPASS_MS const slots = Number.isInteger(deps.slots) && deps.slots! >= 1 ? deps.slots! : await resolveQualityGateSlots() @@ -618,6 +625,7 @@ export async function acquireQualityGateAdmission( ...request, ticketId, pid, + ...(pidNs !== undefined ? { pidNs } : {}), createdAt, admissionVersion: ADMISSION_TICKET_VERSION, ...(footprintKey ? { footprintBytes: await readFootprintEstimate(footprintKey) } : {}), diff --git a/tests/unit/lib/cloister/quality-gate-admission.test.ts b/tests/unit/lib/cloister/quality-gate-admission.test.ts index 6c638fc27a9..37b1581f45a 100644 --- a/tests/unit/lib/cloister/quality-gate-admission.test.ts +++ b/tests/unit/lib/cloister/quality-gate-admission.test.ts @@ -295,6 +295,38 @@ describe('quality gate admission', () => { await handle.release() }) + it('PAN-5754 D-17: keeps a slot whose owner is from another PID namespace and younger than staleMs', async () => { + const rootDir = home() + const foreignOwner = JSON.stringify({ ...JSON.parse(ownerJson(999_999, 9_500)), pidNs: 'pid:[4026531836]' }) + writeFileSync(join(rootDir, 'owner.json'), foreignOwner) + + const handle = await driveUntilResolved(acquireQualityGateAdmission( + request, + { ...deps(rootDir), slots: 2, now: () => 10_000, pidNs: 'pid:[4026532999]' }, + )) + + expect(handle.slot).toBe(1) + expect(readFileSync(join(rootDir, 'owner.json'), 'utf8')).toBe(foreignOwner) + await handle.release() + }) + + it('PAN-5754 D-17: clears a foreign-namespace owner older than staleMs, and a dead same-namespace owner as before', async () => { + const rootDir = home() + writeFileSync(join(rootDir, 'owner.json'), JSON.stringify({ ...JSON.parse(ownerJson(999_999, 0)), pidNs: 'pid:[4026531836]' })) + writeFileSync(join(rootDir, 'slot-1.json'), JSON.stringify({ ...JSON.parse(ownerJson(999_998, 9_900)), pidNs: 'pid:[4026532999]' })) + + const handle = await driveUntilResolved(acquireQualityGateAdmission( + request, + { ...deps(rootDir), slots: 2, now: () => 10_000, pidNs: 'pid:[4026532999]' }, + )) + + expect([0, 1]).toContain(handle.slot) + const remaining = readdirSync(rootDir).filter((entry) => entry === 'owner.json' || entry === 'slot-1.json') + expect(remaining).toEqual([handle.slot === 0 ? 'owner.json' : 'slot-1.json']) + expect(JSON.parse(readFileSync(join(rootDir, handle.slot === 0 ? 'owner.json' : 'slot-1.json'), 'utf8')).pidNs).toBe('pid:[4026532999]') + await handle.release() + }) + it('clears a torn slot file older than the torn grace', async () => { const rootDir = home() const tornPath = join(rootDir, 'slot-1.json') From 0450c2e0001f13fa5fe44133a4d7d23d8d8fb7b0 Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:55:35 -0500 Subject: [PATCH 062/129] chore(workspace): plan artifacts for PAN-5754 Overdeck-Agent: agent-pan-5754 --- .pan/continues/PAN-5754.xbrief.json | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/.pan/continues/PAN-5754.xbrief.json b/.pan/continues/PAN-5754.xbrief.json index f3e532977d0..5c59aaeba67 100644 --- a/.pan/continues/PAN-5754.xbrief.json +++ b/.pan/continues/PAN-5754.xbrief.json @@ -2,7 +2,7 @@ "version": "1", "issueId": "PAN-5754", "created": "2026-12-03T21:28:28.525Z", - "updated": "2026-12-03T22:48:19.150Z", + "updated": "2026-12-03T22:55:35.478Z", "gitState": {}, "decisions": [], "hazards": [], @@ -350,9 +350,22 @@ "doneAt": "2026-12-03T22:48:17.742Z" }, "admission-pidns": { - "status": "in_progress", + "status": "completed", "claimedBy": "agent-pan-5754", - "claimedAt": "2026-12-03T22:48:19.149Z" + "claimedAt": "2026-12-03T22:48:19.149Z", + "doneAt": "2026-12-03T22:55:35.478Z" + }, + "admission-pidns.ac1": { + "status": "completed", + "doneAt": "2026-12-03T22:55:35.478Z" + }, + "admission-pidns.ac2": { + "status": "completed", + "doneAt": "2026-12-03T22:55:35.478Z" + }, + "admission-pidns.ac3": { + "status": "completed", + "doneAt": "2026-12-03T22:55:35.478Z" } } } From b67c30b8ae41e763dcc0df18c161ece94b77e880 Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:55:43 -0500 Subject: [PATCH 063/129] chore(workspace): plan artifacts for PAN-5754 Overdeck-Agent: agent-pan-5754 --- .pan/continues/PAN-5754.xbrief.json | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/.pan/continues/PAN-5754.xbrief.json b/.pan/continues/PAN-5754.xbrief.json index 5c59aaeba67..bf4e3550de8 100644 --- a/.pan/continues/PAN-5754.xbrief.json +++ b/.pan/continues/PAN-5754.xbrief.json @@ -2,7 +2,7 @@ "version": "1", "issueId": "PAN-5754", "created": "2026-12-03T21:28:28.525Z", - "updated": "2026-12-03T22:55:35.478Z", + "updated": "2026-12-03T22:55:43.287Z", "gitState": {}, "decisions": [], "hazards": [], @@ -366,6 +366,11 @@ "admission-pidns.ac3": { "status": "completed", "doneAt": "2026-12-03T22:55:35.478Z" + }, + "peer-rule": { + "status": "in_progress", + "claimedBy": "agent-pan-5754", + "claimedAt": "2026-12-03T22:55:43.287Z" } } } From 91de1140d2ee8b067c41e55ce76bf1b6f2a263d9 Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 18:08:07 -0500 Subject: [PATCH 064/129] feat(dashboard): connections from isolated process trees are not trusted local callers PAN-5754 WI-20 (D-10, FR-9, NFR-1). The sandbox proxy forwards to host loopback and CIDR denies do not work, so the dashboard itself decides who owns an uncredentialed loopback connection: it reads the live isolation roots (/isolation/roots, written by each isolated launcher; a root whose pid is gone or whose /proc start time differs is ignored and deleted), finds the connection's client-side inode in /proc/net/tcp{,6}, walks each root's tree through /proc//task//children and looks for an fd linked to socket:[inode]. A connection owned by an isolated tree is marked on its socket (resolved once per connection, async fs only) and localPeerKind then answers null: no trusted local caller, no session mint. With no live roots nothing in /proc is read; without /proc/net/tcp the rule is off. ensurePeerIdentityFresh resolves the mark for literal-loopback requests with no credential; the wake host awaits isTrustedLocalNodeRequestAsync. The PTY supervisor's POST /api/agents/:id/lifecycle with x-overdeck-pty-token is exempt (ISOLATED_PEER_SELF_AUTH_ROUTES): its handler checks its own token. Deviation: rootRegistrationLauncherLine already lives in agent-isolation/launcher-lines.ts (WI-6); roots.ts holds the reader and the /proc tree walk. The gate test registers the test process itself as a root, so the real /proc decides. Item: peer-rule Item: peer-rule.ac1 Item: peer-rule.ac2 Item: peer-rule.ac3 Item: peer-rule.ac4 Item: peer-rule.ac5 Co-Authored-By: Claude Opus 5.5 Overdeck-Agent: agent-pan-5754 --- .../server/__tests__/isolated-peer.test.ts | 185 ++++++++++++++++++ src/dashboard/server/isolated-peer.ts | 116 +++++++++++ src/dashboard/server/public-ingress.ts | 2 +- src/dashboard/server/routes/dashboard-auth.ts | 42 +++- src/dashboard/server/routes/workspace-wake.ts | 4 +- src/lib/agent-isolation/roots.ts | 126 ++++++++++++ 6 files changed, 468 insertions(+), 7 deletions(-) create mode 100644 src/dashboard/server/__tests__/isolated-peer.test.ts create mode 100644 src/dashboard/server/isolated-peer.ts create mode 100644 src/lib/agent-isolation/roots.ts diff --git a/src/dashboard/server/__tests__/isolated-peer.test.ts b/src/dashboard/server/__tests__/isolated-peer.test.ts new file mode 100644 index 00000000000..7d0326d606a --- /dev/null +++ b/src/dashboard/server/__tests__/isolated-peer.test.ts @@ -0,0 +1,185 @@ +/** + * PAN-5754 WI-20 (D-10): connections owned by an isolated process tree are not trusted + * local callers. Unit cases use a fake /proc; the gate cases register this test process + * as an isolation root and connect over real loopback TCP, so the real /proc decides. + */ +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { request as httpRequest, createServer } from 'node:http'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +import { Context, Effect, Exit, Layer, Scope } from 'effect'; +import { HttpRouter, HttpServer } from 'effect/unstable/http'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; + +import type { ProcFs } from '../../../lib/agent-isolation/roots.js'; + +const originalHome = process.env.OVERDECK_HOME; +const home = mkdtempSync(join(tmpdir(), 'pan-5754-peer-')); +process.env.OVERDECK_HOME = home; + +const { procStartTime, readLiveRoots } = await import('../../../lib/agent-isolation/roots.js'); +const { findConnectionInode, parseProcAddress, resolveIsolatedPeer } = await import('../isolated-peer.js'); + +/** A fake /proc and roots dir held in a map; records every read. */ +function fakeFs(files: Record, links: Record = {}): ProcFs & { reads: string[]; unlinked: string[] } { + const reads: string[] = []; + const unlinked: string[] = []; + const dirs = new Map>(); + for (const path of [...Object.keys(files), ...Object.keys(links)]) { + const parts = path.split('/'); + for (let index = 1; index < parts.length; index++) { + const dir = parts.slice(0, index).join('/') || '/'; + if (!dirs.has(dir)) dirs.set(dir, new Set()); + dirs.get(dir)!.add(parts[index]!); + } + } + const missing = (path: string) => Object.assign(new Error(`ENOENT ${path}`), { code: 'ENOENT' }); + return { + reads, + unlinked, + procRoot: '/proc', + rootsDir: () => '/home/isolation/roots', + readFile: async (path) => { + reads.push(path); + if (path in files) return files[path]!; + throw missing(path); + }, + readdir: async (path) => { + reads.push(path); + const entries = dirs.get(path); + if (!entries) throw missing(path); + return [...entries]; + }, + readlink: async (path) => { + reads.push(path); + if (path in links) return links[path]!; + throw missing(path); + }, + unlink: async (path) => { + unlinked.push(path); + }, + }; +} + +const stat = (pid: number, start: string) => `${pid} (bash (x) y) S 1 ${pid} ${pid} 0 -1 4194560 1 0 0 0 0 0 0 0 20 0 1 0 ${start} 1000 100`; +// Client 127.0.0.1:40000 -> server 127.0.0.1:3011, inode 777; the server end has inode 778. +const TCP = [ + ' sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode', + ' 0: 0100007F:9C40 0100007F:0BC3 01 00000000:00000000 00:00000000 00000000 1000 0 777 1 0', + ' 1: 0100007F:0BC3 0100007F:9C40 01 00000000:00000000 00:00000000 00000000 1000 0 778 1 0', +].join('\n'); +const CONN = { remoteAddress: '127.0.0.1', remotePort: 40000, localAddress: '127.0.0.1', localPort: 3011 }; + +function procTree(ownerPid: number): ProcFs & { reads: string[]; unlinked: string[] } { + return fakeFs({ + '/home/isolation/roots/agent-pan-1.json': JSON.stringify({ pid: 100, startTime: 5000 }), + '/proc/100/stat': stat(100, '5000'), + '/proc/net/tcp': TCP, + '/proc/100/task/100/children': '200', + '/proc/200/task/200/children': '300', + '/proc/300/task/300/children': '', + '/proc/900/task/900/children': '', + }, { + [`/proc/${ownerPid}/fd/3`]: 'socket:[777]', + '/proc/100/fd/0': '/dev/null', + }); +} + +describe('peer rule (fake /proc)', () => { + it('parses IPv4 and IPv4-mapped tcp6 addresses', () => { + expect(parseProcAddress('0100007F:0BC3')).toEqual({ ip: '127.0.0.1', port: 3011 }); + expect(parseProcAddress('0000000000000000FFFF00000100007F:9C40')).toEqual({ ip: '127.0.0.1', port: 40000 }); + expect(parseProcAddress('00000000000000000000000001000000:0BC3')).toEqual({ ip: '::1', port: 3011 }); + }); + + it('finds the client-side inode of a connection', async () => { + expect(await findConnectionInode(CONN, procTree(300))).toBe('777'); + expect(await findConnectionInode({ ...CONN, remoteAddress: '::ffff:127.0.0.1' }, procTree(300))).toBe('777'); + }); + + it('marks a connection owned by a descendant of a live root', async () => { + expect(await resolveIsolatedPeer(CONN, procTree(300))).toBe(true); + }); + + it('does not mark a connection owned by an unrelated pid', async () => { + expect(await resolveIsolatedPeer(CONN, procTree(900))).toBe(false); + }); + + it('ignores and deletes a root whose start time differs, and reads no /proc with no live roots', async () => { + const fs = fakeFs({ + '/home/isolation/roots/agent-pan-1.json': JSON.stringify({ pid: 100, startTime: 4999 }), + '/proc/100/stat': stat(100, '5000'), + '/proc/net/tcp': TCP, + }); + expect(await readLiveRoots(fs)).toEqual([]); + expect(fs.unlinked).toEqual(['/home/isolation/roots/agent-pan-1.json']); + const empty = fakeFs({ '/proc/net/tcp': TCP }); + expect(await resolveIsolatedPeer(CONN, empty)).toBe(false); + expect(empty.reads.filter((path) => path.startsWith('/proc'))).toEqual([]); + }); + + it('reads the start time after the last parenthesis of the command name', () => { + expect(procStartTime(stat(1, '4242'))).toBe('4242'); + }); +}); + +describe('peer rule at the gate (real /proc, this process as a registered root)', () => { + let scope: Scope.Closeable; + let port: number; + + function post(path: string, headers: Record = {}): Promise { + return new Promise((resolve, reject) => { + const req = httpRequest({ host: '127.0.0.1', port, path, method: 'POST', agent: false, headers: { 'content-type': 'application/json', origin: 'http://localhost:3011', ...headers } }, (res) => { + res.resume(); + res.on('end', () => resolve(res.statusCode ?? 0)); + }); + req.on('error', reject); + req.end('{}'); + }); + } + + beforeAll(async () => { + writeFileSync(join(home, 'internal-token'), 'c3'.repeat(32), { mode: 0o600 }); + const { _resetInternalTokenCacheForTests } = await import('../../../lib/internal-token.js'); + const { _resetDashboardSessionTokenForTests } = await import('../routes/dashboard-auth.js'); + _resetInternalTokenCacheForTests(); + _resetDashboardSessionTokenForTests(); + const { remoteRequestGateLayer } = await import('../remote-request-gate.js'); + const { dashboardSessionRouteLayer } = await import('../routes/dashboard-session.js'); + const { jsonResponse } = await import('../http-helpers.js'); + const routes = Layer.mergeAll( + remoteRequestGateLayer, + dashboardSessionRouteLayer, + HttpRouter.add('POST', '/api/agents/:id/lifecycle', Effect.succeed(jsonResponse({ reached: true }))), + ); + const serverLayer = (await import('@effect/platform-node/NodeHttpServer')).layer(() => createServer(), { host: '127.0.0.1', port: 0 }); + scope = await Effect.runPromise(Scope.make()); + const context = await Effect.runPromise(Layer.build(HttpRouter.serve(routes, { disableLogger: true }).pipe(Layer.provideMerge(serverLayer))).pipe(Effect.provideService(Scope.Scope, scope))); + const address = Context.get(context, HttpServer.HttpServer).address; + if (address._tag !== 'TcpAddress') throw new Error('expected a TCP address'); + port = address.port; + }); + + afterAll(async () => { + await Effect.runPromise(Scope.close(scope, Exit.void)); + if (originalHome === undefined) delete process.env.OVERDECK_HOME; + else process.env.OVERDECK_HOME = originalHome; + rmSync(home, { recursive: true, force: true }); + }); + + it('mints as before when no root is registered', async () => { + expect(await post('/api/dashboard/session')).toBe(200); + }); + + it('refuses the mint with 401 for a connection owned by a registered isolated tree, and keeps the PTY lifecycle exception', async () => { + const rootsDir = join(home, 'isolation', 'roots'); + mkdirSync(rootsDir, { recursive: true }); + const startTime = procStartTime(readFileSync('/proc/self/stat', 'utf8')); + writeFileSync(join(rootsDir, 'agent-test.json'), JSON.stringify({ pid: process.pid, startTime: Number(startTime) })); + + expect(await post('/api/dashboard/session')).toBe(401); + expect(await post('/api/agents/agent-test/lifecycle', { 'x-overdeck-pty-token': 'pty-secret' })).toBe(200); + expect(await post('/api/agents/agent-test/lifecycle')).toBe(401); + }); +}); diff --git a/src/dashboard/server/isolated-peer.ts b/src/dashboard/server/isolated-peer.ts new file mode 100644 index 00000000000..3ebc92d6dcd --- /dev/null +++ b/src/dashboard/server/isolated-peer.ts @@ -0,0 +1,116 @@ +/** + * PAN-5754 D-10 (FR-9, NFR-1): isolated process trees are not trusted local callers. + * + * Claude Code's sandbox proxy forwards to host loopback and CIDR denies do not work, so the + * network layer cannot keep an isolated agent off the dashboard port. Instead, for a loopback + * request that carries no credential, the dashboard asks which process owns the client end of + * the TCP connection: it finds the connection's inode in /proc/net/tcp{,6}, walks the process + * trees of the live registered isolation roots (`readLiveRoots`), and looks for an fd linked + * to `socket:[]`. A connection owned by an isolated tree is marked on its socket, and + * `localPeerKind` then answers null: no trusted local caller, no session mint. + * + * The answer is computed once per connection and cached on the socket. With no live roots the + * rule does nothing beyond listing the roots directory; without /proc/net/tcp (macOS) it is off. + * Async file I/O only. + */ +import { join } from 'node:path'; + +import { descendantPids, pidsHoldSocket, readLiveRoots, realProcFs, type ProcFs } from '../../lib/agent-isolation/roots.js'; + +export interface PeerSocket { + remoteAddress?: string; + remotePort?: number; + localAddress?: string; + localPort?: number; +} + +/** + * Routes whose handler checks a non-dashboard secret (D-10): the peer rule is skipped for them, + * so the PTY supervisor inside an isolated tree keeps recording lifecycle with its own token. + */ +export const ISOLATED_PEER_SELF_AUTH_ROUTES: ReadonlyArray<{ method: string; path: RegExp; header: string }> = [ + { method: 'POST', path: /^\/api\/agents\/[^/]+\/lifecycle$/, header: 'x-overdeck-pty-token' }, +]; + +export function isIsolatedPeerSelfAuthRoute(method: string, pathname: string, headers: Record): boolean { + return ISOLATED_PEER_SELF_AUTH_ROUTES.some((route) => route.method === method && route.path.test(pathname) && headers[route.header] !== undefined); +} + +/** A /proc/net/tcp address (`0100007F:1F90`, or 32 hex digits for tcp6) as `ip`/`port`. */ +export function parseProcAddress(hex: string): { ip: string; port: number } | null { + const [ipHex, portHex] = hex.split(':'); + if (!ipHex || !portHex) return null; + const port = Number.parseInt(portHex, 16); + const words = ipHex.match(/.{8}/g); + if (!words || (words.length !== 1 && words.length !== 4)) return null; + // Each 32-bit word is in host (little-endian) byte order. + const bytes = words.flatMap((word) => (word.match(/../g) ?? []).reverse().map((byte) => Number.parseInt(byte, 16))); + if (bytes.length === 4) return { ip: bytes.join('.'), port }; + const mapped = bytes.slice(0, 10).every((byte) => byte === 0) && bytes[10] === 0xff && bytes[11] === 0xff; + if (mapped) return { ip: bytes.slice(12).join('.'), port }; + if (bytes.slice(0, 15).every((byte) => byte === 0) && bytes[15] === 1) return { ip: '::1', port }; + const groups: string[] = []; + for (let index = 0; index < 16; index += 2) groups.push(((bytes[index]! << 8) | bytes[index + 1]!).toString(16)); + return { ip: groups.join(':'), port }; +} + +function canonicalIp(address: string): string { + const lower = address.toLowerCase(); + return lower.startsWith('::ffff:') && lower.includes('.') ? lower.slice('::ffff:'.length) : lower; +} + +/** The inode of the TCP connection whose local end is the client and remote end the server, or null. */ +export async function findConnectionInode(socket: PeerSocket, fs: ProcFs = realProcFs): Promise { + const { remoteAddress, remotePort, localAddress, localPort } = socket; + if (!remoteAddress || !remotePort || !localAddress || !localPort) return null; + const client = canonicalIp(remoteAddress); + const server = canonicalIp(localAddress); + for (const table of ['tcp', 'tcp6']) { + let text: string; + try { + text = await fs.readFile(join(fs.procRoot, 'net', table)); + } catch { + continue; + } + for (const line of text.split('\n').slice(1)) { + const columns = line.trim().split(/\s+/); + if (columns.length < 10) continue; + const local = parseProcAddress(columns[1]!); + const remote = parseProcAddress(columns[2]!); + if (local?.ip === client && local.port === remotePort && remote?.ip === server && remote.port === localPort) { + return columns[9]!; + } + } + } + return null; +} + +/** True when the connection's client end belongs to a live isolated process tree. */ +export async function resolveIsolatedPeer(socket: PeerSocket, fs: ProcFs = realProcFs): Promise { + const roots = await readLiveRoots(fs); + if (roots.length === 0) return false; + const inode = await findConnectionInode(socket, fs); + if (inode === null || inode === '0') return false; + return pidsHoldSocket(await descendantPids(roots.map((root) => root.pid), fs), inode, fs); +} + +const pending = new WeakMap>(); +const settled = new WeakMap(); + +/** Resolve (once per socket) and record whether `socket` belongs to an isolated tree. */ +export function markIsolatedPeer(socket: object & PeerSocket, fs: ProcFs = realProcFs): Promise { + let verdict = pending.get(socket); + if (verdict === undefined) { + verdict = resolveIsolatedPeer(socket, fs).catch(() => false).then((isolated) => { + settled.set(socket, isolated); + return isolated; + }); + pending.set(socket, verdict); + } + return verdict; +} + +/** True when `socket` was resolved as owned by an isolated process tree. */ +export function isSocketMarkedIsolated(socket: unknown): boolean { + return typeof socket === 'object' && socket !== null && settled.get(socket) === true; +} diff --git a/src/dashboard/server/public-ingress.ts b/src/dashboard/server/public-ingress.ts index a2f3f41c83d..1373b54d403 100644 --- a/src/dashboard/server/public-ingress.ts +++ b/src/dashboard/server/public-ingress.ts @@ -52,7 +52,7 @@ export function hasFunnelHeader(headers: HeaderMap): boolean { } /** The Node socket behind an Effect request, read as `channelOfRequest` does; undefined for `fromWeb` requests. */ -function socketOfRequest(request: HttpServerRequest.HttpServerRequest): unknown { +export function socketOfRequest(request: HttpServerRequest.HttpServerRequest): unknown { const source = (request as { source?: unknown }).source; if (typeof source !== 'object' || source === null || !('socket' in source)) return undefined; return (source as Pick).socket; diff --git a/src/dashboard/server/routes/dashboard-auth.ts b/src/dashboard/server/routes/dashboard-auth.ts index c1af9ebbcfc..1cb892ba1af 100644 --- a/src/dashboard/server/routes/dashboard-auth.ts +++ b/src/dashboard/server/routes/dashboard-auth.ts @@ -12,7 +12,8 @@ import { readRemoteAccessConfig } from '../../../lib/remote-access/config.js'; import { type ChannelMarker, channelOfRequest } from '../channel-peer.js'; import { jsonResponse } from '../http-helpers.js'; import { dashboardRunsInContainer, ensureManagedTraefikIdentity, managedTraefikIdentity, type ManagedTraefikIdentity } from '../managed-traefik-identity.js'; -import { publicIngressOf, publicIngressOfIncoming } from '../public-ingress.js'; +import { publicIngressOf, publicIngressOfIncoming, socketOfRequest } from '../public-ingress.js'; +import { isIsolatedPeerSelfAuthRoute, isSocketMarkedIsolated, markIsolatedPeer, type PeerSocket } from '../isolated-peer.js'; import { gatePathname, requiredScopeFor } from '../route-scopes.js'; import { getHeaderFromMap, getTrustedOrigins, normalizeOrigin, type HeaderMap } from './origin-validation.js'; @@ -414,7 +415,33 @@ function requestPeerAddress(request: HttpServerRequest.HttpServerRequest): strin * path that runs ahead of the remote request gate middleware (which awaits it). */ export function ensurePeerIdentityFresh(request: HttpServerRequest.HttpServerRequest): Promise { - return ensureManagedTraefikIdentity(requestPeerAddress(request)); + return Promise.all([ensureManagedTraefikIdentity(requestPeerAddress(request)), resolveIsolatedLoopbackPeer(request)]).then(() => undefined); +} + +function requestPathname(request: { url?: string }): string { + try { + return new URL(request.url ?? '/', 'http://local').pathname; + } catch { + return ''; + } +} + +/** PAN-5754 D-10: a peer-rule exception route (its handler checks its own non-dashboard secret). */ +function isPeerRuleExempt(request: HttpServerRequest.HttpServerRequest): boolean { + return isIsolatedPeerSelfAuthRoute(request.method, requestPathname(request), request.headers as HeaderMap); +} + +/** + * PAN-5754 D-10: for a literal-loopback peer with no credential, resolve (once per connection) + * whether an isolated agent's process tree owns the connection; localPeerKind reads the mark. + */ +async function resolveIsolatedLoopbackPeer(request: HttpServerRequest.HttpServerRequest): Promise { + const socket = socketOfRequest(request); + if (typeof socket !== 'object' || socket === null) return; + const addr = stripMappedPrefix(requestPeerAddress(request)); + if (addr !== '127.0.0.1' && addr !== '::1') return; + if (isPeerRuleExempt(request) || resolveRequestCredential(request) !== null) return; + await markIsolatedPeer(socket as object & PeerSocket); } /** @@ -451,7 +478,8 @@ function localPeerKind(request: HttpServerRequest.HttpServerRequest): 'loopback' if (!raw) return null; // Node reports dual-stack IPv4 peers as IPv4-mapped IPv6 (::ffff:a.b.c.d). const addr = stripMappedPrefix(raw); - if (addr === '127.0.0.1' || addr === '::1') return 'loopback'; + // PAN-5754 D-10: a connection owned by an isolated agent's process tree is not local. + if (addr === '127.0.0.1' || addr === '::1') return isSocketMarkedIsolated(socketOfRequest(request)) && !isPeerRuleExempt(request) ? null : 'loopback'; if (dashboardRunsInContainer()) return peerIsLocalContainerNetwork(addr, networkInterfaces()) ? 'container' : null; return peerIsManagedTraefikForLocalClient(addr, request.headers as HeaderMap, managedTraefikIdentity()) ? 'traefik' : null; } @@ -487,7 +515,13 @@ export function isTrustedLocalCaller(request: HttpServerRequest.HttpServerReques export function isTrustedLocalNodeRequest(request: { headers: IncomingHttpHeaders; socket: object & { remoteAddress?: string } }): boolean { // PAN-5492: the substitute request below has no socket, so the relay tag is read here. if (publicIngressOfIncoming(request) !== null) return false; - return isTrustedLocalCaller({ headers: request.headers, remoteAddress: request.socket.remoteAddress ?? '' } as unknown as HttpServerRequest.HttpServerRequest); + return isTrustedLocalCaller({ headers: request.headers, remoteAddress: request.socket.remoteAddress ?? '', source: { socket: request.socket } } as unknown as HttpServerRequest.HttpServerRequest); +} + +/** PAN-5754: {@link isTrustedLocalNodeRequest} after resolving the peer rule for the raw request's connection. */ +export async function isTrustedLocalNodeRequestAsync(request: { headers: IncomingHttpHeaders; socket: object & { remoteAddress?: string }; method?: string; url?: string }): Promise { + await resolveIsolatedLoopbackPeer({ headers: request.headers, remoteAddress: request.socket.remoteAddress ?? '', source: { socket: request.socket }, method: request.method ?? 'GET', url: request.url ?? '/' } as unknown as HttpServerRequest.HttpServerRequest); + return isTrustedLocalNodeRequest(request); } /** diff --git a/src/dashboard/server/routes/workspace-wake.ts b/src/dashboard/server/routes/workspace-wake.ts index 6797c27c460..562a11a4e01 100644 --- a/src/dashboard/server/routes/workspace-wake.ts +++ b/src/dashboard/server/routes/workspace-wake.ts @@ -45,7 +45,7 @@ import { } from '../../../lib/workspace/workspace-wake-host.js'; import { jsonResponse } from '../http-helpers.js'; import { ensureManagedTraefikIdentity } from '../managed-traefik-identity.js'; -import { isTrustedLocalNodeRequest, rejectUnsafeDashboardMutationRequest } from './dashboard-auth.js'; +import { isTrustedLocalNodeRequestAsync, rejectUnsafeDashboardMutationRequest } from './dashboard-auth.js'; import { httpHandler } from './http-handler.js'; export type WakeState = 'idle' | 'starting' | 'started' | 'failed' | 'no-stack'; @@ -92,7 +92,7 @@ function defaultDeps(): WorkspaceWakeDeps { isTrusted: async (request) => { // PAN-5697: this runs before the gate middleware, so refresh the Traefik identity here. await ensureManagedTraefikIdentity(request.socket.remoteAddress); - return isTrustedLocalNodeRequest(request); + return isTrustedLocalNodeRequestAsync(request); // PAN-5754: the peer rule applies to the wake host too }, now: () => Date.now(), }; diff --git a/src/lib/agent-isolation/roots.ts b/src/lib/agent-isolation/roots.ts new file mode 100644 index 00000000000..9827c2d58c8 --- /dev/null +++ b/src/lib/agent-isolation/roots.ts @@ -0,0 +1,126 @@ +/** + * PAN-5754 D-10: the isolated-launcher root registry. + * + * Each isolated launcher writes `/isolation/roots/.json` holding its pid and kernel + * start time (field 22 of /proc//stat) before it starts the harness; the launcher line is + * `rootRegistrationLauncherLine` in `launcher-lines.ts`. `roots/` lies outside every isolated + * agent's writable paths. An entry whose pid is gone, or whose start time differs (the pid was + * reused), is stale: `readLiveRoots` ignores and deletes it. Async file I/O only (NFR-1). + */ +import { readdir, readFile, readlink, unlink } from 'node:fs/promises'; +import { join } from 'node:path'; + +import { isolationRootsDir } from './paths.js'; + +/** The file system calls the peer rule makes; injected so tests use a fake /proc. */ +export interface ProcFs { + readFile: (path: string) => Promise; + readdir: (path: string) => Promise; + readlink: (path: string) => Promise; + unlink: (path: string) => Promise; + /** `/isolation/roots`. */ + rootsDir: () => string; + /** `/proc`. */ + procRoot: string; +} + +export const realProcFs: ProcFs = { + readFile: (path) => readFile(path, 'utf8'), + readdir: (path) => readdir(path), + readlink: (path) => readlink(path), + unlink: (path) => unlink(path), + rootsDir: isolationRootsDir, + procRoot: '/proc', +}; + +export interface IsolationRoot { + agentId: string; + pid: number; + startTime: string; +} + +/** Field 22 (starttime) of a /proc//stat line: the 20th field after the last `)`. */ +export function procStartTime(stat: string): string | null { + const close = stat.lastIndexOf(')'); + if (close < 0) return null; + return stat.slice(close + 1).trim().split(/\s+/)[19] ?? null; +} + +/** The registered roots whose process still runs with the recorded start time; stale files are deleted. */ +export async function readLiveRoots(fs: ProcFs = realProcFs): Promise { + let entries: string[]; + try { + entries = await fs.readdir(fs.rootsDir()); + } catch { + return []; + } + const roots: IsolationRoot[] = []; + for (const entry of entries) { + if (!entry.endsWith('.json')) continue; + const file = join(fs.rootsDir(), entry); + let record: { pid?: unknown; startTime?: unknown } | null = null; + try { + record = JSON.parse(await fs.readFile(file)) as { pid?: unknown; startTime?: unknown }; + } catch { + record = null; + } + const pid = typeof record?.pid === 'number' && Number.isInteger(record.pid) && record.pid > 0 ? record.pid : null; + const startTime = record?.startTime === undefined || record.startTime === null ? null : String(record.startTime); + let live = false; + if (pid !== null && startTime !== null) { + try { + live = procStartTime(await fs.readFile(join(fs.procRoot, String(pid), 'stat'))) === startTime; + } catch { + live = false; + } + } + if (!live) { + await fs.unlink(file).catch(() => undefined); + continue; + } + roots.push({ agentId: entry.slice(0, -'.json'.length), pid: pid!, startTime: startTime! }); + } + return roots; +} + +/** Every pid in the trees rooted at `rootPids` (the roots included), through /proc//task//children. */ +export async function descendantPids(rootPids: readonly number[], fs: ProcFs = realProcFs): Promise> { + const seen = new Set(); + const queue = [...rootPids]; + while (queue.length > 0) { + const pid = queue.shift()!; + if (seen.has(pid)) continue; + seen.add(pid); + let tids: string[]; + try { + tids = await fs.readdir(join(fs.procRoot, String(pid), 'task')); + } catch { + continue; + } + for (const tid of tids) { + const children = await fs.readFile(join(fs.procRoot, String(pid), 'task', tid, 'children')).catch(() => ''); + for (const child of children.trim().split(/\s+/)) { + const childPid = Number(child); + if (Number.isInteger(childPid) && childPid > 0 && !seen.has(childPid)) queue.push(childPid); + } + } + } + return seen; +} + +/** True when some pid in `pids` holds a file descriptor linked to `socket:[inode]`. */ +export async function pidsHoldSocket(pids: Iterable, inode: string, fs: ProcFs = realProcFs): Promise { + const target = `socket:[${inode}]`; + for (const pid of pids) { + let fds: string[]; + try { + fds = await fs.readdir(join(fs.procRoot, String(pid), 'fd')); + } catch { + continue; + } + for (const fd of fds) { + if ((await fs.readlink(join(fs.procRoot, String(pid), 'fd', fd)).catch(() => '')) === target) return true; + } + } + return false; +} From 7d36afb4952bb56d23a73ece0444f1bf373bbe3a Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 18:08:40 -0500 Subject: [PATCH 065/129] chore(workspace): plan artifacts for PAN-5754 Overdeck-Agent: agent-pan-5754 --- .pan/continues/PAN-5754.xbrief.json | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/.pan/continues/PAN-5754.xbrief.json b/.pan/continues/PAN-5754.xbrief.json index bf4e3550de8..8efbc2c2580 100644 --- a/.pan/continues/PAN-5754.xbrief.json +++ b/.pan/continues/PAN-5754.xbrief.json @@ -2,7 +2,7 @@ "version": "1", "issueId": "PAN-5754", "created": "2026-12-03T21:28:28.525Z", - "updated": "2026-12-03T22:55:43.287Z", + "updated": "2026-12-03T23:08:40.297Z", "gitState": {}, "decisions": [], "hazards": [], @@ -368,9 +368,30 @@ "doneAt": "2026-12-03T22:55:35.478Z" }, "peer-rule": { - "status": "in_progress", + "status": "completed", "claimedBy": "agent-pan-5754", - "claimedAt": "2026-12-03T22:55:43.287Z" + "claimedAt": "2026-12-03T22:55:43.287Z", + "doneAt": "2026-12-03T23:08:40.296Z" + }, + "peer-rule.ac1": { + "status": "completed", + "doneAt": "2026-12-03T23:08:40.296Z" + }, + "peer-rule.ac2": { + "status": "completed", + "doneAt": "2026-12-03T23:08:40.296Z" + }, + "peer-rule.ac3": { + "status": "completed", + "doneAt": "2026-12-03T23:08:40.296Z" + }, + "peer-rule.ac4": { + "status": "completed", + "doneAt": "2026-12-03T23:08:40.296Z" + }, + "peer-rule.ac5": { + "status": "completed", + "doneAt": "2026-12-03T23:08:40.296Z" } } } From e03b4e77b50622e864f87a28c3015bbd4e183720 Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 18:08:42 -0500 Subject: [PATCH 066/129] chore(workspace): plan artifacts for PAN-5754 Overdeck-Agent: agent-pan-5754 --- .pan/continues/PAN-5754.xbrief.json | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/.pan/continues/PAN-5754.xbrief.json b/.pan/continues/PAN-5754.xbrief.json index 8efbc2c2580..019288b2436 100644 --- a/.pan/continues/PAN-5754.xbrief.json +++ b/.pan/continues/PAN-5754.xbrief.json @@ -2,7 +2,7 @@ "version": "1", "issueId": "PAN-5754", "created": "2026-12-03T21:28:28.525Z", - "updated": "2026-12-03T23:08:40.297Z", + "updated": "2026-12-03T23:08:42.092Z", "gitState": {}, "decisions": [], "hazards": [], @@ -392,6 +392,11 @@ "peer-rule.ac5": { "status": "completed", "doneAt": "2026-12-03T23:08:40.296Z" + }, + "traefik-trust": { + "status": "in_progress", + "claimedBy": "agent-pan-5754", + "claimedAt": "2026-12-03T23:08:42.091Z" } } } From 491c912cff4a5599d657c1ccf3253ed1ac1e4d47 Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 18:13:05 -0500 Subject: [PATCH 067/129] feat(dashboard): no uncredentialed Traefik trust while agent isolation is on PAN-5754 WI-21 (D-11). A sandboxed process reaches the managed Traefik through the sandbox proxy at a bridge gateway, and Traefik then forwards it with a client address peerIsManagedTraefikForLocalClient trusts. While agents.isolation.enabled is true, localPeerKind's traefik branch answers null, so an uncredentialed Traefik-forwarded request is not a trusted local caller; the session mint answers 401 { code: 'isolation-sign-in' } naming http://localhost: and the #overdeck_token= link. Browsers holding the overdeck_session cookie are unaffected (they authenticate by credential). agentIsolationEnabled() re-reads config.yaml only when its mtime changes (per-request use) and treats a malformed block as enabled. The PAN-4299 forwarded-auth cases pin isolation off; new cases cover it on. Item: traefik-trust Item: traefik-trust.ac1 Item: traefik-trust.ac2 Item: traefik-trust.ac3 Co-Authored-By: Claude Opus 5.5 Overdeck-Agent: agent-pan-5754 --- .../dashboard-auth-forwarded.test.ts | 36 ++++++++++++++++++- src/dashboard/server/routes/dashboard-auth.ts | 22 ++++++++++-- src/lib/agent-isolation/config.ts | 35 ++++++++++++++++++ 3 files changed, 90 insertions(+), 3 deletions(-) diff --git a/src/dashboard/server/routes/__tests__/dashboard-auth-forwarded.test.ts b/src/dashboard/server/routes/__tests__/dashboard-auth-forwarded.test.ts index 9e02cab2b46..2cd589f6890 100644 --- a/src/dashboard/server/routes/__tests__/dashboard-auth-forwarded.test.ts +++ b/src/dashboard/server/routes/__tests__/dashboard-auth-forwarded.test.ts @@ -16,7 +16,8 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { _resetInternalTokenCacheForTests } from '../../../../lib/internal-token.js'; import { invalidateRemoteAccessConfig } from '../../../../lib/remote-access/config.js'; import { _setManagedTraefikIdentityForTests, type ManagedTraefikIdentity } from '../../managed-traefik-identity.js'; -import { _resetDashboardSessionTokenForTests, rejectUnauthorizedDashboardSessionMintRequest } from '../dashboard-auth.js'; +import { _resetDashboardSessionTokenForTests, dashboardSessionCookieHeader, rejectUnauthorizedDashboardSessionMintRequest } from '../dashboard-auth.js'; +import { _setAgentIsolationEnabledForTests } from '../../../../lib/agent-isolation/config.js'; import { remoteRequestGateLayer } from '../../remote-request-gate.js'; /** overdeck-traefik's address on the bridge it reaches the host from. */ @@ -55,10 +56,13 @@ beforeEach(async () => { _resetDashboardSessionTokenForTests(); invalidateRemoteAccessConfig(); _setManagedTraefikIdentityForTests(TRAEFIK); + // These cases cover Traefik trust as it stands with agent isolation off; PAN-5754 below covers it on. + _setAgentIsolationEnabledForTests(false); }); afterEach(async () => { _setManagedTraefikIdentityForTests(undefined); + _setAgentIsolationEnabledForTests(null); invalidateRemoteAccessConfig(); delete process.env.OVERDECK_INTERNAL_TOKEN; _resetInternalTokenCacheForTests(); @@ -177,3 +181,33 @@ describe('require_token_mint never locks out a local browser — PAN-5344', () = expect(await gateStatus('/api/issues', { peer: BRIDGE_PEER, headers: { 'x-forwarded-for': '192.168.1.50' } })).toBe(401); }); }); + +describe('agent isolation withholds uncredentialed Traefik trust — PAN-5754 D-11', () => { + const local = { 'x-forwarded-for': '172.18.0.1' }; + + it('401s an uncredentialed Traefik-forwarded mint with code isolation-sign-in while isolation is on', async () => { + _setAgentIsolationEnabledForTests(true); + const rejected = mint(BRIDGE_PEER, local) as unknown as { status: number; body: { body?: Uint8Array } } | null; + expect(rejected?.status).toBe(401); + const body = JSON.parse(new TextDecoder().decode(rejected!.body.body)) as { code?: string; error?: string }; + expect(body.code).toBe('isolation-sign-in'); + expect(body.error).toContain('#overdeck_token='); + expect(await gateStatus('/api/agents', { peer: BRIDGE_PEER, headers: local })).toBe(401); + }); + + it('mints as before with isolation off', () => { + _setAgentIsolationEnabledForTests(false); + expect(mint(BRIDGE_PEER, local)).toBeNull(); + }); + + it('still authorizes a browser that holds the overdeck_session cookie through Traefik', async () => { + _setAgentIsolationEnabledForTests(true); + const cookie = dashboardSessionCookieHeader().split(';')[0]!; + expect(await gateStatus('/api/agents', { peer: BRIDGE_PEER, headers: { ...local, cookie } })).toBe(200); + }); + + it('leaves a literal loopback browser unaffected', async () => { + _setAgentIsolationEnabledForTests(true); + expect(mint('127.0.0.1')).toBeNull(); + }); +}); diff --git a/src/dashboard/server/routes/dashboard-auth.ts b/src/dashboard/server/routes/dashboard-auth.ts index 1cb892ba1af..4b5d0607531 100644 --- a/src/dashboard/server/routes/dashboard-auth.ts +++ b/src/dashboard/server/routes/dashboard-auth.ts @@ -14,6 +14,7 @@ import { jsonResponse } from '../http-helpers.js'; import { dashboardRunsInContainer, ensureManagedTraefikIdentity, managedTraefikIdentity, type ManagedTraefikIdentity } from '../managed-traefik-identity.js'; import { publicIngressOf, publicIngressOfIncoming, socketOfRequest } from '../public-ingress.js'; import { isIsolatedPeerSelfAuthRoute, isSocketMarkedIsolated, markIsolatedPeer, type PeerSocket } from '../isolated-peer.js'; +import { agentIsolationEnabled } from '../../../lib/agent-isolation/config.js'; import { gatePathname, requiredScopeFor } from '../route-scopes.js'; import { getHeaderFromMap, getTrustedOrigins, normalizeOrigin, type HeaderMap } from './origin-validation.js'; @@ -481,9 +482,26 @@ function localPeerKind(request: HttpServerRequest.HttpServerRequest): 'loopback' // PAN-5754 D-10: a connection owned by an isolated agent's process tree is not local. if (addr === '127.0.0.1' || addr === '::1') return isSocketMarkedIsolated(socketOfRequest(request)) && !isPeerRuleExempt(request) ? null : 'loopback'; if (dashboardRunsInContainer()) return peerIsLocalContainerNetwork(addr, networkInterfaces()) ? 'container' : null; - return peerIsManagedTraefikForLocalClient(addr, request.headers as HeaderMap, managedTraefikIdentity()) ? 'traefik' : null; + if (!peerIsManagedTraefikForLocalClient(addr, request.headers as HeaderMap, managedTraefikIdentity())) return null; + // PAN-5754 D-11: an isolated agent reaches Traefik through the sandbox proxy at a bridge + // gateway, so while isolation is on an uncredentialed Traefik-forwarded request is not local. + return agentIsolationEnabled() ? null : 'traefik'; } +/** PAN-5754 D-11: a Traefik-forwarded local client that isolation no longer trusts without a credential. */ +function traefikTrustWithheld(request: HttpServerRequest.HttpServerRequest): boolean { + if (dashboardRunsInContainer() || publicIngressOf(request) !== null) return false; + const addr = stripMappedPrefix(requestPeerAddress(request)); + return addr !== '127.0.0.1' && addr !== '::1' + && peerIsManagedTraefikForLocalClient(addr, request.headers as HeaderMap, managedTraefikIdentity()) + && agentIsolationEnabled(); +} + +export const ISOLATION_SIGN_IN = { + error: 'sign in: open http://localhost: on this machine, or use a #overdeck_token= link from `pan serve`', + code: 'isolation-sign-in', +} as const; + /** * THE answer to "is this a browser or process on this machine?" — used by the * session mint and the remote request gate, so they never disagree (PAN-5344). @@ -548,7 +566,7 @@ export function rejectUnauthorizedDashboardSessionMintRequest( // a forwarded loopback request is not local: a local reverse proxy makes a // remote visitor look like one (PAN-3762 D-3762-9, PAN-5344). if (!hasDashboardInternalToken(request) && !isTrustedLocalCaller(request)) { - return jsonResponse({ error: 'unauthorized' }, { status: 401 }); + return jsonResponse(traefikTrustWithheld(request) ? ISOLATION_SIGN_IN : { error: 'unauthorized' }, { status: 401 }); } return null; } diff --git a/src/lib/agent-isolation/config.ts b/src/lib/agent-isolation/config.ts index 8ca4b05c03b..02fce8f2923 100644 --- a/src/lib/agent-isolation/config.ts +++ b/src/lib/agent-isolation/config.ts @@ -5,8 +5,10 @@ * nor `flywheel`. D-2: `agents.isolation.enabled` is read from the global * config.yaml only and defaults to true. */ +import { statSync } from 'node:fs'; import { homedir } from 'node:os'; import { isAbsolute, join } from 'node:path'; +import { GLOBAL_CONFIG_PATH } from '../config-yaml/defaults.js'; import { loadGlobalConfig } from '../config-yaml/load.js'; import type { YamlConfig } from '../config-yaml/schema.js'; import type { AgentTokenRole } from '../mcp/agent-token.js'; @@ -77,3 +79,36 @@ export function isAgentIsolationActive( ): boolean { return isIsolatedTokenRole(role) && readAgentIsolationConfig(config).enabled; } + +let enabledCache: { mtimeMs: number | null; enabled: boolean } | null = null; +let enabledOverride: boolean | null = null; + +/** + * `agents.isolation.enabled` for per-request checks (the dashboard's Traefik trust, D-11): + * re-read only when config.yaml's mtime changes. A malformed block counts as enabled, so a + * broken file never silently restores the weaker trust. + */ +export function agentIsolationEnabled(): boolean { + if (enabledOverride !== null) return enabledOverride; + let mtimeMs: number | null; + try { + mtimeMs = statSync(GLOBAL_CONFIG_PATH).mtimeMs; + } catch { + mtimeMs = null; + } + if (enabledCache?.mtimeMs === mtimeMs) return enabledCache.enabled; + let enabled: boolean; + try { + enabled = readAgentIsolationConfig().enabled; + } catch { + enabled = true; + } + enabledCache = { mtimeMs, enabled }; + return enabled; +} + +/** Test hook: pin `agentIsolationEnabled()`; `null` restores the config read. */ +export function _setAgentIsolationEnabledForTests(value: boolean | null): void { + enabledOverride = value; + enabledCache = null; +} From 521bfac06b296fb7ea49f461b74add879a17c0ef Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 18:13:34 -0500 Subject: [PATCH 068/129] chore(workspace): plan artifacts for PAN-5754 Overdeck-Agent: agent-pan-5754 --- .pan/continues/PAN-5754.xbrief.json | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/.pan/continues/PAN-5754.xbrief.json b/.pan/continues/PAN-5754.xbrief.json index 019288b2436..7a6bc0ade73 100644 --- a/.pan/continues/PAN-5754.xbrief.json +++ b/.pan/continues/PAN-5754.xbrief.json @@ -2,7 +2,7 @@ "version": "1", "issueId": "PAN-5754", "created": "2026-12-03T21:28:28.525Z", - "updated": "2026-12-03T23:08:42.092Z", + "updated": "2026-12-03T23:13:34.557Z", "gitState": {}, "decisions": [], "hazards": [], @@ -394,9 +394,22 @@ "doneAt": "2026-12-03T23:08:40.296Z" }, "traefik-trust": { - "status": "in_progress", + "status": "completed", "claimedBy": "agent-pan-5754", - "claimedAt": "2026-12-03T23:08:42.091Z" + "claimedAt": "2026-12-03T23:08:42.091Z", + "doneAt": "2026-12-03T23:13:34.557Z" + }, + "traefik-trust.ac1": { + "status": "completed", + "doneAt": "2026-12-03T23:13:34.557Z" + }, + "traefik-trust.ac2": { + "status": "completed", + "doneAt": "2026-12-03T23:13:34.557Z" + }, + "traefik-trust.ac3": { + "status": "completed", + "doneAt": "2026-12-03T23:13:34.557Z" } } } From 41679cc84f34222107f557277ea62e347dd9a063 Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 18:13:46 -0500 Subject: [PATCH 069/129] chore(workspace): plan artifacts for PAN-5754 Overdeck-Agent: agent-pan-5754 --- .pan/continues/PAN-5754.xbrief.json | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/.pan/continues/PAN-5754.xbrief.json b/.pan/continues/PAN-5754.xbrief.json index 7a6bc0ade73..595403d8a1f 100644 --- a/.pan/continues/PAN-5754.xbrief.json +++ b/.pan/continues/PAN-5754.xbrief.json @@ -2,7 +2,7 @@ "version": "1", "issueId": "PAN-5754", "created": "2026-12-03T21:28:28.525Z", - "updated": "2026-12-03T23:13:34.557Z", + "updated": "2026-12-03T23:13:46.175Z", "gitState": {}, "decisions": [], "hazards": [], @@ -410,6 +410,11 @@ "traefik-trust.ac3": { "status": "completed", "doneAt": "2026-12-03T23:13:34.557Z" + }, + "launch-sites-runtimes": { + "status": "in_progress", + "claimedBy": "agent-pan-5754", + "claimedAt": "2026-12-03T23:13:46.175Z" } } } From 5e677ecee276a9882fcb056a8cd419cb20d476dd Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 18:25:34 -0500 Subject: [PATCH 070/129] fix(infra): keep the isolation launch wiring out of import cycles PAN-5754 launch-sites follow-up. prepareAgentLaunchAccess lived in agent-isolation/launch.ts, which imported mcp/agent-injection; the launch sites (agents/messaging.ts among them) then reached the agents.ts cycle through a new hop and lint:circular reported new cycles. It now lives in agent-injection.ts, which every launch site already imports, and launch.ts declares the owner fields it reads (IsolationLaunchOwner) instead of importing OverdeckMcpLaunchOwner, so modules that need only prepareAgentIsolation (the runtimes, WI-29) gain no edge to agent-injection. lint:circular passes with no new cycles. Co-Authored-By: Claude Opus 5.5 Overdeck-Agent: agent-pan-5754 --- src/dashboard/server/routes/misc/planning.ts | 2 +- src/lib/agent-isolation/launch.ts | 29 +++++++++++--------- src/lib/agents/messaging.ts | 3 +- src/lib/agents/recovery.ts | 3 +- src/lib/agents/spawn-prep.ts | 3 +- src/lib/agents/spawn.ts | 3 +- src/lib/mcp/agent-injection.ts | 15 ++++++++++ src/lib/overdeck/conversation-runtime.ts | 3 +- src/lib/planning/spawn-planning-session.ts | 3 +- 9 files changed, 38 insertions(+), 26 deletions(-) diff --git a/src/dashboard/server/routes/misc/planning.ts b/src/dashboard/server/routes/misc/planning.ts index 8e53a5be985..aec7db66a3d 100644 --- a/src/dashboard/server/routes/misc/planning.ts +++ b/src/dashboard/server/routes/misc/planning.ts @@ -13,7 +13,7 @@ import { workspaceContextFile } from '../../../../lib/context-layers/layers.js'; import { extractPrefix } from '../../../../lib/issue-id.js'; import { prepareHarnessLaunch } from '../../../../lib/harness-binary.js'; import { generateLauncherScript } from '../../../../lib/launcher-generator.js'; -import { prepareAgentLaunchAccess } from '../../../../lib/agent-isolation/launch.js'; +import { prepareAgentLaunchAccess } from '../../../../lib/mcp/agent-injection.js'; import { PAN_CONTINUE_FILENAME, PAN_DIRNAME } from '../../../../lib/pan-dir/types.js'; import { getOverdeckHome } from '../../../../lib/paths.js'; import { extractTeamPrefix, findProjectByTeam } from '../../../../lib/projects.js'; diff --git a/src/lib/agent-isolation/launch.ts b/src/lib/agent-isolation/launch.ts index c0536e1f67b..823cbecd5d9 100644 --- a/src/lib/agent-isolation/launch.ts +++ b/src/lib/agent-isolation/launch.ts @@ -8,9 +8,10 @@ import { join } from 'node:path'; import type { YamlConfig } from '../config-yaml/schema.js'; +import type { AgentTokenRole } from '../mcp/agent-token.js'; +import type { RuntimeName } from '../runtimes/types.js'; import { normalizeAgentId } from '../agents/identity.js'; import { ensureIsolationToken } from '../mcp/agent-token.js'; -import { prepareClaudeOverdeckMcp, type OverdeckMcpLaunchOwner } from '../mcp/agent-injection.js'; import { resolveHostTool } from '../host-tools.js'; import { getHarnessBehavior } from '../runtimes/behavior.js'; import { writeIsolationFiles } from './claude-settings.js'; @@ -20,6 +21,19 @@ import { agentApiSocketPath, isolationRootsDir, OVERDECK_AGENT_TOKEN_FILE, OVERD import { buildIsolationPolicy } from './policy.js'; import { resolveIsolationPolicyInput } from './policy-input.js'; +/** + * The launch an isolation is prepared for: the fields of `OverdeckMcpLaunchOwner` it reads. + * Declared here, not imported, so the runtime modules that use this file gain no import edge + * to `mcp/agent-injection.ts` (lint:circular). + */ +export interface IsolationLaunchOwner { + agentId: string; + agentKind: 'agent' | 'conversation'; + role: AgentTokenRole; + harness: RuntimeName; + cwd: string; +} + /** Claude Code's sandbox needs both on Linux (D-12). */ export const CLAUDE_SANDBOX_PREREQUISITES = ['bwrap', 'socat'] as const; export type SandboxPrerequisite = (typeof CLAUDE_SANDBOX_PREREQUISITES)[number]; @@ -46,7 +60,7 @@ export function claudeSandboxUnavailableMessage(missing: readonly string[]): str } export async function prepareAgentIsolation( - owner: OverdeckMcpLaunchOwner, + owner: IsolationLaunchOwner, deps: AgentIsolationDeps = {}, ): Promise<{ isolation?: LaunchIsolation }> { if (!isAgentIsolationActive(owner.role, deps.config)) return {}; @@ -79,14 +93,3 @@ export async function prepareAgentIsolation( }; } -/** - * The launcher fields every managed agent launch site spreads: the overdeck MCP config - * (`prepareClaudeOverdeckMcp`, never throws) and the isolation fields (`prepareAgentIsolation`, - * throws to fail the launch closed). One call per site, so no site can wire one without the other. - */ -export async function prepareAgentLaunchAccess( - owner: OverdeckMcpLaunchOwner, -): Promise> & { isolation?: LaunchIsolation }> { - const mcp = await prepareClaudeOverdeckMcp(owner); - return { ...mcp, ...(await prepareAgentIsolation(owner)) }; -} diff --git a/src/lib/agents/messaging.ts b/src/lib/agents/messaging.ts index 48df4581688..4ccf30cb608 100644 --- a/src/lib/agents/messaging.ts +++ b/src/lib/agents/messaging.ts @@ -5,8 +5,7 @@ import { Effect } from 'effect'; import { emitActivityEntry } from '../activity-logger.js'; import { BLANKED_PROVIDER_ENV } from '../child-env.js'; import { generateLauncherScript } from '../launcher-generator.js'; -import { prepareCodexOverdeckMcp } from '../mcp/agent-injection.js'; -import { prepareAgentLaunchAccess } from '../agent-isolation/launch.js'; +import { prepareCodexOverdeckMcp, prepareAgentLaunchAccess } from '../mcp/agent-injection.js'; import { prepareHarnessLaunch } from '../harness-binary.js'; import { appendOperatorInterventionEvent } from '../operator-interventions.js'; import { logAgentLifecycle } from '../persistent-logger.js'; diff --git a/src/lib/agents/recovery.ts b/src/lib/agents/recovery.ts index accdc42fd99..14e4558ce74 100644 --- a/src/lib/agents/recovery.ts +++ b/src/lib/agents/recovery.ts @@ -9,8 +9,7 @@ import { getLatestSessionId } from './activity.js'; import { sendGracefulRestartWarning } from '../graceful-restart.js'; import { checkHook, generateFixedPointPrompt } from '../hooks.js'; import { generateLauncherScript } from '../launcher-generator.js'; -import { prepareCodexOverdeckMcp } from '../mcp/agent-injection.js'; -import { prepareAgentLaunchAccess } from '../agent-isolation/launch.js'; +import { prepareCodexOverdeckMcp, prepareAgentLaunchAccess } from '../mcp/agent-injection.js'; import { resolveHarness } from '../harness-resolve.js'; import { prepareHarnessLaunch } from '../harness-binary.js'; import { normalizeModelOverride, requireModelOverride } from '../model-validation.js'; diff --git a/src/lib/agents/spawn-prep.ts b/src/lib/agents/spawn-prep.ts index c371ac6c1d3..8377323c71c 100644 --- a/src/lib/agents/spawn-prep.ts +++ b/src/lib/agents/spawn-prep.ts @@ -12,8 +12,7 @@ import { transitionJiraIssue } from '../tracker/jira-lifecycle.js'; import { trackerStateToJiraTarget } from '../tracker/jira-status.js'; import { findProjectByPath, getIssuePrefix, resolveProjectFromIssueSync } from '../projects.js'; import { generateLauncherScript } from '../launcher-generator.js'; -import { prepareCodexOverdeckMcp } from '../mcp/agent-injection.js'; -import { prepareAgentLaunchAccess } from '../agent-isolation/launch.js'; +import { prepareCodexOverdeckMcp, prepareAgentLaunchAccess } from '../mcp/agent-injection.js'; import { getProviderForModel, setupCredentialFileAuth, clearCredentialFileAuth } from '../providers.js'; import type { ModelId } from '../settings.js'; import { requireModelOverride } from '../model-validation.js'; diff --git a/src/lib/agents/spawn.ts b/src/lib/agents/spawn.ts index dc5f10bd12c..bf53875014d 100644 --- a/src/lib/agents/spawn.ts +++ b/src/lib/agents/spawn.ts @@ -17,8 +17,7 @@ import { createConversation, getConversationByName, reactivateConversationForSpa import { startWork } from '../cv.js'; import { generateFixedPointPrompt, checkHook, initHook } from '../hooks.js'; import { generateLauncherScript } from '../launcher-generator.js'; -import { prepareCodexOverdeckMcp } from '../mcp/agent-injection.js'; -import { prepareAgentLaunchAccess } from '../agent-isolation/launch.js'; +import { prepareCodexOverdeckMcp, prepareAgentLaunchAccess } from '../mcp/agent-injection.js'; import { getProviderForModel, setupCredentialFileAuth, clearCredentialFileAuth } from '../providers.js'; import { resolveHarness } from '../harness-resolve.js'; import { prepareHarnessLaunch } from '../harness-binary.js'; diff --git a/src/lib/mcp/agent-injection.ts b/src/lib/mcp/agent-injection.ts index 4990e1a8844..83917ac8dde 100644 --- a/src/lib/mcp/agent-injection.ts +++ b/src/lib/mcp/agent-injection.ts @@ -32,6 +32,8 @@ import { atlassianNeedsInteractiveAuth } from '../skill-packs/atlassian.js'; import type { PackMcpServer } from '../skill-packs/adapters.js'; import { CLAUDE_OVERDECK_MCP_CONFIG_FILE, OVERDECK_MCP_SERVER_NAME } from './overdeck-mcp-args.js'; import { resolveSemgrepMcpServer, SEMGREP_MCP_SERVER_NAME, type SemgrepMcpServer } from '../semgrep/in-session.js'; +import { prepareAgentIsolation } from '../agent-isolation/launch.js'; +import type { LaunchIsolation } from '../agent-isolation/launcher-lines.js'; export { harnessGetsOverdeckMcp, overdeckMcpEnabledFor } from './overdeck-mcp-gate.js'; @@ -287,3 +289,16 @@ export async function prepareCodexOverdeckMcp(owner: OverdeckMcpLaunchOwner): Pr } return servers; } + +/** + * PAN-5754 WI-7: the launcher fields every managed agent launch site spreads: the overdeck MCP + * config (`prepareClaudeOverdeckMcp`, never throws) and the isolation fields + * (`prepareAgentIsolation`, throws to fail the launch closed). One call per site, so no site can + * wire one without the other. Here, not in agent-isolation/, so the sites gain no import edge. + */ +export async function prepareAgentLaunchAccess( + owner: OverdeckMcpLaunchOwner, +): Promise> & { isolation?: LaunchIsolation }> { + const mcp = await prepareClaudeOverdeckMcp(owner); + return { ...mcp, ...(await prepareAgentIsolation(owner)) }; +} diff --git a/src/lib/overdeck/conversation-runtime.ts b/src/lib/overdeck/conversation-runtime.ts index ec253c51b6c..07e5effdda0 100644 --- a/src/lib/overdeck/conversation-runtime.ts +++ b/src/lib/overdeck/conversation-runtime.ts @@ -39,8 +39,7 @@ import type { AgentPaneRef, TerminalBackend, TerminalBackendName } from '../term import { normalizeHarnessName, type AgentRole } from '@overdeck/contracts'; import { conversationStateDir, readConversationPaneRole, writeConversationPaneRole } from './conversation-pane-role.js'; import { revokeAgentMcpTokens } from '../mcp/agent-token.js'; -import { conversationTokenRole, prepareCodexOverdeckMcp } from '../mcp/agent-injection.js'; -import { prepareAgentLaunchAccess } from '../agent-isolation/launch.js'; +import { conversationTokenRole, prepareCodexOverdeckMcp, prepareAgentLaunchAccess } from '../mcp/agent-injection.js'; import { codexLaunchPermissions } from '../agent-isolation/codex.js'; import { isAgentIsolationActive } from '../agent-isolation/config.js'; import { validateCwdContainment } from './cwd-containment.js'; diff --git a/src/lib/planning/spawn-planning-session.ts b/src/lib/planning/spawn-planning-session.ts index 329f65f5192..c4b97de99a9 100644 --- a/src/lib/planning/spawn-planning-session.ts +++ b/src/lib/planning/spawn-planning-session.ts @@ -44,8 +44,7 @@ import { getHarnessBehavior } from '../runtimes/behavior.js'; import { launchAndCaptureManagedKimiSession } from '../runtimes/kimi-code.js'; import type { RuntimeName } from '../runtimes/types.js'; import { generateLauncherScript } from '../launcher-generator.js'; -import { prepareCodexOverdeckMcp } from '../mcp/agent-injection.js'; -import { prepareAgentLaunchAccess } from '../agent-isolation/launch.js'; +import { prepareCodexOverdeckMcp, prepareAgentLaunchAccess } from '../mcp/agent-injection.js'; import { BLANKED_PROVIDER_ENV } from '../child-env.js'; import { ensureWorkspacePanDir, getWorkspacePanPaths, writeWorkspaceContext } from '../pan-dir/index.js'; import { resolvePlanningDraftPath } from '../pan-dir/drafts.js'; From 4fe3c14c2e37931b05354452d243fe7238d9b95c Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 18:25:34 -0500 Subject: [PATCH 071/129] feat(infra): prepare isolation inside every runtime spawnAgent PAN-5754 WI-29. Crash recovery (service-crash.ts restartAgent), session rotation and every runtime that builds its own launch now prepare isolation for the agent, with its role read from its saved state (a missing state counts as work, the fail-safe direction): ohmypi, kimi-code, prime-agent and muse spread runtimeLaunchIsolation into generateLauncherScript; the Codex and ACP runtimes, which start a bare command, run it through wrapCommandWithIsolation (bash -c with the isolation lines, then exec). The Codex runtime clamps danger-full-access to workspace-write for an isolated agent and writes that sandbox_mode into its config.toml (D-13). A caller that already prepared isolation is reused. The Claude Code runtime delegates to spawnAgent -> buildAgentLaunchConfig, wired in WI-7. The ACP runtime tests decode the isolation wrapper before asserting on the host command, and the readiness-timeout test advances fake time only after the host launch starts. Item: launch-sites-runtimes Item: launch-sites-runtimes.ac1 Item: launch-sites-runtimes.ac2 Item: launch-sites-runtimes.ac3 Co-Authored-By: Claude Opus 5.5 Overdeck-Agent: agent-pan-5754 --- src/lib/agent-isolation/runtime-launch.ts | 38 ++++++ .../isolation-runtime-launch.test.ts | 122 ++++++++++++++++++ src/lib/runtimes/__tests__/acp.test.ts | 20 ++- src/lib/runtimes/acp.ts | 4 +- src/lib/runtimes/codex.ts | 11 +- src/lib/runtimes/kimi-code.ts | 2 + src/lib/runtimes/muse.ts | 2 + src/lib/runtimes/ohmypi.ts | 2 + src/lib/runtimes/prime-agent.ts | 2 + 9 files changed, 195 insertions(+), 8 deletions(-) create mode 100644 src/lib/agent-isolation/runtime-launch.ts create mode 100644 src/lib/cloister/__tests__/isolation-runtime-launch.test.ts diff --git a/src/lib/agent-isolation/runtime-launch.ts b/src/lib/agent-isolation/runtime-launch.ts new file mode 100644 index 00000000000..e785809f0a5 --- /dev/null +++ b/src/lib/agent-isolation/runtime-launch.ts @@ -0,0 +1,38 @@ +/** + * PAN-5754 WI-29: isolation for launches that go through a runtime's own `spawnAgent` + * (crash recovery in service-crash.ts, session rotation, and every non-Claude runtime that + * builds its own launch) instead of the WI-7 sites. + * + * The agent's role comes from its saved state (runtime spawns carry none), defaulting to `work`. + * Generator-based runtimes spread `runtimeLaunchIsolation(...)` into `generateLauncherScript`; + * runtimes that start a bare command wrap it with `wrapCommandWithIsolation`. + */ +import { getAgentState } from '../agents/agent-state-read.js'; +import type { Role } from '../agents/role.js'; +import type { RuntimeName } from '../runtimes/types.js'; +import { shellQuote } from '../shell-quote.js'; +import { prepareAgentIsolation, type AgentIsolationDeps } from './launch.js'; +import { isolationLauncherLines, type LaunchIsolation } from './launcher-lines.js'; + +export interface RuntimeIsolationTarget { + agentId: string; + workspace: string; + /** Set by a caller that already prepared isolation; reused, never minted twice. */ + isolation?: LaunchIsolation; +} + +export async function runtimeLaunchIsolation( + config: RuntimeIsolationTarget, + harness: RuntimeName, + deps: AgentIsolationDeps & { roleOf?: (agentId: string) => Role | undefined } = {}, +): Promise<{ isolation?: LaunchIsolation }> { + if (config.isolation) return { isolation: config.isolation }; + const role = (deps.roleOf ?? ((agentId: string) => getAgentState(agentId)?.role))(config.agentId) ?? 'work'; + return prepareAgentIsolation({ agentId: config.agentId, agentKind: 'agent', role, harness, cwd: config.workspace }, deps); +} + +/** `bash -c '; exec '`, or the command unchanged without isolation. */ +export function wrapCommandWithIsolation(command: string, isolation: LaunchIsolation | undefined): string { + if (!isolation) return command; + return `bash -c ${shellQuote([...isolationLauncherLines(isolation), `exec ${command}`].join('\n'))}`; +} diff --git a/src/lib/cloister/__tests__/isolation-runtime-launch.test.ts b/src/lib/cloister/__tests__/isolation-runtime-launch.test.ts new file mode 100644 index 00000000000..adbf655b02c --- /dev/null +++ b/src/lib/cloister/__tests__/isolation-runtime-launch.test.ts @@ -0,0 +1,122 @@ +/** + * PAN-5754 WI-29: launches that go through a runtime's own spawnAgent — a Deacon crash + * restart (service-crash.ts), a session rotation (session-rotation.ts) and the Codex runtime — + * carry the isolation lines and never run an isolated agent with danger-full-access. + * The real Codex runtime runs; tmux and the harness binary are mocked, and the mocked + * tmuxCreateSession writes the rollout file Codex would, so the spawn completes. + */ +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { homedir, tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +const launches = vi.hoisted(() => [] as Array<{ session: string; command: string }>); + +vi.mock('../../runtimes/tmux-cli.js', async (importOriginal) => ({ + ...(await importOriginal()), + tmuxCreateSession: vi.fn(async (session: string, _cwd: string, command: string) => { + launches.push({ session, command }); + const { mkdirSync: mkdir, writeFileSync: write } = await import('node:fs'); + const { join: joinPath } = await import('node:path'); + const { homedir: home } = await import('node:os'); + const sessions = joinPath(home(), '.overdeck', 'agents', session, 'codex-home-v2', 'sessions'); + mkdir(sessions, { recursive: true }); + write(joinPath(sessions, 'rollout-2026-12-03T00-00-00-0198a9c3-0000-7000-8000-000000000001.jsonl'), '{}\n'); + }), + tmuxSessionExists: vi.fn(async () => false), + tmuxKillSession: vi.fn(async () => undefined), +})); +vi.mock('../../harness-binary.js', async (importOriginal) => ({ + ...(await importOriginal()), + prepareHarnessLaunch: vi.fn(async () => ({ binaryPath: '/usr/bin/codex', pathExport: 'export PATH="$PATH"' })), +})); +const runtimeFor = vi.hoisted(() => ({ current: null as unknown })); +vi.mock('../../runtimes/index.js', async (importOriginal) => ({ + ...(await importOriginal()), + getRuntimeForAgent: vi.fn(() => runtimeFor.current), +})); + +const { createCodexRuntime } = await import('../../runtimes/codex.js'); +const { saveAgentStateSync } = await import('../../agents/agent-state.js'); +const { restartAgent } = await import('../service-crash.js'); +const { rotateSpecialistSession } = await import('../session-rotation.js'); + +let home: string; +let workspace: string; +const originalHome = process.env.OVERDECK_HOME; + +beforeEach(() => { + home = mkdtempSync(join(tmpdir(), 'pan-5754-runtime-')); + workspace = mkdtempSync(join(tmpdir(), 'pan-5754-runtime-ws-')); + process.env.OVERDECK_HOME = home; + launches.length = 0; + runtimeFor.current = createCodexRuntime(); +}); + +afterEach(() => { + if (originalHome === undefined) delete process.env.OVERDECK_HOME; + else process.env.OVERDECK_HOME = originalHome; + rmSync(home, { recursive: true, force: true }); + rmSync(workspace, { recursive: true, force: true }); + rmSync(join(homedir(), '.overdeck', 'agents'), { recursive: true, force: true }); +}); + +function saveState(id: string, role: string): void { + saveAgentStateSync({ + id, issueId: 'PAN-5754', workspace, harness: 'codex', role, model: 'gpt-5.6', status: 'running', + startedAt: new Date().toISOString(), sessionId: '0198a9c3-0000-7000-8000-000000000001', + } as never); +} + +/** The script inside `bash -c '