lastlight-core 0.21.14 → 0.23.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 (124) hide show
  1. package/config/default.yaml +119 -1
  2. package/dist/admin/routes.js +195 -38
  3. package/dist/admin/routes.js.map +1 -1
  4. package/dist/config/config-resolve.d.ts +38 -1
  5. package/dist/config/config-resolve.js +41 -17
  6. package/dist/config/config-resolve.js.map +1 -1
  7. package/dist/config/config.d.ts +114 -0
  8. package/dist/config/config.js +225 -7
  9. package/dist/config/config.js.map +1 -1
  10. package/dist/config/repo-config.d.ts +120 -0
  11. package/dist/config/repo-config.js +447 -0
  12. package/dist/config/repo-config.js.map +1 -0
  13. package/dist/connectors/github-webhook.d.ts +17 -0
  14. package/dist/connectors/github-webhook.js +150 -17
  15. package/dist/connectors/github-webhook.js.map +1 -1
  16. package/dist/connectors/types.d.ts +48 -1
  17. package/dist/cron/dependabot-discovery.d.ts +68 -11
  18. package/dist/cron/dependabot-discovery.js +78 -20
  19. package/dist/cron/dependabot-discovery.js.map +1 -1
  20. package/dist/cron/fanout.d.ts +10 -0
  21. package/dist/cron/fanout.js +35 -2
  22. package/dist/cron/fanout.js.map +1 -1
  23. package/dist/cron/jobs.d.ts +16 -2
  24. package/dist/cron/jobs.js +69 -9
  25. package/dist/cron/jobs.js.map +1 -1
  26. package/dist/cron/repo-crons.d.ts +110 -0
  27. package/dist/cron/repo-crons.js +169 -0
  28. package/dist/cron/repo-crons.js.map +1 -0
  29. package/dist/cron/review-discovery.d.ts +33 -20
  30. package/dist/cron/review-discovery.js +23 -30
  31. package/dist/cron/review-discovery.js.map +1 -1
  32. package/dist/engine/agent-executor.d.ts +1 -1
  33. package/dist/engine/agent-executor.js +1 -1
  34. package/dist/engine/agent-executor.js.map +1 -1
  35. package/dist/engine/dispatcher.d.ts +98 -1
  36. package/dist/engine/dispatcher.js +248 -231
  37. package/dist/engine/dispatcher.js.map +1 -1
  38. package/dist/engine/executors/orchestrator.js +39 -15
  39. package/dist/engine/executors/orchestrator.js.map +1 -1
  40. package/dist/engine/executors/shared.d.ts +43 -0
  41. package/dist/engine/executors/shared.js +65 -0
  42. package/dist/engine/executors/shared.js.map +1 -1
  43. package/dist/engine/fix-harvest.d.ts +169 -0
  44. package/dist/engine/fix-harvest.js +345 -0
  45. package/dist/engine/fix-harvest.js.map +1 -0
  46. package/dist/engine/fix-markers.d.ts +184 -0
  47. package/dist/engine/fix-markers.js +329 -0
  48. package/dist/engine/fix-markers.js.map +1 -0
  49. package/dist/engine/fix-scratch.d.ts +76 -0
  50. package/dist/engine/fix-scratch.js +77 -0
  51. package/dist/engine/fix-scratch.js.map +1 -0
  52. package/dist/engine/github/github.d.ts +302 -5
  53. package/dist/engine/github/github.js +614 -54
  54. package/dist/engine/github/github.js.map +1 -1
  55. package/dist/engine/github/profiles.d.ts +45 -1
  56. package/dist/engine/github/profiles.js +35 -0
  57. package/dist/engine/github/profiles.js.map +1 -1
  58. package/dist/engine/pr-decisions.d.ts +342 -0
  59. package/dist/engine/pr-decisions.js +721 -0
  60. package/dist/engine/pr-decisions.js.map +1 -0
  61. package/dist/engine/pr-escalation.d.ts +152 -0
  62. package/dist/engine/pr-escalation.js +320 -0
  63. package/dist/engine/pr-escalation.js.map +1 -0
  64. package/dist/engine/pr-notes.d.ts +175 -0
  65. package/dist/engine/pr-notes.js +315 -0
  66. package/dist/engine/pr-notes.js.map +1 -0
  67. package/dist/engine/pr-state.d.ts +313 -0
  68. package/dist/engine/pr-state.js +515 -0
  69. package/dist/engine/pr-state.js.map +1 -0
  70. package/dist/engine/review-check.d.ts +200 -0
  71. package/dist/engine/review-check.js +305 -0
  72. package/dist/engine/review-check.js.map +1 -0
  73. package/dist/engine/router.d.ts +27 -0
  74. package/dist/engine/router.js +156 -22
  75. package/dist/engine/router.js.map +1 -1
  76. package/dist/evals-api.d.ts +10 -0
  77. package/dist/evals-api.js +38 -0
  78. package/dist/evals-api.js.map +1 -1
  79. package/dist/index.js +313 -23
  80. package/dist/index.js.map +1 -1
  81. package/dist/sandbox/index.d.ts +13 -0
  82. package/dist/sandbox/index.js +30 -0
  83. package/dist/sandbox/index.js.map +1 -1
  84. package/dist/sandbox/k8s/init-clone.d.ts +5 -0
  85. package/dist/sandbox/k8s/init-clone.js +27 -0
  86. package/dist/sandbox/k8s/init-clone.js.map +1 -1
  87. package/dist/sandbox/k8s/kubernetes-sandbox.d.ts +26 -1
  88. package/dist/sandbox/k8s/kubernetes-sandbox.js +30 -1
  89. package/dist/sandbox/k8s/kubernetes-sandbox.js.map +1 -1
  90. package/dist/state/execution-store.d.ts +27 -0
  91. package/dist/state/execution-store.js +45 -0
  92. package/dist/state/execution-store.js.map +1 -1
  93. package/dist/state/workflow-run-store.d.ts +73 -0
  94. package/dist/state/workflow-run-store.js +106 -24
  95. package/dist/state/workflow-run-store.js.map +1 -1
  96. package/dist/workflows/pr-scope.d.ts +63 -0
  97. package/dist/workflows/pr-scope.js +113 -0
  98. package/dist/workflows/pr-scope.js.map +1 -0
  99. package/dist/workflows/resume.js +113 -8
  100. package/dist/workflows/resume.js.map +1 -1
  101. package/dist/workflows/runner.d.ts +2 -1
  102. package/dist/workflows/runner.js +143 -10
  103. package/dist/workflows/runner.js.map +1 -1
  104. package/dist/workflows/simple.d.ts +280 -1
  105. package/dist/workflows/simple.js +499 -8
  106. package/dist/workflows/simple.js.map +1 -1
  107. package/dist/workflows/target-policy.d.ts +0 -12
  108. package/dist/workflows/target-policy.js +9 -15
  109. package/dist/workflows/target-policy.js.map +1 -1
  110. package/package.json +4 -4
  111. package/skills/README.md +11 -5
  112. package/skills/dependency-impact/SKILL.md +83 -0
  113. package/skills/fixing/SKILL.md +190 -0
  114. package/skills/pr-review/SKILL.md +26 -9
  115. package/workflows/cron-dependabot-ci-fix.yaml +8 -5
  116. package/workflows/cron-review.yaml +14 -5
  117. package/workflows/dependabot-ci-fix.yaml +86 -2
  118. package/workflows/dependabot-pr-merge.yaml +13 -1
  119. package/workflows/pr-fix.yaml +84 -1
  120. package/workflows/pr-review.yaml +7 -0
  121. package/workflows/prompts/dependabot-ci-fix.md +70 -17
  122. package/workflows/prompts/dependabot-pr-merge.md +203 -80
  123. package/workflows/prompts/diagnose-ci.md +96 -0
  124. package/workflows/prompts/pr-fix.md +63 -4
@@ -1,16 +1,26 @@
1
1
  import { randomUUID } from "crypto";
2
2
  import { routeEvent } from "./router.js";
3
3
  import { runDashboardUrl } from "../notify/model.js";
4
- import { getRuntimeConfig } from "../config/config.js";
5
- import { PR_FIX_SHAPED_WORKFLOWS, DEPENDENCY_WEBHOOK_WORKFLOWS } from "../workflows/target-policy.js";
6
- import { REQUIRES_HUMAN_LABEL } from "../cron/dependabot-discovery.js";
4
+ import { getRuntimeConfig, getBotName, defaultFixConfig, defaultDependenciesConfig, defaultReviewConfig, } from "../config/config.js";
5
+ import { PR_FIX_SHAPED_WORKFLOWS } from "../workflows/target-policy.js";
6
+ import { resolvePrState, prScopedWorkflows } from "./pr-state.js";
7
+ import { resolveDispatchDisposition, reviewCheckPlacement, } from "./pr-decisions.js";
8
+ import { postReviewCheckForSkip } from "./review-check.js";
9
+ import { escalatePr, noticeForkPr } from "./pr-escalation.js";
7
10
  /**
8
11
  * Turn an EventEnvelope into a workflow dispatch (or an in-process handler
9
12
  * run). Classifies via `route`, then acts on the decision. Extracted from the
10
13
  * former `registry.onEvent` closure so every event branch is testable.
11
14
  */
12
15
  export async function dispatch(envelope, deps) {
13
- const route = await (deps.route ?? routeEvent)(envelope, { db: deps.db, github: deps.github });
16
+ const route = await (deps.route ?? routeEvent)(envelope, {
17
+ db: deps.db,
18
+ github: deps.github,
19
+ // Threaded one level up so the `pr.labeled` branch can see a repo's own
20
+ // `review.requestLabel`. Same resolver, same 60 s cache, so the resolution
21
+ // this triggers usually warms the one the dispatch gate makes below.
22
+ resolveRepoPolicy: deps.resolveRepoPolicy,
23
+ });
14
24
  if (route.action === "ignore") {
15
25
  return { kind: "ignored", reason: route.reason };
16
26
  }
@@ -53,40 +63,104 @@ export async function dispatch(envelope, deps) {
53
63
  }
54
64
  return { kind: "handled", handler };
55
65
  }
66
+ // ── The PR state machine (09-state-machine.md) ────────────────────────────
67
+ //
68
+ // Everything past this point is a workflow dispatch, so this is where the
69
+ // pull request's state is resolved — ONCE — for every PR-scoped workflow.
70
+ // The snapshot then answers three questions that used to be asked by three
71
+ // separate pieces of code, each fetching an overlapping subset and each free
72
+ // to disagree: is a run already in flight, may this run at all, and what do
73
+ // the prompts render. It rides down to `dispatchWorkflow` on `_prState`, so
74
+ // the enrichment there costs no second round of API calls.
75
+ //
76
+ // An explicit `@bot` request is an intentional override of the label guard
77
+ // and the per-SHA dedup — the same carve-out `target-policy.ts` already
78
+ // documents for the dependency guard, and the same discriminator the old
79
+ // `dependencyDedupSkip` used (it keyed off the webhook event type, not the
80
+ // handler, precisely so a human asking directly was never gated).
81
+ const explicitRequest = envelope.type === "message" ||
82
+ envelope.type === "comment.created" ||
83
+ envelope.type === "pr_review_comment.created" ||
84
+ // A review requested BY NAME — the reviewer picker, or the Re-run button on
85
+ // our own `last-light/review` check. Both are a human pointing at us, so
86
+ // both override mode, draft and dedup exactly as `@bot review` does. The
87
+ // router has already dropped requests naming somebody else.
88
+ envelope.type === "pr.review_requested";
89
+ // Which route this dispatch arrived on, for `resolveReviewTrigger`. Only
90
+ // `checks-settled` satisfies `after-checks`; `attention` is what defers.
91
+ const reviewRoute = envelope.type === "pr.checks_settled" ? "checks-settled" : "attention";
92
+ const prState = await resolvePrStateForDispatch(handler, context, deps);
93
+ if (prState)
94
+ context._prState = prState;
56
95
  // Guard against double-dispatching the same work. Everything past this
57
96
  // point is a workflow dispatch (or a resume of one), so a run already in
58
97
  // flight for this trigger is a no-op.
98
+ //
99
+ // For a PR-scoped workflow the authority is the snapshot's `runInFlight`
100
+ // (09 → S4), NOT `db.executions.isRunning`. **That guard has never worked at
101
+ // all for them**: it is called with a bare workflow name and a bare issue
102
+ // number, while every phase ledger row is written by `phase-executor.ts`
103
+ // with `skill = "<workflow>:<phase>"` and `trigger_id = "owner/repo#N"`, so
104
+ // no row can ever match on both and it has always returned false. The lock
105
+ // now lives in the DECISION functions (`runLockDrop`), so the cron fan-out
106
+ // and `/api/run` obey it too — it used to be read here and in
107
+ // `resolveReviewTrigger` only, which left `fix-red-dependency-prs` free to
108
+ // dispatch `dependabot-ci-fix` onto a PR with a live `pr-fix` run.
59
109
  const triggerId = String(envelope.issueNumber || envelope.id);
60
- if (deps.db.executions.isRunning(handler, triggerId)) {
110
+ if (!prState && deps.db.executions.isRunning(handler, triggerId)) {
61
111
  console.log(`[event] Skipping: ${handler} already running for ${triggerId}`);
62
112
  if (envelope.type === "message") {
63
113
  await envelope.reply(`That task is already running. Use /status to check progress.`);
64
114
  }
65
115
  return { kind: "skipped", reason: `${handler} already running for ${triggerId}` };
66
116
  }
67
- // Dependency-PR idempotency: on the AUTOMATED check_suite webhook path, skip
68
- // (before any sandbox) a PR the bot has already handled — one carrying
69
- // `requires-human`, or one whose current head SHA we already assessed. A
70
- // multi-app repo re-fires a green/red suite and the daily cron overlaps, so
71
- // without this the same PR gets re-assessed repeatedly, burning tokens and
72
- // flooding the queue. A genuinely new push (new head SHA, no requires-human)
73
- // still runs once; a human `@bot` request (comment.created) is NOT gated.
74
- if ((envelope.type === "pr.checks_passed" || envelope.type === "pr.checks_failed") &&
75
- DEPENDENCY_WEBHOOK_WORKFLOWS.has(handler)) {
76
- const skip = await dependencyDedupSkip(handler, context, deps);
77
- if (skip) {
78
- console.log(`[event] Skipping: ${skip.reason}`);
79
- return skip;
117
+ // Should we spend a run on this PR at all? One pure decision over the
118
+ // snapshot, replacing `dependencyDedupSkip` (the `requires-human` +
119
+ // already-assessed pair) and the fork/branch preflight `handlePrFix` used to
120
+ // do with its own second PR read. `{decision, reason}` rather than a bare
121
+ // enum so the log line, the escalation comment and the admin detail panel are
122
+ // three renderings of ONE source instead of three prose variants that drift.
123
+ if (prState) {
124
+ // The repo's `.lastlight/` layer, folded in BEFORE the decision — the same
125
+ // resolution `dispatchWorkflow` makes one level down, hitting the same 60 s
126
+ // cache. Without it this gate read the operator's budgets while the prompt
127
+ // rendered the repo's.
128
+ const policy = prPolicyConfig(await deps.resolveRepoPolicy?.(handler, context));
129
+ const disposition = await applyPrDispatchGate({ workflowName: handler, state: prState, policy, explicitRequest, route: reviewRoute, logPrefix: "[event]" }, deps);
130
+ if (disposition.decision === "skip") {
131
+ // The two responses that belong to THIS route rather than to the decision
132
+ // — both keyed on a typed field, never on the reason prose.
133
+ //
134
+ // A maintainer whose explicit request lost the run lock is told so; one
135
+ // who is silently dropped will just ask again. (The lock is not policy but
136
+ // a physical constraint, so `@bot` does not override it — the cron
137
+ // re-pickup is what makes dropping sound.)
138
+ if (disposition.runInFlight && explicitRequest) {
139
+ await envelope.reply(`I'm already working on this PR (\`${disposition.runInFlight.workflow}\`). I'll finish that run first — ask me again if it doesn't cover what you need.`);
140
+ }
141
+ // A fork PR is the one skip a human is owed an explanation for on the PR
142
+ // itself: there is nothing wrong with their change, we simply have no
143
+ // branch to push to.
144
+ //
145
+ // Keyed on the DECISION, not on `prState.isFork`. `isFork` is true on
146
+ // every skip a fork PR takes, so it used to explain a decision that was
147
+ // not taken — a run-lock drop, a deferred review or a head-SHA dedup on a
148
+ // fork PR each earned "I can't apply fixes to this PR", once per skip.
149
+ // `noticeForkPr` supplies the other half, the de-duplication (#256).
150
+ if (disposition.forkPr) {
151
+ await noticeForkPr(handler, prState, deps);
152
+ }
153
+ return { kind: "skipped", reason: `${handler}: ${disposition.reason}` };
80
154
  }
81
155
  }
82
156
  // PR fix: lightweight fix-and-push driven by CI failures / a comment. Also
83
157
  // covers pr-fix-shaped workflows (e.g. dependabot-ci-fix) reached via the
84
- // classifier — they all need the PR head branch + failed-check summary that
85
- // handlePrFix resolves, and it dispatches the passed `handler` unchanged.
158
+ // classifier — they all need the PR head branch the snapshot resolved, and
159
+ // it dispatches the passed `handler` unchanged.
86
160
  if ((routeKey === "github.pr_fix" || PR_FIX_SHAPED_WORKFLOWS.has(handler)) &&
87
161
  context.prNumber &&
88
162
  context.repo) {
89
- return handlePrFix(context, handler, deps);
163
+ return handlePrFix(context, handler, deps, prState);
90
164
  }
91
165
  if (handler === "explore-reply") {
92
166
  return handleExploreReply(envelope, context, deps);
@@ -107,55 +181,124 @@ export async function dispatch(envelope, deps) {
107
181
  return handleMessageDispatch(envelope, handler, workflowContext, deps);
108
182
  }
109
183
  // Webhook-triggered workflows (the remaining default path).
110
- return handleWebhookDispatch(envelope, handler, routeKey, workflowContext, deps);
184
+ return handleWebhookDispatch(handler, workflowContext, deps);
111
185
  }
112
186
  /**
113
- * Pre-sandbox idempotency check for a dependency-PR webhook. One cheap PR read
114
- * yields two skip signals:
115
- * • the PR carries `requires-human` → a maintainer owns it; do nothing.
116
- * • the PR's live head SHA equals the SHA of the last SUCCEEDED run of this
117
- * workflow for the PR → there's nothing new to assess (a re-fired suite,
118
- * cron/webhook overlap).
119
- * Returns a `skipped` outcome to short-circuit, or null to let the run proceed.
120
- * A read failure returns null (fail-open) — the workflow's own `ASSESSMENT_COMPLETE`
121
- * marker + the LLM "skip if already commented" instruction remain as backstops,
122
- * and we'd rather occasionally re-run than drop a genuine event.
187
+ * Resolve the PR snapshot for this dispatch, or null when the event is not a
188
+ * PR-scoped one.
189
+ *
190
+ * Null is a real answer, not a failure: it means "no PR policy governs this
191
+ * handler", and the caller falls back to the generic already-running guard.
192
+ * `resolvePrState` itself never throws — every live read is best-effort and
193
+ * degrades to a value that cannot cause a skip (see `PrState.readErrors`), so
194
+ * a GitHub outage can slow us down but can never drop a genuine event.
123
195
  */
124
- async function dependencyDedupSkip(handler, context, deps) {
125
- const github = deps.github;
126
- const repoStr = typeof context.repo === "string" ? context.repo : undefined;
127
- const prNumber = typeof context.prNumber === "number" ? context.prNumber : undefined;
128
- if (!github || !repoStr || !prNumber)
196
+ async function resolvePrStateForDispatch(handler, context, deps) {
197
+ if (!prScopedWorkflows().has(handler))
129
198
  return null;
199
+ const repoStr = typeof context.repo === "string" ? context.repo : "";
200
+ const prNumber = typeof context.prNumber === "number" ? context.prNumber : undefined;
130
201
  const [owner, name] = repoStr.split("/");
131
- if (!owner || !name)
202
+ if (!owner || !name || !prNumber)
132
203
  return null;
133
- let pr;
134
- try {
135
- pr = await github.getPullRequest(owner, name, prNumber);
136
- }
137
- catch (err) {
138
- const msg = err instanceof Error ? err.message : String(err);
139
- console.warn(`[dispatch] dependency dedup read failed for ${repoStr}#${prNumber}: ${msg}`);
140
- return null;
141
- }
142
- const labels = (pr.labels ?? [])
143
- .map((l) => (typeof l === "string" ? l : l?.name ?? ""))
144
- .filter(Boolean);
145
- if (labels.includes(REQUIRES_HUMAN_LABEL)) {
146
- return { kind: "skipped", reason: `${handler}: ${repoStr}#${prNumber} is ${REQUIRES_HUMAN_LABEL}` };
147
- }
148
- const headSha = pr.head?.sha;
149
- const triggerId = `${repoStr}#${prNumber}`;
150
- const lastRun = deps.db.runs.latestSucceededForTrigger(handler, triggerId);
151
- const lastSha = lastRun?.context?.headSha;
152
- if (headSha && typeof lastSha === "string" && headSha === lastSha) {
153
- return {
154
- kind: "skipped",
155
- reason: `${handler}: already assessed ${repoStr}#${prNumber} at ${headSha.slice(0, 7)}`,
156
- };
204
+ return resolvePrState(owner, name, prNumber, {
205
+ github: deps.github,
206
+ db: deps.db,
207
+ botLogin: getRuntimeConfig()?.botLogin ?? "",
208
+ });
209
+ }
210
+ /**
211
+ * The three policy blocks the dispatch gate reads — the operator's config with
212
+ * the target repo's `.lastlight/` layer folded in.
213
+ *
214
+ * ONE config, one decision, every route. This used to be operator-only in the
215
+ * dispatcher and repo-clamped in `dispatchWorkflow`, which failed silently and
216
+ * asymmetrically: the gate used one number while `renderContext` rendered
217
+ * another to the prompt and `lastlight repo config show` reported the same one
218
+ * the prompt got. The repo layer may only ever clamp TIGHTER (add-only, see
219
+ * `packages/shared/src/repo-config-schema.ts`), so the old seam always erred by
220
+ * letting a run through the repo would have refused — which is exactly the
221
+ * direction a budget cap must not err in.
222
+ *
223
+ * `layer` comes from {@link DispatchDeps.resolveRepoPolicy}, which is the same
224
+ * `resolveRepoRunConfig` call `dispatchWorkflow` makes; the `?? operator`
225
+ * fallbacks mirror its `repoConfig?.fix ?? config.fix` exactly.
226
+ */
227
+ export function prPolicyConfig(layer) {
228
+ const rt = getRuntimeConfig();
229
+ return {
230
+ fix: layer?.fix ?? rt?.fix ?? defaultFixConfig(),
231
+ dependencies: layer?.dependencies ?? rt?.dependencies ?? defaultDependenciesConfig(),
232
+ review: layer?.review ?? rt?.review ?? defaultReviewConfig(),
233
+ };
234
+ }
235
+ /**
236
+ * THE dispatch gate — decide, log, and apply the decision's own consequences.
237
+ *
238
+ * Both routes call this one function: the dispatcher for webhook/comment
239
+ * events, and `dispatchWorkflow` for the cron fan-out, `/api/run` and resume.
240
+ * They used to carry two hand-kept-in-step copies of it, reading two different
241
+ * configs (see {@link prPolicyConfig}) and diverging on which side effects a
242
+ * skip earns.
243
+ *
244
+ * The two consequences that belong to the DECISION rather than to the route are
245
+ * applied here, so neither can be forgotten by one caller:
246
+ *
247
+ * - a **deferred review** leaves the placeholder check that says "not yet"
248
+ * (itself route-limited inside `postReviewCheckForSkip` — a statement about a
249
+ * head SHA belongs on PR attention, not on every sweep tick);
250
+ * - a skip that is **terminal for this problem** is labelled and explained, and
251
+ * RECORDS A RUN ROW without which `escalatedAtSha` never persists and the next
252
+ * dispatch reads our own label as a human's permanent hold (09 → D1).
253
+ *
254
+ * What is NOT applied here is the route's own courtesy: replying to the human
255
+ * whose request was dropped, and the fork-PR notice. Both are answers to a
256
+ * person who is watching, so they belong to the route that has one — a daily
257
+ * cron re-posting a fork notice for the life of the PR is spam, not
258
+ * transparency. The caller keys them on the TYPED fields the deciding branch
259
+ * set (`decision.runInFlight`, `state.isFork`), never on the reason prose.
260
+ */
261
+ export async function applyPrDispatchGate(args, deps) {
262
+ const { workflowName, state, policy, route } = args;
263
+ const disposition = resolveDispatchDisposition(workflowName, state, policy, {
264
+ explicitRequest: args.explicitRequest,
265
+ dedupOnHeadSha: true,
266
+ route,
267
+ });
268
+ console.log(`${args.logPrefix} ${workflowName} ${state.repo}#${state.prNumber}: ` +
269
+ `${disposition.decision} — ${disposition.reason}`);
270
+ if (disposition.decision !== "skip")
271
+ return disposition;
272
+ // A run-lock drop is a "come back later", not a verdict: no placeholder, no
273
+ // label, no comment, no run row. Returned to the caller so the route that has
274
+ // a human on the other end can reply.
275
+ if (disposition.runInFlight)
276
+ return disposition;
277
+ // Neither is a failed PR read (`readDegradedDrop`), and here the reason is
278
+ // sharper: every side effect below writes to a pull request we could not
279
+ // read. Labelling `requires-human` off a `labels: []` default, or posting a
280
+ // review placeholder against a head SHA we do not have, would each be a
281
+ // durable statement made on no information.
282
+ if (disposition.readDegraded)
283
+ return disposition;
284
+ if (disposition.review) {
285
+ await postReviewCheckForSkip({
286
+ workflowName,
287
+ placement: reviewCheckPlacement(disposition.review, policy.review),
288
+ postsCheck: policy.review.postsCheck,
289
+ route,
290
+ owner: state.repo.split("/")[0] ?? "",
291
+ repo: state.repo.split("/")[1] ?? "",
292
+ headSha: state.headSha,
293
+ }, {
294
+ github: deps.github,
295
+ botLogin: deps.botLogin ?? getRuntimeConfig()?.botLogin,
296
+ botMention: deps.botMention ?? `@${getBotName()}`,
297
+ });
298
+ return disposition;
157
299
  }
158
- return null;
300
+ await escalatePr(workflowName, state, disposition, policy.fix, deps);
301
+ return disposition;
159
302
  }
160
303
  /**
161
304
  * React 👀 on the GitHub subject that triggered this event, as an immediate
@@ -247,121 +390,22 @@ async function handleMessageDispatch(envelope, handler, workflowContext, deps) {
247
390
  return { kind: "dispatched", workflow: handler };
248
391
  }
249
392
  /**
250
- * Webhook-triggered workflow dispatch. When `reviewPostsCheck` is on and this
251
- * is a PR-attention event routed to pr-review, posts an in-progress
252
- * `last-light/review` Check Run on the PR head SHA so branch protection can
253
- * gate the merge, then completes it from the workflow's terminal result.
393
+ * Webhook-triggered workflow dispatch.
394
+ *
395
+ * It used to own the `last-light/review` Check Run too — created here for the
396
+ * three PR-attention routes only, and completed inside a `.then()` chained onto
397
+ * the in-memory workflow promise. Both halves were wrong (09 → S2): a
398
+ * cron-, comment-, Slack- or CLI-triggered review never got a check at all, and
399
+ * the one that did got stranded `in_progress` on every deploy, every
400
+ * queued-then-resumed run, every cancellation and every crash. The lifecycle now
401
+ * lives in `./review-check.ts` — created once at the `dispatchWorkflow` choke
402
+ * point every route crosses, completed from the run's terminal transition — so
403
+ * this function is back to doing one thing.
254
404
  */
255
- async function handleWebhookDispatch(envelope, handler, routeKey, workflowContext, deps) {
256
- const { github } = deps;
257
- const isPrReviewEvent = envelope.type === "pr.opened" ||
258
- envelope.type === "pr.synchronize" ||
259
- envelope.type === "pr.reopened";
260
- const wantReviewCheck = deps.reviewPostsCheck &&
261
- isPrReviewEvent &&
262
- (routeKey === "github.pr_opened" ||
263
- routeKey === "github.pr_synchronize" ||
264
- routeKey === "github.pr_reopened" ||
265
- handler === "pr-review") &&
266
- !!github &&
267
- !!envelope.repo &&
268
- typeof envelope.prNumber === "number";
269
- let prCheckRunId;
270
- let prOwner = "";
271
- let prRepoName = "";
272
- let prNumberForCheck = 0;
273
- if (wantReviewCheck && github) {
274
- [prOwner, prRepoName] = envelope.repo.split("/");
275
- prNumberForCheck = envelope.prNumber;
276
- try {
277
- const prHeadSha = await github.getPullRequestHeadSha(prOwner, prRepoName, prNumberForCheck);
278
- prCheckRunId = await github.createCheckRun(prOwner, prRepoName, prHeadSha, "last-light/review", {
279
- output: {
280
- title: "Review in progress",
281
- summary: "Last Light is reviewing this PR. The conclusion will land here when the review completes.",
282
- },
283
- });
284
- console.log(`[check] Posted in-progress check ${prCheckRunId} for ${prOwner}/${prRepoName}#${prNumberForCheck} on ${prHeadSha.slice(0, 7)}`);
285
- }
286
- catch (err) {
287
- const msg = err instanceof Error ? err.message : String(err);
288
- console.warn(`[check] failed to create in-progress check: ${msg}`);
289
- }
290
- }
291
- // As soon as the run row exists, point the in-progress check at its dashboard
292
- // deep link so a reviewer can click the check's "Details" straight through to
293
- // the live run. Best-effort + only when the check and a public URL both exist.
294
- const onRunStart = async (runId) => {
295
- if (prCheckRunId === undefined || !github)
296
- return;
297
- const detailsUrl = runDashboardUrl(deps.publicUrl, runId, handler);
298
- if (!detailsUrl)
299
- return;
300
- try {
301
- await github.updateCheckRun(prOwner, prRepoName, prCheckRunId, { detailsUrl });
302
- console.log(`[check] linked check ${prCheckRunId} → ${detailsUrl}`);
303
- }
304
- catch (err) {
305
- const msg = err instanceof Error ? err.message : String(err);
306
- console.warn(`[check] failed to set details_url on check ${prCheckRunId}: ${msg}`);
307
- }
308
- };
309
- const workflowPromise = deps.dispatchWorkflow(handler, { ...workflowContext, _triggerType: "webhook" }, onRunStart);
310
- if (prCheckRunId !== undefined && github) {
311
- const checkId = prCheckRunId;
312
- const owner = prOwner;
313
- const repo = prRepoName;
314
- const prNumber = prNumberForCheck;
315
- workflowPromise
316
- .then(async (result) => {
317
- // Queued: the run hasn't started yet — leave the in-progress check as-is
318
- // rather than completing it with a misleading conclusion. The admission
319
- // path's resume will run the full workflow and the terminal review
320
- // comment will eventually update the PR. (Documented limitation: the
321
- // check stays in-progress until admission fires.)
322
- if (result.queued)
323
- return;
324
- try {
325
- // Re-fetch head SHA in case the PR was rebased mid-review.
326
- const headSha = await github.getPullRequestHeadSha(owner, repo, prNumber);
327
- const review = await github.getLatestBotReview(owner, repo, prNumber, headSha, getRuntimeConfig()?.botLogin);
328
- const conclusion = !result.success
329
- ? "neutral"
330
- : review?.state === "APPROVED"
331
- ? "success"
332
- : review?.state === "CHANGES_REQUESTED"
333
- ? "failure"
334
- : "neutral";
335
- await github.updateCheckRun(owner, repo, checkId, {
336
- status: "completed",
337
- conclusion,
338
- output: {
339
- title: `Review ${conclusion === "success" ? "approved" : conclusion === "failure" ? "requested changes" : "completed"}`,
340
- summary: review?.body?.slice(0, 65000) || "Review complete.",
341
- },
342
- });
343
- console.log(`[check] Completed check ${checkId} → ${conclusion}`);
344
- }
345
- catch (err) {
346
- const msg = err instanceof Error ? err.message : String(err);
347
- console.warn(`[check] failed to complete check ${checkId}: ${msg}`);
348
- }
349
- })
350
- .catch(async (err) => {
351
- const msg = err instanceof Error ? err.message : String(err);
352
- try {
353
- await github.updateCheckRun(owner, repo, checkId, {
354
- status: "completed",
355
- conclusion: "neutral",
356
- output: { title: "Review errored", summary: `Workflow threw: ${msg.slice(0, 1000)}` },
357
- });
358
- }
359
- catch {
360
- /* ignore — best effort */
361
- }
362
- });
363
- }
364
- workflowPromise.catch((err) => {
405
+ async function handleWebhookDispatch(handler, workflowContext, deps) {
406
+ deps
407
+ .dispatchWorkflow(handler, { ...workflowContext, _triggerType: "webhook" })
408
+ .catch((err) => {
365
409
  const msg = err instanceof Error ? err.message : String(err);
366
410
  console.error(`[event] Unhandled error in workflow ${handler}: ${msg}`);
367
411
  });
@@ -452,11 +496,23 @@ async function handleBuild(envelope, context, handler, deps) {
452
496
  return { kind: "dispatched", workflow: handler };
453
497
  }
454
498
  /**
455
- * Lightweight PR fix — fix-and-push, no full build cycle. Resolves the PR's
456
- * head branch and CI failures (needed by the architect/executor), then
457
- * dispatches the `pr-fix` workflow. Bails if the branch can't be determined.
499
+ * Lightweight PR fix — fix-and-push, no full build cycle.
500
+ *
501
+ * This used to be the second of six places that read a PR's state: it fetched
502
+ * the PR again for the head branch, ran its own fork guard, and downloaded the
503
+ * failed-check text — none of which the cron fan-out got, because that calls
504
+ * `dispatchWorkflow` DIRECTLY and never crosses this function. All of it is now
505
+ * one field lookup on the snapshot, and the enrichment the prompts render
506
+ * (`ciSection`, `baseBranch`, `attempt`, `priorAttempts`, …) is projected once
507
+ * at `dispatchWorkflow` by `renderContext`, so both routes carry identical
508
+ * context by construction.
509
+ *
510
+ * The fork guard and every other skip already ran in `dispatch` via
511
+ * `resolveDispatchDisposition`; what is left here is the one degenerate case
512
+ * that is not a policy decision — we could not read the PR at all, so there is
513
+ * no branch to fix.
458
514
  */
459
- async function handlePrFix(context, handler, deps) {
515
+ async function handlePrFix(context, handler, deps, state) {
460
516
  const repoStr = context.repo;
461
517
  const [owner, repo] = repoStr.includes("/") ? repoStr.split("/") : ["", repoStr];
462
518
  const prNumber = context.prNumber;
@@ -464,64 +520,25 @@ async function handlePrFix(context, handler, deps) {
464
520
  console.error(`[event] Invalid repo format: ${repoStr}`);
465
521
  return { kind: "ignored", reason: `invalid repo format: ${repoStr}` };
466
522
  }
467
- let prTitle = context.title || "";
468
- let prBody = context.body || "";
469
- let branch = "";
470
- let failedChecks = "";
471
- let isForkPr = false;
472
- let headRepoFullName = null;
473
- if (deps.github) {
474
- try {
475
- const pr = await deps.github.getPullRequest(owner, repo, prNumber);
476
- prTitle = prTitle || pr.title;
477
- prBody = prBody || pr.body || "";
478
- branch = pr.head.ref;
479
- // Cross-repo (fork) PR detection. A fork PR's head branch lives on
480
- // another repo we have no write access to, and its head ref isn't on
481
- // this repo's origin — so there's nothing for pr-fix to clone or push
482
- // to. Bail here, before any sandbox is provisioned. `head.repo` is null
483
- // when the source fork was deleted; treat that as a fork too (the branch
484
- // is gone either way).
485
- headRepoFullName = pr.head.repo?.full_name ?? null;
486
- const baseRepoFullName = pr.base.repo?.full_name ?? `${owner}/${repo}`;
487
- isForkPr = headRepoFullName === null || headRepoFullName !== baseRepoFullName;
488
- failedChecks = await deps.github.getFailedChecks(owner, repo, pr.head.sha);
489
- }
490
- catch (err) {
491
- console.warn(`[event] Could not fetch PR: ${err.message}`);
492
- }
493
- }
494
- if (isForkPr) {
495
- console.log(`[event] pr-fix skipped: PR #${prNumber} is a fork PR ` +
496
- `(head ${headRepoFullName ?? "deleted fork"} ≠ base ${owner}/${repo})`);
497
- if (deps.github) {
498
- const source = headRepoFullName ? `from \`${headRepoFullName}\`` : "from a now-deleted fork";
499
- await deps.github
500
- .postComment(owner, repo, prNumber, `I can't apply fixes to this PR — it comes ${source}, and I have no write access to the ` +
501
- `source branch (nor is its head ref on \`${owner}/${repo}\`). Re-create the change on a ` +
502
- `branch in \`${owner}/${repo}\` and I'll fix it there.`)
503
- .catch((e) => console.warn(`[event] fork-PR notice comment failed: ${e instanceof Error ? e.message : String(e)}`));
504
- }
505
- return { kind: "ignored", reason: `pr-fix not supported for fork PR #${prNumber}` };
506
- }
507
- if (!branch) {
523
+ if (!state?.headRef) {
508
524
  console.error(`[event] Could not determine branch for PR #${prNumber}`);
509
525
  return { kind: "ignored", reason: `could not determine branch for PR #${prNumber}` };
510
526
  }
511
- console.log(`[event] PR fix for ${repoStr}#${prNumber} on branch ${branch}`);
512
- const ciSection = failedChecks && !failedChecks.includes("No failed checks")
513
- ? `CI FAILURES (from GitHub Actions — fix these first):\n${failedChecks}`
514
- : "";
527
+ console.log(`[event] PR fix for ${repoStr}#${prNumber} on branch ${state.headRef}`);
515
528
  deps.dispatchWorkflow(handler, {
516
529
  repo: repoStr,
517
530
  prNumber,
518
- title: prTitle,
519
- body: prBody,
531
+ // The event's own title/body win when it carried them (a comment trigger
532
+ // quotes the PR it was posted on); the snapshot is the fallback and the
533
+ // only source on the check_suite + cron routes.
534
+ title: context.title || state.title,
535
+ body: context.body || state.body,
520
536
  commentBody: context.commentBody || "",
521
537
  sender: context.sender || "unknown",
522
- branch,
523
- failedChecks,
524
- ciSection,
538
+ // Cron-only: WHY the red sweep summoned this PR (checks-failing | behind |
539
+ // dirty | blocked). Nothing in the snapshot can reconstruct it.
540
+ ...(typeof context.reason === "string" ? { reason: context.reason } : {}),
541
+ _prState: state,
525
542
  _triggerType: "webhook",
526
543
  }).catch((err) => {
527
544
  console.error(`[event] PR fix failed:`, err);