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
package/dist/index.js CHANGED
@@ -5,7 +5,7 @@ import { Hono } from "hono";
5
5
  import { serve } from "@hono/node-server";
6
6
  import { loadConfig, resolveModel, resolveVariant, resolveGithubAuth } from "./config/config.js";
7
7
  import { ConnectorRegistry, GitHubWebhookConnector, SlackConnector, SessionManager, MessageDeliveryService } from "./connectors/index.js";
8
- import { dispatch } from "./engine/dispatcher.js";
8
+ import { dispatch, applyPrDispatchGate, prPolicyConfig, } from "./engine/dispatcher.js";
9
9
  import { MessageBatcher } from "./engine/chat/message-batcher.js";
10
10
  import { chatSystemSuffix, handleChatMessage, loadAgentContext } from "./engine/chat/chat.js";
11
11
  import { configureWorkflowAssets, validateAssets, getWorkflow } from "./workflows/loader.js";
@@ -16,6 +16,7 @@ import { StateDb, isTriggerActorType } from "./state/db.js";
16
16
  import { CronScheduler } from "./cron/scheduler.js";
17
17
  import { getJobs } from "./cron/jobs.js";
18
18
  import { dispatchCronWorkflow, fanOutContexts } from "./cron/fanout.js";
19
+ import { CRON_GLOBALLY_ENABLED_KEY, CRON_NAME_KEY, resolveCronRepos } from "./cron/repo-crons.js";
19
20
  import { sweepSandboxes } from "./cron/sandbox-sweep.js";
20
21
  import { sweepK8sSandboxes } from "./sandbox/k8s/sweep.js";
21
22
  import { discoverGreenDependencyPrs, discoverRedDependencyPrs, } from "./cron/dependabot-discovery.js";
@@ -35,10 +36,29 @@ import { readPackageVersion } from "./admin/version.js";
35
36
  import { GitHubClient } from "./engine/github/github.js";
36
37
  import { setInstallationRepos, isManagedRepo, unmanagedReposInContext } from "./managed-repos.js";
37
38
  import { screenForInjection, flagPrefix } from "./engine/screen/screen.js";
38
- import { runSimpleWorkflow, PR_HEADREF_PREPOPULATE_WORKFLOWS, PR_FIX_SHAPED_WORKFLOWS } from "./workflows/simple.js";
39
+ import { runSimpleWorkflow, resolveRepoRunConfig, PR_HEADREF_PREPOPULATE_WORKFLOWS, PR_FIX_SHAPED_WORKFLOWS, } from "./workflows/simple.js";
40
+ import { resolvePrState, prScopedWorkflows } from "./engine/pr-state.js";
41
+ import { renderContext } from "./engine/pr-decisions.js";
42
+ import { REVIEW_WORKFLOW, bindQueuedReviewCheck, installReviewCheckObserver, openAndBindReviewCheck, } from "./engine/review-check.js";
43
+ import { runDashboardUrl } from "./notify/model.js";
44
+ import { harvestFixMarkers } from "./engine/fix-harvest.js";
39
45
  import { resumeOrphanedWorkflows, resumeSimpleRun } from "./workflows/resume.js";
40
46
  import { createAdmissionController } from "./workflows/admission.js";
41
47
  import { ProgressNotifier, GitHubTransport, SlackTransport, } from "./notify/index.js";
48
+ /**
49
+ /**
50
+ * The `review.trigger` ROUTE this dispatch arrived on, off the context key the
51
+ * cron fan-out sets (`_reviewRoute`).
52
+ *
53
+ * The webhook path sets it in the dispatcher, where the event type is still in
54
+ * hand; everything reaching `dispatchWorkflow` cold is either the sweep (which
55
+ * says so) or a hand-triggered run, and `attention` is the conservative default
56
+ * — the one value `after-checks` refuses.
57
+ */
58
+ function reviewRouteFromContext(context) {
59
+ const raw = context._reviewRoute;
60
+ return raw === "sweep" || raw === "checks-settled" || raw === "attention" ? raw : "attention";
61
+ }
42
62
  /**
43
63
  * Pre-flight validation — checks that config is sane before starting any
44
64
  * services. Exits with code 78 (EX_CONFIG) on configuration errors so
@@ -201,6 +221,16 @@ async function main() {
201
221
  : config.githubToken
202
222
  ? GitHubClient.withToken(config.githubToken)
203
223
  : null;
224
+ // The `last-light/review` check is a PROJECTION OF RUN STATE (09 → S2): this
225
+ // is the one wiring that makes every terminal transition — `simple.ts`,
226
+ // `resume.ts`, the queued-run TTL expiry, the admin cancel — conclude an open
227
+ // check, instead of a `.then()` on an in-memory promise that a deploy,
228
+ // a crash or an admission-queued run silently outlives.
229
+ installReviewCheckObserver(db, {
230
+ github,
231
+ botLogin: config.botLogin,
232
+ botMention: `@${config.botName}`,
233
+ });
204
234
  // Discover the repos the App installation can access and seed the managed-repo
205
235
  // list. When the overlay's `managedRepos` is empty this becomes the effective
206
236
  // allowlist (getManagedRepos falls back to it); a configured list still wins.
@@ -265,9 +295,158 @@ async function main() {
265
295
  console.warn(`[dispatch] ${msg}`);
266
296
  return { success: false, error: msg };
267
297
  }
298
+ // Per-repository config layer (issue #180). Resolved at the SAME choke
299
+ // point and for the same reason as the guard above: every trigger path
300
+ // funnels through here, so one call covers webhook, router, cron, `/api/*`
301
+ // and approval-resume alike. Never throws and never fails a run — a GitHub
302
+ // outage or a malformed `.lastlight/lastlight.yml` degrades to the
303
+ // un-overridden operator config with a warning. `github` is `null` in
304
+ // chat-only mode, which skips the layer entirely.
305
+ const { repoConfig, refusal } = await resolveRepoRunConfig(workflowName, context, { client: github });
306
+ if (refusal) {
307
+ // The repo opting itself out via `disabled.workflows`. Same refusal shape
308
+ // as the unmanaged-repo guard, so every caller already handles it.
309
+ const msg = `dispatchWorkflow(${workflowName}): refusing repo-disabled workflow: ${refusal}`;
310
+ console.warn(`[dispatch] ${msg}`);
311
+ return { success: false, error: msg };
312
+ }
313
+ // ── The PR state machine (09-state-machine.md → S3) ────────────────────
314
+ //
315
+ // One resolved snapshot per dispatch, at the SAME choke point and for the
316
+ // same reason as the two guards above: webhook, cron, `/api/*` and resume
317
+ // all funnel through here.
318
+ //
319
+ // The webhook route already resolved it — the dispatcher needs
320
+ // `runInFlight` before it can decide to dispatch at all — and hands it
321
+ // down on `_prState`, so this costs nothing there. The cron fan-out and
322
+ // the direct API triggers arrive COLD and resolve here, which is what
323
+ // finally closes the gap where every nightly `fix-red-dependency-prs` run
324
+ // carried `branch` + `reason` but an EMPTY `{{ciSection}}`, the repo's
325
+ // default branch instead of the PR's real base, and no fork guard at all:
326
+ // the fan-out calls this function directly and never crosses `handlePrFix`.
327
+ const inheritedPrState = context._prState && typeof context._prState === "object"
328
+ ? context._prState
329
+ : null;
330
+ let prState = inheritedPrState;
331
+ if (!prState &&
332
+ prScopedWorkflows().has(workflowName) &&
333
+ owner &&
334
+ repo &&
335
+ typeof context.prNumber === "number") {
336
+ prState = await resolvePrState(owner, repo, context.prNumber, {
337
+ github,
338
+ db,
339
+ botLogin: config.botLogin,
340
+ botName: config.botName,
341
+ });
342
+ // Only the routes that have NOT already decided are gated here. The
343
+ // dispatcher decides for itself so it can reply to a human whose request
344
+ // it dropped; deciding twice would double every skip and every log line.
345
+ // It is the SAME function, reading the SAME repo-clamped config (it is
346
+ // handed `resolveRepoPolicy`, which is this file's `resolveRepoRunConfig`),
347
+ // so the two routes cannot answer differently.
348
+ //
349
+ // A skip writes NO run row, which is exactly why every gate reachable
350
+ // from here is a LIVE precondition rather than a prior run's verdict —
351
+ // a stored verdict read through a path that records nothing freezes, and
352
+ // the PR is then dead with no label, no comment and no explanation
353
+ // (09 → D1). The one exception, an ESCALATING skip, records one itself.
354
+ const disposition = await applyPrDispatchGate({
355
+ workflowName,
356
+ state: prState,
357
+ policy: prPolicyConfig(repoConfig),
358
+ // The cron fan-out marks itself `sweep` — the RELEASE MECHANISM for
359
+ // every PR whose fix chain ended without pushing, and the only route
360
+ // that reaches an `after-checks` PR no further `check_suite` will ever
361
+ // fire for.
362
+ route: reviewRouteFromContext(context),
363
+ // A direct `/api/run` (the CLI, the dashboard) is an operator asking
364
+ // for a REVIEW by hand, and overrides mode, draft and dedup exactly as
365
+ // `@bot review` does. Deliberately narrowed to `pr-review`: the fix
366
+ // family's skips are budgets and live facts rather than policy, and
367
+ // the human override for those already exists on the comment path.
368
+ explicitRequest: workflowName === REVIEW_WORKFLOW && context._triggerType === "api",
369
+ logPrefix: "[dispatch]",
370
+ }, { db, github, botLogin: config.botLogin, botMention: `@${config.botName}` });
371
+ if (disposition.decision === "skip") {
372
+ // Not an error: the harness correctly determined there is nothing to
373
+ // do — including a run-lock drop, which the daily crons re-pick up.
374
+ // Reporting it as a failure would paint a cron tick red and, on the
375
+ // fan-out, count against `failures`.
376
+ return { success: true };
377
+ }
378
+ }
379
+ // ── The `last-light/review` check (09 → S2) ─────────────────────────────
380
+ //
381
+ // Created at the one choke point every route crosses, rather than in the
382
+ // webhook branch of the dispatcher — a cron-, comment-, Slack- or
383
+ // CLI-triggered review used to get no check at all — and completed from the
384
+ // run's TERMINAL TRANSITION, so it can no longer strand `in_progress` across
385
+ // a deploy. Reaching this line means some gate already said "run".
386
+ //
387
+ // CREATION AND PERSISTENCE ARE ONE STEP, and that is the whole of this
388
+ // helper. The check used to be created here, unconditionally, and recorded
389
+ // on `scratch.reviewCheck` only inside `onRunStart` — but `runSimpleWorkflow`
390
+ // returns `{ queued: true }` BEFORE it invokes `onRunStart` when the run is
391
+ // over the concurrency cap (and again on a duplicate trigger for an
392
+ // already-queued run). The check was then created, never persisted, never
393
+ // observed by the terminal observer, and never concluded. The old accidental
394
+ // repair is gone too: while the run is `queued` it counts as active for the
395
+ // trigger, so the 30-minute sweep resolves `run-in-flight` → placement
396
+ // `none` and posts no superseding check. That is precisely the bug 09 → S2
397
+ // exists to fix, reintroduced through the one path that skips `onRunStart`.
398
+ //
399
+ // So: nothing is created until a run ROW exists to hang it on, and it is
400
+ // recorded in the same breath. `onRunStart` covers the ordinary path; the
401
+ // queued path binds after the fact, below, against the row `runSimpleWorkflow`
402
+ // did create before returning.
403
+ const wantsReviewCheck = workflowName === REVIEW_WORKFLOW &&
404
+ (repoConfig?.review ?? config.review).postsCheck &&
405
+ !!prState?.headSha;
406
+ let reviewCheckBound = false;
407
+ const reviewCheckDeps = { github, botLogin: config.botLogin };
408
+ const reviewCheckDetailsUrl = (runId) => runDashboardUrl(config.publicUrl, runId, workflowName);
409
+ const bindReviewCheck = async (runId) => {
410
+ if (!wantsReviewCheck || reviewCheckBound)
411
+ return;
412
+ reviewCheckBound = true;
413
+ await openAndBindReviewCheck(db, runId, {
414
+ owner,
415
+ repo,
416
+ headSha: prState.headSha,
417
+ detailsUrl: reviewCheckDetailsUrl(runId),
418
+ }, reviewCheckDeps);
419
+ };
420
+ /**
421
+ * The queued half. `runSimpleWorkflow` writes the `queued` row and returns
422
+ * before `onRunStart`, so the run id never reaches us — but the ROW exists,
423
+ * keyed by exactly the trigger id `simple.ts` derived from this same
424
+ * context.
425
+ */
426
+ const bindReviewCheckForQueuedRun = async () => {
427
+ if (!wantsReviewCheck || reviewCheckBound)
428
+ return;
429
+ const number = typeof context.issueNumber === "number"
430
+ ? context.issueNumber
431
+ : typeof context.prNumber === "number"
432
+ ? context.prNumber
433
+ : undefined;
434
+ const triggerId = slackTriggerId ?? (number !== undefined ? `${owner}/${repo}#${number}` : undefined);
435
+ if (!triggerId)
436
+ return;
437
+ reviewCheckBound = true;
438
+ await bindQueuedReviewCheck(db, {
439
+ triggerId,
440
+ workflowName,
441
+ owner,
442
+ repo,
443
+ headSha: prState.headSha,
444
+ detailsUrl: reviewCheckDetailsUrl,
445
+ }, reviewCheckDeps);
446
+ };
268
447
  // Pluck the standard fields, leave the rest in `extra` for the workflow
269
448
  // template to consume.
270
- const { _triggerType, repo: _r, issueNumber, prNumber, title, body, labels, sender, commentBody, triggerId: _triggerId, channelId, threadId, prePopulateBranch: ctxPrePopulateBranch, branch: ctxBranch, triggeredBy: ctxTriggeredBy, triggerActorType: ctxTriggerActorType, source: ctxSource, ...rest } = context;
449
+ const { _triggerType, _prState: _inheritedPrState, _reviewRoute: _ignoredReviewRoute, repo: _r, issueNumber, prNumber, title, body, labels, sender, commentBody, triggerId: _triggerId, channelId, threadId, prePopulateBranch: ctxPrePopulateBranch, branch: ctxBranch, triggeredBy: ctxTriggeredBy, triggerActorType: ctxTriggerActorType, source: ctxSource, ...rest } = context;
271
450
  // Actor logging (issue #205): who triggered this run and how. Callers can
272
451
  // set `triggerActorType` explicitly (the cron manual-fire / api routes);
273
452
  // otherwise derive it from the dispatch shape. `triggeredBy` defaults to
@@ -296,16 +475,36 @@ async function main() {
296
475
  extra.channelId = channelId;
297
476
  if (typeof threadId === "string")
298
477
  extra.threadId = threadId;
478
+ // Project the snapshot into the template variables the prompts render, and
479
+ // persist the WHOLE thing on the run context rather than scattered leaves
480
+ // (§S3) — so the run detail panel can show the decisions that were actually
481
+ // taken, with the inputs that produced them, long after the live state has
482
+ // moved on. One projection at one choke point is what makes the webhook and
483
+ // cron dispatches of a `pr-fix`-shaped workflow carry identical context.
484
+ if (prState) {
485
+ Object.assign(extra, renderContext(prState, repoConfig?.fix ?? config.fix, repoConfig?.dependencies ?? config.dependencies));
486
+ extra.prState = prState;
487
+ }
299
488
  // For PR-scoped read workflows, resolve the PR head ref and ask the
300
489
  // sandbox to pre-clone the repo at that branch. The agent then enters
301
490
  // a workspace that's already a checkout of the PR's actual code —
302
491
  // saves a redundant clone_repo MCP call inside the session.
303
492
  //
304
- // pr-fix (and other pr-fix-shaped workflows like dependabot-ci-fix) already
305
- // plumb `branch` through context (set by handlePrFix) because the fix phase
306
- // needs the branch name to push to; we honor that here as the pre-populate
307
- // branch too so the workspace is pre-checked-out at the PR head.
493
+ // The snapshot's head ref is the authority for every PR-scoped workflow —
494
+ // one read, already taken. It replaces the second `getPullRequest` the
495
+ // block below used to issue for the read-only workflows, and it is the
496
+ // only source the cron fan-out ever had for `dependabot-ci-fix` (via the
497
+ // discoverer's `branch`, which stays as the fallback for a snapshot whose
498
+ // PR read failed).
308
499
  let prePopulateBranch = typeof ctxPrePopulateBranch === "string" ? ctxPrePopulateBranch : undefined;
500
+ if (!prePopulateBranch &&
501
+ prState?.headRef &&
502
+ (PR_FIX_SHAPED_WORKFLOWS.has(workflowName) ||
503
+ PR_HEADREF_PREPOPULATE_WORKFLOWS.has(workflowName))) {
504
+ prePopulateBranch = prState.headRef;
505
+ console.log(`[dispatch] ${workflowName}: pre-populating workspace at ${owner}/${repo}@${prePopulateBranch} ` +
506
+ `(base ${prState.baseRef || "?"})`);
507
+ }
309
508
  if (!prePopulateBranch && typeof ctxBranch === "string" && ctxBranch && PR_FIX_SHAPED_WORKFLOWS.has(workflowName)) {
310
509
  prePopulateBranch = ctxBranch;
311
510
  }
@@ -373,6 +572,7 @@ async function main() {
373
572
  triggerId: slackTriggerId,
374
573
  extra,
375
574
  prePopulateBranch,
575
+ repoConfig,
376
576
  };
377
577
  // For workflows where the architect/agent needs to see the full issue
378
578
  // history (e.g. a build greenlit by "@last-light lets build this!" needs
@@ -468,6 +668,9 @@ async function main() {
468
668
  catch {
469
669
  /* unknown workflow — surfaced downstream by runSimpleWorkflow */
470
670
  }
671
+ // Set by `onRunStart` below, read by `onPhaseEnd`. Undefined only for the
672
+ // window before the run row exists, during which no phase can have ended.
673
+ let harvestRunId;
471
674
  let notifier;
472
675
  const reporterProxy = statusChecklist
473
676
  ? {
@@ -543,17 +746,34 @@ async function main() {
543
746
  slackConnector.showTyping(channelId, threadId, threadId).catch(() => { });
544
747
  }
545
748
  },
546
- onPhaseEnd: async (phase, result) => console.log(`[dispatch] ◀ ${workflowName}/${phase}: ${result.success ? "OK" : "FAILED"}`),
547
- onRunStart: notifierOnRunStart
548
- ? async (runId) => {
549
- // Synchronous notifier setup must finish before simple.ts calls
550
- // reporter.start() (the next statement after it invokes this), so
551
- // run it first, then chain any caller-provided onRunStart.
749
+ onPhaseEnd: async (phase, result) => {
750
+ console.log(`[dispatch] ◀ ${workflowName}/${phase}: ${result.success ? "OK" : "FAILED"}`);
751
+ // The marker harvest (09 → S1). This is the ONLY moment the two marker
752
+ // lines exist in memory — `{{phaseOutputs}}` is empty across a run
753
+ // boundary and the shared per-PR workspace is `reset --hard`-ed between
754
+ // runs, so a marker not persisted here is gone for good.
755
+ if (harvestRunId)
756
+ harvestFixMarkers(db, harvestRunId, workflowName, phase, result.output);
757
+ },
758
+ onRunStart: async (runId) => {
759
+ // The run id is not knowable when this object is built — the row is
760
+ // created inside `runSimpleWorkflow` — and `onPhaseEnd` needs it to
761
+ // write the harvest. This callback fires synchronously before the first
762
+ // phase, so the assignment is always in place by the time it is read.
763
+ harvestRunId = runId;
764
+ // Synchronous notifier setup must finish before simple.ts calls
765
+ // reporter.start() (the next statement after it invokes this), so it
766
+ // runs FIRST — before the first `await` in this callback, which is now
767
+ // the check creation below.
768
+ if (notifierOnRunStart)
552
769
  notifierOnRunStart(runId);
553
- if (onRunStart)
554
- await onRunStart(runId);
555
- }
556
- : onRunStart,
770
+ // Create AND bind the review check the moment the row exists — this is
771
+ // what makes it a projection of run state rather than of an in-memory
772
+ // promise, and it is why every terminal path resolves it for free.
773
+ await bindReviewCheck(runId);
774
+ if (onRunStart)
775
+ await onRunStart(runId);
776
+ },
557
777
  };
558
778
  let result;
559
779
  try {
@@ -571,6 +791,14 @@ async function main() {
571
791
  const summary = result.phases.map((p) => `${p.phase}=${p.success ? "ok" : "fail"}`).join(", ");
572
792
  if (result.queued) {
573
793
  console.log(`[dispatch] ${workflowName} queued (concurrency cap reached)`);
794
+ // A queued run never reaches `onRunStart` — `runSimpleWorkflow` returns
795
+ // the moment it writes the `queued` row — so bind the check here instead
796
+ // of leaving the run's only PR-visible artifact unowned. The row is
797
+ // found the same way `simple.ts` found (or created) it: by trigger id.
798
+ // Admission promotes it through `resumeSimpleRun`, which takes no
799
+ // callbacks at all, so this is the ONLY point at which a queued review's
800
+ // check can be bound to its run.
801
+ await bindReviewCheckForQueuedRun();
574
802
  }
575
803
  else if (result.paused) {
576
804
  console.log(`[dispatch] ${workflowName} paused (${summary})`);
@@ -629,9 +857,19 @@ async function main() {
629
857
  // Settle-aware gate: emit a dependency-PR checks event only once the head
630
858
  // SHA's checks have fully settled (green/red), so a multi-app repo fires
631
859
  // one event per SHA — the last suite to complete — not one per suite.
860
+ // `excludeApp` is the self-gating deadlock fix (07 §7.2): our own
861
+ // `last-light/review` check is on the same head SHA, so without it a
862
+ // queued/in-progress review pins this aggregate at `pending` and the
863
+ // settle event that would dispatch the review never fires.
632
864
  getChecksConclusion: github
633
- ? (owner, repo, ref) => github.getChecksConclusion(owner, repo, ref)
865
+ ? (owner, repo, ref) => github.getChecksConclusion(owner, repo, ref, { excludeApp: config.botName })
634
866
  : undefined,
867
+ // Only broaden `check_suite.completed` beyond dependency PRs when the
868
+ // operator's mode actually consumes a settle event. Deliberately the
869
+ // OPERATOR's value, not a repo's: emitting is what costs event volume,
870
+ // and a repo that opts itself into `after-checks` under an `eager`
871
+ // operator is covered by the 30-minute `check-prs-awaiting-review` sweep.
872
+ reviewTrigger: () => config.review.trigger,
635
873
  });
636
874
  registry.register(githubConnector);
637
875
  }
@@ -665,12 +903,24 @@ async function main() {
665
903
  // introduce a new sweep. The harness `github` client (App auth) is passed to
666
904
  // every discoverer, so a discoverer only needs the subset of it it uses.
667
905
  const PR_DISCOVERERS = {
668
- "green-dependency-prs": discoverGreenDependencyPrs,
669
- "red-dependency-prs": discoverRedDependencyPrs,
906
+ // The green sweep's notion of "green" must match the webhook's: on a repo
907
+ // with no *required* checks, `mergeable_state: "clean"` is true for a PR
908
+ // whose CI is red. `requireSettledChecks` makes it ask the checks too.
909
+ "green-dependency-prs": (repos, gh, opts) => discoverGreenDependencyPrs(repos, gh, {
910
+ ...opts,
911
+ requireSettledChecks: config.dependencies.requireSettledChecks,
912
+ botName: config.botName,
913
+ }),
914
+ "red-dependency-prs": (repos, gh, opts) => discoverRedDependencyPrs(repos, gh, { ...opts, botName: config.botName }),
670
915
  // The pr-review cron: find open PRs awaiting review and fan out one single-PR
671
916
  // pr-review run each. Replaces the old `mode: scan` review run, which ran the
672
917
  // whole listing/reviewing inside the sandbox with a static token it couldn't
673
918
  // re-mint and no way to hand its chosen PR to post-review.
919
+ //
920
+ // A pure CANDIDATE FINDER (09 → S2): it filters nothing but "open, not ours".
921
+ // Draft, already-reviewed-at-this-SHA, run-in-flight and the trigger mode are
922
+ // all decided once by `resolveReviewTrigger` at the dispatch choke point,
923
+ // which the webhook route crosses too.
674
924
  "prs-awaiting-review": (repos, gh, opts) => discoverPrsAwaitingReview(repos, gh, { ...opts, botLogin: config.botLogin }),
675
925
  };
676
926
  // Construct the cron scheduler before mounting admin so the dashboard can
@@ -690,10 +940,35 @@ async function main() {
690
940
  const discoverKey = typeof context.discover === "string" ? context.discover : undefined;
691
941
  const discoverer = discoverKey ? PR_DISCOVERERS[discoverKey] : undefined;
692
942
  if (discoverer) {
693
- const repos = Array.isArray(context.repos)
943
+ const candidates = Array.isArray(context.repos)
694
944
  ? context.repos.filter((r) => typeof r === "string")
695
945
  : [];
696
- const prs = github
946
+ // Narrow to the repos that actually participate in THIS cron before
947
+ // discovering anything (issue #180). A discovery cron bypasses
948
+ // `dispatchCronWorkflow` — it fans out per discovered PR, not per repo —
949
+ // so without this it would never consult a repo's `.lastlight/` cron
950
+ // opt-out and a repo that dropped out of e.g. `dependabot-merge` would
951
+ // still get runs. Resolved exactly the way `cron/fanout.ts` resolves it:
952
+ // the cron's name arrives in the context (`jobs.ts`), a missing name means
953
+ // a caller that built its own context and the list is used verbatim, and
954
+ // an absent `_cronGloballyEnabled` means "on". Non-blocking by
955
+ // construction — warm layers come from cache, misses are fetched
956
+ // concurrently, and one repo's failure degrades to its inherited
957
+ // behaviour rather than aborting the tick.
958
+ const cronName = typeof context[CRON_NAME_KEY] === "string" ? context[CRON_NAME_KEY] : "";
959
+ const repos = cronName
960
+ ? (await resolveCronRepos({
961
+ cron: cronName,
962
+ repos: candidates,
963
+ globallyEnabled: context[CRON_GLOBALLY_ENABLED_KEY] !== false,
964
+ })).repos
965
+ : candidates;
966
+ if (repos.length !== candidates.length) {
967
+ console.log(`[cron] ${cronName}: ${repos.length}/${candidates.length} repo(s) participate in this cron`);
968
+ }
969
+ // Every repo opted out (or a globally-off cron nobody opted into) — no
970
+ // discovery calls, no dispatches, no failure. A cheap no-op tick.
971
+ const prs = github && repos.length
697
972
  ? await discoverer(repos, github, { log: (m) => console.log(m) })
698
973
  : [];
699
974
  console.log(`[cron] ${workflowName}: ${prs.length} ${discoverKey} across ${repos.length} repo(s)`);
@@ -708,6 +983,12 @@ async function main() {
708
983
  // Also red-sweep only — why it was summoned (checks-failing | behind |
709
984
  // dirty | blocked), threaded into the ci-fix prompt as `{{reason}}`.
710
985
  ...(pr.reason ? { reason: pr.reason } : {}),
986
+ // The review sweep announces itself, because `resolveReviewTrigger`
987
+ // treats it differently from a PR-attention event: `after-checks` will
988
+ // not fire on attention, and the sweep is the RELEASE MECHANISM for
989
+ // every PR whose fix chain ended without pushing — no new commit
990
+ // exists, so no further `check_suite` will ever fire for it (09 → S2).
991
+ ...(discoverKey === "prs-awaiting-review" ? { _reviewRoute: "sweep" } : {}),
711
992
  }));
712
993
  ({ dispatched, failures } = await fanOutContexts(workflowName, contexts, dispatchWorkflow));
713
994
  }
@@ -947,8 +1228,17 @@ async function main() {
947
1228
  // sessionManager internally; the dispatcher uses resumeAgentSessionId only
948
1229
  // to decide whether to persist a newly-minted agent session id.
949
1230
  runChat: (message, messagingSessionId, sender) => handleChatMessage(message, messagingSessionId, sender, sessionManager, { chatRunner, sessionsHomeDir: config.sessionsDir }, { model: resolveModel(config.models, "chat"), maxTurns: 10 }),
950
- reviewPostsCheck: config.reviewPostsCheck,
951
1231
  publicUrl: config.publicUrl,
1232
+ // ONE config at the dispatch gate. The dispatcher decides for itself (it
1233
+ // has to — it replies to the human whose request it dropped, and its
1234
+ // dispatches are fire-and-forget), so the way to keep it from carrying a
1235
+ // second, operator-only view of policy is to hand it the very same
1236
+ // resolution `dispatchWorkflow` performs below. `fetchRepoLayer` memoises
1237
+ // per repo for 60 s, so the pair costs one conditional request between them.
1238
+ resolveRepoPolicy: async (workflowName, context) => {
1239
+ const { repoConfig } = await resolveRepoRunConfig(workflowName, context, { client: github });
1240
+ return repoConfig;
1241
+ },
952
1242
  };
953
1243
  // Wire Slack approval buttons into the SAME approval-resolution path as the
954
1244
  // `/approve` slash command. The connector verifies + parses the button click