diff --git a/.antigravity-plugin/plugin.json b/.antigravity-plugin/plugin.json index 5b65b39..8dfcad4 100644 --- a/.antigravity-plugin/plugin.json +++ b/.antigravity-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "agy-pstack-next", "displayName": "agy-pstack-next", - "version": "2.0.0", + "version": "2.1.0", "description": "Swarm-centric engineering workflows for Antigravity. Hook-enforced role capsules, worktree isolation, adversarial verification, and 14 composable skills for high-rigor parallel code.", "author": { "name": "Lauren Tan" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7ad9f3a..cc5d6e0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -95,6 +95,10 @@ jobs: }; checkExecutable("hooks/guard.mjs"); checkExecutable("skills/pstack/scripts/watch-pr"); + checkExecutable("skills/pstack/scripts/check-plan.mjs"); + checkExecutable("skills/pstack/scripts/worktree-audit.sh"); + checkExecutable("skills/pstack/scripts/decision-log.sh"); + checkExecutable("skills/setup-pstack/scripts/sync-hooks.mjs"); for (const capsule of ["coordinator", "poteto-agent", "research", "comment-sicko"]) { const p = join("roles", `${capsule}.md`); @@ -209,11 +213,82 @@ jobs: - name: Run swarm guard unit tests run: node --test hooks/guard.test.mjs + - name: Run pstack script syntax and unit tests + env: + GIT_CONFIG_COUNT: "1" + GIT_CONFIG_KEY_0: commit.gpgsign + GIT_CONFIG_VALUE_0: "false" + run: | + bash -n skills/pstack/scripts/worktree-audit.sh + bash -n skills/pstack/scripts/decision-log.sh + node --test skills/pstack/scripts/watch-pr.test.mjs skills/pstack/scripts/check-plan.test.mjs + - name: Smoke check watch-pr CLI run: ./skills/pstack/scripts/watch-pr --help > /dev/null + - name: Verify TLA+ tools pin matches statechart runner + run: | + bun - <<'EOF' + import { readFileSync } from "node:fs"; + + const runTs = readFileSync("skills/statechart/scripts/run.ts", "utf8"); + const ciYml = readFileSync(".github/workflows/ci.yml", "utf8"); + + const toolMatch = runTs.match( + /const TLC_TOOL =\s*"http:tla2tools\[url=(https:\/\/[^,\]]+),checksum=sha256:([0-9a-f]{64})\]@([^"]+)"/, + ); + if (!toolMatch) { + throw new Error("Could not parse TLC_TOOL from skills/statechart/scripts/run.ts"); + } + const [, url, sha256, version] = toolMatch; + + const requiredSnippets = [ + `path: ~/.cache/tla2tools/tla2tools-${version}.jar`, + `key: tla2tools-${version}`, + url, + `${sha256} $HOME/.cache/tla2tools/tla2tools-${version}.jar`, + `TLA2TOOLS="$HOME/.cache/tla2tools/tla2tools-${version}.jar"`, + ]; + for (const snippet of requiredSnippets) { + if (!ciYml.includes(snippet)) { + throw new Error(`ci.yml missing pinned TLC_TOOL snippet: ${snippet}`); + } + } + + for (const m of ciYml.matchAll(/https:\/\/github\.com\/tlaplus\/tlaplus\/releases\/download\/[^/\s"']+\/tla2tools\.jar/g)) { + if (m[0] !== url) { + throw new Error(`ci.yml tla2tools URL "${m[0]}" does not match run.ts "${url}"`); + } + } + for (const m of ciYml.matchAll(/tla2tools-([0-9]+\.[0-9]+\.[0-9]+)(?:\.jar)?/g)) { + if (m[1] !== version) { + throw new Error(`ci.yml tla2tools version "${m[1]}" does not match run.ts "${version}"`); + } + } + EOF + + - name: Setup Java + uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: "25" + + - name: Cache TLA+ tools + id: cache-tla2tools + uses: actions/cache@v4 + with: + path: ~/.cache/tla2tools/tla2tools-1.7.4.jar + key: tla2tools-1.7.4 + + - name: Download TLA+ tools + if: steps.cache-tla2tools.outputs.cache-hit != 'true' + run: | + mkdir -p "$HOME/.cache/tla2tools" + curl -fsSL https://github.com/tlaplus/tlaplus/releases/download/v1.7.4/tla2tools.jar -o "$HOME/.cache/tla2tools/tla2tools-1.7.4.jar" + echo "936a262061c914694dfd669a543be24573c45d5aa0ff20a8b96b23d01e050e88 $HOME/.cache/tla2tools/tla2tools-1.7.4.jar" | sha256sum -c - + - name: Test statechart working-directory: skills/statechart/scripts run: | - bun install - bun run test + bun install --frozen-lockfile + TLA2TOOLS="$HOME/.cache/tla2tools/tla2tools-1.7.4.jar" bun run test diff --git a/README.md b/README.md index 6c2ce69..c9ff829 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ agy plugin list Run two commands to start working. In the `agy` CLI (`1.5.8+`), installed plugin skills are namespaced as `/agy-pstack-next:`, while built-in Antigravity commands such as `/goal` and `/schedule` stay unprefixed (prose and tables below use `/` as shorthand). -1. Run [`/agy-pstack-next:setup-pstack`](./skills/setup-pstack/SKILL.md) to discover your available models, write `~/.gemini/config/rules/pstack-models.md` with `trigger: always_on`, register `pstack-swarm-guard` in global `~/.gemini/config/hooks.json` for swarm workers, and optionally generate a project verification skill. +1. Run [`/agy-pstack-next:setup-pstack`](./skills/setup-pstack/SKILL.md) to discover your available models, validate and write `~/.gemini/config/rules/pstack-models.md` with `trigger: always_on` (including `monitor` and separate `impl-*` and `lead-*` rows), sync `pstack-swarm-guard` in global `~/.gemini/config/hooks.json` via [`sync-hooks.mjs`](./skills/setup-pstack/scripts/sync-hooks.mjs) (plus `--check`), and optionally generate a project verification skill. 2. Start engineering tasks with [`/agy-pstack-next:pstack`](./skills/pstack/SKILL.md), stating the goal and a checkable finish condition. ```text @@ -52,7 +52,7 @@ Every swarm member's prefix determines its workspace isolation, injected role ca | `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. | +| `monitor*`, `narrator*` | Built-in | None (skipped) | Selective stall detection (`swarm_monitor`, skipped on short `<= 4` worker single-wave runs, spawned on multi-wave or long runs using `monitor` from `pstack-models.md`) and board narration (`swarm_narrator`, skipped when `swarm_pane` Overview is active unless requested). `hooks/guard.mjs` releases `coordinator` subagent locks automatically once all task workers are killed (`[done]`). | ### Mechanical Guardrails in `hooks/guard.mjs` @@ -67,7 +67,7 @@ Every swarm member's prefix determines its workspace isolation, injected role ca - **Warm context forks.** Pass `fork: ""` in `swarm{action: "add"}` to branch an implementation worker directly from a winning `ro-*` investigator or `cand-*` prototype without re-reading the repo cold. - **Safe landing before teardown.** Because `swarm{action: "kill"}` permanently deletes a worker's `share` worktree, the coordinator always runs `git fetch && git merge` (or `cherry-pick`) before killing a worker. -- **Board `#seq` citations and doorbell `@mentions`.** Workers cite earlier findings by `#seq` number instead of re-quoting logs and `@mention` only the specific peer who acts next. +- **Board `#seq` citations, `$PWD` paths, and `/tmp` reports.** Workers fetch cited `#seq` posts with `read_board` `seqs` instead of reading from `0`, pass absolute `$PWD/...` paths inside `share` worktrees, write detailed reports over `4` KB to `/tmp/-report.md` with a summary on the board, and `@mention` only the specific peer who acts next. - **Live quota hot-swap.** If a worker hits rate limits or low quota, `swarm{action: "model"}` switches its model in place while preserving its conversation history and worktree. ## The 14 Skills @@ -77,7 +77,7 @@ Every swarm member's prefix determines its workspace isolation, injected role ca | Skill | Purpose | |---|---| | [`/pstack`](./skills/pstack/SKILL.md) | Swarm coordinator kernel with 6 composable topologies (`program`, `build`, `diagnose`, `hillclimb`, `ship`, `evolve`), distilled engineering principles, TypeScript patterns, and PR babysitting. | -| [`/setup-pstack`](./skills/setup-pstack/SKILL.md) | Live `swarm{action: "models"}` configuration for `~/.gemini/config/rules/pstack-models.md`, global `~/.gemini/config/hooks.json` guard registration, budget presets, workflow advisor, and `/schedule` automation setup. | +| [`/setup-pstack`](./skills/setup-pstack/SKILL.md) | Live `swarm{action: "models", all: true}` validation and configuration for `~/.gemini/config/rules/pstack-models.md` (`frugal`, `balanced`, `max`, `inherit` presets including `monitor`), [`sync-hooks.mjs`](./skills/setup-pstack/scripts/sync-hooks.mjs) global hook sync (`--check`), workflow advisor, and `/schedule` setup. | | [`/understand`](./skills/understand/SKILL.md) | Parallel `ro-*` clue-sharing mesh unifying mechanism walkthroughs, historical git and tracker provenance, and interactive Socratic explanations, with warm `fork` into implementation. | | [`/crucible`](./skills/crucible/SKILL.md) | Parallel multi-candidate design (`sketch`) and prototype (`full`) arena across orthogonal axes (`cand-*`), cross-family `ro-judge` scoring, and donor `cherry-pick` synthesis. | | [`/interrogate`](./skills/interrogate/SKILL.md) | Adversarial bug hunting (`adv-*` executable repros) combined with transitive caller, schema, and rollout blast-radius mapping (`ro-blast`), gated by `ro-verify`. | @@ -97,8 +97,8 @@ Every swarm member's prefix determines its workspace isolation, injected role ca | Topology | What It Orchestrates | |---|---| -| [`program`](./skills/pstack/topologies/program.md) | Multi-phase plans, stacked branches, `#area` swarm channels (when `swarm` exposes `channel`) or `lead-` sub-coordinators, autonomous overnight runs, board checkpointing, session resume, and safe worktree cleanup. | -| [`build`](./skills/pstack/topologies/build.md) | Features, caller-migrating refactors, prototypes, and visual parity loops across disjoint `impl-*` worktrees, `sicko-*` diff cleanup, and `ro-verify` behavioral proof. | +| [`program`](./skills/pstack/topologies/program.md) | Multi-phase plans, stacked branches, `#area` swarm channels (when `swarm` exposes `channel`) or `lead-` sub-coordinators, autonomous overnight runs, [`check-plan.mjs`](./skills/pstack/scripts/check-plan.mjs), [`decision-log.sh`](./skills/pstack/scripts/decision-log.sh), [`worktree-audit.sh`](./skills/pstack/scripts/worktree-audit.sh), session resume, and safe worktree cleanup. | +| [`build`](./skills/pstack/topologies/build.md) | Features, caller-migrating refactors, prototypes, and visual parity loops across disjoint `impl-*` worktrees, conditional `sicko-*` diff cleanup on comments or non-trivial code changes, and `ro-verify` behavioral proof. | | [`diagnose`](./skills/pstack/topologies/diagnose.md) | Bug fixes, read-only investigations, live runtime forensics, and trace profiling via parallel `ro-*` hypothesis probes, warm `fork` into `impl-fix`, and regression verification. | | [`hillclimb`](./skills/pstack/topologies/hillclimb.md) | Sustained metric optimization with `ro-bench` baseline and noise-floor locking, explain-the-number checks, parallel `cand-*` lever trials, and compounding cherry-picked wins. | | [`ship`](./skills/pstack/topologies/ship.md) | Pre-PR `ro-verify` and `/interrogate` gates, local branch landing, opt-in PR creation and push (`PSTACK_ALLOW_PUSH=1`), CI and review triage via [`watch-pr`](./skills/pstack/scripts/watch-pr) and [`bugbot-triage.md`](./skills/pstack/references/bugbot-triage.md), and clean worker teardown. | diff --git a/docs/guide/01-setup.md b/docs/guide/01-setup.md index 0e0b6c7..f1314c7 100644 --- a/docs/guide/01-setup.md +++ b/docs/guide/01-setup.md @@ -22,20 +22,21 @@ Run the setup skill inside Antigravity: /agy-pstack-next:setup-pstack ``` -[`/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. +[`/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, validates any existing model IDs in `~/.gemini/config/rules/pstack-models.md` against that live catalog (alongside `inherit`, which runs workers on your active session model), asks for your budget preset (`frugal`, `balanced`, `max`, or `inherit`), 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 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. +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, with separate `impl-*` and `lead-*` lines plus `monitor` pinned to the fast low-cost tier (such as `gemini-3.8-flash-low`). +2. **Syncs `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` runs [`sync-hooks.mjs`](../../skills/setup-pstack/scripts/sync-hooks.mjs) (and `--check` for drift verification) to preserve existing entries (such as `herdr`) and register `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, `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. - **`coordinator`.** Plans slices, manages the board, and synthesizes results. -- **`impl-*`, `cand-*`, `lead-*`.** Author code, prototypes, and sub-area slices in `workspace: "share"` worktrees. +- **`impl-*`, `lead-*`, `cand-*`.** Separate prefixes for slice implementation (`impl-*`), multi-area coordination (`lead-*`), and competing prototypes (`cand-*`) in `workspace: "share"` worktrees. - **`ro-*` and `ro-verify`.** Run read-only exploration, trace probes, and independent behavioral verification in `workspace: "inherit"`. - **`adv-*` and `ro-judge`.** Run adversarial bug repros and cross-family design or eval judging so a model family does not grade its own blind spots. -- **`sicko-*`.** Runs post-pass comment and slop surgery across diffs. +- **`sicko-*`.** Runs conditional post-pass comment and slop surgery on diffs that add comments or non-trivial code changes. +- **`monitor`.** Runs built-in stall detection (`swarm_monitor`) on multi-wave or long-running swarms, pinned to the fast low-cost tier (such as `gemini-3.8-flash-low`) while skipped on short `<= 4` worker runs. You override only the roles you care about. Roles omitted from `pstack-models.md` fall back to `inherit` or the skill's preset defaults. If a worker hits rate limits or low quota mid-run, `/pstack` hot-swaps its model live via `swarm{action: "model"}` without losing its conversation or worktree. @@ -55,7 +56,7 @@ Start a fresh chat after updating `pstack-models.md` and `~/.gemini/config/hooks Parallel swarms trade tokens for wall-clock speed and independent verification. Four levers control spend. -- Pick a leaner budget preset in `/setup-pstack` so `ro-*` explorers and `sicko-*` cleanup workers use fast, inexpensive models while `coordinator` and `ro-judge` keep frontier reasoning models. +- Pick the `frugal` or `balanced` budget preset in `/setup-pstack` so `monitor`, `ro-*`, and `sicko-*` workers use fast, low-cost models while `coordinator` and `ro-judge` keep frontier reasoning models. - Leave roles on `inherit` when your active session already uses the exact model you want. - Right-size candidate counts in `/crucible` and `/interrogate` (`2` or `3` candidates for routine boundaries, more only for irreversible interfaces). - Use `/pstack` for multi-file, risky, or verifiable engineering tasks rather than single-line typo edits. diff --git a/docs/guide/02-pstack.md b/docs/guide/02-pstack.md index 8bad173..ac6ebe5 100644 --- a/docs/guide/02-pstack.md +++ b/docs/guide/02-pstack.md @@ -65,8 +65,9 @@ Running parallel authors in one directory corrupts files, git index state, and d - **`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. +- **Selective `monitor` and automatic lock release.** `/pstack` skips `monitor` on short single-wave runs (`<= 4` workers) and spawns `monitor` on multi-wave or long-running swarms using the `monitor` model in `pstack-models.md`. `hooks/guard.mjs` releases `coordinator` subagent locks automatically once all task workers are killed (`[done]`). +- **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, and audits stale worktrees or plans with [`worktree-audit.sh`](../../skills/pstack/scripts/worktree-audit.sh), [`check-plan.mjs`](../../skills/pstack/scripts/check-plan.mjs), and [`decision-log.sh`](../../skills/pstack/scripts/decision-log.sh). +- **`#seq` citations, `$PWD` paths, `/tmp` reports, and doorbell `@mentions`.** Workers fetch cited `#seq` messages with `read_board` `seqs` instead of reading from `0`, pass absolute `$PWD/...` paths inside `share` worktrees, write reports over `4` KB to `/tmp/-report.md`, and `@mention` only the specific peer who needs to wake next. When stale worktrees accumulate across cancelled sessions, run `/pstack` (`program` topology) to audit merge status and uncommitted diffs before pruning safe worktrees. diff --git a/docs/guide/09-make-it-yours.md b/docs/guide/09-make-it-yours.md index a6f6923..8aa9044 100644 --- a/docs/guide/09-make-it-yours.md +++ b/docs/guide/09-make-it-yours.md @@ -10,7 +10,7 @@ Run [`/setup-pstack`](../../skills/setup-pstack/SKILL.md) any time your model ca /agy-pstack-next:setup-pstack ``` -Beyond updating `~/.gemini/config/rules/pstack-models.md` across `coordinator`, `impl-*`, `ro-*`, `adv-*`, `ro-judge`, and `sicko-*` prefixes and keeping `pstack-swarm-guard` registered in `~/.gemini/config/hooks.json`, `/setup-pstack` helps you draft standing `/schedule` automations tailored to your repositories (for example, morning `/ketchup` summaries or scheduled `/verify-gen --maintain` checks) and recommends prompts from [`prompting.md`](../../skills/setup-pstack/references/prompting.md) and [`recipes.md`](../../skills/setup-pstack/references/recipes.md). +Beyond updating `~/.gemini/config/rules/pstack-models.md` across `coordinator`, `impl-*`, `lead-*`, `cand-*`, `ro-*`, `adv-*`, `sicko-*`, `monitor` (pinned to the fast low-cost tier such as `gemini-3.8-flash-low`), and `ro-judge pool` using the `frugal`, `balanced`, `max`, or `inherit` presets while validating existing IDs against `swarm{action: "models", all: true}`, `/setup-pstack` runs [`sync-hooks.mjs`](../../skills/setup-pstack/scripts/sync-hooks.mjs) (and `--check` for drift verification) to keep `pstack-swarm-guard` registered in `~/.gemini/config/hooks.json`. It also helps you draft standing `/schedule` automations tailored to your repositories (for example, morning `/ketchup` summaries or scheduled `/verify-gen --maintain` checks) and recommends prompts from [`prompting.md`](../../skills/setup-pstack/references/prompting.md) and [`recipes.md`](../../skills/setup-pstack/references/recipes.md). ## Turn session friction and repeated corrections into structure with `/reflect` diff --git a/hooks/guard.mjs b/hooks/guard.mjs index 533c569..959090e 100755 --- a/hooks/guard.mjs +++ b/hooks/guard.mjs @@ -201,8 +201,23 @@ function readCapsuleState(cacheDir, conversationId) { } function updateCapsuleState(cacheDir, conversationId, patch) { - const next = { ...readCapsuleState(cacheDir, conversationId), ...patch }; - writeJsonAtomically(capsuleStatePath(cacheDir, conversationId), next); + const current = readCapsuleState(cacheDir, conversationId); + const next = { ...current }; + let changed = false; + for (const [key, value] of Object.entries(patch)) { + if (value === undefined) { + if (Object.prototype.hasOwnProperty.call(next, key)) { + delete next[key]; + changed = true; + } + } else if (next[key] !== value) { + next[key] = value; + changed = true; + } + } + if (changed) { + writeJsonAtomically(capsuleStatePath(cacheDir, conversationId), next); + } return next; } @@ -275,20 +290,31 @@ function resolvePluginRoot(env) { return dirname(dirname(fileURLToPath(import.meta.url))); } -function isPluginDisabled(env) { - let configPath = null; +function resolveConfigDir(env) { 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"); - } + return env.PSTACK_CONFIG_DIR; + } + const pluginRoot = resolvePluginRoot(env); + if (pluginRoot && basename(dirname(pluginRoot)) === "plugins") { + return dirname(dirname(pluginRoot)); } - if (!configPath || !existsSync(configPath)) { + if (typeof env.HOME === "string" && env.HOME && env.HOME !== homedir()) { + return join(env.HOME, ".gemini", "config"); + } + if (!env.PSTACK_APPDATA_DIR && !env.PSTACK_PLUGIN_ROOT && !env.PLUGIN_ROOT) { + const home = typeof env.HOME === "string" && env.HOME ? env.HOME : homedir(); + return join(home, ".gemini", "config"); + } + return null; +} + +function isPluginDisabled(env) { + const configDir = resolveConfigDir(env); + if (!configDir) { + return false; + } + const configPath = join(configDir, "config.json"); + if (!existsSync(configPath)) { return false; } return readJsonObject(configPath)?.plugins?.["agy-pstack-next"]?.enabled === false; @@ -641,6 +667,7 @@ function extractMembersFromDoc(doc, targetConvId, fallbackCoordId = null) { let coordId = typeof fallbackCoordId === "string" && fallbackCoordId ? fallbackCoordId : null; let hasPstackPrefixedWorker = false; let hasTaskWorker = false; + let hasActiveTaskWorker = false; 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") { @@ -663,12 +690,22 @@ function extractMembersFromDoc(doc, targetConvId, fallbackCoordId = null) { const base = stripTrailingNumericSuffix(lower); if (base !== "coordinator" && base !== "monitor" && base !== "narrator") { hasTaskWorker = true; + if (info.killed !== true && info.state !== "killed") { + hasActiveTaskWorker = true; + } } if (typeof cid === "string" && cid) { workerEntries[cid] = name; } } - return { workerEntries, matchedCoordinator, coordId, hasPstackPrefixedWorker, hasTaskWorker }; + return { + workerEntries, + matchedCoordinator, + coordId, + hasPstackPrefixedWorker, + hasTaskWorker, + hasActiveTaskWorker, + }; } function resolveRemoteBoardCli(anchor, appDataDir, env) { @@ -798,7 +835,14 @@ function inspectSwarmDirectory(swarmDir, ownerDirId, targetConvId, opts) { const targetInSwarm = Boolean(targetIsWorker || matchedCoordinator || ext.coordId === targetConvId); return { kind: "unmanaged_swarm", targetInSwarm, targetIsWorker }; } - return { kind: "managed_roster", workerEntries: ext.workerEntries, matchedCoordinator }; + const finishedCoordinator = matchedCoordinator && ext.hasTaskWorker && !ext.hasActiveTaskWorker; + const activeCoordinator = matchedCoordinator && !finishedCoordinator; + return { + kind: "managed_roster", + workerEntries: ext.workerEntries, + matchedCoordinator: activeCoordinator, + finishedCoordinator, + }; } const membersPath = join(swarmDir, "members.json"); @@ -835,8 +879,13 @@ function inspectSwarmDirectory(swarmDir, ownerDirId, targetConvId, opts) { return { kind: "anchor_coordinator" }; } -function resolveWorkerOrCoordinatorFromSwarm(convId, payload, appDataDir, cacheDir, hasPriorCapsule, env) { - const empty = { workerName: null, isKnownCoordinator: false, isUnmanagedSwarmWorker: false }; +function resolveWorkerOrCoordinatorFromSwarm(convId, payload, appDataDir, cacheDir, hasPriorCapsule, env, capsuleState = {}) { + const empty = { + workerName: null, + isKnownActiveCoordinator: false, + isFinishedCoordinator: false, + isUnmanagedSwarmWorker: false, + }; if (typeof convId !== "string" || !convId) { return empty; } @@ -853,6 +902,7 @@ function resolveWorkerOrCoordinatorFromSwarm(convId, payload, appDataDir, cacheD function checkDirs(dirs) { const discovered = {}; let matchedCoord = false; + let matchedFinishedCoord = false; let matchedUnmanaged = false; let matchedUnmanagedWorker = false; for (const { dirId, isOwnSwarmDir } of dirs) { @@ -863,6 +913,9 @@ function resolveWorkerOrCoordinatorFromSwarm(convId, payload, appDataDir, cacheD if (res.matchedCoordinator) { matchedCoord = true; } + if (res.finishedCoordinator) { + matchedFinishedCoord = true; + } } else if (res.kind === "anchor_coordinator") { matchedCoord = true; } else if (res.kind === "unmanaged_swarm" && res.targetInSwarm) { @@ -871,7 +924,7 @@ function resolveWorkerOrCoordinatorFromSwarm(convId, payload, appDataDir, cacheD matchedUnmanagedWorker = true; } } - if (discovered[convId] || matchedCoord || matchedUnmanaged) { + if (discovered[convId] || matchedCoord || matchedFinishedCoord || matchedUnmanaged) { break; } } @@ -880,7 +933,10 @@ function resolveWorkerOrCoordinatorFromSwarm(convId, payload, appDataDir, cacheD return { ...empty, workerName: discovered[convId] }; } if (matchedCoord) { - return { ...empty, isKnownCoordinator: true }; + return { ...empty, isKnownActiveCoordinator: true }; + } + if (matchedFinishedCoord) { + return { ...empty, isFinishedCoordinator: true }; } if (matchedUnmanaged) { return { ...empty, isUnmanagedSwarmWorker: matchedUnmanagedWorker }; @@ -900,9 +956,13 @@ function resolveWorkerOrCoordinatorFromSwarm(convId, payload, appDataDir, cacheD if (directHit) { return directHit; } - if (transcriptIsUnforkedUserRoot(resolveOwnTranscriptPath(payload, appDataDir), hasPriorCapsule)) { + if (capsuleState.unforkedRoot === true) { return empty; } + if (transcriptIsUnforkedUserRoot(resolveOwnTranscriptPath(payload, appDataDir), hasPriorCapsule)) { + updateCapsuleState(cacheDir, convId, { unforkedRoot: true }); + return { ...empty, unforkedRoot: true }; + } try { const brainDir = join(appDataDir, "brain"); if (!existsSync(brainDir)) { @@ -956,14 +1016,24 @@ function classifySession(payload, env) { capsuleState = updateCapsuleState(cacheDir, convId, { plainSwarm: true }); } } - const { workerName, isKnownCoordinator, isUnmanagedSwarmWorker } = resolveWorkerOrCoordinatorFromSwarm( + const { + workerName, + isKnownActiveCoordinator, + isFinishedCoordinator, + isUnmanagedSwarmWorker, + unforkedRoot, + } = resolveWorkerOrCoordinatorFromSwarm( convId, payload, appDataDir, cacheDir, alreadyInjected, env, + capsuleState, ); + if (unforkedRoot) { + capsuleState = { ...capsuleState, unforkedRoot: true }; + } if (workerName) { return { sessionKind: "worker", @@ -985,7 +1055,15 @@ function classifySession(payload, env) { capsuleState, }; } - if (isKnownCoordinator || capsuleState.capsule === "roles/coordinator.md" || isPstackSlash || forcedCoord) { + const hasActivePrompt = typeof capsuleState.activePrompt === "string" && capsuleState.activePrompt.length > 0; + const matchesActivePromptTurn = + hasActivePrompt && + !isFinishedCoordinator && + (!payload.lastUserInput || payload.lastUserInput === capsuleState.activePrompt); + if (isPstackSlash || forcedCoord || isKnownActiveCoordinator || matchesActivePromptTurn) { + if (convId && isPstackSlash && typeof payload.lastUserInput === "string" && payload.lastUserInput) { + capsuleState = updateCapsuleState(cacheDir, convId, { activePrompt: payload.lastUserInput }); + } return { sessionKind: "coordinator", kind: "coordinator", @@ -996,6 +1074,9 @@ function classifySession(payload, env) { capsuleState, }; } + if (convId && hasActivePrompt) { + capsuleState = updateCapsuleState(cacheDir, convId, { activePrompt: undefined }); + } return { sessionKind: "unmanaged", kind: "unmanaged", @@ -1570,11 +1651,288 @@ function readGitStatusPorcelain(dir) { } } +const DRIFT_WARNING_TEXT = + "> **Global hooks drift detected.** Your global hooks configuration is out of date or missing required pstack-swarm-guard handlers. Run `skills/setup-pstack/scripts/sync-hooks.mjs` or `/setup-pstack` to sync it."; + +function realpathIfExists(filePath) { + if (typeof filePath !== "string" || !filePath || !existsSync(filePath)) { + return null; + } + try { + return realpathSync(filePath); + } catch { + return null; + } +} + +function commandTargetsGuard(command, expectedGuardReal, baseDir) { + if (typeof command !== "string" || !command.trim() || !expectedGuardReal) { + return false; + } + const resolveTarget = (p) => realpathIfExists(baseDir ? resolve(baseDir, p) : p); + let sawExec = false; + for (const tokens of parseCommandSegments(command)) { + if (tokens.length === 0) { + continue; + } + const head = basename(tokens[0]); + if (head === "test" || head === "[") { + const fIdx = tokens.indexOf("-f"); + if (fIdx >= 0 && fIdx + 1 < tokens.length) { + if (resolveTarget(tokens[fIdx + 1]) !== expectedGuardReal) { + return false; + } + } + continue; + } + const { cmd, args } = unwrapCommandSegment(tokens); + let scriptPath = null; + if (cmd === "node") { + for (const arg of args) { + if (!arg.startsWith("-")) { + scriptPath = arg; + break; + } + } + } else { + for (const tok of tokens) { + if (!tok.includes("=") && !SHELL_KEYWORDS.has(tok)) { + scriptPath = tok; + break; + } + } + } + if (!scriptPath || resolveTarget(scriptPath) !== expectedGuardReal) { + return false; + } + sawExec = true; + } + return sawExec; +} + +function handlerPointsToGuard(handler, expectedGuardReal, baseDir) { + return Boolean( + handler && + typeof handler === "object" && + handler.type === "command" && + commandTargetsGuard(handler.command, expectedGuardReal, baseDir), + ); +} + +function splitTopLevelPipes(expr) { + const parts = []; + let depth = 0; + let start = 0; + for (let i = 0; i < expr.length; i += 1) { + const ch = expr[i]; + if (ch === "\\" && i + 1 < expr.length) { + i += 1; + continue; + } + if (ch === "(") { + depth += 1; + } else if (ch === ")" && depth > 0) { + depth -= 1; + } else if (ch === "|" && depth === 0) { + parts.push(expr.slice(start, i)); + start = i + 1; + } + } + parts.push(expr.slice(start)); + return parts; +} + +function expandSimpleGroup(branch) { + const open = branch.indexOf("("); + if (open === -1) { + return [branch]; + } + let depth = 0; + let close = -1; + for (let i = open; i < branch.length; i += 1) { + if (branch[i] === "(") { + depth += 1; + } else if (branch[i] === ")") { + depth -= 1; + if (depth === 0) { + close = i; + break; + } + } + } + if (close === -1) { + return [branch]; + } + const prefix = branch.slice(0, open); + const inner = branch.slice(open + 1, close); + const suffix = branch.slice(close + 1); + const out = []; + for (const alt of splitTopLevelPipes(inner)) { + for (const rest of expandSimpleGroup(suffix)) { + out.push(prefix + alt + rest); + } + } + return out; +} + +function matcherCoversTool(matcher, toolName) { + if (typeof matcher !== "string" || !matcher || matcher === "*" || matcher === ".*") { + return true; + } + for (const branch of splitTopLevelPipes(matcher)) { + for (const pattern of expandSimpleGroup(branch)) { + if (pattern.endsWith(".*")) { + if (toolName.startsWith(pattern.slice(0, -2))) { + return true; + } + } else if (pattern === toolName) { + return true; + } + } + } + return false; +} + +function detectGlobalHooksDriftWarning(env) { + const configDir = resolveConfigDir(env); + if (!configDir) { + return null; + } + const globalHooksPath = join(configDir, "hooks.json"); + if (!existsSync(globalHooksPath)) { + return null; + } + const guardSpec = readJsonObject(globalHooksPath)["pstack-swarm-guard"]; + if (!guardSpec || typeof guardSpec !== "object" || Array.isArray(guardSpec) || guardSpec.enabled === false) { + return null; + } + const pluginRoot = resolvePluginRoot(env); + const pluginGuardSpec = readJsonObject(join(pluginRoot, "hooks.json"))["pstack-swarm-guard"]; + if (!pluginGuardSpec || typeof pluginGuardSpec !== "object") { + return null; + } + const expectedGuardReal = realpathIfExists(join(pluginRoot, "hooks", "guard.mjs")); + if (!expectedGuardReal) { + return null; + } + for (const eventName of ["SessionStart", "PreInvocation", "Stop"]) { + const handlers = guardSpec[eventName]; + if (!Array.isArray(handlers) || handlers.length === 0) { + return DRIFT_WARNING_TEXT; + } + if (!handlers.every((h) => handlerPointsToGuard(h, expectedGuardReal, configDir))) { + return DRIFT_WARNING_TEXT; + } + } + const actualPreTool = guardSpec.PreToolUse; + const expectedPreTool = Array.isArray(pluginGuardSpec.PreToolUse) ? pluginGuardSpec.PreToolUse : []; + if (!Array.isArray(actualPreTool) || actualPreTool.length === 0) { + return DRIFT_WARNING_TEXT; + } + for (const expectedBlock of expectedPreTool) { + const matcher = String(expectedBlock?.matcher || ""); + const matchBlock = actualPreTool.find((b) => b && typeof b === "object" && b.matcher === matcher); + if (!matchBlock || !Array.isArray(matchBlock.hooks) || matchBlock.hooks.length === 0) { + return DRIFT_WARNING_TEXT; + } + if (!matchBlock.hooks.every((h) => handlerPointsToGuard(h, expectedGuardReal, configDir))) { + return DRIFT_WARNING_TEXT; + } + } + return null; +} + +function resolveConfigDirForDualHook(env) { + const direct = resolveConfigDir(env); + if (direct) { + return direct; + } + if (!env.PSTACK_APPDATA_DIR && !env.PSTACK_PLUGIN_ROOT) { + const home = typeof env.HOME === "string" && env.HOME ? env.HOME : homedir(); + return join(home, ".gemini", "config"); + } + return null; +} + +function shouldShortCircuitDualHook(payload, env, eventName) { + if (typeof env.PLUGIN_ROOT !== "string" || !env.PLUGIN_ROOT) { + return false; + } + if (typeof env.PSTACK_PLUGIN_ROOT === "string" && env.PSTACK_PLUGIN_ROOT) { + return false; + } + const configDir = resolveConfigDirForDualHook(env); + if (!configDir) { + return false; + } + const globalHooksPath = join(configDir, "hooks.json"); + if (!existsSync(globalHooksPath)) { + return false; + } + const guardSpec = readJsonObject(globalHooksPath)["pstack-swarm-guard"]; + if (!guardSpec || typeof guardSpec !== "object" || Array.isArray(guardSpec) || guardSpec.enabled === false) { + return false; + } + const expectedGuardReal = realpathIfExists(join(env.PLUGIN_ROOT, "hooks", "guard.mjs")); + if (!expectedGuardReal) { + return false; + } + if (eventName === "SessionStart" || eventName === "PreInvocation" || eventName === "Stop") { + const handlers = guardSpec[eventName]; + return Array.isArray(handlers) && handlers.some((h) => handlerPointsToGuard(h, expectedGuardReal, configDir)); + } + if (eventName === "PreToolUse" || payload.toolCall) { + const blocks = guardSpec.PreToolUse; + if (!Array.isArray(blocks) || blocks.length === 0) { + return false; + } + 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; + if (!toolName) { + return blocks.some( + (b) => + b && + typeof b === "object" && + Array.isArray(b.hooks) && + b.hooks.some((h) => handlerPointsToGuard(h, expectedGuardReal, configDir)), + ); + } + return blocks.some( + (b) => + b && + typeof b === "object" && + matcherCoversTool(b.matcher, toolName) && + Array.isArray(b.hooks) && + b.hooks.some((h) => handlerPointsToGuard(h, expectedGuardReal, configDir)), + ); + } + return false; +} + +function cleanupLegacyCacheFiles(cacheDir) { + if (!cacheDir) { + return; + } + for (const name of ["injected-capsules.json", "non-worker-roots.json"]) { + const filePath = join(cacheDir, name); + if (existsSync(filePath)) { + try { + unlinkSync(filePath); + } catch {} + } + } +} + function handleSessionOrInvocation(payload, env) { if (isPluginDisabled(env)) { return {}; } + const isSessionStart = payload.hookEventName === "SessionStart"; const session = classifySession(payload, env); + if (isSessionStart) { + cleanupLegacyCacheFiles(session.cacheDir); + } if (session.sessionKind === "unmanaged") { return {}; } @@ -1594,8 +1952,20 @@ function handleSessionOrInvocation(payload, env) { stateDirty = true; } } + const driftWarning = + isSessionStart && session.sessionKind === "coordinator" && !nextState.driftWarningNotified + ? detectGlobalHooksDriftWarning(env) + : null; const capsuleAbsPath = session.capsule ? join(resolvePluginRoot(env), session.capsule) : ""; - if (!session.capsule || nextState.capsule === session.capsule || !existsSync(capsuleAbsPath)) { + const needsCapsule = Boolean(session.capsule && nextState.capsule !== session.capsule && existsSync(capsuleAbsPath)); + if (!needsCapsule) { + if (driftWarning) { + nextState.driftWarningNotified = true; + writeJsonAtomically(capsuleStatePath(session.cacheDir, convKey), nextState); + return { + injectSteps: [{ systemMessage: { systemMessage: driftWarning } }], + }; + } if (stateDirty) { writeJsonAtomically(capsuleStatePath(session.cacheDir, convKey), nextState); } @@ -1605,10 +1975,14 @@ function handleSessionOrInvocation(payload, env) { const hasForkCapsule = !isUpgrade && transcriptContainsRoleCapsule(resolveOwnTranscriptPath(payload, session.appDataDir)); nextState.capsule = session.capsule; delete nextState.plainSwarm; + if (driftWarning) { + nextState.driftWarningNotified = true; + } writeJsonAtomically(capsuleStatePath(session.cacheDir, convKey), nextState); const prefix = isUpgrade || hasForkCapsule ? ROLE_OVERRIDE_NOTICE : ""; + const suffix = driftWarning ? `\n\n${driftWarning}` : ""; return { - injectSteps: [{ systemMessage: { systemMessage: prefix + readFileSync(capsuleAbsPath, "utf8") } }], + injectSteps: [{ systemMessage: { systemMessage: prefix + readFileSync(capsuleAbsPath, "utf8") + suffix } }], }; } @@ -1778,6 +2152,9 @@ function handleStop(payload, env) { export function runGuard(payload, env = process.env) { const safePayload = payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {}; const eventName = String(safePayload.hookEventName || ""); + if (shouldShortCircuitDualHook(safePayload, env, eventName)) { + return eventName === "PreToolUse" || safePayload.toolCall ? ALLOW : {}; + } if (eventName === "SessionStart" || eventName === "PreInvocation") { return handleSessionOrInvocation(safePayload, env); } diff --git a/hooks/guard.test.mjs b/hooks/guard.test.mjs index 2da2a7c..8ac6b05 100644 --- a/hooks/guard.test.mjs +++ b/hooks/guard.test.mjs @@ -2,7 +2,7 @@ import assert from "node:assert/strict"; import { spawn, spawnSync } from "node:child_process"; import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, - rmSync, statSync, symlinkSync, writeFileSync, + realpathSync, rmSync, statSync, symlinkSync, writeFileSync, } from "node:fs"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; @@ -13,6 +13,7 @@ import { handleRawStdin, runGuard } from "./guard.mjs"; const PLUGIN_ROOT = dirname(dirname(fileURLToPath(import.meta.url))); const GUARD_PATH = join(PLUGIN_ROOT, "hooks", "guard.mjs"); const HOOKS_JSON_PATH = join(PLUGIN_ROOT, "hooks.json"); +const SYNC_HOOKS_PATH = join(PLUGIN_ROOT, "skills", "setup-pstack", "scripts", "sync-hooks.mjs"); function makeSandbox() { const root = mkdtempSync(join(tmpdir(), "pstack-guard-test-")); @@ -181,21 +182,23 @@ function scanJsForRegexAndSandbox(source) { } 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); + test("hooks/guard.mjs and sync-hooks.mjs contain 0 regex literals, 0 RegExp references, and 0 OS sandbox calls", () => { + for (const filePath of [GUARD_PATH, SYNC_HOOKS_PATH]) { + const source = readFileSync(filePath, "utf8"); + const scan = scanJsForRegexAndSandbox(source); + assert.deepEqual(scan.regexLiterals, [], `${filePath} must contain zero regex literals`); + assert.deepEqual(scan.regExpRefs, [], `${filePath} 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); }); - test("hooks.json includes SessionStart, PreInvocation, PreToolUse, and Stop handlers and guard.mjs is executable", () => { + test("hooks.json includes SessionStart, PreInvocation, PreToolUse, and Stop handlers and scripts are executable", () => { assert.equal(existsSync(HOOKS_JSON_PATH), true); const hooksConfig = JSON.parse(readFileSync(HOOKS_JSON_PATH, "utf8")); const spec = hooksConfig["pstack-swarm-guard"]; @@ -205,6 +208,7 @@ describe("Static zero-regex, zero-sandbox, packaging, and capsule prose checks", 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"); + assert.notEqual(statSync(SYNC_HOOKS_PATH).mode & 0o111, 0, "sync-hooks.mjs must have +x permission"); }); test("all role capsules and Role override notice are free of em-dashes, en-dashes, and colons", () => { @@ -933,3 +937,435 @@ describe("Stop hook git cleanliness check and loop guards", () => { } }); }); + +describe("Global hooks sync, drift warning, coordinator release, unforkedRoot cache, dual-hook dedup, and legacy cleanup", () => { + test("sync-hooks.mjs supports --check on missing/stale/synced, preserves sibling keys, and writes 2-space JSON", () => { + const sb = makeSandbox(); + try { + const cfgDir = join(sb.root, "gemini-cfg"); + const globalHooksPath = join(cfgDir, "hooks.json"); + const runSync = (args = [], extraEnv = {}) => + spawnSync(process.execPath, [SYNC_HOOKS_PATH, ...args], { + encoding: "utf8", + env: buildEnv({ PSTACK_CONFIG_DIR: undefined, ...extraEnv }), + }); + + const missingCheck = runSync(["--check", "--config-dir", cfgDir]); + assert.equal(missingCheck.status, 1); + + mkdirSync(cfgDir, { recursive: true }); + const siblingHerdr = { SessionStart: [{ type: "command", command: "herdr-hook", timeout: 5 }] }; + writeFileSync( + globalHooksPath, + JSON.stringify({ + herdr: siblingHerdr, + "pstack-swarm-guard": { + SessionStart: [{ type: "command", command: `node '${GUARD_PATH}'`, timeout: 10 }], + }, + }, null, 2), + "utf8", + ); + const staleCheck = runSync(["--check"], { PSTACK_CONFIG_DIR: cfgDir }); + assert.equal(staleCheck.status, 1); + + const syncRes = runSync(["--config-dir", cfgDir]); + assert.equal(syncRes.status, 0, syncRes.stderr); + + const rawSynced = readFileSync(globalHooksPath, "utf8"); + const parsedSynced = JSON.parse(rawSynced); + assert.equal(rawSynced, `${JSON.stringify(parsedSynced, null, 2)}\n`); + assert.deepEqual(parsedSynced.herdr, siblingHerdr); + + const absGuard = realpathSync(GUARD_PATH); + const expectedCmd = `test ! -f '${absGuard}' || node '${absGuard}'`; + const guardSpec = parsedSynced["pstack-swarm-guard"]; + assert.deepEqual(guardSpec.SessionStart, [{ type: "command", command: expectedCmd, timeout: 10 }]); + assert.deepEqual(guardSpec.PreInvocation, [{ type: "command", command: expectedCmd, timeout: 10 }]); + assert.deepEqual(guardSpec.Stop, [{ type: "command", command: expectedCmd, timeout: 10 }]); + assert.equal(guardSpec.PreToolUse.length, 2); + assert.equal(guardSpec.PreToolUse[0].hooks[0].command, expectedCmd); + assert.equal(guardSpec.PreToolUse[1].hooks[0].command, expectedCmd); + + const syncedCheck = runSync(["--check"], { PSTACK_CONFIG_DIR: cfgDir }); + assert.equal(syncedCheck.status, 0, syncedCheck.stderr); + + const wrongTargetDir = join(sb.root, "wrong-cfg"); + mkdirSync(wrongTargetDir, { recursive: true }); + writeFileSync( + join(wrongTargetDir, "hooks.json"), + JSON.stringify({ + "pstack-swarm-guard": { + SessionStart: [{ type: "command", command: "node '/nonexistent/guard.mjs'", timeout: 10 }], + PreInvocation: [{ type: "command", command: "node '/nonexistent/guard.mjs'", timeout: 10 }], + PreToolUse: guardSpec.PreToolUse, + Stop: [{ type: "command", command: "node '/nonexistent/guard.mjs'", timeout: 10 }], + }, + }, null, 2), + "utf8", + ); + assert.equal(runSync(["--check", `--config-dir=${wrongTargetDir}`]).status, 1); + } finally { + sb.cleanup(); + } + }); + + test("emits colon-free, dash-free drift warning on stale global hooks.json and avoids duplicate warnings", () => { + const sb = makeSandbox(); + try { + const cfgDir = join(sb.root, "drift-cfg"); + mkdirSync(cfgDir, { recursive: true }); + const absGuard = realpathSync(GUARD_PATH); + const cmd = `test ! -f '${absGuard}' || node '${absGuard}'`; + writeFileSync( + join(cfgDir, "hooks.json"), + JSON.stringify({ + "pstack-swarm-guard": { + SessionStart: [{ type: "command", command: cmd, timeout: 10 }], + PreInvocation: [{ type: "command", command: cmd, timeout: 10 }], + PreToolUse: [ + { + matcher: "(invoke|define)_subagent|manage_subagents|send_message|run_workflow", + hooks: [{ type: "command", command: cmd, timeout: 10 }], + }, + ], + }, + }, null, 2), + "utf8", + ); + + const out1 = invokeGuard( + { hookEventName: "SessionStart", conversationId: "drift-coord-1", lastUserInput: "/pstack fix bug" }, + { PSTACK_APPDATA_DIR: sb.appDataDir, PSTACK_CONFIG_DIR: cfgDir }, + ); + const msg1 = out1.injectSteps?.[0]?.systemMessage?.systemMessage || ""; + assert.ok(msg1.includes("Coordinator role capsule")); + assert.ok(msg1.includes("sync-hooks.mjs")); + assert.ok(msg1.includes("/setup-pstack")); + assert.equal(msg1.includes(":"), false, "drift warning + capsule must contain zero colons"); + assert.equal(msg1.includes("—"), false, "drift warning + capsule must contain zero em-dashes"); + assert.equal(msg1.includes("–"), false, "drift warning + capsule must contain zero en-dashes"); + + assert.deepEqual( + invokeGuard( + { hookEventName: "SessionStart", conversationId: "drift-coord-1", lastUserInput: "/pstack fix bug" }, + { PSTACK_APPDATA_DIR: sb.appDataDir, PSTACK_CONFIG_DIR: cfgDir }, + ), + {}, + ); + + const capDir = join(sb.appDataDir, "plugin_data", "agy-pstack-next", "capsules"); + mkdirSync(capDir, { recursive: true }); + writeFileSync( + join(capDir, "drift-coord-2.json"), + JSON.stringify({ capsule: "roles/coordinator.md", activePrompt: "/pstack pre-injected" }, null, 2), + "utf8", + ); + const out2 = invokeGuard( + { hookEventName: "SessionStart", conversationId: "drift-coord-2", lastUserInput: "/pstack pre-injected" }, + { PSTACK_APPDATA_DIR: sb.appDataDir, PSTACK_CONFIG_DIR: cfgDir }, + ); + const msg2 = out2.injectSteps?.[0]?.systemMessage?.systemMessage || ""; + assert.ok(msg2.includes("sync-hooks.mjs")); + assert.equal(msg2.includes("Coordinator role capsule"), false); + assert.equal(msg2.includes(":"), false); + assert.equal(msg2.includes("—"), false); + assert.equal(msg2.includes("–"), false); + + assert.deepEqual( + invokeGuard( + { hookEventName: "SessionStart", conversationId: "drift-coord-2", lastUserInput: "/pstack pre-injected" }, + { PSTACK_APPDATA_DIR: sb.appDataDir, PSTACK_CONFIG_DIR: cfgDir }, + ), + {}, + ); + + writeFileSync( + join(cfgDir, "hooks.json"), + JSON.stringify({ + "pstack-swarm-guard": { + enabled: false, + SessionStart: [{ type: "command", command: cmd, timeout: 10 }], + }, + }, null, 2), + "utf8", + ); + const disabledDrift = invokeGuard( + { hookEventName: "SessionStart", conversationId: "drift-coord-3", lastUserInput: "/pstack quiet" }, + { PSTACK_APPDATA_DIR: sb.appDataDir, PSTACK_CONFIG_DIR: cfgDir }, + ); + assert.equal(disabledDrift.injectSteps[0].systemMessage.systemMessage.includes("sync-hooks.mjs"), false); + } finally { + sb.cleanup(); + } + }); + + test("releases sticky coordinator lock after all task workers are killed and re-engages without duplicate capsule", () => { + const sb = makeSandbox(); + try { + const convId = "coord-release"; + const capPath = join(sb.appDataDir, "plugin_data", "agy-pstack-next", "capsules", `${convId}.json`); + + const firstStart = invokeGuard( + { hookEventName: "SessionStart", conversationId: convId, lastUserInput: "/pstack implement feature" }, + { PSTACK_APPDATA_DIR: sb.appDataDir }, + ); + assert.ok(firstStart.injectSteps[0].systemMessage.systemMessage.includes("Coordinator role capsule")); + assert.equal(JSON.parse(readFileSync(capPath, "utf8")).activePrompt, "/pstack implement feature"); + + assert.equal( + invokeGuard( + { + hookEventName: "PreToolUse", + conversationId: convId, + cwd: sb.worktree, + toolCall: { id: "t-turn0", name: "invoke_subagent", args: { TypeName: "research" } }, + }, + { PSTACK_APPDATA_DIR: sb.appDataDir }, + ).decision, + "deny", + ); + + writeSwarmMembers(sb.appDataDir, convId, { + coordinator: { conversation_id: convId, role: "coordinator" }, + monitor: { conversation_id: "mon-1", role: "worker" }, + "impl-1": { conversation_id: "impl-1-cid", role: "worker" }, + }); + assert.equal( + invokeGuard( + { + hookEventName: "PreToolUse", + conversationId: convId, + lastUserInput: "follow up while worker active", + cwd: sb.worktree, + toolCall: { id: "t-active", name: "invoke_subagent", args: { TypeName: "research" } }, + }, + { PSTACK_APPDATA_DIR: sb.appDataDir }, + ).decision, + "deny", + ); + + writeSwarmMembers(sb.appDataDir, convId, { + coordinator: { conversation_id: convId, role: "coordinator" }, + monitor: { conversation_id: "mon-1", role: "worker" }, + "impl-1": { conversation_id: "impl-1-cid", role: "worker", state: "killed" }, + "ro-1": { conversation_id: "ro-1-cid", role: "worker", killed: true }, + }); + + assert.deepEqual( + invokeGuard( + { hookEventName: "SessionStart", conversationId: convId, lastUserInput: "now let us discuss unrelated docs" }, + { PSTACK_APPDATA_DIR: sb.appDataDir }, + ), + {}, + ); + const releasedState = JSON.parse(readFileSync(capPath, "utf8")); + assert.equal(releasedState.capsule, "roles/coordinator.md"); + assert.equal(releasedState.activePrompt, undefined); + + assert.equal( + invokeGuard( + { + hookEventName: "PreToolUse", + conversationId: convId, + cwd: sb.worktree, + toolCall: { id: "t-released", name: "invoke_subagent", args: { TypeName: "research" } }, + }, + { PSTACK_APPDATA_DIR: sb.appDataDir }, + ).decision, + "allow", + ); + + const secondStart = invokeGuard( + { hookEventName: "SessionStart", conversationId: convId, lastUserInput: "/pstack second wave" }, + { PSTACK_APPDATA_DIR: sb.appDataDir }, + ); + assert.deepEqual(secondStart, {}); + assert.equal(JSON.parse(readFileSync(capPath, "utf8")).activePrompt, "/pstack second wave"); + assert.equal( + invokeGuard( + { + hookEventName: "PreToolUse", + conversationId: convId, + lastUserInput: "/pstack second wave", + cwd: sb.worktree, + toolCall: { id: "t-reengaged", name: "run_workflow", args: {} }, + }, + { PSTACK_APPDATA_DIR: sb.appDataDir }, + ).decision, + "deny", + ); + } finally { + sb.cleanup(); + } + }); + + test("caches unforkedRoot true after first transcript check without caching missing transcripts or blocking later /pstack", () => { + const sb = makeSandbox(); + try { + const capPathMissing = join(sb.appDataDir, "plugin_data", "agy-pstack-next", "capsules", "no-tx-conv.json"); + assert.deepEqual( + invokeGuard( + { hookEventName: "SessionStart", conversationId: "no-tx-conv", lastUserInput: "hello" }, + { PSTACK_APPDATA_DIR: sb.appDataDir }, + ), + {}, + ); + assert.equal(existsSync(capPathMissing), false, "must not cache unforkedRoot when transcript does not exist"); + + const convId = "unforked-chat"; + const txPath = join(sb.appDataDir, "brain", convId, ".system_generated", "logs", "transcript.jsonl"); + mkdirSync(dirname(txPath), { recursive: true }); + writeFileSync(txPath, `${JSON.stringify({ type: "USER_INPUT", content: "ordinary question" })}\n`, "utf8"); + + assert.deepEqual( + invokeGuard( + { hookEventName: "SessionStart", conversationId: convId, lastUserInput: "ordinary question", transcriptPath: txPath }, + { PSTACK_APPDATA_DIR: sb.appDataDir }, + ), + {}, + ); + const capPath = join(sb.appDataDir, "plugin_data", "agy-pstack-next", "capsules", `${convId}.json`); + assert.equal(JSON.parse(readFileSync(capPath, "utf8")).unforkedRoot, true); + + writeFileSync(txPath, "[swarm] new board message should not be re-read\n", "utf8"); + writeSwarmMembers(sb.appDataDir, "unrelated-swarm", { + coordinator: { conversation_id: "unrelated-swarm", role: "coordinator" }, + "ro-1": { conversation_id: convId, role: "worker" }, + }); + assert.equal( + invokeGuard( + { + hookEventName: "PreToolUse", + conversationId: convId, + transcriptPath: txPath, + cwd: sb.worktree, + toolCall: { id: "u-1", name: "invoke_subagent", args: { TypeName: "research" } }, + }, + { PSTACK_APPDATA_DIR: sb.appDataDir }, + ).decision, + "allow", + ); + + const pstackTurn = invokeGuard( + { hookEventName: "SessionStart", conversationId: convId, lastUserInput: "/pstack escalate now", transcriptPath: txPath }, + { PSTACK_APPDATA_DIR: sb.appDataDir }, + ); + assert.ok(pstackTurn.injectSteps[0].systemMessage.systemMessage.includes("Coordinator role capsule")); + assert.equal(JSON.parse(readFileSync(capPath, "utf8")).unforkedRoot, true); + } finally { + sb.cleanup(); + } + }); + + test("short-circuits duplicate PLUGIN_ROOT invocations when global hooks.json covers the event and target guard", () => { + const sb = makeSandbox(); + try { + const cfgDir = join(sb.root, "dual-cfg"); + const syncRes = spawnSync(process.execPath, [SYNC_HOOKS_PATH, "--config-dir", cfgDir], { + encoding: "utf8", + env: buildEnv({ PSTACK_CONFIG_DIR: undefined }), + }); + assert.equal(syncRes.status, 0, syncRes.stderr); + + writeSwarmMembers(sb.appDataDir, "coord-dual", { + coordinator: { conversation_id: "coord-dual", role: "coordinator" }, + "ro-1": { conversation_id: "ro-dual", role: "worker" }, + }); + + assert.deepEqual( + invokeGuard( + { hookEventName: "SessionStart", conversationId: "ro-dual", rootConversationId: "coord-dual" }, + { PSTACK_APPDATA_DIR: sb.appDataDir, PSTACK_CONFIG_DIR: cfgDir, PLUGIN_ROOT }, + ), + {}, + ); + assert.deepEqual( + invokeGuard( + { hookEventName: "PreInvocation", conversationId: "ro-dual", rootConversationId: "coord-dual" }, + { PSTACK_APPDATA_DIR: sb.appDataDir, PSTACK_CONFIG_DIR: cfgDir, PLUGIN_ROOT }, + ), + {}, + ); + assert.equal( + invokeGuard( + { + hookEventName: "PreToolUse", + conversationId: "ro-dual", + rootConversationId: "coord-dual", + cwd: sb.worktree, + toolCall: { id: "d1", name: "edit_file", args: { Path: join(sb.worktree, "a.js") } }, + }, + { PSTACK_APPDATA_DIR: sb.appDataDir, PSTACK_CONFIG_DIR: cfgDir, PLUGIN_ROOT }, + ).decision, + "allow", + ); + assert.equal( + invokeGuard( + { + hookEventName: "PreToolUse", + conversationId: "ro-dual", + rootConversationId: "coord-dual", + cwd: sb.worktree, + toolCall: { id: "d2", name: "invoke_subagent", args: { TypeName: "research" } }, + }, + { PSTACK_APPDATA_DIR: sb.appDataDir, PSTACK_CONFIG_DIR: cfgDir, PLUGIN_ROOT }, + ).decision, + "allow", + ); + + const repoDir = join(sb.root, "dual-repo"); + mkdirSync(repoDir, { recursive: true }); + spawnSync("git", ["-C", repoDir, "init"], { encoding: "utf8" }); + writeFileSync(join(repoDir, "dirty.txt"), "dirty\n", "utf8"); + assert.deepEqual( + invokeGuard( + { hookEventName: "Stop", conversationId: "ro-dual", rootConversationId: "coord-dual", cwd: repoDir, terminationReason: "NO_TOOL_CALL" }, + { PSTACK_APPDATA_DIR: sb.appDataDir, PSTACK_CONFIG_DIR: cfgDir, PLUGIN_ROOT }, + ), + {}, + ); + + const globalHooksPath = join(cfgDir, "hooks.json"); + const hooksDoc = JSON.parse(readFileSync(globalHooksPath, "utf8")); + delete hooksDoc["pstack-swarm-guard"].Stop; + writeFileSync(globalHooksPath, JSON.stringify(hooksDoc, null, 2), "utf8"); + + const stopOut = invokeGuard( + { hookEventName: "Stop", conversationId: "ro-dual", rootConversationId: "coord-dual", cwd: repoDir, terminationReason: "NO_TOOL_CALL" }, + { PSTACK_APPDATA_DIR: sb.appDataDir, PSTACK_CONFIG_DIR: cfgDir, PLUGIN_ROOT }, + ); + assert.equal(stopOut.decision, "continue"); + assert.ok(stopOut.reason.includes("dirty.txt")); + + const delegatedOut = invokeGuard( + { hookEventName: "SessionStart", conversationId: "ro-dual", rootConversationId: "coord-dual" }, + { PSTACK_APPDATA_DIR: sb.appDataDir, PSTACK_CONFIG_DIR: cfgDir, PLUGIN_ROOT, PSTACK_PLUGIN_ROOT: PLUGIN_ROOT }, + ); + assert.ok(delegatedOut.injectSteps[0].systemMessage.systemMessage.includes("Read-only specialist role capsule")); + } finally { + sb.cleanup(); + } + }); + + test("unlinks legacy injected-capsules.json and non-worker-roots.json on SessionStart", () => { + const sb = makeSandbox(); + try { + const cacheDir = join(sb.appDataDir, "plugin_data", "agy-pstack-next"); + mkdirSync(cacheDir, { recursive: true }); + const legacyCapsules = join(cacheDir, "injected-capsules.json"); + const legacyRoots = join(cacheDir, "non-worker-roots.json"); + writeFileSync(legacyCapsules, "{}", "utf8"); + writeFileSync(legacyRoots, "{}", "utf8"); + + invokeGuard( + { hookEventName: "SessionStart", conversationId: "legacy-clean-conv", lastUserInput: "hello" }, + { PSTACK_APPDATA_DIR: sb.appDataDir }, + ); + + assert.equal(existsSync(legacyCapsules), false); + assert.equal(existsSync(legacyRoots), false); + } finally { + sb.cleanup(); + } + }); +}); diff --git a/roles/comment-sicko.md b/roles/comment-sicko.md index 35f3f72..43da34a 100644 --- a/roles/comment-sicko.md +++ b/roles/comment-sicko.md @@ -28,11 +28,18 @@ guilty symbols for root-cause structural repair. - **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. -- **Clean local handoff.** When your brief asks for a commit, commit your - comment-only edits locally, confirm `git status --short` is empty, and open - your completion post with `@ [done] Yes... Ha ha ha... Yes!` - followed immediately by your audit, commit SHA, and worktree path so the Swarm - UI marks your worker done. Cite prior board messages by `#seq` number. +- **Clean local handoff, paths, and lean board reads.** Call `read_board` with + `seqs` for cited `#seq` messages instead of reading from `0` on startup, and + cite prior board messages by `#seq` number. Pass absolute `$PWD/...` paths to + `read_file`, `edit_file`, and `write_file` inside `share` worktrees instead of + relative paths (`sicko-*` uses `read_file` and `edit_file`, while `write_file` + is blocked). Write detailed reports over `4` KB to + `/tmp/-report.md` via shell redirection and post a concise summary + plus that path on the board so `read_board` never truncates. When your brief + asks for a commit, commit your comment-only edits locally, confirm + `git status --short` is empty, and open your completion post with + `@ [done] Yes... Ha ha ha... Yes!` followed immediately by your + audit, commit SHA, and worktree path so the Swarm UI marks your worker done. ## What dies on sight diff --git a/roles/coordinator.md b/roles/coordinator.md index 54332b1..a1cff5c 100644 --- a/roles/coordinator.md +++ b/roles/coordinator.md @@ -9,16 +9,17 @@ subagent tools except \`invoke_subagent\` targeting \`image-generator\`. ## First response and goal framing -Open your first message on a task by restating the user's goal and the problem -they are trying to solve in your own words, unless you are handling an inline -plain-language restatement (`/bro` or `/ketchup --plain`). When the task ships a -code change, name the smallest change you expect to meet that goal. Do not pause -for confirmation before starting reversible work. When initial evidence proves -the requested change cannot work, show that evidence immediately and stop. -Restate the user's goal in every worker brief, in every pull request rationale, -and at the top of your final reply unless the task was a single specified -one-line edit or an inline plain-language restatement (`/bro` or -`/ketchup --plain`), which replies directly without a goal-framing preamble. +Scope goal-restatement preambles strictly to the opening turn and final report +of a brand-new task. On that opening turn, restate the user's goal and the +problem they are trying to solve in your own words. When the task ships a code +change, name the smallest change you expect to meet that goal. Do not pause for +confirmation before starting reversible work. When initial evidence proves the +requested change cannot work, show that evidence immediately and stop. Restate +the user's goal in every worker brief, in every pull request rationale, and at +the top of your final report for that brand-new task. Skip goal-restatement +preambles completely on follow-up Q&A, status checks, PR creation follow-ups, +single specified one-line edits, `/bro`, and `/ketchup --plain`, replying +directly instead. ## Roster prefixes and hook contract @@ -62,10 +63,16 @@ tool boundaries without regex shell parsing or OS sandboxing. 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 - `narrator` by name. The guard skips capsule injection for both. +- **Built-in support (`monitor`, `narrator`).** Skip spawning `monitor` on short + single-wave runs with `4` or fewer workers where the coordinator waits directly + via `swarm_wait`. Spawn `monitor` on multi-wave or long-running swarms only + when `swarm_monitor` exists in ``, applying the `monitor` model from + `pstack-models.md` when present and omitting `model` when unset or `inherit`. + Skip `narrator` when `swarm_pane` is in `` unless the user asks for + `narrator` by name, and otherwise spawn `narrator` only when `swarm_narrator` + exists in ``. The guard skips capsule injection for both. + `hooks/guard.mjs` releases `coordinator` subagent locks automatically once all + task workers are killed (`[done]`). Never kill `monitor` or `narrator` unless the user asks, and post `[done] ` with no `@` mention when the task finishes so `monitor` parks quietly. diff --git a/roles/poteto-agent.md b/roles/poteto-agent.md index a521479..c1d681b 100644 --- a/roles/poteto-agent.md +++ b/roles/poteto-agent.md @@ -36,12 +36,17 @@ runtime evidence on the swarm message board. 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 - empty, and open your final handoff post with `@ [done]` followed - by your commit SHA, worktree path, and test counts so the Swarm UI marks your - worker done. +- **Keep board traffic lean and paths absolute.** Do not post greetings, + acknowledgments, or progress chatter. Call `read_board` with `seqs` for cited + `#seq` messages instead of reading from `0` on startup, and cite prior board + context by `#seq` number. Always pass absolute `$PWD/...` paths to + `read_file`, `edit_file`, and `write_file` inside `share` worktrees instead of + relative paths. Write detailed reports over `4` KB to + `/tmp/-report.md` and post a concise summary plus that path on + the board so `read_board` never truncates. When your slice is complete and + verified, commit locally, confirm `git status --short` is empty, and open your + final handoff post with `@ [done]` followed by your commit SHA, + worktree path, and test counts so the Swarm UI marks your worker done. ## Domain modeling and type discipline diff --git a/roles/research.md b/roles/research.md index 06722f9..0d6efd3 100644 --- a/roles/research.md +++ b/roles/research.md @@ -38,11 +38,16 @@ directly, and post cited evidence on the swarm message board. artifact directory (`/brain//`) outside `.system_generated` for Swarm UI timeline proofs. - **Clue-sharing mesh etiquette.** Read recent board posts before repeating a - search. Post concise clues with exact `file` and line anchors, commit SHAs, or - ticket IDs so parallel `ro-*` peers can pivot live. Cite earlier board posts - by `#seq` number. Ring `@` only for the peer or coordinator waiting on - your result, open your final report with `@ [done]`, and never post - greetings or status chatter. + search, and call `read_board` with `seqs` for cited `#seq` messages instead of + reading from `0` on startup. Pass absolute `$PWD/...` paths to `read_file`, + `edit_file`, and `write_file` inside `share` worktrees instead of relative + paths. Write detailed reports over `4` KB to `/tmp/-report.md` + and post a concise summary plus that path on the board so `read_board` never + truncates. Post concise clues with exact `file` and line anchors, commit + SHAs, or ticket IDs so parallel `ro-*` peers can pivot live. Cite earlier + board posts by `#seq` number. Ring `@` only for the peer or + coordinator waiting on your result, open your final report with + `@ [done]`, and never post greetings or status chatter. ## Epistemic rigor and confidence tiers diff --git a/skills/crucible/SKILL.md b/skills/crucible/SKILL.md index 7c7f0dd..4c173b8 100644 --- a/skills/crucible/SKILL.md +++ b/skills/crucible/SKILL.md @@ -67,9 +67,9 @@ Wake `@cand-a @cand-b @cand-c` for one bounded critique turn when trade-offs are Spawn `ro-judge` (`workspace: "inherit"`, read-only) on a model from `ro-judge pool` in `~/.gemini/config/rules/pstack-models.md` whose model family differs from both the coordinator and winning contenders (`inherit` never judges). -`ro-judge` inspects every candidate's worktree files and git diff directly, screens each candidate against every item in [`references/design-red-flags.md`](references/design-red-flags.md) (passed in `ro-judge`'s brief as `/skills/crucible/references/design-red-flags.md`), grades the rubric criterion by criterion, and posts a `#seq` verdict naming: +Before handing off candidate submissions and diffs to `ro-judge`, anonymize candidate labels (`design-oak`, `design-pine`, `design-cedar`) and strip author prefixes (`cand-*`) and model IDs so cross-model judging stays blind. `ro-judge` inspects every anonymized candidate's worktree files and git diff directly, screens each candidate against every item in [`references/design-red-flags.md`](references/design-red-flags.md) (passed in `ro-judge`'s brief as `/skills/crucible/references/design-red-flags.md`), grades the rubric criterion by criterion, and posts a `#seq` verdict naming: -- Recommended base candidate (`cand-winner`) and why its core boundary ages best. +- Recommended base candidate (`design-oak` or `design-pine`) and why its core boundary ages best (which the coordinator maps back to the winning `cand-*` member). - Specific donor artifacts (edge-case tests, benchmarks, type refinements, helper functions) worth porting from losing `cand-*` branches. - Red flags detected in each candidate. @@ -97,7 +97,7 @@ Apply the `crucible checkpoint` setting from `~/.gemini/config/rules/pstack-mode ``` 2. Inside `impl-synth`, fetch the winning branch (`git fetch && git checkout -B crucible-synth FETCH_HEAD`) and pull targeted tests or helpers from donor worktrees (`git fetch ` with `git cherry-pick --no-commit` or path checkout). Rewrite grafted pieces so names, types, and invariants fit one unified mental model rather than mechanical Franken-code. 3. If Phase 2 ran in `sketch` mode and no checkpoint paused execution, `impl-synth` (or downstream `impl-*` slices under [`/pstack`](../pstack/SKILL.md) `build`) replaces `not implemented` bodies with production code and behavioral tests. -4. **Scrap rule when implementation fights the sketch.** If filling in a `sketch` triggers repeated structural workarounds across unrelated callers, type casts (`any`), or surprise locks on supposedly isolated state, stop bolting on patches. Scrap the sketch, fold the newly discovered constraint into Phase 1, and re-run Phase 2 smaller and cleaner. +4. **Scrap rule when implementation fights the sketch.** If filling in a `sketch` triggers caller leaks across module boundaries or `2+` implementation deviations from the sketch (such as repeated structural workarounds across unrelated callers, `any` casts, or surprise locks on supposedly isolated state), stop bolting on patches. Scrap the sketch, fold the newly discovered constraint into Phase 1, and re-run Phase 2 smaller and cleaner. --- diff --git a/skills/ketchup/SKILL.md b/skills/ketchup/SKILL.md index c1b8354..5029c6b 100644 --- a/skills/ketchup/SKILL.md +++ b/skills/ketchup/SKILL.md @@ -6,9 +6,9 @@ description: >- (--video), and cross-session transcript and swarm recall (--recall). Parallel read-only ro-* gatherers inspect board.jsonl #seq deltas, members.json, Swarm UI Overview plan.json, optional narrator view.json, prior swarm boards, - git log, and gh pr state. Use for /agy-pstack-next:ketchup, /ketchup, "catch me up", - "ketchup --plain", "explain that in plain words", "ketchup --video", "recall - my work on X", or "where did I leave off". + git log, and gh pr state. Use for /agy-pstack-next:ketchup, /ketchup, + "catch me up", "ketchup --plain", "ketchup --video", "recall my work on X", + or "where did I leave off". --- # Ketchup @@ -51,7 +51,7 @@ Write in plain spoken English like one teammate catching up another. Say "the te 1. **Opening line.** One short sentence naming what waits on the human right now, or stating that nothing waits on them. If nothing changed and nothing waits, say so in one sentence and stop. 2. **Visuals first, then tight summary (under 100 words excluding visuals and action items).** - Embed real screenshots and recordings captured during the work inline. Mark any visible UI change lacking a capture with `No screenshot yet` and state plainly what changed on screen. - - Draw a small Mermaid diagram (`<=6` boxes, `<=8` words per box, conversational labels rather than `Status: pass` tags) or `xychart-beta` chart when connections, PR stacks, or measured numbers read faster visually than in prose. Markdown tables are not visuals. Never draw an uncaptured screen, invent a number, or repeat a fact across visuals and bullets. + - Generate an architecture or flow visual via `invoke_subagent` targeting `image-generator` (permitted by `hooks/guard.mjs`), or render an interactive visual via `generative_ui` when `generative_ui` is mounted in ``, whenever a visual communicates the change faster than prose. Use a small Mermaid diagram (`<=6` boxes, `<=8` words per box, conversational labels rather than `Status: pass` tags) or `xychart-beta` chart for lightweight PR stacks or measured numbers. Markdown tables are not visuals. Never draw an uncaptured screen, invent a number, or repeat a fact across visuals and bullets. - Give one short spoken-style bullet per thing the human asked for ("Checkout was timing out from an unindexed lookup and is fixed now"), naming whether it is done, running, failed, or unchecked, plus any bug caught and fixed along the way. Never mark an item done while a human decision still blocks it. - Add one line naming any remaining work the coordinator or swarm can finish autonomously without human input. 3. **Action items (~30 words per item, never truncate or replace items with a count).** @@ -73,7 +73,7 @@ Follow all gathering and action-item rules of Standard catch-up, replacing the s 1. **Progressive slide design.** Plan one core takeaway and one visual point per slide from real screenshots, diffs, and verified numbers. Mutate one visual canvas progressively across slides using consistent colors, arrows, and highlights rather than cutting between unrelated layouts. Never render bullet lists, status tables, or disconnected boxes as slides. 2. **Dedicated subtitle strip.** Place one conversational subtitle (`~10` words) in a fixed-height empty strip below the slide frame so subtitles never cover visual content. State what the picture means rather than reading out box labels. -3. **Hold timing and verification.** Burn subtitles directly into slide frames (never screen-record). Hold each slide fully visible (excluding transition motion) for at least **1 second per 3 newly added words** (counting the subtitle plus new or changed slide labels, while words inside embedded screenshots do not count). Before embedding, inspect one rendered frame per slide at chat size to verify subtitle legibility and measure frame holds directly, re-rendering any slide that clips or flashes too fast. +3. **Hold timing and verification.** Burn subtitles directly into slide frames (never screen-record). Hold each slide fully visible (excluding transition motion) for at least **1 second per 3 newly added words** (counting the subtitle plus new or changed slide labels, while words inside embedded screenshots do not count). Automated still-frame detectors miscount fade-in and fade-out transitions, so measure frame holds directly from your rendered timeline timestamps instead of relying on still-frame detectors. Before embedding, inspect one rendered frame per slide at chat size to verify subtitle legibility, re-rendering any slide that clips or flashes too fast. 4. **Reply layout.** Output the one-sentence opening line, the inline MP4 artifact, one line of remaining autonomous work, and the text **Action items** (matching option names shown in the video). If rendering fails, state that in one line and deliver the text Action items cleanly. ### 4. Cross-session recall (`/ketchup --recall`) diff --git a/skills/pstack/SKILL.md b/skills/pstack/SKILL.md index 5604694..755f4d1 100644 --- a/skills/pstack/SKILL.md +++ b/skills/pstack/SKILL.md @@ -12,94 +12,63 @@ metadata: # Pstack swarm kernel -You are the **Swarm Coordinator**. You own framing, architecture decomposition, swarm sizing, disjoint slice boundaries, judging `#seq` evidence against real artifacts, landing verified commits locally, and communicating candidly with the user. Technical execution, bulk code exploration, adversarial probing, and independent verification belong to native swarm workers. +You are the **Swarm Coordinator**. If `Coordinator role capsule` is not already in ``, read [`../../roles/coordinator.md`](../../roles/coordinator.md) before spawning workers. -## 1. Coordinator stance +Run all `/pstack` work through prefix-typed native swarm workers (`impl-*`, `cand-*`, `lead-*`, `adv-*`, `sicko-*` with `workspace: "share"`; `ro-*`, `ro-verify` with `workspace: "inherit"`). Never bypass the swarm by hand-editing multi-file changes as coordinator, and never call `run_workflow` or legacy subagent tools except `invoke_subagent` targeting `image-generator`. -- **Restate the goal first.** Open your work by stating, in your own words, the user's goal, the problem being solved, and the smallest change expected to solve it. Do not block waiting for confirmation. Carry that goal statement into every worker brief, every PR's `## Why` section, and your final report. If initial evidence proves the requested change cannot solve the user's goal, show the evidence immediately and stop. -- **Plan, delegate, judge, and integrate.** Never burn coordinator context hand-editing multi-file implementations or reading megabytes of raw logs. Keep `/brain//task.md` updated with the active topology's steps and throughput checkpoint. Inspect worker diffs and test receipts directly before merging, and never pass through a worker's self-report unchecked. -- **Candor over sycophancy.** When an approach is flawed, scope does not earn its complexity, or a hypothesis fails empirical checks, say so plainly with evidence (`Attack the Premise` in [references/principles.md](references/principles.md)). -- **Clean prose everywhere.** Write short declarative sentences in replies, briefs, commits, and docs. Never use em-dashes or mid-sentence prose colons (verbatim `open_board` text from `swarm`, `sidecar://` links, and `file://` links are exempt from the prose colon ban). Every factual claim carries its measurement, file-and-line citation, or explicit uncertainty label in the same sentence. Frame every final report around what changed for end users or callers first, and what future maintainers inherit second. +## 1. Operational kernel -## 2. Prefix-typed roster contract (`hooks/guard.mjs`) +- **Checkpointing (`task.md`).** Track active topology phases, slice fences, and verification status in `/brain//task.md`. +- **Worker briefs and models.** Workers do not mount plugin skills in ``. Resolve `` from this skill's path and pass explicit `SKILL.md` paths (plus `/roles/.md` when global `hooks.json` is inactive) in briefs. Apply `pstack-models.md` models from `` (including `monitor`; omit `model` when unset or `inherit`). Tell `share` workers to pass absolute `$PWD/...` paths, fetch cited `#seq` posts with `read_board{seqs: [...]}`, and write reports over `4` KB to `/tmp/-report.md` with a board summary. +- **Selective `monitor` and lock release.** Skip `monitor` on short single-wave runs (`<= 4` workers via `swarm_wait`). Spawn `monitor` on multi-wave or long-running swarms when `swarm_monitor` is in ``, applying `monitor` from `pstack-models.md` (or omitting when unset/`inherit`). Skip `narrator` when `swarm_pane` is in `` unless asked by name. `hooks/guard.mjs` releases `coordinator` subagent locks automatically once all task workers are killed (`[done]`). +- **Swarm UI Overview (`swarm_pane`).** When `swarm_pane` is in ``, load it before briefing workers and write `/brain//.system_generated/swarm/plan.json` after adding or changing workers (`goal.title` 4-8 words, `goal.line` up to 12 words, `tasks`, and 1-6 outcome `threads`): -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: +```json +{"goal":{"title":"Fix Hub split pane layouts","line":"Audit, fix, then verify in both themes."},"tasks":{"impl-1":"Fix split card"},"threads":[{"id":"t-1","title":"Split pane cards","goal":"Panes share one card.","tasks":["impl-1"]}]} +``` -| Roster prefix | `workspace` | Injected capsule | Runtime guard enforced by `hooks/guard.mjs` | Primary responsibility | -| --- | --- | --- | --- | --- | -| 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 ``. | + On UI tasks, tell UI workers (`impl-*`, `cand-*`, `ro-verify`) to save full-window screenshots in their own `/brain//` folder (outside `.system_generated/`) and post `Screenshot: | ` on its own line. +- **Channels, paging, and teardown.** Use `swarm{action: "title"}`, batch `tasks`/`n`, and warm `fork`. Keep `<= 8` workers on the main board; for `> 8`, open `#area` channels via `swarm{action: "channel"}` under `lead-` (`workspace: "share"`) when `"channel"` is exposed, or coordinate via `lead-` with `@lead-` mentions. Page cold starts and catch-ups via `read_board{since: , limit: 100}` from `0` to `head`, idle via `swarm_wait`, and end active-swarm user replies with verbatim `open_board` when non-empty. Hot-swap waiting workers with `swarm{action: "model"}`, `git fetch` and merge commits before `swarm{action: "kill"}` on task workers, keep `monitor` and `narrator` alive unless asked, and close with `[done] ` (no `@`). Settle empirical forks with `ro-*` probes or sketches instead of `ask_question`, and pause only before remote pushes (`PSTACK_ALLOW_PUSH=1`), PRs, or irreversible actions. -**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`. +## 2. Routing table -**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. - -**Model selection.** `~/.gemini/config/rules/pstack-models.md` (configured via `/setup-pstack`) requires `trigger: always_on` YAML frontmatter so `agy` injects it into `` on every turn. When active in context, pass one configured per-prefix `model` ID per `swarm{action: "add"}` call without calling `read_file` on that rule file manually. For comma-separated model lists (such as `cand-*` or `adv-*`), single-worker `cand-*` spawns pick the first live entry and parallel `cand-*` (or `adv-*`) spawns cycle live entries in order across individual `add` calls. Worker-spawned helpers apply the matching prefix model from `` when present and non-`inherit` (picking the first live entry or cycling in order across parallel helpers), or omit `model` to inherit their parent worker's model. When a prefix is unset or `inherit`, omit `model` so the new member inherits its caller's model. - -## 3. Native swarm mechanics - -- **Swarm title and batch spawning (`title`, `tasks`, `n`).** Call `swarm{action: "title", title: ""}` when starting a swarm so the Swarm UI names the run clearly. For parallel slices or worker pools sharing one prefix, brief, and model, `swarm{action: "add"}` accepts `tasks` (a sharded slice array spawning `-1` through `-`) or `n` (a homogeneous worker count spawning `-1` through `-`). `hooks/guard.mjs` strips trailing `-` suffixes and classifies every numbered worker under its base prefix automatically (`@` and `swarm{action: "kill", name: ""}` address the group while `@-1` targets one member). -- **Warm context handoffs (`fork`).** Pass `fork: ""` in `swarm{action: "add"}` (for example, `swarm{action: "add", name: "impl-fix", workspace: "share", fork: "ro-probe-1", brief: "..."}`) whenever an author or synthesizer builds directly on an investigator's or winning candidate's warm context. When global `hooks.json` is active, `hooks/guard.mjs` upgrades the forked worker's role capsule automatically on its first turn. When global `hooks.json` is not active, pass `/roles/.md` explicitly in the brief. -- **Topic channels when supported.** Stay on the main board for `<= 8` workers. For `> 8` concurrent workers or multi-area DAGs, check whether the live `swarm` tool declaration includes `"channel"` in `action`. When `"channel"` is present, partition traffic with `swarm{action: "channel"}` (`#area`) and assign one `lead-` (`workspace: "share"`) per channel so leaf chatter never wakes unrelated slices. When `"channel"` is absent, coordinate on the main board under `lead-` coordinators (`workspace: "share"`) with strict `@mention` discipline so leaf updates mention only `@lead-`. -- **`#seq` citations and paged board reads.** Cite board messages by sequence number (`#12`) and pull specific posts via `read_board{seqs: [12]}` or incremental deltas via `read_board{since: }`. Never copy-paste raw worker logs across briefs. Because `read_board` defaults to `limit: 20`, cold-start session pickup and catch-up after busy bursts must page `read_board{since: , limit: 100}` starting from `` (`0` on cold start) until `` reaches `head`. -- **Doorbell `@mention` hygiene.** `@name` wakes a sleeping agent and spends a turn. Never use `@name` as a passive CC. On peer handoffs (`impl-1` to `@ro-verify`), mention only the next actor and require workers to open final completion posts with `@ [done]` so the Swarm UI marks parked workers done. Post non-urgent progress unaddressed. Reserve `@all` for swarm-wide holds or interface contract changes. Sleep for free with `swarm_wait{since: }` instead of polling `read_board` in a loop. -- **Swarm UI Overview (`swarm_pane`).** When `swarm_pane` is present in ``, load `swarm_pane` before briefing workers, skip `narrator` unless the user asks for `narrator` by name, and write `/brain//.system_generated/swarm/plan.json` (`goal`, `tasks`, and 1 to 6 outcome `threads`) after adding workers. Rewrite `plan.json` whenever workers, task assignments, or goals change. On UI, layout, or visual tasks, instruct UI-facing workers (`impl-*`, `cand-*`, `ro-verify`) in their briefs to save full-window timeline screenshots under their own `/brain//` directory (outside `.system_generated/`) and flag each step on its own board line as `Screenshot: | `. Skip screenshot instructions on backend, infra, data, or docs work. -- **Show `open_board` on mid-flight status replies.** Even when you start a swarm directly without loading the built-in `swarm` skill from ``, whenever you reply to the user while the swarm is active (on the turn that launches a continuing swarm or whenever the user asks what the swarm is doing), end your reply with the verbatim `open_board` string from your latest `swarm` `add` or `status` result on its own line whenever `open_board` is non-empty. Call `swarm{action: "status"}` if none is in view, omit the line when `open_board` is empty, and never fabricate a board command or link yourself. -- **Quota and capacity hot-swap (`swarm{action: "model"}`).** On `[quota]` warnings or model capacity errors, inspect valid models via `swarm{action: "models"}` and switch the `waiting` worker (or yourself) in place with `swarm{action: "model", name, model}` while preserving full conversation history. Never `kill` and re-`add` merely to switch models. -- **Land commits BEFORE `swarm{action: "kill"}`.** `swarm{action: "kill", name}` is permanent and **deletes that worker's `share` or `branch` worktree**. Keep finished `impl-*` and `cand-*` workers parked in `waiting` (zero token cost) until you run `git fetch && git merge --no-edit FETCH_HEAD` (or `git cherry-pick `) and verify `git status --short` locally. Only after commits are safely landed in your branch, call `swarm{action: "kill"}` on every task worker (`impl-*`, `cand-*`, `lead-*`, `ro-*`, `adv-*`, `sicko-*`) while leaving built-in `monitor` and `narrator` (`*-N`) alive unless the user asks. -- **Board closure (`[done] `).** Once verification passes on the integrated tree and all task workers are killed, post `[done] ` with no `@` symbol in the text so `monitor` goes quiet before you deliver your final user reply. - -## 4. Autonomous obstacle clearing - -Absorbing the figure-it-out discipline, you own clearing obstacles end to end without stalling on the human: - -- **Settle empirical forks by running code.** Never call `ask_question` to ask which technical approach works better, how an API behaves, or whether a layout fits. Build a quick throwaway sketch or run a `ro-*` probe and let runtime evidence decide. -- **Build missing local levers.** When a codebase lacks a repro harness, codemod, trace SQLite loader, or visual diff script, build that deterministic tool first (`Build the Lever` in [references/principles.md](references/principles.md)) so verification is repeatable. -- **Design a custom phase loop when no single topology fits.** State a falsifiable exit predicate, sequence riskiest unknowns and shared foundations first, execute one verifiable unit per commit (`Sequence Verifiable Units`), and record every milestone on the board (`#seq`). -- **Pause only at true human boundaries.** Never push to a remote or open/merge a PR unless requested. Always pause before irreversible external side effects (force-pushing shared branches, production deployments, destructive external data mutations, customer-facing messages) or genuine product-taste tradeoffs no experiment can settle. - -## 5. Routing table - -Compose topologies freely when a task spans phases (such as `diagnose` -> `build` -> `ship`, or `program` coordinating `build`, `hillclimb`, and `ship`). Read the matched topology file before spawning workers: +Compose topologies freely across phases (`diagnose` to `build` to `ship`, or `program` coordinating `build`, `hillclimb`, and `ship`). Read the matched topology file before spawning workers. ### Core topologies (`topologies/*.md`) | Topology | File | When to use | | --- | --- | --- | -| **Program** | [topologies/program.md](topologies/program.md) | Multi-phase plans, `lead-` delegation (with `#area` channels when `swarm` exposes `"channel"`), stacked branch queues, unattended `/goal` or `schedule` loops, safe pause, paged cold-start pickup (`read_board{since: , limit: 100}`), and worktree disk cleanup | -| **Build** | [topologies/build.md](topologies/build.md) | Features, caller-migrating refactors (delete legacy APIs in one wave), throwaway empirical prototypes, `control-ui` visual parity loops, `sicko-*` cleanup, and `1:2-4` `ro-verify` gates | -| **Diagnose** | [topologies/diagnose.md](topologies/diagnose.md) | Bug fixes, read-only investigations, live runtime forensics, SQLite trace/heap forensics, competing `ro-*` hypothesis probes, failing repro first, and warm `fork: "ro-winner"` into `impl-fix` | -| **Hillclimb** | [topologies/hillclimb.md](topologies/hillclimb.md) | One-off perf fixes and sustained metric hillclimbs with `ro-bench` baseline and noise-floor locks, `Explain the Number` arithmetic checks, parallel `cand-*` levers, `#seq` scoreboards, and cherry-pick compounding | -| **Ship** | [topologies/ship.md](topologies/ship.md) | Local branch integration, pre-PR `ro-verify` and `/interrogate`, user-requested push and PR creation (`PSTACK_ALLOW_PUSH=1`), CI and Bugbot babysitting with `/scripts/watch-pr`, bottom-up stack landing, and `kill` teardown | -| **Evolve** | [topologies/evolve.md](topologies/evolve.md) | Authoring and evaluating skills, role capsules, and hooks using unseen holdout scenarios, blinded `agy -p --mode auto` trials across `impl-eval-*`, blind `ro-judge` grading, and structural iteration | +| **Program** | [topologies/program.md](topologies/program.md) | Multi-phase plans, `lead-` (`#area` channels when available), stacked branches, `/goal` or `schedule` loops, pause, paged pickup, and worktree cleanup | +| **Build** | [topologies/build.md](topologies/build.md) | Features, caller-migrating refactors (delete legacy APIs in one wave), prototypes, `control-ui` parity loops, conditional `sicko-*`, and `ro-verify` gates | +| **Diagnose** | [topologies/diagnose.md](topologies/diagnose.md) | Bug fixes, read-only probes, trace/heap forensics, competing `ro-*` hypotheses, failing repro first, and warm `fork: "ro-winner"` into `impl-fix` | +| **Hillclimb** | [topologies/hillclimb.md](topologies/hillclimb.md) | Perf fixes and metric hillclimbs with `ro-bench` baseline and noise-floor locks, arithmetic checks, parallel `cand-*` levers, and cherry-pick compounding | +| **Ship** | [topologies/ship.md](topologies/ship.md) | Local integration, pre-PR `ro-verify` and `/interrogate`, opt-in push (`PSTACK_ALLOW_PUSH=1`), CI/Bugbot watch via `watch-pr`, stack landing, and `kill` | +| **Evolve** | [topologies/evolve.md](topologies/evolve.md) | Skill, capsule, and hook evals with holdout scenarios, `agy -p --mode auto` trials across `impl-eval-*`, blind `ro-judge` grading, and iteration | ### Bundled references and tools -- [references/principles.md](references/principles.md) compiles all 24 engineering, architecture, verification, and swarm delegation principles. -- [references/ts-patterns.md](references/ts-patterns.md) covers TypeScript domain modeling, branded primitives, discriminated unions, boundary schemas, and exhaustiveness checks. -- [references/bugbot-triage.md](references/bugbot-triage.md) defines the `fix` / `dismiss` / `ask` rubric and field-tested patterns for automated PR review threads. -- [scripts/watch-pr](scripts/watch-pr) (`/scripts/watch-pr`) is the executable GitHub PR and queued-stack watcher (`--pr`, `--stack`, `--queued-stack`, `--status-only`, `--pretty`). +- [references/principles.md](references/principles.md) compiles the 24 engineering, verification, and delegation principles. +- [references/ts-patterns.md](references/ts-patterns.md) covers TypeScript domain modeling, branded primitives, discriminated unions, and boundary schemas. +- [references/bugbot-triage.md](references/bugbot-triage.md) defines the `fix` / `dismiss` / `ask` rubric for PR review threads. +- [scripts/watch-pr](scripts/watch-pr) (`/scripts/watch-pr`) watches GitHub PRs and queued stacks (`--pr`, `--stack`, `--queued-stack`, `--status-only`, `--pretty`). +- [scripts/check-plan.mjs](scripts/check-plan.mjs) validates Swarm UI `plan.json` schemas and multi-phase plans deterministically. +- [scripts/worktree-audit.sh](scripts/worktree-audit.sh) audits git worktrees for merge ancestry, uncommitted edits, and cleanup safety. +- [scripts/decision-log.sh](scripts/decision-log.sh) appends and inspects structured engineering decisions alongside `#seq` checkpoints. ### Sibling skills in Pstack v2 -Route specialized sub-workflows directly to their sibling skills: - | Skill | File | Role in the swarm | | --- | --- | --- | -| `/setup-pstack` | [../setup-pstack/SKILL.md](../setup-pstack/SKILL.md) | Configure `~/.gemini/config/rules/pstack-models.md` per role prefix, budget presets, workflow recipes, and `/schedule` automations | -| `/understand` | [../understand/SKILL.md](../understand/SKILL.md) | Parallel `ro-*` clue-sharing mesh for mechanism walkthroughs, git/tracker provenance archaeology, and interactive walkthroughs | -| `/crucible` | [../crucible/SKILL.md](../crucible/SKILL.md) | Competing design exploration (`sketch` or `full`) across orthogonal `cand-*` axes, cross-family `ro-judge`, and donor `cherry-pick` synthesis | -| `/interrogate` | [../interrogate/SKILL.md](../interrogate/SKILL.md) | Adversarial `adv-*` exploit reproduction and `ro-blast` transitive caller, schema, and rollout blast-radius mapping | -| `/reflect` | [../reflect/SKILL.md](../reflect/SKILL.md) | Post-mortems, mid-session correction capture, and mining `transcript.jsonl` + `board.jsonl` to encode lessons in hooks, capsules, or tests | -| `/ketchup` | [../ketchup/SKILL.md](../ketchup/SKILL.md) | Live swarm board, transcript, git, and PR catch-up briefings in standard, `--plain`, or `--video` formats | +| `/setup-pstack` | [../setup-pstack/SKILL.md](../setup-pstack/SKILL.md) | Configure `pstack-models.md` per prefix, budget presets, `sync-hooks.mjs`, recipes, and `/schedule` automations | +| `/understand` | [../understand/SKILL.md](../understand/SKILL.md) | Parallel `ro-*` clue-sharing mesh for mechanism walkthroughs, provenance archaeology, and interactive teaching | +| `/crucible` | [../crucible/SKILL.md](../crucible/SKILL.md) | Competing designs (`sketch` or `full`) across orthogonal `cand-*` axes, blind `ro-judge`, and donor `cherry-pick` synthesis | +| `/interrogate` | [../interrogate/SKILL.md](../interrogate/SKILL.md) | Adversarial `adv-*` exploit repros and `ro-blast` transitive caller, schema, and rollout blast-radius mapping | +| `/reflect` | [../reflect/SKILL.md](../reflect/SKILL.md) | Post-mortems, correction capture, and mining `transcript.jsonl` + `board.jsonl` into structural hooks, capsules, or tests | +| `/ketchup` | [../ketchup/SKILL.md](../ketchup/SKILL.md) | Live swarm, transcript, git, and PR catch-up briefings in standard, `--plain`, `--video`, or `--recall` formats | | `/bro` | [../bro/SKILL.md](../bro/SKILL.md) | Inline zero-jargon restatement of the preceding message in plain human language with no swarm fan-out | -| `/verify-gen` | [../verify-gen/SKILL.md](../verify-gen/SKILL.md) | Author and maintain (`--maintain`) behavioral E2E verification skills and formal property/state-machine (`--formal`) suites | -| `/control-ui` | [../control-ui/SKILL.md](../control-ui/SKILL.md) | Drive and inspect web, IDE, and Electron UIs with isolated ephemeral ports and per-worker browser `--user-data-dir` profiles | -| `/control-cli` | [../control-cli/SKILL.md](../control-cli/SKILL.md) | Drive interactive CLIs and TUIs with isolated PTY sessions, temp state directories, and clean environment overrides | -| `/statechart` | [../statechart/SKILL.md](../statechart/SKILL.md) | Compile, check, and render formal statecharts for stateful protocols, UI lifecycles, and swarm coordination flows | +| `/verify-gen` | [../verify-gen/SKILL.md](../verify-gen/SKILL.md) | Author and `--maintain` behavioral E2E verification skills and `--formal` property or state-machine suites | +| `/control-ui` | [../control-ui/SKILL.md](../control-ui/SKILL.md) | Drive web, IDE, and Electron UIs with ephemeral ports and isolated browser `--user-data-dir` profiles | +| `/control-cli` | [../control-cli/SKILL.md](../control-cli/SKILL.md) | Drive interactive CLIs and TUIs with isolated PTY sessions, temp state dirs, and clean env overrides | +| `/statechart` | [../statechart/SKILL.md](../statechart/SKILL.md) | Compile, check, and render formal statecharts for stateful protocols, UI lifecycles, and swarm flows | | `/technical-writing` | [../technical-writing/SKILL.md](../technical-writing/SKILL.md) | Diátaxis mode selection, STE instruction clarity, Global English precision, and zero AI-slop prose | | `/make-bot-ui` | [../make-bot-ui/SKILL.md](../make-bot-ui/SKILL.md) | Design and implement chat, agent, and bot interfaces | diff --git a/skills/pstack/scripts/check-plan.mjs b/skills/pstack/scripts/check-plan.mjs new file mode 100755 index 0000000..9a1828b --- /dev/null +++ b/skills/pstack/scripts/check-plan.mjs @@ -0,0 +1,209 @@ +#!/usr/bin/env node +import fs from "node:fs"; +import process from "node:process"; + +const RULE = + "Tests alone are not sufficient verification. A PR is verified only when its unit, live, and perf boxes are all checked."; +const LANES = /Ten lanes on `[^`<>]+` at the PR head/; +const SUB_BLOCKS = [ + "Depends on.", + "Files.", + "Build.", + "You see.", + "Verify, unit.", + "Verify, live.", + "Verify, perf.", + "Review gate.", + "Merge.", +]; +const PROGRAM_H3 = ["Arm the program", "Spawn owners", "PR mechanics", "Verdict and merge", "Boot recipe"]; +const PROGRAM_MARKERS = ["/schedule 1h", "status message"]; +const HOW_TO_READ_MARKERS = [ + "One box is one unit of work", + "names the evidence", + "Check a box only when its evidence exists", + "playbooks/", + RULE, +]; +const PERF_ITEMS = ["Metric.", "Probe.", "Baseline.", "Rule."]; +const BOX = /^\s*- \[[ x]\] (.*)$/; + +const file = process.argv[2]; +if (!file) { + console.error("Usage: node check-plan.mjs "); + process.exit(2); +} + +const raw = fs.readFileSync(file, "utf8").split(/\r?\n/); +const problems = []; +const fail = (line, message) => problems.push(`${file}:${line}: ${message}`); + +let start = 0; +if (raw[0] === "---") { + start = raw.indexOf("---", 1) + 1; +} + +const lines = []; +let fence = null; +const openingFence = (text) => { + const match = text.match(/^ {0,3}(`{3,}|~{3,})(.*)$/); + if (!match || (match[1][0] === "`" && match[2].includes("`"))) return null; + return { char: match[1][0], length: match[1].length }; +}; +const closingFence = (text, opening) => { + const match = text.match(/^ {0,3}(`+|~+)[ \t]*$/); + return Boolean( + match && + match[1][0] === opening.char && + match[1].length >= opening.length, + ); +}; +for (let i = start; i < raw.length; i++) { + const text = raw[i]; + const n = i + 1; + let code = Boolean(fence); + if (fence && closingFence(text, fence)) { + code = false; + fence = null; + } else if (!fence) { + fence = openingFence(text); + code = Boolean(fence); + } + lines.push({ n, text, code }); + if (code) continue; + const prose = text + .replace(/(? (!l.code && l.text.startsWith("## ") ? l.text.slice(3).trim() : null); +const sections = []; +for (const l of lines) { + const title = h2(l); + if (title !== null) sections.push({ title, n: l.n, body: [] }); + else if (sections.length) sections.at(-1).body.push(l); +} +const find = (title) => sections.find((s) => s.title === title); +const bodyText = (s) => s.body.map((l) => l.text).join("\n"); +const boxes = (ls) => ls.filter((l) => !l.code && BOX.test(l.text)).map((l) => ({ n: l.n, text: l.text.match(BOX)[1] })); + +const h1 = lines.findIndex((l) => !l.code && l.text.startsWith("# ")); +if (h1 === -1) fail(1, "no H1 title"); +const howToRead = find("How to read this"); +if (!howToRead) fail(1, 'no "## How to read this" section'); +if (h1 !== -1 && howToRead) { + const intro = lines.slice(h1 + 1).filter((l) => l.n < howToRead.n && l.text.trim() !== ""); + if (intro.length >= 10) fail(lines[h1].n, `intro is ${intro.length} lines, under ten required`); + for (const marker of HOW_TO_READ_MARKERS) { + if (!bodyText(howToRead).includes(marker)) fail(howToRead.n, `How to read this lacks "${marker}"`); + } +} + +const program = find("Program checklist"); +if (!program) fail(1, 'no "## Program checklist" section'); +else { + const h3s = program.body.filter((l) => !l.code && l.text.startsWith("### ")).map((l) => l.text.slice(4).trim()); + let cursor = 0; + for (const name of PROGRAM_H3) { + const at = h3s.findIndex((t, i) => i >= cursor && t.startsWith(name)); + if (at === -1) fail(program.n, `Program checklist lacks "### ${name}" in order`); + else cursor = at + 1; + } + const programBody = bodyText(program); + if (!programBody.includes("~/.gemini/config/plugins/pstack/")) { + fail(program.n, 'Program checklist lacks "~/.gemini/config/plugins/pstack/"'); + } + for (const marker of PROGRAM_MARKERS) { + if (!programBody.includes(marker)) fail(program.n, `Program checklist lacks "${marker}"`); + } +} + +const close = find("Close the program"); +if (!close) fail(1, 'no "## Close the program" section'); +const programIndex = sections.indexOf(program); +const closeIndex = sections.indexOf(close); +const prSections = programIndex === -1 || closeIndex === -1 ? [] : sections.slice(programIndex + 1, closeIndex); +if (prSections.length === 0) fail(1, "no PR sections between Program checklist and Close the program"); + +const report = []; +for (const pr of prSections) { + const heads = []; + for (const l of pr.body) { + if (l.code) continue; + const m = l.text.match(/^\*\*([^*]+)\*\*(.*)$/); + if (m && SUB_BLOCKS.includes(m[1])) heads.push({ name: m[1], n: l.n, rest: m[2].trim(), lines: [] }); + else if (heads.length) heads.at(-1).lines.push(l); + } + const names = heads.map((h) => h.name); + if (names.join("|") !== SUB_BLOCKS.join("|")) { + fail(pr.n, `${pr.title}: sub-blocks are [${names.join(", ")}], expected [${SUB_BLOCKS.join(", ")}]`); + } + const block = (name) => heads.find((h) => h.name === name); + const counts = {}; + for (const h of heads) counts[h.name] = boxes(h.lines).length; + + const depends = block("Depends on."); + if (depends && depends.rest === "") fail(depends.n, `${pr.title}: Depends on names nothing`); + for (const name of ["Files.", "Build.", "You see.", "Verify, unit.", "Merge."]) { + const b = block(name); + if (b && boxes(b.lines).length === 0) fail(b.n, `${pr.title}: ${name} has no box`); + } + for (const name of ["Verify, unit.", "Verify, live.", "Verify, perf."]) { + const b = block(name); + if (b && !b.rest.startsWith(RULE)) fail(b.n, `${pr.title}: ${name} does not open with the rule`); + } + + const live = block("Verify, live."); + if (live) { + if (!LANES.test(live.rest)) fail(live.n, `${pr.title}: Verify, live lacks "Ten lanes on \`\` at the PR head" with the model filled in`); + const lanes = boxes(live.lines).map((b) => ({ ...b, m: b.text.match(/^Lane (\d+)\. /) })); + const numbers = lanes.filter((b) => b.m).map((b) => Number(b.m[1])).sort((a, b) => a - b); + if (numbers.join(",") !== "1,2,3,4,5,6,7,8,9,10") fail(live.n, `${pr.title}: lanes are [${numbers.join(",")}], expected 1 to 10`); + for (const lane of lanes) { + if (!lane.m) fail(lane.n, `${pr.title}: live box is not a lane`); + else if (!/Save `[^`]+`/.test(lane.text)) fail(lane.n, `${pr.title}: lane ${lane.m[1]} names no screenshot`); + else if (!lane.text.includes("Pass when")) fail(lane.n, `${pr.title}: lane ${lane.m[1]} has no pass predicate`); + } + } + + const perf = block("Verify, perf."); + if (perf) { + const items = boxes(perf.lines).map((b) => b.text.split(" ")[0]); + if (items.join("|") !== PERF_ITEMS.join("|")) fail(perf.n, `${pr.title}: perf boxes are [${items.join(", ")}], expected [${PERF_ITEMS.join(", ")}]`); + } + + const gate = block("Review gate."); + if (gate) { + const gateBoxes = boxes(gate.lines); + if (gate.rest.startsWith("None.")) { + if (gateBoxes.length) fail(gate.n, `${pr.title}: Review gate says None but has boxes`); + } else { + const text = gate.lines.map((l) => l.text).join("\n"); + if (gateBoxes.length === 0) fail(gate.n, `${pr.title}: Review gate has no box`); + for (const word of ["screenshot", "video", "operator"]) { + if (!text.includes(word)) fail(gate.n, `${pr.title}: Review gate lacks "${word}"`); + } + } + } + + const total = boxes(pr.body).length; + const cells = SUB_BLOCKS.filter((s) => s !== "Depends on.").map((s) => `${s.replace(/[ ,.]+/g, "-").replace(/-$/, "").toLowerCase()}=${counts[s] ?? 0}`); + report.push(`${pr.title} boxes=${total} ${cells.join(" ")}`); +} + +if (closeIndex !== -1) { + const tail = sections.slice(closeIndex + 1); + for (const s of tail) { + if (!s.title.startsWith("Appendix")) fail(s.n, `"## ${s.title}" after Close the program is not an appendix`); + } + if (!tail.some((s) => s.title.includes("Prototype evidence"))) fail(close.n, 'no "## Appendix ... Prototype evidence" section'); +} + +for (const line of report) console.log(line); +console.log(`${prSections.length} PR sections, ${problems.length} problems`); +for (const p of problems) console.error(p); +process.exit(problems.length ? 1 : 0); diff --git a/skills/pstack/scripts/check-plan.test.mjs b/skills/pstack/scripts/check-plan.test.mjs new file mode 100644 index 0000000..28d083b --- /dev/null +++ b/skills/pstack/scripts/check-plan.test.mjs @@ -0,0 +1,173 @@ +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { spawnSync } from "node:child_process"; +import { fileURLToPath } from "node:url"; +import test from "node:test"; +import assert from "node:assert/strict"; + +const scriptDir = dirname(fileURLToPath(import.meta.url)); +const checker = join(scriptDir, "check-plan.mjs"); +const decisionLog = join(scriptDir, "decision-log.sh"); +const rule = + "Tests alone are not sufficient verification. A PR is verified only when its unit, live, and perf boxes are all checked."; + +const validPlan = `# Demo + +## How to read this +One box is one unit of work and names the evidence. Check a box only when its evidence exists. See playbooks/. +${rule} + +## Program checklist +### Arm the program +### Spawn owners +### PR mechanics +### Verdict and merge +### Boot recipe +\`~/.gemini/config/plugins/pstack/\` /schedule 1h status message + +## PR 1 +**Depends on.** None. +**Files.** +- [ ] Do the thing. +**Build.** +- [ ] Do the thing. +**You see.** +- [ ] Do the thing. +**Verify, unit.** ${rule} +- [ ] Check the thing. +**Verify, live.** ${rule} Ten lanes on \`example-model\` at the PR head +${Array.from({ length: 10 }, (_, i) => `- [ ] Lane ${i + 1}. Save \`lane-${i + 1}.png\`. Pass when evidence exists.`).join("\n")} +**Verify, perf.** ${rule} +- [ ] Metric. Recorded. +- [ ] Probe. Recorded. +- [ ] Baseline. Recorded. +- [ ] Rule. Recorded. +**Review gate.** None. +**Merge.** +- [ ] Merge when approved. + +## Close the program +Close. + +## Appendix Prototype evidence +Recorded. +`; + +const runPlan = (example, expectedExit) => { + const directory = mkdtempSync(join(tmpdir(), "check-plan-test-")); + const file = join(directory, "plan.md"); + writeFileSync(file, validPlan + example); + try { + const result = spawnSync("node", [checker, file], { encoding: "utf8" }); + assert.equal(result.status, expectedExit); + return result; + } finally { + rmSync(directory, { recursive: true, force: true }); + } +}; + +test("accepts ordinary, indented, and longer closing fences", () => { + for (const indent of ["", " ", " ", " "]) + runPlan(`${indent}\`\`\`markdown\n## Example only\n${indent}\`\`\`\n`, 0); + runPlan("```markdown\n## Example only\n````\n", 0); +}); + +test("accepts nested backticks and tilde info strings", () => { + runPlan("````markdown\n```markdown\n## Example only\n```\n````\n", 0); + runPlan("~~~markdown `info`\n## Example only\n ~~~\n", 0); +}); + +test("keeps mismatched, shorter, and suffixed closers inside the fence", () => { + runPlan("````markdown\n~~~\n## Example only\n````\n", 0); + runPlan("````markdown\n```\n## Example only\n````\n", 0); + runPlan("````markdown\n``` info\n## Example only\n````\n", 0); +}); + +test("rejects headings and prose outside a proper close", () => { + for (const suffix of [" ", "\t"]) { + const heading = runPlan(`\`\`\`markdown\n## Example only\n\`\`\`${suffix}\n## Example only\n`, 1); + assert.ok(heading.stderr.includes('"## Example only" after Close the program is not an appendix')); + } + + const prose = runPlan("```markdown\nThis prose has a mid-sentence colon: inside code\n```\nThis prose has a mid-sentence colon: bad.\n", 1); + assert.ok(prose.stderr.includes("mid-sentence colon")); +}); + +test("rejects backtick info strings containing a backtick", () => { + const result = runPlan("```markdown `invalid`\n## Example only\n```\n", 1); + assert.ok(result.stderr.includes('"## Example only" after Close the program is not an appendix')); +}); + +test("ignores prose punctuation inside matching multi-backtick code spans", () => { + for (const count of [2, 3, 4]) { + const delimiter = "`".repeat(count); + runPlan(`Use ${delimiter}echo \`x\`: “quoted” — example${delimiter}.\n`, 0); + } +}); + +test("checks prose following a multi-backtick span and unmatched delimiters", () => { + const outside = runPlan("Use ``echo `x`: y``. Bad: prose.\n", 1); + assert.ok(outside.stderr.includes("mid-sentence colon")); + const unmatched = runPlan("Use ``unclosed: bad` here.\n", 1); + assert.ok(unmatched.stderr.includes("mid-sentence colon")); +}); + +test("accepts installed Antigravity plugin path in Program checklist", () => { + const directory = mkdtempSync(join(tmpdir(), "check-plan-test-")); + const file = join(directory, "plan.md"); + writeFileSync( + file, + validPlan.replace("`~/.gemini/config/plugins/pstack/`", "`~/.gemini/config/plugins/pstack/skills/swarm/SKILL.md`"), + ); + try { + const result = spawnSync("node", [checker, file], { encoding: "utf8" }); + assert.equal(result.status, 0); + } finally { + rmSync(directory, { recursive: true, force: true }); + } +}); + +test("decision-log.sh sanitizes tabs, newlines, CRs, and spreadsheet formula prefixes", () => { + const directory = mkdtempSync(join(tmpdir(), "decision-log-test-")); + const logfile = join(directory, "nested", "decisions.tsv"); + try { + const badArgs = spawnSync(decisionLog, [logfile, "phase"], { encoding: "utf8" }); + assert.equal(badArgs.status, 1); + + const run1 = spawnSync( + decisionLog, + [logfile, "=phase\t1", "+decision\nline", "-why\rcr", "@evidence", "ok"], + { encoding: "utf8" }, + ); + assert.equal(run1.status, 0); + + const run2 = spawnSync( + decisionLog, + [logfile, "normal", "safe", "reason", "link", "pass"], + { encoding: "utf8" }, + ); + assert.equal(run2.status, 0); + + const rows = readFileSync(logfile, "utf8").trimEnd().split("\n"); + assert.equal(rows.length, 3); + assert.equal(rows[0], "ts\tphase\tdecision\twhy\tevidence\tresult"); + + const cols1 = rows[1].split("\t"); + assert.equal(cols1.length, 6); + assert.match(cols1[0], /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/); + assert.deepEqual(cols1.slice(1), [ + "'=phase 1", + "'+decision line", + "'-why cr", + "'@evidence", + "ok", + ]); + + const cols2 = rows[2].split("\t"); + assert.equal(cols2.length, 6); + assert.deepEqual(cols2.slice(1), ["normal", "safe", "reason", "link", "pass"]); + } finally { + rmSync(directory, { recursive: true, force: true }); + } +}); diff --git a/skills/pstack/scripts/decision-log.sh b/skills/pstack/scripts/decision-log.sh new file mode 100755 index 0000000..2a4c805 --- /dev/null +++ b/skills/pstack/scripts/decision-log.sh @@ -0,0 +1,34 @@ +#!/usr/bin/env bash +# Append a well-formed row to a pstack decision log (TSV). +# Usage: decision-log.sh +set -euo pipefail + +if [ "$#" -ne 6 ]; then + printf 'usage: decision-log.sh \n' >&2 + exit 1 +fi + +logfile="$1" +shift + +logdir="$(dirname "$logfile")" +if [ -n "$logdir" ] && [ "$logdir" != "." ] && [ ! -d "$logdir" ]; then + mkdir -p "$logdir" +fi + +if [ ! -s "$logfile" ]; then + printf 'ts\tphase\tdecision\twhy\tevidence\tresult\n' >> "$logfile" +fi + +ts="$(date -u +%Y-%m-%dT%H:%M:%SZ)" +clean() { + local v + v=$(printf '%s' "$1" | tr '\t\n\r' ' ') + case "$v" in + =*|+*|-*|@*) printf "'%s" "$v" ;; + *) printf '%s' "$v" ;; + esac +} +printf '%s\t%s\t%s\t%s\t%s\t%s\n' \ + "$ts" "$(clean "$1")" "$(clean "$2")" "$(clean "$3")" "$(clean "$4")" "$(clean "$5")" \ + >> "$logfile" diff --git a/skills/pstack/scripts/watch-pr b/skills/pstack/scripts/watch-pr index 7d5f597..2af4b29 100755 --- a/skills/pstack/scripts/watch-pr +++ b/skills/pstack/scripts/watch-pr @@ -1,8 +1,10 @@ #!/usr/bin/env node import { spawn } from "node:child_process"; import { realpathSync } from "node:fs"; +import { resolve } from "node:path"; import { setTimeout as delay } from "node:timers/promises"; import { fileURLToPath } from "node:url"; +import { parseArgs as parseNodeArgs } from "node:util"; const REVIEW_THREADS_QUERY = ` query ReviewThreads($owner: String!, $repo: String!, $pr: Int!, $after: String) { @@ -108,7 +110,7 @@ const AUTOMATION_TOKENS = [ "review automation", ]; -class CliUsageError extends Error { +export class CliUsageError extends Error { constructor(message, exitCode = 64) { super(message); this.name = "CliUsageError"; @@ -116,7 +118,7 @@ class CliUsageError extends Error { } } -class WatcherQueryError extends Error { +export class WatcherQueryError extends Error { constructor(failure) { super(failure.detail); this.name = "WatcherQueryError"; @@ -128,7 +130,7 @@ function nonEmpty(items) { return items.length === 0 ? null : [items[0], ...items.slice(1)]; } -function parsePrNumber(value, label = "PR number") { +export function parsePrNumber(value, label = "PR number") { if (typeof value !== "number" || !Number.isInteger(value) || value <= 0) { throw new Error(`${label} must be a positive integer`); } @@ -709,7 +711,7 @@ export class GhGitHubReader { } } -async function resolveChecks(reader, context) { +export async function resolveChecks(reader, context) { const fast = await reader.checksFastPath(context); const direct = fast.kind === "checks" ? nonEmpty(fast.checks) : null; if (direct !== null) return { source: "gh-pr-checks", checks: direct }; @@ -733,7 +735,7 @@ async function resolveChecks(reader, context) { }); } -async function resolveReviewThreads(reader, context) { +export async function resolveReviewThreads(reader, context) { const threads = []; let after = null; do { @@ -814,7 +816,7 @@ export async function discoverStack(reader, context) { return orderStack(context, await reader.openPullRequests(context)); } -function assessGitHubMerge(args) { +export function assessGitHubMerge(args) { if (args.mergeStateStatus === "BLOCKED") { if (args.headRollupState === "ERROR" || args.headRollupState === "FAILURE") { return { @@ -856,7 +858,7 @@ async function mergeAssessment(reader, facts) { }; } -async function readSnapshot(args) { +export async function readSnapshot(args) { const facts = await args.reader.pullRequest(args.context); if (facts.state === "MERGED" || facts.mergedAt !== null) { return { kind: "merged", context: args.context, facts }; @@ -1009,7 +1011,7 @@ function readyContribution(row, allowDraft) { }; } -function classifyPr(row, allowDraft = false) { +export function classifyPr(row, allowDraft = false) { for (const blocker of [ conflictBlocker(row), threadBlocker(row), @@ -1028,7 +1030,7 @@ function classifyPr(row, allowDraft = false) { : { kind: "ready", pr: ready }; } -function selectTierMajorStackDecision(rows, allowDraft = false) { +export function selectTierMajorStackDecision(rows, allowDraft = false) { for (const tier of [conflictBlocker, threadBlocker, ciBlocker]) { for (const row of rows) { const blocker = tier(row); @@ -1059,7 +1061,7 @@ function selectTierMajorStackDecision(rows, allowDraft = false) { return { kind: "clear", prs }; } -const queryBackoffSeconds = (interval, failures) => +export const queryBackoffSeconds = (interval, failures) => Math.min(Math.max(interval, 60) * 2 ** (failures - 1), 300); function verdictFactory(clock, mode) { @@ -1161,7 +1163,7 @@ async function pollUntilTerminal(args) { } } -async function runSimple(args) { +export async function runSimple(args) { const stamp = verdictFactory(args.dependencies.clock, args.mode); const step = async () => { const rows = []; @@ -1266,7 +1268,7 @@ async function runSimple(args) { }); } -const createQueueState = (queue, now) => ({ +export const createQueueState = (queue, now) => ({ queue, snapshots: new Map(), work: { kind: "whole-stack-sweep", remaining: queue }, @@ -1285,7 +1287,7 @@ const orderedRows = (state) => const activeRows = (state) => orderedRows(state).filter((row) => row.kind !== "merged"); -function planQueue(state, now) { +export function planQueue(state, now) { if (state.work !== null) return state; if (state.snapshots.size === 0 || now >= state.nextSweepAt) { const remaining = nonEmpty( @@ -1303,7 +1305,7 @@ function planQueue(state, now) { : { ...state, work: { kind: "frontier-poll", frontier } }; } -function applyQueueSnapshot(state, snapshot, now, options) { +export function applyQueueSnapshot(state, snapshot, now, options) { if (state.work === null) throw new Error("queue has no read in flight"); const snapshots = new Map(state.snapshots); snapshots.set(snapshot.context.number, snapshot); @@ -1337,7 +1339,7 @@ function applyQueueSnapshot(state, snapshot, now, options) { }; } -function evaluateQueue(state, now, options) { +export function evaluateQueue(state, now, options) { const active = activeRows(state); if (active.length === 0) { const merged = nonEmpty( @@ -1400,7 +1402,7 @@ function evaluateQueue(state, now, options) { }; } -async function runQueued(args) { +export async function runQueued(args) { let state = createQueueState(args.contexts, args.dependencies.clock.now()); const stamp = verdictFactory(args.dependencies.clock, "queued-stack"); args.dependencies.emit( @@ -1719,7 +1721,8 @@ Options: `; function parsePositiveNumber(flag, value) { - const parsed = Number(value); + const trimmed = String(value).trim(); + const parsed = trimmed === "" ? NaN : Number(trimmed); if (!Number.isFinite(parsed) || parsed <= 0) { throw new CliUsageError(`error: option '${flag}' argument '${value}' is invalid. must be greater than zero\n`); } @@ -1727,7 +1730,8 @@ function parsePositiveNumber(flag, value) { } function parseNonNegativeNumber(flag, value) { - const parsed = Number(value); + const trimmed = String(value).trim(); + const parsed = trimmed === "" ? NaN : Number(trimmed); if (!Number.isFinite(parsed) || parsed < 0) { throw new CliUsageError(`error: option '${flag}' argument '${value}' is invalid. must be zero or greater\n`); } @@ -1735,7 +1739,8 @@ function parseNonNegativeNumber(flag, value) { } function parsePositiveInteger(flag, value) { - const parsed = Number(value); + const trimmed = String(value).trim(); + const parsed = trimmed === "" ? NaN : Number(trimmed); if (!Number.isInteger(parsed) || parsed <= 0) { throw new CliUsageError(`error: option '${flag}' argument '${value}' is invalid. must be a positive integer\n`); } @@ -1743,8 +1748,9 @@ function parsePositiveInteger(flag, value) { } function parseCliPrNumber(flag, value) { + const trimmed = String(value).trim().replace(/^#/, ""); try { - return parsePrNumber(Number(String(value).replace(/^#/, ""))); + return parsePrNumber(trimmed === "" ? NaN : Number(trimmed)); } catch { throw new CliUsageError(`error: option '${flag}' argument '${value}' is invalid. must be a positive integer\n`); } @@ -1764,88 +1770,70 @@ function parseStackPrList(flag, value) { return parsed; } -export function parseArgs(argv, io) { - let owner = null; - let repo = null; - let pr = null; - let stack = false; - let queuedStack = false; - let stackPrs; - let interval = 60; - let sweepInterval = 300; - let timeout = 0; - let maxQueryErrors = 5; - let statusOnly = false; - let allowDraft = false; - let pretty = false; - - const needValue = (flag, idx) => { - if (idx + 1 >= argv.length) { - throw new CliUsageError(`error: option '${flag}' argument missing\n`); - } - return argv[idx + 1]; - }; +const CLI_OPTIONS = { + owner: { type: "string" }, + repo: { type: "string" }, + pr: { type: "string" }, + stack: { type: "boolean", default: false }, + "queued-stack": { type: "boolean", default: false }, + "stack-prs": { type: "string" }, + interval: { type: "string" }, + "sweep-interval": { type: "string" }, + timeout: { type: "string" }, + "max-query-errors": { type: "string" }, + "status-only": { type: "boolean", default: false }, + "allow-draft": { type: "boolean", default: false }, + pretty: { type: "boolean", default: false }, + help: { type: "boolean", short: "h", default: false }, +}; - for (let i = 0; i < argv.length; i += 1) { - const rawArg = argv[i]; - if (rawArg === "-h" || rawArg === "--help") { - io.stdout(HELP_TEXT); - throw new CliUsageError("", 0); - } - const eqIndex = rawArg.indexOf("="); - const flag = eqIndex >= 0 ? rawArg.slice(0, eqIndex) : rawArg; - const inlineVal = eqIndex >= 0 ? rawArg.slice(eqIndex + 1) : null; - const takeVal = () => { - if (inlineVal !== null) return inlineVal; - const val = needValue(flag, i); - i += 1; - return val; - }; - - switch (flag) { - case "--owner": - owner = takeVal(); - break; - case "--repo": - repo = takeVal(); - break; - case "--pr": - pr = parseCliPrNumber(flag, takeVal()); - break; - case "--stack": - stack = true; - break; - case "--queued-stack": - queuedStack = true; - break; - case "--stack-prs": - stackPrs = parseStackPrList(flag, takeVal()); - break; - case "--interval": - interval = parsePositiveNumber(flag, takeVal()); - break; - case "--sweep-interval": - sweepInterval = parsePositiveNumber(flag, takeVal()); - break; - case "--timeout": - timeout = parseNonNegativeNumber(flag, takeVal()); - break; - case "--max-query-errors": - maxQueryErrors = parsePositiveInteger(flag, takeVal()); - break; - case "--status-only": - statusOnly = true; - break; - case "--allow-draft": - allowDraft = true; - break; - case "--pretty": - pretty = true; - break; - default: - throw new CliUsageError(`error: unknown option '${rawArg}'\n`); - } - } +export function parseArgs(argv, io) { + let values; + try { + ({ values } = parseNodeArgs({ + args: argv, + options: CLI_OPTIONS, + strict: true, + allowPositionals: false, + })); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + throw new CliUsageError(`error: ${message}\n`); + } + + if (values.help) { + io.stdout(HELP_TEXT); + throw new CliUsageError("", 0); + } + + const owner = values.owner ?? null; + const repo = values.repo ?? null; + const pr = values.pr !== undefined ? parseCliPrNumber("--pr", values.pr) : null; + const stack = values.stack; + const queuedStack = values["queued-stack"]; + const stackPrs = + values["stack-prs"] !== undefined + ? parseStackPrList("--stack-prs", values["stack-prs"]) + : undefined; + const interval = + values.interval !== undefined + ? parsePositiveNumber("--interval", values.interval) + : 60; + const sweepInterval = + values["sweep-interval"] !== undefined + ? parsePositiveNumber("--sweep-interval", values["sweep-interval"]) + : 300; + const timeout = + values.timeout !== undefined + ? parseNonNegativeNumber("--timeout", values.timeout) + : 0; + const maxQueryErrors = + values["max-query-errors"] !== undefined + ? parsePositiveInteger("--max-query-errors", values["max-query-errors"]) + : 5; + const statusOnly = values["status-only"]; + const allowDraft = values["allow-draft"]; + const pretty = values.pretty; if (stack && queuedStack) { throw new CliUsageError( @@ -1940,10 +1928,18 @@ export async function main(argv, runtime = realRuntime()) { return verdict.exitCode; } -const isMain = - process.argv[1] !== undefined && - realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url)); +function isEntrypoint() { + if (!process.argv[1]) return false; + try { + return ( + realpathSync(resolve(process.argv[1])) === + realpathSync(fileURLToPath(import.meta.url)) + ); + } catch { + return false; + } +} -if (isMain) { +if (isEntrypoint()) { process.exitCode = await main(process.argv.slice(2)); } diff --git a/skills/pstack/scripts/watch-pr.test.mjs b/skills/pstack/scripts/watch-pr.test.mjs new file mode 100644 index 0000000..3a5c0f4 --- /dev/null +++ b/skills/pstack/scripts/watch-pr.test.mjs @@ -0,0 +1,1426 @@ +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { + CliUsageError, + GhGitHubReader, + WatcherQueryError, + applyQueueSnapshot, + assessGitHubMerge, + buildReviewThreads, + classifyPr, + createQueueState, + evaluateQueue, + main, + mapRollupNode, + orderStack, + parseArgs, + parseFastCheck, + parsePrNumber, + parsePullRequest, + parseReviewThreadPage, + planQueue, + queryBackoffSeconds, + readSnapshot, + renderJson, + renderPretty, + resolveChecks, + resolveContext, + resolveReviewThreads, + runQueued, + runSimple, + selectTierMajorStackDecision, +} from "./watch-pr"; + +const scriptDir = dirname(fileURLToPath(import.meta.url)); +const watchPrPath = join(scriptDir, "watch-pr"); +const watchPrUrl = pathToFileURL(watchPrPath).href; + +const silentIo = { stdout: () => {}, stderr: () => {} }; + +function toRawThread(thread) { + return { id: thread.id, firstComment: thread.firstComment, resolved: false }; +} + +function passingCheck(name = "ci") { + return { + kind: "passed", + name, + reportedState: "SUCCESS", + description: "", + link: "", + workflow: "", + }; +} + +function pendingCheck(name = "ci") { + return { + kind: "pending", + name, + reportedState: "PENDING", + description: "", + link: "", + workflow: "", + }; +} + +function failedCheck(name = "ci") { + return { + kind: "failed", + name, + reportedState: "FAILURE", + description: "", + link: "", + workflow: "", + }; +} + +function fakeReader(options = {}) { + const calls = []; + const context = options.current ?? { + owner: "owner", + repo: "repo", + number: parsePrNumber(1), + }; + const defaults = { + context, + mergeable: "MERGEABLE", + mergeStateStatus: "CLEAN", + reviewDecision: "APPROVED", + headRefOid: "head", + headRefName: "feature", + baseRefName: "main", + state: "OPEN", + mergedAt: null, + isDraft: false, + }; + let page = 0; + let threadPage = 0; + return { + calls, + async originRepo() { + calls.push("originRepo"); + return options.origin === undefined + ? { owner: "owner", repo: "repo" } + : options.origin; + }, + async currentPr(pr) { + calls.push("currentPr"); + return { ...context, number: pr ?? context.number }; + }, + async pullRequest(requested) { + calls.push("pullRequest"); + return { ...defaults, ...options.facts, context: requested }; + }, + async openPullRequests() { + calls.push("openPullRequests"); + return options.openPullRequests ?? []; + }, + async checksFastPath() { + calls.push("checksFastPath"); + return options.fastPath ?? { kind: "checks", checks: [passingCheck()] }; + }, + async checkRollupPage(_requested, after) { + calls.push(`checkRollupPage:${after ?? "null"}`); + return options.rollupPages?.[page++] ?? { checks: [], endCursor: null }; + }, + async reviewThreadPage(_requested, after) { + calls.push(`reviewThreadPage:${after ?? "null"}`); + return ( + options.threadPages?.[threadPage++] ?? { + threads: (options.threads ?? []).map(toRawThread), + endCursor: null, + } + ); + }, + async commitRollups() { + calls.push("commitRollups"); + return options.commitRollups ?? [{ oid: "head", state: "SUCCESS" }]; + }, + }; +} + +function testRuntime(reader) { + const stdout = []; + const stderr = []; + return { + stdout, + stderr, + runtime: { + reader, + clock: { + now: () => 0, + observedAt: () => "2026-07-26T00:00:00.000Z", + async sleep() { + throw new Error("test unexpectedly slept"); + }, + }, + stdout: (value) => stdout.push(value), + stderr: (value) => stderr.push(value), + }, + }; +} + +describe("parseArgs", () => { + it("uses the specified defaults", () => { + assert.deepEqual(parseArgs([], silentIo), { + owner: null, + repo: null, + pr: null, + mode: "single", + stackPrs: [], + statusOnly: false, + pretty: false, + polling: { + interval: 60, + sweepInterval: 300, + timeout: 0, + maxQueryErrors: 5, + allowDraft: false, + }, + }); + }); + + it("parses a frozen queued stack bottom-to-top", () => { + const parsed = parseArgs( + [ + "--queued-stack", + "--stack-prs", + "#10, 11,#12", + "--interval", + "2.5", + "--sweep-interval", + "30", + "--timeout", + "0", + "--max-query-errors", + "3", + "--allow-draft", + "--pretty", + ], + silentIo + ); + assert.equal(parsed.mode, "queued-stack"); + assert.deepEqual(parsed.stackPrs.map(Number), [10, 11, 12]); + assert.deepEqual(parsed.polling, { + interval: 2.5, + sweepInterval: 30, + timeout: 0, + maxQueryErrors: 3, + allowDraft: true, + }); + assert.equal(parsed.pretty, true); + }); + + it("rejects every invalid mode and numeric shape as usage", async () => { + const invalid = [ + ["--unknown"], + ["--interval", "0"], + ["--sweep-interval", "-1"], + ["--timeout", "-1"], + ["--max-query-errors", "1.5"], + ["--stack", "--queued-stack"], + ["--stack-prs", "1,2"], + ["--queued-stack", "--stack-prs", "1,1"], + ]; + for (const argv of invalid) { + const harness = testRuntime(fakeReader()); + assert.equal(await main(argv, harness.runtime), 64); + assert.deepEqual(harness.stdout, []); + assert.ok(harness.stderr.join("").includes("error:")); + } + }); + + it("rejects boolean flags with =false arguments as CliUsageError (exit 64)", async () => { + const negated = [ + "--stack=false", + "--pretty=false", + "--status-only=false", + "--allow-draft=false", + "--queued-stack=false", + ]; + for (const flag of negated) { + assert.throws( + () => parseArgs([flag], silentIo), + (err) => err instanceof CliUsageError && err.exitCode === 64 + ); + const harness = testRuntime(fakeReader()); + assert.equal(await main([flag], harness.runtime), 64); + assert.deepEqual(harness.stdout, []); + assert.ok(harness.stderr.join("").includes("error:")); + } + }); +}); + +describe("rendering", () => { + const context = { + owner: "owner", + repo: "repo", + number: parsePrNumber(1), + }; + const status = { + schemaVersion: 1, + sequence: 1, + observedAt: "2026-07-26T00:00:00.000Z", + mode: "single", + kind: "STATUS", + terminal: true, + exitCode: 0, + reason: "status-only", + rows: [ + { + kind: "merged", + context, + facts: { + context, + mergeable: "MERGEABLE", + mergeStateStatus: "CLEAN", + reviewDecision: "APPROVED", + headRefOid: "head", + headRefName: "feature", + baseRefName: "main", + state: "MERGED", + mergedAt: "now", + isDraft: false, + }, + }, + ], + }; + + it("emits compact valid JSON by default", () => { + const rendered = renderJson(status); + assert.equal(rendered.endsWith("\n"), true); + assert.deepEqual(JSON.parse(rendered), status); + }); + + it("renders the Markdown table from the same verdict only", () => { + const rendered = renderPretty(status); + assert.ok(rendered.includes("| PR | CI | Review | Merge |")); + assert.ok( + rendered.includes( + "| [#1](https://github.com/owner/repo/pull/1) | - | - | merged |" + ) + ); + }); +}); + +describe("main", () => { + it("returns EX_USAGE 64 and writes usage errors only to stderr", async () => { + const harness = testRuntime(fakeReader()); + assert.equal(await main(["--interval", "0"], harness.runtime), 64); + assert.deepEqual(harness.stdout, []); + assert.ok( + harness.stderr + .join("") + .includes("option '--interval' argument '0' is invalid") + ); + }); + + it("bypasses the queue machine for queued-stack status-only", async () => { + const reader = fakeReader(); + const harness = testRuntime(reader); + const code = await main( + [ + "--owner", + "owner", + "--repo", + "repo", + "--queued-stack", + "--stack-prs", + "1", + "--status-only", + ], + harness.runtime + ); + assert.equal(code, 0); + assert.equal(harness.stdout.length, 1); + const verdict = JSON.parse(harness.stdout[0]); + assert.equal(verdict.kind, "STATUS"); + assert.equal(verdict.terminal, true); + assert.equal(verdict.exitCode, 0); + assert.equal(verdict.mode, "queued-stack"); + assert.ok(!harness.stdout[0].includes('"kind":"QUEUE"')); + }); + + it("returns exit 4 for a hidden GitHub-side CI refusal", async () => { + const reader = fakeReader({ + facts: { mergeStateStatus: "BLOCKED" }, + fastPath: { kind: "checks", checks: [passingCheck()] }, + commitRollups: [{ oid: "head", state: "FAILURE" }], + }); + const harness = testRuntime(reader); + const code = await main( + ["--owner", "owner", "--repo", "repo", "--pr", "1"], + harness.runtime + ); + assert.equal(code, 4); + assert.equal(harness.stdout.length, 1); + const verdict = JSON.parse(harness.stdout[0]); + assert.equal(verdict.kind, "BLOCKER"); + assert.equal(verdict.exitCode, 4); + assert.equal(verdict.blocker.kind, "failing-checks"); + assert.equal(verdict.blocker.ci.kind, "ci-github-rejected"); + }); + + it("shows help without touching the reader", async () => { + const reader = fakeReader(); + const harness = testRuntime(reader); + assert.equal(await main(["--help"], harness.runtime), 0); + assert.ok(harness.stdout.join("").includes("JSON (NDJSON while polling)")); + assert.deepEqual(reader.calls, []); + }); + + it("does not throw ENOENT when imported via stdin (node --input-type=module -)", () => { + const child = spawnSync( + process.execPath, + ["--input-type=module", "-"], + { + input: `import { parseArgs } from ${JSON.stringify(watchPrUrl)}; console.log(typeof parseArgs);`, + encoding: "utf8", + timeout: 2000, + } + ); + assert.equal(child.error, undefined); + assert.equal(child.status, 0); + assert.equal(child.stdout.trim(), "function"); + }); +}); + +const ghContext = { + owner: "owner", + repo: "repo", + number: parsePrNumber(42), +}; + +describe("checks fallback chain", () => { + it("uses a non-empty fast-path result without a rollup query", async () => { + const reader = fakeReader({ + fastPath: { kind: "checks", checks: [passingCheck("fast")] }, + }); + const read = await resolveChecks(reader, ghContext); + assert.equal(read.source, "gh-pr-checks"); + assert.deepEqual( + read.checks.map((check) => check.name), + ["fast"] + ); + assert.deepEqual(reader.calls, ["checksFastPath"]); + }); + + it("paginates GraphQL when the fast path is unusable", async () => { + const reader = fakeReader({ + fastPath: { kind: "unusable", exitCode: 8, stderr: "" }, + rollupPages: [ + { checks: [passingCheck("first")], endCursor: "next" }, + { checks: [failedCheck("second")], endCursor: null }, + ], + }); + const read = await resolveChecks(reader, ghContext); + assert.equal(read.source, "graphql-rollup"); + assert.deepEqual( + read.checks.map((check) => check.name), + ["first", "second"] + ); + assert.deepEqual(reader.calls, [ + "checksFastPath", + "checkRollupPage:null", + "checkRollupPage:next", + ]); + }); + + it("falls back when valid fast-path JSON represented an empty list", async () => { + const reader = fakeReader({ + fastPath: { kind: "checks", checks: [] }, + rollupPages: [{ checks: [pendingCheck("fallback")], endCursor: null }], + }); + assert.equal((await resolveChecks(reader, ghContext)).checks[0].name, "fallback"); + assert.deepEqual(reader.calls, ["checksFastPath", "checkRollupPage:null"]); + }); + + it("fails closed when both paths are empty", async () => { + const reader = fakeReader({ + fastPath: { + kind: "unusable", + exitCode: 8, + stderr: "credential cannot read checks", + }, + }); + await assert.rejects( + () => resolveChecks(reader, ghContext), + (error) => + error instanceof WatcherQueryError && + error.failure.kind === "checks-unavailable" + ); + assert.deepEqual(reader.calls, ["checksFastPath", "checkRollupPage:null"]); + }); +}); + +describe("rollup node mapping", () => { + it("maps terminal and non-terminal CheckRun states fail closed", () => { + const cases = [ + ["IN_PROGRESS", null, "pending", "PENDING"], + ["COMPLETED", "SUCCESS", "passed", "SUCCESS"], + ["COMPLETED", "NEUTRAL", "skipped", "NEUTRAL"], + ["COMPLETED", "SKIPPED", "skipped", "SKIPPED"], + ["COMPLETED", "ACTION_REQUIRED", "failed", "ACTION_REQUIRED"], + ["COMPLETED", "TIMED_OUT", "failed", "FAILURE"], + ["COMPLETED", "FUTURE_VALUE", "failed", "FAILURE"], + ]; + for (const [status, conclusion, kind, reportedState] of cases) { + const mapped = mapRollupNode({ + __typename: "CheckRun", + name: "ci", + status, + conclusion, + }); + assert.equal(mapped.kind, kind); + assert.equal(mapped.reportedState, reportedState); + } + }); + + it("classifies an in-progress Code Review Gate from the rollup as the gate", () => { + assert.equal( + mapRollupNode({ + __typename: "CheckRun", + name: "Code Review Gate", + status: "IN_PROGRESS", + conclusion: null, + }).kind, + "code-review-gate" + ); + assert.equal( + mapRollupNode({ + __typename: "StatusContext", + context: "Code Review Gate", + state: "PENDING", + }).kind, + "code-review-gate" + ); + }); + + it("classifies a Code Review Gate waiting on an owner approval as the gate", () => { + const mapped = mapRollupNode({ + __typename: "CheckRun", + name: "Code Review Gate", + status: "COMPLETED", + conclusion: "ACTION_REQUIRED", + description: "1 of 2 policies", + }); + assert.equal(mapped.kind, "code-review-gate"); + assert.equal(mapped.reportedState, "ACTION_REQUIRED"); + }); + + it("classifies a fast-path Code Review Gate waiting on an owner approval as the gate", () => { + const gate = parseFastCheck({ + name: "Code Review Gate", + state: "ACTION_REQUIRED", + bucket: "fail", + }); + assert.equal(gate.kind, "code-review-gate"); + assert.equal(gate.reportedState, "ACTION_REQUIRED"); + + const regular = parseFastCheck({ + name: "ci", + state: "ACTION_REQUIRED", + bucket: "fail", + }); + assert.equal(regular.kind, "failed"); + assert.equal(regular.reportedState, "ACTION_REQUIRED"); + }); + + it("maps StatusContext states and drops unknown typenames", () => { + const pending = mapRollupNode({ + __typename: "StatusContext", + context: "ci", + state: "EXPECTED", + }); + assert.equal(pending.kind, "pending"); + assert.equal(pending.reportedState, "PENDING"); + + const unknown = mapRollupNode({ + __typename: "StatusContext", + context: "ci", + state: "FUTURE_VALUE", + }); + assert.equal(unknown.kind, "failed"); + assert.equal(unknown.reportedState, "FUTURE_VALUE"); + + assert.equal(mapRollupNode({ __typename: "FutureNode" }), null); + }); +}); + +describe("closed enum parsing", () => { + const rawPullRequest = { + mergeable: "MERGEABLE", + mergeStateStatus: "CLEAN", + reviewDecision: "APPROVED", + headRefOid: "head", + headRefName: "feature", + baseRefName: "main", + state: "OPEN", + mergedAt: null, + isDraft: false, + }; + + it("accepts mergeStateStatus CONFLICTING", () => { + assert.equal( + parsePullRequest( + { ...rawPullRequest, mergeStateStatus: "CONFLICTING" }, + ghContext + ).mergeStateStatus, + "CONFLICTING" + ); + }); + + it("reads gh's empty reviewDecision as no decision rather than a parse failure", () => { + assert.equal( + parsePullRequest({ ...rawPullRequest, reviewDecision: "" }, ghContext) + .reviewDecision, + null + ); + }); + + it("still rejects an unknown reviewDecision", () => { + assert.throws( + () => + parsePullRequest( + { ...rawPullRequest, reviewDecision: "MAYBE" }, + ghContext + ), + WatcherQueryError + ); + }); + + it("rejects unknown enum values as retryable errors carrying the raw value", () => { + assert.throws( + () => + parsePullRequest( + { ...rawPullRequest, mergeStateStatus: "FUTURE_STATE" }, + ghContext + ), + (error) => { + assert.ok(error instanceof WatcherQueryError); + assert.equal(error.failure.kind, "missing-key"); + assert.equal(error.failure.retryable, true); + assert.equal(error.failure.rawValue, '"FUTURE_STATE"'); + return true; + } + ); + }); +}); + +it("annotates Bugbot threads with distinct review-pass counts", () => { + const response = { + data: { + repository: { + pullRequest: { + reviewThreads: { + pageInfo: { hasNextPage: false, endCursor: null }, + nodes: [ + { + id: "one", + isResolved: false, + comments: { + nodes: [ + { + body: "RUN_ID: run-1", + createdAt: "now", + path: "a.ts", + line: 1, + author: { login: "bugbot" }, + }, + ], + }, + }, + { + id: "two", + isResolved: false, + comments: { + nodes: [ + { + body: "CURSOR_AUTOMATION_ID: run-2 severity high", + createdAt: "now", + path: null, + line: null, + author: { login: "cursor" }, + }, + ], + }, + }, + { + id: "resolved", + isResolved: true, + comments: { + nodes: [ + { + body: "RUN_ID: run-3", + createdAt: "now", + path: null, + line: null, + author: { login: "bugbot" }, + }, + ], + }, + }, + ], + }, + }, + }, + }, + }; + const threads = buildReviewThreads(parseReviewThreadPage(response).threads); + assert.equal(threads.length, 2); + assert.deepEqual( + threads.map((thread) => thread.isBugbot), + [true, true] + ); + assert.deepEqual( + threads.map((thread) => thread.bugbotReviewPasses), + [3, 3] + ); +}); + +describe("review thread pagination", () => { + const thread = (id, resolved = false) => ({ + id, + firstComment: { + authorLogin: "someone", + body: "please fix", + path: "a.ts", + line: 1, + createdAt: "now", + }, + resolved, + }); + + it("keeps walking pages until the cursor is exhausted", async () => { + const reader = fakeReader({ + threadPages: [ + { threads: [thread("one")], endCursor: "next" }, + { threads: [thread("two")], endCursor: "last" }, + { threads: [thread("three")], endCursor: null }, + ], + }); + const threads = await resolveReviewThreads(reader, ghContext); + assert.deepEqual( + threads.map((item) => item.id), + ["one", "two", "three"] + ); + assert.deepEqual(reader.calls, [ + "reviewThreadPage:null", + "reviewThreadPage:next", + "reviewThreadPage:last", + ]); + }); + + it("sees an unresolved thread that sits past the first page", async () => { + const reader = fakeReader({ + threadPages: [ + { threads: [thread("early", true)], endCursor: "next" }, + { threads: [thread("late")], endCursor: null }, + ], + }); + const threads = await resolveReviewThreads(reader, ghContext); + assert.deepEqual( + threads.map((item) => item.id), + ["late"] + ); + }); + + it("stops after a single page when the cursor is exhausted", async () => { + const reader = fakeReader({ + threadPages: [{ threads: [thread("only")], endCursor: null }], + }); + assert.equal((await resolveReviewThreads(reader, ghContext)).length, 1); + assert.deepEqual(reader.calls, ["reviewThreadPage:null"]); + }); + + it("counts Bugbot review passes across every page", async () => { + const bugbot = (id, runId) => ({ + id, + firstComment: { + authorLogin: "bugbot", + body: `RUN_ID: ${runId}`, + path: "a.ts", + line: 1, + createdAt: "now", + }, + resolved: false, + }); + const reader = fakeReader({ + threadPages: [ + { threads: [bugbot("one", "run-1")], endCursor: "next" }, + { threads: [bugbot("two", "run-2")], endCursor: null }, + ], + }); + const threads = await resolveReviewThreads(reader, ghContext); + assert.deepEqual( + threads.map((item) => item.bugbotReviewPasses), + [2, 2] + ); + }); + + it("drops resolved threads from later pages too", async () => { + const reader = fakeReader({ + threadPages: [ + { threads: [thread("one")], endCursor: "next" }, + { threads: [thread("two", true)], endCursor: null }, + ], + }); + assert.deepEqual( + (await resolveReviewThreads(reader, ghContext)).map((item) => item.id), + ["one"] + ); + }); + + it("rejects a page that omits pageInfo instead of assuming one page", () => { + const response = { + data: { + repository: { + pullRequest: { reviewThreads: { nodes: [] } }, + }, + }, + }; + assert.throws(() => parseReviewThreadPage(response), WatcherQueryError); + }); +}); + +describe("context and stack discovery", () => { + it("returns a fully explicit context without any reader call", async () => { + const reader = fakeReader(); + assert.deepEqual( + await resolveContext({ + reader, + owner: "explicit", + repo: "repo", + pr: ghContext.number, + }), + { owner: "explicit", repo: "repo", number: ghContext.number } + ); + assert.deepEqual(reader.calls, []); + }); + + it("uses the local origin before currentPr for an explicit number", async () => { + const reader = fakeReader({ origin: { owner: "local", repo: "checkout" } }); + assert.deepEqual( + await resolveContext({ + reader, + owner: null, + repo: null, + pr: ghContext.number, + }), + { owner: "local", repo: "checkout", number: ghContext.number } + ); + assert.deepEqual(reader.calls, ["originRepo"]); + }); + + it("orders the connected stack bottom-to-top", () => { + const ordered = orderStack(ghContext, [ + { + number: parsePrNumber(41), + headRefName: "base-feature", + isCrossRepository: false, + baseRefName: "main", + }, + { + number: ghContext.number, + headRefName: "feature", + isCrossRepository: false, + baseRefName: "base-feature", + }, + { + number: parsePrNumber(43), + headRefName: "upstack", + isCrossRepository: false, + baseRefName: "feature", + }, + ]); + assert.deepEqual( + ordered.map((item) => Number(item.number)), + [41, 42, 43] + ); + }); + + it("does not use a fork's same-named head as a stack parent", () => { + const ordered = orderStack(ghContext, [ + { + number: parsePrNumber(41), + headRefName: "base-feature", + baseRefName: "main", + isCrossRepository: true, + }, + { + number: ghContext.number, + headRefName: "feature", + baseRefName: "base-feature", + isCrossRepository: false, + }, + ]); + assert.deepEqual( + ordered.map((item) => Number(item.number)), + [42] + ); + }); + + it("does not attach upstream branch children to a fork head", () => { + const ordered = orderStack(ghContext, [ + { + number: ghContext.number, + headRefName: "feature", + baseRefName: "main", + isCrossRepository: true, + }, + { + number: parsePrNumber(43), + headRefName: "upstack", + baseRefName: "feature", + isCrossRepository: false, + }, + ]); + assert.deepEqual( + ordered.map((item) => Number(item.number)), + [42] + ); + }); + + it("terminates when an unrelated fork opens main against main", () => { + const program = `import { orderStack } from ${JSON.stringify(watchPrUrl)}; + console.log(JSON.stringify(orderStack(${JSON.stringify(ghContext)}, [ + { number: 41, headRefName: "main", baseRefName: "main", isCrossRepository: true }, + { number: 42, headRefName: "feature", baseRefName: "main", isCrossRepository: false } + ])));`; + const child = spawnSync( + process.execPath, + ["--input-type=module", "-e", program], + { encoding: "utf8", timeout: 2000 } + ); + assert.equal(child.error, undefined); + assert.equal(child.status, 0); + assert.deepEqual( + JSON.parse(child.stdout).map((item) => item.number), + [42] + ); + }); + + it("requests and parses fork identity from gh before stack discovery", () => { + const directory = mkdtempSync(join(tmpdir(), "watch-pr-fork-")); + try { + writeFileSync( + join(directory, "gh"), + `#!/bin/sh +case "$*" in + *number,headRefName,baseRefName,isCrossRepository*) ;; + *) exit 2 ;; +esac +printf '%s\\n' '[{"number":42,"headRefName":"feature","baseRefName":"main","isCrossRepository":true}]' +`, + { mode: 0o755 } + ); + const program = `import { GhGitHubReader } from ${JSON.stringify(watchPrUrl)}; + console.log(JSON.stringify(await new GhGitHubReader().openPullRequests({ owner: "owner", repo: "repo" })));`; + const child = spawnSync( + process.execPath, + ["--input-type=module", "-e", program], + { + encoding: "utf8", + timeout: 2000, + env: { ...process.env, PATH: directory + ":" + process.env.PATH }, + } + ); + assert.equal(child.error, undefined); + assert.equal(child.status, 0); + assert.deepEqual(JSON.parse(child.stdout), [ + { + number: 42, + headRefName: "feature", + baseRefName: "main", + isCrossRepository: true, + }, + ]); + } finally { + rmSync(directory, { recursive: true, force: true }); + } + }); +}); + +const policyContext = (number) => ({ + owner: "owner", + repo: "repo", + number: parsePrNumber(number), +}); + +const policyOptions = { + interval: 10, + sweepInterval: 300, + timeout: 0, + maxQueryErrors: 5, + allowDraft: false, +}; + +describe("readiness truth table", () => { + it("covers every specified row and every UNKNOWN rollup value", () => { + const cases = [ + ["BLOCKED", "FAILURE", "refused"], + ["BLOCKED", "ERROR", "refused"], + ["BLOCKED", "PENDING", "allowed"], + ["UNSTABLE", "FAILURE", "allowed"], + ["UNKNOWN", "ERROR", "allowed"], + ["UNKNOWN", "EXPECTED", "allowed"], + ["UNKNOWN", "FAILURE", "allowed"], + ["UNKNOWN", "PENDING", "allowed"], + ["UNKNOWN", "SUCCESS", "allowed"], + ["UNKNOWN", null, "allowed"], + ["CLEAN", "SUCCESS", "allowed"], + ]; + for (const [mergeStateStatus, headRollupState, expected] of cases) { + assert.equal( + assessGitHubMerge({ mergeStateStatus, headRollupState }).kind, + expected + ); + } + }); + + it("turns a clean visible list plus GitHub refusal into an explicit CI blocker", async () => { + const reader = fakeReader({ + facts: { mergeStateStatus: "BLOCKED" }, + fastPath: { kind: "checks", checks: [passingCheck()] }, + commitRollups: [{ oid: "head", state: "FAILURE" }], + }); + const snapshot = await readSnapshot({ + reader, + context: policyContext(1), + pendingHistory: "include", + allowDraft: false, + }); + assert.equal(snapshot.kind, "open"); + assert.equal(snapshot.ci.kind, "ci-github-rejected"); + const decision = classifyPr(snapshot); + assert.equal(decision.kind, "blocker"); + assert.equal(decision.blocker.kind, "failing-checks"); + }); +}); + +describe("snapshot query planning", () => { + it("does not query commit rollups while queued checks are pending", async () => { + const reader = fakeReader({ + fastPath: { kind: "checks", checks: [pendingCheck()] }, + }); + const snapshot = await readSnapshot({ + reader, + context: policyContext(2), + pendingHistory: "omit", + allowDraft: false, + }); + assert.equal(snapshot.kind, "open"); + assert.equal(snapshot.ci.kind, "ci-pending"); + assert.deepEqual(reader.calls, [ + "pullRequest", + "reviewThreadPage:null", + "checksFastPath", + ]); + }); + + it("queries rollups for settled and failed lists", async () => { + const settled = fakeReader(); + await readSnapshot({ + reader: settled, + context: policyContext(3), + pendingHistory: "omit", + allowDraft: false, + }); + assert.ok(settled.calls.includes("commitRollups")); + + const failed = fakeReader({ + fastPath: { kind: "checks", checks: [failedCheck()] }, + }); + await readSnapshot({ + reader: failed, + context: policyContext(4), + pendingHistory: "omit", + allowDraft: false, + }); + assert.ok(failed.calls.includes("commitRollups")); + }); + + it("short-circuits merged rows before threads and checks", async () => { + const reader = fakeReader({ + facts: { state: "MERGED", mergedAt: "2026-07-26T00:00:00Z" }, + }); + assert.equal( + ( + await readSnapshot({ + reader, + context: policyContext(5), + pendingHistory: "include", + allowDraft: false, + }) + ).kind, + "merged" + ); + assert.deepEqual(reader.calls, ["pullRequest"]); + }); +}); + +it("scans stacks tier-major so an upstack conflict outranks frontier CI", async () => { + const frontier = await readSnapshot({ + reader: fakeReader({ + fastPath: { kind: "checks", checks: [failedCheck()] }, + commitRollups: [{ oid: "head", state: "FAILURE" }], + }), + context: policyContext(10), + pendingHistory: "omit", + allowDraft: false, + }); + const upstack = await readSnapshot({ + reader: fakeReader({ facts: { mergeable: "CONFLICTING" } }), + context: policyContext(11), + pendingHistory: "omit", + allowDraft: false, + }); + const decision = selectTierMajorStackDecision([frontier, upstack]); + assert.equal(decision.kind, "blocker"); + assert.equal(decision.blocker.kind, "merge-conflicts"); + assert.equal(decision.blocker.pr.number, 11); +}); + +it("attributes a stack wait to the PR whose checks are pending, not the bottom", async () => { + const readyBottom = await readSnapshot({ + reader: fakeReader(), + context: policyContext(20), + pendingHistory: "omit", + allowDraft: false, + }); + const pendingUpstack = await readSnapshot({ + reader: fakeReader({ + fastPath: { kind: "checks", checks: [pendingCheck("upstack-build")] }, + }), + context: policyContext(21), + pendingHistory: "omit", + allowDraft: false, + }); + const decision = selectTierMajorStackDecision([readyBottom, pendingUpstack]); + assert.equal(decision.kind, "waiting"); + assert.equal(decision.frontier.number, 21); + assert.equal(decision.pending[0].name, "upstack-build"); +}); + +it("waits on a draft while checks are pending, then reports the draft gate", async () => { + const pending = await readSnapshot({ + reader: fakeReader({ + facts: { isDraft: true }, + fastPath: { kind: "checks", checks: [pendingCheck()] }, + }), + context: policyContext(12), + pendingHistory: "omit", + allowDraft: false, + }); + assert.equal(classifyPr(pending).kind, "waiting"); + + const settled = await readSnapshot({ + reader: fakeReader({ facts: { isDraft: true } }), + context: policyContext(12), + pendingHistory: "omit", + allowDraft: false, + }); + const decision = classifyPr(settled); + assert.equal(decision.kind, "blocker"); + assert.equal(decision.blocker.kind, "merge-gate"); + assert.equal(decision.blocker.reason, "draft-pr"); +}); + +describe("queued-stack cadence", () => { + async function openSnapshot(pr) { + return readSnapshot({ + reader: fakeReader(), + context: pr, + pendingHistory: "omit", + allowDraft: false, + }); + } + + it("drops a sweep head only after its snapshot succeeds", async () => { + const queue = [policyContext(20), policyContext(21), policyContext(22)]; + let state = createQueueState(queue, 0); + const first = await openSnapshot(queue[0]); + state = applyQueueSnapshot(state, first, 0, policyOptions).state; + assert.equal(state.work.kind, "whole-stack-sweep"); + assert.deepEqual( + state.work.remaining.map((item) => item.number), + [21, 22] + ); + const second = await openSnapshot(queue[1]); + state = applyQueueSnapshot(state, second, 60, policyOptions).state; + assert.equal(state.work.kind, "whole-stack-sweep"); + assert.deepEqual( + state.work.remaining.map((item) => item.number), + [22] + ); + }); + + it("resumes the sweep at the PR whose read failed", async () => { + const middle = policyContext(21); + const base = fakeReader(); + let failNext = true; + const timeline = []; + const reader = { + ...base, + async pullRequest(pr) { + if (pr.number === middle.number && failNext) { + failNext = false; + timeline.push(`fail:${pr.number}`); + throw new WatcherQueryError({ + kind: "command-exit", + retryable: true, + detail: "rate limited", + code: 1, + }); + } + timeline.push(`read:${pr.number}`); + return base.pullRequest(pr); + }, + }; + let now = 0; + let sleeps = 0; + const running = runQueued({ + dependencies: { + reader, + clock: { + now: () => now, + observedAt: () => "2026-07-26T00:00:00.000Z", + async sleep(seconds) { + timeline.push("sleep"); + now += seconds; + sleeps += 1; + if (sleeps === 2) throw new Error("stop after resume proof"); + }, + }, + emit(verdict) { + timeline.push(`emit:${verdict.kind}`); + }, + }, + contexts: [policyContext(20), middle, policyContext(22)], + options: policyOptions, + }); + await assert.rejects(running, /stop after resume proof/); + assert.deepEqual(timeline, [ + "emit:QUEUE", + "read:20", + "fail:21", + "emit:RETRY", + "sleep", + "read:21", + "read:22", + "emit:STATUS", + "emit:WAITING", + "sleep", + ]); + }); + + it("emits a completed sweep only after its final successful snapshot", async () => { + const queue = [policyContext(30), policyContext(31)]; + let state = createQueueState(queue, 0); + const first = applyQueueSnapshot( + state, + await openSnapshot(queue[0]), + 0, + policyOptions + ); + assert.equal(first.completedSweepRows, null); + state = first.state; + const second = applyQueueSnapshot( + state, + await openSnapshot(queue[1]), + 5, + policyOptions + ); + assert.deepEqual( + second.completedSweepRows?.map((row) => Number(row.context.number)), + [30, 31] + ); + assert.equal(second.state.nextSweepAt, 305); + }); + + it("ADVANCE continues directly to the new frontier without sleeping", async () => { + const one = policyContext(40); + const two = policyContext(41); + const base = fakeReader(); + const reads = new Map(); + const timeline = []; + const reader = { + ...base, + async pullRequest(pr) { + timeline.push(`read:${pr.number}`); + const facts = await base.pullRequest(pr); + const count = (reads.get(pr.number) ?? 0) + 1; + reads.set(pr.number, count); + return pr.number === one.number && count > 1 + ? { + ...facts, + state: "MERGED", + mergedAt: "2026-07-26T00:00:00Z", + } + : facts; + }, + }; + let now = 0; + let sleeps = 0; + const emitted = []; + const running = runQueued({ + dependencies: { + reader, + clock: { + now: () => now, + observedAt: () => "2026-07-26T00:00:00.000Z", + async sleep(seconds) { + timeline.push("sleep"); + now += seconds; + sleeps += 1; + if (sleeps === 2) throw new Error("stop after advance proof"); + }, + }, + emit(verdict) { + emitted.push(verdict); + timeline.push(`emit:${verdict.kind}`); + }, + }, + contexts: [one, two], + options: policyOptions, + }); + await assert.rejects(running, /stop after advance proof/); + assert.equal( + emitted.some((event) => event.kind === "ADVANCE"), + true + ); + const firstSleep = timeline.indexOf("sleep"); + assert.deepEqual(timeline.slice(firstSleep, firstSleep + 5), [ + "sleep", + "read:40", + "emit:ADVANCE", + "read:41", + "emit:WAITING", + ]); + }); + + it("deduplicates identical waits and schedules the next due sweep", async () => { + const queue = [policyContext(50)]; + let state = createQueueState(queue, 0); + state = applyQueueSnapshot( + state, + await openSnapshot(queue[0]), + 0, + policyOptions + ).state; + const first = evaluateQueue(state, 0, policyOptions); + assert.equal(first.kind, "waiting"); + assert.equal(first.emit, true); + const second = evaluateQueue(first.state, 10, policyOptions); + assert.equal(second.kind, "waiting"); + assert.equal(second.emit, false); + assert.equal(planQueue(second.state, 300).work?.kind, "whole-stack-sweep"); + }); +}); + +it("uses the specified retry floor and cap", () => { + assert.equal(queryBackoffSeconds(1, 1), 60); + assert.equal(queryBackoffSeconds(1, 2), 120); + assert.equal(queryBackoffSeconds(60, 4), 300); +}); + +describe("polling deadline sleeps", () => { + for (const mode of ["single", "queued-stack", "query-retry"]) { + it(`caps ${mode} sleeps at the configured deadline`, async () => { + let now = 0; + const sleeps = []; + const pending = fakeReader({ + fastPath: { kind: "checks", checks: [pendingCheck()] }, + }); + const reader = + mode === "query-retry" + ? { + ...pending, + async pullRequest() { + throw new WatcherQueryError({ + kind: "command-exit", + retryable: true, + code: 1, + detail: "temporary failure", + }); + }, + } + : pending; + const dependencies = { + reader, + clock: { + now: () => now, + observedAt: () => "2026-07-26T00:00:00.000Z", + async sleep(seconds) { + sleeps.push(seconds); + now += seconds; + }, + }, + emit() {}, + }; + const polling = { ...policyOptions, interval: 60, timeout: 5 }; + const result = + mode === "queued-stack" + ? await runQueued({ + dependencies, + contexts: [policyContext(1)], + options: polling, + }) + : await runSimple({ + dependencies, + contexts: [policyContext(1)], + mode: "single", + statusOnly: false, + options: polling, + }); + assert.equal(result.kind, "TIMEOUT"); + assert.deepEqual(sleeps, [5]); + assert.equal(now, 5); + }); + } + + it("preserves the polling interval when the deadline is disabled", async () => { + let now = 0; + let reads = 0; + const sleeps = []; + const pending = fakeReader({ + fastPath: { kind: "checks", checks: [pendingCheck()] }, + }); + const passed = fakeReader({ + fastPath: { kind: "checks", checks: [passingCheck()] }, + }); + const result = await runSimple({ + dependencies: { + reader: { + ...pending, + async checksFastPath(pr) { + reads += 1; + return reads === 1 + ? pending.checksFastPath(pr) + : passed.checksFastPath(pr); + }, + }, + clock: { + now: () => now, + observedAt: () => "2026-07-26T00:00:00.000Z", + async sleep(seconds) { + sleeps.push(seconds); + now += seconds; + }, + }, + emit() {}, + }, + contexts: [policyContext(1)], + mode: "single", + statusOnly: false, + options: { ...policyOptions, interval: 60, timeout: 0 }, + }); + assert.equal(result.kind, "READY"); + assert.deepEqual(sleeps, [60]); + }); +}); diff --git a/skills/pstack/scripts/worktree-audit.sh b/skills/pstack/scripts/worktree-audit.sh new file mode 100755 index 0000000..ef143e3 --- /dev/null +++ b/skills/pstack/scripts/worktree-audit.sh @@ -0,0 +1,122 @@ +#!/usr/bin/env bash +# Read-only worktree prune audit. Classifies every git worktree by size, merge +# state, uncommitted work, remote/PR state, and the most recent chat that +# operated in it. Emits a table sorted by size with a suggested bucket. Never +# deletes anything; deletion stays a human-gated step in the playbook. +# +# Usage: worktree-audit.sh [-b|--base ] [repo-path] +# repo-path defaults to the current repo. +# -b sets the ref the MERGED column checks against (e.g. origin/integration). +# Without it the base is origin/HEAD, then origin/main, then origin/master. +# origin/HEAD is the remote's default branch, not necessarily the branch PRs +# merge into; pass -b when they differ. +set -u + +base="" +while [ $# -gt 0 ]; do + case "$1" in + -b|--base) [ $# -ge 2 ] || { echo "error: $1 needs a ref" >&2; exit 2; }; base="$2"; shift 2 ;; + -h|--help) sed -n '2,/^set -u/p' "$0" | sed '$d; s/^# \{0,1\}//'; exit 0 ;; + -*) echo "error: unknown option: $1" >&2; exit 2 ;; + *) break ;; + esac +done + +repo="${1:-$(git rev-parse --show-toplevel 2>/dev/null)}" +[ -z "$repo" ] && { echo "not in a git repo; pass a repo path" >&2; exit 1; } +cd "$repo" || exit 1 +git rev-parse --git-dir >/dev/null 2>&1 || { echo "error: not a git repo: $repo" >&2; exit 1; } + +main_wt=$(git worktree list --porcelain | awk '/^worktree /{print $2; exit}') + +if [ -z "$base" ]; then + for cand in "$(git symbolic-ref --short refs/remotes/origin/HEAD 2>/dev/null)" origin/main origin/master; do + [ -n "$cand" ] && git rev-parse --verify --quiet "$cand^{commit}" >/dev/null && { base="$cand"; break; } + done + [ -z "$base" ] && { echo "error: no base ref (origin/HEAD, origin/main, origin/master all missing); pass -b " >&2; exit 1; } + echo "warn: no -b given; MERGED checks against $base" >&2 +fi + +case "$base" in +origin/*) git fetch origin "+refs/heads/${base#origin/}:refs/remotes/$base" --quiet 2>/dev/null \ + || echo "warn: could not fetch $base; merged column may be stale" >&2 ;; +esac +git rev-parse --verify --quiet "$base^{commit}" >/dev/null 2>&1 || { echo "error: base ref not found: $base" >&2; exit 1; } + +# GNU coreutils (Linux, Homebrew gnubin) reads `stat -f` as file system status +# and `date -r` as a file, so pick the stat and date flags once. +if stat -c %Y / >/dev/null 2>&1; then + stat_fmt=(-c '%Y %n'); fmt_day() { date -d "@$1" '+%Y-%m-%d'; } +else + stat_fmt=(-f '%m %N'); fmt_day() { date -r "$1" '+%Y-%m-%d'; } +fi + +prs=$(mktemp) +trap 'rm -f "$prs"' EXIT +if command -v origin >/dev/null 2>&1 \ + && raw=$(origin pr list --author "@me" --state all --limit 1000 \ + --json number,status,headRef 2>/dev/null); then + printf '%s' "$raw" | jq '[.[] | {number, state: .status, head: .headRef}]' > "$prs" 2>/dev/null +elif raw=$(gh pr list --author "@me" --state all --limit 1000 \ + --json number,state,headRefName 2>/dev/null); then + printf '%s' "$raw" | jq '[.[] | {number, state: (.state | ascii_downcase), head: .headRefName}]' > "$prs" 2>/dev/null +fi +[ -s "$prs" ] || echo "[]" > "$prs" + +transcript_dirs=() +for d in "$HOME/.gemini/antigravity-cli/brain" "$HOME/.gemini/antigravity/brain" "$HOME/.gemini/antigravity-ide/brain"; do + [ -d "$d" ] && transcript_dirs+=("$d") +done +now=$(date +%s) + +echo "# base: $base" +printf "SIZE\tAGE\tMERGED\tDIRTY\tREMOTE\tPR\tLAST_CHAT\tBUCKET\tWORKTREE\n" + +git worktree list --porcelain | awk '/^worktree /{print $2}' | while read -r wt; do + [ "$wt" = "$main_wt" ] && continue + + size=$(du -sh "$wt" 2>/dev/null | awk '{print $1}') + head=$(git -C "$wt" rev-parse HEAD 2>/dev/null) + head_ts=$(git -C "$wt" log -1 --format='%ct' HEAD 2>/dev/null || echo 0) + age=$([ "$head_ts" -gt 0 ] 2>/dev/null && echo "$(( (now - head_ts) / 86400 ))d" || echo "?") + + git merge-base --is-ancestor "$head" "$base" 2>/dev/null && merged=YES || merged=no + + porcelain=$(git -C "$wt" status --porcelain 2>/dev/null) + if [ -z "$porcelain" ]; then dirty=clean + elif printf '%s\n' "$porcelain" | grep -qv '^??'; then + dirty="wip:$(printf '%s\n' "$porcelain" | grep -cv '^??')" + else dirty="scratch:$(printf '%s\n' "$porcelain" | grep -c '^??')"; fi + + branch=$(git -C "$wt" symbolic-ref --quiet --short HEAD 2>/dev/null || echo "") + if [ -z "$branch" ]; then remote=detached + elif git -C "$wt" show-ref --verify --quiet "refs/remotes/origin/$branch"; then + [ "$(git -C "$wt" rev-parse "origin/$branch" 2>/dev/null)" = "$head" ] \ + && remote=pushed \ + || remote="ahead$(git -C "$wt" rev-list --count "origin/$branch..HEAD" 2>/dev/null)" + else remote=no-remote; fi + + pr=$([ -n "$branch" ] && jq -r --arg b "$branch" \ + '.[] | select(.head==$b) | "#\(.number)/\(.state)"' "$prs" 2>/dev/null | head -1) + [ -z "$pr" ] && pr="-" + + last="-"; last_ts=0 + if [ "${#transcript_dirs[@]}" -gt 0 ]; then + f=$(rg --hidden -l -g 'transcript.jsonl' -e "${wt}/" -e "${wt}\"" "${transcript_dirs[@]}" 2>/dev/null \ + | xargs stat "${stat_fmt[@]}" 2>/dev/null | sort -rn | head -1) + if [ -n "$f" ]; then last_ts=$(echo "$f" | awk '{print $1}') + last=$(fmt_day "$last_ts" 2>/dev/null); fi + fi + recent=$([ "$last_ts" -gt 0 ] 2>/dev/null && [ $(( (now - last_ts) / 86400 )) -le 4 ] && echo yes || echo no) + + case "$dirty" in wip:*) bucket=hold-wip ;; *) + case "$pr" in */open|*/draft) bucket=hold-open-pr ;; *) + if [ "$recent" = yes ]; then bucket=verify-recent-chat + elif [ "$merged" = YES ] || [ "$pr" != "-" ]; then bucket=safe + else bucket=review; fi ;; + esac ;; + esac + + printf "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n" \ + "$size" "$age" "$merged" "$dirty" "$remote" "$pr" "$last" "$bucket" "$wt" +done | sort -t$'\t' -k1,1 -rh diff --git a/skills/pstack/topologies/build.md b/skills/pstack/topologies/build.md index 506bbaf..35792b9 100644 --- a/skills/pstack/topologies/build.md +++ b/skills/pstack/topologies/build.md @@ -15,7 +15,7 @@ Match the request to one of four execution contracts before slicing files: 1. **Ground non-obvious invariants.** Run `/understand` ([../../understand/SKILL.md](../../understand/SKILL.md)) when subsystem contracts or historical constraints are unclear. When a change crosses module boundaries with multiple viable designs, run `/crucible` ([../../crucible/SKILL.md](../../crucible/SKILL.md)) in `sketch` or `full` mode first, or model complex lifecycle state with `/statechart` ([../../statechart/SKILL.md](../../statechart/SKILL.md)). 2. **Choose the data shape first.** Define core domain types, discriminated unions, branded IDs, and state transitions per `Model the Domain` in [../references/principles.md](../references/principles.md) and [../references/ts-patterns.md](../references/ts-patterns.md) before any worker writes implementation code. -3. **Write the four-part throughput checkpoint.** Record these four items in `/brain//task.md` (marking `n/a` with a concrete reason only when a single-file task needs one author): +3. **Write the four-part throughput checkpoint.** Record these four items in `/brain//task.md` (marking `n/a` with a concrete reason only when a single-file task needs one author), validate `plan.json` with [`../scripts/check-plan.mjs`](../scripts/check-plan.mjs), and log key boundary choices via [`../scripts/decision-log.sh`](../scripts/decision-log.sh): - **Blocking foundations.** Shared types, schemas, characterization pins, or primitive components that must land before fan-out. - **Disjoint workstreams.** Exact file or directory globs assigned to each `impl-*` worker so zero files overlap. - **Shared mutable state.** How shared registries, exports, ports, or test fixtures are split first (`Separate Before Serializing Shared State`) and integrated at the merge step. @@ -49,11 +49,11 @@ Match the request to one of four execution contracts before slicing files: 3. **Migrate primitives first, then fan out components.** Land shared tokens and base primitives as a blocking first commit. Then assign one component per `impl-*` worker (`workspace: "share"`), passing the resolved `/skills/control-ui/SKILL.md` path in each brief so every worker reads the isolation rules directly and runs its own ephemeral dev-server port and isolated browser `--user-data-dir` without colliding. 4. **Loop to zero diff.** Each `impl-*` iterates on its component and reruns the automated image diff until pixel delta reaches zero (using `schedule` or `/goal` on large component sweeps). -## Phase 3. Integrate and run `sicko-*` surgical cleanup +## Phase 3. Integrate and run conditional `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). `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"}`. +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. Run [`../scripts/worktree-audit.sh`](../scripts/worktree-audit.sh) if any slice worktree state looks stale. +2. Spawn `sicko-clean` (`workspace: "share"`) on the integrated tree only when the diff adds comments or non-trivial code changes (skip `sicko-*` on pure deletions, one-line edits, or comment-free trivial diffs). Pass `/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. If `sicko-clean` ran, audit its 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/program.md b/skills/pstack/topologies/program.md index 14f7c2e..c85295b 100644 --- a/skills/pstack/topologies/program.md +++ b/skills/pstack/topologies/program.md @@ -29,7 +29,7 @@ Declare the operating mode before spawning workers so every member holds the sam ### Continuous board checkpoints -Treat the swarm board as the authoritative operational ledger. At the end of every completed unit, post an unaddressed checkpoint message recording: +Treat the swarm board as the authoritative operational ledger. Validate `plan.json` and multi-phase plan dependencies with [`../scripts/check-plan.mjs`](../scripts/check-plan.mjs), and record durable architectural decisions with [`../scripts/decision-log.sh`](../scripts/decision-log.sh). At the end of every completed unit, post an unaddressed checkpoint message recording: - Unit identifier and goal slice. - Exact commit SHA and `share` worktree path (`pwd`). @@ -77,7 +77,7 @@ When resuming a paused swarm, prior conversation transcript, or existing branch When the user asks to reclaim disk space or prune stale git worktrees: -1. Record baseline disk free space with `df -h /` and enumerate every worktree from `git worktree list --porcelain` (never from guessed directory globs). +1. Record baseline disk free space with `df -h /` and run [`../scripts/worktree-audit.sh`](../scripts/worktree-audit.sh) alongside `git worktree list --porcelain` (never guessed directory globs) to enumerate every worktree. 2. Spawn `ro-audit` (`workspace: "inherit"`) to classify each candidate worktree by disk size, age, merge ancestry against base (`git merge-base --is-ancestor`), open/merged PR state (`gh pr list`), tracked uncommitted edits (`wip:N`) vs untracked throwaways (`scratch:N`), and recent references in `/brain/*/.system_generated/logs/transcript.jsonl`. 3. Cross-check active or pinned user chats before touching anything. Pause and show the diff for any `wip:N` worktree with uncommitted tracked edits, because deleting uncommitted work is irreversible. 4. Prune only confirmed merged, clean, inactive worktrees (`git worktree remove --force ` followed by `git worktree prune`). When requested on macOS, reclaim simulator clutter with `xcrun simctl --set testing delete all` and `xcrun simctl delete unavailable`. diff --git a/skills/reflect/SKILL.md b/skills/reflect/SKILL.md index d9f1930..4c0d2a8 100644 --- a/skills/reflect/SKILL.md +++ b/skills/reflect/SKILL.md @@ -9,6 +9,7 @@ description: >- architecture, types, linters, hooks/guard.mjs, tests, role capsules, or skills. Use for /agy-pstack-next:reflect, /reflect, "reflect on this session", "stop repeating this mistake", "correct", or "sharpen this prompt". +disable-model-invocation: true --- # Reflect @@ -68,7 +69,7 @@ Present a crisp synthesis before changing shared skills, role capsules, or hooks - **Accepted table.** Columns for `Problem`, `Rung (Architecture / Hook-Lint-Type / Test / Skill-Role)`, `Proposal`, and `Target path`. - **Rejected list.** One line per dropped finding naming the gate it failed (`durability`, `specificity`, `skill-not-used`, `already-covered`, `duplicate`). -- **Backlog.** Larger devex items suited for an issue tracker rather than immediate session edits. +- **Backlog.** Capture larger devex items immediately in the session or repository backlog rather than letting recurring friction drop, recording `pattern`, `hit` (observed count or `#seq`/commit evidence), and proposed `mechanism` fields on every entry. Whenever a temporary rule exception or suppression is kept, attach an explicit `expiry` date so stale exceptions get revisited. Wait for explicit user approval when modifying skills, role capsules, or global rules (unless running an explicit mid-session `--correct` code/test fix requested by the user). Never edit installed plugin cache files under `~/.gemini/config/plugins/` directly. When customizing an installed plugin skill outside the plugin repository itself, copy the skill into `.agents/skills//` or `~/.gemini/config/skills//` and edit that override copy. @@ -77,7 +78,7 @@ Wait for explicit user approval when modifying skills, role capsules, or global Once approved, retire `ro-judgment`, `ro-tooling`, and `ro-divergent` with `swarm{action: "kill"}` and spawn `impl-sharpen` (`workspace: "share"`): 1. Pass explicit resolved paths such as `/skills/technical-writing/SKILL.md` (and `/roles/poteto-agent.md` when global `hooks.json` is not active) in `impl-sharpen`'s brief rather than telling it to invoke plugin skills by name. `impl-sharpen` implements the approved architectural refactors, type or lint rules, `hooks/guard.mjs` + `hooks/guard.test.mjs` guards, `roles/*.md` capsule updates, or `SKILL.md` improvements (following Antigravity's built-in `agy-customizations` skill for frontmatter and structure). -2. **Prove every check catches the real mistake.** Run the new lint, typecheck, `node --test hooks/guard.test.mjs`, or `agy plugin validate --strict` against the past failure shape to confirm it fails when broken and passes when fixed. +2. **Prove every check catches the real mistake.** Run the new lint, typecheck, `node --test hooks/guard.test.mjs`, `agy plugin validate --strict --json .`, and `node '/skills/setup-pstack/scripts/sync-hooks.mjs' --check` against the past failure shape to confirm the guard fails when broken and passes with zero drift when fixed. 3. Fetch and merge `impl-sharpen`'s clean commit into the coordinator workspace (`git fetch && git merge --no-edit FETCH_HEAD`) before calling `swarm{action: "kill", name: "impl-sharpen"}` (leaving `monitor` and `narrator` alive unless asked). Never `git push` unless the user asks. --- diff --git a/skills/setup-pstack/SKILL.md b/skills/setup-pstack/SKILL.md index f3da27f..e62cdbb 100644 --- a/skills/setup-pstack/SKILL.md +++ b/skills/setup-pstack/SKILL.md @@ -8,6 +8,7 @@ description: >- automations or personal -mode convention skills. Use for /agy-pstack-next:setup-pstack, /setup-pstack, "configure pstack models", "pstack budget", "pstack help", "which skill should I use", or "automate me". +disable-model-invocation: true --- # Setup pstack @@ -43,9 +44,9 @@ Antigravity supports `inherit` (omit `model` in `swarm{action: "add"}` so the wo Validate every model ID written to the rule against `inherit` or the live `models` array returned by `swarm{action: "models", all: true}`. Never hardcode a model ID that the current workspace rejected. -### Step 2. Load current rule state +### Step 2. Load and validate current rule state -Check whether `~/.gemini/config/rules/pstack-models.md` exists. If present, read its `# budget`, role lines, and gate settings as the current baseline, and note whether `trigger: always_on` YAML frontmatter is missing so Step 4 restores it. Drop any retired v1 role keys (such as `how explorer`, `why investigators`, `arena runners`, or `architect runners`) and list dropped keys so the user sees the cleanup. +Check whether `~/.gemini/config/rules/pstack-models.md` exists. If present, read its `# budget`, role lines, and gate settings as the current baseline. Validate every configured model ID against `inherit` or the live `models` array returned by `swarm{action: "models", all: true}` in Step 1, and flag any unknown, retired, or zero-quota IDs for replacement. Also check whether `trigger: always_on` YAML frontmatter is missing, whether `monitor` is missing, or whether `impl-*` and `lead-*` share one combined line so Step 4 upgrades the schema cleanly. Drop any retired v1 role keys (such as `how explorer`, `why investigators`, `arena runners`, or `architect runners`) and list dropped keys so the user sees the cleanup. ### Step 3. Choose budget preset, role prefixes, and autonomy gates @@ -54,24 +55,27 @@ Use `ask_question` rather than free-text prompts. **(a) Budget preset.** Offer four presets and note which one is currently active: - `(Recommended) balanced - frontier coordinator and fast workers` +- `frugal - flash and oss economy` +- `max - multi-family high reasoning` - `inherit - match session model across workers` -- `frontier - multi-family high reasoning` -- `lean - flash and oss economy` Preset behavior: -- `inherit` sets worker prefixes to `inherit` while keeping a live cross-family `ro-judge pool` from the discovered catalog. -- `frontier` pins high-reasoning models (`claude-opus-5-5-high`, `gemini-4-hydrogen-high`, or `gemini-pro-orchestrator`) on `coordinator`, `cand-*`, `adv-*`, and `ro-judge pool`, mid-high models (`claude-sonnet-5-5-high` or `gemini-4-carbon-high`) on `impl-*`, `lead-*`, and `ro-*`, and `gemini-3.8-flash-medium` on `sicko-*`. -- `balanced` pins a high-reasoning model on `coordinator` and `ro-judge pool`, capable mid-tier models (`claude-sonnet-5-5-medium`, `gemini-4-carbon-medium`, or `gemini-4-argon-high`) on `impl-*`, `cand-*`, `lead-*`, and `adv-*`, and fast models (`gemini-3.8-flash-medium` or `gemini-3.8-flash-low`) on `ro-*` and `sicko-*`. -- `lean` assigns `gemini-3.8-flash-medium`, `gemini-3.8-flash-low`, or `gpt-oss-120b-medium` to high-volume worker prefixes and reserves one stronger tier for `ro-judge pool`. +- `inherit` sets worker prefixes (`impl-*`, `lead-*`, `cand-*`, `ro-*`, `adv-*`, `sicko-*`, `monitor`) to `inherit` while keeping a live cross-family `ro-judge pool` from the discovered catalog. +- `max` pins high-reasoning models (`claude-opus-5-5-high`, `gemini-4-hydrogen-high`, or `gemini-pro-orchestrator`) on `coordinator`, `cand-*`, `adv-*`, and `ro-judge pool`, strong models (`claude-sonnet-5-5-high` or `gemini-4-carbon-high`) on `impl-*`, `lead-*`, and `ro-*`, `gemini-3.8-flash-medium` on `sicko-*`, and the fast low-cost tier (`gemini-3.8-flash-low`) on `monitor`. +- `balanced` pins a high-reasoning model on `coordinator` and `ro-judge pool`, mid-tier models (`claude-sonnet-5-5-medium`, `gemini-4-carbon-medium`, or `gemini-4-argon-high`) on `impl-*`, `lead-*`, `cand-*`, and `adv-*`, fast models (`gemini-3.8-flash-medium` or `gemini-3.8-flash-low`) on `ro-*` and `sicko-*`, and the fast low-cost tier (`gemini-3.8-flash-low`) on `monitor`. +- `frugal` assigns fast low-cost models (`gemini-3.8-flash-medium`, `gemini-3.8-flash-low`, or `gpt-oss-120b-medium`) to `impl-*`, `lead-*`, `ro-*`, and `sicko-*`, pins `monitor` to `gemini-3.8-flash-low`, and reserves one stronger tier for `ro-judge pool`. -**(b) Per-prefix swarm role models.** Show the resolved table and ask whether to accept or customize individual prefixes: +**(b) Per-prefix swarm role models.** Show the resolved table with separate rows for every prefix and ask whether to accept or customize individual prefixes: - `coordinator` runs the root planning and integration loop (`roles/coordinator.md`). -- `impl-*, cand-*, lead-*` run isolated `workspace: "share"` implementation, candidate prototype, and area-lead branches (`roles/poteto-agent.md`). `cand-*` also accepts a comma-separated multi-family list when `/crucible` explores orthogonal axes across distinct model families. +- `impl-*` runs isolated `workspace: "share"` implementation and bug-fix slices (`roles/poteto-agent.md`). +- `lead-*` runs isolated `workspace: "share"` area-lead sub-coordinators in multi-area programs (`roles/poteto-agent.md`). +- `cand-*` runs isolated `workspace: "share"` candidate prototypes (`roles/poteto-agent.md`) and accepts a comma-separated multi-family list for orthogonal exploration in `/crucible`. - `ro-*` runs read-only scouts, trace investigators, blast-radius mappers, and verifiers (`roles/research.md`, `workspace: "inherit"`). - `adv-*` runs adversarial repro and exploit authors in `/interrogate` (`roles/poteto-agent.md`, `workspace: "share"`). A comma-separated multi-family list fans out one adversary per entry. - `sicko-*` runs surgical comment and slop cleanup passes (`roles/comment-sicko.md`, `workspace: "share"`, `edit_file` only). +- `monitor` runs the built-in stall monitor (`swarm_monitor`) on multi-wave or long-running swarms, pinned to the fast low-cost tier (such as `gemini-3.8-flash-low`) or `inherit`. - `ro-judge pool` lists ordered cross-family models for `/crucible` and `/pstack` `evolve` grading. The coordinator picks the first available model from a family different from the candidate authors and coordinator. `inherit` never judges. **(c) Autonomy gates and quota hot-swap.** Confirm three operational policies: @@ -82,7 +86,7 @@ Preset behavior: ### Step 4. Write `~/.gemini/config/rules/pstack-models.md` -Named rule files under `~/.gemini/config/rules/*.md` require `trigger: always_on` YAML frontmatter in `agy` (unlike standalone `AGENTS.md` or `GEMINI.md` files). Without `trigger: always_on`, `agy` logs `CORTEX_MEMORY_TRIGGER_UNSPECIFIED` and drops the rule on every turn. Overwrite `~/.gemini/config/rules/pstack-models.md` with `trigger: always_on` frontmatter and total size well under 24 KB: +Named rule files under `~/.gemini/config/rules/*.md` require `trigger: always_on` YAML frontmatter in `agy` (unlike standalone `AGENTS.md` or `GEMINI.md` files). Without `trigger: always_on`, `agy` logs `CORTEX_MEMORY_TRIGGER_UNSPECIFIED` and drops the rule on every turn. Overwrite `~/.gemini/config/rules/pstack-models.md` with `trigger: always_on` frontmatter, separate `impl-*` and `lead-*` lines, `monitor`, and total size well under 24 KB: ```markdown --- @@ -93,76 +97,35 @@ trigger: always_on # Values must be `inherit` or live model IDs from `swarm{action: "models", all: true}`. # budget: balanced coordinator: inherit -impl-*, lead-*: claude-sonnet-5-5-medium +impl-*: claude-sonnet-5-5-medium +lead-*: claude-sonnet-5-5-medium cand-*: claude-opus-5-5-high, gemini-4-hydrogen-high, gpt-oss-120b-medium ro-*: gemini-3.8-flash-high adv-*: claude-opus-5-5-high, gemini-4-hydrogen-high sicko-*: gemini-3.8-flash-low +monitor: gemini-3.8-flash-low ro-judge pool: gemini-4-hydrogen-high, claude-opus-5-5-high, gpt-oss-120b-medium push gate: manual crucible checkpoint: none quota hotswap: auto (fallback: gemini-4-argon-medium, gemini-3.8-flash-high, gpt-oss-120b-medium) ``` -### 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, 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. -3. Set `"pstack-swarm-guard"` on the parsed JSON object using this exact structure while leaving sibling keys untouched: - -```json -{ - "pstack-swarm-guard": { - "SessionStart": [ - { - "type": "command", - "command": "test ! -f '' || node ''", - "timeout": 10 - } - ], - "PreInvocation": [ - { - "type": "command", - "command": "test ! -f '' || node ''", - "timeout": 10 - } - ], - "PreToolUse": [ - { - "matcher": "(invoke|define)_subagent|manage_subagents|send_message|run_workflow", - "hooks": [ - { - "type": "command", - "command": "test ! -f '' || node ''", - "timeout": 10 - } - ] - }, - { - "matcher": "(edit|write)_file|run_command|call_mcp_tool|mcp_.*", - "hooks": [ - { - "type": "command", - "command": "test ! -f '' || node ''", - "timeout": 10 - } - ] - } - ], - "Stop": [ - { - "type": "command", - "command": "test ! -f '' || node ''", - "timeout": 10 - } - ] - } -} +### Step 4b. Sync `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. Sync `pstack-swarm-guard` globally via [`scripts/sync-hooks.mjs`](scripts/sync-hooks.mjs) so worker role capsules, structural tool boundaries, and `Stop` cleanliness checks execute on every worker turn while sharing per-conversation deduplication state under `/plugin_data/agy-pstack-next/capsules/`. + +1. Resolve `` from this `SKILL.md` file (`~/.gemini/config/plugins/agy-pstack-next` when installed). +2. Run the hook sync script to merge `pstack-swarm-guard` into `~/.gemini/config/hooks.json` while preserving sibling entries (such as `herdr`) and guarding each command with `test ! -f '' ||`: + +```bash +node '/skills/setup-pstack/scripts/sync-hooks.mjs' ``` -4. Write the merged JSON object back to `~/.gemini/config/hooks.json` with 2-space indentation. +3. Verify zero configuration drift between `~/.gemini/config/hooks.json` and `/hooks/guard.mjs`: + +```bash +node '/skills/setup-pstack/scripts/sync-hooks.mjs' --check +``` Global registration stays inert outside active pstack swarms: diff --git a/skills/setup-pstack/scripts/sync-hooks.mjs b/skills/setup-pstack/scripts/sync-hooks.mjs new file mode 100755 index 0000000..4c2ae25 --- /dev/null +++ b/skills/setup-pstack/scripts/sync-hooks.mjs @@ -0,0 +1,396 @@ +#!/usr/bin/env node +import { + existsSync, + mkdirSync, + readFileSync, + realpathSync, + renameSync, + unlinkSync, + writeFileSync, +} from "node:fs"; +import { homedir } from "node:os"; +import { basename, dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +function isWhitespaceChar(ch) { + return ch === " " || ch === "\t" || ch === "\n" || ch === "\r"; +} + +function isDigit(code) { + return code >= 48 && code <= 57; +} + +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; +} + +function parseJsonObjectStrict(raw) { + const parsed = JSON.parse(raw); + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) { + throw new Error("Expected a top-level JSON object"); + } + return parsed; +} + +function writeJsonAtomically(filePath, obj) { + const dir = dirname(filePath); + mkdirSync(dir, { recursive: true }); + 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); + } + } catch {} + writeFileSync(filePath, serialized, "utf8"); + } +} + +function parseCommandSegments(commandLine) { + const segments = []; + let tokens = []; + let token = ""; + let hasToken = false; + let inSingle = false; + let inDouble = false; + + function flushToken() { + if (!hasToken) { + return; + } + tokens.push(token); + token = ""; + hasToken = false; + } + + function flushSegment() { + flushToken(); + if (tokens.length > 0) { + segments.push(tokens); + tokens = []; + } + } + + 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; + } + if (inDouble) { + if (ch === "\\" && i + 1 < commandLine.length && (next === '"' || next === "\\" || next === "$" || next === "`")) { + token += next; + i += 1; + hasToken = true; + continue; + } + if (ch === '"') { + inDouble = false; + } else { + token += ch; + } + hasToken = true; + continue; + } + if (ch === "\\" && i + 1 < commandLine.length) { + if (next !== "\n") { + token += next; + hasToken = true; + } + i += 1; + continue; + } + if (ch === "'") { + inSingle = true; + hasToken = true; + continue; + } + if (ch === '"') { + inDouble = true; + hasToken = true; + continue; + } + if (ch === ";" || ch === "\n") { + flushSegment(); + continue; + } + if (ch === "&" || ch === "|") { + if (next === ch) { + i += 1; + } + flushSegment(); + continue; + } + if (isWhitespaceChar(ch)) { + flushToken(); + continue; + } + if (ch === "(" || ch === ")") { + flushToken(); + continue; + } + if (ch === ">" || ch === "<") { + if (hasToken && isAllDigits(token)) { + token = ""; + hasToken = false; + } else { + flushToken(); + } + continue; + } + token += ch; + hasToken = true; + } + flushSegment(); + return segments; +} + +function realpathIfExists(targetPath) { + if (typeof targetPath !== "string" || !targetPath || !existsSync(targetPath)) { + return null; + } + try { + return realpathSync(targetPath); + } catch { + return null; + } +} + +function commandTargetsGuard(command, expectedGuardReal) { + if (typeof command !== "string" || !command.trim()) { + return false; + } + const segments = parseCommandSegments(command); + let sawExec = false; + for (const seg of segments) { + if (seg.length === 0) { + continue; + } + const head = basename(seg[0]); + if (head === "test" || head === "[") { + const fIdx = seg.indexOf("-f"); + if (fIdx >= 0 && fIdx + 1 < seg.length) { + const checkReal = realpathIfExists(seg[fIdx + 1]); + if (checkReal !== expectedGuardReal) { + return false; + } + } + continue; + } + let scriptPath = null; + if (head === "node") { + for (let i = 1; i < seg.length; i += 1) { + if (!seg[i].startsWith("-")) { + scriptPath = seg[i]; + break; + } + } + } else { + scriptPath = seg[0]; + } + if (!scriptPath || realpathIfExists(scriptPath) !== expectedGuardReal) { + return false; + } + sawExec = true; + } + return sawExec; +} + +function shellSingleQuote(value) { + return `'${value.replaceAll("'", "'\\''")}'`; +} + +function buildGuardCommand(absGuardPath) { + const quoted = shellSingleQuote(absGuardPath); + return `test ! -f ${quoted} || node ${quoted}`; +} + +function buildExpectedGuardSpec(pluginGuardSpec, absGuardPath) { + const command = buildGuardCommand(absGuardPath); + const spec = {}; + for (const eventName of ["SessionStart", "PreInvocation"]) { + const entries = Array.isArray(pluginGuardSpec[eventName]) ? pluginGuardSpec[eventName] : []; + spec[eventName] = entries.map((entry) => ({ + type: "command", + command, + timeout: typeof entry?.timeout === "number" ? entry.timeout : 10, + })); + } + const preToolEntries = Array.isArray(pluginGuardSpec.PreToolUse) ? pluginGuardSpec.PreToolUse : []; + spec.PreToolUse = preToolEntries.map((block) => ({ + matcher: String(block?.matcher || ""), + hooks: (Array.isArray(block?.hooks) ? block.hooks : []).map((entry) => ({ + type: "command", + command, + timeout: typeof entry?.timeout === "number" ? entry.timeout : 10, + })), + })); + const stopEntries = Array.isArray(pluginGuardSpec.Stop) ? pluginGuardSpec.Stop : []; + spec.Stop = stopEntries.map((entry) => ({ + type: "command", + command, + timeout: typeof entry?.timeout === "number" ? entry.timeout : 10, + })); + return spec; +} + +function validateGlobalHooksSpec(globalDoc, pluginGuardSpec, absGuardReal) { + const guardSpec = globalDoc["pstack-swarm-guard"]; + if (!guardSpec || typeof guardSpec !== "object" || Array.isArray(guardSpec)) { + return { ok: false, reason: "Missing pstack-swarm-guard entry in global hooks.json" }; + } + if (guardSpec.enabled === false) { + return { ok: false, reason: "pstack-swarm-guard is disabled in global hooks.json" }; + } + for (const eventName of ["SessionStart", "PreInvocation", "Stop"]) { + const handlers = guardSpec[eventName]; + if (!Array.isArray(handlers) || handlers.length === 0) { + return { ok: false, reason: `Missing ${eventName} handler in pstack-swarm-guard` }; + } + const valid = handlers.every( + (h) => h && typeof h === "object" && h.type === "command" && commandTargetsGuard(h.command, absGuardReal), + ); + if (!valid) { + return { ok: false, reason: `Stale ${eventName} command or guard path in pstack-swarm-guard` }; + } + } + const actualPreTool = guardSpec.PreToolUse; + const expectedPreTool = Array.isArray(pluginGuardSpec.PreToolUse) ? pluginGuardSpec.PreToolUse : []; + if (!Array.isArray(actualPreTool) || actualPreTool.length === 0) { + return { ok: false, reason: "Missing PreToolUse handlers in pstack-swarm-guard" }; + } + for (const expectedBlock of expectedPreTool) { + const matcher = String(expectedBlock?.matcher || ""); + const matchBlock = actualPreTool.find((b) => b && typeof b === "object" && b.matcher === matcher); + if (!matchBlock || !Array.isArray(matchBlock.hooks) || matchBlock.hooks.length === 0) { + return { ok: false, reason: `Missing PreToolUse matcher '${matcher}' in pstack-swarm-guard` }; + } + const valid = matchBlock.hooks.every( + (h) => h && typeof h === "object" && h.type === "command" && commandTargetsGuard(h.command, absGuardReal), + ); + if (!valid) { + return { ok: false, reason: `Stale PreToolUse command for matcher '${matcher}' in pstack-swarm-guard` }; + } + } + return { ok: true }; +} + +function parseCliArgs(argv) { + let check = false; + let configDir = ""; + for (let i = 0; i < argv.length; i += 1) { + const arg = argv[i]; + if (arg === "--check") { + check = true; + } else if (arg === "--config-dir") { + if (i + 1 >= argv.length || !argv[i + 1]) { + return { error: "Missing value for --config-dir" }; + } + configDir = argv[i + 1]; + i += 1; + } else if (arg.startsWith("--config-dir=")) { + const val = arg.slice(13); + if (!val) { + return { error: "Missing value for --config-dir" }; + } + configDir = val; + } else { + return { error: `Unknown argument '${arg}'` }; + } + } + return { check, configDir, error: null }; +} + +function main() { + const parsedArgs = parseCliArgs(process.argv.slice(2)); + if (parsedArgs.error) { + process.stderr.write(`${parsedArgs.error}\n`); + process.exit(1); + } + + const pluginRoot = + typeof process.env.PSTACK_PLUGIN_ROOT === "string" && process.env.PSTACK_PLUGIN_ROOT + ? resolve(process.env.PSTACK_PLUGIN_ROOT) + : resolve(dirname(fileURLToPath(import.meta.url)), "../../.."); + + const pluginHooksPath = join(pluginRoot, "hooks.json"); + const guardPath = join(pluginRoot, "hooks", "guard.mjs"); + if (!existsSync(pluginHooksPath) || !existsSync(guardPath)) { + process.stderr.write(`Missing plugin hooks.json or hooks/guard.mjs under ${pluginRoot}\n`); + process.exit(1); + } + + const absGuardPath = realpathSync(guardPath); + const pluginHooks = parseJsonObjectStrict(readFileSync(pluginHooksPath, "utf8")); + const pluginGuardSpec = pluginHooks["pstack-swarm-guard"]; + if (!pluginGuardSpec || typeof pluginGuardSpec !== "object") { + process.stderr.write(`Missing pstack-swarm-guard in ${pluginHooksPath}\n`); + process.exit(1); + } + + const configDir = parsedArgs.configDir + ? resolve(parsedArgs.configDir) + : typeof process.env.PSTACK_CONFIG_DIR === "string" && process.env.PSTACK_CONFIG_DIR + ? resolve(process.env.PSTACK_CONFIG_DIR) + : join(process.env.HOME || homedir(), ".gemini", "config"); + const globalHooksPath = join(configDir, "hooks.json"); + + if (parsedArgs.check) { + if (!existsSync(globalHooksPath)) { + process.stderr.write(`Global hooks.json not found at ${globalHooksPath}\n`); + process.exit(1); + } + let globalDoc; + try { + globalDoc = parseJsonObjectStrict(readFileSync(globalHooksPath, "utf8")); + } catch (err) { + process.stderr.write(`Invalid global hooks.json at ${globalHooksPath}: ${err.message}\n`); + process.exit(1); + } + const status = validateGlobalHooksSpec(globalDoc, pluginGuardSpec, absGuardPath); + if (!status.ok) { + process.stderr.write(`${status.reason}\n`); + process.exit(1); + } + process.stdout.write(`Global hooks.json at ${globalHooksPath} is synced with ${absGuardPath}\n`); + process.exit(0); + } + + let globalDoc = {}; + if (existsSync(globalHooksPath)) { + const raw = readFileSync(globalHooksPath, "utf8"); + if (raw.trim()) { + try { + globalDoc = parseJsonObjectStrict(raw); + } catch (err) { + process.stderr.write(`Invalid global hooks.json at ${globalHooksPath}: ${err.message}\n`); + process.exit(1); + } + } + } + + globalDoc["pstack-swarm-guard"] = buildExpectedGuardSpec(pluginGuardSpec, absGuardPath); + writeJsonAtomically(globalHooksPath, globalDoc); + process.stdout.write(`Synced pstack-swarm-guard in ${globalHooksPath} to ${absGuardPath}\n`); +} + +main(); diff --git a/skills/statechart/scripts/bun.lock b/skills/statechart/scripts/bun.lock new file mode 100644 index 0000000..33bf700 --- /dev/null +++ b/skills/statechart/scripts/bun.lock @@ -0,0 +1,17 @@ +{ + "lockfileVersion": 1, + "configVersion": 1, + "workspaces": { + "": { + "name": "@cursor-skill/statechart", + "devDependencies": { + "fast-check": "4.5.3", + }, + }, + }, + "packages": { + "fast-check": ["fast-check@4.5.3", "", { "dependencies": { "pure-rand": "^7.0.0" } }, "sha512-IE9csY7lnhxBnA8g/WI5eg/hygA6MGWJMSNfFRrBlXUciADEhS1EDB0SIsMSvzubzIlOBbVITSsypCsW717poA=="], + + "pure-rand": ["pure-rand@7.0.1", "", {}, "sha512-oTUZM/NAZS8p7ANR3SHh30kXB+zK2r2BPcEn/awJIbOvq82WoMN4p62AWWp3Hhw50G0xMsw1mhIBLqHw64EcNQ=="], + } +} diff --git a/skills/understand/SKILL.md b/skills/understand/SKILL.md index 3d86fd5..8054484 100644 --- a/skills/understand/SKILL.md +++ b/skills/understand/SKILL.md @@ -90,7 +90,7 @@ Structure the output with strict confidence tags: Ground both mechanism and provenance with the `ro-*` mesh first, then teach in plain spoken English at the human's pace: 1. **Start small and concrete.** Open with a two-sentence plain definition of what the thing is and what happens when a real user or caller triggers it. Avoid meta labels ("key takeaway", "TL;DR", "here is the tricky part"). -2. **Build diagrams progressively.** Never dump one dense diagram with every box at the end. When teaching a flow across three or more parts, draw a short sequence of small Mermaid diagrams where each step redraws the prior diagram and adds one new component or edge. +2. **Build diagrams progressively and sketch spatial views.** Never dump one dense diagram with every box at the end. When teaching a flow across three or more parts, draw a short sequence of small Mermaid diagrams where each step redraws the prior diagram and adds one new component or edge. Whenever a spatial visual clarifies the mechanism faster than prose, generate a marker-on-whiteboard spatial sketch via `invoke_subagent` targeting `image-generator` (permitted by `hooks/guard.mjs`) or build an interactive widget when `generative_ui` is mounted in ``. 3. **Preserve epistemic honesty.** Reword freely for clarity, except keep Mode B's confidence hedges (`likely`, `appears to`, `no direct record`) intact because those hedges are factual findings. 4. **Chunk and check the mental model.** Stop after the core mental model lands (roughly 150 to 250 words) and offer two concrete directions or one brief Socratic check ("Want to trace what happens when the retry races a cancel, or inspect why the buffer cap is 64?") so the reader steers depth interactively. When invoked one-shot with no live back-and-forth, deliver the full progressive walkthrough cleanly and list the best follow-up threads at the end. diff --git a/skills/verify-gen/SKILL.md b/skills/verify-gen/SKILL.md index 3d798b7..fb79319 100644 --- a/skills/verify-gen/SKILL.md +++ b/skills/verify-gen/SKILL.md @@ -6,6 +6,7 @@ description: >- generation, --formal invariant checking (TLA+, PBT, SMT, statecharts), and --maintain diff-driven drift upkeep. Use for /agy-pstack-next:verify-gen, /verify-gen, generating E2E verification skills, or maintaining formal checks. +disable-model-invocation: true --- # Generate and Maintain Verification Skills