lastlight-core 0.32.1 → 0.33.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 (74) hide show
  1. package/config/default.yaml +81 -0
  2. package/dist/admin/board-cache.d.ts +81 -0
  3. package/dist/admin/board-cache.js +301 -0
  4. package/dist/admin/board-cache.js.map +1 -0
  5. package/dist/admin/board-stream.d.ts +47 -0
  6. package/dist/admin/board-stream.js +45 -0
  7. package/dist/admin/board-stream.js.map +1 -0
  8. package/dist/admin/board.d.ts +264 -0
  9. package/dist/admin/board.js +376 -0
  10. package/dist/admin/board.js.map +1 -0
  11. package/dist/admin/routes.js +943 -13
  12. package/dist/admin/routes.js.map +1 -1
  13. package/dist/config/config.d.ts +88 -0
  14. package/dist/config/config.js +163 -0
  15. package/dist/config/config.js.map +1 -1
  16. package/dist/connectors/github-webhook.d.ts +16 -0
  17. package/dist/connectors/github-webhook.js +104 -8
  18. package/dist/connectors/github-webhook.js.map +1 -1
  19. package/dist/connectors/types.d.ts +9 -2
  20. package/dist/cron/issue-discovery.d.ts +120 -0
  21. package/dist/cron/issue-discovery.js +127 -0
  22. package/dist/cron/issue-discovery.js.map +1 -0
  23. package/dist/cron/runner.d.ts +25 -1
  24. package/dist/cron/runner.js +53 -10
  25. package/dist/cron/runner.js.map +1 -1
  26. package/dist/engine/build-decisions.d.ts +91 -0
  27. package/dist/engine/build-decisions.js +295 -0
  28. package/dist/engine/build-decisions.js.map +1 -0
  29. package/dist/engine/build-gate.d.ts +78 -0
  30. package/dist/engine/build-gate.js +355 -0
  31. package/dist/engine/build-gate.js.map +1 -0
  32. package/dist/engine/executors/shared.d.ts +1 -0
  33. package/dist/engine/executors/shared.js +13 -2
  34. package/dist/engine/executors/shared.js.map +1 -1
  35. package/dist/engine/github/github-app-client.js +25 -1
  36. package/dist/engine/github/github-app-client.js.map +1 -1
  37. package/dist/engine/github/github.d.ts +195 -6
  38. package/dist/engine/github/github.js +331 -6
  39. package/dist/engine/github/github.js.map +1 -1
  40. package/dist/engine/pr-decisions.d.ts +23 -0
  41. package/dist/engine/pr-decisions.js.map +1 -1
  42. package/dist/engine/router.js +108 -1
  43. package/dist/engine/router.js.map +1 -1
  44. package/dist/engine/stage-advance.d.ts +92 -0
  45. package/dist/engine/stage-advance.js +129 -0
  46. package/dist/engine/stage-advance.js.map +1 -0
  47. package/dist/engine/stage-labels.d.ts +57 -0
  48. package/dist/engine/stage-labels.js +58 -0
  49. package/dist/engine/stage-labels.js.map +1 -0
  50. package/dist/engine/stage-observer.d.ts +79 -0
  51. package/dist/engine/stage-observer.js +221 -0
  52. package/dist/engine/stage-observer.js.map +1 -0
  53. package/dist/index.js +110 -2
  54. package/dist/index.js.map +1 -1
  55. package/dist/logging/phase-log.d.ts +6 -0
  56. package/dist/logging/phase-log.js +16 -0
  57. package/dist/logging/phase-log.js.map +1 -1
  58. package/dist/state/activity-store.d.ts +45 -1
  59. package/dist/state/activity-store.js +44 -0
  60. package/dist/state/activity-store.js.map +1 -1
  61. package/dist/state/execution-store.d.ts +48 -0
  62. package/dist/state/execution-store.js +112 -0
  63. package/dist/state/execution-store.js.map +1 -1
  64. package/dist/state/schema/pg.d.ts +2 -2
  65. package/dist/state/schema/sqlite.d.ts +2 -2
  66. package/dist/state/workflow-run-store.d.ts +51 -0
  67. package/dist/state/workflow-run-store.js +98 -0
  68. package/dist/state/workflow-run-store.js.map +1 -1
  69. package/dist/workflows/simple.d.ts +40 -1
  70. package/dist/workflows/simple.js +113 -2
  71. package/dist/workflows/simple.js.map +1 -1
  72. package/package.json +4 -4
  73. package/workflows/cron-autonomy.yaml +24 -0
  74. package/workflows/prompts/pr.md +18 -1
@@ -0,0 +1,221 @@
1
+ /**
2
+ * The TERMINAL half of the software-factory stage pipeline — the second and
3
+ * final call site of `./stage-advance.ts`.
4
+ *
5
+ * The dispatch-time advance (`./build-gate.ts`, guard 2) moves an issue onto
6
+ * the stage's `running` label before the run starts. Nothing moved it off
7
+ * again: without this module `agent-building` is a dead end, and every issue
8
+ * the pipeline ever picked up sits there forever while the run that owns it
9
+ * has long since finished. This closes that loop.
10
+ *
11
+ * ```
12
+ * agent-building ──▶ ready-for-human (succeeded)
13
+ * └──▶ agent-blocked (failed | cancelled)
14
+ * ```
15
+ *
16
+ * ## Why an observer, and not a line in `simple.ts`
17
+ *
18
+ * The precedent is exact, and it is `./review-check.ts`: the `last-light/review`
19
+ * check used to be completed from a `.then()` chained onto the in-memory
20
+ * workflow promise, so it stranded on every deploy, every resume, every TTL
21
+ * expiry and every crash. The fix was not routing but DURABILITY — make the
22
+ * projection follow the run's PERSISTED terminal transition, wherever that
23
+ * transition happens. Hanging off `TerminalRunObserver` is what makes
24
+ * `simple.ts`, `resume.ts`, the queued-run TTL expiry and the admin cancel all
25
+ * move the label for free, and what stops a ninth terminal path being added
26
+ * without one. A stage label stranded at `agent-building` is the same class of
27
+ * bug as a check stranded at `in_progress`, with a worse symptom: it is the
28
+ * source of truth for where an issue has got to, so a human scanning the
29
+ * tracker reads a lie.
30
+ *
31
+ * ## The observer contract
32
+ *
33
+ * `workflow-run-store.ts` states it: **synchronous, never throws, never
34
+ * re-enters the store.** Everything here is one cheap synchronous filter and
35
+ * then a fire-and-forget of the GitHub work, the same shape
36
+ * `installReviewCheckObserver` uses — the promise carries a `.catch`, which is
37
+ * both how the rejection gets somewhere to go and how it satisfies the
38
+ * `lint-floating-promises` gate.
39
+ *
40
+ * ## Idempotency, without bookkeeping
41
+ *
42
+ * The observer can fire more than once for one run — a restart-resumed run that
43
+ * finishes twice, a retry, a cancel racing a finish. It needs no dedup state,
44
+ * because `advanceStage` is naturally idempotent at both ends: re-adding a label
45
+ * the issue already carries is a no-op for GitHub's `addLabels`, and
46
+ * `GitHubClient.removeLabel` swallows the 404 that means "already gone" (see
47
+ * `github.ts` — the one status that means "already in the desired state"). So a
48
+ * second firing re-asserts the same two facts and changes nothing. Recording a
49
+ * "already advanced" flag would buy nothing and add a write that could itself
50
+ * fail or go stale; the durable fact is the run row, and the label is its
51
+ * projection.
52
+ */
53
+ import { advanceStage } from "./stage-advance.js";
54
+ import { getAutonomyConfig } from "../config/config.js";
55
+ import { logger } from "../logging/logger.js";
56
+ const log = logger("stage-observer");
57
+ /**
58
+ * The stage name this run was dispatched under, or `null` if it was not a
59
+ * stage dispatch at all.
60
+ *
61
+ * Read BY NAME off the stored `context`, never through a mirrored type — the
62
+ * same rule `PrStatePanel` follows. That JSON was written by whatever build was
63
+ * running when the run started and is read back here by whatever build is
64
+ * running when it ends, which for a paused-then-resumed run can be a different
65
+ * release. A type assertion would claim a guarantee the storage cannot make.
66
+ *
67
+ * Two keys, because two things are being asked and only one of them exists on
68
+ * every dispatch today: `_stage` is what the router stamps (`router.ts`, the
69
+ * `issue.labeled` case) and is the one that NAMES the stage, so a run without it
70
+ * cannot be advanced whatever else it carries. `_autonomous` is the gate's own
71
+ * "this dispatch is autonomous" flag; where it is present and explicitly
72
+ * `false`, that is a deliberate statement and it wins. An `@bot build` comment
73
+ * carries neither, which is the case that matters most: a human-asked build
74
+ * must never acquire stage labels it did not enter the pipeline through.
75
+ */
76
+ function readStageName(run) {
77
+ const ctx = run.context ?? {};
78
+ if (ctx._autonomous === false)
79
+ return null;
80
+ const stage = ctx._stage;
81
+ if (typeof stage !== "string" || !stage)
82
+ return null;
83
+ return stage;
84
+ }
85
+ /**
86
+ * Which label a terminal status lands on.
87
+ *
88
+ * Every terminal status of `workflow_runs` is named explicitly rather than
89
+ * being swept up by an `else`, so adding a fourth one is a type error here
90
+ * instead of a silent mis-labelling. The three are the store's own union
91
+ * (`succeeded | failed | cancelled`).
92
+ *
93
+ * `cancelled` maps to `on_failure` with `failed`: from the issue's point of
94
+ * view they are the same fact — the build did not get there and a person needs
95
+ * to look. `agent-blocked` is the label that says so, and leaving a cancelled
96
+ * run on `agent-building` would strand it exactly as before.
97
+ *
98
+ * **`paused` is NOT terminal and never reaches this function** — the store only
99
+ * ever notifies for the three above. That is load-bearing rather than
100
+ * incidental: a run sitting on an approval gate is `paused`, and the whole
101
+ * point of an HITL gate is that the work is still in flight while a human
102
+ * decides. Moving the label there would report a build as finished mid-run,
103
+ * and — because the resume path finishes the run later — move it a second time.
104
+ * This is the easy mistake in this module; the type is what prevents it.
105
+ */
106
+ function targetLabel(stage, status) {
107
+ switch (status) {
108
+ case "succeeded":
109
+ return stage.on_success;
110
+ case "failed":
111
+ return stage.on_failure;
112
+ case "cancelled":
113
+ return stage.on_failure;
114
+ }
115
+ }
116
+ /**
117
+ * Where this run happened. The `owner` / `repo` / `issueNumber` COLUMNS are
118
+ * preferred and are populated for a build run — `createRun` writes them from
119
+ * the normalized repo ref and the dispatch context's issue number.
120
+ *
121
+ * `triggerId` (`owner/repo#N`) is the fallback, not the primary, because it is
122
+ * a formatted string and the columns are the structured fact. It earns its
123
+ * place anyway: it is the value the run is KEYED on, so it is the one field
124
+ * that cannot be absent.
125
+ */
126
+ function locate(run) {
127
+ if (run.owner && run.repo && typeof run.issueNumber === "number" && run.issueNumber > 0) {
128
+ return { owner: run.owner, repo: run.repo, issueNumber: run.issueNumber };
129
+ }
130
+ const match = /^([^/]+)\/([^#]+)#(\d+)$/.exec(run.triggerId ?? "");
131
+ if (!match)
132
+ return null;
133
+ return { owner: match[1], repo: match[2], issueNumber: Number(match[3]) };
134
+ }
135
+ /** The async half — everything the synchronous observer fires and forgets. */
136
+ async function advanceTerminalStage(run, status, stageName, deps) {
137
+ // An operator renamed or removed the stage between dispatch and completion,
138
+ // or the run predates the stage. There is no label vocabulary to move within,
139
+ // so there is nothing correct to do — and nothing alarming either, which is
140
+ // why this is debug rather than warn.
141
+ const stage = getAutonomyConfig().stages[stageName];
142
+ if (!stage) {
143
+ log.debug("Terminal stage run names a stage that is not configured; leaving its label alone", {
144
+ runId: run.id,
145
+ workflow: run.workflowName,
146
+ stage: stageName,
147
+ status,
148
+ });
149
+ return;
150
+ }
151
+ const where = locate(run);
152
+ if (!where) {
153
+ log.warn("Terminal stage run has no issue to label", {
154
+ runId: run.id,
155
+ workflow: run.workflowName,
156
+ stage: stageName,
157
+ triggerId: run.triggerId,
158
+ status,
159
+ });
160
+ return;
161
+ }
162
+ const to = targetLabel(stage, status);
163
+ const advance = await advanceStage({ ...where, from: stage.running, to }, { github: deps.github });
164
+ // Same condition `build-gate.ts` warns on, and for the same reason: the label
165
+ // IS the stage, so a half-advance is the projection degrading. `advanced:
166
+ // false` means the issue is still reported as building when it is not;
167
+ // `removed: false` means it now claims both. Neither loses the run — that
168
+ // fact is in the database — but both mislead a human reading the tracker,
169
+ // which is the audience the whole pipeline is for.
170
+ if (!advance.advanced || !advance.removed) {
171
+ log.warn("Terminal stage label advance degraded — the issue's stage now misreports", {
172
+ runId: run.id,
173
+ workflow: run.workflowName,
174
+ stage: stageName,
175
+ status,
176
+ ...where,
177
+ from: stage.running,
178
+ to,
179
+ advanced: advance.advanced,
180
+ removed: advance.removed,
181
+ reason: advance.reason,
182
+ });
183
+ return;
184
+ }
185
+ log.info("Advanced the stage label on a terminal run", {
186
+ runId: run.id,
187
+ workflow: run.workflowName,
188
+ stage: stageName,
189
+ status,
190
+ ...where,
191
+ from: stage.running,
192
+ to,
193
+ });
194
+ // The label moved, so anything caching the OLD one is now wrong. Best-effort
195
+ // and deliberately last: a cache that refuses to clear must not turn a
196
+ // successful advance into a logged failure.
197
+ try {
198
+ deps.onAdvanced?.(`${where.owner}/${where.repo}`);
199
+ }
200
+ catch (err) {
201
+ log.debug("Stage advance notification failed", { runId: run.id, err });
202
+ }
203
+ }
204
+ /**
205
+ * Wire {@link advanceTerminalStage} onto every terminal run transition. Called
206
+ * once, at boot, beside `installReviewCheckObserver`.
207
+ */
208
+ export function installStageObserver(db, deps) {
209
+ db.runs.addTerminalObserver((run, status) => {
210
+ const stageName = readStageName(run);
211
+ if (!stageName)
212
+ return;
213
+ advanceTerminalStage(run, status, stageName, deps).catch((err) => {
214
+ // The observer contract's "never throws" end of the bargain. The run is
215
+ // already persisted as terminal; no projection of it may undo that, and
216
+ // one failing must not cost the other observers their notification.
217
+ log.warn("Terminal stage advance failed for run", { runId: run.id, stage: stageName, err });
218
+ });
219
+ });
220
+ }
221
+ //# sourceMappingURL=stage-observer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stage-observer.js","sourceRoot":"","sources":["../../src/engine/stage-observer.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmDG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,iBAAiB,EAA4B,MAAM,qBAAqB,CAAC;AAClF,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAK9C,MAAM,GAAG,GAAG,MAAM,CAAC,gBAAgB,CAAC,CAAC;AAuBrC;;;;;;;;;;;;;;;;;;GAkBG;AACH,SAAS,aAAa,CAAC,GAAgB;IACrC,MAAM,GAAG,GAAG,GAAG,CAAC,OAAO,IAAI,EAAE,CAAC;IAC9B,IAAI,GAAG,CAAC,WAAW,KAAK,KAAK;QAAE,OAAO,IAAI,CAAC;IAC3C,MAAM,KAAK,GAAG,GAAG,CAAC,MAAM,CAAC;IACzB,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK;QAAE,OAAO,IAAI,CAAC;IACrD,OAAO,KAAK,CAAC;AACf,CAAC;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,SAAS,WAAW,CAClB,KAA0B,EAC1B,MAA4C;IAE5C,QAAQ,MAAM,EAAE,CAAC;QACf,KAAK,WAAW;YACd,OAAO,KAAK,CAAC,UAAU,CAAC;QAC1B,KAAK,QAAQ;YACX,OAAO,KAAK,CAAC,UAAU,CAAC;QAC1B,KAAK,WAAW;YACd,OAAO,KAAK,CAAC,UAAU,CAAC;IAC5B,CAAC;AACH,CAAC;AAED;;;;;;;;;GASG;AACH,SAAS,MAAM,CAAC,GAAgB;IAC9B,IAAI,GAAG,CAAC,KAAK,I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,CAAC,GAAG,KAAK,CAAC,KAAK,IAAI,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC;IACpD,CAAC;IAAC,OAAO,GAAY,EAAE,CAAC;QACtB,GAAG,CAAC,KAAK,CAAC,mCAAmC,EAAE,EAAE,KAAK,EAAE,GAAG,CAAC,EAAE,EAAE,GAAG,EAAE,CAAC,CAAC;IACzE,CAAC;AACH,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,oBAAoB,CAAC,EAAW,EAAE,IAAuB;IACvE,EAAE,CAAC,IAAI,CAAC,mBAAmB,CAAC,CAAC,GAAG,EAAE,MAAM,EAAE,EAAE;QAC1C,MAAM,SAAS,GAAG,aAAa,CAAC,GAAG,CAAC,CAAC;QACrC,IAAI,CAAC,SAAS;YAAE,OAAO;QACvB,oBAAoB,CAAC,GAAG,EAAE,MAAM,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC,KAAK,CAAC,CAAC,GAAY,EAAE,EAAE;YACxE,wEAAwE;YACxE,wEAAwE;YACxE,oEAAoE;YACpE,GAAG,CAAC,IAAI,CAAC,uCAAuC,EAAE,EAAE,KAAK,EAAE,GAAG,CAAC,EAAE,EAAE,KAAK,EAAE,SAAS,EAAE,GAAG,EAAE,CAAC,CAAC;QAC9F,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC"}
package/dist/index.js CHANGED
@@ -23,6 +23,7 @@ import { sweepK8sSandboxes } from "./sandbox/k8s/sweep.js";
23
23
  import { discoverGreenDependencyPrs, discoverRedDependencyPrs, REQUIRES_HUMAN_LABEL, } from "./cron/dependabot-discovery.js";
24
24
  import { buildCronHandlers } from "./cron/handlers.js";
25
25
  import { discoverPrsAwaitingReview } from "./cron/review-discovery.js";
26
+ import { discoverIssuesReadyForAgent } from "./cron/issue-discovery.js";
26
27
  import { mountAdmin } from "./admin/index.js";
27
28
  import { cleanupOrphanedSandboxes } from "./sandbox/index.js";
28
29
  import { mountSkillBundle } from "./sandbox/k8s/skill-bundle-route.js";
@@ -42,7 +43,11 @@ import { screenForInjection, flagPrefix } from "./engine/screen/screen.js";
42
43
  import { runSimpleWorkflow, resolveRepoRunConfig, prepopulatesPrHeadRef, isPrFixShaped, } from "./workflows/simple.js";
43
44
  import { resolvePrState, resolveSpecContext, prScopedWorkflows, } from "./engine/pr-state.js";
44
45
  import { renderContext } from "./engine/pr-decisions.js";
46
+ import { applyBuildDispatchGate } from "./engine/build-gate.js";
45
47
  import { REVIEW_WORKFLOW, bindQueuedReviewCheck, installReviewCheckObserver, openAndBindReviewCheck, } from "./engine/review-check.js";
48
+ import { installStageObserver } from "./engine/stage-observer.js";
49
+ import { invalidateBoard } from "./admin/board-cache.js";
50
+ import { noteBoardRunChange } from "./admin/board-stream.js";
46
51
  import { runDashboardUrl } from "./notify/model.js";
47
52
  import { harvestFixMarkers } from "./engine/fix-harvest.js";
48
53
  import { harvestReviewTriage } from "./engine/review-triage.js";
@@ -278,6 +283,26 @@ async function main() {
278
283
  botLogin: config.botLogin,
279
284
  botMention: `@${config.botName}`,
280
285
  });
286
+ // The STAGE LABEL is a projection of run state in exactly the same sense, and
287
+ // is wired here for exactly the same reason (`src/engine/stage-observer.ts`).
288
+ // The dispatch gate moves an issue onto `agent-building`; this is the only
289
+ // thing that ever moves it off, so without it every issue the pipeline picks
290
+ // up strands there while the run that owns it has long since finished.
291
+ // The board stream's run-side signal. The GitHub half of a card is cached
292
+ // and the run half is read live, so a run FINISHING changes what the board
293
+ // shows without touching the cache — invisible to `boardRevision` alone.
294
+ // A counter bump satisfies the observer contract (synchronous, never throws,
295
+ // never re-enters the store) exactly.
296
+ db.runs.addTerminalObserver(() => noteBoardRunChange());
297
+ installStageObserver(db, {
298
+ github,
299
+ // A moved label makes the board's cached copy wrong, and the board is the
300
+ // surface somebody is watching this happen on. Without this the card shows
301
+ // its run as FAILED while still sitting in the "building" column until the
302
+ // TTL lapses — the run read is live, the label read is cached, and the card
303
+ // disagrees with itself in the meantime.
304
+ onAdvanced: (repo) => invalidateBoard(repo),
305
+ });
281
306
  // Feedback signals recorded while telemetry was off carry no export watermark
282
307
  // (issue #255), so enabling OTel later can still put them on the traces they
283
308
  // grade instead of starting the backend from zero. Bounded per boot; a no-op
@@ -421,6 +446,65 @@ async function main() {
421
446
  log.warn(msg, { workflowName, refusal });
422
447
  return { success: false, error: msg };
423
448
  }
449
+ // ── The BUILD dispatch gate (the issue side of the same rule) ──────────
450
+ //
451
+ // The ISSUE-side twin of the PR gate below, at the SAME choke point and for
452
+ // the same reason as the three guards above: webhook, cron, `/api/*` and
453
+ // resume all funnel through here, so this is the one place that can promise
454
+ // EVERY dispatch surface crossed the gate. That is the design invariant, not
455
+ // an implementation detail — the Phase 4 backstop sweep and `/api/run` will
456
+ // arrive here too and need no gate of their own, which is exactly what stops
457
+ // three surfaces growing three disagreeing copies of one policy.
458
+ //
459
+ // Gated on the context being a STAGE dispatch. `_stage` is what the router
460
+ // emits beside `_routeKey`; a stage dispatch that somehow carries no stage
461
+ // name still enters the gate (with an unresolvable name), because the one
462
+ // thing it must not do is skip the gate and run ungoverned.
463
+ const stageName = typeof context._stage === "string" ? context._stage : undefined;
464
+ if (stageName !== undefined || context._routeKey === "github.issue_labeled") {
465
+ const gate = await applyBuildDispatchGate({
466
+ repo: repoStr ?? "",
467
+ issueNumber: typeof context.issueNumber === "number" ? context.issueNumber : 0,
468
+ labels: Array.isArray(context.labels) ? context.labels : [],
469
+ addedLabel: typeof context._addedLabel === "string" ? context._addedLabel : undefined,
470
+ // The label route is the only surface that exists today. The sweep and
471
+ // `/api/run` will name themselves here.
472
+ route: context._triggerType === "api" ? "api" : context._triggerType === "cron" ? "sweep" : "labeled",
473
+ senderIsBot: context._senderIsBot === true,
474
+ stage: stageName ?? "",
475
+ }, { db, github });
476
+ if (gate.decision === "skip") {
477
+ // `success: true`, exactly as the PR gate's skip returns: the harness
478
+ // correctly determined there is nothing to do. Reporting it as an error
479
+ // would paint a cron tick red and count against a fan-out's `failures`.
480
+ return { success: true };
481
+ }
482
+ // The stage's approval gates, onto the context for the run to union onto
483
+ // its effective approval map (`workflows/simple.ts`). It rides the context
484
+ // rather than a parameter because it is a property of THIS dispatch — the
485
+ // same argument `_explicitRequest` makes below.
486
+ //
487
+ // THE AUTONOMY MARK, and it is load-bearing in a way `_stage` is not.
488
+ // `_stage` says WHICH stage; this says the run reached us through the
489
+ // autonomous pipeline at all. Both are persisted on the run row, and two
490
+ // readers key on this one specifically:
491
+ //
492
+ // - `engine/build-gate.ts` counts the autonomous builds in flight for
493
+ // `autonomy.budget.maxConcurrentBuilds`, by reading it back off every
494
+ // ACTIVE run's stored context. Unstamped, that count is permanently
495
+ // zero and the concurrency ceiling never fires — a budget that reads
496
+ // as enforced and is not.
497
+ // - `workflows/simple.ts` decides whether the stage's `on_merge` policy
498
+ // applies, so a human's `@bot build` can never auto-merge.
499
+ //
500
+ // Stamped HERE rather than in the gate because the gate returns a
501
+ // decision and mutates nothing — the same split `_autonomyGates` below
502
+ // follows, and the reason both ride the context rather than a parameter:
503
+ // they are properties of THIS dispatch, not of the issue.
504
+ context._autonomous = true;
505
+ if (gate.gates)
506
+ context._autonomyGates = gate.gates;
507
+ }
424
508
  // ── The PR state machine (09-state-machine.md → S3) ────────────────────
425
509
  //
426
510
  // One resolved snapshot per dispatch, at the SAME choke point and for the
@@ -1142,6 +1226,14 @@ async function main() {
1142
1226
  // The harness client memoizes an Octokit per installation; drop it when
1143
1227
  // the App is uninstalled so a re-install can't be served by a dead one.
1144
1228
  onInstallationRemoved: (installationId) => github?.forgetInstallation(installationId),
1229
+ // A delivery that moved, opened, closed or merged something makes the
1230
+ // board's cached GitHub answer wrong — and the board is the surface
1231
+ // somebody is watching it happen on. This is the hook `invalidateBoard`
1232
+ // was written for and never had: until now the ONLY things that
1233
+ // invalidated were the dashboard's own mutations and a finished run, so a
1234
+ // human labelling an issue on github.com moved nothing for up to the full
1235
+ // TTL. Synchronous by contract, like the hooks around it.
1236
+ onBoardChanged: (repo) => invalidateBoard(repo),
1145
1237
  // Team/org membership changed — forget the affected slice of the
1146
1238
  // dashboard visibility cache (issue #169). Deleting rows is the whole
1147
1239
  // response: the cache is filled on demand per logged-in user, so the next
@@ -1285,7 +1377,11 @@ async function main() {
1285
1377
  // Add a discoverer + a `cron-*.yaml` with the matching `discover:` key to
1286
1378
  // introduce a new sweep. The harness `github` client (App auth) is passed to
1287
1379
  // every discoverer, so a discoverer only needs the subset of it it uses.
1288
- const PR_DISCOVERERS = {
1380
+ // Named CRON_DISCOVERERS, not PR_DISCOVERERS: the autonomy backstop sweep
1381
+ // discovers ISSUES, so the registry is no longer PR-only. `CronDiscoverer` is
1382
+ // the runner's own contract, imported rather than re-spelled here so the two
1383
+ // cannot drift.
1384
+ const CRON_DISCOVERERS = {
1289
1385
  // The green sweep's notion of "green" must match the webhook's: on a repo
1290
1386
  // with no *required* checks, `mergeable_state: "clean"` is true for a PR
1291
1387
  // whose CI is red. `requireSettledChecks` makes it ask the checks too.
@@ -1305,6 +1401,18 @@ async function main() {
1305
1401
  // all decided once by `resolveReviewTrigger` at the dispatch choke point,
1306
1402
  // which the webhook route crosses too.
1307
1403
  "prs-awaiting-review": (repos, gh, opts) => discoverPrsAwaitingReview(repos, gh, { ...opts, botLogin: config.botLogin }),
1404
+ // The autonomy backstop sweep (`workflows/cron-autonomy.yaml`): find the
1405
+ // open issues sitting at a stage's `enter` label and fan out one bounded
1406
+ // single-issue run of the stage's workflow each. It closes the one gap the
1407
+ // label pipeline has — a dropped or undelivered `issues.labeled` webhook
1408
+ // leaves an issue at `ready-for-agent` with nothing ever re-checking.
1409
+ //
1410
+ // A pure CANDIDATE FINDER: open, carries `enter`, does NOT carry `running`.
1411
+ // The allow-list, the hold, already-built, run-in-flight and every budget
1412
+ // are decided once by `resolveBuildTrigger` at the dispatch choke point the
1413
+ // webhook route crosses too — which is also why this sweep cannot become
1414
+ // the re-dispatch spend loop. See `cron/issue-discovery.ts`.
1415
+ "issues-ready-for-agent": (repos, gh, opts) => discoverIssuesReadyForAgent(repos, gh, opts),
1308
1416
  };
1309
1417
  // Construct the cron scheduler before mounting admin so the dashboard can
1310
1418
  // list/toggle/edit registered cron jobs. Jobs are registered further down
@@ -1314,7 +1422,7 @@ async function main() {
1314
1422
  const cronRunner = makeCronRunner({
1315
1423
  db,
1316
1424
  github,
1317
- discoverers: PR_DISCOVERERS,
1425
+ discoverers: CRON_DISCOVERERS,
1318
1426
  dispatch: dispatchWorkflow,
1319
1427
  });
1320
1428
  const cron = new CronScheduler(db, cronRunner);