@codyswann/lisa 4.91.0 → 4.92.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 (88) 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 +30 -2
  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 +6 -0
  9. package/plugins/lisa/rules/reference/rejection-detection.md +12 -0
  10. package/plugins/lisa/skills/lisa-github-build-intake/SKILL.md +6 -0
  11. package/plugins/lisa-agy/plugin.json +1 -1
  12. package/plugins/lisa-agy/skills/lisa-github-build-intake/SKILL.md +6 -0
  13. package/plugins/lisa-cdk/.claude-plugin/plugin.json +1 -1
  14. package/plugins/lisa-cdk/.codex-plugin/plugin.json +1 -1
  15. package/plugins/lisa-cdk-agy/plugin.json +1 -1
  16. package/plugins/lisa-cdk-copilot/.claude-plugin/plugin.json +1 -1
  17. package/plugins/lisa-cdk-cursor/.claude-plugin/plugin.json +1 -1
  18. package/plugins/lisa-cdk-devin/.claude-plugin/plugin.json +1 -1
  19. package/plugins/lisa-cdk-devin/.devin-plugin/plugin.json +1 -1
  20. package/plugins/lisa-copilot/.claude-plugin/plugin.json +1 -1
  21. package/plugins/lisa-copilot/rules/reference/rejection-detection.md +12 -0
  22. package/plugins/lisa-copilot/skills/lisa-github-build-intake/SKILL.md +6 -0
  23. package/plugins/lisa-cursor/.claude-plugin/plugin.json +1 -1
  24. package/plugins/lisa-cursor/rules/rejection-detection-reference.mdc +12 -0
  25. package/plugins/lisa-cursor/skills/lisa-github-build-intake/SKILL.md +6 -0
  26. package/plugins/lisa-devin/.claude-plugin/plugin.json +1 -1
  27. package/plugins/lisa-devin/.devin-plugin/plugin.json +1 -1
  28. package/plugins/lisa-devin/rules/reference/rejection-detection.md +12 -0
  29. package/plugins/lisa-devin/skills/lisa-github-build-intake/SKILL.md +6 -0
  30. package/plugins/lisa-expo/.claude-plugin/plugin.json +1 -1
  31. package/plugins/lisa-expo/.codex-plugin/plugin.json +1 -1
  32. package/plugins/lisa-expo-agy/plugin.json +1 -1
  33. package/plugins/lisa-expo-copilot/.claude-plugin/plugin.json +1 -1
  34. package/plugins/lisa-expo-cursor/.claude-plugin/plugin.json +1 -1
  35. package/plugins/lisa-expo-devin/.claude-plugin/plugin.json +1 -1
  36. package/plugins/lisa-expo-devin/.devin-plugin/plugin.json +1 -1
  37. package/plugins/lisa-harper-fabric/.claude-plugin/plugin.json +1 -1
  38. package/plugins/lisa-harper-fabric/.codex-plugin/plugin.json +1 -1
  39. package/plugins/lisa-harper-fabric-agy/plugin.json +1 -1
  40. package/plugins/lisa-harper-fabric-copilot/.claude-plugin/plugin.json +1 -1
  41. package/plugins/lisa-harper-fabric-cursor/.claude-plugin/plugin.json +1 -1
  42. package/plugins/lisa-harper-fabric-devin/.claude-plugin/plugin.json +1 -1
  43. package/plugins/lisa-harper-fabric-devin/.devin-plugin/plugin.json +1 -1
  44. package/plugins/lisa-nestjs/.claude-plugin/plugin.json +1 -1
  45. package/plugins/lisa-nestjs/.codex-plugin/plugin.json +1 -1
  46. package/plugins/lisa-nestjs-agy/plugin.json +1 -1
  47. package/plugins/lisa-nestjs-copilot/.claude-plugin/plugin.json +1 -1
  48. package/plugins/lisa-nestjs-cursor/.claude-plugin/plugin.json +1 -1
  49. package/plugins/lisa-nestjs-devin/.claude-plugin/plugin.json +1 -1
  50. package/plugins/lisa-nestjs-devin/.devin-plugin/plugin.json +1 -1
  51. package/plugins/lisa-openclaw/.claude-plugin/plugin.json +1 -1
  52. package/plugins/lisa-openclaw/.codex-plugin/plugin.json +1 -1
  53. package/plugins/lisa-openclaw-agy/plugin.json +1 -1
  54. package/plugins/lisa-openclaw-copilot/.claude-plugin/plugin.json +1 -1
  55. package/plugins/lisa-openclaw-cursor/.claude-plugin/plugin.json +1 -1
  56. package/plugins/lisa-openclaw-devin/.claude-plugin/plugin.json +1 -1
  57. package/plugins/lisa-openclaw-devin/.devin-plugin/plugin.json +1 -1
  58. package/plugins/lisa-phaser/.claude-plugin/plugin.json +1 -1
  59. package/plugins/lisa-phaser/.codex-plugin/plugin.json +1 -1
  60. package/plugins/lisa-phaser-agy/plugin.json +1 -1
  61. package/plugins/lisa-phaser-copilot/.claude-plugin/plugin.json +1 -1
  62. package/plugins/lisa-phaser-cursor/.claude-plugin/plugin.json +1 -1
  63. package/plugins/lisa-phaser-devin/.claude-plugin/plugin.json +1 -1
  64. package/plugins/lisa-phaser-devin/.devin-plugin/plugin.json +1 -1
  65. package/plugins/lisa-rails/.claude-plugin/plugin.json +1 -1
  66. package/plugins/lisa-rails/.codex-plugin/plugin.json +1 -1
  67. package/plugins/lisa-rails-agy/plugin.json +1 -1
  68. package/plugins/lisa-rails-copilot/.claude-plugin/plugin.json +1 -1
  69. package/plugins/lisa-rails-cursor/.claude-plugin/plugin.json +1 -1
  70. package/plugins/lisa-rails-devin/.claude-plugin/plugin.json +1 -1
  71. package/plugins/lisa-rails-devin/.devin-plugin/plugin.json +1 -1
  72. package/plugins/lisa-typescript/.claude-plugin/plugin.json +1 -1
  73. package/plugins/lisa-typescript/.codex-plugin/plugin.json +1 -1
  74. package/plugins/lisa-typescript-agy/plugin.json +1 -1
  75. package/plugins/lisa-typescript-copilot/.claude-plugin/plugin.json +1 -1
  76. package/plugins/lisa-typescript-cursor/.claude-plugin/plugin.json +1 -1
  77. package/plugins/lisa-typescript-devin/.claude-plugin/plugin.json +1 -1
  78. package/plugins/lisa-typescript-devin/.devin-plugin/plugin.json +1 -1
  79. package/plugins/lisa-wiki/.claude-plugin/plugin.json +1 -1
  80. package/plugins/lisa-wiki/.codex-plugin/plugin.json +1 -1
  81. package/plugins/lisa-wiki-agy/plugin.json +1 -1
  82. package/plugins/lisa-wiki-copilot/.claude-plugin/plugin.json +1 -1
  83. package/plugins/lisa-wiki-cursor/.claude-plugin/plugin.json +1 -1
  84. package/plugins/lisa-wiki-devin/.claude-plugin/plugin.json +1 -1
  85. package/plugins/lisa-wiki-devin/.devin-plugin/plugin.json +1 -1
  86. package/plugins/src/base/rules/reference/rejection-detection.md +12 -0
  87. package/plugins/src/base/skills/lisa-github-build-intake/SKILL.md +6 -0
  88. package/scripts/lisa-ci-failure-redispatch.mjs +763 -0
@@ -0,0 +1,763 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Wake the owning agent when a required check fails on its pull request.
4
+ *
5
+ * The gap (CodySwannGT/lisa#4607): when a required check fails on an agent's
6
+ * PR, nothing tells the agent. The work item sits in the claimed lane, the PR
7
+ * stalls, and a human has to notice. Agent work is not complete until CI is
8
+ * green, so a failed required check must put the item back where build intake
9
+ * looks — the ready lane — with a marker that tells intake to send the agent
10
+ * back to the EXISTING PR rather than start again.
11
+ *
12
+ * Decide, then act. `planRedispatch` is a pure read over an injectable `gh`
13
+ * runner and returns the writes it would make; `applyPlan` performs them. A
14
+ * recorded fixture serves the reads for tests and `--dry-run` demonstrations
15
+ * and refuses every write, so a fixture can never touch the tracker.
16
+ *
17
+ * What counts:
18
+ * - A required check FAILED when its `gh pr checks` bucket is `fail`. A
19
+ * `cancel` bucket is not a failure — a cancelled run is usually superseded by
20
+ * a newer push or a manual re-run, and bouncing an item for it would
21
+ * re-dispatch an agent for a failure nobody observed. It is not a pass
22
+ * either, so it holds the clear path until it resolves.
23
+ * - Every required check PASSED when each bucket is `pass` or `skipping`.
24
+ * - Anything else is still running: no write.
25
+ *
26
+ * Writes need positive evidence. A run for a superseded head, a fork PR, a PR
27
+ * with no or a foreign `Work-Item:`, a closed item, or an item outside the
28
+ * claimed lane all end with no write.
29
+ *
30
+ * Repo-only: this is the Lisa monorepo's own automation and is deliberately
31
+ * NOT shipped to host projects (CodySwannGT/lisa#4607, Out of Scope).
32
+ * @module scripts/lisa-ci-failure-redispatch
33
+ */
34
+ import { spawnSync } from "node:child_process";
35
+ import { readFileSync } from "node:fs";
36
+ import process from "node:process";
37
+
38
+ import { invokedAsScript } from "../all/copy-overwrite/scripts/lib/invoked-as-script.mjs";
39
+ import {
40
+ soleWorkItem,
41
+ trackerContract,
42
+ } from "../all/copy-overwrite/scripts/lisa-work-item.mjs";
43
+
44
+ const SHA = /^[0-9a-f]{40}$/u;
45
+ const FAILURE_MARKER =
46
+ /<!-- \[lisa-ci-failed\] pr=(\d+) sha=([0-9a-f]{40}) -->/u;
47
+ const CLEARED_MARKER = /<!-- \[lisa-ci-cleared\] run=\d+ -->/u;
48
+ /** Any Lisa lifecycle marker — the claim, attempt, and CI markers alike. */
49
+ const LISA_MARKER = /\[(?:lisa-[a-z0-9-]+|claude-build-intake)\]/u;
50
+ const NO_REQUIRED = /no (?:required )?checks reported/iu;
51
+
52
+ /**
53
+ * The only comment authors whose `[lisa-ci-failed]` / `[lisa-ci-cleared]`
54
+ * markers count. Anyone who can comment on an issue can type a marker; a
55
+ * forged one must neither suppress a real re-dispatch nor make the workflow
56
+ * edit an outsider's comment and restore a lane. The workflow posts with
57
+ * `GITHUB_TOKEN`, whose author is `github-actions[bot]`.
58
+ */
59
+ export const MARKER_AUTHORS = Object.freeze(["github-actions[bot]"]);
60
+ /**
61
+ * One write a plan would make.
62
+ * @typedef {object} PlannedAction
63
+ * @property {string} kind - `comment`, `relabel`, or `edit-comment`.
64
+ * @property {string} [item] - Canonical work item, for `comment` and `relabel`.
65
+ * @property {string} [body] - Comment body, for `comment` and `edit-comment`.
66
+ * @property {string} [remove] - Lane label to remove, for `relabel`.
67
+ * @property {string} [add] - Lane label to add, for `relabel`.
68
+ * @property {number} [commentId] - Numeric comment id, for `edit-comment`.
69
+ */
70
+
71
+ /**
72
+ * The decision for one completed run.
73
+ * @typedef {object} Plan
74
+ * @property {string} outcome - Outcome name, e.g. `redispatch` or `non-agent-pr`.
75
+ * @property {string} reason - Plain-language reason.
76
+ * @property {PlannedAction[]} actions - Writes, in order; empty for a no-op.
77
+ * @property {number} [pr] - Resolved PR number.
78
+ * @property {string} [sha] - Run head SHA.
79
+ * @property {string} [item] - Canonical work item.
80
+ * @property {string} [repository] - Repository the writes target.
81
+ * @property {number} [runId] - Actions run id.
82
+ */
83
+
84
+ /** The three writes a plan can contain. */
85
+ const ACTION = Object.freeze({
86
+ comment: "comment",
87
+ relabel: "relabel",
88
+ editComment: "edit-comment",
89
+ });
90
+
91
+ /**
92
+ * The machine marker a failure comment carries, one per PR head.
93
+ * @param {number} pr - Pull request number.
94
+ * @param {string} sha - Head commit the failure was observed on.
95
+ * @returns {string} The HTML-comment marker.
96
+ */
97
+ export function failureMarker(pr, sha) {
98
+ return `<!-- [lisa-ci-failed] pr=${pr} sha=${sha} -->`;
99
+ }
100
+
101
+ /**
102
+ * Judge the PR's required checks.
103
+ * @param {Array<{name: string, bucket: string}>} checks - `gh pr checks --required` rows.
104
+ * @returns {{verdict: "fail"|"pass"|"pending", failing: string[]}} The judgment.
105
+ */
106
+ export function classifyRequiredChecks(checks) {
107
+ const failing = checks.filter(c => c.bucket === "fail").map(c => c.name);
108
+ if (failing.length > 0) return { verdict: "fail", failing };
109
+ const settled = checks.every(c => ["pass", "skipping"].includes(c.bucket));
110
+ return { verdict: settled ? "pass" : "pending", failing: [] };
111
+ }
112
+
113
+ /**
114
+ * Serve recorded `gh` answers keyed by their argv; refuse anything else.
115
+ * @param {Record<string, {stdout?: unknown, ok?: boolean, stderr?: string}>} recordings - Recorded answers.
116
+ * @returns {Function} A gh runner that never reaches the network.
117
+ */
118
+ export function recordedGh(recordings) {
119
+ return (args, options = {}) => {
120
+ if (options.write)
121
+ throw new Error(
122
+ `refusing to write through a recorded fixture: gh ${args.join(" ")}`
123
+ );
124
+ const key = args.join(" ");
125
+ if (!Object.hasOwn(recordings, key))
126
+ throw new Error(`gh call not recorded in the fixture: gh ${key}`);
127
+ const { stdout = "", ok = true, stderr = "" } = recordings[key];
128
+ const text = typeof stdout === "string" ? stdout : JSON.stringify(stdout);
129
+ return { ok, stdout: text, stderr };
130
+ };
131
+ }
132
+
133
+ /**
134
+ * The live gh runner. Never throws on a non-zero exit; callers judge `ok`.
135
+ * @param {string[]} args - Arguments to `gh`.
136
+ * @param {{input?: string}} [options] - Optional stdin.
137
+ * @returns {{ok: boolean, stdout: string, stderr: string}} Outcome.
138
+ */
139
+ export function liveGh(args, options = {}) {
140
+ const result = spawnSync("gh", args, {
141
+ encoding: "utf8",
142
+ input: options.input,
143
+ timeout: 60_000,
144
+ maxBuffer: 64 * 1024 * 1024,
145
+ });
146
+ const stderr = result.error
147
+ ? String(result.error.message)
148
+ : (result.stderr ?? "");
149
+ return { ok: result.status === 0, stdout: result.stdout ?? "", stderr };
150
+ }
151
+
152
+ /**
153
+ * Run a gh read and parse its JSON, or throw naming the call.
154
+ * @param {Function} gh - Runner.
155
+ * @param {string[]} args - Arguments.
156
+ * @returns {any} Parsed stdout.
157
+ */
158
+ function readJson(gh, args) {
159
+ const result = gh(args);
160
+ if (!result.ok)
161
+ throw new Error(`gh ${args.join(" ")} failed: ${result.stderr}`);
162
+ return JSON.parse(result.stdout);
163
+ }
164
+
165
+ /**
166
+ * Candidate PR numbers for the run's head.
167
+ * @param {object} run - `workflow_run` object.
168
+ * @param {string} repo - Repository.
169
+ * @param {Function} gh - Runner.
170
+ * @returns {number[]} Distinct PR numbers.
171
+ */
172
+ function candidatePullRequests(run, repo, gh) {
173
+ const listed = (run.pull_requests ?? []).map(pr => pr.number);
174
+ if (listed.length > 0) return [...new Set(listed)];
175
+ const found = readJson(gh, [
176
+ "pr",
177
+ "list",
178
+ "--repo",
179
+ repo,
180
+ "--state",
181
+ "open",
182
+ "--search",
183
+ run.head_sha,
184
+ "--json",
185
+ "number,headRefOid",
186
+ ]);
187
+ return found
188
+ .filter(pr => pr.headRefOid === run.head_sha)
189
+ .map(pr => pr.number);
190
+ }
191
+
192
+ /**
193
+ * Resolve the run to one open, same-repository PR at the run's head and its work item.
194
+ * @param {object} run - `workflow_run` object.
195
+ * @param {object} contract - Tracker contract.
196
+ * @param {Function} gh - Runner.
197
+ * @returns {{stop?: object, pr?: number, item?: string}} A stop decision or the binding.
198
+ */
199
+ function resolveBinding(run, contract, gh) {
200
+ const repo = contract.repository;
201
+ const prs = candidatePullRequests(run, repo, gh);
202
+ if (prs.length === 0)
203
+ return {
204
+ stop: stop("no-pull-request", "no open PR carries this run's head"),
205
+ };
206
+ if (prs.length > 1)
207
+ return {
208
+ stop: stop(
209
+ "ambiguous-pull-request",
210
+ `several PRs carry this head: ${prs.join(", ")}`
211
+ ),
212
+ };
213
+ const pr = readJson(gh, [
214
+ "pr",
215
+ "view",
216
+ String(prs[0]),
217
+ "--repo",
218
+ repo,
219
+ "--json",
220
+ "number,state,body,headRefOid,isCrossRepository",
221
+ ]);
222
+ const base = { pr: pr.number };
223
+ if (pr.state !== "OPEN")
224
+ return { stop: stop("pull-request-not-open", `PR is ${pr.state}`, base) };
225
+ if (pr.headRefOid !== run.head_sha)
226
+ return {
227
+ stop: stop(
228
+ "superseded-head",
229
+ `the PR head is now ${pr.headRefOid}`,
230
+ base
231
+ ),
232
+ };
233
+ if (pr.isCrossRepository)
234
+ return {
235
+ stop: stop("non-agent-pr", "a fork PR is never an agent PR", base),
236
+ };
237
+ try {
238
+ return {
239
+ pr: pr.number,
240
+ item: soleWorkItem(pr.body ?? "", contract, "pull-request body"),
241
+ };
242
+ } catch (error) {
243
+ return { stop: stop("non-agent-pr", String(error.message), base) };
244
+ }
245
+ }
246
+
247
+ /**
248
+ * A no-write decision.
249
+ * @param {string} outcome - Outcome name.
250
+ * @param {string} reason - Plain-language reason.
251
+ * @param {object} [extra] - Fields already known.
252
+ * @returns {Plan} Plan with no actions.
253
+ */
254
+ function stop(outcome, reason, extra = {}) {
255
+ return { ...extra, outcome, reason, actions: [] };
256
+ }
257
+
258
+ /**
259
+ * Read the item's state, labels and comments, oldest comment first.
260
+ * @param {string} item - Canonical `owner/repo#n`.
261
+ * @param {string} repo - Repository.
262
+ * @param {Function} gh - Runner.
263
+ * @returns {{number: string, open: boolean, labels: string[], comments: object[]}} Item view.
264
+ */
265
+ function readItem(item, repo, gh) {
266
+ const number = item.slice(item.lastIndexOf("#") + 1);
267
+ const view = readJson(gh, [
268
+ "issue",
269
+ "view",
270
+ number,
271
+ "--repo",
272
+ repo,
273
+ "--json",
274
+ "state,labels",
275
+ ]);
276
+ const pages = readJson(gh, [
277
+ "api",
278
+ `repos/${repo}/issues/${number}/comments`,
279
+ "--paginate",
280
+ "--slurp",
281
+ ]);
282
+ const comments = pages
283
+ .flat()
284
+ .toSorted((a, b) =>
285
+ String(a.created_at).localeCompare(String(b.created_at))
286
+ );
287
+ return {
288
+ number,
289
+ open: view.state === "OPEN",
290
+ labels: view.labels.map(l => l.name),
291
+ comments,
292
+ };
293
+ }
294
+
295
+ /**
296
+ * Read the PR's required checks; `null` when the PR has none.
297
+ * @param {number} pr - PR number.
298
+ * @param {string} repo - Repository.
299
+ * @param {Function} gh - Runner.
300
+ * @returns {Array<object>|null} Rows, or null.
301
+ */
302
+ function readRequiredChecks(pr, repo, gh) {
303
+ const args = [
304
+ "pr",
305
+ "checks",
306
+ String(pr),
307
+ "--repo",
308
+ repo,
309
+ "--required",
310
+ "--json",
311
+ "name,state,bucket",
312
+ ];
313
+ const result = gh(args);
314
+ // `gh pr checks` exits non-zero when a check failed or is pending, yet still
315
+ // prints the rows; only an unparseable answer is a failed read.
316
+ try {
317
+ const rows = JSON.parse(result.stdout);
318
+ if (Array.isArray(rows)) return rows;
319
+ } catch {
320
+ // fall through
321
+ }
322
+ if (NO_REQUIRED.test(result.stderr)) return null;
323
+ throw new Error(`gh ${args.join(" ")} failed: ${result.stderr}`);
324
+ }
325
+
326
+ /**
327
+ * The marker comment for this PR head, if any.
328
+ * @param {object[]} comments - Item comments.
329
+ * @param {number} pr - PR number.
330
+ * @param {string} sha - Head SHA.
331
+ * @returns {object|undefined} The comment.
332
+ */
333
+ function markerComment(comments, pr, sha) {
334
+ return comments.find(c => {
335
+ if (!trustedAuthor(c)) return false;
336
+ const match = FAILURE_MARKER.exec(c.body ?? "");
337
+ return match !== null && Number(match[1]) === pr && match[2] === sha;
338
+ });
339
+ }
340
+
341
+ /**
342
+ * The PR number a comment's failure marker names, if it carries one.
343
+ * @param {object} comment - Item comment.
344
+ * @returns {number|null} PR number.
345
+ */
346
+ function markerPr(comment) {
347
+ if (!trustedAuthor(comment)) return null;
348
+ const match = FAILURE_MARKER.exec(comment.body ?? "");
349
+ return match === null ? null : Number(match[1]);
350
+ }
351
+
352
+ /**
353
+ * True when the comment was posted by an identity whose markers count.
354
+ * @param {object} comment - Item comment.
355
+ * @returns {boolean} Whether its markers are trusted.
356
+ */
357
+ function trustedAuthor(comment) {
358
+ return MARKER_AUTHORS.includes(comment.user?.login ?? "");
359
+ }
360
+
361
+ /**
362
+ * True when the item gained `lane` after `comment` was posted. Comments alone
363
+ * cannot say a claim happened: a claim path that posts its claim comment once
364
+ * per item leaves no newer comment when it re-claims, but the label event is
365
+ * always recorded.
366
+ * @param {object[]} events - Issue events.
367
+ * @param {object} comment - The marker comment.
368
+ * @param {string} lane - Lane label.
369
+ * @returns {boolean} Whether a later `labeled` event exists.
370
+ */
371
+ function laneGainedSince(events, comment, lane) {
372
+ return events.some(
373
+ e =>
374
+ e.event === "labeled" &&
375
+ e.label?.name === lane &&
376
+ String(e.created_at) > String(comment.created_at)
377
+ );
378
+ }
379
+
380
+ /**
381
+ * Read the item's issue events (label history).
382
+ * @param {string} number - Issue number.
383
+ * @param {string} repo - Repository.
384
+ * @param {Function} gh - Runner.
385
+ * @returns {object[]} Events.
386
+ */
387
+ function readEvents(number, repo, gh) {
388
+ return readJson(gh, [
389
+ "api",
390
+ `repos/${repo}/issues/${number}/events`,
391
+ "--paginate",
392
+ "--slurp",
393
+ ]).flat();
394
+ }
395
+
396
+ /**
397
+ * True when `comment` is the newest comment carrying any Lisa marker — nothing
398
+ * (a claim, an attempt, a hold) has happened to the item since it was posted.
399
+ * @param {object[]} comments - Item comments, oldest first.
400
+ * @param {object} comment - The marker comment.
401
+ * @returns {boolean} Whether it is the newest.
402
+ */
403
+ function isNewestLisaMarker(comments, comment) {
404
+ // A forged failure marker counts for nothing, including as "something newer".
405
+ const marked = comments.filter(
406
+ c =>
407
+ LISA_MARKER.test(c.body ?? "") &&
408
+ (trustedAuthor(c) || !FAILURE_MARKER.test(c.body ?? ""))
409
+ );
410
+ return marked.at(-1)?.id === comment.id;
411
+ }
412
+
413
+ /**
414
+ * Plan the failure path.
415
+ * @param {object} ctx - Resolved context.
416
+ * @returns {Plan} Plan.
417
+ */
418
+ function planFailure(ctx) {
419
+ const { item, view, pr, sha, failing, lanes } = ctx;
420
+ const known = { pr, sha, item };
421
+ const relabel = {
422
+ kind: ACTION.relabel,
423
+ item,
424
+ remove: lanes.claimed,
425
+ add: lanes.ready,
426
+ };
427
+ const claimed = view.labels.includes(lanes.claimed);
428
+ const existing = markerComment(view.comments, pr, sha);
429
+ if (existing) {
430
+ if (
431
+ claimed &&
432
+ !CLEARED_MARKER.test(existing.body) &&
433
+ isNewestLisaMarker(view.comments, existing) &&
434
+ !laneGainedSince(ctx.events(), existing, lanes.claimed)
435
+ )
436
+ return {
437
+ ...known,
438
+ outcome: "relabel-repair",
439
+ reason: "marker posted but the lane move did not land",
440
+ actions: [relabel],
441
+ };
442
+ return stop(
443
+ "already-reported",
444
+ "this PR head already has a [lisa-ci-failed] marker",
445
+ known
446
+ );
447
+ }
448
+ if (!claimed)
449
+ return stop(
450
+ "not-claimed",
451
+ `the item is not in the claimed lane (${lanes.claimed})`,
452
+ known
453
+ );
454
+ const body = [
455
+ `A required check failed on pull request #${pr} at commit ${sha}: ${failing.join(", ")}.`,
456
+ "",
457
+ `Lisa moved this item from \`${lanes.claimed}\` back to \`${lanes.ready}\` so build intake sends the owning agent back to fix the existing pull request. The work is not complete until every required check passes.`,
458
+ "",
459
+ failureMarker(pr, sha),
460
+ ].join("\n");
461
+ return {
462
+ ...known,
463
+ outcome: "redispatch",
464
+ reason: "a required check failed",
465
+ actions: [{ kind: ACTION.comment, item, body }, relabel],
466
+ };
467
+ }
468
+
469
+ /**
470
+ * Plan the clear path.
471
+ * @param {object} ctx - Resolved context.
472
+ * @returns {Plan} Plan.
473
+ */
474
+ function planClear(ctx) {
475
+ const { item, view, pr, sha, runId, lanes } = ctx;
476
+ const known = { pr, sha, item };
477
+ // A green head clears every uncleared marker on this PR, not only the one
478
+ // naming this head: once the agent pushes a fix, the failed head is
479
+ // superseded and no run will ever pass on it, so a marker scoped to it alone
480
+ // would stay uncleared — and hold the item "not complete" — forever.
481
+ const open = view.comments.filter(
482
+ c => markerPr(c) === pr && !CLEARED_MARKER.test(c.body)
483
+ );
484
+ if (open.length === 0) {
485
+ if (markerComment(view.comments, pr, sha))
486
+ return stop(
487
+ "already-cleared",
488
+ "the marker for this head is already cleared",
489
+ known
490
+ );
491
+ return stop(
492
+ "nothing-to-clear",
493
+ "every required check passed and no uncleared marker names this PR",
494
+ known
495
+ );
496
+ }
497
+ const actions = open.map(c => ({
498
+ kind: ACTION.editComment,
499
+ commentId: c.id,
500
+ body: `${c.body}\n\nEvery required check now passes on ${sha}; cleared by run ${runId}.\n<!-- [lisa-ci-cleared] run=${runId} -->`,
501
+ }));
502
+ const unclaimed =
503
+ view.labels.includes(lanes.ready) && !view.labels.includes(lanes.claimed);
504
+ const newest = open.find(c => isNewestLisaMarker(view.comments, c));
505
+ if (
506
+ unclaimed &&
507
+ newest !== undefined &&
508
+ !laneGainedSince(ctx.events(), newest, lanes.claimed)
509
+ ) {
510
+ actions.push({
511
+ kind: ACTION.relabel,
512
+ item,
513
+ remove: lanes.ready,
514
+ add: lanes.claimed,
515
+ });
516
+ return {
517
+ ...known,
518
+ outcome: "clear-and-restore",
519
+ reason: "checks passed while the marker left the item unclaimed",
520
+ actions,
521
+ };
522
+ }
523
+ return {
524
+ ...known,
525
+ outcome: "cleared",
526
+ reason: "every required check passed for the marked head",
527
+ actions,
528
+ };
529
+ }
530
+
531
+ /**
532
+ * Decide what one completed run means for its PR's work item. Reads only.
533
+ * @param {{run: object, repository: string, contract: object, gh: Function}} input - Run and readers.
534
+ * @returns {Plan} What to write, and why.
535
+ */
536
+ export function planRedispatch({ run, repository, contract, gh }) {
537
+ if (!SHA.test(run?.head_sha ?? ""))
538
+ throw new Error("the run payload carries no concrete head SHA");
539
+ if (String(repository).toLowerCase() !== contract.repository.toLowerCase())
540
+ return stop(
541
+ "foreign-repository",
542
+ `run belongs to ${repository}, not ${contract.repository}`
543
+ );
544
+ const binding = resolveBinding(run, contract, gh);
545
+ if (binding.stop) return { sha: run.head_sha, ...binding.stop };
546
+ const { pr, item } = binding;
547
+ const known = { pr, sha: run.head_sha, item };
548
+ const view = readItem(item, contract.repository, gh);
549
+ if (!view.open)
550
+ return stop("work-item-closed", "the work item is closed", known);
551
+ const checks = readRequiredChecks(pr, contract.repository, gh);
552
+ if (checks === null)
553
+ return stop("no-required-checks", "the PR has no required checks", known);
554
+ const { verdict, failing } = classifyRequiredChecks(checks);
555
+ const ctx = {
556
+ ...known,
557
+ view,
558
+ failing,
559
+ runId: run.id,
560
+ lanes: contract.lifecycle,
561
+ // Read lazily: only a lane repair or restore needs the label history.
562
+ events: () => readEvents(view.number, contract.repository, gh),
563
+ };
564
+ if (verdict === "fail") return planFailure(ctx);
565
+ if (verdict === "pass") return planClear(ctx);
566
+ return stop(
567
+ "checks-pending",
568
+ "no required check has failed and some have not finished",
569
+ known
570
+ );
571
+ }
572
+
573
+ /**
574
+ * Plan a recorded fixture: its event payload plus the gh answers it recorded.
575
+ * @param {{event: object, gh: object}} fixture - Recorded fixture.
576
+ * @param {object} contract - Tracker contract.
577
+ * @returns {Plan} Plan.
578
+ */
579
+ export function planFromFixture(fixture, contract) {
580
+ return planFromEvent(fixture.event, contract, recordedGh(fixture.gh));
581
+ }
582
+
583
+ /**
584
+ * Plan a `workflow_run` event payload (or a bare run object).
585
+ * @param {object} event - Event payload.
586
+ * @param {object} contract - Tracker contract.
587
+ * @param {Function} gh - Runner.
588
+ * @returns {Plan} Plan.
589
+ */
590
+ function planFromEvent(event, contract, gh) {
591
+ const run = event.workflow_run ?? event;
592
+ const repository = run.repository?.full_name ?? event.repository?.full_name;
593
+ return {
594
+ repository: contract.repository,
595
+ runId: run.id,
596
+ ...planRedispatch({ run, repository, contract, gh }),
597
+ };
598
+ }
599
+
600
+ /**
601
+ * The gh argv and stdin for one planned write.
602
+ * @param {object} action - Planned action.
603
+ * @param {string} repo - Repository.
604
+ * @returns {{args: string[], input?: string}} The call.
605
+ */
606
+ function writeCall(action, repo) {
607
+ const number = String(action.item ?? "").slice(
608
+ String(action.item ?? "").lastIndexOf("#") + 1
609
+ );
610
+ if (action.kind === ACTION.comment)
611
+ return {
612
+ args: ["issue", "comment", number, "--repo", repo, "--body-file", "-"],
613
+ input: action.body,
614
+ };
615
+ if (action.kind === ACTION.relabel)
616
+ return {
617
+ args: [
618
+ "issue",
619
+ "edit",
620
+ number,
621
+ "--repo",
622
+ repo,
623
+ "--remove-label",
624
+ action.remove,
625
+ "--add-label",
626
+ action.add,
627
+ ],
628
+ };
629
+ if (action.kind === ACTION.editComment)
630
+ return {
631
+ args: [
632
+ "api",
633
+ "-X",
634
+ "PATCH",
635
+ `repos/${repo}/issues/comments/${action.commentId}`,
636
+ "--input",
637
+ "-",
638
+ ],
639
+ input: JSON.stringify({ body: action.body }),
640
+ };
641
+ throw new Error(`unknown planned action: ${action.kind}`);
642
+ }
643
+
644
+ /**
645
+ * Perform a plan's writes in order, stopping at the first failure.
646
+ * @param {{repository: string, actions: object[]}} plan - Plan.
647
+ * @param {Function} gh - Runner.
648
+ * @returns {void}
649
+ */
650
+ export function applyPlan(plan, gh) {
651
+ for (const action of plan.actions) {
652
+ const { args, input } = writeCall(action, plan.repository);
653
+ const result = gh(args, { input, write: true });
654
+ if (!result.ok)
655
+ throw new Error(`gh ${args.join(" ")} failed: ${result.stderr}`);
656
+ }
657
+ }
658
+
659
+ /**
660
+ * Plain-language lines describing a plan.
661
+ * @param {object} plan - Plan.
662
+ * @param {boolean} dryRun - Whether nothing will be written.
663
+ * @returns {string[]} Lines.
664
+ */
665
+ function describePlan(plan, dryRun) {
666
+ const prLabel = plan.pr ? `#${plan.pr}` : "(none)";
667
+ const lines = [
668
+ `run ${plan.runId ?? "?"} -> PR ${prLabel} -> work item ${plan.item ?? "(none)"}`,
669
+ `outcome: ${plan.outcome} — ${plan.reason}${dryRun ? " (dry run: nothing written)" : ""}`,
670
+ ];
671
+ for (const action of plan.actions) {
672
+ const verb = dryRun ? "planned" : "done";
673
+ if (action.kind === ACTION.comment)
674
+ lines.push(
675
+ `${verb}: comment on ${action.item}: ${action.body.split("\n")[0]}`
676
+ );
677
+ if (action.kind === ACTION.relabel)
678
+ lines.push(
679
+ `${verb}: move ${action.item} from ${action.remove} to ${action.add}`
680
+ );
681
+ if (action.kind === ACTION.editComment)
682
+ lines.push(`${verb}: mark comment ${action.commentId} cleared`);
683
+ }
684
+ return lines;
685
+ }
686
+
687
+ /**
688
+ * Parse CLI flags.
689
+ * @param {string[]} argv - Arguments.
690
+ * @returns {{runId?: string, payload?: string, dryRun: boolean}} Options.
691
+ */
692
+ function parseArgs(argv) {
693
+ const options = { dryRun: false };
694
+ for (let i = 0; i < argv.length; i += 1) {
695
+ if (argv[i] === "--dry-run") options.dryRun = true;
696
+ else if (argv[i] === "--run-id") options.runId = argv[++i];
697
+ else if (argv[i] === "--payload") options.payload = argv[++i];
698
+ else throw new Error(`unknown argument: ${argv[i]}`);
699
+ }
700
+ if (!options.runId === !options.payload)
701
+ throw new Error("pass exactly one of --run-id <id> or --payload <file>");
702
+ if (options.runId !== undefined && !/^[1-9]\d*$/u.test(options.runId))
703
+ throw new Error(
704
+ `--run-id must be a positive integer, got '${options.runId}'`
705
+ );
706
+ return options;
707
+ }
708
+
709
+ /**
710
+ * Load the event and choose the runner it is read through.
711
+ * @param {{runId?: string, payload?: string, dryRun: boolean}} options - Options.
712
+ * @param {object} contract - Tracker contract.
713
+ * @param {Function} gh - Live runner.
714
+ * @returns {{event: object, gh: Function}} Event and runner.
715
+ */
716
+ function loadEvent(options, contract, gh) {
717
+ if (options.runId)
718
+ return {
719
+ event: readJson(gh, [
720
+ "api",
721
+ `repos/${contract.repository}/actions/runs/${options.runId}`,
722
+ ]),
723
+ gh,
724
+ };
725
+ const data = JSON.parse(readFileSync(options.payload, "utf8"));
726
+ if (data.gh === undefined) return { event: data, gh };
727
+ if (!options.dryRun)
728
+ throw new Error("a recorded fixture can only be replayed with --dry-run");
729
+ return { event: data.event, gh: recordedGh(data.gh) };
730
+ }
731
+
732
+ /**
733
+ * CLI entry: plan one run and, unless `--dry-run`, apply it.
734
+ * @param {string[]} argv - Arguments.
735
+ * @param {{gh?: Function, write?: Function, contract?: object}} [deps] - Injectables.
736
+ * @returns {number} Exit code: 0 decided, 1 failed read/write, 2 bad usage.
737
+ */
738
+ export function main(argv, deps = {}) {
739
+ const write = deps.write ?? (line => process.stdout.write(`${line}\n`));
740
+ let options;
741
+ let source;
742
+ try {
743
+ options = parseArgs(argv);
744
+ const contract = deps.contract ?? trackerContract();
745
+ source = { contract, ...loadEvent(options, contract, deps.gh ?? liveGh) };
746
+ } catch (error) {
747
+ write(`lisa-ci-failure-redispatch: ${error.message}`);
748
+ return 2;
749
+ }
750
+ try {
751
+ const plan = planFromEvent(source.event, source.contract, source.gh);
752
+ if (!options.dryRun) applyPlan(plan, source.gh);
753
+ for (const line of describePlan(plan, options.dryRun)) write(line);
754
+ write(JSON.stringify(plan, null, 2));
755
+ return 0;
756
+ } catch (error) {
757
+ write(`lisa-ci-failure-redispatch: ${error.message}`);
758
+ return 1;
759
+ }
760
+ }
761
+
762
+ if (invokedAsScript(import.meta.url))
763
+ process.exitCode = main(process.argv.slice(2));