pr-shepherd 0.10.3 → 0.12.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 (37) hide show
  1. package/.claude-plugin/plugin.json +2 -2
  2. package/README.md +51 -9
  3. package/bin/agent-runtime.mjs +7 -0
  4. package/bin/checks/triage.mjs +5 -46
  5. package/bin/cli/args.mjs +10 -2
  6. package/bin/cli/default-iterate.mjs +54 -0
  7. package/bin/cli/duration-flag.mjs +22 -0
  8. package/bin/cli/fix-formatter.mjs +25 -15
  9. package/bin/cli/formatters.mjs +26 -38
  10. package/bin/cli/handlers.mjs +26 -24
  11. package/bin/cli/iterate-formatter.mjs +14 -10
  12. package/bin/cli/iterate-instructions.mjs +75 -0
  13. package/bin/cli/iterate-lean.mjs +59 -6
  14. package/bin/cli/list-formatters.mjs +11 -0
  15. package/bin/cli-parser.iterate-fixtures.mjs +2 -0
  16. package/bin/cli-parser.mjs +15 -1
  17. package/bin/commands/check.mjs +6 -6
  18. package/bin/commands/commit-suggestion.mjs +34 -80
  19. package/bin/commands/iterate/classify.mjs +5 -4
  20. package/bin/commands/iterate/escalate.mjs +2 -1
  21. package/bin/commands/iterate/fix-code.mjs +16 -8
  22. package/bin/commands/iterate/helpers.mjs +34 -0
  23. package/bin/commands/iterate/index.mjs +2 -2
  24. package/bin/commands/iterate/render.mjs +25 -37
  25. package/bin/commands/iterate/stall.mjs +3 -1
  26. package/bin/commands/iterate.mjs +1 -1
  27. package/bin/commands/monitor.mjs +68 -17
  28. package/bin/commands/ready-delay.mjs +2 -1
  29. package/bin/commands/resolve-instructions.mjs +8 -4
  30. package/bin/commands/resolve.mjs +4 -4
  31. package/bin/config.json +1 -3
  32. package/bin/index.mjs +1 -0
  33. package/bin/reporters/agent.mjs +6 -2
  34. package/bin/reporters/check-instructions.mjs +11 -5
  35. package/bin/reporters/json.mjs +2 -2
  36. package/bin/reporters/text.mjs +24 -16
  37. package/package.json +3 -2
@@ -4,24 +4,23 @@ import { checkEscalateTriggers, validateBaseBranch, buildEscalateSuggestion, bui
4
4
  import { buildResolveCommand } from "./classify.mjs";
5
5
  import { buildFixInstructions } from "./render.mjs";
6
6
  import { applyStallGuard } from "./stall.mjs";
7
- import { tryCancelRun } from "./helpers.mjs";
7
+ import { tryCancelRun, buildInProgressRunIds } from "./helpers.mjs";
8
8
  export async function handleFixCode(ctx) {
9
9
  const { base, report, opts, headSha, stallKey, prNumber, stallTimeoutSeconds, repoOwner, repoName, reviewSummaryIds, firstLookSummaries, editedSummaries, surfacedApprovals, } = ctx;
10
10
  const failingChecks = report.checks.failing;
11
11
  const stored = await readFixAttempts({ owner: repoOwner, repo: repoName, pr: prNumber });
12
12
  const isNewSha = stored?.headSha !== headSha;
13
- // Accumulate across shas — only increment when a push is detected (sha changed)
14
13
  const currentAttempts = stored ? { ...stored.threadAttempts } : {};
15
14
  if (isNewSha) {
16
15
  for (const t of report.threads.actionable) {
17
16
  currentAttempts[t.id] = (currentAttempts[t.id] ?? 0) + 1;
18
17
  }
19
18
  }
20
- const escalateTriggers = checkEscalateTriggers(report.threads.actionable, report.comments.actionable, report.changesRequestedReviews, failingChecks, currentAttempts, report.mergeStatus.status === "CONFLICTS");
19
+ const escalateTriggers = checkEscalateTriggers(report.threads.actionable, report.threads.resolutionOnly, report.comments.actionable, report.changesRequestedReviews, failingChecks, currentAttempts, report.mergeStatus.status === "CONFLICTS");
21
20
  if (escalateTriggers.triggers.length > 0) {
22
21
  const escalateBase = {
23
22
  triggers: escalateTriggers.triggers,
24
- unresolvedThreads: report.threads.actionable.map(toAgentThread),
23
+ unresolvedThreads: [...report.threads.actionable, ...report.threads.resolutionOnly].map(toAgentThread),
25
24
  ambiguousComments: report.comments.actionable.map(toAgentComment),
26
25
  changesRequestedReviews: report.changesRequestedReviews,
27
26
  attemptHistory: escalateTriggers.thrashHistory,
@@ -36,7 +35,6 @@ export async function handleFixCode(ctx) {
36
35
  },
37
36
  };
38
37
  }
39
- // Save updated state (only incremented on sha change)
40
38
  await writeFixAttempts({ owner: repoOwner, repo: repoName, pr: prNumber }, { headSha, threadAttempts: currentAttempts });
41
39
  let cancelled = [];
42
40
  if (!opts.noAutoCancelActionable) {
@@ -46,18 +44,26 @@ export async function handleFixCode(ctx) {
46
44
  const results = await Promise.all(uniqueRunIds.map((id) => tryCancelRun(id, repoOwner, repoName)));
47
45
  cancelled = results.filter((id) => id !== null);
48
46
  }
47
+ const cancelledSet = new Set(cancelled);
49
48
  const baseLookup = validateBaseBranch(report.baseBranch);
50
49
  const threads = report.threads.actionable.map(toAgentThread);
50
+ const resolutionOnlyThreads = report.threads.resolutionOnly;
51
51
  const actionableComments = report.comments.actionable.map(toAgentComment);
52
52
  const checks = toAgentChecks(failingChecks);
53
53
  const { changesRequestedReviews } = report;
54
54
  const hasConflicts = report.mergeStatus.status === "CONFLICTS";
55
+ const needsPush = threads.length > 0 ||
56
+ actionableComments.length > 0 ||
57
+ checks.length > 0 ||
58
+ changesRequestedReviews.length > 0 ||
59
+ hasConflicts;
60
+ const inProgressRunIds = needsPush ? buildInProgressRunIds(report, cancelledSet) : [];
55
61
  const allCommentIds = [...actionableComments.map((c) => c.id), ...reviewSummaryIds];
56
- const resolveCommand = buildResolveCommand(threads, allCommentIds, changesRequestedReviews, checks, prNumber);
62
+ const resolveCommand = buildResolveCommand(threads, resolutionOnlyThreads, allCommentIds, changesRequestedReviews, checks, prNumber);
57
63
  if (baseLookup.isFallback && (resolveCommand.requiresHeadSha || hasConflicts)) {
58
64
  const fallbackEscalateBase = {
59
65
  triggers: ["base-branch-unknown"],
60
- unresolvedThreads: threads,
66
+ unresolvedThreads: [...threads, ...resolutionOnlyThreads.map(toAgentThread)],
61
67
  ambiguousComments: actionableComments,
62
68
  changesRequestedReviews,
63
69
  suggestion: buildEscalateSuggestion(["base-branch-unknown"], baseLookup.failureReason),
@@ -73,7 +79,7 @@ export async function handleFixCode(ctx) {
73
79
  }
74
80
  const firstLookThreads = report.threads.firstLook;
75
81
  const firstLookComments = report.comments.firstLook;
76
- const instructions = buildFixInstructions(threads, actionableComments, checks, changesRequestedReviews, baseLookup.branch, resolveCommand, hasConflicts, prNumber, cancelled.length, firstLookThreads, firstLookComments, firstLookSummaries, editedSummaries);
82
+ const instructions = buildFixInstructions(threads, actionableComments, checks, changesRequestedReviews, baseLookup.branch, resolveCommand, hasConflicts, prNumber, cancelled.length, firstLookThreads, firstLookComments, firstLookSummaries, editedSummaries, inProgressRunIds, resolutionOnlyThreads);
77
83
  return applyStallGuard(stallKey, stallTimeoutSeconds, headSha, base, prNumber, {
78
84
  ...base,
79
85
  baseBranch: baseLookup.branch,
@@ -81,6 +87,7 @@ export async function handleFixCode(ctx) {
81
87
  fix: {
82
88
  mode: "rebase-and-push",
83
89
  threads,
90
+ resolutionOnlyThreads,
84
91
  actionableComments,
85
92
  reviewSummaryIds,
86
93
  firstLookSummaries,
@@ -92,6 +99,7 @@ export async function handleFixCode(ctx) {
92
99
  instructions,
93
100
  firstLookThreads,
94
101
  firstLookComments,
102
+ inProgressRunIds,
95
103
  },
96
104
  cancelled,
97
105
  }, report, reviewSummaryIds);
@@ -2,6 +2,13 @@ import { execFile as execFileCb } from "node:child_process";
2
2
  import { promisify } from "node:util";
3
3
  import { rest } from "../../github/http.mjs";
4
4
  const execFile = promisify(execFileCb);
5
+ export function buildInProgressRunIds(report, cancelledSet) {
6
+ return [
7
+ ...new Set(report.checks.inProgress
8
+ .map((c) => c.runId)
9
+ .filter((id) => id !== null && !cancelledSet.has(id))),
10
+ ];
11
+ }
5
12
  export function buildSummary(report) {
6
13
  return {
7
14
  passing: report.checks.passing.length,
@@ -84,6 +91,33 @@ export async function getCurrentHeadSha() {
84
91
  return null;
85
92
  }
86
93
  }
94
+ export function buildWaitLog(base) {
95
+ const { summary, remainingSeconds } = base;
96
+ const parts = [`WAIT: ${summary.passing} passing, ${summary.inProgress} in-progress`];
97
+ switch (base.mergeStatus) {
98
+ case "BLOCKED":
99
+ if (base.reviewDecision === "REVIEW_REQUIRED")
100
+ parts.push("awaiting human review");
101
+ else if (base.reviewDecision === "APPROVED")
102
+ parts.push("awaiting additional approvals");
103
+ else
104
+ parts.push("awaiting human review or branch protection");
105
+ break;
106
+ case "BEHIND":
107
+ parts.push("branch is behind base");
108
+ break;
109
+ case "DRAFT":
110
+ parts.push("PR is a draft");
111
+ break;
112
+ case "UNSTABLE":
113
+ parts.push("some checks are unstable");
114
+ break;
115
+ }
116
+ if (remainingSeconds > 0) {
117
+ parts.push(`${remainingSeconds}s until auto-cancel`);
118
+ }
119
+ return parts.join(" — ");
120
+ }
87
121
  export function buildCooldownResult(prNumber, readyDelaySeconds) {
88
122
  return {
89
123
  action: "cooldown",
@@ -4,10 +4,9 @@ import { getCurrentPrNumber } from "../../github/client.mjs";
4
4
  import { graphql } from "../../github/http.mjs";
5
5
  import { MARK_PR_READY_MUTATION } from "../../github/queries.mjs";
6
6
  import { loadConfig } from "../../config/load.mjs";
7
- import { getLastCommitTime, getCurrentHeadSha, buildSummary, buildRelevantChecks, buildCooldownResult, } from "./helpers.mjs";
7
+ import { getLastCommitTime, getCurrentHeadSha, buildSummary, buildRelevantChecks, buildCooldownResult, buildWaitLog, } from "./helpers.mjs";
8
8
  import { classifyReviewSummaries } from "./classify.mjs";
9
9
  import { applyStallGuard } from "./stall.mjs";
10
- import { buildWaitLog } from "./render.mjs";
11
10
  import { handleFixCode } from "./fix-code.mjs";
12
11
  export async function runIterate(opts) {
13
12
  const config = loadConfig();
@@ -97,6 +96,7 @@ export async function runIterate(opts) {
97
96
  edited: report.editedSummaries,
98
97
  }, report.approvedReviews, config.iterate.minimizeApprovals);
99
98
  const hasActionableWork = report.threads.actionable.length > 0 ||
99
+ report.threads.resolutionOnly.length > 0 ||
100
100
  report.comments.actionable.length > 0 ||
101
101
  report.changesRequestedReviews.length > 0 ||
102
102
  report.checks.failing.length > 0 ||
@@ -1,3 +1,6 @@
1
+ export const FIX_INSTRUCTION_STOP_AFTER_PUSH = "Stop this iteration — CI needs time to run on the new push before the next tick.";
2
+ export const FIX_INSTRUCTION_STOP_BEFORE_NEXT_TICK = "Stop this iteration before the next tick.";
3
+ export const FIX_INSTRUCTION_END_ITERATION = "End this iteration.";
1
4
  /**
2
5
  * Render a resolve command as a shell snippet. Wraps `$DISMISS_MESSAGE` and whitespace-bearing
3
6
  * argv entries in double quotes for placeholder substitution. Throws if argv contains `"`, `$`,
@@ -18,11 +21,14 @@ export function renderResolveCommand(rc) {
18
21
  }
19
22
  return parts.join(" ");
20
23
  }
21
- export function buildFixInstructions(threads, actionableComments, checks, reviews, baseBranch, resolveCommand, hasConflicts, prNumber, cancelledCount, firstLookThreads = [], firstLookComments = [], firstLookSummaries = [], editedSummaries = []) {
24
+ export function buildFixInstructions(threads, actionableComments, checks, reviews, baseBranch, resolveCommand, hasConflicts, prNumber, cancelledCount, firstLookThreads = [], firstLookComments = [], firstLookSummaries = [], editedSummaries = [], inProgressRunIds = [], resolutionOnlyThreads = []) {
22
25
  const instructions = [];
26
+ if (inProgressRunIds.length > 0) {
27
+ instructions.push(`Cancel in-progress CI runs first: for each ID under \`## In-progress runs\`, run \`gh run cancel <id>\`. Do this before applying any code fixes — the push at the end of this iteration will supersede those runs anyway, so letting them continue burns CI minutes for results no one will read. If \`gh\` reports a run is already completed, ignore it and continue with the next ID.`);
28
+ }
23
29
  const hasSuggestions = threads.some((t) => t.suggestion);
24
30
  if (hasSuggestions) {
25
- instructions.push(`For each thread marked \`[suggestion]\` under \`## Review threads\`: run \`npx pr-shepherd commit-suggestion ${prNumber} --thread-id <id> --message "<one-sentence headline>" --format=json\`, one thread at a time. On \`applied: true\` the CLI already resolved the thread — remove its ID from \`--resolve-thread-ids\` in the \`resolve:\` command below. On \`applied: false\` read \`reason\` and \`patch\`, fall through to the manual-edit step, and do not retry the same command. Optionally pass \`--dry-run\` (omitting \`--message\`) to preview the patch without mutating the working tree.`);
31
+ instructions.push(`For each thread marked \`[suggestion]\` under \`## Review threads\`: run \`npx pr-shepherd commit-suggestion ${prNumber} --thread-id <id> --message "<one-sentence headline>" --format=json\` to retrieve the patch and suggested commit. The CLI does not mutate the working tree — apply the patch yourself (run \`git apply\` with the diff shown, or edit the file directly using the line range), then stage the listed file and run the suggested \`git commit\` from the \`## Instructions\` section. Include the thread ID in \`--resolve-thread-ids\` in the \`resolve:\` command below (the thread is not auto-resolved). If the patch fails to apply, fall through to the manual-edit step. Do not retry the same command.`);
26
32
  }
27
33
  if (threads.length > 0 || actionableComments.length > 0) {
28
34
  const suggestionFallback = hasSuggestions
@@ -30,11 +36,20 @@ export function buildFixInstructions(threads, actionableComments, checks, review
30
36
  : "";
31
37
  instructions.push(`Apply code fixes: read and edit each file referenced under \`## Review threads\` and \`## Actionable comments\` above.${suggestionFallback}`);
32
38
  }
33
- const checksWithRunId = checks.filter((c) => c.runId);
39
+ if (resolutionOnlyThreads.length > 0) {
40
+ instructions.push(`Resolve the threads under \`## Review threads to resolve\` with the \`resolve:\` command shown below. These threads are already outdated or minimized, so no code edit is required for them unless their body reveals separate work you choose to do.`);
41
+ }
42
+ const cancelledRunIdChecks = checks.filter((c) => c.runId && c.conclusion === "CANCELLED");
43
+ const failedRunIdChecks = checks.filter((c) => c.runId && c.conclusion !== "CANCELLED");
34
44
  const externalChecks = checks.filter((c) => !c.runId && c.detailsUrl);
35
45
  const bareChecks = checks.filter((c) => !c.runId && !c.detailsUrl);
36
- if (checksWithRunId.length > 0) {
37
- instructions.push(`For each failing check under \`## Failing checks\` with a run ID, examine the log tail in the fenced block to decide what to do:\n - If the log tail shows a transient runner or infrastructure failure (network timeout, runner setup crash, OOM kill), run \`gh run rerun <runId> --failed\` and stop this iteration — CI will re-run automatically.\n - If the log tail shows a real test or build failure, apply a code fix.\n - If the fenced log block is absent, run \`gh run view <runId> --log-failed\` first to fetch it, then choose between rerun and fix above.`);
46
+ if (failedRunIdChecks.length > 0) {
47
+ instructions.push(`For each failing check under \`## Failing checks\` with a run ID and no \`[conclusion: CANCELLED]\` tag: run \`gh run view <runId> --log-failed\` to fetch the failing job's log.`);
48
+ instructions.push(`If the log shows a transient infrastructure failure (network timeout, runner setup crash, OOM kill): run \`gh run rerun <runId> --failed\`.`);
49
+ instructions.push(`If the log shows a real test/build failure: apply a code fix.`);
50
+ }
51
+ if (cancelledRunIdChecks.length > 0) {
52
+ instructions.push(`For each \`[conclusion: CANCELLED]\` bullet under \`## Failing checks\`: the run was cancelled outside Shepherd's control (manual cancel, newer push, concurrency-group eviction). Run \`gh run rerun <runId>\` only if the cancellation looks unintended; otherwise treat it as resolved by the superseding run. Do NOT confuse these with IDs under \`## Cancelled runs\` — those were cancelled by Shepherd itself.`);
38
53
  }
39
54
  if (externalChecks.length > 0) {
40
55
  instructions.push(`For each bullet in \`## Failing checks\` starting with \`external\` (external status check): open the linked URL in a browser to inspect the failure — log tails are not available for external checks.`);
@@ -64,7 +79,7 @@ export function buildFixInstructions(threads, actionableComments, checks, review
64
79
  }
65
80
  const firstLookTotal = firstLookThreads.length + firstLookComments.length;
66
81
  if (firstLookTotal > 0) {
67
- instructions.push(`Items in \`## First-look items\` are for acknowledgement only — do not pass their IDs to \`--resolve-thread-ids\`, \`--minimize-comment-ids\`, or \`--dismiss-review-ids\`. Acknowledge each one with a one-line classification (e.g. "outdated — addressed by commit abc1234", "resolved — already fixed", "minimized — noise").`);
82
+ instructions.push(`Items in \`## First-look items\` are shown so you can acknowledge their current status before acting. If a first-look thread also appears under \`## Review threads to resolve\`, its ID is already included in the \`resolve:\` command; otherwise do not pass first-look-only IDs to mutation flags.`);
68
83
  }
69
84
  if (firstLookSummaries.length > 0) {
70
85
  instructions.push(`Review the bodies shown under \`## Review summaries (first look — to be minimized)\` — you are seeing these for the first time. Their IDs are already included in the \`resolve:\` command's \`--minimize-comment-ids\`; if any warrants a \`## Shepherd Journal\` entry, record it before running resolve.`);
@@ -73,7 +88,7 @@ export function buildFixInstructions(threads, actionableComments, checks, review
73
88
  firstLookThreads.filter((t) => t.edited).length +
74
89
  firstLookComments.filter((c) => c.edited).length;
75
90
  if (editedTotal > 0) {
76
- instructions.push(`Items under \`## Review summaries (edited since first look)\` and any first-look bullet tagged \`, edited\` were updated by their author after you previously acknowledged them. Read the updated body. Do **not** include their IDs in \`--minimize-comment-ids\`, \`--resolve-thread-ids\`, or \`--dismiss-review-ids\` — they are already closed or minimized on GitHub.`);
91
+ instructions.push(`Items under \`## Review summaries (edited since first look)\` and any first-look bullet tagged \`, edited\` were updated by their author after you previously acknowledged them. Read the updated body before deciding whether any matching \`## Review threads to resolve\` item should be resolved.`);
77
92
  }
78
93
  if (resolveCommand.hasMutations) {
79
94
  const substituteParts = [];
@@ -93,40 +108,13 @@ export function buildFixInstructions(threads, actionableComments, checks, review
93
108
  instructions.push(`For any large decisions or rejections you made this iteration, add or update a \`## Shepherd Journal\` section in the PR description (\`gh pr edit ${prNumber} --body …\`) summarizing each decision. For threads and comments, use the markdown link shown in its heading above; for reviews, reference the review ID.`);
94
109
  }
95
110
  if (needsPush) {
96
- instructions.push(`Stop this iteration — CI needs time to run on the new push before the next tick.`);
111
+ instructions.push(FIX_INSTRUCTION_STOP_AFTER_PUSH);
97
112
  }
98
113
  else if (resolveCommand.hasMutations) {
99
- instructions.push(`Stop this iteration before the next tick.`);
114
+ instructions.push(FIX_INSTRUCTION_STOP_BEFORE_NEXT_TICK);
100
115
  }
101
116
  else {
102
- instructions.push(`End this iteration.`);
117
+ instructions.push(FIX_INSTRUCTION_END_ITERATION);
103
118
  }
104
119
  return instructions;
105
120
  }
106
- export function buildWaitLog(base) {
107
- const { summary, remainingSeconds } = base;
108
- const parts = [`WAIT: ${summary.passing} passing, ${summary.inProgress} in-progress`];
109
- switch (base.mergeStatus) {
110
- case "BLOCKED":
111
- if (base.reviewDecision === "REVIEW_REQUIRED")
112
- parts.push("awaiting human review");
113
- else if (base.reviewDecision === "APPROVED")
114
- parts.push("awaiting additional approvals");
115
- else
116
- parts.push("awaiting human review or branch protection");
117
- break;
118
- case "BEHIND":
119
- parts.push("branch is behind base");
120
- break;
121
- case "DRAFT":
122
- parts.push("PR is a draft");
123
- break;
124
- case "UNSTABLE":
125
- parts.push("some checks are unstable");
126
- break;
127
- }
128
- if (remainingSeconds > 0) {
129
- parts.push(`${remainingSeconds}s until auto-cancel`);
130
- }
131
- return parts.join(" — ");
132
- }
@@ -7,6 +7,7 @@ export function computeStallFingerprint(action, headSha, base, report, reviewSum
7
7
  ...report.checks.inProgress.map((p) => `inProgress:${p.name}`),
8
8
  ].sort();
9
9
  const threads = report.threads.actionable.map((t) => t.id).sort();
10
+ const resolutionOnlyThreads = report.threads.resolutionOnly.map((t) => t.id).sort();
10
11
  const comments = report.comments.actionable.map((c) => c.id).sort();
11
12
  const reviews = report.changesRequestedReviews.map((r) => r.id).sort();
12
13
  const summaries = [...reviewSummaryIds].sort();
@@ -19,6 +20,7 @@ export function computeStallFingerprint(action, headSha, base, report, reviewSum
19
20
  isDraft: base.isDraft,
20
21
  checks,
21
22
  threads,
23
+ resolutionOnlyThreads,
22
24
  comments,
23
25
  reviews,
24
26
  summaries,
@@ -42,7 +44,7 @@ export async function applyStallGuard(stallKey, stallTimeoutSeconds, headSha, ba
42
44
  const stalledMinutes = Math.floor(ageSeconds / 60);
43
45
  const escalateBase = {
44
46
  triggers: ["stall-timeout"],
45
- unresolvedThreads: report.threads.actionable.map(toAgentThread),
47
+ unresolvedThreads: [...report.threads.actionable, ...report.threads.resolutionOnly].map(toAgentThread),
46
48
  ambiguousComments: report.comments.actionable.map(toAgentComment),
47
49
  changesRequestedReviews: report.changesRequestedReviews,
48
50
  suggestion: buildEscalateSuggestion(["stall-timeout"], String(stalledMinutes)),
@@ -1,2 +1,2 @@
1
1
  export { runIterate } from "./iterate/index.mjs";
2
- export { renderResolveCommand } from "./iterate/render.mjs";
2
+ export { FIX_INSTRUCTION_END_ITERATION, FIX_INSTRUCTION_STOP_AFTER_PUSH, FIX_INSTRUCTION_STOP_BEFORE_NEXT_TICK, renderResolveCommand, } from "./iterate/render.mjs";
@@ -1,5 +1,6 @@
1
1
  import { getCurrentPrNumber } from "../github/client.mjs";
2
2
  import { loadConfig } from "../config/load.mjs";
3
+ import { joinSections } from "../util/markdown.mjs";
3
4
  export async function runMonitor(opts) {
4
5
  const config = loadConfig();
5
6
  const prNumber = opts.prNumber ?? (await getCurrentPrNumber());
@@ -16,30 +17,48 @@ export async function runMonitor(opts) {
16
17
  // step 1 of formatMonitorResult's ## Instructions and the in-prompt Self-dedup
17
18
  // block depend on this exact string — don't change the format.
18
19
  const loopTag = `#pr-shepherd-loop:pr=${prNumber}:`;
19
- const loopPrompt = buildLoopPrompt(prNumber, loopTag, opts.readyDelaySuffix);
20
20
  const loopArgs = interval;
21
- return { prNumber, loopTag, loopArgs, loopPrompt };
21
+ const reusableCommand = buildIterateCommand(prNumber, opts.readyDelaySuffix);
22
+ const loopPrompt = buildLoopPrompt(prNumber, loopTag, reusableCommand, loopArgs, opts.runtime ?? "claude");
23
+ return {
24
+ prNumber,
25
+ loopTag,
26
+ loopArgs,
27
+ loopPrompt,
28
+ reusableCommand,
29
+ };
22
30
  }
23
31
  // ---------------------------------------------------------------------------
24
32
  // Formatters
25
33
  // ---------------------------------------------------------------------------
26
- export function formatMonitorResult(result) {
34
+ export function formatMonitorResult(result, opts) {
27
35
  const { prNumber, loopTag, loopArgs, loopPrompt } = result;
28
- return [
29
- `# PR #${prNumber} [MONITOR]`,
30
- "",
31
- `Loop tag: \`${loopTag}\``,
32
- `Loop args: \`${loopArgs}\``,
33
- "",
36
+ const runtime = opts?.runtime ?? "claude";
37
+ const sections = [
38
+ [
39
+ `# PR #${prNumber} [MONITOR]`,
40
+ "",
41
+ `Loop tag: \`${loopTag}\``,
42
+ `Loop args: \`${loopArgs}\``,
43
+ ].join("\n"),
44
+ runtime === "codex" ? `Reusable command: \`${result.reusableCommand}\`` : null,
34
45
  "## Loop prompt",
35
- "",
36
46
  loopPrompt,
37
- "",
38
47
  "## Instructions",
39
- "",
40
- `1. Run \`CronList\`. If any job's prompt contains \`${loopTag}\`, run the \`## Loop prompt\` body once inline (as if it were a cron tick) then stop — do not create a duplicate loop.`,
41
- `2. Otherwise, invoke the \`/loop\` skill via the Skill tool. Build the \`args\` parameter as: only the value inside the backticks on the \`Loop args\` line above (the interval — not the \`Loop args:\` label), then a blank line, then the full \`## Loop prompt\` body.`,
42
- ].join("\n");
48
+ buildMonitorInstructions(result, runtime)
49
+ .map((inst, i) => `${i + 1}. ${inst}`)
50
+ .join("\n"),
51
+ ];
52
+ return joinSections(sections);
53
+ }
54
+ export function formatMonitorJson(result, opts) {
55
+ const runtime = opts?.runtime ?? "claude";
56
+ const { reusableCommand, ...base } = result;
57
+ return {
58
+ ...base,
59
+ ...(runtime === "codex" && { reusableCommand }),
60
+ instructions: buildMonitorInstructions(result, runtime),
61
+ };
43
62
  }
44
63
  // ---------------------------------------------------------------------------
45
64
  // Internal
@@ -53,9 +72,29 @@ function validateReadyDelaySuffix(readyDelaySuffix) {
53
72
  }
54
73
  return trimmed;
55
74
  }
56
- function buildLoopPrompt(prNumber, loopTag, readyDelaySuffix) {
75
+ function buildIterateCommand(prNumber, readyDelaySuffix) {
57
76
  const validatedDelay = validateReadyDelaySuffix(readyDelaySuffix);
58
- const iterateCmd = `npx pr-shepherd iterate ${prNumber}${validatedDelay ? ` --ready-delay ${validatedDelay}` : ""}`;
77
+ return `npx pr-shepherd ${prNumber}${validatedDelay ? ` --ready-delay ${validatedDelay}` : ""}`;
78
+ }
79
+ function buildLoopPrompt(prNumber, loopTag, iterateCmd, loopArgs, runtime = "claude") {
80
+ if (runtime === "codex") {
81
+ return [
82
+ loopTag,
83
+ "",
84
+ "**IMPORTANT — Codex recurrence rules:**",
85
+ "- Run the command below once and follow its `## Instructions` exactly.",
86
+ `- If the output tells you to continue the active Codex goal, wait about the configured interval (${loopArgs}) and rerun the reusable command from the monitor output.`,
87
+ "- Stop only when Shepherd emits `[CANCEL]` because the ready-delay completed or the PR was merged/closed, or when Shepherd emits `[ESCALATE]` (including `stall-timeout` for repeated unchanged CI failures).",
88
+ "- Do not call `/loop`, `ScheduleWakeup`, `CronCreate`, or `npx pr-shepherd monitor`; Codex recurrence is explicit `iterate` command cycles.",
89
+ "",
90
+ "Run in a single Bash call:",
91
+ ` ${iterateCmd}`,
92
+ "",
93
+ `Exit codes 0–3 are all valid. If the command crashes (non-zero exit, no markdown output starting with \`# PR #${prNumber} [\`), report the first line of stderr and stop so the user can retry.`,
94
+ "",
95
+ "The output is Markdown. The first line is an H1 heading of the form `# PR #<N> [<ACTION>]`. Every output ends with a `## Instructions` section — follow those numbered steps exactly.",
96
+ ].join("\n");
97
+ }
59
98
  return [
60
99
  loopTag,
61
100
  "",
@@ -73,3 +112,15 @@ function buildLoopPrompt(prNumber, loopTag, readyDelaySuffix) {
73
112
  "The output is Markdown. The first line is an H1 heading of the form `# PR #<N> [<ACTION>]`. Every output ends with a `## Instructions` section — follow those numbered steps exactly.",
74
113
  ].join("\n");
75
114
  }
115
+ function buildMonitorInstructions(result, runtime) {
116
+ if (runtime === "codex") {
117
+ return [
118
+ "Run the `## Loop prompt` body once inline now.",
119
+ `For an active Codex goal, keep cycling with \`${result.reusableCommand}\` about every configured interval (${result.loopArgs}) until a terminal condition is reached. Codex does not create a \`/loop\` monitor.`,
120
+ ];
121
+ }
122
+ return [
123
+ `Run \`CronList\`. If any job's prompt contains \`${result.loopTag}\`, run the \`## Loop prompt\` body once inline (as if it were a cron tick) then stop — do not create a duplicate loop.`,
124
+ "Otherwise, invoke the `/loop` skill via the Skill tool. Build the `args` parameter as: only the value inside the backticks on the `Loop args` line above (the interval — not the `Loop args:` label), then a blank line, then the full `## Loop prompt` body.",
125
+ ];
126
+ }
@@ -16,7 +16,8 @@ import { resolveStateBase } from "../state/base.mjs";
16
16
  * - If `isReady == true`: start or continue the ready timer.
17
17
  * - If `isReady == false`: reset the timer.
18
18
  *
19
- * When `shouldCancel == true`, the slash command should invoke `/loop cancel`.
19
+ * When `shouldCancel == true`, the formatter tells loop-capable agents to cancel
20
+ * the loop and tells one-shot agents to stop.
20
21
  */
21
22
  export async function updateReadyDelay(prNumber, isReady, readyDelaySeconds, owner, repo) {
22
23
  const markerPath = readySincePath(prNumber, owner, repo);
@@ -4,9 +4,10 @@
4
4
  * `buildFixInstructions` in `commands/iterate/render.mts`).
5
5
  */
6
6
  export function buildFetchInstructions(prNumber, result) {
7
- const { actionableThreads, firstLookThreads, actionableComments, firstLookComments, changesRequestedReviews, reviewSummaries, commitSuggestionsEnabled, } = result;
7
+ const { actionableThreads, resolutionOnlyThreads, firstLookThreads, actionableComments, firstLookComments, changesRequestedReviews, reviewSummaries, commitSuggestionsEnabled, } = result;
8
8
  const firstLookTotal = firstLookThreads.length + firstLookComments.length;
9
9
  const total = actionableThreads.length +
10
+ resolutionOnlyThreads.length +
10
11
  actionableComments.length +
11
12
  changesRequestedReviews.length +
12
13
  reviewSummaries.length +
@@ -21,15 +22,15 @@ export function buildFetchInstructions(prNumber, result) {
21
22
  const instructions = [];
22
23
  instructions.push(`Classify every item listed above into exactly one of: Fixed / Actionable / Not relevant / Outdated / Acknowledge. Do not silently skip any item. Bot-authored review summaries (authors whose name contains \`[bot]\` or matches \`copilot-pull-request-reviewer\`, \`gemini-code-assist\`) default to Acknowledge with reason "bot summary — no actionable content" unless the body calls out an unaddressed issue.`);
23
24
  if (firstLookTotal > 0) {
24
- instructions.push(`Items in \`## First-look items\` are for acknowledgement only — do not pass their IDs to \`--resolve-thread-ids\`, \`--minimize-comment-ids\`, or \`--dismiss-review-ids\`. Acknowledge each one with a one-line classification (e.g. "outdated — addressed by commit abc1234", "resolved — already fixed", "minimized — noise").`);
25
+ instructions.push(`Items in \`## First-look items\` are shown so you can acknowledge their current status before acting. If a first-look thread also appears under \`## Review threads to resolve\`, include its ID in \`--resolve-thread-ids\`; otherwise do not pass first-look-only IDs to mutation flags.`);
25
26
  }
26
27
  const editedTotal = firstLookThreads.filter((t) => t.edited).length +
27
28
  firstLookComments.filter((c) => c.edited).length;
28
29
  if (editedTotal > 0) {
29
- instructions.push(`First-look bullets tagged \`, edited\` were updated by their author after you previously acknowledged them. Read the updated body. Do **not** include their IDs in \`--resolve-thread-ids\`, \`--minimize-comment-ids\`, or \`--dismiss-review-ids\` — they are already closed or minimized on GitHub.`);
30
+ instructions.push(`First-look bullets tagged \`, edited\` were updated by their author after you previously acknowledged them. Read the updated body before deciding whether any matching \`## Review threads to resolve\` item should be resolved.`);
30
31
  }
31
32
  if (hasSuggestions) {
32
- instructions.push(`For each Actionable thread marked \`[suggestion]\` in \`## Actionable Review Threads\` above: run \`npx pr-shepherd commit-suggestion ${prNumber} --thread-id <id> --message "<one-sentence headline>" --format=json\`, one thread at a time. On \`applied: true\` mark it Fixed — the CLI already resolved the thread, so exclude the ID from \`--resolve-thread-ids\`. On \`applied: false\` read \`reason\` and \`patch\`, then fall through to the manual fix step — do not retry the same command. Optionally pass \`--dry-run\` (omitting \`--message\`) if you want to inspect the unified diff before it mutates the working tree — the CLI validates with \`git apply --check\`, returns the patch and \`valid: true/false\`, and exits \`1\` on drift without committing or resolving the thread.`);
33
+ instructions.push(`For each Actionable thread marked \`[suggestion]\` in \`## Actionable Review Threads\` above: run \`npx pr-shepherd commit-suggestion ${prNumber} --thread-id <id> --message "<one-sentence headline>" --format=json\` to retrieve the patch and suggested commit. The CLI does not mutate the working tree — apply the patch yourself (run \`git apply\` with the diff shown, or edit the file directly using the line range), then stage the listed file and run the suggested \`git commit\` from the \`## Instructions\` section. Include the thread ID in \`--resolve-thread-ids\` in the resolve command below (the thread is not auto-resolved). If the patch fails to apply (drift since the suggestion was written), fall through to the manual fix step. Do not retry the same \`commit-suggestion\` invocation.`);
33
34
  }
34
35
  if (hasCodeItems) {
35
36
  instructions.push(`Read and edit each file referenced under \`## Actionable Review Threads\`, \`## Actionable PR Comments\`, and \`## Pending CHANGES_REQUESTED reviews\` above. Reclassify each fixed item as Fixed. If an item is too complex to address, leave it as Actionable for the final report.`);
@@ -38,6 +39,9 @@ export function buildFetchInstructions(prNumber, result) {
38
39
  instructions.push(`Rebase and push: \`BASE_BRANCH=$(gh pr view ${prNumber} --json baseRefName --jq .baseRefName) && git fetch origin && git rebase "origin/$BASE_BRANCH" && git push --force-with-lease\`.`);
39
40
  instructions.push(`Cancel stale in-progress runs: \`BRANCH=$(git rev-parse --abbrev-ref HEAD) && CURRENT_SHA=$(git rev-parse HEAD) && gh run list --branch "$BRANCH" --status in_progress --json databaseId,headSha --jq ".[] | select(.headSha != \\"$CURRENT_SHA\\") | .databaseId" | xargs -I{} gh run cancel {}\`.`);
40
41
  }
42
+ if (resolutionOnlyThreads.length > 0) {
43
+ instructions.push(`Resolve each thread under \`## Review threads to resolve\` with \`--resolve-thread-ids\`. These threads are already outdated or minimized, so no code edit is required for them unless their body reveals separate work you choose to do.`);
44
+ }
41
45
  const requireShaHint = hasCodeItems
42
46
  ? ` Include \`--require-sha $(git rev-parse HEAD)\` only when the rebase-and-push step above ran.`
43
47
  : "";
@@ -6,7 +6,6 @@ import { loadConfig } from "../config/load.mjs";
6
6
  import { extractSuggestion } from "../suggestions/extract.mjs";
7
7
  import { buildFetchInstructions } from "./resolve-instructions.mjs";
8
8
  import { loadSeenMap, markSeen, classifyItem } from "../state/seen-comments.mjs";
9
- /** Fetch mode: auto-resolve outdated threads and return all active items for LLM triage. */
10
9
  export async function runResolveFetch(opts) {
11
10
  const repo = await getRepoInfo();
12
11
  const prNumber = opts.prNumber ?? (await getCurrentPrNumber());
@@ -15,7 +14,7 @@ export async function runResolveFetch(opts) {
15
14
  }
16
15
  const { data } = await fetchPrBatch(prNumber, repo);
17
16
  const stateKey = { owner: repo.owner, repo: repo.name, pr: prNumber };
18
- const unresolvedThreads = data.reviewThreads.filter((t) => !t.isResolved && !t.isMinimized);
17
+ const unresolvedThreads = data.reviewThreads.filter((t) => !t.isResolved);
19
18
  const visibleComments = data.comments.filter((c) => !c.isMinimized);
20
19
  const outdatedCandidates = data.reviewThreads.filter((t) => t.isOutdated);
21
20
  const resolvedCandidates = data.reviewThreads.filter((t) => t.isResolved && !t.isOutdated);
@@ -68,7 +67,8 @@ export async function runResolveFetch(opts) {
68
67
  process.stderr.write(`pr-shepherd: auto-resolve outdated threads failed (continuing): ${errors.join(", ")}\n`);
69
68
  }
70
69
  }
71
- const activeThreads = unresolvedThreads.filter((t) => !t.isOutdated);
70
+ const activeThreads = unresolvedThreads.filter((t) => !t.isOutdated && !t.isMinimized);
71
+ const resolutionOnlyThreads = unresolvedThreads.filter((t) => !autoResolvedIds.has(t.id) && (t.isOutdated || t.isMinimized));
72
72
  const cfg = loadConfig();
73
73
  const actionableThreads = activeThreads.map(({ isResolved: _r, isOutdated: _o, ...rest }) => {
74
74
  const thread = rest;
@@ -118,6 +118,7 @@ export async function runResolveFetch(opts) {
118
118
  const result = {
119
119
  prNumber,
120
120
  actionableThreads,
121
+ resolutionOnlyThreads,
121
122
  firstLookThreads,
122
123
  actionableComments: visibleComments,
123
124
  firstLookComments,
@@ -127,7 +128,6 @@ export async function runResolveFetch(opts) {
127
128
  };
128
129
  return { ...result, instructions: buildFetchInstructions(prNumber, result) };
129
130
  }
130
- /** Mutation mode: resolve/minimize/dismiss by ID. */
131
131
  export async function runResolveMutate(opts) {
132
132
  const repo = await getRepoInfo();
133
133
  const prNumber = opts.prNumber ?? (await getCurrentPrNumber());
package/bin/config.json CHANGED
@@ -17,9 +17,7 @@
17
17
  "fetchReviewSummaries": true
18
18
  },
19
19
  "checks": {
20
- "ciTriggerEvents": ["pull_request", "pull_request_target"],
21
- "logTailLines": 5,
22
- "logTailChars": 200
20
+ "ciTriggerEvents": ["pull_request", "pull_request_target"]
23
21
  },
24
22
  "mergeStatus": {
25
23
  "blockingReviewerLogins": ["copilot"]
package/bin/index.mjs CHANGED
@@ -3,6 +3,7 @@
3
3
  * pr-shepherd — unified GitHub PR status + auto-resolve CLI
4
4
  *
5
5
  * Usage:
6
+ * pr-shepherd [PR]
6
7
  * pr-shepherd check [PR]
7
8
  * pr-shepherd resolve [PR]
8
9
  * pr-shepherd iterate [PR]
@@ -3,7 +3,8 @@
3
3
  *
4
4
  * These strip fields that are always-false by the time items reach iterate
5
5
  * (isResolved, isOutdated, isMinimized, createdAtUnix) and check metadata the
6
- * monitor prompt never reads (event, status, conclusion, category).
6
+ * monitor prompt never reads (event, status, category).
7
+ * conclusion is preserved on AgentCheck so the formatter can branch on CANCELLED.
7
8
  * detailsUrl is preserved in AgentCheck as a fallback for external status checks.
8
9
  * The original domain types are preserved for check command output.
9
10
  */
@@ -27,15 +28,18 @@ export function toAgentComment(c) {
27
28
  return { id: c.id, author: c.author, body: c.body, url: c.url };
28
29
  }
29
30
  export function toAgentCheck(c) {
31
+ if (c.conclusion === "SKIPPED" || c.conclusion === "NEUTRAL") {
32
+ throw new Error(`Unexpected conclusion ${c.conclusion} in toAgentCheck`);
33
+ }
30
34
  return {
31
35
  name: c.name,
32
36
  runId: c.runId,
33
37
  detailsUrl: c.detailsUrl,
38
+ conclusion: c.conclusion,
34
39
  ...(c.workflowName !== undefined && { workflowName: c.workflowName }),
35
40
  ...(c.jobName !== undefined && { jobName: c.jobName }),
36
41
  ...(c.failedStep !== undefined && { failedStep: c.failedStep }),
37
42
  ...(c.summary !== undefined && { summary: c.summary }),
38
- ...(c.logTail !== undefined && { logTail: c.logTail }),
39
43
  };
40
44
  }
41
45
  /**
@@ -3,11 +3,15 @@
3
3
  * All rebase policy, CI budget policy, and ready-to-merge gating live here so the
4
4
  * skill stays a thin dispatcher and these rules co-evolve with the CLI data model.
5
5
  */
6
- export function buildCheckInstructions(report) {
6
+ export function buildCheckInstructions(report, opts) {
7
+ const runtime = opts?.runtime ?? "claude";
7
8
  const { mergeStatus, checks, threads, comments, changesRequestedReviews, status } = report;
8
9
  const instructions = [];
9
10
  // 1. Summary
10
- const totalActionable = threads.actionable.length + comments.actionable.length + changesRequestedReviews.length;
11
+ const totalActionable = threads.actionable.length +
12
+ threads.resolutionOnly.length +
13
+ comments.actionable.length +
14
+ changesRequestedReviews.length;
11
15
  const total = checks.passing.length +
12
16
  checks.failing.length +
13
17
  checks.inProgress.length +
@@ -28,8 +32,8 @@ export function buildCheckInstructions(report) {
28
32
  for (const c of checks.failing) {
29
33
  const stepHint = c.failedStep ? ` (failed step: \`${c.failedStep}\`)` : "";
30
34
  const diagnosisHint = c.runId
31
- ? c.logTail !== undefined
32
- ? `examine the log tail${stepHint} — if transient, run \`gh run rerun ${c.runId} --failed\`; otherwise apply a fix`
35
+ ? c.conclusion === "CANCELLED"
36
+ ? `cancelled — if unintended, rerun with \`gh run rerun ${c.runId}\``
33
37
  : `run \`gh run view ${c.runId} --log-failed\`${stepHint} to diagnose — if transient, rerun with \`gh run rerun ${c.runId} --failed\`; otherwise apply a fix`
34
38
  : c.detailsUrl
35
39
  ? `open the check details (${c.detailsUrl}) to diagnose the failure`
@@ -54,7 +58,9 @@ export function buildCheckInstructions(report) {
54
58
  }
55
59
  // 5. Continuous monitoring pointer (suppressed only when truly ready to merge)
56
60
  if (!isReady) {
57
- instructions.push("This is a one-shot check. For continuous monitoring that acts on these signals automatically, use `/pr-shepherd:monitor`.");
61
+ instructions.push(runtime === "codex"
62
+ ? `This is a one-shot check. For follow-up monitoring, run \`npx pr-shepherd ${report.pr}\`.`
63
+ : "This is a one-shot check. For continuous monitoring that acts on these signals automatically, use `/pr-shepherd:monitor`.");
58
64
  }
59
65
  return instructions;
60
66
  }
@@ -5,6 +5,6 @@
5
5
  * without string-scraping the human-readable text reporter.
6
6
  */
7
7
  import { buildCheckInstructions } from "./check-instructions.mjs";
8
- export function formatJson(report) {
9
- return JSON.stringify({ ...report, instructions: buildCheckInstructions(report) }, null, 2);
8
+ export function formatJson(report, opts) {
9
+ return JSON.stringify({ ...report, instructions: buildCheckInstructions(report, opts) }, null, 2);
10
10
  }