pr-shepherd 2.2.9 → 2.2.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/.agents/plugins/marketplace.json +2 -2
  2. package/.claude-plugin/marketplace.json +2 -2
  3. package/.claude-plugin/plugin.json +1 -1
  4. package/.grok-plugin/marketplace.json +2 -2
  5. package/README.md +1 -1
  6. package/bin/checks/classify.mjs +4 -2
  7. package/bin/cli/help-command-pages.d.mts +2 -2
  8. package/bin/cli/help-iterate-poll-pages.d.mts +2 -2
  9. package/bin/cli/help-iterate-poll-pages.mjs +7 -0
  10. package/bin/cli/help-top-page.d.mts +1 -1
  11. package/bin/cli/help-top-page.mjs +1 -0
  12. package/bin/cli/help.d.mts +3 -3
  13. package/bin/cli/iterate-instructions.mjs +7 -4
  14. package/bin/cli/poll-handler.mjs +49 -67
  15. package/bin/cli/poll-loop-options.d.mts +25 -0
  16. package/bin/cli/poll-loop-options.mjs +58 -0
  17. package/bin/cli/poll-watch.d.mts +27 -0
  18. package/bin/cli/poll-watch.mjs +48 -0
  19. package/bin/cli/watch-report.d.mts +17 -0
  20. package/bin/cli/watch-report.mjs +33 -0
  21. package/bin/commands/iterate/api-usage.mjs +16 -1
  22. package/bin/commands/iterate/gh-cache.d.mts +12 -0
  23. package/bin/commands/iterate/gh-cache.mjs +98 -0
  24. package/bin/commands/iterate/index.mjs +77 -55
  25. package/bin/commands/iterate/merge-plan.d.mts +1 -1
  26. package/bin/commands/poll-options.d.mts +3 -0
  27. package/bin/commands/poll-summary.d.mts +3 -0
  28. package/bin/commands/poll-summary.mjs +5 -1
  29. package/bin/commands/poll-watch-verify.d.mts +6 -0
  30. package/bin/commands/poll-watch-verify.mjs +16 -0
  31. package/bin/commands/poll.mjs +3 -3
  32. package/bin/exit-codes.d.mts +2 -0
  33. package/bin/exit-codes.mjs +2 -0
  34. package/bin/github/batch-parser-helpers.mjs +4 -1
  35. package/bin/state/process-start.d.mts +14 -0
  36. package/bin/state/process-start.mjs +35 -0
  37. package/bin/state/watch-lock.d.mts +29 -0
  38. package/bin/state/watch-lock.mjs +145 -0
  39. package/bin/state/watch-set.d.mts +23 -0
  40. package/bin/state/watch-set.mjs +58 -0
  41. package/bin/types/merge-action.d.mts +8 -0
  42. package/package.json +1 -1
  43. package/plugins/pr-shepherd/.claude-plugin/plugin.json +1 -1
  44. package/plugins/pr-shepherd/.codex-plugin/plugin.json +1 -1
  45. package/plugins/pr-shepherd/hooks/pipe-guard-parse.d.mts +4 -0
  46. package/plugins/pr-shepherd/hooks/pipe-guard-parse.mjs +142 -0
  47. package/plugins/pr-shepherd/hooks/poll-guard.d.mts +1 -0
  48. package/plugins/pr-shepherd/hooks/poll-guard.mjs +23 -1
@@ -0,0 +1,35 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { readFileSync } from "node:fs";
3
+ export const defaultProcessStartDeps = {
4
+ platform: process.platform,
5
+ readFile: (path) => readFileSync(path, "utf8"),
6
+ ps: (pid) => execFileSync("ps", ["-o", "lstart=", "-p", String(pid)], {
7
+ encoding: "utf8",
8
+ env: { ...process.env, LC_ALL: "C" },
9
+ timeout: 2000,
10
+ stdio: ["ignore", "pipe", "ignore"],
11
+ }),
12
+ };
13
+ /** Field 22 of `/proc/<pid>/stat` (start time in ticks since boot); `comm` may contain spaces. */
14
+ export function parseLinuxStartTicks(stat) {
15
+ const rest = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
16
+ const ticks = rest[19];
17
+ return ticks && /^\d+$/.test(ticks) ? ticks : undefined;
18
+ }
19
+ /**
20
+ * An opaque token that identifies one process incarnation of `pid`: `/proc` start ticks on Linux,
21
+ * `ps -o lstart=` elsewhere (macOS). Undefined when it cannot be read, for example when a
22
+ * sandbox hides the process; callers must then fall back to PID liveness alone.
23
+ */
24
+ export function readProcessStart(pid, deps = defaultProcessStartDeps) {
25
+ try {
26
+ if (deps.platform === "linux") {
27
+ const ticks = parseLinuxStartTicks(deps.readFile(`/proc/${pid}/stat`));
28
+ return ticks && `linux:${ticks}`;
29
+ }
30
+ return deps.ps(pid).trim() || undefined;
31
+ }
32
+ catch {
33
+ return undefined;
34
+ }
35
+ }
@@ -0,0 +1,29 @@
1
+ export interface WatchRepo {
2
+ owner: string;
3
+ name: string;
4
+ }
5
+ export interface WatchHolder {
6
+ pr: number;
7
+ pid: number;
8
+ /** Opaque process start token; absent when the holder's start time could not be read. */
9
+ startedAt?: string;
10
+ /** The holder's relevant flags, such as `--merge`. */
11
+ flags: string[];
12
+ }
13
+ export type AcquireResult = {
14
+ acquired: true;
15
+ } | {
16
+ acquired: false;
17
+ holder: WatchHolder;
18
+ };
19
+ /** Claims the per-PR watcher lock, taking it over from a dead or PID-reused holder. */
20
+ export declare function acquireWatchLock(repo: WatchRepo, pr: number, flags: string[]): AcquireResult;
21
+ /**
22
+ * Per-tick ownership check for a PR this process holds: one file read when the lock is still ours.
23
+ * A missing or unreadable file is recreated (an `admin clean` may have removed the directory), a
24
+ * stale holder is taken over, and a live other holder is left untouched and returned as lost.
25
+ */
26
+ export declare function verifyWatchLock(repo: WatchRepo, pr: number, flags: string[]): AcquireResult;
27
+ /** Removes this process's lock for `pr`; another process's lock is never touched. */
28
+ export declare function releaseWatchLock(repo: WatchRepo, pr: number): void;
29
+ export declare function releaseAllWatchLocks(): void;
@@ -0,0 +1,145 @@
1
+ import { linkSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
2
+ import { dirname } from "node:path";
3
+ import { resolvePrStatePath } from "./base.mjs";
4
+ import { readProcessStart } from "./process-start.mjs";
5
+ const LOCK_FILE = "watch.lock.json";
6
+ const GUARD_FILE = "watch.lock.guard";
7
+ const GUARD_STALE_MS = 10_000;
8
+ const ATTEMPTS = 4;
9
+ const held = new Map();
10
+ let hooksInstalled = false;
11
+ let tmpSeq = 0;
12
+ const keyOf = (repo, pr) => `${repo.owner}/${repo.name}#${pr}`;
13
+ const pathFor = (repo, pr, file = LOCK_FILE) => resolvePrStatePath({ owner: repo.owner, repo: repo.name, pr }, file);
14
+ function readHolder(path) {
15
+ try {
16
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
17
+ const valid = Number.isInteger(parsed.pid) && parsed.pid > 0 && Array.isArray(parsed.flags);
18
+ return valid ? parsed : undefined;
19
+ }
20
+ catch {
21
+ return undefined;
22
+ }
23
+ }
24
+ /** Only ESRCH proves the process is gone; EPERM (a sandbox hiding it) means it exists. */
25
+ function pidAlive(pid) {
26
+ try {
27
+ process.kill(pid, 0);
28
+ return true;
29
+ }
30
+ catch (error) {
31
+ return error.code !== "ESRCH";
32
+ }
33
+ }
34
+ /** Dead holder, or a live PID whose readable start time differs (PID reuse). Unreadable start: alive. */
35
+ function isStale(holder) {
36
+ if (!pidAlive(holder.pid))
37
+ return true;
38
+ if (!holder.startedAt)
39
+ return false;
40
+ const current = readProcessStart(holder.pid);
41
+ return current !== undefined && current !== holder.startedAt;
42
+ }
43
+ /** Publishes the full lock content atomically: the hard link fails with EEXIST when a lock exists. */
44
+ function linkLock(path, holder) {
45
+ const tmp = `${path}.${process.pid}.${(tmpSeq += 1)}.tmp`;
46
+ writeFileSync(tmp, JSON.stringify(holder));
47
+ try {
48
+ linkSync(tmp, path);
49
+ return true;
50
+ }
51
+ catch (error) {
52
+ if (error.code === "EEXIST")
53
+ return false;
54
+ throw error;
55
+ }
56
+ finally {
57
+ rmSync(tmp, { force: true });
58
+ }
59
+ }
60
+ /** Only the holder of the guard may remove a stale lock, so two takeovers cannot both win. */
61
+ function takeOver(repo, pr, mine) {
62
+ const path = pathFor(repo, pr);
63
+ const guard = pathFor(repo, pr, GUARD_FILE);
64
+ try {
65
+ writeFileSync(guard, "", { flag: "wx" });
66
+ }
67
+ catch (error) {
68
+ if (error.code !== "EEXIST")
69
+ throw error;
70
+ // A guard left by a crashed takeover must not block the PR forever.
71
+ const guardMtime = statSync(guard, { throwIfNoEntry: false })?.mtimeMs ?? Date.now();
72
+ if (Date.now() - guardMtime > GUARD_STALE_MS) {
73
+ rmSync(guard, { force: true });
74
+ }
75
+ return false;
76
+ }
77
+ try {
78
+ const current = readHolder(path);
79
+ if (current && !isStale(current))
80
+ return false;
81
+ rmSync(path, { force: true });
82
+ return linkLock(path, mine);
83
+ }
84
+ finally {
85
+ rmSync(guard, { force: true });
86
+ }
87
+ }
88
+ /** Claims the per-PR watcher lock, taking it over from a dead or PID-reused holder. */
89
+ export function acquireWatchLock(repo, pr, flags) {
90
+ const path = pathFor(repo, pr);
91
+ mkdirSync(dirname(path), { recursive: true });
92
+ const startedAt = readProcessStart(process.pid);
93
+ const mine = { pr, pid: process.pid, ...(startedAt && { startedAt }), flags };
94
+ for (let attempt = 0; attempt < ATTEMPTS; attempt += 1) {
95
+ if (linkLock(path, mine) || takeOverIfStale(repo, pr, mine)) {
96
+ track(repo, pr);
97
+ return { acquired: true };
98
+ }
99
+ const current = readHolder(path);
100
+ if (current && !isStale(current))
101
+ return { acquired: false, holder: current };
102
+ }
103
+ throw new Error(`could not acquire the watch lock for PR #${pr}`);
104
+ }
105
+ /**
106
+ * Per-tick ownership check for a PR this process holds: one file read when the lock is still ours.
107
+ * A missing or unreadable file is recreated (an `admin clean` may have removed the directory), a
108
+ * stale holder is taken over, and a live other holder is left untouched and returned as lost.
109
+ */
110
+ export function verifyWatchLock(repo, pr, flags) {
111
+ if (readHolder(pathFor(repo, pr))?.pid === process.pid)
112
+ return { acquired: true };
113
+ const result = acquireWatchLock(repo, pr, flags);
114
+ if (!result.acquired)
115
+ held.delete(keyOf(repo, pr));
116
+ return result;
117
+ }
118
+ function takeOverIfStale(repo, pr, mine) {
119
+ const current = readHolder(pathFor(repo, pr));
120
+ return (current === undefined || isStale(current)) && takeOver(repo, pr, mine);
121
+ }
122
+ /** Removes this process's lock for `pr`; another process's lock is never touched. */
123
+ export function releaseWatchLock(repo, pr) {
124
+ held.delete(keyOf(repo, pr));
125
+ const path = pathFor(repo, pr);
126
+ if (readHolder(path)?.pid === process.pid)
127
+ rmSync(path, { force: true });
128
+ }
129
+ export function releaseAllWatchLocks() {
130
+ for (const { repo, pr } of held.values())
131
+ releaseWatchLock(repo, pr);
132
+ }
133
+ function track(repo, pr) {
134
+ held.set(keyOf(repo, pr), { repo, pr });
135
+ if (hooksInstalled)
136
+ return;
137
+ hooksInstalled = true;
138
+ process.on("exit", releaseAllWatchLocks);
139
+ for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) {
140
+ process.once(signal, () => {
141
+ releaseAllWatchLocks();
142
+ process.kill(process.pid, signal);
143
+ });
144
+ }
145
+ }
@@ -0,0 +1,23 @@
1
+ import { ShepherdError } from "../exit-codes.mts";
2
+ import { type WatchHolder, type WatchRepo } from "./watch-lock.mts";
3
+ /** Thrown when a PR a run needs turns out to be watched by another live process. */
4
+ export declare class WatchedError extends ShepherdError {
5
+ readonly repo: WatchRepo;
6
+ readonly holders: WatchHolder[];
7
+ constructor(repo: WatchRepo, holders: WatchHolder[]);
8
+ }
9
+ /** The per-PR locks one repeating run holds. */
10
+ export interface WatchSet {
11
+ readonly repo: WatchRepo;
12
+ /** Locks the PRs not yet held; returns the holders of those another process already watches. */
13
+ claim(prs: number[]): WatchHolder[];
14
+ /** After a tick: releases rows that stopped, claims rows that appeared; throws if one is watched. */
15
+ sync(rows: ReadonlyArray<{
16
+ pr: number;
17
+ action: string;
18
+ }>): void;
19
+ /** Before a tick: re-checks every held lock; returns the PRs another live process now holds. */
20
+ verify(): WatchHolder[];
21
+ releaseAll(): void;
22
+ }
23
+ export declare function createWatchSet(repo: WatchRepo, flags: string[]): WatchSet;
@@ -0,0 +1,58 @@
1
+ import { EXIT, ShepherdError } from "../exit-codes.mjs";
2
+ import { acquireWatchLock, verifyWatchLock, releaseWatchLock, } from "./watch-lock.mjs";
3
+ /** Thrown when a PR a run needs turns out to be watched by another live process. */
4
+ export class WatchedError extends ShepherdError {
5
+ repo;
6
+ holders;
7
+ constructor(repo, holders) {
8
+ super("PR is already watched by another pr-shepherd process", EXIT.WATCHED);
9
+ this.name = "WatchedError";
10
+ this.repo = repo;
11
+ this.holders = holders;
12
+ }
13
+ }
14
+ export function createWatchSet(repo, flags) {
15
+ const held = new Set();
16
+ const release = (pr) => {
17
+ held.delete(pr);
18
+ releaseWatchLock(repo, pr);
19
+ };
20
+ const claim = (prs) => {
21
+ const blocked = [];
22
+ for (const pr of prs.filter((candidate) => !held.has(candidate))) {
23
+ const result = acquireWatchLock(repo, pr, flags);
24
+ if (result.acquired)
25
+ held.add(pr);
26
+ else
27
+ blocked.push(result.holder);
28
+ }
29
+ return blocked;
30
+ };
31
+ return {
32
+ repo,
33
+ claim,
34
+ sync(rows) {
35
+ for (const row of rows)
36
+ if (row.action === "cancel" && held.has(row.pr))
37
+ release(row.pr);
38
+ const blocked = claim(rows.filter((row) => row.action !== "cancel").map((row) => row.pr));
39
+ if (blocked.length > 0)
40
+ throw new WatchedError(repo, blocked);
41
+ },
42
+ verify() {
43
+ const lost = [];
44
+ for (const pr of held) {
45
+ const result = verifyWatchLock(repo, pr, flags);
46
+ if (result.acquired)
47
+ continue;
48
+ held.delete(pr);
49
+ lost.push(result.holder);
50
+ }
51
+ return lost;
52
+ },
53
+ releaseAll() {
54
+ for (const pr of held)
55
+ release(pr);
56
+ },
57
+ };
58
+ }
@@ -14,5 +14,13 @@ export interface MergeCommandPlan {
14
14
  * `apply merge --transport rest` for a queue.
15
15
  */
16
16
  restFallbackCommand?: ShellCommand;
17
+ /**
18
+ * gh's 24h HTTP cache holds a stale GraphQL rate-limit error that makes `gh pr merge` fail while
19
+ * Shepherd's live GraphQL quota is healthy. Present only when found; delete `paths` first.
20
+ */
21
+ ghCacheStaleRateLimit?: {
22
+ paths: string[];
23
+ expiresAt: string;
24
+ };
17
25
  }
18
26
  export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pr-shepherd",
3
- "version": "2.2.9",
3
+ "version": "2.2.11",
4
4
  "description": "Autonomous PR CI monitor and review-comment resolver for agentic coding tools",
5
5
  "keywords": [
6
6
  "automation",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "pr-shepherd",
3
3
  "description": "Autonomous PR CI monitor and review-comment resolver for agentic coding tools",
4
- "version": "2.2.9",
4
+ "version": "2.2.11",
5
5
  "author": {
6
6
  "name": "Jonathan Ong",
7
7
  "email": "jonathanrichardong@gmail.com"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pr-shepherd",
3
- "version": "2.2.9",
3
+ "version": "2.2.11",
4
4
  "description": "Autonomous PR CI monitor and review-comment resolver for Codex.",
5
5
  "author": {
6
6
  "name": "Jonathan Ong",
@@ -0,0 +1,4 @@
1
+ export declare function isBalanced(text: string): boolean;
2
+ export declare function splitCommands(masked: string): { text: string; term: "pipe" | "flow" }[];
3
+ export declare function runsShepherd(words: string[]): boolean;
4
+ export declare function pipesShepherd(command: unknown): boolean;
@@ -0,0 +1,142 @@
1
+ // A small, conservative shell reader for the pipe guard. It answers one question:
2
+ // is a pr-shepherd command's stdout certainly piped into another command? Anything
3
+ // it cannot read with confidence (unbalanced quotes, odd syntax) answers "no".
4
+
5
+ import { maskShell } from "./poll-guard-shell.mjs";
6
+
7
+ const ASSIGNMENT = /^[A-Za-z_]\w*=/;
8
+ const LEADING_KEYWORDS = new Set([
9
+ "!",
10
+ "time",
11
+ "then",
12
+ "do",
13
+ "else",
14
+ "elif",
15
+ "if",
16
+ "while",
17
+ "until",
18
+ ]);
19
+ const FLOW = "flow";
20
+ const PIPE = "pipe";
21
+
22
+ /** True when every quote, backtick, and `$(…)` in `text` is closed. Heredoc text may defeat it, which only allows. */
23
+ export function isBalanced(text) {
24
+ const stack = [];
25
+ for (let i = 0; i < text.length; i++) {
26
+ const c = text[i];
27
+ const top = stack.at(-1);
28
+ if (c === "\\") i++;
29
+ else if (top === "d") {
30
+ if (c === '"') stack.pop();
31
+ else if (c === "`") stack.push("b");
32
+ else if (c === "$" && text[i + 1] === "(") {
33
+ stack.push("p");
34
+ i++;
35
+ }
36
+ } else if (c === "'") {
37
+ const end = singleQuoteEnd(text, i);
38
+ if (end === -1) return false;
39
+ i = end;
40
+ } else if (c === "$" && text[i + 1] === "'") {
41
+ const end = singleQuoteEnd(text, i + 1, true);
42
+ if (end === -1) return false;
43
+ i = end;
44
+ } else if (c === '"') stack.push("d");
45
+ else if (c === "`") {
46
+ if (top === "b") stack.pop();
47
+ else stack.push("b");
48
+ } else if (c === "(") stack.push("p");
49
+ else if (c === ")") {
50
+ if (top === "p") stack.pop();
51
+ } else if (c === "#" && (i === 0 || /[\s;&|(]/.test(text[i - 1]))) {
52
+ const end = text.indexOf("\n", i);
53
+ if (end === -1) break;
54
+ i = end;
55
+ }
56
+ }
57
+ return stack.length === 0;
58
+ }
59
+
60
+ /** Index of the quote closing the one at `from`, or -1. `$'…'` honors backslash escapes. */
61
+ function singleQuoteEnd(text, from, escapes = false) {
62
+ for (let j = from + 1; j < text.length; j++) {
63
+ if (escapes && text[j] === "\\") j++;
64
+ else if (text[j] === "'") return j;
65
+ }
66
+ return -1;
67
+ }
68
+
69
+ /**
70
+ * Splits masked text into simple commands. Each is `{ text, term }`, where `term` is
71
+ * "pipe" when a single `|` or `|&` follows it directly and "flow" for any other
72
+ * boundary. Redirections such as `2>&1`, `&>f`, and `>|f` are not boundaries.
73
+ */
74
+ export function splitCommands(masked) {
75
+ const parts = [];
76
+ let start = 0;
77
+ const cut = (at, term, width = 1) => {
78
+ parts.push({ text: masked.slice(start, at), term });
79
+ start = at + width;
80
+ };
81
+ for (let i = 0; i < masked.length; i++) {
82
+ const c = masked[i];
83
+ const prev = masked[i - 1];
84
+ const next = masked[i + 1];
85
+ if (c === ";" || c === "\n" || c === "(" || c === ")" || c === "`") cut(i, FLOW);
86
+ else if (c === "&") {
87
+ if (next === "&") {
88
+ cut(i, FLOW, 2);
89
+ i++;
90
+ } else if (prev !== "<" && prev !== ">" && next !== ">") cut(i, FLOW);
91
+ } else if (c === "|" && prev !== ">") {
92
+ if (next === "|") {
93
+ cut(i, FLOW, 2);
94
+ i++;
95
+ } else if (next === "&") {
96
+ cut(i, PIPE, 2);
97
+ i++;
98
+ } else cut(i, PIPE);
99
+ }
100
+ }
101
+ parts.push({ text: masked.slice(start), term: FLOW });
102
+ return parts;
103
+ }
104
+
105
+ /** The command's words after leading keywords and `VAR=value` assignments. */
106
+ function commandWords(text) {
107
+ const words = text.split(/\s+/).filter(Boolean);
108
+ while (words.length > 0 && (ASSIGNMENT.test(words[0]) || LEADING_KEYWORDS.has(words[0]))) {
109
+ words.shift();
110
+ }
111
+ return words;
112
+ }
113
+
114
+ const isShepherd = (word) => /^pr-shepherd(?:@\S*)?$/.test(word);
115
+
116
+ /**
117
+ * Whether the words run pr-shepherd: `pr-shepherd`, a path ending `/pr-shepherd`,
118
+ * or `npx [-flags] pr-shepherd` / `pnpm exec [-flags] pr-shepherd`.
119
+ */
120
+ export function runsShepherd(words) {
121
+ const [first, ...rest] = words;
122
+ if (first === undefined) return false;
123
+ if (first === "pr-shepherd" || first.endsWith("/pr-shepherd")) return true;
124
+ let args;
125
+ if (first === "npx") args = rest;
126
+ else if (first === "pnpm" && rest[0] === "exec") args = rest.slice(1);
127
+ else return false;
128
+ while (args[0]?.startsWith("-")) args.shift();
129
+ return args[0] !== undefined && isShepherd(args[0]);
130
+ }
131
+
132
+ /** True when a pr-shepherd invocation in `command` is certainly followed by a pipe. */
133
+ export function pipesShepherd(command) {
134
+ if (typeof command !== "string" || !isBalanced(command)) return false;
135
+ // A backslash-newline joins lines. Blank it (odd backslash runs only) before masking.
136
+ const joined = command.replace(/(\\+)\n/g, (m, run) =>
137
+ run.length % 2 === 1 ? `${run.slice(0, -1)} ` : m,
138
+ );
139
+ return splitCommands(maskShell(joined)).some(
140
+ ({ text, term }) => term === PIPE && runsShepherd(commandWords(text)),
141
+ );
142
+ }
@@ -13,3 +13,4 @@ export declare function main(
13
13
  stdinText: string,
14
14
  env: Record<string, string | undefined>,
15
15
  ): GuardResult;
16
+ export declare const PIPE_DENY_REASON: string;
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  // PreToolUse hook for Claude Code and Codex: flags shell commands that poll
3
- // GitHub PR or CI state instead of running one `pr-shepherd … --until-terminal`.
3
+ // GitHub PR or CI state instead of running one `pr-shepherd … --until-terminal`,
4
+ // and always blocks a Bash command that certainly pipes pr-shepherd's output.
4
5
  //
5
6
  // Level: PR_SHEPHERD_POLL_GUARD, else the Claude Code plugin option `poll_guard`
6
7
  // (CLAUDE_PLUGIN_OPTION_POLL_GUARD): `disabled`, `advisory` (default: the call
@@ -12,11 +13,32 @@ import { isAbsolute, resolve } from "node:path";
12
13
  import { pathToFileURL } from "node:url";
13
14
 
14
15
  import { detectPoller, expandPath, guardMessage, readLevel } from "./poll-guard-detect.mjs";
16
+ import { pipesShepherd } from "./pipe-guard-parse.mjs";
17
+
18
+ export const PIPE_DENY_REASON =
19
+ "Piping pr-shepherd output drops its `## Instructions` section and the IDs you must act on; run pr-shepherd without a pipe and read the full output.";
15
20
 
16
21
  const MAX_SCRIPT_BYTES = 64 * 1024;
17
22
 
18
23
  /** Decides the hook result for one tool call. Returns { stdout, stderr, code }. */
19
24
  export function runGuard(input, env, readText = readSmallFile) {
25
+ // A piped pr-shepherd always denies, whatever the poll level. The substring check
26
+ // is the cheap prefilter: most Bash commands mention neither `pr-shepherd` nor `|`.
27
+ const text = input?.tool_input?.command;
28
+ if (
29
+ input?.tool_name === "Bash" &&
30
+ typeof text === "string" &&
31
+ text.includes("pr-shepherd") &&
32
+ text.includes("|") &&
33
+ pipesShepherd(text)
34
+ ) {
35
+ const hookSpecificOutput = {
36
+ hookEventName: "PreToolUse",
37
+ permissionDecision: "deny",
38
+ permissionDecisionReason: PIPE_DENY_REASON,
39
+ };
40
+ return { stdout: `${JSON.stringify({ hookSpecificOutput })}\n`, stderr: "", code: 0 };
41
+ }
20
42
  const { level, error } = readLevel({
21
43
  PR_SHEPHERD_POLL_GUARD: env.PR_SHEPHERD_POLL_GUARD || env.CLAUDE_PLUGIN_OPTION_POLL_GUARD,
22
44
  });