@codyswann/lisa 4.96.3 → 4.97.1

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 (103) hide show
  1. package/dist/core/nightly-e2e-guard-behavior-certificate.js +2 -2
  2. package/dist/core/upstream-evidence-manifest.d.ts.map +1 -1
  3. package/dist/core/upstream-evidence-manifest.js +45 -5
  4. package/dist/core/upstream-evidence-manifest.js.map +1 -1
  5. package/package.json +4 -4
  6. package/plugins/lisa/.claude-plugin/plugin.json +1 -1
  7. package/plugins/lisa/.codex-plugin/plugin.json +1 -1
  8. package/plugins/lisa/.codex-plugin/skills/lisa-github-build-intake/SKILL.md +1 -1
  9. package/plugins/lisa/.codex-plugin/skills/lisa-implement/SKILL.md +12 -1
  10. package/plugins/lisa/.codex-plugin/skills/lisa-track/SKILL.md +25 -2
  11. package/plugins/lisa/rules/reference/rejection-detection.md +2 -2
  12. package/plugins/lisa/skills/lisa-github-build-intake/SKILL.md +1 -1
  13. package/plugins/lisa/skills/lisa-implement/SKILL.md +12 -1
  14. package/plugins/lisa/skills/lisa-track/SKILL.md +25 -2
  15. package/plugins/lisa-agy/plugin.json +1 -1
  16. package/plugins/lisa-agy/skills/lisa-github-build-intake/SKILL.md +1 -1
  17. package/plugins/lisa-agy/skills/lisa-implement/SKILL.md +12 -1
  18. package/plugins/lisa-agy/skills/lisa-track/SKILL.md +25 -2
  19. package/plugins/lisa-cdk/.claude-plugin/plugin.json +1 -1
  20. package/plugins/lisa-cdk/.codex-plugin/plugin.json +1 -1
  21. package/plugins/lisa-cdk-agy/plugin.json +1 -1
  22. package/plugins/lisa-cdk-copilot/.claude-plugin/plugin.json +1 -1
  23. package/plugins/lisa-cdk-cursor/.claude-plugin/plugin.json +1 -1
  24. package/plugins/lisa-cdk-devin/.claude-plugin/plugin.json +1 -1
  25. package/plugins/lisa-cdk-devin/.devin-plugin/plugin.json +1 -1
  26. package/plugins/lisa-copilot/.claude-plugin/plugin.json +1 -1
  27. package/plugins/lisa-copilot/rules/reference/rejection-detection.md +2 -2
  28. package/plugins/lisa-copilot/skills/lisa-github-build-intake/SKILL.md +1 -1
  29. package/plugins/lisa-copilot/skills/lisa-implement/SKILL.md +12 -1
  30. package/plugins/lisa-copilot/skills/lisa-track/SKILL.md +25 -2
  31. package/plugins/lisa-cursor/.claude-plugin/plugin.json +1 -1
  32. package/plugins/lisa-cursor/rules/rejection-detection-reference.mdc +2 -2
  33. package/plugins/lisa-cursor/skills/lisa-github-build-intake/SKILL.md +1 -1
  34. package/plugins/lisa-cursor/skills/lisa-implement/SKILL.md +12 -1
  35. package/plugins/lisa-cursor/skills/lisa-track/SKILL.md +25 -2
  36. package/plugins/lisa-devin/.claude-plugin/plugin.json +1 -1
  37. package/plugins/lisa-devin/.devin-plugin/plugin.json +1 -1
  38. package/plugins/lisa-devin/rules/reference/rejection-detection.md +2 -2
  39. package/plugins/lisa-devin/skills/lisa-github-build-intake/SKILL.md +1 -1
  40. package/plugins/lisa-devin/skills/lisa-implement/SKILL.md +12 -1
  41. package/plugins/lisa-devin/skills/lisa-track/SKILL.md +25 -2
  42. package/plugins/lisa-expo/.claude-plugin/plugin.json +1 -1
  43. package/plugins/lisa-expo/.codex-plugin/plugin.json +1 -1
  44. package/plugins/lisa-expo-agy/plugin.json +1 -1
  45. package/plugins/lisa-expo-copilot/.claude-plugin/plugin.json +1 -1
  46. package/plugins/lisa-expo-cursor/.claude-plugin/plugin.json +1 -1
  47. package/plugins/lisa-expo-devin/.claude-plugin/plugin.json +1 -1
  48. package/plugins/lisa-expo-devin/.devin-plugin/plugin.json +1 -1
  49. package/plugins/lisa-harper-fabric/.claude-plugin/plugin.json +1 -1
  50. package/plugins/lisa-harper-fabric/.codex-plugin/plugin.json +1 -1
  51. package/plugins/lisa-harper-fabric-agy/plugin.json +1 -1
  52. package/plugins/lisa-harper-fabric-copilot/.claude-plugin/plugin.json +1 -1
  53. package/plugins/lisa-harper-fabric-cursor/.claude-plugin/plugin.json +1 -1
  54. package/plugins/lisa-harper-fabric-devin/.claude-plugin/plugin.json +1 -1
  55. package/plugins/lisa-harper-fabric-devin/.devin-plugin/plugin.json +1 -1
  56. package/plugins/lisa-nestjs/.claude-plugin/plugin.json +1 -1
  57. package/plugins/lisa-nestjs/.codex-plugin/plugin.json +1 -1
  58. package/plugins/lisa-nestjs-agy/plugin.json +1 -1
  59. package/plugins/lisa-nestjs-copilot/.claude-plugin/plugin.json +1 -1
  60. package/plugins/lisa-nestjs-cursor/.claude-plugin/plugin.json +1 -1
  61. package/plugins/lisa-nestjs-devin/.claude-plugin/plugin.json +1 -1
  62. package/plugins/lisa-nestjs-devin/.devin-plugin/plugin.json +1 -1
  63. package/plugins/lisa-openclaw/.claude-plugin/plugin.json +1 -1
  64. package/plugins/lisa-openclaw/.codex-plugin/plugin.json +1 -1
  65. package/plugins/lisa-openclaw-agy/plugin.json +1 -1
  66. package/plugins/lisa-openclaw-copilot/.claude-plugin/plugin.json +1 -1
  67. package/plugins/lisa-openclaw-cursor/.claude-plugin/plugin.json +1 -1
  68. package/plugins/lisa-openclaw-devin/.claude-plugin/plugin.json +1 -1
  69. package/plugins/lisa-openclaw-devin/.devin-plugin/plugin.json +1 -1
  70. package/plugins/lisa-phaser/.claude-plugin/plugin.json +1 -1
  71. package/plugins/lisa-phaser/.codex-plugin/plugin.json +1 -1
  72. package/plugins/lisa-phaser-agy/plugin.json +1 -1
  73. package/plugins/lisa-phaser-copilot/.claude-plugin/plugin.json +1 -1
  74. package/plugins/lisa-phaser-cursor/.claude-plugin/plugin.json +1 -1
  75. package/plugins/lisa-phaser-devin/.claude-plugin/plugin.json +1 -1
  76. package/plugins/lisa-phaser-devin/.devin-plugin/plugin.json +1 -1
  77. package/plugins/lisa-rails/.claude-plugin/plugin.json +1 -1
  78. package/plugins/lisa-rails/.codex-plugin/plugin.json +1 -1
  79. package/plugins/lisa-rails-agy/plugin.json +1 -1
  80. package/plugins/lisa-rails-copilot/.claude-plugin/plugin.json +1 -1
  81. package/plugins/lisa-rails-cursor/.claude-plugin/plugin.json +1 -1
  82. package/plugins/lisa-rails-devin/.claude-plugin/plugin.json +1 -1
  83. package/plugins/lisa-rails-devin/.devin-plugin/plugin.json +1 -1
  84. package/plugins/lisa-typescript/.claude-plugin/plugin.json +1 -1
  85. package/plugins/lisa-typescript/.codex-plugin/plugin.json +1 -1
  86. package/plugins/lisa-typescript-agy/plugin.json +1 -1
  87. package/plugins/lisa-typescript-copilot/.claude-plugin/plugin.json +1 -1
  88. package/plugins/lisa-typescript-cursor/.claude-plugin/plugin.json +1 -1
  89. package/plugins/lisa-typescript-devin/.claude-plugin/plugin.json +1 -1
  90. package/plugins/lisa-typescript-devin/.devin-plugin/plugin.json +1 -1
  91. package/plugins/lisa-wiki/.claude-plugin/plugin.json +1 -1
  92. package/plugins/lisa-wiki/.codex-plugin/plugin.json +1 -1
  93. package/plugins/lisa-wiki-agy/plugin.json +1 -1
  94. package/plugins/lisa-wiki-copilot/.claude-plugin/plugin.json +1 -1
  95. package/plugins/lisa-wiki-cursor/.claude-plugin/plugin.json +1 -1
  96. package/plugins/lisa-wiki-devin/.claude-plugin/plugin.json +1 -1
  97. package/plugins/lisa-wiki-devin/.devin-plugin/plugin.json +1 -1
  98. package/plugins/src/base/rules/reference/rejection-detection.md +2 -2
  99. package/plugins/src/base/skills/lisa-github-build-intake/SKILL.md +1 -1
  100. package/plugins/src/base/skills/lisa-implement/SKILL.md +12 -1
  101. package/plugins/src/base/skills/lisa-track/SKILL.md +25 -2
  102. package/scripts/lisa-ci-failure-redispatch.mjs +87 -17
  103. package/scripts/lisa-ci-rework-route.mjs +380 -0
@@ -20,7 +20,12 @@
20
20
  * a newer push or a manual re-run, and bouncing an item for it would
21
21
  * re-dispatch an agent for a failure nobody observed. It is not a pass
22
22
  * either, so it holds the clear path until it resolves.
23
- * - Every required check PASSED when each bucket is `pass` or `skipping`.
23
+ * - Every required check PASSED when each bucket is `pass` or `skipping` AND
24
+ * every required context the PR's base-branch rulesets name has reported.
25
+ * `gh pr checks --required` lists only checks that reported, so a required
26
+ * context with no row — CI never dispatched, or not started — is pending,
27
+ * not passed (CodySwannGT/lisa#4711). A reported failure is still a failure
28
+ * however many contexts are missing.
24
29
  * - Anything else is still running: no write.
25
30
  *
26
31
  * What triggers a decision (CodySwannGT/lisa#4678): a CI workflow run, and
@@ -51,11 +56,18 @@ import {
51
56
  } from "../all/copy-overwrite/scripts/lisa-work-item.mjs";
52
57
 
53
58
  const SHA = /^[0-9a-f]{40}$/u;
54
- const FAILURE_MARKER =
59
+ /**
60
+ * The failure marker; captures the PR number and head SHA. Exported with the
61
+ * other marker patterns and predicates below so the dispatch-side reader
62
+ * (`scripts/lisa-ci-rework-route.mjs`, CodySwannGT/lisa#4677) shares one
63
+ * definition with the producer instead of a copy that could drift.
64
+ */
65
+ export const FAILURE_MARKER =
55
66
  /<!-- \[lisa-ci-failed\] pr=(\d+) sha=([0-9a-f]{40}) -->/u;
56
- const CLEARED_MARKER = /<!-- \[lisa-ci-cleared\] run=\d+ -->/u;
67
+ /** The line a later all-green run appends to a failure marker's comment. */
68
+ export const CLEARED_MARKER = /<!-- \[lisa-ci-cleared\] run=\d+ -->/u;
57
69
  /** Any Lisa lifecycle marker — the claim, attempt, and CI markers alike. */
58
- const LISA_MARKER = /\[(?:lisa-[a-z0-9-]+|claude-build-intake)\]/u;
70
+ export const LISA_MARKER = /\[(?:lisa-[a-z0-9-]+|claude-build-intake)\]/u;
59
71
  const NO_REQUIRED = /no (?:required )?checks reported/iu;
60
72
  /** Read every page of a REST list as one array of pages. */
61
73
  const PAGINATE = Object.freeze(["--paginate", "--slurp"]);
@@ -205,7 +217,7 @@ function candidatePullRequests(run, repo, gh) {
205
217
  * @param {object} run - `workflow_run` object.
206
218
  * @param {object} contract - Tracker contract.
207
219
  * @param {Function} gh - Runner.
208
- * @returns {{stop?: object, pr?: number, item?: string}} A stop decision or the binding.
220
+ * @returns {{stop?: object, pr?: number, baseRef?: string, item?: string}} A stop decision or the binding.
209
221
  */
210
222
  function resolveBinding(run, contract, gh) {
211
223
  const repo = contract.repository;
@@ -228,7 +240,7 @@ function resolveBinding(run, contract, gh) {
228
240
  "--repo",
229
241
  repo,
230
242
  "--json",
231
- "number,state,body,headRefOid,isCrossRepository",
243
+ "number,state,body,headRefOid,isCrossRepository,baseRefName",
232
244
  ]);
233
245
  const base = { pr: pr.number };
234
246
  if (pr.state !== "OPEN")
@@ -248,6 +260,7 @@ function resolveBinding(run, contract, gh) {
248
260
  try {
249
261
  return {
250
262
  pr: pr.number,
263
+ baseRef: pr.baseRefName,
251
264
  item: soleWorkItem(pr.body ?? "", contract, "pull-request body"),
252
265
  };
253
266
  } catch (error) {
@@ -284,22 +297,33 @@ function readItem(item, repo, gh) {
284
297
  "--json",
285
298
  "state,labels",
286
299
  ]);
300
+ return {
301
+ number,
302
+ open: view.state === "OPEN",
303
+ labels: view.labels.map(l => l.name),
304
+ comments: readItemComments(number, repo, gh),
305
+ };
306
+ }
307
+
308
+ /**
309
+ * Read every comment on an issue, oldest first. Throws naming the call when
310
+ * the read fails. Shared with `scripts/lisa-ci-rework-route.mjs`.
311
+ * @param {string} number - Issue number.
312
+ * @param {string} repo - Repository.
313
+ * @param {Function} gh - Runner.
314
+ * @returns {object[]} Comments sorted by `created_at`.
315
+ */
316
+ export function readItemComments(number, repo, gh) {
287
317
  const pages = readJson(gh, [
288
318
  "api",
289
319
  `repos/${repo}/issues/${number}/comments`,
290
320
  ...PAGINATE,
291
321
  ]);
292
- const comments = pages
322
+ return pages
293
323
  .flat()
294
324
  .toSorted((a, b) =>
295
325
  String(a.created_at).localeCompare(String(b.created_at))
296
326
  );
297
- return {
298
- number,
299
- open: view.state === "OPEN",
300
- labels: view.labels.map(l => l.name),
301
- comments,
302
- };
303
327
  }
304
328
 
305
329
  /**
@@ -364,7 +388,7 @@ function markerPr(comment) {
364
388
  * @param {object} comment - Item comment.
365
389
  * @returns {boolean} Whether its markers are trusted.
366
390
  */
367
- function trustedAuthor(comment) {
391
+ export function trustedAuthor(comment) {
368
392
  return MARKER_AUTHORS.includes(comment.user?.login ?? "");
369
393
  }
370
394
 
@@ -409,7 +433,7 @@ function readEvents(number, repo, gh) {
409
433
  * @param {object} comment - The marker comment.
410
434
  * @returns {boolean} Whether it is the newest.
411
435
  */
412
- function isNewestLisaMarker(comments, comment) {
436
+ export function isNewestLisaMarker(comments, comment) {
413
437
  // A forged failure marker counts for nothing, including as "something newer".
414
438
  const marked = comments.filter(
415
439
  c =>
@@ -537,6 +561,38 @@ function planClear(ctx) {
537
561
  };
538
562
  }
539
563
 
564
+ /**
565
+ * Hold a pass whose reported rows leave a required context unreported.
566
+ *
567
+ * `gh pr checks --required` lists only checks that have REPORTED, so a
568
+ * required check that never ran — CI not dispatched on a conflicting PR, or
569
+ * not started yet — is missing from the rows rather than failing in them
570
+ * (CodySwannGT/lisa#4711). The base branch's rulesets are the authority on
571
+ * what is required; a context they name with no row has not passed, so the
572
+ * pass is pending. Read only on a pass, or when no required row has reported
573
+ * at all: a reported failure is a failure whatever else is missing, and a
574
+ * pending verdict is already pending.
575
+ * @param {Array<{name: string}>} checks - Reported required rows.
576
+ * @param {string} baseRef - The PR's base branch.
577
+ * @param {object} contract - Tracker contract.
578
+ * @param {Function} gh - Runner.
579
+ * @param {object} known - Fields already known.
580
+ * @returns {Plan|null} A `checks-pending` stop, or null when nothing is unreported.
581
+ */
582
+ function holdUnreported(checks, baseRef, contract, gh, known) {
583
+ if (typeof baseRef !== "string" || baseRef === "")
584
+ throw new Error("the pull request read carries no base branch");
585
+ const required = requiredContexts(contract.repository, baseRef, gh);
586
+ const reported = new Set(checks.map(c => c.name));
587
+ const unreported = [...required].filter(context => !reported.has(context));
588
+ if (unreported.length === 0) return null;
589
+ return stop(
590
+ "checks-pending",
591
+ `${unreported.length} of ${required.size} required checks on ${baseRef} have not reported on this head: ${unreported.join(", ")}`,
592
+ known
593
+ );
594
+ }
595
+
540
596
  /**
541
597
  * Decide what one completed run means for its PR's work item. Reads only.
542
598
  * @param {{run: object, repository: string, contract: object, gh: Function}} input - Run and readers.
@@ -558,8 +614,18 @@ export function planRedispatch({ run, repository, contract, gh }) {
558
614
  if (!view.open)
559
615
  return stop("work-item-closed", "the work item is closed", known);
560
616
  const checks = readRequiredChecks(pr, contract.repository, gh);
617
+ // gh answers "no required checks reported" both when nothing is required
618
+ // and when nothing required has reported YET; only the ruleset tells them
619
+ // apart.
561
620
  if (checks === null)
562
- return stop("no-required-checks", "the PR has no required checks", known);
621
+ return (
622
+ holdUnreported([], binding.baseRef, contract, gh, known) ??
623
+ stop(
624
+ "no-required-checks",
625
+ `the rulesets on ${binding.baseRef} require no status checks`,
626
+ known
627
+ )
628
+ );
563
629
  const { verdict, failing } = classifyRequiredChecks(checks);
564
630
  const ctx = {
565
631
  ...known,
@@ -571,7 +637,11 @@ export function planRedispatch({ run, repository, contract, gh }) {
571
637
  events: () => readEvents(view.number, contract.repository, gh),
572
638
  };
573
639
  if (verdict === "fail") return planFailure(ctx);
574
- if (verdict === "pass") return planClear(ctx);
640
+ if (verdict === "pass")
641
+ return (
642
+ holdUnreported(checks, binding.baseRef, contract, gh, known) ??
643
+ planClear(ctx)
644
+ );
575
645
  return stop(
576
646
  "checks-pending",
577
647
  "no required check has failed and some have not finished",
@@ -0,0 +1,380 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Decide whether a dispatched work item goes back to its existing PR.
4
+ *
5
+ * The gap (CodySwannGT/lisa#4677): when a required check fails on an agent's
6
+ * PR, `lisa-ci-failure-redispatch` posts a bot-authored
7
+ * `<!-- [lisa-ci-failed] pr=<n> sha=<head> -->` marker on the work item and
8
+ * moves it back to the ready lane. Build intake reads that marker and sends the
9
+ * agent back to the PR, but the session manager dispatches through
10
+ * `lisa-implement` → `lisa-track`, which never looked — so a bounced item was
11
+ * rebuilt from scratch and could open a second PR for the same work.
12
+ *
13
+ * This script is the one place the trust rules live, so both dispatch paths
14
+ * (`lisa-track` Phase 3 and `lisa-github-build-intake` 3b) reach the same
15
+ * answer. It reads the item's comments — which the caller must do BEFORE it
16
+ * posts its own claim comment, a newer Lisa marker that would hide the signal —
17
+ * and, when the newest counted marker is an uncleared failure marker, verifies
18
+ * the PR it names. The marker patterns, the trusted-author predicate, the
19
+ * newest-marker predicate and the comment reader are imported from the
20
+ * producer script so the two cannot drift.
21
+ *
22
+ * Read-only: it never writes to the tracker. Every failed read routes to the
23
+ * normal path, because building again is recoverable and a wrong route is not.
24
+ *
25
+ * Repo-only: like its producer, it lives in this repository's `scripts/` and
26
+ * is NOT shipped to host projects; `lisa-track` runs it only when it exists.
27
+ * @module scripts/lisa-ci-rework-route
28
+ */
29
+ import { readFileSync } from "node:fs";
30
+ import process from "node:process";
31
+
32
+ import { invokedAsScript } from "../all/copy-overwrite/scripts/lib/invoked-as-script.mjs";
33
+ import {
34
+ soleWorkItem,
35
+ trackerContract,
36
+ workItemLines,
37
+ } from "../all/copy-overwrite/scripts/lisa-work-item.mjs";
38
+ import {
39
+ CLEARED_MARKER,
40
+ FAILURE_MARKER,
41
+ MARKER_AUTHORS,
42
+ LISA_MARKER,
43
+ isNewestLisaMarker,
44
+ liveGh,
45
+ readItemComments,
46
+ recordedGh,
47
+ trustedAuthor,
48
+ } from "./lisa-ci-failure-redispatch.mjs";
49
+
50
+ /**
51
+ * Bot-authored failure markers for one PR at which dispatch stops retrying and
52
+ * blocks for a person. Mirrors build intake 3b's "3 or more" loop bound: every
53
+ * bounce gives the item a fresh ready-lane entry, so without a bound a PR that
54
+ * keeps failing would be re-dispatched forever.
55
+ */
56
+ export const CI_LOOP_BOUND = 3;
57
+
58
+ /**
59
+ * The one decision the CLI prints. `ci-rework` carries the PR to drive;
60
+ * `blocked` is the loop bound; `implement` carries why the marker was ignored.
61
+ * @typedef {object} RouteDecision
62
+ * @property {"ci-rework"|"blocked"|"implement"} route - Where the work goes.
63
+ * @property {string} [reason] - Reason code for `implement` and `blocked`.
64
+ * @property {string} [detail] - Plain-language reason.
65
+ * @property {string} [item] - Canonical work item.
66
+ * @property {number} [pr] - The marker's pull request.
67
+ * @property {string} [sha] - The head the failure was observed on.
68
+ * @property {string} [headRefName] - The pull request's head branch.
69
+ * @property {string[]} [failingChecks] - Failing check names from the marker comment.
70
+ * @property {number} [markerCount] - Bot-authored failure markers for this PR.
71
+ */
72
+
73
+ /** The first line the producer writes on a failure comment. */
74
+ const FAILURE_LINE =
75
+ /^A required check failed on pull request #\d+ at commit [0-9a-f]{40}: (.+)\.$/mu;
76
+ const ITEM_NUMBER = /^[1-9]\d*$/u;
77
+ const ITEM_REF = /^([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)#([1-9]\d*)$/u;
78
+ const REPO = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u;
79
+ /**
80
+ * Dispatch-bookkeeping markers: the lifecycle claim, build intake's legacy
81
+ * claim, and the session manager's own notes (stop, release, worker failed,
82
+ * answer delivered). None of them says anything about the PR's checks.
83
+ */
84
+ const CLAIM_MARKERS =
85
+ /\[(?:lisa-tracker-claim|claude-build-intake|lisa-session-manager)\]/gu;
86
+
87
+ /**
88
+ * A decision to resolve and implement the item the normal way.
89
+ * @param {string} reason - Short reason code.
90
+ * @param {string} detail - Plain-language reason.
91
+ * @returns {RouteDecision} Decision.
92
+ */
93
+ function implement(reason, detail) {
94
+ return { route: "implement", reason, detail };
95
+ }
96
+
97
+ /**
98
+ * The failing check names on a failure comment's first line.
99
+ * @param {string} body - Comment body.
100
+ * @returns {string[]} Check names; empty when the line is not the producer's.
101
+ */
102
+ export function failingChecksFrom(body) {
103
+ const match = FAILURE_LINE.exec(String(body ?? ""));
104
+ return match === null ? [] : match[1].split(", ");
105
+ }
106
+
107
+ /**
108
+ * True when the comment carries a failure marker, whoever wrote it.
109
+ * @param {object} comment - Item comment.
110
+ * @returns {boolean} Whether it carries one.
111
+ */
112
+ function carriesFailure(comment) {
113
+ return FAILURE_MARKER.test(comment.body ?? "");
114
+ }
115
+
116
+ /**
117
+ * True when every Lisa marker the comment carries is a claim marker.
118
+ * @param {object} comment - Item comment.
119
+ * @returns {boolean} Whether it is a claim-only comment.
120
+ */
121
+ function claimOnly(comment) {
122
+ const body = String(comment.body ?? "");
123
+ return (
124
+ LISA_MARKER.test(body) &&
125
+ !LISA_MARKER.test(body.replaceAll(CLAIM_MARKERS, ""))
126
+ );
127
+ }
128
+
129
+ /**
130
+ * The producer's newest-marker test with claim comments left out. The
131
+ * session manager claims an item before its worker runs this helper, and a
132
+ * re-claim can post another claim comment, so a claim posted after the
133
+ * failure marker must not hide it: an uncleared marker on an open, bound PR
134
+ * still means the PR is red, whoever claimed the item since. Forged failure
135
+ * markers are already left out by the producer's predicate.
136
+ * @param {object[]} comments - Item comments, oldest first.
137
+ * @param {object} marker - The failure marker comment.
138
+ * @returns {boolean} Whether it is the newest counted marker.
139
+ */
140
+ function isNewestCountedMarker(comments, marker) {
141
+ return isNewestLisaMarker(
142
+ comments.filter(c => c === marker || !claimOnly(c)),
143
+ marker
144
+ );
145
+ }
146
+
147
+ /**
148
+ * Pick the failure marker that could count, or say why none does.
149
+ * @param {object[]} comments - Item comments, oldest first.
150
+ * @returns {{marker?: object, decision?: object}} The marker or a decision.
151
+ */
152
+ function judgeMarker(comments) {
153
+ const marker = comments
154
+ .filter(c => carriesFailure(c) && trustedAuthor(c))
155
+ .at(-1);
156
+ if (marker === undefined) {
157
+ const forged = comments.findLast(carriesFailure);
158
+ if (forged === undefined)
159
+ return {
160
+ decision: implement(
161
+ "no-marker",
162
+ "the item carries no [lisa-ci-failed] marker"
163
+ ),
164
+ };
165
+ return {
166
+ decision: implement(
167
+ "untrusted-author",
168
+ `the [lisa-ci-failed] marker was posted by ${forged.user?.login ?? "an unknown author"}, not ${MARKER_AUTHORS.join(" or ")}; ignored`
169
+ ),
170
+ };
171
+ }
172
+ if (!isNewestCountedMarker(comments, marker))
173
+ return {
174
+ decision: implement(
175
+ "not-newest",
176
+ "a newer Lisa marker (not a claim) was posted after the [lisa-ci-failed] marker, so it no longer describes the item"
177
+ ),
178
+ };
179
+ if (CLEARED_MARKER.test(marker.body))
180
+ return {
181
+ decision: implement(
182
+ "cleared",
183
+ "the [lisa-ci-failed] marker is cleared: a later run passed every required check"
184
+ ),
185
+ };
186
+ return { marker };
187
+ }
188
+
189
+ /**
190
+ * Check the named PR is open, same-repository and bound to this item.
191
+ * @param {object} view - `gh pr view` JSON.
192
+ * @param {string} item - Canonical `owner/repo#n`.
193
+ * @param {object} contract - Tracker contract scoped to the item's repository.
194
+ * @returns {RouteDecision|null} An implement decision, or null when the PR checks out.
195
+ */
196
+ function judgePull(view, item, contract) {
197
+ if (view.state !== "OPEN")
198
+ return implement(
199
+ "pull-request-not-open",
200
+ `the marker's pull request is ${view.state}`
201
+ );
202
+ if (view.isCrossRepository)
203
+ return implement(
204
+ "fork-pull-request",
205
+ "the marker's pull request comes from a fork"
206
+ );
207
+ let bound;
208
+ try {
209
+ bound = soleWorkItem(view.body ?? "", contract, "pull-request body");
210
+ } catch (error) {
211
+ // Exactly one declared value that still fails names something else (an
212
+ // item in another repository); zero or several declarations bind nothing.
213
+ const declared = new Set(workItemLines(view.body ?? ""));
214
+ const reason =
215
+ declared.size === 1 ? "other-work-item" : "unbound-pull-request";
216
+ return implement(reason, String(error.message));
217
+ }
218
+ if (bound.toLowerCase() !== item.toLowerCase())
219
+ return implement(
220
+ "other-work-item",
221
+ `the marker's pull request is bound to ${bound}, not ${item}`
222
+ );
223
+ return null;
224
+ }
225
+
226
+ /**
227
+ * Read one gh JSON answer, or throw naming the call.
228
+ * @param {Function} gh - Runner.
229
+ * @param {string[]} args - Arguments.
230
+ * @returns {any} Parsed stdout.
231
+ */
232
+ function readJson(gh, args) {
233
+ const result = gh(args);
234
+ if (!result.ok)
235
+ throw new Error(`gh ${args.join(" ")} failed: ${result.stderr}`);
236
+ return JSON.parse(result.stdout);
237
+ }
238
+
239
+ /**
240
+ * Route a counted marker: verify its PR, then apply the loop bound.
241
+ * @param {{marker: object, comments: object[], item: string, repository: string, contract: object, gh: Function}} ctx - Context.
242
+ * @returns {RouteDecision} Decision.
243
+ */
244
+ function routeMarker({ marker, comments, item, repository, contract, gh }) {
245
+ const [, prText, sha] = FAILURE_MARKER.exec(marker.body);
246
+ const pr = Number(prText);
247
+ const view = readJson(gh, [
248
+ "pr",
249
+ "view",
250
+ prText,
251
+ "--repo",
252
+ repository,
253
+ "--json",
254
+ "state,isCrossRepository,body,headRefName",
255
+ ]);
256
+ const refused = judgePull(view, item, { ...contract, repository });
257
+ if (refused) return refused;
258
+ const markerCount = comments.filter(
259
+ c =>
260
+ trustedAuthor(c) && Number(FAILURE_MARKER.exec(c.body ?? "")?.[1]) === pr
261
+ ).length;
262
+ const failingChecks = failingChecksFrom(marker.body);
263
+ if (markerCount >= CI_LOOP_BOUND)
264
+ return {
265
+ route: "blocked",
266
+ reason: "ci-loop-bound",
267
+ detail: `pull request #${pr} has failed its required checks ${markerCount} times; stop retrying and ask a person`,
268
+ item,
269
+ pr,
270
+ sha,
271
+ failingChecks,
272
+ markerCount,
273
+ };
274
+ return {
275
+ route: "ci-rework",
276
+ item,
277
+ pr,
278
+ sha,
279
+ headRefName: view.headRefName,
280
+ failingChecks,
281
+ markerCount,
282
+ };
283
+ }
284
+
285
+ /**
286
+ * Decide the dispatch route for one GitHub work item. Reads only.
287
+ * @param {{item: string, contract: object, gh: Function, repository?: string}} input - Item number, contract, runner.
288
+ * @returns {RouteDecision} `ci-rework`, `blocked`, or `implement` decision.
289
+ */
290
+ export function decideRoute({ item, contract, gh, repository }) {
291
+ if (contract?.provider !== "github")
292
+ return implement(
293
+ "tracker-not-github",
294
+ "only the GitHub tracker carries [lisa-ci-failed] markers"
295
+ );
296
+ const repo = repository ?? contract.repository;
297
+ const ref = `${repo}#${item}`;
298
+ try {
299
+ const comments = readItemComments(String(item), repo, gh);
300
+ const { marker, decision } = judgeMarker(comments);
301
+ if (decision) return decision;
302
+ return routeMarker({
303
+ marker,
304
+ comments,
305
+ item: ref,
306
+ repository: repo,
307
+ contract,
308
+ gh,
309
+ });
310
+ } catch (error) {
311
+ return implement(
312
+ "read-failed",
313
+ `could not read the item or its pull request: ${error.message}`
314
+ );
315
+ }
316
+ }
317
+
318
+ /**
319
+ * Decide the route from a recorded fixture: the gh answers it recorded.
320
+ * @param {{gh: object}} fixture - Recorded fixture.
321
+ * @param {string} item - Item number.
322
+ * @param {object} contract - Tracker contract.
323
+ * @returns {RouteDecision} Decision.
324
+ */
325
+ export function routeFromFixture(fixture, item, contract) {
326
+ return decideRoute({ item, contract, gh: recordedGh(fixture.gh) });
327
+ }
328
+
329
+ /**
330
+ * Parse CLI flags.
331
+ * @param {string[]} argv - Arguments.
332
+ * @returns {{item: string, repository?: string, payload?: string}} Options.
333
+ */
334
+ function parseArgs(argv) {
335
+ const flags = {};
336
+ for (let i = 0; i < argv.length; i += 2) {
337
+ const [flag, value] = [argv[i], argv[i + 1]];
338
+ if (!["--item", "--repo", "--payload"].includes(flag))
339
+ throw new Error(`unknown argument: ${flag}`);
340
+ if (value === undefined) throw new Error(`${flag} needs a value`);
341
+ flags[flag.slice(2)] = value;
342
+ }
343
+ const ref = ITEM_REF.exec(flags.item ?? "");
344
+ if (ref === null && !ITEM_NUMBER.test(flags.item ?? ""))
345
+ throw new Error("pass --item <n> or --item <owner>/<repo>#<n>");
346
+ if (flags.repo !== undefined && !REPO.test(flags.repo))
347
+ throw new Error(`--repo must be <owner>/<repo>, got '${flags.repo}'`);
348
+ if (ref && flags.repo && ref[1].toLowerCase() !== flags.repo.toLowerCase())
349
+ throw new Error(`--item ${flags.item} is not in --repo ${flags.repo}`);
350
+ return {
351
+ item: ref ? ref[2] : flags.item,
352
+ repository: flags.repo ?? ref?.[1],
353
+ payload: flags.payload,
354
+ };
355
+ }
356
+
357
+ /**
358
+ * CLI entry: print one JSON decision line.
359
+ * @param {string[]} argv - Arguments.
360
+ * @param {{gh?: Function, write?: Function, contract?: object}} [deps] - Injectables.
361
+ * @returns {number} Exit code: 0 decided (any route), 2 bad usage or configuration.
362
+ */
363
+ export function main(argv, deps = {}) {
364
+ const write = deps.write ?? (line => process.stdout.write(`${line}\n`));
365
+ try {
366
+ const options = parseArgs(argv);
367
+ const contract = deps.contract ?? trackerContract();
368
+ const gh = options.payload
369
+ ? recordedGh(JSON.parse(readFileSync(options.payload, "utf8")).gh)
370
+ : (deps.gh ?? liveGh);
371
+ write(JSON.stringify(decideRoute({ ...options, contract, gh })));
372
+ return 0;
373
+ } catch (error) {
374
+ write(`lisa-ci-rework-route: ${error.message}`);
375
+ return 2;
376
+ }
377
+ }
378
+
379
+ if (invokedAsScript(import.meta.url))
380
+ process.exitCode = main(process.argv.slice(2));