From 80a734e2ae5ebdd4bff2befb10bd9b01f1097264 Mon Sep 17 00:00:00 2001 From: davidrobertson Date: Sun, 8 Nov 2026 20:01:13 -0500 Subject: [PATCH 1/7] test(pstack): reproduce plugin dependency mutation --- .../poteto-mode/scripts/bootstrap.test.ts | 56 ++++++++++++++++++- 1 file changed, 55 insertions(+), 1 deletion(-) diff --git a/plugins/pstack/skills/poteto-mode/scripts/bootstrap.test.ts b/plugins/pstack/skills/poteto-mode/scripts/bootstrap.test.ts index 2c6816ac..62b9248d 100644 --- a/plugins/pstack/skills/poteto-mode/scripts/bootstrap.test.ts +++ b/plugins/pstack/skills/poteto-mode/scripts/bootstrap.test.ts @@ -1,5 +1,7 @@ import { describe, expect, it } from "bun:test"; -import { join } from "node:path"; +import { cpSync, existsSync, mkdtempSync, readdirSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { basename, join } from "node:path"; const nodeEntryPoints = [ ["bootstrap", "bootstrap.ts"], @@ -19,3 +21,55 @@ describe("Bun runtime guard", () => { }); } }); + +describe("dependency bootstrap", () => { + it("runs copied watch-pr without installing dependencies inside the plugin", () => { + const directory = mkdtempSync(join(tmpdir(), "pstack-bootstrap-")); + const pluginDirectory = join(directory, "plugins", "pstack"); + const scriptsDirectory = join(pluginDirectory, "skills", "poteto-mode", "scripts"); + + try { + cpSync(import.meta.dir, scriptsDirectory, { + recursive: true, + filter: (source) => basename(source) !== "node_modules", + }); + const initialEntries = readdirSync(pluginDirectory, { recursive: true }).sort(); + const environment: Record = { + ...process.env, + HOME: join(directory, "home"), + XDG_CONFIG_HOME: join(directory, "config"), + XDG_CACHE_HOME: join(directory, "cache"), + BUN_INSTALL: join(directory, "bun"), + BUN_INSTALL_CACHE_DIR: join(directory, "bun-cache"), + }; + delete environment.NODE_PATH; + delete environment.NODE_OPTIONS; + delete environment.BUN_OPTIONS; + + for (let attempt = 0; attempt < 2; attempt++) { + const result = Bun.spawnSync([ + process.execPath, + "--no-env-file", + "--config=/dev/null", + join(scriptsDirectory, "watch-pr", "watch-pr"), + "--help", + ], { cwd: directory, env: environment }); + + expect({ + exitCode: result.exitCode, + stdout: result.stdout.toString(), + stderr: result.stderr.toString(), + }).toEqual({ + exitCode: 0, + stdout: expect.stringContaining("Usage: watch-pr [options]"), + stderr: "", + }); + } + + expect(existsSync(join(scriptsDirectory, "node_modules"))).toBe(false); + expect(readdirSync(pluginDirectory, { recursive: true }).sort()).toEqual(initialEntries); + } finally { + rmSync(directory, { recursive: true, force: true }); + } + }, 60_000); +}); From 27d7dd1a51b4d6519becb212a25e8197315a3a0f Mon Sep 17 00:00:00 2001 From: davidrobertson Date: Sun, 8 Nov 2026 20:16:49 -0500 Subject: [PATCH 2/7] fix(pstack): keep runtime dependencies outside plugin --- NOTICE.md | 2 +- UPSTREAM.md | 1 + .../poteto-mode/scripts/bootstrap.test.ts | 352 ++++++++++++++++-- .../skills/poteto-mode/scripts/bootstrap.ts | 136 ++++--- 4 files changed, 403 insertions(+), 88 deletions(-) diff --git a/NOTICE.md b/NOTICE.md index c6f7b90f..61d20ea5 100644 --- a/NOTICE.md +++ b/NOTICE.md @@ -38,7 +38,7 @@ Summary of structural changes: - The native `plugins/pstack/skills/` tree is the only user-facing workflow surface. Claude Code and Codex invoke those skills directly. - Seven skills imported from `cursor-team-kit`: `deslop`, `thermo-nuclear-code-quality-review`, `make-pr-easy-to-review`, `fix-ci`, `fix-merge-conflicts`, `get-pr-comments`, `what-did-i-get-done`. All copied verbatim — no rewiring needed. - `plugins/pstack/skills/babysit/` is independently authored as the Claude Code analog of Cursor's `/babysit` built-in. It has no upstream pstack equivalent; its workflow is informed by Cursor's public `/babysit` behavior. No code or prose was copied from any source. -- `plugins/pstack/skills/poteto-mode/scripts/` is vendored from upstream (`watch-pr`, `orch`, `bootstrap.ts`, `worktree-audit.sh`, `package.json`, `bun.lock`) with these port edits: `worktree-audit.sh` reads `~/.claude/projects/` instead of Cursor's transcript directory and warns when `jq` or `rg` is missing (their absence silently blanks the columns the prune decision reads), the private workspace package is named `@open-pstack/poteto-mode-tools`, `bootstrap.ts` rejects Node before it reads Bun-only APIs, and `package.json` includes the port-authored tests in `bun run test`. `check-plan.mjs` is the Cursor 0.14.3 checker adapted for the shared Claude Code and Codex skeleton. `bootstrap.test.ts` and `check-plan.test.ts` are authored for this port. `check-plan.test.ts` also carries the fence cases from upstream's `check-plan.test.ts` at 0.15.20, run against the extracted plan skeleton. +- `plugins/pstack/skills/poteto-mode/scripts/` is vendored from upstream (`watch-pr`, `orch`, `bootstrap.ts`, `worktree-audit.sh`, `package.json`, `bun.lock`) with these port edits: `worktree-audit.sh` reads `~/.claude/projects/` instead of Cursor's transcript directory and warns when `jq` or `rg` is missing (their absence silently blanks the columns the prune decision reads), the private workspace package is named `@open-pstack/poteto-mode-tools`, `bootstrap.ts` rejects Node before it reads Bun-only APIs and installs frozen dependencies in a user cache keyed by the manifest and lockfile outside the plugin, then registers Commander with Bun before the CLI imports it (#293), and `package.json` includes the port-authored tests in `bun run test`. `check-plan.mjs` is the Cursor 0.14.3 checker adapted for the shared Claude Code and Codex skeleton. `bootstrap.test.ts` and `check-plan.test.ts` are authored for this port. `check-plan.test.ts` also carries the fence cases from upstream's `check-plan.test.ts` at 0.15.20, run against the extracted plan skeleton. - `plugins/pstack/agents/comment-sicko.md` is upstream's `Comment Sicko` agent, renamed to `comment-sicko` so the name works as a Claude Code `subagent_type`. The body is verbatim. - `plugins/pstack/agents/poteto-agent.md` keeps the upstream prompt and adds Claude Code `skills` frontmatter so the isolated subagent preloads `pstack:poteto-mode`. - Claude-native lanes are port-authored agent definitions. Fable, Opus and Sonnet select their rolling family alias, and the Opus 5.5 and Haiku 5.5 pins select their exact model, each with the requested effort, for every selectable Claude-native pair in the model catalog. `registry/render.ts` generates them from the runner registry. diff --git a/UPSTREAM.md b/UPSTREAM.md index 452a93e1..e4fd3a20 100644 --- a/UPSTREAM.md +++ b/UPSTREAM.md @@ -47,6 +47,7 @@ The table above is the current Cursor sync point. Open Pstack 1.17.0 imported th ## Local port-patch ledger +- **#293 — dependency cache outside the plugin**: upstream's `bootstrap.ts` installs `watch-pr` dependencies into the plugin, where Bun's TypeScript bin symlink breaks Codex hook fingerprinting. The port keeps `ensureDependenciesInstalled(): void` and the early Bun guard, but hashes `package.json` and `bun.lock` into a harness-independent user cache under `XDG_CACHE_HOME`, Windows local app data, or `~/.cache`. Frozen installs run in unique staging directories and publish by atomic rename; concurrent starters reuse the completed winner and remove only their own staging data. An incomplete published cache stays untouched and reports its path for removal. The bootstrap loads Commander from that cache and registers it with Bun before the CLI imports it, without restarting the command or changing its environment. Preserve this divergence during syncs. Existing plugin installations polluted by the old bootstrap need a clean reinstall; this bootstrap does not repair them. - **#235 — Claude transcript folder encoding**: the port wrote Claude Code's per-project transcript path into `recall`, `automate-me` and the `session-pickup` playbook. Claude Code encodes each `/` and each `.` in the workspace path as `-`, so a `.claude/worktrees/` session's folder holds `--claude-worktrees-`. Keep both characters in those three lines during syncs. - **#140 — Reflect transcript resolution**: Cursor's Reflect step 1 reads the `agent-transcripts/` directory its system prompt names; the port had substituted Claude Code's per-project directory, which left Codex without a lookup. The port replaces that step's body with one line that points to `plugins/pstack/skills/poteto-mode/references/codex-tools.md#active-transcripts`, and leaves the rest of `reflect/SKILL.md` unchanged. That mapping section holds the harness specifics: the Claude per-project scope, layouts, candidate and scan limits, opening-message verification, the Codex resolver call, and the 2,000-word digest fallback. The port-authored Bun resolver `plugins/pstack/skills/poteto-mode/scripts/resolve-codex-transcript.ts`, started through the `sh` launcher `resolve-codex-transcript` next to it so project Bun config and `.env` files cannot affect it, looks up the parent's known chat ID in Codex's read-only `threads` index, checks rollout scope and ownership, and prints opening-message metadata without transcript text. Preserve this divergence during upstream syncs: keep step 1 as the one-line pointer and keep the mapping section and resolver. - **#120 — harness config homes** (tracked for #105): Cursor's setup destination is `~/.cursor/rules/`. The shared port resolves nonempty `CLAUDE_CONFIG_DIR` / `CODEX_HOME`, otherwise `$HOME/.claude` / `$HOME/.codex`, once at `plugins/pstack/skills/poteto-mode/references/codex-tools.md#harness-config-homes`. `setup-pstack/SKILL.md` reuses that home for reads, sheet/integration writes, snapshots, restoration, and readback; Claude preserves the literal legacy import at the default home and renders exactly `@./pstack-models.md` for redirected homes, keeping spaces and `#` in the config-directory name out of the import line; reruns replace the one import whose target basename is `pstack-models.md`, append if absent, and stop if duplicated. Preserve this intentional divergence during upstream syncs. The named config-home invariant in `tests/skill-collision-repro.sh` rejects literal default destinations outside the legacy import, requires the literal default-home rendering and zero/one/many import rules, and verifies unset/empty/space-containing resolution without daily writes. See `CHANGES.md` for the port correction and `tests/setup-config-home-repro.sh` for redirected live-evidence preparation. The Cursor sync point is unchanged. diff --git a/plugins/pstack/skills/poteto-mode/scripts/bootstrap.test.ts b/plugins/pstack/skills/poteto-mode/scripts/bootstrap.test.ts index 62b9248d..0c6296a3 100644 --- a/plugins/pstack/skills/poteto-mode/scripts/bootstrap.test.ts +++ b/plugins/pstack/skills/poteto-mode/scripts/bootstrap.test.ts @@ -1,12 +1,26 @@ -import { describe, expect, it } from "bun:test"; -import { cpSync, existsSync, mkdtempSync, readdirSync, rmSync } from "node:fs"; +import { afterEach, describe, expect, it } from "bun:test"; +import { + cpSync, + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + readdirSync, + realpathSync, + rmSync, + writeFileSync, +} from "node:fs"; import { tmpdir } from "node:os"; -import { basename, join } from "node:path"; +import { basename, delimiter, join } from "node:path"; const nodeEntryPoints = [ ["bootstrap", "bootstrap.ts"], ["watch-pr", "watch-pr/watch-pr"], ] as const; +const bunPackageCache = Bun.spawnSync([process.execPath, "pm", "cache"], { + cwd: import.meta.dir, +}) + .stdout.toString().trim(); describe("Bun runtime guard", () => { for (const [name, path] of nodeEntryPoints) { @@ -23,53 +37,309 @@ describe("Bun runtime guard", () => { }); describe("dependency bootstrap", () => { - it("runs copied watch-pr without installing dependencies inside the plugin", () => { + const directories: string[] = []; + afterEach(() => { + for (const directory of directories.splice(0)) { + rmSync(directory, { recursive: true, force: true }); + } + }); + + function fixture() { const directory = mkdtempSync(join(tmpdir(), "pstack-bootstrap-")); + directories.push(directory); const pluginDirectory = join(directory, "plugins", "pstack"); const scriptsDirectory = join(pluginDirectory, "skills", "poteto-mode", "scripts"); + const configPath = join(directory, "bunfig.toml"); + writeFileSync(configPath, ""); + cpSync(import.meta.dir, scriptsDirectory, { + recursive: true, + filter: (source) => basename(source) !== "node_modules", + }); + const environment: Record = { + ...process.env, + HOME: join(directory, "home"), + USERPROFILE: join(directory, "home"), + LOCALAPPDATA: join(directory, "local"), + XDG_CONFIG_HOME: join(directory, "config"), + XDG_CACHE_HOME: join(directory, "cache"), + BUN_INSTALL: join(directory, "bun"), + BUN_INSTALL_CACHE_DIR: bunPackageCache, + }; + delete environment.NODE_PATH; + delete environment.NODE_OPTIONS; + delete environment.BUN_OPTIONS; - try { - cpSync(import.meta.dir, scriptsDirectory, { - recursive: true, - filter: (source) => basename(source) !== "node_modules", - }); - const initialEntries = readdirSync(pluginDirectory, { recursive: true }).sort(); - const environment: Record = { - ...process.env, - HOME: join(directory, "home"), - XDG_CONFIG_HOME: join(directory, "config"), - XDG_CACHE_HOME: join(directory, "cache"), - BUN_INSTALL: join(directory, "bun"), - BUN_INSTALL_CACHE_DIR: join(directory, "bun-cache"), - }; - delete environment.NODE_PATH; - delete environment.NODE_OPTIONS; - delete environment.BUN_OPTIONS; - - for (let attempt = 0; attempt < 2; attempt++) { - const result = Bun.spawnSync([ - process.execPath, - "--no-env-file", - "--config=/dev/null", - join(scriptsDirectory, "watch-pr", "watch-pr"), - "--help", - ], { cwd: directory, env: environment }); - - expect({ + function command(args = ["--help"], entry = join("watch-pr", "watch-pr")) { + return [ + process.execPath, + "--no-env-file", + `--config=${configPath}`, + "--no-install", + join(scriptsDirectory, entry), + ...args, + ]; + } + + return { + directory, + pluginDirectory, + scriptsDirectory, + configPath, + environment, + command, + cacheRoot: join(directory, "cache", "open-pstack", "poteto-mode-tools"), + run(args = ["--help"], entry = join("watch-pr", "watch-pr"), input = "") { + const result = Bun.spawnSync(command(args, entry), { + cwd: directory, + env: environment, + stdin: Buffer.from(input), + }); + return { exitCode: result.exitCode, stdout: result.stdout.toString(), stderr: result.stderr.toString(), - }).toEqual({ - exitCode: 0, - stdout: expect.stringContaining("Usage: watch-pr [options]"), - stderr: "", - }); - } + }; + }, + }; + } + + const helpResult = { + exitCode: 0, + stdout: expect.stringContaining("Usage: watch-pr [options]"), + stderr: "", + }; + + it("runs copied watch-pr without installing dependencies inside the plugin", () => { + const test = fixture(); + const initialEntries = readdirSync(test.pluginDirectory, { recursive: true }).sort(); + + for (let attempt = 0; attempt < 2; attempt++) { + expect(test.run()).toEqual(helpResult); + } + + expect(existsSync(join(test.scriptsDirectory, "node_modules"))).toBe(false); + expect(readdirSync(test.pluginDirectory, { recursive: true }).sort()).toEqual(initialEntries); + }, 60_000); + + it("publishes one complete cache for concurrent cold starts", async () => { + const test = fixture(); + const children = Array.from({ length: 4 }, () => Bun.spawn(test.command(), { + cwd: test.directory, + env: test.environment, + stdin: "ignore", + stdout: "pipe", + stderr: "pipe", + })); + const results = await Promise.all(children.map(async (child) => { + const [exitCode, stdout, stderr] = await Promise.all([ + child.exited, + new Response(child.stdout).text(), + new Response(child.stderr).text(), + ]); + return { exitCode, stdout, stderr }; + })); + + for (const result of results) expect(result).toEqual(helpResult); + expect(readdirSync(test.cacheRoot)).toHaveLength(1); + expect(existsSync(join(test.scriptsDirectory, "node_modules"))).toBe(false); + expect(test.run()).toEqual(helpResult); + }, 60_000); + + it("loads the cached dependency instead of an incompatible ancestor package", () => { + const test = fixture(); + const ancestor = join(test.directory, "node_modules", "commander"); + mkdirSync(ancestor, { recursive: true }); + writeFileSync(join(ancestor, "package.json"), '{"name":"commander","version":"0.0.0","main":"index.js"}'); + writeFileSync(join(ancestor, "index.js"), 'throw new Error("wrong commander");\n'); + + expect(test.run()).toEqual(helpResult); + expect(existsSync(join(test.scriptsDirectory, "node_modules"))).toBe(false); + }, 60_000); + + it("accepts a cache path containing the platform path-list delimiter", () => { + const test = fixture(); + test.environment.XDG_CACHE_HOME = join(test.directory, `cache${delimiter}path`); + + expect(test.run()).toEqual(helpResult); + expect(existsSync(join(test.scriptsDirectory, "node_modules"))).toBe(false); + }, 60_000); - expect(existsSync(join(scriptsDirectory, "node_modules"))).toBe(false); - expect(readdirSync(pluginDirectory, { recursive: true }).sort()).toEqual(initialEntries); + it("uses fresh caches when either the manifest or frozen lockfile changes", () => { + const test = fixture(); + expect(test.run()).toEqual(helpResult); + const originalCache = join(test.cacheRoot, readdirSync(test.cacheRoot)[0]!); + const manifestPath = join(test.scriptsDirectory, "package.json"); + const lockfilePath = join(test.scriptsDirectory, "bun.lock"); + const originalManifest = readFileSync(manifestPath, "utf8"); + const originalLockfile = readFileSync(lockfilePath, "utf8"); + + writeFileSync(manifestPath, `${originalManifest}\n`); + expect(test.run()).toEqual(helpResult); + expect(readdirSync(test.cacheRoot)).toHaveLength(2); + + writeFileSync(lockfilePath, `${originalLockfile}\n`); + expect(test.run()).toEqual(helpResult); + expect(readdirSync(test.cacheRoot)).toHaveLength(3); + expect(readFileSync(join(originalCache, "package.json"), "utf8")).toBe(originalManifest); + expect(readFileSync(join(originalCache, "bun.lock"), "utf8")).toBe(originalLockfile); + }, 60_000); + + it("preserves arguments, runtime flags, cwd, streams, status, and existing NODE_PATH", () => { + const test = fixture(); + const externalPaths = [join(test.directory, "first modules"), join(test.directory, "second modules")]; + const externalPackage = join(externalPaths[1]!, "bootstrap-external-probe"); + mkdirSync(externalPackage, { recursive: true }); + writeFileSync(join(externalPackage, "package.json"), JSON.stringify({ + type: "module", + exports: "./index.js", + })); + writeFileSync(join(externalPackage, "index.js"), 'export default "external dependency";\n'); + test.environment.NODE_PATH = externalPaths.join(delimiter); + writeFileSync(join(test.scriptsDirectory, "probe.ts"), ` +import { ensureDependenciesInstalled } from "./bootstrap.ts"; +ensureDependenciesInstalled(); +const { Command } = await import("commander"); +console.log(JSON.stringify({ + name: new Command("probe").name(), + args: process.argv.slice(2), + execArgv: process.execArgv, + cwd: process.cwd(), + input: await Bun.stdin.text(), + nodePath: process.env.NODE_PATH, + external: (await import("bootstrap-external-probe")).default, +})); +console.error("probe stderr"); +process.exit(23); +`); + + const result = test.run(["--value", "two words", "-"], "probe.ts", "stdin payload\n"); + expect(result.exitCode).toBe(23); + expect(result.stderr).toBe("probe stderr\n"); + const observed = JSON.parse(result.stdout); + expect(observed).toMatchObject({ + name: "probe", + args: ["--value", "two words", "-"], + execArgv: ["--no-env-file", `--config=${test.configPath}`, "--no-install"], + cwd: realpathSync(test.directory), + input: "stdin payload\n", + external: "external dependency", + }); + expect(observed.nodePath).toBe(externalPaths.join(delimiter)); + expect(existsSync(join(test.scriptsDirectory, "node_modules"))).toBe(false); + }, 60_000); + + it("reports an incomplete published cache without replacing or deleting it", () => { + const test = fixture(); + expect(test.run()).toEqual(helpResult); + const cacheDirectory = join(test.cacheRoot, readdirSync(test.cacheRoot)[0]!); + rmSync(join(cacheDirectory, "node_modules", "commander"), { recursive: true }); + const entries = readdirSync(test.cacheRoot, { recursive: true }).sort(); + + const result = test.run(); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain(`Incomplete poteto-mode dependency cache at ${cacheDirectory}`); + expect(result.stderr).toContain("Remove that cache directory and re-run."); + expect(readdirSync(test.cacheRoot, { recursive: true }).sort()).toEqual(entries); + expect(existsSync(join(test.scriptsDirectory, "node_modules"))).toBe(false); + }, 60_000); + + it("retains frozen-install diagnostics and removes only failed staging data", () => { + const test = fixture(); + expect(test.run()).toEqual(helpResult); + const publishedCaches = readdirSync(test.cacheRoot); + writeFileSync(join(test.scriptsDirectory, "bun.lock"), "invalid lockfile\n"); + + const result = test.run(); + expect(result.exitCode).toBe(1); + expect(result.stdout).toContain("bun install"); + expect(result.stderr).toContain("lockfile"); + expect(result.stderr).toContain("bun install --frozen-lockfile exited with status 1"); + expect(readdirSync(test.cacheRoot)).toEqual(publishedCaches); + expect(existsSync(join(test.scriptsDirectory, "node_modules"))).toBe(false); + }, 60_000); + + it("keeps the working directory selected by a relative Bun --cwd flag", () => { + const test = fixture(); + const launchDirectory = join(test.directory, "work", "start"); + mkdirSync(launchDirectory, { recursive: true }); + writeFileSync(join(test.scriptsDirectory, "cwd-probe.ts"), ` +import { ensureDependenciesInstalled } from "./bootstrap.ts"; +ensureDependenciesInstalled(); +console.log(process.cwd()); +`); + const [bun, ...args] = test.command([], "cwd-probe.ts"); + + for (const flags of [["--cwd=.."], ["--cwd", ".."]]) { + const result = Bun.spawnSync([bun!, ...flags, ...args], { + cwd: launchDirectory, + env: test.environment, + }); + expect(result.exitCode).toBe(0); + expect(result.stderr.toString()).toBe(""); + expect(result.stdout.toString().trim()).toBe( + realpathSync(join(test.directory, "work")) + ); + } + }, 60_000); + + it("stops the running command when its process is terminated", async () => { + if (process.platform === "win32") return; + const test = fixture(); + expect(test.run()).toEqual(helpResult); + const readyPath = join(test.directory, "ready"); + test.environment.PSTACK_BOOTSTRAP_TEST_READY = readyPath; + writeFileSync(join(test.scriptsDirectory, "signal-probe.ts"), ` +import { writeFileSync } from "node:fs"; +import { ensureDependenciesInstalled } from "./bootstrap.ts"; +ensureDependenciesInstalled(); +writeFileSync(process.env.PSTACK_BOOTSTRAP_TEST_READY!, String(process.pid)); +setInterval(() => {}, 1000); +`); + const child = Bun.spawn(test.command([], "signal-probe.ts"), { + cwd: test.directory, + env: test.environment, + stdout: "ignore", + stderr: "pipe", + }); + let commandPid: number | undefined; + try { + for (let attempt = 0; attempt < 400 && !existsSync(readyPath); attempt++) { + if (child.exitCode !== null) break; + await Bun.sleep(25); + } + expect(existsSync(readyPath)).toBe(true); + commandPid = Number(readFileSync(readyPath, "utf8")); + child.kill("SIGTERM"); + await child.exited; + let running = true; + try { + process.kill(commandPid, 0); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error; + running = false; + } + expect(running).toBe(false); } finally { - rmSync(directory, { recursive: true, force: true }); + if (child.exitCode === null) child.kill("SIGKILL"); + if (commandPid && commandPid !== child.pid) { + try { + process.kill(commandPid, "SIGKILL"); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error; + } + } } }, 60_000); + + it("uses a user cache when XDG_CACHE_HOME is absent", () => { + const test = fixture(); + delete test.environment.XDG_CACHE_HOME; + + expect(test.run()).toEqual(helpResult); + const cacheHome = process.platform === "win32" + ? test.environment.LOCALAPPDATA! + : join(test.environment.HOME!, ".cache"); + expect(readdirSync(join(cacheHome, "open-pstack", "poteto-mode-tools"))).toHaveLength(1); + expect(existsSync(join(test.scriptsDirectory, "node_modules"))).toBe(false); + }, 60_000); }); diff --git a/plugins/pstack/skills/poteto-mode/scripts/bootstrap.ts b/plugins/pstack/skills/poteto-mode/scripts/bootstrap.ts index 64e86d42..fc97918d 100644 --- a/plugins/pstack/skills/poteto-mode/scripts/bootstrap.ts +++ b/plugins/pstack/skills/poteto-mode/scripts/bootstrap.ts @@ -1,6 +1,17 @@ import { createHash } from "node:crypto"; -import { existsSync, readFileSync, writeFileSync } from "node:fs"; -import { join } from "node:path"; +import { createRequire } from "node:module"; +import { + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + realpathSync, + renameSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { homedir } from "node:os"; +import { dirname, join, resolve, sep } from "node:path"; if (typeof Bun === "undefined") { console.error( @@ -10,60 +21,93 @@ if (typeof Bun === "undefined") { } const scriptsDirectory = import.meta.dir; -const nodeModulesDirectory = join(scriptsDirectory, "node_modules"); -const commanderPackagePath = join( - nodeModulesDirectory, - "commander", - "package.json" -); -const installKeyPath = join( - nodeModulesDirectory, - ".poteto-mode-tools-install-key" -); -function currentInstallKey(): string { - return createHash("sha256") - .update(readFileSync(join(scriptsDirectory, "package.json"))) - .update("\0") - .update(readFileSync(join(scriptsDirectory, "bun.lock"))) - .digest("hex"); +function dependencyCacheRoot(): string { + const cacheHome = + process.env.XDG_CACHE_HOME || + (process.platform === "win32" + ? process.env.LOCALAPPDATA || join(homedir(), "AppData", "Local") + : join(homedir(), ".cache")); + return resolve(cacheHome, "open-pstack", "poteto-mode-tools"); } -export function ensureDependenciesInstalled(): void { - const installKey = currentInstallKey(); - if ( - existsSync(commanderPackagePath) && - existsSync(installKeyPath) && - readFileSync(installKeyPath, "utf8").trim() === installKey - ) { - return; +function hasCommander(directory: string): boolean { + try { + const entry = Bun.resolveSync("commander", directory); + const commanderDirectory = realpathSync( + join(directory, "node_modules", "commander") + ); + return realpathSync(entry).startsWith(commanderDirectory + sep); + } catch { + return false; } +} - const result = Bun.spawnSync( - [process.execPath, "install", "--frozen-lockfile"], - { cwd: scriptsDirectory } - ); - if (result.exitCode !== 0) { - process.stdout.write(result.stdout); - process.stderr.write(result.stderr); - throw new Error( - `bun install --frozen-lockfile exited with status ${result.exitCode}` +function installDependencies( + cacheDirectory: string, + packageJson: Buffer, + lockfile: Buffer +): void { + const cacheRoot = dirname(cacheDirectory); + mkdirSync(cacheRoot, { recursive: true }); + const stagingDirectory = mkdtempSync(join(cacheRoot, ".staging-")); + try { + writeFileSync(join(stagingDirectory, "package.json"), packageJson); + writeFileSync(join(stagingDirectory, "bun.lock"), lockfile); + const result = Bun.spawnSync( + [process.execPath, "install", "--frozen-lockfile"], + { cwd: stagingDirectory } ); + if (result.exitCode !== 0) { + process.stdout.write(result.stdout); + process.stderr.write(result.stderr); + throw new Error( + `bun install --frozen-lockfile exited with status ${result.exitCode}` + ); + } + if (!hasCommander(stagingDirectory)) { + throw new Error( + "bun install --frozen-lockfile completed without installing commander" + ); + } + + try { + renameSync(stagingDirectory, cacheDirectory); + } catch (error) { + if (!existsSync(cacheDirectory)) throw error; + } + } finally { + rmSync(stagingDirectory, { recursive: true, force: true }); } - if (!existsSync(commanderPackagePath)) { +} + +export function ensureDependenciesInstalled(): void { + const packageJson = readFileSync(join(scriptsDirectory, "package.json")); + const lockfile = readFileSync(join(scriptsDirectory, "bun.lock")); + const installKey = createHash("sha256") + .update(packageJson) + .update("\0") + .update(lockfile) + .digest("hex"); + const cacheDirectory = join(dependencyCacheRoot(), installKey); + if (!existsSync(cacheDirectory)) { + installDependencies(cacheDirectory, packageJson, lockfile); + } + if (!hasCommander(cacheDirectory)) { throw new Error( - "bun install --frozen-lockfile completed without installing commander" + `Incomplete poteto-mode dependency cache at ${cacheDirectory}. Remove that cache directory and re-run.` ); } - writeFileSync(installKeyPath, `${installKey}\n`); - - const restarted = Bun.spawnSync([process.execPath, ...process.argv.slice(1)], { - cwd: process.cwd(), - env: process.env, - stdin: "inherit", - stdout: "inherit", - stderr: "inherit", + const load = createRequire(join(cacheDirectory, "package.json")); + const commander = load("commander"); + Bun.plugin({ + name: "pstack-commander", + setup(builder) { + builder.module("commander", () => ({ + loader: "object", + exports: commander, + })); + }, }); - process.exit(restarted.exitCode ?? 1); } From 34fb97637965de4220178b1be90ccbce9f133467 Mon Sep 17 00:00:00 2001 From: Eric Litman Date: Tue, 1 Dec 2026 08:35:18 -0500 Subject: [PATCH 3/7] refactor(pstack): simplify watch-pr dependency cache and install production deps only (#293) Co-Authored-By: Claude Opus 5.5 --- UPSTREAM.md | 2 +- .../poteto-mode/scripts/bootstrap.test.ts | 156 ++---------------- .../skills/poteto-mode/scripts/bootstrap.ts | 29 ++-- 3 files changed, 30 insertions(+), 157 deletions(-) diff --git a/UPSTREAM.md b/UPSTREAM.md index e4fd3a20..a0904041 100644 --- a/UPSTREAM.md +++ b/UPSTREAM.md @@ -47,7 +47,7 @@ The table above is the current Cursor sync point. Open Pstack 1.17.0 imported th ## Local port-patch ledger -- **#293 — dependency cache outside the plugin**: upstream's `bootstrap.ts` installs `watch-pr` dependencies into the plugin, where Bun's TypeScript bin symlink breaks Codex hook fingerprinting. The port keeps `ensureDependenciesInstalled(): void` and the early Bun guard, but hashes `package.json` and `bun.lock` into a harness-independent user cache under `XDG_CACHE_HOME`, Windows local app data, or `~/.cache`. Frozen installs run in unique staging directories and publish by atomic rename; concurrent starters reuse the completed winner and remove only their own staging data. An incomplete published cache stays untouched and reports its path for removal. The bootstrap loads Commander from that cache and registers it with Bun before the CLI imports it, without restarting the command or changing its environment. Preserve this divergence during syncs. Existing plugin installations polluted by the old bootstrap need a clean reinstall; this bootstrap does not repair them. +- **#293 — dependency cache outside the plugin**: upstream's `bootstrap.ts` installs `watch-pr` dependencies into the plugin, where Bun's TypeScript bin symlink breaks Codex hook fingerprinting. The port runs `bun install --frozen-lockfile --production` in a user cache keyed by the hash of `package.json` and `bun.lock`, under an absolute `XDG_CACHE_HOME`, Windows local app data, or `~/.cache`, and publishes it by atomic rename. It then registers Commander from that cache with Bun before the CLI imports it. Preserve this divergence and the early Bun guard during syncs; never install into the plugin tree. - **#235 — Claude transcript folder encoding**: the port wrote Claude Code's per-project transcript path into `recall`, `automate-me` and the `session-pickup` playbook. Claude Code encodes each `/` and each `.` in the workspace path as `-`, so a `.claude/worktrees/` session's folder holds `--claude-worktrees-`. Keep both characters in those three lines during syncs. - **#140 — Reflect transcript resolution**: Cursor's Reflect step 1 reads the `agent-transcripts/` directory its system prompt names; the port had substituted Claude Code's per-project directory, which left Codex without a lookup. The port replaces that step's body with one line that points to `plugins/pstack/skills/poteto-mode/references/codex-tools.md#active-transcripts`, and leaves the rest of `reflect/SKILL.md` unchanged. That mapping section holds the harness specifics: the Claude per-project scope, layouts, candidate and scan limits, opening-message verification, the Codex resolver call, and the 2,000-word digest fallback. The port-authored Bun resolver `plugins/pstack/skills/poteto-mode/scripts/resolve-codex-transcript.ts`, started through the `sh` launcher `resolve-codex-transcript` next to it so project Bun config and `.env` files cannot affect it, looks up the parent's known chat ID in Codex's read-only `threads` index, checks rollout scope and ownership, and prints opening-message metadata without transcript text. Preserve this divergence during upstream syncs: keep step 1 as the one-line pointer and keep the mapping section and resolver. - **#120 — harness config homes** (tracked for #105): Cursor's setup destination is `~/.cursor/rules/`. The shared port resolves nonempty `CLAUDE_CONFIG_DIR` / `CODEX_HOME`, otherwise `$HOME/.claude` / `$HOME/.codex`, once at `plugins/pstack/skills/poteto-mode/references/codex-tools.md#harness-config-homes`. `setup-pstack/SKILL.md` reuses that home for reads, sheet/integration writes, snapshots, restoration, and readback; Claude preserves the literal legacy import at the default home and renders exactly `@./pstack-models.md` for redirected homes, keeping spaces and `#` in the config-directory name out of the import line; reruns replace the one import whose target basename is `pstack-models.md`, append if absent, and stop if duplicated. Preserve this intentional divergence during upstream syncs. The named config-home invariant in `tests/skill-collision-repro.sh` rejects literal default destinations outside the legacy import, requires the literal default-home rendering and zero/one/many import rules, and verifies unset/empty/space-containing resolution without daily writes. See `CHANGES.md` for the port correction and `tests/setup-config-home-repro.sh` for redirected live-evidence preparation. The Cursor sync point is unchanged. diff --git a/plugins/pstack/skills/poteto-mode/scripts/bootstrap.test.ts b/plugins/pstack/skills/poteto-mode/scripts/bootstrap.test.ts index 0c6296a3..76e8b822 100644 --- a/plugins/pstack/skills/poteto-mode/scripts/bootstrap.test.ts +++ b/plugins/pstack/skills/poteto-mode/scripts/bootstrap.test.ts @@ -6,12 +6,11 @@ import { mkdtempSync, readFileSync, readdirSync, - realpathSync, rmSync, writeFileSync, } from "node:fs"; import { tmpdir } from "node:os"; -import { basename, delimiter, join } from "node:path"; +import { basename, join } from "node:path"; const nodeEntryPoints = [ ["bootstrap", "bootstrap.ts"], @@ -119,6 +118,9 @@ describe("dependency bootstrap", () => { expect(existsSync(join(test.scriptsDirectory, "node_modules"))).toBe(false); expect(readdirSync(test.pluginDirectory, { recursive: true }).sort()).toEqual(initialEntries); + const cacheDirectory = join(test.cacheRoot, readdirSync(test.cacheRoot)[0]!); + expect(existsSync(join(cacheDirectory, "node_modules", "commander"))).toBe(true); + expect(existsSync(join(cacheDirectory, "node_modules", "typescript"))).toBe(false); }, 60_000); it("publishes one complete cache for concurrent cold starts", async () => { @@ -156,14 +158,6 @@ describe("dependency bootstrap", () => { expect(existsSync(join(test.scriptsDirectory, "node_modules"))).toBe(false); }, 60_000); - it("accepts a cache path containing the platform path-list delimiter", () => { - const test = fixture(); - test.environment.XDG_CACHE_HOME = join(test.directory, `cache${delimiter}path`); - - expect(test.run()).toEqual(helpResult); - expect(existsSync(join(test.scriptsDirectory, "node_modules"))).toBe(false); - }, 60_000); - it("uses fresh caches when either the manifest or frozen lockfile changes", () => { const test = fixture(); expect(test.run()).toEqual(helpResult); @@ -184,50 +178,6 @@ describe("dependency bootstrap", () => { expect(readFileSync(join(originalCache, "bun.lock"), "utf8")).toBe(originalLockfile); }, 60_000); - it("preserves arguments, runtime flags, cwd, streams, status, and existing NODE_PATH", () => { - const test = fixture(); - const externalPaths = [join(test.directory, "first modules"), join(test.directory, "second modules")]; - const externalPackage = join(externalPaths[1]!, "bootstrap-external-probe"); - mkdirSync(externalPackage, { recursive: true }); - writeFileSync(join(externalPackage, "package.json"), JSON.stringify({ - type: "module", - exports: "./index.js", - })); - writeFileSync(join(externalPackage, "index.js"), 'export default "external dependency";\n'); - test.environment.NODE_PATH = externalPaths.join(delimiter); - writeFileSync(join(test.scriptsDirectory, "probe.ts"), ` -import { ensureDependenciesInstalled } from "./bootstrap.ts"; -ensureDependenciesInstalled(); -const { Command } = await import("commander"); -console.log(JSON.stringify({ - name: new Command("probe").name(), - args: process.argv.slice(2), - execArgv: process.execArgv, - cwd: process.cwd(), - input: await Bun.stdin.text(), - nodePath: process.env.NODE_PATH, - external: (await import("bootstrap-external-probe")).default, -})); -console.error("probe stderr"); -process.exit(23); -`); - - const result = test.run(["--value", "two words", "-"], "probe.ts", "stdin payload\n"); - expect(result.exitCode).toBe(23); - expect(result.stderr).toBe("probe stderr\n"); - const observed = JSON.parse(result.stdout); - expect(observed).toMatchObject({ - name: "probe", - args: ["--value", "two words", "-"], - execArgv: ["--no-env-file", `--config=${test.configPath}`, "--no-install"], - cwd: realpathSync(test.directory), - input: "stdin payload\n", - external: "external dependency", - }); - expect(observed.nodePath).toBe(externalPaths.join(delimiter)); - expect(existsSync(join(test.scriptsDirectory, "node_modules"))).toBe(false); - }, 60_000); - it("reports an incomplete published cache without replacing or deleting it", () => { const test = fixture(); expect(test.run()).toEqual(helpResult); @@ -253,93 +203,23 @@ process.exit(23); expect(result.exitCode).toBe(1); expect(result.stdout).toContain("bun install"); expect(result.stderr).toContain("lockfile"); - expect(result.stderr).toContain("bun install --frozen-lockfile exited with status 1"); + expect(result.stderr).toContain("bun install --frozen-lockfile --production exited with status 1"); expect(readdirSync(test.cacheRoot)).toEqual(publishedCaches); expect(existsSync(join(test.scriptsDirectory, "node_modules"))).toBe(false); }, 60_000); - it("keeps the working directory selected by a relative Bun --cwd flag", () => { - const test = fixture(); - const launchDirectory = join(test.directory, "work", "start"); - mkdirSync(launchDirectory, { recursive: true }); - writeFileSync(join(test.scriptsDirectory, "cwd-probe.ts"), ` -import { ensureDependenciesInstalled } from "./bootstrap.ts"; -ensureDependenciesInstalled(); -console.log(process.cwd()); -`); - const [bun, ...args] = test.command([], "cwd-probe.ts"); + for (const [name, xdgCacheHome] of [["absent", undefined], ["relative", "cache"]] as const) { + it(`uses a user cache when XDG_CACHE_HOME is ${name}`, () => { + const test = fixture(); + test.environment.XDG_CACHE_HOME = xdgCacheHome; - for (const flags of [["--cwd=.."], ["--cwd", ".."]]) { - const result = Bun.spawnSync([bun!, ...flags, ...args], { - cwd: launchDirectory, - env: test.environment, - }); - expect(result.exitCode).toBe(0); - expect(result.stderr.toString()).toBe(""); - expect(result.stdout.toString().trim()).toBe( - realpathSync(join(test.directory, "work")) - ); - } - }, 60_000); - - it("stops the running command when its process is terminated", async () => { - if (process.platform === "win32") return; - const test = fixture(); - expect(test.run()).toEqual(helpResult); - const readyPath = join(test.directory, "ready"); - test.environment.PSTACK_BOOTSTRAP_TEST_READY = readyPath; - writeFileSync(join(test.scriptsDirectory, "signal-probe.ts"), ` -import { writeFileSync } from "node:fs"; -import { ensureDependenciesInstalled } from "./bootstrap.ts"; -ensureDependenciesInstalled(); -writeFileSync(process.env.PSTACK_BOOTSTRAP_TEST_READY!, String(process.pid)); -setInterval(() => {}, 1000); -`); - const child = Bun.spawn(test.command([], "signal-probe.ts"), { - cwd: test.directory, - env: test.environment, - stdout: "ignore", - stderr: "pipe", - }); - let commandPid: number | undefined; - try { - for (let attempt = 0; attempt < 400 && !existsSync(readyPath); attempt++) { - if (child.exitCode !== null) break; - await Bun.sleep(25); - } - expect(existsSync(readyPath)).toBe(true); - commandPid = Number(readFileSync(readyPath, "utf8")); - child.kill("SIGTERM"); - await child.exited; - let running = true; - try { - process.kill(commandPid, 0); - } catch (error) { - if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error; - running = false; - } - expect(running).toBe(false); - } finally { - if (child.exitCode === null) child.kill("SIGKILL"); - if (commandPid && commandPid !== child.pid) { - try { - process.kill(commandPid, "SIGKILL"); - } catch (error) { - if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error; - } - } - } - }, 60_000); - - it("uses a user cache when XDG_CACHE_HOME is absent", () => { - const test = fixture(); - delete test.environment.XDG_CACHE_HOME; - - expect(test.run()).toEqual(helpResult); - const cacheHome = process.platform === "win32" - ? test.environment.LOCALAPPDATA! - : join(test.environment.HOME!, ".cache"); - expect(readdirSync(join(cacheHome, "open-pstack", "poteto-mode-tools"))).toHaveLength(1); - expect(existsSync(join(test.scriptsDirectory, "node_modules"))).toBe(false); - }, 60_000); + expect(test.run()).toEqual(helpResult); + const cacheHome = process.platform === "win32" + ? test.environment.LOCALAPPDATA! + : join(test.environment.HOME!, ".cache"); + expect(readdirSync(join(cacheHome, "open-pstack", "poteto-mode-tools"))).toHaveLength(1); + expect(existsSync(join(test.directory, "cache", "open-pstack"))).toBe(false); + expect(existsSync(join(test.scriptsDirectory, "node_modules"))).toBe(false); + }, 60_000); + } }); diff --git a/plugins/pstack/skills/poteto-mode/scripts/bootstrap.ts b/plugins/pstack/skills/poteto-mode/scripts/bootstrap.ts index fc97918d..9bac50f1 100644 --- a/plugins/pstack/skills/poteto-mode/scripts/bootstrap.ts +++ b/plugins/pstack/skills/poteto-mode/scripts/bootstrap.ts @@ -5,13 +5,12 @@ import { mkdirSync, mkdtempSync, readFileSync, - realpathSync, renameSync, rmSync, writeFileSync, } from "node:fs"; import { homedir } from "node:os"; -import { dirname, join, resolve, sep } from "node:path"; +import { dirname, isAbsolute, join, resolve } from "node:path"; if (typeof Bun === "undefined") { console.error( @@ -23,24 +22,18 @@ if (typeof Bun === "undefined") { const scriptsDirectory = import.meta.dir; function dependencyCacheRoot(): string { + const xdgCacheHome = process.env.XDG_CACHE_HOME; const cacheHome = - process.env.XDG_CACHE_HOME || - (process.platform === "win32" - ? process.env.LOCALAPPDATA || join(homedir(), "AppData", "Local") - : join(homedir(), ".cache")); + xdgCacheHome && isAbsolute(xdgCacheHome) + ? xdgCacheHome + : process.platform === "win32" + ? process.env.LOCALAPPDATA || join(homedir(), "AppData", "Local") + : join(homedir(), ".cache"); return resolve(cacheHome, "open-pstack", "poteto-mode-tools"); } function hasCommander(directory: string): boolean { - try { - const entry = Bun.resolveSync("commander", directory); - const commanderDirectory = realpathSync( - join(directory, "node_modules", "commander") - ); - return realpathSync(entry).startsWith(commanderDirectory + sep); - } catch { - return false; - } + return existsSync(join(directory, "node_modules", "commander", "package.json")); } function installDependencies( @@ -55,19 +48,19 @@ function installDependencies( writeFileSync(join(stagingDirectory, "package.json"), packageJson); writeFileSync(join(stagingDirectory, "bun.lock"), lockfile); const result = Bun.spawnSync( - [process.execPath, "install", "--frozen-lockfile"], + [process.execPath, "install", "--frozen-lockfile", "--production"], { cwd: stagingDirectory } ); if (result.exitCode !== 0) { process.stdout.write(result.stdout); process.stderr.write(result.stderr); throw new Error( - `bun install --frozen-lockfile exited with status ${result.exitCode}` + `bun install --frozen-lockfile --production exited with status ${result.exitCode}` ); } if (!hasCommander(stagingDirectory)) { throw new Error( - "bun install --frozen-lockfile completed without installing commander" + "bun install --frozen-lockfile --production completed without installing commander" ); } From 3cb4418c7e52951c2b1e410ed37b495d92dbc633 Mon Sep 17 00:00:00 2001 From: Eric Litman Date: Tue, 1 Dec 2026 08:36:49 -0500 Subject: [PATCH 4/7] fix(watch-pr): treat null GraphQL statusCheckRollup as no checks instead of retryable failure (#296) Co-Authored-By: Claude Opus 5.5 --- NOTICE.md | 2 +- UPSTREAM.md | 1 + .../scripts/watch-pr/fakes.test-helper.ts | 2 +- .../scripts/watch-pr/github.test.ts | 41 +++++++++++++++---- .../poteto-mode/scripts/watch-pr/github.ts | 13 ++++-- .../scripts/watch-pr/policy.test.ts | 41 +++++++++++++++++++ .../poteto-mode/scripts/watch-pr/policy.ts | 29 +++++++++++-- .../poteto-mode/scripts/watch-pr/render.ts | 2 +- .../poteto-mode/scripts/watch-pr/types.ts | 23 +++++++---- 9 files changed, 127 insertions(+), 27 deletions(-) diff --git a/NOTICE.md b/NOTICE.md index 61d20ea5..36e3e6aa 100644 --- a/NOTICE.md +++ b/NOTICE.md @@ -38,7 +38,7 @@ Summary of structural changes: - The native `plugins/pstack/skills/` tree is the only user-facing workflow surface. Claude Code and Codex invoke those skills directly. - Seven skills imported from `cursor-team-kit`: `deslop`, `thermo-nuclear-code-quality-review`, `make-pr-easy-to-review`, `fix-ci`, `fix-merge-conflicts`, `get-pr-comments`, `what-did-i-get-done`. All copied verbatim — no rewiring needed. - `plugins/pstack/skills/babysit/` is independently authored as the Claude Code analog of Cursor's `/babysit` built-in. It has no upstream pstack equivalent; its workflow is informed by Cursor's public `/babysit` behavior. No code or prose was copied from any source. -- `plugins/pstack/skills/poteto-mode/scripts/` is vendored from upstream (`watch-pr`, `orch`, `bootstrap.ts`, `worktree-audit.sh`, `package.json`, `bun.lock`) with these port edits: `worktree-audit.sh` reads `~/.claude/projects/` instead of Cursor's transcript directory and warns when `jq` or `rg` is missing (their absence silently blanks the columns the prune decision reads), the private workspace package is named `@open-pstack/poteto-mode-tools`, `bootstrap.ts` rejects Node before it reads Bun-only APIs and installs frozen dependencies in a user cache keyed by the manifest and lockfile outside the plugin, then registers Commander with Bun before the CLI imports it (#293), and `package.json` includes the port-authored tests in `bun run test`. `check-plan.mjs` is the Cursor 0.14.3 checker adapted for the shared Claude Code and Codex skeleton. `bootstrap.test.ts` and `check-plan.test.ts` are authored for this port. `check-plan.test.ts` also carries the fence cases from upstream's `check-plan.test.ts` at 0.15.20, run against the extracted plan skeleton. +- `plugins/pstack/skills/poteto-mode/scripts/` is vendored from upstream (`watch-pr`, `orch`, `bootstrap.ts`, `worktree-audit.sh`, `package.json`, `bun.lock`) with these port edits: `worktree-audit.sh` reads `~/.claude/projects/` instead of Cursor's transcript directory and warns when `jq` or `rg` is missing (their absence silently blanks the columns the prune decision reads), the private workspace package is named `@open-pstack/poteto-mode-tools`, `bootstrap.ts` rejects Node before it reads Bun-only APIs and installs frozen dependencies in a user cache keyed by the manifest and lockfile outside the plugin, then registers Commander with Bun before the CLI imports it (#293), `watch-pr` reads a head with no GraphQL check rollup as having no checks instead of a retryable query failure (#296), and `package.json` includes the port-authored tests in `bun run test`. `check-plan.mjs` is the Cursor 0.14.3 checker adapted for the shared Claude Code and Codex skeleton. `bootstrap.test.ts` and `check-plan.test.ts` are authored for this port. `check-plan.test.ts` also carries the fence cases from upstream's `check-plan.test.ts` at 0.15.20, run against the extracted plan skeleton. - `plugins/pstack/agents/comment-sicko.md` is upstream's `Comment Sicko` agent, renamed to `comment-sicko` so the name works as a Claude Code `subagent_type`. The body is verbatim. - `plugins/pstack/agents/poteto-agent.md` keeps the upstream prompt and adds Claude Code `skills` frontmatter so the isolated subagent preloads `pstack:poteto-mode`. - Claude-native lanes are port-authored agent definitions. Fable, Opus and Sonnet select their rolling family alias, and the Opus 5.5 and Haiku 5.5 pins select their exact model, each with the requested effort, for every selectable Claude-native pair in the model catalog. `registry/render.ts` generates them from the runner registry. diff --git a/UPSTREAM.md b/UPSTREAM.md index a0904041..d9a3ed12 100644 --- a/UPSTREAM.md +++ b/UPSTREAM.md @@ -47,6 +47,7 @@ The table above is the current Cursor sync point. Open Pstack 1.17.0 imported th ## Local port-patch ledger +- **#296 — heads with no check rollup**: upstream's `watch-pr` treats a GraphQL `statusCheckRollup` of `null` as an unreadable rollup and retries until `--max-query-errors`, so a repository with no CI never settles. The port reads a null rollup as no checks: `--status-only` reports `✅ no checks` at once, and watch mode confirms with one re-read after one backoff before it reports ready. A rollup with no readable contexts, or a PR with no commits, still fails closed. Preserve this divergence during syncs. - **#293 — dependency cache outside the plugin**: upstream's `bootstrap.ts` installs `watch-pr` dependencies into the plugin, where Bun's TypeScript bin symlink breaks Codex hook fingerprinting. The port runs `bun install --frozen-lockfile --production` in a user cache keyed by the hash of `package.json` and `bun.lock`, under an absolute `XDG_CACHE_HOME`, Windows local app data, or `~/.cache`, and publishes it by atomic rename. It then registers Commander from that cache with Bun before the CLI imports it. Preserve this divergence and the early Bun guard during syncs; never install into the plugin tree. - **#235 — Claude transcript folder encoding**: the port wrote Claude Code's per-project transcript path into `recall`, `automate-me` and the `session-pickup` playbook. Claude Code encodes each `/` and each `.` in the workspace path as `-`, so a `.claude/worktrees/` session's folder holds `--claude-worktrees-`. Keep both characters in those three lines during syncs. - **#140 — Reflect transcript resolution**: Cursor's Reflect step 1 reads the `agent-transcripts/` directory its system prompt names; the port had substituted Claude Code's per-project directory, which left Codex without a lookup. The port replaces that step's body with one line that points to `plugins/pstack/skills/poteto-mode/references/codex-tools.md#active-transcripts`, and leaves the rest of `reflect/SKILL.md` unchanged. That mapping section holds the harness specifics: the Claude per-project scope, layouts, candidate and scan limits, opening-message verification, the Codex resolver call, and the 2,000-word digest fallback. The port-authored Bun resolver `plugins/pstack/skills/poteto-mode/scripts/resolve-codex-transcript.ts`, started through the `sh` launcher `resolve-codex-transcript` next to it so project Bun config and `.env` files cannot affect it, looks up the parent's known chat ID in Codex's read-only `threads` index, checks rollout scope and ownership, and prints opening-message metadata without transcript text. Preserve this divergence during upstream syncs: keep step 1 as the one-line pointer and keep the mapping section and resolver. diff --git a/plugins/pstack/skills/poteto-mode/scripts/watch-pr/fakes.test-helper.ts b/plugins/pstack/skills/poteto-mode/scripts/watch-pr/fakes.test-helper.ts index 84ccf596..b6122b43 100644 --- a/plugins/pstack/skills/poteto-mode/scripts/watch-pr/fakes.test-helper.ts +++ b/plugins/pstack/skills/poteto-mode/scripts/watch-pr/fakes.test-helper.ts @@ -112,7 +112,7 @@ export function fakeReader( }, async checkRollupPage(_requested, after) { calls.push(`checkRollupPage:${after ?? "null"}`); - return options.rollupPages?.[page++] ?? { checks: [], endCursor: null }; + return options.rollupPages?.[page++] ?? { kind: "contexts", checks: [], endCursor: null }; }, async reviewThreadPage(_requested, after) { calls.push(`reviewThreadPage:${after ?? "null"}`); diff --git a/plugins/pstack/skills/poteto-mode/scripts/watch-pr/github.test.ts b/plugins/pstack/skills/poteto-mode/scripts/watch-pr/github.test.ts index 4e589383..f4bf6917 100644 --- a/plugins/pstack/skills/poteto-mode/scripts/watch-pr/github.test.ts +++ b/plugins/pstack/skills/poteto-mode/scripts/watch-pr/github.test.ts @@ -45,8 +45,8 @@ describe("checks fallback chain", () => { const reader = fakeReader({ fastPath: { kind: "unusable", exitCode: 8, stderr: "" }, rollupPages: [ - { checks: [passingCheck("first")], endCursor: "next" }, - { checks: [failedCheck("second")], endCursor: null }, + { kind: "contexts", checks: [passingCheck("first")], endCursor: "next" }, + { kind: "contexts", checks: [failedCheck("second")], endCursor: null }, ], }); const read = await resolveChecks(reader, context); @@ -62,15 +62,17 @@ describe("checks fallback chain", () => { 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 }], + rollupPages: [ + { kind: "contexts", checks: [pendingCheck("fallback")], endCursor: null }, + ], }); - expect((await resolveChecks(reader, context)).checks[0].name).toBe( - "fallback" - ); + expect( + (await resolveChecks(reader, context)).checks.map((check) => check.name) + ).toEqual(["fallback"]); expect(reader.calls).toEqual(["checksFastPath", "checkRollupPage:null"]); }); - it("fails closed when both paths are empty", async () => { + it("fails closed when the rollup exists with no readable contexts", async () => { const reader = fakeReader({ fastPath: { kind: "unusable", @@ -83,6 +85,31 @@ describe("checks fallback chain", () => { ); expect(reader.calls).toEqual(["checksFastPath", "checkRollupPage:null"]); }); + + it("reports no checks when gh finds none and the head has no rollup", () => { + const directory = mkdtempSync(join(tmpdir(), "watch-pr-no-checks-")); + try { + writeFileSync(join(directory, "gh"), `#!/bin/sh +case "$1 $2" in + "pr checks") echo "no checks reported on the 'feature' branch" >&2; exit 1 ;; + "api graphql") printf '%s\\n' '{"data":{"repository":{"pullRequest":{"commits":{"nodes":[{"commit":{"statusCheckRollup":null}}]}}}}}' ;; + *) exit 2 ;; +esac +`, { mode: 0o755 }); + const program = `import { GhGitHubReader, resolveChecks } from ${JSON.stringify(import.meta.dir + "/github.ts")}; + console.log(JSON.stringify(await resolveChecks(new GhGitHubReader(), ${JSON.stringify(context)})));`; + const child = spawnSync(process.execPath, ["-e", program], { + encoding: "utf8", timeout: 2000, + env: { ...process.env, PATH: directory + ":" + process.env.PATH }, + }); + expect(child.error).toBeUndefined(); + expect(child.stderr).toBe(""); + expect(child.status).toBe(0); + expect(JSON.parse(child.stdout)).toEqual({ source: "no-checks", checks: [] }); + } finally { + rmSync(directory, { recursive: true, force: true }); + } + }); }); describe("rollup node mapping", () => { diff --git a/plugins/pstack/skills/poteto-mode/scripts/watch-pr/github.ts b/plugins/pstack/skills/poteto-mode/scripts/watch-pr/github.ts index 123a33b1..6c4ada1b 100644 --- a/plugins/pstack/skills/poteto-mode/scripts/watch-pr/github.ts +++ b/plugins/pstack/skills/poteto-mode/scripts/watch-pr/github.ts @@ -553,13 +553,13 @@ export class GhGitHubReader implements T.GitHubReader { at(value, ["data", "repository", "pullRequest", "commits", "nodes"]), "commits.nodes" ); - if (commits.length === 0) return { checks: [], endCursor: null }; + if (commits.length === 0) + return { kind: "contexts", checks: [], endCursor: null }; const commit = record( at(commits[commits.length - 1], ["commit"]), "commit" ); - if (commit.statusCheckRollup === null) - return { checks: [], endCursor: null }; + if (commit.statusCheckRollup === null) return { kind: "no-rollup" }; const contexts = record( at(commit, ["statusCheckRollup", "contexts"]), "contexts" @@ -574,7 +574,11 @@ export class GhGitHubReader implements T.GitHubReader { page.endCursor, "contexts.pageInfo.endCursor" ); - return { checks, endCursor: page.hasNextPage && cursor ? cursor : null }; + return { + kind: "contexts", + checks, + endCursor: page.hasNextPage && cursor ? cursor : null, + }; } async reviewThreadPage( context: T.PrContext, @@ -621,6 +625,7 @@ export async function resolveChecks( let after: string | null = null; do { const page = await reader.checkRollupPage(context, after); + if (page.kind === "no-rollup") return { source: "no-checks", checks: [] }; checks.push(...page.checks); after = page.endCursor; } while (after !== null); diff --git a/plugins/pstack/skills/poteto-mode/scripts/watch-pr/policy.test.ts b/plugins/pstack/skills/poteto-mode/scripts/watch-pr/policy.test.ts index 966b7536..26135988 100644 --- a/plugins/pstack/skills/poteto-mode/scripts/watch-pr/policy.test.ts +++ b/plugins/pstack/skills/poteto-mode/scripts/watch-pr/policy.test.ts @@ -480,3 +480,44 @@ describe("polling deadline sleeps", () => { }); }); + +describe("heads without a check rollup", () => { + const run = async (statusOnly: boolean) => { + const sleeps: number[] = []; + const emitted: ProgressVerdict[] = []; + let now = 0; + const result = await runSimple({ + dependencies: { + reader: fakeReader({ + fastPath: { kind: "unusable", exitCode: 1, stderr: "no checks reported on the 'feature' branch" }, + rollupPages: [{ kind: "no-rollup" }, { kind: "no-rollup" }], + }), + clock: { + now: () => now, + observedAt: () => "2026-07-26T00:00:00.000Z", + async sleep(seconds) { sleeps.push(seconds); now += seconds; }, + }, + emit(verdict) { emitted.push(verdict as ProgressVerdict); }, + }, + contexts: [context(1)], mode: "single", statusOnly, + options: { ...options, interval: 60 }, + }); + return { result, sleeps, emitted }; + }; + + it("confirms no checks with one re-read before reporting ready", async () => { + const { result, sleeps, emitted } = await run(false); + expect(emitted.map((verdict) => verdict.kind)).toEqual(["RETRY"]); + expect(emitted[0]).toMatchObject({ failure: { kind: "checks-unavailable" } }); + expect(sleeps).toEqual([60]); + expect(result.kind).toBe("READY"); + }); + + it("settles status-only immediately with no checks", async () => { + const { result, sleeps, emitted } = await run(true); + expect(result).toMatchObject({ kind: "STATUS", exitCode: 0 }); + expect(result.kind === "STATUS" && result.rows[0].kind === "open" && result.rows[0].ci.source).toBe("no-checks"); + expect(sleeps).toEqual([]); + expect(emitted).toEqual([]); + }); +}); diff --git a/plugins/pstack/skills/poteto-mode/scripts/watch-pr/policy.ts b/plugins/pstack/skills/poteto-mode/scripts/watch-pr/policy.ts index 8179f2d8..4fd99af3 100644 --- a/plugins/pstack/skills/poteto-mode/scripts/watch-pr/policy.ts +++ b/plugins/pstack/skills/poteto-mode/scripts/watch-pr/policy.ts @@ -1,4 +1,5 @@ import { + ChecksUnavailable, WatcherQueryError, resolveChecks, resolveReviewThreads, @@ -69,13 +70,14 @@ export async function readSnapshot(args: { return { kind: "closed", context: args.context, facts }; const threads = await resolveReviewThreads(args.reader, args.context); const checks = await resolveChecks(args.reader, args.context); + const all: readonly T.Check[] = checks.checks; const failed = nonEmpty( - checks.checks.filter( + all.filter( (check): check is T.FailedCheck => check.kind === "failed" ) ); const pending = nonEmpty( - checks.checks.filter( + all.filter( (check): check is T.PendingCheck => check.kind === "pending" ) ); @@ -84,7 +86,7 @@ export async function readSnapshot(args: { ci = { kind: "ci-pending", source: checks.source, - all: checks.checks, + all, failed: [], pending, hadPreviousPassingCi: false, @@ -93,7 +95,7 @@ export async function readSnapshot(args: { const merge = await mergeAssessment(args.reader, facts); const base = { source: checks.source, - all: checks.checks, + all, hadPreviousPassingCi: merge.hadPreviousPassingCi, }; if (failed !== null) @@ -420,6 +422,21 @@ async function pollUntilTerminal(args: { } } } +function confirmNoChecks( + rows: readonly T.PrSnapshot[], + confirmed: Set +): void { + const fresh = rows.flatMap((row) => + row.kind === "open" && row.ci.source === "no-checks" + ? [`${row.context.number}@${row.facts.headRefOid}`] + : [] + ).filter((key) => !confirmed.has(key)); + if (fresh.length === 0) return; + for (const key of fresh) confirmed.add(key); + throw new ChecksUnavailable( + `no checks reported for ${fresh.join(", ")}; reading again to confirm` + ); +} export async function runSimple(args: { readonly dependencies: RunDependencies; readonly contexts: T.NonEmpty; @@ -428,6 +445,7 @@ export async function runSimple(args: { readonly options: T.PollingOptions; }): Promise { const stamp = verdictFactory(args.dependencies.clock, args.mode); + const confirmed = new Set(); const step = async (): Promise> => { const rows: T.PrSnapshot[] = []; for (const context of args.contexts) @@ -454,6 +472,7 @@ export async function runSimple(args: { }; if (args.mode === "queued-stack") throw new Error("queued-stack requires status-only in the simple runner"); + confirmNoChecks(complete, confirmed); if (args.mode === "stack") args.dependencies.emit( stamp( @@ -717,6 +736,7 @@ export async function runQueued(args: { }): Promise { let state = createQueueState(args.contexts, args.dependencies.clock.now()); const stamp = verdictFactory(args.dependencies.clock, "queued-stack"); + const confirmed = new Set(); args.dependencies.emit( stamp({ kind: "QUEUE", terminal: false, queue: args.contexts }) ); @@ -751,6 +771,7 @@ export async function runQueued(args: { pendingHistory: "omit", allowDraft: args.options.allowDraft, }); + confirmNoChecks([snapshot], confirmed); const applied = applyQueueSnapshot( state, snapshot, diff --git a/plugins/pstack/skills/poteto-mode/scripts/watch-pr/render.ts b/plugins/pstack/skills/poteto-mode/scripts/watch-pr/render.ts index 0e935839..3d6f24fb 100644 --- a/plugins/pstack/skills/poteto-mode/scripts/watch-pr/render.ts +++ b/plugins/pstack/skills/poteto-mode/scripts/watch-pr/render.ts @@ -6,7 +6,7 @@ function ciCell(row: T.PrSnapshot): string { const was = row.ci.hadPreviousPassingCi ? ", was ✅" : ""; switch (row.ci.kind) { case "ci-clean": - return "✅"; + return row.ci.source === "no-checks" ? "✅ no checks" : "✅"; case "ci-pending": return `⏳ ${row.ci.pending.length} pending${was}`; case "ci-failing": diff --git a/plugins/pstack/skills/poteto-mode/scripts/watch-pr/types.ts b/plugins/pstack/skills/poteto-mode/scripts/watch-pr/types.ts index 60b9abca..7124af6b 100644 --- a/plugins/pstack/skills/poteto-mode/scripts/watch-pr/types.ts +++ b/plugins/pstack/skills/poteto-mode/scripts/watch-pr/types.ts @@ -87,10 +87,12 @@ export type Check = }); export type FailedCheck = Extract; export type PendingCheck = Extract; -export interface CheckRead { - readonly source: "gh-pr-checks" | "graphql-rollup"; - readonly checks: NonEmpty; -} +export type CheckRead = + | { + readonly source: "gh-pr-checks" | "graphql-rollup"; + readonly checks: NonEmpty; + } + | { readonly source: "no-checks"; readonly checks: readonly [] }; export interface CommitRollup { readonly oid: string; readonly state: RollupState; @@ -116,7 +118,7 @@ export type GitHubMergeAllowed = export type GitHubMergeAssessment = GitHubMergeAllowed | GitHubMergeRefusal; interface CiBase { readonly source: CheckRead["source"]; - readonly all: NonEmpty; + readonly all: readonly Check[]; readonly hadPreviousPassingCi: boolean; } export type CiFailing = CiBase & { @@ -376,10 +378,13 @@ export type ChecksFastPath = readonly exitCode: number; readonly stderr: string; }; -export interface RollupPage { - readonly checks: readonly Check[]; - readonly endCursor: string | null; -} +export type RollupPage = + | { + readonly kind: "contexts"; + readonly checks: readonly Check[]; + readonly endCursor: string | null; + } + | { readonly kind: "no-rollup" }; export interface RawReviewThread { readonly id: string; readonly firstComment: ReviewComment | null; From c473ae1c023cc633742a942f772ae9f0e4508e33 Mon Sep 17 00:00:00 2001 From: Eric Litman Date: Tue, 1 Dec 2026 08:38:56 -0500 Subject: [PATCH 5/7] feat(verify): add shipped-tools:watch-pr live-gate feature (#293) Co-Authored-By: Claude Opus 5.5 --- .../verify-open-pstack/features/README.md | 4 +-- .../verify-open-pstack/features/recipes.ts | 29 ++++++++++++++++++- .../features/shipped-tools.md | 8 +++-- .../verify-open-pstack/scripts/core.test.ts | 15 ++++++---- .../skills/verify-open-pstack/scripts/core.ts | 5 ++-- 5 files changed, 49 insertions(+), 12 deletions(-) diff --git a/.claude/skills/verify-open-pstack/features/README.md b/.claude/skills/verify-open-pstack/features/README.md index 5a99210d..9b164034 100644 --- a/.claude/skills/verify-open-pstack/features/README.md +++ b/.claude/skills/verify-open-pstack/features/README.md @@ -12,7 +12,7 @@ The ownership table below says which features a changed path reaches. `SKILL.md` | `assets` | Installed UI/resource surface for each actual consumer found in the pinned plugin manifests | | `setup` | Installed setup/model configuration with byte-exact daily Claude file restoration before publication | | `runner` | Installed parent invoking real configured provider lanes | -| `tools` | Installed parent invoking the changed shipped CLI | +| `tools` | Installed parent invoking the changed shipped CLI: `shipped-tools:watch-pr` for `watch-pr` and its dependency bootstrap, `shipped-tools` for the rest | | `project` | Native discovery/invocation of this verifier in both harnesses | | `nonRuntime` | Explicit ordinary repository documentation, policy, non-shipped assets, and unit-test paths; no plugin harness launch | @@ -22,7 +22,7 @@ A change to `plugins/pstack/.claude-plugin/plugin.json`, `.claude-plugin/marketp Asset ownership is consumer-driven, not blanket shared ownership. Inspect the exact candidate's plugin manifests. At present, `plugins/pstack/assets/logo.png` is referenced only by `plugins/pstack/.codex-plugin/plugin.json`, so a logo-only change selects the installed Codex asset surface and does not invent a Claude exercise. New shipped assets must be added to `assets` and must have a real manifest consumer; missing, ambiguous, or unknown consumption fails closed. -`bootstrap.ts` belongs to `tools`; exercise its actual consumer, `watch-pr`, including dependency bootstrapping rather than the unrelated external runner. +`bootstrap.ts`, `watch-pr/**`, and the poteto-mode scripts' `package.json` and `bun.lock` belong to `tools` and reach only `shipped-tools:watch-pr`: its actual consumer, `watch-pr`, including dependency bootstrapping, followed by the startup hook in the same installation. They never reach the unrelated external runner. Catalog paths take precedence over `shared` and over the skill match, so `references/model-catalog.md` and the generated agents select only `catalog`, `setup`, and `runner`. Each generated agent is listed by exact path; a new one is unmapped until it is added to `catalog`. Skill-owned `SKILL.md`, `references/**`, and `playbooks/**` select their skill. poteto-mode's `SKILL.md` also reaches Claude's `agent-preload:poteto-agent`, because poteto-agent preloads it. Additional executable paths must be registered explicitly. `core.ts` assigns the Codex transcript resolver, `poteto-mode/scripts/resolve-codex-transcript.ts`, and its launcher, `poteto-mode/scripts/resolve-codex-transcript`, to `reflect` by their exact paths, so a change to it selects `skill-invocation:reflect` rather than the unrelated shipped-tool recipe. Shared consumed mappings select every dependent skill conservatively. The coverage test inventories tracked plugin files; new unmapped files block CI and runs. Deleted skill surfaces cannot silently disappear from evidence: choose a surviving documented entry point demonstrating the intended removal, or report blocked. diff --git a/.claude/skills/verify-open-pstack/features/recipes.ts b/.claude/skills/verify-open-pstack/features/recipes.ts index b6fb03f9..2b8c8012 100644 --- a/.claude/skills/verify-open-pstack/features/recipes.ts +++ b/.claude/skills/verify-open-pstack/features/recipes.ts @@ -1,6 +1,6 @@ import { Database } from 'bun:sqlite'; import { createHash } from 'node:crypto'; -import { lstat, mkdir, readFile, realpath, rm, writeFile } from 'node:fs/promises'; +import { lstat, mkdir, readdir, readFile, realpath, rm, writeFile } from 'node:fs/promises'; import { homedir } from 'node:os'; import { basename, join } from 'node:path'; import { pathToFileURL } from 'node:url'; @@ -747,6 +747,32 @@ const shippedTools: Case = { }, }; +const WATCH_PR = 'skills/poteto-mode/scripts/watch-pr/watch-pr'; +const toolCache = async (f: Fixture): Promise => join((await f.run(['printenv', 'XDG_CACHE_HOME'])).trim(), 'open-pstack/poteto-mode-tools'); +const watchPr: Case = { + id: 'watch-pr', + codexSandbox: 'danger-full-access', + async prepare(f) { + await rm(await toolCache(f), { recursive: true, force: true }); + }, + prompt: f => `${invoke(f.harness, 'poteto-mode', `Do no engineering work. Run the installed helper ${join(f.location, WATCH_PR)} with only the --help flag, exactly once, and reply with the first line it prints.`)} ${rules(f.dir)}`, + async assert(record, f) { + const helper = join(f.location, WATCH_PR); + const ran = record.tools.find(t => !t.failed && String(t.input.command ?? '').includes(`${helper} --help`)); + if (!ran) throw new Error('tool-not-run:watch-pr'); + if (!ran.result?.includes('Usage: watch-pr [options]')) throw new Error('usage-missing:watch-pr'); + if (await lstat(join(f.location, 'skills/poteto-mode/scripts/node_modules')).catch(() => undefined)) throw new Error('plugin-mutated:node_modules'); + const root = await toolCache(f), entries = await readdir(root).catch(() => []); + if (entries.length !== 1) throw new Error(`tool-cache-entries:${entries.length}`); + const cache = join(root, entries[0]!); + if (!await lstat(join(cache, 'node_modules/commander/package.json')).catch(() => undefined)) throw new Error('tool-cache-missing:commander'); + if (await lstat(join(cache, 'node_modules/typescript')).catch(() => undefined)) throw new Error('tool-cache-dev-dependency:typescript'); + const help = join(f.dir, 'watch-pr-help.txt'); + await writeFile(help, ran.result); + return { assertions: ['tool-ran:watch-pr', 'usage-printed', 'plugin-unchanged', 'cache-production-only'], files: [help, join(cache, 'package.json')] }; + }, +}; + const PRELOAD_TASK = 'Without invoking Skill or reading any file, reply with the first Core principle named in the preloaded poteto-mode skill.'; const agentPreload: Case = { id: 'dispatch', @@ -898,6 +924,7 @@ export function recipe(feature: string, harness: Harness, routes: string[] = []) if (feature === 'setup' || feature === 'skill-invocation:setup-pstack') return setup; if (feature === 'catalog') return catalog(harness); if (feature === 'shipped-tools') return [shippedTools]; + if (feature === 'shipped-tools:watch-pr') return [watchPr, startupHook]; if (feature === 'agent-preload:poteto-agent' && harness === 'claude') return [agentPreload]; if (feature === 'skill-invocation:reflect') return reflect(harness); const skill = /^skill-invocation:([a-z][a-z0-9-]+)$/.exec(feature)?.[1]; diff --git a/.claude/skills/verify-open-pstack/features/shipped-tools.md b/.claude/skills/verify-open-pstack/features/shipped-tools.md index 36146828..d9a4b901 100644 --- a/.claude/skills/verify-open-pstack/features/shipped-tools.md +++ b/.claude/skills/verify-open-pstack/features/shipped-tools.md @@ -12,7 +12,7 @@ Invoke the installed `poteto-mode` parent for watch/plan/audit, installed `state Use the candidate's installed help and documented arguments. Create fixture state/output under the private run root; use an explicitly named safe test PR where remote reads are required. Have the native installed workflow drive the changed tool, then inspect its real structured output and persisted state. For the audit assert no mutation; for logging check the written TSV and escaping; for statechart check the written chart and report; for watch/plan preserve the observed result and verdict. Retain native transcripts and these state artifacts. Label any direct helper invocation `local CLI` separately. Name every touched tool and changed branch in the recipe. -`bootstrap.ts` changes require its real shipped-tool consumer, `watch-pr`, including its clean dependency bootstrap path. They do not select the unrelated external runner. +A change to `bootstrap.ts`, `watch-pr/**`, or the poteto-mode scripts' `package.json` or `bun.lock` reaches only `shipped-tools:watch-pr`, never the unrelated external runner. Other tool paths reach `shipped-tools`. ## Gotchas @@ -20,4 +20,8 @@ A mock test is not live proof. Never perform PR writes from a candidate process ## Headless -The `shipped-tools` recipe in `recipes.ts` has the installed `show-me-your-work` workflow run its `log.sh` against a fixture TSV. It asserts the helper command ran from the installed plugin and the persisted row, including formula escaping. `watch-pr`, `check-plan`, the worktree audit, and `statechart` have no case yet. +The `shipped-tools` recipe in `recipes.ts` has the installed `show-me-your-work` workflow run its `log.sh` against a fixture TSV. It asserts the helper command ran from the installed plugin and the persisted row, including formula escaping. + +The `shipped-tools:watch-pr` recipe runs two cases in the same installation. `watch-pr` first removes the run's tool cache under `$XDG_CACHE_HOME/open-pstack/poteto-mode-tools/`, then has the installed `poteto-mode` parent run the installed `watch-pr --help`, with Codex's full-access sandbox so `bun install` can reach the registry. It asserts the command ran from the installed plugin and printed its usage, that the installed `skills/poteto-mode/scripts/node_modules` does not exist, and that the cache holds exactly one entry with Commander and without TypeScript. `startup` then runs the `hook:startup` check in that installation, so a plugin tree the bootstrap changed would fail the next session's hook. + +`check-plan`, the worktree audit, and `statechart` have no case yet. diff --git a/.claude/skills/verify-open-pstack/scripts/core.test.ts b/.claude/skills/verify-open-pstack/scripts/core.test.ts index b007f730..57924372 100644 --- a/.claude/skills/verify-open-pstack/scripts/core.test.ts +++ b/.claude/skills/verify-open-pstack/scripts/core.test.ts @@ -202,10 +202,15 @@ describe('registry and ownership', () => { r.observations = r.observations.filter(o => o.harness !== 'claude'); expect(() => completeEvidence(r)).toThrow('Missing/duplicate evidence: claude/project-skill'); }); - test('bootstrap changes require its shipped tool consumers, not the unrelated runner', () => { - const s = classify([{ filename: 'plugins/pstack/skills/poteto-mode/scripts/bootstrap.ts' }], registry); - expect(s.noRuntime).toBe(false); - expect(s.features).toEqual(withGrok(both('shipped-tools'))); + test('watch-pr and its dependency bootstrap reach only the watch-pr tool case', () => { + const scripts = 'plugins/pstack/skills/poteto-mode/scripts/'; + for (const [filename, feature] of [ + ['bootstrap.ts', 'shipped-tools:watch-pr'], ['watch-pr/github.ts', 'shipped-tools:watch-pr'], ['watch-pr/watch-pr', 'shipped-tools:watch-pr'], + ['package.json', 'shipped-tools:watch-pr'], ['bun.lock', 'shipped-tools:watch-pr'], ['check-plan.mjs', 'shipped-tools'], ['worktree-audit.sh', 'shipped-tools'], + ]) { + expect([filename, classify([{ filename: `${scripts}${filename}` }], registry).features]).toEqual([filename, withGrok(both(feature!))]); + } + for (const harness of HARNESSES) expect(recipe('shipped-tools:watch-pr', harness).map(c => c.id)).toEqual(['watch-pr', 'startup']); }); test('the transcript resolver belongs to Reflect rather than unrelated shipped tools', () => { const path = 'plugins/pstack/skills/poteto-mode/scripts/resolve-codex-transcript.ts'; @@ -237,7 +242,7 @@ describe('registry and ownership', () => { }); test('the shared recipe implementation reaches every implemented recipe and preserves project proof', () => { const path = '.claude/skills/verify-open-pstack/features/recipes.ts'; - const expected = [...both('catalog', 'setup', 'runner', 'shipped-tools', 'hook:startup', 'project-skill', 'writers', + const expected = [...both('catalog', 'setup', 'runner', 'shipped-tools', 'shipped-tools:watch-pr', 'hook:startup', 'project-skill', 'writers', ...WRITER_PROVIDERS.map(provider => `writers:${provider}`), ...registry.skills.map(skill => `skill-invocation:${skill}`)), 'claude:agent-preload:poteto-agent', 'grok:dispatch', 'grok:setup', 't3:dispatch'].sort(); for (const file of [{ filename: path }, { filename: 'docs/moved.md', previous_filename: path }]) { diff --git a/.claude/skills/verify-open-pstack/scripts/core.ts b/.claude/skills/verify-open-pstack/scripts/core.ts index 0ee5ddc5..b3d9d951 100644 --- a/.claude/skills/verify-open-pstack/scripts/core.ts +++ b/.claude/skills/verify-open-pstack/scripts/core.ts @@ -23,6 +23,7 @@ const T3_DISPATCH_PATHS = [ '.claude/skills/verify-open-pstack/scripts/harness.ts', '.claude/skills/verify-open-pstack/scripts/doctor.ts', ]; const GROK_FEATURES = ['grok:dispatch', 'grok:setup'] as const; +const WATCH_PR_PATHS = /^plugins\/pstack\/skills\/poteto-mode\/scripts\/(?:bootstrap\.ts|watch-pr\/.+|package\.json|bun\.lock)$/; export const VERSION_MANIFESTS: Readonly> = { 'plugins/pstack/.claude-plugin/plugin.json': 'claude', '.claude-plugin/marketplace.json': 'claude', 'plugins/pstack/.codex-plugin/plugin.json': 'codex', @@ -44,7 +45,7 @@ export function classify(files: ChangedFile[], registry: Registry): Selection { } if (T3_DISPATCH_PATHS.includes(path)) features.add('t3:dispatch'); const sharedRecipe = path === '.claude/skills/verify-open-pstack/features/recipes.ts'; - if (sharedRecipe) both('catalog', 'writers', ...WRITER_PROVIDERS.map(provider => `writers:${provider}`)); + if (sharedRecipe) both('catalog', 'writers', ...WRITER_PROVIDERS.map(provider => `writers:${provider}`), 'shipped-tools:watch-pr'); const catalog = registry.catalog.some(p => matches(path, p)); if (catalog) { both('catalog', 'setup', 'runner'); grok(); covered = true; } if (sharedRecipe || (!catalog && registry.shared.some(p => matches(path, p)))) { @@ -54,7 +55,7 @@ export function classify(files: ChangedFile[], registry: Registry): Selection { grok(); covered = true; } for (const [key, feature] of [['setup', 'setup'], ['runner', 'runner'], ['tools', 'shipped-tools'], ['project', 'project-skill']] as const) { - if (registry[key].some(p => matches(path, p))) { both(feature); grok(); covered = true; } + if (registry[key].some(p => matches(path, p))) { both(feature === 'shipped-tools' && WATCH_PR_PATHS.test(path) ? 'shipped-tools:watch-pr' : feature); grok(); covered = true; } } if (/^plugins\/pstack\/skills\/poteto-mode\/scripts\/resolve-codex-transcript(?:\.ts)?$/.test(path)) { skills.add('reflect'); grok(); covered = true; } const provider = /^plugins\/pstack\/skills\/poteto-mode\/scripts\/runner\/providers\/(?:fixtures\/)?([a-z]+)?/.exec(path); From 25fe7d469a3af47730f406ba01321c3926502f3b Mon Sep 17 00:00:00 2001 From: Eric Litman Date: Tue, 1 Dec 2026 08:51:47 -0500 Subject: [PATCH 6/7] fix(verify): match quoted watch-pr helper path in shipped-tools:watch-pr recipe --- .claude/skills/verify-open-pstack/features/recipes.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/.claude/skills/verify-open-pstack/features/recipes.ts b/.claude/skills/verify-open-pstack/features/recipes.ts index 2b8c8012..21d644c0 100644 --- a/.claude/skills/verify-open-pstack/features/recipes.ts +++ b/.claude/skills/verify-open-pstack/features/recipes.ts @@ -758,7 +758,11 @@ const watchPr: Case = { prompt: f => `${invoke(f.harness, 'poteto-mode', `Do no engineering work. Run the installed helper ${join(f.location, WATCH_PR)} with only the --help flag, exactly once, and reply with the first line it prints.`)} ${rules(f.dir)}`, async assert(record, f) { const helper = join(f.location, WATCH_PR); - const ran = record.tools.find(t => !t.failed && String(t.input.command ?? '').includes(`${helper} --help`)); + const ran = record.tools.find(t => { + if (t.failed) return false; + const command = String(t.input.command ?? ''); + return command.includes(helper) && /(?:^|\s)--help(?:\s|$)/.test(command); + }); if (!ran) throw new Error('tool-not-run:watch-pr'); if (!ran.result?.includes('Usage: watch-pr [options]')) throw new Error('usage-missing:watch-pr'); if (await lstat(join(f.location, 'skills/poteto-mode/scripts/node_modules')).catch(() => undefined)) throw new Error('plugin-mutated:node_modules'); From 98a89f81943c8a17e519af3fec3a8e59ea499ce9 Mon Sep 17 00:00:00 2001 From: Eric Litman Date: Tue, 1 Dec 2026 09:00:59 -0500 Subject: [PATCH 7/7] fix(verify): match shell-wrapped watch-pr --help command in Codex recipe --- .../verify-open-pstack/features/recipes.ts | 2 +- .../verify-open-pstack/scripts/runner.test.ts | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/.claude/skills/verify-open-pstack/features/recipes.ts b/.claude/skills/verify-open-pstack/features/recipes.ts index 21d644c0..7b3872a0 100644 --- a/.claude/skills/verify-open-pstack/features/recipes.ts +++ b/.claude/skills/verify-open-pstack/features/recipes.ts @@ -761,7 +761,7 @@ const watchPr: Case = { const ran = record.tools.find(t => { if (t.failed) return false; const command = String(t.input.command ?? ''); - return command.includes(helper) && /(?:^|\s)--help(?:\s|$)/.test(command); + return command.includes(helper) && /(?:^|\s)--help(?:$|[\s'"])/.test(command); }); if (!ran) throw new Error('tool-not-run:watch-pr'); if (!ran.result?.includes('Usage: watch-pr [options]')) throw new Error('usage-missing:watch-pr'); diff --git a/.claude/skills/verify-open-pstack/scripts/runner.test.ts b/.claude/skills/verify-open-pstack/scripts/runner.test.ts index c500888c..9302881a 100644 --- a/.claude/skills/verify-open-pstack/scripts/runner.test.ts +++ b/.claude/skills/verify-open-pstack/scripts/runner.test.ts @@ -52,3 +52,22 @@ test('the runner recipe adds one linked-worktree writer case for a Codex parent await writeFile(path, JSON.stringify({ ...receipt, argv: [...receipt.argv.slice(0, settings), ...receipt.argv.slice(settings + 2)] })); await expect(writer.assert(record, f)).rejects.toThrow('shared-git-not-denied'); }); + +test('shipped-tools:watch-pr matches shell-wrapped Codex commands and rejects non-help flags', async () => { + const dir = await realpath(await mkdtemp(join(tmpdir(), 'pstack-watch-pr-recipe-'))); roots.push(dir); + const location = join(dir, 'plugin'), cache = join(dir, 'cache'), entry = join(cache, 'open-pstack/poteto-mode-tools/abc123'); + await mkdir(join(entry, 'node_modules/commander'), { recursive: true }); + await writeFile(join(entry, 'node_modules/commander/package.json'), '{}'); + await writeFile(join(entry, 'package.json'), '{}'); + const helper = join(location, 'skills/poteto-mode/scripts/watch-pr/watch-pr'); + const f: Fixture = { harness: 'codex', dir, workspace: dir, location, configHome: dir, run: async () => `${cache}\n` }; + const watch = recipe('shipped-tools:watch-pr', 'codex')[0]!; + const record = (cmd: string): SessionRecord => ({ + harness: 'codex', exitCode: 0, started: Date.now() - 1000, skills: ['pstack:poteto-mode'], commands: [cmd], context: [], + tools: [{ name: 'command', id: 'cmd-1', input: { command: cmd }, result: 'Usage: watch-pr [options]\n', parent: null, failed: false }], + }); + + expect((await watch.assert(record(`/bin/zsh -c '${helper} --help'`), f)).assertions) + .toEqual(['tool-ran:watch-pr', 'usage-printed', 'plugin-unchanged', 'cache-production-only']); + await expect(watch.assert(record(`/bin/zsh -c '${helper} --help-extra'`), f)).rejects.toThrow('tool-not-run:watch-pr'); +});