diff --git a/README.md b/README.md index 443a55f..6c2ce69 100644 --- a/README.md +++ b/README.md @@ -39,7 +39,7 @@ New to the toolkit or unsure which workflow fits a task? Ask [`/agy-pstack-next: ## Hook-Enforced Swarm Architecture -Pstack v2 replaces prompt-only delegation rules with mechanical enforcement via root [`hooks.json`](./hooks.json), global `~/.gemini/config/hooks.json` registration (configured by `/setup-pstack` so native `Swarm Worker` subagents execute the same hook while sharing `/plugin_data/agy-pstack-next` state), [`hooks/guard.mjs`](./hooks/guard.mjs), and four role capsules under `roles/`. +Pstack v2 replaces prompt-only delegation rules with mechanical enforcement via root [`hooks.json`](./hooks.json), global `~/.gemini/config/hooks.json` registration (configured by `/setup-pstack` so native `Swarm Worker` subagents execute the same `SessionStart`, `PreInvocation`, `PreToolUse`, and `Stop` hook while sharing per-conversation state under `/plugin_data/agy-pstack-next/capsules/`), [`hooks/guard.mjs`](./hooks/guard.mjs), and four role capsules under `roles/`. ### Prefix-Typed Roster Contract @@ -48,19 +48,19 @@ Every swarm member's prefix determines its workspace isolation, injected role ca | Member Prefix | Default Workspace | Role Capsule | Enforced Permissions | |---|---|---|---| | 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 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`. | +| `impl-*`, `cand-*`, `lead-*` | `workspace: "share"` | [`roles/poteto-agent.md`](./roles/poteto-agent.md) | Edits strictly inside its own worktree, artifact dir outside `.system_generated/`, and canonical temp roots. `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, artifact dir, and canonical temp roots. `git push` and mutating `gh` commands always blocked. | +| `ro-*` | `workspace: "inherit"` | [`roles/research.md`](./roles/research.md) | Strictly read-only. Blocks `edit_file`, `write_file` outside canonical temp roots and brain-directory timeline screenshots, mutating `git`, `gh`, and MCP calls, and verifies `git status` cleanliness on `Stop`. | +| `sicko-*` | `workspace: "share"` | [`roles/comment-sicko.md`](./roles/comment-sicko.md) | Comment and slop surgeon. Confines `edit_file` to its own worktree. Blocks `write_file`, `git push`, file-restoring or history-rewriting `git` subcommands, and mutating `gh` commands, and rejects untracked or deleted files on `Stop`. | | `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 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. +- **Per-conversation capsule injection.** `SessionStart` and `PreInvocation` resolve each conversation against local `/brain/*/.system_generated/swarm/members.json` or remote `swarm.json` (`--roster-only`) rosters, write per-conversation state atomically under `/plugin_data/agy-pstack-next/capsules/.json`, and inject its matching `roles/*.md` capsule once per role, upgrading cleanly if a worker's roster entry appears after startup. +- **Scoped lifecycle, inline skill pass-through, and plain `/swarm`.** 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, `PreToolUse` gating, and `Stop` cleanliness checks globally. Coordinator activation triggers only on leading swarm-orchestrating slash commands (`/pstack`, `/understand`, `/crucible`, `/interrogate`, `/reflect`, `/verify-gen`, or `/ketchup` without `--plain`) or active swarm rosters, so standalone inline skills (`/bro`, `/technical-writing`, `/setup-pstack`, `/statechart`, `/control-ui`, `/control-cli`, `/make-bot-ui`, and `/ketchup --plain`), mid-sentence `/pstack` mentions, and plain built-in `/swarm` sessions without pstack prefixes pass through unmanaged. +- **Native swarm exclusivity.** `PreToolUse` blocks `run_workflow` and legacy subagent tools (except `invoke_subagent` targeting `image-generator`) across all managed roles so every pstack workflow runs on the shared `#seq` message board. +- **Zero-regex, zero-sandbox structural confinement.** `PreToolUse` resolves `realpathSync` on the deepest existing ancestor of every `edit_file` and `write_file` path, blocking `../` traversal, symlink escapes into sibling worktrees, and worker writes inside `.system_generated/`, while parsing `run_command` argv structurally only for `git` and `gh` footguns with zero shell regexes or OS sandboxing. +- **Read-only research integrity and `Stop` cleanliness checks.** `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 `Stop` verifies `git status` cleanliness for `ro-*` and rejects untracked or deleted files for `sicko-*`. - **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 930ce53..0e0b6c7 100644 --- a/docs/guide/01-setup.md +++ b/docs/guide/01-setup.md @@ -25,9 +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` 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. +2. **Registers `pstack-swarm-guard` in global `~/.gemini/config/hooks.json`.** Root plugin [`hooks.json`](../../hooks.json) covers top-level sessions across `SessionStart`, `PreInvocation`, `PreToolUse`, and `Stop`, 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 ''` across those four hook events. Both hook paths share `/plugin_data/agy-pstack-next` state (per-conversation `capsules/.json` files and `member-map.json`), so swarm workers enforce capsules, structural zero-regex/zero-sandbox tool confinement, and `Stop` cleanliness checks 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. +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, `PreToolUse` gating, and `Stop` cleanliness checks across global hooks too. Standalone inline skills (`/bro`, `/technical-writing`, `/setup-pstack`, `/statechart`, `/control-ui`, `/control-cli`, `/make-bot-ui`, and `/ketchup --plain`), mid-sentence `/pstack` prose mentions, and plain built-in `/swarm` sessions without 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/docs/guide/02-pstack.md b/docs/guide/02-pstack.md index 6dd06f1..8bad173 100644 --- a/docs/guide/02-pstack.md +++ b/docs/guide/02-pstack.md @@ -1,6 +1,6 @@ # Route work through `/pstack` -[`/pstack`](../../skills/pstack/SKILL.md) is the swarm coordinator kernel. You describe the outcome and how to verify it. The coordinator selects one of six composable topologies, sizes a prefix-typed worker roster on the native swarm board, enforces worktree boundaries through `hooks/guard.mjs`, and lands only verified commits. +[`/pstack`](../../skills/pstack/SKILL.md) is the swarm coordinator kernel. You describe the outcome and how to verify it. The coordinator selects one of six composable topologies, sizes a prefix-typed worker roster on the native swarm board, enforces structural zero-regex, zero-sandbox worktree boundaries through [`hooks.json`](../../hooks.json) and [`hooks/guard.mjs`](../../hooks/guard.mjs), and lands only verified commits. ![A dispatcher pulls a switch lever to route robots on rail handcars toward lit gates for bug fixes, features, and investigations.](./images/router.jpg) @@ -63,8 +63,8 @@ If you want help tightening a high-stakes prompt before launching a swarm, ask [ Running parallel authors in one directory corrupts files, git index state, and dev ports. Pstack v2 isolates swarm execution mechanically. -- **`workspace: "share"` per author.** Every `impl-*`, `cand-*`, `lead-*`, `adv-*`, and `sicko-*` worker gets its own git working copy. [`hooks/guard.mjs`](../../hooks/guard.mjs) resolves `realpathSync` on every `edit_file` and `write_file` call so no worker can escape its worktree via `../` or symlinks. -- **Read-only `ro-*` workers.** Explorers and verifiers run in `workspace: "inherit"` with zero repository write permissions, keeping temporary test artifacts strictly under `/tmp`. +- **`workspace: "share"` per author.** Every `impl-*`, `cand-*`, `lead-*`, `adv-*`, and `sicko-*` worker gets its own git working copy. [`hooks/guard.mjs`](../../hooks/guard.mjs) stores per-conversation capsule state under `capsules/` and resolves `realpathSync` on every `edit_file` and `write_file` call with zero regexes or OS sandboxing so no worker can escape its worktree via `../` or symlinks. +- **Read-only `ro-*` workers and `Stop` cleanliness checks.** Explorers and verifiers run in `workspace: "inherit"` with zero repository write permissions (`edit_file` and mutating `git`, `gh`, and MCP calls are blocked, keeping `write_file` probes strictly under canonical temp roots and timeline screenshots). On `Stop`, `hooks/guard.mjs` checks `git status` cleanliness for `ro-*` and rejects untracked or deleted files for `sicko-*`. Inline non-swarm skills (`/bro`, `/technical-writing`, `/setup-pstack`, `/statechart`, `/control-ui`, `/control-cli`, `/make-bot-ui`, and `/ketchup --plain`) pass through unmanaged. - **Merge before `kill`.** Calling `swarm{action: "kill"}` permanently deletes a worker's `share` worktree. The coordinator always fetches and merges (or cherry-picks) verified worker SHAs before killing any worker. - **`#seq` citations and doorbell `@mentions`.** Workers reference earlier board messages by `#seq` number rather than pasting duplicate logs, and `@mention` only the specific peer who needs to wake next. diff --git a/docs/guide/03-understand.md b/docs/guide/03-understand.md index 077922f..f0bee02 100644 --- a/docs/guide/03-understand.md +++ b/docs/guide/03-understand.md @@ -6,7 +6,7 @@ Editing unfamiliar code blind is the fastest way to ship subtle regressions. Age ## One parallel `ro-*` mesh, three modes -[`/understand`](../../skills/understand/SKILL.md) spawns a read-only swarm mesh (`ro-code`, `ro-git`, `ro-tracker`, `ro-docs` in `workspace: "inherit"`). Because `hooks/guard.mjs` enforces read-only safety mechanically across files, shell commands, and MCP tools, every `ro-*` worker can cross-query source files, `git log` and `git blame`, GitHub PRs, issue trackers, and design docs simultaneously. Workers post `#seq` clues on the shared board so peers pivot live when `git blame` uncovers a decisive PR or incident ticket. +[`/understand`](../../skills/understand/SKILL.md) spawns a read-only swarm mesh (`ro-code`, `ro-git`, `ro-tracker`, `ro-docs` in `workspace: "inherit"`). Because `hooks/guard.mjs` enforces structural zero-regex, zero-sandbox read-only gating across `edit_file`, `write_file`, mutating `git` and `gh` commands, and mutating MCP tools (with per-conversation `capsules/` state and `Stop` `git status` cleanliness checks), every `ro-*` worker can cross-query source files, `git log` and `git blame`, GitHub PRs, issue trackers, and design docs simultaneously. Workers post `#seq` clues on the shared board so peers pivot live when `git blame` uncovers a decisive PR or incident ticket. Pick any of `/understand`'s three modes through natural phrasing. @@ -54,7 +54,7 @@ When returning to a long-running swarm or resuming work from earlier in the week Parallel `ro-*` gatherers inspect `board.jsonl` `#seq` deltas, `members.json` roster state (plus `/brain//swarm_view/view.json` when `narrator` is active in Antigravity 2.0), prior `/brain/*/.system_generated/swarm/` boards, `git log`, and open `gh pr` status without mutating anything. Every item waiting on your decision comes back with options, `#seq` evidence, and risk so you can decide from the briefing alone. -Run [`/bro`](../../skills/bro/SKILL.md) (`/agy-pstack-next:bro`) to restate the previous message in plain everyday words, pass `--plain` to `/ketchup` for a zero-jargon catch-up summary, or pass `--video` for a short subtitled slide walkthrough of what changed: +Run [`/bro`](../../skills/bro/SKILL.md) (`/agy-pstack-next:bro`) to restate the previous message in plain everyday words, pass `--plain` to `/ketchup` for a zero-jargon catch-up summary, or pass `--video` for a short subtitled slide walkthrough of what changed. Standalone `/bro` and `/ketchup --plain` invocations pass through `hooks/guard.mjs` unmanaged without activating coordinator capsules or blocking subagents: ```text /agy-pstack-next:bro diff --git a/docs/guide/05-build-and-clean.md b/docs/guide/05-build-and-clean.md index 2d7b7c9..7f5613e 100644 --- a/docs/guide/05-build-and-clean.md +++ b/docs/guide/05-build-and-clean.md @@ -49,7 +49,7 @@ When `impl-*`, `adv-*`, and `ro-verify` exercise apps concurrently on one machin ## TypeScript and test-first discipline in the capsule -Every `impl-*`, `cand-*`, and `lead-*` worker receives [`roles/poteto-agent.md`](../../roles/poteto-agent.md) automatically via `hooks/guard.mjs`, backed by [`ts-patterns.md`](../../skills/pstack/references/ts-patterns.md). +Every `impl-*`, `cand-*`, and `lead-*` worker receives [`roles/poteto-agent.md`](../../roles/poteto-agent.md) automatically via `hooks/guard.mjs` (tracked per conversation under `capsules/`), backed by [`ts-patterns.md`](../../skills/pstack/references/ts-patterns.md). - **Behavioral tests first.** Write the smallest test that fails for the intended user-observable reason before changing production code. Skip brittle mock-heavy unit scaffolding when running the real CLI or HTTP boundary proves more. - **Illegal states unrepresentable.** Parse external data as `unknown` at boundaries, model state transitions with discriminated unions, enforce exhaustiveness with `never`, and derive types from authoritative schemas. @@ -58,9 +58,9 @@ Every `impl-*`, `cand-*`, and `lead-*` worker receives [`roles/poteto-agent.md`] Authors defend their own narrating comments and defensive boilerplate. Before `ro-verify` signs off on a non-trivial diff in `build` or `ship`, `/pstack` spawns `sicko-clean` (`workspace: "share"`), which receives [`roles/comment-sicko.md`](../../roles/comment-sicko.md). -`hooks/guard.mjs` enforces `sicko-*` boundaries mechanically. It permits `edit_file` inside the worker's worktree while blocking `write_file` and `git push`, ensuring cleanup never invents new wrapper files or pushes unverified commits. `sicko-*` keeps only license headers, public API docstrings, external bug links, and genuine third-party quirk explanations. Every comment that apologizes for confusing internal code becomes either a root-cause simplification or a structural type, lint, or test check, and the comment comes out. +`hooks/guard.mjs` enforces `sicko-*` boundaries structurally with zero regexes or OS sandboxing. It confines `edit_file` to the worker's worktree, blocks `write_file`, `git push`, file-restoring or history-rewriting `git` subcommands, and mutating `gh` commands, and checks `git status` on `Stop` to reject untracked or deleted files. `sicko-*` keeps only license headers, public API docstrings, external bug links, and genuine third-party quirk explanations. Every comment that apologizes for confusing internal code becomes either a root-cause simplification or a structural type, lint, or test check, and the comment comes out. -For standalone documentation, READMEs, RFCs, and PR bodies, invoke [`/technical-writing`](../../skills/technical-writing/SKILL.md) to enforce Diataxis mode discipline, crisp Global English syntax, zero AI filler, and `ro-*` technical accuracy checks. +For standalone documentation, READMEs, RFCs, and PR bodies, invoke [`/technical-writing`](../../skills/technical-writing/SKILL.md) (which passes through `hooks/guard.mjs` unmanaged as a standalone inline skill) to enforce Diataxis mode discipline, crisp Global English syntax, zero AI filler, and `ro-*` technical accuracy checks. **Pitfall.** Never treat diff cleanup as optional polish after review. Redundant guards, narrating comments, and dead compatibility branches hide bugs and slow down every reviewer who reads the PR. diff --git a/hooks.json b/hooks.json index 9a4e5d1..4a0a8d1 100644 --- a/hooks.json +++ b/hooks.json @@ -35,6 +35,13 @@ } ] } + ], + "Stop": [ + { + "type": "command", + "command": "./hooks/guard.mjs", + "timeout": 10 + } ] } } diff --git a/hooks/guard.mjs b/hooks/guard.mjs index f58bc02..533c569 100755 --- a/hooks/guard.mjs +++ b/hooks/guard.mjs @@ -17,186 +17,117 @@ import { } from "node:fs"; import { homedir, tmpdir } from "node:os"; import { basename, dirname, extname, isAbsolute, join, relative, resolve } from "node:path"; -import { fileURLToPath } from "node:url"; - -const LEGACY_SUBAGENT_TOOLS = new Set([ - "invoke_subagent", - "define_subagent", - "manage_subagents", - "send_message", - "run_workflow", -]); - -const SWARM_BOARD_TOOLS = new Set([ - "post_message", - "read_board", - "swarm_wait", - "swarm", -]); - -const PSTACK_SLASH_COMMAND_RE = - /(?:^|\s)\/(?:agy-pstack-next:)?(?:pstack|setup-pstack|understand|crucible|interrogate|reflect|ketchup|bro|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/; - +import { fileURLToPath, pathToFileURL } from "node:url"; + +function wordSet(text) { + return new Set(text.split(" ").filter(Boolean)); +} + +const LEGACY_SUBAGENT_TOOLS = wordSet( + "invoke_subagent define_subagent manage_subagents send_message run_workflow", +); +const SWARM_BOARD_TOOLS = wordSet( + "post_message read_board swarm_wait swarm list_resources read_resource", +); +const MUTATING_MCP_VERBS = wordSet( + "create update delete remove set post reply resolve merge close push write edit append restore upload generate install uninstall send modify patch drop insert", +); +const COORDINATOR_SLASH_COMMANDS = wordSet( + "pstack understand crucible interrogate reflect verify-gen ketchup", +); +const RO_BLOCKED_GIT_SUBCOMMANDS = wordSet( + "add stage commit push pull merge rebase cherry-pick reset clean am apply mv rm checkout switch revert restore init clone update-ref", +); +const SICKO_BLOCKED_GIT_SUBCOMMANDS = wordSet( + "push pull fetch checkout switch restore reset clean rebase merge cherry-pick revert stash worktree init clone am apply rm mv", +); +const GH_MUTATING_ACTIONS = { + pr: wordSet("create merge close reopen edit ready comment review"), + issue: wordSet("create edit close delete reopen comment"), + release: wordSet("create delete edit upload"), + repo: wordSet("create delete edit fork archive rename"), +}; +const SCREENSHOT_EXTENSIONS = wordSet(".png .jpg .jpeg .webp"); +const SHELL_KEYWORDS = wordSet("if then else elif fi while until do done { } !"); const ROLE_OVERRIDE_NOTICE = "> **Role override.** Your active swarm role has changed. The role capsule below supersedes every earlier role capsule in this conversation history, including rules inherited through `fork`.\n\n"; -const MUTATING_MCP_PATTERN = - /(^|_)(create|update|delete|remove|set|post|reply|resolve|merge|close|push|write|edit|append|restore|upload|generate|install|uninstall|send|modify|patch|drop|insert)(_|$)/i; - -const MUTATING_GIT_SUBCOMMANDS = new Set([ - "add", - "stage", - "commit", - "push", - "pull", - "merge", - "rebase", - "cherry-pick", - "reset", - "clean", - "am", - "apply", - "mv", - "rm", - "checkout", - "switch", - "revert", - "restore", - "init", - "clone", - "update-ref", -]); - -const GIT_GLOBAL_VALUE_FLAGS = new Set([ - "-C", - "-c", - "--git-dir", - "--work-tree", - "--namespace", - "--super-prefix", - "--config-env", -]); - -const HARD_BLOCKED_RO_FS_COMMANDS = new Set([ - "rmdir", - "chown", - "chgrp", - "patch", - "ln", -]); +function isDigit(code) { + return code >= 48 && code <= 57; +} -const SICKO_BLOCKED_FS_COMMANDS = new Set([ - "cp", - "mv", - "rm", - "rmdir", - "unlink", - "ln", - "install", - "mkdir", - "touch", - "truncate", - "dd", - "patch", - "chmod", - "chown", - "chgrp", -]); +function isAlpha(code) { + return (code >= 65 && code <= 90) || (code >= 97 && code <= 122); +} -const NPM_INSTALL_SUBCOMMANDS = new Set([ - "install", - "i", - "add", - "ci", - "uninstall", - "remove", - "rm", - "un", - "update", - "up", - "link", - "unlink", - "dedupe", - "prune", - "rebuild", - "publish", - "init", - "dlx", -]); +function isIdentPart(code) { + return isAlpha(code) || code === 95 || isDigit(code); +} -const PIP_INSTALL_SUBCOMMANDS = new Set([ - "install", - "uninstall", - "download", - "wheel", -]); +function isWhitespaceChar(ch) { + return ch === " " || ch === "\t" || ch === "\n" || ch === "\r"; +} -const NODE_SINGLE_PATH_FS_APIS = new Set([ - "writeFileSync", - "writeFile", - "appendFileSync", - "appendFile", - "unlinkSync", - "unlink", - "rmSync", - "rm", - "rmdirSync", - "rmdir", - "mkdirSync", - "mkdir", - "mkdtempSync", - "mkdtemp", - "chmodSync", - "chmod", - "chownSync", - "chown", - "truncateSync", - "truncate", - "createWriteStream", -]); +function isAllDigits(text) { + if (text.length === 0) { + return false; + } + for (let i = 0; i < text.length; i += 1) { + if (!isDigit(text.charCodeAt(i))) { + return false; + } + } + return true; +} -const NODE_TWO_PATH_FS_APIS = new Set([ - "renameSync", - "rename", - "symlinkSync", - "symlink", - "linkSync", - "link", -]); +function isShellIdent(text) { + if (text.length === 0) { + return false; + } + const first = text.charCodeAt(0); + if (!isAlpha(first) && first !== 95) { + return false; + } + for (let i = 1; i < text.length; i += 1) { + if (!isIdentPart(text.charCodeAt(i))) { + return false; + } + } + return true; +} -const NODE_COPY_FS_APIS = new Set([ - "copyFileSync", - "copyFile", - "cpSync", - "cp", -]); +function isSafeConvId(conversationId) { + return ( + typeof conversationId === "string" && + conversationId.length > 0 && + !conversationId.includes("/") && + !conversationId.includes("\\") && + conversationId !== "." && + conversationId !== ".." + ); +} -function normalizeToolName(rawName) { - const name = typeof rawName === "string" ? rawName : String(rawName || ""); - return name.startsWith("default_api:") ? name.slice("default_api:".length) : name; +function parseJsonObjectSafe(raw) { + if (typeof raw !== "string" || !raw.trim()) { + return null; + } + try { + const parsed = JSON.parse(raw); + if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) { + return parsed; + } + } catch { + return null; + } + return null; } function readJsonObject(filePath) { try { - if (!existsSync(filePath)) return {}; - const parsed = JSON.parse(readFileSync(filePath, "utf8")); - return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {}; + if (!existsSync(filePath)) { + return {}; + } + return parseJsonObjectSafe(readFileSync(filePath, "utf8")) || {}; } catch { return {}; } @@ -205,30 +136,27 @@ function readJsonObject(filePath) { function writeJsonAtomically(filePath, obj) { const dir = dirname(filePath); mkdirSync(dir, { recursive: true }); - const suffix = `${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}`; - const tmpPath = join(dir, `.${basename(filePath)}.${suffix}.tmp`); - const serialized = JSON.stringify(obj, null, 2) + "\n"; + const suffix = `${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`; + const tmpPath = join(dir, `.${basename(filePath)}.${suffix}`); + const serialized = `${JSON.stringify(obj, null, 2)}\n`; try { writeFileSync(tmpPath, serialized, "utf8"); renameSync(tmpPath, filePath); } catch { try { - if (existsSync(tmpPath)) unlinkSync(tmpPath); + if (existsSync(tmpPath)) { + unlinkSync(tmpPath); + } } catch {} writeFileSync(filePath, serialized, "utf8"); } } -function updateJsonKey(filePath, key, value) { - const current = readJsonObject(filePath); - if (current[key] === value) return; - current[key] = value; - writeJsonAtomically(filePath, current); -} - function updateJsonKeys(filePath, entries) { const keys = Object.keys(entries); - if (keys.length === 0) return; + if (keys.length === 0) { + return; + } const current = readJsonObject(filePath); let changed = false; for (const key of keys) { @@ -242,382 +170,598 @@ function updateJsonKeys(filePath, entries) { } } +function safeConvFilename(conversationId) { + if (typeof conversationId !== "string" || !conversationId) { + return "__unknown__"; + } + if (conversationId === "." || conversationId === "..") { + return "__dot__"; + } + let out = ""; + for (let i = 0; i < conversationId.length; i += 1) { + const c = conversationId.charCodeAt(i); + if (isAlpha(c) || isDigit(c) || c === 46 || c === 95 || c === 45) { + out += conversationId[i]; + } else { + out += "_"; + } + } + return out; +} + +function capsuleStatePath(cacheDir, conversationId) { + return join(cacheDir, "capsules", `${safeConvFilename(conversationId)}.json`); +} + +function readCapsuleState(cacheDir, conversationId) { + if (!conversationId) { + return {}; + } + return readJsonObject(capsuleStatePath(cacheDir, conversationId)); +} + +function updateCapsuleState(cacheDir, conversationId, patch) { + const next = { ...readCapsuleState(cacheDir, conversationId), ...patch }; + writeJsonAtomically(capsuleStatePath(cacheDir, conversationId), next); + return next; +} + function resolveAppDataDir(payload, env) { - if (typeof env.PSTACK_APPDATA_DIR === "string" && env.PSTACK_APPDATA_DIR.length > 0) { + if (typeof env.PSTACK_APPDATA_DIR === "string" && env.PSTACK_APPDATA_DIR) { return env.PSTACK_APPDATA_DIR; } - const candidates = [payload.transcriptPath, payload.artifactDirectoryPath]; - for (const candidate of candidates) { - if (typeof candidate !== "string" || candidate.length === 0) continue; - const normalized = candidate.replace(/\\/g, "/"); - const brainIdx = normalized.indexOf("/brain/"); + for (const candidate of [payload.transcriptPath, payload.artifactDirectoryPath]) { + if (typeof candidate !== "string" || !candidate) { + continue; + } + const norm = candidate.replaceAll("\\", "/"); + const brainIdx = norm.indexOf("/brain/"); if (brainIdx > 0) { return candidate.slice(0, brainIdx); } - if (normalized.endsWith("/brain") && normalized.length > 6) { - return candidate.slice(0, normalized.length - 6); + if (norm.endsWith("/brain") && norm.length > 6) { + return candidate.slice(0, norm.length - 6); + } + const marker = "/.gemini/antigravity"; + const markerIdx = norm.indexOf(marker); + if (markerIdx >= 0) { + let end = markerIdx + marker.length; + if (norm[end] === "-") { + const start = end + 1; + end = start; + while (end < norm.length && (isIdentPart(norm.charCodeAt(end)) || norm[end] === "-")) { + end += 1; + } + if (end === start) { + end = -1; + } + } + if (end > 0 && (end === norm.length || norm[end] === "/")) { + return candidate.slice(0, end); + } } } - for (const candidate of candidates) { - if (typeof candidate !== "string" || candidate.length === 0) continue; - const match = candidate.match(/^(.*?[/\\]\.gemini[/\\]antigravity(?:-[a-zA-Z0-9_-]+)?)(?:[/\\]|$)/); - if (match) return match[1]; - } - if (typeof env.ANTIGRAVITY_APP_DATA_DIR === "string" && env.ANTIGRAVITY_APP_DATA_DIR.length > 0) { + if (typeof env.ANTIGRAVITY_APP_DATA_DIR === "string" && env.ANTIGRAVITY_APP_DATA_DIR) { return env.ANTIGRAVITY_APP_DATA_DIR; } - if (typeof env.PLUGIN_DATA === "string" && env.PLUGIN_DATA.length > 0) { - const parent = dirname(env.PLUGIN_DATA); - if (basename(parent) === "plugin_data") { - return dirname(parent); + if (typeof env.PLUGIN_DATA === "string" && env.PLUGIN_DATA) { + if (basename(dirname(env.PLUGIN_DATA)) === "plugin_data") { + return dirname(dirname(env.PLUGIN_DATA)); } } return null; } function resolveCacheDir(appDataDir, env) { - if (typeof env.PSTACK_CACHE_DIR === "string" && env.PSTACK_CACHE_DIR.length > 0) { + if (typeof env.PSTACK_CACHE_DIR === "string" && env.PSTACK_CACHE_DIR) { return env.PSTACK_CACHE_DIR; } - if (typeof env.PLUGIN_DATA === "string" && env.PLUGIN_DATA.length > 0) { + if (typeof env.PLUGIN_DATA === "string" && env.PLUGIN_DATA) { return env.PLUGIN_DATA; } - return appDataDir - ? join(appDataDir, "plugin_data", "agy-pstack-next") - : join(tmpdir(), "pstack-swarm-guard"); + if (appDataDir) { + return join(appDataDir, "plugin_data", "agy-pstack-next"); + } + return join(tmpdir(), "pstack-swarm-guard"); } function resolvePluginRoot(env) { - if (typeof env.PSTACK_PLUGIN_ROOT === "string" && env.PSTACK_PLUGIN_ROOT.length > 0) { + if (typeof env.PSTACK_PLUGIN_ROOT === "string" && env.PSTACK_PLUGIN_ROOT) { return env.PSTACK_PLUGIN_ROOT; } - if (typeof env.PLUGIN_ROOT === "string" && env.PLUGIN_ROOT.length > 0) { + if (typeof env.PLUGIN_ROOT === "string" && env.PLUGIN_ROOT) { return env.PLUGIN_ROOT; } 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"); +function isPluginDisabled(env) { + let configPath = null; + if (typeof env.PSTACK_CONFIG_DIR === "string" && env.PSTACK_CONFIG_DIR) { + configPath = join(env.PSTACK_CONFIG_DIR, "config.json"); + } else { + const pluginRoot = resolvePluginRoot(env); + if (pluginRoot && basename(dirname(pluginRoot)) === "plugins") { + configPath = join(dirname(dirname(pluginRoot)), "config.json"); + } else if (!env.PSTACK_APPDATA_DIR && !env.PSTACK_PLUGIN_ROOT && !env.PLUGIN_ROOT) { + const home = typeof env.HOME === "string" && env.HOME ? env.HOME : homedir(); + configPath = join(home, ".gemini", "config", "config.json"); + } + } + if (!configPath || !existsSync(configPath)) { + return false; + } + return readJsonObject(configPath)?.plugins?.["agy-pstack-next"]?.enabled === false; +} + +function resolveRealTargetPath(targetPath, baseDir, depth = 0) { + if (depth > 16) { + return null; } - const pluginRoot = resolvePluginRoot(env); - if (pluginRoot && basename(dirname(pluginRoot)) === "plugins") { - return join(dirname(dirname(pluginRoot)), "config.json"); + const absTarget = resolve(baseDir, targetPath); + const tail = []; + let cur = absTarget; + while (true) { + try { + const st = lstatSync(cur); + if (st.isSymbolicLink()) { + try { + const real = realpathSync(cur); + return tail.length > 0 ? join(real, ...tail) : real; + } catch { + const nextTarget = resolve(dirname(cur), readlinkSync(cur)); + const combined = tail.length > 0 ? join(nextTarget, ...tail) : nextTarget; + return resolveRealTargetPath(combined, dirname(cur), depth + 1); + } + } + const real = realpathSync(cur); + return tail.length > 0 ? join(real, ...tail) : real; + } catch { + const parent = dirname(cur); + if (parent === cur) { + return absTarget; + } + tail.unshift(basename(cur)); + cur = parent; + } } - 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"); +} + +function isStrictlyInside(targetPath, rootDir) { + const rel = relative(rootDir, targetPath); + return ( + rel.length > 0 && + rel !== ".." && + !rel.startsWith("../") && + !rel.startsWith("..\\") && + !isAbsolute(rel) + ); +} + +function isInsideOrEqual(targetPath, rootDir) { + return targetPath === rootDir || isStrictlyInside(targetPath, rootDir); +} + +function getCanonicalTempRoots(env) { + const roots = new Set(["/tmp", "/private/tmp"]); + for (const candidate of ["/tmp", "/private/tmp", env.TMPDIR, tmpdir()]) { + if (typeof candidate !== "string" || !candidate) { + continue; + } + try { + roots.add(realpathSync(candidate)); + } catch { + roots.add(resolve(candidate)); + } } - return null; + return [...roots]; } -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 isInsideCanonicalTempRoots( + realTarget, + canonicalTempRoots, + realCwd, + { allowRootEqual = false, excludeRealCwd = false } = {}, +) { + if (!realTarget || (excludeRealCwd && realCwd && isInsideOrEqual(realTarget, realCwd))) { + return false; + } + if (realCwd) { + for (const tempRoot of canonicalTempRoots) { + if (!isStrictlyInside(realCwd, tempRoot)) { + continue; + } + const parts = relative(tempRoot, realCwd).replaceAll("\\", "/").split("/").filter(Boolean); + if (parts.length >= 2) { + const container = join(tempRoot, parts[0]); + if (isInsideOrEqual(realTarget, container) && !isInsideOrEqual(realTarget, join(container, "tmp"))) { + return false; + } + } + } + } + return canonicalTempRoots.some((root) => { + return allowRootEqual ? isInsideOrEqual(realTarget, root) : isStrictlyInside(realTarget, root); + }); +} + +function isSystemGeneratedArtifactPath(resolvedPath, realArtifact) { + if (!resolvedPath || !realArtifact) { + return false; + } + if (isInsideOrEqual(resolvedPath, join(realArtifact, ".system_generated"))) { + return true; + } + if (!isStrictlyInside(resolvedPath, realArtifact)) { + return false; + } + const relParts = relative(realArtifact, resolvedPath).replaceAll("\\", "/").split("/"); + return relParts.includes(".system_generated"); +} + +function isAllowedReadOnlyArtifactImage(resolvedPath, realArtifact, realCwd) { + if (!resolvedPath || !realArtifact || !isStrictlyInside(resolvedPath, realArtifact)) { + return false; + } + if (isSystemGeneratedArtifactPath(resolvedPath, realArtifact)) { + return false; + } + if (realCwd && isInsideOrEqual(resolvedPath, realCwd)) { + return false; + } + const segments = relative(realArtifact, resolvedPath).replaceAll("\\", "/").split("/").filter(Boolean); + if (segments.length === 0) { + return false; + } + let cur = realArtifact; + for (let i = 0; i < segments.length - 1; i += 1) { + if (!segments[i] || segments[i].startsWith(".")) { + return false; + } + cur = join(cur, segments[i]); + try { + if (!lstatSync(cur).isDirectory()) { + return false; + } + } catch {} + } + const leaf = segments[segments.length - 1]; + if (!leaf || leaf.startsWith(".") || !SCREENSHOT_EXTENSIONS.has(extname(leaf).toLowerCase())) { + return false; + } + try { + const st = lstatSync(resolvedPath); + if (st.isSymbolicLink() || st.isDirectory()) { + return false; + } + } catch {} + return true; +} + +function isValidRemoteSwarmId(id) { + if (typeof id !== "string" || id.length < 4 || id.length > 128 || id.startsWith("-")) { + return false; + } + for (let i = 0; i < id.length; i += 1) { + const c = id.charCodeAt(i); + if (!isAlpha(c) && !isDigit(c) && c !== 46 && c !== 95 && c !== 45) { + return false; + } + } + return true; +} + +function stripTrailingNumericSuffix(name) { + const dash = name.lastIndexOf("-"); + if (dash > 0 && dash < name.length - 1 && isAllDigits(name.slice(dash + 1))) { + return name.slice(0, dash); + } + return name; +} + +function classifyLeadingSlash(lastUserInput) { + if (typeof lastUserInput !== "string" || !lastUserInput) { + return { isPstackSlash: false, isBuiltinSwarmSlash: false }; + } + let body = lastUserInput.trimStart(); + while (body.startsWith("<")) { + const closeIdx = body.indexOf(">"); + if (closeIdx <= 1) { + break; + } + const tagBody = body.slice(1, closeIdx); + const firstCode = tagBody.startsWith("/") ? tagBody.charCodeAt(1) : tagBody.charCodeAt(0); + if (tagBody.includes("\n") || (!isAlpha(firstCode) && firstCode !== 95)) { + break; + } + body = body.slice(closeIdx + 1).trimStart(); + } + if (!body.startsWith("/")) { + return { isPstackSlash: false, isBuiltinSwarmSlash: false }; + } + let end = 1; + while (end < body.length && !isWhitespaceChar(body[end]) && body[end] !== "<") { + end += 1; + } + let cmd = body.slice(1, end).toLowerCase(); + if (cmd.startsWith("agy-pstack-next:") || cmd.startsWith("agy-pstack-next/")) { + cmd = cmd.slice(16); + } + if (cmd === "swarm") { + return { isPstackSlash: false, isBuiltinSwarmSlash: true }; + } + if (!COORDINATOR_SLASH_COMMANDS.has(cmd)) { + return { isPstackSlash: false, isBuiltinSwarmSlash: false }; + } + if (cmd === "ketchup") { + let i = end; + while (i < body.length) { + while (i < body.length && isWhitespaceChar(body[i])) { + i += 1; + } + if (i >= body.length) { + break; + } + if (body[i] === "<") { + const close = body.indexOf(">", i + 1); + if (close > i) { + i = close + 1; + continue; + } + } + let tEnd = i; + while (tEnd < body.length && !isWhitespaceChar(body[tEnd]) && body[tEnd] !== "<") { + tEnd += 1; + } + if (body.slice(i, tEnd) === "--plain") { + return { isPstackSlash: false, isBuiltinSwarmSlash: false }; + } + i = tEnd; + } + } + return { isPstackSlash: true, isBuiltinSwarmSlash: false }; } function resolveOwnTranscriptPath(payload, appDataDir) { - if (typeof payload.transcriptPath === "string" && payload.transcriptPath.length > 0) { + if (typeof payload.transcriptPath === "string" && payload.transcriptPath) { return payload.transcriptPath; } - if (appDataDir && typeof payload.conversationId === "string" && payload.conversationId.length > 0) { - const stdPath = join( - appDataDir, - "brain", - payload.conversationId, - ".system_generated", - "logs", - "transcript.jsonl", - ); - if (existsSync(stdPath)) return stdPath; - const flatPath = join(appDataDir, "brain", payload.conversationId, "transcript.jsonl"); - if (existsSync(flatPath)) return flatPath; + if (!appDataDir || !isSafeConvId(payload.conversationId)) { + return null; + } + const candidates = [ + join(appDataDir, "brain", payload.conversationId, ".system_generated", "logs", "transcript.jsonl"), + join(appDataDir, "brain", payload.conversationId, "transcript.jsonl"), + ]; + for (const candidate of candidates) { + if (existsSync(candidate)) { + return candidate; + } } return null; } +function hasForkMemoryMarker(text) { + if (typeof text !== "string") { + return false; + } + const prefix = "Everything before this turn is @"; + const suffix = "'s memory"; + let idx = text.indexOf(prefix); + while (idx !== -1) { + let pos = idx + prefix.length; + while (pos < text.length && (isIdentPart(text.charCodeAt(pos)) || text[pos] === "-")) { + pos += 1; + } + if (pos > idx + prefix.length && text.startsWith(suffix, pos)) { + return true; + } + idx = text.indexOf(prefix, idx + 1); + } + return false; +} + function isSystemRoleCapsuleStep(parsed) { - if (!parsed || typeof parsed !== "object") return false; + if (!parsed || typeof parsed !== "object") { + return false; + } if (parsed.type !== "SYSTEM_MESSAGE" && parsed.source !== "SYSTEM_SDK") { return false; } - return typeof parsed.content === "string" && ROLE_CAPSULE_HEADING_RE.test(parsed.content); + if (typeof parsed.content !== "string") { + return false; + } + const suffix = " role capsule"; + return parsed.content.split("\n").some((raw) => { + const line = (raw.endsWith("\r") ? raw.slice(0, -1) : raw).toLowerCase(); + return line.startsWith("# ") && line.endsWith(suffix) && line.length > 2 + suffix.length; + }); } -function transcriptIsUnforkedUserRoot(transcriptPath, hasPriorInjectedCapsule) { - if (!transcriptPath || !existsSync(transcriptPath)) return false; +function transcriptIsUnforkedUserRoot(transcriptPath, hasPriorCapsule) { + if (!transcriptPath || !existsSync(transcriptPath)) { + return false; + } try { const content = readFileSync(transcriptPath, "utf8"); if ( - /\[swarm\] new board message|Your assignment \(recorded on the board/.test(content) || - FORK_MEMORY_MARKER_RE.test(content) + content.includes("[swarm] new board message") || + content.includes("Your assignment (recorded on the board") || + hasForkMemoryMarker(content) ) { return false; } - let sawFirstStep = false; - for (const line of content.split(/\r?\n/)) { - const trimmed = line.trim(); - if (!trimmed) continue; + let sawFirst = false; + for (const rawLine of content.split("\n")) { + const trimmed = rawLine.trim(); + if (!trimmed) { + continue; + } const parsed = JSON.parse(trimmed); - if (!parsed || typeof parsed !== "object") return false; - if (!sawFirstStep) { - if (parsed.type !== "USER_INPUT") return false; - sawFirstStep = true; + if (!parsed || typeof parsed !== "object") { + return false; + } + if (!sawFirst) { + if (parsed.type !== "USER_INPUT") { + return false; + } + sawFirst = true; } - if (typeof parsed.content === "string" && FORK_MEMORY_MARKER_RE.test(parsed.content)) { + if (hasForkMemoryMarker(parsed.content)) { return false; } - if (!hasPriorInjectedCapsule && isSystemRoleCapsuleStep(parsed)) { + if (!hasPriorCapsule && isSystemRoleCapsuleStep(parsed)) { return false; } } - return sawFirstStep; + return sawFirst; } catch { return false; } } function transcriptContainsRoleCapsule(transcriptPath) { - if (!transcriptPath || !existsSync(transcriptPath)) return false; - try { - const content = readFileSync(transcriptPath, "utf8"); - for (const line of content.split(/\r?\n/)) { - const trimmed = line.trim(); - if (!trimmed) continue; - try { - const parsed = JSON.parse(trimmed); - if (isSystemRoleCapsuleStep(parsed)) { - return true; - } - } catch {} - } - } catch { + if (!transcriptPath || !existsSync(transcriptPath)) { return false; } + try { + for (const rawLine of readFileSync(transcriptPath, "utf8").split("\n")) { + const parsed = parseJsonObjectSafe(rawLine); + if (parsed && (isSystemRoleCapsuleStep(parsed) || hasForkMemoryMarker(parsed.content))) { + return true; + } + } + } catch {} return false; } -function extractMembersFromDoc(doc, targetConversationId, fallbackCoordId = null) { +function extractMembersFromDoc(doc, targetConvId, fallbackCoordId = null) { const workerEntries = {}; let matchedCoordinator = false; - let coordId = - typeof fallbackCoordId === "string" && fallbackCoordId.length > 0 ? fallbackCoordId : null; + let coordId = typeof fallbackCoordId === "string" && fallbackCoordId ? 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, - coordId, - hasPstackPrefixedWorker, - hasTaskWorker, - }; - } - for (const [memberName, info] of Object.entries(members)) { - if (!info || typeof info !== "object") continue; + const members = doc && typeof doc === "object" && doc.members && typeof doc.members === "object" ? doc.members : {}; + for (const [name, info] of Object.entries(members)) { + if (!info || typeof info !== "object") { + continue; + } const cid = info.conversation_id || info.conversationId; - if (memberName === "coordinator" || info.role === "coordinator") { - if (typeof cid === "string" && cid.length > 0) { + if (name === "coordinator" || info.role === "coordinator") { + if (typeof cid === "string" && cid) { coordId = cid; - if (cid === targetConversationId) matchedCoordinator = true; + if (cid === targetConvId) { + matchedCoordinator = true; + } } continue; } - if (PSTACK_WORKER_PREFIX_RE.test(memberName)) { + const lower = name.toLowerCase(); + if (["impl-", "cand-", "lead-", "ro-", "adv-", "sicko-"].some((prefix) => lower.startsWith(prefix))) { hasPstackPrefixedWorker = true; } - if (!BUILTIN_SUPPORT_MEMBER_RE.test(memberName)) { + const base = stripTrailingNumericSuffix(lower); + if (base !== "coordinator" && base !== "monitor" && base !== "narrator") { hasTaskWorker = true; } - if (typeof cid === "string" && cid.length > 0) { - workerEntries[cid] = memberName; + if (typeof cid === "string" && cid) { + workerEntries[cid] = name; } } - return { - hasMembers: true, - workerEntries, - matchedCoordinator, - coordId, - hasPstackPrefixedWorker, - hasTaskWorker, - }; -} - -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; + return { workerEntries, matchedCoordinator, coordId, hasPstackPrefixedWorker, hasTaskWorker }; } -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; +function resolveRemoteBoardCli(anchor, appDataDir, env) { + if (typeof env.PSTACK_REMOTE_SWARM_CLI === "string" && env.PSTACK_REMOTE_SWARM_CLI) { + return env.PSTACK_REMOTE_SWARM_CLI; } - if ( - doc.backend === "local" && - typeof doc.swarm_id === "string" && - doc.swarm_id.length > 0 && - !doc.swarm_id.startsWith("-") && - REMOTE_SWARM_ID_RE.test(doc.swarm_id) - ) { - return doc.swarm_id; + let cfgPath = null; + if (typeof env.PSTACK_REMOTE_BOARD_CONFIG === "string" && env.PSTACK_REMOTE_BOARD_CONFIG) { + cfgPath = env.PSTACK_REMOTE_BOARD_CONFIG; + } else if (appDataDir) { + cfgPath = join(appDataDir, "builtin", "plugins", "swarm", "sidecars", "swarm_board", "remote_board.json"); } - return ownerDirId; -} - -function parseRemoteSwarmAnchor(doc) { - if (!doc || typeof doc !== "object") return null; - if (typeof doc.backend !== "string" || doc.backend.length === 0 || doc.backend === "local") { + if (!cfgPath || !existsSync(cfgPath)) { return null; } - if ( - typeof doc.swarm_id !== "string" || - doc.swarm_id.startsWith("-") || - !REMOTE_SWARM_ID_RE.test(doc.swarm_id) - ) { + const cfg = readJsonObject(cfgPath); + if (typeof cfg.backend !== "string" || cfg.backend !== anchor.backend) { return null; } - let db = ""; - if (doc.db !== undefined && doc.db !== null && doc.db !== "") { - if (typeof doc.db !== "string" || doc.db.startsWith("-")) { - return null; + const isExecutable = (filePath) => { + try { + accessSync(filePath, fsConstants.X_OK); + return statSync(filePath).isFile(); + } catch { + return false; + } + }; + const envOverride = typeof cfg.cli_env === "string" && cfg.cli_env ? env[cfg.cli_env] : ""; + if (typeof envOverride === "string" && envOverride) { + if (!envOverride.includes("/") || isExecutable(envOverride)) { + return envOverride; } - 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; + const cliList = Array.isArray(cfg.cli) ? cfg.cli.filter((c) => typeof c === "string" && c) : []; + const pathDirs = String(env.PATH || process.env.PATH || "").split(":").filter(Boolean); + for (const candidate of cliList) { + const locations = candidate.includes("/") ? [candidate] : pathDirs.map((dir) => join(dir, candidate)); + const found = locations.find(isExecutable); + if (found) { + return found; + } } + return cliList[cliList.length - 1] || null; } -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; +function resolveRemoteSwarmRoster(anchorDoc, appDataDir, cacheDir, env, targetConvId) { + if (!anchorDoc || typeof anchorDoc !== "object") { + return null; } - 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) { + if (typeof anchorDoc.backend !== "string" || !anchorDoc.backend || anchorDoc.backend === "local") { 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; + if (!isValidRemoteSwarmId(anchorDoc.swarm_id)) { + return null; } - 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; + if (anchorDoc.db !== undefined && anchorDoc.db !== null && anchorDoc.db !== "") { + if (typeof anchorDoc.db !== "string" || anchorDoc.db.startsWith("-")) { + return null; + } } - return false; -} - -function resolveRemoteSwarmRoster(anchorDoc, appDataDir, cacheDir, env, targetConversationId) { - const anchor = parseRemoteSwarmAnchor(anchorDoc); - if (!anchor) return null; + const anchor = { backend: anchorDoc.backend, swarmId: anchorDoc.swarm_id, db: anchorDoc.db || "" }; const cliBin = resolveRemoteBoardCli(anchor, appDataDir, env); - if (!cliBin) return null; - + 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 }; + const cached = readJsonObject(rostersPath)[anchor.swarmId]; + if ( + cached && + typeof cached === "object" && + typeof cached.fetchedAt === "number" && + cached.members && + typeof cached.members === "object" && + !Array.isArray(cached.members) + ) { + const age = Date.now() - cached.fetchedAt; + const inRoster = Boolean( + targetConvId && + Object.values(cached.members).some((info) => { + return info && typeof info === "object" && (info.conversation_id || info.conversationId) === targetConvId; + }), + ); + const ttlMs = inRoster ? 15000 : 5000; + if (age >= 0 && age < ttlMs) { + return { members: cached.members }; } } - try { - const cliArgs = [ - "swarm", - "--json", - "--roster-only", - ...(anchor.db ? ["--db", anchor.db] : []), - anchor.swarmId, - ]; + const cliArgs = ["swarm", "--json", "--roster-only"]; + if (anchor.db) { + cliArgs.push("--db", anchor.db); + } + cliArgs.push(anchor.swarmId); const stdout = execFileSync(cliBin, cliArgs, { encoding: "utf8", timeout: 2500, @@ -625,374 +769,172 @@ function resolveRemoteSwarmRoster(anchorDoc, appDataDir, cacheDir, env, targetCo 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 {} + for (const rawLine of String(stdout || "").split("\n")) { + const doc = parseJsonObjectSafe(rawLine); + if (doc && doc.swarm_id === anchor.swarmId && doc.members && typeof doc.members === "object" && !Array.isArray(doc.members)) { + matchedMembers = doc.members; + } } - if (!matchedMembers) return null; - updateJsonKey(rostersPath, anchor.swarmId, { - fetchedAt: Date.now(), - members: matchedMembers, - }); + if (!matchedMembers) { + return null; + } + updateJsonKeys(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, - }); +function inspectSwarmDirectory(swarmDir, ownerDirId, targetConvId, opts) { + function classifyRoster(doc, fallbackCoordId, ownMatch) { + const ext = extractMembersFromDoc(doc, targetConvId, fallbackCoordId); + const coordState = ext.coordId ? readCapsuleState(opts.cacheDir, ext.coordId) : {}; + const hasCoordCapsule = typeof coordState.capsule === "string" && coordState.capsule.length > 0; + const hasMarkerFile = existsSync(join(swarmDir, "pstack.json")); + const managed = ext.hasPstackPrefixedWorker || hasCoordCapsule || hasMarkerFile || (!coordState.plainSwarm && !ext.hasTaskWorker); + const matchedCoordinator = ext.matchedCoordinator || ownMatch; 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, - }; + const targetIsWorker = Boolean(ext.workerEntries[targetConvId]); + const targetInSwarm = Boolean(targetIsWorker || matchedCoordinator || ext.coordId === targetConvId); + return { kind: "unmanaged_swarm", targetInSwarm, targetIsWorker }; } - return { - kind: "managed_roster", - workerEntries: extracted.workerEntries, - matchedCoordinator: extracted.matchedCoordinator || isOwnSwarmDir, - hasUnmatchedAnchor: false, - }; + return { kind: "managed_roster", workerEntries: ext.workerEntries, matchedCoordinator }; } + const membersPath = join(swarmDir, "members.json"); + if (existsSync(membersPath)) { + return classifyRoster(readJsonObject(membersPath), ownerDirId, opts.isOwnSwarmDir); + } 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, - ); + const explicit = + anchorDoc.coordinator_conversation_id || + anchorDoc.coordinatorConversationId || + anchorDoc.coordinator_id || + anchorDoc.coordinatorId; + let anchorCoordId = ownerDirId; + if (typeof explicit === "string" && explicit) { + anchorCoordId = explicit; + } else if (anchorDoc.backend === "local" && isValidRemoteSwarmId(anchorDoc.swarm_id)) { + anchorCoordId = anchorDoc.swarm_id; + } + const remoteRoster = resolveRemoteSwarmRoster(anchorDoc, opts.appDataDir, opts.cacheDir, opts.env, targetConvId); 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, - }; - } - - 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 classifyRoster(remoteRoster, anchorCoordId, anchorCoordId === targetConvId); } - - if (anchorDoc?.backend === "local") { + if (anchorCoordId !== targetConvId) { return { kind: "none" }; } - - return { kind: "anchor_unresolved" }; + const coordState = readCapsuleState(opts.cacheDir, anchorCoordId); + if (coordState.plainSwarm && !coordState.capsule && !existsSync(join(swarmDir, "pstack.json"))) { + return { kind: "unmanaged_swarm", targetInSwarm: true, targetIsWorker: false }; + } + return { kind: "anchor_coordinator" }; } -function resolveWorkerOrCoordinatorFromSwarm( - conversationId, - payload, - appDataDir, - cacheDir, - hasPriorInjectedCapsule, - env, - injectedMap, - plainSwarmRoots, -) { - if (typeof conversationId !== "string" || conversationId.length === 0) { - return { workerName: null, isKnownCoordinator: false, isUnmanagedSwarmWorker: false }; +function resolveWorkerOrCoordinatorFromSwarm(convId, payload, appDataDir, cacheDir, hasPriorCapsule, env) { + const empty = { workerName: null, isKnownCoordinator: false, isUnmanagedSwarmWorker: false }; + if (typeof convId !== "string" || !convId) { + return empty; } - 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, isUnmanagedSwarmWorker: false }; + const cachedName = readJsonObject(mapPath)[convId]; + if (typeof cachedName === "string" && cachedName && cachedName !== "coordinator") { + return { ...empty, workerName: cachedName }; } - if (!appDataDir) { - return { workerName: null, isKnownCoordinator: false, isUnmanagedSwarmWorker: false }; + return empty; } - 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) - ) { - continue; - } - checkedRoots.add(rootId); - const swarmDir = join(appDataDir, "brain", rootId, ".system_generated", "swarm"); - 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, - }; - } - 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), - }; + function checkDirs(dirs) { + const discovered = {}; + let matchedCoord = false; + let matchedUnmanaged = false; + let matchedUnmanagedWorker = false; + for (const { dirId, isOwnSwarmDir } of dirs) { + const swarmDir = join(appDataDir, "brain", dirId, ".system_generated", "swarm"); + const res = inspectSwarmDirectory(swarmDir, dirId, convId, { appDataDir, cacheDir, env, isOwnSwarmDir }); + if (res.kind === "managed_roster") { + Object.assign(discovered, res.workerEntries); + if (res.matchedCoordinator) { + matchedCoord = true; + } + } else if (res.kind === "anchor_coordinator") { + matchedCoord = true; + } else if (res.kind === "unmanaged_swarm" && res.targetInSwarm) { + matchedUnmanaged = true; + if (res.targetIsWorker) { + matchedUnmanagedWorker = true; + } + } + if (discovered[convId] || matchedCoord || matchedUnmanaged) { + break; } - skipNonWorkerCache = true; - if (res.hasUnmatchedAnchor) hasAnchorWithoutMembers = true; } - } - - const ownSwarmDir = join(appDataDir, "brain", conversationId, ".system_generated", "swarm"); - 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, - }; + updateJsonKeys(mapPath, discovered); + if (discovered[convId]) { + return { ...empty, workerName: discovered[convId] }; } - if (ownRes.matchedCoordinator) { - return { workerName: null, isKnownCoordinator: true, isUnmanagedSwarmWorker: false }; + if (matchedCoord) { + return { ...empty, isKnownCoordinator: true }; } - 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; + if (matchedUnmanaged) { + return { ...empty, isUnmanagedSwarmWorker: matchedUnmanagedWorker }; + } + return null; } - const nonWorkerRootsPath = join(cacheDir, "non-worker-roots.json"); - const nonWorkerRoots = readJsonObject(nonWorkerRootsPath); - if (nonWorkerRoots[conversationId]) { - return { workerName: null, isKnownCoordinator: false, isUnmanagedSwarmWorker: false }; + const priorityDirs = []; + for (const rootId of [payload.rootConversationId, payload.parentConversationId]) { + if (typeof rootId === "string" && rootId && rootId !== convId && !checkedRoots.has(rootId)) { + checkedRoots.add(rootId); + priorityDirs.push({ dirId: rootId, isOwnSwarmDir: false }); + } } - - const ownTranscriptPath = resolveOwnTranscriptPath(payload, appDataDir); - if (transcriptIsUnforkedUserRoot(ownTranscriptPath, hasPriorInjectedCapsule)) { - return { workerName: null, isKnownCoordinator: false, isUnmanagedSwarmWorker: false }; + priorityDirs.push({ dirId: convId, isOwnSwarmDir: true }); + const directHit = checkDirs(priorityDirs); + if (directHit) { + return directHit; } - - const brainDir = join(appDataDir, "brain"); - if (!existsSync(brainDir)) { - return { workerName: null, isKnownCoordinator: false, isUnmanagedSwarmWorker: false }; + if (transcriptIsUnforkedUserRoot(resolveOwnTranscriptPath(payload, appDataDir), hasPriorCapsule)) { + return empty; } - - let entries = []; try { - entries = readdirSync(brainDir, { withFileTypes: true }); + const brainDir = join(appDataDir, "brain"); + if (!existsSync(brainDir)) { + return empty; + } + const otherDirs = readdirSync(brainDir, { withFileTypes: true }) + .filter((entry) => (entry.isDirectory() || entry.isSymbolicLink()) && entry.name !== convId && !checkedRoots.has(entry.name)) + .map((entry) => ({ dirId: entry.name, isOwnSwarmDir: false })); + return checkDirs(otherDirs) || empty; } catch { - 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) - ) { - continue; - } - const swarmDir = join(brainDir, entry.name, ".system_generated", "swarm"); - 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; - } - } - - updateJsonKeys(mapPath, discoveredWorkers); - if (discoveredWorkers[conversationId]) { - return { - workerName: discoveredWorkers[conversationId], - isKnownCoordinator: false, - isUnmanagedSwarmWorker: false, - }; - } - if (matchedCoordinator) { - return { workerName: null, isKnownCoordinator: true, isUnmanagedSwarmWorker: false }; - } - if (matchedUnmanagedSwarm) { - return { - workerName: null, - isKnownCoordinator: false, - isUnmanagedSwarmWorker: matchedUnmanagedWorker, - }; - } - - if (!hasAnchorWithoutMembers && !skipNonWorkerCache) { - updateJsonKey(nonWorkerRootsPath, conversationId, true); + return empty; } - return { workerName: null, isKnownCoordinator: false, isUnmanagedSwarmWorker: false }; } function classifyWorkerMember(memberName) { - if ( - memberName === "narrator" || - memberName.startsWith("narrator-") || - memberName === "monitor" || - memberName.startsWith("monitor-") - ) { - return { kind: "builtin", capsule: null }; - } - if ( - memberName.startsWith("impl-") || - memberName.startsWith("cand-") || - memberName.startsWith("lead-") - ) { - return { kind: "author", capsule: "roles/poteto-agent.md" }; + const lower = memberName.toLowerCase(); + const base = stripTrailingNumericSuffix(lower); + if (base === "monitor" || base === "narrator" || lower.startsWith("monitor-") || lower.startsWith("narrator-")) { + return { kind: "support", capsule: null }; } - if (memberName.startsWith("adv-")) { + if (lower.startsWith("adv-")) { return { kind: "adversary", capsule: "roles/poteto-agent.md" }; } - if (memberName.startsWith("ro-")) { - return { kind: "readonly", capsule: "roles/research.md" }; - } - if (memberName.startsWith("sicko-")) { + if (lower.startsWith("sicko-")) { return { kind: "sicko", capsule: "roles/comment-sicko.md" }; } - const baseMemberName = memberName.replace(/-\d+$/, ""); if ( - baseMemberName === "verifier" || - memberName.startsWith("verifier-") || - baseMemberName.endsWith("-verifier") || - memberName.startsWith("verify-") + lower.startsWith("ro-") || + base === "verifier" || + lower.startsWith("verifier-") || + base.endsWith("-verifier") || + lower.startsWith("verify-") ) { return { kind: "readonly", capsule: "roles/research.md" }; } @@ -1002,62 +944,37 @@ function classifyWorkerMember(memberName) { function classifySession(payload, env) { const appDataDir = resolveAppDataDir(payload, env); const cacheDir = resolveCacheDir(appDataDir, env); - const conversationId = typeof payload.conversationId === "string" ? payload.conversationId : ""; - const injectedPath = join(cacheDir, "injected-capsules.json"); - const injectedMap = readJsonObject(injectedPath); - const alreadyInjected = - conversationId.length > 0 && - typeof injectedMap[conversationId] === "string" && - injectedMap[conversationId].length > 0; - - 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, - ); - + const convId = typeof payload.conversationId === "string" ? payload.conversationId : ""; + let capsuleState = readCapsuleState(cacheDir, convId); + const alreadyInjected = typeof capsuleState.capsule === "string" && capsuleState.capsule.length > 0; + const { isPstackSlash, isBuiltinSwarmSlash } = classifyLeadingSlash(payload.lastUserInput); + const forcedCoord = env.PSTACK_FORCE_COORDINATOR === "1"; + if (convId) { + if ((isPstackSlash || forcedCoord) && capsuleState.plainSwarm) { + capsuleState = updateCapsuleState(cacheDir, convId, { plainSwarm: false }); + } else if (isBuiltinSwarmSlash && !alreadyInjected && !capsuleState.plainSwarm) { + capsuleState = updateCapsuleState(cacheDir, convId, { plainSwarm: true }); + } + } + const { workerName, isKnownCoordinator, isUnmanagedSwarmWorker } = resolveWorkerOrCoordinatorFromSwarm( + convId, + payload, + appDataDir, + cacheDir, + alreadyInjected, + env, + ); if (workerName) { - const { kind, capsule } = classifyWorkerMember(workerName); return { sessionKind: "worker", - kind, + ...classifyWorkerMember(workerName), memberName: workerName, - capsule, appDataDir, cacheDir, - injectedMap, + capsuleState, }; } - - if (isUnmanagedSwarmWorker && !alreadyInjected && !forcedCoordinator) { + if (isUnmanagedSwarmWorker && !alreadyInjected && !forcedCoord) { return { sessionKind: "unmanaged", kind: "unmanaged", @@ -1065,16 +982,10 @@ function classifySession(payload, env) { capsule: null, appDataDir, cacheDir, - injectedMap, + capsuleState, }; } - - if ( - isKnownCoordinator || - alreadyInjected || - matchesSlashCommand || - forcedCoordinator - ) { + if (isKnownCoordinator || capsuleState.capsule === "roles/coordinator.md" || isPstackSlash || forcedCoord) { return { sessionKind: "coordinator", kind: "coordinator", @@ -1082,10 +993,9 @@ function classifySession(payload, env) { capsule: "roles/coordinator.md", appDataDir, cacheDir, - injectedMap, + capsuleState, }; } - return { sessionKind: "unmanaged", kind: "unmanaged", @@ -1093,5973 +1003,796 @@ function classifySession(payload, env) { capsule: null, appDataDir, cacheDir, - injectedMap, + capsuleState, }; } -function resolveRealTargetPath(targetPath, baseDir, depth = 0) { - if (depth > 16) return null; - const absTarget = resolve(baseDir, targetPath); - const tailParts = []; - let current = absTarget; +function parseCommandSegments(commandLine) { + const segments = []; + let tokens = []; + let token = ""; + let hasToken = false; + let inSingle = false; + let inDouble = false; + let parenDepth = 0; + let skipNext = false; - while (true) { - try { - const stat = lstatSync(current); - if (stat.isSymbolicLink()) { - try { - const resolvedReal = realpathSync(current); - return tailParts.length > 0 ? join(resolvedReal, ...tailParts) : resolvedReal; - } catch { - const linkTarget = readlinkSync(current); - const nextTarget = resolve(dirname(current), linkTarget); - const combined = tailParts.length > 0 ? join(nextTarget, ...tailParts) : nextTarget; - return resolveRealTargetPath(combined, dirname(current), depth + 1); - } - } - const resolvedReal = realpathSync(current); - return tailParts.length > 0 ? join(resolvedReal, ...tailParts) : resolvedReal; - } catch { - const parent = dirname(current); - if (parent === current) { - return absTarget; - } - tailParts.unshift(basename(current)); - current = parent; + function flushToken() { + if (!hasToken) { + return; } - } -} - -function isStrictlyInside(targetPath, rootDir) { - const rel = relative(rootDir, targetPath); - return rel.length > 0 && rel !== ".." && !rel.startsWith("../") && !rel.startsWith("..\\") && !isAbsolute(rel); -} - -function isInsideOrEqual(targetPath, rootDir) { - return targetPath === rootDir || isStrictlyInside(targetPath, rootDir); -} - -function getCanonicalTempRoots(env) { - const roots = new Set(["/tmp", "/private/tmp"]); - for (const candidate of ["/tmp", "/private/tmp", env.TMPDIR, tmpdir()]) { - if (typeof candidate !== "string" || candidate.length === 0) continue; - try { - roots.add(realpathSync(candidate)); - } catch { - roots.add(resolve(candidate)); + if (skipNext) { + skipNext = false; + } else { + tokens.push(token); } + token = ""; + hasToken = false; + parenDepth = 0; } - return [...roots]; -} -function getSandboxContainerInTemp(realCwd, canonicalTempRoots) { - if (!realCwd) return null; - for (const tempRoot of canonicalTempRoots) { - if (!isStrictlyInside(realCwd, tempRoot)) continue; - const rel = relative(tempRoot, realCwd); - const parts = rel.split(/[\\/]/).filter(Boolean); - if (parts.length >= 2) { - return join(tempRoot, parts[0]); + function flushSegment() { + flushToken(); + if (tokens.length > 0) { + segments.push(tokens); + tokens = []; } + skipNext = false; } - return null; -} -function isInsideCanonicalTempRoots(realTarget, canonicalTempRoots, realCwd, options = {}) { - const { allowRootEqual = false, excludeRealCwd = false } = options; - if (!realTarget) return false; - if (excludeRealCwd && realCwd && isInsideOrEqual(realTarget, realCwd)) { - return false; - } - const sandboxContainer = getSandboxContainerInTemp(realCwd, canonicalTempRoots); - if (sandboxContainer && isInsideOrEqual(realTarget, sandboxContainer)) { - const sandboxTmp = join(sandboxContainer, "tmp"); - if (!isInsideOrEqual(realTarget, sandboxTmp)) { - return false; + for (let i = 0; i < commandLine.length; i += 1) { + const ch = commandLine[i]; + const next = commandLine[i + 1]; + if (inSingle) { + if (ch === "'") { + inSingle = false; + } else { + token += ch; + } + hasToken = true; + continue; } - } - return canonicalTempRoots.some((root) => - allowRootEqual ? isInsideOrEqual(realTarget, root) : isStrictlyInside(realTarget, root), - ); -} - -function replaceSafeRuntimeTokens(input) { - return input - .replace(/\$\{\$\}|\$\$/g, "0") - .replace(/\$\{(?:PPID|RANDOM|BASHPID)\}|\$(?:PPID|RANDOM|BASHPID)(?![A-Za-z0-9_])/g, "0") - .replace( - /\$\(\s*date\s+(?:-u\s+)?(?:\+[A-Za-z0-9_%:.-]+|"\+[A-Za-z0-9_%:.-]+"|'\+[A-Za-z0-9_%:.-]+')\s*\)/g, - "0", - ) - .replace(/\$\(\s*uuidgen\s*\)/g, "0"); -} - -function findMatchingBrace(str, openBraceIdx) { - let depth = 1; - let i = openBraceIdx + 1; - let inSingle = false; - let inDouble = false; - while (i < str.length && depth > 0) { - const ch = str[i]; - if (ch === "\\" && !inSingle) { - i += 2; + if (inDouble) { + if (ch === "\\" && i + 1 < commandLine.length) { + if (next === "\n") { + i += 1; + continue; + } + if (next === '"' || next === "\\" || next === "$" || next === "`") { + token += next; + i += 1; + hasToken = true; + continue; + } + } + if (ch === '"') { + inDouble = false; + } else { + token += ch; + } + hasToken = true; continue; } - if (ch === "'" && !inDouble) { - inSingle = !inSingle; + if (ch === "\\" && i + 1 < commandLine.length) { + if (next !== "\n") { + token += next; + hasToken = true; + } i += 1; continue; } - if (ch === '"' && !inSingle) { - inDouble = !inDouble; - i += 1; + if (ch === "'") { + inSingle = true; + hasToken = true; continue; } - if (!inSingle && !inDouble) { - if (ch === "{") depth += 1; - else if (ch === "}") { - depth -= 1; - if (depth === 0) return i; + if (ch === '"') { + inDouble = true; + hasToken = true; + continue; + } + if (ch === "#" && !hasToken) { + while (i + 1 < commandLine.length && commandLine[i + 1] !== "\n") { + i += 1; } + continue; } - i += 1; - } - return -1; -} - -function expandShellVarsOnce(input, envState) { - let out = ""; - let changed = false; - let i = 0; - - while (i < input.length) { - const ch = input[i]; - if (ch === "\\" && i + 1 < input.length && (input[i + 1] === "$" || input[i + 1] === "`" || input[i + 1] === "~")) { - out += input.slice(i, i + 2); - i += 2; + if (ch === ";" || ch === "\n") { + flushSegment(); continue; } - if (ch !== "$") { - out += ch; - i += 1; + if (ch === "&" && next === ">") { + flushToken(); + i += commandLine[i + 2] === ">" ? 2 : 1; + skipNext = true; continue; } - - if (input[i + 1] === "{") { - const closeIdx = findMatchingBrace(input, i + 1); - if (closeIdx < 0) return { ok: false, value: "", changed: false }; - const body = input.slice(i + 2, closeIdx); - const paramMatch = body.match(/^([A-Za-z_][A-Za-z0-9_]*)(?:(:?[-=])([\s\S]*))?$/); - if (!paramMatch) return { ok: false, value: "", changed: false }; - const [, varName, op, fallbackVal = ""] = paramMatch; - const rawVal = typeof envState[varName] === "string" ? envState[varName] : undefined; - - if (!op) { - if (rawVal === undefined) return { ok: false, value: "", changed: false }; - out += rawVal; - } else if (op === ":-" || op === ":=") { - const chosen = rawVal !== undefined && rawVal.length > 0 ? rawVal : fallbackVal; - if (op === ":=" && (rawVal === undefined || rawVal.length === 0)) { - envState[varName] = chosen; - } - out += chosen; - } else { - const chosen = rawVal !== undefined ? rawVal : fallbackVal; - if (op === "=" && rawVal === undefined) { - envState[varName] = chosen; - } - out += chosen; + if (ch === "&" || ch === "|") { + if (next === ch) { + i += 1; } - changed = true; - i = closeIdx + 1; + flushSegment(); continue; } - - const bareMatch = input.slice(i + 1).match(/^([A-Za-z_][A-Za-z0-9_]*)/); - if (bareMatch) { - const varName = bareMatch[1]; - const rawVal = typeof envState[varName] === "string" ? envState[varName] : undefined; - if (rawVal === undefined) return { ok: false, value: "", changed: false }; - out += rawVal; - changed = true; - i += 1 + varName.length; + if (isWhitespaceChar(ch)) { + flushToken(); continue; } - - out += ch; - i += 1; - } - - return { ok: true, value: out, changed }; -} - -function resolveShellTargetPath(rawToken, baseDir, mergedEnv = {}, options = {}) { - const { requireAbsoluteAfterExpand = false } = options; - if (typeof rawToken !== "string" || rawToken.length === 0) return null; - if (rawToken === "/dev/null") return "/dev/null"; - - const envState = mergedEnv && typeof mergedEnv === "object" ? { ...mergedEnv } : {}; - let expanded = rawToken; - if (expanded.startsWith("\\~")) { - expanded = expanded.slice(1); - } else if (expanded === "~" || expanded.startsWith("~/")) { - const home = envState.HOME || homedir(); - expanded = expanded === "~" ? home : join(home, expanded.slice(2)); - } else if (expanded.startsWith("~")) { - return null; - } - - for (let pass = 0; pass < 4; pass += 1) { - expanded = replaceSafeRuntimeTokens(expanded); - if (!expanded.includes("$")) break; - const step = expandShellVarsOnce(expanded, envState); - if (!step.ok) return null; - expanded = step.value; - if (!step.changed) break; - } - expanded = replaceSafeRuntimeTokens(expanded); - - if (!expanded || /[$`]/.test(expanded)) { - return null; - } - if (requireAbsoluteAfterExpand && !isAbsolute(expanded)) { - return null; - } - - return resolveRealTargetPath(expanded, baseDir); -} - -function preprocessHeredocs(command) { - const lines = command.split("\n"); - const keptLines = []; - const unquotedBodies = []; - let lineIdx = 0; - - while (lineIdx < lines.length) { - const line = lines[lineIdx]; - keptLines.push(line); - const pendingHeredocs = []; - let inSingle = false; - let inDouble = false; - - for (let i = 0; i < line.length; i += 1) { - const ch = line[i]; - if (ch === "\\" && !inSingle) { - i += 1; - continue; - } - if (ch === "'" && !inDouble) { - inSingle = !inSingle; - continue; + if (ch === "(") { + if (hasToken) { + parenDepth += 1; + token += ch; } - if (ch === '"' && !inSingle) { - inDouble = !inDouble; - continue; + continue; + } + if (ch === ")") { + if (parenDepth > 0) { + parenDepth -= 1; + token += ch; + } else { + flushToken(); } - if (!inSingle && !inDouble && ch === "#" && (i === 0 || " \t;|(&".includes(line[i - 1]))) { - break; + continue; + } + if (ch === ">" || ch === "<") { + if (hasToken && isAllDigits(token)) { + token = ""; + hasToken = false; + } else { + flushToken(); } - if (!inSingle && !inDouble && ch === "<" && line[i + 1] === "<" && line[i + 2] !== "<") { - let j = i + 2; - const stripTabs = line[j] === "-"; - if (stripTabs) j += 1; - while (j < line.length && (line[j] === " " || line[j] === "\t")) j += 1; - let delim = ""; - let quotedDelim = false; - let delimSingle = false; - let delimDouble = false; - while (j < line.length) { - const c = line[j]; - if (!delimSingle && !delimDouble && " \t;|()&<>".includes(c)) break; - if (c === "\\" && !delimSingle) { - quotedDelim = true; - if (j + 1 < line.length) delim += line[j + 1]; - j += 2; - continue; - } - if (c === "'" && !delimDouble) { - quotedDelim = true; - delimSingle = !delimSingle; - j += 1; - continue; - } - if (c === '"' && !delimSingle) { - quotedDelim = true; - delimDouble = !delimDouble; - j += 1; - continue; + if (ch === "<" && next === "<" && commandLine[i + 2] === "<") { + i += 2; + skipNext = true; + } else if ((ch === ">" && (next === ">" || next === "|")) || (ch === "<" && (next === "<" || next === ">"))) { + i += 1; + skipNext = true; + } else if (next === "&") { + i += 1; + if (isDigit(commandLine.charCodeAt(i + 1))) { + while (isDigit(commandLine.charCodeAt(i + 1))) { + i += 1; } - delim += c; - j += 1; - } - if (delim.length > 0) { - pendingHeredocs.push({ delim, stripTabs, quotedDelim }); + } else if (commandLine[i + 1] === "-") { + i += 1; + } else { + skipNext = true; } - i = j - 1; - } - } - - lineIdx += 1; - for (const h of pendingHeredocs) { - const bodyLines = []; - while (lineIdx < lines.length) { - const rawBodyLine = lines[lineIdx]; - const cmpLine = h.stripTabs ? rawBodyLine.replace(/^\t+/, "") : rawBodyLine; - lineIdx += 1; - if (cmpLine === h.delim) break; - bodyLines.push(rawBodyLine); - } - if (!h.quotedDelim && bodyLines.length > 0) { - unquotedBodies.push(bodyLines.join("\n")); + } else { + skipNext = true; } - } - } - - return { - strippedCommand: keptLines.join("\n"), - unquotedBodies, - }; -} - -function scanBalancedDollarSub(str, dollarIdx) { - let depth = 1; - let j = dollarIdx + 2; - let subSingle = false; - let subDouble = false; - while (j < str.length && depth > 0) { - const c = str[j]; - if (c === "\\" && !subSingle) { - j += 2; continue; } - if (c === "'" && !subDouble) subSingle = !subSingle; - else if (c === '"' && !subSingle) subDouble = !subDouble; - else if (!subSingle && !subDouble) { - if (c === "(") depth += 1; - else if (c === ")") depth -= 1; - } - j += 1; + token += ch; + hasToken = true; } - return depth === 0 ? j : -1; + flushSegment(); + return segments; } -function extractCommandSubstitutions(command) { - const subs = []; - let i = 0; - let inSingle = false; - let inDouble = false; - - while (i < command.length) { - const ch = command[i]; - if (ch === "\\" && !inSingle) { - i += 2; - continue; - } - if (ch === "'" && !inDouble) { - inSingle = !inSingle; - i += 1; +function unwrapCommandSegment(tokens) { + const inlineEnv = {}; + let idx = 0; + while (idx < tokens.length) { + const tok = tokens[idx]; + if (SHELL_KEYWORDS.has(tok)) { + idx += 1; continue; } - if (ch === '"' && !inSingle) { - inDouble = !inDouble; - i += 1; + const eq = tok.indexOf("="); + if (eq > 0 && isShellIdent(tok.slice(0, eq))) { + inlineEnv[tok.slice(0, eq)] = tok.slice(eq + 1); + idx += 1; continue; } - if (!inSingle && ch === "$" && command[i + 1] === "(") { - const endIdx = scanBalancedDollarSub(command, i); - if (endIdx > 0) { - subs.push(command.slice(i + 2, endIdx - 1)); - i = endIdx; - continue; - } - } - if (!inSingle && ch === "`") { - let j = i + 1; - while (j < command.length) { - if (command[j] === "\\") { - j += 2; + const base = basename(tok); + if (base === "env") { + idx += 1; + while (idx < tokens.length) { + const arg = tokens[idx]; + if (arg === "-u" || arg === "--unset" || arg === "-C" || arg === "-S") { + idx += 2; continue; } - if (command[j] === "`") break; - j += 1; - } - if (j < command.length) { - subs.push(command.slice(i + 1, j)); - i = j + 1; - continue; - } - } - i += 1; - } - return subs; -} - -function readNextShellToken(str, startIdx, options = {}) { - const { preserveLiteralEscapes = false } = options; - let i = startIdx; - while (i < str.length && (str[i] === " " || str[i] === "\t")) { - i += 1; - } - if (i >= str.length) return { token: "", nextIdx: i }; - let token = ""; - let inSingle = false; - let inDouble = false; - let sawAnyChar = false; - - while (i < str.length) { - const ch = str[i]; - if (!inSingle && !inDouble && " \t\r\n|&;()<>".includes(ch)) { - break; - } - if (!inSingle && ch === "$" && str[i + 1] === "(") { - const endIdx = scanBalancedDollarSub(str, i); - if (endIdx > 0) { - token += str.slice(i, endIdx); - sawAnyChar = true; - i = endIdx; - continue; - } - } - if (!inSingle && ch === "$" && str[i + 1] === "{") { - const closeIdx = findMatchingBrace(str, i + 1); - if (closeIdx > 0) { - token += str.slice(i, closeIdx + 1); - sawAnyChar = true; - i = closeIdx + 1; - continue; - } - } - if (!inSingle && ch === "`") { - let j = i + 1; - while (j < str.length) { - if (str[j] === "\\") { - j += 2; + if (arg.startsWith("-")) { + idx += 1; continue; } - if (str[j] === "`") break; - j += 1; - } - if (j < str.length) { - token += str.slice(i, j + 1); - sawAnyChar = true; - i = j + 1; - continue; - } - } - if (ch === "\\" && !inSingle) { - if (i + 1 < str.length) { - const next = str[i + 1]; - if (preserveLiteralEscapes && (next === "$" || next === "`" || (!sawAnyChar && next === "~"))) { - token += "\\" + next; - } else { - token += next; + const envEq = arg.indexOf("="); + if (envEq > 0 && isShellIdent(arg.slice(0, envEq))) { + inlineEnv[arg.slice(0, envEq)] = arg.slice(envEq + 1); + idx += 1; + continue; } + break; } - sawAnyChar = true; - i += 2; continue; } - if (ch === "'" && !inDouble) { - inSingle = !inSingle; - if (preserveLiteralEscapes && !sawAnyChar && str[i + 1] === "~") { - token += "\\~"; - sawAnyChar = true; - i += 2; - continue; + if (base === "command" || base === "nohup" || base === "time") { + idx += 1; + while (idx < tokens.length && tokens[idx].startsWith("-") && tokens[idx] !== "--") { + idx += 1; + } + if (tokens[idx] === "--") { + idx += 1; } - sawAnyChar = true; - i += 1; continue; } - if (ch === '"' && !inSingle) { - inDouble = !inDouble; - if (preserveLiteralEscapes && !sawAnyChar && str[i + 1] === "~") { - token += "\\~"; - sawAnyChar = true; - i += 2; - continue; + return { cmd: base, args: tokens.slice(idx + 1), inlineEnv }; + } + return { cmd: "", args: [], inlineEnv }; +} + +function parseGitCommand(args) { + const globalDirs = []; + const valueFlags = wordSet("-c --namespace --super-prefix --config-env"); + for (let i = 0; i < args.length; i += 1) { + const arg = args[i]; + if (arg === "-C" || arg === "--git-dir" || arg === "--work-tree") { + if (i + 1 < args.length) { + globalDirs.push({ flag: arg, dir: args[i + 1] }); } - sawAnyChar = true; i += 1; - continue; - } - if (preserveLiteralEscapes && inSingle && (ch === "$" || ch === "`")) { - token += "\\" + ch; - sawAnyChar = true; + } else if (arg.startsWith("-C") && arg.length > 2) { + globalDirs.push({ flag: "-C", dir: arg.slice(2) }); + } else if (arg.startsWith("--git-dir=")) { + globalDirs.push({ flag: "--git-dir", dir: arg.slice(10) }); + } else if (arg.startsWith("--work-tree=")) { + globalDirs.push({ flag: "--work-tree", dir: arg.slice(12) }); + } else if (valueFlags.has(arg)) { i += 1; - continue; + } else if (!arg.startsWith("-")) { + return { subcmd: arg, subArgs: args.slice(i + 1), globalDirs }; } - token += ch; - sawAnyChar = true; - i += 1; } - return { token, nextIdx: i }; + return { subcmd: "", subArgs: [], globalDirs }; } -function splitRawShellSegments(command) { - const items = []; - let start = 0; - let inSingle = false; - let inDouble = false; - let atTokenBoundary = true; - let connectorBefore = ""; - let i = 0; - - const pushSlice = (endIdx, connectorAfter = "") => { - const sub = command.slice(start, endIdx); - if (sub.trim().length > 0) { - items.push({ type: "segment", text: sub, connectorBefore, connectorAfter }); +function resolveCheckedOutBranch(globalDirs, fallbackDir) { + let curBase = fallbackDir || process.cwd(); + let explicitGitDir = null; + for (const entry of globalDirs) { + const resolved = resolveRealTargetPath(entry.dir, curBase); + if (entry.flag === "-C") { + curBase = resolved || resolve(curBase, entry.dir); + } else if (entry.flag === "--git-dir") { + explicitGitDir = resolved || resolve(curBase, entry.dir); } - }; + } + const gitArgs = explicitGitDir + ? ["--git-dir", explicitGitDir, "symbolic-ref", "--short", "-q", "HEAD"] + : ["-C", curBase, "symbolic-ref", "--short", "-q", "HEAD"]; + try { + return execFileSync("git", gitArgs, { + encoding: "utf8", + timeout: 1500, + stdio: ["ignore", "pipe", "ignore"], + }).trim(); + } catch { + return null; + } +} - while (i < command.length) { - const ch = command[i]; - if (ch === "\\" && !inSingle) { - if (command[i + 1] !== "\n") atTokenBoundary = false; - i += 2; - continue; - } - if (ch === "'" && !inDouble) { - inSingle = !inSingle; - atTokenBoundary = false; - i += 1; - continue; - } - if (ch === '"' && !inSingle) { - inDouble = !inDouble; - atTokenBoundary = false; - i += 1; +function isForcePushToProtectedBranch(subArgs, globalDirs, fallbackDir) { + let hasForce = false; + let afterDash = false; + const pos = []; + const valFlags = wordSet("-o --push-option --repo --receive-pack --exec"); + for (let i = 0; i < subArgs.length; i += 1) { + const arg = subArgs[i]; + if (!afterDash && arg === "--") { + afterDash = true; continue; } - if (!inSingle && ch === "$" && command[i + 1] === "(") { - const endIdx = scanBalancedDollarSub(command, i); - if (endIdx > 0) { - atTokenBoundary = false; - i = endIdx; - continue; - } - } - if (!inSingle && ch === "$" && command[i + 1] === "{") { - const closeIdx = findMatchingBrace(command, i + 1); - if (closeIdx > 0) { - atTokenBoundary = false; - i = closeIdx + 1; - continue; - } - } - if (!inSingle && ch === "`") { - let j = i + 1; - while (j < command.length) { - if (command[j] === "\\") { - j += 2; - continue; - } - if (command[j] === "`") break; - j += 1; - } - if (j < command.length) { - atTokenBoundary = false; - i = j + 1; - continue; - } - } - if (!inSingle && !inDouble) { - if (ch === " " || ch === "\t" || ch === "\r") { - atTokenBoundary = true; - i += 1; + if (!afterDash && arg.startsWith("-")) { + if (arg === "--force-with-lease" || arg.startsWith("--force-with-lease=") || arg === "--force-if-includes") { continue; } - if (ch === "#" && atTokenBoundary) { - while (i < command.length && command[i] !== "\n") i += 1; - continue; - } - if (ch === "(" || ch === ")") { - pushSlice(i, ch); - items.push({ type: "paren", dir: ch }); - i += 1; - start = i; - connectorBefore = ch; - atTokenBoundary = true; - continue; + if (arg === "--force" || arg.startsWith("--force=") || (!arg.startsWith("--") && arg.includes("f"))) { + hasForce = true; } - if (ch === "\n" || ch === ";") { - pushSlice(i, ch); + if (valFlags.has(arg)) { i += 1; - start = i; - connectorBefore = ch; - atTokenBoundary = true; - continue; - } - if (ch === "&" && command[i + 1] === ">") { - const opLen = command[i + 2] === ">" ? 3 : 2; - const { nextIdx } = readNextShellToken(command, i + opLen); - i = nextIdx; - atTokenBoundary = true; - continue; - } - if (ch === ">" && command[i + 1] === "&") { - const fdMatch = command.slice(i + 2).match(/^(?:\d+|-)(?=$|[\s|&;()<>])/); - if (fdMatch) { - i += 2 + fdMatch[0].length; - atTokenBoundary = true; - continue; - } - const { nextIdx } = readNextShellToken(command, i + 2); - i = nextIdx; - atTokenBoundary = true; - continue; - } - if (ch === "<" && command[i + 1] === "&") { - const fdMatch = command.slice(i + 2).match(/^(?:\d+|-)(?=$|[\s|&;()<>])/); - if (fdMatch) { - i += 2 + fdMatch[0].length; - atTokenBoundary = true; - continue; - } - const { nextIdx } = readNextShellToken(command, i + 2); - i = nextIdx; - atTokenBoundary = true; - continue; - } - if (ch === "|" || ch === "&") { - const op = command[i + 1] === ch ? ch + ch : ch; - pushSlice(i, op); - i += op.length; - start = i; - connectorBefore = op; - atTokenBoundary = true; - continue; } + continue; } - atTokenBoundary = false; - i += 1; + pos.push(arg); } - pushSlice(command.length, ""); - return items; -} - -function extractOutputRedirectTargets(command, activeEnv = {}) { - const targets = []; - const envSnapshot = { ...activeEnv }; - let i = 0; - let inSingle = false; - let inDouble = false; - while (i < command.length) { - const ch = command[i]; - if (ch === "\\" && !inSingle) { - i += 2; - continue; + let checkCheckedOutHead = hasForce && pos.length <= 1; + const refSpecs = pos.length >= 2 ? pos.slice(1) : pos; + for (const spec of refSpecs) { + const plusForced = spec.startsWith("+"); + const clean = plusForced ? spec.slice(1) : spec; + const dst = clean.includes(":") ? clean.slice(clean.lastIndexOf(":") + 1) : clean; + const branch = dst.startsWith("refs/heads/") ? dst.slice(11) : dst; + if ((branch === "main" || branch === "master") && (hasForce || plusForced)) { + return true; } - if (ch === "'" && !inDouble) { - inSingle = !inSingle; - i += 1; - continue; + if ((branch === "HEAD" || clean === "HEAD") && (hasForce || plusForced)) { + checkCheckedOutHead = true; } - if (ch === '"' && !inSingle) { - inDouble = !inDouble; - i += 1; - continue; + } + + if (checkCheckedOutHead) { + const headBranch = resolveCheckedOutBranch(globalDirs, fallbackDir); + if (headBranch === "main" || headBranch === "master") { + return true; } - if (!inSingle && ch === "$" && command[i + 1] === "(") { - const endIdx = scanBalancedDollarSub(command, i); - if (endIdx > 0) { - i = endIdx; - continue; - } + } + return false; +} + +function hasMutatingGitListArgs(subArgs, cfg) { + let hasQuery = false; + let afterDash = false; + const pos = []; + for (let i = 0; i < subArgs.length; i += 1) { + const arg = subArgs[i]; + if (!afterDash && arg === "--") { + afterDash = true; + continue; } - if (!inSingle && ch === "$" && command[i + 1] === "{") { - const closeIdx = findMatchingBrace(command, i + 1); - if (closeIdx > 0) { - i = closeIdx + 1; - continue; + if (!afterDash && arg.startsWith("-")) { + const hasShort = + !arg.startsWith("--") && + !(cfg.allowNSkip && arg.startsWith("-n")) && + [...arg.slice(1)].some((ch) => cfg.mutShort.has(ch)); + if (cfg.mutExact.has(arg) || cfg.mutPfx.some((p) => arg.startsWith(p)) || hasShort) { + return true; } - } - if (!inSingle && ch === "`") { - let j = i + 1; - while (j < command.length) { - if (command[j] === "\\") { - j += 2; - continue; - } - if (command[j] === "`") break; - j += 1; + if (cfg.qExact.has(arg) || cfg.qPfx.some((p) => arg.startsWith(p))) { + hasQuery = true; } - if (j < command.length) { - i = j + 1; - continue; + if (cfg.allowNSkip && arg === "-n" && i + 1 < subArgs.length && isAllDigits(subArgs[i + 1])) { + i += 1; + } else if (cfg.valFlags.has(arg)) { + i += 1; } - } - if (!inSingle && !inDouble && ch === "#" && (i === 0 || " \t\r\n;|(&".includes(command[i - 1]))) { - while (i < command.length && command[i] !== "\n") i += 1; continue; } - if (!inSingle && !inDouble && ch === "&" && command[i + 1] === ">") { - const opLen = command[i + 2] === ">" ? 3 : 2; - const { token, nextIdx } = readNextShellToken(command, i + opLen, { preserveLiteralEscapes: true }); - targets.push({ target: token, env: envSnapshot }); - i = nextIdx; - continue; + pos.push(arg); + } + return pos.length > 0 && !hasQuery; +} + +const LIST_VAL_FLAGS = wordSet( + "--sort --format --color --column --contains --no-contains --merged --no-merged --points-at", +); +const QUERY_PFX = ["--contains=", "--no-contains=", "--merged=", "--no-merged=", "--points-at="]; +const TAG_CFG = { + mutExact: wordSet("-d --delete -a --annotate -s --sign -f --force -m --message -F --file -u --local-user --create-reflog"), + mutShort: wordSet("d a s f m F u"), + mutPfx: ["--message=", "--file=", "--local-user="], + qExact: wordSet("-l --list -v --verify --contains --no-contains --merged --no-merged --points-at"), + qPfx: QUERY_PFX, + valFlags: LIST_VAL_FLAGS, + allowNSkip: true, +}; +const BRANCH_CFG = { + mutExact: wordSet("-d -D --delete -m -M --move -c -C --copy -u --set-upstream-to --unset-upstream --edit-description --create-reflog"), + mutShort: wordSet("d D m M c C u"), + mutPfx: ["--set-upstream-to="], + qExact: wordSet("-l --list -a --all -r --remotes --contains --no-contains --merged --no-merged --points-at --show-current"), + qPfx: QUERY_PFX, + valFlags: LIST_VAL_FLAGS, + allowNSkip: false, +}; + +function isMutatingGitActionForReadOnly(subcmd, subArgs) { + if (RO_BLOCKED_GIT_SUBCOMMANDS.has(subcmd)) { + return true; + } + if (subcmd === "worktree" || subcmd === "stash" || subcmd === "remote") { + const first = subArgs.find((x) => !x.startsWith("-")) || ""; + if (subcmd === "worktree") { + return Boolean(first && first !== "list"); } - if (!inSingle && !inDouble && ch === "<" && command[i + 1] === ">") { - const { token, nextIdx } = readNextShellToken(command, i + 2, { preserveLiteralEscapes: true }); - targets.push({ target: token, env: envSnapshot }); - i = nextIdx; + if (subcmd === "stash") { + return first !== "list" && first !== "show"; + } + return Boolean(first && first !== "show" && first !== "get-url"); + } + if (subcmd === "tag") { + return hasMutatingGitListArgs(subArgs, TAG_CFG); + } + if (subcmd === "branch") { + return hasMutatingGitListArgs(subArgs, BRANCH_CFG); + } + if (subcmd !== "config") { + return false; + } + const writes = wordSet("--unset --unset-all --replace-all --add --remove-section --rename-section --edit -e"); + const reads = wordSet("--get --get-all --get-regexp --get-urlmatch --list -l"); + const vals = wordSet("-f --file --blob --type --default"); + let hasRead = false; + let afterDash = false; + const pos = []; + for (let i = 0; i < subArgs.length; i += 1) { + const arg = subArgs[i]; + if (!afterDash && arg === "--") { + afterDash = true; continue; } - if (!inSingle && !inDouble && ch === ">") { - if (command[i + 1] === "&") { - const fdMatch = command.slice(i + 2).match(/^(?:\d+|-)(?=$|[\s|&;()<>])/); - if (fdMatch) { - i += 2 + fdMatch[0].length; - continue; - } - const { token, nextIdx } = readNextShellToken(command, i + 2, { preserveLiteralEscapes: true }); - targets.push({ target: token, env: envSnapshot }); - i = nextIdx; - continue; + if (!afterDash && arg.startsWith("-")) { + if (writes.has(arg)) { + return true; + } + if (reads.has(arg)) { + hasRead = true; + } + if (vals.has(arg)) { + i += 1; } - const opLen = command[i + 1] === ">" || command[i + 1] === "|" ? 2 : 1; - const { token, nextIdx } = readNextShellToken(command, i + opLen, { preserveLiteralEscapes: true }); - targets.push({ target: token, env: envSnapshot }); - i = nextIdx; continue; } - i += 1; + pos.push(arg); } - return targets; + return !hasRead && pos.length >= 2; } -function tokenizeSingleSegment(segment) { - const tokens = []; - let token = ""; - let hasTokenChars = false; - let inSingle = false; - let inDouble = false; - let i = 0; - - const flushToken = () => { - if (hasTokenChars) { - tokens.push(token); - token = ""; - hasTokenChars = false; - } - }; - - while (i < segment.length) { - const ch = segment[i]; - if (ch === "\\" && !inSingle) { - if (i + 1 < segment.length && segment[i + 1] === "\n") { - i += 2; - continue; - } - hasTokenChars = true; - if (i + 1 < segment.length) token += segment[i + 1]; - i += 2; - continue; - } - if (ch === "'" && !inDouble) { - inSingle = !inSingle; - hasTokenChars = true; - i += 1; - continue; +function isEffectiveGitDirInsideTemp(globalDirs, fallbackBaseDir, tempRoots, realCwd) { + const check = (dir) => isInsideCanonicalTempRoots(dir, tempRoots, realCwd); + if (globalDirs.length === 0) { + return check(realCwd || resolveRealTargetPath(fallbackBaseDir, process.cwd())); + } + let curBase = fallbackBaseDir; + let sawC = false; + for (const entry of globalDirs) { + const resolved = resolveRealTargetPath(entry.dir, curBase); + if (!resolved) { + return false; } - if (ch === '"' && !inSingle) { - inDouble = !inDouble; - hasTokenChars = true; - i += 1; - continue; + if (entry.flag === "-C") { + curBase = resolved; + sawC = true; + } else if (!check(resolved)) { + return false; } - if (!inSingle && ch === "$" && segment[i + 1] === "(") { - const endIdx = scanBalancedDollarSub(segment, i); - if (endIdx > 0) { - hasTokenChars = true; - token += segment.slice(i, endIdx); - i = endIdx; - continue; - } - } - if (!inSingle && ch === "$" && segment[i + 1] === "{") { - const closeIdx = findMatchingBrace(segment, i + 1); - if (closeIdx > 0) { - hasTokenChars = true; - token += segment.slice(i, closeIdx + 1); - i = closeIdx + 1; - continue; - } - } - if (!inSingle && ch === "`") { - let j = i + 1; - while (j < segment.length) { - if (segment[j] === "\\") { - j += 2; - continue; - } - if (segment[j] === "`") break; - j += 1; - } - if (j < segment.length) { - hasTokenChars = true; - token += segment.slice(i, j + 1); - i = j + 1; - continue; - } - } - if (!inSingle && !inDouble) { - if (ch === " " || ch === "\t" || ch === "\r") { - flushToken(); - i += 1; - continue; - } - if (ch === "#" && !hasTokenChars) { - while (i < segment.length && segment[i] !== "\n") i += 1; - continue; - } - if (ch === "&" && segment[i + 1] === ">") { - flushToken(); - const opLen = segment[i + 2] === ">" ? 3 : 2; - const { nextIdx } = readNextShellToken(segment, i + opLen); - i = nextIdx; - continue; - } - if (ch === ">" || ch === "<") { - if (hasTokenChars && /^\d+$/.test(token)) { - token = ""; - hasTokenChars = false; - } else { - flushToken(); - } - if (ch === "<" && segment[i + 1] === "<" && segment[i + 2] === "<") { - const { nextIdx } = readNextShellToken(segment, i + 3); - i = nextIdx; - continue; - } - if (ch === "<" && segment[i + 1] === "<") { - const opLen = segment[i + 2] === "-" ? 3 : 2; - const { nextIdx } = readNextShellToken(segment, i + opLen); - i = nextIdx; - continue; - } - if ((ch === ">" || ch === "<") && segment[i + 1] === "&") { - const fdMatch = segment.slice(i + 2).match(/^(?:\d+|-)/); - if (fdMatch) { - i += 2 + fdMatch[0].length; - continue; - } - const { nextIdx } = readNextShellToken(segment, i + 2); - i = nextIdx; - continue; - } - const opLen = - segment[i + 1] === ch || segment[i + 1] === "|" || segment[i + 1] === "&" || segment[i + 1] === ">" - ? 2 - : 1; - const { nextIdx } = readNextShellToken(segment, i + opLen); - i = nextIdx; - continue; - } - } - hasTokenChars = true; - token += ch; - i += 1; - } - - flushToken(); - return tokens; -} - -function assignEnvVar(envObj, outerEnv, key, rawVal) { - const priorVal = - typeof envObj[key] === "string" - ? envObj[key] - : outerEnv && typeof outerEnv[key] === "string" - ? outerEnv[key] - : undefined; - if (priorVal !== undefined && rawVal.includes("$")) { - const escapedKey = key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - const selfExpanded = rawVal - .replace(new RegExp(`\\$\\{${escapedKey}\\}`, "g"), priorVal) - .replace(new RegExp(`\\$${escapedKey}(?![A-Za-z0-9_])`, "g"), priorVal); - envObj[key] = selfExpanded; - return; - } - envObj[key] = rawVal; -} - -const SHELL_KEYWORD_PREFIXES = new Set([ - "if", - "then", - "else", - "elif", - "fi", - "while", - "until", - "do", - "done", - "esac", - "{", - "}", - "!", -]); - -const READ_VALUE_FLAGS = new Set(["-p", "-t", "-n", "-N", "-d", "-u", "-i", "-a"]); - -function unwrapCommandSegment(tokens, inheritedEnv = {}, outerEnv = {}) { - const env = { ...inheritedEnv }; - const assignedKeys = []; - const taintedVars = []; - let idx = 0; - - while (idx < tokens.length) { - const tok = tokens[idx]; - if (SHELL_KEYWORD_PREFIXES.has(tok)) { - idx += 1; - continue; - } - if ((tok === "for" || tok === "select") && idx === 0) { - if (idx + 1 < tokens.length && /^[A-Za-z_][A-Za-z0-9_]*$/.test(tokens[idx + 1])) { - taintedVars.push(tokens[idx + 1]); - } - return { cmd: "", rawCmd: "", args: [], env, assignedKeys, taintedVars }; - } - if (tok === "case" && idx === 0) { - return { cmd: "", rawCmd: "", args: [], env, assignedKeys, taintedVars }; - } - if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(tok)) { - const eq = tok.indexOf("="); - const key = tok.slice(0, eq); - assignEnvVar(env, outerEnv, key, tok.slice(eq + 1)); - assignedKeys.push(key); - idx += 1; - continue; - } - const base = basename(tok); - if ( - (base === "export" || base === "local" || base === "readonly" || base === "declare" || base === "typeset") && - tok === base - ) { - for (let j = idx + 1; j < tokens.length; j += 1) { - const arg = tokens[j]; - if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(arg)) { - const eq = arg.indexOf("="); - const key = arg.slice(0, eq); - assignEnvVar(env, outerEnv, key, arg.slice(eq + 1)); - assignedKeys.push(key); - } - } - return { cmd: "export", rawCmd: tok, args: tokens.slice(idx + 1), env, assignedKeys, taintedVars }; - } - if (base === "unset" && tok === "unset") { - for (let j = idx + 1; j < tokens.length; j += 1) { - const arg = tokens[j]; - if (!arg.startsWith("-")) delete env[arg]; - } - return { cmd: "unset", rawCmd: tok, args: tokens.slice(idx + 1), env, assignedKeys, taintedVars }; - } - if (base === "read" && tok === "read") { - for (let j = idx + 1; j < tokens.length; j += 1) { - const arg = tokens[j]; - if (arg.startsWith("-") && arg.length > 1) { - if (READ_VALUE_FLAGS.has(arg)) j += 1; - continue; - } - if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(arg)) { - taintedVars.push(arg); - } - } - return { cmd: "read", rawCmd: tok, args: tokens.slice(idx + 1), env, assignedKeys, taintedVars }; - } - if (base === "env") { - idx += 1; - while (idx < tokens.length) { - const envArg = tokens[idx]; - if (envArg === "-i" || envArg === "-") { - idx += 1; - continue; - } - if (envArg === "-u") { - if (idx + 1 < tokens.length) delete env[tokens[idx + 1]]; - idx += 2; - continue; - } - if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(envArg)) { - const eq = envArg.indexOf("="); - assignEnvVar(env, outerEnv, envArg.slice(0, eq), envArg.slice(eq + 1)); - idx += 1; - continue; - } - break; - } - continue; - } - if (base === "command" || base === "builtin" || base === "nohup" || base === "time") { - idx += 1; - while (idx < tokens.length && tokens[idx].startsWith("-") && tokens[idx] !== "--") { - idx += 1; - } - if (tokens[idx] === "--") idx += 1; - continue; - } - if (base === "sudo") { - idx += 1; - while (idx < tokens.length && tokens[idx].startsWith("-")) { - const flag = tokens[idx]; - idx += 1; - if (flag === "-u" || flag === "-g" || flag === "-C" || flag === "-h" || flag === "-p") { - idx += 1; - } - } - continue; - } - if (base === "xargs") { - idx += 1; - while (idx < tokens.length && tokens[idx].startsWith("-")) { - const flag = tokens[idx]; - idx += 1; - if (["-I", "-L", "-n", "-P", "-s", "-d", "-E", "-a"].includes(flag)) { - idx += 1; - } - } - continue; - } - break; - } - - if (idx >= tokens.length) { - return { cmd: "", rawCmd: "", args: [], env, assignedKeys, taintedVars }; - } - return { - cmd: basename(tokens[idx]), - rawCmd: tokens[idx], - args: tokens.slice(idx + 1), - env, - assignedKeys, - taintedVars, - }; -} - -function replaceObjectKeys(target, source) { - for (const k of Object.keys(target)) delete target[k]; - Object.assign(target, source); -} - -function collectInvocations(command, depth = 0, inheritedEnv = {}, outerEnv = {}) { - if (depth > 8 || !command) return { invocations: [], redirectTargets: [] }; - const { strippedCommand, unquotedBodies } = preprocessHeredocs(command); - const redirectTargets = []; - const invocations = []; - const scriptEnv = { ...inheritedEnv }; - const envStack = []; - - const rawItems = splitRawShellSegments(strippedCommand); - for (const item of rawItems) { - if (item.type === "paren") { - if (item.dir === "(") { - envStack.push({ ...scriptEnv }); - } else if (envStack.length > 0) { - replaceObjectKeys(scriptEnv, envStack.pop()); - } - continue; - } - - const rawSeg = item.text; - const isPipelineStage = item.connectorBefore === "|" || item.connectorAfter === "|"; - const isConditional = item.connectorBefore === "&&" || item.connectorBefore === "||"; - const tokens = tokenizeSingleSegment(rawSeg); - const parsed = unwrapCommandSegment(tokens, scriptEnv, outerEnv); - - for (const sub of extractCommandSubstitutions(rawSeg)) { - const subRes = collectInvocations(sub, depth + 1, parsed.env, outerEnv); - redirectTargets.push(...subRes.redirectTargets); - invocations.push(...subRes.invocations); - } - - redirectTargets.push(...extractOutputRedirectTargets(rawSeg, parsed.env)); - - for (const tv of parsed.taintedVars) { - if (!isPipelineStage) { - parsed.env[tv] = "$__TAINTED__"; - scriptEnv[tv] = "$__TAINTED__"; - } - } - - if (!parsed.cmd) { - if (!isPipelineStage) { - if (isConditional) { - for (const key of parsed.assignedKeys) { - scriptEnv[key] = "$__TAINTED__"; - } - } else { - Object.assign(scriptEnv, parsed.env); - } - } - continue; - } - if (parsed.cmd === "export" || parsed.cmd === "unset" || parsed.cmd === "read") { - if (!isPipelineStage) { - if (isConditional) { - for (const key of parsed.assignedKeys) { - scriptEnv[key] = "$__TAINTED__"; - } - } else { - replaceObjectKeys(scriptEnv, parsed.env); - } - } - continue; - } - invocations.push(parsed); - - if (["sh", "bash", "zsh", "dash", "ksh"].includes(parsed.cmd)) { - for (let i = 0; i < parsed.args.length; i += 1) { - const arg = parsed.args[i]; - if (arg === "--") break; - if (/^-[a-zA-Z]*c$/.test(arg) && i + 1 < parsed.args.length) { - const inner = collectInvocations(parsed.args[i + 1], depth + 1, parsed.env, outerEnv); - redirectTargets.push(...inner.redirectTargets); - invocations.push(...inner.invocations); - break; - } - } - } else if (parsed.cmd === "eval" && parsed.args.length > 0) { - const inner = collectInvocations(parsed.args.join(" "), depth + 1, parsed.env, outerEnv); - redirectTargets.push(...inner.redirectTargets); - invocations.push(...inner.invocations); - } - } - - for (const body of unquotedBodies) { - for (const sub of extractCommandSubstitutions(body)) { - const subRes = collectInvocations(sub, depth + 1, scriptEnv, outerEnv); - redirectTargets.push(...subRes.redirectTargets); - invocations.push(...subRes.invocations); - } - } - - return { invocations, redirectTargets }; -} - -function extractPositionalPaths(args) { - const paths = []; - let afterDoubleDash = false; - for (const arg of args) { - if (!afterDoubleDash && arg === "--") { - afterDoubleDash = true; - continue; - } - if (!afterDoubleDash && arg.startsWith("-") && arg.length > 1) { - continue; - } - paths.push(arg); - } - return paths; -} - -function extractChmodTargets(args) { - let i = 0; - while (i < args.length) { - const arg = args[i]; - if (arg === "--") { - i += 1; - break; - } - if (arg === "--reference") { - i += 2; - continue; - } - if (arg.startsWith("--reference=")) { - return args.slice(i + 1).filter((a) => a !== "--"); - } - if ( - ["-R", "-v", "-c", "-f", "-h", "-H", "-L", "-P", "--recursive", "--changes", "--silent", "--quiet", "--verbose"].includes( - arg, - ) || - /^-[RvcfhHLP]+$/.test(arg) - ) { - i += 1; - continue; - } - break; - } - if (i >= args.length) return []; - return args.slice(i + 1).filter((a) => a !== "--"); -} - -function extractCpOrMvSpec(args) { - let targetDir = null; - const positionals = []; - let afterDoubleDash = false; - - for (let i = 0; i < args.length; i += 1) { - const arg = args[i]; - if (!afterDoubleDash && arg === "--") { - afterDoubleDash = true; - continue; - } - if (!afterDoubleDash && arg.startsWith("-") && arg.length > 1) { - if (arg === "-t" || arg === "--target-directory") { - if (i + 1 >= args.length) return { valid: false, sources: [], destinations: [] }; - targetDir = args[i + 1]; - i += 1; - continue; - } - if (arg.startsWith("--target-directory=")) { - targetDir = arg.slice("--target-directory=".length); - continue; - } - if (arg.startsWith("-t") && arg.length > 2) { - targetDir = arg.slice(2); - continue; - } - if (arg === "-S" || arg === "--suffix") { - i += 1; - continue; - } - continue; - } - positionals.push(arg); - } - - if (targetDir !== null) { - if (positionals.length === 0) return { valid: false, sources: [], destinations: [] }; - return { valid: true, sources: positionals, destinations: [targetDir] }; - } - if (positionals.length < 2) { - return { valid: false, sources: [], destinations: [] }; - } - return { - valid: true, - sources: positionals.slice(0, -1), - destinations: [positionals[positionals.length - 1]], - }; -} - -function extractLnSpec(args) { - let isSymbolic = false; - let targetDir = null; - const positionals = []; - let afterDoubleDash = false; - - for (let i = 0; i < args.length; i += 1) { - const arg = args[i]; - if (!afterDoubleDash && arg === "--") { - afterDoubleDash = true; - continue; - } - if (!afterDoubleDash && arg.startsWith("-") && arg.length > 1) { - if (arg === "--symbolic" || (!arg.startsWith("--") && /^-[a-zA-Z]*s/.test(arg))) { - isSymbolic = true; - } - if (arg === "-t" || arg === "--target-directory") { - if (i + 1 >= args.length) return { valid: false, isSymbolic, sources: [], linkPaths: [] }; - targetDir = args[i + 1]; - i += 1; - continue; - } - if (arg.startsWith("--target-directory=")) { - targetDir = arg.slice("--target-directory=".length); - continue; - } - if (arg === "-S" || arg === "--suffix") { - i += 1; - continue; - } - continue; - } - positionals.push(arg); - } - - if (targetDir !== null) { - if (positionals.length === 0) return { valid: false, isSymbolic, sources: [], linkPaths: [] }; - return { valid: true, isSymbolic, sources: positionals, linkPaths: [targetDir], linkIsDir: true }; - } - if (positionals.length === 1) { - return { valid: true, isSymbolic, sources: [positionals[0]], linkPaths: ["."], linkIsDir: true }; - } - if (positionals.length >= 2) { - return { - valid: true, - isSymbolic, - sources: positionals.slice(0, -1), - linkPaths: [positionals[positionals.length - 1]], - linkIsDir: positionals.length > 2, - }; - } - return { valid: false, isSymbolic, sources: [], linkPaths: [], linkIsDir: false }; -} - -function extractPatchTargets(args) { - const dirTargets = []; - const fileTargets = []; - const positionals = []; - let afterDoubleDash = false; - - for (let i = 0; i < args.length; i += 1) { - const arg = args[i]; - if (!afterDoubleDash && arg === "--") { - afterDoubleDash = true; - continue; - } - if (!afterDoubleDash && arg.startsWith("-") && arg.length > 1) { - if (arg === "-d" || arg === "--directory") { - if (i + 1 >= args.length) return { valid: false, dirTargets: [], fileTargets: [] }; - dirTargets.push(args[i + 1]); - i += 1; - continue; - } - if (arg.startsWith("--directory=")) { - dirTargets.push(arg.slice("--directory=".length)); - continue; - } - if (arg.startsWith("-d") && arg.length > 2) { - dirTargets.push(arg.slice(2)); - continue; - } - if (arg === "-o" || arg === "--output" || arg === "-r" || arg === "--reject-file") { - if (i + 1 >= args.length) return { valid: false, dirTargets: [], fileTargets: [] }; - fileTargets.push(args[i + 1]); - i += 1; - continue; - } - if (arg.startsWith("--output=")) { - fileTargets.push(arg.slice("--output=".length)); - continue; - } - if (arg.startsWith("--reject-file=")) { - fileTargets.push(arg.slice("--reject-file=".length)); - continue; - } - if ( - ["-i", "--input", "-p", "--strip", "-F", "--fuzz", "-V", "--version-control", "-B", "--prefix", "-Y", "--basename-prefix", "-z", "--suffix", "-D", "--ifdef", "-g", "--get"].includes( - arg, - ) - ) { - i += 1; - continue; - } - continue; - } - positionals.push(arg); - } - - if (positionals.length >= 1) { - fileTargets.push(positionals[0]); - } - return { valid: true, dirTargets, fileTargets }; -} - -function extractSedInPlaceTargets(args) { - let hasInPlace = false; - let hasExplicitScript = false; - let afterDoubleDash = false; - const positionals = []; - - for (let i = 0; i < args.length; i += 1) { - const arg = args[i]; - if (!afterDoubleDash && arg === "--") { - afterDoubleDash = true; - continue; - } - if (!afterDoubleDash) { - if (arg === "-e" || arg === "--expression" || arg === "-f" || arg === "--file") { - hasExplicitScript = true; - i += 1; - continue; - } - if ( - (arg.startsWith("-e") && arg.length > 2) || - arg.startsWith("--expression=") || - (arg.startsWith("-f") && arg.length > 2) || - arg.startsWith("--file=") - ) { - hasExplicitScript = true; - continue; - } - if (arg === "-i") { - hasInPlace = true; - if (i + 1 < args.length && (args[i + 1] === "" || args[i + 1].startsWith("."))) { - i += 1; - } - continue; - } - if (arg === "--in-place" || arg.startsWith("--in-place=") || (!arg.startsWith("--") && /^-[a-zA-Z]*i/.test(arg))) { - hasInPlace = true; - if (!arg.startsWith("--") && arg.endsWith("i") && i + 1 < args.length && args[i + 1] === "") { - i += 1; - } - continue; - } - if (arg.startsWith("-") && arg.length > 1) { - continue; - } - } - positionals.push(arg); - } - - if (!hasInPlace) return null; - return hasExplicitScript ? positionals : positionals.slice(1); -} - -function extractPerlRubyInPlaceTargets(args) { - let hasInPlace = false; - let hasInlineScript = false; - let afterDoubleDash = false; - const positionals = []; - - for (let i = 0; i < args.length; i += 1) { - const arg = args[i]; - if (!afterDoubleDash && arg === "--") { - afterDoubleDash = true; - continue; - } - if (!afterDoubleDash && arg.startsWith("-") && arg.length > 1) { - if (!arg.startsWith("--") && /^-[a-zA-Z]*i/.test(arg)) { - hasInPlace = true; - } - if (arg === "-e" || arg === "-E" || (!arg.startsWith("--") && /^-[a-zA-Z.]*[eE]$/.test(arg))) { - hasInlineScript = true; - i += 1; - continue; - } - continue; - } - positionals.push(arg); - } - - if (!hasInPlace) return null; - return hasInlineScript ? positionals : positionals.slice(1); -} - -function parseCallArguments(code, openParenIdx) { - const args = []; - let current = ""; - let depth = 1; - let i = openParenIdx + 1; - let quote = null; - - while (i < code.length && depth > 0) { - const ch = code[i]; - if (quote) { - current += ch; - if (ch === "\\" && i + 1 < code.length) { - current += code[i + 1]; - i += 2; - continue; - } - if (quote.length === 3) { - if (code.slice(i, i + 3) === quote) { - current += code.slice(i + 1, i + 3); - quote = null; - i += 3; - continue; - } - } else if (ch === quote) { - quote = null; - } - i += 1; - continue; - } - - if (code.slice(i, i + 3) === "'''" || code.slice(i, i + 3) === '"""') { - quote = code.slice(i, i + 3); - current += quote; - i += 3; - continue; - } - if (ch === "'" || ch === '"' || ch === "`") { - quote = ch; - current += ch; - i += 1; - continue; - } - if (ch === "(" || ch === "[" || ch === "{") { - depth += 1; - current += ch; - i += 1; - continue; - } - if (ch === ")" || ch === "]" || ch === "}") { - depth -= 1; - if (depth === 0) break; - current += ch; - i += 1; - continue; - } - if (ch === "," && depth === 1) { - args.push(current.trim()); - current = ""; - i += 1; - continue; - } - current += ch; - i += 1; - } - - if (depth !== 0) return null; - if (current.trim().length > 0 || args.length > 0) { - args.push(current.trim()); - } - return args; -} - -function unescapeSimpleLiteral(inner, isRaw = false) { - if (isRaw) return inner; - let out = ""; - for (let i = 0; i < inner.length; i += 1) { - if (inner[i] === "\\" && i + 1 < inner.length) { - const next = inner[i + 1]; - if (next === "n") out += "\n"; - else if (next === "r") out += "\r"; - else if (next === "t") out += "\t"; - else out += next; - i += 1; - continue; - } - out += inner[i]; - } - return out; -} - -function parseStaticJsString(expr) { - if (typeof expr !== "string") return { ok: false, value: "" }; - const trimmed = expr.trim(); - if (trimmed.length < 2) return { ok: false, value: "" }; - const q = trimmed[0]; - if (q !== "'" && q !== '"' && q !== "`") return { ok: false, value: "" }; - if (trimmed[trimmed.length - 1] !== q) return { ok: false, value: "" }; - const inner = trimmed.slice(1, -1); - for (let i = 0; i < inner.length; i += 1) { - if (inner[i] === "\\") { - i += 1; - continue; - } - if (inner[i] === q) return { ok: false, value: "" }; - if (q === "`" && inner[i] === "$" && inner[i + 1] === "{") { - return { ok: false, value: "" }; - } - } - return { ok: true, value: unescapeSimpleLiteral(inner, false) }; -} - -function parseStaticPyString(expr) { - if (typeof expr !== "string") return { ok: false, value: "" }; - let trimmed = expr.trim(); - let isRaw = false; - let isFormat = false; - const prefixMatch = trimmed.match(/^([rRbBuUfF]{1,2})(?=['"])/); - if (prefixMatch) { - const p = prefixMatch[1].toLowerCase(); - isRaw = p.includes("r"); - isFormat = p.includes("f"); - trimmed = trimmed.slice(prefixMatch[1].length); - } - let quote = ""; - if (trimmed.startsWith("'''") && trimmed.endsWith("'''") && trimmed.length >= 6) { - quote = "'''"; - } else if (trimmed.startsWith('"""') && trimmed.endsWith('"""') && trimmed.length >= 6) { - quote = '"""'; - } else if ((trimmed.startsWith("'") && trimmed.endsWith("'")) || (trimmed.startsWith('"') && trimmed.endsWith('"'))) { - if (trimmed.length >= 2) quote = trimmed[0]; - } - if (!quote) return { ok: false, value: "" }; - const inner = trimmed.slice(quote.length, trimmed.length - quote.length); - if (isFormat && /[{}]/.test(inner)) return { ok: false, value: "" }; - if (quote.length === 1) { - for (let i = 0; i < inner.length; i += 1) { - if (inner[i] === "\\") { - i += 1; - continue; - } - if (inner[i] === quote) return { ok: false, value: "" }; - } - } - return { ok: true, value: unescapeSimpleLiteral(inner, isRaw) }; -} - -const JS_NON_MEMBER_PREFIX_KEYWORDS = new Set([ - "return", - "typeof", - "await", - "yield", - "throw", - "delete", - "void", - "case", - "in", - "of", - "else", - "new", -]); - -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|lchmod|chown|truncate|rename|renames|replace|rmtree|move|copy|copy2|copyfile|copytree|symlink|link|write_text|write_bytes|touch|symlink_to|hardlink_to|link_to)\b/; - -const PYTHON_PATH_CLASS_NAMES = new Set([ - "Path", - "PurePath", - "PosixPath", - "WindowsPath", - "PurePosixPath", - "PureWindowsPath", -]); - -const PYTHON_FS_MODULE_NAMES = new Set(["os", "posix", "shutil"]); - -const PYTHON_OS_SHUTIL_FN_NAMES = new Set([ - "remove", - "unlink", - "rmdir", - "removedirs", - "mkdir", - "makedirs", - "chmod", - "lchmod", - "chown", - "truncate", - "rename", - "renames", - "replace", - "rmtree", - "move", - "copy", - "copy2", - "copyfile", - "copytree", - "symlink", - "link", -]); - -const PYTHON_STRING_RETURNING_METHODS = new Set([ - "read_text", - "read", - "readline", - "strip", - "lstrip", - "rstrip", - "lower", - "upper", - "casefold", - "title", - "capitalize", - "swapcase", - "decode", - "format", - "format_map", - "join", - "removeprefix", - "removesuffix", - "expandtabs", - "zfill", - "center", - "ljust", - "rjust", - "translate", -]); - -const PYTHON_STATEMENT_KEYWORDS = new Set([ - "and", - "as", - "assert", - "await", - "case", - "del", - "elif", - "else", - "for", - "from", - "if", - "import", - "in", - "is", - "lambda", - "not", - "or", - "raise", - "return", - "while", - "with", - "yield", -]); - -const PYTHON_REFLECTION_IDENT_RE = - /\b(?:getattr|setattr|delattr|vars|globals|locals|methodcaller|attrgetter|__dict__|__getattribute__|__getattr__|__setattr__|__delattr__|__subclasses__|__mro__|__bases__|__base__|__builtins__)\b/; - -const PYTHON_EVAL_EXEC_RE = /(?:^|[^\w.])(?:builtins\s*\.\s*)?(?:eval|exec)\b/; - -const PYTHON_UNBOUND_MUTATION_ATTR_RE = - /\.\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*\()/; - -const PYTHON_UNBOUND_OPEN_RE = - /(?:(?:^|[^\w.])=\s*(?:builtins\s*\.\s*|_?io\s*\.\s*|codecs\s*\.\s*)?open\b(?!\s*\()|\b(?:builtins|_?io|codecs)\s*\.\s*open\b(?!\s*\())/; - -function findMatchingCloseForward(str, openIdx) { - let depth = 0; - let quote = null; - let i = openIdx; - while (i < str.length) { - const ch = str[i]; - if (quote) { - if (ch === "\\") { - i += 2; - continue; - } - if (quote.length === 3) { - if (str.slice(i, i + 3) === quote) { - quote = null; - i += 3; - continue; - } - } else if (ch === quote) { - quote = null; - } - i += 1; - continue; - } - if (str.slice(i, i + 3) === "'''" || str.slice(i, i + 3) === '"""') { - quote = str.slice(i, i + 3); - i += 3; - continue; - } - if (ch === "'" || ch === '"' || ch === "`") { - quote = ch; - i += 1; - continue; - } - if (ch === "(" || ch === "[" || ch === "{") { - depth += 1; - } else if (ch === ")" || ch === "]" || ch === "}") { - depth -= 1; - if (depth === 0) return i; - } - i += 1; - } - return -1; -} - -function stripBalancedOuterParens(expr) { - let cur = String(expr || "").trim(); - while (cur.startsWith("(") && cur.endsWith(")")) { - if (findMatchingCloseForward(cur, 0) !== cur.length - 1) break; - cur = cur.slice(1, -1).trim(); - } - return cur; -} - -function unwrapPythonExprParensAndWalrus(rawExpr) { - let cur = stripBalancedOuterParens(rawExpr); - while (cur) { - const m = cur.match(/^[A-Za-z_][A-Za-z0-9_]*\s*:=\s*([\s\S]+)$/); - if (!m) break; - cur = stripBalancedOuterParens(m[1]); - } - return cur; -} - -function findFStringExprSpan(str, openBraceIdx) { - let parenDepth = 0; - let braceDepth = 1; - let inFormatSpec = false; - let exprEndIdx = -1; - let j = openBraceIdx + 1; - while (j < str.length) { - const ch = str[j]; - if (!inFormatSpec) { - let nestedPrefix = ""; - if (/[A-Za-z_]/.test(ch)) { - const wStart = j; - while (j < str.length && /[A-Za-z0-9_]/.test(str[j])) j += 1; - const word = str.slice(wStart, j); - if (!/^[rRbBuUfFtT]{1,2}$/.test(word) || (str[j] !== "'" && str[j] !== '"')) { - continue; - } - nestedPrefix = word; - } - if (str[j] === "'" || str[j] === '"') { - const q = - str.slice(j, j + 3) === "'''" || str.slice(j, j + 3) === '"""' - ? str.slice(j, j + 3) - : str[j]; - const nestedIsFormat = /[fFtT]/.test(nestedPrefix); - j += q.length; - while (j < str.length) { - if (str[j] === "\\") { - j += 2; - continue; - } - if (q.length === 3) { - if (str.slice(j, j + 3) === q) { - j += 3; - break; - } - } else if (str[j] === q) { - j += 1; - break; - } - if (nestedIsFormat && str[j] === "{") { - if (str[j + 1] === "{") { - j += 2; - continue; - } - const innerSpan = findFStringExprSpan(str, j); - if (innerSpan) { - j = innerSpan.closeBrace + 1; - continue; - } - } - j += 1; - } - continue; - } - if (ch === "#") { - while (j < str.length && str[j] !== "\n" && str[j] !== "\r") j += 1; - continue; - } - if (ch === "(" || ch === "[") { - parenDepth += 1; - j += 1; - continue; - } - if (ch === ")" || ch === "]") { - parenDepth = Math.max(0, parenDepth - 1); - j += 1; - continue; - } - if (ch === "{") { - braceDepth += 1; - j += 1; - continue; - } - if (ch === "}") { - braceDepth -= 1; - if (braceDepth === 0) { - return { - exprStart: openBraceIdx + 1, - exprEnd: exprEndIdx < 0 ? j : exprEndIdx, - closeBrace: j, - }; - } - j += 1; - continue; - } - if (parenDepth === 0 && braceDepth === 1) { - if (ch === ":") { - exprEndIdx = j; - inFormatSpec = true; - j += 1; - continue; - } - if (ch === "!" && /^[rsa]\s*[:}]/.test(str.slice(j + 1, j + 6))) { - exprEndIdx = j; - inFormatSpec = true; - j += 1; - continue; - } - } - j += 1; - continue; - } - if (ch === "{") { - braceDepth += 1; - j += 1; - continue; - } - if (ch === "}") { - braceDepth -= 1; - if (braceDepth === 0) { - return { - exprStart: openBraceIdx + 1, - exprEnd: exprEndIdx < 0 ? j : exprEndIdx, - closeBrace: j, - }; - } - j += 1; - continue; - } - j += 1; - } - return null; -} - -function scanPythonTokensRange(code, startIdx, limitIdx, tokens, openStack) { - let i = startIdx; - const end = Math.min(limitIdx, code.length); - while (i < end) { - const ch = code[i]; - if (/\s/.test(ch)) { - i += 1; - continue; - } - if (ch === "#") { - while (i < end && code[i] !== "\n") i += 1; - continue; - } - let prefix = ""; - let strStart = -1; - let quoteIdx = -1; - if (/[A-Za-z_]/.test(ch)) { - const wStart = i; - while (i < end && /[A-Za-z0-9_]/.test(code[i])) i += 1; - const word = code.slice(wStart, i); - if ( - i < end && - /^[rRbBuUfFtT]{1,2}$/.test(word) && - (code[i] === "'" || code[i] === '"' || code[i] === "`") - ) { - prefix = word; - strStart = wStart; - quoteIdx = i; - } else { - tokens.push({ kind: "ident", start: wStart, end: i, text: word }); - continue; - } - } else if (ch === "'" || ch === '"' || ch === "`") { - strStart = i; - quoteIdx = i; - } - - if (quoteIdx >= 0) { - const q = - quoteIdx + 3 <= code.length && - (code.slice(quoteIdx, quoteIdx + 3) === "'''" || - code.slice(quoteIdx, quoteIdx + 3) === '"""') - ? code.slice(quoteIdx, quoteIdx + 3) - : code[quoteIdx]; - const isFormat = /[fFtT]/.test(prefix); - if (!isFormat) { - i = quoteIdx + q.length; - let closed = false; - while (i < end) { - if (code[i] === "\\") { - i += 2; - continue; - } - if (q.length === 3) { - if (i + 3 <= end && code.slice(i, i + 3) === q) { - i += 3; - closed = true; - break; - } - } else if (code[i] === q) { - i += 1; - closed = true; - break; - } - i += 1; - } - tokens.push({ kind: "string", start: strStart, end: Math.min(i, end), closed, isFormat: false }); - continue; - } - - let j = quoteIdx + q.length; - let fullStrEnd = -1; - const interpSpans = []; - while (j < code.length) { - if (code[j] === "\\") { - j += 2; - continue; - } - if (q.length === 3) { - if (code.slice(j, j + 3) === q) { - fullStrEnd = j + 3; - break; - } - } else if (code[j] === q) { - fullStrEnd = j + 1; - break; - } - if (code[j] === "{") { - if (code[j + 1] === "{") { - j += 2; - continue; - } - const span = findFStringExprSpan(code, j); - if (span) { - interpSpans.push({ openBrace: j, exprStart: span.exprStart, exprEnd: span.exprEnd, closeBrace: span.closeBrace }); - let sj = span.exprEnd; - while (sj < span.closeBrace) { - if (code[sj] === "{" && code[sj + 1] !== "{") { - const subSpan = findFStringExprSpan(code, sj); - if (subSpan) { - interpSpans.push({ - openBrace: sj, - exprStart: subSpan.exprStart, - exprEnd: subSpan.exprEnd, - closeBrace: subSpan.closeBrace, - }); - sj = subSpan.closeBrace + 1; - continue; - } - } - sj += 1; - } - j = span.closeBrace + 1; - continue; - } - interpSpans.push({ openBrace: j, exprStart: j + 1, exprEnd: code.length, closeBrace: code.length }); - break; - } - if (code[j] === "}" && code[j + 1] === "}") { - j += 2; - continue; - } - j += 1; - } - - if (fullStrEnd >= 0 && fullStrEnd <= end) { - tokens.push({ kind: "string", start: strStart, end: fullStrEnd, closed: true, isFormat: true }); - i = fullStrEnd; - continue; - } - - let activeSpan = null; - for (const sp of interpSpans) { - if (sp.openBrace < end && end <= sp.closeBrace) { - if (!activeSpan || sp.openBrace > activeSpan.openBrace) { - activeSpan = sp; - } - } - } - if (activeSpan && end <= activeSpan.exprEnd) { - const openIdx = tokens.length; - tokens.push({ kind: "open", start: activeSpan.openBrace, end: activeSpan.openBrace + 1, ch: "{" }); - openStack.push(openIdx); - scanPythonTokensRange(code, activeSpan.exprStart, end, tokens, openStack); - i = end; - continue; - } - - tokens.push({ kind: "string", start: strStart, end, closed: false, isFormat: true }); - i = end; - continue; - } - - if (ch === "(" || ch === "[" || ch === "{") { - const idx = tokens.length; - tokens.push({ kind: "open", start: i, end: i + 1, ch }); - openStack.push(idx); - i += 1; - continue; - } - if (ch === ")" || ch === "]" || ch === "}") { - const openTokenIdx = openStack.length > 0 ? openStack.pop() : -1; - tokens.push({ kind: "close", start: i, end: i + 1, ch, openTokenIdx }); - i += 1; - continue; - } - if (ch === ".") { - tokens.push({ kind: "dot", start: i, end: i + 1 }); - i += 1; - continue; - } - tokens.push({ kind: "other", start: i, end: i + 1, ch }); - i += 1; - } -} - -function scanPythonTokensBefore(code, limitIdx) { - const tokens = []; - const openStack = []; - scanPythonTokensRange(code, 0, limitIdx, tokens, openStack); - return tokens; -} - -function stripPythonCommentsAndContinuations(rawCode) { - let out = ""; - let bracketDepth = 0; - let i = 0; - while (i < rawCode.length) { - const ch = rawCode[i]; - let prefix = ""; - let strStart = -1; - let quoteIdx = -1; - if (/[A-Za-z_]/.test(ch)) { - const wStart = i; - while (i < rawCode.length && /[A-Za-z0-9_]/.test(rawCode[i])) i += 1; - const word = rawCode.slice(wStart, i); - if (/^[rRbBuUfFtT]{1,2}$/.test(word) && (rawCode[i] === "'" || rawCode[i] === '"')) { - prefix = word; - strStart = wStart; - quoteIdx = i; - } else { - out += word; - continue; - } - } else if (ch === "'" || ch === '"') { - strStart = i; - quoteIdx = i; - } - - if (quoteIdx >= 0) { - const q = - rawCode.slice(quoteIdx, quoteIdx + 3) === "'''" || - rawCode.slice(quoteIdx, quoteIdx + 3) === '"""' - ? rawCode.slice(quoteIdx, quoteIdx + 3) - : rawCode[quoteIdx]; - const isFormat = /[fFtT]/.test(prefix); - i = quoteIdx + q.length; - if (!isFormat) { - while (i < rawCode.length) { - if (rawCode[i] === "\\") { - i += 2; - continue; - } - if (q.length === 3) { - if (rawCode.slice(i, i + 3) === q) { - i += 3; - break; - } - } else if (rawCode[i] === q) { - i += 1; - break; - } - i += 1; - } - out += rawCode.slice(strStart, Math.min(i, rawCode.length)); - continue; - } - - out += prefix + q; - while (i < rawCode.length) { - if (rawCode[i] === "\\") { - out += rawCode.slice(i, Math.min(i + 2, rawCode.length)); - i += 2; - continue; - } - if (q.length === 3) { - if (rawCode.slice(i, i + 3) === q) { - out += q; - i += 3; - break; - } - } else if (rawCode[i] === q) { - out += q; - i += 1; - break; - } - if (rawCode[i] === "{") { - if (rawCode[i + 1] === "{") { - out += "{{"; - i += 2; - continue; - } - const span = findFStringExprSpan(rawCode, i); - if (span) { - const normExpr = normalizeInlinePythonCode(rawCode.slice(span.exprStart, span.exprEnd)); - const specRaw = rawCode.slice(span.exprEnd, span.closeBrace); - let normSpec = ""; - let sj = 0; - while (sj < specRaw.length) { - if (specRaw[sj] === "{" && specRaw[sj + 1] !== "{") { - const subSpan = findFStringExprSpan(specRaw, sj); - if (subSpan) { - normSpec += `{${normalizeInlinePythonCode(specRaw.slice(subSpan.exprStart, subSpan.exprEnd))}${specRaw.slice(subSpan.exprEnd, subSpan.closeBrace + 1)}`; - sj = subSpan.closeBrace + 1; - continue; - } - } - normSpec += specRaw[sj]; - sj += 1; - } - out += `{${normExpr}${normSpec}}`; - i = span.closeBrace + 1; - continue; - } - } - if (rawCode[i] === "}" && rawCode[i + 1] === "}") { - out += "}}"; - i += 2; - continue; - } - out += rawCode[i]; - i += 1; - } - continue; - } - - if (ch === "\\") { - if (rawCode[i + 1] === "\r" && rawCode[i + 2] === "\n") { - out += " "; - i += 3; - continue; - } - if (rawCode[i + 1] === "\n" || rawCode[i + 1] === "\r") { - out += " "; - i += 2; - continue; - } - } - if (ch === "#") { - out += " "; - while (i < rawCode.length && rawCode[i] !== "\n" && rawCode[i] !== "\r") i += 1; - continue; - } - if (ch === "(" || ch === "[" || ch === "{") { - bracketDepth += 1; - out += ch; - i += 1; - continue; - } - if (ch === ")" || ch === "]" || ch === "}") { - bracketDepth = Math.max(0, bracketDepth - 1); - out += ch; - i += 1; - continue; - } - if (ch === "\r" || ch === "\n") { - if (ch === "\r" && rawCode[i + 1] === "\n") i += 2; - else i += 1; - out += bracketDepth > 0 ? " " : "\n"; - continue; - } - out += ch; - i += 1; - } - return out; -} - -function unwrapParenthesizedPythonRefs(code) { - const chars = code.split(""); - const maxPasses = Math.max(1, Math.floor(chars.length / 2) + 1); - for (let pass = 0; pass < maxPasses; pass += 1) { - const cur = chars.join(""); - const tokens = scanPythonTokensBefore(cur, cur.length); - let changed = false; - for (let closeIdx = 0; closeIdx < tokens.length; closeIdx += 1) { - const closeTok = tokens[closeIdx]; - if (closeTok.kind !== "close" || closeTok.ch !== ")" || closeTok.openTokenIdx < 0) continue; - const openIdx = closeTok.openTokenIdx; - const openTok = tokens[openIdx]; - if (openTok.ch !== "(" || openIdx + 1 >= closeIdx) continue; - const prev = openIdx > 0 ? tokens[openIdx - 1] : null; - const isGroupingOpen = - prev === null || - prev.kind === "open" || - prev.kind === "other" || - (prev.kind === "ident" && PYTHON_STATEMENT_KEYWORDS.has(prev.text) && prev.text !== "import"); - if (!isGroupingOpen) continue; - - const topTokens = []; - let validPrimary = true; - let k = openIdx + 1; - while (k < closeIdx) { - const t = tokens[k]; - if (t.kind === "open") { - let matchClose = -1; - for (let m = k + 1; m < closeIdx; m += 1) { - if (tokens[m].kind === "close" && tokens[m].openTokenIdx === k) { - matchClose = m; - break; - } - } - if (matchClose < 0) { - validPrimary = false; - break; - } - topTokens.push({ kind: "group" }); - k = matchClose + 1; - continue; - } - if ( - t.kind === "ident" && - !PYTHON_STATEMENT_KEYWORDS.has(t.text) && - t.text !== "class" && - t.text !== "def" - ) { - topTokens.push(t); - k += 1; - continue; - } - if (t.kind === "string") { - if (topTokens.length > 0 && topTokens[topTokens.length - 1].kind === "string") { - validPrimary = false; - break; - } - topTokens.push(t); - k += 1; - continue; - } - if (t.kind === "dot") { - topTokens.push(t); - k += 1; - continue; - } - validPrimary = false; - break; - } - if ( - !validPrimary || - topTokens.length === 0 || - topTokens[0].kind === "dot" || - topTokens[topTokens.length - 1].kind === "dot" - ) { - continue; - } - - const endsWithAttr = - topTokens.length >= 3 && - topTokens[topTokens.length - 1].kind === "ident" && - topTokens[topTokens.length - 2].kind === "dot"; - const nextTok = closeIdx + 1 < tokens.length ? tokens[closeIdx + 1] : null; - const followedByChain = - nextTok !== null && - (nextTok.kind === "dot" || - (nextTok.kind === "open" && (nextTok.ch === "(" || nextTok.ch === "[")) || - (nextTok.kind === "close" && nextTok.ch === ")")); - if (endsWithAttr || followedByChain) { - chars[openTok.start] = " "; - chars[closeTok.start] = " "; - changed = true; - break; - } - } - if (!changed) return cur; - } - return chars.join(""); -} - -function normalizeInlinePythonCode(rawCode) { - const stripped = stripPythonCommentsAndContinuations(String(rawCode || "")); - return unwrapParenthesizedPythonRefs(stripped); -} - -function maskSlicePreservingNewlines(slice) { - let out = ""; - for (let idx = 0; idx < slice.length; idx += 1) { - out += slice[idx] === "\n" ? "\n" : " "; - } - return out; -} - -function maskPythonNonCodeStrings(code) { - let out = ""; - let i = 0; - while (i < code.length) { - const ch = code[i]; - let prefix = ""; - let quoteIdx = -1; - if (/[A-Za-z_]/.test(ch)) { - const wStart = i; - while (i < code.length && /[A-Za-z0-9_]/.test(code[i])) i += 1; - const word = code.slice(wStart, i); - if (/^[rRbBuUfFtT]{1,2}$/.test(word) && (code[i] === "'" || code[i] === '"')) { - prefix = word; - quoteIdx = i; - } else { - out += word; - continue; - } - } else if (ch === "'" || ch === '"') { - quoteIdx = i; - } - - if (quoteIdx >= 0) { - const q = - code.slice(quoteIdx, quoteIdx + 3) === "'''" || code.slice(quoteIdx, quoteIdx + 3) === '"""' - ? code.slice(quoteIdx, quoteIdx + 3) - : code[quoteIdx]; - const isFormat = /[fFtT]/.test(prefix); - out += prefix + q; - i = quoteIdx + q.length; - if (!isFormat) { - const innerStart = i; - let closed = false; - while (i < code.length) { - if (code[i] === "\\") { - if (i + 1 < code.length) { - i += 2; - } else { - i += 1; - } - continue; - } - if (q.length === 3) { - if (code.slice(i, i + 3) === q) { - out += maskSlicePreservingNewlines(code.slice(innerStart, i)) + q; - i += 3; - closed = true; - break; - } - } else if (code[i] === q) { - out += maskSlicePreservingNewlines(code.slice(innerStart, i)) + q; - i += 1; - closed = true; - break; - } - i += 1; - } - if (!closed) { - out += maskSlicePreservingNewlines(code.slice(innerStart)); - } - continue; - } - - while (i < code.length) { - if (code[i] === "\\") { - const escSlice = code.slice(i, Math.min(i + 2, code.length)); - out += maskSlicePreservingNewlines(escSlice); - i += escSlice.length; - continue; - } - if (q.length === 3) { - if (code.slice(i, i + 3) === q) { - out += q; - i += 3; - break; - } - } else if (code[i] === q) { - out += q; - i += 1; - break; - } - if (code[i] === "{") { - if (code[i + 1] === "{") { - out += " "; - i += 2; - continue; - } - const span = findFStringExprSpan(code, i); - if (span) { - const maskedExpr = maskPythonNonCodeStrings(code.slice(span.exprStart, span.exprEnd)); - const specRaw = code.slice(span.exprEnd, span.closeBrace); - let maskedSpec = ""; - let sj = 0; - while (sj < specRaw.length) { - if (specRaw[sj] === "{" && specRaw[sj + 1] !== "{") { - const subSpan = findFStringExprSpan(specRaw, sj); - if (subSpan) { - maskedSpec += `{${maskPythonNonCodeStrings(specRaw.slice(subSpan.exprStart, subSpan.exprEnd))}${maskSlicePreservingNewlines(specRaw.slice(subSpan.exprEnd, subSpan.closeBrace))}}`; - sj = subSpan.closeBrace + 1; - continue; - } - } - maskedSpec += specRaw[sj] === "\n" ? "\n" : " "; - sj += 1; - } - out += `{${maskedExpr}${maskedSpec}}`; - i = span.closeBrace + 1; - continue; - } - out += code.slice(i); - i = code.length; - break; - } - if (code[i] === "}" && code[i + 1] === "}") { - out += " "; - i += 2; - continue; - } - out += code[i] === "\n" ? "\n" : " "; - i += 1; - } - continue; - } - - out += ch; - i += 1; - } - return out; -} - -function extractPythonReceiverBeforeDot(code, dotIdx) { - const tokens = scanPythonTokensBefore(code, dotIdx); - if (tokens.length === 0) return ""; - let cur = tokens.length - 1; - const endCharIdx = tokens[cur].end; - let startCharIdx = null; - while (cur >= 0) { - const tok = tokens[cur]; - if (tok.kind === "string") { - startCharIdx = tok.start; - break; - } - if (tok.kind === "close") { - if (tok.openTokenIdx < 0) return null; - startCharIdx = tokens[tok.openTokenIdx].start; - cur = tok.openTokenIdx - 1; - if ( - cur >= 0 && - (tokens[cur].kind === "ident" || tokens[cur].kind === "close" || tokens[cur].kind === "string") - ) { - continue; - } - if (cur >= 0 && tokens[cur].kind === "dot") { - startCharIdx = tokens[cur].start; - cur -= 1; - continue; - } - break; - } - if (tok.kind === "ident") { - if (cur === 0 || tokens[cur - 1].kind !== "dot") { - if (PYTHON_STATEMENT_KEYWORDS.has(tok.text)) break; - startCharIdx = tok.start; - break; - } - startCharIdx = tokens[cur - 1].start; - cur -= 2; - if (cur < 0) return null; - continue; - } - break; - } - if (startCharIdx === null) return ""; - return code.slice(startCharIdx, endCharIdx); -} - -function isSinglePyStringLiteralExpr(expr) { - const trimmed = stripBalancedOuterParens(expr); - if (!trimmed) return false; - const tokens = scanPythonTokensBefore(trimmed, trimmed.length); - return tokens.length === 1 && tokens[0].kind === "string" && tokens[0].closed === true; -} - -function isPythonPathlibModuleExpr(rawExpr, symbols) { - const expr = unwrapPythonExprParensAndWalrus(rawExpr); - if (!expr) return false; - if (symbols.pathlibModuleIdents.has(expr)) return true; - const tokens = scanPythonTokensBefore(expr, expr.length); - if ( - tokens.length >= 3 && - tokens[tokens.length - 1].kind === "ident" && - tokens[tokens.length - 2].kind === "dot" - ) { - const subAttr = tokens[tokens.length - 1].text; - const base = expr.slice(0, tokens[tokens.length - 2].start); - if ((subAttr === "_local" || subAttr === "_abc") && isPythonPathlibModuleExpr(base, symbols)) { - return true; - } - } - if ( - /^(?:__import__|builtins\s*\.\s*__import__|importlib\s*\.\s*import_module|import_module)\s*\(\s*['"]pathlib(?:\.[A-Za-z0-9_]+)?['"]\s*\)$/.test( - expr, - ) - ) { - return true; - } - return /^sys\s*\.\s*modules\s*(?:\[\s*['"]pathlib(?:\.[A-Za-z0-9_]+)?['"]\s*\]|\.\s*get\s*\(\s*['"]pathlib(?:\.[A-Za-z0-9_]+)?['"])/.test( - expr, - ); -} - -function isPythonFsModuleExpr(rawExpr, symbols) { - const expr = unwrapPythonExprParensAndWalrus(rawExpr); - if (!expr) return false; - if (symbols.fsModuleIdents.has(expr)) return true; - if ( - /^(?:__import__|builtins\s*\.\s*__import__|importlib\s*\.\s*import_module|import_module)\s*\(\s*['"](?:os|posix|shutil)['"]\s*\)$/.test( - expr, - ) - ) { - return true; - } - return /^sys\s*\.\s*modules\s*(?:\[\s*['"](?:os|posix|shutil)['"]\s*\]|\.\s*get\s*\(\s*['"](?:os|posix|shutil)['"])/.test( - expr, - ); -} - -function receiverReferencesFsModule(rawExpr, symbols) { - const expr = unwrapPythonExprParensAndWalrus(rawExpr); - if (!expr) return false; - if (isPythonFsModuleExpr(expr, symbols)) return true; - if ( - /\b(?:__import__|import_module)\s*\(\s*['"](?:os|posix|shutil)['"]\s*\)|sys\s*\.\s*modules\s*(?:\[\s*['"](?:os|posix|shutil)['"]\s*\]|\.\s*get\s*\(\s*['"](?:os|posix|shutil)['"])/.test( - expr, - ) - ) { - return true; - } - const tokens = scanPythonTokensBefore(expr, expr.length); - for (let idx = 0; idx < tokens.length; idx += 1) { - const tok = tokens[idx]; - if (tok.kind !== "ident") continue; - if (symbols.fsModuleReturningFuncs && symbols.fsModuleReturningFuncs.has(tok.text)) return true; - if (symbols.fsModuleIdents.has(tok.text)) { - const t1 = idx + 1 < tokens.length ? tokens[idx + 1] : null; - const t2 = idx + 2 < tokens.length ? tokens[idx + 2] : null; - if ( - t1 && - t1.kind === "dot" && - t2 && - t2.kind === "ident" && - (t2.text === "path" || - t2.text === "environ" || - t2.text === "sep" || - t2.text === "linesep" || - t2.text === "devnull" || - t2.text === "getpid" || - t2.text === "getcwd") - ) { - continue; - } - return true; - } - } - return false; -} - -function isPythonPathClassExpr(rawExpr, symbols) { - const expr = unwrapPythonExprParensAndWalrus(rawExpr); - if (!expr) return false; - if (symbols.pathClassIdents.has(expr)) return true; - const tokens = scanPythonTokensBefore(expr, expr.length); - if (tokens.length === 0) return false; - const last = tokens[tokens.length - 1]; - if (last.kind === "ident" && tokens.length >= 3 && tokens[tokens.length - 2].kind === "dot") { - const attr = last.text; - const base = expr.slice(0, tokens[tokens.length - 2].start); - if (attr === "__class__") return true; - if (PYTHON_PATH_CLASS_NAMES.has(attr) && isPythonPathlibModuleExpr(base, symbols)) { - return true; - } - } - if (last.kind === "close" && last.ch === ")" && last.openTokenIdx > 0) { - const callee = unwrapPythonExprParensAndWalrus(expr.slice(0, tokens[last.openTokenIdx].start)); - if (callee === "type" || callee === "builtins.type") return true; - if (symbols.pathClassReturningFuncs && symbols.pathClassReturningFuncs.has(callee)) return true; - } - return false; -} - -function receiverReferencesUnboundPathClass(rawExpr, symbols) { - const expr = unwrapPythonExprParensAndWalrus(rawExpr); - if (!expr) return false; - if (isPythonPathClassExpr(expr, symbols)) return true; - const tokens = scanPythonTokensBefore(expr, expr.length); - for (let idx = 0; idx < tokens.length; idx += 1) { - const tok = tokens[idx]; - if (tok.kind !== "ident") continue; - if (symbols.pathClassReturningFuncs && symbols.pathClassReturningFuncs.has(tok.text)) return true; - if (tok.text === "__class__" || tok.text === "type") return true; - if (symbols.pathClassIdents.has(tok.text)) { - const nextTok = idx + 1 < tokens.length ? tokens[idx + 1] : null; - if (!nextTok || nextTok.kind !== "open" || nextTok.ch !== "(") { - return true; - } - } - } - return false; -} - -function isPythonPathCtorCallExpr(rawExpr, symbols) { - const expr = unwrapPythonExprParensAndWalrus(rawExpr); - if (!expr) return null; - const tokens = scanPythonTokensBefore(expr, expr.length); - if (tokens.length < 2) return null; - const last = tokens[tokens.length - 1]; - if (last.kind !== "close" || last.ch !== ")" || last.openTokenIdx <= 0) return null; - const callee = unwrapPythonExprParensAndWalrus(expr.slice(0, tokens[last.openTokenIdx].start)); - let isPathCallee = symbols.pathClassIdents.has(callee) || PYTHON_PATH_CLASS_NAMES.has(callee); - if (!isPathCallee) { - const calleeTokens = scanPythonTokensBefore(callee, callee.length); - if ( - calleeTokens.length >= 3 && - calleeTokens[calleeTokens.length - 1].kind === "ident" && - calleeTokens[calleeTokens.length - 2].kind === "dot" - ) { - const attr = calleeTokens[calleeTokens.length - 1].text; - const base = callee.slice(0, calleeTokens[calleeTokens.length - 2].start); - if (PYTHON_PATH_CLASS_NAMES.has(attr) && isPythonPathlibModuleExpr(base, symbols)) { - isPathCallee = true; - } - } - } - if (!isPathCallee) return null; - return parseCallArguments(expr, tokens[last.openTokenIdx].start); -} - -function collectPythonSymbolBindings(code, preMasked = null) { - const masked = preMasked ?? maskPythonNonCodeStrings(code); - const pathClassIdents = new Set(PYTHON_PATH_CLASS_NAMES); - const pathInstanceIdents = new Set(); - const pathClassReturningFuncs = new Set(); - const fsModuleReturningFuncs = new Set(); - const fsModuleIdents = new Set(PYTHON_FS_MODULE_NAMES); - const pathlibModuleIdents = new Set(["pathlib", "pathlib._local", "pathlib._abc"]); - const fsFuncAliases = new Map(); - const openAliases = new Set(); - const fsOpenAliases = new Set(); - const taintedIdents = new Set([ - ...pathClassIdents, - ...fsModuleIdents, - ...pathlibModuleIdents, - "sys", - "builtins", - "importlib", - "posixpath", - "ntpath", - "genericpath", - "io", - "_io", - "codecs", - "operator", - "type", - ]); - - const plainImportRe = /(?:^|[\n;])\s*import\s+([^\n;#]+)/g; - let im; - while ((im = plainImportRe.exec(masked)) !== null) { - for (const part of im[1].split(",")) { - const m = part.trim().match(/^([A-Za-z_][A-Za-z0-9_.]*)(?:\s+as\s+([A-Za-z_][A-Za-z0-9_]*))?$/); - if (!m) continue; - const mod = m[1]; - const bound = m[2] || mod.split(".")[0]; - taintedIdents.add(bound); - if (PYTHON_FS_MODULE_NAMES.has(mod)) fsModuleIdents.add(bound); - if (mod === "pathlib" || mod.startsWith("pathlib.")) { - pathlibModuleIdents.add(bound); - if (!m[2]) pathlibModuleIdents.add(mod); - } - } - } - - const fromImportRe = /\bfrom\s+([A-Za-z_][A-Za-z0-9_.]*)\s+import\s+([^\n;#]+)/g; - while ((im = fromImportRe.exec(masked)) !== null) { - const mod = im[1]; - const clause = stripBalancedOuterParens(im[2]); - for (const part of clause.split(",")) { - const m = part.trim().match(/^([A-Za-z_][A-Za-z0-9_]*)(?:\s+as\s+([A-Za-z_][A-Za-z0-9_]*))?$/); - if (!m) continue; - const orig = m[1]; - const bound = m[2] || orig; - taintedIdents.add(bound); - if ( - (mod === "pathlib" || mod.startsWith("pathlib.") || pathlibModuleIdents.has(mod)) && - PYTHON_PATH_CLASS_NAMES.has(orig) - ) { - pathClassIdents.add(bound); - } - if (mod === "pathlib" && (orig === "_local" || orig === "_abc")) { - pathlibModuleIdents.add(bound); - } - if (PYTHON_FS_MODULE_NAMES.has(mod) && PYTHON_OS_SHUTIL_FN_NAMES.has(orig)) { - fsFuncAliases.set(bound, { fnName: orig, mod }); - } - if (PYTHON_FS_MODULE_NAMES.has(mod) && orig === "open") { - fsOpenAliases.add(bound); - } - if (["io", "_io", "builtins", "codecs"].includes(mod) && orig === "open") { - openAliases.add(bound); - } - if (PYTHON_FS_MODULE_NAMES.has(orig)) fsModuleIdents.add(bound); - if (orig === "pathlib") pathlibModuleIdents.add(bound); - } - } - - const classDefs = []; - const classDefRe = /\bclass\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(/g; - let cm; - while ((cm = classDefRe.exec(masked)) !== null) { - const clsName = cm[1]; - const openParenIdx = cm.index + cm[0].length - 1; - const baseArgs = parseCallArguments(code, openParenIdx); - if (baseArgs === null) { - pathClassIdents.add(clsName); - taintedIdents.add(clsName); - } else { - classDefs.push([clsName, baseArgs]); - } - } - - const defHeaders = []; - const defRe = /\bdef\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(/g; - let dm; - while ((dm = defRe.exec(masked)) !== null) { - defHeaders.push({ name: dm[1], index: dm.index }); - } - const defReturns = []; - if (defHeaders.length > 0) { - const retRe = /\breturn\s+([^\n;#]+)/g; - let rm; - while ((rm = retRe.exec(masked)) !== null) { - let owner = null; - for (const dh of defHeaders) { - if (dh.index < rm.index) owner = dh.name; - } - if (owner) { - const retStart = rm.index + rm[0].length - rm[1].length; - defReturns.push([owner, code.slice(retStart, retStart + rm[1].length).trim()]); - } - } - } - - const pairs = []; - const assignStmtRe = /(?:^|[\n;])\s*([A-Za-z_][A-Za-z0-9_]*(?:\s*,\s*[A-Za-z_][A-Za-z0-9_]*|\s*=\s*[A-Za-z_][A-Za-z0-9_]*)*)\s*=(?!=)\s*([^\n;#]+)/g; - let am; - while ((am = assignStmtRe.exec(masked)) !== null) { - const lhsRaw = am[1].trim(); - const rhsStart = am.index + am[0].length - am[2].length; - const rhsRaw = code.slice(rhsStart, rhsStart + am[2].length).trim(); - if (lhsRaw.includes(",")) { - const lhsNames = lhsRaw.split(",").map((s) => s.trim()); - const rhsTuple = parseCallArguments(`(${stripBalancedOuterParens(rhsRaw)})`, 0); - if (rhsTuple && rhsTuple.length === lhsNames.length) { - for (let idx = 0; idx < lhsNames.length; idx += 1) { - pairs.push([lhsNames[idx], rhsTuple[idx]]); - } - } else { - for (const name of lhsNames) pairs.push([name, rhsRaw]); - } - } else { - for (const name of lhsRaw.split("=").map((s) => s.trim())) { - if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) pairs.push([name, rhsRaw]); - } - } - } - - const walrusRe = /\b([A-Za-z_][A-Za-z0-9_]*)\s*:=\s*([^,)\]\n;#]+)/g; - while ((am = walrusRe.exec(masked)) !== null) { - const rhsStart = am.index + am[0].length - am[2].length; - pairs.push([am[1], code.slice(rhsStart, rhsStart + am[2].length).trim()]); - } - - const forLoopRe = /\bfor\s+([A-Za-z_][A-Za-z0-9_]*)\s+in\s+([^\n:#]+):/g; - const forPairs = []; - while ((am = forLoopRe.exec(masked)) !== null) { - const iterStart = am.index + am[0].length - 1 - am[2].length; - forPairs.push([am[1], code.slice(iterStart, iterStart + am[2].length).trim()]); - } - - const symbols = { - pathClassIdents, - pathInstanceIdents, - pathClassReturningFuncs, - fsModuleReturningFuncs, - fsModuleIdents, - pathlibModuleIdents, - fsFuncAliases, - openAliases, - fsOpenAliases, - taintedIdents, - }; - const maxPasses = pairs.length + classDefs.length + forPairs.length + defReturns.length + 8; - for (let pass = 0; pass < maxPasses; pass += 1) { - const beforeSize = - pathClassIdents.size + - pathInstanceIdents.size + - pathClassReturningFuncs.size + - fsModuleReturningFuncs.size + - fsModuleIdents.size + - pathlibModuleIdents.size + - fsFuncAliases.size + - openAliases.size + - fsOpenAliases.size + - taintedIdents.size; - for (const [lhs, rhs] of pairs) { - if (isPythonFsModuleExpr(rhs, symbols)) { - fsModuleIdents.add(lhs); - taintedIdents.add(lhs); - } else if (isPythonPathlibModuleExpr(rhs, symbols)) { - pathlibModuleIdents.add(lhs); - taintedIdents.add(lhs); - } else if (isPythonPathClassExpr(rhs, symbols)) { - pathClassIdents.add(lhs); - taintedIdents.add(lhs); - } else { - const stripped = unwrapPythonExprParensAndWalrus(rhs); - const maskedStripped = maskPythonNonCodeStrings(stripped); - if (fsFuncAliases.has(stripped)) { - fsFuncAliases.set(lhs, fsFuncAliases.get(stripped)); - taintedIdents.add(lhs); - } else if (openAliases.has(stripped)) { - openAliases.add(lhs); - taintedIdents.add(lhs); - } else if (fsOpenAliases.has(stripped)) { - fsOpenAliases.add(lhs); - taintedIdents.add(lhs); - } else if (isPythonPathCtorCallExpr(stripped, symbols) !== null || pathInstanceIdents.has(stripped)) { - pathInstanceIdents.add(lhs); - taintedIdents.add(lhs); - } else if ( - taintedIdents.has(stripped) || - receiverReferencesUnboundPathClass(stripped, symbols) || - receiverReferencesFsModule(stripped, symbols) || - /\b(?:__import__|import_module|globals|locals|vars|getattr|type)\s*\(|\b(?:__class__|__base__|__bases__|__mro__|__subclasses__|__dict__)\b|sys\s*\.\s*modules/.test( - maskedStripped, - ) - ) { - taintedIdents.add(lhs); - } - } - } - for (const [fnName, retExpr] of defReturns) { - if (receiverReferencesUnboundPathClass(retExpr, symbols)) { - pathClassReturningFuncs.add(fnName); - taintedIdents.add(fnName); - } - if (receiverReferencesFsModule(retExpr, symbols)) { - fsModuleReturningFuncs.add(fnName); - taintedIdents.add(fnName); - } - } - for (const [clsName, baseArgs] of classDefs) { - for (const rawBase of baseArgs) { - const baseExpr = unwrapPythonExprParensAndWalrus(rawBase); - if (!baseExpr) continue; - if ( - isPythonPathClassExpr(baseExpr, symbols) || - isPythonPathlibModuleExpr(baseExpr, symbols) - ) { - pathClassIdents.add(clsName); - taintedIdents.add(clsName); - break; - } - const baseTokens = scanPythonTokensBefore(baseExpr, baseExpr.length); - if ( - baseTokens.some( - (tok) => - tok.kind === "ident" && - (pathClassIdents.has(tok.text) || pathlibModuleIdents.has(tok.text)), - ) - ) { - pathClassIdents.add(clsName); - taintedIdents.add(clsName); - break; - } - } - } - for (const [loopVar, iterExpr] of forPairs) { - const iterTokens = scanPythonTokensBefore(iterExpr, iterExpr.length); - for (const tok of iterTokens) { - if (tok.kind !== "ident") continue; - if (pathClassIdents.has(tok.text) || tok.text === "type" || tok.text === "__class__") { - pathClassIdents.add(loopVar); - taintedIdents.add(loopVar); - } else if (fsModuleIdents.has(tok.text)) { - fsModuleIdents.add(loopVar); - taintedIdents.add(loopVar); - } else if (pathlibModuleIdents.has(tok.text)) { - pathlibModuleIdents.add(loopVar); - taintedIdents.add(loopVar); - } - } - } - const afterSize = - pathClassIdents.size + - pathInstanceIdents.size + - pathClassReturningFuncs.size + - fsModuleReturningFuncs.size + - fsModuleIdents.size + - pathlibModuleIdents.size + - fsFuncAliases.size + - openAliases.size + - fsOpenAliases.size + - taintedIdents.size; - if (afterSize === beforeSize) break; - } - - return symbols; -} - -function isValidStrReplaceArgs(methodArgs) { - const effective = - methodArgs.length > 0 && methodArgs[methodArgs.length - 1] === "" - ? methodArgs.slice(0, -1) - : methodArgs; - if (effective.length !== 2 && effective.length !== 3) return false; - if (effective.some((a) => a.length === 0 || a.startsWith("*"))) return false; - const { positionals, kwargs } = splitPythonCallArgs(effective); - const kwKeys = Object.keys(kwargs); - if (kwKeys.length === 0) { - return positionals.length === 2 || positionals.length === 3; - } - return positionals.length === 2 && kwKeys.length === 1 && kwKeys[0] === "count"; -} - -function isSafeStrReplaceReceiver(rawExpr, symbols, depth = 0) { - if (depth > 6 || rawExpr === null) return false; - const expr = stripBalancedOuterParens(rawExpr); - if (!expr) return false; - if (isPythonPathClassExpr(expr, symbols) || isPythonFsModuleExpr(expr, symbols)) return false; - if (isSinglePyStringLiteralExpr(expr)) return true; - if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(expr)) { - return !symbols.taintedIdents.has(expr); - } - const tokens = scanPythonTokensBefore(expr, expr.length); - if (tokens.length < 2) return false; - const last = tokens[tokens.length - 1]; - if (last.kind !== "close" || last.ch !== ")" || last.openTokenIdx <= 0) return false; - const callArgs = parseCallArguments(expr, tokens[last.openTokenIdx].start); - if (!callArgs) return false; - if (last.openTokenIdx === 1 && tokens[0].kind === "ident") { - const fn = tokens[0].text; - return ["str", "repr", "chr", "format", "ascii"].includes(fn) && !symbols.taintedIdents.has(fn); - } - if ( - last.openTokenIdx >= 3 && - tokens[last.openTokenIdx - 1].kind === "ident" && - tokens[last.openTokenIdx - 2].kind === "dot" - ) { - const methodName = tokens[last.openTokenIdx - 1].text; - const subRecv = stripBalancedOuterParens(expr.slice(0, tokens[last.openTokenIdx - 2].start)); - if (!subRecv) return false; - if (methodName === "replace") { - return isValidStrReplaceArgs(callArgs) && isSafeStrReplaceReceiver(subRecv, symbols, depth + 1); - } - if (methodName === "get") { - if (subRecv === "os.environ" || subRecv === "posix.environ") return true; - return /^[A-Za-z_][A-Za-z0-9_]*$/.test(subRecv) && !symbols.taintedIdents.has(subRecv); - } - if (methodName === "dumps" && subRecv === "json") return true; - if (PYTHON_STRING_RETURNING_METHODS.has(methodName)) { - return !isPythonPathClassExpr(subRecv, symbols) && !isPythonFsModuleExpr(subRecv, symbols); - } - } - return false; -} - -function isVarBoundToVerifiedTmpRoot(varName, code) { - if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(varName)) return false; - const varEsc = varName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - const assignRe = new RegExp( - `(?:^|[\\n;])\\s*(?:(?:const|let|var)\\s+)?${varEsc}\\s*=\\s*([^\\n;]+)`, - "g", - ); - let lastRhs = null; - let m; - while ((m = assignRe.exec(code)) !== null) { - lastRhs = m[1].trim(); - } - if (!lastRhs || lastRhs.includes("..")) return false; - return /^(?:[fFrRuUbB]{0,2}['"`](?:\/private)?\/tmp(?:\/|['"`\b])|[^\n;]*(?:mkdtemp|mkdtempSync|gettempdir|tmpdir)\s*\(|os\.environ\.get\(\s*['"]TMPDIR['"])/.test( - lastRhs, - ); -} - -function isSafeTmpTemplateOrJoin(expr, code, allowPath) { - if (!allowPath("/tmp/__pstack_probe__", { allowRootEqual: false, allowDevNull: false })) { - return false; - } - const trimmed = expr.trim(); - if (trimmed.includes("..")) return false; - if (/^`(?:\/private)?\/tmp\/[^`]+`$/.test(trimmed)) { - return true; - } - const jsVarTemplate = trimmed.match(/^`\$\{([A-Za-z_][A-Za-z0-9_]*)\}(?:\/[^`]*)?`$/); - if (jsVarTemplate && isVarBoundToVerifiedTmpRoot(jsVarTemplate[1], code)) { - return true; - } - if ( - /^[fF](?:'''[\s\S]*'''|"""[\s\S]*"""|'[^']*'|"[^"]*")$/.test(trimmed) && - /^[fF]['"]{1,3}(?:\/private)?\/tmp\//.test(trimmed) - ) { - return true; - } - const pyVarTemplate = trimmed.match(/^[fF](?:'''|"""|'|\")\{([A-Za-z_][A-Za-z0-9_]*)\}(?:\/[^'"]*)?(?:'''|"""|'|\")$/); - if (pyVarTemplate && isVarBoundToVerifiedTmpRoot(pyVarTemplate[1], code)) { - return true; - } - 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 >= 1) { - if (innerArgs.some((a) => a.includes(".."))) return false; - const rootArg = innerArgs[0].trim(); - if ( - /^['"`](?:\/private)?\/tmp(?:\/|['"`]$)/.test(rootArg) || - /\b(?:mkdtemp|mkdtempSync|gettempdir|tmpdir)\s*\(/.test(rootArg) - ) { - return true; - } - if (isVarBoundToVerifiedTmpRoot(rootArg, code)) { - return true; - } - } - } - return false; -} - -function unwrapPythonPathCtor(expr, symbols = null) { - const trimmed = stripBalancedOuterParens(expr); - if (!trimmed) return ""; - if (symbols) { - const ctorArgs = isPythonPathCtorCallExpr(trimmed, symbols); - if (ctorArgs) { - if (ctorArgs.length === 0) return trimmed; - if (ctorArgs.length === 1) return ctorArgs[0].trim(); - return `os.path.join(${ctorArgs.join(", ")})`; - } - } - const m = trimmed.match( - /^(?:pathlib\s*\.\s*)?(?:Path|PurePath|PosixPath|WindowsPath|PurePosixPath|PureWindowsPath)\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; - const varEsc = trimmed.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - const assignRe = new RegExp(`(?:^|[\\n;])\\s*(?:(?:const|let|var)\\s+)?${varEsc}\\s*=\\s*([^\\n;]+)`, "g"); - let lastRhs = null; - let m; - while ((m = assignRe.exec(code)) !== null) { - lastRhs = m[1].trim(); - } - if (!lastRhs) return null; - const normalizedRhs = isPython ? unwrapPythonPathCtor(lastRhs) : lastRhs; - return isPython ? parseStaticPyString(normalizedRhs) : parseStaticJsString(normalizedRhs); -} - -function resolveStaticArgValue(argExpr, code, isPython) { - const normalizedExpr = isPython ? unwrapPythonPathCtor(argExpr || "") : String(argExpr || ""); - const lit = isPython ? parseStaticPyString(normalizedExpr) : parseStaticJsString(normalizedExpr); - if (lit.ok) return lit.value; - const bound = resolveSimpleVarBinding(code, normalizedExpr, 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", - allowReadOnlyArtifactCopySource = null, - registerReadOnlyMkdir = null, - } = options; - - const bracketRe = /(?:([A-Za-z_$][A-Za-z0-9_$]*)|([)\]'"]))\s*\[([^\]]*)\]/g; - let bm; - while ((bm = bracketRe.exec(code)) !== null) { - const ident = bm[1] || ""; - const bracketBody = bm[3] || ""; - if (ident && JS_NON_MEMBER_PREFIX_KEYWORDS.has(ident)) continue; - const afterBracket = code.slice(bm.index + bm[0].length); - const isFsReceiver = - ident === "fs" || - ident === "fsp" || - ident === "promises" || - /require\s*\(\s*['"](?:node:)?fs(?:\/promises)?['"]\s*\)\s*$/.test(code.slice(0, bm.index + (bm[2] ? 1 : 0))); - if (NODE_MUTATION_NAME_RE.test(bracketBody) || (isFsReceiver && /^\s*\(/.test(afterBracket))) { - if (!allowDynamicPaths) { - return `Dynamic fs mutation via inline Node script is blocked for ${roleLabel}.`; - } - } - } - - if ( - !allowDynamicPaths && - (/\.\s*(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(?!\s*\()/.test( - code, - ) || - /\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)\s*\bas\b/.test( - code, - ) || - /(?:const|let|var|\(|^|[;\n,])\s*\{[^}]*\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)\s*:[^}]*\}\s*=/.test( - code, - )) - ) { - return `Aliased fs mutation API in inline Node script is blocked for ${roleLabel}.`; - } - - const checkNodePathArg = (argExpr, opts) => { - const rawExpr = String(argExpr || ""); - const lit = parseStaticJsString(rawExpr); - if (lit.ok) { - return allowPath(lit.value, opts); - } - const bound = resolveSimpleVarBinding(code, rawExpr, false); - if (bound && bound.ok) { - return allowPath(bound.value, opts); - } - const joined = resolveStaticJoinOrTemplate(rawExpr, code, false); - if (joined !== null) { - return allowPath(joined, opts); - } - if (isSafeTmpTemplateOrJoin(rawExpr, code, allowPath)) { - return true; - } - if (/\.system_generated(?:[/\\'"`]|$)/.test(rawExpr)) { - return false; - } - return allowDynamicPaths; - }; - - const callRe = - /\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|open)\s*\(/g; - - let match; - while ((match = callRe.exec(code)) !== null) { - const fnName = match[1]; - if ((fnName === "open" || fnName === "openSync") && !/\bfs\b|node:fs/.test(code)) { - continue; - } - const openParenIdx = match.index + match[0].length - 1; - const callArgs = parseCallArguments(code, openParenIdx); - if (!callArgs) { - return `Unparseable fs.${fnName} call in inline Node script is blocked for ${roleLabel}.`; - } - - if (fnName === "open" || fnName === "openSync") { - if (callArgs.length >= 2) { - const modeLit = parseStaticJsString(callArgs[1]); - if (modeLit.ok && (modeLit.value === "r" || modeLit.value === "rs")) { - continue; - } - } else { - continue; - } - if (!checkNodePathArg(callArgs[0], { allowRootEqual: false, allowDevNull: true })) { - return `Inline Node fs.${fnName} write outside allowed roots is blocked for ${roleLabel}.`; - } - continue; - } - - if (NODE_SINGLE_PATH_FS_APIS.has(fnName)) { - 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: 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 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 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, - allowArtifactRoot: false, - forbidReadOnlyArtifact: !srcOkForRoArtifact, - }) - ) { - return `Inline Node fs.${fnName} destination outside allowed roots is blocked for ${roleLabel}.`; - } - continue; - } - - if (NODE_TWO_PATH_FS_APIS.has(fnName)) { - 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, - allowArtifactRoot: false, - forbidReadOnlyArtifact: isLink || !srcOkForRoArtifact, - disallowArtifactRoot: 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; -} - -function splitPythonCallArgs(callArgs) { - const positionals = []; - const kwargs = {}; - const trimmed = - callArgs.length > 0 && callArgs[callArgs.length - 1] === "" - ? callArgs.slice(0, -1) - : callArgs; - for (const arg of trimmed) { - const kwMatch = arg.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=(?!=)\s*([\s\S]*)$/); - if (kwMatch) { - kwargs[kwMatch[1]] = kwMatch[2].trim(); - } else { - positionals.push(arg); - } - } - return { positionals, kwargs }; -} - -function hasDisallowedPythonAlias(code) { - const fromImportRe = /\bfrom\s+pathlib(?:\.[A-Za-z0-9_]+)?\s+import\s+([^\n;]+)/g; - let im; - while ((im = fromImportRe.exec(code)) !== null) { - const clause = im[1]; - if (/\bas\b/.test(clause) && PYTHON_MUTATION_NAME_RE.test(clause)) { - return true; - } - } - return false; -} - -function checkInlinePythonFs(rawCode, allowPath, options = {}) { - const { - allowDynamicPaths = false, - roleLabel = "read-only ro-* workers", - allowReadOnlyArtifactCopySource = null, - registerReadOnlyMkdir = null, - } = options; - - const code = normalizeInlinePythonCode(rawCode); - const maskedCode = maskPythonNonCodeStrings(code); - - if (PYTHON_REFLECTION_IDENT_RE.test(maskedCode) || PYTHON_EVAL_EXEC_RE.test(maskedCode)) { - return `Dynamic Python reflection or attribute dispatch in inline Python script is blocked for ${roleLabel}.`; - } - - if (PYTHON_UNBOUND_MUTATION_ATTR_RE.test(maskedCode) || PYTHON_UNBOUND_OPEN_RE.test(maskedCode)) { - return `Aliased filesystem mutation API in inline Python script is blocked for ${roleLabel}.`; - } - - if (!allowDynamicPaths && hasDisallowedPythonAlias(maskedCode)) { - return `Aliased filesystem mutation API in inline Python script is blocked for ${roleLabel}.`; - } - - const pySymbols = collectPythonSymbolBindings(code, maskedCode); - - const checkPyPathArg = (argExpr, opts) => { - const rawExpr = unwrapPythonPathCtor(argExpr || "", pySymbols); - const lit = parseStaticPyString(rawExpr); - if (lit.ok) { - return allowPath(lit.value, opts); - } - const bound = resolveSimpleVarBinding(code, rawExpr, true); - if (bound && bound.ok) { - return allowPath(bound.value, opts); - } - const joined = resolveStaticJoinOrTemplate(rawExpr, code, true); - if (joined !== null) { - return allowPath(joined, opts); - } - if (isSafeTmpTemplateOrJoin(rawExpr, code, allowPath)) { - return true; - } - if (/\.system_generated(?:[/\\'"`]|$)/.test(rawExpr)) { - return false; - } - return allowDynamicPaths; - }; - - const resolvePythonPathReceiverArg = (rawRecv) => { - if (rawRecv === null) return { valid: false, found: true, expr: null }; - const recvExpr = unwrapPythonExprParensAndWalrus(rawRecv); - const ctorArgs = isPythonPathCtorCallExpr(recvExpr, pySymbols); - if (ctorArgs !== null) { - if (ctorArgs.length !== 1) return { valid: false, found: true, expr: null }; - return { valid: true, found: true, expr: ctorArgs[0] }; - } - if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(recvExpr)) { - const varEsc = recvExpr.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - const assignRe = new RegExp(`(?:^|[\\n;])\\s*${varEsc}\\s*=\\s*([^\\n;#]+)`, "g"); - let lastRhs = null; - let am; - while ((am = assignRe.exec(code)) !== null) { - lastRhs = am[1].trim(); - } - if (lastRhs !== null) { - const boundCtorArgs = isPythonPathCtorCallExpr(lastRhs, pySymbols); - if (boundCtorArgs !== null && boundCtorArgs.length === 1) { - return { valid: true, found: true, expr: boundCtorArgs[0] }; - } - } - } - return { valid: true, found: false, expr: null }; - }; - - const validateOsShutilCall = (fnName, qualifier, callArgs) => { - const { positionals, kwargs } = splitPythonCallArgs(callArgs); - if (["copy", "copy2", "copyfile", "copytree"].includes(fnName)) { - if (!qualifier && !/\bshutil\b/.test(maskedCode)) return null; - 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 ( - !dstExpr || - !checkPyPathArg(dstExpr, { - allowRootEqual: true, - allowDevNull: true, - allowArtifactDir: allowImgDir, - allowArtifactRoot: allowImgDir, - forbidReadOnlyArtifact: isCopyTree || !srcOkForRoArtifact, - }) - ) { - return `Inline Python ${fnName}() destination outside allowed roots is blocked for ${roleLabel}.`; - } - return null; - } - if (["rename", "renames", "replace", "move", "symlink", "link"].includes(fnName)) { - 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 ( - !srcExpr || - !dstExpr || - !checkPyPathArg(srcExpr, { - allowRootEqual: false, - allowDevNull: false, - forbidReadOnlyArtifact: isLink, - disallowArtifactRoot: isLink, - customBaseDir: symlinkBaseDir, - }) || - !checkPyPathArg(dstExpr, { - allowRootEqual: fnName === "move", - allowDevNull: false, - allowArtifactDir: allowMoveDir, - allowArtifactRoot: allowMoveDir, - forbidReadOnlyArtifact: isLink || !srcOkForRoArtifact, - disallowArtifactRoot: isLink || fnName !== "move", - }) - ) { - return `Inline Python ${fnName}() outside allowed roots is blocked for ${roleLabel}.`; - } - return null; - } - const singleExpr = positionals[0] ?? kwargs.path ?? kwargs.name ?? ""; - const isMkdir = fnName === "mkdir" || fnName === "makedirs"; - const forbidRo = ["rmdir", "removedirs", "rmtree", "chmod", "lchmod", "chown"].includes(fnName); - if ( - !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, pySymbols), code, true); - if (mkdirVal) registerReadOnlyMkdir(mkdirVal); - } - return null; - }; - - const validatePyOpenArgs = (openArgs) => { - const { positionals, kwargs } = splitPythonCallArgs(openArgs); - const modeExpr = positionals[1] ?? kwargs.mode ?? null; - if (modeExpr === null) return null; - const modeLit = parseStaticPyString(modeExpr); - if (modeLit.ok && /^[rbtU]+$/.test(modeLit.value) && modeLit.value.includes("r")) { - return null; - } - const pathExpr = positionals[0] ?? kwargs.file ?? ""; - if (!checkPyPathArg(pathExpr, { allowRootEqual: false, allowDevNull: true })) { - return `Inline Python open() for write outside allowed roots is blocked for ${roleLabel}.`; - } - return null; - }; - - if (registerReadOnlyMkdir) { - const preMkdirRe = /(?:(?:os|posix)\s*\.\s*|\b)(?:mkdir|makedirs)\s*\(/g; - let pm; - while ((pm = preMkdirRe.exec(maskedCode)) !== 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, pySymbols), code, true); - if (dVal) registerReadOnlyMkdir(dVal); - } - for (const [alias, entry] of pySymbols.fsFuncAliases.entries()) { - if (entry.fnName !== "mkdir" && entry.fnName !== "makedirs") continue; - const aliasEsc = alias.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - const aliasCallRe = new RegExp(`(?:^|[^\\w.])${aliasEsc}\\s*\\(`, "g"); - while ((pm = aliasCallRe.exec(maskedCode)) !== 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, pySymbols), 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|link_to|open)\s*\(/g; - let match; - while ((match = pathMethodRe.exec(maskedCode)) !== null) { - const method = match[1]; - const openParenIdx = match.index + match[0].length - 1; - const methodArgs = parseCallArguments(code, openParenIdx); - if (!methodArgs) { - return `Unparseable .${method}() call in inline Python script is blocked for ${roleLabel}.`; - } - const rawRecv = extractPythonReceiverBeforeDot(code, match.index); - if (rawRecv === null) { - return `Unparseable .${method}() receiver in inline Python script is blocked for ${roleLabel}.`; - } - if (receiverReferencesUnboundPathClass(rawRecv, pySymbols)) { - return `Unbound Python Path.${method}() call in inline Python script is blocked for ${roleLabel}.`; - } - if (PYTHON_OS_SHUTIL_FN_NAMES.has(method) && isPythonFsModuleExpr(rawRecv, pySymbols)) { - continue; - } - if (receiverReferencesFsModule(rawRecv, pySymbols)) { - return `Wrapped filesystem module .${method}() call in inline Python script is blocked for ${roleLabel}.`; - } - if (method === "open") { - const recvTrimmed = unwrapPythonExprParensAndWalrus(rawRecv); - if ( - recvTrimmed === "io" || - recvTrimmed === "_io" || - recvTrimmed === "builtins" || - recvTrimmed === "codecs" - ) { - const openDeny = validatePyOpenArgs(methodArgs); - if (openDeny) return openDeny; - continue; - } - if (isPythonFsModuleExpr(rawRecv, pySymbols)) { - const { positionals, kwargs } = splitPythonCallArgs(methodArgs); - const pathExpr = positionals[0] ?? kwargs.path ?? ""; - if (!pathExpr || !checkPyPathArg(pathExpr, { allowRootEqual: false, allowDevNull: true })) { - return `Inline Python os.open() outside allowed roots is blocked for ${roleLabel}.`; - } - continue; - } - const { positionals, kwargs } = splitPythonCallArgs(methodArgs); - const modeExpr = positionals[0] ?? kwargs.mode ?? null; - if (modeExpr === null) continue; - const modeLit = parseStaticPyString(modeExpr); - if (modeLit.ok && /^[rbtU]+$/.test(modeLit.value) && modeLit.value.includes("r")) { - continue; - } - } - if ( - method === "replace" && - isValidStrReplaceArgs(methodArgs) && - isSafeStrReplaceReceiver(rawRecv, pySymbols) - ) { - continue; - } - if ( - ["write_text", "write_bytes", "unlink", "rmdir", "mkdir", "touch", "chmod", "lchmod"].includes( - method, - ) - ) { - const { positionals: uPos, kwargs: uKw } = splitPythonCallArgs(methodArgs); - const selfCandidate = uPos[0] ?? uKw.self ?? null; - if (selfCandidate !== null) { - const trimmedSelf = unwrapPythonExprParensAndWalrus(selfCandidate); - if ( - isPythonPathCtorCallExpr(trimmedSelf, pySymbols) !== null || - pySymbols.pathInstanceIdents.has(trimmedSelf) || - resolvePythonPathReceiverArg(trimmedSelf).found - ) { - return `Unbound Python Path.${method}() call in inline Python script is blocked for ${roleLabel}.`; - } - } - } - const recv = resolvePythonPathReceiverArg(rawRecv); - const isMkdir = method === "mkdir"; - const isLinkMethod = - method === "symlink_to" || method === "hardlink_to" || method === "link_to"; - const forbidRo = - isLinkMethod || - method === "rmdir" || - method === "chmod" || - method === "lchmod"; - if (!recv.valid) { - return `Inline Python Path.${method}() outside allowed roots is blocked for ${roleLabel}.`; - } - if (recv.found) { - if ( - !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, pySymbols), 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); - if (mPos.length >= 2 || Object.hasOwn(mKw, "self")) { - return `Unbound Python Path.${method}() call in inline Python script is blocked for ${roleLabel}.`; - } - 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 isTwoArgCall = mPos.length >= 2 || (mPos.length === 1 && Object.hasOwn(mKw, "target")); - const srcArgExpr = isTwoArgCall ? mPos[0] : null; - const targetExpr = isTwoArgCall ? (mPos[1] ?? mKw.target ?? "") : (mPos[0] ?? mKw.target ?? ""); - const recvVal = srcArgExpr - ? resolveStaticArgValue(srcArgExpr, code, true) - : 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 ( - srcArgExpr !== null && - !checkPyPathArg(srcArgExpr, { - allowRootEqual: false, - allowDevNull: false, - allowArtifactDir: false, - allowArtifactRoot: false, - disallowArtifactRoot: true, - }) - ) { - return `Inline Python Path.${method}() outside allowed roots is blocked for ${roleLabel}.`; - } - if ( - !targetExpr || - !checkPyPathArg(targetExpr, { - allowRootEqual: false, - allowDevNull: false, - allowArtifactDir: false, - allowArtifactRoot: false, - disallowArtifactRoot: true, - forbidReadOnlyArtifact: !srcOkForRoArtifact, - }) - ) { - return `Inline Python Path.${method}() target outside allowed roots is blocked for ${roleLabel}.`; - } - } - } - - const openRe = /(?:^|[^\w.])(?:_?io\s*\.\s*|builtins\s*\.\s*|codecs\s*\.\s*)?open\s*\(/g; - while ((match = openRe.exec(maskedCode)) !== null) { - const openParenIdx = match.index + match[0].length - 1; - const openArgs = parseCallArguments(code, openParenIdx); - if (!openArgs) { - return `Unparseable open() call in inline Python script is blocked for ${roleLabel}.`; - } - const openDeny = validatePyOpenArgs(openArgs); - if (openDeny) return openDeny; - } - - const hasFsImport = /\b(?:os|posix|shutil)\b/.test(maskedCode); - const osShutilRe = - /(?:(os|posix|shutil)\s*\.\s*|\b)(remove|unlink|rmdir|removedirs|mkdir|makedirs|chmod|lchmod|chown|truncate|rename|renames|replace|rmtree|move|copy|copy2|copyfile|copytree|symlink|link)\s*\(/g; - while ((match = osShutilRe.exec(maskedCode)) !== null) { - let qualifier = match[1] || ""; - const fnName = match[2]; - if (!qualifier) { - const dotMatch = maskedCode.slice(0, match.index).match(/\.\s*$/); - if (dotMatch) { - const memberRecv = extractPythonReceiverBeforeDot(code, match.index - dotMatch[0].length); - if (!isPythonFsModuleExpr(memberRecv, pySymbols)) { - if (receiverReferencesFsModule(memberRecv, pySymbols)) { - return `Wrapped filesystem module .${fnName}() call in inline Python script is blocked for ${roleLabel}.`; - } - continue; - } - qualifier = "fs_alias"; - } else if (!hasFsImport) { - continue; - } - } - const openParenIdx = match.index + match[0].length - 1; - const callArgs = parseCallArguments(code, openParenIdx); - if (!callArgs) { - return `Unparseable ${fnName}() call in inline Python script is blocked for ${roleLabel}.`; - } - const callDeny = validateOsShutilCall(fnName, qualifier, callArgs); - if (callDeny) return callDeny; - } - - if ( - pySymbols.fsFuncAliases.size > 0 || - pySymbols.openAliases.size > 0 || - pySymbols.fsOpenAliases.size > 0 - ) { - const bodyMasked = maskedCode - .replace(/\bfrom\s+[A-Za-z_][A-Za-z0-9_.]*\s+import\s+[^\n;]+/g, (s) => " ".repeat(s.length)) - .replace(/(?:^|[\n;])\s*import\s+[^\n;]+/g, (s) => - s.replace(/[^\n]/g, " "), - ); - - const checkAliasUsages = (alias, validateCallFn, fnLabel) => { - const aliasEsc = alias.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - const refRe = new RegExp(`(?:^|[^\\w.])(${aliasEsc})\\b`, "g"); - let rm; - while ((rm = refRe.exec(bodyMasked)) !== null) { - const aliasEnd = rm.index + rm[0].length; - const aliasStart = aliasEnd - rm[1].length; - const beforeTrimmed = bodyMasked.slice(0, aliasStart).trimEnd(); - if (beforeTrimmed.endsWith(".")) continue; - const afterAlias = bodyMasked.slice(aliasEnd); - const callMatch = afterAlias.match(/^\s*\(/); - if (callMatch) { - const openParenIdx = aliasEnd + callMatch[0].length - 1; - const callArgs = parseCallArguments(code, openParenIdx); - if (!callArgs) { - return `Unparseable ${fnLabel}() call in inline Python script is blocked for ${roleLabel}.`; - } - const deny = validateCallFn(callArgs); - if (deny) return deny; - continue; - } - const isSimpleAssignRhs = - /(?:^|[\n;])\s*[A-Za-z_][A-Za-z0-9_]*\s*=$/.test(beforeTrimmed) && - /^\s*(?:$|[\n;])/.test(afterAlias); - const isSimpleAssignLhs = - /(?:^|[\n;])$/.test(beforeTrimmed) && /^\s*=(?!=)/.test(afterAlias); - if (isSimpleAssignRhs || isSimpleAssignLhs) continue; - return `Aliased filesystem mutation API in inline Python script is blocked for ${roleLabel}.`; - } - return null; - }; - - for (const [alias, entry] of pySymbols.fsFuncAliases.entries()) { - const deny = checkAliasUsages( - alias, - (callArgs) => validateOsShutilCall(entry.fnName, entry.mod, callArgs), - entry.fnName, - ); - if (deny) return deny; - } - for (const alias of pySymbols.openAliases) { - const deny = checkAliasUsages(alias, validatePyOpenArgs, "open"); - if (deny) return deny; - } - for (const alias of pySymbols.fsOpenAliases) { - const deny = checkAliasUsages( - alias, - (callArgs) => { - const { positionals, kwargs } = splitPythonCallArgs(callArgs); - const pathExpr = positionals[0] ?? kwargs.path ?? ""; - if (!pathExpr || !checkPyPathArg(pathExpr, { allowRootEqual: false, allowDevNull: true })) { - return `Inline Python os.open() outside allowed roots is blocked for ${roleLabel}.`; - } - return null; - }, - "open", - ); - if (deny) return deny; - } - } - - const screenshotRe = /\.\s*screenshot\s*\(/g; - while ((match = screenshotRe.exec(maskedCode)) !== 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; -} - -function parseGitCommand(args) { - const globalDirs = []; - let i = 0; - while (i < args.length) { - const arg = args[i]; - if (arg === "-C" || arg === "--git-dir" || arg === "--work-tree") { - if (i + 1 < args.length) globalDirs.push(args[i + 1]); - i += 2; - continue; - } - if (arg.startsWith("-C") && arg.length > 2) { - globalDirs.push(arg.slice(2)); - i += 1; - continue; - } - if (arg.startsWith("--git-dir=")) { - globalDirs.push(arg.slice("--git-dir=".length)); - i += 1; - continue; - } - if (arg.startsWith("--work-tree=")) { - globalDirs.push(arg.slice("--work-tree=".length)); - i += 1; - continue; - } - if (GIT_GLOBAL_VALUE_FLAGS.has(arg)) { - i += 2; - continue; - } - if ( - arg.startsWith("-c") || - arg.startsWith("--namespace=") || - arg.startsWith("--config-env=") - ) { - i += 1; - continue; - } - if (arg.startsWith("-")) { - i += 1; - continue; - } - return { subcmd: arg, subArgs: args.slice(i + 1), globalDirs }; - } - return { subcmd: "", subArgs: [], globalDirs }; -} - -function isReadOnlyGitTagArgs(subArgs) { - if (subArgs.length === 0) return true; - let hasReadOnlyFlag = false; - for (let i = 0; i < subArgs.length; i += 1) { - const arg = subArgs[i]; - if (arg === "--") break; - if ( - ["-d", "--delete", "-a", "--annotate", "-s", "--sign", "-f", "--force", "-m", "--message", "-F", "--file", "-u", "--local-user", "--create-reflog"].includes( - arg, - ) || - arg.startsWith("--message=") || - arg.startsWith("--file=") || - arg.startsWith("--local-user=") || - (!arg.startsWith("--") && /^-[a-zA-Z]*[dasfmuF]/.test(arg)) - ) { - return false; - } - if ( - arg === "-l" || - arg === "--list" || - arg === "-v" || - arg === "--verify" || - arg === "--contains" || - arg.startsWith("--contains=") || - arg === "--points-at" || - arg.startsWith("--points-at=") - ) { - hasReadOnlyFlag = true; - if (arg === "--contains" || arg === "--points-at") { - i += 1; - } - } - } - return hasReadOnlyFlag; -} - -function isReadOnlyGitStashArgs(subArgs) { - return subArgs.length > 0 && (subArgs[0] === "list" || subArgs[0] === "show"); -} - -function isMutatingGitAction(subcmd, subArgs) { - if (MUTATING_GIT_SUBCOMMANDS.has(subcmd)) return true; - if (subcmd === "tag") return !isReadOnlyGitTagArgs(subArgs); - if (subcmd === "stash") return !isReadOnlyGitStashArgs(subArgs); - if (subcmd === "branch") { - return subArgs.some((a) => ["-d", "-D", "-m", "-M", "-c", "-C", "--delete", "--move", "--copy"].includes(a)); - } - if (subcmd === "worktree") { - const action = subArgs.find((a) => !a.startsWith("-")) || ""; - return Boolean(action && action !== "list"); - } - if (subcmd === "notes") { - const action = subArgs.find((a) => !a.startsWith("-")) || ""; - return Boolean(action && action !== "list" && action !== "show"); - } - if (subcmd === "replace") { - return subArgs.length > 0 && !subArgs.some((a) => a === "-l" || a === "--list"); - } - if (subcmd === "submodule") { - const action = subArgs.find((a) => !a.startsWith("-")) || ""; - return Boolean(action && action !== "status" && action !== "summary"); - } - if (subcmd === "symbolic-ref") { - if (subArgs.some((a) => a === "-d" || a === "--delete")) return true; - const positionals = extractPositionalPaths(subArgs); - return positionals.length >= 2; - } - return false; -} - -function isMutatingGitFetchForReadOnly(subArgs) { - const positionals = []; - let afterDoubleDash = false; - for (let i = 0; i < subArgs.length; i += 1) { - const arg = subArgs[i]; - if (!afterDoubleDash && arg === "--") { - afterDoubleDash = true; - continue; - } - if (!afterDoubleDash && arg.startsWith("-")) { - if ( - ["-p", "--prune", "-f", "--force", "-u", "--update-head-ok"].includes(arg) || - (!arg.startsWith("--") && /^-[a-zA-Z]*[pfu]/.test(arg)) - ) { - return true; - } - if (["--depth", "--deepen", "--shallow-since", "--shallow-exclude", "--negotiation-tip", "-o", "--server-option", "--upload-pack", "--refmap", "-j", "--jobs"].includes(arg)) { - i += 1; - } - continue; - } - positionals.push(arg); - } - return positionals.slice(1).some((refspec) => refspec.includes(":")); -} - -function isForcePushToProtectedBranch(subArgs) { - let hasForceOrDeleteFlag = false; - const positionals = []; - let afterDoubleDash = false; - - for (let i = 0; i < subArgs.length; i += 1) { - const arg = subArgs[i]; - if (!afterDoubleDash && arg === "--") { - afterDoubleDash = true; - continue; - } - if (!afterDoubleDash && arg.startsWith("-")) { - if ( - arg === "--force" || - arg.startsWith("--force=") || - arg === "--force-with-lease" || - arg.startsWith("--force-with-lease=") || - arg === "--force-if-includes" || - arg === "--delete" || - (!arg.startsWith("--") && /^-[a-zA-Z]*[fd]/.test(arg)) - ) { - hasForceOrDeleteFlag = true; - } - if (["-o", "--push-option", "--repo", "--receive-pack", "--exec"].includes(arg)) { - i += 1; - } - continue; - } - positionals.push(arg); - } - - const refspecs = positionals.length >= 2 ? positionals.slice(1) : positionals; - for (const spec of refspecs) { - const plusForced = spec.startsWith("+"); - const colonDelete = spec.startsWith(":"); - const clean = plusForced ? spec.slice(1) : spec; - const dst = clean.includes(":") ? clean.split(":").pop() : clean; - const branch = dst.replace(/^refs\/heads\//, ""); - if ((branch === "main" || branch === "master") && (hasForceOrDeleteFlag || plusForced || colonDelete)) { - return true; - } - } - return false; -} - -function extractPathsSkippingValueFlags(args, valueFlags) { - const paths = []; - let afterDoubleDash = false; - for (let i = 0; i < args.length; i += 1) { - const arg = args[i]; - if (!afterDoubleDash && arg === "--") { - afterDoubleDash = true; - continue; - } - if (!afterDoubleDash && arg.startsWith("-") && arg.length > 1) { - if (valueFlags.has(arg)) { - i += 1; - } - continue; - } - paths.push(arg); - } - return paths; -} - -function extractInstallTargets(args) { - let dirMode = false; - let targetDir = null; - const positionals = []; - let afterDoubleDash = false; - for (let i = 0; i < args.length; i += 1) { - const arg = args[i]; - if (!afterDoubleDash && arg === "--") { - afterDoubleDash = true; - continue; - } - if (!afterDoubleDash && arg.startsWith("-") && arg.length > 1) { - if (arg === "-d" || arg === "--directory" || (!arg.startsWith("--") && /^-[a-zA-Z]*d/.test(arg))) { - dirMode = true; - } - if (arg === "-t" || arg === "--target-directory") { - if (i + 1 >= args.length) return { valid: false, targets: [] }; - targetDir = args[i + 1]; - i += 1; - continue; - } - if (arg.startsWith("--target-directory=")) { - targetDir = arg.slice("--target-directory=".length); - continue; - } - if (["-m", "--mode", "-o", "--owner", "-g", "--group", "-S", "--suffix"].includes(arg)) { - i += 1; - } - continue; - } - positionals.push(arg); - } - if (dirMode) { - return positionals.length > 0 ? { valid: true, targets: positionals } : { valid: false, targets: [] }; - } - if (targetDir !== null) { - return positionals.length > 0 ? { valid: true, targets: [targetDir] } : { valid: false, targets: [] }; - } - if (positionals.length < 2) return { valid: false, targets: [] }; - return { valid: true, targets: [positionals[positionals.length - 1]] }; -} - -function extractCurlWriteTargets(args) { - const fileTargets = []; - let usesRemoteName = false; - let outputDir = "."; - for (let i = 0; i < args.length; i += 1) { - const arg = args[i]; - if (arg === "--") break; - if (arg === "-o" || arg === "--output") { - if (i + 1 < args.length) { - if (args[i + 1] !== "-") fileTargets.push(args[i + 1]); - i += 1; - } - continue; - } - if (arg.startsWith("--output=")) { - const v = arg.slice("--output=".length); - if (v !== "-") fileTargets.push(v); - continue; - } - if (arg.startsWith("-o") && arg.length > 2) { - const v = arg.slice(2); - if (v !== "-") fileTargets.push(v); - continue; - } - if (arg === "--output-dir" && i + 1 < args.length) { - outputDir = args[i + 1]; - i += 1; - continue; - } - if (arg.startsWith("--output-dir=")) { - outputDir = arg.slice("--output-dir=".length); - continue; - } - if (arg === "-O" || arg === "--remote-name" || arg === "--remote-name-all" || (!arg.startsWith("--") && /^-[a-zA-Z]*O/.test(arg))) { - usesRemoteName = true; - } - } - return { fileTargets, dirTargets: usesRemoteName ? [outputDir] : [] }; -} - -function extractWgetWriteTargets(args) { - let isSpider = false; - let outputDoc = null; - let dirPrefix = null; - for (let i = 0; i < args.length; i += 1) { - const arg = args[i]; - if (arg === "--") break; - if (arg === "--spider") { - isSpider = true; - continue; - } - if (arg === "-O" || arg === "--output-document") { - if (i + 1 < args.length) { - outputDoc = args[i + 1]; - i += 1; - } - continue; - } - if (arg.startsWith("--output-document=")) { - outputDoc = arg.slice("--output-document=".length); - continue; - } - if (arg.startsWith("-O") && arg.length > 2) { - outputDoc = arg.slice(2); - continue; - } - if (arg === "-P" || arg === "--directory-prefix") { - if (i + 1 < args.length) { - dirPrefix = args[i + 1]; - i += 1; - } - continue; - } - if (arg.startsWith("--directory-prefix=")) { - dirPrefix = arg.slice("--directory-prefix=".length); - continue; - } - if (arg.startsWith("-P") && arg.length > 2) { - dirPrefix = arg.slice(2); - continue; - } - } - if (isSpider) return { fileTargets: [], dirTargets: [] }; - if (outputDoc !== null) { - return outputDoc === "-" ? { fileTargets: [], dirTargets: [] } : { fileTargets: [outputDoc], dirTargets: [] }; - } - return { fileTargets: [], dirTargets: [dirPrefix || "."] }; -} - -function extractTarWriteTargets(args) { - let isExtract = false; - let isCreateOrUpdate = false; - let toStdout = false; - let targetDir = "."; - let archiveFile = null; - for (let i = 0; i < args.length; i += 1) { - const arg = args[i]; - if (arg === "--") break; - if (arg === "-O" || arg === "--to-stdout") toStdout = true; - if (arg === "-x" || arg === "--extract" || arg === "--get") isExtract = true; - if (arg === "-c" || arg === "--create" || arg === "-r" || arg === "--append" || arg === "-u" || arg === "--update") { - isCreateOrUpdate = true; - } - if (!arg.startsWith("--") && (arg.startsWith("-") || i === 0)) { - const flags = arg.startsWith("-") ? arg.slice(1) : arg; - if (flags.includes("x")) isExtract = true; - if (/[cru]/.test(flags)) isCreateOrUpdate = true; - if (flags.includes("O")) toStdout = true; - if (flags.endsWith("f") && i + 1 < args.length) { - archiveFile = args[i + 1]; - i += 1; - continue; - } - if (flags.endsWith("C") && i + 1 < args.length) { - targetDir = args[i + 1]; - i += 1; - continue; - } - } - if (arg === "-C" || arg === "--directory") { - if (i + 1 < args.length) { - targetDir = args[i + 1]; - i += 1; - } - continue; - } - if (arg.startsWith("--directory=")) { - targetDir = arg.slice("--directory=".length); - continue; - } - if (arg === "-f" || arg === "--file") { - if (i + 1 < args.length) { - archiveFile = args[i + 1]; - i += 1; - } - continue; - } - if (arg.startsWith("--file=")) { - archiveFile = arg.slice("--file=".length); - } - } - const fileTargets = []; - const dirTargets = []; - if (isExtract && !toStdout) dirTargets.push(targetDir); - if (isCreateOrUpdate && archiveFile && archiveFile !== "-" && archiveFile !== "/dev/null") { - fileTargets.push(archiveFile); - } - return { fileTargets, dirTargets }; -} - -function extractUnzipWriteTargets(args) { - let readOnly = false; - let targetDir = "."; - for (let i = 0; i < args.length; i += 1) { - const arg = args[i]; - if (arg === "--") break; - if (["-l", "-v", "-t", "-p", "-c", "-Z"].includes(arg) || (!arg.startsWith("--") && /^-[a-zA-Z]*[lvtpcZ]/.test(arg))) { - readOnly = true; - } - if (arg === "-d" && i + 1 < args.length) { - targetDir = args[i + 1]; - i += 1; - continue; - } - if (arg.startsWith("-d") && arg.length > 2) { - targetDir = arg.slice(2); - } - } - return readOnly ? [] : [targetDir]; -} - -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) { - const arg = args[i]; - if (!afterDoubleDash && arg === "--") { - afterDoubleDash = true; - continue; - } - if (!afterDoubleDash && arg.startsWith("-") && arg.length > 1) { - 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; - } - continue; - } - positionals.push(arg); - } - 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) { - const roots = []; - let i = 0; - while (i < args.length) { - const arg = args[i]; - if (arg === "-H" || arg === "-L" || arg === "-P" || arg === "-O" || arg === "-D") { - if (arg === "-D") i += 1; - i += 1; - continue; - } - if (arg.startsWith("-") || arg === "!" || arg === "(" || arg === ",") break; - roots.push(arg); - i += 1; - } - const searchRoots = roots.length > 0 ? roots : ["."]; - let hasDelete = false; - const fprintTargets = []; - const execCommands = []; - - for (; i < args.length; i += 1) { - const arg = args[i]; - if (arg === "-delete") { - hasDelete = true; - continue; - } - if (arg === "-fprint" || arg === "-fprint0" || arg === "-fls" || arg === "-fprintf") { - if (i + 1 < args.length) { - fprintTargets.push(args[i + 1]); - i += arg === "-fprintf" ? 2 : 1; - } - continue; - } - if (arg === "-exec" || arg === "-execdir" || arg === "-ok" || arg === "-okdir") { - const innerTokens = []; - let j = i + 1; - while (j < args.length && args[j] !== ";" && args[j] !== "+") { - innerTokens.push(args[j]); - j += 1; - } - if (innerTokens.length > 0) { - execCommands.push(innerTokens); - } - i = j; - } - } - return { searchRoots, hasDelete, fprintTargets, execCommands }; -} - -function checkSharedTargetConfinement(inv, allowPath, roleLabel, validateInnerTokens) { - 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, - allowArtifactDir: true, - requireArtifactDir: 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, 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, 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, forbidReadOnlyArtifact: true })) - ) { - return `Command 'truncate' outside allowed paths is blocked for ${roleLabel}.`; - } - return null; - } - if (cmd === "dd") { - const ofArg = args.find((a) => a.startsWith("of=")); - if (ofArg) { - const target = ofArg.slice(3); - if (!allowPath(target, { allowRootEqual: false, allowDevNull: true })) { - return `Command 'dd' output target outside allowed paths is blocked for ${roleLabel}.`; - } - } - return null; - } - if (cmd === "install") { - const spec = extractInstallTargets(args); - 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; - } - if (cmd === "curl") { - const { fileTargets, dirTargets } = extractCurlWriteTargets(args); - if ( - fileTargets.some((f) => !allowPath(f, { allowRootEqual: false, allowDevNull: true })) || - dirTargets.some((d) => !allowPath(d, { allowRootEqual: true, allowDevNull: false, forbidReadOnlyArtifact: true })) - ) { - return `Command 'curl' writing outside allowed paths is blocked for ${roleLabel}.`; - } - return null; - } - if (cmd === "wget") { - const { fileTargets, dirTargets } = extractWgetWriteTargets(args); - if ( - fileTargets.some((f) => !allowPath(f, { allowRootEqual: false, allowDevNull: true })) || - dirTargets.some((d) => !allowPath(d, { allowRootEqual: true, allowDevNull: false, forbidReadOnlyArtifact: true })) - ) { - return `Command 'wget' writing outside allowed paths is blocked for ${roleLabel}.`; - } - return null; - } - if (cmd === "tar") { - const { fileTargets, dirTargets } = extractTarWriteTargets(args); - if ( - 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}.`; - } - return null; - } - if (cmd === "unzip") { - const dirTargets = extractUnzipWriteTargets(args); - 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; - } - if (cmd === "rsync") { - const spec = extractRsyncWriteSpec(args); - if (!spec.dryRun && spec.destination) { - 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, - 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}.`; - } - } - return null; - } - if (cmd === "find") { - const { searchRoots, hasDelete, fprintTargets, execCommands } = extractFindEffects(args); - 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, forbidReadOnlyArtifact: true }))) { - return `Command 'find -fprint/-fls' outside allowed paths is blocked for ${roleLabel}.`; - } - for (const innerTokens of execCommands) { - const innerDeny = validateInnerTokens(innerTokens, searchRoots); - if (innerDeny) return innerDeny; - } - return null; - } - return undefined; -} - -function extractNodePreloadTargets(args, mergedEnv) { - const targets = []; - const scanArgs = (list) => { - for (let i = 0; i < list.length; i += 1) { - const arg = list[i]; - if (arg === "--") break; - if ( - (arg === "-r" || arg === "--require" || arg === "--import" || arg === "--loader" || arg === "--experimental-loader") && - i + 1 < list.length - ) { - targets.push(list[i + 1]); - i += 1; - continue; - } - for (const prefix of ["--require=", "--import=", "--loader=", "--experimental-loader="]) { - if (arg.startsWith(prefix)) { - targets.push(arg.slice(prefix.length)); - break; - } - } - } - }; - scanArgs(args); - if (typeof mergedEnv.NODE_OPTIONS === "string" && mergedEnv.NODE_OPTIONS.trim().length > 0) { - scanArgs(tokenizeSingleSegment(mergedEnv.NODE_OPTIONS)); - } - return targets; -} - -function findInterpreterScriptArg(cmd, args) { - const isNode = cmd === "node" || cmd === "nodejs" || cmd === "bun"; - const isPy = /^python(?:\d+(?:\.\d+)?)?$/.test(cmd); - const isShell = ["sh", "bash", "zsh", "dash", "ksh"].includes(cmd); - const isPerlRuby = cmd === "perl" || cmd === "ruby"; - if (!isNode && !isPy && !isShell && !isPerlRuby) return null; - - const valueFlags = isNode - ? new Set(["-e", "--eval", "-p", "--print", "-r", "--require", "--import", "--loader", "--experimental-loader", "--conditions", "-C"]) - : isPy - ? new Set(["-c", "-m", "-W", "-X", "-Q"]) - : isShell - ? new Set(["-c", "-o"]) - : new Set(["-e", "-E", "-I", "-M", "-m", "-C"]); - - let hasTestFlag = false; - for (let i = 0; i < args.length; i += 1) { - const arg = args[i]; - if (arg === "--") { - return i + 1 < args.length ? { scriptToken: args[i + 1], hasTestFlag } : null; - } - if (isNode && arg === "--test") { - hasTestFlag = true; - continue; - } - if (isNode && (arg === "-e" || arg === "--eval" || arg === "-p" || arg === "--print" || arg.startsWith("--eval=") || arg.startsWith("--print="))) { - return null; - } - if (isPy && (arg === "-c" || /^-[A-Za-z]+c$/.test(arg) || arg === "-m")) { - return null; - } - if (isShell && /^-[a-zA-Z]*c$/.test(arg)) { - return null; - } - if (isPerlRuby && (arg === "-e" || arg === "-E" || /^-[a-zA-Z.]*[eE]$/.test(arg))) { - return null; - } - if (arg.startsWith("-") && arg.length > 1) { - if (valueFlags.has(arg)) i += 1; - continue; - } - return { scriptToken: arg, hasTestFlag }; - } - return null; -} - -function inspectSingleTempFile(scriptToken, modeHint, context) { - const { - allowPath, - nodePyOptions, - canonicalTempRoots, - realCwd, - fallbackBaseDir, - mergedEnv, - outerEnv, - roleLabel, - kind, - validateShellCode, - } = context; - - const resolved = resolveShellTargetPath(scriptToken, fallbackBaseDir, mergedEnv); - if (!resolved) return null; - - const inTemp = isInsideCanonicalTempRoots(resolved, canonicalTempRoots, realCwd, { - allowRootEqual: false, - excludeRealCwd: false, - }); - if (!inTemp) return null; - - if (kind === "sicko") { - return `Executing temporary script '${scriptToken}' is blocked for comment-sicko workers.`; - } - - if (!existsSync(resolved)) { - return `Temporary script '${scriptToken}' must exist on disk before execution for ${roleLabel}.`; - } - - let rawBuf; - try { - if (!statSync(resolved).isFile()) { - return `Temporary script '${scriptToken}' is not a readable file for ${roleLabel}.`; - } - rawBuf = readFileSync(resolved); - } catch { - return `Temporary script '${scriptToken}' could not be read for ${roleLabel}.`; - } - - if (rawBuf.includes(0)) { - if (kind === "readonly" || kind === "sicko") { - return `Executing binary file '${scriptToken}' in canonical temp roots is blocked for ${roleLabel}.`; - } - return null; - } - - const code = rawBuf.toString("utf8"); - const ext = extname(resolved).toLowerCase(); - const firstLine = code.split(/\r?\n/, 1)[0] || ""; - const isNode = - modeHint === "node" || - [".js", ".mjs", ".cjs"].includes(ext) || - /#!\s*\/.*\bnode\b/.test(firstLine); - const isPy = - modeHint === "python" || - ext === ".py" || - /#!\s*\/.*\bpython/.test(firstLine); - const isPerlRuby = - modeHint === "perl" || - modeHint === "ruby" || - ext === ".pl" || - ext === ".rb" || - /#!\s*\/.*\b(?:perl|ruby)\b/.test(firstLine); - const isShell = - modeHint === "shell" || - [".sh", ".bash", ".zsh"].includes(ext) || - /#!\s*\/.*\b(?:sh|bash|zsh|dash|ksh)\b/.test(firstLine); - - if (isPerlRuby) { - if (kind === "readonly" || kind === "sicko") { - return `Executing temporary ${modeHint || "perl/ruby"} script '${scriptToken}' is blocked for ${roleLabel}.`; - } - return null; - } - if (isNode) { - return checkInlineNodeFs(code, allowPath, nodePyOptions); - } - if (isPy) { - return checkInlinePythonFs(code, allowPath, nodePyOptions); - } - if (isShell) { - return validateShellCode(code, mergedEnv, outerEnv); - } - return validateShellCode(code, mergedEnv, outerEnv); -} - -function inspectTempScriptFile(inv, context) { - const { canonicalTempRoots, realCwd, fallbackBaseDir, mergedEnv, roleLabel, kind } = context; - - if (inv.cmd === "node" || inv.cmd === "nodejs" || inv.cmd === "bun") { - for (const preloadTarget of extractNodePreloadTargets(inv.args, mergedEnv)) { - const preloadDeny = inspectSingleTempFile(preloadTarget, "node", context); - if (preloadDeny) return preloadDeny; - } - } - - if (/^python(?:\d+(?:\.\d+)?)?$/.test(inv.cmd)) { - const mIdx = inv.args.indexOf("-m"); - if (mIdx >= 0 && mIdx + 1 < inv.args.length && typeof mergedEnv.PYTHONPATH === "string") { - const modName = inv.args[mIdx + 1]; - const modRel = modName.replace(/\./g, "/"); - for (const pyRoot of mergedEnv.PYTHONPATH.split(/[:;]/).filter(Boolean)) { - const resolvedRoot = resolveShellTargetPath(pyRoot, fallbackBaseDir, mergedEnv); - if ( - resolvedRoot && - isInsideCanonicalTempRoots(resolvedRoot, canonicalTempRoots, realCwd, { - allowRootEqual: true, - excludeRealCwd: false, - }) - ) { - if (kind === "sicko") { - return `Executing Python module '${modName}' from PYTHONPATH in canonical temp roots is blocked for ${roleLabel}.`; - } - const modFile = join(resolvedRoot, `${modRel}.py`); - const modInit = join(resolvedRoot, modRel, "__init__.py"); - const candidate = existsSync(modFile) ? modFile : existsSync(modInit) ? modInit : null; - if (candidate) { - const modDeny = inspectSingleTempFile(candidate, "python", context); - if (modDeny) return modDeny; - } else if (kind === "readonly") { - return `Unresolvable Python module '${modName}' with PYTHONPATH in canonical temp roots is blocked for ${roleLabel}.`; - } - } - } - } - } - - if (inv.cmd === "source" || inv.cmd === ".") { - const sourced = inv.args[0]; - if (sourced) { - return inspectSingleTempFile(sourced, "shell", context); - } - return null; - } - - let scriptToken = null; - let modeHint = ""; - const interp = findInterpreterScriptArg(inv.cmd, inv.args); - if (interp) { - scriptToken = interp.scriptToken; - if (inv.cmd === "node" || inv.cmd === "nodejs" || inv.cmd === "bun") modeHint = "node"; - else if (/^python/.test(inv.cmd)) modeHint = "python"; - else if (inv.cmd === "perl" || inv.cmd === "ruby") modeHint = inv.cmd; - else modeHint = "shell"; - } else if (inv.rawCmd && (inv.rawCmd.includes("/") || inv.rawCmd.startsWith(".") || inv.rawCmd.startsWith("~"))) { - scriptToken = inv.rawCmd; - } - - if (!scriptToken) return null; - return inspectSingleTempFile(scriptToken, modeHint, context); -} - -function extractInlineCodeCheck(inv, allowPath, nodePyOptions) { - const { cmd, args } = inv; - if (cmd === "node" || cmd === "nodejs" || cmd === "bun") { - for (let i = 0; i < args.length; i += 1) { - const arg = args[i]; - if (arg === "--") break; - if ((arg === "-e" || arg === "--eval" || arg === "-p" || arg === "--print") && i + 1 < args.length) { - const deny = checkInlineNodeFs(args[i + 1], allowPath, nodePyOptions); - if (deny) return deny; - i += 1; - continue; - } - if (arg.startsWith("--eval=")) { - const deny = checkInlineNodeFs(arg.slice("--eval=".length), allowPath, nodePyOptions); - if (deny) return deny; - } else if (arg.startsWith("--print=")) { - const deny = checkInlineNodeFs(arg.slice("--print=".length), allowPath, nodePyOptions); - if (deny) return deny; - } - } - } - if (/^python(?:\d+(?:\.\d+)?)?$/.test(cmd)) { - for (let i = 0; i < args.length; i += 1) { - const arg = args[i]; - if (arg === "--" || arg === "-m") break; - if ((arg === "-c" || /^-[A-Za-z]+c$/.test(arg)) && i + 1 < args.length) { - const deny = checkInlinePythonFs(args[i + 1], allowPath, nodePyOptions); - if (deny) return deny; - break; - } - if (!arg.startsWith("-")) break; - } - } - return null; -} - -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; - - if (HARD_BLOCKED_RO_FS_COMMANDS.has(cmd)) { - return `Filesystem mutation command '${cmd}' is blocked for read-only ro-* workers.`; - } - - const sharedDeny = checkSharedTargetConfinement(inv, allowReadOnlyTempPath, "read-only ro-* workers", validateInnerTokens); - if (sharedDeny !== undefined) return sharedDeny; - - if (cmd === "rm" || cmd === "unlink") { - const paths = extractPositionalPaths(args); - if ( - paths.length === 0 || - paths.some((p) => !allowReadOnlyTempPath(p, { allowRootEqual: false, allowDevNull: false })) - ) { - 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 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( - (d) => - !allowReadOnlyTempPath(d, { - allowRootEqual: true, - allowDevNull: true, - allowArtifactDir: validArtifactImageCopy, - allowArtifactRoot: validArtifactImageCopy, - forbidReadOnlyArtifact: !validArtifactImageCopy, - }), - ) - ) { - 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 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 })) || - mvSpec.destinations.some( - (d) => - !allowReadOnlyTempPath(d, { - allowRootEqual: true, - allowDevNull: false, - allowArtifactDir: validArtifactImageMove, - allowArtifactRoot: validArtifactImageMove, - forbidReadOnlyArtifact: !validArtifactImageMove, - }), - ) - ) { - return "Filesystem command 'mv' outside canonical temp roots or allowed artifact screenshot paths is blocked for read-only ro-* workers."; - } - return null; - } - - 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, canonical temp roots, or allowed artifact screenshot paths is blocked for read-only ro-* workers."; - } - return null; - } - - if (cmd === "sed" && extractSedInPlaceTargets(args) !== null) { - return "In-place 'sed -i' is blocked for read-only ro-* workers."; - } - - if ((cmd === "perl" || cmd === "ruby") && extractPerlRubyInPlaceTargets(args) !== null) { - return `In-place '${cmd} -i' is blocked for read-only ro-* workers.`; - } - - const inlineDeny = extractInlineCodeCheck(inv, allowReadOnlyTempPath, { - allowDynamicPaths: false, - roleLabel: "read-only ro-* workers", - allowReadOnlyArtifactCopySource: checkReadOnlyCopySource, - registerReadOnlyMkdir, - }); - if (inlineDeny) return inlineDeny; - - if (cmd === "git") { - const { subcmd, subArgs } = parseGitCommand(args); - if (subcmd === "fetch" && isMutatingGitFetchForReadOnly(subArgs)) { - return "Mutating 'git fetch' with colon refspec or prune/force/update flags is blocked for read-only ro-* workers."; - } - if (isMutatingGitAction(subcmd, subArgs)) { - return `Mutating git command 'git ${subcmd}' is blocked for read-only ro-* workers.`; - } - } - - if (cmd === "npm" || cmd === "pnpm" || cmd === "bun") { - const sub = args.find((a) => !a.startsWith("-")) || ""; - if (NPM_INSTALL_SUBCOMMANDS.has(sub)) { - return `Package manager command '${cmd} ${sub}' is blocked for read-only ro-* workers.`; - } - } - - if (cmd === "yarn") { - const sub = args.find((a) => !a.startsWith("-")) || ""; - if (!sub || NPM_INSTALL_SUBCOMMANDS.has(sub) || sub === "upgrade") { - return `Package manager command 'yarn ${sub || "install"}' is blocked for read-only ro-* workers.`; - } - } - - if (cmd === "pip" || cmd === "pip3") { - const sub = args.find((a) => !a.startsWith("-")) || ""; - if (PIP_INSTALL_SUBCOMMANDS.has(sub)) { - return `Package install command '${cmd} ${sub}' is blocked for read-only ro-* workers.`; - } - } - - if (cmd === "uv") { - const nonFlags = args.filter((a) => !a.startsWith("-")); - if ( - ["add", "remove", "sync", "lock"].includes(nonFlags[0] || "") || - (nonFlags[0] === "pip" && PIP_INSTALL_SUBCOMMANDS.has(nonFlags[1] || "")) - ) { - return "Package mutation via 'uv' is blocked for read-only ro-* workers."; - } - } - - if ((cmd === "python" || cmd === "python3") && args[0] === "-m" && args[1] === "pip") { - const sub = args.slice(2).find((a) => !a.startsWith("-")) || ""; - if (PIP_INSTALL_SUBCOMMANDS.has(sub)) { - return "Package install via 'python -m pip' is blocked for read-only ro-* workers."; - } - } - - if (cmd === "cargo" || cmd === "go" || cmd === "brew" || cmd === "gem" || cmd === "poetry") { - const sub = args.find((a) => !a.startsWith("-")) || ""; - if (["install", "uninstall", "add", "remove", "upgrade", "update", "get"].includes(sub)) { - return `Package command '${cmd} ${sub}' is blocked for read-only ro-* workers.`; - } - } - - if (cmd === "apt" || cmd === "apt-get" || cmd === "apk") { - return `System package command '${cmd}' is blocked for read-only ro-* workers.`; - } - - return null; -} - -function checkAuthorShellConfinement(inv, allowAuthorShellPath, resolveForBase, validateInnerTokens) { - const { cmd, args } = inv; - if (!cmd) return null; - - const sharedDeny = checkSharedTargetConfinement( - inv, - allowAuthorShellPath, - "confined worker worktree, artifact directory, or canonical temp roots", - validateInnerTokens, - ); - if (sharedDeny !== undefined) return sharedDeny; - - if (cmd === "cp") { - const cpSpec = extractCpOrMvSpec(args); - if ( - !cpSpec.valid || - cpSpec.destinations.some((d) => !allowAuthorShellPath(d, { allowRootEqual: true, allowDevNull: true })) - ) { - return "Command 'cp' targeting a path outside confined worker worktree, artifact directory, or canonical temp roots is blocked."; - } - } - - if (cmd === "mv") { - const mvSpec = extractCpOrMvSpec(args); - if ( - !mvSpec.valid || - mvSpec.sources.some((s) => !allowAuthorShellPath(s, { allowRootEqual: false, allowDevNull: false })) || - mvSpec.destinations.some((d) => !allowAuthorShellPath(d, { allowRootEqual: true, allowDevNull: true })) - ) { - return "Command 'mv' targeting a path outside confined worker worktree, artifact directory, or canonical temp roots is blocked."; - } - } - - if (cmd === "ln") { - const lnSpec = extractLnSpec(args); - if ( - !lnSpec.valid || - 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."; - } - const resolvedLink = resolveForBase(lnSpec.linkPaths[0]); - 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, 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, - disallowArtifactRoot: true, - }) - ) { - return "Command 'ln -s' pointing outside confined worker worktree, artifact directory, or canonical temp roots is blocked."; - } - } - } - - 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, - isRecursiveDelete: hasRecursiveFlag, - }), - ) - ) { - return `Command '${cmd}' targeting a path outside confined worker worktree, artifact directory, or canonical temp roots is blocked.`; - } - } - - if (cmd === "patch") { - const patchSpec = extractPatchTargets(args); - if ( - !patchSpec.valid || - patchSpec.dirTargets.some((d) => !allowAuthorShellPath(d, { allowRootEqual: true, allowDevNull: false })) || - patchSpec.fileTargets.some((f) => !allowAuthorShellPath(f, { allowRootEqual: false, allowDevNull: true })) - ) { - return "Command 'patch' targeting a path outside confined worker worktree, artifact directory, or canonical temp roots is blocked."; - } - } - - if (cmd === "sed") { - const sedTargets = extractSedInPlaceTargets(args); - if ( - sedTargets !== null && - (sedTargets.length === 0 || - sedTargets.some((t) => !allowAuthorShellPath(t, { allowRootEqual: false, allowDevNull: false }))) - ) { - return "Command 'sed -i' targeting a path outside confined worker worktree, artifact directory, or canonical temp roots is blocked."; - } - } - - if (cmd === "perl" || cmd === "ruby") { - const editTargets = extractPerlRubyInPlaceTargets(args); - if ( - editTargets !== null && - (editTargets.length === 0 || - editTargets.some((t) => !allowAuthorShellPath(t, { allowRootEqual: false, allowDevNull: false }))) - ) { - return `Command '${cmd} -i' targeting a path outside confined worker worktree, artifact directory, or canonical temp roots is blocked.`; - } - } - - if (cmd === "tee") { - const files = extractPositionalPaths(args); - if (files.some((f) => !allowAuthorShellPath(f, { allowRootEqual: false, allowDevNull: true }))) { - return "Command 'tee' targeting a path outside confined worker worktree, artifact directory, /dev/null, or canonical temp roots is blocked."; - } - } - - const inlineDeny = extractInlineCodeCheck(inv, allowAuthorShellPath, { - allowDynamicPaths: true, - roleLabel: "author/adversary workers", - }); - if (inlineDeny) return inlineDeny; - - if (cmd === "git") { - const { subcmd, subArgs, globalDirs } = parseGitCommand(args); - if (isMutatingGitAction(subcmd, subArgs) && globalDirs.some((d) => !allowAuthorShellPath(d, { allowRootEqual: true, allowDevNull: false }))) { - return `Mutating git command 'git ${subcmd}' targeting a repository outside confined worktree or canonical temp roots is blocked.`; - } - } - - return null; + } + return sawC ? check(curBase) : true; } -function checkSickoShellInvocation(inv, allowSickoWritePath, resolveForBase, realCwd, validateInnerTokens) { - const { cmd, args } = inv; - if (!cmd) return null; - - if (SICKO_BLOCKED_FS_COMMANDS.has(cmd)) { - return `Filesystem mutation command '${cmd}' is blocked for comment-sicko workers; use edit_file on existing files only.`; +function isMutatingGhCommand(args) { + let idx = 0; + while (idx < args.length) { + const arg = args[idx]; + if (arg === "-R" || arg === "--repo" || arg === "--hostname") { + idx += 2; + } else if (arg.startsWith("-")) { + idx += 1; + } else { + break; + } } - - if (cmd === "curl" || cmd === "wget" || cmd === "tar" || cmd === "unzip" || cmd === "rsync" || cmd === "find") { - const sharedDeny = checkSharedTargetConfinement(inv, allowSickoWritePath, "comment-sicko workers", validateInnerTokens); - if (sharedDeny) return sharedDeny; + if (idx >= args.length) { + return false; } - - if (cmd === "tee") { - const files = extractPositionalPaths(args); - if (files.some((f) => f !== "/dev/null")) { - return "Command 'tee' writing to files is blocked for comment-sicko workers."; + const group = args[idx].toLowerCase(); + const rest = args.slice(idx + 1); + if (group in GH_MUTATING_ACTIONS) { + for (let i = 0; i < rest.length; i += 1) { + if (rest[i] === "-R" || rest[i] === "--repo") { + i += 1; + continue; + } + if (!rest[i].startsWith("-")) { + return GH_MUTATING_ACTIONS[group].has(rest[i].toLowerCase()); + } } + return false; } - - if (cmd === "sed" && extractSedInPlaceTargets(args) !== null) { - return "In-place 'sed -i' is blocked for comment-sicko workers; use edit_file only."; + if (group !== "api") { + return false; } - - if ((cmd === "perl" || cmd === "ruby") && extractPerlRubyInPlaceTargets(args) !== null) { - return `In-place '${cmd} -i' is blocked for comment-sicko workers; use edit_file only.`; + for (let i = 0; i < rest.length; i += 1) { + const arg = rest[i]; + if (arg === "-X" || arg === "--method") { + if (String(rest[i + 1] || "").toUpperCase() !== "GET") { + return true; + } + i += 1; + } else if (arg.startsWith("-X") && arg.length > 2 && arg.slice(2).toUpperCase() !== "GET") { + return true; + } else if (arg.startsWith("--method=") && arg.slice(9).toUpperCase() !== "GET") { + return true; + } else if ( + ["-f", "-F", "--raw-field", "--field", "--input"].includes(arg) || + ["-f", "-F", "--raw-field=", "--field=", "--input="].some((p) => arg.startsWith(p)) + ) { + return true; + } } + return false; +} - const inlineDeny = extractInlineCodeCheck(inv, allowSickoWritePath, { - allowDynamicPaths: false, - roleLabel: "comment-sicko workers", - }); - if (inlineDeny) return inlineDeny; - - if (cmd === "git") { - const { subcmd, subArgs, globalDirs } = parseGitCommand(args); - for (const dir of globalDirs) { - const resolved = resolveForBase(dir); - if (!resolved || !realCwd || !isInsideOrEqual(resolved, realCwd)) { - return "Git command targeting a directory outside the confined worktree is blocked for comment-sicko workers."; +function checkRunCommand(commandLine, session, roots, env) { + const { kind, memberName } = session; + const { realCwd, fallbackBaseDir, canonicalTempRoots } = roots; + for (const tokens of parseCommandSegments(commandLine)) { + const { cmd, args, inlineEnv } = unwrapCommandSegment(tokens); + if (cmd === "git") { + const { subcmd, subArgs, globalDirs } = parseGitCommand(args); + if (subcmd === "push") { + if (isForcePushToProtectedBranch(subArgs, globalDirs, realCwd || fallbackBaseDir)) { + return "Force-pushing to main or master is blocked across all swarm roles."; + } + if (kind === "readonly" || kind === "adversary" || kind === "sicko") { + return `Role '${kind}' (${memberName || kind}) is never permitted to run git push.`; + } + if (kind === "author" && inlineEnv.PSTACK_ALLOW_PUSH !== "1" && env.PSTACK_ALLOW_PUSH !== "1") { + return "Author workers cannot run git push without explicit PSTACK_ALLOW_PUSH=1 authorization."; + } } - } - if (subcmd !== "add" && subcmd !== "commit" && isMutatingGitAction(subcmd, subArgs)) { - return `Mutating or file-restoring git command 'git ${subcmd}' is blocked for comment-sicko workers.`; + if ( + kind === "readonly" && + !isEffectiveGitDirInsideTemp(globalDirs, fallbackBaseDir, canonicalTempRoots, realCwd) && + isMutatingGitActionForReadOnly(subcmd, subArgs) + ) { + return `Mutating git command 'git ${subcmd}' outside canonical temp roots is blocked for read-only workers.`; + } + if (kind === "sicko") { + let curBase = realCwd || fallbackBaseDir; + for (const entry of globalDirs) { + const resolved = resolveRealTargetPath(entry.dir, curBase); + if (!resolved || !realCwd || !isInsideOrEqual(resolved, realCwd)) { + return "Git command targeting a directory outside the confined worktree is blocked for comment-sicko workers."; + } + if (entry.flag === "-C") { + curBase = resolved; + } + } + if (SICKO_BLOCKED_GIT_SUBCOMMANDS.has(subcmd)) { + return `Git subcommand 'git ${subcmd}' is blocked for comment-sicko workers.`; + } + } + } else if (cmd === "gh" && (kind === "readonly" || kind === "adversary" || kind === "sicko") && isMutatingGhCommand(args)) { + return `Mutating gh command is blocked for '${kind}' workers.`; } } - return null; } -function extractMcpToolName(toolName, args) { - if (toolName === "call_mcp_tool") { - return String(args.ToolName || args.toolName || args.name || ""); - } - if (toolName.startsWith("mcp_")) { - return toolName.replace(/^mcp_[^_]+_/, ""); +function readGitStatusPorcelain(dir) { + try { + const stdout = execFileSync("git", ["-C", dir, "status", "--porcelain"], { + encoding: "utf8", + timeout: 2000, + stdio: ["ignore", "pipe", "ignore"], + }); + const lines = String(stdout || "") + .split("\n") + .map((line) => (line.endsWith("\r") ? line.slice(0, -1) : line)) + .filter(Boolean); + return { ok: true, lines }; + } catch { + return { ok: false, lines: [] }; } - return ""; } function handleSessionOrInvocation(payload, env) { if (isPluginDisabled(env)) { return {}; } - - const session = classifySession(payload, env, ""); - if (session.sessionKind === "unmanaged" || !session.capsule) { + const session = classifySession(payload, env); + if (session.sessionKind === "unmanaged") { return {}; } - - const convKey = payload.conversationId || "__unknown__"; - const injectedPath = join(session.cacheDir, "injected-capsules.json"); - const injectedMap = session.injectedMap || readJsonObject(injectedPath); - const priorCapsule = injectedMap[convKey]; - if (priorCapsule === session.capsule) { - return {}; + const convKey = typeof payload.conversationId === "string" && payload.conversationId ? payload.conversationId : "__unknown__"; + const nextState = { ...session.capsuleState }; + let stateDirty = false; + if ( + (session.kind === "readonly" || session.kind === "sicko") && + nextState.baselineGitStatus === undefined && + typeof payload.cwd === "string" && + payload.cwd && + existsSync(payload.cwd) + ) { + const gitStatus = readGitStatusPorcelain(realpathSync(payload.cwd)); + if (gitStatus.ok) { + nextState.baselineGitStatus = gitStatus.lines; + stateDirty = true; + } } - - const pluginRoot = resolvePluginRoot(env); - const capsuleAbsPath = join(pluginRoot, session.capsule); - if (!existsSync(capsuleAbsPath)) { + const capsuleAbsPath = session.capsule ? join(resolvePluginRoot(env), session.capsule) : ""; + if (!session.capsule || nextState.capsule === session.capsule || !existsSync(capsuleAbsPath)) { + if (stateDirty) { + writeJsonAtomically(capsuleStatePath(session.cacheDir, convKey), nextState); + } return {}; } - - const rawCapsuleText = readFileSync(capsuleAbsPath, "utf8"); - const isUpgrade = typeof priorCapsule === "string" && priorCapsule.length > 0; - const hasForkCapsule = - !isUpgrade && transcriptContainsRoleCapsule(resolveOwnTranscriptPath(payload, session.appDataDir)); - const capsuleText = isUpgrade || hasForkCapsule ? ROLE_OVERRIDE_NOTICE + rawCapsuleText : rawCapsuleText; - - updateJsonKey(injectedPath, convKey, session.capsule); - + const isUpgrade = typeof nextState.capsule === "string" && nextState.capsule.length > 0; + const hasForkCapsule = !isUpgrade && transcriptContainsRoleCapsule(resolveOwnTranscriptPath(payload, session.appDataDir)); + nextState.capsule = session.capsule; + delete nextState.plainSwarm; + writeJsonAtomically(capsuleStatePath(session.cacheDir, convKey), nextState); + const prefix = isUpgrade || hasForkCapsule ? ROLE_OVERRIDE_NOTICE : ""; return { - injectSteps: [ - { - systemMessage: { - systemMessage: capsuleText, - }, - }, - ], + injectSteps: [{ systemMessage: { systemMessage: prefix + readFileSync(capsuleAbsPath, "utf8") } }], }; } -function parseToolArgs(rawArgs) { - if (!rawArgs) return {}; - if (typeof rawArgs === "string") { - try { - const parsed = JSON.parse(rawArgs); - return parsed && typeof parsed === "object" ? parsed : {}; - } catch { - return {}; - } - } - return typeof rawArgs === "object" ? rawArgs : {}; -} - -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 = - rawArtifactDir.length > 0 - ? existsSync(rawArtifactDir) - ? realpathSync(rawArtifactDir) - : resolveRealTargetPath(rawArtifactDir, fallbackBaseDir) - : null; - const canonicalTempRoots = getCanonicalTempRoots(env); - 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; - 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 deny(reason) { + return { decision: "deny", reason }; } -function isAllowedReadOnlyArtifactPath( - resolvedPath, - realArtifact, - realCwd, - { 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; - - 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; -} +const ALLOW = { decision: "allow" }; function handlePreToolUse(payload, env) { if (isPluginDisabled(env)) { - return { decision: "allow" }; + return ALLOW; } - - const toolCall = payload.toolCall && typeof payload.toolCall === "object" ? payload.toolCall : {}; - const toolName = normalizeToolName(toolCall.name); - const args = parseToolArgs(toolCall.args); - - const session = classifySession(payload, env, toolName); + const tc = payload.toolCall && typeof payload.toolCall === "object" ? payload.toolCall : {}; + const rawName = typeof tc.name === "string" ? tc.name : String(tc.name || ""); + const toolName = rawName.startsWith("default_api:") ? rawName.slice(12) : rawName; + const args = (typeof tc.args === "string" ? parseJsonObjectSafe(tc.args) : tc.args) || {}; + const session = classifySession(payload, env); if (session.sessionKind === "unmanaged") { - return { decision: "allow" }; + return ALLOW; } if (LEGACY_SUBAGENT_TOOLS.has(toolName)) { - return { - decision: "deny", - reason: "Legacy subagent tools are disabled in Swarm-Centric Pstack v2. Use native swarm.", - }; + const subType = String(args.TypeName ?? args.SubagentName ?? args.typeName ?? args.subagentName ?? "").trim().toLowerCase(); + if (toolName === "invoke_subagent" && subType === "image-generator") { + return ALLOW; + } + return deny("Legacy subagent tools are disabled in Swarm-Centric Pstack v2. Use native swarm."); } const { kind, memberName } = session; - const { hasValidCwd, realCwd, fallbackBaseDir, realArtifact, canonicalTempRoots } = - resolveWorkerConfinementRoots(payload, env, session.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(); + let rawArt = ""; + if (typeof payload.artifactDirectoryPath === "string" && payload.artifactDirectoryPath) { + rawArt = payload.artifactDirectoryPath; + } else if (typeof session.appDataDir === "string" && session.appDataDir && isSafeConvId(payload.conversationId)) { + rawArt = join(session.appDataDir, "brain", payload.conversationId); + } + const realArtifact = rawArt + ? existsSync(rawArt) + ? realpathSync(rawArt) + : resolveRealTargetPath(rawArt, fallbackBaseDir) + : null; + const canonicalTempRoots = getCanonicalTempRoots(env); - if (kind === "readonly") { - if (toolName === "edit_file" || toolName === "write_file") { - const rawTarget = args.Path ?? args.path ?? args.TargetFile ?? args.targetFile ?? args.file_path ?? ""; - if (typeof rawTarget !== "string" || rawTarget.length === 0) { - return { - decision: "deny", - reason: `Read-only worker (${memberName || "ro-*"}) cannot call ${toolName} without a valid temp path.`, - }; + if (kind === "readonly" && (toolName === "call_mcp_tool" || toolName.startsWith("mcp_"))) { + let mcpName = ""; + if (toolName === "call_mcp_tool") { + mcpName = String(args.ToolName || args.toolName || args.name || ""); + } else { + const secondUnderscore = toolName.indexOf("_", 4); + mcpName = secondUnderscore > 4 ? toolName.slice(secondUnderscore + 1) : toolName.slice(4); + } + const segments = mcpName.toLowerCase().replaceAll("-", "_").split("_"); + if (!SWARM_BOARD_TOOLS.has(mcpName) && segments.some((seg) => MUTATING_MCP_VERBS.has(seg))) { + return deny(`Mutating MCP tool '${mcpName}' is blocked for read-only workers.`); + } + } + + if (toolName === "edit_file" || toolName === "write_file") { + const rawTarget = args.Path ?? args.path ?? args.TargetFile ?? args.targetFile ?? args.file_path ?? ""; + if (kind === "readonly") { + if (toolName === "edit_file") { + return deny(`Read-only worker (${memberName || "ro-*"}) cannot call edit_file.`); + } + if (typeof rawTarget !== "string" || !rawTarget) { + return deny(`Read-only worker (${memberName || "ro-*"}) cannot call write_file without a valid path.`); } 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}'.`, - }; + return deny(`Read-only worker (${memberName || "ro-*"}) cannot write protected or unresolvable path '${rawTarget}'.`); } if (realArtifact && isInsideOrEqual(realTarget, realArtifact)) { - if (toolName === "write_file" && isAllowedReadOnlyArtifactPath(realTarget, realArtifact, realCwd)) { - return { decision: "allow" }; + if (isAllowedReadOnlyArtifactImage(realTarget, realArtifact, realCwd)) { + return 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.`, - }; + return deny(`Read-only worker (${memberName || "ro-*"}) can only write screenshot images (.png, .jpg, .jpeg, .webp) inside its artifact directory.`); } - if ( - !isInsideCanonicalTempRoots(realTarget, canonicalTempRoots, realCwd, { - allowRootEqual: false, - excludeRealCwd: true, - }) - ) { - return { - decision: "deny", - reason: `Read-only worker (${memberName || "ro-*"}) can only call ${toolName} inside canonical temp roots.`, - }; + if (isInsideCanonicalTempRoots(realTarget, canonicalTempRoots, realCwd, { excludeRealCwd: true })) { + return ALLOW; } - return { decision: "allow" }; + return deny(`Read-only worker (${memberName || "ro-*"}) can only call write_file inside canonical temp roots.`); } - - if (toolName === "run_command") { - const commandLine = String(args.CommandLine ?? args.command ?? args.commandLine ?? ""); - - 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, 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 (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, { - allowRootEqual, - excludeRealCwd: true, - }); - }; - - 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 })) { - return "Output file redirection outside /dev/null, canonical temp roots, or allowed artifact screenshot paths is blocked for read-only ro-* workers."; - } - } - - 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; - const innerAllow = (rawToken, opts = {}) => { - if (rawToken === "{}" || rawToken.includes("{}")) { - return searchRoots.every((r) => allowInvTempPath(r, { allowRootEqual: true, allowDevNull: false })); - } - return allowInvTempPath(rawToken, opts); - }; - 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, - 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", - allowReadOnlyArtifactCopySource: checkReadOnlyCopySource, - registerReadOnlyMkdir, - }, - canonicalTempRoots, - realCwd, - fallbackBaseDir, - mergedEnv, - outerEnv, - roleLabel: "read-only ro-* workers", - kind, - validateShellCode: (scriptCode, scriptEnv, baseOuterEnv) => - validateReadOnlyShell(scriptCode, scriptEnv, baseOuterEnv, depth + 1), - }); - if (scriptDeny) return scriptDeny; - } - return null; - }; - - const roDeny = validateReadOnlyShell(commandLine, {}, env, 0); - if (roDeny) { - return { decision: "deny", reason: roDeny }; - } + if (kind === "sicko" && toolName === "write_file") { + return deny(`Comment-sicko worker (${memberName || "sicko-*"}) cannot call write_file; use edit_file on existing files only.`); } - - if (toolName === "call_mcp_tool" || toolName.startsWith("mcp_")) { - const mcpToolName = extractMcpToolName(toolName, args); - if (!SWARM_BOARD_TOOLS.has(mcpToolName)) { - const normalized = mcpToolName.replace(/-/g, "_"); - if (MUTATING_MCP_PATTERN.test(normalized)) { - return { - decision: "deny", - reason: `Mutating MCP tool '${mcpToolName}' is blocked for read-only ro-* workers.`, - }; - } + if (kind === "author" || kind === "adversary" || kind === "sicko") { + if (typeof rawTarget !== "string" || !rawTarget) { + return deny("Missing target file path."); + } + if (!hasValidCwd || !realCwd) { + return deny("Missing or non-existent worker cwd for path confinement."); + } + const realTarget = resolveRealTargetPath(rawTarget, realCwd); + if (!realTarget) { + return deny("Target file path failed symlink resolution."); + } + if (isSystemGeneratedArtifactPath(realTarget, realArtifact)) { + return deny(`Path '${rawTarget}' inside protected '.system_generated' artifact metadata is blocked.`); + } + const insideCwd = isStrictlyInside(realTarget, realCwd); + const insideArtifact = kind !== "sicko" && realArtifact ? isStrictlyInside(realTarget, realArtifact) : false; + const insideTemp = kind !== "sicko" && isInsideCanonicalTempRoots(realTarget, canonicalTempRoots, realCwd); + if (!insideCwd && !insideArtifact && !insideTemp) { + return deny(`Path '${rawTarget}' escapes confined worker worktree '${realCwd}'.`); } - } - } - - if (kind === "sicko" && toolName === "write_file") { - return { - decision: "deny", - reason: `Comment-sicko worker (${memberName || "sicko-*"}) cannot call write_file; use edit_file on existing files only.`, - }; - } - - if ( - (kind === "author" || kind === "adversary" || kind === "sicko") && - (toolName === "edit_file" || toolName === "write_file") - ) { - const rawTarget = args.Path ?? args.path ?? args.TargetFile ?? args.targetFile ?? args.file_path ?? ""; - if (typeof rawTarget !== "string" || rawTarget.length === 0) { - return { decision: "deny", reason: "Missing target file path." }; - } - if (!hasValidCwd || !realCwd) { - return { decision: "deny", reason: "Missing or non-existent worker cwd for path confinement." }; - } - - const realTarget = resolveRealTargetPath(rawTarget, realCwd); - if (!realTarget) { - 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 = - kind === "author" || kind === "adversary" - ? isInsideCanonicalTempRoots(realTarget, canonicalTempRoots, realCwd, { - allowRootEqual: false, - excludeRealCwd: false, - }) - : false; - - if (!insideCwd && !insideArtifact && !insideTemp) { - return { - decision: "deny", - reason: `Path '${rawTarget}' escapes confined worker worktree '${realCwd}'.`, - }; } } if (toolName === "run_command") { const commandLine = String(args.CommandLine ?? args.command ?? args.commandLine ?? ""); - const { invocations, redirectTargets } = collectInvocations(commandLine, 0, {}, env); - - if (kind === "sicko") { - for (const redirectTarget of redirectTargets) { - if (redirectTarget.target !== "/dev/null") { - return { - decision: "deny", - reason: - "Shell file redirection outside /dev/null is blocked for comment-sicko workers; use edit_file on existing files only.", - }; - } - } - const allowSickoWritePath = (_rawToken, opts = {}) => { - if (opts.allowDevNull && _rawToken === "/dev/null") return true; - return false; - }; - for (const inv of invocations) { - const mergedEnv = { ...env, ...inv.env }; - const resolveForBase = (rawToken) => - resolveShellTargetPath(rawToken, realCwd || fallbackBaseDir, mergedEnv); - const validateInnerTokens = (innerTokens) => { - const innerInv = unwrapCommandSegment(innerTokens, inv.env, env); - if (!innerInv.cmd) return null; - return checkSickoShellInvocation(innerInv, allowSickoWritePath, resolveForBase, realCwd, validateInnerTokens); - }; - const sickoDeny = checkSickoShellInvocation(inv, allowSickoWritePath, resolveForBase, realCwd, validateInnerTokens); - if (sickoDeny) { - return { decision: "deny", reason: sickoDeny }; - } - const scriptDeny = inspectTempScriptFile(inv, { - allowPath: allowSickoWritePath, - nodePyOptions: { allowDynamicPaths: false, roleLabel: "comment-sicko workers" }, - canonicalTempRoots, - realCwd, - fallbackBaseDir, - mergedEnv, - outerEnv: env, - roleLabel: "comment-sicko workers", - kind, - validateShellCode: () => "Executing temporary shell script is blocked for comment-sicko workers.", - }); - if (scriptDeny) { - return { decision: "deny", reason: scriptDeny }; - } - } + const reason = checkRunCommand(commandLine, session, { realCwd, fallbackBaseDir, canonicalTempRoots }, env); + if (reason) { + return deny(reason); } + } + return ALLOW; +} - if (kind === "author" || kind === "adversary") { - const checkConfinedShellPath = (rawToken, mergedEnv, opts = {}) => { - const { - allowRootEqual = false, - allowDevNull = false, - customBaseDir = null, - isRecursiveDelete = false, - disallowArtifactRoot = false, - } = opts; - const activeBase = customBaseDir || realCwd; - if (!activeBase && !isAbsolute(rawToken) && !rawToken.startsWith("~") && !rawToken.startsWith("$")) { - return false; - } - const resolved = resolveShellTargetPath(rawToken, activeBase || fallbackBaseDir, mergedEnv); - if (!resolved) return false; - if (allowDevNull && resolved === "/dev/null") return true; - if (isSystemGeneratedArtifactPath(resolved, realArtifact)) return false; - if ( - isRecursiveDelete && - 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 && !disallowArtifactRoot ? true : isStrictlyInside(resolved, realArtifact); - } - return isInsideCanonicalTempRoots(resolved, canonicalTempRoots, realCwd, { - allowRootEqual, - excludeRealCwd: false, - }); - }; - - const validateAuthorShell = (code, inheritedEnv = {}, outerEnv = env, depth = 0) => { - if (depth > 4) return "Nested shell script depth limit exceeded."; - const shellData = depth === 0 ? { invocations, redirectTargets } : collectInvocations(code, 0, inheritedEnv, outerEnv); - - for (const redirectTarget of shellData.redirectTargets) { - const mergedEnv = { ...outerEnv, ...redirectTarget.env }; - if (!checkConfinedShellPath(redirectTarget.target, mergedEnv, { allowRootEqual: false, allowDevNull: true })) { - return "Shell output redirection outside confined worker worktree, artifact directory, /dev/null, or canonical temp roots is blocked."; - } - } - - for (const inv of shellData.invocations) { - const mergedEnv = { ...outerEnv, ...inv.env }; - const allowInvPath = (rawToken, opts = {}) => checkConfinedShellPath(rawToken, mergedEnv, opts); - const resolveForBase = (rawToken) => - resolveShellTargetPath(rawToken, realCwd || fallbackBaseDir, mergedEnv); - const validateInnerTokens = (innerTokens, searchRoots) => { - const innerInv = unwrapCommandSegment(innerTokens, inv.env, outerEnv); - if (!innerInv.cmd) return null; - const innerAllow = (rawToken, opts = {}) => { - if (rawToken === "{}" || rawToken.includes("{}")) { - return searchRoots.every((r) => allowInvPath(r, { allowRootEqual: true, allowDevNull: false })); - } - return allowInvPath(rawToken, opts); - }; - return checkAuthorShellConfinement(innerInv, innerAllow, resolveForBase, validateInnerTokens); - }; - const authorDeny = checkAuthorShellConfinement(inv, allowInvPath, resolveForBase, validateInnerTokens); - if (authorDeny) return authorDeny; - - const scriptDeny = inspectTempScriptFile(inv, { - allowPath: allowInvPath, - nodePyOptions: { allowDynamicPaths: true, roleLabel: "author/adversary workers" }, - canonicalTempRoots, - realCwd, - fallbackBaseDir, - mergedEnv, - outerEnv, - roleLabel: "author/adversary workers", - kind, - validateShellCode: (scriptCode, scriptEnv, baseOuterEnv) => - validateAuthorShell(scriptCode, scriptEnv, baseOuterEnv, depth + 1), - }); - if (scriptDeny) return scriptDeny; - } - return null; - }; - - const authorDeny = validateAuthorShell(commandLine, {}, env, 0); - if (authorDeny) { - return { decision: "deny", reason: authorDeny }; - } +function handleStop(payload, env) { + if (isPluginDisabled(env) || payload.continuationActive) { + return {}; + } + if (payload.terminationReason && payload.terminationReason !== "NO_TOOL_CALL") { + return {}; + } + const session = classifySession(payload, env); + if (session.sessionKind === "unmanaged" || (session.kind !== "readonly" && session.kind !== "sicko")) { + return {}; + } + if (typeof payload.cwd !== "string" || !payload.cwd || !existsSync(payload.cwd)) { + return {}; + } + const realCwd = realpathSync(payload.cwd); + if (session.kind === "readonly" && isInsideCanonicalTempRoots(realCwd, getCanonicalTempRoots(env), realCwd, { allowRootEqual: true })) { + return {}; + } + const gitStatus = readGitStatusPorcelain(realCwd); + if (!gitStatus.ok) { + return {}; + } + const baseline = new Set(Array.isArray(session.capsuleState?.baselineGitStatus) ? session.capsuleState.baselineGitStatus : []); + const unexpected = gitStatus.lines.filter((line) => { + if (baseline.has(line)) { + return false; } - - for (const inv of invocations) { - if (inv.cmd !== "git") continue; - const { subcmd, subArgs } = parseGitCommand(inv.args); - if (subcmd !== "push") continue; - - if (isForcePushToProtectedBranch(subArgs)) { - return { - decision: "deny", - reason: "Force-pushing to main or master is blocked across all swarm roles.", - }; - } - - if (kind === "adversary" || kind === "sicko") { - return { - decision: "deny", - reason: `Role '${kind}' (${memberName}) is never permitted to run git push.`, - }; - } - - if (kind === "author") { - const allowPush = - inv.env.PSTACK_ALLOW_PUSH === "1" || - env.PSTACK_ALLOW_PUSH === "1"; - if (!allowPush) { - return { - decision: "deny", - reason: - "Author workers cannot run git push without explicit PSTACK_ALLOW_PUSH=1 authorization.", - }; - } - } + if (session.kind === "readonly") { + return true; } + return line.startsWith("?? ") || (line.length >= 2 && (line[0] === "D" || line[1] === "D")); + }); + if (unexpected.length === 0) { + return {}; } - - return { decision: "allow" }; + const paths = unexpected.map((l) => (l.length > 3 ? l.slice(3) : l)).join(", "); + return { + decision: "continue", + reason: + session.kind === "readonly" + ? `Read-only worker left unexpected git changes or untracked files: ${paths}. Clean them up before stopping.` + : `Comment-sicko worker left unexpected untracked or deleted git entries: ${paths}. Clean them up before stopping.`, + }; } -function main() { - let rawInput = ""; - try { - rawInput = readFileSync(0, "utf8"); - } catch { - rawInput = ""; +export function runGuard(payload, env = process.env) { + const safePayload = payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {}; + const eventName = String(safePayload.hookEventName || ""); + if (eventName === "SessionStart" || eventName === "PreInvocation") { + return handleSessionOrInvocation(safePayload, env); } + if (eventName === "Stop") { + return handleStop(safePayload, env); + } + if (eventName === "PreToolUse" || safePayload.toolCall) { + return handlePreToolUse(safePayload, env); + } + return {}; +} - if ( - typeof process.env.PSTACK_PLUGIN_ROOT === "string" && - process.env.PSTACK_PLUGIN_ROOT.length > 0 && - process.env.PSTACK_GUARD_DELEGATED !== "1" - ) { - const targetGuard = join(process.env.PSTACK_PLUGIN_ROOT, "hooks", "guard.mjs"); +export async function handleRawStdin(rawInput, env = process.env) { + if (typeof env.PSTACK_PLUGIN_ROOT === "string" && env.PSTACK_PLUGIN_ROOT && env.PSTACK_GUARD_DELEGATED !== "1") { + const targetGuard = join(env.PSTACK_PLUGIN_ROOT, "hooks", "guard.mjs"); if (existsSync(targetGuard)) { let selfReal = null; let targetReal = null; @@ -7068,39 +1801,31 @@ function main() { targetReal = realpathSync(targetGuard); } catch {} if (selfReal && targetReal && selfReal !== targetReal) { - const delegatedOut = execFileSync(process.execPath, [targetReal], { - input: rawInput, - env: { ...process.env, PSTACK_GUARD_DELEGATED: "1" }, - encoding: "utf8", - }); - process.stdout.write(delegatedOut); - return; - } - } - } - - let payload = {}; - if (rawInput.trim().length > 0) { - try { - const parsed = JSON.parse(rawInput); - if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) { - payload = parsed; + const delegatedEnv = { ...env, PSTACK_GUARD_DELEGATED: "1" }; + const mod = await import(pathToFileURL(targetReal).href); + if (typeof mod.handleRawStdin === "function") { + return await mod.handleRawStdin(rawInput, delegatedEnv); + } + if (typeof mod.runGuard === "function") { + return `${JSON.stringify(await mod.runGuard(parseJsonObjectSafe(rawInput) || {}, delegatedEnv))}\n`; + } } - } catch { - payload = {}; } } - - const eventName = String(payload.hookEventName || ""); - let output = {}; - - if (eventName === "SessionStart" || eventName === "PreInvocation") { - output = handleSessionOrInvocation(payload, process.env); - } else if (eventName === "PreToolUse" || payload.toolCall) { - output = handlePreToolUse(payload, process.env); - } - - process.stdout.write(JSON.stringify(output) + "\n"); + return `${JSON.stringify(runGuard(parseJsonObjectSafe(rawInput) || {}, env))}\n`; } -main(); +let isMain = false; +try { + isMain = Boolean( + process.argv[1] && + realpathSync(resolve(process.argv[1])) === realpathSync(fileURLToPath(import.meta.url)), + ); +} catch {} +if (isMain) { + let rawInput = ""; + try { + rawInput = readFileSync(0, "utf8"); + } catch {} + process.stdout.write(await handleRawStdin(rawInput, process.env)); +} diff --git a/hooks/guard.test.mjs b/hooks/guard.test.mjs index 2bef170..2da2a7c 100644 --- a/hooks/guard.test.mjs +++ b/hooks/guard.test.mjs @@ -1,22 +1,14 @@ import assert from "node:assert/strict"; -import { spawnSync } from "node:child_process"; +import { spawn, spawnSync } from "node:child_process"; import { - chmodSync, - copyFileSync, - existsSync, - mkdirSync, - mkdtempSync, - readFileSync, - realpathSync, - rmSync, - statSync, - symlinkSync, - writeFileSync, + chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, + rmSync, statSync, symlinkSync, writeFileSync, } from "node:fs"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { describe, test } from "node:test"; import { fileURLToPath } from "node:url"; +import { handleRawStdin, runGuard } from "./guard.mjs"; const PLUGIN_ROOT = dirname(dirname(fileURLToPath(import.meta.url))); const GUARD_PATH = join(PLUGIN_ROOT, "hooks", "guard.mjs"); @@ -34,7 +26,6 @@ function makeSandbox() { mkdirSync(siblingWorktree, { recursive: true }); mkdirSync(outsideDir, { recursive: true }); mkdirSync(customTmpDir, { recursive: true }); - return { root, appDataDir, @@ -51,3536 +42,892 @@ function makeSandbox() { function writeSwarmMembers(appDataDir, coordId, members) { const swarmDir = join(appDataDir, "brain", coordId, ".system_generated", "swarm"); mkdirSync(swarmDir, { recursive: true }); - writeFileSync( - join(swarmDir, "members.json"), - JSON.stringify({ title: "test-swarm", members }, null, 2), - "utf8", - ); -} - -function writeTranscriptLines(transcriptPath, steps) { - mkdirSync(dirname(transcriptPath), { recursive: true }); - const text = steps - .map((s) => (typeof s === "string" ? s : JSON.stringify(s))) - .join("\n") + "\n"; - writeFileSync(transcriptPath, text, "utf8"); + writeFileSync(join(swarmDir, "members.json"), JSON.stringify({ title: "test-swarm", members }, null, 2), "utf8"); } -function runGuard(payload, envOverrides = {}, guardScriptPath = GUARD_PATH) { +function buildEnv(envOverrides = {}) { const env = { ...process.env }; - delete env.PSTACK_APPDATA_DIR; - delete env.ANTIGRAVITY_APP_DATA_DIR; - delete env.PLUGIN_DATA; - 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) - ) { + for (const k of [ + "PSTACK_APPDATA_DIR", "ANTIGRAVITY_APP_DATA_DIR", "PLUGIN_DATA", "PLUGIN_ROOT", + "PSTACK_PLUGIN_ROOT", "PSTACK_CACHE_DIR", "PSTACK_CONFIG_DIR", + "PSTACK_REMOTE_SWARM_CLI", "PSTACK_REMOTE_BOARD_CONFIG", + "PSTACK_GUARD_DELEGATED", "PSTACK_ALLOW_PUSH", "PSTACK_FORCE_COORDINATOR", + ]) { + delete env[k]; + } + if (!("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; } + return env; +} + +function invokeGuard(payload, envOverrides = {}) { + return runGuard(payload, buildEnv(envOverrides)); +} +function runGuardCli(payload, envOverrides = {}, guardScriptPath = GUARD_PATH) { const res = spawnSync(process.execPath, [guardScriptPath], { input: JSON.stringify(payload), encoding: "utf8", - env, + env: buildEnv(envOverrides), }); - assert.equal(res.status, 0, `guard exited non-zero: ${res.stderr}`); return JSON.parse(res.stdout); } -describe("hooks.json, guard.mjs packaging, and role capsule prose", () => { - test("places hooks.json at plugin root with run_workflow matcher and executable script", () => { - assert.equal(existsSync(HOOKS_JSON_PATH), true); - assert.equal(existsSync(join(PLUGIN_ROOT, "hooks", "hooks.json")), false); +function scanJsForRegexAndSandbox(source) { + const regexLiterals = []; + const regExpRefs = []; + const EXPR_END_KEYWORDS = new Set(["this", "super", "true", "false", "null"]); + const NON_EXPR_KEYWORDS = new Set([ + "return", "throw", "case", "delete", "void", "typeof", "yield", "await", + "in", "instanceof", "of", "new", "else", "do", + ]); + let prevCanEndExpr = false; + let i = 0; + + while (i < source.length) { + const ch = source[i]; + if (ch === " " || ch === "\t" || ch === "\n" || ch === "\r") { i += 1; continue; } + if (ch === "#" && i === 0 && source[1] === "!") { + while (i < source.length && source[i] !== "\n") i += 1; + continue; + } + if (ch === "/" && source[i + 1] === "/") { + while (i < source.length && source[i] !== "\n") i += 1; + continue; + } + if (ch === "/" && source[i + 1] === "*") { + i += 2; + while (i < source.length && !(source[i] === "*" && source[i + 1] === "/")) i += 1; + i += 2; + continue; + } + if (ch === "'" || ch === '"' || ch === "`") { + const quote = ch; + i += 1; + while (i < source.length) { + if (source[i] === "\\") { i += 2; continue; } + if (quote === "`" && source[i] === "$" && source[i + 1] === "{") { + i += 2; + let depth = 1; + while (i < source.length && depth > 0) { + if (source[i] === "{") depth += 1; + else if (source[i] === "}") depth -= 1; + i += 1; + } + continue; + } + if (source[i] === quote) { i += 1; break; } + i += 1; + } + prevCanEndExpr = true; + continue; + } + if (ch === "/") { + if (!prevCanEndExpr) { + const start = i; + i += 1; + let inClass = false; + while (i < source.length) { + if (source[i] === "\\") { i += 2; continue; } + if (source[i] === "[") inClass = true; + else if (source[i] === "]") inClass = false; + else if (source[i] === "/" && !inClass) { i += 1; break; } + i += 1; + } + regexLiterals.push(source.slice(start, i)); + prevCanEndExpr = true; + continue; + } + i += 1; + prevCanEndExpr = false; + continue; + } + if ((ch >= "a" && ch <= "z") || (ch >= "A" && ch <= "Z") || ch === "_" || ch === "$") { + const start = i; + while (i < source.length && (/[A-Za-z0-9_$]/.test(source[i]))) i += 1; + const ident = source.slice(start, i); + if (ident === "RegExp") regExpRefs.push(start); + prevCanEndExpr = EXPR_END_KEYWORDS.has(ident) || !NON_EXPR_KEYWORDS.has(ident); + continue; + } + if (ch >= "0" && ch <= "9") { + while (i < source.length && /[0-9a-fA-FxXoObBn._]/.test(source[i])) i += 1; + prevCanEndExpr = true; + continue; + } + if (ch === ")" || ch === "]") { i += 1; prevCanEndExpr = true; continue; } + if ((ch === "+" && source[i + 1] === "+") || (ch === "-" && source[i + 1] === "-")) { + i += 2; + prevCanEndExpr = true; + continue; + } + i += 1; + prevCanEndExpr = false; + } - const hooksConfig = JSON.parse(readFileSync(HOOKS_JSON_PATH, "utf8")); - const guardSpec = hooksConfig["pstack-swarm-guard"]; - assert.ok(guardSpec); - assert.deepEqual(guardSpec.SessionStart, [ - { type: "command", command: "./hooks/guard.mjs", timeout: 10 }, - ]); - assert.deepEqual(guardSpec.PreInvocation, [ - { type: "command", command: "./hooks/guard.mjs", timeout: 10 }, - ]); - assert.equal(guardSpec.PreToolUse.length, 2); - assert.equal( - guardSpec.PreToolUse[0].matcher, - "(invoke|define)_subagent|manage_subagents|send_message|run_workflow", - ); - assert.equal( - guardSpec.PreToolUse[1].matcher, - "(edit|write)_file|run_command|call_mcp_tool|mcp_.*", - ); + return { + regexLiterals, + regExpRefs, + hasSandboxExec: source.includes("sandbox-exec"), + hasBwrap: source.includes("bwrap"), + hasUnshare: source.includes("unshare"), + }; +} + +describe("Static zero-regex, zero-sandbox, packaging, and capsule prose checks", () => { + test("hooks/guard.mjs contains 0 regex literals, 0 RegExp references, and 0 OS sandbox calls", () => { + const guardSource = readFileSync(GUARD_PATH, "utf8"); + const scan = scanJsForRegexAndSandbox(guardSource); + assert.deepEqual(scan.regexLiterals, [], "guard.mjs must contain zero regex literals"); + assert.deepEqual(scan.regExpRefs, [], "guard.mjs must contain zero RegExp references"); + assert.equal(scan.hasSandboxExec, false); + assert.equal(scan.hasBwrap, false); + assert.equal(scan.hasUnshare, false); + + const probe = scanJsForRegexAndSandbox("const x = a / b; const y = /abc/i; const z = new RegExp('a');"); + assert.equal(probe.regexLiterals.length, 1); + assert.equal(probe.regExpRefs.length, 1); + }); - const mode = statSync(GUARD_PATH).mode; - assert.notEqual(mode & 0o111, 0, "hooks/guard.mjs must have +x permission"); + test("hooks.json includes SessionStart, PreInvocation, PreToolUse, and Stop handlers and guard.mjs is executable", () => { + assert.equal(existsSync(HOOKS_JSON_PATH), true); + const hooksConfig = JSON.parse(readFileSync(HOOKS_JSON_PATH, "utf8")); + const spec = hooksConfig["pstack-swarm-guard"]; + assert.ok(spec); + assert.deepEqual(spec.SessionStart, [{ type: "command", command: "./hooks/guard.mjs", timeout: 10 }]); + assert.deepEqual(spec.PreInvocation, [{ type: "command", command: "./hooks/guard.mjs", timeout: 10 }]); + assert.deepEqual(spec.Stop, [{ type: "command", command: "./hooks/guard.mjs", timeout: 10 }]); + assert.equal(spec.PreToolUse.length, 2); + assert.notEqual(statSync(GUARD_PATH).mode & 0o111, 0, "hooks/guard.mjs must have +x permission"); }); - test("keeps all role capsules free of em-dashes, en-dashes, and mid-sentence colons with required guidance", () => { - const roleFiles = [ - "coordinator.md", - "research.md", - "poteto-agent.md", - "comment-sicko.md", - ]; - for (const name of roleFiles) { + test("all role capsules and Role override notice are free of em-dashes, en-dashes, and colons", () => { + for (const name of ["coordinator.md", "research.md", "poteto-agent.md", "comment-sicko.md"]) { const content = readFileSync(join(PLUGIN_ROOT, "roles", name), "utf8"); assert.equal(content.includes("—"), false, `${name} contains em-dash`); assert.equal(content.includes("–"), false, `${name} contains en-dash`); assert.equal(content.includes(":"), false, `${name} contains colon`); } - const coordText = readFileSync(join(PLUGIN_ROOT, "roles", "coordinator.md"), "utf8"); - assert.match(coordText, /always_on/); - assert.match(coordText, /SKILL\.md/); - assert.match(coordText, /Never kill `monitor` or `narrator` unless the user\s+asks/); - - const researchText = readFileSync(join(PLUGIN_ROOT, "roles", "research.md"), "utf8"); - assert.match(researchText, /canonical temp roots/); - }); -}); - -describe("Legacy subagent and run_workflow ban with default_api prefix normalization", () => { - test("denies all 5 legacy and workflow tools (bare and default_api:) across managed roles while allowing unmanaged sessions", () => { const sb = makeSandbox(); try { - writeSwarmMembers(sb.appDataDir, "coord-conv", { - coordinator: { conversation_id: "coord-conv", role: "coordinator" }, - monitor: { conversation_id: "mon-conv", role: "worker" }, - "impl-1": { conversation_id: "impl-conv", role: "worker" }, - "ro-1": { conversation_id: "ro-conv", role: "worker" }, - verifier: { conversation_id: "verifier-conv", role: "worker" }, - "adv-1": { conversation_id: "adv-conv", role: "worker" }, - "sicko-1": { conversation_id: "sicko-conv", role: "worker" }, - }); - - const bannedTools = [ - "invoke_subagent", - "define_subagent", - "manage_subagents", - "send_message", - "run_workflow", - ]; - const managedConvIds = [ - "coord-conv", - "mon-conv", - "impl-conv", - "ro-conv", - "verifier-conv", - "adv-conv", - "sicko-conv", - ]; - - for (const convId of managedConvIds) { - for (const bareTool of bannedTools) { - for (const toolName of [bareTool, `default_api:${bareTool}`]) { - const out = runGuard({ - hookEventName: "PreToolUse", - conversationId: convId, - transcriptPath: join(sb.appDataDir, "brain", convId, "transcript.jsonl"), - cwd: sb.worktree, - toolCall: { id: "tc-1", name: toolName, args: {} }, - }); - assert.deepEqual(out, { - decision: "deny", - reason: "Legacy subagent tools are disabled in Swarm-Centric Pstack v2. Use native swarm.", - }); - } - } - } - - for (const bareTool of bannedTools) { - for (const toolName of [bareTool, `default_api:${bareTool}`]) { - const unmanagedOut = runGuard({ - hookEventName: "PreToolUse", - conversationId: "ordinary-chat-conv", - transcriptPath: join(sb.appDataDir, "brain", "ordinary-chat-conv", "transcript.jsonl"), - lastUserInput: "Refactor utils.ts using a subagent", - cwd: sb.worktree, - toolCall: { id: "tc-2", name: toolName, args: {} }, - }); - assert.deepEqual(unmanagedOut, { decision: "allow" }); - } - } - - const prefixedWriteOnRo = runGuard( - { - hookEventName: "PreToolUse", - conversationId: "ro-conv", - cwd: sb.worktree, - toolCall: { - id: "tc-3", - name: "default_api:write_file", - args: { Path: join(sb.worktree, "blocked.txt") }, - }, - }, - { PSTACK_APPDATA_DIR: sb.appDataDir }, - ); - assert.equal(prefixedWriteOnRo.decision, "deny"); - } finally { - sb.cleanup(); - } - }); -}); - -describe("appDataDir resolution and shared plugin_data/agy-pstack-next cache", () => { - test("resolves ANTIGRAVITY_APP_DATA_DIR and shares plugin_data/agy-pstack-next across plugin and global hooks without duplicate injections", () => { - const root = mkdtempSync(join(tmpdir(), "pstack-variants-")); - try { - for (const product of ["antigravity-cli", "antigravity", "antigravity-ide"]) { - const appData = join(root, ".gemini", product); - writeSwarmMembers(appData, "coord-1", { - "ro-probe": { conversation_id: `conv-${product}`, role: "worker" }, - }); - - const viaTranscript = runGuard({ - hookEventName: "SessionStart", - conversationId: `conv-${product}`, - transcriptPath: join( - appData, - "brain", - `conv-${product}`, - ".system_generated", - "logs", - "transcript.jsonl", - ), - }); - const expectedResearch = readFileSync(join(PLUGIN_ROOT, "roles", "research.md"), "utf8"); - assert.deepEqual(viaTranscript, { - injectSteps: [{ systemMessage: { systemMessage: expectedResearch } }], - }); - } - - const cliAppData = join(root, ".gemini", "antigravity-cli-global"); - const sharedPluginData = join(cliAppData, "plugin_data", "agy-pstack-next"); - writeSwarmMembers(cliAppData, "coord-dual", { - coordinator: { conversation_id: "coord-dual", role: "coordinator" }, - "sicko-clean": { conversationId: "worker-via-env", role: "worker" }, - }); - - const expectedCoord = readFileSync(join(PLUGIN_ROOT, "roles", "coordinator.md"), "utf8"); - const fromPluginHook = runGuard( - { - hookEventName: "SessionStart", - conversationId: "coord-dual", - }, - { - ANTIGRAVITY_APP_DATA_DIR: cliAppData, - PLUGIN_DATA: sharedPluginData, - }, + const transcriptPath = join(sb.appDataDir, "brain", "forked-impl", ".system_generated", "logs", "transcript.jsonl"); + mkdirSync(dirname(transcriptPath), { recursive: true }); + writeFileSync( + transcriptPath, + JSON.stringify({ type: "SYSTEM_MESSAGE", content: "# Research role capsule\n" }) + "\n", + "utf8", ); - assert.deepEqual(fromPluginHook, { - injectSteps: [{ systemMessage: { systemMessage: expectedCoord } }], + writeSwarmMembers(sb.appDataDir, "coord-punct", { + coordinator: { conversation_id: "coord-punct", role: "coordinator" }, + "impl-1": { conversation_id: "forked-impl", role: "worker" }, }); - - const fromGlobalHook = runGuard( - { - hookEventName: "SessionStart", - conversationId: "coord-dual", - }, - { - ANTIGRAVITY_APP_DATA_DIR: cliAppData, - }, + const out = invokeGuard( + { hookEventName: "SessionStart", conversationId: "forked-impl", rootConversationId: "coord-punct", transcriptPath }, + { PSTACK_APPDATA_DIR: sb.appDataDir }, ); - assert.deepEqual(fromGlobalHook, {}); - assert.equal(existsSync(join(sharedPluginData, "injected-capsules.json")), true); + const injected = out.injectSteps[0].systemMessage.systemMessage; + assert.ok(injected.startsWith("> **Role override.**")); + assert.equal(injected.includes("—"), false); + assert.equal(injected.includes("–"), false); + assert.equal(injected.includes(":"), false); - const expectedSicko = readFileSync(join(PLUGIN_ROOT, "roles", "comment-sicko.md"), "utf8"); - const workerViaEnvAppData = runGuard( - { - hookEventName: "SessionStart", - conversationId: "worker-via-env", - rootConversationId: "coord-dual", - }, - { - ANTIGRAVITY_APP_DATA_DIR: cliAppData, - }, + const forkMemTranscript = join(sb.appDataDir, "brain", "forked-ro-mem", ".system_generated", "logs", "transcript.jsonl"); + mkdirSync(dirname(forkMemTranscript), { recursive: true }); + writeFileSync( + forkMemTranscript, + JSON.stringify({ type: "USER_INPUT", content: "Everything before this turn is @ro-1's memory. Now inspect." }) + "\n", + "utf8", ); - assert.deepEqual(workerViaEnvAppData, { - injectSteps: [{ systemMessage: { systemMessage: expectedSicko } }], + writeSwarmMembers(sb.appDataDir, "coord-punct", { + coordinator: { conversation_id: "coord-punct", role: "coordinator" }, + "impl-1": { conversation_id: "forked-impl", role: "worker" }, + "ro-1": { conversation_id: "forked-ro-mem", role: "worker" }, }); - assert.equal(existsSync(join(sharedPluginData, "member-map.json")), true); - - const customPluginRoot = join(root, "custom-plugin"); - const customPluginData = join(root, "custom-plugin-data"); - mkdirSync(join(customPluginRoot, "roles"), { recursive: true }); - writeFileSync(join(customPluginRoot, "roles", "coordinator.md"), "custom-coord-capsule\n", "utf8"); - const viaOverrides = runGuard( - { hookEventName: "SessionStart", conversationId: "override-conv" }, - { - PSTACK_APPDATA_DIR: cliAppData, - PLUGIN_ROOT: customPluginRoot, - PLUGIN_DATA: customPluginData, - PSTACK_FORCE_COORDINATOR: "1", - }, + const memOut = invokeGuard( + { hookEventName: "SessionStart", conversationId: "forked-ro-mem", rootConversationId: "coord-punct", transcriptPath: forkMemTranscript }, + { PSTACK_APPDATA_DIR: sb.appDataDir }, ); - assert.deepEqual(viaOverrides, { - injectSteps: [{ systemMessage: { systemMessage: "custom-coord-capsule\n" } }], - }); - assert.equal(existsSync(join(customPluginData, "injected-capsules.json")), true); + assert.ok(memOut.injectSteps[0].systemMessage.systemMessage.startsWith("> **Role override.**")); } finally { - rmSync(root, { recursive: true, force: true }); + sb.cleanup(); } }); +}); - test("skips builtin monitor and narrator roles cleanly without capsule injection", () => { +describe("Session classification, non-hijacking activation, disablement, and delegation", () => { + test("does not hijack mid-sentence /pstack, plain /swarm, /ketchup --plain, or standalone inline skills", () => { const sb = makeSandbox(); try { - writeSwarmMembers(sb.appDataDir, "coord-1", { - monitor: { conversation_id: "id-mon", role: "worker" }, - "monitor-2": { conversation_id: "id-mon-2", role: "worker" }, - narrator: { conversation_id: "id-nar", role: "worker" }, - "narrator-1": { conversation_id: "id-nar-1", role: "worker" }, - }); - - for (const id of ["id-mon", "id-mon-2", "id-nar", "id-nar-1"]) { - for (const hookEventName of ["SessionStart", "PreInvocation"]) { - const out = runGuard( - { hookEventName, conversationId: id, rootConversationId: "coord-1" }, + const unmanagedInputs = [ + "Is v2 better than /pstack in everyday chats?", + "Compare /pstack with built-in /swarm please.", + "/swarm investigate flaky test", + "/ketchup --plain", + "\n/ketchup --plain summarize that\n", + "/bro explain what this hook does", + "/technical-writing polish this doc", + "/setup-pstack", + "/statechart validate", + "/control-ui check localhost", + "/control-cli test cli", + "/make-bot-ui scaffold", + ]; + for (let i = 0; i < unmanagedInputs.length; i += 1) { + const convId = `unmanaged-${i}`; + assert.deepEqual( + invokeGuard({ hookEventName: "SessionStart", conversationId: convId, lastUserInput: unmanagedInputs[i] }, { PSTACK_APPDATA_DIR: sb.appDataDir }), + {}, + `expected unmanaged SessionStart for: ${unmanagedInputs[i]}`, + ); + assert.deepEqual( + invokeGuard( + { + hookEventName: "PreToolUse", + conversationId: convId, + cwd: sb.worktree, + toolCall: { id: "sub-1", name: "invoke_subagent", args: { TypeName: "research" } }, + }, { PSTACK_APPDATA_DIR: sb.appDataDir }, - ); - assert.deepEqual(out, {}); - } + ), + { decision: "allow" }, + `expected invoke_subagent allowed for: ${unmanagedInputs[i]}`, + ); } } finally { sb.cleanup(); } }); -}); -describe("Session classification (worker, coordinator, unmanaged) and O(1) lookup", () => { - test("leaves non-swarm chats unmanaged and classifies coordinators strictly across the 5 coordinator signals", () => { + test("activates coordinator ONLY on explicit leading slash commands, forced env, roster, or cached coordinator capsule", () => { const sb = makeSandbox(); try { - const coordCapsule = readFileSync(join(PLUGIN_ROOT, "roles", "coordinator.md"), "utf8"); - - const normalTranscript = join( - sb.appDataDir, - "brain", - "normal-chat", - ".system_generated", - "logs", - "transcript.jsonl", - ); - writeTranscriptLines(normalTranscript, [ - { step_index: 0, type: "USER_INPUT", content: "Fix the failing unit test" }, - ]); - - assert.deepEqual( - runGuard( - { - hookEventName: "SessionStart", - conversationId: "normal-chat", - transcriptPath: normalTranscript, - lastUserInput: "Fix the failing unit test", - }, - { PSTACK_APPDATA_DIR: sb.appDataDir }, - ), - {}, - ); - assert.deepEqual( - runGuard( - { - hookEventName: "PreInvocation", - conversationId: "normal-chat", - transcriptPath: normalTranscript, - lastUserInput: "/compact please", - }, - { PSTACK_APPDATA_DIR: sb.appDataDir }, - ), - {}, - ); - assert.deepEqual( - runGuard( - { - hookEventName: "PreInvocation", - conversationId: "normal-chat", - transcriptPath: normalTranscript, - lastUserInput: "See https://example.com/pstack for docs", - }, - { PSTACK_APPDATA_DIR: sb.appDataDir }, - ), - {}, - ); - assert.deepEqual( - runGuard( - { - hookEventName: "PreInvocation", - conversationId: "normal-chat", - transcriptPath: normalTranscript, - lastUserInput: "thanks bro, looks good", - }, - { PSTACK_APPDATA_DIR: sb.appDataDir }, - ), - {}, - ); - - const slashPrompts = [ - "/pstack ship auth", - "/agy-pstack-next:pstack check compatibility", - "please run /agy-pstack-next:setup-pstack", - "/understand auth flow", - "/agy-pstack-next:crucible parser", - "/interrogate hooks", - "/reflect session", - "/ketchup --plain", - "/bro", - "/agy-pstack-next:bro", - "/verify-gen --formal", - "/control-ui login", - "/control-cli repl", - "/statechart spec.ts", - "/technical-writing README.md", - "/make-bot-ui chat", + const coordInputs = [ + "/pstack fix bug", + " \n /agy-pstack-next:pstack build feature\n", + "/understand why hooks fired", + "/crucible design new parser", + "/interrogate auth flow", + "/reflect on PR #4", + "/verify-gen create harness", + "/ketchup", + "/ketchup --video", + "/agy-pstack-next:ketchup --recall guard", ]; - - slashPrompts.forEach((prompt, idx) => { - const convId = `slash-coord-${idx}`; - const out = runGuard( - { - hookEventName: "PreInvocation", - conversationId: convId, - lastUserInput: prompt, - }, + for (let i = 0; i < coordInputs.length; i += 1) { + const convId = `coord-slash-${i}`; + const out = invokeGuard( + { hookEventName: "SessionStart", conversationId: convId, lastUserInput: coordInputs[i] }, { PSTACK_APPDATA_DIR: sb.appDataDir }, ); - assert.deepEqual(out, { - injectSteps: [{ systemMessage: { systemMessage: coordCapsule } }], - }); - }); - - const followUpDenied = runGuard( - { - hookEventName: "PreToolUse", - conversationId: "slash-coord-0", - lastUserInput: "looks good, continue", - cwd: sb.worktree, - toolCall: { id: "t1", name: "invoke_subagent", args: {} }, - }, - { PSTACK_APPDATA_DIR: sb.appDataDir }, - ); - assert.equal(followUpDenied.decision, "deny"); - - for (const boardTool of ["swarm", "default_api:swarm", "post_message", "read_board", "default_api:swarm_wait"]) { - const out = runGuard( + assert.ok(out.injectSteps?.[0]?.systemMessage?.systemMessage?.includes("Coordinator role capsule"), `expected coordinator capsule for ${coordInputs[i]}`); + const subDeny = invokeGuard( { hookEventName: "PreToolUse", - conversationId: "spontaneous-swarm-root", + conversationId: convId, cwd: sb.worktree, - toolCall: { id: "b1", name: boardTool, args: { action: "status" } }, + toolCall: { id: "sub-2", name: "invoke_subagent", args: { TypeName: "research" } }, }, { PSTACK_APPDATA_DIR: sb.appDataDir }, ); - assert.equal(out.decision, "allow"); + assert.equal(subDeny.decision, "deny"); } - const unmanagedAfterBoardTool = runGuard( - { - hookEventName: "SessionStart", - conversationId: "spontaneous-swarm-root", - }, - { PSTACK_APPDATA_DIR: sb.appDataDir }, - ); - assert.deepEqual(unmanagedAfterBoardTool, {}); - - writeSwarmMembers(sb.appDataDir, "own-swarm-coord", { - coordinator: { conversation_id: "own-swarm-coord", role: "coordinator" }, - }); - const viaOwnSwarm = runGuard( - { hookEventName: "SessionStart", conversationId: "own-swarm-coord" }, - { PSTACK_APPDATA_DIR: sb.appDataDir }, - ); - assert.deepEqual(viaOwnSwarm, { - injectSteps: [{ systemMessage: { systemMessage: coordCapsule } }], - }); - const viaForceEnv = runGuard( - { hookEventName: "SessionStart", conversationId: "forced-coord" }, + const forced = invokeGuard( + { hookEventName: "SessionStart", conversationId: "forced-coord", lastUserInput: "hello" }, { PSTACK_APPDATA_DIR: sb.appDataDir, PSTACK_FORCE_COORDINATOR: "1" }, ); - assert.deepEqual(viaForceEnv, { - injectSteps: [{ systemMessage: { systemMessage: coordCapsule } }], - }); + assert.ok(forced.injectSteps?.[0]?.systemMessage?.systemMessage?.includes("Coordinator role capsule")); } finally { sb.cleanup(); } }); - test("resolves workers in O(1), skips brain scan on USER_INPUT transcripts, caches non-worker-roots.json, and batch-caches workers", () => { + test("supports remote swarm.json --roster-only with 15s TTL / 5s miss backoff and validates remote swarm IDs", () => { const sb = makeSandbox(); try { - const cacheDir = join(sb.appDataDir, "plugin_data", "agy-pstack-next"); - - writeSwarmMembers(sb.appDataDir, "other-swarm", { - "ro-decoy": { conversation_id: "user-root-conv", role: "worker" }, - }); - const userTranscript = join( - sb.appDataDir, - "brain", - "user-root-conv", - ".system_generated", - "logs", - "transcript.jsonl", - ); - writeTranscriptLines(userTranscript, [ - { step_index: 0, type: "USER_INPUT", content: "Normal user chat" }, - ]); - - const skippedScanOut = runGuard( - { - hookEventName: "SessionStart", - conversationId: "user-root-conv", - transcriptPath: userTranscript, - }, - { PSTACK_APPDATA_DIR: sb.appDataDir }, + const mockCli = join(sb.root, "mock-swarm-cli.sh"); + const countFile = join(sb.root, "cli-calls.txt"); + writeFileSync( + mockCli, + `#!/bin/sh +echo "call" >> "${countFile}" +echo '{"swarm_id":"remote_swarm.1","members":{"coordinator":{"conversation_id":"rcoord","role":"coordinator"},"ro-1":{"conversation_id":"rworker-1","role":"worker"}}}' +`, + "utf8", ); - assert.deepEqual(skippedScanOut, {}); + chmodSync(mockCli, 0o755); - const subagentTranscript = join( - sb.appDataDir, - "brain", - "custom-subagent-1", - ".system_generated", - "logs", - "transcript.jsonl", - ); - writeTranscriptLines(subagentTranscript, [ - { step_index: 0, type: "SYSTEM_MESSAGE", content: "Subagent task" }, - ]); + const swarmDir = join(sb.appDataDir, "brain", "rcoord", ".system_generated", "swarm"); + mkdirSync(swarmDir, { recursive: true }); + writeFileSync(join(swarmDir, "swarm.json"), JSON.stringify({ backend: "spanner", swarm_id: "remote_swarm.1" }), "utf8"); - const firstSubagentOut = runGuard( - { - hookEventName: "SessionStart", - conversationId: "custom-subagent-1", - transcriptPath: subagentTranscript, - }, - { PSTACK_APPDATA_DIR: sb.appDataDir }, + const out1 = invokeGuard( + { hookEventName: "SessionStart", conversationId: "rworker-1", rootConversationId: "rcoord" }, + { PSTACK_APPDATA_DIR: sb.appDataDir, PSTACK_REMOTE_SWARM_CLI: mockCli }, ); - assert.deepEqual(firstSubagentOut, {}); - - const nonWorkerRoots = JSON.parse(readFileSync(join(cacheDir, "non-worker-roots.json"), "utf8")); - assert.equal(nonWorkerRoots["custom-subagent-1"], true); + assert.ok(out1.injectSteps[0].systemMessage.systemMessage.includes("Read-only specialist role capsule")); + const mapDoc = JSON.parse(readFileSync(join(sb.appDataDir, "plugin_data", "agy-pstack-next", "member-map.json"), "utf8")); + assert.equal(mapDoc["rworker-1"], "ro-1"); - const memberMapAfterScan = JSON.parse(readFileSync(join(cacheDir, "member-map.json"), "utf8")); - assert.equal(memberMapAfterScan["user-root-conv"], "ro-decoy"); - - writeSwarmMembers(sb.appDataDir, "late-other-swarm", { - "ro-should-not-scan": { conversation_id: "custom-subagent-1", role: "worker" }, - }); - const secondSubagentOut = runGuard( - { - hookEventName: "PreInvocation", - conversationId: "custom-subagent-1", - transcriptPath: subagentTranscript, - }, - { PSTACK_APPDATA_DIR: sb.appDataDir }, + invokeGuard( + { hookEventName: "SessionStart", conversationId: "missing-worker", rootConversationId: "rcoord" }, + { PSTACK_APPDATA_DIR: sb.appDataDir, PSTACK_REMOTE_SWARM_CLI: mockCli }, ); - assert.deepEqual(secondSubagentOut, {}); + assert.equal(readFileSync(countFile, "utf8").trim().split("\n").length, 1); - writeSwarmMembers(sb.appDataDir, "direct-root", { - coordinator: { conversation_id: "direct-root", role: "coordinator" }, - "impl-a": { conversation_id: "w-impl-a", role: "worker" }, - "cand-b": { conversation_id: "w-cand-b", role: "worker" }, - "lead-c": { conversation_id: "w-lead-c", role: "worker" }, - }); - - const agentCapsule = readFileSync(join(PLUGIN_ROOT, "roles", "poteto-agent.md"), "utf8"); - const viaRootConvId = runGuard( - { - hookEventName: "SessionStart", - conversationId: "w-impl-a", - rootConversationId: "direct-root", - }, - { PSTACK_APPDATA_DIR: sb.appDataDir }, - ); - assert.deepEqual(viaRootConvId, { - injectSteps: [{ systemMessage: { systemMessage: agentCapsule } }], - }); + for (const badId of ["abc", "-bad", "bad/id", "a".repeat(129)]) { + const badDir = join(sb.appDataDir, "brain", "bad-coord", ".system_generated", "swarm"); + mkdirSync(badDir, { recursive: true }); + writeFileSync(join(badDir, "swarm.json"), JSON.stringify({ backend: "spanner", swarm_id: badId }), "utf8"); + invokeGuard( + { hookEventName: "SessionStart", conversationId: "someone", rootConversationId: "bad-coord" }, + { PSTACK_APPDATA_DIR: sb.appDataDir, PSTACK_REMOTE_SWARM_CLI: mockCli }, + ); + } + assert.equal(readFileSync(countFile, "utf8").trim().split("\n").length, 1); + } finally { + sb.cleanup(); + } + }); - const mapBatch = JSON.parse(readFileSync(join(cacheDir, "member-map.json"), "utf8")); - assert.equal(mapBatch["w-impl-a"], "impl-a"); - assert.equal(mapBatch["w-cand-b"], "cand-b"); - assert.equal(mapBatch["w-lead-c"], "lead-c"); - assert.equal(mapBatch["direct-root"], undefined); + test("classifies numbered suffixes and respects config.json disablement with zero cache writes", () => { + const sb = makeSandbox(); + try { + writeSwarmMembers(sb.appDataDir, "coord-suffix", { + coordinator: { conversation_id: "coord-suffix", role: "coordinator" }, + "impl-2": { conversation_id: "c-impl", role: "worker" }, + "cand-3": { conversation_id: "c-cand", role: "worker" }, + "lead-1": { conversation_id: "c-lead", role: "worker" }, + "ro-4": { conversation_id: "c-ro", role: "worker" }, + "adv-2": { conversation_id: "c-adv", role: "worker" }, + "sicko-5": { conversation_id: "c-sicko", role: "worker" }, + verifier: { conversation_id: "c-v0", role: "worker" }, + "verifier-2": { conversation_id: "c-v1", role: "worker" }, + "auth-verifier-3": { conversation_id: "c-v2", role: "worker" }, + "verify-2": { conversation_id: "c-v3", role: "worker" }, + "monitor-1": { conversation_id: "c-mon", role: "worker" }, + "narrator-2": { conversation_id: "c-nar", role: "worker" }, + }); + + for (const vid of ["c-ro", "c-v0", "c-v1", "c-v2", "c-v3"]) { + assert.equal( + invokeGuard( + { hookEventName: "PreToolUse", conversationId: vid, rootConversationId: "coord-suffix", cwd: sb.worktree, toolCall: { id: "1", name: "edit_file", args: { Path: join(sb.worktree, "a.js") } } }, + { PSTACK_APPDATA_DIR: sb.appDataDir }, + ).decision, + "deny", + ); + } + for (const supId of ["c-mon", "c-nar"]) { + assert.deepEqual( + invokeGuard({ hookEventName: "SessionStart", conversationId: supId, rootConversationId: "coord-suffix" }, { PSTACK_APPDATA_DIR: sb.appDataDir }), + {}, + ); + assert.equal( + invokeGuard( + { hookEventName: "PreToolUse", conversationId: supId, rootConversationId: "coord-suffix", cwd: sb.worktree, toolCall: { id: "2", name: "run_workflow", args: {} } }, + { PSTACK_APPDATA_DIR: sb.appDataDir }, + ).decision, + "deny", + ); + } - rmSync(join(sb.appDataDir, "brain", "direct-root"), { recursive: true, force: true }); - const cachedCand = runGuard( - { hookEventName: "SessionStart", conversationId: "w-cand-b" }, - { PSTACK_APPDATA_DIR: sb.appDataDir }, + const cfgDir = join(sb.root, "cfg"); + mkdirSync(cfgDir, { recursive: true }); + writeFileSync(join(cfgDir, "config.json"), JSON.stringify({ plugins: { "agy-pstack-next": { enabled: false } } }), "utf8"); + const cacheDir = join(sb.root, "disabled-cache"); + assert.deepEqual( + invokeGuard( + { hookEventName: "SessionStart", conversationId: "c-ro", rootConversationId: "coord-suffix" }, + { PSTACK_APPDATA_DIR: sb.appDataDir, PSTACK_CONFIG_DIR: cfgDir, PSTACK_CACHE_DIR: cacheDir }, + ), + {}, ); - assert.deepEqual(cachedCand, { - injectSteps: [{ systemMessage: { systemMessage: agentCapsule } }], - }); + assert.equal(existsSync(cacheDir), false); } finally { sb.cleanup(); } }); -}); -describe("Verifier helper mapping and capsule override notices on upgrade and fork", () => { - test("maps verifier, verifier-*, *-verifier, and verify-* helpers to readonly while preserving explicit prefixes", () => { + test("16-way parallel SessionStart suffers zero capsule write loss and avoids negative-cache poisoning", async () => { 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 sickoCapsule = readFileSync(join(PLUGIN_ROOT, "roles", "comment-sicko.md"), "utf8"); + const members = { coordinator: { conversation_id: "coord-race", role: "coordinator" } }; + for (let i = 0; i < 16; i += 1) { + members[`ro-${i}`] = { conversation_id: `ro-race-${i}`, role: "worker" }; + } + writeSwarmMembers(sb.appDataDir, "coord-race", members); - writeSwarmMembers(sb.appDataDir, "coord-v", { - verifier: { conversation_id: "id-v0", role: "worker" }, - "verifier-1": { conversation_id: "id-v1", role: "worker" }, - "api-verifier": { conversation_id: "id-v2", role: "worker" }, - "verify-links": { conversation_id: "id-v3", role: "worker" }, - "impl-verifier": { conversation_id: "id-impl-v", role: "worker" }, - "sicko-verifier": { conversation_id: "id-sicko-v", role: "worker" }, - }); + const spawnSessionStart = (convId) => + new Promise((resolvePromise, reject) => { + const child = spawn(process.execPath, [GUARD_PATH], { + env: buildEnv({ PSTACK_APPDATA_DIR: sb.appDataDir }), + stdio: ["pipe", "pipe", "pipe"], + }); + let out = ""; + let err = ""; + child.stdout.on("data", (d) => { out += d; }); + child.stderr.on("data", (d) => { err += d; }); + child.on("close", (code) => { + if (code !== 0) reject(new Error(`exit ${code}: ${err}`)); + else resolvePromise(JSON.parse(out)); + }); + child.stdin.end(JSON.stringify({ hookEventName: "SessionStart", conversationId: convId, rootConversationId: "coord-race", cwd: sb.worktree })); + }); - for (const id of ["id-v0", "id-v1", "id-v2", "id-v3"]) { - const sessionOut = runGuard( - { hookEventName: "SessionStart", conversationId: id, rootConversationId: "coord-v" }, - { PSTACK_APPDATA_DIR: sb.appDataDir }, + const results = await Promise.all(Array.from({ length: 16 }, (_, i) => spawnSessionStart(`ro-race-${i}`))); + for (let i = 0; i < 16; i += 1) { + assert.equal(results[i].injectSteps.length, 1); + const capFile = join(sb.appDataDir, "plugin_data", "agy-pstack-next", "capsules", `ro-race-${i}.json`); + assert.equal(existsSync(capFile), true); + assert.equal(JSON.parse(readFileSync(capFile, "utf8")).capsule, "roles/research.md"); + assert.deepEqual( + invokeGuard({ hookEventName: "PreInvocation", conversationId: `ro-race-${i}`, rootConversationId: "coord-race" }, { PSTACK_APPDATA_DIR: sb.appDataDir }), + {}, ); - assert.deepEqual(sessionOut, { - injectSteps: [{ systemMessage: { systemMessage: researchCapsule } }], - }); + } - const editRepoOut = runGuard( + assert.deepEqual( + invokeGuard({ hookEventName: "SessionStart", conversationId: "late-ro" }, { PSTACK_APPDATA_DIR: sb.appDataDir }), + {}, + ); + writeSwarmMembers(sb.appDataDir, "coord-late", { + coordinator: { conversation_id: "coord-late", role: "coordinator" }, + "ro-late": { conversation_id: "late-ro", role: "worker" }, + }); + assert.equal( + invokeGuard( { hookEventName: "PreToolUse", - conversationId: id, + conversationId: "late-ro", cwd: sb.worktree, - toolCall: { id: "t1", name: "write_file", args: { Path: join(sb.worktree, "out.txt") } }, + toolCall: { id: "late-w", name: "write_file", args: { Path: join(sb.worktree, "pwn.txt") } }, }, { PSTACK_APPDATA_DIR: sb.appDataDir }, - ); - assert.equal(editRepoOut.decision, "deny"); - } - - const implVerifierOut = runGuard( - { hookEventName: "SessionStart", conversationId: "id-impl-v", rootConversationId: "coord-v" }, - { PSTACK_APPDATA_DIR: sb.appDataDir }, - ); - assert.deepEqual(implVerifierOut, { - injectSteps: [{ systemMessage: { systemMessage: agentCapsule } }], - }); - - const sickoVerifierOut = runGuard( - { hookEventName: "SessionStart", conversationId: "id-sicko-v", rootConversationId: "coord-v" }, - { PSTACK_APPDATA_DIR: sb.appDataDir }, + ).decision, + "deny", ); - assert.deepEqual(sickoVerifierOut, { - injectSteps: [{ systemMessage: { systemMessage: sickoCapsule } }], - }); } finally { sb.cleanup(); } }); - test("prepends concise role-override notice when upgrading injected-capsules.json or forking a capsule transcript", () => { + test("delegates via PSTACK_PLUGIN_ROOT dynamic import() in-process without spawning a second Node process", async () => { const sb = makeSandbox(); try { - const coordCapsule = readFileSync(join(PLUGIN_ROOT, "roles", "coordinator.md"), "utf8"); - const researchCapsule = readFileSync(join(PLUGIN_ROOT, "roles", "research.md"), "utf8"); - const agentCapsule = readFileSync(join(PLUGIN_ROOT, "roles", "poteto-agent.md"), "utf8"); - - const firstCoord = runGuard( - { - hookEventName: "SessionStart", - conversationId: "upgrade-conv", - lastUserInput: "/pstack audit", - }, - { PSTACK_APPDATA_DIR: sb.appDataDir }, + const altRoot = join(sb.root, "alt-plugin"); + mkdirSync(join(altRoot, "hooks"), { recursive: true }); + writeFileSync( + join(altRoot, "hooks", "guard.mjs"), + `export async function handleRawStdin(raw, env) { + const p = JSON.parse(raw); + return JSON.stringify({ delegated: true, pid: process.pid, flag: env.PSTACK_GUARD_DELEGATED, event: p.hookEventName }) + "\\n"; +} +`, + "utf8", ); - assert.deepEqual(firstCoord, { - injectSteps: [{ systemMessage: { systemMessage: coordCapsule } }], - }); - - writeSwarmMembers(sb.appDataDir, "coord-root", { - "ro-1": { conversation_id: "upgrade-conv", role: "worker" }, - "impl-forked": { conversation_id: "forked-impl-conv", role: "worker" }, - "impl-from-coord": { conversation_id: "forked-from-coord-conv", role: "worker" }, - }); - - const upgraded = runGuard( - { - hookEventName: "PreInvocation", - conversationId: "upgrade-conv", - rootConversationId: "coord-root", - }, - { PSTACK_APPDATA_DIR: sb.appDataDir }, + const outStr = await handleRawStdin( + JSON.stringify({ hookEventName: "SessionStart", conversationId: "x" }), + buildEnv({ PSTACK_PLUGIN_ROOT: altRoot }), ); - const upgradedMsg = upgraded.injectSteps[0].systemMessage.systemMessage; - assert.equal(upgradedMsg.endsWith(researchCapsule), true); - assert.notEqual(upgradedMsg, researchCapsule); - assert.match(upgradedMsg, /Role override/); - assert.match(upgradedMsg, /supersedes/); - assert.equal(upgradedMsg.includes("—"), false); - assert.equal(upgradedMsg.includes(":"), false); + const out = JSON.parse(outStr); + assert.equal(out.delegated, true); + assert.equal(out.pid, process.pid); + assert.equal(out.flag, "1"); + assert.equal(out.event, "SessionStart"); - const dedupedUpgrade = runGuard( - { - hookEventName: "PreInvocation", - conversationId: "upgrade-conv", - rootConversationId: "coord-root", - }, - { PSTACK_APPDATA_DIR: sb.appDataDir }, - ); - assert.deepEqual(dedupedUpgrade, {}); + const cliOut = runGuardCli({ hookEventName: "SessionStart", conversationId: "x" }, { PSTACK_PLUGIN_ROOT: altRoot }); + assert.equal(cliOut.delegated, true); + assert.equal(cliOut.flag, "1"); - const forkedTranscript = join( - sb.appDataDir, - "brain", - "forked-impl-conv", - ".system_generated", - "logs", - "transcript.jsonl", + const runOnlyRoot = join(sb.root, "run-only-plugin"); + mkdirSync(join(runOnlyRoot, "hooks"), { recursive: true }); + writeFileSync( + join(runOnlyRoot, "hooks", "guard.mjs"), + `export function runGuard(p, env) { return { runOnly: true, flag: env.PSTACK_GUARD_DELEGATED, event: p.hookEventName }; }\n`, + "utf8", ); - writeTranscriptLines(forkedTranscript, [ - { - step_index: 0, - source: "SYSTEM_SDK", - type: "SYSTEM_MESSAGE", - content: `The following system message was injected by a SessionStart hook:\n${researchCapsule}`, - }, - ]); + const runOnlyOut = JSON.parse(await handleRawStdin( + JSON.stringify({ hookEventName: "PreInvocation", conversationId: "y" }), + buildEnv({ PSTACK_PLUGIN_ROOT: runOnlyRoot }), + )); + assert.deepEqual(runOnlyOut, { runOnly: true, flag: "1", event: "PreInvocation" }); + } finally { + sb.cleanup(); + } + }); +}); - const forkedInject = runGuard( - { - hookEventName: "SessionStart", - conversationId: "forked-impl-conv", - rootConversationId: "coord-root", - transcriptPath: forkedTranscript, - }, - { PSTACK_APPDATA_DIR: sb.appDataDir }, - ); - const forkedMsg = forkedInject.injectSteps[0].systemMessage.systemMessage; - assert.equal(forkedMsg.endsWith(agentCapsule), true); - assert.notEqual(forkedMsg, agentCapsule); - assert.match(forkedMsg, /Role override/); - assert.match(forkedMsg, /supersedes/); - - const forkedRepeat = runGuard( - { - hookEventName: "PreInvocation", - conversationId: "forked-impl-conv", - rootConversationId: "coord-root", - transcriptPath: forkedTranscript, - }, - { PSTACK_APPDATA_DIR: sb.appDataDir }, - ); - assert.deepEqual(forkedRepeat, {}); - - const forkedCoordTranscript = join( - sb.appDataDir, - "brain", - "forked-from-coord-conv", - ".system_generated", - "logs", - "transcript.jsonl", - ); - writeTranscriptLines(forkedCoordTranscript, [ - { step_index: 0, type: "USER_INPUT", content: "/pstack fix guard" }, - { - step_index: 1, - type: "SYSTEM_MESSAGE", - content: `The following system message was injected by a PreInvocation hook:\n${coordCapsule}`, - }, - ]); - - const forkedFromCoordInject = runGuard( - { - hookEventName: "SessionStart", - conversationId: "forked-from-coord-conv", - transcriptPath: forkedCoordTranscript, - }, - { PSTACK_APPDATA_DIR: sb.appDataDir }, - ); - const forkedCoordMsg = forkedFromCoordInject.injectSteps[0].systemMessage.systemMessage; - assert.equal(forkedCoordMsg.endsWith(agentCapsule), true); - assert.match(forkedCoordMsg, /Role override/); - } finally { - sb.cleanup(); - } - }); -}); - -describe("Author and adversary worktree, artifact, temp-root, and shell confinement", () => { - test("allows write_file and edit_file in cwd, artifactDir, and canonical temp roots while blocking sibling, outside, and symlink escapes", () => { +describe("PreToolUse structural gates, path confinement, MCP, and git/gh checks", () => { + test("blocks legacy subagent tools and run_workflow EXCEPT invoke_subagent with image-generator", () => { const sb = makeSandbox(); - const slashTmpSandbox = mkdtempSync("/tmp/pstack-author-tmp-"); try { - const artifactDir = join(sb.appDataDir, "brain", "impl-conv"); - mkdirSync(artifactDir, { recursive: true }); - writeSwarmMembers(sb.appDataDir, "coord-1", { - "impl-auth": { conversation_id: "impl-conv", role: "worker" }, - "adv-sec": { conversation_id: "adv-conv", role: "worker" }, - "eval-runner-1": { conversation_id: "eval-conv", role: "worker" }, + writeSwarmMembers(sb.appDataDir, "coord-sub", { + coordinator: { conversation_id: "coord-sub", role: "coordinator" }, + "impl-1": { conversation_id: "impl-sub", role: "worker" }, + "ro-1": { conversation_id: "ro-sub", role: "worker" }, + "adv-1": { conversation_id: "adv-sub", role: "worker" }, + "sicko-1": { conversation_id: "sicko-sub", role: "worker" }, + monitor: { conversation_id: "mon-sub", role: "worker" }, }); - const outsideExistingFile = join(sb.outsideDir, "secret.txt"); - writeFileSync(outsideExistingFile, "secret", "utf8"); - symlinkSync(sb.outsideDir, join(sb.worktree, "linked-outside-dir")); - symlinkSync(outsideExistingFile, join(sb.worktree, "linked-outside-file.txt")); - symlinkSync(join(sb.outsideDir, "nonexistent-victim.txt"), join(sb.worktree, "dangling-escape.txt")); - symlinkSync(sb.outsideDir, join(slashTmpSandbox, "tmp-escape-link")); - - const internalRealDir = join(sb.worktree, "packages", "core"); - mkdirSync(internalRealDir, { recursive: true }); - symlinkSync(internalRealDir, join(sb.worktree, "internal-link")); - - const checkPath = (convId, toolName, targetPath) => - runGuard( - { - hookEventName: "PreToolUse", - conversationId: convId, - rootConversationId: "coord-1", - artifactDirectoryPath: artifactDir, - cwd: sb.worktree, - toolCall: { id: "tc", name: toolName, args: { Path: targetPath } }, - }, - { PSTACK_APPDATA_DIR: sb.appDataDir, TMPDIR: sb.customTmpDir }, - ); - - assert.equal( - checkPath("impl-conv", "write_file", join(sb.worktree, "src", "new", "deep", "index.mjs")).decision, - "allow", - ); - assert.equal( - checkPath("impl-conv", "edit_file", "relative/new-subdir/module.mjs").decision, - "allow", - ); - assert.equal( - checkPath("impl-conv", "write_file", join(sb.worktree, "internal-link", "sub", "ok.mjs")).decision, - "allow", - ); - assert.equal( - checkPath("impl-conv", "write_file", join(artifactDir, "scratch", "notes.md")).decision, - "allow", - ); - assert.equal( - checkPath("eval-conv", "write_file", join(slashTmpSandbox, "trial-1", ".agents", "skills", "s", "SKILL.md")).decision, - "allow", - ); - assert.equal( - checkPath("adv-conv", "write_file", "/private/tmp/pstack-adv-repro.mjs").decision, - "allow", - ); - assert.equal( - checkPath("adv-conv", "edit_file", join(sb.customTmpDir, "repro-notes.txt")).decision, - "allow", - ); - - assert.equal( - checkPath("impl-conv", "write_file", "../swarm-worker-a-sibling/hack.mjs").decision, - "deny", - ); - assert.equal( - checkPath("impl-conv", "edit_file", join(sb.siblingWorktree, "hack.mjs")).decision, - "deny", - ); - assert.equal( - checkPath("impl-conv", "write_file", join(sb.worktree, "linked-outside-dir", "new", "pwn.mjs")).decision, - "deny", - ); - assert.equal( - checkPath("adv-conv", "edit_file", join(sb.worktree, "linked-outside-file.txt")).decision, - "deny", - ); - assert.equal( - checkPath("eval-conv", "write_file", join(sb.worktree, "dangling-escape.txt")).decision, - "deny", - ); - assert.equal( - checkPath("eval-conv", "write_file", join(slashTmpSandbox, "tmp-escape-link", "pwn.mjs")).decision, - "deny", - ); - - const coordOutside = checkPath("coord-1", "write_file", join(sb.outsideDir, "pstack-models.md")); - assert.equal(coordOutside.decision, "allow"); + for (const convId of ["coord-sub", "impl-sub", "ro-sub", "adv-sub", "sicko-sub", "mon-sub"]) { + for (const tool of ["invoke_subagent", "define_subagent", "manage_subagents", "send_message", "run_workflow"]) { + assert.equal( + invokeGuard( + { hookEventName: "PreToolUse", conversationId: convId, rootConversationId: "coord-sub", cwd: sb.worktree, toolCall: { id: "t1", name: `default_api:${tool}`, args: {} } }, + { PSTACK_APPDATA_DIR: sb.appDataDir }, + ).decision, + "deny", + ); + } + for (const key of ["TypeName", "SubagentName", "typeName", "subagentName"]) { + assert.equal( + invokeGuard( + { hookEventName: "PreToolUse", conversationId: convId, rootConversationId: "coord-sub", cwd: sb.worktree, toolCall: { id: "t2", name: "default_api:invoke_subagent", args: { [key]: "Image-Generator" } } }, + { PSTACK_APPDATA_DIR: sb.appDataDir }, + ).decision, + "allow", + ); + } + } } finally { - rmSync(slashTmpSandbox, { recursive: true, force: true }); sb.cleanup(); } }); - test("confines author and adversary run_command redirects and cp/mv/ln/rm/patch/sed -i targets", () => { + test("enforces realpath, symlink, sibling-prefix, and .system_generated confinement across roles", () => { const sb = makeSandbox(); - const slashTmpSandbox = mkdtempSync("/tmp/pstack-author-shell-"); try { - const artifactDir = join(sb.appDataDir, "brain", "impl-conv"); - mkdirSync(artifactDir, { recursive: true }); - symlinkSync(sb.outsideDir, join(slashTmpSandbox, "tmp-escape")); - - writeSwarmMembers(sb.appDataDir, "coord-1", { - "impl-1": { conversation_id: "impl-conv", role: "worker" }, - "adv-1": { conversation_id: "adv-conv", role: "worker" }, - }); - - const runAuthorCmd = (convId, CommandLine) => - runGuard( - { - hookEventName: "PreToolUse", - conversationId: convId, - rootConversationId: "coord-1", - artifactDirectoryPath: artifactDir, - cwd: sb.worktree, - toolCall: { id: "c1", name: "run_command", args: { CommandLine } }, - }, + writeSwarmMembers(sb.appDataDir, "coord-path", { + coordinator: { conversation_id: "coord-path", role: "coordinator" }, + "impl-1": { conversation_id: "impl-p", role: "worker" }, + "adv-1": { conversation_id: "adv-p", role: "worker" }, + "sicko-1": { conversation_id: "sicko-p", role: "worker" }, + "ro-1": { conversation_id: "ro-p", role: "worker" }, + }); + symlinkSync(sb.outsideDir, join(sb.worktree, "escape-dir")); + symlinkSync(join(sb.outsideDir, "dangling.txt"), join(sb.worktree, "dangling-link.txt")); + + const callPath = (convId, name, Path) => + invokeGuard( + { hookEventName: "PreToolUse", conversationId: convId, rootConversationId: "coord-path", cwd: sb.worktree, toolCall: { id: "p", name, args: { Path } } }, { PSTACK_APPDATA_DIR: sb.appDataDir, TMPDIR: sb.customTmpDir }, ); - const allowedCmds = [ - "echo build-ok > dist/output.txt", - "node --test hooks/guard.test.mjs 2>/dev/null", - `echo trial > ${join(slashTmpSandbox, "out.log")}`, - `echo custom-tmp > ${join(sb.customTmpDir, "scratch.log")}`, - "echo $TMPDIR/ok > $TMPDIR/probe.txt", - "cp /etc/hosts ./hosts-copy.txt", - `cp README.md ${join(slashTmpSandbox, "README.bak")}`, - `cp ${join(slashTmpSandbox, "README.bak")} .`, - "mv src/old.mjs src/new.mjs", - `mv ${join(slashTmpSandbox, "staged.json")} src/staged.json`, - "ln -s ../core packages/link-core", - "rm -rf dist/ build/", - `rm -f ${join(slashTmpSandbox, "out.log")}`, - "patch -p1 < fix.diff", - "patch src/app.mjs fix.diff", - "sed -i '' '/^DEBUG/d' src/app.mjs", - "sed -i 's/foo/bar/g' src/app.mjs", - `cat <<'EOF' > ${join(slashTmpSandbox, "heredoc.mjs")}\nconst x = a > b;\nrm -rf /outside\nEOF`, - ]; - - for (const cmd of allowedCmds) { - assert.equal(runAuthorCmd("impl-conv", cmd).decision, "allow", `expected allow for: ${cmd}`); - assert.equal(runAuthorCmd("adv-conv", cmd).decision, "allow", `expected allow for adv: ${cmd}`); - } - - const deniedCmds = [ - `echo escaped > ${join(sb.outsideDir, "escaped.txt")}`, - "echo escaped > ../swarm-worker-a-sibling/escaped.txt", - "echo escaped > ~/escaped-home.txt", - `echo escaped > ${join(slashTmpSandbox, "tmp-escape", "pwn.txt")}`, - `cp /etc/hosts ${join(sb.outsideDir, "escaped.txt")}`, - "cp src/a.mjs ../swarm-worker-a-sibling/a.mjs", - `mv src/a.mjs ${join(sb.outsideDir, "a.mjs")}`, - `mv ${join(sb.outsideDir, "secret.txt")} src/secret.txt`, - `ln -s /etc/hosts ${join(sb.outsideDir, "hosts-link")}`, - `ln -s ${join(sb.outsideDir, "secret.txt")} ./escape-link`, - `rm -rf ${join(sb.outsideDir, "victim")}`, - "rm -f ../swarm-worker-a-sibling/file.mjs", - `patch -d ${sb.outsideDir} -p1 < fix.diff`, - `patch ${join(sb.outsideDir, "victim.txt")} fix.diff`, - `sed -i '' 's/a/b/g' ${join(sb.outsideDir, "victim.txt")}`, - "sed -i 's/a/b/g' ../swarm-worker-a-sibling/victim.txt", - ]; - - for (const cmd of deniedCmds) { - assert.equal(runAuthorCmd("impl-conv", cmd).decision, "deny", `expected deny for: ${cmd}`); - assert.equal(runAuthorCmd("adv-conv", cmd).decision, "deny", `expected deny for adv: ${cmd}`); - } + for (const convId of ["impl-p", "adv-p"]) { + assert.equal(callPath(convId, "write_file", join(sb.worktree, "src", "ok.js")).decision, "allow"); + assert.equal(callPath(convId, "edit_file", join(sb.customTmpDir, "scratch.txt")).decision, "allow"); + assert.equal(callPath(convId, "write_file", join(sb.appDataDir, "brain", convId, "report.md")).decision, "allow"); + assert.equal(callPath(convId, "write_file", join(sb.appDataDir, "brain", convId, ".system_generated", "bad.json")).decision, "deny"); + assert.equal(callPath(convId, "write_file", join(sb.siblingWorktree, "pwn.js")).decision, "deny"); + assert.equal(callPath(convId, "edit_file", join(sb.outsideDir, "secret.txt")).decision, "deny"); + assert.equal(callPath(convId, "write_file", join(sb.worktree, "escape-dir", "pwn.txt")).decision, "deny"); + assert.equal(callPath(convId, "write_file", join(sb.worktree, "dangling-link.txt")).decision, "deny"); + } + + assert.equal(callPath("sicko-p", "write_file", join(sb.worktree, "new.js")).decision, "deny"); + assert.equal(callPath("sicko-p", "edit_file", join(sb.worktree, "existing.js")).decision, "allow"); + assert.equal(callPath("sicko-p", "edit_file", join(sb.customTmpDir, "scratch.txt")).decision, "deny"); + assert.equal(callPath("sicko-p", "edit_file", join(sb.siblingWorktree, "existing.js")).decision, "deny"); + + assert.equal(callPath("ro-p", "edit_file", join(sb.customTmpDir, "scratch.txt")).decision, "deny"); + assert.equal(callPath("ro-p", "write_file", join(sb.customTmpDir, "notes.md")).decision, "allow"); + assert.equal(callPath("ro-p", "write_file", "/tmp/ro-probe-file.json").decision, "allow"); + assert.equal(callPath("ro-p", "write_file", join(sb.appDataDir, "brain", "ro-p", "shot.png")).decision, "allow"); + assert.equal(callPath("ro-p", "write_file", join(sb.appDataDir, "brain", "ro-p", "notes.md")).decision, "deny"); + assert.equal(callPath("ro-p", "write_file", join(sb.appDataDir, "brain", "ro-p", ".system_generated", "shot.png")).decision, "deny"); + assert.equal(callPath("ro-p", "write_file", join(sb.worktree, "shot.png")).decision, "deny"); } finally { - rmSync(slashTmpSandbox, { recursive: true, force: true }); sb.cleanup(); } }); -}); -describe("ro-* Read-Only Guard with canonical temp roots, inline script checks, and read-only git refs", () => { - test("allows ro-* temp-root write_file/edit_file/FS/inline-script/git-tag/git-stash probes while blocking non-temp mutations", () => { + test("gates mutating MCP tools for readonly while allowing board tools and read-only calls", () => { const sb = makeSandbox(); - const slashTmpDir = mkdtempSync("/tmp/pstack-ro-probe-"); try { - symlinkSync(sb.outsideDir, join(slashTmpDir, "escape-symlink")); - writeSwarmMembers(sb.appDataDir, "coord-1", { - "ro-verify": { conversation_id: "ro-id", role: "worker" }, + writeSwarmMembers(sb.appDataDir, "coord-mcp", { + coordinator: { conversation_id: "coord-mcp", role: "coordinator" }, + "ro-1": { conversation_id: "ro-mcp", role: "worker" }, }); - - const callRoFileTool = (toolName, targetPath) => - runGuard( - { - hookEventName: "PreToolUse", - conversationId: "ro-id", - rootConversationId: "coord-1", - cwd: sb.worktree, - toolCall: { id: "t1", name: toolName, args: { Path: targetPath } }, - }, - { PSTACK_APPDATA_DIR: sb.appDataDir, TMPDIR: sb.customTmpDir }, - ); - - assert.equal(callRoFileTool("write_file", join(slashTmpDir, "probe.txt")).decision, "allow"); - assert.equal(callRoFileTool("edit_file", "/private/tmp/ro-notes.md").decision, "allow"); - assert.equal(callRoFileTool("write_file", join(sb.customTmpDir, "tmpdir-probe.json")).decision, "allow"); - assert.equal(callRoFileTool("write_file", realpathSync(slashTmpDir) + "/real-probe.txt").decision, "allow"); - - assert.equal(callRoFileTool("write_file", join(sb.worktree, "f.txt")).decision, "deny"); - assert.equal(callRoFileTool("edit_file", join(sb.worktree, "f.txt")).decision, "deny"); - assert.equal(callRoFileTool("write_file", join(sb.outsideDir, "f.txt")).decision, "deny"); - assert.equal(callRoFileTool("write_file", "/tmp/../etc/pwned").decision, "deny"); - assert.equal(callRoFileTool("write_file", join(slashTmpDir, "escape-symlink", "pwn.txt")).decision, "deny"); - - const runCmd = (CommandLine) => - runGuard( - { - hookEventName: "PreToolUse", - conversationId: "ro-id", - rootConversationId: "coord-1", - cwd: sb.worktree, - toolCall: { id: "t2", name: "run_command", args: { CommandLine } }, - }, - { PSTACK_APPDATA_DIR: sb.appDataDir, TMPDIR: sb.customTmpDir }, + const callMcp = (name, args) => + invokeGuard( + { hookEventName: "PreToolUse", conversationId: "ro-mcp", rootConversationId: "coord-mcp", cwd: sb.worktree, toolCall: { id: "m", name, args } }, + { PSTACK_APPDATA_DIR: sb.appDataDir }, ); - const allowedCommands = [ - "git status --short", - "git -C /tmp/repo diff 051c56d -- skills/statechart/scripts", - "git log --oneline -n 10 2>/dev/null", - "git show HEAD:hooks.json", - "git tag", - "git tag -l", - "git tag -l 'v1.*'", - "git tag --list", - "git tag -v v1.0.0", - "git tag --verify v1.0.0", - "git tag --contains HEAD", - "git tag --points-at HEAD", - "git stash list", - "git stash show", - "git stash show -p stash@{0}", - "node --test hooks/guard.test.mjs 2>&1", - "grep -rn 'git push|rm -rf' hooks/", - "sed -n '1,20p' README.md", - "npm test", - `echo probe-result > ${join(slashTmpDir, "probe.txt")}`, - `echo tmpdir-result > ${join(sb.customTmpDir, "probe.txt")}`, - "echo env-tmp > $TMPDIR/env-probe.txt", - "git status | tee /dev/null", - `git log -n 3 | tee -a ${join(slashTmpDir, "git.log")}`, - `mkdir -p ${join(slashTmpDir, "nested")} && cp README.md ${join(slashTmpDir, "nested", "README.md")}`, - `mv ${join(slashTmpDir, "a.txt")} ${join(slashTmpDir, "b.txt")}`, - `chmod +x ${join(slashTmpDir, "probe.sh")} && unlink ${join(slashTmpDir, "b.txt")}`, - `rm -rf ${join(slashTmpDir, "nested")} ${join(sb.customTmpDir, "probe.txt")}`, - "node -e \"console.log(JSON.parse(require('fs').readFileSync('hooks.json', 'utf8')))\"", - `node -e "require('fs').writeFileSync('${join(slashTmpDir, "inline.json")}', '{}')"`, - "python3 -c \"import json; print(json.load(open('hooks.json', encoding='utf-8')))\"", - `python3 -c "open('${join(slashTmpDir, "py.txt")}', 'w').write('ok')"`, - `python3 -c "from pathlib import Path; Path('${join(slashTmpDir, "p.txt")}').write_text('ok')"`, - `python3 -c "import os; os.remove('${join(slashTmpDir, "p.txt")}')"`, - ]; - for (const cmd of allowedCommands) { - assert.equal(runCmd(cmd).decision, "allow", `expected allow for: ${cmd}`); + for (const allowed of ["post_message", "read_board", "swarm_wait", "swarm", "list_resources", "read_resource", "get_issue", "list_pulls"]) { + assert.equal(callMcp("call_mcp_tool", { ToolName: allowed }).decision, "allow"); } - - const deniedCommands = [ - "git commit -m 'sneaky'", - "git -C /tmp/repo push origin main", - "git merge feature", - "git rebase main", - "git cherry-pick abc1234", - "git reset --hard HEAD~1", - "git clean -fd", - "git stash", - "git stash push", - "git stash pop", - "git stash drop", - "git stash apply", - "git stash clear", - "git tag v2.0.0", - "git tag -a v2.0.0 -m 'release'", - "git tag -d v2.0.0", - "git tag --delete v2.0.0", - "git tag -f -l v2.0.0", - "git am patch.mbox", - "git apply fix.patch", - "git mv a.js b.js", - "git rm a.js", - "git checkout -b new-branch", - "git checkout -B reset-branch", - "git checkout --orphan empty-branch", - "git checkout -- README.md", - "git switch -c another-branch", - "git switch -C force-branch", - "rm -rf dist", - `rm -f ${join(slashTmpDir, "escape-symlink", "secret.txt")}`, - "rmdir empty-dir", - "mv a.txt b.txt", - `mv README.md ${join(slashTmpDir, "stolen.md")}`, - "cp a.txt b.txt", - `cp ${join(slashTmpDir, "a.txt")} README.md`, - "chmod +x script.sh", - "unlink README.md", - "chown nobody file.txt", - "truncate -s 0 file.txt", - "dd if=/dev/zero of=out.bin count=1", - "patch -p1 < fix.diff", - "sed -i '' 's/foo/bar/g' file.txt", - "perl -pi -e 's/foo/bar/g' file.txt", - "npm install lodash", - "pnpm add zod", - "yarn", - "yarn add react", - "bun install", - "pip install requests", - "python3 -m pip install click", - "echo hacked > README.md", - "echo escaped > /tmp/../etc/pwned", - `echo escaped > ${join(slashTmpDir, "escape-symlink", "pwned.txt")}`, - "echo appended >> notes.md", - "git status | tee status.txt", - "git status | tee /tmp/../outside.txt", - "sh -c 'rm -f secret.txt'", - "echo $(touch pwned.txt)", - "node -e \"require('fs').writeFileSync('README.md', 'hacked')\"", - "node -e \"import('node:fs').then(fs => fs.unlinkSync('hooks.json'))\"", - `node -e "require('fs').writeFileSync('${join(slashTmpDir, "escape-symlink", "pwn.txt")}', 'x')"`, - "node -e \"const p = 'README.md'; require('fs').rmSync(p)\"", - "node -e \"const w = require('fs').writeFileSync; w('README.md', 'x')\"", - "node -e \"const { writeFileSync: w } = require('fs'); w('README.md', 'x')\"", - "python3 -c \"open('README.md', 'w').write('hacked')\"", - "python3 -c \"import os; r = os.remove; r('hooks.json')\"", - "python3 -c \"from os import remove as r; r('hooks.json')\"", - "python3 -c \"o = open; o('README.md', 'w').write('x')\"", - "python3 -c \"import os; os.remove('hooks.json')\"", - "python3 -c \"import shutil; shutil.rmtree('skills')\"", - "python3 -c \"from pathlib import Path; Path('README.md').write_text('x')\"", - "python3 -c \"from pathlib import Path; p = Path('README.md'); p.write_text('x')\"", - ]; - for (const cmd of deniedCommands) { - assert.equal(runCmd(cmd).decision, "deny", `expected deny for: ${cmd}`); + assert.equal(callMcp("mcp_github_get_pull_request", {}).decision, "allow"); + for (const blocked of ["create_issue", "update-pr", "delete_comment", "post_review", "merge_pull", "send_email", "insert_row"]) { + assert.equal(callMcp("call_mcp_tool", { ToolName: blocked }).decision, "deny"); } + assert.equal(callMcp("mcp_github_create_issue", {}).decision, "deny"); } finally { - rmSync(slashTmpDir, { recursive: true, force: true }); sb.cleanup(); } }); - test("allows native swarm and read-only MCP calls while blocking mutating MCP tools", () => { + test("allows all 10 prior false positives on ro-* while blocking git and gh footguns across roles", () => { const sb = makeSandbox(); try { - writeSwarmMembers(sb.appDataDir, "coord-1", { - "ro-mesh": { conversation_id: "ro-mcp-id", role: "worker" }, - }); - - const callTool = (name, args = {}) => - runGuard( - { - hookEventName: "PreToolUse", - conversationId: "ro-mcp-id", - rootConversationId: "coord-1", - cwd: sb.worktree, - toolCall: { id: "m1", name, args }, - }, - { PSTACK_APPDATA_DIR: sb.appDataDir }, - ); - - assert.equal(callTool("call_mcp_tool", { ToolName: "post_message" }).decision, "allow"); - assert.equal(callTool("call_mcp_tool", { ToolName: "read_board" }).decision, "allow"); - assert.equal(callTool("call_mcp_tool", { ToolName: "swarm_wait" }).decision, "allow"); - assert.equal(callTool("call_mcp_tool", { ToolName: "swarm" }).decision, "allow"); - assert.equal(callTool("mcp_swarm_post_message").decision, "allow"); - - assert.equal(callTool("mcp_github_get_pull_request").decision, "allow"); - assert.equal(callTool("mcp_linear_list_issues").decision, "allow"); - assert.equal(callTool("call_mcp_tool", { ToolName: "search_code" }).decision, "allow"); - assert.equal(callTool("call_mcp_tool", { toolName: "inspect_trace" }).decision, "allow"); + writeSwarmMembers(sb.appDataDir, "coord-cmd", { + coordinator: { conversation_id: "coord-cmd", role: "coordinator" }, + "ro-1": { conversation_id: "ro-cmd", role: "worker" }, + "impl-1": { conversation_id: "impl-cmd", role: "worker" }, + "adv-1": { conversation_id: "adv-cmd", role: "worker" }, + "sicko-1": { conversation_id: "sicko-cmd", role: "worker" }, + }); + + const runCmd = (convId, CommandLine, extraEnv = {}) => + invokeGuard( + { hookEventName: "PreToolUse", conversationId: convId, rootConversationId: "coord-cmd", cwd: sb.worktree, toolCall: { id: "c", name: "run_command", args: { CommandLine } } }, + { PSTACK_APPDATA_DIR: sb.appDataDir, TMPDIR: sb.customTmpDir, ...extraEnv }, + ); + + const allowedRoCommands = [ + `python3 -c "print('a:b'.split(':')[0].replace('a', 'c'))"`, + `python3 -c "d = {'a': 1}; print(d.copy())"`, + `python3 -c "import os; print(getattr(os, 'sep'))"`, + `node -e "const o = { rm: 1 }; console.log(o.rm)"`, + `node -e "console.log('fs.writeFileSync and open(a, b)')"`, + `git tag --sort=-creatordate`, + `git tag -n5`, + `git tag -n 5`, + `echo 'print(1)' > /tmp/pstack_chain_probe.py && python3 /tmp/pstack_chain_probe.py`, + `for t in 1 2; do echo ok > "/tmp/pstack_race_test/t\${t}/out.txt"; done`, + `git status && git diff && git log -n 5 && git show HEAD && git blame README.md && git rev-parse HEAD`, + `git worktree list && git stash list && git stash show && git tag && git tag -l 'v*'`, + `git branch && git branch -a && git branch --show-current && git branch > /tmp/branches.txt`, + `git remote && git remote -v && git remote show origin && git config --get user.name && git config --list && git config user.name`, + `git -C ${sb.customTmpDir}/scratch init && git -C /tmp/scratch commit -m test`, + `gh pr view 1 && gh pr list && gh api repos/org/repo && gh api -X GET repos/org/repo`, + `echo "git push -f origin main"`, + ]; + for (const cmd of allowedRoCommands) { + assert.equal(runCmd("ro-cmd", cmd).decision, "allow", `expected ro allow: ${cmd}`); + } + + const deniedRoCommands = [ + `git add .`, + `git commit -m x`, + `git push origin feat`, + `git pull`, + `git checkout main`, + `git switch main`, + `git restore .`, + `git reset --hard`, + `git clean -fd`, + `git branch evil-branch`, + `git branch -D feat`, + `git tag v1.0.0`, + `git tag -d v1.0.0`, + `git stash`, + `git stash pop`, + `git worktree add /tmp/wt`, + `git remote add evil https://example.com`, + `git config user.name Evil`, + `git config --unset user.name`, + `git -C ${sb.customTmpDir}/scratch -C ${sb.outsideDir} commit -m pwn`, + `gh pr create --title x --body y`, + `gh pr merge 1`, + `gh issue comment 1 --body hi`, + `gh release create v1`, + `gh repo Fork org/repo`, + `gh api -X POST repos/o/r/issues`, + `gh api repos/o/r/issues -f title=x`, + `gh api repos/o/r/issues --input body.json`, + ]; + for (const cmd of deniedRoCommands) { + assert.equal(runCmd("ro-cmd", cmd).decision, "deny", `expected ro deny: ${cmd}`); + } - assert.equal(callTool("mcp_github_create_pull_request").decision, "deny"); - assert.equal(callTool("mcp_github_merge_pull_request").decision, "deny"); - assert.equal(callTool("mcp_linear_update_issue").decision, "deny"); - assert.equal(callTool("mcp_slack_send_message").decision, "deny"); - assert.equal(callTool("call_mcp_tool", { ToolName: "delete_branch" }).decision, "deny"); - assert.equal(callTool("call_mcp_tool", { ToolName: "reply_to_comment" }).decision, "deny"); - assert.equal(callTool("call_mcp_tool", { toolName: "write-page" }).decision, "deny"); + for (const convId of ["coord-cmd", "impl-cmd", "ro-cmd", "adv-cmd", "sicko-cmd"]) { + for (const cmd of [ + "git push --force origin main", + "git push -f origin master", + "git push -uf origin HEAD:main", + "git push origin +main", + "(git push -f origin +HEAD:refs/heads/master)", + ]) { + assert.equal(runCmd(convId, cmd, { PSTACK_ALLOW_PUSH: "1" }).decision, "deny", `expected force-push deny for ${convId}: ${cmd}`); + } + } + assert.equal(runCmd("coord-cmd", "git push --force-with-lease origin main").decision, "allow"); + assert.equal(runCmd("coord-cmd", "git push --force-if-includes origin main").decision, "allow"); + assert.equal(runCmd("impl-cmd", "git push --force-with-lease origin main", { PSTACK_ALLOW_PUSH: "1" }).decision, "allow"); + + const gitInWt = (args) => spawnSync("git", ["-C", sb.worktree, ...args], { encoding: "utf8" }); + gitInWt(["init", "-b", "main"]); + gitInWt(["config", "user.email", "test@example.com"]); + gitInWt(["config", "user.name", "Test"]); + writeFileSync(join(sb.worktree, "init.txt"), "init\n", "utf8"); + gitInWt(["add", "init.txt"]); + gitInWt(["commit", "-m", "init"]); + for (const cmd of ["git push --force", "git push -f origin", "git push -f origin HEAD", "git push origin +HEAD"]) { + assert.equal(runCmd("coord-cmd", cmd).decision, "deny", `expected implicit main deny for coord: ${cmd}`); + assert.equal(runCmd("impl-cmd", cmd, { PSTACK_ALLOW_PUSH: "1" }).decision, "deny", `expected implicit main deny for impl: ${cmd}`); + } + gitInWt(["checkout", "-b", "feat/force-ok"]); + for (const cmd of ["git push --force", "git push -f origin", "git push -f origin HEAD"]) { + assert.equal(runCmd("coord-cmd", cmd).decision, "allow", `expected feature-branch allow for coord: ${cmd}`); + assert.equal(runCmd("impl-cmd", cmd, { PSTACK_ALLOW_PUSH: "1" }).decision, "allow", `expected feature-branch allow for impl: ${cmd}`); + } + assert.equal(runCmd("impl-cmd", "git push --force origin main", { PSTACK_ALLOW_PUSH: "1" }).decision, "deny"); + const mainRepo = join(sb.root, "other-main-repo"); + mkdirSync(mainRepo, { recursive: true }); + spawnSync("git", ["-C", mainRepo, "init", "-b", "main"], { encoding: "utf8" }); + assert.equal(runCmd("coord-cmd", `git -C ${mainRepo} push -f origin`).decision, "deny"); + + assert.equal(runCmd("impl-cmd", "git push origin feat").decision, "deny"); + assert.equal(runCmd("impl-cmd", "PSTACK_ALLOW_PUSH=1 git push origin feat").decision, "allow"); + assert.equal(runCmd("impl-cmd", "env PSTACK_ALLOW_PUSH=1 git push origin feat").decision, "allow"); + assert.equal(runCmd("impl-cmd", "PSTACK_ALLOW_PUSH=1 echo hi && git push origin feat").decision, "deny"); + assert.equal(runCmd("impl-cmd", "git push origin feat", { PSTACK_ALLOW_PUSH: "1" }).decision, "allow"); + + for (const convId of ["adv-cmd", "sicko-cmd"]) { + assert.equal(runCmd(convId, "PSTACK_ALLOW_PUSH=1 git push origin feat", { PSTACK_ALLOW_PUSH: "1" }).decision, "deny"); + assert.equal(runCmd(convId, "gh pr close 1").decision, "deny"); + } + + for (const cmd of ["git status", "git diff", "git log -n 2", "git add src/a.js", "git commit -m 'clean'"]) { + assert.equal(runCmd("sicko-cmd", cmd).decision, "allow", `expected sicko allow: ${cmd}`); + } + for (const cmd of ["git fetch", "git checkout -- .", "git restore .", "git reset --hard", "git rm foo.js", "git mv a b", `git -C ${sb.outsideDir} add .`]) { + assert.equal(runCmd("sicko-cmd", cmd).decision, "deny", `expected sicko deny: ${cmd}`); + } } finally { sb.cleanup(); } }); }); -describe("sicko-* Guard and git push Gate", () => { - test("enforces sicko-* write_file ban, edit_file confinement, shell file-creation/mutation ban, and git push block", () => { +describe("Stop hook git cleanliness check and loop guards", () => { + function initGitRepo(dir) { + const run = (args) => spawnSync("git", ["-C", dir, ...args], { encoding: "utf8" }); + run(["init"]); + run(["config", "user.email", "test@example.com"]); + run(["config", "user.name", "Test"]); + writeFileSync(join(dir, "tracked.txt"), "hello\n", "utf8"); + writeFileSync(join(dir, "baseline-dirty.txt"), "initial\n", "utf8"); + run(["add", "tracked.txt", "baseline-dirty.txt"]); + run(["commit", "-m", "init"]); + writeFileSync(join(dir, "baseline-dirty.txt"), "dirty-before-session\n", "utf8"); + } + + test("enforces git cleanliness on Stop for readonly and sicko against SessionStart/PreInvocation baseline", () => { const sb = makeSandbox(); try { - const targetInside = join(sb.worktree, "app.mjs"); - writeFileSync(targetInside, "// comment\nexport const x = 1;\n", "utf8"); - writeSwarmMembers(sb.appDataDir, "coord-1", { - "sicko-1": { conversation_id: "sicko-id", role: "worker" }, + initGitRepo(sb.worktree); + writeSwarmMembers(sb.appDataDir, "coord-stop", { + coordinator: { conversation_id: "coord-stop", role: "coordinator" }, + "ro-1": { conversation_id: "ro-stop", role: "worker" }, + "sicko-1": { conversation_id: "sicko-stop", role: "worker" }, + "impl-1": { conversation_id: "impl-stop", role: "worker" }, }); - const writeAttempt = runGuard( - { - hookEventName: "PreToolUse", - conversationId: "sicko-id", - rootConversationId: "coord-1", - cwd: sb.worktree, - toolCall: { id: "s1", name: "write_file", args: { Path: targetInside } }, - }, - { PSTACK_APPDATA_DIR: sb.appDataDir }, - ); - assert.equal(writeAttempt.decision, "deny"); + invokeGuard({ hookEventName: "SessionStart", conversationId: "ro-stop", rootConversationId: "coord-stop", cwd: sb.worktree }, { PSTACK_APPDATA_DIR: sb.appDataDir }); + invokeGuard({ hookEventName: "SessionStart", conversationId: "sicko-stop", rootConversationId: "coord-stop", cwd: sb.worktree }, { PSTACK_APPDATA_DIR: sb.appDataDir }); - const editInside = runGuard( - { - hookEventName: "PreToolUse", - conversationId: "sicko-id", - rootConversationId: "coord-1", - cwd: sb.worktree, - toolCall: { id: "s2", name: "edit_file", args: { Path: targetInside } }, - }, - { PSTACK_APPDATA_DIR: sb.appDataDir }, + assert.deepEqual( + invokeGuard({ hookEventName: "Stop", conversationId: "ro-stop", rootConversationId: "coord-stop", cwd: sb.worktree, terminationReason: "NO_TOOL_CALL" }, { PSTACK_APPDATA_DIR: sb.appDataDir }), + {}, ); - assert.equal(editInside.decision, "allow"); - const editOutside = runGuard( - { - hookEventName: "PreToolUse", - conversationId: "sicko-id", - rootConversationId: "coord-1", - cwd: sb.worktree, - toolCall: { - id: "s3", - name: "edit_file", - args: { Path: join(sb.outsideDir, "other.mjs") }, - }, - }, + writeFileSync(join(sb.worktree, "tracked.txt"), "mutated\n", "utf8"); + const roStop = invokeGuard( + { hookEventName: "Stop", conversationId: "ro-stop", rootConversationId: "coord-stop", cwd: sb.worktree, terminationReason: "NO_TOOL_CALL" }, { PSTACK_APPDATA_DIR: sb.appDataDir }, ); - assert.equal(editOutside.decision, "deny"); + assert.equal(roStop.decision, "continue"); + assert.ok(roStop.reason.includes("tracked.txt")); - const editTmpDeniedForSicko = runGuard( - { - hookEventName: "PreToolUse", - conversationId: "sicko-id", - rootConversationId: "coord-1", - cwd: sb.worktree, - toolCall: { - id: "s3b", - name: "edit_file", - args: { Path: "/tmp/sicko-scratch.mjs" }, - }, - }, - { PSTACK_APPDATA_DIR: sb.appDataDir }, + assert.deepEqual( + invokeGuard( + { hookEventName: "Stop", conversationId: "ro-stop", rootConversationId: "coord-stop", cwd: sb.worktree, continuationActive: true }, + { PSTACK_APPDATA_DIR: sb.appDataDir }, + ), + {}, ); - assert.equal(editTmpDeniedForSicko.decision, "deny"); - - const runSickoCmd = (CommandLine, extraEnv = {}) => - runGuard( - { - hookEventName: "PreToolUse", - conversationId: "sicko-id", - rootConversationId: "coord-1", - cwd: sb.worktree, - toolCall: { id: "s4", name: "run_command", args: { CommandLine } }, - }, - { PSTACK_APPDATA_DIR: sb.appDataDir, ...extraEnv }, - ); - - for (const allowedSickoCmd of [ - "git status --short", - "git diff HEAD", - "git blame app.mjs", - "git log -S 'MUST KILL' 2>/dev/null", - "node --test hooks/guard.test.mjs 2>&1", - "git commit -am 'chore: strip narration comments'", - "git status | tee /dev/null", - ]) { - assert.equal( - runSickoCmd(allowedSickoCmd).decision, - "allow", - `expected sicko allow for: ${allowedSickoCmd}`, - ); - } - - for (const deniedSickoCmd of [ - "echo 'export const y = 2;' > new.ts", - "echo scratch > /tmp/sicko.txt", - "cat app.mjs >> copy.mjs", - "git status | tee status.txt", - "cp app.mjs copy.mjs", - "mv app.mjs renamed.mjs", - "rm -f app.mjs", - "touch created.ts", - "truncate -s 0 app.mjs", - "dd if=/dev/zero of=app.mjs count=1", - "patch -p1 < comments.diff", - "sed -i '' '/^\\/\\//d' app.mjs", - "perl -pi -e 's/\\/\\/.*//' app.mjs", - "PSTACK_ALLOW_PUSH=1 git push origin feat", - ]) { - assert.equal( - runSickoCmd(deniedSickoCmd, { PSTACK_ALLOW_PUSH: "1" }).decision, - "deny", - `expected sicko deny for: ${deniedSickoCmd}`, - ); - } - } finally { - sb.cleanup(); - } - }); - - test("enforces adv-* push ban, impl-* PSTACK_ALLOW_PUSH=1 gate, and universal force-push main/master ban", () => { - const sb = makeSandbox(); - try { - writeSwarmMembers(sb.appDataDir, "coord-id", { - coordinator: { conversation_id: "coord-id", role: "coordinator" }, - "adv-1": { conversation_id: "adv-id", role: "worker" }, - "impl-1": { conversation_id: "impl-id", role: "worker" }, - }); - - const runPush = (convId, CommandLine, extraEnv = {}) => - runGuard( - { - hookEventName: "PreToolUse", - conversationId: convId, - rootConversationId: convId === "coord-id" ? undefined : "coord-id", - cwd: sb.worktree, - toolCall: { id: "p1", name: "run_command", args: { CommandLine } }, - }, - { PSTACK_APPDATA_DIR: sb.appDataDir, ...extraEnv }, - ); - - assert.equal(runPush("adv-id", "git push origin feat").decision, "deny"); - assert.equal( - runPush("adv-id", "PSTACK_ALLOW_PUSH=1 git push origin feat", { PSTACK_ALLOW_PUSH: "1" }).decision, - "deny", + assert.deepEqual( + invokeGuard( + { hookEventName: "Stop", conversationId: "ro-stop", rootConversationId: "coord-stop", cwd: sb.worktree, terminationReason: "MAX_TURNS" }, + { PSTACK_APPDATA_DIR: sb.appDataDir }, + ), + {}, ); - assert.equal(runPush("impl-id", "git push origin feat").decision, "deny"); - assert.equal( - runPush("impl-id", "echo PSTACK_ALLOW_PUSH=1 && git push origin feat").decision, - "deny", - ); - assert.equal( - runPush("impl-id", "git commit -m 'enforce git push gate'").decision, - "allow", + assert.deepEqual( + invokeGuard( + { hookEventName: "Stop", conversationId: "sicko-stop", rootConversationId: "coord-stop", cwd: sb.worktree, terminationReason: "NO_TOOL_CALL" }, + { PSTACK_APPDATA_DIR: sb.appDataDir }, + ), + {}, ); - assert.equal( - runPush("impl-id", "PSTACK_ALLOW_PUSH=1 git push origin feat").decision, - "allow", + writeFileSync(join(sb.worktree, "stray-untracked.txt"), "oops\n", "utf8"); + const sickoUntracked = invokeGuard( + { hookEventName: "Stop", conversationId: "sicko-stop", rootConversationId: "coord-stop", cwd: sb.worktree, terminationReason: "NO_TOOL_CALL" }, + { PSTACK_APPDATA_DIR: sb.appDataDir }, ); - assert.equal( - runPush("impl-id", "git push origin feat", { PSTACK_ALLOW_PUSH: "1" }).decision, - "allow", + assert.equal(sickoUntracked.decision, "continue"); + assert.ok(sickoUntracked.reason.includes("stray-untracked.txt")); + rmSync(join(sb.worktree, "stray-untracked.txt")); + rmSync(join(sb.worktree, "tracked.txt")); + const sickoDeleted = invokeGuard( + { hookEventName: "Stop", conversationId: "sicko-stop", rootConversationId: "coord-stop", cwd: sb.worktree }, + { PSTACK_APPDATA_DIR: sb.appDataDir }, ); + assert.equal(sickoDeleted.decision, "continue"); + assert.ok(sickoDeleted.reason.includes("tracked.txt")); - assert.equal( - runPush("impl-id", "PSTACK_ALLOW_PUSH=1 git push --force origin main").decision, - "deny", - ); - assert.equal( - runPush("impl-id", "PSTACK_ALLOW_PUSH=1 git push -f origin master").decision, - "deny", + assert.deepEqual( + invokeGuard( + { hookEventName: "Stop", conversationId: "impl-stop", rootConversationId: "coord-stop", cwd: sb.worktree }, + { PSTACK_APPDATA_DIR: sb.appDataDir }, + ), + {}, ); - assert.equal(runPush("coord-id", "git push --force origin main").decision, "deny"); - assert.equal(runPush("coord-id", "git push -f origin master").decision, "deny"); - assert.equal(runPush("coord-id", "git push origin +HEAD:main").decision, "deny"); - assert.equal(runPush("coord-id", "git push --force-with-lease origin main").decision, "deny"); - - assert.equal(runPush("coord-id", "git push origin main").decision, "allow"); - assert.equal(runPush("coord-id", "git push --force origin feat-stack").decision, "allow"); - } finally { - sb.cleanup(); - } - }); -}); -describe("agy 1.5.9 audit fixes: shell vars, evolve isolation, numbered verifiers, B4 confinement, M2/M3/T1, and swarm capacity", () => { - test("B1+M2+B4 expands per-segment shell vars and redirects while anchoring canonicalTempRoots to outer env", () => { - const sb = makeSandbox(); - try { - writeSwarmMembers(sb.appDataDir, "coord-1", { - "ro-cli": { conversation_id: "ro-id", role: "worker" }, - "impl-cli": { conversation_id: "impl-id", role: "worker" }, - "adv-cli": { conversation_id: "adv-id", role: "worker" }, + writeSwarmMembers(sb.appDataDir, "coord-stop", { + coordinator: { conversation_id: "coord-stop", role: "coordinator" }, + "ro-1": { conversation_id: "ro-stop", role: "worker" }, + "ro-2": { conversation_id: "ro-late-cwd", role: "worker" }, + "sicko-1": { conversation_id: "sicko-stop", role: "worker" }, + "impl-1": { conversation_id: "impl-stop", role: "worker" }, }); - - const runCmd = (convId, CommandLine) => - runGuard( - { - hookEventName: "PreToolUse", - conversationId: convId, - cwd: sb.worktree, - toolCall: { id: "v1", name: "run_command", args: { CommandLine } }, - }, - { PSTACK_APPDATA_DIR: sb.appDataDir, TMPDIR: sb.customTmpDir }, - ); - - const allowedCommands = [ - 'RUN_DIR="/tmp/cli-${WORKER_NAME:-local}-$$-$(date +%s)"; mkdir -p "$RUN_DIR/home" "$RUN_DIR/tmp" "$RUN_DIR/artifacts" && echo ok > "$RUN_DIR/artifacts/help.txt"', - 'RUN_ID="run-42"; mkdir -p "/tmp/verify-app-$RUN_ID" "/tmp/statechart-${WORKER_NAME:-local}-${RUN_ID:-$$}"', - 'RUN_DIR="/tmp/cli-$(date -u +%Y%m%d)-$(uuidgen)"; mkdir -p "$RUN_DIR" && echo x > "$RUN_DIR/out.txt"', - "HOME=/tmp/h echo hi > ~/out.txt", - "export HOME=/tmp/h; echo ok > ~/ok.txt", - ]; - - for (const convId of ["ro-id", "impl-id", "adv-id"]) { - for (const cmd of allowedCommands) { - assert.equal(runCmd(convId, cmd).decision, "allow", `expected allow for ${convId}: ${cmd}`); - } - } - - const deniedCommands = [ - `export TMPDIR=${sb.outsideDir}; echo x > $TMPDIR/pwn.txt`, - `TMPDIR=${sb.outsideDir} mkdir -p $TMPDIR/pwn`, - "echo x > $UNSET_VAR/pwn.txt", - "echo x > $(id)/pwn.txt", - `RUN_DIR="${sb.outsideDir}"; echo x > "$RUN_DIR/pwn.txt"`, - ]; - - for (const convId of ["ro-id", "impl-id", "adv-id"]) { - for (const cmd of deniedCommands) { - assert.equal(runCmd(convId, cmd).decision, "deny", `expected deny for ${convId}: ${cmd}`); - } - } - } finally { - sb.cleanup(); - } - }); - - test("B2 isolates evolve trials via PSTACK_PLUGIN_ROOT delegation and PSTACK_CACHE_DIR", () => { - const sb = makeSandbox(); - try { - const stagedPlugin = join(sb.root, "pack-oak"); - const stagedCache = join(sb.root, "state-oak"); - mkdirSync(join(stagedPlugin, "hooks"), { recursive: true }); - mkdirSync(join(stagedPlugin, "roles"), { recursive: true }); - writeFileSync(join(stagedPlugin, "roles", "coordinator.md"), "staged-oak-coord\n", "utf8"); - writeFileSync( - join(stagedPlugin, "hooks", "guard.mjs"), - `#!/usr/bin/env node\nprocess.stdout.write(JSON.stringify({ delegatedFrom: "pack-oak", delegatedFlag: process.env.PSTACK_GUARD_DELEGATED }) + "\\n");\n`, - "utf8", - ); - - const delegatedOut = runGuard( - { hookEventName: "SessionStart", conversationId: "oak-conv" }, - { PSTACK_PLUGIN_ROOT: stagedPlugin, PSTACK_CACHE_DIR: stagedCache }, + invokeGuard({ hookEventName: "SessionStart", conversationId: "ro-late-cwd", rootConversationId: "coord-stop" }, { PSTACK_APPDATA_DIR: sb.appDataDir }); + invokeGuard({ hookEventName: "PreInvocation", conversationId: "ro-late-cwd", rootConversationId: "coord-stop", cwd: sb.worktree }, { PSTACK_APPDATA_DIR: sb.appDataDir }); + assert.deepEqual( + invokeGuard({ hookEventName: "Stop", conversationId: "ro-late-cwd", rootConversationId: "coord-stop", cwd: sb.worktree, terminationReason: "NO_TOOL_CALL" }, { PSTACK_APPDATA_DIR: sb.appDataDir }), + {}, ); - assert.deepEqual(delegatedOut, { delegatedFrom: "pack-oak", delegatedFlag: "1" }); - writeSwarmMembers(sb.appDataDir, "coord-evolve", { - "ro-oak": { conversation_id: "ro-oak-id", role: "worker" }, - }); - const stagedRolesOnly = join(sb.root, "pack-pine"); - mkdirSync(join(stagedRolesOnly, "roles"), { recursive: true }); - writeFileSync(join(stagedRolesOnly, "roles", "research.md"), "pine-research-capsule\n", "utf8"); - - const isolatedSessionOut = runGuard( - { hookEventName: "SessionStart", conversationId: "ro-oak-id" }, - { - PSTACK_APPDATA_DIR: sb.appDataDir, - PSTACK_PLUGIN_ROOT: stagedRolesOnly, - PSTACK_CACHE_DIR: stagedCache, - }, + const scratchRepo = join(sb.customTmpDir, "scratch-stop"); + mkdirSync(scratchRepo, { recursive: true }); + initGitRepo(scratchRepo); + writeFileSync(join(scratchRepo, "tracked.txt"), "scratch-dirty\n", "utf8"); + assert.deepEqual( + invokeGuard( + { hookEventName: "Stop", conversationId: "ro-stop", rootConversationId: "coord-stop", cwd: scratchRepo, terminationReason: "NO_TOOL_CALL" }, + { PSTACK_APPDATA_DIR: sb.appDataDir, TMPDIR: sb.customTmpDir }, + ), + {}, ); - assert.deepEqual(isolatedSessionOut, { - injectSteps: [{ systemMessage: { systemMessage: "pine-research-capsule\n" } }], - }); - assert.equal(existsSync(join(stagedCache, "injected-capsules.json")), true); - assert.equal(existsSync(join(stagedCache, "member-map.json")), true); - assert.equal(existsSync(join(sb.appDataDir, "plugin_data", "agy-pstack-next", "injected-capsules.json")), false); - } finally { - sb.cleanup(); - } - }); - - test("B3 maps numbered *-verifier-k copies to readonly while keeping impl-verifier-k and sicko-verifier-k roles", () => { - 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 sickoCapsule = readFileSync(join(PLUGIN_ROOT, "roles", "comment-sicko.md"), "utf8"); - - writeSwarmMembers(sb.appDataDir, "coord-b3", { - "api-verifier-1": { conversation_id: "api-v1", role: "worker" }, - "api-verifier-2": { conversation_id: "api-v2", role: "worker" }, - "impl-verifier-1": { conversation_id: "impl-v1", role: "worker" }, - "sicko-verifier-1": { conversation_id: "sicko-v1", role: "worker" }, - }); - - for (const id of ["api-v1", "api-v2"]) { - const sOut = runGuard( - { hookEventName: "SessionStart", conversationId: id }, + assert.deepEqual( + invokeGuard( + { hookEventName: "Stop", conversationId: "ro-stop", rootConversationId: "coord-stop", cwd: sb.outsideDir, terminationReason: "NO_TOOL_CALL" }, { PSTACK_APPDATA_DIR: sb.appDataDir }, - ); - assert.deepEqual(sOut, { injectSteps: [{ systemMessage: { systemMessage: researchCapsule } }] }); - - const wOut = runGuard( - { - hookEventName: "PreToolUse", - conversationId: id, - cwd: sb.worktree, - toolCall: { id: "t1", name: "write_file", args: { Path: join(sb.worktree, "x.txt") } }, - }, - { PSTACK_APPDATA_DIR: sb.appDataDir }, - ); - assert.equal(wOut.decision, "deny"); - } - - assert.deepEqual( - runGuard({ hookEventName: "SessionStart", conversationId: "impl-v1" }, { PSTACK_APPDATA_DIR: sb.appDataDir }), - { injectSteps: [{ systemMessage: { systemMessage: agentCapsule } }] }, - ); - assert.deepEqual( - runGuard({ hookEventName: "SessionStart", conversationId: "sicko-v1" }, { PSTACK_APPDATA_DIR: sb.appDataDir }), - { injectSteps: [{ systemMessage: { systemMessage: sickoCapsule } }] }, - ); - } finally { - sb.cleanup(); - } - }); - - test("B4 enforces git, download/archive, find, and temp script confinement while preserving swarm capacity", () => { - const sb = makeSandbox(); - const slashTmpDir = mkdtempSync("/tmp/pstack-b4-"); - try { - writeSwarmMembers(sb.appDataDir, "coord-b4", { - "ro-verify": { conversation_id: "ro-id", role: "worker" }, - "impl-1": { conversation_id: "impl-id", role: "worker" }, - "adv-1": { conversation_id: "adv-id", role: "worker" }, - "sicko-1": { conversation_id: "sicko-id", role: "worker" }, - }); - - const badJs = join(slashTmpDir, "bad.mjs"); - const okJs = join(slashTmpDir, "ok.mjs"); - const badPy = join(slashTmpDir, "bad.py"); - const okPy = join(slashTmpDir, "ok.py"); - const badSh = join(slashTmpDir, "bad.sh"); - const okSh = join(slashTmpDir, "ok.sh"); - const perlScript = join(slashTmpDir, "probe.pl"); - const codemodJs = join(slashTmpDir, "codemod.mjs"); - const outsidePy = join(slashTmpDir, "outside.py"); - - writeFileSync(badJs, "import fs from 'node:fs'; fs.writeFileSync('README.md', 'pwn');\n", "utf8"); - writeFileSync( - okJs, - `import fs from 'node:fs'; import path from 'node:path'; const runDir = '${slashTmpDir}'; fs.writeFileSync(path.join(runDir, 'after.png'), 'ok'); fs.writeFileSync(\`/tmp/ui-\${id}/shot.png\`, 'ok');\n`, - "utf8", - ); - writeFileSync(badPy, "from pathlib import Path\nPath('README.md').write_text('pwn')\n", "utf8"); - writeFileSync( - okPy, - `import os, tempfile\nrun_dir = tempfile.mkdtemp(prefix='ui-')\nopen(os.path.join(run_dir, 'out.txt'), 'w').write('ok')\nopen(f'/tmp/ui-{id}/snap.txt', 'w').write('ok')\n`, - "utf8", - ); - writeFileSync(badSh, "#!/bin/sh\nrm -f README.md\n", "utf8"); - writeFileSync(okSh, `#!/bin/sh\necho ok > ${join(slashTmpDir, "sh-ok.txt")}\n`, "utf8"); - writeFileSync(perlScript, "print 'hi';\n", "utf8"); - writeFileSync( - codemodJs, - "import fs from 'node:fs'; for (const f of files) { fs.writeFileSync(f, 'updated'); }\n", - "utf8", - ); - writeFileSync( - outsidePy, - `from pathlib import Path\nPath('${join(sb.outsideDir, "pwn.txt")}').write_text('x')\n`, - "utf8", - ); - - const runCmd = (convId, CommandLine) => - runGuard( - { - hookEventName: "PreToolUse", - conversationId: convId, - cwd: sb.worktree, - toolCall: { id: "b4", name: "run_command", args: { CommandLine } }, - }, - { PSTACK_APPDATA_DIR: sb.appDataDir, TMPDIR: sb.customTmpDir }, - ); - - const roAllowed = [ - "git fetch origin", - "git notes list", - "git replace -l", - "git submodule status", - "git symbolic-ref HEAD", - "curl https://example.com", - `curl -o ${join(slashTmpDir, "dl.json")} https://example.com`, - "wget --spider https://example.com", - `wget -P ${slashTmpDir} https://example.com/a.txt`, - "tar -tf archive.tar", - `tar -xf archive.tar -C ${slashTmpDir}`, - "unzip -l archive.zip", - `unzip archive.zip -d ${slashTmpDir}`, - `rsync -n -a src/ ${sb.outsideDir}/`, - `find ${slashTmpDir} -delete`, - `node ${okJs}`, - `python3 ${okPy}`, - `sh ${okSh}`, - `node -e "import fs from 'node:fs'; fs.writeFileSync(\\\`/tmp/ui-\${id}/after.png\\\`, 'ok')"`, - "python3 -c \"open(f'/tmp/ui-{id}/snap.txt', 'w').write('ok')\"", - ]; - for (const cmd of roAllowed) { - assert.equal(runCmd("ro-id", cmd).decision, "allow", `expected ro allow: ${cmd}`); - } - - const roDenied = [ - "git pull", - "git update-ref HEAD HEAD~1", - "git fetch origin main:refs/heads/x", - "git fetch -p", - "git fetch --force", - "git notes add -m x", - "git replace HEAD~1 HEAD", - "git submodule update", - "git symbolic-ref HEAD refs/heads/x", - "truncate -s 0 README.md", - "dd if=/dev/zero of=README.md count=1", - "install src.txt README.md", - "curl -o README.md https://example.com", - "curl -O https://example.com/a.txt", - "wget https://example.com/a.txt", - "wget -O README.md https://example.com", - "tar -xf archive.tar", - "tar -cf out.tar src/", - "unzip archive.zip", - "rsync -a src/ dst/", - "rsync -a src/ user@host:dst/", - "find . -delete", - "find . -fprint out.txt", - "find . -exec rm {} ;", - `node ${join(slashTmpDir, "nonexistent.mjs")}`, - `node ${badJs}`, - `python3 ${badPy}`, - `sh ${badSh}`, - `perl ${perlScript}`, - ]; - for (const cmd of roDenied) { - assert.equal(runCmd("ro-id", cmd).decision, "deny", `expected ro deny: ${cmd}`); - } - - const authorAllowed = [ - `git fetch ${sb.siblingWorktree} abc1234 && git cherry-pick abc1234`, - `git -C ${sb.siblingWorktree} status --short`, - `git -C ${join(slashTmpDir, "trial")} init && git -C ${join(slashTmpDir, "trial")} add . && git -C ${join(slashTmpDir, "trial")} commit -m init`, - `node ${codemodJs}`, - "node -e \"const fs = require('fs'); for (const f of files) fs.writeFileSync(f, 'x')\"", - "python3 -c \"from pathlib import Path\nfor p in paths:\n Path(p).write_text('x')\"", - `mkdir -p ${join(slashTmpDir, "d")} && touch ${join(slashTmpDir, "d", "f")}`, - `curl -o ${join(slashTmpDir, "a.json")} https://example.com`, - ]; - for (const convId of ["impl-id", "adv-id"]) { - for (const cmd of authorAllowed) { - assert.equal(runCmd(convId, cmd).decision, "allow", `expected ${convId} allow: ${cmd}`); - } - } - - const authorDenied = [ - `git -C ${sb.outsideDir} commit -m pwn`, - `mkdir -p ${join(sb.outsideDir, "pwn")}`, - `touch ${join(sb.outsideDir, "pwn.txt")}`, - `chmod +x ${join(sb.outsideDir, "pwn.sh")}`, - `truncate -s 0 ${join(sb.outsideDir, "pwn.txt")}`, - `dd if=/dev/zero of=${join(sb.outsideDir, "pwn.bin")} count=1`, - `install README.md ${join(sb.outsideDir, "README.md")}`, - `curl -o ${join(sb.outsideDir, "pwn.txt")} https://example.com`, - `wget -P ${sb.outsideDir} https://example.com/a.txt`, - `tar -xf a.tar -C ${sb.outsideDir}`, - `unzip a.zip -d ${sb.outsideDir}`, - `rsync -a src/ ${sb.outsideDir}/`, - `find ${sb.outsideDir} -delete`, - `find ${sb.outsideDir} -exec rm {} ;`, - `node -e "require('fs').writeFileSync('${join(sb.outsideDir, "pwn.txt")}', 'x')"`, - `python3 -c "from pathlib import Path; Path('../../outside/x').write_text('x')"`, - `python3 ${outsidePy}`, - ]; - for (const convId of ["impl-id", "adv-id"]) { - for (const cmd of authorDenied) { - assert.equal(runCmd(convId, cmd).decision, "deny", `expected ${convId} deny: ${cmd}`); - } - } - - for (const sickoOk of ["git add app.mjs", "git commit -m 'strip comments'", "git status --short"]) { - assert.equal(runCmd("sicko-id", sickoOk).decision, "allow", `expected sicko allow: ${sickoOk}`); - } - for (const sickoBad of [ - "git checkout -- .", - "git restore app.mjs", - "git reset --hard HEAD", - "git clean -fd", - "git pull", - `git -C ${sb.outsideDir} status`, - "chmod +x app.mjs", - "curl -o app.mjs https://example.com", - "wget https://example.com/a.txt", - "tar -xf a.tar", - "unzip a.zip", - "rsync -a a b", - "find . -delete", - `node ${okJs}`, - `node -e "require('fs').writeFileSync('${join(slashTmpDir, "x.txt")}', 'x')"`, - `python3 -c "open('${join(slashTmpDir, "x.txt")}', 'w').write('x')"`, - ]) { - assert.equal(runCmd("sicko-id", sickoBad).decision, "deny", `expected sicko deny: ${sickoBad}`); - } - } finally { - rmSync(slashTmpDir, { recursive: true, force: true }); - sb.cleanup(); - } - }); - - test("M2+M3+T1 fixes node array literals, python Path aliases, transcript step filtering, forkStep, and swarm.json anchor", () => { - 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 coordCapsule = readFileSync(join(PLUGIN_ROOT, "roles", "coordinator.md"), "utf8"); - - writeSwarmMembers(sb.appDataDir, "coord-m", { - "ro-m": { conversation_id: "ro-m-id", role: "worker" }, - "impl-fork": { conversation_id: "impl-fork-id", role: "worker" }, - }); - - const runRo = (CommandLine) => - runGuard( - { - hookEventName: "PreToolUse", - conversationId: "ro-m-id", - cwd: sb.worktree, - toolCall: { id: "m2", name: "run_command", args: { CommandLine } }, - }, - { PSTACK_APPDATA_DIR: sb.appDataDir }, - ); - - for (const okCmd of [ - "node -e \"console.log(['arm64']); console.log(['blink']); const x = ['rm'];\"", - "node -e \"function f() { return ['rm']; }\"", - "python3 -c \"from pathlib import Path as P, PurePath as PP; print(P('.'), PP('a'))\"", - ]) { - assert.equal(runRo(okCmd).decision, "allow", `expected M2 allow: ${okCmd}`); - } - - for (const badCmd of [ - "node -e \"const fs = require('fs'); fs['rmSync']('README.md')\"", - "node -e \"require('fs')['rm']('README.md', () => {})\"", - "node -e \"const fs = require('fs'); const fn = 'rmSync'; fs[fn]('README.md')\"", - "python3 -c \"from os import remove as r; r('hooks.json')\"", - "python3 -c \"import shutil as s; s.rmtree('skills')\"", - ]) { - assert.equal(runRo(badCmd).decision, "deny", `expected M2 deny: ${badCmd}`); - } - - const readFileTranscript = join( - sb.appDataDir, - "brain", - "read-file-user-conv", - ".system_generated", - "logs", - "transcript.jsonl", - ); - writeTranscriptLines(readFileTranscript, [ - { step_index: 0, type: "USER_INPUT", content: "Read roles/coordinator.md" }, - { step_index: 1, type: "TOOL_OUTPUT", content: "# Coordinator role capsule\n..." }, - ]); - writeSwarmMembers(sb.appDataDir, "decoy-swarm", { - "ro-decoy": { conversation_id: "read-file-user-conv", role: "worker" }, - }); - assert.deepEqual( - runGuard( - { - hookEventName: "SessionStart", - conversationId: "read-file-user-conv", - transcriptPath: readFileTranscript, - }, - { PSTACK_APPDATA_DIR: sb.appDataDir }, - ), - {}, - ); - - const forkTranscript = join( - sb.appDataDir, - "brain", - "impl-fork-id", - ".system_generated", - "logs", - "transcript.jsonl", - ); - writeTranscriptLines(forkTranscript, [ - { step_index: 0, type: "USER_INPUT", content: "Help me refactor this repo" }, - { - step_index: 1, - type: "USER_INPUT", - content: "You are @impl-fork. Everything before this turn is @coordinator's memory.", - }, - ]); - const forkSessionOut = runGuard( - { - hookEventName: "SessionStart", - conversationId: "impl-fork-id", - transcriptPath: forkTranscript, - }, - { PSTACK_APPDATA_DIR: sb.appDataDir }, - ); - assert.deepEqual(forkSessionOut, { - injectSteps: [{ systemMessage: { systemMessage: agentCapsule } }], - }); - - const spannerCoordDir = join(sb.appDataDir, "brain", "spanner-coord", ".system_generated", "swarm"); - mkdirSync(spannerCoordDir, { recursive: true }); - writeFileSync( - join(spannerCoordDir, "swarm.json"), - JSON.stringify({ backend: "spanner", coordinator_conversation_id: "spanner-coord" }), - "utf8", - ); - const spannerCoordOut = runGuard( - { hookEventName: "SessionStart", conversationId: "spanner-coord" }, - { PSTACK_APPDATA_DIR: sb.appDataDir }, - ); - assert.deepEqual(spannerCoordOut, { - injectSteps: [{ systemMessage: { systemMessage: coordCapsule } }], - }); - - const spannerWorkerTranscript = join( - sb.appDataDir, - "brain", - "spanner-worker", - ".system_generated", - "logs", - "transcript.jsonl", - ); - writeTranscriptLines(spannerWorkerTranscript, [ - { step_index: 0, type: "SYSTEM_MESSAGE", content: "[swarm] new board message #1" }, - ]); - runGuard( - { - hookEventName: "SessionStart", - conversationId: "spanner-worker", - transcriptPath: spannerWorkerTranscript, - }, - { PSTACK_APPDATA_DIR: sb.appDataDir }, - ); - const nonWorkerPath = join(sb.appDataDir, "plugin_data", "agy-pstack-next", "non-worker-roots.json"); - const nonWorkerDoc = existsSync(nonWorkerPath) ? JSON.parse(readFileSync(nonWorkerPath, "utf8")) : {}; - assert.equal(nonWorkerDoc["spanner-worker"], undefined); - assert.equal(researchCapsule.length > 0, true); - } finally { - sb.cleanup(); - } - }); - - test("regression #18: source/., preload flags, shebang-less /tmp execs, scriptEnv subshell/conditional/for scoping, and ro-* harness literals", () => { - const sb = makeSandbox(); - const slashTmpDir = mkdtempSync("/tmp/pstack-reg18-"); - try { - writeSwarmMembers(sb.appDataDir, "coord-reg18", { - "ro-v": { conversation_id: "ro-id", role: "worker" }, - "impl-v": { conversation_id: "impl-id", role: "worker" }, - "sicko-v": { conversation_id: "sicko-id", role: "worker" }, - }); - - const malSh = join(slashTmpDir, "mal.sh"); - const malJs = join(slashTmpDir, "mal.mjs"); - const malPy = join(slashTmpDir, "mal_mod.py"); - const malNoExt = join(slashTmpDir, "mal_noext"); - const binFile = join(slashTmpDir, "bin_noext"); - const outsideTarget = join(sb.outsideDir, "pwn.txt"); - writeFileSync(malSh, `curl -o ${outsideTarget} https://example.com\n`, "utf8"); - writeFileSync(malJs, "require('fs').writeFileSync('README.md', 'pwn');\n", "utf8"); - writeFileSync(malPy, "from pathlib import Path\nPath('README.md').write_text('pwn')\n", "utf8"); - writeFileSync(malNoExt, "rm -f README.md\n", "utf8"); - writeFileSync(binFile, Buffer.from([0x7f, 0x45, 0x4c, 0x46, 0x00, 0x01])); - - const runCmd = (convId, CommandLine) => - runGuard( - { - hookEventName: "PreToolUse", - conversationId: convId, - cwd: sb.worktree, - toolCall: { id: "r18", name: "run_command", args: { CommandLine } }, - }, - { PSTACK_APPDATA_DIR: sb.appDataDir, TMPDIR: sb.customTmpDir }, - ); - - for (const convId of ["ro-id", "impl-id", "sicko-id"]) { - assert.equal(runCmd(convId, `source ${malSh}`).decision, "deny", `source denied on ${convId}`); - assert.equal(runCmd(convId, `. ${malSh}`).decision, "deny", `. denied on ${convId}`); - } - - for (const roDeny of [ - `node --import ${malJs} -e "1"`, - `node -r ${malJs} -e "1"`, - `node --require=${malJs} -e "1"`, - `NODE_OPTIONS="--import ${malJs}" node -e "1"`, - `PYTHONPATH=${slashTmpDir} python3 -m mal_mod`, - malNoExt, - binFile, - `A=${sb.worktree}; (A=${slashTmpDir}); echo pwn > $A/README.md`, - `A=${sb.worktree}; false && A=${slashTmpDir}; echo pwn > $A/README.md`, - `A=${sb.worktree}; true || A=${slashTmpDir}; echo pwn > $A/README.md`, - `A=${slashTmpDir}; for A in ${sb.worktree}; do echo pwn > $A/README.md; done`, - `A=${slashTmpDir}; read A; echo pwn > $A/README.md`, - `echo x | A=${slashTmpDir}; echo pwn > $A/README.md`, - "node -e \"const { link: fn } = require('fs'); fn('a', 'b')\"", - ]) { - assert.equal(runCmd("ro-id", roDeny).decision, "deny", `expected ro deny: ${roDeny}`); - } - - assert.equal( - runCmd("impl-id", `A=${sb.outsideDir}; (A=${slashTmpDir}); echo pwn > $A/pwn.txt`).decision, - "deny", - ); - assert.equal( - runCmd("impl-id", `A=${sb.outsideDir}; false && A=${slashTmpDir}; echo pwn > $A/pwn.txt`).decision, - "deny", - ); - assert.equal( - runCmd("impl-id", `A=${slashTmpDir}; for A in ${sb.outsideDir}; do echo pwn > $A/pwn.txt; done`).decision, - "deny", - ); - - for (const roAllow of [ - "python3 -c \"import os; run_dir = f'/tmp/cli-{os.getpid()}'; open(os.path.join(run_dir, 'out.txt'), 'w').write('ok')\"", - "python3 -c \"import os; run_dir = f'/tmp/cli-{os.getpid()}'; open(f'{run_dir}/out.txt', 'w').write('ok')\"", - "node -e \"const fs = require('node:fs'); const runDir = `/tmp/ui-artifacts-${Date.now()}`; fs.writeFileSync(`${runDir}/aria.json`, '{}')\"", - "node -e \"console.log(pkg['platform'], pkg['arm64'], pkg['blink'])\"", - "node -e \"const item = { from: f, link: raw }; console.log(item)\"", - ]) { - assert.equal(runCmd("ro-id", roAllow).decision, "allow", `expected ro allow: ${roAllow}`); - } - } finally { - rmSync(slashTmpDir, { recursive: true, force: true }); - sb.cleanup(); - } - }); -}); - -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 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) { - 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}`, - `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( - { - 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}`, - ); - } - } - - 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", - ); - 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(); - } - }); - - test("handles agy 1.5.9 local swarm.json anchors without invoking remote CLI or blocking non-worker-roots cache while preserving remote spanner anchors", () => { - 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"); - - const callsLog = join(sb.root, "local-vs-remote-cli-calls.jsonl"); - const mockCli = join(sb.root, "mock-swarm-cli.mjs"); - writeFileSync( - mockCli, - `#!/usr/bin/env node -import { appendFileSync } from "node:fs"; -const args = process.argv.slice(2); -appendFileSync(${JSON.stringify(callsLog)}, JSON.stringify(args) + "\\n", "utf8"); -const swarmId = args[args.length - 1]; -if (swarmId === "swm_remote_v1") { - process.stdout.write(JSON.stringify({ - swarm_id: swarmId, - members: { - coordinator: { conversation_id: "remote-v1-coord", role: "coordinator" }, - "ro-1": { conversation_id: "remote-v1-ro", role: "worker" }, - }, - }) + "\\n"); -} -`, - "utf8", - ); - chmodSync(mockCli, 0o755); - - const writeAnchor = (dirId, doc) => { - const dir = join(sb.appDataDir, "brain", dirId, ".system_generated", "swarm"); - mkdirSync(dir, { recursive: true }); - writeFileSync(join(dir, "swarm.json"), JSON.stringify(doc), "utf8"); - }; - - writeAnchor("local-full-coord", { - version: 1, - backend: "local", - swarm_id: "local-full-coord", - created_at: "2026-11-15T08:00:00.000Z", - }); - writeSwarmMembers(sb.appDataDir, "local-full-coord", { - coordinator: { conversation_id: "local-full-coord", role: "coordinator" }, - "impl-1": { conversation_id: "local-full-impl", role: "worker" }, - "ro-1": { conversation_id: "local-full-ro", role: "worker" }, - }); - - assert.deepEqual( - runGuard( - { hookEventName: "SessionStart", conversationId: "local-full-coord" }, - { PSTACK_APPDATA_DIR: sb.appDataDir, PSTACK_REMOTE_SWARM_CLI: mockCli }, - ), - { injectSteps: [{ systemMessage: { systemMessage: coordCapsule } }] }, - ); - assert.deepEqual( - runGuard( - { - hookEventName: "SessionStart", - conversationId: "local-full-impl", - rootConversationId: "local-full-coord", - }, - { PSTACK_APPDATA_DIR: sb.appDataDir, PSTACK_REMOTE_SWARM_CLI: mockCli }, - ), - { injectSteps: [{ systemMessage: { systemMessage: agentCapsule } }] }, - ); - assert.deepEqual( - runGuard( - { - hookEventName: "SessionStart", - conversationId: "local-full-ro", - rootConversationId: "local-full-coord", - }, - { PSTACK_APPDATA_DIR: sb.appDataDir, PSTACK_REMOTE_SWARM_CLI: mockCli }, - ), - { injectSteps: [{ systemMessage: { systemMessage: researchCapsule } }] }, - ); - assert.equal( - runGuard( - { - hookEventName: "PreToolUse", - conversationId: "local-full-ro", - cwd: sb.worktree, - toolCall: { id: "lr-1", name: "write_file", args: { Path: join(sb.worktree, "blocked.txt") } }, - }, - { PSTACK_APPDATA_DIR: sb.appDataDir, PSTACK_REMOTE_SWARM_CLI: mockCli }, - ).decision, - "deny", - ); - - writeAnchor("local-orphan-coord", { - version: 1, - backend: "local", - swarm_id: "local-orphan-coord", - created_at: "2026-11-15T08:01:00.000Z", - }); - writeAnchor("local-orphan-dir", { - version: 1, - backend: "local", - swarm_id: "local-orphan-coord-alias", - created_at: "2026-11-15T08:01:30.000Z", - }); - writeAnchor("plain-local-coord", { - version: 1, - backend: "local", - swarm_id: "plain-local-coord", - created_at: "2026-11-15T08:01:45.000Z", - }); - - assert.deepEqual( - runGuard( - { hookEventName: "SessionStart", conversationId: "local-orphan-coord" }, - { PSTACK_APPDATA_DIR: sb.appDataDir, PSTACK_REMOTE_SWARM_CLI: mockCli }, - ), - { injectSteps: [{ systemMessage: { systemMessage: coordCapsule } }] }, - ); - assert.deepEqual( - runGuard( - { - hookEventName: "SessionStart", - conversationId: "local-orphan-coord-alias", - rootConversationId: "local-orphan-dir", - }, - { PSTACK_APPDATA_DIR: sb.appDataDir, PSTACK_REMOTE_SWARM_CLI: mockCli }, - ), - { injectSteps: [{ systemMessage: { systemMessage: coordCapsule } }] }, - ); - assert.deepEqual( - runGuard( - { - hookEventName: "SessionStart", - conversationId: "plain-local-coord", - lastUserInput: "/swarm local plain title", - }, - { PSTACK_APPDATA_DIR: sb.appDataDir, PSTACK_REMOTE_SWARM_CLI: mockCli }, - ), - {}, - ); - assert.deepEqual( - runGuard( - { hookEventName: "SessionStart", conversationId: "unrelated-conv" }, - { PSTACK_APPDATA_DIR: sb.appDataDir, PSTACK_REMOTE_SWARM_CLI: mockCli }, - ), - {}, - ); - assert.equal(existsSync(callsLog), false, "local swarm.json must never invoke remote CLI"); - - const nonWorkersAfterLocalOrphan = existsSync(join(cacheDir, "non-worker-roots.json")) - ? JSON.parse(readFileSync(join(cacheDir, "non-worker-roots.json"), "utf8")) - : {}; - assert.equal(nonWorkersAfterLocalOrphan["unrelated-conv"], true); - - writeAnchor("remote-v1-coord", { - version: 1, - backend: "spanner", - swarm_id: "swm_remote_v1", - created_at: "2026-11-15T08:02:00.000Z", - db: "projects/p/instances/i/databases/d", - coordinator_conversation_id: "remote-v1-coord", - }); - assert.deepEqual( - runGuard( - { - hookEventName: "SessionStart", - conversationId: "remote-v1-ro", - rootConversationId: "remote-v1-coord", - }, - { PSTACK_APPDATA_DIR: sb.appDataDir, PSTACK_REMOTE_SWARM_CLI: mockCli }, - ), - { injectSteps: [{ systemMessage: { systemMessage: researchCapsule } }] }, - ); - const callsAfterRemoteResolved = readFileSync(callsLog, "utf8") - .trim() - .split("\n") - .map((line) => JSON.parse(line)); - assert.equal(callsAfterRemoteResolved.length, 1); - assert.deepEqual(callsAfterRemoteResolved[0], [ - "swarm", - "--json", - "--roster-only", - "--db", - "projects/p/instances/i/databases/d", - "swm_remote_v1", - ]); - - writeAnchor("remote-missing-coord", { - version: 1, - backend: "spanner", - swarm_id: "swm_remote_missing", - created_at: "2026-11-15T08:03:00.000Z", - coordinator_conversation_id: "remote-missing-coord", - }); - assert.deepEqual( - runGuard( - { - hookEventName: "SessionStart", - conversationId: "remote-unresolved-conv", - rootConversationId: "remote-missing-coord", - }, - { PSTACK_APPDATA_DIR: sb.appDataDir, PSTACK_REMOTE_SWARM_CLI: mockCli }, ), {}, ); - const nonWorkersAfterRemoteUnresolved = existsSync(join(cacheDir, "non-worker-roots.json")) - ? JSON.parse(readFileSync(join(cacheDir, "non-worker-roots.json"), "utf8")) - : {}; - assert.equal(nonWorkersAfterRemoteUnresolved["remote-unresolved-conv"], undefined); - } finally { - sb.cleanup(); - } - }); - - test("allows multi-argument Python str.replace in inline scripts while blocking 1-arg Path.replace and escaping rename or replace targets", () => { - const sb = makeSandbox(); - try { - writeSwarmMembers(sb.appDataDir, "coord-py-replace", { - coordinator: { conversation_id: "coord-py-replace", role: "coordinator" }, - "ro-py": { conversation_id: "ro-py-id", role: "worker" }, - "impl-py": { conversation_id: "impl-py-id", role: "worker" }, - "adv-py": { conversation_id: "adv-py-id", role: "worker" }, - "sicko-py": { conversation_id: "sicko-py-id", role: "worker" }, - }); - - const runPyCmd = (convId, CommandLine) => - runGuard( - { - hookEventName: "PreToolUse", - conversationId: convId, - rootConversationId: "coord-py-replace", - cwd: sb.worktree, - toolCall: { id: "py-rep", name: "run_command", args: { CommandLine } }, - }, - { PSTACK_APPDATA_DIR: sb.appDataDir, TMPDIR: sb.customTmpDir }, - ); - - const roAllowed = [ - `python3 -c "print('hello'.replace('e', 'a'))"`, - `python3 -c "s = 'foobar'; print(s.replace('foo', 'bar'))"`, - `python3 -c "s = 'aaa'; print(s.replace('a', 'b', 1))"`, - `python3 -c "s = 'aaa'; print(s.replace('a', 'b', count=1))"`, - `python3 -c "s = 'aaa'; print(s.replace('a', 'b',))"`, - `python3 -c "from pathlib import Path; print(Path('README.md').read_text().replace('foo', 'bar'))"`, - `python3 -c "import os; print(os.environ.get('PATH', '').replace('/usr', '/opt'))"`, - `python3 -c "from pathlib import Path; Path('/tmp/src').replace('/tmp/dst')"`, - `python3 -c "from pathlib import Path; Path('/tmp/src').rename('/tmp/dst')"`, - `python3 -c "from pathlib import Path; Path('/tmp/src').replace(target='/tmp/dst')"`, - `python3 -c "from pathlib import Path; Path('/tmp/src').rename(target='/tmp/dst')"`, - ]; - for (const cmd of roAllowed) { - assert.equal(runPyCmd("ro-py-id", cmd).decision, "allow", `expected ro allow for ${cmd}`); - } - - const roDenied = [ - `python3 -c "p.replace('/Users/repo/out')"`, - `python3 -c "p.replace('/Users/repo/out',)"`, - `python3 -c "p.replace(target='/Users/repo/out')"`, - `python3 -c "p.replace(target='/Users/repo/out',)"`, - `python3 -c "p.replace(*['/Users/repo/out'])"`, - `python3 -c "p.replace('/Users/repo/out', *[])"`, - `python3 -c "p.replace(**{'target': '/Users/repo/out'})"`, - `python3 -c "from pathlib import Path; Path('/tmp/src').replace('/Users/repo/dst')"`, - `python3 -c "from pathlib import Path; Path('/tmp/src').rename('/Users/repo/dst')"`, - `python3 -c "from pathlib import Path; Path('/tmp/src').replace(target='/Users/repo/dst')"`, - `python3 -c "from pathlib import Path; Path('/tmp/src').rename(target='/Users/repo/dst')"`, - `python3 -c "from pathlib import Path; Path('/tmp/src').replace('${join(sb.worktree, "dst")}')"`, - `python3 -c "from pathlib import Path; Path('/tmp/src').rename('${join(sb.worktree, "dst")}')"`, - `python3 -c "from pathlib import Path; Path('/tmp/src').replace('/tmp')"`, - `python3 -c "from pathlib import Path; Path('/tmp/src').rename('/tmp')"`, - `python3 -c "import os; os.replace('/tmp/src', '/Users/repo/dst')"`, - `python3 -c "import os; os.rename('/tmp/src', '/Users/repo/dst')"`, - `python3 -c "import os; os.replace('/tmp/src', '/tmp')"`, - `python3 -c "from pathlib import Path; print('a'.replace('a', str(Path('README.md').write_text('x'))))"`, - ]; - for (const cmd of roDenied) { - assert.equal(runPyCmd("ro-py-id", cmd).decision, "deny", `expected ro deny for ${cmd}`); - } - - for (const convId of ["impl-py-id", "adv-py-id"]) { - assert.equal( - runPyCmd(convId, `python3 -c "s = 'cfg'; print(s.replace('/etc/old', '/etc/new'))"`).decision, - "allow", - ); - for (const badAuthorCmd of [ - `python3 -c "from pathlib import Path; Path('/tmp/src').replace('${join(sb.outsideDir, "dst")}')"`, - `python3 -c "from pathlib import Path; Path('/tmp/src').rename('${join(sb.outsideDir, "dst")}')"`, - `python3 -c "p.replace('${join(sb.outsideDir, "dst")}')"`, - `python3 -c "from pathlib import Path; Path('/tmp/src').replace('${sb.worktree}')"`, - ]) { - assert.equal(runPyCmd(convId, badAuthorCmd).decision, "deny", `expected ${convId} deny for ${badAuthorCmd}`); - } - } - - assert.equal( - runPyCmd("sicko-py-id", `python3 -c "print('hello'.replace('e', 'a'))"`).decision, - "allow", - ); - assert.equal( - runPyCmd("sicko-py-id", `python3 -c "p.replace('/tmp/out')"`).decision, - "deny", - ); - } finally { - sb.cleanup(); - } - }); - - test("blocks unbound Python Path classes, parenthesized or aliased os and Path receivers, and type or __class__ escapes across all worker roles", () => { - const sb = makeSandbox(); - try { - writeSwarmMembers(sb.appDataDir, "coord-py-unbound", { - coordinator: { conversation_id: "coord-py-unbound", role: "coordinator" }, - "ro-u": { conversation_id: "ro-u-id", role: "worker" }, - "impl-u": { conversation_id: "impl-u-id", role: "worker" }, - "adv-u": { conversation_id: "adv-u-id", role: "worker" }, - "sicko-u": { conversation_id: "sicko-u-id", role: "worker" }, - }); - - const runRolePy = (convId, CommandLine) => - runGuard( - { - hookEventName: "PreToolUse", - conversationId: convId, - rootConversationId: "coord-py-unbound", - cwd: sb.worktree, - toolCall: { id: "py-unb", name: "run_command", args: { CommandLine } }, - }, - { PSTACK_APPDATA_DIR: sb.appDataDir, TMPDIR: sb.customTmpDir }, - ); - - const outsideDst = join(sb.outsideDir, "dst"); - const outsideFile = join(sb.outsideDir, "f"); - - const deniedForAllRoles = [ - `python3 -c "from pathlib import Path; Path.replace(Path('/tmp/src'), '${outsideDst}')"`, - `python3 -c "from pathlib import Path; Path.replace(Path('/tmp/src'), '/Users/repo/dst')"`, - `python3 -c "import pathlib; pathlib.Path.replace(pathlib.Path('/tmp/src'), '${outsideDst}')"`, - `python3 -c "from pathlib import PosixPath; PosixPath.replace(PosixPath('/tmp/src'), '${outsideDst}')"`, - `python3 -c "from pathlib import PurePath; PurePath.replace(PurePath('/tmp/src'), '${outsideDst}')"`, - `python3 -c "from pathlib import WindowsPath; WindowsPath.replace(WindowsPath('/tmp/src'), '${outsideDst}')"`, - `python3 -c "from pathlib import PurePosixPath; PurePosixPath.replace(PurePosixPath('/tmp/src'), '${outsideDst}')"`, - `python3 -c "from pathlib import PureWindowsPath; PureWindowsPath.replace(PureWindowsPath('/tmp/src'), '${outsideDst}')"`, - `python3 -c "from pathlib import Path; Path.rename(Path('/tmp/src'), '${outsideDst}')"`, - `python3 -c "from pathlib import Path; Path.write_text(Path('${outsideFile}'), 'x')"`, - `python3 -c "from pathlib import Path; (Path).replace(Path('/tmp/src'), '${outsideDst}')"`, - `python3 -c "import pathlib; ((pathlib).Path).replace(pathlib.Path('/tmp/src'), '${outsideDst}')"`, - `python3 -c "import os; (os).replace('/tmp/src', '${outsideDst}')"`, - `python3 -c "import os; (os).rename('/tmp/src', '${outsideDst}')"`, - `python3 -c "import os; (os).replace('${outsideDst}', '/tmp/dst')"`, - `python3 -c "import os; (os).rename('${outsideDst}', '/tmp/dst')"`, - `python3 -c "import os; m = os; m.replace('/tmp/src', '${outsideDst}')"`, - `python3 -c "import os; m = os; m.rename('/tmp/src', '${outsideDst}')"`, - `python3 -c "import os; m = os; m.replace('${outsideDst}', '/tmp/dst')"`, - `python3 -c "import shutil; m = shutil; m.move('/tmp/src', '${outsideDst}')"`, - `python3 -c "from pathlib import Path; P = Path; P.replace(Path('/tmp/src'), '${outsideDst}')"`, - `python3 -c "from pathlib import Path; P = Path; P.write_text(Path('${outsideFile}'), 'x')"`, - `python3 -c "from pathlib import Path as P; P.replace(P('/tmp/src'), '${outsideDst}')"`, - `python3 -c "from pathlib import Path; p = Path('/tmp/src'); p.__class__.replace(p, '${outsideDst}')"`, - `python3 -c "from pathlib import Path; p = Path('/tmp/src'); type(p).replace(p, '${outsideDst}')"`, - `python3 -c "from pathlib import Path; p = Path('/tmp/src'); C = p.__class__; C.replace(p, '${outsideDst}')"`, - `python3 -c "from pathlib import Path; p = Path('/tmp/src'); T = type(p); T.replace(p, '${outsideDst}')"`, - `python3 -c "import sys, os; sys.modules.get('os').replace('/tmp/src', '${outsideDst}')"`, - ]; - - for (const convId of ["ro-u-id", "impl-u-id", "adv-u-id", "sicko-u-id"]) { - for (const cmd of deniedForAllRoles) { - assert.equal(runRolePy(convId, cmd).decision, "deny", `expected ${convId} deny for ${cmd}`); - } - } - - for (const convId of ["ro-u-id", "impl-u-id", "adv-u-id"]) { - assert.equal( - runRolePy(convId, `python3 -c "import os; (os).replace('/tmp/src', '/tmp/dst')"`).decision, - "allow", - ); - assert.equal( - runRolePy(convId, `python3 -c "import os; m = os; m.rename('/tmp/src', '/tmp/dst')"`).decision, - "allow", - ); - } - assert.equal( - runRolePy("sicko-u-id", `python3 -c "import os; (os).replace('/tmp/src', '/tmp/dst')"`).decision, - "deny", - ); - - const legitStrReplaceCmds = [ - `python3 -c "print('hello'.replace('e', 'a'))"`, - `python3 -c "print(('hello').replace('e', 'a'))"`, - `python3 -c "name = 'world'; print(f'hi {name}'.replace('hi', 'hello'))"`, - `python3 -c "from pathlib import Path; print(Path('README.md').read_text().replace('a', 'b'))"`, - `python3 -c "s = ' foo '; print(s.strip().replace('foo', 'bar'))"`, - `python3 -c "s = 'FOO'; print(s.lower().replace('foo', 'bar'))"`, - `python3 -c "s = 'foo'; print(s.upper().replace('FOO', 'BAR'))"`, - `python3 -c "raw = b'foo'; print(raw.decode('utf-8').replace('foo', 'bar'))"`, - `python3 -c "print('hello {}'.format('world').replace('world', 'swarm'))"`, - `python3 -c "items = ['a', 'b']; print(','.join(items).replace(',', ';'))"`, - `python3 -c "import os; print(os.environ.get('PATH', '').replace('/usr', '/opt'))"`, - `python3 -c "d = {'k': 'val'}; print(d.get('k', '').replace('val', 'ok'))"`, - `python3 -c "print(str(123).replace('2', '9'))"`, - `python3 -c "s = 'foobar'; print(s.replace('foo', 'bar').replace('bar', 'baz'))"`, - ]; - - for (const convId of ["ro-u-id", "impl-u-id", "adv-u-id", "sicko-u-id"]) { - for (const cmd of legitStrReplaceCmds) { - assert.equal(runRolePy(convId, cmd).decision, "allow", `expected ${convId} allow for ${cmd}`); - } - } - } finally { - sb.cleanup(); - } - }); - - test("blocks Python Path subclasses, comment and continuation dot obfuscation, reflection dispatch, and aliased os or shutil escapes across worker roles", () => { - const sb = makeSandbox(); - try { - writeSwarmMembers(sb.appDataDir, "coord-py-struct", { - coordinator: { conversation_id: "coord-py-struct", role: "coordinator" }, - "ro-s": { conversation_id: "ro-s-id", role: "worker" }, - "impl-s": { conversation_id: "impl-s-id", role: "worker" }, - "adv-s": { conversation_id: "adv-s-id", role: "worker" }, - "sicko-s": { conversation_id: "sicko-s-id", role: "worker" }, - }); - - const runRolePy = (convId, CommandLine) => - runGuard( - { - hookEventName: "PreToolUse", - conversationId: convId, - rootConversationId: "coord-py-struct", - cwd: sb.worktree, - toolCall: { id: "py-str", name: "run_command", args: { CommandLine } }, - }, - { PSTACK_APPDATA_DIR: sb.appDataDir, TMPDIR: sb.customTmpDir }, - ); - - const outsideDst = join(sb.outsideDir, "dst"); - const outsideFile = join(sb.outsideDir, "f"); - const worktreeDst = join(sb.worktree, "dst"); - - const deniedForAllRoles = [ - `python3 -c "from pathlib import Path\nclass S(Path):\n pass\nS.replace(Path('/tmp/src'), '${outsideDst}')"`, - `python3 -c "from pathlib import PosixPath\nclass S(PosixPath):\n pass\nS.replace(PosixPath('/tmp/src'), '${outsideDst}')"`, - `python3 -c "import pathlib\nclass S(pathlib.Path):\n pass\nS.replace(pathlib.Path('/tmp/src'), '${outsideDst}')"`, - `python3 -c "from pathlib import PosixPath\nclass S1(PosixPath):\n pass\nclass S2(S1):\n pass\nS2.replace(PosixPath('/tmp/src'), '${outsideDst}')"`, - `python3 -c "from pathlib import PosixPath\nclass S1(PosixPath):\n pass\nclass S2(S1):\n pass\nS2('/tmp/src').replace('${outsideDst}')"`, - `python3 -c "from pathlib import Path\nclass S1(Path):\n pass\nclass S2(S1):\n pass\nS2('${outsideFile}').write_text('x')"`, - `python3 -c "from pathlib import Path\n(Path.#c\nreplace)(Path('/tmp/src'), '${outsideDst}')"`, - `python3 -c "from pathlib import Path\n(Path('${outsideFile}').#c\nwrite_text)('x')"`, - `python3 -c "import os\n(os.#c\nreplace)('/tmp/src', '${outsideDst}')"`, - `python3 -c 'from pathlib import Path\nPath.\\\nreplace(Path("/tmp/src"), "${outsideDst}")'`, - `python3 -c 'from pathlib import Path\nPath("${outsideFile}").\\\nwrite_text("x")'`, - `python3 -c 'import os\nos.\\\nreplace("/tmp/src", "${outsideDst}")'`, - `python3 -c "from pathlib import Path; (Path.replace)(Path('/tmp/src'), '${outsideDst}')"`, - `python3 -c "import os; (os.replace)('/tmp/src', '${outsideDst}')"`, - `python3 -c "import os; ((os.replace))('/tmp/src', '${outsideDst}')"`, - `python3 -c "import os\n((os.#c\nreplace))('/tmp/src', '${outsideDst}')"`, - `python3 -c "from pathlib import Path; (Path('${outsideFile}').write_text)('x')"`, - `python3 -c 'from pathlib import Path\nPath.replace\\\n(Path("/tmp/src"), "${outsideDst}")'`, - `python3 -c "import os\n(os.replace #c\n)('/tmp/src', '${outsideDst}')"`, - `python3 -c "import os; getattr(os, 'replace')('/tmp/src', '${outsideDst}')"`, - `python3 -c "from pathlib import Path; getattr(Path, 'replace')(Path('/tmp/src'), '${outsideDst}')"`, - `python3 -c "import os; setattr(os, 'x', 1)"`, - `python3 -c "import os; delattr(os, 'x')"`, - `python3 -c "import os; vars(os)['replace']('/tmp/src', '${outsideDst}')"`, - `python3 -c "from pathlib import Path; globals()['Path'].replace(Path('/tmp/src'), '${outsideDst}')"`, - `python3 -c "from pathlib import Path; locals()['Path'].replace(Path('/tmp/src'), '${outsideDst}')"`, - `python3 -c "import os; os.__dict__['replace']('/tmp/src', '${outsideDst}')"`, - `python3 -c "from pathlib import Path; Path.__dict__['replace'](Path('/tmp/src'), '${outsideDst}')"`, - `python3 -c "import os; os.__getattribute__('replace')('/tmp/src', '${outsideDst}')"`, - `python3 -c "from pathlib import Path; p = Path('/tmp/src'); p.__getattr__('replace')('${outsideDst}')"`, - `python3 -c "from pathlib import Path; Path.__subclasses__()[0].replace(Path('/tmp/src'), '${outsideDst}')"`, - `python3 -c "from pathlib import Path; Path.__mro__[0].replace(Path('/tmp/src'), '${outsideDst}')"`, - `python3 -c "from pathlib import PosixPath; PosixPath.__bases__[0].replace(PosixPath('/tmp/src'), '${outsideDst}')"`, - `python3 -c "from pathlib import PosixPath; PosixPath.__base__.replace(PosixPath('/tmp/src'), '${outsideDst}')"`, - `python3 -c "import operator; from pathlib import Path; operator.methodcaller('replace', '${outsideDst}')(Path('/tmp/src'))"`, - `python3 -c "import operator, os; operator.attrgetter('replace')(os)('/tmp/src', '${outsideDst}')"`, - `python3 -c "from operator import methodcaller; from pathlib import Path; methodcaller('replace', '${outsideDst}')(Path('/tmp/src'))"`, - `python3 -c "from operator import attrgetter; import os; attrgetter('replace')(os)('/tmp/src', '${outsideDst}')"`, - `python3 -c "from os import replace as r; r('/tmp/src', '${outsideDst}')"`, - `python3 -c "from os import replace as r; r('${outsideDst}', '/tmp/dst')"`, - `python3 -c "from os import rename as r; r('/tmp/src', '${outsideDst}')"`, - `python3 -c "from posix import replace as r; r('/tmp/src', '${outsideDst}')"`, - `python3 -c "from shutil import move as mv; mv('/tmp/src', '${outsideDst}')"`, - `python3 -c "from shutil import copy as cp; cp('/tmp/src', '${outsideDst}')"`, - `python3 -c "from os import (\n replace as r,\n)\nr('/tmp/src', '${outsideDst}')"`, - `python3 -c "import os; r = os.replace; r('/tmp/src', '/tmp/dst')"`, - `python3 -c "import os; r = os.replace; r('/tmp/src', '${outsideDst}')"`, - `python3 -c "from pathlib import Path; p = Path('/tmp/a'); f = p.write_text; f('x')"`, - `python3 -c "from pathlib import Path; p = Path('${outsideFile}'); f = p.write_text; f('x')"`, - `python3 -c "from pathlib import Path; p = Path('/tmp/src'); f = p.replace; f('${outsideDst}')"`, - ]; - - for (const convId of ["ro-s-id", "impl-s-id", "adv-s-id", "sicko-s-id"]) { - for (const cmd of deniedForAllRoles) { - assert.equal(runRolePy(convId, cmd).decision, "deny", `expected ${convId} deny for ${cmd}`); - } - } - - for (const convId of ["ro-s-id", "impl-s-id", "adv-s-id"]) { - assert.equal( - runRolePy(convId, `python3 -c "from os import replace as r; r('/tmp/src', '/tmp/dst')"`).decision, - "allow", - ); - assert.equal( - runRolePy(convId, `python3 -c "from posix import rename as rn; rn('/tmp/src', '/tmp/dst')"`).decision, - "allow", - ); - assert.equal( - runRolePy(convId, `python3 -c "from shutil import move as mv; mv('/tmp/src', '/tmp/dst')"`).decision, - "allow", - ); - assert.equal( - runRolePy(convId, `python3 -c "from shutil import copy as cp; cp('/tmp/src', '/tmp/dst')"`).decision, - "allow", - ); - } - - assert.equal( - runRolePy("ro-s-id", `python3 -c "from os import replace as r; r('/tmp/src', '${worktreeDst}')"`).decision, - "deny", - ); - for (const convId of ["impl-s-id", "adv-s-id"]) { - assert.equal( - runRolePy(convId, `python3 -c "from os import replace as r; r('/tmp/src', '${worktreeDst}')"`).decision, - "allow", - ); - } - for (const cmd of [ - `python3 -c "from os import replace as r; r('/tmp/src', '/tmp/dst')"`, - `python3 -c "from shutil import copy as cp; cp('/tmp/src', '/tmp/dst')"`, - ]) { - assert.equal(runRolePy("sicko-s-id", cmd).decision, "deny"); - } - - const legitReadOnlySnippets = [ - `python3 -c "# inspect string\ns = 'hello # world'\n# second comment\nprint(s.replace('hello', 'hi'))"`, - `python3 -c 's = "alpha beta"\nprint(s.\\\nreplace("alpha", "gamma"))'`, - `python3 -c "s = 'getattr __dict__ vars globals locals methodcaller attrgetter'\nprint(s.replace('getattr', 'safe'))"`, - `python3 -c "s = '(os.replace) and f = os.replace'\n# harmless comment mentioning getattr and __dict__\nprint((s.replace)('os.replace', 'noop'))"`, - ]; - - for (const convId of ["ro-s-id", "impl-s-id", "adv-s-id", "sicko-s-id"]) { - for (const cmd of legitReadOnlySnippets) { - assert.equal(runRolePy(convId, cmd).decision, "allow", `expected ${convId} allow for ${cmd}`); - } - } - } finally { - sb.cleanup(); - } - }); - - test("blocks f-string and t-string interpolation escapes and container, conditional, boolean, or lambda wrapped Path and FS receivers across worker roles", () => { - const sb = makeSandbox(); - try { - writeSwarmMembers(sb.appDataDir, "coord-py-fstr", { - coordinator: { conversation_id: "coord-py-fstr", role: "coordinator" }, - "ro-f": { conversation_id: "ro-f-id", role: "worker" }, - "impl-f": { conversation_id: "impl-f-id", role: "worker" }, - "adv-f": { conversation_id: "adv-f-id", role: "worker" }, - "sicko-f": { conversation_id: "sicko-f-id", role: "worker" }, - }); - - const runRolePy = (convId, CommandLine) => - runGuard( - { - hookEventName: "PreToolUse", - conversationId: convId, - rootConversationId: "coord-py-fstr", - cwd: sb.worktree, - toolCall: { id: "py-fstr", name: "run_command", args: { CommandLine } }, - }, - { PSTACK_APPDATA_DIR: sb.appDataDir, TMPDIR: sb.customTmpDir }, - ); - - const outsideDst = join(sb.outsideDir, "dst"); - const outsideFile = join(sb.outsideDir, "f"); - const worktreeFile = join(sb.worktree, "ok.txt"); - - const deniedForAllRoles = [ - `python3 -c 'from pathlib import Path; f"{Path.replace(Path("/tmp/src"), "${outsideDst}")}"'`, - `python3 -c 'from pathlib import Path; t"{Path.replace(Path("/tmp/src"), "${outsideDst}")}"'`, - `python3 -c 'from pathlib import Path; f"{(Path.#c\nreplace)(Path("/tmp/src"), "${outsideDst}")}"'`, - `python3 -c 'from pathlib import Path; f"""{(Path.#c\nreplace)(Path("/tmp/src"), "${outsideDst}")}"""'`, - `python3 -c 'from pathlib import Path; f"""{Path("${outsideFile}").write_text("x")}"""'`, - `python3 -c 'from pathlib import Path; f"{Path("${outsideFile}").write_text("x")}"'`, - `python3 -c 'from pathlib import Path; f"outer {f"{Path.replace(Path("/tmp/src"), "${outsideDst}")}"} end"'`, - `python3 -c 'from pathlib import Path; f"outer {f"{Path("${outsideFile}").write_text("x")}"} end"'`, - `python3 -c 'import os; f"{[os][0].replace("/tmp/src", "${outsideDst}")}"'`, - `python3 -c 'import os; f"{[os][0].remove("${outsideFile}")}"'`, - `python3 -c "from pathlib import Path; [Path][0].write_text(Path('${outsideFile}'), 'x')"`, - `python3 -c "from pathlib import Path; [Path][0].replace(Path('/tmp/src'), '${outsideDst}')"`, - `python3 -c "import os; [os][0].replace('/tmp/src', '${outsideDst}')"`, - `python3 -c "import os; [os][0].remove('${outsideFile}')"`, - `python3 -c "import shutil; [shutil][0].rmtree('${sb.outsideDir}')"`, - `python3 -c "from pathlib import Path; (Path if 1 else Path).write_text(Path('${outsideFile}'), 'x')"`, - `python3 -c "from pathlib import Path; (Path if 1 else Path).replace(Path('/tmp/src'), '${outsideDst}')"`, - `python3 -c "from pathlib import Path; (None or Path).write_text(Path('${outsideFile}'), 'x')"`, - `python3 -c "import os; (None or os).replace('/tmp/src', '${outsideDst}')"`, - `python3 -c "import os; (None or os).remove('${outsideFile}')"`, - `python3 -c "from pathlib import Path; (lambda: Path)().write_text(Path('${outsideFile}'), 'x')"`, - `python3 -c "from pathlib import Path; (lambda: Path)().replace(Path('/tmp/src'), '${outsideDst}')"`, - `python3 -c "import os; (lambda: os)().replace('/tmp/src', '${outsideDst}')"`, - `python3 -c "import os; (lambda: os)().remove('${outsideFile}')"`, - `python3 -c "from pathlib import Path\ndef g():\n return Path\ng().write_text(Path('${outsideFile}'), 'x')"`, - `python3 -c "from pathlib import Path\ndef g():\n return Path\np = Path('${outsideFile}')\ng().write_text(p, 'x')"`, - ]; - - for (const convId of ["ro-f-id", "impl-f-id", "adv-f-id", "sicko-f-id"]) { - for (const cmd of deniedForAllRoles) { - assert.equal(runRolePy(convId, cmd).decision, "deny", `expected ${convId} deny for ${cmd}`); - } - } - - const legitFStringSnippets = [ - `python3 -c "name = 'world'; print(f'hi {name}'.replace('hi', 'hello'))"`, - `python3 -c "s = 'alpha'; print(f'{s.replace(\"a\", \"b\")}')"`, - `python3 -c 's = "alpha"; print(f"outer {f"{s.replace("a", "b")}"} end")'`, - `python3 -c "items = ['a', 'b']; print(','.join(items).replace(',', ';'))"`, - ]; - - for (const convId of ["ro-f-id", "impl-f-id", "adv-f-id", "sicko-f-id"]) { - for (const cmd of legitFStringSnippets) { - assert.equal(runRolePy(convId, cmd).decision, "allow", `expected ${convId} allow for ${cmd}`); - } - } - - for (const convId of ["impl-f-id", "adv-f-id"]) { - assert.equal( - runRolePy( - convId, - `python3 -c "import os; from pathlib import Path; Path(os.path.join('${sb.worktree}', 'ok.txt')).write_text('ok')"`, - ).decision, - "allow", - ); - assert.equal( - runRolePy(convId, `python3 -c "from pathlib import Path; p = Path('${worktreeFile}'); p.write_text('ok')"`).decision, - "allow", - ); - } } finally { sb.cleanup(); } diff --git a/roles/comment-sicko.md b/roles/comment-sicko.md index ab0ebc8..35f3f72 100644 --- a/roles/comment-sicko.md +++ b/roles/comment-sicko.md @@ -15,15 +15,16 @@ guilty symbols for root-cause structural repair. - **Strict file scope.** Audit the exact files named in your brief. When no file list is provided, audit the current diff against `main` inside your assigned `share` worktree. -- **Enforced tool leash.** The guard hook confines `edit_file`, `git add`, and - `git commit` to your `cwd` worktree and blocks `write_file`, shell file - redirects outside `/dev/null`, mutating filesystem or archive commands (`cp`, - `mv`, `rm`, `touch`, `truncate`, `dd`, `patch`, `sed -i`, `perl -i`, `curl`, - `wget`, `tar`, `unzip`, `rsync`, `find`, `chmod`), temp scripts, mutating - inline `node` or `python` calls, file-restoring or remote `git` subcommands - (`checkout`, `restore`, `reset`, `clean`, `push`), `run_workflow`, and legacy - subagent tools. Native swarm tools (`swarm`, `post_message`, `read_board`, - `swarm_wait`, `schedule`, and `manage_task`) remain unrestricted. +- **Enforced tool leash.** The guard hook confines `edit_file` to your `cwd` + worktree outside `.system_generated`, blocks `write_file`, blocks `git push` + and file-restoring or history-rewriting `git` subcommands (`pull`, `fetch`, + `checkout`, `switch`, `restore`, `reset`, `clean`, `rebase`, `merge`, + `cherry-pick`, `revert`, `stash`, `worktree`, `init`, `clone`, `am`, `apply`, + `rm`, `mv`), blocks mutating `gh` commands, blocks `run_workflow` and legacy + subagent tools except `invoke_subagent` targeting `image-generator`, and + checks `git status` on `Stop` to reject untracked or deleted files. Native + swarm tools (`swarm`, `post_message`, `read_board`, `swarm_wait`, `schedule`, + and `manage_task`) remain unrestricted. - **Comments only, zero logic edits.** Delete unwanted comments cleanly with `edit_file` while keeping surrounding formatting intact. Never add, modify, rename, or delete executable statements, types, imports, or test assertions. diff --git a/roles/coordinator.md b/roles/coordinator.md index cb34264..54332b1 100644 --- a/roles/coordinator.md +++ b/roles/coordinator.md @@ -4,8 +4,8 @@ You are the swarm coordinator in Swarm-Centric Pstack v2. You own goal framing, topology selection, worker roster sizing, disjoint worktree boundaries, evidence judgment on the message board, branch integration, and the final user reply. Technical file sweeps, code edits, reproductions, and broad explorations belong -to workers on the native swarm board. Never call legacy subagent tools or -`run_workflow`. +to workers on the native swarm board. Never call \`run_workflow\` or legacy +subagent tools except \`invoke_subagent\` targeting \`image-generator\`. ## First response and goal framing @@ -22,30 +22,46 @@ one-line edit or an inline plain-language restatement (`/bro` or ## Roster prefixes and hook contract -Name every worker with its enforced prefix so `hooks/guard.mjs` injects the -matching role capsule and enforces its runtime tool boundaries. +Coordinator activation triggers only on leading swarm-orchestrating slash +commands (`/pstack`, `/understand`, `/crucible`, `/interrogate`, `/reflect`, +`/verify-gen`, or `/ketchup` without `--plain`) or active swarm rosters in +`members.json` or `swarm.json`. Standalone inline skills (`/bro`, +`/technical-writing`, `/setup-pstack`, `/statechart`, `/control-ui`, +`/control-cli`, `/make-bot-ui`, and `/ketchup --plain`), plain `/swarm` runs +without pstack worker prefixes, and mid-sentence prose mentions stay unmanaged. +`hooks/guard.mjs` stores per-conversation capsule state under +`/plugin_data/agy-pstack-next/capsules/`. Across managed roles, +the guard blocks `run_workflow`, `define_subagent`, `manage_subagents`, +`send_message`, and `invoke_subagent` except when `invoke_subagent` targets +`image-generator`. Name every worker with its enforced prefix so +`hooks/guard.mjs` injects the matching role capsule and enforces its structural +tool boundaries without regex shell parsing or OS sandboxing. - **Authoring workers (`impl-*`, `cand-*`, `lead-*`).** Pass `workspace` set to `"share"` so each author edits inside an isolated git worktree. Authors write features, bug fixes, refactors, candidate prototypes, and area integrations. - The guard confines edits and shell file targets to the worktree, conversation - artifact directory, and canonical temp roots (`/tmp`, `/private/tmp`, and - `TMPDIR`), and blocks `git push` unless explicitly granted `PSTACK_ALLOW_PUSH=1`. + The guard confines `edit_file` and `write_file` paths to the `cwd` worktree, + conversation artifact directory outside `.system_generated`, and canonical + temp roots (`/tmp`, `/private/tmp`, and `TMPDIR`), and blocks `git push` + unless granted `PSTACK_ALLOW_PUSH=1`. - **Read-only specialists (`ro-*`, `verifier`, `verifier-*`, `*-verifier`, `verify-*`).** Pass `workspace` set to `"inherit"`. Read-only workers run mechanism walkthroughs, historical provenance searches, blast-radius maps, benchmark baselines, blind evaluations, and independent verification gates. The guard - allows ephemeral scratch writes inside canonical temp roots while blocking - repository mutations, non-temp shell writes, inline script writes outside temp - roots, and mutating MCP calls. + blocks `edit_file`, restricts `write_file` to canonical temp roots and + allowed screenshot image files in the worker's own brain directory outside + `.system_generated`, blocks mutating `git`, `gh`, and MCP calls, and runs a + turn-end `Stop` hook `git status` cleanliness check. - **Adversarial hunters (`adv-*`).** Pass `workspace` set to `"share"`. Adversaries write executable exploit tests and reproduce subtle edge cases - inside their confined worktree or canonical temp roots. They can never push. + inside their confined worktree, conversation artifact directory, or canonical + temp roots. They can never run `git push` or mutating `gh` commands. - **Comment surgeons (`sicko-*`).** Pass `workspace` set to `"share"`. Comment - surgeons delete narration and workaround excuses using `edit_file` only, - flagging guilty symbols as `MUST KILL` without altering executable code. They - cannot call `write_file`, redirect shell output to files, run mutating - filesystem commands, or push. + surgeons delete narration and workaround excuses using `edit_file` inside the + `cwd` worktree only, flagging guilty symbols as `MUST KILL` without altering + executable code. The guard blocks `write_file`, `git push`, file-restoring or + history-rewriting `git` subcommands, and mutating `gh` commands, and runs a + turn-end `Stop` hook check rejecting untracked or deleted files. - **Built-in support (`monitor`, `narrator`).** Spawn these only when their corresponding built-in skills exist in your active catalog, and skip `narrator` when `swarm_pane` is in `` unless the user asks for diff --git a/roles/poteto-agent.md b/roles/poteto-agent.md index 35555bb..a521479 100644 --- a/roles/poteto-agent.md +++ b/roles/poteto-agent.md @@ -8,23 +8,23 @@ runtime evidence on the swarm message board. ## Ownership and runtime boundaries - **Stay inside your confined worktree.** The guard hook enforces strict - `realpath` confinement on `edit_file`, `write_file`, shell output redirects, - and mutating filesystem commands (`cp`, `mv`, `ln`, `rm`, `patch`, `sed -i`). - Write only inside your `cwd` worktree, conversation artifact directory, or - canonical temp roots (`/tmp`, `/private/tmp`, and `TMPDIR`), and never mutate - sibling worktrees or parent repositories via relative paths or symlinks. - Read-only inspection and cross-worktree donor imports (`git fetch - ` and read-only `git -C ` status, diff, or log checks) remain - allowed for warm `fork` and synthesis handoffs. + `realpath` confinement on `edit_file` and `write_file` inside your `cwd` + worktree, your conversation artifact directory outside `.system_generated`, + and canonical temp roots (`/tmp`, `/private/tmp`, and `TMPDIR`). Never mutate + sibling worktrees or parent repositories, and never write outside those + boundaries. Read-only inspection and cross-worktree donor imports + (`git fetch ` and read-only `git -C ` status, + diff, or log checks) remain allowed for warm `fork` and synthesis handoffs. - **Respect file boundaries.** Touch only the files or directories assigned in your brief. Leave out-of-scope deletions and cross-slice merges to the integration shepherd or coordinator. - **Coordinate on native swarm, never legacy subagents.** Legacy subagent tools - and `run_workflow` are hard-blocked across managed swarm roles, while native - swarm tools (`swarm`, `post_message`, `read_board`, `swarm_wait`, `schedule`, - and `manage_task`) remain unrestricted. Spawn helper workers via `swarm` `add` - (passing warm `fork` when carrying context forward, landing any `share` helper - commits before calling `kill` on your own helpers, and using `model` for quota + (except `invoke_subagent` targeting `image-generator`) and `run_workflow` are + hard-blocked across managed swarm roles, while native swarm tools (`swarm`, + `post_message`, `read_board`, `swarm_wait`, `schedule`, and `manage_task`) + remain unrestricted. Spawn helper workers via `swarm` `add` (passing warm + `fork` when carrying context forward, landing any `share` helper commits + before calling `kill` on your own helpers, and using `model` for quota hot-swap) whenever your slice splits into parallel pieces or needs an independent `ro-*` or `verifier` check. When spawning helpers, apply the matching prefix model from `pstack-models.md` in `` when present @@ -32,9 +32,10 @@ runtime evidence on the swarm message board. single helper or cycling live entries in order across parallel helpers), or omit `model` to inherit your parent model. - **Keep pushes gated.** Never run `git push` on your own initiative. `adv-*` - workers are permanently blocked from pushing, and authoring workers are - blocked unless the coordinator explicitly authorizes pushing with - `PSTACK_ALLOW_PUSH=1`. Force-pushing `main` or `master` is always blocked. + workers are permanently blocked from `git push` and mutating `gh` commands, + and authoring workers are blocked from `git push` unless explicitly authorized + with `PSTACK_ALLOW_PUSH=1`. Force-pushing `main` or `master` is always + blocked. - **Keep board traffic lean.** Do not post greetings, acknowledgments, or progress chatter. Cite prior board context by `#seq` number. When your slice is complete and verified, commit locally, confirm `git status --short` is diff --git a/roles/research.md b/roles/research.md index c776eee..06722f9 100644 --- a/roles/research.md +++ b/roles/research.md @@ -8,18 +8,15 @@ directly, and post cited evidence on the swarm message board. ## Strict read-only contract -- **Zero repository or external mutations.** The guard hook blocks `edit_file`, - `write_file`, shell redirections outside `/dev/null`, filesystem commands - (`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`) 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. +- **Zero repository or external mutations.** Never mutate repository files or + external shared state. The guard hook blocks `edit_file`, blocks `write_file` + outside canonical temp roots (`/tmp`, `/private/tmp`, and `TMPDIR`) and + allowed screenshot image files in your own brain directory outside + `.system_generated`, blocks mutating `git` and `gh` commands, blocks mutating + MCP tools, blocks `run_workflow` and legacy subagent tools except + `invoke_subagent` for `image-generator`, and verifies `git status` + cleanliness on `Stop` without brittle shell or inline-script regexes. 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`, diff --git a/skills/pstack/SKILL.md b/skills/pstack/SKILL.md index c6b3f52..5604694 100644 --- a/skills/pstack/SKILL.md +++ b/skills/pstack/SKILL.md @@ -23,18 +23,18 @@ You are the **Swarm Coordinator**. You own framing, architecture decomposition, ## 2. Prefix-typed roster contract (`hooks/guard.mjs`) -Root `hooks.json` and global `~/.gemini/config/hooks.json` (`pstack-swarm-guard`, registered via `/setup-pstack`) run `hooks/guard.mjs` to enforce role-capsule injection (`SessionStart` and `PreInvocation`) and tool or path boundaries (`PreToolUse`) automatically from each member's roster prefix. Legacy subagent tools are globally blocked across every role. Always name workers by their contract prefix: +Root `hooks.json` and global `~/.gemini/config/hooks.json` (`pstack-swarm-guard`, registered via `/setup-pstack`) run `hooks/guard.mjs` to enforce role-capsule injection (`SessionStart` and `PreInvocation`), structural tool and path gates (`PreToolUse`), and `git status` cleanliness checks (`Stop`) automatically from each member's roster prefix with zero regexes or OS sandboxing. Across managed roles, the guard blocks `run_workflow` and legacy subagent tools except `invoke_subagent` targeting `image-generator`. Always name workers by their contract prefix: | Roster prefix | `workspace` | Injected capsule | Runtime guard enforced by `hooks/guard.mjs` | Primary responsibility | | --- | --- | --- | --- | --- | -| 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 (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 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`. +| Coordinator (root) | root checkout | `roles/coordinator.md` | Legacy subagent tools (except `image-generator`) and `run_workflow` 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 `edit_file` and `write_file` to own worktree, artifact dir outside `.system_generated/`, and canonical temp roots. `git push` denied unless `PSTACK_ALLOW_PUSH=1`. Force-push to `main` or `master` denied. | Disjoint slice implementation, competing candidates, area leads | +| `ro-*` | `"inherit"` | `roles/research.md` | `edit_file`, mutating `git`, `gh`, and MCP calls denied. `write_file` restricted to canonical temp roots and screenshot images in own `brain//` outside `.system_generated/`. `Stop` verifies `git status` cleanliness. | Read-only probes, benchmarks (`ro-bench`), blind judging (`ro-judge`), independent gates (`ro-verify`) | +| `adv-*` | `"share"` | `roles/poteto-agent.md` | `realpathSync` confines `edit_file` and `write_file` to own worktree, artifact dir outside `.system_generated/`, and canonical temp roots. `git push` and mutating `gh` commands permanently denied. | Executable exploit and repro tests (`/interrogate`) | +| `sicko-*` | `"share"` | `roles/comment-sicko.md` | `edit_file` confined to own worktree. `write_file`, `git push`, file-restoring or history-rewriting `git` subcommands, and mutating `gh` commands denied. `Stop` rejects untracked or deleted files. | Post-implementation comment and AI-slop surgical pass | +| `monitor`, `narrator` (`*-*`) | `"inherit"` | `null` (skipped) | Legacy subagent tools (except `image-generator`) and `run_workflow` 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, state, disablement, and remote rosters.** Coordinator activation triggers only on leading swarm-orchestrating slash commands (`/pstack`, `/understand`, `/crucible`, `/interrogate`, `/reflect`, `/verify-gen`, or `/ketchup` without `--plain`) or active swarm rosters. Plain non-pstack `/swarm` runs without pstack prefixes (`impl-*`, `cand-*`, `lead-*`, `ro-*`, `adv-*`, `sicko-*`), mid-sentence `/pstack` prose mentions, `/ketchup --plain`, and standalone inline skills (`/bro`, `/technical-writing`, `/setup-pstack`, `/statechart`, `/control-ui`, `/control-cli`, `/make-bot-ui`) pass through `hooks/guard.mjs` unmanaged. Running `agy plugin disable agy-pstack-next` suspends capsule injection, `PreToolUse` gating, and `Stop` checks via `plugins["agy-pstack-next"].enabled` in `~/.gemini/config/config.json`. `hooks/guard.mjs` stores per-conversation state atomically in `/capsules/.json`, and on remote multi-host swarms backed by `swarm.json` anchors it 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. diff --git a/skills/pstack/topologies/build.md b/skills/pstack/topologies/build.md index c22a56b..506bbaf 100644 --- a/skills/pstack/topologies/build.md +++ b/skills/pstack/topologies/build.md @@ -52,7 +52,7 @@ Match the request to one of four execution contracts before slicing files: ## Phase 3. Integrate and run `sicko-*` surgical cleanup 1. Fetch and merge each completed `impl-*` slice into your integration worktree (`git fetch && git merge --no-edit FETCH_HEAD`) while keeping `impl-*` workers parked in `waiting` until verification clears. -2. Spawn `sicko-clean` (`workspace: "share"`) on the integrated tree (passing `/roles/comment-sicko.md` in its brief when global `hooks.json` is not active). Enforced by `hooks/guard.mjs`, `sicko-*` can call `edit_file` only (`write_file`, shell file redirects, and `git push` are denied) to strip narrating comments, AI code slop, redundant try/catch guards on trusted paths, and unexamined lint suppressions, flagging any load-bearing constraint comments that should be encoded structurally instead. +2. Spawn `sicko-clean` (`workspace: "share"`) on the integrated tree (passing `/roles/comment-sicko.md` in its brief when global `hooks.json` is not active). `hooks/guard.mjs` enforces structural zero-regex gating so `sicko-*` can call `edit_file` inside its own worktree only (`write_file`, `git push`, file-restoring or history-rewriting `git` subcommands, and mutating `gh` commands are denied, and `Stop` rejects untracked or deleted files) to strip narrating comments, AI code slop, redundant try/catch guards on trusted paths, and unexamined lint suppressions, flagging any load-bearing constraint comments that should be encoded structurally instead. 3. Audit `sicko-clean`'s diff to confirm zero behavioral mutations, fetch and merge its commit into the integration tree, and retire `sicko-clean` with `swarm{action: "kill", name: "sicko-clean"}`. ## Phase 4. Independent `ro-verify` behavioral gate diff --git a/skills/pstack/topologies/evolve.md b/skills/pstack/topologies/evolve.md index bd47619..31627fa 100644 --- a/skills/pstack/topologies/evolve.md +++ b/skills/pstack/topologies/evolve.md @@ -29,7 +29,7 @@ Evaluate changes like controlled scientific experiments rather than anecdotal sp Fan out trial execution across parallel `impl-eval-*` workers (`workspace: "share"`, passing `/roles/poteto-agent.md` in each brief when global `hooks.json` is not active): 1. **Stage each trial arm's plugin pack and sanitized repo clone.** Each `impl-eval-` creates a clean, standalone git repository clone or fixture under `/tmp/-` containing the target fixture code, plus a neutral staged plugin tree under `/tmp/` (using neutral names such as `/tmp/pack-oak` and `/tmp/pack-pine` with zero banned blinding words) containing that arm's `roles/`, `hooks/`, and `skills/` directories and an empty state directory `/tmp/` (such as `/tmp/state-oak` and `/tmp/state-pine`). Because `agy` has no `--plugin-dir` flag and skips external `../` symlinks during workspace discovery, also copy the arm's target skill files directly into `/tmp/-/.agents/skills//SKILL.md` (along with any companion `references/`, `topologies/`, or `scripts/` files) and never create external `../` symlinks. -2. **Execute headless runs with `PSTACK_PLUGIN_ROOT`, `PSTACK_CACHE_DIR`, and `--mode auto`.** `PSTACK_PLUGIN_ROOT=/tmp/` delegates global and plugin hook invocations across the trial coordinator and every spawned native swarm worker or helper to the staged `/tmp//hooks/guard.mjs` and `/tmp//roles/*.md` (and anchors `/skills/` brief paths to the staged pack), while `PSTACK_CACHE_DIR=/tmp/` isolates capsule deduplication state (`injected-capsules.json`, `member-map.json`, and `non-worker-roots.json`) per arm without restricting full swarm execution. Non-interactive `agy -p` runs have no interactive approval prompt, so always pass `--mode auto`. Because `--sandbox` mounts `.git` read-only, choose the command by whether the trial commits code: +2. **Execute headless runs with `PSTACK_PLUGIN_ROOT`, `PSTACK_CACHE_DIR`, and `--mode auto`.** `PSTACK_PLUGIN_ROOT=/tmp/` delegates global and plugin hook invocations across the trial coordinator and every spawned native swarm worker or helper to the staged `/tmp//hooks/guard.mjs` and `/tmp//roles/*.md` (and anchors `/skills/` brief paths to the staged pack), while `PSTACK_CACHE_DIR=/tmp/` isolates per-conversation capsule state (`capsules/.json`, alongside `member-map.json`) per arm without restricting full swarm execution. Non-interactive `agy -p` runs have no interactive approval prompt, so always pass `--mode auto`. Because `--sandbox` mounts `.git` read-only, choose the command by whether the trial commits code: - **Commit-producing trials** (bug fixes, features, refactors that stage or commit git changes) omit `--sandbox` inside the isolated `/tmp/-` clone: ```sh PSTACK_PLUGIN_ROOT=/tmp/ PSTACK_CACHE_DIR=/tmp/ agy -p "" --mode auto diff --git a/skills/setup-pstack/SKILL.md b/skills/setup-pstack/SKILL.md index 36a6f3c..f3da27f 100644 --- a/skills/setup-pstack/SKILL.md +++ b/skills/setup-pstack/SKILL.md @@ -106,7 +106,7 @@ quota hotswap: auto (fallback: gemini-4-argon-medium, gemini-3.8-flash-high, gpt ### Step 4b. Register `pstack-swarm-guard` in global `~/.gemini/config/hooks.json` -In `agy`, synthetic `Swarm Worker` subagent specs do not inherit user-plugin `hooks.json` bundles, whereas global `~/.gemini/config/hooks.json` runs across both root sessions and every swarm worker. Register `pstack-swarm-guard` globally so worker role capsules and tool confinement execute on every worker turn. Because `hooks/guard.mjs` stores `injected-capsules.json` and `member-map.json` in `/plugin_data/agy-pstack-next` whether invoked from the plugin hook or `~/.gemini/config/hooks.json`, both registrations share deduplication state and never double-inject the coordinator. +In `agy`, synthetic `Swarm Worker` subagent specs do not inherit user-plugin `hooks.json` bundles, whereas global `~/.gemini/config/hooks.json` runs across both root sessions and every swarm worker. Register `pstack-swarm-guard` globally so worker role capsules, structural tool boundaries, and `Stop` cleanliness checks execute on every worker turn. Because `hooks/guard.mjs` stores per-conversation state under `/plugin_data/agy-pstack-next/capsules/` alongside `member-map.json` whether invoked from the plugin hook or `~/.gemini/config/hooks.json`, both registrations share deduplication state and never double-inject the coordinator. 1. Read `~/.gemini/config/hooks.json` first if it exists and parse its top-level JSON object, preserving every existing hook entry (such as `herdr`). Start from `{}` only when `~/.gemini/config/hooks.json` does not exist. 2. Resolve `` to the canonical absolute filesystem path of `hooks/guard.mjs` (expand `$HOME` into a full path rather than writing `~` inside single quotes). Prefer `~/.gemini/config/plugins/agy-pstack-next/hooks/guard.mjs` when installed, and otherwise resolve `../../hooks/guard.mjs` relative to this `SKILL.md` file. Verify `` exists on disk. @@ -150,6 +150,13 @@ In `agy`, synthetic `Swarm Worker` subagent specs do not inherit user-plugin `ho } ] } + ], + "Stop": [ + { + "type": "command", + "command": "test ! -f '' || node ''", + "timeout": 10 + } ] } } @@ -160,8 +167,8 @@ In `agy`, synthetic `Swarm Worker` subagent specs do not inherit user-plugin `ho 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. +- **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, `PreToolUse` gating, and `Stop` cleanliness checks across global hooks too. +- **Plain `/swarm` and inline skill pass-through.** Plain built-in `/swarm` sessions without pstack worker prefixes (`impl-*`, `cand-*`, `lead-*`, `ro-*`, `adv-*`, `sicko-*`), mid-sentence `/pstack` prose mentions, `/ketchup --plain`, and standalone inline non-swarm skills (`/bro`, `/technical-writing`, `/setup-pstack`, `/statechart`, `/control-ui`, `/control-cli`, `/make-bot-ui`) 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.