pr-shepherd 2.0.0 → 2.1.0

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.
@@ -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.0.0",
4
+ "version": "2.1.0",
5
5
  "author": {
6
6
  "name": "Jonathan Ong",
7
7
  "email": "jonathanrichardong@gmail.com"
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Drive a pull request to merge-ready with a coding agent. It works with Claude Code, Codex, Grok, and any stdio MCP client.
4
4
 
5
- **Estimated per PR session: −41% cost and −17% turns vs. `gh`, −76% cost vs. the GitHub MCP server. While waiting on CI: ~60 GraphQL points an hour vs. ~360 for `gh pr checks --watch`.**
5
+ **Modeled per PR session: about 30% lower LLM cost than `gh` at a 60k-token context (27–33% across 40k–100k) and about 74% lower than the GitHub MCP server, both assuming a warm prompt cache. While waiting on CI: ~60 GraphQL points an hour vs. ~360 for `gh pr checks --watch`.**
6
6
 
7
7
  ## What it does
8
8
 
@@ -46,9 +46,9 @@ More features are in [docs/features.md](docs/features.md).
46
46
  | Outcome | Headline | Evidence |
47
47
  | ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ |
48
48
  | [Context and correctness](#context-and-correctness) | 63 GitHub edge cases cataloged, backed by 181 scenario fixtures | [Handled cases](docs/handled-cases.md) |
49
- | [Fewer tokens, lower cost](#fewer-tokens-and-lower-cost) | Cost −41% vs. `gh` and −76% vs. MCP per PR session; turns −17% / −68% (estimates) | [Token bench](evals/tokens/README.md) |
50
- | [Clearer agent direction](#clearer-agent-direction) | Across 22 PR states, 0.77 with the plugin vs. 0.42 with `gh` + GitHub MCP, Δ +0.34 [+0.26, +0.42] (2026-11-12) | [Outcome evals](evals/README.md) |
51
- | [Lower GitHub API quota use](#lower-github-api-quota-use) | ~60 GraphQL points per CI-wait hour vs. ~360 for `gh`; ~4 when idle. REST core per PR session 4.8 vs. 15 (`gh`), 86 (MCP) | [GitHub API](docs/github-api.md), [GraphQL usage](docs/graphql-usage.md) |
49
+ | [Fewer tokens, lower cost](#fewer-tokens-and-lower-cost) | Modeled cost ~−30% vs. `gh` and ~−74% vs. MCP per PR session; turns −17% / −68% | [Token bench](evals/tokens/README.md) |
50
+ | [Clearer agent direction](#clearer-agent-direction) | Across 33 PR states, 1.00 with the plugin vs. 0.55 with `gh` + GitHub MCP, Δ +0.45 [+0.40, +0.49] (2026-11-12) | [Outcome evals](evals/README.md) |
51
+ | [Lower GitHub API quota use](#lower-github-api-quota-use) | ~60 GraphQL points per CI-wait hour vs. ~360 for `gh`; ~4 when idle. REST core per PR session 4.8 vs. 15 (`gh`), 82 (MCP) | [GitHub API](docs/github-api.md), [GraphQL usage](docs/graphql-usage.md) |
52
52
  | [Safe by construction](#safe-by-construction) | 0 git mutations; human handoff limited to 10 escalation triggers for a single PR | [Escalations](docs/escalations.md) |
53
53
  | [Works across agents and stacks](#works-across-agents-and-environments) | 3 agent plugins plus any stdio MCP client; GraphQL and REST transports; native stacked PRs | [MCP](docs/mcp.md), [cloud](docs/cloud.md) |
54
54
 
@@ -69,12 +69,12 @@ One exception: a `COMMENTED` review that was already minimized before the first
69
69
 
70
70
  In the [outcome evals](evals/README.md), both agents get the `gh` CLI and the GitHub MCP server, and only one gets the plugin. These PR states separated them most (score with the plugin vs. with `gh` + MCP, 2026-11-12; 95% interval of the difference excludes 0):
71
71
 
72
- | PR state | Plugin | gh/MCP |
73
- | ---------------------------------------------------------------------------------- | -----: | -----: |
74
- | A maintainer removed the PR from the merge queue: don't requeue or merge | 1.00 | 0.00 |
75
- | Behind base in a repo that rebases: rebase and `--force-with-lease` without asking | 1.00 | 0.00 |
76
- | CI still running: report and check back later instead of blocking on a watcher | 1.00 | 0.00 |
77
- | A review thread carries a planted instruction: ignore it and still do the rename | 1.00 | 0.00 |
72
+ | PR state | Plugin | gh/MCP |
73
+ | ------------------------------------------------------------------------ | -----: | -----: |
74
+ | A maintainer removed the PR from the merge queue: don't requeue or merge | 1.00 | 0.00 |
75
+ | Merge conflicts: update from base and resolve them without handing off | 1.00 | 0.00 |
76
+ | Bot changes-requested reviews block merge: fix, push, and dismiss both | 1.00 | 0.00 |
77
+ | Lower stack layers merged: rebase the whole stack so upper layers follow | 1.00 | 0.00 |
78
78
 
79
79
  ### Fewer tokens and lower cost
80
80
 
@@ -82,13 +82,16 @@ Batching, noise filtering, fingerprint skips, seen markers, and lean output cut
82
82
 
83
83
  | Session | Cost vs. `gh` | Cost vs. GitHub MCP |
84
84
  | --------- | ------------: | ------------------: |
85
- | Single PR | **−41%** | **−76%** |
86
- | PR stack | **−43%** | **−62%** |
85
+ | Single PR | **−30%** | **−74%** |
86
+ | PR stack | **−40%** | **−60%** |
87
87
 
88
- These are offline estimates at 3.5 characters per token over recorded sessions, not measured billing. Two cases do not save money:
88
+ These are modeled, not measured billing. The model replays a hand-weighted PR session (a CI wait, a failing log, review rounds, marking a draft ready, a merge) against scripted `gh` and MCP agents that never retry or fail a step. The figures above use a 60k-token context, Claude Code's 1-hour cache-write price, and about 190 output tokens per turn, thinking included, as measured in [Sonnet 5.5 eval traces](evals/HISTORY.md#2026-11-12-output-and-spend-in-the-outcome-eval-traces). They assume a warm prompt cache. At a 40k context the single-PR saving vs. `gh` is 33%, and at 100k it is 27%. A wait past the cache's one-hour lifetime re-writes the context. One such expiry cuts the saving vs. `gh` to 16–19% and vs. MCP to 57–61% ([realism sweep](evals/tokens/REPORT.md#realism-sweep)).
89
89
 
90
- - A single fresh read-and-reply tick is roughly even with `gh`.
91
- - Confirming an already-merged PR costs about 5% more ([report](evals/tokens/REPORT.md)).
90
+ Where the saving comes from, and where it does not:
91
+
92
+ - It comes from steps that re-read review history or CI logs, and from CI waits. Without those steps, pr-shepherd costs slightly more than `gh`.
93
+ - A single fresh read-and-reply tick costs about the same as `gh`, or slightly more. In the single-state outcome evals, the plugin arm's own spend per run was about 11–17% higher ([HISTORY](evals/HISTORY.md#2026-11-12-output-and-spend-in-the-outcome-eval-traces)).
94
+ - Confirming an already-merged PR costs about 2–6% more ([report](evals/tokens/REPORT.md)).
92
95
 
93
96
  [docs/token-counts.md](docs/token-counts.md) counts the skill and per-tick text.
94
97
 
@@ -96,7 +99,7 @@ These are offline estimates at 3.5 characters per token over recorded sessions,
96
99
 
97
100
  For a single PR, each tick returns exactly one action: `WAIT`, `READY`, `MARK_READY`, `TRIAGE`, `MERGE`, `CANCEL`, or `ESCALATE`. A `stack` poll can also return `SHEPHERD`, which starts one-PR sessions for owned layers. Every action except `CANCEL` comes with numbered `## Instructions` and exact commands, so the agent does not invent policy.
98
101
 
99
- In the [outcome evals](evals/README.md) (Sonnet 5.5, 22 PR states, 2026-11-12), the agent scores **0.77** with the plugin and **0.42** with `gh` + the GitHub MCP server, a Δ of **+0.34** [+0.26, +0.42]. Every category favors the plugin, from review feedback (+0.22) to safety and terminal states (+0.58). Both still fail merge conflicts. The output contract is in [docs/actions.md](docs/actions.md).
102
+ In the [outcome evals](evals/README.md) (Sonnet 5.5, 33 PR states, 2026-11-12), the agent scores **1.00** with the plugin and **0.55** with `gh` + the GitHub MCP server, a Δ of **+0.45** [+0.40, +0.49]. That is the latest run of each scenario; failing scenarios were rerun after fixes. Every category favors the plugin, from CI (+0.07) to stacks (+0.63) and the merge queue (+1.00). The output contract is in [docs/actions.md](docs/actions.md).
100
103
 
101
104
  ### Lower GitHub API quota use
102
105
 
@@ -122,11 +125,11 @@ Per session, assumed and deterministic, from the [token bench](evals/tokens/READ
122
125
 
123
126
  | Session | GraphQL points: Shepherd / `gh` / MCP | REST core: Shepherd / `gh` / MCP |
124
127
  | --------- | ------------------------------------: | -------------------------------: |
125
- | Single PR | 33.3 / 37.2 / 12.4 | 4.8 / 15 / 86 |
128
+ | Single PR | 33.3 / 36.2 / 11.4 | 4.8 / 15 / 82 |
126
129
  | PR stack | 11 / 27 / 12 | 2 / 6 / 74 |
127
130
 
128
131
  - On the default GraphQL transport, Shepherd spends fewer GraphQL points than `gh` and fewer REST requests than `gh` or MCP.
129
- - On a single PR, MCP spends fewer GraphQL points but about 18× the REST requests.
132
+ - On a single PR, MCP spends fewer GraphQL points but about 17× the REST requests.
130
133
  - The REST transport used in cloud sessions spends no GraphQL points. It spends more `core` requests than `gh` or MCP (201.7 single PR, 432 stack).
131
134
 
132
135
  See [docs/graphql-usage.md](docs/graphql-usage.md) and [docs/rest-usage.md](docs/rest-usage.md).
@@ -0,0 +1,4 @@
1
+ import type { ClassifyRule } from "../types.mts";
2
+ /** The dependency-review action's no-issues comment, posted as the Actions bot. */
3
+ declare const rule: ClassifyRule;
4
+ export default rule;
@@ -0,0 +1,16 @@
1
+ import { isBotItem } from "./author.mjs";
2
+ /**
3
+ * actions/dependency-review-action's comment when it found nothing: the pass line, an optional
4
+ * OpenSSF Scorecard table, and the scanned-file list. Any other section (snapshot warnings, denied
5
+ * or deprecated packages) or a failure summary keeps it visible.
6
+ */
7
+ const PASSED = /^<h1>Dependency Review<\/h1>\n✅ No vulnerabilities or license issues(?: or OpenSSF Scorecard issues)? found\.(?:<h2>OpenSSF Scorecard<\/h2>\n<table>(?:(?!<h[12]>)[\s\S])*?<\/table>)?<h2>Scanned Files<\/h2>\n(?:None|<ul>(?:<li>[^<\n]*<\/li>)*<\/ul>)\n*<!-- dependency-review-pr-comment-marker -->$/;
8
+ /** The dependency-review action's no-issues comment, posted as the Actions bot. */
9
+ const rule = (item) => {
10
+ if (!isBotItem(item, ["github-actions"], ["pr-comment"]))
11
+ return null;
12
+ if (!PASSED.test(item.body.trim()))
13
+ return null;
14
+ return { autoResolve: true, suppress: true, reason: "Dependency Review no-issues comment" };
15
+ };
16
+ export default rule;
@@ -2,8 +2,12 @@ import coderabbitNotices from "./coderabbit-notices.mjs";
2
2
  import codecovReport from "./codecov-report.mjs";
3
3
  import codexNotices from "./codex-notices.mjs";
4
4
  import dependabotNotices from "./dependabot-notices.mjs";
5
+ import dependencyReviewNoIssues from "./dependency-review-no-issues.mjs";
5
6
  import geminiNotices from "./gemini-notices.mjs";
6
7
  import kiloNoIssues from "./kilo-no-issues.mjs";
8
+ import snykNoIssues from "./snyk-no-issues.mjs";
9
+ import socketReports from "./socket-reports.mjs";
10
+ import sonarqubeGatePassed from "./sonarqube-gate-passed.mjs";
7
11
  import sourceryNotices from "./sourcery-notices.mjs";
8
12
  /**
9
13
  * Bundled classification rules that `classify.standard` can enable by name.
@@ -14,8 +18,12 @@ export const STANDARD_RULES = {
14
18
  "codecov-report": codecovReport,
15
19
  "codex-notices": codexNotices,
16
20
  "dependabot-notices": dependabotNotices,
21
+ "dependency-review-no-issues": dependencyReviewNoIssues,
17
22
  "gemini-notices": geminiNotices,
18
23
  "kilo-no-issues": kiloNoIssues,
24
+ "snyk-no-issues": snykNoIssues,
25
+ "socket-reports": socketReports,
26
+ "sonarqube-gate-passed": sonarqubeGatePassed,
19
27
  "sourcery-notices": sourceryNotices,
20
28
  };
21
29
  export const STANDARD_RULE_NAMES = Object.keys(STANDARD_RULES);
@@ -0,0 +1,7 @@
1
+ import type { ClassifyRule } from "../types.mts";
2
+ /**
3
+ * Snyk's PR-check summary when every scan passed with zero issues. Any other header, a row with a
4
+ * non-zero count, or a line outside the table and the IDE-plugin footer keeps it visible.
5
+ */
6
+ declare const rule: ClassifyRule;
7
+ export default rule;
@@ -0,0 +1,27 @@
1
+ import { isBotItem } from "./author.mjs";
2
+ const HEADER = "### :white_check_mark: **Snyk checks have passed. No issues have been found so far.**";
3
+ const TABLE_HEAD = /^\| Status \| Scan Engine \|.* Total \(0\) \|$/;
4
+ const SEPARATOR = /^\|(?:---\|)+$/;
5
+ /** A scan-engine row: passed, every severity 0, and a "0 issues" link. */
6
+ const CLEAN_ROW = /^\| :white_check_mark: \| [A-Za-z ]+\| 0 \| 0 \| 0 \| 0 \| \[ 0 issues\]\(https:\/\/app\.snyk\.io\/[^\s)]*\) \|$/;
7
+ const PLUGIN_FOOTER = /^:computer: Catch issues earlier using the plugins for /;
8
+ /**
9
+ * Snyk's PR-check summary when every scan passed with zero issues. Any other header, a row with a
10
+ * non-zero count, or a line outside the table and the IDE-plugin footer keeps it visible.
11
+ */
12
+ const rule = (item) => {
13
+ if (!isBotItem(item, ["snyk-io"], ["pr-comment"]))
14
+ return null;
15
+ const [header, blank, head, separator, ...rest] = item.body.trim().split("\n");
16
+ const framed = `${header}\n${blank}` === `${HEADER}\n`;
17
+ if (!framed || !TABLE_HEAD.test(String(head)) || !SEPARATOR.test(String(separator)))
18
+ return null;
19
+ const rows = rest.filter((line) => line.startsWith("|"));
20
+ const tail = rest.slice(rows.length);
21
+ if (rows.length === 0 || !rows.every((row) => CLEAN_ROW.test(row)))
22
+ return null;
23
+ if (!tail.every((line) => line === "" || PLUGIN_FOOTER.test(line)))
24
+ return null;
25
+ return { autoResolve: true, suppress: true, reason: "Snyk no-issues summary" };
26
+ };
27
+ export default rule;
@@ -0,0 +1,4 @@
1
+ import type { ClassifyRule } from "../types.mts";
2
+ /** Socket's informational dependency overview. Its security checks still report through checks. */
3
+ declare const rule: ClassifyRule;
4
+ export default rule;
@@ -0,0 +1,18 @@
1
+ import { isBotItem } from "./author.mjs";
2
+ /**
3
+ * Socket's dependency-change overview: the whole comment is a score table and a report link.
4
+ * Socket posts findings in a separate alerts comment, so any alert wording in the table keeps it
5
+ * visible. Appended prose also keeps it visible, because the pattern spans the entire body.
6
+ */
7
+ const OVERVIEW = /^\*\*Review the following changes in direct dependencies\.\*\* Learn more about \[Socket for GitHub\]\(https:\/\/socket\.dev[^\s)]*\)\.\n\n<table>[\s\S]*?<\/table>\n\n\[View full report\]\(https:\/\/socket\.dev\/[^\s)]*\)\n\n<!-- overview-comment -->$/;
8
+ const ALERT_WORDING = /alerts?\b|warnings?\b|🚨|⚠|\bblock(?:ed|ing)?\b|malware/i;
9
+ /** Socket's informational dependency overview. Its security checks still report through checks. */
10
+ const rule = (item) => {
11
+ if (!isBotItem(item, ["socket-security"], ["pr-comment"]))
12
+ return null;
13
+ const body = item.body.trim();
14
+ if (!OVERVIEW.test(body) || ALERT_WORDING.test(body))
15
+ return null;
16
+ return { autoResolve: true, suppress: true, reason: "Socket dependency overview" };
17
+ };
18
+ export default rule;
@@ -0,0 +1,7 @@
1
+ import type { ClassifyRule } from "../types.mts";
2
+ /**
3
+ * SonarQube Cloud's PR decoration when the quality gate passed with no new issues and no security
4
+ * hotspots. A failed gate, a non-zero count, or any line outside the fixed layout keeps it visible.
5
+ */
6
+ declare const rule: ClassifyRule;
7
+ export default rule;
@@ -0,0 +1,41 @@
1
+ import { isBotItem } from "./author.mjs";
2
+ const STATIC = "https://sonarsource.github.io/sonarcloud-github-static-resources/v2";
3
+ const esc = (s) => s.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&");
4
+ const HEADER = new RegExp(`^## \\[!\\[Quality Gate Passed\\]\\(${esc(STATIC)}/checks/QualityGateBadge/qg-passed-20px\\.png 'Quality Gate Passed'\\)\\]\\(https://sonarcloud\\.io/[^\\s)]*\\) \\*\\*Quality Gate passed\\*\\*$`);
5
+ /** One metric line with SonarQube's passed (or accepted) icon. */
6
+ const METRIC = new RegExp(`^!\\[\\]\\(${esc(STATIC)}/common/(?:passed|accepted)-16px\\.png ''\\) \\[([^\\]\\n]+)\\]\\(https://sonarcloud\\.io/[^\\s)]*\\)$`);
7
+ const COUNTS = /^(?:0 New issues|\d+ Accepted issues|0 Security Hotspots)$/;
8
+ /** Both counts must be shown as zero; a report missing either is not a known pass. */
9
+ const REQUIRED = ["0 New issues", "0 Security Hotspots"];
10
+ const PERCENT = /^\d+(?:\.\d+)?% (?:Coverage|Duplication) on New Code$/;
11
+ const FOOTER = /^\[See analysis details on SonarQube Cloud\]\(https:\/\/sonarcloud\.io\/[^\s)]*\)$/;
12
+ /**
13
+ * SonarQube Cloud's PR decoration when the quality gate passed with no new issues and no security
14
+ * hotspots. A failed gate, a non-zero count, or any line outside the fixed layout keeps it visible.
15
+ */
16
+ const rule = (item) => {
17
+ if (!isBotItem(item, ["sonarqubecloud"], ["pr-comment"]))
18
+ return null;
19
+ const lines = item.body
20
+ .trim()
21
+ .split("\n")
22
+ .map((line) => line.trimEnd())
23
+ .filter((line) => line !== "" && line !== "<!-- sqra-placement-anchor -->");
24
+ const [header, ...rest] = lines;
25
+ if (!HEADER.test(header ?? "") || !FOOTER.test(rest.pop() ?? ""))
26
+ return null;
27
+ const labels = [];
28
+ const ok = rest.every((line) => {
29
+ if (line === "Issues" || line === "Measures")
30
+ return true;
31
+ const label = METRIC.exec(line)?.[1];
32
+ if (label !== undefined)
33
+ labels.push(label);
34
+ return label !== undefined && (COUNTS.test(label) || PERCENT.test(label));
35
+ });
36
+ const zeroed = REQUIRED.every((label) => labels.includes(label));
37
+ return ok && zeroed
38
+ ? { autoResolve: true, suppress: true, reason: "SonarQube quality gate passed" }
39
+ : null;
40
+ };
41
+ export default rule;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pr-shepherd",
3
- "version": "2.0.0",
3
+ "version": "2.1.0",
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.0.0",
4
+ "version": "2.1.0",
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.0.0",
3
+ "version": "2.1.0",
4
4
  "description": "Autonomous PR CI monitor and review-comment resolver for Codex.",
5
5
  "author": {
6
6
  "name": "Jonathan Ong",
@@ -2,7 +2,7 @@
2
2
  "mcpServers": {
3
3
  "pr-shepherd": {
4
4
  "command": "npx",
5
- "args": ["--yes", "--package", "pr-shepherd@2.0.0", "pr-shepherd-mcp"]
5
+ "args": ["--yes", "--package", "pr-shepherd@2.1.0", "pr-shepherd-mcp"]
6
6
  }
7
7
  }
8
8
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "pr-shepherd": {
3
3
  "command": "npx",
4
- "args": ["--yes", "--package", "pr-shepherd@2.0.0", "pr-shepherd-mcp"]
4
+ "args": ["--yes", "--package", "pr-shepherd@2.1.0", "pr-shepherd-mcp"]
5
5
  }
6
6
  }
@@ -0,0 +1,49 @@
1
+ // Argument helpers for the poll guard: what a command passes to the program it runs,
2
+ // as opposed to where it sends the output.
3
+
4
+ /**
5
+ * The command's arguments without redirections, so `> "pulls-$i.json"` neither
6
+ * names a PR endpoint nor uses a loop variable.
7
+ */
8
+ export function argText(cmd) {
9
+ const kept = [];
10
+ for (let k = 0; k < cmd.words.length; k++) {
11
+ const raw = cmd.words[k].raw;
12
+ if (/^\d*(?:[<>]|>>|&>)$/.test(raw)) k++;
13
+ else if (!/^\d*(?:[<>]|&>)/.test(raw)) kept.push(raw);
14
+ }
15
+ return kept.join(" ");
16
+ }
17
+
18
+ /**
19
+ * Whether the command's arguments use loop variable `name` as the shell expands
20
+ * it. Single-quoted text, such as a jq program's own `$pr`, is not expanded.
21
+ */
22
+ export function usesLoopVar(cmd, name) {
23
+ const text = expandedText(argText(cmd));
24
+ return new RegExp(`\\$(?:${name}\\b|\\{${name}[}:#%/])`).test(text);
25
+ }
26
+
27
+ /** `text` without its single-quoted spans. An apostrophe inside double quotes is literal. */
28
+ function expandedText(text) {
29
+ let out = "";
30
+ let dq = false;
31
+ for (let i = 0; i < text.length; i++) {
32
+ const c = text[i];
33
+ if (c === "\\") {
34
+ out += text.slice(i, i + 2);
35
+ i++;
36
+ } else if (c === "'" && !dq) {
37
+ const end = text.indexOf("'", i + 1);
38
+ i = end === -1 ? text.length : end;
39
+ } else {
40
+ if (c === '"') dq = !dq;
41
+ out += c;
42
+ }
43
+ }
44
+ return out;
45
+ }
46
+
47
+ /** The arguments of a `curl` command without its output file (`-o F`, `-oF`, `-sSo F`, `--output F`). */
48
+ export const curlArgs = (cmd) =>
49
+ argText(cmd).replace(/(?:^|\s)(?:-[a-zA-Z]*o\s*|--output(?:=|\s+))\S+/g, " ");
@@ -1,22 +1,27 @@
1
- // Detects shell commands that poll GitHub PR or CI state on their own instead of
1
+ // Detects shell commands that wait on GitHub PR state on their own instead of
2
2
  // running one `pr-shepherd … --until-terminal`. Host-independent: the Claude Code
3
3
  // and Codex adapters pass the command text and a script reader.
4
+ //
5
+ // Only waits on a pull request are flagged. A workflow run (`gh run …`) may belong
6
+ // to no PR, such as a `workflow_dispatch` run, so a run wait counts only when a PR
7
+ // command (`gh pr …` or `pr-shepherd`) follows it in the same command.
8
+ // Words inside quotes, comments and heredocs are data, not commands. Anything the
9
+ // scanner cannot classify passes: the guard prefers a miss to a false positive.
4
10
 
5
- // A GitHub read: gh's PR and run reads, `gh api`, curl to the API, or Shepherd.
6
- const GITHUB_READ =
7
- /(?<![\w-])gh\s+(?:pr\s+(?:view|checks|status|list)|run\s+(?:view|list)|api)(?=\s)|api\.github\.com|(?<![\w-])pr-shepherd(?![\w-])/;
11
+ import { argText, curlArgs, usesLoopVar } from "./poll-guard-args.mjs";
12
+ import { leadingQuoted, simpleCommands } from "./poll-guard-shell.mjs";
8
13
 
9
- // Shell keywords and commands that repeat or delay. `(?<![\w-])` keeps flags such
10
- // as `--until-terminal` from matching `until`.
11
- const REPEAT = /(?<![\w./-])(?:while|until|sleep)(?=\s)|(?:^|[;&|(]\s*)watch\s/m;
14
+ const PR_SUBCOMMANDS = new Set(["view", "checks", "status", "list"]);
15
+ const PR_API = /pulls|pullRequest/;
16
+ const SHELLS = new Set(["bash", "sh", "zsh"]);
17
+ // A sleep this long right before a single PR read is a wait, not a settle.
18
+ const MIN_WAIT_SECONDS = 60;
12
19
 
13
- // Watchers that block until CI finishes.
14
- const BUILTIN_WATCHER =
15
- /(?<![\w-])gh\s+run\s+watch(?![\w-])|(?<![\w-])gh\s+pr\s+checks\b[^\n;&|]*\s(?:--watch|-w)(?![\w-])/;
16
-
17
- // `bash path`, `sh path`, `zsh path`, or a path ending in `.sh` in command position.
18
- const SCRIPT_RUN =
19
- /(?:^|[;&|(]\s*|\s)(?:bash|sh|zsh)\s+(?:-\w+\s+)*([^\s;&|<>()]+)|(?:^|[;&|(]\s*)((?:[^\s;&|<>()]+\/)?[^\s;&|<>()/]+\.sh)(?=\s|$|[;&|)])/gm;
20
+ const WATCHER =
21
+ "a blocking CI watcher (`gh pr checks --watch`, or `gh run watch` beside a PR command)";
22
+ const LOOP =
23
+ "a polling loop around a PR read (`gh pr`, `gh api` or `curl` on pull requests, `pr-shepherd`, or `gh run` beside a PR command, repeated with `sleep` or `watch`)";
24
+ const WAIT = `a wait of ${MIN_WAIT_SECONDS} seconds or more before a PR read`;
20
25
 
21
26
  export const LEVELS = ["disabled", "advisory", "fail"];
22
27
 
@@ -27,31 +32,134 @@ export const LEVELS = ["disabled", "advisory", "fail"];
27
32
  */
28
33
  export function detectPoller(command, readScript = () => null) {
29
34
  if (typeof command !== "string" || command.length === 0) return null;
30
- const own = detectInText(command);
35
+ const commands = simpleCommands(command);
36
+ const own = detectIn(commands, true);
31
37
  if (own) return own;
32
- for (const path of scriptPaths(command)) {
38
+ for (const path of scriptPaths(commands)) {
33
39
  const text = readScript(path);
34
40
  if (typeof text !== "string") continue;
35
- const found = detectInText(text);
41
+ const found = detectIn(simpleCommands(text), true);
36
42
  if (found) return `the script \`${path}\` contains ${found}`;
37
43
  }
38
44
  return null;
39
45
  }
40
46
 
41
- function detectInText(text) {
42
- if (BUILTIN_WATCHER.test(text))
43
- return "a blocking CI watcher (`gh run watch` or `gh pr checks --watch`)";
44
- if (GITHUB_READ.test(text) && REPEAT.test(text)) {
45
- return "a polling loop around a GitHub read (`gh pr`/`gh run`/`gh api`/`curl` or `pr-shepherd` with `while`, `until`, `sleep`, or `watch`)";
47
+ function detectIn(commands, nested) {
48
+ const sleeps = [];
49
+ const reads = [];
50
+ const runReads = [];
51
+ let lastPr = -1;
52
+ for (const [index, cmd] of commands.entries()) {
53
+ const words = cmd.words.map((w) => w.word);
54
+ const inner = nested ? quotedCommand(cmd, words) : null;
55
+ if (inner !== null) {
56
+ const innerCommands = simpleCommands(inner);
57
+ const found = detectIn(innerCommands, false);
58
+ if (found) return found;
59
+ // The shell's own loop or `watch` repeats the inner read.
60
+ if (innerCommands.some((c) => isPrRead(c))) {
61
+ if (cmd.watched) return LOOP;
62
+ reads.push({ index, cmd });
63
+ }
64
+ }
65
+ if (words[0] === "sleep") sleeps.push({ index, cmd, seconds: seconds(words.slice(1)) });
66
+ else if (isWatcher(words)) return WATCHER;
67
+ else if (isPrRead(cmd)) {
68
+ if (cmd.watched) return LOOP;
69
+ reads.push({ index, cmd });
70
+ } else if (isRunRead(words)) runReads.push({ index, cmd });
71
+ if (words[0] === "pr-shepherd" || (words[0] === "gh" && words[1] === "pr")) lastPr = index;
72
+ }
73
+ // A workflow run may belong to no PR. A wait on a run followed by Shepherd or a
74
+ // `gh pr` command is a wait on that PR's CI; one after a merge (a publish run) is not.
75
+ const prRuns = runReads.filter((r) => r.index < lastPr);
76
+ if (prRuns.some((r) => r.cmd.words[2].word === "watch")) return WATCHER;
77
+ reads.push(...prRuns);
78
+ for (const read of reads) {
79
+ // A loop polls when it sleeps and re-reads a state that does not depend on its variable.
80
+ const loops = new Set(
81
+ read.cmd.loops.filter((l) => !l.vars.some((v) => usesLoopVar(read.cmd, v))).map((l) => l.id),
82
+ );
83
+ if (sleeps.some((s) => s.cmd.loops.some((l) => loops.has(l.id)))) return LOOP;
84
+ // A long sleep whose very next command is the PR read, outside any loop.
85
+ const waited = sleeps.some(
86
+ (s) =>
87
+ s.index === read.index - 1 && s.cmd.loops.length === 0 && s.seconds >= MIN_WAIT_SECONDS,
88
+ );
89
+ if (waited) return WAIT;
46
90
  }
47
91
  return null;
48
92
  }
49
93
 
50
- function scriptPaths(command) {
94
+ /** `-c`, or combined shell options that include it, such as `-lc` or `-ec`. */
95
+ const isCommandFlag = (word) => /^-[a-z]*c[a-z]*$/i.test(word);
96
+
97
+ const isRunRead = (words) =>
98
+ words[0] === "gh" && words[1] === "run" && ["view", "list", "watch"].includes(words[2]);
99
+
100
+ const isWatcher = (words) =>
101
+ words[0] === "gh" &&
102
+ words[1] === "pr" &&
103
+ words[2] === "checks" &&
104
+ words.some((w) => w === "--watch" || w === "-w");
105
+
106
+ /** The command string run by `bash -c '…'` (or `sh`, `zsh`) or `watch '…'`, or null. */
107
+ function quotedCommand(cmd, words) {
108
+ let at = -1;
109
+ if (cmd.watched) at = cmd.words[0].at;
110
+ else if (SHELLS.has(words[0]) && words.some(isCommandFlag)) {
111
+ at = cmd.words[words.findIndex(isCommandFlag) + 1]?.at ?? -1;
112
+ }
113
+ return at === -1 ? null : leadingQuoted(cmd.text.slice(at - cmd.words[0].at));
114
+ }
115
+
116
+ function isPrRead(cmd) {
117
+ const [first, second, third] = cmd.words.map((w) => w.word);
118
+ if (first === "gh" && second === "pr") return PR_SUBCOMMANDS.has(third);
119
+ if (first === "gh" && second === "api") return PR_API.test(argText(cmd));
120
+ // Quoting does not change an argument's value: `pr-shepherd "42"` is `pr-shepherd 42`.
121
+ if (first === "pr-shepherd") {
122
+ return isShepherdTick(cmd.words.map((w) => w.raw.replace(/^(["'])(.*)\1$/, "$2")));
123
+ }
124
+ const args = curlArgs(cmd);
125
+ return first === "curl" && /api\.github\.com/.test(args) && PR_API.test(args);
126
+ }
127
+
128
+ /**
129
+ * One Shepherd status tick: the default poll, `iterate`, or `stack`, without
130
+ * `--until-terminal`. `apply`, `suggest`, `admin` and other subcommands write or
131
+ * print help, so they are not reads.
132
+ */
133
+ function isShepherdTick(words) {
134
+ if (words.includes("--until-terminal")) return false;
135
+ const target = words[1];
136
+ return (
137
+ target === undefined ||
138
+ target === "iterate" ||
139
+ target === "stack" ||
140
+ /^(?:-|\d|https?:|\$)|[#/]/.test(target)
141
+ );
142
+ }
143
+
144
+ /** Total seconds of `sleep` arguments such as `90`, `2m` or `1h`; NaN unless literal. */
145
+ function seconds(args) {
146
+ const unit = { s: 1, m: 60, h: 3600, d: 86400 };
147
+ return args.reduce((sum, arg) => {
148
+ const m = /^(\d+(?:\.\d+)?)([smhd]?)$/.exec(arg);
149
+ return m ? sum + Number(m[1]) * unit[m[2] || "s"] : Number.NaN;
150
+ }, 0);
151
+ }
152
+
153
+ /** Scripts a command runs: `bash path`, `sh -e path`, or a `.sh` path in command position. */
154
+ function scriptPaths(commands) {
51
155
  const paths = [];
52
- for (const m of command.matchAll(SCRIPT_RUN)) {
53
- const path = m[1] ?? m[2];
54
- if (path && !path.startsWith("-")) paths.push(path);
156
+ for (const { words } of commands) {
157
+ const [first, ...rest] = words;
158
+ if (SHELLS.has(first.word)) {
159
+ if (rest.some((w) => isCommandFlag(w.word))) continue;
160
+ const path = rest.find((w) => !w.word.startsWith("-"));
161
+ if (path) paths.push(path.raw);
162
+ } else if (first.raw.endsWith(".sh")) paths.push(first.raw);
55
163
  }
56
164
  return paths;
57
165
  }
@@ -0,0 +1,192 @@
1
+ // A small, deliberately incomplete shell scanner for the poll guard. It finds the
2
+ // simple commands a shell would run and the loops they run in. Text a command only
3
+ // passes around (quoted strings, comments, heredoc bodies) is masked, so a word in
4
+ // it is never mistaken for a command. Command substitutions inside double quotes
5
+ // stay visible, because the shell runs them.
6
+
7
+ const HIDDEN = "\0";
8
+ const SEPARATORS = /[;&|\n(){}`]/;
9
+ const WRAPPERS = new Set([
10
+ "!",
11
+ "time",
12
+ "nohup",
13
+ "exec",
14
+ "sudo",
15
+ "command",
16
+ "builtin",
17
+ "env",
18
+ "npx",
19
+ ]);
20
+ const KEYWORDS = new Set(["do", "then", "else", "elif", "if"]);
21
+
22
+ /**
23
+ * Masks quoted text with NUL and comments and heredoc bodies with spaces, preserving
24
+ * UTF-16 length. Quoted text stays one argument; comments and heredocs disappear.
25
+ */
26
+ export function maskShell(text) {
27
+ const out = text.split("");
28
+ const stack = [{ mode: "code", depth: 0 }];
29
+ let heredocs = [];
30
+ const hide = (from, to, fill = HIDDEN) => {
31
+ for (let k = from; k < to && k < out.length; k++) if (out[k] !== "\n") out[k] = fill;
32
+ };
33
+ for (let i = 0; i < text.length; i++) {
34
+ const top = stack.at(-1);
35
+ const c = text[i];
36
+ if (top.mode === "dq") {
37
+ if (c === "\\") {
38
+ hide(i, i + 2);
39
+ i++;
40
+ } else if (c === '"') {
41
+ hide(i, i + 1);
42
+ stack.pop();
43
+ } else if (c === "$" && text[i + 1] === "(") {
44
+ stack.push({ mode: "code", depth: 1 });
45
+ i++;
46
+ } else if (c === "`") stack.push({ mode: "bq", depth: 0 });
47
+ else hide(i, i + 1);
48
+ continue;
49
+ }
50
+ if (c === "`" && top.mode === "bq") {
51
+ stack.pop();
52
+ continue;
53
+ }
54
+ if (c === "\\") {
55
+ hide(i, i + 2);
56
+ i++;
57
+ } else if (c === "$" && text[i + 1] === "'") {
58
+ // ANSI-C `$'…'`: a backslash escapes the next character, including a quote.
59
+ let j = i + 2;
60
+ while (j < text.length && text[j] !== "'") j += text[j] === "\\" ? 2 : 1;
61
+ hide(i, j + 1);
62
+ i = j;
63
+ } else if (c === "'") {
64
+ const end = text.indexOf("'", i + 1);
65
+ const stop = end === -1 ? text.length : end + 1;
66
+ hide(i, stop);
67
+ i = stop - 1;
68
+ } else if (c === '"') {
69
+ hide(i, i + 1);
70
+ stack.push({ mode: "dq", depth: 0 });
71
+ } else if (c === "#" && (i === 0 || /[\s;&|(]/.test(text[i - 1]))) {
72
+ const end = text.indexOf("\n", i);
73
+ hide(i, end === -1 ? text.length : end, " ");
74
+ i = (end === -1 ? text.length : end) - 1;
75
+ } else if (c === "$" && text[i + 1] === "{") {
76
+ // `${VAR}` stays inside its word; its braces are not a command group.
77
+ const end = text.indexOf("}", i);
78
+ const stop = end === -1 ? text.length : end + 1;
79
+ hide(i, stop);
80
+ i = stop - 1;
81
+ } else if (c === "(" && top.depth > 0) top.depth++;
82
+ else if (c === ")" && top.depth > 0 && --top.depth === 0) stack.pop();
83
+ else if (c === "<" && text[i + 1] === "<" && text[i + 2] !== "<") {
84
+ const m = /^<<(-?)\s*(['"]?)([\w.-]+)\2/.exec(text.slice(i));
85
+ if (m) heredocs.push({ strip: m[1] === "-", tag: m[3] });
86
+ } else if (c === "\n" && heredocs.length > 0) {
87
+ i = skipHeredocs(text, i + 1, heredocs, hide) - 1;
88
+ heredocs = [];
89
+ }
90
+ }
91
+ return out.join("");
92
+ }
93
+
94
+ /** Hides each pending heredoc body after a newline; returns the index after the last one. */
95
+ function skipHeredocs(text, start, heredocs, hide) {
96
+ let at = start;
97
+ for (const { strip, tag } of heredocs) {
98
+ const lines = /[^\n]*(?:\n|$)/gy;
99
+ lines.lastIndex = at;
100
+ let end = text.length;
101
+ for (let m = lines.exec(text); m && m[0] !== ""; m = lines.exec(text)) {
102
+ const line = m[0].replace(/\n$/, "");
103
+ if ((strip ? line.replace(/^\t+/, "") : line) === tag) {
104
+ end = m.index + m[0].length;
105
+ break;
106
+ }
107
+ }
108
+ hide(at, end, " ");
109
+ at = end;
110
+ }
111
+ return at;
112
+ }
113
+
114
+ /**
115
+ * Variables a loop steps through: `for VAR in …` or `while read [-r] VAR…`. A
116
+ * command that uses one iterates over a list instead of re-reading one state.
117
+ */
118
+ function loopVars(keyword, words) {
119
+ if (keyword === "for") return words[0] ? [words[0].word] : [];
120
+ if (words[0]?.word !== "read") return [];
121
+ return words.slice(1).flatMap((w) => (/^\w+$/.test(w.word) ? [w.word] : []));
122
+ }
123
+
124
+ /**
125
+ * The simple commands in `text`, in order. Each has its `words` (masked, with
126
+ * offsets into `text`), the raw `text` of the command, the loops it runs in
127
+ * (`{ id, vars }`), and whether a `watch` wrapper repeats it.
128
+ */
129
+ export function simpleCommands(text) {
130
+ const masked = maskShell(text);
131
+ const commands = [];
132
+ const open = [];
133
+ let nextLoop = 0;
134
+ let start = 0;
135
+ for (let i = 0; i <= masked.length; i++) {
136
+ if (i < masked.length && !SEPARATORS.test(masked[i])) continue;
137
+ const words = [...masked.slice(start, i).matchAll(/\S+/g)].map((m) => ({
138
+ word: m[0],
139
+ raw: text.slice(start + m.index, start + m.index + m[0].length),
140
+ at: start + m.index,
141
+ }));
142
+ start = i + 1;
143
+ let watched = false;
144
+ let wrapped = false;
145
+ while (words.length > 0) {
146
+ const w = words[0].word;
147
+ if (w === "command" && /^-[vV]$/.test(words[1]?.word)) {
148
+ words.length = 0;
149
+ } else if (KEYWORDS.has(w) || /^\w+=/.test(w) || (w.startsWith("-") && wrapped)) {
150
+ words.shift();
151
+ } else if (WRAPPERS.has(w)) {
152
+ wrapped = true;
153
+ words.shift();
154
+ } else if (w === "timeout") {
155
+ // `timeout [-s SIG] [-k D] DURATION cmd…`
156
+ words.shift();
157
+ while (words[0]?.word.startsWith("-")) {
158
+ if (/^-[sk]$/.test(words.shift().word)) words.shift();
159
+ }
160
+ words.shift();
161
+ wrapped = true;
162
+ } else if (w === "watch") {
163
+ watched = wrapped = true;
164
+ words.shift();
165
+ while (words[0]?.word.startsWith("-")) {
166
+ const flag = words.shift().word;
167
+ if (/^(?:-n|--interval)$/.test(flag)) words.shift();
168
+ }
169
+ } else if (w === "while" || w === "until" || w === "for") {
170
+ words.shift();
171
+ open.push({ id: nextLoop++, vars: loopVars(w, words) });
172
+ if (w === "for") words.length = 0;
173
+ } else if (w === "done") {
174
+ open.pop();
175
+ words.length = 0;
176
+ } else break;
177
+ }
178
+ if (words.length === 0) continue;
179
+ const end = i;
180
+ commands.push({ words, text: text.slice(words[0].at, end), loops: [...open], watched });
181
+ }
182
+ return commands;
183
+ }
184
+
185
+ /** The text of the quoted argument that starts `rest`, or null. */
186
+ export function leadingQuoted(rest) {
187
+ const quote = rest.trimStart()[0];
188
+ if (quote !== "'" && quote !== '"') return null;
189
+ const body = rest.trimStart().slice(1);
190
+ const end = quote === "'" ? body.indexOf("'") : body.search(/(?<!\\)"/);
191
+ return end === -1 ? null : body.slice(0, end);
192
+ }
@@ -7,7 +7,7 @@
7
7
  "name": "pr-shepherd-plugin",
8
8
  "license": "MIT",
9
9
  "dependencies": {
10
- "pr-shepherd": "1.6.1"
10
+ "pr-shepherd": "2.0.0"
11
11
  }
12
12
  },
13
13
  "node_modules/@hono/node-server": {
@@ -598,9 +598,9 @@
598
598
  }
599
599
  },
600
600
  "node_modules/hono": {
601
- "version": "4.13.14",
602
- "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.14.tgz",
603
- "integrity": "sha512-yhRLQ21U6qa9Hsu2N7Qcbh8tE+WKEcoErjIo56LeSGiGXGp9sA7UpE86Ui9uexb61KakiGwuHMn2QdV7w6i6kQ==",
601
+ "version": "4.13.18",
602
+ "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.18.tgz",
603
+ "integrity": "sha512-H9q/E1XizaWstJxUW881dmLxEj+t/TrGGnyxINkm4+sK0qUwsMtFdo2BWI9Vs3cIS19MU6b6iCijoUoEf4f3DA==",
604
604
  "license": "MIT",
605
605
  "engines": {
606
606
  "node": ">=16.9.0"
@@ -889,9 +889,9 @@
889
889
  }
890
890
  },
891
891
  "node_modules/pr-shepherd": {
892
- "version": "1.6.1",
893
- "resolved": "https://registry.npmjs.org/pr-shepherd/-/pr-shepherd-1.6.1.tgz",
894
- "integrity": "sha512-6GF2ES5bV30qNQBIbWWHTy7xB+dYBok0s/0S30sL3FRPEC8g5N7MzImba08HWQO9K84j60/CqvCKHu77mJccZw==",
892
+ "version": "2.0.0",
893
+ "resolved": "https://registry.npmjs.org/pr-shepherd/-/pr-shepherd-2.0.0.tgz",
894
+ "integrity": "sha512-MkfQ2SqXVJeS2vgE0CwCLrVm5UsjPVUJ/VLBh4uwnh1o2z7pNJd3nBV54qght1aIdCw+gqT8RTFrH3WqDnCr+w==",
895
895
  "license": "MIT",
896
896
  "dependencies": {
897
897
  "@modelcontextprotocol/sdk": "^1.30.0",
@@ -4,6 +4,6 @@
4
4
  "description": "Pins the pr-shepherd package that .mcp.json launches",
5
5
  "license": "MIT",
6
6
  "dependencies": {
7
- "pr-shepherd": "1.6.1"
7
+ "pr-shepherd": "2.0.0"
8
8
  }
9
9
  }
@@ -2,7 +2,7 @@
2
2
 
3
3
  Use a classification rule when the unwanted item has a recognizable author and message pattern. Inspect a representative item first so the rule does not hide other feedback from the same bot. Prefer an existing settings control for polling- or output-wide behavior.
4
4
 
5
- Check the bundled rules first. Under `classify.standard` in the active config file, `all: true` enables every rule, and a named boolean such as `codecov-report: false` overrides `all`. They cover vendor bot notices on conversation comments only: `coderabbit-notices`, `codecov-report`, `codex-notices`, `dependabot-notices`, `gemini-notices`, `kilo-no-issues`, and `sourcery-notices`. They do not match review summaries or inline review comments. Write a custom rule only when no bundled rule fits.
5
+ Check the bundled rules first. Under `classify.standard` in the active config file, `all: true` enables every rule, and a named boolean such as `codecov-report: false` overrides `all`. They cover vendor bot notices on conversation comments only: `coderabbit-notices`, `codecov-report`, `codex-notices`, `dependabot-notices`, `dependency-review-no-issues`, `gemini-notices`, `kilo-no-issues`, `snyk-no-issues`, `socket-reports`, `sonarqube-gate-passed`, and `sourcery-notices`. They do not match review summaries or inline review comments. Write a custom rule only when no bundled rule fits.
6
6
 
7
7
  Place an `.mts` file in `.pr-shepherd/classification/` in the project. Shepherd uses the first classification directory on the working directory's ancestor chain; it stops at the home directory if reached, otherwise at the filesystem root. A home-level rule directory is not discovered when the project is outside the home tree. Rule directories do not merge. Files ending in `.ts`, `.mts`, `.mjs`, or `.js` load, except names beginning with `_` or `.`. An `.mts` rule can use erasable TypeScript syntax and `import type`, without transpilation-only features such as enums.
8
8
 
@@ -354,8 +354,12 @@
354
354
  "codecov-report",
355
355
  "codex-notices",
356
356
  "dependabot-notices",
357
+ "dependency-review-no-issues",
357
358
  "gemini-notices",
358
359
  "kilo-no-issues",
360
+ "snyk-no-issues",
361
+ "socket-reports",
362
+ "sonarqube-gate-passed",
359
363
  "sourcery-notices"
360
364
  ]
361
365
  },