lastlight-core 0.22.0 → 0.23.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/config/default.yaml +70 -2
  2. package/dist/config/config.d.ts +35 -0
  3. package/dist/config/config.js +152 -3
  4. package/dist/config/config.js.map +1 -1
  5. package/dist/config/repo-config.d.ts +7 -0
  6. package/dist/config/repo-config.js +15 -0
  7. package/dist/config/repo-config.js.map +1 -1
  8. package/dist/connectors/github-webhook.d.ts +17 -0
  9. package/dist/connectors/github-webhook.js +150 -17
  10. package/dist/connectors/github-webhook.js.map +1 -1
  11. package/dist/connectors/types.d.ts +48 -1
  12. package/dist/cron/dependabot-discovery.d.ts +68 -11
  13. package/dist/cron/dependabot-discovery.js +78 -20
  14. package/dist/cron/dependabot-discovery.js.map +1 -1
  15. package/dist/cron/jobs.d.ts +4 -0
  16. package/dist/cron/jobs.js +38 -4
  17. package/dist/cron/jobs.js.map +1 -1
  18. package/dist/cron/review-discovery.d.ts +33 -20
  19. package/dist/cron/review-discovery.js +23 -30
  20. package/dist/cron/review-discovery.js.map +1 -1
  21. package/dist/engine/agent-executor.d.ts +1 -1
  22. package/dist/engine/agent-executor.js +1 -1
  23. package/dist/engine/agent-executor.js.map +1 -1
  24. package/dist/engine/dispatcher.d.ts +98 -1
  25. package/dist/engine/dispatcher.js +248 -231
  26. package/dist/engine/dispatcher.js.map +1 -1
  27. package/dist/engine/executors/shared.d.ts +43 -0
  28. package/dist/engine/executors/shared.js +65 -0
  29. package/dist/engine/executors/shared.js.map +1 -1
  30. package/dist/engine/fix-harvest.d.ts +169 -0
  31. package/dist/engine/fix-harvest.js +345 -0
  32. package/dist/engine/fix-harvest.js.map +1 -0
  33. package/dist/engine/fix-markers.d.ts +184 -0
  34. package/dist/engine/fix-markers.js +329 -0
  35. package/dist/engine/fix-markers.js.map +1 -0
  36. package/dist/engine/fix-scratch.d.ts +76 -0
  37. package/dist/engine/fix-scratch.js +77 -0
  38. package/dist/engine/fix-scratch.js.map +1 -0
  39. package/dist/engine/github/github.d.ts +212 -5
  40. package/dist/engine/github/github.js +481 -54
  41. package/dist/engine/github/github.js.map +1 -1
  42. package/dist/engine/pr-decisions.d.ts +342 -0
  43. package/dist/engine/pr-decisions.js +721 -0
  44. package/dist/engine/pr-decisions.js.map +1 -0
  45. package/dist/engine/pr-escalation.d.ts +152 -0
  46. package/dist/engine/pr-escalation.js +320 -0
  47. package/dist/engine/pr-escalation.js.map +1 -0
  48. package/dist/engine/pr-notes.d.ts +175 -0
  49. package/dist/engine/pr-notes.js +315 -0
  50. package/dist/engine/pr-notes.js.map +1 -0
  51. package/dist/engine/pr-state.d.ts +313 -0
  52. package/dist/engine/pr-state.js +515 -0
  53. package/dist/engine/pr-state.js.map +1 -0
  54. package/dist/engine/review-check.d.ts +200 -0
  55. package/dist/engine/review-check.js +305 -0
  56. package/dist/engine/review-check.js.map +1 -0
  57. package/dist/engine/router.d.ts +27 -0
  58. package/dist/engine/router.js +156 -22
  59. package/dist/engine/router.js.map +1 -1
  60. package/dist/evals-api.d.ts +7 -0
  61. package/dist/evals-api.js +30 -0
  62. package/dist/evals-api.js.map +1 -1
  63. package/dist/index.js +268 -20
  64. package/dist/index.js.map +1 -1
  65. package/dist/sandbox/index.d.ts +13 -0
  66. package/dist/sandbox/index.js +30 -0
  67. package/dist/sandbox/index.js.map +1 -1
  68. package/dist/sandbox/k8s/init-clone.d.ts +5 -0
  69. package/dist/sandbox/k8s/init-clone.js +27 -0
  70. package/dist/sandbox/k8s/init-clone.js.map +1 -1
  71. package/dist/state/execution-store.d.ts +27 -0
  72. package/dist/state/execution-store.js +45 -0
  73. package/dist/state/execution-store.js.map +1 -1
  74. package/dist/state/workflow-run-store.d.ts +73 -0
  75. package/dist/state/workflow-run-store.js +106 -24
  76. package/dist/state/workflow-run-store.js.map +1 -1
  77. package/dist/workflows/pr-scope.d.ts +63 -0
  78. package/dist/workflows/pr-scope.js +113 -0
  79. package/dist/workflows/pr-scope.js.map +1 -0
  80. package/dist/workflows/resume.js +17 -4
  81. package/dist/workflows/resume.js.map +1 -1
  82. package/dist/workflows/simple.d.ts +94 -1
  83. package/dist/workflows/simple.js +206 -3
  84. package/dist/workflows/simple.js.map +1 -1
  85. package/dist/workflows/target-policy.d.ts +0 -12
  86. package/dist/workflows/target-policy.js +9 -15
  87. package/dist/workflows/target-policy.js.map +1 -1
  88. package/package.json +4 -4
  89. package/skills/README.md +11 -5
  90. package/skills/dependency-impact/SKILL.md +83 -0
  91. package/skills/fixing/SKILL.md +194 -0
  92. package/skills/pr-comment/SKILL.md +4 -1
  93. package/skills/pr-review/SKILL.md +26 -9
  94. package/workflows/cron-dependabot-ci-fix.yaml +8 -5
  95. package/workflows/cron-review.yaml +14 -5
  96. package/workflows/dependabot-ci-fix.yaml +86 -2
  97. package/workflows/dependabot-pr-merge.yaml +13 -1
  98. package/workflows/pr-fix.yaml +84 -1
  99. package/workflows/pr-review.yaml +7 -0
  100. package/workflows/prompts/dependabot-ci-fix.md +70 -17
  101. package/workflows/prompts/dependabot-pr-merge.md +209 -81
  102. package/workflows/prompts/diagnose-ci.md +96 -0
  103. package/workflows/prompts/pr-fix.md +63 -4
@@ -0,0 +1,721 @@
1
+ /**
2
+ * The four decisions the PR state machine makes — all PURE functions over a
3
+ * resolved {@link PrState} (`./pr-state.ts`).
4
+ *
5
+ * | Function | Replaces |
6
+ * |-------------------------|---------------------------------------------------------------------------------|
7
+ * | `mayMerge` | the merge prompt's `mergeable_state` heuristic; the green cron's `clean` filter |
8
+ * | `resolveFixDisposition` | `dependencyDedupSkip`; the prior-class escalation table |
9
+ * | `resolveReviewTrigger` | the four scattered review-trigger enforcement points + the cron's draft filter |
10
+ * | `renderContext` | `enrichPrFixContext`; everything the prompts render |
11
+ *
12
+ * Each returns **`{ decision, reason, inputs }`**, never a bare enum. The reason
13
+ * string is produced by the decision and rendered in three places — the log
14
+ * line, the escalation comment, and the run detail panel — so there is ONE
15
+ * source and three renderings rather than three prose variants that drift. The
16
+ * reason is written `"<case>: <explanation>"` so the case stays greppable
17
+ * without a parallel enum to keep in sync.
18
+ *
19
+ * `inputs` is the subset of the snapshot the decision actually read. It exists
20
+ * so the detail panel can show WHY without the view re-deriving anything, and
21
+ * so a table test asserts the decision and its justification together.
22
+ *
23
+ * Purity is the point: 09-state-machine.md observes that most verification of
24
+ * this plan becomes a table test over literal `PrState` fixtures — no GitHub
25
+ * mock, no sandbox, no harness.
26
+ */
27
+ import { renderCiFailureReport } from "./github/github.js";
28
+ import { PR_FIX_SHAPED_WORKFLOWS } from "../workflows/target-policy.js";
29
+ import { ATTEMPT_FREE_CLASSES } from "./fix-markers.js";
30
+ import { renderPrNotes } from "./pr-notes.js";
31
+ import { PR_NOTES_FILE_NAME, VERIFY_SCRIPT_NAME } from "./fix-scratch.js";
32
+ // ---------------------------------------------------------------------------
33
+ // The PR-scoped run lock — 09 → S4
34
+ // ---------------------------------------------------------------------------
35
+ /**
36
+ * "Another run already owns this PR" — stated ONCE, for every disposition.
37
+ *
38
+ * The lock is PR-scoped across every PR-scoped workflow (`pr-fix`,
39
+ * `dependabot-ci-fix`, `dependabot-pr-merge`, `pr-review`), and
40
+ * `prScopedWorkflows()` is exactly the union of the three dispositions below —
41
+ * so a guard that lives in one of them is a guard only one route obeys. It used
42
+ * to: `resolveReviewTrigger` checked `runInFlight` and the two others did not,
43
+ * while the dispatcher checked it inline for the webhook/comment route and
44
+ * `dispatchWorkflow` (the cron fan-out and `/api/run`) never did at all. The
45
+ * daily `fix-red-dependency-prs` could therefore dispatch `dependabot-ci-fix`
46
+ * onto a PR that already had a live `pr-fix` run, and
47
+ * `merge-green-dependency-prs` could enable auto-merge against a PR whose fix
48
+ * run was still writing its marker — the two sequences 09 → S4 names verbatim
49
+ * as the reason the lock exists.
50
+ *
51
+ * That is worse than harmless duplication now that the fix family shares ONE
52
+ * workspace per PR (`${repo}-${prNumber}-fix`): two runs `git fetch` +
53
+ * `reset --hard` + `git clean -fdx` the same directory while an agent works in
54
+ * it, and each rewrites the other's `.git/lastlight-verify.sh` gate.
55
+ *
56
+ * It is checked FIRST in each disposition, before every other skip, because it
57
+ * is the one skip that is purely transient. Ordering it after the escalating
58
+ * skips would label a PR `requires-human` for a budget that a run currently in
59
+ * flight is still spending; ordering it after `explicitRequest` would let an
60
+ * `@bot fix this` walk straight into the running agent's workspace.
61
+ */
62
+ /**
63
+ * "We could not read the pull request" — the one place {@link PrState.readErrors}
64
+ * is allowed to change an outcome.
65
+ *
66
+ * Every live read in `resolvePrState` is best-effort and degrades to a value
67
+ * that cannot cause a skip. That fail-open is load-bearing and stays: we would
68
+ * far rather re-run than silently drop a genuine event because GitHub had a bad
69
+ * minute. But `getPullRequest` is not like the others. It is the read that
70
+ * supplies `labels`, `isFork`, `isDraft`, `headSha` and `headRef` — the inputs
71
+ * to almost every guard below — and its degraded values are all the PERMISSIVE
72
+ * ones: `labels: []` so the `requires-human` hold does not apply, `isFork:
73
+ * false` so the fork guard does not apply, `headSha: ""` so the dedup does not
74
+ * apply. A 403 or 404 therefore produces a snapshot that looks perfectly
75
+ * healthy, and the cron route then dispatches a repo-write sandbox run against
76
+ * a pull request we know nothing about (#256).
77
+ *
78
+ * So this one read failing is a "come back later", not a verdict — the same
79
+ * shape as {@link runLockDrop}: no label, no comment, no run row, and the cron
80
+ * re-pickup is what makes dropping sound. Every OTHER read failing still
81
+ * fails open exactly as documented.
82
+ */
83
+ function readDegradedDrop(decision, state, inputs) {
84
+ const failed = state.readErrors.filter((e) => e.startsWith("getPullRequest"));
85
+ if (!failed.length)
86
+ return null;
87
+ return {
88
+ decision,
89
+ reason: `read-degraded: could not read the pull request (${failed.join("; ")}), so every guard below ` +
90
+ `would be evaluating defaults rather than facts`,
91
+ inputs: { ...inputs, readErrors: failed },
92
+ readDegraded: true,
93
+ };
94
+ }
95
+ function runLockDrop(decision, state, inputs) {
96
+ if (!state.runInFlight)
97
+ return null;
98
+ const { workflow, runId } = state.runInFlight;
99
+ return {
100
+ decision,
101
+ reason: `run-in-flight: ${workflow} ${runId} is already working this PR`,
102
+ inputs,
103
+ runInFlight: state.runInFlight,
104
+ };
105
+ }
106
+ // ---------------------------------------------------------------------------
107
+ // mayMerge — 09 → D10
108
+ // ---------------------------------------------------------------------------
109
+ /**
110
+ * May this PR be merged AT ALL — by either mechanism?
111
+ *
112
+ * The plan originally gated only DIRECT merge on settled-passing checks and let
113
+ * `github_enable_auto_merge` through ungated, on the reasoning that GitHub's
114
+ * required-checks gate is the real backstop. That reasoning is circular. Auto-
115
+ * merge merges as soon as all merge REQUIREMENTS are satisfied, and on a repo
116
+ * with no required status checks there are no requirements beyond mergeability
117
+ * — so `github_enable_auto_merge` on an already-mergeable PR merges it
118
+ * essentially immediately. Auto-merge and direct merge are the same action
119
+ * there, and that is not a hypothetical population: it is the exact one the
120
+ * merge prompt already documents ("on a repo with no required checks, a PR
121
+ * whose checks are FAILING still reports as mergeable, so a direct merge would
122
+ * land a RED PR — this has happened").
123
+ *
124
+ * So one predicate gates the decision to merge, and auto-merge stays the
125
+ * preferred *mechanism* (it genuinely handles the race between our decision and
126
+ * a late-created check) without being credited with a guarantee it only
127
+ * provides on protected repos.
128
+ *
129
+ * `minSettledChecks` ships at `1` and is operator-only: a `max(repo, operator)`
130
+ * clamp would weld the escape hatch shut in the direction a CI-less repo needs
131
+ * it. The CI-less case is handled on the fact instead — `checksState === "none"`
132
+ * is simply insufficient evidence, which Phase 5 uses to withhold auto-merge
133
+ * from MAJOR bumps while non-majors continue down the existing path.
134
+ */
135
+ export function mayMerge(state, cfg) {
136
+ const inputs = {
137
+ checksState: state.checksState,
138
+ settledCheckCount: state.settledCheckCount,
139
+ minSettledChecks: cfg.minSettledChecks,
140
+ requireSettledChecks: cfg.requireSettledChecks,
141
+ };
142
+ if (!cfg.requireSettledChecks) {
143
+ return {
144
+ decision: true,
145
+ reason: "checks-not-required: dependencies.requireSettledChecks is off",
146
+ inputs,
147
+ };
148
+ }
149
+ if (state.checksState === "pending") {
150
+ return { decision: false, reason: "checks-pending: CI has not settled yet", inputs };
151
+ }
152
+ if (state.checksState === "failing") {
153
+ return { decision: false, reason: "checks-failing: CI is red on the head commit", inputs };
154
+ }
155
+ if (state.checksState === "none") {
156
+ return {
157
+ decision: false,
158
+ reason: "no-checks: the head commit has no checks or statuses at all",
159
+ inputs,
160
+ };
161
+ }
162
+ if (state.settledCheckCount < cfg.minSettledChecks) {
163
+ return {
164
+ decision: false,
165
+ reason: `too-few-checks: ${state.settledCheckCount} settled check(s), ` +
166
+ `dependencies.minSettledChecks is ${cfg.minSettledChecks}`,
167
+ inputs,
168
+ };
169
+ }
170
+ return {
171
+ decision: true,
172
+ reason: `checks-passing: ${state.settledCheckCount} settled check(s), all green`,
173
+ inputs,
174
+ };
175
+ }
176
+ /**
177
+ * Decide whether to spend a fix run on this PR.
178
+ *
179
+ * Replaces `dependencyDedupSkip` and the prior-run escalation table. Two
180
+ * structural rules govern it:
181
+ *
182
+ * **No prior-run verdict may gate dispatch unless the skipping path writes a
183
+ * run row.** A skip returns `{ kind: "skipped" }` and writes NO row, so a gate
184
+ * on "what did the last run conclude" reads the same stale row forever: the PR
185
+ * is dead, with no label, no comment and nothing on the PR explaining why —
186
+ * strictly worse than `requires-human`, which is at least visible. That is
187
+ * exactly how `upstream-broken` would have latched a PR permanently dead (09 →
188
+ * D1), so `upstream-broken` is resolved here as a LIVE `baseChecksState`
189
+ * precondition. The diagnosis class remains an explanation, never a dispatch
190
+ * input.
191
+ *
192
+ * **`requires-human` is a notification, not a state.** The state is "we
193
+ * escalated at head SHA X", so the guard is stateful rather than the label: a
194
+ * maintainer's push re-arms the loop, while a human who applied the label by
195
+ * hand (no escalating run of ours to match) keeps a hard permanent override.
196
+ *
197
+ * Three of the skips are terminal for this problem and carry an
198
+ * {@link EscalationCase} so the caller labels and explains them on the PR
199
+ * (`./pr-escalation.ts`); the rest are deliberately silent. Which is which is a
200
+ * property of the branch, not of its prose — see {@link EscalationCase}.
201
+ */
202
+ export function resolveFixDisposition(state, cfg, opts = {}) {
203
+ const inputs = {
204
+ baseChecksState: state.baseChecksState,
205
+ checksState: state.checksState,
206
+ headSha: state.headSha,
207
+ escalatedBy: state.escalatedBy,
208
+ escalatedAtSha: state.escalatedAtSha,
209
+ attempt: state.attempt,
210
+ maxAttempts: cfg.maxAttempts,
211
+ cumulativeCostUsd: state.cumulativeCostUsd,
212
+ maxCostUsd: cfg.maxCostUsd,
213
+ priorDiagnosisClass: state.priorDiagnosisClass,
214
+ retryableClasses: cfg.retryableClasses,
215
+ runInFlight: state.runInFlight,
216
+ explicitRequest: !!opts.explicitRequest,
217
+ };
218
+ // We could not read the PR at all — see `readDegradedDrop`. Above even the
219
+ // run lock, because `runInFlight` is the one input below that does NOT come
220
+ // from the failed read: reporting "another run owns this PR" would be true
221
+ // but beside the point, and the honest answer is that we know nothing.
222
+ const blind = readDegradedDrop("skip", state, inputs);
223
+ if (blind)
224
+ return blind;
225
+ // The PR-scoped run lock, before anything else — see `runLockDrop`.
226
+ const locked = runLockDrop("skip", state, inputs);
227
+ if (locked)
228
+ return locked;
229
+ // A fork PR has no branch we can push to. Cheapest possible skip: before the
230
+ // budget arithmetic, before any sandbox.
231
+ if (state.isFork) {
232
+ return {
233
+ decision: "skip",
234
+ reason: `fork-pr: head ${state.headRepoFullName ?? "(deleted fork)"} is not on ${state.repo}, ` +
235
+ `so there is nothing to clone or push to`,
236
+ inputs,
237
+ forkPr: true,
238
+ };
239
+ }
240
+ // LIVE precondition, not a prior verdict. Re-evaluated every event, so the
241
+ // moment the base goes green the PR is eligible again — with no label to
242
+ // clear and no run row required to un-stick it.
243
+ if (state.baseChecksState === "failing") {
244
+ return {
245
+ decision: "skip",
246
+ reason: `upstream-broken: base branch ${state.baseRef || "(unknown)"} is failing — a fix here cannot make CI green`,
247
+ inputs,
248
+ };
249
+ }
250
+ if (state.escalatedBy === "human" && !opts.explicitRequest) {
251
+ return {
252
+ decision: "skip",
253
+ reason: "human-hold: requires-human was applied by a human, not by one of our runs — a permanent override",
254
+ inputs,
255
+ };
256
+ }
257
+ if (state.escalatedBy === "us" && !opts.explicitRequest) {
258
+ // We escalated. Still binding only while the head is the one we escalated
259
+ // at, or a commit WE authored on top of it — anyone else's push IS the
260
+ // human intervention we asked for, and re-arms both the counter and the
261
+ // merge path without anyone having to remove a label.
262
+ const sameProblem = state.headSha === state.escalatedAtSha || state.headIsOurs;
263
+ if (sameProblem) {
264
+ return {
265
+ decision: "skip",
266
+ reason: `escalated: we escalated this PR at ${(state.escalatedAtSha ?? "").slice(0, 7)} and nothing has changed since`,
267
+ inputs,
268
+ };
269
+ }
270
+ }
271
+ // The three ESCALATING skips. Ordering between them is cosmetic — all three
272
+ // apply the same label and the same comment, so it only picks which case the
273
+ // comment names — but they must all come AFTER the guards above, or a fork PR
274
+ // whose budget happens to be spent would be labelled `requires-human` for a
275
+ // problem that is not its author's to fix.
276
+ if (cfg.maxCostUsd !== null && state.cumulativeCostUsd >= cfg.maxCostUsd) {
277
+ return {
278
+ decision: "skip",
279
+ reason: `budget-exhausted: $${state.cumulativeCostUsd.toFixed(2)} spent on this PR, ` +
280
+ `fix.maxCostUsd is $${cfg.maxCostUsd.toFixed(2)}`,
281
+ inputs,
282
+ escalation: "budget-exhausted",
283
+ };
284
+ }
285
+ if (state.attempt > cfg.maxAttempts) {
286
+ return {
287
+ decision: "skip",
288
+ reason: `attempts-exhausted: attempt ${state.attempt} exceeds fix.maxAttempts ${cfg.maxAttempts}`,
289
+ inputs,
290
+ escalation: "attempts-exhausted",
291
+ };
292
+ }
293
+ // The ONE prior-run verdict that gates dispatch — and it is only allowed to
294
+ // because this skip WRITES A RUN ROW (09 → D1's general rule: "no prior-run
295
+ // verdict may gate dispatch unless the skipping path writes a run row").
296
+ // `upstream-broken` was the counter-example: gated on a remembered class
297
+ // through a path that recorded nothing, so `latestForTrigger` returned the
298
+ // same stale row forever and the PR was dead. It became a live precondition
299
+ // above; this one escalates instead, which is both visible and clearable.
300
+ //
301
+ // Expressed against `fix.retryableClasses` rather than hardcoding
302
+ // `infra-dependent`, because that leaf's whole contract is "classes another
303
+ // attempt may help with; every other class escalates immediately". The two
304
+ // exclusions are exactly {@link ATTEMPT_FREE_CLASSES}, which is not a
305
+ // coincidence: `flaky` is bounded by `fix.maxFlakyDeferrals` (a deferral, not
306
+ // a verdict) and `upstream-broken` is not this PR's fault — the same reason
307
+ // they cost no attempt is the reason they must not escalate.
308
+ const priorClass = state.priorDiagnosisClass;
309
+ if (priorClass &&
310
+ !ATTEMPT_FREE_CLASSES.has(priorClass) &&
311
+ !cfg.retryableClasses.includes(priorClass) &&
312
+ !opts.explicitRequest) {
313
+ return {
314
+ decision: "skip",
315
+ reason: `not-retryable: attempt ${state.attempt - 1} diagnosed \`${priorClass}\`, which is not in ` +
316
+ `fix.retryableClasses (${cfg.retryableClasses.join(", ") || "none"}) — another attempt cannot help`,
317
+ inputs,
318
+ escalation: "not-retryable",
319
+ };
320
+ }
321
+ // "Already assessed at this exact SHA" — the automated routes' idempotency
322
+ // contract. A multi-app repo re-fires a suite and the daily cron overlaps, so
323
+ // without this the same PR is re-assessed repeatedly. SUCCEEDED runs only,
324
+ // which is what leaves room for a genuine retry: a run that CRASHED at this
325
+ // SHA records nothing here and is attempted again (bounded by `maxAttempts`),
326
+ // while a run that correctly concluded "not fixable from here" recorded
327
+ // `succeeded` and is not.
328
+ if (opts.dedupOnHeadSha && !opts.explicitRequest && state.headSha) {
329
+ const assessedBy = [...PR_FIX_SHAPED_WORKFLOWS].find((w) => state.assessedHeadShaByWorkflow[w] === state.headSha);
330
+ if (assessedBy) {
331
+ return {
332
+ decision: "skip",
333
+ reason: `already-assessed: ${assessedBy} already handled ${state.headSha.slice(0, 7)}`,
334
+ inputs,
335
+ };
336
+ }
337
+ }
338
+ return {
339
+ decision: "run",
340
+ reason: `attempt ${state.attempt}/${cfg.maxAttempts}`,
341
+ inputs,
342
+ };
343
+ }
344
+ /**
345
+ * Which check the decision implies. Keyed on the TYPED decision plus the mode,
346
+ * never on the reason prose — the same rule the escalation applier follows.
347
+ */
348
+ export function reviewCheckPlacement(decision, cfg) {
349
+ if (decision === "dispatch")
350
+ return "in-progress";
351
+ if (decision === "skip")
352
+ return "none";
353
+ return cfg.trigger === "on-request" ? "neutral" : "queued";
354
+ }
355
+ /**
356
+ * One resolver, every route.
357
+ *
358
+ * The split is DISCOVERY vs POLICY, not webhook vs cron: `review-discovery.ts`
359
+ * finds candidates and learns nothing about modes, drafts or settled checks,
360
+ * while this function — called from the single dispatch choke point — decides.
361
+ * The alternative was three independent implementations of `review.trigger`,
362
+ * in a plan whose thesis is "make the policy configurable rather than
363
+ * hardcoded".
364
+ *
365
+ * FIX OUTRANKS REVIEW. A settled-failing suite routes to the fix family, and
366
+ * the review is simply not dispatched — not deferred, not queued, no record.
367
+ * That is a consequence of the PR-scoped run lock rather than a separate field:
368
+ * if a fix run is in flight, reviewing a tree it is concurrently rewriting
369
+ * produces a review that is stale before it lands.
370
+ */
371
+ export function resolveReviewTrigger(state, cfg, opts = {}) {
372
+ const route = opts.route ?? "attention";
373
+ const inputs = {
374
+ trigger: cfg.trigger,
375
+ skipDraft: cfg.skipDraft,
376
+ requestLabel: cfg.requestLabel,
377
+ isDraft: state.isDraft,
378
+ checksState: state.checksState,
379
+ botReviewAtHead: state.botReviewAtHead?.state ?? null,
380
+ runInFlight: state.runInFlight,
381
+ route,
382
+ explicitRequest: !!opts.explicitRequest,
383
+ };
384
+ // We could not read the PR at all — see `readDegradedDrop`. `skip`, not
385
+ // `defer`: a deferral posts a placeholder check saying "not yet" against a
386
+ // head SHA, and we do not reliably know the head SHA.
387
+ const blind = readDegradedDrop("skip", state, inputs);
388
+ if (blind)
389
+ return blind;
390
+ // The PR-scoped run lock, before anything else — see `runLockDrop`. Above the
391
+ // explicit-request branch on purpose: the lock is not policy but a physical
392
+ // constraint (one workspace, one branch, one agent), so it is the one thing an
393
+ // `@bot review` does NOT override. The dispatcher replies to the human whose
394
+ // request it dropped; the 30-minute sweep is the re-pickup.
395
+ const locked = runLockDrop("skip", state, inputs);
396
+ if (locked)
397
+ return locked;
398
+ const labelRequested = !!cfg.requestLabel && state.labels.includes(cfg.requestLabel);
399
+ if (opts.explicitRequest || labelRequested) {
400
+ return {
401
+ decision: "dispatch",
402
+ reason: labelRequested
403
+ ? `requested: the \`${cfg.requestLabel}\` label asks for a review`
404
+ : "requested: an explicit review request overrides mode, draft and dedup",
405
+ inputs,
406
+ };
407
+ }
408
+ if (cfg.trigger === "on-request") {
409
+ // `defer`, not `skip`: a label, a comment, or the check's own Re-run button
410
+ // can still ask for this review, and `postsCheck` advertises exactly that.
411
+ return {
412
+ decision: "defer",
413
+ reason: "on-request: review.trigger is `on-request` and nobody asked",
414
+ inputs,
415
+ };
416
+ }
417
+ if (cfg.skipDraft && state.isDraft) {
418
+ return { decision: "skip", reason: "draft: review.skipDraft is on", inputs };
419
+ }
420
+ if (state.botReviewAtHead) {
421
+ return {
422
+ decision: "skip",
423
+ reason: `already-reviewed: we reviewed ${state.headSha.slice(0, 7)} (${state.botReviewAtHead.state})`,
424
+ inputs,
425
+ };
426
+ }
427
+ if (cfg.trigger === "after-checks") {
428
+ // "On settle, EITHER COLOUR." The `passing` variant was deleted: a PR we
429
+ // gave up on never goes green, so under `passing` the escalated PRs — the
430
+ // ones most needing human eyes — would be the only ones with no review at
431
+ // all. Either colour is also what lets the review cite the CI failure.
432
+ //
433
+ // THE SWEEP IS EXEMPT FROM THE PENDING DEFERRAL — the `route !== "sweep"`
434
+ // below is the whole of that decision.
435
+ //
436
+ // `pending` used to defer on every route, the sweep included — and a check
437
+ // run that never CONCLUDES is then deferred by every route, forever. That is not a hypothetical: a fork PR's `workflow_run`
438
+ // awaiting maintainer approval, a dead self-hosted runner, or a third-party
439
+ // app that opens a check and crashes all leave the aggregate `pending` with
440
+ // no further `check_suite` ever coming. `check-prs-awaiting-review` calls
441
+ // itself the RELEASE MECHANISM, and it was not one for this case; with
442
+ // `review.postsCheck` on, the `queued` placeholder then sits there
443
+ // permanently and a repo that made `last-light/review` required has an
444
+ // unmergeable PR. This ships as the DEFAULT (`review.trigger:
445
+ // after-checks`), so it is the packaged behaviour.
446
+ //
447
+ // The sweep cannot tell "CI is still running" from "this check will never
448
+ // conclude" — nothing in the snapshot dates the pending state — so it must
449
+ // choose which error to make. It dispatches: a review posted 30 minutes into
450
+ // a still-running CI run costs TIMING (the review cannot cite a failure that
451
+ // has not happened yet, and the next push re-arms `botReviewAtHead`
452
+ // anyway), while a PR that is never reviewed and possibly never mergeable
453
+ // costs CORRECTNESS. `after-checks` is "on settle, either colour" — the
454
+ // COLOUR was never the gate, and on the one route that exists precisely to
455
+ // pick up what no webhook will ever fire for, neither is settling.
456
+ if (state.checksState === "pending" && route !== "sweep") {
457
+ return { decision: "defer", reason: "checks-pending: waiting for CI to settle", inputs };
458
+ }
459
+ if (route === "attention") {
460
+ return {
461
+ decision: "defer",
462
+ reason: "after-checks: review.trigger waits for a settled check suite, not PR attention",
463
+ inputs,
464
+ };
465
+ }
466
+ }
467
+ return {
468
+ decision: "dispatch",
469
+ reason: `${cfg.trigger}: ${route} route, checks ${state.checksState}`,
470
+ inputs,
471
+ };
472
+ }
473
+ // ---------------------------------------------------------------------------
474
+ // resolveMergeDisposition — the dependency-merge route's dispatch gate
475
+ // ---------------------------------------------------------------------------
476
+ /**
477
+ * Should a `dependabot-pr-merge` run be dispatched for this PR?
478
+ *
479
+ * `resolveFixDisposition` cannot serve this route: its fork guard, attempt
480
+ * counter and cost cap are facts about the FIX FAMILY, and a PR whose fix
481
+ * attempts are exhausted must still be mergeable the moment CI goes green.
482
+ * What the two share is the pair of guards that are facts about the PULL
483
+ * REQUEST — "a human told us to stay out" and "we already assessed this exact
484
+ * head" — so those are restated here rather than inherited.
485
+ *
486
+ * Note what is deliberately NOT here: {@link mayMerge}. That predicate gates
487
+ * the ACTION (Phase 5's merge decision, inside the run, where the impact tier
488
+ * is known); this gates the DISPATCH. The only overlap worth paying for before
489
+ * a sandbox is `pending` — CI is still running, so there is nothing to decide
490
+ * yet and the settled webhook or the daily cron will bring the PR back. Using
491
+ * the full `mayMerge` here would additionally refuse every CI-less repo
492
+ * (`checksState === "none"`), which 09 → D10 explicitly reserves for MAJOR
493
+ * bumps rather than applying to the whole route.
494
+ */
495
+ export function resolveMergeDisposition(state, cfg, opts = {}) {
496
+ const inputs = {
497
+ checksState: state.checksState,
498
+ settledCheckCount: state.settledCheckCount,
499
+ requireSettledChecks: cfg.requireSettledChecks,
500
+ headSha: state.headSha,
501
+ escalatedBy: state.escalatedBy,
502
+ escalatedAtSha: state.escalatedAtSha,
503
+ runInFlight: state.runInFlight,
504
+ explicitRequest: !!opts.explicitRequest,
505
+ };
506
+ // We could not read the PR at all — see `readDegradedDrop`. It matters most
507
+ // on this route: `mergeable_state`, the labels and the fork flag all come
508
+ // from that read, and enabling auto-merge on a pull request we cannot see is
509
+ // the one irreversible thing this codebase does.
510
+ const blind = readDegradedDrop("skip", state, inputs);
511
+ if (blind)
512
+ return blind;
513
+ // The PR-scoped run lock, before anything else — see `runLockDrop`. This is
514
+ // the branch that stops `merge-green-dependency-prs` enabling auto-merge
515
+ // against a PR whose fix run is still in flight: the fix pushes, CI goes
516
+ // green while the run is still writing its comment and marker, and the merge
517
+ // route then acts on a tree that is still being rewritten.
518
+ const locked = runLockDrop("skip", state, inputs);
519
+ if (locked)
520
+ return locked;
521
+ if (state.escalatedBy === "human" && !opts.explicitRequest) {
522
+ return {
523
+ decision: "skip",
524
+ reason: "human-hold: requires-human was applied by a human, not by one of our runs — a permanent override",
525
+ inputs,
526
+ };
527
+ }
528
+ if (state.escalatedBy === "us" && !opts.explicitRequest) {
529
+ const sameProblem = state.headSha === state.escalatedAtSha || state.headIsOurs;
530
+ if (sameProblem) {
531
+ return {
532
+ decision: "skip",
533
+ reason: `escalated: we escalated this PR at ${(state.escalatedAtSha ?? "").slice(0, 7)} and nothing has changed since`,
534
+ inputs,
535
+ };
536
+ }
537
+ }
538
+ if (opts.dedupOnHeadSha && !opts.explicitRequest && state.headSha) {
539
+ if (state.assessedHeadShaByWorkflow["dependabot-pr-merge"] === state.headSha) {
540
+ return {
541
+ decision: "skip",
542
+ reason: `already-assessed: dependabot-pr-merge already handled ${state.headSha.slice(0, 7)}`,
543
+ inputs,
544
+ };
545
+ }
546
+ }
547
+ // The cheapest possible "wait while CI is still running" guard — before any
548
+ // sandbox is provisioned. A multi-app repo settles one suite at a time and
549
+ // the daily cron overlaps the webhook, so without this a merge assessment
550
+ // runs against a PR whose verdict is not in yet.
551
+ if (cfg.requireSettledChecks && state.checksState === "pending") {
552
+ return {
553
+ decision: "skip",
554
+ reason: "checks-pending: CI has not settled yet — the settled webhook or the daily cron will bring it back",
555
+ inputs,
556
+ };
557
+ }
558
+ return { decision: "run", reason: `checks ${state.checksState}`, inputs };
559
+ }
560
+ /**
561
+ * Which decision governs a dispatch of `workflowName`, resolved to one verdict.
562
+ *
563
+ * The dispatcher (webhook / comment routes) and `dispatchWorkflow` (cron,
564
+ * `/api/run`) both need the same answer, and the whole point of 09 is that they
565
+ * must not each carry their own version of it. So the workflow→decision mapping
566
+ * lives here, once, as a pure function — the call sites differ only in what they
567
+ * DO with a `skip` (reply to the human who asked, versus log and record nothing).
568
+ *
569
+ * `pr-review` crosses {@link resolveReviewTrigger}. Its three-valued verdict
570
+ * collapses to two here — `defer` and `skip` are both "do not spend a run now"
571
+ * — but the caller keeps the undegraded decision on {@link Decision.review},
572
+ * because the CHECK RUN each should leave behind differs: see
573
+ * {@link reviewCheckPlacement}.
574
+ *
575
+ * The PR-scoped run lock is enforced inside each of the three, not here: the
576
+ * lock's span (`prScopedWorkflows()`) is exactly the union of the three
577
+ * branches, so the `ungated` fallback below is unreachable for a workflow the
578
+ * lock covers — and a caller that reaches one of the dispositions directly
579
+ * (`pr-escalation.ts`'s tests, the evals harness) gets the same answer as one
580
+ * that comes through here. See {@link runLockDrop}.
581
+ */
582
+ export function resolveDispatchDisposition(workflowName, state, cfg, opts = {}) {
583
+ if (PR_FIX_SHAPED_WORKFLOWS.has(workflowName)) {
584
+ return resolveFixDisposition(state, cfg.fix, opts);
585
+ }
586
+ if (workflowName === "dependabot-pr-merge") {
587
+ return resolveMergeDisposition(state, cfg.dependencies, opts);
588
+ }
589
+ if (workflowName === "pr-review") {
590
+ const review = resolveReviewTrigger(state, cfg.review, opts);
591
+ return {
592
+ decision: review.decision === "dispatch" ? "run" : "skip",
593
+ reason: review.reason,
594
+ inputs: review.inputs,
595
+ review: review.decision,
596
+ // Carried through the collapse: a review dropped by the run lock is the
597
+ // same kind of "come back later" as a fix dropped by it, and the caller
598
+ // owes the same reply to whoever asked. `readDegraded` rides along for
599
+ // the same reason and one more — it is what stops the caller posting a
600
+ // placeholder check against a head SHA we could not read.
601
+ ...(review.runInFlight ? { runInFlight: review.runInFlight } : {}),
602
+ ...(review.readDegraded ? { readDegraded: true } : {}),
603
+ };
604
+ }
605
+ return {
606
+ decision: "run",
607
+ reason: `ungated: no dispatch policy governs ${workflowName}`,
608
+ inputs: { workflowName },
609
+ };
610
+ }
611
+ // ---------------------------------------------------------------------------
612
+ // renderContext
613
+ // ---------------------------------------------------------------------------
614
+ /**
615
+ * Project the snapshot into the template variables the prompts render.
616
+ *
617
+ * Replaces `enrichPrFixContext` and closes the divergence 00 records as a
618
+ * latent bug: the cron fan-out called `dispatchWorkflow` DIRECTLY, bypassing
619
+ * `handlePrFix`, so every nightly `fix-red-dependency-prs` run carried
620
+ * `branch` + `reason` but an EMPTY `{{ciSection}}` and no fork guard — while
621
+ * the webhook route carried `ciSection` but no `{{reason}}`. One projection at
622
+ * one choke point makes both routes identical by construction.
623
+ *
624
+ * Pure: the CI report was already fetched into the snapshot, so this renders it
625
+ * rather than fetching it.
626
+ *
627
+ * `fix` and `dependencies` are optional because the variables they contribute
628
+ * are policy, not state — they come from the run's already-repo-clamped config
629
+ * blocks, not from the PR. Omitting one leaves its variables undefined, which
630
+ * the prompts' own `{{#if maxAttempts}}`-style guards already handle.
631
+ */
632
+ export function renderContext(state, fix, dependencies) {
633
+ // The merge gate, decided ONCE here rather than re-derived in prose by the
634
+ // merge prompt. 09's thesis is one source and three renderings; a predicate
635
+ // restated as an instruction is a fourth reading free to disagree — and it
636
+ // did. `{{#if !checksSettledPassing}}` (what the prompt gated its
637
+ // "gate is CLOSED" banner on) diverges from `mayMerge` in both directions:
638
+ // it misses `settledCheckCount < minSettledChecks`, so an operator who raises
639
+ // `minSettledChecks` gets a banner claiming the gate is open while the gate
640
+ // is shut; and it ignores the `requireSettledChecks: false` exemption, so a
641
+ // deployment that turned the gate off still gets told not to merge.
642
+ const merge = dependencies ? mayMerge(state, dependencies) : undefined;
643
+ const failedChecks = state.ciReport ? renderCiFailureReport(state.ciReport) : "";
644
+ return {
645
+ // Identity / targeting.
646
+ headSha: state.headSha,
647
+ branch: state.headRef,
648
+ // The PR's REAL base — not the repo default. A PR targeting a release
649
+ // branch used to have the fix prompt merge the wrong base in step 1.
650
+ baseBranch: state.baseRef,
651
+ prTitle: state.title,
652
+ prLabels: state.labels,
653
+ isDraft: state.isDraft,
654
+ // Check evidence.
655
+ checksState: state.checksState,
656
+ checksSettledPassing: state.checksState === "passing",
657
+ settledCheckCount: state.settledCheckCount,
658
+ // The gate itself, and the reason IT produced — so the prompt states the
659
+ // same case the log line and the admin panel state.
660
+ mayMerge: merge?.decision,
661
+ mayMergeReason: merge?.reason,
662
+ baseChecksState: state.baseChecksState,
663
+ failedChecks,
664
+ // The "No failed checks found." sentinel must not reach the prompt as if it
665
+ // were evidence — `{{#if ciSection}}` is how the templates gate the block.
666
+ ciSection: failedChecks && !failedChecks.includes("No failed checks")
667
+ ? `CI FAILURES (from GitHub Actions — fix these first):\n${failedChecks}`
668
+ : "",
669
+ ciLogsAvailable: state.ciReport?.logsAvailable ?? false,
670
+ // The BRANCHABLE half of the same fact, and not simply the negation of the
671
+ // line above: `ciLogsAvailable` is false both when the log download failed
672
+ // AND when there is no CI report at all (nothing failing, nothing to
673
+ // fetch). A prompt branching on the negation would warn "the harness could
674
+ // not download the job logs" on a perfectly green PR. This is true only
675
+ // when we HAVE a report and its logs are missing — which is the case
676
+ // `skills/fixing/SKILL.md` tells the agent to name in its verdict, using a
677
+ // fact it was never handed until now (#256). The cause is already spoken by
678
+ // `renderCiFailureReport`'s banner inside `{{ciSection}}`, so it is not
679
+ // duplicated here.
680
+ ciLogsUnavailable: !!state.ciReport && !state.ciReport.logsAvailable,
681
+ // Retry state. `maxAttempts` is rendered by all three fix prompts as
682
+ // `{{#if maxAttempts}} of {{maxAttempts}}{{/if}}` and was simply never
683
+ // provided — "this is attempt 2" instead of "this is attempt 2 of 3", which
684
+ // is the half that tells the agent whether to spend or to stop.
685
+ attempt: state.attempt,
686
+ maxAttempts: fix?.maxAttempts,
687
+ priorAttempts: state.priorAttempts,
688
+ // The PR journal (10-pr-memory.md), projected to ONE fenced string.
689
+ //
690
+ // A string, not the array, and that is the enforcement rather than a
691
+ // convenience: this is the only consumer `PrState.notes` has, so a note can
692
+ // reach an agent's eyes and can reach nothing else. There is no
693
+ // `notesSayFlaky` boolean, no `hasNotes` flag, no per-kind list — nothing a
694
+ // YAML `skip_if` / `until` expression or a decision function could branch
695
+ // on. Notes inform; they never authorise. The fence and the trust statement
696
+ // are emitted by `renderPrNotes` itself rather than written into the
697
+ // (forkable) prompt templates, so no fork can drop them.
698
+ priorNotes: renderPrNotes(state.notes),
699
+ // Where the agent appends a new note, and where it writes the push gate.
700
+ // Template variables rather than literals in each prompt so both placements
701
+ // stay resolvable in ONE place; both are bare relative paths because the
702
+ // agent's cwd is the checkout on every backend, and both sit under `.git/`
703
+ // so no `git add -A` can commit them (see `engine/executors/shared.ts`).
704
+ // `until_bash` still carries the gate path as a literal — the engine's
705
+ // `validateShellCommand` rejects any command containing `{{` — and
706
+ // `tests/workflows/pr-fix.test.ts` pins that literal to this constant.
707
+ notesFile: PR_NOTES_FILE_NAME,
708
+ verifyScript: VERIFY_SCRIPT_NAME,
709
+ // Flaky-deferral state. The PROMOTION itself (a third consecutive `flaky`
710
+ // is treated as `reproducible`, 09 → S1) is ACTED ON elsewhere —
711
+ // `promoteFlakyDiagnosis` in `workflows/simple.ts` drops the `class=flaky`
712
+ // row from the `fix` phase's `skip_if` for that run, because the engine's
713
+ // expression grammar has no negation to express the conjunction with. What
714
+ // is exposed here is the same fact for the PROMPT, so the agent can say why
715
+ // `flaky` is no longer being accepted for this PR.
716
+ flakyDeferrals: state.flakyDeferrals,
717
+ maxFlakyDeferrals: fix?.maxFlakyDeferrals,
718
+ flakyPromoted: fix !== undefined && state.flakyDeferrals >= fix.maxFlakyDeferrals,
719
+ };
720
+ }
721
+ //# sourceMappingURL=pr-decisions.js.map