pr-shepherd 1.6.1 → 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.
Files changed (46) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +52 -54
  3. package/bin/classify/standard/dependency-review-no-issues.d.mts +4 -0
  4. package/bin/classify/standard/dependency-review-no-issues.mjs +16 -0
  5. package/bin/classify/standard/index.mjs +8 -0
  6. package/bin/classify/standard/snyk-no-issues.d.mts +7 -0
  7. package/bin/classify/standard/snyk-no-issues.mjs +27 -0
  8. package/bin/classify/standard/socket-reports.d.mts +4 -0
  9. package/bin/classify/standard/socket-reports.mjs +18 -0
  10. package/bin/classify/standard/sonarqube-gate-passed.d.mts +7 -0
  11. package/bin/classify/standard/sonarqube-gate-passed.mjs +41 -0
  12. package/bin/cli/iterate-instructions.mjs +1 -1
  13. package/bin/cli/iterate-lean.mjs +1 -0
  14. package/bin/cli/list-formatters.d.mts +7 -0
  15. package/bin/cli/list-formatters.mjs +7 -1
  16. package/bin/cli/triage-formatter.mjs +8 -2
  17. package/bin/commands/check.mjs +2 -1
  18. package/bin/commands/iterate/check-instructions.d.mts +1 -1
  19. package/bin/commands/iterate/check-instructions.mjs +2 -2
  20. package/bin/commands/iterate/classify.mjs +3 -3
  21. package/bin/commands/iterate/conflict-candidate-files.d.mts +9 -0
  22. package/bin/commands/iterate/conflict-candidate-files.mjs +19 -0
  23. package/bin/commands/iterate/escalate.mjs +2 -1
  24. package/bin/commands/iterate/native-stack-rebase.mjs +6 -1
  25. package/bin/commands/iterate/triage.mjs +16 -0
  26. package/bin/commands/review-commit.d.mts +7 -0
  27. package/bin/commands/review-commit.mjs +11 -0
  28. package/bin/github/rest-conflict-files-read.d.mts +7 -0
  29. package/bin/github/rest-conflict-files-read.mjs +33 -0
  30. package/bin/types/github.d.mts +8 -0
  31. package/bin/types/iterate.d.mts +5 -3
  32. package/package.json +1 -1
  33. package/plugins/pr-shepherd/.claude-plugin/plugin.json +1 -1
  34. package/plugins/pr-shepherd/.codex-plugin/plugin.json +1 -1
  35. package/plugins/pr-shepherd/.codex.mcp.json +1 -1
  36. package/plugins/pr-shepherd/.mcp.json +1 -1
  37. package/plugins/pr-shepherd/hooks/poll-guard-args.mjs +49 -0
  38. package/plugins/pr-shepherd/hooks/poll-guard-detect.mjs +134 -26
  39. package/plugins/pr-shepherd/hooks/poll-guard-shell.mjs +192 -0
  40. package/plugins/pr-shepherd/package-lock.json +10 -10
  41. package/plugins/pr-shepherd/package.json +1 -1
  42. package/plugins/pr-shepherd/skills/pr-shepherd/SKILL.md +9 -17
  43. package/plugins/pr-shepherd/skills/pr-shepherd/references/triage-loop.md +1 -1
  44. package/plugins/pr-shepherd/skills/reduce-pr-noise/references/classifiers.md +1 -1
  45. package/pr-shepherd.schema.json +4 -0
  46. /package/plugins/pr-shepherd/skills/pr-shepherd/references/{create-pr.md → create-a-pr.md} +0 -0
@@ -54,6 +54,11 @@ export function buildNativeStackLayerRebase(repo, pr, stack, trunkConflict, stac
54
54
  : { parentBranch: pr.baseBranch };
55
55
  return buildNativeStackRebaseInstruction(repo, stack.number, start);
56
56
  }
57
+ /**
58
+ * The branch-update route for a conflicting PR that is not a native stack layer. Rebase versus
59
+ * merge is the repository's convention, so the step points at it instead of choosing.
60
+ */
61
+ const RESOLVE_CONFLICTS = "Check the base branch's instructions (such as `AGENTS.md`) only for whether to rebase or merge, update the branch from its base that way, and resolve each conflict keeping both sides' changes unless they contradict.";
57
62
  /**
58
63
  * Point at the conflicts, and at the stack rebase when the PR is a native stack layer. A queued
59
64
  * conflicting entry cannot form a merge group, so GitHub removes it once the queue reaches it.
@@ -63,7 +68,7 @@ export function buildNativeStackLayerRebase(repo, pr, stack, trunkConflict, stac
63
68
  */
64
69
  export function buildConflictInstruction(stackRebase, dequeueCommand) {
65
70
  const pointer = "The branch has merge conflicts (see `**branch**` above).";
66
- const resolve = stackRebase ?? "Resolve them before committing.";
71
+ const resolve = stackRebase ?? RESOLVE_CONFLICTS;
67
72
  if (!dequeueCommand)
68
73
  return `${pointer} ${resolve}`;
69
74
  return `${pointer} ${buildQueuedConflictChoice(dequeueCommand, resolve, stackRebase !== undefined)}`;
@@ -14,6 +14,7 @@ import { buildNativeStackLayerRebase } from "./native-stack-rebase.mjs";
14
14
  import { buildDequeueCommand } from "./merge-plan.mjs";
15
15
  import { renderShellCommand } from "../../cli/runner.mjs";
16
16
  import { lookupUpperLayerTrunkConflict } from "./stack-trunk-conflict.mjs";
17
+ import { lookupConflictCandidateFiles } from "./conflict-candidate-files.mjs";
17
18
  import { lookupMergedBasePullRequests } from "./merged-base-pull-requests.mjs";
18
19
  import { conflictingHeadCiNote, countReportedChecks, insertConflictingHeadCiNote, } from "./conflicting-head-ci.mjs";
19
20
  import { conflictingHeadFirstSeenUnix } from "../../state/conflicting-head-seen.mjs";
@@ -313,6 +314,15 @@ async function handleTriageTick(ctx) {
313
314
  baseRefOid: report.baseRefOid,
314
315
  })
315
316
  : [];
317
+ // Native stack layers update from trunk or a parent, so a base comparison names no useful files.
318
+ const conflictCandidateFiles = hasConflicts && !stack && headRef
319
+ ? await lookupConflictCandidateFiles({
320
+ owner: repoOwner,
321
+ repo: repoName,
322
+ baseRefName: baseLookup.branch,
323
+ headRefOid: headRef,
324
+ })
325
+ : undefined;
316
326
  // A bottom open layer can still retain its merged parent's PR base. Its update starts
317
327
  // at trunk regardless of that base comparison; true upper layers first check the parent.
318
328
  const trunkConflict = hasConflicts && stack && report.stackBottomPr === prNumber
@@ -385,6 +395,11 @@ async function handleTriageTick(ctx) {
385
395
  `Inspect every PR under \`## Merged PRs matching the current base\`. If this PR is the remaining layer intended for a merged parent's base branch, run \`${retarget}\` after replacing \`<verified-parent-base>\` with that parent's shell-quoted base branch, then rerun Shepherd immediately and follow its fresh instructions instead of the remaining steps here. Otherwise keep the current base and follow the remaining conflict-resolution steps.`,
386
396
  ]);
387
397
  }
398
+ if (conflictCandidateFiles) {
399
+ // Follows the conflict step; without one (index -1) it leads the list.
400
+ const conflictAt = instructions.findIndex((step) => step.includes("merge conflicts"));
401
+ instructions.splice(conflictAt + 1, 0, pathA("Start with the files under `## Files changed on both sides since the merge base`: the PR and its base both changed them, so they are the likeliest conflicts, but GitHub does not list conflicting files and the list may be incomplete. Resolve the conflicts yourself rather than handing them to the user."));
402
+ }
388
403
  const checkRunCount = countReportedChecks(report.checks);
389
404
  const suitesEmpty = report.headCheckSuitesEmpty === true;
390
405
  const nowMs = Date.now();
@@ -402,6 +417,7 @@ async function handleTriageTick(ctx) {
402
417
  ...base,
403
418
  baseBranch: baseLookup.branch,
404
419
  ...(mergedBasePullRequests.length > 0 && { mergedBasePullRequests }),
420
+ ...(conflictCandidateFiles && { conflictCandidateFiles }),
405
421
  ...(trunkConflict && { stackTrunkConflict: trunkConflict.trunk }),
406
422
  action: "triage",
407
423
  triage: {
@@ -0,0 +1,7 @@
1
+ import type { Review } from "../types/github.mts";
2
+ /**
3
+ * Surface where each changes-requested review was submitted relative to the PR head.
4
+ * `commitOid` stays only when it differs from the head, and then `headOid` carries the head;
5
+ * a review on the head carries neither (lean output). Raw data only — no staleness verdict.
6
+ */
7
+ export declare function withHeadOid(reviews: Review[], headOid: string): Review[];
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Surface where each changes-requested review was submitted relative to the PR head.
3
+ * `commitOid` stays only when it differs from the head, and then `headOid` carries the head;
4
+ * a review on the head carries neither (lean output). Raw data only — no staleness verdict.
5
+ */
6
+ export function withHeadOid(reviews, headOid) {
7
+ return reviews.map((review) => {
8
+ const { commitOid, ...rest } = review;
9
+ return commitOid && commitOid !== headOid ? { ...rest, commitOid, headOid } : rest;
10
+ });
11
+ }
@@ -0,0 +1,7 @@
1
+ import type { RepoInfo } from "./client.mts";
2
+ /**
3
+ * Files changed by the PR head and by the base branch since their merge base. GitHub exposes
4
+ * no list of conflicting files, so this intersection is raw evidence of where a conflict can be.
5
+ * Read through REST on both transports: GraphQL has no per-file compare.
6
+ */
7
+ export declare function readRestFilesChangedOnBothSides(repo: RepoInfo, baseRef: string, headRef: string): Promise<string[]>;
@@ -0,0 +1,33 @@
1
+ import { readRest, restArray, restObject, restRepoPath, restString } from "./rest-reader-core.mjs";
2
+ function compareFiles(files) {
3
+ return files.map((value) => {
4
+ const file = restObject(value, "compare file");
5
+ const filename = restString(file.filename, "compare file name");
6
+ return typeof file.previous_filename === "string"
7
+ ? { filename, previous: file.previous_filename }
8
+ : { filename };
9
+ });
10
+ }
11
+ /**
12
+ * Compare lists `files` on its first page only (later pages carry commits), and at most 300 of
13
+ * them, so a very large change can yield an incomplete list. One commit per page keeps it small.
14
+ */
15
+ async function readSide(repo, basehead) {
16
+ const body = restObject(await readRest("GET", `${restRepoPath(repo)}/compare/${basehead}?per_page=1`), "compare");
17
+ return { files: compareFiles(restArray(body.files, "compare files")), body };
18
+ }
19
+ /**
20
+ * Files changed by the PR head and by the base branch since their merge base. GitHub exposes
21
+ * no list of conflicting files, so this intersection is raw evidence of where a conflict can be.
22
+ * Read through REST on both transports: GraphQL has no per-file compare.
23
+ */
24
+ export async function readRestFilesChangedOnBothSides(repo, baseRef, headRef) {
25
+ const { files: head, body } = await readSide(repo, `${encodeURIComponent(baseRef)}...${encodeURIComponent(headRef)}`);
26
+ const mergeBase = restString(restObject(body.merge_base_commit, "compare merge base").sha, "compare merge base SHA");
27
+ const { files: base } = await readSide(repo, `${mergeBase}...${encodeURIComponent(baseRef)}`);
28
+ // A rename on either side still matches through the name the other side changed.
29
+ const baseNames = new Set(base.flatMap((file) => [file.filename, file.previous ?? file.filename]));
30
+ return head
31
+ .filter((file) => baseNames.has(file.filename) || baseNames.has(file.previous ?? file.filename))
32
+ .map((file) => file.filename);
33
+ }
@@ -19,6 +19,12 @@ export interface MergedBasePullRequest {
19
19
  nameWithOwner: string;
20
20
  };
21
21
  }
22
+ /** Files changed on both the PR head and its base since their merge base; not a conflict list. */
23
+ export interface ConflictCandidateFiles {
24
+ /** Paths, capped. `total` counts every shared file. */
25
+ files: string[];
26
+ total: number;
27
+ }
22
28
  export type AuthorType = "User" | "Bot" | "Unknown";
23
29
  type RepositoryPermission = "NONE" | "READ" | "TRIAGE" | "WRITE" | "MAINTAIN" | "ADMIN";
24
30
  /** Raw GitHub viewer fields used to gate remote actions. */
@@ -134,6 +140,8 @@ export interface Review {
134
140
  staleBotCr?: boolean;
135
141
  /** Commit OID the review was made against, when available from GraphQL. */
136
142
  commitOid?: string;
143
+ /** PR head OID, set on changes-requested reviews only when `commitOid` differs from it. Raw data, not a staleness verdict. */
144
+ headOid?: string;
137
145
  /** Review HTML URL, when the batch query selected it. */
138
146
  url?: string;
139
147
  /** True when commitOid !== headRefOid AND all associated threads are resolved/outdated. Distinct from `staleBotCr` (time-based). Reviews with no threads are not marked stale. */
@@ -1,6 +1,6 @@
1
1
  import type { AgentThread, AgentComment, AgentCheck, GlobalOptions, RelevantCheck, ShepherdStatus, FirstLookThread, FirstLookComment, EditedComment, RuleAutoResolveReport } from "./report.mts";
2
2
  import type { ActiveCheck, PrActivitySummary } from "./activity.mts";
3
- import type { BranchProtection, MergeStateStatus, MergedBasePullRequest, Review, ReviewDecision, ReviewThread, ShepherdMergeStatus } from "./github.mts";
3
+ import type { BranchProtection, MergeStateStatus, MergedBasePullRequest, ConflictCandidateFiles, Review, ReviewDecision, ReviewThread, ShepherdMergeStatus } from "./github.mts";
4
4
  import type { MergeRequirements } from "./merge-requirements.mts";
5
5
  import type { EscalateDetails } from "./escalate.mts";
6
6
  import type { MergeCommandPlan } from "./merge-action.mts";
@@ -44,6 +44,8 @@ export interface IterateResultBase {
44
44
  stackTrunkConflict?: string;
45
45
  /** Merged PRs whose exact head commit and repository match this conflicting PR's base. */
46
46
  mergedBasePullRequests?: MergedBasePullRequest[];
47
+ /** Conflicting non-stack PR: files changed on both sides since the merge base. */
48
+ conflictCandidateFiles?: ConflictCandidateFiles;
47
49
  /** Null when no classic protection rule exists or the base ref is unavailable. */
48
50
  branchProtection: BranchProtection | null;
49
51
  mergeRequirements?: MergeRequirements;
@@ -93,11 +95,11 @@ interface IterateResultCancel extends IterateResultBase {
93
95
  log: string;
94
96
  }
95
97
  export interface ResolveCommand {
96
- /** Argv for spawn-style execution. May contain a `$DISMISS_MESSAGE` placeholder. `--require-sha` is never in `argv` — `renderResolveCommand` (from `commands/iterate/render.mts`) appends `--require-sha HEAD` when rendering if `requiresHeadSha` is true. Use `renderResolveCommand` to render as a command string; don't naive-join. */
98
+ /** Argv for spawn-style execution. May contain a `$CHANGE_MESSAGE` placeholder. `--require-sha` is never in `argv` — `renderResolveCommand` (from `commands/iterate/render.mts`) appends `--require-sha HEAD` when rendering if `requiresHeadSha` is true. Use `renderResolveCommand` to render as a command string; don't naive-join. */
97
99
  argv: string[];
98
100
  /** When true, `renderResolveCommand` appends `--require-sha HEAD` to the rendered command. */
99
101
  requiresHeadSha: boolean;
100
- /** Whether the model must substitute $DISMISS_MESSAGE with a specific description of the fix. */
102
+ /** Whether the model must substitute $CHANGE_MESSAGE with a specific description of the fix. */
101
103
  requiresDismissMessage: boolean;
102
104
  /** Thread IDs that should receive a reply. Viewer-authored human IDs may also appear in resolveThreadIds. */
103
105
  replyThreadIds?: string[];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pr-shepherd",
3
- "version": "1.6.1",
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": "1.6.1",
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": "1.6.1",
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@1.6.1", "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@1.6.1", "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
  }