From d26af38610e21ac80301894e56639c89843b10bf Mon Sep 17 00:00:00 2001 From: Kaitian Xie Date: Sat, 14 Nov 2026 23:34:54 +0800 Subject: [PATCH 1/3] docs(swarm): cover agy 1.5.9 lifecycle guards, swarm_pane, and remote rosters Update /setup-pstack global hook commands with a test ! -f check and document plugin disable parity, plain /swarm pass-through, swarm_pane plan.json and brain-directory timeline screenshots, and remote --roster-only lookup across capsules, skills, setup guide, and README. --- README.md | 13 +++++++------ docs/guide/01-setup.md | 4 +++- roles/coordinator.md | 19 +++++++++++++++---- roles/research.md | 18 ++++++++++++------ skills/control-ui/SKILL.md | 16 ++++++++++++++-- skills/pstack/SKILL.md | 7 +++++-- skills/setup-pstack/SKILL.md | 14 ++++++++++---- 7 files changed, 66 insertions(+), 25 deletions(-) diff --git a/README.md b/README.md index ebcf79c..295b090 100644 --- a/README.md +++ b/README.md @@ -50,16 +50,17 @@ Every swarm member's prefix determines its workspace isolation, injected role ca | Coordinator (root chat) | Primary checkout | [`roles/coordinator.md`](./roles/coordinator.md) | Plans slices, manages swarm lifecycle, judges `#seq` evidence, and merges verified commits. | | `impl-*`, `cand-*`, `lead-*` | `workspace: "share"` | [`roles/poteto-agent.md`](./roles/poteto-agent.md) | Edits strictly inside its own worktree. `git push` blocked unless `PSTACK_ALLOW_PUSH=1` is set. | | `adv-*` | `workspace: "share"` | [`roles/poteto-agent.md`](./roles/poteto-agent.md) | Writes executable repros and exploit probes inside its own worktree. `git push` always blocked. | -| `ro-*` | `workspace: "inherit"` | [`roles/research.md`](./roles/research.md) | Strictly read-only. Blocks `edit_file`, `write_file`, mutating shell or git commands, and mutating MCP calls. Allows `/tmp` probes. | +| `ro-*` | `workspace: "inherit"` | [`roles/research.md`](./roles/research.md) | Strictly read-only. Blocks `edit_file`, `write_file`, mutating shell or git commands, and mutating MCP calls outside temp roots and brain-directory timeline screenshots. | | `sicko-*` | `workspace: "share"` | [`roles/comment-sicko.md`](./roles/comment-sicko.md) | Comment and slop surgeon. Allows `edit_file` inside its own worktree. Blocks `write_file` and `git push`. | -| `monitor*`, `narrator*` | Built-in | None (skipped) | Native stall detection and board narration with zero extra capsule tokens. | +| `monitor*`, `narrator*` | Built-in | None (skipped) | Native stall detection (`swarm_monitor`) and board narration (`swarm_narrator`, skipped when `swarm_pane` Overview is active unless requested) with zero extra capsule tokens. | ### Mechanical Guardrails in `hooks/guard.mjs` -- **One-time capsule injection.** `SessionStart` and `PreInvocation` resolve each conversation against `/brain/*/.system_generated/swarm/members.json` and inject its matching `roles/*.md` capsule once per role, upgrading cleanly if a worker's roster entry appears after startup. -- **Native swarm exclusivity.** `PreToolUse` blocks legacy subagent tools and `run_workflow` across all roles so every multi-agent workflow runs on the shared `#seq` message board. -- **Symlink-safe worktree confinement.** `PreToolUse` resolves `realpathSync` on the nearest existing ancestor of every `edit_file` and `write_file` path, blocking `../` traversal and symlink escapes into sibling worktrees. -- **Read-only research integrity.** `ro-*` workers can inspect code, run tests, query read-only MCPs, and write temporary probes under `/tmp`, while `hooks/guard.mjs` denies repository mutations. +- **One-time capsule injection.** `SessionStart` and `PreInvocation` resolve each conversation against local `/brain/*/.system_generated/swarm/members.json` or remote `swarm.json` (`--roster-only`) rosters and inject its matching `roles/*.md` capsule once per role, upgrading cleanly if a worker's roster entry appears after startup. +- **Scoped lifecycle and plain `/swarm` pass-through.** Global `~/.gemini/config/hooks.json` commands guard execution with `test ! -f '' ||` so `agy plugin uninstall agy-pstack-next` leaves a clean exit-0 no-op. `hooks/guard.mjs` inspects `~/.gemini/config/config.json` (`plugins["agy-pstack-next"].enabled`) so `agy plugin disable agy-pstack-next` suspends capsule injection and `PreToolUse` gating globally, and plain built-in `/swarm` sessions without a pstack skill or pstack worker prefixes (`impl-*`, `cand-*`, `lead-*`, `ro-*`, `adv-*`, `sicko-*`) pass through unmanaged. +- **Native swarm exclusivity.** `PreToolUse` blocks legacy subagent tools and `run_workflow` across all managed roles so every pstack workflow runs on the shared `#seq` message board. +- **Symlink-safe worktree confinement.** `PreToolUse` resolves `realpathSync` on the nearest existing ancestor of every `edit_file` and `write_file` path, blocking `../` traversal, symlink escapes into sibling worktrees, and worker writes inside `.system_generated/`. +- **Read-only research integrity.** `ro-*` workers can inspect code, run tests, query read-only MCPs, write temporary probes under canonical temp roots, and save Swarm UI timeline screenshots inside their own `/brain//` directory outside `.system_generated/`, while `hooks/guard.mjs` denies repository mutations. - **Push gating.** Force-pushes to `main` or `master` are always denied. Adversarial (`adv-*`) and cleanup (`sicko-*`) workers can never push, and author workers push only when explicitly authorized with `PSTACK_ALLOW_PUSH=1`. ### Native Swarm Mechanics diff --git a/docs/guide/01-setup.md b/docs/guide/01-setup.md index 7e63ae4..d24a1b2 100644 --- a/docs/guide/01-setup.md +++ b/docs/guide/01-setup.md @@ -25,7 +25,9 @@ Run the setup skill inside Antigravity: [`/setup-pstack`](../../skills/setup-pstack/SKILL.md) queries `swarm{action: "models", all: true}` to discover every model currently available in your Antigravity environment across Claude, Gemini, and GPT-OSS families, alongside `inherit` (which runs workers on your active session model). It asks for your budget preset and performs two machine-local setup steps. 1. **Writes `~/.gemini/config/rules/pstack-models.md` with `trigger: always_on` frontmatter.** Named rule files under `~/.gemini/config/rules/*.md` require `trigger: always_on` YAML frontmatter in `agy` so every coordinator turn receives your model and autonomy settings automatically. -2. **Registers `pstack-swarm-guard` in global `~/.gemini/config/hooks.json`.** Root plugin [`hooks.json`](../../hooks.json) covers top-level sessions, whereas `agy` native `Swarm Worker` subagents do not inherit user-plugin hooks. `/setup-pstack` reads any existing `~/.gemini/config/hooks.json` object first (preserving entries such as `herdr`) and registers `pstack-swarm-guard` pointing to your absolute `hooks/guard.mjs` path. Both hook paths share `/plugin_data/agy-pstack-next` state (`injected-capsules.json` and `member-map.json`), so swarm workers enforce capsules and tool confinement without duplicate injections in the root coordinator. +2. **Registers `pstack-swarm-guard` in global `~/.gemini/config/hooks.json`.** Root plugin [`hooks.json`](../../hooks.json) covers top-level sessions, whereas `agy` native `Swarm Worker` subagents do not inherit user-plugin hooks. `/setup-pstack` reads any existing `~/.gemini/config/hooks.json` object first (preserving entries such as `herdr`) and registers `pstack-swarm-guard` as `test ! -f '' || node ''`. Both hook paths share `/plugin_data/agy-pstack-next` state (`injected-capsules.json` and `member-map.json`), so swarm workers enforce capsules and tool confinement without duplicate injections in the root coordinator. + +That global entry stays inert outside active pstack runs. Guarding the command with `test ! -f '' ||` keeps `~/.gemini/config/hooks.json` a clean exit-0 no-op if `agy plugin uninstall agy-pstack-next` removes the plugin directory. `hooks/guard.mjs` also inspects `~/.gemini/config/config.json` (`plugins["agy-pstack-next"].enabled`), so running `agy plugin disable agy-pstack-next` suspends capsule injection and `PreToolUse` gating across global hooks too. Plain built-in `/swarm` sessions that do not invoke a pstack skill or pstack worker prefixes (`impl-*`, `cand-*`, `lead-*`, `ro-*`, `adv-*`, `sicko-*`) pass through `hooks/guard.mjs` unmanaged. Every swarm workflow reads `pstack-models.md` to pin models by role prefix. diff --git a/roles/coordinator.md b/roles/coordinator.md index 79b7069..14bf1df 100644 --- a/roles/coordinator.md +++ b/roles/coordinator.md @@ -44,10 +44,12 @@ matching role capsule and enforces its runtime tool boundaries. cannot call `write_file`, redirect shell output to files, run mutating filesystem commands, or push. - **Built-in support (`monitor`, `narrator`).** Spawn these only when their - corresponding built-in skills exist in your active catalog. The guard skips - capsule injection for both. Never kill `monitor` or `narrator` unless the user - asks, and post `[done] ` with no `@` mention when the task finishes - so `monitor` parks quietly. + corresponding built-in skills exist in your active catalog, and skip + `narrator` when `swarm_pane` is in `` unless the user asks for + `narrator` by name. The guard skips capsule injection for both. + Never kill `monitor` or `narrator` unless the user asks, and post + `[done] ` with no `@` mention when the task finishes so `monitor` + parks quietly. ## Native swarm mechanics @@ -89,6 +91,15 @@ matching role capsule and enforces its runtime tool boundaries. `trigger` set to `always_on` so `agy` loads them into `` on every turn. When active in context, apply those per-prefix model tiers without reading the file from disk. +- **Populate the Swarm UI Overview (`swarm_pane`).** When `swarm_pane` is in + ``, load `swarm_pane` before briefing workers, skip `narrator` unless + requested by name, and write `plan.json` under + `/brain//.system_generated/swarm/plan.json` after + adding workers. Rewrite `plan.json` whenever workers, task assignments, or + goals change. On UI or visual tasks, instruct UI workers (`impl-*`, `cand-*`, + and `ro-verify`) to save full-window timeline screenshots under their own + `/brain//` folder outside `.system_generated` and + flag each step on its own board line per `swarm_pane`. - **Surface `open_board` on mid-flight replies.** When `native_swarm` is not loaded in your active `` catalog and you reply to the user while the swarm is running (on the turn that spawns a continuing swarm or on any diff --git a/roles/research.md b/roles/research.md index d124c8c..3f60069 100644 --- a/roles/research.md +++ b/roles/research.md @@ -13,11 +13,13 @@ directly, and post cited evidence on the swarm message board. (`rm`, `mv`, `cp`, `mkdir`, `chmod`, `unlink`, `touch`, `tee`), and inline `node -e` or `python3 -c` filesystem writes or deletes whenever the resolved target falls outside canonical temp roots (`/tmp`, `/private/tmp`, and - `TMPDIR`). It also blocks mutating git subcommands (`commit`, `push`, `merge`, - `rebase`, `cherry-pick`, `reset`, `clean`, `checkout`, `switch`, and mutating - `stash` or `tag` forms), in-place editors (`sed -i`, `perl -i`, `patch`), - package installs, mutating MCP tool calls, `run_workflow`, and legacy subagent - tools. Never attempt to bypass these guards. + `TMPDIR`) or allowed screenshot paths in your own conversation artifact + directory outside `.system_generated`. It also blocks mutating git subcommands + (`commit`, `push`, `merge`, `rebase`, `cherry-pick`, `reset`, `clean`, + `checkout`, `switch`, and mutating `stash` or `tag` forms), in-place editors + (`sed -i`, `perl -i`, `patch`), package installs, mutating MCP tool calls, + `run_workflow`, and legacy subagent tools. Never attempt to bypass these + guards. - **Full inspection, temp-root probe, and native swarm access.** Read source files freely, inspect git history and read-only refs (`git status`, `git diff`, `git log`, `git show`, `git blame`, `git tag -l`, @@ -28,7 +30,11 @@ directly, and post cited evidence on the swarm message board. trackers, docs, team chat, observability, error tracking, and analytics warehouses, and use native swarm tools (`swarm` including `add` for read-only helpers and `model` for quota hot-swap, `post_message`, `read_board`, - `swarm_wait`, `schedule`, and `manage_task`). + `swarm_wait`, `schedule`, and `manage_task`). Alongside canonical temp roots, + the guard permits writing or copying screenshot image files (`.png`, `.jpg`, + `.jpeg`, `.webp`) and screenshot subdirectories inside your own conversation + artifact directory (`/brain//`) outside + `.system_generated` for Swarm UI timeline proofs. - **Clue-sharing mesh etiquette.** Read recent board posts before repeating a search. Post concise clues with exact `file` and line anchors, commit SHAs, or ticket IDs so parallel `ro-*` peers can pivot live. Cite earlier board posts diff --git a/skills/control-ui/SKILL.md b/skills/control-ui/SKILL.md index c352431..183c4a1 100644 --- a/skills/control-ui/SKILL.md +++ b/skills/control-ui/SKILL.md @@ -21,7 +21,7 @@ Parallel swarm workers (`impl-*`, `cand-*`, `adv-*`, and `ro-verify`) share one 1. **Ephemeral app ports.** Start dev servers and local APIs on OS-assigned or worker-unique ports (`--port 0` or an explicit free port) and parse the bound URL from startup output instead of assuming `3000`, `4173`, or `5173`. 2. **Isolated `--user-data-dir` and CDP port.** Launch every Chromium or Electron instance with `--user-data-dir=/tmp/ui-profile--` and `--remote-debugging-port=0` (reading `DevToolsActivePort` in that profile directory or the `ws://127.0.0.1:` stderr line). Concurrent workers never share cookies, IndexedDB, service workers, or debug sockets. -3. **Scoped `/tmp` artifact directories.** Write screenshots, ARIA snapshots, traces, and temporary probe scripts to `/tmp/ui-artifacts--/`. Hook guards block `ro-*` workers from writing inside the repository tree, so `/tmp` keeps probes portable across all roles. +3. **Scoped `/tmp` artifact directories.** Write ephemeral browser profiles, ARIA dumps, traces, scratch screenshots, and temporary probe scripts to `/tmp/ui-artifacts--/` (saving or copying milestone `.png`, `.jpg`, `.jpeg`, or `.webp` screenshots into `/brain//` outside `.system_generated/` when posting Swarm UI timeline proofs). Hook guards block `ro-*` workers from writing inside the repository tree, while allowing `/tmp` probes and brain-directory screenshot files. 4. **Exact PID teardown.** Record the exact PIDs of dev servers and browser instances started by this worker and kill only those PIDs on exit, then remove the disposable profile directory while retaining proof artifacts needed for `#seq` board reports. ## Setup Pattern @@ -89,7 +89,19 @@ Replace `` with a stable landmark or `data-*` root from the c 3. Execute a single structural action (click, fill, keypress, drag, scroll, navigate, or resize). 4. Wait on an observable DOM or network state transition rather than a fixed sleep. 5. Capture a fresh snapshot or screenshot and verify the expected state change. -6. Record before-and-after artifact paths when reporting `#seq` proof on the swarm board. +6. Record before-and-after artifact paths when reporting `#seq` proof on the swarm board, adding standalone `Screenshot: | ` lines from `/brain//` when Swarm UI timeline proofs are requested. + +## Swarm UI Timeline Screenshots + +Keep `/tmp/ui-artifacts--/` for ephemeral browser profiles, ARIA dumps, traces, and probe scripts. When capturing visual timeline proofs for the Swarm UI Overview (`swarm_pane`), workers (`impl-*`, `cand-*`, and `ro-verify`) save or copy full-window `.png`, `.jpg`, `.jpeg`, or `.webp` screenshots into their own `/brain//` artifact directory (excluding `.system_generated/`). The Swarm UI reads timeline images only from each worker's brain folder, and `hooks/guard.mjs` allows read-only screenshot writes and screenshot subdirectories inside a worker's own brain directory. + +1. Keep the same screen, viewport size, and theme across shots. Capture the full window with no crops or diff composites. +2. Save or copy each milestone `.png`, `.jpg`, `.jpeg`, or `.webp` file under `/brain//` outside `.system_generated/`. +3. Flag each step on its own line in your board post: + +```text +Screenshot: | +``` ## Raw CDP Capabilities diff --git a/skills/pstack/SKILL.md b/skills/pstack/SKILL.md index 8ad344a..73974dd 100644 --- a/skills/pstack/SKILL.md +++ b/skills/pstack/SKILL.md @@ -29,10 +29,12 @@ Root `hooks.json` and global `~/.gemini/config/hooks.json` (`pstack-swarm-guard` | --- | --- | --- | --- | --- | | Coordinator (root) | root checkout | `roles/coordinator.md` | Legacy subagent tools denied. Force-push to `main` or `master` denied. | Decompose, spawn, judge `#seq` evidence, merge verified commits | | `impl-*`, `cand-*`, `lead-*` | `"share"` | `roles/poteto-agent.md` | `realpathSync` confines writes to own worktree and temp roots. `git push` denied unless `PSTACK_ALLOW_PUSH=1`. | Disjoint slice implementation, competing candidates, area leads | -| `ro-*` | `"inherit"` | `roles/research.md` | `edit_file`, `write_file`, and mutating shell, git, and MCP calls denied outside temp roots. | Read-only probes, benchmarks (`ro-bench`), blind judging (`ro-judge`), independent gates (`ro-verify`) | +| `ro-*` | `"inherit"` | `roles/research.md` | `edit_file`, `write_file`, and mutating shell, git, and MCP calls denied outside temp roots (except screenshot images in own `brain//` outside `.system_generated/`). | Read-only probes, benchmarks (`ro-bench`), blind judging (`ro-judge`), independent gates (`ro-verify`) | | `adv-*` | `"share"` | `roles/poteto-agent.md` | `realpathSync` confines writes to own worktree and temp roots. `git push` permanently denied. | Executable exploit and repro tests (`/interrogate`) | | `sicko-*` | `"share"` | `roles/comment-sicko.md` | `edit_file`-only inside own worktree. `write_file`, shell file redirects, and `git push` permanently denied. | Post-implementation comment and AI-slop surgical pass | -| `monitor`, `narrator` (`*-*`) | `"inherit"` | `null` (skipped) | Legacy subagent tools denied. Capsule injection skipped cleanly. | Built-in stall monitor and board narrator **only** when `swarm_monitor` or `swarm_narrator` exists in `` | +| `monitor`, `narrator` (`*-*`) | `"inherit"` | `null` (skipped) | Legacy subagent tools denied. Capsule injection skipped cleanly. | Built-in stall monitor when `swarm_monitor` exists in ``. When `swarm_pane` exists in ``, its Overview replaces `narrator`, so skip `narrator` unless the user asks for `narrator` by name. Otherwise spawn `narrator` only when `swarm_narrator` exists in ``. | + +**Scope, disablement, and remote rosters.** Plain non-pstack `/swarm` runs that invoke neither a pstack skill nor pstack worker prefixes (`impl-*`, `cand-*`, `lead-*`, `ro-*`, `adv-*`, `sicko-*`) pass through `hooks/guard.mjs` unmanaged. Running `agy plugin disable agy-pstack-next` suspends capsule injection and `PreToolUse` gating via `plugins["agy-pstack-next"].enabled` in `~/.gemini/config/config.json`. On remote multi-host swarms backed by `swarm.json` anchors, `hooks/guard.mjs` resolves worker roles via `--roster-only` into `member-map.json`. **Worker skill and capsule paths in briefs.** Native `Swarm Worker` subagents do not mount installed plugin skills in ``, and worker hooks run only when `pstack-swarm-guard` is registered in global `~/.gemini/config/hooks.json`. Derive `` from this skill's directory path in ``. Pass explicit resolved `SKILL.md` and reference paths in worker briefs (such as `/skills/statechart/SKILL.md`, `/skills/control-ui/SKILL.md`, and `/skills/control-cli/SKILL.md`) for `read_file` rather than telling workers to invoke plugin skills by name. When global `~/.gemini/config/hooks.json` is not active, also pass the resolved `/roles/.md` path (`poteto-agent.md`, `research.md`, or `comment-sicko.md`) in each worker brief to read first. @@ -44,6 +46,7 @@ Root `hooks.json` and global `~/.gemini/config/hooks.json` (`pstack-swarm-guard` - **Topic channels when supported.** Stay on the main board for `<= 8` workers. For `> 8` concurrent workers or multi-area DAGs, check whether the live `swarm` tool declaration includes `"channel"` in `action`. When `"channel"` is present, partition traffic with `swarm{action: "channel"}` (`#area`) and assign one `lead-` (`workspace: "share"`) per channel so leaf chatter never wakes unrelated slices. When `"channel"` is absent, coordinate on the main board under `lead-` coordinators (`workspace: "share"`) with strict `@mention` discipline so leaf updates mention only `@lead-`. - **`#seq` citations and paged board reads.** Cite board messages by sequence number (`#12`) and pull specific posts via `read_board{seqs: [12]}` or incremental deltas via `read_board{since: }`. Never copy-paste raw worker logs across briefs. Because `read_board` defaults to `limit: 20`, cold-start session pickup and catch-up after busy bursts must page `read_board{since: , limit: 100}` starting from `` (`0` on cold start) until `` reaches `head`. - **Doorbell `@mention` hygiene.** `@name` wakes a sleeping agent and spends a turn. Never use `@name` as a passive CC. On peer handoffs (`impl-1` to `@ro-verify`), mention only the next actor and require workers to open final completion posts with `@ [done]` so the Swarm UI marks parked workers done. Post non-urgent progress unaddressed. Reserve `@all` for swarm-wide holds or interface contract changes. Sleep for free with `swarm_wait{since: }` instead of polling `read_board` in a loop. +- **Swarm UI Overview (`swarm_pane`).** When `swarm_pane` is present in ``, load `swarm_pane` before briefing workers, skip `narrator` unless the user asks for `narrator` by name, and write `/brain//.system_generated/swarm/plan.json` (`goal`, `tasks`, and 1 to 6 outcome `threads`) after adding workers. Rewrite `plan.json` whenever workers, task assignments, or goals change. On UI, layout, or visual tasks, instruct UI-facing workers (`impl-*`, `cand-*`, `ro-verify`) in their briefs to save full-window timeline screenshots under their own `/brain//` directory (outside `.system_generated/`) and flag each step on its own board line as `Screenshot: | `. Skip screenshot instructions on backend, infra, data, or docs work. - **Show `open_board` on mid-flight status replies.** When `native_swarm` is not loaded in `` and you reply to the user while the swarm is active (on the turn that launches a continuing swarm or whenever the user asks what the swarm is doing), end your reply with the verbatim `open_board` string from your latest `swarm` `add` or `status` result on its own line. Call `swarm{action: "status"}` if none is in view, omit the line when `open_board` is empty, and never fabricate a board command or link yourself. - **Quota and capacity hot-swap (`swarm{action: "model"}`).** On `[quota]` warnings or model capacity errors, inspect valid models via `swarm{action: "models"}` and switch the `waiting` worker (or yourself) in place with `swarm{action: "model", name, model}` while preserving full conversation history. Never `kill` and re-`add` merely to switch models. - **Land commits BEFORE `swarm{action: "kill"}`.** `swarm{action: "kill", name}` is permanent and **deletes that worker's `share` or `branch` worktree**. Keep finished `impl-*` and `cand-*` workers parked in `waiting` (zero token cost) until you run `git fetch && git merge --no-edit FETCH_HEAD` (or `git cherry-pick `) and verify `git status --short` locally. Only after commits are safely landed in your branch, call `swarm{action: "kill"}` on every task worker (`impl-*`, `cand-*`, `lead-*`, `ro-*`, `adv-*`, `sicko-*`) while leaving built-in `monitor` and `narrator` (`*-N`) alive unless the user asks. diff --git a/skills/setup-pstack/SKILL.md b/skills/setup-pstack/SKILL.md index 5ad8559..7f55158 100644 --- a/skills/setup-pstack/SKILL.md +++ b/skills/setup-pstack/SKILL.md @@ -118,14 +118,14 @@ In `agy`, synthetic `Swarm Worker` subagent specs do not inherit user-plugin `ho "SessionStart": [ { "type": "command", - "command": "node ''", + "command": "test ! -f '' || node ''", "timeout": 10 } ], "PreInvocation": [ { "type": "command", - "command": "node ''", + "command": "test ! -f '' || node ''", "timeout": 10 } ], @@ -135,7 +135,7 @@ In `agy`, synthetic `Swarm Worker` subagent specs do not inherit user-plugin `ho "hooks": [ { "type": "command", - "command": "node ''", + "command": "test ! -f '' || node ''", "timeout": 10 } ] @@ -145,7 +145,7 @@ In `agy`, synthetic `Swarm Worker` subagent specs do not inherit user-plugin `ho "hooks": [ { "type": "command", - "command": "node ''", + "command": "test ! -f '' || node ''", "timeout": 10 } ] @@ -157,6 +157,12 @@ In `agy`, synthetic `Swarm Worker` subagent specs do not inherit user-plugin `ho 4. Write the merged JSON object back to `~/.gemini/config/hooks.json` with 2-space indentation. +Global registration stays inert outside active pstack swarms: + +- **Safe uninstall.** Guarding each command with `test ! -f '' ||` keeps global `~/.gemini/config/hooks.json` a clean exit-0 no-op if `agy plugin uninstall agy-pstack-next` removes the plugin directory. +- **Disable parity.** `hooks/guard.mjs` inspects `~/.gemini/config/config.json` (`plugins["agy-pstack-next"].enabled`), so running `agy plugin disable agy-pstack-next` suspends capsule injection and `PreToolUse` gating across global hooks too. +- **Plain `/swarm` pass-through.** Plain built-in `/swarm` sessions that do not invoke a pstack skill or pstack worker prefixes (`impl-*`, `cand-*`, `lead-*`, `ro-*`, `adv-*`, `sicko-*`) pass through `hooks/guard.mjs` unmanaged. + Tell the user that `~/.gemini/config/rules/pstack-models.md` and `~/.gemini/config/hooks.json` were saved and take effect on new conversations and newly spawned workers, while `swarm{action: "model"}` can hot-swap waiting workers immediately in the active swarm. ### Step 5. Offer project verification harnesses once From 5fdf2169b71c37464ebde02de200eff5d302236b Mon Sep 17 00:00:00 2001 From: Kaitian Xie Date: Sat, 14 Nov 2026 23:58:02 +0800 Subject: [PATCH 2/3] fix(guard): resolve agy 1.5.9 native swarm compatibility caveats Honor plugin disable flags in config.json before session capsule injection or PreToolUse gating, resolving config paths from PSTACK_CONFIG_DIR, parent plugin directories, or HOME. Leave built-in /swarm sessions and unprefixed plain swarms unmanaged without polluting member-map.json or non-worker-roots.json, while upgrading cleanly when pstack workers or commands join. Allow read-only workers to write Overview timeline screenshots inside explicit or brain/ artifact directories and protect .system_generated metadata across all worker roles. Resolve remote swarm.json anchors through bounded --roster-only CLI probes cached in remote-rosters.json with fail-open fallback. --- hooks/guard.mjs | 1163 +++++++++++++++++++++++++++++++++++++----- hooks/guard.test.mjs | 923 ++++++++++++++++++++++++++++++++- 2 files changed, 1948 insertions(+), 138 deletions(-) diff --git a/hooks/guard.mjs b/hooks/guard.mjs index d97eefe..d592fab 100755 --- a/hooks/guard.mjs +++ b/hooks/guard.mjs @@ -1,6 +1,8 @@ #!/usr/bin/env node import { execFileSync } from "node:child_process"; import { + accessSync, + constants as fsConstants, existsSync, lstatSync, mkdirSync, @@ -35,6 +37,18 @@ const SWARM_BOARD_TOOLS = new Set([ const PSTACK_SLASH_COMMAND_RE = /(?:^|\s)\/(?:agy-pstack-next:)?(?:pstack|setup-pstack|understand|crucible|interrogate|reflect|ketchup|verify-gen|control-ui|control-cli|statechart|technical-writing|make-bot-ui)\b/i; +const BUILTIN_SWARM_SLASH_RE = /(?:^|\s)\/swarm\b/i; + +const PSTACK_WORKER_PREFIX_RE = /^(?:impl|cand|lead|ro|adv|sicko)-/i; + +const BUILTIN_SUPPORT_MEMBER_RE = /^(?:coordinator|monitor(?:-\d+)?|narrator(?:-\d+)?)$/i; + +const REMOTE_SWARM_ID_RE = /^[A-Za-z0-9._-]{4,128}$/; + +const REMOTE_ROSTER_TTL_MS = 15000; + +const REMOTE_MISS_BACKOFF_MS = 5000; + const ROLE_CAPSULE_HEADING_RE = /(?:^|\r?\n|\\n)# [^\r\n\\]+ role capsule(?:\r?\n|\\n|$)/i; const FORK_MEMORY_MARKER_RE = /Everything before this turn is @[A-Za-z0-9_-]+'s memory/; @@ -283,6 +297,28 @@ function resolvePluginRoot(env) { return dirname(dirname(fileURLToPath(import.meta.url))); } +function resolveConfigJsonPath(env) { + if (typeof env.PSTACK_CONFIG_DIR === "string" && env.PSTACK_CONFIG_DIR.length > 0) { + return join(env.PSTACK_CONFIG_DIR, "config.json"); + } + const pluginRoot = resolvePluginRoot(env); + if (pluginRoot && basename(dirname(pluginRoot)) === "plugins") { + return join(dirname(dirname(pluginRoot)), "config.json"); + } + if (!env.PSTACK_APPDATA_DIR && !env.PSTACK_PLUGIN_ROOT && !env.PLUGIN_ROOT) { + const home = typeof env.HOME === "string" && env.HOME.length > 0 ? env.HOME : homedir(); + return join(home, ".gemini", "config", "config.json"); + } + return null; +} + +function isPluginDisabled(env) { + const configPath = resolveConfigJsonPath(env); + if (!configPath || !existsSync(configPath)) return false; + const parsed = readJsonObject(configPath); + return parsed?.plugins?.["agy-pstack-next"]?.enabled === false; +} + function resolveOwnTranscriptPath(payload, appDataDir) { if (typeof payload.transcriptPath === "string" && payload.transcriptPath.length > 0) { return payload.transcriptPath; @@ -364,38 +400,353 @@ function transcriptContainsRoleCapsule(transcriptPath) { return false; } -function extractMembersFromDoc(doc, targetConversationId) { +function extractMembersFromDoc(doc, targetConversationId, fallbackCoordId = null) { const workerEntries = {}; let matchedCoordinator = false; + let coordId = + typeof fallbackCoordId === "string" && fallbackCoordId.length > 0 ? fallbackCoordId : null; + let hasPstackPrefixedWorker = false; + let hasTaskWorker = false; const members = doc && typeof doc === "object" ? doc.members : null; if (!members || typeof members !== "object") { - return { hasMembers: false, workerEntries, matchedCoordinator }; + return { + hasMembers: false, + workerEntries, + matchedCoordinator, + coordId, + hasPstackPrefixedWorker, + hasTaskWorker, + }; } for (const [memberName, info] of Object.entries(members)) { if (!info || typeof info !== "object") continue; const cid = info.conversation_id || info.conversationId; - if (typeof cid !== "string" || cid.length === 0) continue; if (memberName === "coordinator" || info.role === "coordinator") { - if (cid === targetConversationId) matchedCoordinator = true; + if (typeof cid === "string" && cid.length > 0) { + coordId = cid; + if (cid === targetConversationId) matchedCoordinator = true; + } continue; } - workerEntries[cid] = memberName; + if (PSTACK_WORKER_PREFIX_RE.test(memberName)) { + hasPstackPrefixedWorker = true; + } + if (!BUILTIN_SUPPORT_MEMBER_RE.test(memberName)) { + hasTaskWorker = true; + } + if (typeof cid === "string" && cid.length > 0) { + workerEntries[cid] = memberName; + } } - return { hasMembers: true, workerEntries, matchedCoordinator }; + return { + hasMembers: true, + workerEntries, + matchedCoordinator, + coordId, + hasPstackPrefixedWorker, + hasTaskWorker, + }; } -function anchorMatchesCoordinator(anchorPath, targetConversationId, ownerDirId) { - if (!existsSync(anchorPath)) return false; - const doc = readJsonObject(anchorPath); +function isManagedPstackSwarm({ + swarmDir, + coordId, + hasPstackPrefixedWorker, + hasTaskWorker, + injectedMap, + plainSwarmRoots, +}) { + const hasPstackMarker = Boolean(swarmDir && existsSync(join(swarmDir, "pstack.json"))); + const coordAlreadyManaged = Boolean((coordId && injectedMap[coordId]) || hasPstackMarker); + if (hasPstackPrefixedWorker || coordAlreadyManaged) { + return true; + } + if (coordId && plainSwarmRoots[coordId]) { + return false; + } + if (hasTaskWorker) { + return false; + } + return true; +} + +function getAnchorCoordinatorId(doc, ownerDirId) { const explicitCoord = doc.coordinator_conversation_id || doc.coordinatorConversationId || doc.coordinator_id || doc.coordinatorId; if (typeof explicitCoord === "string" && explicitCoord.length > 0) { - return explicitCoord === targetConversationId; + return explicitCoord; + } + return ownerDirId; +} + +function parseRemoteSwarmAnchor(doc) { + if (!doc || typeof doc !== "object") return null; + if (typeof doc.backend !== "string" || doc.backend.length === 0) return null; + if ( + typeof doc.swarm_id !== "string" || + doc.swarm_id.startsWith("-") || + !REMOTE_SWARM_ID_RE.test(doc.swarm_id) + ) { + return null; + } + let db = ""; + if (doc.db !== undefined && doc.db !== null && doc.db !== "") { + if (typeof doc.db !== "string" || doc.db.startsWith("-")) { + return null; + } + db = doc.db; + } + return { backend: doc.backend, swarmId: doc.swarm_id, db }; +} + +function isExecutableFile(filePath) { + try { + accessSync(filePath, fsConstants.X_OK); + return statSync(filePath).isFile(); + } catch { + return false; + } +} + +function resolveRemoteBoardCli(anchor, appDataDir, env) { + if (typeof env.PSTACK_REMOTE_SWARM_CLI === "string" && env.PSTACK_REMOTE_SWARM_CLI.length > 0) { + return env.PSTACK_REMOTE_SWARM_CLI; + } + const cfgPath = + typeof env.PSTACK_REMOTE_BOARD_CONFIG === "string" && env.PSTACK_REMOTE_BOARD_CONFIG.length > 0 + ? env.PSTACK_REMOTE_BOARD_CONFIG + : appDataDir + ? join( + appDataDir, + "builtin", + "plugins", + "swarm", + "sidecars", + "swarm_board", + "remote_board.json", + ) + : null; + if (!cfgPath || !existsSync(cfgPath)) return null; + const cfg = readJsonObject(cfgPath); + if (typeof cfg.backend !== "string" || cfg.backend.length === 0 || cfg.backend !== anchor.backend) { + return null; + } + const cliEnvName = typeof cfg.cli_env === "string" ? cfg.cli_env : ""; + const envOverride = cliEnvName ? env[cliEnvName] : ""; + if ( + typeof envOverride === "string" && + envOverride.length > 0 && + (!envOverride.includes("/") || isExecutableFile(envOverride)) + ) { + return envOverride; + } + const cliList = Array.isArray(cfg.cli) + ? cfg.cli.filter((c) => typeof c === "string" && c.length > 0) + : []; + if (cliList.length === 0) return null; + const pathDirs = String(env.PATH || process.env.PATH || "") + .split(":") + .filter(Boolean); + for (const candidate of cliList) { + const hits = candidate.includes("/") + ? [candidate] + : pathDirs.map((dir) => join(dir, candidate)); + const found = hits.find(isExecutableFile); + if (found) return found; + } + return cliList[cliList.length - 1]; +} + +function rosterContainsConversation(members, targetConversationId) { + if (!members || typeof members !== "object" || !targetConversationId) return false; + for (const info of Object.values(members)) { + if (!info || typeof info !== "object") continue; + const cid = info.conversation_id || info.conversationId; + if (cid === targetConversationId) return true; + } + return false; +} + +function resolveRemoteSwarmRoster(anchorDoc, appDataDir, cacheDir, env, targetConversationId) { + const anchor = parseRemoteSwarmAnchor(anchorDoc); + if (!anchor) return null; + const cliBin = resolveRemoteBoardCli(anchor, appDataDir, env); + if (!cliBin) return null; + + const rostersPath = join(cacheDir, "remote-rosters.json"); + const rostersCache = readJsonObject(rostersPath); + const cachedEntry = rostersCache[anchor.swarmId]; + const now = Date.now(); + const hasValidCache = + Boolean(cachedEntry) && + typeof cachedEntry === "object" && + typeof cachedEntry.fetchedAt === "number" && + Boolean(cachedEntry.members) && + typeof cachedEntry.members === "object" && + !Array.isArray(cachedEntry.members); + + if (hasValidCache) { + const age = now - cachedEntry.fetchedAt; + const inRoster = rosterContainsConversation(cachedEntry.members, targetConversationId); + if ( + (inRoster && age >= 0 && age < REMOTE_ROSTER_TTL_MS) || + (!inRoster && age >= 0 && age < REMOTE_MISS_BACKOFF_MS) + ) { + return { members: cachedEntry.members }; + } + } + + try { + const cliArgs = [ + "swarm", + "--json", + "--roster-only", + ...(anchor.db ? ["--db", anchor.db] : []), + anchor.swarmId, + ]; + const stdout = execFileSync(cliBin, cliArgs, { + encoding: "utf8", + timeout: 2500, + env: { ...env, TERM: "dumb" }, + stdio: ["ignore", "pipe", "ignore"], + }); + let matchedMembers = null; + for (const line of String(stdout || "").split(/\r?\n/)) { + const trimmed = line.trim(); + if (!trimmed) continue; + try { + const doc = JSON.parse(trimmed); + if ( + doc && + typeof doc === "object" && + doc.swarm_id === anchor.swarmId && + doc.members && + typeof doc.members === "object" && + !Array.isArray(doc.members) + ) { + matchedMembers = doc.members; + } + } catch {} + } + if (!matchedMembers) return null; + updateJsonKey(rostersPath, anchor.swarmId, { + fetchedAt: Date.now(), + members: matchedMembers, + }); + return { members: matchedMembers }; + } catch { + return null; + } +} + +function inspectSwarmDirectory(swarmDir, ownerDirId, targetConversationId, context) { + const { appDataDir, cacheDir, env, injectedMap, plainSwarmRoots, isOwnSwarmDir } = context; + const membersPath = join(swarmDir, "members.json"); + if (existsSync(membersPath)) { + const extracted = extractMembersFromDoc( + readJsonObject(membersPath), + targetConversationId, + ownerDirId, + ); + const managed = isManagedPstackSwarm({ + swarmDir, + coordId: extracted.coordId, + hasPstackPrefixedWorker: extracted.hasPstackPrefixedWorker, + hasTaskWorker: extracted.hasTaskWorker, + injectedMap, + plainSwarmRoots, + }); + if (!managed) { + const targetIsWorker = Boolean(extracted.workerEntries[targetConversationId]); + const targetInSwarm = Boolean( + targetIsWorker || + extracted.matchedCoordinator || + extracted.coordId === targetConversationId || + isOwnSwarmDir, + ); + return { + kind: "unmanaged_swarm", + targetInSwarm, + targetIsWorker, + hasUnmatchedAnchor: false, + }; + } + return { + kind: "managed_roster", + workerEntries: extracted.workerEntries, + matchedCoordinator: extracted.matchedCoordinator || isOwnSwarmDir, + hasUnmatchedAnchor: false, + }; + } + + const anchorPath = join(swarmDir, "swarm.json"); + if (!existsSync(anchorPath)) { + return { kind: "none" }; + } + + const anchorDoc = readJsonObject(anchorPath); + const anchorCoordId = getAnchorCoordinatorId(anchorDoc, ownerDirId); + const remoteRoster = resolveRemoteSwarmRoster( + anchorDoc, + appDataDir, + cacheDir, + env, + targetConversationId, + ); + if (remoteRoster) { + const extracted = extractMembersFromDoc(remoteRoster, targetConversationId, anchorCoordId); + const managed = isManagedPstackSwarm({ + swarmDir, + coordId: extracted.coordId, + hasPstackPrefixedWorker: extracted.hasPstackPrefixedWorker, + hasTaskWorker: extracted.hasTaskWorker, + injectedMap, + plainSwarmRoots, + }); + const matchesCoord = extracted.matchedCoordinator || anchorCoordId === targetConversationId; + const targetIsWorker = Boolean(extracted.workerEntries[targetConversationId]); + const targetInSwarm = Boolean( + targetIsWorker || + matchesCoord || + extracted.coordId === targetConversationId, + ); + if (!managed) { + return { + kind: "unmanaged_swarm", + targetInSwarm, + targetIsWorker, + hasUnmatchedAnchor: !targetInSwarm, + }; + } + return { + kind: "managed_roster", + workerEntries: extracted.workerEntries, + matchedCoordinator: matchesCoord, + hasUnmatchedAnchor: !targetInSwarm, + }; } - return ownerDirId === targetConversationId; + + if (anchorCoordId === targetConversationId) { + const suppressedByPlainSwarm = Boolean( + plainSwarmRoots[anchorCoordId] && + !injectedMap[anchorCoordId] && + !existsSync(join(swarmDir, "pstack.json")), + ); + if (suppressedByPlainSwarm) { + return { + kind: "unmanaged_swarm", + targetInSwarm: true, + targetIsWorker: false, + hasUnmatchedAnchor: false, + }; + } + return { kind: "anchor_coordinator" }; + } + + return { kind: "anchor_unresolved" }; } function resolveWorkerOrCoordinatorFromSwarm( @@ -404,130 +755,196 @@ function resolveWorkerOrCoordinatorFromSwarm( appDataDir, cacheDir, hasPriorInjectedCapsule, + env, + injectedMap, + plainSwarmRoots, ) { if (typeof conversationId !== "string" || conversationId.length === 0) { - return { workerName: null, isKnownCoordinator: false }; + return { workerName: null, isKnownCoordinator: false, isUnmanagedSwarmWorker: false }; } const mapPath = join(cacheDir, "member-map.json"); const cachedMap = readJsonObject(mapPath); const cachedName = cachedMap[conversationId]; if (typeof cachedName === "string" && cachedName.length > 0 && cachedName !== "coordinator") { - return { workerName: cachedName, isKnownCoordinator: false }; + return { workerName: cachedName, isKnownCoordinator: false, isUnmanagedSwarmWorker: false }; } if (!appDataDir) { - return { workerName: null, isKnownCoordinator: false }; + return { workerName: null, isKnownCoordinator: false, isUnmanagedSwarmWorker: false }; } const candidateRoots = [payload.rootConversationId, payload.parentConversationId]; const checkedRoots = new Set(); let hasAnchorWithoutMembers = false; + let skipNonWorkerCache = false; for (const rootId of candidateRoots) { - if (typeof rootId !== "string" || rootId.length === 0 || rootId === conversationId || checkedRoots.has(rootId)) { + if ( + typeof rootId !== "string" || + rootId.length === 0 || + rootId === conversationId || + checkedRoots.has(rootId) + ) { continue; } checkedRoots.add(rootId); const swarmDir = join(appDataDir, "brain", rootId, ".system_generated", "swarm"); - const membersPath = join(swarmDir, "members.json"); - if (!existsSync(membersPath)) { - const anchorPath = join(swarmDir, "swarm.json"); - if (existsSync(anchorPath)) { - if (anchorMatchesCoordinator(anchorPath, conversationId, rootId)) { - return { workerName: null, isKnownCoordinator: true }; - } - hasAnchorWithoutMembers = true; + const res = inspectSwarmDirectory(swarmDir, rootId, conversationId, { + appDataDir, + cacheDir, + env, + injectedMap, + plainSwarmRoots, + isOwnSwarmDir: false, + }); + if (res.kind === "managed_roster") { + updateJsonKeys(mapPath, res.workerEntries); + if (res.workerEntries[conversationId]) { + return { + workerName: res.workerEntries[conversationId], + isKnownCoordinator: false, + isUnmanagedSwarmWorker: false, + }; } - continue; - } - const { workerEntries, matchedCoordinator } = extractMembersFromDoc( - readJsonObject(membersPath), - conversationId, - ); - updateJsonKeys(mapPath, workerEntries); - if (workerEntries[conversationId]) { - return { workerName: workerEntries[conversationId], isKnownCoordinator: false }; - } - if (matchedCoordinator) { - return { workerName: null, isKnownCoordinator: true }; + if (res.matchedCoordinator) { + return { workerName: null, isKnownCoordinator: true, isUnmanagedSwarmWorker: false }; + } + if (res.hasUnmatchedAnchor) hasAnchorWithoutMembers = true; + } else if (res.kind === "anchor_coordinator") { + return { workerName: null, isKnownCoordinator: true, isUnmanagedSwarmWorker: false }; + } else if (res.kind === "anchor_unresolved") { + hasAnchorWithoutMembers = true; + } else if (res.kind === "unmanaged_swarm") { + if (res.targetInSwarm) { + return { + workerName: null, + isKnownCoordinator: false, + isUnmanagedSwarmWorker: Boolean(res.targetIsWorker), + }; + } + skipNonWorkerCache = true; + if (res.hasUnmatchedAnchor) hasAnchorWithoutMembers = true; } } const ownSwarmDir = join(appDataDir, "brain", conversationId, ".system_generated", "swarm"); - const ownMembersPath = join(ownSwarmDir, "members.json"); - if (existsSync(ownMembersPath)) { - const { workerEntries } = extractMembersFromDoc(readJsonObject(ownMembersPath), conversationId); - updateJsonKeys(mapPath, workerEntries); - if (workerEntries[conversationId]) { - return { workerName: workerEntries[conversationId], isKnownCoordinator: false }; + const ownRes = inspectSwarmDirectory(ownSwarmDir, conversationId, conversationId, { + appDataDir, + cacheDir, + env, + injectedMap, + plainSwarmRoots, + isOwnSwarmDir: true, + }); + if (ownRes.kind === "managed_roster") { + updateJsonKeys(mapPath, ownRes.workerEntries); + if (ownRes.workerEntries[conversationId]) { + return { + workerName: ownRes.workerEntries[conversationId], + isKnownCoordinator: false, + isUnmanagedSwarmWorker: false, + }; } - return { workerName: null, isKnownCoordinator: true }; - } - - const ownAnchorPath = join(ownSwarmDir, "swarm.json"); - if (anchorMatchesCoordinator(ownAnchorPath, conversationId, conversationId)) { - return { workerName: null, isKnownCoordinator: true }; + if (ownRes.matchedCoordinator) { + return { workerName: null, isKnownCoordinator: true, isUnmanagedSwarmWorker: false }; + } + if (ownRes.hasUnmatchedAnchor) hasAnchorWithoutMembers = true; + } else if (ownRes.kind === "anchor_coordinator") { + return { workerName: null, isKnownCoordinator: true, isUnmanagedSwarmWorker: false }; + } else if (ownRes.kind === "unmanaged_swarm") { + return { + workerName: null, + isKnownCoordinator: false, + isUnmanagedSwarmWorker: Boolean(ownRes.targetIsWorker), + }; + } else if (ownRes.kind === "anchor_unresolved") { + hasAnchorWithoutMembers = true; } const nonWorkerRootsPath = join(cacheDir, "non-worker-roots.json"); const nonWorkerRoots = readJsonObject(nonWorkerRootsPath); if (nonWorkerRoots[conversationId]) { - return { workerName: null, isKnownCoordinator: false }; + return { workerName: null, isKnownCoordinator: false, isUnmanagedSwarmWorker: false }; } const ownTranscriptPath = resolveOwnTranscriptPath(payload, appDataDir); if (transcriptIsUnforkedUserRoot(ownTranscriptPath, hasPriorInjectedCapsule)) { - return { workerName: null, isKnownCoordinator: false }; + return { workerName: null, isKnownCoordinator: false, isUnmanagedSwarmWorker: false }; } const brainDir = join(appDataDir, "brain"); if (!existsSync(brainDir)) { - return { workerName: null, isKnownCoordinator: false }; + return { workerName: null, isKnownCoordinator: false, isUnmanagedSwarmWorker: false }; } let entries = []; try { entries = readdirSync(brainDir, { withFileTypes: true }); } catch { - return { workerName: null, isKnownCoordinator: false }; + return { workerName: null, isKnownCoordinator: false, isUnmanagedSwarmWorker: false }; } const discoveredWorkers = {}; let matchedCoordinator = false; + let matchedUnmanagedSwarm = false; + let matchedUnmanagedWorker = false; for (const entry of entries) { - if ((!entry.isDirectory() && !entry.isSymbolicLink()) || entry.name === conversationId || checkedRoots.has(entry.name)) { + if ( + (!entry.isDirectory() && !entry.isSymbolicLink()) || + entry.name === conversationId || + checkedRoots.has(entry.name) + ) { continue; } const swarmDir = join(brainDir, entry.name, ".system_generated", "swarm"); - const membersPath = join(swarmDir, "members.json"); - if (!existsSync(membersPath)) { - const anchorPath = join(swarmDir, "swarm.json"); - if (existsSync(anchorPath)) { - if (anchorMatchesCoordinator(anchorPath, conversationId, entry.name)) { - matchedCoordinator = true; - } else { - hasAnchorWithoutMembers = true; - } - } - continue; + const res = inspectSwarmDirectory(swarmDir, entry.name, conversationId, { + appDataDir, + cacheDir, + env, + injectedMap, + plainSwarmRoots, + isOwnSwarmDir: false, + }); + if (res.kind === "managed_roster") { + Object.assign(discoveredWorkers, res.workerEntries); + if (res.matchedCoordinator) matchedCoordinator = true; + if (res.hasUnmatchedAnchor) hasAnchorWithoutMembers = true; + } else if (res.kind === "anchor_coordinator") { + matchedCoordinator = true; + } else if (res.kind === "anchor_unresolved") { + hasAnchorWithoutMembers = true; + } else if (res.kind === "unmanaged_swarm") { + if (res.targetInSwarm) { + matchedUnmanagedSwarm = true; + if (res.targetIsWorker) matchedUnmanagedWorker = true; + } + if (res.hasUnmatchedAnchor) hasAnchorWithoutMembers = true; } - const extracted = extractMembersFromDoc(readJsonObject(membersPath), conversationId); - Object.assign(discoveredWorkers, extracted.workerEntries); - if (extracted.matchedCoordinator) matchedCoordinator = true; } updateJsonKeys(mapPath, discoveredWorkers); if (discoveredWorkers[conversationId]) { - return { workerName: discoveredWorkers[conversationId], isKnownCoordinator: false }; + return { + workerName: discoveredWorkers[conversationId], + isKnownCoordinator: false, + isUnmanagedSwarmWorker: false, + }; } if (matchedCoordinator) { - return { workerName: null, isKnownCoordinator: true }; + return { workerName: null, isKnownCoordinator: true, isUnmanagedSwarmWorker: false }; + } + if (matchedUnmanagedSwarm) { + return { + workerName: null, + isKnownCoordinator: false, + isUnmanagedSwarmWorker: matchedUnmanagedWorker, + }; } - if (!hasAnchorWithoutMembers) { + if (!hasAnchorWithoutMembers && !skipNonWorkerCache) { updateJsonKey(nonWorkerRootsPath, conversationId, true); } - return { workerName: null, isKnownCoordinator: false }; + return { workerName: null, isKnownCoordinator: false, isUnmanagedSwarmWorker: false }; } function classifyWorkerMember(memberName) { @@ -578,13 +995,39 @@ function classifySession(payload, env) { typeof injectedMap[conversationId] === "string" && injectedMap[conversationId].length > 0; - const { workerName, isKnownCoordinator } = resolveWorkerOrCoordinatorFromSwarm( - conversationId, - payload, - appDataDir, - cacheDir, - alreadyInjected, - ); + const matchesSlashCommand = + typeof payload.lastUserInput === "string" && PSTACK_SLASH_COMMAND_RE.test(payload.lastUserInput); + const forcedCoordinator = env.PSTACK_FORCE_COORDINATOR === "1"; + const matchesBuiltinSwarmSlash = + typeof payload.lastUserInput === "string" && BUILTIN_SWARM_SLASH_RE.test(payload.lastUserInput); + + const plainSwarmRootsPath = join(cacheDir, "plain-swarm-roots.json"); + const plainSwarmRoots = readJsonObject(plainSwarmRootsPath); + if (conversationId.length > 0) { + if (matchesSlashCommand || forcedCoordinator) { + if (plainSwarmRoots[conversationId]) { + plainSwarmRoots[conversationId] = false; + updateJsonKey(plainSwarmRootsPath, conversationId, false); + } + } else if (matchesBuiltinSwarmSlash && !alreadyInjected) { + if (!plainSwarmRoots[conversationId]) { + plainSwarmRoots[conversationId] = true; + updateJsonKey(plainSwarmRootsPath, conversationId, true); + } + } + } + + const { workerName, isKnownCoordinator, isUnmanagedSwarmWorker } = + resolveWorkerOrCoordinatorFromSwarm( + conversationId, + payload, + appDataDir, + cacheDir, + alreadyInjected, + env, + injectedMap, + plainSwarmRoots, + ); if (workerName) { const { kind, capsule } = classifyWorkerMember(workerName); @@ -599,9 +1042,17 @@ function classifySession(payload, env) { }; } - const matchesSlashCommand = - typeof payload.lastUserInput === "string" && PSTACK_SLASH_COMMAND_RE.test(payload.lastUserInput); - const forcedCoordinator = env.PSTACK_FORCE_COORDINATOR === "1"; + if (isUnmanagedSwarmWorker && !alreadyInjected && !forcedCoordinator) { + return { + sessionKind: "unmanaged", + kind: "unmanaged", + memberName: null, + capsule: null, + appDataDir, + cacheDir, + injectedMap, + }; + } if ( isKnownCoordinator || @@ -2305,6 +2756,138 @@ function resolveSimpleVarBinding(code, expr, isPython) { return isPython ? parseStaticPyString(lastRhs) : parseStaticJsString(lastRhs); } +function resolveStaticArgValue(argExpr, code, isPython) { + const lit = isPython ? parseStaticPyString(argExpr || "") : parseStaticJsString(argExpr || ""); + if (lit.ok) return lit.value; + const bound = resolveSimpleVarBinding(code, argExpr || "", isPython); + if (bound && bound.ok) return bound.value; + return null; +} + +function resolveStaticJoinOrTemplate(expr, code, isPython) { + const trimmed = String(expr || "").trim(); + if (!trimmed || trimmed.includes("..")) return null; + + const joinMatch = trimmed.match( + /^(?:path\s*\.\s*join|os\s*\.\s*path\s*\.\s*join|join)\s*\(([\s\S]*)\)$/, + ); + if (joinMatch) { + const innerArgs = parseCallArguments(`(${joinMatch[1]})`, 0); + if (!innerArgs || innerArgs.length === 0) return null; + const rootVal = resolveStaticArgValue(innerArgs[0], code, isPython); + if (rootVal === null) return null; + const parts = [rootVal]; + for (let i = 1; i < innerArgs.length; i += 1) { + const staticPart = resolveStaticArgValue(innerArgs[i], code, isPython); + if (staticPart !== null) { + parts.push(staticPart); + continue; + } + const subTemplate = resolveStaticJoinOrTemplate(innerArgs[i], code, isPython); + if (subTemplate !== null && !isAbsolute(subTemplate)) { + parts.push(subTemplate); + continue; + } + return null; + } + return join(...parts); + } + + if (!isPython && trimmed.startsWith("`") && trimmed.endsWith("`") && trimmed.length >= 2) { + const inner = trimmed.slice(1, -1); + let out = ""; + let i = 0; + while (i < inner.length) { + if (inner[i] === "\\" && i + 1 < inner.length) { + out += inner.slice(i, i + 2); + i += 2; + continue; + } + if (inner[i] === "`") return null; + if (inner[i] === "$" && inner[i + 1] === "{") { + const closeIdx = findMatchingBrace(inner, i + 1); + if (closeIdx < 0) return null; + const slot = inner.slice(i + 2, closeIdx).trim(); + const bound = resolveSimpleVarBinding(code, slot, false); + if (bound && bound.ok) { + out += bound.value; + } else if ( + out.length > 0 && + !out.endsWith("/") && + !out.endsWith("\\") && + !out.endsWith(".") && + !/[/\\]/.test(slot) + ) { + out += "0"; + } else { + return null; + } + i = closeIdx + 1; + continue; + } + out += inner[i]; + i += 1; + } + return unescapeSimpleLiteral(out, false); + } + + if (isPython && /^[fF](?:'''[\s\S]*'''|"""[\s\S]*"""|'[^']*'|"[^"]*")$/.test(trimmed)) { + const body = trimmed.slice(1); + const quote = body.startsWith("'''") || body.startsWith('"""') ? body.slice(0, 3) : body[0]; + const inner = body.slice(quote.length, body.length - quote.length); + let out = ""; + let i = 0; + while (i < inner.length) { + if (inner[i] === "\\" && i + 1 < inner.length) { + out += inner.slice(i, i + 2); + i += 2; + continue; + } + if (inner[i] === "{") { + const closeIdx = findMatchingBrace(inner, i); + if (closeIdx < 0) return null; + const slot = inner.slice(i + 1, closeIdx).trim(); + const bound = resolveSimpleVarBinding(code, slot, true); + if (bound && bound.ok) { + out += bound.value; + } else if ( + out.length > 0 && + !out.endsWith("/") && + !out.endsWith("\\") && + !out.endsWith(".") && + !/[/\\]/.test(slot) + ) { + out += "0"; + } else { + return null; + } + i = closeIdx + 1; + continue; + } + out += inner[i]; + i += 1; + } + return unescapeSimpleLiteral(out, false); + } + + return null; +} + +function extractJsObjectProperty(objExpr, propName) { + const trimmed = String(objExpr || "").trim(); + if (!trimmed.startsWith("{") || !trimmed.endsWith("}")) return null; + const props = parseCallArguments(`(${trimmed.slice(1, -1)})`, 0); + if (!props) return null; + const propEsc = propName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + const kvRe = new RegExp(`^(?:['"]${propEsc}['"]|${propEsc})\\s*:\\s*([\\s\\S]+)$`); + for (const prop of props) { + if (prop === propName) return propName; + const m = prop.match(kvRe); + if (m) return m[1].trim(); + } + return null; +} + function checkInlineNodeFs(code, allowPath, options = {}) { const { allowDynamicPaths = false, roleLabel = "read-only ro-* workers" } = options; @@ -2343,15 +2926,23 @@ function checkInlineNodeFs(code, allowPath, options = {}) { } const checkNodePathArg = (argExpr, opts) => { - const lit = parseStaticJsString(argExpr || ""); + const rawExpr = String(argExpr || ""); + if (/\.system_generated(?:[/\\'"`]|$)/.test(rawExpr)) { + return false; + } + const lit = parseStaticJsString(rawExpr); if (lit.ok) { return allowPath(lit.value, opts); } - const bound = resolveSimpleVarBinding(code, argExpr || "", false); + const bound = resolveSimpleVarBinding(code, rawExpr, false); if (bound && bound.ok) { return allowPath(bound.value, opts); } - if (isSafeTmpTemplateOrJoin(argExpr || "", code, allowPath)) { + const joined = resolveStaticJoinOrTemplate(rawExpr, code, false); + if (joined !== null) { + return allowPath(joined, opts); + } + if (isSafeTmpTemplateOrJoin(rawExpr, code, allowPath)) { return true; } return allowDynamicPaths; @@ -2388,36 +2979,98 @@ function checkInlineNodeFs(code, allowPath, options = {}) { } if (NODE_SINGLE_PATH_FS_APIS.has(fnName)) { - const allowRoot = fnName === "mkdirSync" || fnName === "mkdir"; + const isMkdir = fnName === "mkdirSync" || fnName === "mkdir"; + const forbidRoArtifact = + fnName === "rmdirSync" || + fnName === "rmdir" || + fnName === "mkdtempSync" || + fnName === "mkdtemp" || + fnName === "chmodSync" || + fnName === "chmod" || + fnName === "chownSync" || + fnName === "chown"; const allowNull = fnName === "writeFileSync" || fnName === "writeFile" || fnName === "appendFileSync" || fnName === "appendFile" || fnName === "createWriteStream"; - if (!checkNodePathArg(callArgs[0], { allowRootEqual: allowRoot, allowDevNull: allowNull })) { + if ( + !checkNodePathArg(callArgs[0], { + allowRootEqual: isMkdir, + allowDevNull: allowNull, + allowArtifactDir: isMkdir, + allowArtifactRoot: isMkdir, + forbidReadOnlyArtifact: forbidRoArtifact, + }) + ) { return `Inline Node fs.${fnName} outside allowed roots is blocked for ${roleLabel}.`; } continue; } if (NODE_COPY_FS_APIS.has(fnName)) { - if (!checkNodePathArg(callArgs[1], { allowRootEqual: true, allowDevNull: true })) { + const forbidRoArtifact = fnName === "cpSync" || fnName === "cp"; + const srcVal = resolveStaticArgValue(callArgs[0] || "", code, false); + const srcIsImg = Boolean(srcVal && /\.(?:png|jpe?g|webp)$/i.test(srcVal)); + if ( + !checkNodePathArg(callArgs[1], { + allowRootEqual: true, + allowDevNull: true, + allowArtifactDir: false, + forbidReadOnlyArtifact: forbidRoArtifact && !srcIsImg, + }) + ) { return `Inline Node fs.${fnName} destination outside allowed roots is blocked for ${roleLabel}.`; } continue; } if (NODE_TWO_PATH_FS_APIS.has(fnName)) { + const isLink = + fnName === "symlinkSync" || + fnName === "symlink" || + fnName === "linkSync" || + fnName === "link"; if ( - !checkNodePathArg(callArgs[0], { allowRootEqual: false, allowDevNull: false }) || - !checkNodePathArg(callArgs[1], { allowRootEqual: true, allowDevNull: false }) + !checkNodePathArg(callArgs[0], { + allowRootEqual: false, + allowDevNull: false, + forbidReadOnlyArtifact: isLink, + }) || + !checkNodePathArg(callArgs[1], { + allowRootEqual: true, + allowDevNull: false, + allowArtifactDir: false, + forbidReadOnlyArtifact: isLink, + }) ) { return `Inline Node fs.${fnName} outside allowed roots is blocked for ${roleLabel}.`; } } } + const screenshotRe = /\.\s*screenshot\s*\(/g; + while ((match = screenshotRe.exec(code)) !== null) { + const openParenIdx = match.index + match[0].length - 1; + const callArgs = parseCallArguments(code, openParenIdx); + if (!callArgs) { + if (!allowDynamicPaths) { + return `Unparseable .screenshot() call in inline Node script is blocked for ${roleLabel}.`; + } + continue; + } + if (callArgs.length >= 1) { + const pathProp = extractJsObjectProperty(callArgs[0], "path"); + if ( + pathProp !== null && + !checkNodePathArg(pathProp, { allowRootEqual: false, allowDevNull: false }) + ) { + return `Inline Node .screenshot() path outside allowed roots is blocked for ${roleLabel}.`; + } + } + } + return null; } @@ -2474,15 +3127,23 @@ function checkInlinePythonFs(code, allowPath, options = {}) { } const checkPyPathArg = (argExpr, opts) => { - const lit = parseStaticPyString(argExpr || ""); + const rawExpr = String(argExpr || ""); + if (/\.system_generated(?:[/\\'"`]|$)/.test(rawExpr)) { + return false; + } + const lit = parseStaticPyString(rawExpr); if (lit.ok) { return allowPath(lit.value, opts); } - const bound = resolveSimpleVarBinding(code, argExpr || "", true); + const bound = resolveSimpleVarBinding(code, rawExpr, true); if (bound && bound.ok) { return allowPath(bound.value, opts); } - if (isSafeTmpTemplateOrJoin(argExpr || "", code, allowPath)) { + const joined = resolveStaticJoinOrTemplate(rawExpr, code, true); + if (joined !== null) { + return allowPath(joined, opts); + } + if (isSafeTmpTemplateOrJoin(rawExpr, code, allowPath)) { return true; } return allowDynamicPaths; @@ -2516,12 +3177,34 @@ function checkInlinePythonFs(code, allowPath, options = {}) { continue; } const ctorArgs = parseCallArguments(`(${ctorMatch[1]})`, 0); - const allowRoot = method === "mkdir"; - if (!ctorArgs || ctorArgs.length !== 1 || !checkPyPathArg(ctorArgs[0], { allowRootEqual: allowRoot, allowDevNull: false })) { + const isMkdir = method === "mkdir"; + const forbidRo = + method === "symlink_to" || + method === "hardlink_to" || + method === "rmdir" || + method === "chmod" || + method === "lchmod"; + if ( + !ctorArgs || + ctorArgs.length !== 1 || + !checkPyPathArg(ctorArgs[0], { + allowRootEqual: isMkdir, + allowDevNull: false, + allowArtifactDir: isMkdir, + allowArtifactRoot: isMkdir, + forbidReadOnlyArtifact: forbidRo, + }) + ) { return `Inline Python Path.${method}() outside allowed roots is blocked for ${roleLabel}.`; } if (method === "rename" || method === "replace") { - if (!checkPyPathArg(methodArgs[0] || "", { allowRootEqual: true, allowDevNull: false })) { + if ( + !checkPyPathArg(methodArgs[0] || "", { + allowRootEqual: true, + allowDevNull: false, + allowArtifactDir: false, + }) + ) { return `Inline Python Path.${method}() target outside allowed roots is blocked for ${roleLabel}.`; } } @@ -2565,26 +3248,77 @@ function checkInlinePythonFs(code, allowPath, options = {}) { const { positionals } = splitPythonCallArgs(callArgs); if (["copy", "copy2", "copyfile", "copytree"].includes(fnName)) { if (!qualifier && !/\bshutil\b/.test(code)) continue; - if (!checkPyPathArg(positionals[1] || "", { allowRootEqual: true, allowDevNull: true })) { + const srcVal = resolveStaticArgValue(positionals[0] || "", code, true); + const srcIsImg = Boolean(srcVal && /\.(?:png|jpe?g|webp)$/i.test(srcVal)); + const allowImgDir = srcIsImg && (fnName === "copy" || fnName === "copy2"); + if ( + !checkPyPathArg(positionals[1] || "", { + allowRootEqual: true, + allowDevNull: true, + allowArtifactDir: allowImgDir, + allowArtifactRoot: allowImgDir, + forbidReadOnlyArtifact: fnName === "copytree", + }) + ) { return `Inline Python ${fnName}() destination outside allowed roots is blocked for ${roleLabel}.`; } continue; } if (["rename", "renames", "replace", "move", "symlink", "link"].includes(fnName)) { + const isLink = fnName === "symlink" || fnName === "link"; if ( - !checkPyPathArg(positionals[0] || "", { allowRootEqual: false, allowDevNull: false }) || - !checkPyPathArg(positionals[1] || "", { allowRootEqual: true, allowDevNull: false }) + !checkPyPathArg(positionals[0] || "", { + allowRootEqual: false, + allowDevNull: false, + forbidReadOnlyArtifact: isLink, + }) || + !checkPyPathArg(positionals[1] || "", { + allowRootEqual: true, + allowDevNull: false, + allowArtifactDir: false, + forbidReadOnlyArtifact: isLink, + }) ) { return `Inline Python ${fnName}() outside allowed roots is blocked for ${roleLabel}.`; } continue; } - const allowRoot = fnName === "mkdir" || fnName === "makedirs"; - if (!checkPyPathArg(positionals[0] || "", { allowRootEqual: allowRoot, allowDevNull: false })) { + const isMkdir = fnName === "mkdir" || fnName === "makedirs"; + const forbidRo = ["rmdir", "removedirs", "rmtree", "chmod", "chown"].includes(fnName); + if ( + !checkPyPathArg(positionals[0] || "", { + allowRootEqual: isMkdir, + allowDevNull: false, + allowArtifactDir: isMkdir, + allowArtifactRoot: isMkdir, + forbidReadOnlyArtifact: forbidRo, + }) + ) { return `Inline Python ${fnName}() outside allowed roots is blocked for ${roleLabel}.`; } } + const screenshotRe = /\.\s*screenshot\s*\(/g; + while ((match = screenshotRe.exec(code)) !== null) { + const openParenIdx = match.index + match[0].length - 1; + const callArgs = parseCallArguments(code, openParenIdx); + if (!callArgs) { + if (!allowDynamicPaths) { + return `Unparseable .screenshot() call in inline Python script is blocked for ${roleLabel}.`; + } + continue; + } + const { positionals, kwargs } = splitPythonCallArgs(callArgs); + const pathExpr = kwargs.path ?? positionals[0] ?? null; + if ( + pathExpr !== null && + pathExpr !== "None" && + !checkPyPathArg(pathExpr, { allowRootEqual: false, allowDevNull: false }) + ) { + return `Inline Python .screenshot() path outside allowed roots is blocked for ${roleLabel}.`; + } + } + return null; } @@ -3085,28 +3819,48 @@ function checkSharedTargetConfinement(inv, allowPath, roleLabel, validateInnerTo const { cmd, args } = inv; if (cmd === "mkdir") { const paths = extractPathsSkippingValueFlags(args, new Set(["-m", "--mode"])); - if (paths.length === 0 || paths.some((p) => !allowPath(p, { allowRootEqual: true, allowDevNull: false }))) { + if ( + paths.length === 0 || + paths.some( + (p) => + !allowPath(p, { + allowRootEqual: true, + allowDevNull: false, + allowArtifactDir: true, + allowArtifactRoot: true, + }), + ) + ) { return `Command 'mkdir' outside allowed paths is blocked for ${roleLabel}.`; } return null; } if (cmd === "touch") { const paths = extractPathsSkippingValueFlags(args, new Set(["-d", "--date", "-r", "--reference", "-t"])); - if (paths.length === 0 || paths.some((p) => !allowPath(p, { allowRootEqual: false, allowDevNull: false }))) { + if ( + paths.length === 0 || + paths.some((p) => !allowPath(p, { allowRootEqual: false, allowDevNull: false, forbidReadOnlyArtifact: true })) + ) { return `Command 'touch' outside allowed paths is blocked for ${roleLabel}.`; } return null; } if (cmd === "chmod") { const paths = extractChmodTargets(args); - if (paths.length === 0 || paths.some((p) => !allowPath(p, { allowRootEqual: false, allowDevNull: false }))) { + if ( + paths.length === 0 || + paths.some((p) => !allowPath(p, { allowRootEqual: false, allowDevNull: false, forbidReadOnlyArtifact: true })) + ) { return `Command 'chmod' outside allowed paths is blocked for ${roleLabel}.`; } return null; } if (cmd === "truncate") { const paths = extractPathsSkippingValueFlags(args, new Set(["-s", "--size", "-r", "--reference"])); - if (paths.length === 0 || paths.some((p) => !allowPath(p, { allowRootEqual: false, allowDevNull: false }))) { + if ( + paths.length === 0 || + paths.some((p) => !allowPath(p, { allowRootEqual: false, allowDevNull: false, forbidReadOnlyArtifact: true })) + ) { return `Command 'truncate' outside allowed paths is blocked for ${roleLabel}.`; } return null; @@ -3123,7 +3877,10 @@ function checkSharedTargetConfinement(inv, allowPath, roleLabel, validateInnerTo } if (cmd === "install") { const spec = extractInstallTargets(args); - if (!spec.valid || spec.targets.some((t) => !allowPath(t, { allowRootEqual: true, allowDevNull: false }))) { + if ( + !spec.valid || + spec.targets.some((t) => !allowPath(t, { allowRootEqual: true, allowDevNull: false, forbidReadOnlyArtifact: true })) + ) { return `Command 'install' targeting outside allowed paths is blocked for ${roleLabel}.`; } return null; @@ -3132,7 +3889,7 @@ function checkSharedTargetConfinement(inv, allowPath, roleLabel, validateInnerTo const { fileTargets, dirTargets } = extractCurlWriteTargets(args); if ( fileTargets.some((f) => !allowPath(f, { allowRootEqual: false, allowDevNull: true })) || - dirTargets.some((d) => !allowPath(d, { allowRootEqual: true, allowDevNull: false })) + dirTargets.some((d) => !allowPath(d, { allowRootEqual: true, allowDevNull: false, forbidReadOnlyArtifact: true })) ) { return `Command 'curl' writing outside allowed paths is blocked for ${roleLabel}.`; } @@ -3142,7 +3899,7 @@ function checkSharedTargetConfinement(inv, allowPath, roleLabel, validateInnerTo const { fileTargets, dirTargets } = extractWgetWriteTargets(args); if ( fileTargets.some((f) => !allowPath(f, { allowRootEqual: false, allowDevNull: true })) || - dirTargets.some((d) => !allowPath(d, { allowRootEqual: true, allowDevNull: false })) + dirTargets.some((d) => !allowPath(d, { allowRootEqual: true, allowDevNull: false, forbidReadOnlyArtifact: true })) ) { return `Command 'wget' writing outside allowed paths is blocked for ${roleLabel}.`; } @@ -3151,8 +3908,8 @@ function checkSharedTargetConfinement(inv, allowPath, roleLabel, validateInnerTo if (cmd === "tar") { const { fileTargets, dirTargets } = extractTarWriteTargets(args); if ( - fileTargets.some((f) => !allowPath(f, { allowRootEqual: false, allowDevNull: true })) || - dirTargets.some((d) => !allowPath(d, { allowRootEqual: true, allowDevNull: false })) + fileTargets.some((f) => !allowPath(f, { allowRootEqual: false, allowDevNull: true, forbidReadOnlyArtifact: true })) || + dirTargets.some((d) => !allowPath(d, { allowRootEqual: true, allowDevNull: false, forbidReadOnlyArtifact: true })) ) { return `Command 'tar' writing outside allowed paths is blocked for ${roleLabel}.`; } @@ -3160,7 +3917,7 @@ function checkSharedTargetConfinement(inv, allowPath, roleLabel, validateInnerTo } if (cmd === "unzip") { const dirTargets = extractUnzipWriteTargets(args); - if (dirTargets.some((d) => !allowPath(d, { allowRootEqual: true, allowDevNull: false }))) { + if (dirTargets.some((d) => !allowPath(d, { allowRootEqual: true, allowDevNull: false, forbidReadOnlyArtifact: true }))) { return `Command 'unzip' extracting outside allowed paths is blocked for ${roleLabel}.`; } return null; @@ -3171,7 +3928,7 @@ function checkSharedTargetConfinement(inv, allowPath, roleLabel, validateInnerTo if (/^(?:[A-Za-z0-9._-]+@)?[A-Za-z0-9._-]+:/.test(spec.destination) || spec.destination.startsWith("rsync://")) { return `Command 'rsync' to remote destination is blocked for ${roleLabel}.`; } - if (!allowPath(spec.destination, { allowRootEqual: true, allowDevNull: false })) { + if (!allowPath(spec.destination, { allowRootEqual: true, allowDevNull: false, forbidReadOnlyArtifact: true })) { return `Command 'rsync' targeting outside allowed paths is blocked for ${roleLabel}.`; } } @@ -3179,10 +3936,21 @@ function checkSharedTargetConfinement(inv, allowPath, roleLabel, validateInnerTo } if (cmd === "find") { const { searchRoots, hasDelete, fprintTargets, execCommands } = extractFindEffects(args); - if (hasDelete && searchRoots.some((r) => !allowPath(r, { allowRootEqual: true, allowDevNull: false }))) { + if ( + hasDelete && + searchRoots.some( + (r) => + !allowPath(r, { + allowRootEqual: true, + allowDevNull: false, + forbidReadOnlyArtifact: true, + isRecursiveDelete: true, + }), + ) + ) { return `Command 'find -delete' outside allowed paths is blocked for ${roleLabel}.`; } - if (fprintTargets.some((f) => !allowPath(f, { allowRootEqual: false, allowDevNull: true }))) { + if (fprintTargets.some((f) => !allowPath(f, { allowRootEqual: false, allowDevNull: true, forbidReadOnlyArtifact: true }))) { return `Command 'find -fprint/-fls' outside allowed paths is blocked for ${roleLabel}.`; } for (const innerTokens of execCommands) { @@ -3476,30 +4244,50 @@ function isMutatingReadOnlyInvocation(inv, allowReadOnlyTempPath, validateInnerT paths.length === 0 || paths.some((p) => !allowReadOnlyTempPath(p, { allowRootEqual: false, allowDevNull: false })) ) { - return `Filesystem command '${cmd}' outside canonical temp roots is blocked for read-only ro-* workers.`; + return `Filesystem command '${cmd}' outside canonical temp roots or allowed artifact screenshot paths is blocked for read-only ro-* workers.`; } return null; } if (cmd === "cp") { const cpSpec = extractCpOrMvSpec(args); + const allSourcesImages = + cpSpec.sources.length > 0 && cpSpec.sources.every((s) => /\.(?:png|jpe?g|webp)$/i.test(s)); if ( !cpSpec.valid || - cpSpec.destinations.some((d) => !allowReadOnlyTempPath(d, { allowRootEqual: true, allowDevNull: true })) + cpSpec.destinations.some( + (d) => + !allowReadOnlyTempPath(d, { + allowRootEqual: true, + allowDevNull: true, + allowArtifactDir: allSourcesImages, + allowArtifactRoot: allSourcesImages, + }), + ) ) { - return "Filesystem command 'cp' targeting paths outside canonical temp roots is blocked for read-only ro-* workers."; + return "Filesystem command 'cp' targeting paths outside canonical temp roots or allowed artifact screenshot paths is blocked for read-only ro-* workers."; } return null; } if (cmd === "mv") { const mvSpec = extractCpOrMvSpec(args); + const allSourcesImages = + mvSpec.sources.length > 0 && mvSpec.sources.every((s) => /\.(?:png|jpe?g|webp)$/i.test(s)); if ( !mvSpec.valid || mvSpec.sources.some((s) => !allowReadOnlyTempPath(s, { allowRootEqual: false, allowDevNull: false })) || - mvSpec.destinations.some((d) => !allowReadOnlyTempPath(d, { allowRootEqual: true, allowDevNull: false })) + mvSpec.destinations.some( + (d) => + !allowReadOnlyTempPath(d, { + allowRootEqual: true, + allowDevNull: false, + allowArtifactDir: allSourcesImages, + allowArtifactRoot: allSourcesImages, + }), + ) ) { - return "Filesystem command 'mv' outside canonical temp roots is blocked for read-only ro-* workers."; + return "Filesystem command 'mv' outside canonical temp roots or allowed artifact screenshot paths is blocked for read-only ro-* workers."; } return null; } @@ -3507,7 +4295,7 @@ function isMutatingReadOnlyInvocation(inv, allowReadOnlyTempPath, validateInnerT if (cmd === "tee") { const files = extractPositionalPaths(args); if (files.some((f) => !allowReadOnlyTempPath(f, { allowRootEqual: false, allowDevNull: true }))) { - return "Command 'tee' targeting paths outside /dev/null or canonical temp roots is blocked for read-only ro-* workers."; + return "Command 'tee' targeting paths outside /dev/null, canonical temp roots, or allowed artifact screenshot paths is blocked for read-only ro-* workers."; } return null; } @@ -3644,9 +4432,19 @@ function checkAuthorShellConfinement(inv, allowAuthorShellPath, resolveForBase, if (cmd === "rm" || cmd === "unlink" || cmd === "rmdir") { const paths = extractPositionalPaths(args); + const hasRecursiveFlag = + cmd === "rm" && + args.some((a) => a === "--recursive" || (/^-[A-Za-z]+$/.test(a) && /[rR]/.test(a))); if ( paths.length === 0 || - paths.some((p) => !allowAuthorShellPath(p, { allowRootEqual: false, allowDevNull: false })) + paths.some( + (p) => + !allowAuthorShellPath(p, { + allowRootEqual: false, + allowDevNull: false, + isRecursiveDelete: hasRecursiveFlag, + }), + ) ) { return `Command '${cmd}' targeting a path outside confined worker worktree, artifact directory, or canonical temp roots is blocked.`; } @@ -3769,6 +4567,10 @@ function extractMcpToolName(toolName, args) { } function handleSessionOrInvocation(payload, env) { + if (isPluginDisabled(env)) { + return {}; + } + const session = classifySession(payload, env, ""); if (session.sessionKind === "unmanaged" || !session.capsule) { return {}; @@ -3820,24 +4622,62 @@ function parseToolArgs(rawArgs) { return typeof rawArgs === "object" ? rawArgs : {}; } -function resolveWorkerConfinementRoots(payload, env) { +function isSafeConversationId(id) { + return ( + typeof id === "string" && + id.length > 0 && + !/[/\\]/.test(id) && + id !== "." && + id !== ".." + ); +} + +function resolveWorkerConfinementRoots(payload, env, appDataDir) { const hasValidCwd = typeof payload.cwd === "string" && payload.cwd.length > 0 && existsSync(payload.cwd); const realCwd = hasValidCwd ? realpathSync(payload.cwd) : null; const fallbackBaseDir = realCwd || process.cwd(); + const rawArtifactDir = + typeof payload.artifactDirectoryPath === "string" && payload.artifactDirectoryPath.length > 0 + ? payload.artifactDirectoryPath + : typeof appDataDir === "string" && appDataDir.length > 0 && isSafeConversationId(payload.conversationId) + ? join(appDataDir, "brain", payload.conversationId) + : ""; const realArtifact = - typeof payload.artifactDirectoryPath === "string" && - payload.artifactDirectoryPath.length > 0 && - existsSync(payload.artifactDirectoryPath) - ? realpathSync(payload.artifactDirectoryPath) - : typeof payload.artifactDirectoryPath === "string" && payload.artifactDirectoryPath.length > 0 - ? resolveRealTargetPath(payload.artifactDirectoryPath, fallbackBaseDir) - : null; + rawArtifactDir.length > 0 + ? existsSync(rawArtifactDir) + ? realpathSync(rawArtifactDir) + : resolveRealTargetPath(rawArtifactDir, fallbackBaseDir) + : null; const canonicalTempRoots = getCanonicalTempRoots(env); return { hasValidCwd, realCwd, fallbackBaseDir, realArtifact, canonicalTempRoots }; } +function isSystemGeneratedArtifactPath(resolvedPath, realArtifact) { + if (!resolvedPath || !realArtifact) return false; + return isInsideOrEqual(resolvedPath, join(realArtifact, ".system_generated")); +} + +function isAllowedReadOnlyArtifactPath( + resolvedPath, + realArtifact, + realCwd, + { allowDirectory = false } = {}, +) { + if (!resolvedPath || !realArtifact) return false; + if (!isStrictlyInside(resolvedPath, realArtifact)) return false; + if (isSystemGeneratedArtifactPath(resolvedPath, realArtifact)) return false; + if (realCwd && isInsideOrEqual(resolvedPath, realCwd)) return false; + if (/\.(?:png|jpe?g|webp)$/i.test(resolvedPath)) return true; + if (allowDirectory === true && extname(resolvedPath) === "") return true; + return false; +} + function handlePreToolUse(payload, env) { + if (isPluginDisabled(env)) { + return { decision: "allow" }; + } + const toolCall = payload.toolCall && typeof payload.toolCall === "object" ? payload.toolCall : {}; const toolName = normalizeToolName(toolCall.name); const args = parseToolArgs(toolCall.args); @@ -3856,7 +4696,7 @@ function handlePreToolUse(payload, env) { const { kind, memberName } = session; const { hasValidCwd, realCwd, fallbackBaseDir, realArtifact, canonicalTempRoots } = - resolveWorkerConfinementRoots(payload, env); + resolveWorkerConfinementRoots(payload, env, session.appDataDir); if (kind === "readonly") { if (toolName === "edit_file" || toolName === "write_file") { @@ -3868,8 +4708,22 @@ function handlePreToolUse(payload, env) { }; } const realTarget = resolveRealTargetPath(rawTarget, fallbackBaseDir); + if (!realTarget || isSystemGeneratedArtifactPath(realTarget, realArtifact)) { + return { + decision: "deny", + reason: `Read-only worker (${memberName || "ro-*"}) cannot call ${toolName} on protected or unresolvable path '${rawTarget}'.`, + }; + } + if (realArtifact && isInsideOrEqual(realTarget, realArtifact)) { + if (toolName === "write_file" && isAllowedReadOnlyArtifactPath(realTarget, realArtifact, realCwd)) { + return { decision: "allow" }; + } + return { + decision: "deny", + reason: `Read-only worker (${memberName || "ro-*"}) can only write screenshot image files (.png, .jpg, .jpeg, .webp) via write_file inside its artifact directory.`, + }; + } if ( - !realTarget || !isInsideCanonicalTempRoots(realTarget, canonicalTempRoots, realCwd, { allowRootEqual: false, excludeRealCwd: true, @@ -3891,10 +4745,30 @@ function handlePreToolUse(payload, env) { const { invocations, redirectTargets } = collectInvocations(code, 0, inheritedEnv, outerEnv); const makeAllowInvTempPath = (mergedEnv) => (rawToken, opts = {}) => { - const { allowRootEqual = false, allowDevNull = false } = opts; + const { + allowRootEqual = false, + allowDevNull = false, + allowArtifactDir = false, + allowArtifactRoot = false, + forbidReadOnlyArtifact = false, + } = opts; const resolved = resolveShellTargetPath(rawToken, fallbackBaseDir, mergedEnv); if (!resolved) return false; if (allowDevNull && resolved === "/dev/null") return true; + if (isSystemGeneratedArtifactPath(resolved, realArtifact)) return false; + if (realArtifact && isInsideOrEqual(resolved, realArtifact)) { + if (forbidReadOnlyArtifact) return false; + if ( + allowArtifactRoot && + resolved === realArtifact && + !(realCwd && isInsideOrEqual(resolved, realCwd)) + ) { + return true; + } + return isAllowedReadOnlyArtifactPath(resolved, realArtifact, realCwd, { + allowDirectory: Boolean(allowArtifactDir), + }); + } return isInsideCanonicalTempRoots(resolved, canonicalTempRoots, realCwd, { allowRootEqual, excludeRealCwd: true, @@ -3904,7 +4778,7 @@ function handlePreToolUse(payload, env) { for (const redirectTarget of redirectTargets) { const mergedEnv = { ...outerEnv, ...redirectTarget.env }; if (!makeAllowInvTempPath(mergedEnv)(redirectTarget.target, { allowRootEqual: false, allowDevNull: true })) { - return "Output file redirection outside /dev/null or canonical temp roots is blocked for read-only ro-* workers."; + return "Output file redirection outside /dev/null, canonical temp roots, or allowed artifact screenshot paths is blocked for read-only ro-* workers."; } } @@ -3987,6 +4861,13 @@ function handlePreToolUse(payload, env) { return { decision: "deny", reason: "Target file path failed symlink resolution." }; } + if (isSystemGeneratedArtifactPath(realTarget, realArtifact)) { + return { + decision: "deny", + reason: `Path '${rawTarget}' inside protected '.system_generated' artifact metadata is blocked for worker '${memberName || kind}'.`, + }; + } + const insideCwd = isStrictlyInside(realTarget, realCwd); const insideArtifact = realArtifact ? isStrictlyInside(realTarget, realArtifact) : false; const insideTemp = @@ -4056,7 +4937,12 @@ function handlePreToolUse(payload, env) { if (kind === "author" || kind === "adversary") { const checkConfinedShellPath = (rawToken, mergedEnv, opts = {}) => { - const { allowRootEqual = false, allowDevNull = false, customBaseDir = null } = opts; + const { + allowRootEqual = false, + allowDevNull = false, + customBaseDir = null, + isRecursiveDelete = false, + } = opts; const activeBase = customBaseDir || realCwd; if (!activeBase && !isAbsolute(rawToken) && !rawToken.startsWith("~") && !rawToken.startsWith("$")) { return false; @@ -4064,15 +4950,20 @@ function handlePreToolUse(payload, env) { const resolved = resolveShellTargetPath(rawToken, activeBase || fallbackBaseDir, mergedEnv); if (!resolved) return false; if (allowDevNull && resolved === "/dev/null") return true; - if (realCwd && (allowRootEqual ? isInsideOrEqual(resolved, realCwd) : isStrictlyInside(resolved, realCwd))) { - return true; - } + if (isSystemGeneratedArtifactPath(resolved, realArtifact)) return false; if ( + isRecursiveDelete && realArtifact && - (allowRootEqual ? isInsideOrEqual(resolved, realArtifact) : isStrictlyInside(resolved, realArtifact)) + isInsideOrEqual(join(realArtifact, ".system_generated"), resolved) ) { + return false; + } + if (realCwd && (allowRootEqual ? isInsideOrEqual(resolved, realCwd) : isStrictlyInside(resolved, realCwd))) { return true; } + if (realArtifact && isInsideOrEqual(resolved, realArtifact)) { + return allowRootEqual ? true : isStrictlyInside(resolved, realArtifact); + } return isInsideCanonicalTempRoots(resolved, canonicalTempRoots, realCwd, { allowRootEqual, excludeRealCwd: false, diff --git a/hooks/guard.test.mjs b/hooks/guard.test.mjs index 98a6255..ed1cb81 100644 --- a/hooks/guard.test.mjs +++ b/hooks/guard.test.mjs @@ -1,6 +1,8 @@ import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; import { + chmodSync, + copyFileSync, existsSync, mkdirSync, mkdtempSync, @@ -64,7 +66,7 @@ function writeTranscriptLines(transcriptPath, steps) { writeFileSync(transcriptPath, text, "utf8"); } -function runGuard(payload, envOverrides = {}) { +function runGuard(payload, envOverrides = {}, guardScriptPath = GUARD_PATH) { const env = { ...process.env }; delete env.PSTACK_APPDATA_DIR; delete env.ANTIGRAVITY_APP_DATA_DIR; @@ -72,15 +74,27 @@ function runGuard(payload, envOverrides = {}) { delete env.PLUGIN_ROOT; delete env.PSTACK_PLUGIN_ROOT; delete env.PSTACK_CACHE_DIR; + delete env.PSTACK_CONFIG_DIR; + delete env.PSTACK_REMOTE_SWARM_CLI; + delete env.PSTACK_REMOTE_BOARD_CONFIG; delete env.PSTACK_GUARD_DELEGATED; delete env.PSTACK_ALLOW_PUSH; delete env.PSTACK_FORCE_COORDINATOR; + if ( + guardScriptPath === GUARD_PATH && + !("PSTACK_CONFIG_DIR" in envOverrides) && + !("HOME" in envOverrides) && + !("PLUGIN_ROOT" in envOverrides) && + !("PSTACK_PLUGIN_ROOT" in envOverrides) + ) { + env.PSTACK_CONFIG_DIR = join(PLUGIN_ROOT, ".nonexistent-pstack-config-dir"); + } for (const [k, v] of Object.entries(envOverrides)) { if (v === undefined || v === null) delete env[k]; else env[k] = v; } - const res = spawnSync(process.execPath, [GUARD_PATH], { + const res = spawnSync(process.execPath, [guardScriptPath], { input: JSON.stringify(payload), encoding: "utf8", env, @@ -1927,3 +1941,908 @@ describe("agy 1.5.9 audit fixes: shell vars, evolve isolation, numbered verifier } }); }); + +describe("agy 1.5.9 native swarm compatibility caveats", () => { + test("Caveat 3 respects config.json plugin disable across PSTACK_CONFIG_DIR, plugins layout, and HOME fallback without cache writes", () => { + const sb = makeSandbox(); + try { + const coordCapsule = readFileSync(join(PLUGIN_ROOT, "roles", "coordinator.md"), "utf8"); + writeSwarmMembers(sb.appDataDir, "coord-c3", { + coordinator: { conversation_id: "coord-c3", role: "coordinator" }, + "ro-1": { conversation_id: "ro-c3", role: "worker" }, + "sicko-1": { conversation_id: "sicko-c3", role: "worker" }, + "impl-1": { conversation_id: "impl-c3", role: "worker" }, + }); + + const cfgDir = join(sb.root, "custom-config"); + mkdirSync(cfgDir, { recursive: true }); + writeFileSync( + join(cfgDir, "config.json"), + JSON.stringify({ plugins: { "agy-pstack-next": { enabled: false } } }), + "utf8", + ); + + assert.deepEqual( + runGuard( + { + hookEventName: "SessionStart", + conversationId: "coord-c3", + lastUserInput: "/pstack audit hooks", + }, + { PSTACK_APPDATA_DIR: sb.appDataDir, PSTACK_CONFIG_DIR: cfgDir }, + ), + {}, + ); + assert.deepEqual( + runGuard( + { + hookEventName: "PreInvocation", + conversationId: "ro-c3", + rootConversationId: "coord-c3", + }, + { PSTACK_APPDATA_DIR: sb.appDataDir, PSTACK_CONFIG_DIR: cfgDir }, + ), + {}, + ); + + const cacheDir = join(sb.appDataDir, "plugin_data", "agy-pstack-next"); + assert.equal(existsSync(join(cacheDir, "injected-capsules.json")), false); + assert.equal(existsSync(join(cacheDir, "member-map.json")), false); + assert.equal(existsSync(join(cacheDir, "plain-swarm-roots.json")), false); + + assert.deepEqual( + runGuard( + { + hookEventName: "PreToolUse", + conversationId: "coord-c3", + cwd: sb.worktree, + toolCall: { id: "t1", name: "invoke_subagent", args: {} }, + }, + { PSTACK_APPDATA_DIR: sb.appDataDir, PSTACK_CONFIG_DIR: cfgDir }, + ), + { decision: "allow" }, + ); + assert.deepEqual( + runGuard( + { + hookEventName: "PreToolUse", + conversationId: "ro-c3", + cwd: sb.worktree, + toolCall: { id: "t2", name: "write_file", args: { Path: join(sb.worktree, "mutated.txt") } }, + }, + { PSTACK_APPDATA_DIR: sb.appDataDir, PSTACK_CONFIG_DIR: cfgDir }, + ), + { decision: "allow" }, + ); + assert.deepEqual( + runGuard( + { + hookEventName: "PreToolUse", + conversationId: "sicko-c3", + cwd: sb.worktree, + toolCall: { id: "t3", name: "write_file", args: { Path: join(sb.worktree, "created.txt") } }, + }, + { PSTACK_APPDATA_DIR: sb.appDataDir, PSTACK_CONFIG_DIR: cfgDir }, + ), + { decision: "allow" }, + ); + assert.deepEqual( + runGuard( + { + hookEventName: "PreToolUse", + conversationId: "impl-c3", + cwd: sb.worktree, + toolCall: { id: "t4", name: "run_command", args: { CommandLine: "git push origin main" } }, + }, + { PSTACK_APPDATA_DIR: sb.appDataDir, PSTACK_CONFIG_DIR: cfgDir }, + ), + { decision: "allow" }, + ); + + writeFileSync( + join(cfgDir, "config.json"), + JSON.stringify({ plugins: { "agy-pstack-next": { enabled: true } } }), + "utf8", + ); + assert.deepEqual( + runGuard( + { + hookEventName: "SessionStart", + conversationId: "coord-c3", + lastUserInput: "/pstack audit hooks", + }, + { PSTACK_APPDATA_DIR: sb.appDataDir, PSTACK_CONFIG_DIR: cfgDir }, + ), + { injectSteps: [{ systemMessage: { systemMessage: coordCapsule } }] }, + ); + + const simulatedHome = join(sb.root, "sim-home"); + const simulatedConfigDir = join(simulatedHome, ".gemini", "config"); + const simulatedPluginDir = join(simulatedConfigDir, "plugins", "agy-pstack-next"); + mkdirSync(join(simulatedPluginDir, "hooks"), { recursive: true }); + mkdirSync(join(simulatedPluginDir, "roles"), { recursive: true }); + copyFileSync(GUARD_PATH, join(simulatedPluginDir, "hooks", "guard.mjs")); + chmodSync(join(simulatedPluginDir, "hooks", "guard.mjs"), 0o755); + copyFileSync( + join(PLUGIN_ROOT, "roles", "coordinator.md"), + join(simulatedPluginDir, "roles", "coordinator.md"), + ); + writeFileSync( + join(simulatedConfigDir, "config.json"), + JSON.stringify({ plugins: { "agy-pstack-next": { enabled: false } } }), + "utf8", + ); + + assert.deepEqual( + runGuard( + { + hookEventName: "SessionStart", + conversationId: "sim-coord", + lastUserInput: "/pstack run", + }, + { PSTACK_APPDATA_DIR: sb.appDataDir, PLUGIN_ROOT: simulatedPluginDir }, + ), + {}, + ); + assert.deepEqual( + runGuard( + { + hookEventName: "SessionStart", + conversationId: "sim-coord-installed", + lastUserInput: "/pstack run", + }, + { PSTACK_APPDATA_DIR: sb.appDataDir }, + join(simulatedPluginDir, "hooks", "guard.mjs"), + ), + {}, + ); + assert.deepEqual( + runGuard( + { + hookEventName: "PreToolUse", + conversationId: "ro-c3", + cwd: sb.worktree, + toolCall: { id: "t5", name: "write_file", args: { Path: join(sb.worktree, "ok.txt") } }, + }, + { PSTACK_APPDATA_DIR: sb.appDataDir }, + join(simulatedPluginDir, "hooks", "guard.mjs"), + ), + { decision: "allow" }, + ); + + const isolatedHomeOut = runGuard( + { + hookEventName: "SessionStart", + conversationId: "isolated-from-home", + lastUserInput: "/pstack run", + }, + { PSTACK_APPDATA_DIR: sb.appDataDir, HOME: simulatedHome }, + ); + assert.deepEqual(isolatedHomeOut, { + injectSteps: [{ systemMessage: { systemMessage: coordCapsule } }], + }); + + const bareHomeAppData = join(simulatedHome, ".gemini", "antigravity-cli"); + mkdirSync(join(bareHomeAppData, "brain"), { recursive: true }); + assert.deepEqual( + runGuard( + { + hookEventName: "SessionStart", + conversationId: "home-fallback-coord", + lastUserInput: "/pstack run", + }, + { HOME: simulatedHome }, + ), + {}, + ); + } finally { + sb.cleanup(); + } + }); + + test("Caveat 1 keeps built-in /swarm and unprefixed plain swarms unmanaged with clean cache hygiene while upgrading cleanly to pstack", () => { + const sb = makeSandbox(); + try { + const coordCapsule = readFileSync(join(PLUGIN_ROOT, "roles", "coordinator.md"), "utf8"); + const agentCapsule = readFileSync(join(PLUGIN_ROOT, "roles", "poteto-agent.md"), "utf8"); + const researchCapsule = readFileSync(join(PLUGIN_ROOT, "roles", "research.md"), "utf8"); + const cacheDir = join(sb.appDataDir, "plugin_data", "agy-pstack-next"); + + writeSwarmMembers(sb.appDataDir, "plain-slash-coord", { + coordinator: { conversation_id: "plain-slash-coord", role: "coordinator" }, + monitor: { conversation_id: "plain-slash-mon", role: "worker" }, + }); + + assert.deepEqual( + runGuard( + { + hookEventName: "SessionStart", + conversationId: "plain-slash-coord", + lastUserInput: "/swarm investigate flaky test", + }, + { PSTACK_APPDATA_DIR: sb.appDataDir }, + ), + {}, + ); + const plainRootsDoc = JSON.parse(readFileSync(join(cacheDir, "plain-swarm-roots.json"), "utf8")); + assert.equal(plainRootsDoc["plain-slash-coord"], true); + + assert.deepEqual( + runGuard( + { + hookEventName: "SessionStart", + conversationId: "plain-slash-mon", + rootConversationId: "plain-slash-coord", + }, + { PSTACK_APPDATA_DIR: sb.appDataDir }, + ), + {}, + ); + assert.deepEqual( + runGuard( + { + hookEventName: "PreToolUse", + conversationId: "plain-slash-coord", + cwd: sb.worktree, + toolCall: { id: "ps-1", name: "invoke_subagent", args: {} }, + }, + { PSTACK_APPDATA_DIR: sb.appDataDir }, + ), + { decision: "allow" }, + ); + + const plainAnchorDir = join(sb.appDataDir, "brain", "plain-anchor-coord", ".system_generated", "swarm"); + mkdirSync(plainAnchorDir, { recursive: true }); + writeFileSync( + join(plainAnchorDir, "swarm.json"), + JSON.stringify({ backend: "spanner", coordinator_conversation_id: "plain-anchor-coord" }), + "utf8", + ); + assert.deepEqual( + runGuard( + { + hookEventName: "SessionStart", + conversationId: "plain-anchor-coord", + lastUserInput: "/swarm coordinate remote team", + }, + { PSTACK_APPDATA_DIR: sb.appDataDir }, + ), + {}, + ); + + writeSwarmMembers(sb.appDataDir, "plain-organic-coord", { + coordinator: { conversation_id: "plain-organic-coord", role: "coordinator" }, + monitor: { conversation_id: "plain-organic-mon", role: "worker" }, + parser: { conversation_id: "plain-parser", role: "worker" }, + docs: { conversation_id: "plain-docs", role: "worker" }, + verifier: { conversation_id: "plain-verifier", role: "worker" }, + }); + + for (const id of ["plain-organic-coord", "plain-parser", "plain-docs", "plain-verifier"]) { + assert.deepEqual( + runGuard( + { + hookEventName: "SessionStart", + conversationId: id, + lastUserInput: + id === "plain-parser" + ? "You are @parser. Compare built-in swarm with /pstack docs." + : "Work on your slice.", + }, + { PSTACK_APPDATA_DIR: sb.appDataDir }, + ), + {}, + `expected plain swarm member ${id} to stay unmanaged`, + ); + } + + assert.deepEqual( + runGuard( + { + hookEventName: "PreToolUse", + conversationId: "plain-verifier", + rootConversationId: "plain-organic-coord", + cwd: sb.worktree, + toolCall: { + id: "pv-1", + name: "write_file", + args: { Path: join(sb.worktree, "plain-verifier-allowed.txt") }, + }, + }, + { PSTACK_APPDATA_DIR: sb.appDataDir }, + ), + { decision: "allow" }, + ); + + const mapBeforeUpgrade = existsSync(join(cacheDir, "member-map.json")) + ? JSON.parse(readFileSync(join(cacheDir, "member-map.json"), "utf8")) + : {}; + assert.equal(mapBeforeUpgrade["plain-parser"], undefined); + assert.equal(mapBeforeUpgrade["plain-docs"], undefined); + assert.equal(mapBeforeUpgrade["plain-verifier"], undefined); + + const nonWorkerBeforeUpgrade = existsSync(join(cacheDir, "non-worker-roots.json")) + ? JSON.parse(readFileSync(join(cacheDir, "non-worker-roots.json"), "utf8")) + : {}; + assert.equal(nonWorkerBeforeUpgrade["plain-parser"], undefined); + assert.equal(nonWorkerBeforeUpgrade["plain-verifier"], undefined); + assert.equal(nonWorkerBeforeUpgrade["plain-organic-coord"], undefined); + + writeSwarmMembers(sb.appDataDir, "plain-organic-coord", { + coordinator: { conversation_id: "plain-organic-coord", role: "coordinator" }, + monitor: { conversation_id: "plain-organic-mon", role: "worker" }, + parser: { conversation_id: "plain-parser", role: "worker" }, + docs: { conversation_id: "plain-docs", role: "worker" }, + verifier: { conversation_id: "plain-verifier", role: "worker" }, + "impl-1": { conversation_id: "upgraded-impl-1", role: "worker" }, + }); + + assert.deepEqual( + runGuard( + { hookEventName: "SessionStart", conversationId: "plain-parser" }, + { PSTACK_APPDATA_DIR: sb.appDataDir }, + ), + { injectSteps: [{ systemMessage: { systemMessage: agentCapsule } }] }, + ); + assert.deepEqual( + runGuard( + { hookEventName: "SessionStart", conversationId: "plain-verifier" }, + { PSTACK_APPDATA_DIR: sb.appDataDir }, + ), + { injectSteps: [{ systemMessage: { systemMessage: researchCapsule } }] }, + ); + assert.equal( + runGuard( + { + hookEventName: "PreToolUse", + conversationId: "plain-verifier", + cwd: sb.worktree, + toolCall: { + id: "pv-2", + name: "write_file", + args: { Path: join(sb.worktree, "blocked-after-upgrade.txt") }, + }, + }, + { PSTACK_APPDATA_DIR: sb.appDataDir }, + ).decision, + "deny", + ); + assert.deepEqual( + runGuard( + { hookEventName: "SessionStart", conversationId: "plain-organic-coord" }, + { PSTACK_APPDATA_DIR: sb.appDataDir }, + ), + { injectSteps: [{ systemMessage: { systemMessage: coordCapsule } }] }, + ); + + writeSwarmMembers(sb.appDataDir, "plain-slash-coord", { + coordinator: { conversation_id: "plain-slash-coord", role: "coordinator" }, + verifier: { conversation_id: "slash-v0", role: "worker" }, + "verifier-1": { conversation_id: "slash-v1", role: "worker" }, + "api-verifier": { conversation_id: "slash-api-v", role: "worker" }, + "verify-links": { conversation_id: "slash-vlinks", role: "worker" }, + "eval-runner-1": { conversation_id: "slash-eval-1", role: "worker" }, + }); + + assert.deepEqual( + runGuard( + { + hookEventName: "PreInvocation", + conversationId: "plain-slash-coord", + lastUserInput: "/pstack take over this swarm", + }, + { PSTACK_APPDATA_DIR: sb.appDataDir }, + ), + { injectSteps: [{ systemMessage: { systemMessage: coordCapsule } }] }, + ); + assert.equal( + JSON.parse(readFileSync(join(cacheDir, "plain-swarm-roots.json"), "utf8"))["plain-slash-coord"], + false, + ); + + for (const roId of ["slash-v0", "slash-v1", "slash-api-v", "slash-vlinks"]) { + assert.deepEqual( + runGuard( + { + hookEventName: "SessionStart", + conversationId: roId, + rootConversationId: "plain-slash-coord", + }, + { PSTACK_APPDATA_DIR: sb.appDataDir }, + ), + { injectSteps: [{ systemMessage: { systemMessage: researchCapsule } }] }, + ); + } + assert.deepEqual( + runGuard( + { + hookEventName: "SessionStart", + conversationId: "slash-eval-1", + rootConversationId: "plain-slash-coord", + }, + { PSTACK_APPDATA_DIR: sb.appDataDir }, + ), + { injectSteps: [{ systemMessage: { systemMessage: agentCapsule } }] }, + ); + + writeSwarmMembers(sb.appDataDir, "marker-coord", { + coordinator: { conversation_id: "marker-coord", role: "coordinator" }, + parser: { conversation_id: "marker-parser", role: "worker" }, + }); + writeFileSync( + join(sb.appDataDir, "brain", "marker-coord", ".system_generated", "swarm", "pstack.json"), + "{}\n", + "utf8", + ); + assert.deepEqual( + runGuard( + { hookEventName: "SessionStart", conversationId: "marker-parser", rootConversationId: "marker-coord" }, + { PSTACK_APPDATA_DIR: sb.appDataDir }, + ), + { injectSteps: [{ systemMessage: { systemMessage: agentCapsule } }] }, + ); + } finally { + sb.cleanup(); + } + }); + + test("Caveat 2 allows ro-* Overview timeline screenshots in explicit and fallback brain/ artifact dirs while protecting .system_generated across all worker roles", () => { + const sb = makeSandbox(); + const slashTmpDir = mkdtempSync("/tmp/pstack-c2-"); + try { + writeSwarmMembers(sb.appDataDir, "coord-c2", { + coordinator: { conversation_id: "coord-c2", role: "coordinator" }, + "ro-ui": { conversation_id: "ro-c2", role: "worker" }, + "impl-ui": { conversation_id: "impl-c2", role: "worker" }, + "adv-ui": { conversation_id: "adv-c2", role: "worker" }, + "sicko-ui": { conversation_id: "sicko-c2", role: "worker" }, + }); + + const roFallbackArtifact = join(sb.appDataDir, "brain", "ro-c2"); + const roExplicitArtifact = join(sb.root, "explicit-ro-artifact"); + mkdirSync(roExplicitArtifact, { recursive: true }); + const implArtifact = join(sb.appDataDir, "brain", "impl-c2"); + const advArtifact = join(sb.appDataDir, "brain", "adv-c2"); + const sickoArtifact = join(sb.appDataDir, "brain", "sicko-c2"); + const coordArtifact = join(sb.appDataDir, "brain", "coord-c2"); + for (const dir of [roFallbackArtifact, implArtifact, advArtifact, sickoArtifact, coordArtifact]) { + mkdirSync(join(dir, ".system_generated", "logs"), { recursive: true }); + mkdirSync(join(dir, ".system_generated", "swarm"), { recursive: true }); + writeFileSync(join(dir, ".system_generated", "logs", "transcript.jsonl"), "{}\n", "utf8"); + } + + const callFileTool = (convId, toolName, targetPath, artifactDirectoryPath = undefined) => + runGuard( + { + hookEventName: "PreToolUse", + conversationId: convId, + rootConversationId: convId === "coord-c2" ? undefined : "coord-c2", + ...(artifactDirectoryPath !== undefined ? { artifactDirectoryPath } : {}), + cwd: sb.worktree, + toolCall: { id: "f-c2", name: toolName, args: { Path: targetPath } }, + }, + { PSTACK_APPDATA_DIR: sb.appDataDir, TMPDIR: sb.customTmpDir }, + ); + + for (const artDir of [roFallbackArtifact, roExplicitArtifact]) { + const explicitParam = artDir === roExplicitArtifact ? roExplicitArtifact : undefined; + for (const ext of ["png", "jpg", "jpeg", "webp", "PNG", "WEBP"]) { + assert.equal( + callFileTool("ro-c2", "write_file", join(artDir, "timeline", `shot.${ext}`), explicitParam).decision, + "allow", + `expected ro write_file allow for .${ext} in ${artDir}`, + ); + } + assert.equal( + callFileTool("ro-c2", "edit_file", join(artDir, "shot.png"), explicitParam).decision, + "deny", + ); + for (const blockedRel of [ + "report.md", + "data.json", + "probe.js", + "notes.txt", + ".system_generated/shot.png", + ".system_generated/logs/transcript.jsonl", + ]) { + assert.equal( + callFileTool("ro-c2", "write_file", join(artDir, blockedRel), explicitParam).decision, + "deny", + `expected ro write_file deny for ${blockedRel}`, + ); + } + assert.equal(callFileTool("ro-c2", "write_file", artDir, explicitParam).decision, "deny"); + } + + const tempPlaywrightMjs = join(slashTmpDir, "capture-ok.mjs"); + writeFileSync( + tempPlaywrightMjs, + `import fs from 'node:fs'; fs.mkdirSync('${join(roFallbackArtifact, "shots")}', { recursive: true }); await page.screenshot({ path: '${join(roFallbackArtifact, "shots", "overview.png")}', fullPage: true });\n`, + "utf8", + ); + const tempBadPlaywrightMjs = join(slashTmpDir, "capture-bad.mjs"); + writeFileSync( + tempBadPlaywrightMjs, + `await page.screenshot({ path: '${join(roFallbackArtifact, ".system_generated", "overview.png")}' });\n`, + "utf8", + ); + + const runRoShell = (CommandLine) => + runGuard( + { + hookEventName: "PreToolUse", + conversationId: "ro-c2", + rootConversationId: "coord-c2", + cwd: sb.worktree, + toolCall: { id: "sh-ro", name: "run_command", args: { CommandLine } }, + }, + { PSTACK_APPDATA_DIR: sb.appDataDir, TMPDIR: sb.customTmpDir }, + ); + + const roAllowedCmds = [ + `mkdir -p ${roFallbackArtifact} ${join(roFallbackArtifact, "shots", "sub")}`, + `cat ${join(slashTmpDir, "raw.png")} > ${join(roFallbackArtifact, "overview.png")}`, + `cp ${join(slashTmpDir, "a.png")} ${join(roFallbackArtifact, "shots", "a.png")}`, + `cp ${join(slashTmpDir, "a.webp")} ${join(roFallbackArtifact, "shots")}`, + `mv ${join(slashTmpDir, "a.jpg")} ${join(roFallbackArtifact, "shots", "a.jpg")}`, + `mv ${join(roFallbackArtifact, "shots", "a.jpg")} ${join(roFallbackArtifact, "shots", "b.jpeg")}`, + `tee ${join(roFallbackArtifact, "pipe.png")} < ${join(slashTmpDir, "a.png")}`, + `curl -sL https://example.com/frame.png -o ${join(roFallbackArtifact, "frame.png")}`, + `rm -f ${join(roFallbackArtifact, "frame.png")}`, + `unlink ${join(roFallbackArtifact, "shots", "b.jpeg")}`, + `node -e "const fs = require('node:fs'); fs.mkdirSync('${join(roFallbackArtifact, "shots")}', { recursive: true }); fs.writeFileSync('${join(roFallbackArtifact, "shots", "snap.png")}', buf); fs.copyFileSync('${join(slashTmpDir, "a.png")}', '${join(roFallbackArtifact, "shots", "copy.webp")}')"`, + `node -e "await page.screenshot({ path: '${join(roFallbackArtifact, "pane.jpg")}' })"`, + `node ${tempPlaywrightMjs}`, + `python3 -c "import os; os.makedirs('${join(roFallbackArtifact, "shots")}', exist_ok=True); open('${join(roFallbackArtifact, "shots", "py.png")}', 'wb').write(b'x')"`, + `python3 -c "from pathlib import Path; Path('${join(roFallbackArtifact, "shots")}').mkdir(parents=True, exist_ok=True); Path('${join(roFallbackArtifact, "shots", "p.webp")}').write_bytes(b'x')"`, + `python3 -c "page.screenshot(path='${join(roFallbackArtifact, "py-shot.jpeg")}')"`, + ]; + for (const cmd of roAllowedCmds) { + assert.equal(runRoShell(cmd).decision, "allow", `expected ro screenshot shell allow: ${cmd}`); + } + + const roDeniedCmds = [ + `echo bad > ${join(roFallbackArtifact, "report.md")}`, + `echo bad > ${join(roFallbackArtifact, ".system_generated", "shot.png")}`, + `cp ${join(slashTmpDir, "notes.md")} ${join(roFallbackArtifact, "shots")}`, + `cp ${join(slashTmpDir, "notes.md")} ${join(roFallbackArtifact, "notes.md")}`, + `mv ${join(slashTmpDir, "notes.txt")} ${join(roFallbackArtifact, "notes.txt")}`, + `tee ${join(roFallbackArtifact, "out.json")}`, + `curl -sL https://example.com/data -o ${join(roFallbackArtifact, "out.json")}`, + `mkdir -p ${join(roFallbackArtifact, "notes.md")}`, + `mkdir -p ${join(roFallbackArtifact, ".system_generated", "sub")}`, + `rm -f ${join(roFallbackArtifact, "notes.md")}`, + `rm -rf ${roFallbackArtifact}`, + `ln -s /etc/passwd ${join(roFallbackArtifact, "shot.png")}`, + `node -e "require('node:fs').writeFileSync('${join(roFallbackArtifact, "notes.md")}', 'x')"`, + `node -e "require('node:fs').symlinkSync('/etc/passwd', '${join(roFallbackArtifact, "shot.png")}')"`, + `node -e "await page.screenshot({ path: '${join(sb.outsideDir, "escape.png")}' })"`, + `node ${tempBadPlaywrightMjs}`, + `python3 -c "open('${join(roFallbackArtifact, "notes.txt")}', 'w').write('x')"`, + `python3 -c "page.screenshot(path='${join(roFallbackArtifact, ".system_generated", "x.png")}')"`, + ]; + for (const cmd of roDeniedCmds) { + assert.equal(runRoShell(cmd).decision, "deny", `expected ro screenshot shell deny: ${cmd}`); + } + + for (const [convId, artDir] of [ + ["ro-c2", roFallbackArtifact], + ["impl-c2", implArtifact], + ["adv-c2", advArtifact], + ["sicko-c2", sickoArtifact], + ]) { + const transcriptTarget = join(artDir, ".system_generated", "logs", "transcript.jsonl"); + const swarmPlanTarget = join(artDir, ".system_generated", "swarm", "plan.json"); + assert.equal(callFileTool(convId, "edit_file", transcriptTarget).decision, "deny"); + assert.equal(callFileTool(convId, "write_file", swarmPlanTarget).decision, "deny"); + + for (const sysGenCmd of [ + `echo forged >> ${transcriptTarget}`, + `cp ${join(slashTmpDir, "a.json")} ${swarmPlanTarget}`, + `rm -rf ${join(artDir, ".system_generated")}`, + `rm -rf ${artDir}`, + `find ${artDir} -delete`, + `node -e "require('node:fs').writeFileSync('${transcriptTarget}', '{}')"`, + `python3 -c "open('${transcriptTarget}', 'w').write('{}')"`, + ]) { + assert.equal( + runGuard( + { + hookEventName: "PreToolUse", + conversationId: convId, + rootConversationId: "coord-c2", + cwd: sb.worktree, + toolCall: { id: "sg-sh", name: "run_command", args: { CommandLine: sysGenCmd } }, + }, + { PSTACK_APPDATA_DIR: sb.appDataDir, TMPDIR: sb.customTmpDir }, + ).decision, + "deny", + `expected .system_generated deny for ${convId}: ${sysGenCmd}`, + ); + } + } + + assert.equal( + callFileTool("impl-c2", "write_file", join(implArtifact, "notes.md")).decision, + "allow", + ); + assert.equal( + callFileTool( + "coord-c2", + "write_file", + join(coordArtifact, ".system_generated", "swarm", "plan.json"), + coordArtifact, + ).decision, + "allow", + ); + + writeSwarmMembers(sb.appDataDir, "coord-unsafe", { + "ro-unsafe-1": { conversation_id: "../outside", role: "worker" }, + "ro-unsafe-2": { conversation_id: "..", role: "worker" }, + }); + assert.equal( + callFileTool("../outside", "write_file", join(sb.appDataDir, "outside", "shot.png")).decision, + "deny", + ); + assert.equal( + callFileTool("..", "write_file", join(sb.appDataDir, "shot.png")).decision, + "deny", + ); + } finally { + rmSync(slashTmpDir, { recursive: true, force: true }); + sb.cleanup(); + } + }); + + test("Caveat 4 resolves remote swarm.json anchors via bounded --roster-only CLI probe with cache, O(1) member-map, and clean fail-open", () => { + const sb = makeSandbox(); + try { + const researchCapsule = readFileSync(join(PLUGIN_ROOT, "roles", "research.md"), "utf8"); + const agentCapsule = readFileSync(join(PLUGIN_ROOT, "roles", "poteto-agent.md"), "utf8"); + const cacheDir = join(sb.appDataDir, "plugin_data", "agy-pstack-next"); + + const callsLog = join(sb.root, "remote-cli-calls.jsonl"); + const rosterStateFile = join(sb.root, "remote-roster-state.json"); + const mockCli = join(sb.root, "mock-remote-swarm-cli.mjs"); + writeFileSync( + rosterStateFile, + JSON.stringify({ + swm_remote_pstack: { + coordinator: { conversation_id: "remote-coord", role: "coordinator" }, + "impl-1": { conversation_id: "remote-impl-1", role: "worker" }, + "ro-1": { conversation_id: "remote-ro-1", role: "worker" }, + }, + swm_remote_plain: { + coordinator: { conversation_id: "remote-plain-coord", role: "coordinator" }, + parser: { conversation_id: "remote-plain-parser", role: "worker" }, + verifier: { conversation_id: "remote-plain-verifier", role: "worker" }, + }, + }), + "utf8", + ); + writeFileSync( + mockCli, + `#!/usr/bin/env node +import { appendFileSync, readFileSync } from "node:fs"; +const args = process.argv.slice(2); +appendFileSync(${JSON.stringify(callsLog)}, JSON.stringify(args) + "\\n", "utf8"); +if (process.env.MOCK_CLI_MODE === "fail") process.exit(2); +if (process.env.MOCK_CLI_MODE === "hang") { setTimeout(() => {}, 10000); } else { + const swarmId = args[args.length - 1]; + const state = JSON.parse(readFileSync(${JSON.stringify(rosterStateFile)}, "utf8")); + const members = state[swarmId]; + if (members) { + process.stdout.write(JSON.stringify({ type: "meta", ok: true }) + "\\n"); + process.stdout.write(JSON.stringify({ swarm_id: swarmId, members }) + "\\n"); + } +} +`, + "utf8", + ); + chmodSync(mockCli, 0o755); + + const writeRemoteAnchor = (coordId, doc) => { + const dir = join(sb.appDataDir, "brain", coordId, ".system_generated", "swarm"); + mkdirSync(dir, { recursive: true }); + writeFileSync(join(dir, "swarm.json"), JSON.stringify(doc), "utf8"); + }; + + writeRemoteAnchor("remote-coord", { + backend: "spanner", + swarm_id: "swm_remote_pstack", + db: "projects/p/instances/i/databases/d", + coordinator_conversation_id: "remote-coord", + }); + + assert.deepEqual( + runGuard( + { + hookEventName: "SessionStart", + conversationId: "remote-ro-1", + rootConversationId: "remote-coord", + }, + { PSTACK_APPDATA_DIR: sb.appDataDir, PSTACK_REMOTE_SWARM_CLI: mockCli }, + ), + { injectSteps: [{ systemMessage: { systemMessage: researchCapsule } }] }, + ); + + const recordedCalls = readFileSync(callsLog, "utf8").trim().split("\n").map((l) => JSON.parse(l)); + assert.equal(recordedCalls.length, 1); + assert.deepEqual(recordedCalls[0], [ + "swarm", + "--json", + "--roster-only", + "--db", + "projects/p/instances/i/databases/d", + "swm_remote_pstack", + ]); + + const remoteCache = JSON.parse(readFileSync(join(cacheDir, "remote-rosters.json"), "utf8")); + assert.ok(remoteCache.swm_remote_pstack); + assert.equal(remoteCache.swm_remote_pstack.members["ro-1"].conversation_id, "remote-ro-1"); + + assert.equal( + runGuard( + { + hookEventName: "PreToolUse", + conversationId: "remote-ro-1", + cwd: sb.worktree, + toolCall: { id: "r1", name: "write_file", args: { Path: join(sb.worktree, "nope.txt") } }, + }, + { PSTACK_APPDATA_DIR: sb.appDataDir, PSTACK_REMOTE_SWARM_CLI: mockCli }, + ).decision, + "deny", + ); + assert.deepEqual( + runGuard( + { hookEventName: "SessionStart", conversationId: "remote-impl-1" }, + { PSTACK_APPDATA_DIR: sb.appDataDir, PSTACK_REMOTE_SWARM_CLI: mockCli }, + ), + { injectSteps: [{ systemMessage: { systemMessage: agentCapsule } }] }, + ); + assert.equal(readFileSync(callsLog, "utf8").trim().split("\n").length, 1); + + const sidecarDir = join( + sb.appDataDir, + "builtin", + "plugins", + "swarm", + "sidecars", + "swarm_board", + ); + mkdirSync(sidecarDir, { recursive: true }); + writeFileSync( + join(sidecarDir, "remote_board.json"), + JSON.stringify({ backend: "spanner", cli: [mockCli] }), + "utf8", + ); + + writeRemoteAnchor("remote-plain-coord", { + backend: "spanner", + swarm_id: "swm_remote_plain", + coordinator_conversation_id: "remote-plain-coord", + }); + + assert.deepEqual( + runGuard( + { + hookEventName: "SessionStart", + conversationId: "remote-plain-verifier", + rootConversationId: "remote-plain-coord", + }, + { PSTACK_APPDATA_DIR: sb.appDataDir }, + ), + {}, + ); + const memberMapAfterPlain = JSON.parse(readFileSync(join(cacheDir, "member-map.json"), "utf8")); + assert.equal(memberMapAfterPlain["remote-plain-verifier"], undefined); + assert.equal(memberMapAfterPlain["remote-plain-parser"], undefined); + + const lateWorkerTranscript = join( + sb.appDataDir, + "brain", + "remote-ro-late", + ".system_generated", + "logs", + "transcript.jsonl", + ); + writeTranscriptLines(lateWorkerTranscript, [ + { step_index: 0, type: "SYSTEM_MESSAGE", content: "[swarm] new board message #2" }, + ]); + const callsBeforeBackoffProbe = readFileSync(callsLog, "utf8").trim().split("\n").length; + assert.deepEqual( + runGuard( + { + hookEventName: "SessionStart", + conversationId: "remote-ro-late", + rootConversationId: "remote-coord", + transcriptPath: lateWorkerTranscript, + }, + { PSTACK_APPDATA_DIR: sb.appDataDir }, + ), + {}, + ); + assert.equal(readFileSync(callsLog, "utf8").trim().split("\n").length, callsBeforeBackoffProbe); + const nonWorkerAfterMiss = existsSync(join(cacheDir, "non-worker-roots.json")) + ? JSON.parse(readFileSync(join(cacheDir, "non-worker-roots.json"), "utf8")) + : {}; + assert.equal(nonWorkerAfterMiss["remote-ro-late"], undefined); + + writeFileSync( + rosterStateFile, + JSON.stringify({ + swm_remote_pstack: { + coordinator: { conversation_id: "remote-coord", role: "coordinator" }, + "impl-1": { conversation_id: "remote-impl-1", role: "worker" }, + "ro-1": { conversation_id: "remote-ro-1", role: "worker" }, + "ro-late": { conversation_id: "remote-ro-late", role: "worker" }, + }, + }), + "utf8", + ); + const agedCache = JSON.parse(readFileSync(join(cacheDir, "remote-rosters.json"), "utf8")); + agedCache.swm_remote_pstack.fetchedAt = Date.now() - 6000; + writeFileSync(join(cacheDir, "remote-rosters.json"), JSON.stringify(agedCache), "utf8"); + + assert.deepEqual( + runGuard( + { + hookEventName: "SessionStart", + conversationId: "remote-ro-late", + rootConversationId: "remote-coord", + transcriptPath: lateWorkerTranscript, + }, + { PSTACK_APPDATA_DIR: sb.appDataDir }, + ), + { injectSteps: [{ systemMessage: { systemMessage: researchCapsule } }] }, + ); + + writeRemoteAnchor("flag-inject-coord", { + backend: "spanner", + swarm_id: "-bad-flag", + db: "--evil-db", + }); + const callsBeforeBadAnchor = readFileSync(callsLog, "utf8").trim().split("\n").length; + runGuard( + { + hookEventName: "SessionStart", + conversationId: "flag-worker", + rootConversationId: "flag-inject-coord", + transcriptPath: lateWorkerTranscript, + }, + { PSTACK_APPDATA_DIR: sb.appDataDir, PSTACK_REMOTE_SWARM_CLI: mockCli }, + ); + assert.equal(readFileSync(callsLog, "utf8").trim().split("\n").length, callsBeforeBadAnchor); + + writeRemoteAnchor("fail-open-coord", { + backend: "spanner", + swarm_id: "swm_fail_open", + coordinator_conversation_id: "fail-open-coord", + }); + for (const mode of ["fail", "hang"]) { + assert.deepEqual( + runGuard( + { + hookEventName: "SessionStart", + conversationId: `fail-open-worker-${mode}`, + rootConversationId: "fail-open-coord", + transcriptPath: lateWorkerTranscript, + }, + { + PSTACK_APPDATA_DIR: sb.appDataDir, + PSTACK_REMOTE_SWARM_CLI: mockCli, + MOCK_CLI_MODE: mode, + }, + ), + {}, + ); + const nonWorkers = existsSync(join(cacheDir, "non-worker-roots.json")) + ? JSON.parse(readFileSync(join(cacheDir, "non-worker-roots.json"), "utf8")) + : {}; + assert.equal(nonWorkers[`fail-open-worker-${mode}`], undefined); + } + } finally { + sb.cleanup(); + } + }); +}); From 1bbd656d46e2fc1504b4ab7124c5d8343ec8ba8b Mon Sep 17 00:00:00 2001 From: Kaitian Xie Date: Sun, 15 Nov 2026 00:38:40 +0800 Subject: [PATCH 3/3] Harden Caveat 2 artifact screenshot and .system_generated confinement Reject dotfile and extension-bearing directory segments, directory or non-image copy sources, and recursive directory copies when read-only workers target artifact screenshot paths. Validate Python Path.symlink_to, Path.hardlink_to, and Path.link_to targets across direct, variable-bound, and Path-wrapped expressions. Block rsync delete flags and glob or brace patterns that can reach .system_generated inside worker artifact roots, with behavioral regression coverage. --- hooks/guard.mjs | 541 ++++++++++++++++++++++++++++++++++++------- hooks/guard.test.mjs | 83 +++++++ 2 files changed, 535 insertions(+), 89 deletions(-) diff --git a/hooks/guard.mjs b/hooks/guard.mjs index d592fab..a55c092 100755 --- a/hooks/guard.mjs +++ b/hooks/guard.mjs @@ -2679,7 +2679,7 @@ const NODE_MUTATION_NAME_RE = /\b(?:writeFileSync|writeFile|appendFileSync|appendFile|unlinkSync|unlink|rmSync|rm|rmdirSync|rmdir|renameSync|rename|copyFileSync|copyFile|cpSync|cp|mkdirSync|mkdir|mkdtempSync|mkdtemp|chmodSync|chmod|chownSync|chown|truncateSync|truncate|symlinkSync|symlink|linkSync|link|createWriteStream|openSync)\b/; const PYTHON_MUTATION_NAME_RE = - /\b(?:remove|unlink|rmdir|removedirs|mkdir|makedirs|chmod|chown|truncate|rename|renames|replace|rmtree|move|copy|copy2|copyfile|copytree|symlink|link|write_text|write_bytes|touch|lchmod|symlink_to|hardlink_to)\b/; + /\b(?:remove|unlink|rmdir|removedirs|mkdir|makedirs|chmod|chown|truncate|rename|renames|replace|rmtree|move|copy|copy2|copyfile|copytree|symlink|link|write_text|write_bytes|touch|lchmod|symlink_to|hardlink_to|link_to)\b/; function isVarBoundToVerifiedTmpRoot(varName, code) { if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(varName)) return false; @@ -2742,6 +2742,16 @@ function isSafeTmpTemplateOrJoin(expr, code, allowPath) { return false; } +function unwrapPythonPathCtor(expr) { + const trimmed = String(expr || "").trim(); + const m = trimmed.match(/^(?:pathlib\s*\.\s*)?Path\s*\(([\s\S]*)\)$/); + if (!m) return trimmed; + const args = parseCallArguments(`(${m[1]})`, 0); + if (!args || args.length === 0) return trimmed; + if (args.length === 1) return args[0].trim(); + return `os.path.join(${args.join(", ")})`; +} + function resolveSimpleVarBinding(code, expr, isPython) { const trimmed = expr.trim(); if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(trimmed)) return null; @@ -2753,13 +2763,15 @@ function resolveSimpleVarBinding(code, expr, isPython) { lastRhs = m[1].trim(); } if (!lastRhs) return null; - return isPython ? parseStaticPyString(lastRhs) : parseStaticJsString(lastRhs); + const normalizedRhs = isPython ? unwrapPythonPathCtor(lastRhs) : lastRhs; + return isPython ? parseStaticPyString(normalizedRhs) : parseStaticJsString(normalizedRhs); } function resolveStaticArgValue(argExpr, code, isPython) { - const lit = isPython ? parseStaticPyString(argExpr || "") : parseStaticJsString(argExpr || ""); + const normalizedExpr = isPython ? unwrapPythonPathCtor(argExpr || "") : String(argExpr || ""); + const lit = isPython ? parseStaticPyString(normalizedExpr) : parseStaticJsString(normalizedExpr); if (lit.ok) return lit.value; - const bound = resolveSimpleVarBinding(code, argExpr || "", isPython); + const bound = resolveSimpleVarBinding(code, normalizedExpr, isPython); if (bound && bound.ok) return bound.value; return null; } @@ -2889,7 +2901,12 @@ function extractJsObjectProperty(objExpr, propName) { } function checkInlineNodeFs(code, allowPath, options = {}) { - const { allowDynamicPaths = false, roleLabel = "read-only ro-* workers" } = options; + const { + allowDynamicPaths = false, + roleLabel = "read-only ro-* workers", + allowReadOnlyArtifactCopySource = null, + registerReadOnlyMkdir = null, + } = options; const bracketRe = /(?:([A-Za-z_$][A-Za-z0-9_$]*)|([)\]'"]))\s*\[([^\]]*)\]/g; let bm; @@ -2927,9 +2944,6 @@ function checkInlineNodeFs(code, allowPath, options = {}) { const checkNodePathArg = (argExpr, opts) => { const rawExpr = String(argExpr || ""); - if (/\.system_generated(?:[/\\'"`]|$)/.test(rawExpr)) { - return false; - } const lit = parseStaticJsString(rawExpr); if (lit.ok) { return allowPath(lit.value, opts); @@ -2945,6 +2959,9 @@ function checkInlineNodeFs(code, allowPath, options = {}) { if (isSafeTmpTemplateOrJoin(rawExpr, code, allowPath)) { return true; } + if (/\.system_generated(?:[/\\'"`]|$)/.test(rawExpr)) { + return false; + } return allowDynamicPaths; }; @@ -3000,25 +3017,39 @@ function checkInlineNodeFs(code, allowPath, options = {}) { allowRootEqual: isMkdir, allowDevNull: allowNull, allowArtifactDir: isMkdir, + requireArtifactDir: isMkdir, allowArtifactRoot: isMkdir, forbidReadOnlyArtifact: forbidRoArtifact, }) ) { return `Inline Node fs.${fnName} outside allowed roots is blocked for ${roleLabel}.`; } + if (isMkdir && registerReadOnlyMkdir) { + const mkdirVal = + resolveStaticArgValue(callArgs[0] || "", code, false) ?? + resolveStaticJoinOrTemplate(callArgs[0] || "", code, false); + if (mkdirVal) registerReadOnlyMkdir(mkdirVal); + } continue; } if (NODE_COPY_FS_APIS.has(fnName)) { - const forbidRoArtifact = fnName === "cpSync" || fnName === "cp"; + const isCpDirApi = fnName === "cpSync" || fnName === "cp"; + const hasRecursiveOpt = + isCpDirApi && callArgs.length >= 3 && /\brecursive\b/.test(String(callArgs[2] || "")); const srcVal = resolveStaticArgValue(callArgs[0] || "", code, false); - const srcIsImg = Boolean(srcVal && /\.(?:png|jpe?g|webp)$/i.test(srcVal)); + const srcOkForRoArtifact = + !hasRecursiveOpt && + (allowReadOnlyArtifactCopySource + ? Boolean(srcVal && allowReadOnlyArtifactCopySource(srcVal)) + : Boolean(srcVal && /\.(?:png|jpe?g|webp)$/i.test(srcVal))); if ( !checkNodePathArg(callArgs[1], { allowRootEqual: true, allowDevNull: true, allowArtifactDir: false, - forbidReadOnlyArtifact: forbidRoArtifact && !srcIsImg, + allowArtifactRoot: false, + forbidReadOnlyArtifact: !srcOkForRoArtifact, }) ) { return `Inline Node fs.${fnName} destination outside allowed roots is blocked for ${roleLabel}.`; @@ -3027,22 +3058,32 @@ function checkInlineNodeFs(code, allowPath, options = {}) { } if (NODE_TWO_PATH_FS_APIS.has(fnName)) { - const isLink = - fnName === "symlinkSync" || - fnName === "symlink" || - fnName === "linkSync" || - fnName === "link"; + const isSymlink = fnName === "symlinkSync" || fnName === "symlink"; + const isLink = isSymlink || fnName === "linkSync" || fnName === "link"; + const srcVal = resolveStaticArgValue(callArgs[0] || "", code, false); + const dstVal = resolveStaticArgValue(callArgs[1] || "", code, false); + const symlinkBaseDir = + isSymlink && dstVal && isAbsolute(dstVal) ? dirname(dstVal) : null; + const srcOkForRoArtifact = + !isLink && + (allowReadOnlyArtifactCopySource + ? Boolean(srcVal && allowReadOnlyArtifactCopySource(srcVal)) + : Boolean(srcVal && /\.(?:png|jpe?g|webp)$/i.test(srcVal))); if ( !checkNodePathArg(callArgs[0], { allowRootEqual: false, allowDevNull: false, forbidReadOnlyArtifact: isLink, + disallowArtifactRoot: isLink, + customBaseDir: symlinkBaseDir, }) || !checkNodePathArg(callArgs[1], { allowRootEqual: true, allowDevNull: false, allowArtifactDir: false, - forbidReadOnlyArtifact: isLink, + allowArtifactRoot: false, + forbidReadOnlyArtifact: isLink || !srcOkForRoArtifact, + disallowArtifactRoot: isLink, }) ) { return `Inline Node fs.${fnName} outside allowed roots is blocked for ${roleLabel}.`; @@ -3090,7 +3131,7 @@ function splitPythonCallArgs(callArgs) { function hasDisallowedPythonAlias(code) { if ( - /\.\s*(write_text|write_bytes|unlink|rmdir|mkdir|touch|chmod|lchmod|rename|replace|symlink_to|hardlink_to|remove|removedirs|makedirs|chown|truncate|renames|rmtree|move|copy|copy2|copyfile|copytree|symlink|link)\b(?!\s*\()/.test( + /\.\s*(write_text|write_bytes|unlink|rmdir|mkdir|touch|chmod|lchmod|rename|replace|symlink_to|hardlink_to|link_to|remove|removedirs|makedirs|chown|truncate|renames|rmtree|move|copy|copy2|copyfile|copytree|symlink|link)\b(?!\s*\()/.test( code, ) || /(?:^|[^\w.])=\s*(?:builtins\s*\.\s*|io\s*\.\s*)?open\b(?!\s*\()/.test(code) @@ -3120,17 +3161,19 @@ function hasDisallowedPythonAlias(code) { } function checkInlinePythonFs(code, allowPath, options = {}) { - const { allowDynamicPaths = false, roleLabel = "read-only ro-* workers" } = options; + const { + allowDynamicPaths = false, + roleLabel = "read-only ro-* workers", + allowReadOnlyArtifactCopySource = null, + registerReadOnlyMkdir = null, + } = options; if (!allowDynamicPaths && hasDisallowedPythonAlias(code)) { return `Aliased filesystem mutation API in inline Python script is blocked for ${roleLabel}.`; } const checkPyPathArg = (argExpr, opts) => { - const rawExpr = String(argExpr || ""); - if (/\.system_generated(?:[/\\'"`]|$)/.test(rawExpr)) { - return false; - } + const rawExpr = unwrapPythonPathCtor(argExpr || ""); const lit = parseStaticPyString(rawExpr); if (lit.ok) { return allowPath(lit.value, opts); @@ -3146,11 +3189,58 @@ function checkInlinePythonFs(code, allowPath, options = {}) { if (isSafeTmpTemplateOrJoin(rawExpr, code, allowPath)) { return true; } + if (/\.system_generated(?:[/\\'"`]|$)/.test(rawExpr)) { + return false; + } return allowDynamicPaths; }; + const resolvePythonPathReceiverArg = (prefixStr) => { + const ctorMatch = prefixStr.match(/(?:pathlib\s*\.\s*)?Path\s*\(\s*([^()]*)\s*\)\s*$/); + if (ctorMatch) { + const ctorArgs = parseCallArguments(`(${ctorMatch[1]})`, 0); + if (!ctorArgs || ctorArgs.length !== 1) return { valid: false, found: true, expr: null }; + return { valid: true, found: true, expr: ctorArgs[0] }; + } + const varMatch = prefixStr.match(/(?:^|[^\w.])([A-Za-z_][A-Za-z0-9_]*)\s*$/); + if (varMatch) { + const varEsc = varMatch[1].replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + const assignRe = new RegExp( + `(?:^|[\\n;])\\s*${varEsc}\\s*=\\s*(?:pathlib\\s*\\.\\s*)?Path\\s*\\(\\s*([^()]*)\\s*\\)`, + "g", + ); + let lastBody = null; + let am; + while ((am = assignRe.exec(code)) !== null) { + lastBody = am[1]; + } + if (lastBody !== null) { + const boundArgs = parseCallArguments(`(${lastBody})`, 0); + if (boundArgs && boundArgs.length === 1) { + return { valid: true, found: true, expr: boundArgs[0] }; + } + } + } + return { valid: true, found: false, expr: null }; + }; + + if (registerReadOnlyMkdir) { + const preMkdirRe = /(?:(?:os|posix)\s*\.\s*|\b)(?:mkdir|makedirs)\s*\(/g; + let pm; + while ((pm = preMkdirRe.exec(code)) !== null) { + const mArgs = parseCallArguments(code, pm.index + pm[0].length - 1); + if (!mArgs) continue; + const { positionals: pPos, kwargs: pKw } = splitPythonCallArgs(mArgs); + const dExpr = pPos[0] ?? pKw.path ?? pKw.name ?? ""; + const dVal = + resolveStaticArgValue(dExpr, code, true) ?? + resolveStaticJoinOrTemplate(unwrapPythonPathCtor(dExpr), code, true); + if (dVal) registerReadOnlyMkdir(dVal); + } + } + const pathMethodRe = - /\.\s*(write_text|write_bytes|unlink|rmdir|mkdir|touch|chmod|lchmod|rename|replace|symlink_to|hardlink_to|open)\s*\(/g; + /\.\s*(write_text|write_bytes|unlink|rmdir|mkdir|touch|chmod|lchmod|rename|replace|symlink_to|hardlink_to|link_to|open)\s*\(/g; let match; while ((match = pathMethodRe.exec(code)) !== null) { const method = match[1]; @@ -3169,40 +3259,77 @@ function checkInlinePythonFs(code, allowPath, options = {}) { } } const prefix = code.slice(0, match.index); - const ctorMatch = prefix.match(/(?:pathlib\s*\.\s*)?Path\s*\(\s*([^()]*)\s*\)\s*$/); - if (!ctorMatch) { - if (!allowDynamicPaths) { - return `Inline Python Path.${method}() on non-literal receiver is blocked for ${roleLabel}.`; - } - continue; - } - const ctorArgs = parseCallArguments(`(${ctorMatch[1]})`, 0); + const recv = resolvePythonPathReceiverArg(prefix); const isMkdir = method === "mkdir"; + const isLinkMethod = + method === "symlink_to" || method === "hardlink_to" || method === "link_to"; const forbidRo = - method === "symlink_to" || - method === "hardlink_to" || + isLinkMethod || method === "rmdir" || method === "chmod" || method === "lchmod"; - if ( - !ctorArgs || - ctorArgs.length !== 1 || - !checkPyPathArg(ctorArgs[0], { - allowRootEqual: isMkdir, - allowDevNull: false, - allowArtifactDir: isMkdir, - allowArtifactRoot: isMkdir, - forbidReadOnlyArtifact: forbidRo, - }) - ) { + if (!recv.valid) { return `Inline Python Path.${method}() outside allowed roots is blocked for ${roleLabel}.`; } - if (method === "rename" || method === "replace") { + if (recv.found) { if ( - !checkPyPathArg(methodArgs[0] || "", { + !checkPyPathArg(recv.expr, { + allowRootEqual: isMkdir, + allowDevNull: false, + allowArtifactDir: isMkdir, + requireArtifactDir: isMkdir, + allowArtifactRoot: isMkdir, + forbidReadOnlyArtifact: forbidRo, + disallowArtifactRoot: isLinkMethod, + }) + ) { + return `Inline Python Path.${method}() outside allowed roots is blocked for ${roleLabel}.`; + } + if (isMkdir && registerReadOnlyMkdir) { + const mkdirVal = + resolveStaticArgValue(recv.expr, code, true) ?? + resolveStaticJoinOrTemplate(unwrapPythonPathCtor(recv.expr), code, true); + if (mkdirVal) registerReadOnlyMkdir(mkdirVal); + } + } else if (!allowDynamicPaths) { + return `Inline Python Path.${method}() on non-literal receiver is blocked for ${roleLabel}.`; + } + + if (isLinkMethod) { + const { positionals: mPos, kwargs: mKw } = splitPythonCallArgs(methodArgs); + const targetExpr = mPos[0] ?? mKw.target ?? ""; + const recvVal = recv.found ? resolveStaticArgValue(recv.expr, code, true) : null; + const symlinkBaseDir = + method === "symlink_to" && recvVal && isAbsolute(recvVal) ? dirname(recvVal) : null; + if ( + !targetExpr || + !checkPyPathArg(targetExpr, { + allowRootEqual: false, + allowDevNull: false, + allowArtifactDir: false, + allowArtifactRoot: false, + forbidReadOnlyArtifact: true, + disallowArtifactRoot: true, + customBaseDir: symlinkBaseDir, + }) + ) { + return `Inline Python Path.${method}() target outside allowed roots is blocked for ${roleLabel}.`; + } + } else if (method === "rename" || method === "replace") { + const { positionals: mPos, kwargs: mKw } = splitPythonCallArgs(methodArgs); + const targetExpr = mPos[0] ?? mKw.target ?? ""; + const recvVal = recv.found ? resolveStaticArgValue(recv.expr, code, true) : null; + const srcOkForRoArtifact = allowReadOnlyArtifactCopySource + ? Boolean(recvVal && allowReadOnlyArtifactCopySource(recvVal)) + : Boolean(recvVal && /\.(?:png|jpe?g|webp)$/i.test(recvVal)); + if ( + !targetExpr || + !checkPyPathArg(targetExpr, { allowRootEqual: true, allowDevNull: false, allowArtifactDir: false, + allowArtifactRoot: false, + forbidReadOnlyArtifact: !srcOkForRoArtifact, }) ) { return `Inline Python Path.${method}() target outside allowed roots is blocked for ${roleLabel}.`; @@ -3245,19 +3372,27 @@ function checkInlinePythonFs(code, allowPath, options = {}) { if (!callArgs) { return `Unparseable ${fnName}() call in inline Python script is blocked for ${roleLabel}.`; } - const { positionals } = splitPythonCallArgs(callArgs); + const { positionals, kwargs } = splitPythonCallArgs(callArgs); if (["copy", "copy2", "copyfile", "copytree"].includes(fnName)) { if (!qualifier && !/\bshutil\b/.test(code)) continue; - const srcVal = resolveStaticArgValue(positionals[0] || "", code, true); - const srcIsImg = Boolean(srcVal && /\.(?:png|jpe?g|webp)$/i.test(srcVal)); - const allowImgDir = srcIsImg && (fnName === "copy" || fnName === "copy2"); + const srcExpr = positionals[0] ?? kwargs.src ?? ""; + const dstExpr = positionals[1] ?? kwargs.dst ?? ""; + const isCopyTree = fnName === "copytree"; + const srcVal = !isCopyTree ? resolveStaticArgValue(srcExpr, code, true) : null; + const srcOkForRoArtifact = + !isCopyTree && + (allowReadOnlyArtifactCopySource + ? Boolean(srcVal && allowReadOnlyArtifactCopySource(srcVal)) + : Boolean(srcVal && /\.(?:png|jpe?g|webp)$/i.test(srcVal))); + const allowImgDir = srcOkForRoArtifact && (fnName === "copy" || fnName === "copy2"); if ( - !checkPyPathArg(positionals[1] || "", { + !dstExpr || + !checkPyPathArg(dstExpr, { allowRootEqual: true, allowDevNull: true, allowArtifactDir: allowImgDir, allowArtifactRoot: allowImgDir, - forbidReadOnlyArtifact: fnName === "copytree", + forbidReadOnlyArtifact: isCopyTree || !srcOkForRoArtifact, }) ) { return `Inline Python ${fnName}() destination outside allowed roots is blocked for ${roleLabel}.`; @@ -3265,37 +3400,65 @@ function checkInlinePythonFs(code, allowPath, options = {}) { continue; } if (["rename", "renames", "replace", "move", "symlink", "link"].includes(fnName)) { - const isLink = fnName === "symlink" || fnName === "link"; + const srcExpr = positionals[0] ?? kwargs.src ?? ""; + const dstExpr = positionals[1] ?? kwargs.dst ?? ""; + const isSymlink = fnName === "symlink"; + const isLink = isSymlink || fnName === "link"; + const srcVal = !isLink ? resolveStaticArgValue(srcExpr, code, true) : null; + const dstVal = isSymlink ? resolveStaticArgValue(dstExpr, code, true) : null; + const symlinkBaseDir = + isSymlink && dstVal && isAbsolute(dstVal) ? dirname(dstVal) : null; + const srcOkForRoArtifact = + !isLink && + (allowReadOnlyArtifactCopySource + ? Boolean(srcVal && allowReadOnlyArtifactCopySource(srcVal)) + : Boolean(srcVal && /\.(?:png|jpe?g|webp)$/i.test(srcVal))); + const allowMoveDir = srcOkForRoArtifact && fnName === "move"; if ( - !checkPyPathArg(positionals[0] || "", { + !srcExpr || + !dstExpr || + !checkPyPathArg(srcExpr, { allowRootEqual: false, allowDevNull: false, forbidReadOnlyArtifact: isLink, + disallowArtifactRoot: isLink, + customBaseDir: symlinkBaseDir, }) || - !checkPyPathArg(positionals[1] || "", { + !checkPyPathArg(dstExpr, { allowRootEqual: true, allowDevNull: false, - allowArtifactDir: false, - forbidReadOnlyArtifact: isLink, + allowArtifactDir: allowMoveDir, + allowArtifactRoot: allowMoveDir, + forbidReadOnlyArtifact: isLink || !srcOkForRoArtifact, + disallowArtifactRoot: isLink, }) ) { return `Inline Python ${fnName}() outside allowed roots is blocked for ${roleLabel}.`; } continue; } + const singleExpr = positionals[0] ?? kwargs.path ?? kwargs.name ?? ""; const isMkdir = fnName === "mkdir" || fnName === "makedirs"; const forbidRo = ["rmdir", "removedirs", "rmtree", "chmod", "chown"].includes(fnName); if ( - !checkPyPathArg(positionals[0] || "", { + !singleExpr || + !checkPyPathArg(singleExpr, { allowRootEqual: isMkdir, allowDevNull: false, allowArtifactDir: isMkdir, + requireArtifactDir: isMkdir, allowArtifactRoot: isMkdir, forbidReadOnlyArtifact: forbidRo, }) ) { return `Inline Python ${fnName}() outside allowed roots is blocked for ${roleLabel}.`; } + if (isMkdir && registerReadOnlyMkdir) { + const mkdirVal = + resolveStaticArgValue(singleExpr, code, true) ?? + resolveStaticJoinOrTemplate(unwrapPythonPathCtor(singleExpr), code, true); + if (mkdirVal) registerReadOnlyMkdir(mkdirVal); + } } const screenshotRe = /\.\s*screenshot\s*\(/g; @@ -3744,6 +3907,8 @@ function extractUnzipWriteTargets(args) { function extractRsyncWriteSpec(args) { let dryRun = false; + let hasDelete = false; + let removeSourceFiles = false; const positionals = []; let afterDoubleDash = false; for (let i = 0; i < args.length; i += 1) { @@ -3756,6 +3921,12 @@ function extractRsyncWriteSpec(args) { if (arg === "-n" || arg === "--dry-run" || arg === "--list-only" || (!arg.startsWith("--") && /^-[a-zA-Z]*n/.test(arg))) { dryRun = true; } + if (arg.startsWith("--del")) { + hasDelete = true; + } + if (arg === "--remove-source-files") { + removeSourceFiles = true; + } if (["-e", "--rsh", "--exclude", "--include", "--filter", "--files-from", "--log-file", "--out-format", "--compare-dest", "--copy-dest", "--link-dest"].includes(arg)) { i += 1; } @@ -3763,8 +3934,16 @@ function extractRsyncWriteSpec(args) { } positionals.push(arg); } - if (dryRun || positionals.length < 2) return { dryRun: true, destination: null }; - return { dryRun: false, destination: positionals[positionals.length - 1] }; + if (dryRun || positionals.length < 2) { + return { dryRun: true, destination: null, sources: [], hasDelete: false, removeSourceFiles: false }; + } + return { + dryRun: false, + destination: positionals[positionals.length - 1], + sources: positionals.slice(0, -1), + hasDelete, + removeSourceFiles, + }; } function extractFindEffects(args) { @@ -3827,6 +4006,7 @@ function checkSharedTargetConfinement(inv, allowPath, roleLabel, validateInnerTo allowRootEqual: true, allowDevNull: false, allowArtifactDir: true, + requireArtifactDir: true, allowArtifactRoot: true, }), ) @@ -3928,7 +4108,25 @@ function checkSharedTargetConfinement(inv, allowPath, roleLabel, validateInnerTo if (/^(?:[A-Za-z0-9._-]+@)?[A-Za-z0-9._-]+:/.test(spec.destination) || spec.destination.startsWith("rsync://")) { return `Command 'rsync' to remote destination is blocked for ${roleLabel}.`; } - if (!allowPath(spec.destination, { allowRootEqual: true, allowDevNull: false, forbidReadOnlyArtifact: true })) { + if ( + !allowPath(spec.destination, { + allowRootEqual: true, + allowDevNull: false, + forbidReadOnlyArtifact: true, + isRecursiveDelete: spec.hasDelete, + disallowArtifactRoot: spec.hasDelete, + }) || + (spec.removeSourceFiles && + spec.sources.some( + (s) => + !allowPath(s, { + allowRootEqual: false, + allowDevNull: false, + forbidReadOnlyArtifact: true, + isRecursiveDelete: true, + }), + )) + ) { return `Command 'rsync' targeting outside allowed paths is blocked for ${roleLabel}.`; } } @@ -4227,7 +4425,26 @@ function extractInlineCodeCheck(inv, allowPath, nodePyOptions) { return null; } -function isMutatingReadOnlyInvocation(inv, allowReadOnlyTempPath, validateInnerTokens) { +function hasCpRecursiveOrArchiveFlag(args) { + for (const arg of args) { + if (arg === "--") break; + if (arg === "--recursive" || arg === "--archive" || arg.startsWith("--archive=")) { + return true; + } + if (!arg.startsWith("--") && /^-[A-Za-z]*[rRa]/.test(arg)) { + return true; + } + } + return false; +} + +function isMutatingReadOnlyInvocation( + inv, + allowReadOnlyTempPath, + validateInnerTokens, + checkReadOnlyCopySource = null, + registerReadOnlyMkdir = null, +) { const { cmd, args } = inv; if (!cmd) return null; @@ -4251,8 +4468,13 @@ function isMutatingReadOnlyInvocation(inv, allowReadOnlyTempPath, validateInnerT if (cmd === "cp") { const cpSpec = extractCpOrMvSpec(args); - const allSourcesImages = - cpSpec.sources.length > 0 && cpSpec.sources.every((s) => /\.(?:png|jpe?g|webp)$/i.test(s)); + const hasRecOrArchive = hasCpRecursiveOrArchiveFlag(args); + const validArtifactImageCopy = + !hasRecOrArchive && + cpSpec.sources.length > 0 && + cpSpec.sources.every((s) => + checkReadOnlyCopySource ? checkReadOnlyCopySource(s) : /\.(?:png|jpe?g|webp)$/i.test(s), + ); if ( !cpSpec.valid || cpSpec.destinations.some( @@ -4260,8 +4482,9 @@ function isMutatingReadOnlyInvocation(inv, allowReadOnlyTempPath, validateInnerT !allowReadOnlyTempPath(d, { allowRootEqual: true, allowDevNull: true, - allowArtifactDir: allSourcesImages, - allowArtifactRoot: allSourcesImages, + allowArtifactDir: validArtifactImageCopy, + allowArtifactRoot: validArtifactImageCopy, + forbidReadOnlyArtifact: !validArtifactImageCopy, }), ) ) { @@ -4272,8 +4495,11 @@ function isMutatingReadOnlyInvocation(inv, allowReadOnlyTempPath, validateInnerT if (cmd === "mv") { const mvSpec = extractCpOrMvSpec(args); - const allSourcesImages = - mvSpec.sources.length > 0 && mvSpec.sources.every((s) => /\.(?:png|jpe?g|webp)$/i.test(s)); + const validArtifactImageMove = + mvSpec.sources.length > 0 && + mvSpec.sources.every((s) => + checkReadOnlyCopySource ? checkReadOnlyCopySource(s) : /\.(?:png|jpe?g|webp)$/i.test(s), + ); if ( !mvSpec.valid || mvSpec.sources.some((s) => !allowReadOnlyTempPath(s, { allowRootEqual: false, allowDevNull: false })) || @@ -4282,8 +4508,9 @@ function isMutatingReadOnlyInvocation(inv, allowReadOnlyTempPath, validateInnerT !allowReadOnlyTempPath(d, { allowRootEqual: true, allowDevNull: false, - allowArtifactDir: allSourcesImages, - allowArtifactRoot: allSourcesImages, + allowArtifactDir: validArtifactImageMove, + allowArtifactRoot: validArtifactImageMove, + forbidReadOnlyArtifact: !validArtifactImageMove, }), ) ) { @@ -4311,6 +4538,8 @@ function isMutatingReadOnlyInvocation(inv, allowReadOnlyTempPath, validateInnerT const inlineDeny = extractInlineCodeCheck(inv, allowReadOnlyTempPath, { allowDynamicPaths: false, roleLabel: "read-only ro-* workers", + allowReadOnlyArtifactCopySource: checkReadOnlyCopySource, + registerReadOnlyMkdir, }); if (inlineDeny) return inlineDeny; @@ -4413,7 +4642,9 @@ function checkAuthorShellConfinement(inv, allowAuthorShellPath, resolveForBase, const lnSpec = extractLnSpec(args); if ( !lnSpec.valid || - lnSpec.linkPaths.some((l) => !allowAuthorShellPath(l, { allowRootEqual: true, allowDevNull: false })) + lnSpec.linkPaths.some( + (l) => !allowAuthorShellPath(l, { allowRootEqual: true, allowDevNull: false, disallowArtifactRoot: true }), + ) ) { return "Command 'ln' creating a link outside confined worker worktree, artifact directory, or canonical temp roots is blocked."; } @@ -4421,10 +4652,18 @@ function checkAuthorShellConfinement(inv, allowAuthorShellPath, resolveForBase, const linkBaseDir = resolvedLink ? (lnSpec.linkIsDir ? resolvedLink : dirname(resolvedLink)) : null; for (const src of lnSpec.sources) { if (!lnSpec.isSymbolic) { - if (!allowAuthorShellPath(src, { allowRootEqual: false, allowDevNull: false })) { + if (!allowAuthorShellPath(src, { allowRootEqual: false, allowDevNull: false, disallowArtifactRoot: true })) { return "Command 'ln' hardlinking a source outside confined worker worktree, artifact directory, or canonical temp roots is blocked."; } - } else if (linkBaseDir && !allowAuthorShellPath(src, { allowRootEqual: true, allowDevNull: false, customBaseDir: linkBaseDir })) { + } else if ( + linkBaseDir && + !allowAuthorShellPath(src, { + allowRootEqual: true, + allowDevNull: false, + customBaseDir: linkBaseDir, + disallowArtifactRoot: true, + }) + ) { return "Command 'ln -s' pointing outside confined worker worktree, artifact directory, or canonical temp roots is blocked."; } } @@ -4653,23 +4892,104 @@ function resolveWorkerConfinementRoots(payload, env, appDataDir) { return { hasValidCwd, realCwd, fallbackBaseDir, realArtifact, canonicalTempRoots }; } +function hasUnsafeArtifactRelativePath(resolvedPath, realArtifact) { + if (!resolvedPath || !realArtifact || !isStrictlyInside(resolvedPath, realArtifact)) { + return false; + } + const rel = relative(realArtifact, resolvedPath); + if (rel.includes(".system_generated")) return true; + if ((rel.includes("{") || rel.includes("}")) && rel.includes("..")) return true; + const firstSeg = rel.split(/[\\/]/)[0] || ""; + if (!firstSeg) return false; + if (/^[*?[{^]/.test(firstSeg)) return true; + if (/^[!+@]\(/.test(firstSeg)) return true; + if (firstSeg.includes("{") || firstSeg.includes("}")) return true; + if (firstSeg.startsWith(".") && /[*?[\]()]/.test(firstSeg)) return true; + return false; +} + function isSystemGeneratedArtifactPath(resolvedPath, realArtifact) { if (!resolvedPath || !realArtifact) return false; - return isInsideOrEqual(resolvedPath, join(realArtifact, ".system_generated")); + if (isInsideOrEqual(resolvedPath, join(realArtifact, ".system_generated"))) return true; + return hasUnsafeArtifactRelativePath(resolvedPath, realArtifact); +} + +function isValidReadOnlyImageSourcePath(resolvedSrc, pendingMkdirs = null) { + if (!resolvedSrc) return false; + if (/[*?[\]{}]/.test(resolvedSrc)) return false; + if (pendingMkdirs && pendingMkdirs.has(resolvedSrc)) return false; + const leaf = basename(resolvedSrc); + if (!leaf || leaf.startsWith(".") || !/\.(?:png|jpe?g|webp)$/i.test(leaf)) { + return false; + } + try { + const st = lstatSync(resolvedSrc); + if (st.isDirectory() || st.isSymbolicLink()) return false; + } catch {} + return true; +} + +function isCleanArtifactDirSegment(seg) { + return ( + Boolean(seg) && + !seg.startsWith(".") && + extname(seg) === "" && + !/[*?[\]{}()]/.test(seg) + ); } function isAllowedReadOnlyArtifactPath( resolvedPath, realArtifact, realCwd, - { allowDirectory = false } = {}, + { allowDirectory = false, requireDirectory = false } = {}, ) { if (!resolvedPath || !realArtifact) return false; if (!isStrictlyInside(resolvedPath, realArtifact)) return false; if (isSystemGeneratedArtifactPath(resolvedPath, realArtifact)) return false; if (realCwd && isInsideOrEqual(resolvedPath, realCwd)) return false; - if (/\.(?:png|jpe?g|webp)$/i.test(resolvedPath)) return true; - if (allowDirectory === true && extname(resolvedPath) === "") return true; + + const rel = relative(realArtifact, resolvedPath); + const segments = rel.split(/[\\/]/).filter(Boolean); + if (segments.length === 0) return false; + + if (requireDirectory) { + let cur = realArtifact; + for (const seg of segments) { + if (!isCleanArtifactDirSegment(seg)) return false; + cur = join(cur, seg); + try { + if (!lstatSync(cur).isDirectory()) return false; + } catch {} + } + return true; + } + + let cur = realArtifact; + for (let i = 0; i < segments.length - 1; i += 1) { + const seg = segments[i]; + if (!isCleanArtifactDirSegment(seg)) return false; + cur = join(cur, seg); + try { + if (!lstatSync(cur).isDirectory()) return false; + } catch {} + } + + const leaf = segments[segments.length - 1]; + if (!leaf || leaf.startsWith(".") || leaf.includes("{") || leaf.includes("}")) { + return false; + } + let leafStat = null; + try { + leafStat = lstatSync(resolvedPath); + } catch {} + if (leafStat && leafStat.isSymbolicLink()) return false; + if (/\.(?:png|jpe?g|webp)$/i.test(leaf)) { + return !(leafStat && leafStat.isDirectory()); + } + if (allowDirectory === true && isCleanArtifactDirSegment(leaf)) { + return !(leafStat && !leafStat.isDirectory()); + } return false; } @@ -4743,30 +5063,35 @@ function handlePreToolUse(payload, env) { const validateReadOnlyShell = (code, inheritedEnv = {}, outerEnv = env, depth = 0) => { if (depth > 4) return "Nested shell script depth limit exceeded for read-only ro-* workers."; const { invocations, redirectTargets } = collectInvocations(code, 0, inheritedEnv, outerEnv); + const pendingMkdirs = new Set(); const makeAllowInvTempPath = (mergedEnv) => (rawToken, opts = {}) => { const { allowRootEqual = false, allowDevNull = false, allowArtifactDir = false, + requireArtifactDir = false, allowArtifactRoot = false, forbidReadOnlyArtifact = false, + disallowArtifactRoot = false, + customBaseDir = null, } = opts; - const resolved = resolveShellTargetPath(rawToken, fallbackBaseDir, mergedEnv); + const resolved = resolveShellTargetPath(rawToken, customBaseDir || fallbackBaseDir, mergedEnv); if (!resolved) return false; if (allowDevNull && resolved === "/dev/null") return true; if (isSystemGeneratedArtifactPath(resolved, realArtifact)) return false; if (realArtifact && isInsideOrEqual(resolved, realArtifact)) { if (forbidReadOnlyArtifact) return false; - if ( - allowArtifactRoot && - resolved === realArtifact && - !(realCwd && isInsideOrEqual(resolved, realCwd)) - ) { - return true; + if (resolved === realArtifact) { + return ( + Boolean(allowArtifactRoot) && + !disallowArtifactRoot && + !(realCwd && isInsideOrEqual(resolved, realCwd)) + ); } return isAllowedReadOnlyArtifactPath(resolved, realArtifact, realCwd, { allowDirectory: Boolean(allowArtifactDir), + requireDirectory: Boolean(requireArtifactDir), }); } return isInsideCanonicalTempRoots(resolved, canonicalTempRoots, realCwd, { @@ -4775,6 +5100,11 @@ function handlePreToolUse(payload, env) { }); }; + const makeCheckReadOnlyCopySource = (mergedEnv) => (rawToken) => { + const resolvedSrc = resolveShellTargetPath(rawToken, fallbackBaseDir, mergedEnv); + return isValidReadOnlyImageSourcePath(resolvedSrc, pendingMkdirs); + }; + for (const redirectTarget of redirectTargets) { const mergedEnv = { ...outerEnv, ...redirectTarget.env }; if (!makeAllowInvTempPath(mergedEnv)(redirectTarget.target, { allowRootEqual: false, allowDevNull: true })) { @@ -4785,6 +5115,11 @@ function handlePreToolUse(payload, env) { for (const inv of invocations) { const mergedEnv = { ...outerEnv, ...inv.env }; const allowInvTempPath = makeAllowInvTempPath(mergedEnv); + const checkReadOnlyCopySource = makeCheckReadOnlyCopySource(mergedEnv); + const registerReadOnlyMkdir = (rawToken) => { + const resolvedDir = resolveShellTargetPath(rawToken, fallbackBaseDir, mergedEnv); + if (resolvedDir) pendingMkdirs.add(resolvedDir); + }; const validateInnerTokens = (innerTokens, searchRoots) => { const innerInv = unwrapCommandSegment(innerTokens, inv.env, outerEnv); if (!innerInv.cmd) return null; @@ -4794,14 +5129,41 @@ function handlePreToolUse(payload, env) { } return allowInvTempPath(rawToken, opts); }; - return isMutatingReadOnlyInvocation(innerInv, innerAllow, validateInnerTokens); + const innerCopySourceCheck = (rawToken) => { + if (rawToken === "{}" || rawToken.includes("{}")) return false; + return checkReadOnlyCopySource(rawToken); + }; + return isMutatingReadOnlyInvocation( + innerInv, + innerAllow, + validateInnerTokens, + innerCopySourceCheck, + registerReadOnlyMkdir, + ); }; - const denyReason = isMutatingReadOnlyInvocation(inv, allowInvTempPath, validateInnerTokens); + const denyReason = isMutatingReadOnlyInvocation( + inv, + allowInvTempPath, + validateInnerTokens, + checkReadOnlyCopySource, + registerReadOnlyMkdir, + ); if (denyReason) return denyReason; + if (inv.cmd === "mkdir") { + for (const p of extractPathsSkippingValueFlags(inv.args, new Set(["-m", "--mode"]))) { + registerReadOnlyMkdir(p); + } + } + const scriptDeny = inspectTempScriptFile(inv, { allowPath: allowInvTempPath, - nodePyOptions: { allowDynamicPaths: false, roleLabel: "read-only ro-* workers" }, + nodePyOptions: { + allowDynamicPaths: false, + roleLabel: "read-only ro-* workers", + allowReadOnlyArtifactCopySource: checkReadOnlyCopySource, + registerReadOnlyMkdir, + }, canonicalTempRoots, realCwd, fallbackBaseDir, @@ -4942,6 +5304,7 @@ function handlePreToolUse(payload, env) { allowDevNull = false, customBaseDir = null, isRecursiveDelete = false, + disallowArtifactRoot = false, } = opts; const activeBase = customBaseDir || realCwd; if (!activeBase && !isAbsolute(rawToken) && !rawToken.startsWith("~") && !rawToken.startsWith("$")) { @@ -4962,7 +5325,7 @@ function handlePreToolUse(payload, env) { return true; } if (realArtifact && isInsideOrEqual(resolved, realArtifact)) { - return allowRootEqual ? true : isStrictlyInside(resolved, realArtifact); + return allowRootEqual && !disallowArtifactRoot ? true : isStrictlyInside(resolved, realArtifact); } return isInsideCanonicalTempRoots(resolved, canonicalTempRoots, realCwd, { allowRootEqual, diff --git a/hooks/guard.test.mjs b/hooks/guard.test.mjs index ed1cb81..b236449 100644 --- a/hooks/guard.test.mjs +++ b/hooks/guard.test.mjs @@ -2501,24 +2501,69 @@ describe("agy 1.5.9 native swarm compatibility caveats", () => { assert.equal(runRoShell(cmd).decision, "allow", `expected ro screenshot shell allow: ${cmd}`); } + const evilDirPng = join(slashTmpDir, "evil_dir.png"); + const payloadSh = join(slashTmpDir, "payload.sh"); + const existingDirInExplicitArt = join(roExplicitArtifact, "existing_dir.png"); + mkdirSync(evilDirPng, { recursive: true }); + mkdirSync(existingDirInExplicitArt, { recursive: true }); + writeFileSync(payloadSh, "#!/bin/sh\necho pwn\n", "utf8"); + writeFileSync(join(evilDirPng, "payload.sh"), "#!/bin/sh\necho pwn\n", "utf8"); + + assert.equal( + callFileTool("ro-c2", "write_file", existingDirInExplicitArt, roExplicitArtifact).decision, + "deny", + ); + assert.equal( + callFileTool("ro-c2", "write_file", join(roFallbackArtifact, "evil.png", "shot.png")).decision, + "deny", + ); + assert.equal( + callFileTool("ro-c2", "write_file", join(roFallbackArtifact, ".png")).decision, + "deny", + ); + const roDeniedCmds = [ `echo bad > ${join(roFallbackArtifact, "report.md")}`, `echo bad > ${join(roFallbackArtifact, ".system_generated", "shot.png")}`, + `echo bad > ${join(roFallbackArtifact, "evil.png", "shot.png")}`, + `echo bad > ${join(roFallbackArtifact, ".png")}`, `cp ${join(slashTmpDir, "notes.md")} ${join(roFallbackArtifact, "shots")}`, `cp ${join(slashTmpDir, "notes.md")} ${join(roFallbackArtifact, "notes.md")}`, `mv ${join(slashTmpDir, "notes.txt")} ${join(roFallbackArtifact, "notes.txt")}`, `tee ${join(roFallbackArtifact, "out.json")}`, `curl -sL https://example.com/data -o ${join(roFallbackArtifact, "out.json")}`, `mkdir -p ${join(roFallbackArtifact, "notes.md")}`, + `mkdir -p ${join(roFallbackArtifact, "evil.png")}`, + `mkdir -p ${join(roFallbackArtifact, ".png")}`, + `mkdir -p ${join(roFallbackArtifact, "evil.png")} && cp ${payloadSh} ${join(roFallbackArtifact, "evil.png")}`, `mkdir -p ${join(roFallbackArtifact, ".system_generated", "sub")}`, + `cp -r ${evilDirPng} ${join(roFallbackArtifact, "shots")}`, + `cp -a ${evilDirPng} ${join(roFallbackArtifact, "shots")}`, + `cp ${evilDirPng} ${join(roFallbackArtifact, "shots")}`, + `mv ${evilDirPng} ${join(roFallbackArtifact, "shots")}`, + `mkdir -p ${join(slashTmpDir, "staged_dir.png")} && mv ${join(slashTmpDir, "staged_dir.png")} ${join(roFallbackArtifact, "shots")}`, + `cp ${payloadSh} ${join(roFallbackArtifact, "disguised.png")}`, + `mv ${payloadSh} ${join(roFallbackArtifact, "disguised.png")}`, + `cp ${join(slashTmpDir, "*.png")} ${join(roFallbackArtifact, "shots")}`, `rm -f ${join(roFallbackArtifact, "notes.md")}`, `rm -rf ${roFallbackArtifact}`, `ln -s /etc/passwd ${join(roFallbackArtifact, "shot.png")}`, `node -e "require('node:fs').writeFileSync('${join(roFallbackArtifact, "notes.md")}', 'x')"`, + `node -e "require('node:fs').mkdirSync('${join(roFallbackArtifact, "evil.png")}', { recursive: true })"`, + `node -e "require('node:fs').copyFileSync('${payloadSh}', '${join(roFallbackArtifact, "disguised.png")}')"`, + `node -e "require('node:fs').cpSync('${evilDirPng}', '${join(roFallbackArtifact, "shots", "evil_dir.png")}', { recursive: true })"`, + `node -e "const fs = require('node:fs'); fs.mkdirSync('${join(slashTmpDir, "inline_dir.png")}'); fs.renameSync('${join(slashTmpDir, "inline_dir.png")}', '${join(roFallbackArtifact, "shots", "inline_dir.png")}')"`, `node -e "require('node:fs').symlinkSync('/etc/passwd', '${join(roFallbackArtifact, "shot.png")}')"`, `node -e "await page.screenshot({ path: '${join(sb.outsideDir, "escape.png")}' })"`, `node ${tempBadPlaywrightMjs}`, `python3 -c "open('${join(roFallbackArtifact, "notes.txt")}', 'w').write('x')"`, + `python3 -c "import os, shutil; os.makedirs('${join(roFallbackArtifact, "evil.png")}', exist_ok=True); shutil.copy('${payloadSh}', '${join(roFallbackArtifact, "evil.png")}')"`, + `python3 -c "import os; os.makedirs('${join(roFallbackArtifact, "evil.png")}', exist_ok=True)"`, + `python3 -c "from pathlib import Path; Path('${join(roFallbackArtifact, "evil.png")}').mkdir(parents=True, exist_ok=True)"`, + `python3 -c "import shutil; shutil.copy('${payloadSh}', '${join(roFallbackArtifact, "disguised.png")}')"`, + `python3 -c "import shutil; shutil.copytree('${evilDirPng}', '${join(roFallbackArtifact, "shots", "evil_dir.png")}')"`, + `python3 -c "import os, shutil; os.makedirs('${join(slashTmpDir, "py_dir.png")}', exist_ok=True); shutil.move('${join(slashTmpDir, "py_dir.png")}', '${join(roFallbackArtifact, "shots")}')"`, + `python3 -c "from pathlib import Path; Path('${join(slashTmpDir, "ro_repo_sym")}').symlink_to('${join(sb.worktree, "README.md")}')"`, `python3 -c "page.screenshot(path='${join(roFallbackArtifact, ".system_generated", "x.png")}')"`, ]; for (const cmd of roDeniedCmds) { @@ -2541,9 +2586,26 @@ describe("agy 1.5.9 native swarm compatibility caveats", () => { `cp ${join(slashTmpDir, "a.json")} ${swarmPlanTarget}`, `rm -rf ${join(artDir, ".system_generated")}`, `rm -rf ${artDir}`, + `rm -rf ${join(artDir, ".*")}`, + `rm -rf ${join(artDir, ".s*")}`, + `rm -rf ${join(artDir, ".?ystem_generated")}`, + `rm -rf ${join(artDir, "[.]system_generated")}`, + `rm -rf ${join(artDir, "*")}`, + `rm -rf ${join(artDir, "{.system_generated,scratch}")}`, + `rm -rf ${join(artDir, "scratch", "{../.system_generated,a}")}`, + `rsync -a --delete ${slashTmpDir}/ ${artDir}/`, + `rsync -a --del ${slashTmpDir}/ ${artDir}/`, + `rsync -a --delete-after ${slashTmpDir}/ ${artDir}/`, + `rsync -a --remove-source-files ${artDir} ${slashTmpDir}/out/`, + `ln -s ${artDir} ${join(slashTmpDir, "art_root_link")}`, `find ${artDir} -delete`, `node -e "require('node:fs').writeFileSync('${transcriptTarget}', '{}')"`, `python3 -c "open('${transcriptTarget}', 'w').write('{}')"`, + `python3 -c "from pathlib import Path; Path('${join(slashTmpDir, "sym")}').symlink_to('${transcriptTarget}')" && echo "{}" > ${join(slashTmpDir, "sym")}`, + `python3 -c "from pathlib import Path; Path('${join(slashTmpDir, "hl")}').hardlink_to('${transcriptTarget}')"`, + `python3 -c "from pathlib import Path; p = Path('${join(slashTmpDir, "sym_var")}'); p.symlink_to('${transcriptTarget}')"`, + `python3 -c "from pathlib import Path; Path('${join(slashTmpDir, "sym_out")}').symlink_to(Path('${join(sb.outsideDir, "outside.txt")}'))"`, + `python3 -c "from pathlib import Path; Path('${join(slashTmpDir, "sym_root")}').symlink_to('${artDir}')"`, ]) { assert.equal( runGuard( @@ -2562,6 +2624,27 @@ describe("agy 1.5.9 native swarm compatibility caveats", () => { } } + for (const allowedImplCmd of [ + `rsync -a --delete ${slashTmpDir}/ ${join(implArtifact, "scratch")}/`, + `rm -rf ${join(implArtifact, "scratch", "*")}`, + `python3 -c "from pathlib import Path; Path('${join(slashTmpDir, "ok_sym")}').symlink_to('${join(sb.worktree, "src.js")}')"`, + ]) { + assert.equal( + runGuard( + { + hookEventName: "PreToolUse", + conversationId: "impl-c2", + rootConversationId: "coord-c2", + cwd: sb.worktree, + toolCall: { id: "impl-ok", name: "run_command", args: { CommandLine: allowedImplCmd } }, + }, + { PSTACK_APPDATA_DIR: sb.appDataDir, TMPDIR: sb.customTmpDir }, + ).decision, + "allow", + `expected impl confined command allow: ${allowedImplCmd}`, + ); + } + assert.equal( callFileTool("impl-c2", "write_file", join(implArtifact, "notes.md")).decision, "allow",