lastlight-core 0.32.2 → 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 (69) 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 +156 -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/github/github.d.ts +195 -6
  33. package/dist/engine/github/github.js +331 -6
  34. package/dist/engine/github/github.js.map +1 -1
  35. package/dist/engine/pr-decisions.d.ts +23 -0
  36. package/dist/engine/pr-decisions.js.map +1 -1
  37. package/dist/engine/router.js +108 -1
  38. package/dist/engine/router.js.map +1 -1
  39. package/dist/engine/stage-advance.d.ts +92 -0
  40. package/dist/engine/stage-advance.js +129 -0
  41. package/dist/engine/stage-advance.js.map +1 -0
  42. package/dist/engine/stage-labels.d.ts +57 -0
  43. package/dist/engine/stage-labels.js +58 -0
  44. package/dist/engine/stage-labels.js.map +1 -0
  45. package/dist/engine/stage-observer.d.ts +79 -0
  46. package/dist/engine/stage-observer.js +221 -0
  47. package/dist/engine/stage-observer.js.map +1 -0
  48. package/dist/index.js +110 -2
  49. package/dist/index.js.map +1 -1
  50. package/dist/logging/phase-log.d.ts +6 -0
  51. package/dist/logging/phase-log.js +16 -0
  52. package/dist/logging/phase-log.js.map +1 -1
  53. package/dist/state/activity-store.d.ts +45 -1
  54. package/dist/state/activity-store.js +44 -0
  55. package/dist/state/activity-store.js.map +1 -1
  56. package/dist/state/execution-store.d.ts +48 -0
  57. package/dist/state/execution-store.js +112 -0
  58. package/dist/state/execution-store.js.map +1 -1
  59. package/dist/state/schema/pg.d.ts +2 -2
  60. package/dist/state/schema/sqlite.d.ts +2 -2
  61. package/dist/state/workflow-run-store.d.ts +51 -0
  62. package/dist/state/workflow-run-store.js +98 -0
  63. package/dist/state/workflow-run-store.js.map +1 -1
  64. package/dist/workflows/simple.d.ts +40 -1
  65. package/dist/workflows/simple.js +113 -2
  66. package/dist/workflows/simple.js.map +1 -1
  67. package/package.json +3 -3
  68. package/workflows/cron-autonomy.yaml +24 -0
  69. package/workflows/prompts/pr.md +18 -1
@@ -14,6 +14,7 @@ import { routeEvent } from "../engine/router.js";
14
14
  import { applyPrDispatchGate, prPolicyConfig } from "../engine/dispatcher.js";
15
15
  import { resolvePrState, prTriggerId } from "../engine/pr-state.js";
16
16
  import { holdReply } from "../engine/pr-decisions.js";
17
+ import { advanceStage } from "../engine/stage-advance.js";
17
18
  import { prFixShapedWorkflows } from "../workflows/target-policy.js";
18
19
  import { classifyComment } from "../engine/screen/classifier.js";
19
20
  import { getWorkflowTriggers, getWorkflowTriggerKinds, resolveIntentHandler, } from "../workflows/triggers.js";
@@ -27,14 +28,92 @@ import { TeamVisibilityResolver } from "../engine/github/team-visibility.js";
27
28
  * shows more.
28
29
  */
29
30
  const MAX_REPO_SCOPE = 200;
31
+ /**
32
+ * Most repos ONE board may cover — deliberately not {@link MAX_REPO_SCOPE}.
33
+ *
34
+ * That cap bounds a WHERE clause; this one bounds live GitHub reads, and the
35
+ * two are three orders of magnitude apart in what they cost. Twenty repos is
36
+ * two GraphQL documents per TTL window (see `listOpenBoardItems`); two hundred
37
+ * would be twenty, on the same budget the harness spends reviewing pull
38
+ * requests. Over the cap the scope is TRUNCATED and says so — never a 400 — so
39
+ * the UI can report "showing 20 of 57" instead of silently showing a subset.
40
+ */
41
+ const MAX_BOARD_REPOS = 20;
42
+ /**
43
+ * The ONLY route keys a board dispatch may resolve a workflow through.
44
+ *
45
+ * The board posts an issue number, not a workflow name. That is the whole
46
+ * point: a free-form workflow name accepted from a browser would turn one card
47
+ * action into a generic "run anything against any managed repo" surface, which
48
+ * is a much larger thing than the button says it is — and it already exists,
49
+ * deliberately, as `POST /api/run` for operators who want it.
50
+ *
51
+ * So the workflow is resolved from `routes.github` — the operator's own route
52
+ * map — and then CHECKED to be one of these three keys' values. An operator who
53
+ * repoints `issue_build` at a different workflow moves this surface with it,
54
+ * which is right; an operator who never configured the stage at all gets a
55
+ * refusal rather than a dispatch, which is also right.
56
+ */
57
+ const ISSUE_DISPATCH_ROUTE_KEYS = ["issue_opened", "issue_labeled", "issue_build"];
58
+ const STAGE_SLOTS = ["enter", "running", "on_success", "on_failure"];
59
+ /**
60
+ * Which stage — and which of its four slots — a configured label names.
61
+ *
62
+ * The flat allow-list the stage route builds answers "may this label be
63
+ * written", which is the SECURITY question and stays exactly as it was. This
64
+ * answers the different question a dispatch needs: WHICH stage the human just
65
+ * asked for, and which column of it they dropped on. Only `enter` and `running`
66
+ * mean "build this"; the two terminal slots are where a run has already ended.
67
+ *
68
+ * Fails CLOSED on a label two stages both claim. That is a real config, and a
69
+ * SPEND decision taken on an undecidable one is the wrong direction to guess in
70
+ * — the same reason `build-gate.ts` refuses an unknown stage rather than
71
+ * picking a default.
72
+ */
73
+ function stageSlotForLabel(label) {
74
+ if (!label)
75
+ return null;
76
+ const hits = [];
77
+ for (const [name, stage] of Object.entries(getAutonomyConfig().stages)) {
78
+ for (const slot of STAGE_SLOTS) {
79
+ if (stage[slot] && stage[slot] === label) {
80
+ hits.push({ stage: name, slot });
81
+ break;
82
+ }
83
+ }
84
+ }
85
+ if (hits.length === 0)
86
+ return null;
87
+ const names = [...new Set(hits.map((h) => h.stage))];
88
+ if (names.length > 1)
89
+ return { kind: "ambiguous", stages: names };
90
+ return { kind: "match", stage: hits[0].stage, slot: hits[0].slot };
91
+ }
92
+ /**
93
+ * Is `workflow` one the operator's own route map already points an issue
94
+ * trigger at? See {@link ISSUE_DISPATCH_ROUTE_KEYS} for why that check exists.
95
+ *
96
+ * Shared by BOTH board surfaces — the dispatch button and the drag — because
97
+ * two copies of this check are two things free to drift, and the one that
98
+ * drifts open is a "run anything against any managed repo" hole.
99
+ */
100
+ function isIssueRoutableWorkflow(workflow) {
101
+ const routable = new Set(ISSUE_DISPATCH_ROUTE_KEYS.map((key) => getRoutes().github?.[key]).filter(Boolean));
102
+ return routable.has(workflow);
103
+ }
30
104
  import { getRuntimeConfig, getRoutes, getBotName, resolveKubernetesConfig,
31
105
  // The redaction rule for every surface that echoes YAML back to the
32
106
  // dashboard. IMPORTED, never mirrored: `GET /repos/:owner/:repo/config`
33
107
  // returns a repo's UNTRUSTED `.lastlight/lastlight.yml` raw and
34
108
  // pre-validation, so a copy that drifted behind config.ts's would leak a
35
109
  // pasted credential. It must stay single-source (see config.ts).
36
- redactPublic, } from "../config/config.js";
110
+ redactPublic, getAutonomyConfig, getHoldLabel, } from "../config/config.js";
37
111
  import { fetchRepoLayer, refreshRepoLayer, getCachedRepoLayer, repoConfigPolicy, repoConfigBaseFromRuntime, resolveRepoConfig, } from "../config/repo-config.js";
112
+ import { issueTriggerId } from "../engine/build-decisions.js";
113
+ import { applyBuildDispatchGate } from "../engine/build-gate.js";
114
+ import { buildBoard } from "./board.js";
115
+ import { getBoardItems, invalidateBoard, BOARD_TTL_MS } from "./board-cache.js";
116
+ import { boardSignature, BOARD_TICK_MS, BOARD_HEARTBEAT_MS } from "./board-stream.js";
38
117
  import { reapSandboxWorkspace } from "../sandbox/reap.js";
39
118
  import { artifactStore } from "../sandbox/artifact-store.js";
40
119
  import { reclaimSandbox } from "../sandbox/k8s/reclaim.js";
@@ -1764,6 +1843,224 @@ export function createAdminRoutes(db, sessions, chatSessions, config) {
1764
1843
  // artifact-key count. Managed repos with no activity are included so the tab
1765
1844
  // shows the full fleet; ordered newest-activity first, then name. Read-only —
1766
1845
  // the server keeps returning global data (see issue #169).
1846
+ /**
1847
+ * The pipeline board — every open issue and pull request in scope, filed
1848
+ * under the stage label it carries.
1849
+ *
1850
+ * Read-only, and thin on purpose: scope resolution here, the GitHub read in
1851
+ * `board-cache.ts`, the projection in `board.ts`. It therefore records no
1852
+ * activity — `recordActivityFor` is for USER-INITIATED mutations, and a
1853
+ * dashboard polling every twenty seconds would drown the audit stream.
1854
+ *
1855
+ * **Three queries, whatever the card count — plus two CONDITIONAL ledger
1856
+ * reads**: one when a card has failed (the reason a FAILED band owes the
1857
+ * reader) and one when a card is live (the phase it is actually running,
1858
+ * which `current_phase` lags by one). Both are O(1) in cards and both are
1859
+ * skipped entirely when no card needs them. The cached items, ONE
1860
+ * `latestForTriggers` over every card's trigger id, and ONE `listPending()`.
1861
+ * A per-card run lookup would be fifty statements to render one screen.
1862
+ */
1863
+ app.get("/board", async (c) => {
1864
+ const autonomy = getAutonomyConfig();
1865
+ const stages = Object.entries(autonomy.stages).map(([id, stage]) => ({
1866
+ id,
1867
+ enter: stage.enter,
1868
+ running: stage.running,
1869
+ on_success: stage.on_success,
1870
+ on_failure: stage.on_failure,
1871
+ }));
1872
+ const managedSet = new Set(getManagedRepos());
1873
+ // ── The board's universe is the AUTONOMY ALLOW-LIST, not the managed list ──
1874
+ //
1875
+ // This board is a view of ONE pipeline, and `autonomy.repos` is what decides
1876
+ // which repos have one. A managed repo that is not on the list has no stage
1877
+ // labels anybody writes, no `build` the gate would admit, and every action
1878
+ // offered on its cards answers `409 not-autonomous` — because the card
1879
+ // actions cross the real dispatch gate, which checks exactly this list. So
1880
+ // showing those repos renders columns and menus for work that structurally
1881
+ // cannot run, and pays a live GitHub read per repo to do it.
1882
+ //
1883
+ // Intersected with the managed set rather than trusted outright: the two are
1884
+ // configured independently, and a repo named in `autonomy.repos` that the
1885
+ // App cannot see is a typo, not a target.
1886
+ const eligible = new Set(autonomy.repos.filter((r) => managedSet.has(r)));
1887
+ // Scope, in precedence order. Each step narrows to `eligible`.
1888
+ const requested = (c.req.query("repos") || "")
1889
+ .split(",")
1890
+ .map((r) => r.trim())
1891
+ .filter(Boolean);
1892
+ let candidates;
1893
+ let reason;
1894
+ if (requested.length > 0) {
1895
+ candidates = requested.filter((r) => eligible.has(r));
1896
+ reason = "the repos you asked for";
1897
+ }
1898
+ else {
1899
+ // The same call `/me/repos` makes. `repos: null` is its fail-open
1900
+ // sentinel — no GitHub identity, the feature off, a team too large — and
1901
+ // it means "no filter", never "no access".
1902
+ const visible = await teamVisibility.visibleRepos(actorFromContext(c));
1903
+ if (visible.repos) {
1904
+ candidates = visible.repos.filter((r) => eligible.has(r));
1905
+ reason = "the autonomous repos your GitHub teams can see";
1906
+ }
1907
+ else {
1908
+ // EVERY eligible repo, ordered by activity — not `distinctRepos()`
1909
+ // filtered down to the eligible ones. Those are different answers: a
1910
+ // repo added to `autonomy.repos` this morning has no runs yet, so the
1911
+ // filtered form would hide it on the one day somebody most wants to
1912
+ // watch it start. Activity ORDERS the list so the truncation below
1913
+ // keeps the repos somebody is working in; the tail is the rest of the
1914
+ // allow-list, which is small by construction.
1915
+ const active = await db.runs.distinctRepos();
1916
+ const ordered = [];
1917
+ const seen = new Set();
1918
+ for (const { repo } of active) {
1919
+ if (eligible.has(repo) && !seen.has(repo)) {
1920
+ seen.add(repo);
1921
+ ordered.push(repo);
1922
+ }
1923
+ }
1924
+ for (const repo of eligible)
1925
+ if (!seen.has(repo))
1926
+ ordered.push(repo);
1927
+ candidates = ordered;
1928
+ reason = "the repos on the autonomy allow-list";
1929
+ }
1930
+ }
1931
+ // Said plainly, because an empty board with no explanation reads as broken
1932
+ // rather than as un-opted-in — and `autonomy.repos: []` is the shipped
1933
+ // default, so this is what a fresh install sees.
1934
+ if (eligible.size === 0)
1935
+ reason = "no repos are on the autonomy allow-list";
1936
+ const truncated = candidates.length > MAX_BOARD_REPOS;
1937
+ const scope = {
1938
+ repos: candidates.slice(0, MAX_BOARD_REPOS),
1939
+ // Everything the board COULD show, so the UI's scope picker offers only
1940
+ // repos that can actually appear. Sorted for a stable dropdown.
1941
+ eligible: [...eligible].sort(),
1942
+ truncated,
1943
+ reason: truncated
1944
+ ? `showing ${MAX_BOARD_REPOS} of ${candidates.length} — ${reason}`
1945
+ : reason,
1946
+ };
1947
+ const base = { generatedAt: new Date().toISOString(), ttlSeconds: BOARD_TTL_MS / 1000, scope };
1948
+ // Not configured: no columns, and — the point of checking here — no GitHub
1949
+ // reads at all. A deployment that has not opted into the pipeline pays
1950
+ // nothing for the tab existing.
1951
+ if (stages.length === 0) {
1952
+ return c.json({ ...base, configured: false, degraded: [], columns: [] });
1953
+ }
1954
+ // No eligible repos: render the (empty) columns and touch GitHub not at all.
1955
+ // Same argument as the `configured: false` early return above — a deployment
1956
+ // that has not opted a repo in pays nothing for the tab existing.
1957
+ if (scope.repos.length === 0) {
1958
+ return c.json(buildBoard({
1959
+ items: [],
1960
+ runs: new Map(),
1961
+ approvals: [],
1962
+ stages,
1963
+ holdLabel: getHoldLabel(),
1964
+ scope,
1965
+ degraded: [],
1966
+ generatedAt: base.generatedAt,
1967
+ ttlSeconds: base.ttlSeconds,
1968
+ }, { unstaged: c.req.query("unstaged") === "1" }));
1969
+ }
1970
+ if (!config.github) {
1971
+ return c.json({
1972
+ ...base,
1973
+ configured: true,
1974
+ degraded: scope.repos.map((repo) => ({ repo, error: "No GitHub client is configured." })),
1975
+ columns: [],
1976
+ });
1977
+ }
1978
+ const { items, degraded } = await getBoardItems(scope.repos, {
1979
+ github: config.github,
1980
+ force: c.req.query("refresh") === "1",
1981
+ });
1982
+ const runs = await db.runs.latestForTriggers(items.map((item) => issueTriggerId(item.repo, item.number)));
1983
+ const pending = await db.approvals.listPending();
1984
+ // The fourth statement, and only when something failed. `workflow_runs` has
1985
+ // no error column, so a FAILED card's reason comes from the ledger row of
1986
+ // the phase that stopped it. Batched, so it stays O(1) in cards — the
1987
+ // property the header's claim is really about — and a board with nothing
1988
+ // failing pays nothing for it.
1989
+ const failedRunIds = [...runs.values()]
1990
+ .filter((run) => run.status === "failed")
1991
+ .map((run) => run.id);
1992
+ const failures = failedRunIds.length > 0
1993
+ ? await db.executions.failureReasonsForRuns(failedRunIds)
1994
+ : undefined;
1995
+ // And the fifth, on the same terms: what each LIVE run is running right
1996
+ // now. `workflow_runs.current_phase` is written on phase COMPLETION, so it
1997
+ // lags by one — a run on `executor` reads `architect`. The ledger knows,
1998
+ // because an in-flight phase is the row with no `finished_at`.
1999
+ const activeRunIds = [...runs.values()]
2000
+ .filter((run) => run.status === "queued" || run.status === "running" || run.status === "paused")
2001
+ .map((run) => run.id);
2002
+ const inFlight = activeRunIds.length > 0
2003
+ ? await db.executions.inFlightPhasesForRuns(activeRunIds)
2004
+ : undefined;
2005
+ return c.json(buildBoard({
2006
+ items,
2007
+ runs,
2008
+ approvals: pending,
2009
+ ...(failures ? { failures } : {}),
2010
+ ...(inFlight ? { inFlight } : {}),
2011
+ stages,
2012
+ holdLabel: getHoldLabel(),
2013
+ scope,
2014
+ degraded: degraded,
2015
+ generatedAt: base.generatedAt,
2016
+ ttlSeconds: base.ttlSeconds,
2017
+ }, { unstaged: c.req.query("unstaged") === "1" }));
2018
+ });
2019
+ /**
2020
+ * `GET /board/stream` — the board's change stream.
2021
+ *
2022
+ * Push-only-on-change, modelled line for line on the session-list stream
2023
+ * above. What it pushes is a SIGNAL and never the board: see
2024
+ * `admin/board-stream.ts` for why that distinction is load-bearing rather
2025
+ * than an optimisation.
2026
+ *
2027
+ * Auth needs nothing special — `authMiddleware` is mounted at `/*` and
2028
+ * already accepts `?token=`, because `EventSource` cannot set headers.
2029
+ */
2030
+ app.get("/board/stream", (c) => {
2031
+ return streamSSE(c, async (stream) => {
2032
+ let prev = null; // null = nothing sent yet
2033
+ let lastBeat = Date.now();
2034
+ let stopped = false;
2035
+ stream.onAbort(() => {
2036
+ stopped = true;
2037
+ });
2038
+ const push = async () => {
2039
+ const revision = await boardSignature(db);
2040
+ const now = Date.now();
2041
+ const changed = revision !== prev;
2042
+ // The heartbeat is not decoration here — see BOARD_HEARTBEAT_MS.
2043
+ if (!changed && now - lastBeat < BOARD_HEARTBEAT_MS)
2044
+ return;
2045
+ prev = revision;
2046
+ lastBeat = now;
2047
+ await stream.writeSSE({
2048
+ event: "board",
2049
+ data: JSON.stringify({ revision, changed, at: new Date(now).toISOString() }),
2050
+ });
2051
+ };
2052
+ // The handshake frame: `prev` is null, so this always sends. It is what
2053
+ // tells the client the stream is live, and the client skips it rather
2054
+ // than treating it as news.
2055
+ await push();
2056
+ while (!stopped) {
2057
+ await stream.sleep(BOARD_TICK_MS);
2058
+ if (stopped)
2059
+ break;
2060
+ await push();
2061
+ }
2062
+ });
2063
+ });
1767
2064
  app.get("/repos", async (c) => {
1768
2065
  const managed = new Set(getManagedRepos());
1769
2066
  const activity = new Map((await db.runs.distinctRepos()).map((r) => [r.repo, r]));
@@ -2405,6 +2702,13 @@ export function createAdminRoutes(db, sessions, chatSessions, config) {
2405
2702
  });
2406
2703
  // ── Un-stick a pull request — the third retry surface ─────────────────────
2407
2704
  //
2705
+ // EXTRACTED from the route below so the pipeline board's card actions reach
2706
+ // this exact path rather than growing a second one. The board offers "Retry
2707
+ // run" on a PR card; had that posted somewhere new, `resolvePrState` +
2708
+ // `applyPrDispatchGate` would have acquired a second caller free to resolve a
2709
+ // different snapshot or skip a branch — which is the drift the PR gate's
2710
+ // copies already caused once. One function, one decision point, two callers.
2711
+ //
2408
2712
  // `lastlight pr retry <owner/repo#N> [reason]` and (eventually) the dashboard.
2409
2713
  // The other two surfaces are a `@<bot> retry` comment and taking
2410
2714
  // `requires-human` off by hand; all three write the SAME record
@@ -2440,13 +2744,9 @@ export function createAdminRoutes(db, sessions, chatSessions, config) {
2440
2744
  // fork guard, the run lock, `upstream-broken` or a degraded read — and, on the
2441
2745
  // skips that are none of those, what records the standalone `retry-requested`
2442
2746
  // row so the ask survives to the next event.
2443
- app.post("/prs/:owner/:repo/:number/retry", async (c) => {
2444
- const { owner, repo: name } = c.req.param();
2747
+ async function retryPullRequest(c, args) {
2748
+ const { owner, name, prNumber, reason } = args;
2445
2749
  const repo = `${owner}/${name}`;
2446
- const prNumber = Number.parseInt(c.req.param("number"), 10);
2447
- if (!Number.isInteger(prNumber) || prNumber <= 0) {
2448
- return c.json({ error: `invalid pull request number: ${c.req.param("number")}` }, 400);
2449
- }
2450
2750
  // The same allowlist that gates every other repo-touching path. A retry must
2451
2751
  // not be a way to make the harness act on a repo the operator never
2452
2752
  // enrolled — `dispatchWorkflow` refuses it too, but that refusal happens
@@ -2459,12 +2759,6 @@ export function createAdminRoutes(db, sessions, chatSessions, config) {
2459
2759
  if (!github || !config.dispatchWorkflow) {
2460
2760
  return c.json({ error: "pull-request retry is not configured" }, 503);
2461
2761
  }
2462
- // Free text from `lastlight pr retry <ref> "<reason>"`. Untrusted, and
2463
- // deliberately NOT sanitized here: `resolvePrState` runs it through
2464
- // `pr-notes.ts`'s sanitizer where the record is built, so no surface can
2465
- // skip that step.
2466
- const body = (await c.req.json().catch(() => ({})));
2467
- const reason = typeof body?.reason === "string" && body.reason.trim() ? body.reason.trim() : undefined;
2468
2762
  const by = actorFromContext(c) ?? "admin";
2469
2763
  // Which workflow is "go again"? The one that last worked this PR — the same
2470
2764
  // row `escalatePr` recorded against and the same row `resolvePrState` reads
@@ -2561,6 +2855,642 @@ export function createAdminRoutes(db, sessions, chatSessions, config) {
2561
2855
  retry,
2562
2856
  reason: disposition.reason,
2563
2857
  });
2858
+ }
2859
+ app.post("/prs/:owner/:repo/:number/retry", async (c) => {
2860
+ const { owner, repo: name } = c.req.param();
2861
+ const prNumber = Number.parseInt(c.req.param("number"), 10);
2862
+ if (!Number.isInteger(prNumber) || prNumber <= 0) {
2863
+ return c.json({ error: `invalid pull request number: ${c.req.param("number")}` }, 400);
2864
+ }
2865
+ // Free text from `lastlight pr retry <ref> "<reason>"`. Untrusted, and
2866
+ // deliberately NOT sanitized here: `resolvePrState` runs it through
2867
+ // `pr-notes.ts`'s sanitizer where the record is built, so no surface can
2868
+ // skip that step.
2869
+ const body = (await c.req.json().catch(() => ({})));
2870
+ const reason = typeof body?.reason === "string" && body.reason.trim() ? body.reason.trim() : undefined;
2871
+ return retryPullRequest(c, { owner, name, prNumber, reason });
2872
+ });
2873
+ // ── Start a build from the pipeline board ─────────────────────────────────
2874
+ //
2875
+ // The board's one mutating action on an ISSUE card. Everything else it offers
2876
+ // already had an endpoint — approve/reject resolve through
2877
+ // `POST /approvals/:id/respond`, cancel/retry through the workflow-run
2878
+ // routes, and a PR card's retry through `retryPullRequest` above — so this is
2879
+ // the only new surface Phase 7 adds.
2880
+ //
2881
+ // ## It crosses a gate; it does not dispatch blind
2882
+ //
2883
+ // `dispatchWorkflow` already guards the managed-repo allowlist, the repo's
2884
+ // own `disabled.workflows`, and the PR gate. What nothing guarded was the
2885
+ // ISSUE hold on a dashboard-initiated dispatch: a card whose issue carries
2886
+ // the hold label would have dispatched, because the hold is checked inside
2887
+ // `applyBuildDispatchGate` and nothing on this path had reached it. So this
2888
+ // route crosses that gate itself, for the same reason the PR retry above
2889
+ // crosses `applyPrDispatchGate` itself: the route that answers a human is the
2890
+ // route that has to be able to TELL them why not, and a fire-and-forget
2891
+ // dispatch can only ever answer "accepted".
2892
+ //
2893
+ // `dispatchWorkflow` then crosses the build gate a SECOND time, and that is
2894
+ // deliberate rather than tolerated. The context carries `_stage`, which is
2895
+ // what `engine/stage-observer.ts` reads to move the issue off the `running`
2896
+ // label when the run ends — drop it to dodge the second gate and every
2897
+ // board-started build strands on `agent-building` forever, which is precisely
2898
+ // the bug that module exists to prevent. The second crossing is harmless
2899
+ // because the consequence it applies is idempotent: `addLabels` re-adding a
2900
+ // label the issue already carries is a no-op, and `removeLabel` swallows the
2901
+ // 404 that means "already gone" (`stage-observer.ts` makes the same argument
2902
+ // about its own re-firing). The choke point stays the choke point; this route
2903
+ // just gets to answer first.
2904
+ app.post("/issues/:owner/:repo/:number/dispatch", async (c) => {
2905
+ const { owner, repo: name } = c.req.param();
2906
+ const repo = `${owner}/${name}`;
2907
+ const issueNumber = Number.parseInt(c.req.param("number"), 10);
2908
+ if (!Number.isInteger(issueNumber) || issueNumber <= 0) {
2909
+ return c.json({ error: `invalid issue number: ${c.req.param("number")}` }, 400);
2910
+ }
2911
+ // The same allowlist every other repo-touching path is gated on, checked
2912
+ // before anything is read or recorded against the repo.
2913
+ if (!isManagedRepo(repo)) {
2914
+ return c.json({ error: `${repo} is not a managed repository` }, 403);
2915
+ }
2916
+ const github = config.github ?? null;
2917
+ if (!github || !config.dispatchWorkflow) {
2918
+ return c.json({ error: "issue dispatch is not configured" }, 503);
2919
+ }
2920
+ const body = (await c.req.json().catch(() => ({})));
2921
+ const reason = typeof body?.reason === "string" && body.reason.trim() ? body.reason.trim() : undefined;
2922
+ // The stage names the workflow, the labels and the gates. Defaulting to the
2923
+ // first configured stage is what lets the board post a bare issue number;
2924
+ // an unknown name fails CLOSED, exactly as the gate itself does, because
2925
+ // everything downstream is keyed on names only the stage carries.
2926
+ const stages = getAutonomyConfig().stages;
2927
+ const stageName = typeof body?.stage === "string" && body.stage.trim()
2928
+ ? body.stage.trim()
2929
+ : Object.keys(stages)[0];
2930
+ const stage = stageName ? stages[stageName] : undefined;
2931
+ if (!stageName || !stage) {
2932
+ return c.json({ error: `unknown stage: \`${stageName ?? ""}\` is not in \`autonomy.stages\`` }, 400);
2933
+ }
2934
+ // THE ALLOW-LIST. See `ISSUE_DISPATCH_ROUTE_KEYS` — the workflow has to be
2935
+ // one the operator's own route map already points an issue trigger at.
2936
+ if (!isIssueRoutableWorkflow(stage.workflow)) {
2937
+ return c.json({
2938
+ error: `workflow \`${stage.workflow}\` is not reachable from an issue route ` +
2939
+ `(${ISSUE_DISPATCH_ROUTE_KEYS.join(", ")}), so the board may not dispatch it`,
2940
+ }, 400);
2941
+ }
2942
+ // ── THE LIVE RE-READ ────────────────────────────────────────────────────
2943
+ //
2944
+ // Never the cached board snapshot. The board is stale by design — up to
2945
+ // `BOARD_TTL_MS` (two minutes) — which is the right trade for RENDERING a
2946
+ // card and the wrong one entirely for DECIDING on it. Two minutes is ample
2947
+ // for a maintainer to apply the hold label and watch a build start anyway,
2948
+ // and the hold is the one instruction that must never lose a race. So the
2949
+ // labels the gate reads are the labels GitHub reports right now.
2950
+ let live;
2951
+ try {
2952
+ live = await github.getIssue(owner, name, issueNumber);
2953
+ }
2954
+ catch (err) {
2955
+ log.warn("Board dispatch could not read the issue", { repo, issueNumber, err });
2956
+ return c.json({ error: `could not read ${repo}#${issueNumber} from GitHub`, dispatched: false }, 502);
2957
+ }
2958
+ // The pipeline builds ISSUES. A pull request reached through the issues API
2959
+ // would cross a gate keyed on issue facts and dispatch a build against a
2960
+ // branch nobody asked to rebuild.
2961
+ if (live.pull_request) {
2962
+ return c.json({ error: `${repo}#${issueNumber} is a pull request, not an issue` }, 400);
2963
+ }
2964
+ const labels = (live.labels ?? [])
2965
+ .map((l) => (typeof l === "string" ? l : l?.name ?? ""))
2966
+ .filter(Boolean);
2967
+ const gate = await applyBuildDispatchGate({
2968
+ repo,
2969
+ issueNumber,
2970
+ labels,
2971
+ // A person clicked a button in the dashboard. Not `labeled` (no label
2972
+ // was applied) and not `sweep` (nothing discovered this).
2973
+ route: "api",
2974
+ // A browser session is a human by construction. The flag exists to make
2975
+ // `already-built` a HARD skip for machines and a permitted retry for
2976
+ // people, and this surface is unambiguously the latter.
2977
+ senderIsBot: false,
2978
+ stage: stageName,
2979
+ }, { db, github });
2980
+ const holdLabel = getHoldLabel();
2981
+ const held = labels.includes(holdLabel) ? holdLabel : null;
2982
+ const targetId = issueTriggerId(repo, issueNumber);
2983
+ const by = actorFromContext(c) ?? "admin";
2984
+ if (gate.decision === "skip") {
2985
+ // Recorded as loudly as a success, per the `pr.retry` precedent: a
2986
+ // refusal nobody can find afterwards is indistinguishable from the
2987
+ // feature quietly not working. Every skip on THIS surface is a refusal —
2988
+ // unlike the PR retry, no branch here parks an ask for a later event to
2989
+ // honour — so the outcome is always `denied`.
2990
+ await recordActivityFor(c, db, {
2991
+ action: "issue.dispatch",
2992
+ targetType: "issue",
2993
+ targetId,
2994
+ outcome: "denied",
2995
+ detail: {
2996
+ stage: stageName,
2997
+ workflow: stage.workflow,
2998
+ dispatched: false,
2999
+ reason: String(gate.reason ?? "").slice(0, 200),
3000
+ ...(reason ? { note: reason } : {}),
3001
+ },
3002
+ });
3003
+ return c.json({
3004
+ repo,
3005
+ issueNumber,
3006
+ stage: stageName,
3007
+ workflow: stage.workflow,
3008
+ dispatched: false,
3009
+ // The hold is the one skip that owes a human a sentence rather than a
3010
+ // reason string, and it is the SAME sentence every other surface
3011
+ // gives them.
3012
+ reason: held ? holdReply(held) : gate.reason,
3013
+ ...(held ? { held } : {}),
3014
+ }, 409);
3015
+ }
3016
+ // Fire-and-forget, exactly like `cron trigger` and the PR retry above: a
3017
+ // build takes minutes and the dashboard is waiting on this response.
3018
+ log.info("board dispatch", { workflow: stage.workflow, repo, issueNumber, stage: stageName, by });
3019
+ config.dispatchWorkflow(stage.workflow, {
3020
+ repo,
3021
+ issueNumber,
3022
+ title: live.title,
3023
+ body: live.body ?? "",
3024
+ labels,
3025
+ _triggerType: "api",
3026
+ // `_stage` names the stage for `stage-observer.ts`; `_autonomous` is what
3027
+ // `build-gate.ts` counts for `maxConcurrentBuilds` and what `simple.ts`
3028
+ // reads for the stage's `on_merge` policy. Both are stamped here because
3029
+ // both are properties of THIS dispatch.
3030
+ _stage: stageName,
3031
+ _autonomous: true,
3032
+ ...(gate.gates ? { _autonomyGates: gate.gates } : {}),
3033
+ sender: by,
3034
+ triggeredBy: by,
3035
+ }).catch((err) => {
3036
+ log.error("board dispatch failed", { workflow: stage.workflow, repo, issueNumber, err });
3037
+ });
3038
+ // The freshness lever that matters. Without this the card keeps rendering
3039
+ // its pre-dispatch stage for up to the full TTL, so the button appears to
3040
+ // have done nothing and the obvious next move is to press it again.
3041
+ invalidateBoard(repo);
3042
+ await recordActivityFor(c, db, {
3043
+ action: "issue.dispatch",
3044
+ targetType: "issue",
3045
+ targetId,
3046
+ detail: {
3047
+ stage: stageName,
3048
+ workflow: stage.workflow,
3049
+ dispatched: true,
3050
+ ...(reason ? { note: reason } : {}),
3051
+ },
3052
+ });
3053
+ return c.json({
3054
+ repo,
3055
+ issueNumber,
3056
+ stage: stageName,
3057
+ workflow: stage.workflow,
3058
+ dispatched: true,
3059
+ reason: gate.reason,
3060
+ });
3061
+ });
3062
+ // ── Move an issue between pipeline columns ────────────────────────────────
3063
+ //
3064
+ // `POST /issues/:owner/:repo/:number/stage`, body `{ to, from? }`. The drag
3065
+ // gesture on the board, and the second — last — mutating action it offers on
3066
+ // an issue card.
3067
+ //
3068
+ // ## There is no pipeline table, so a "move" is a label write
3069
+ //
3070
+ // The stage LABEL is the source of truth for where an issue has got to
3071
+ // (`stage-labels.ts`, `stage-advance.ts`). Nothing else records a column: the
3072
+ // board (`board.ts`) is a projection of the open issues GitHub reports and the
3073
+ // stage label each one carries. So moving a card cannot be a row update — it
3074
+ // is `advanceStage`, the same add-then-remove the harness performs host-side
3075
+ // at every dispatch, driven from a browser instead of from a run. We go
3076
+ // through that module rather than calling `addLabels`/`removeLabel` here
3077
+ // because its ORDERING is load-bearing: add first, and a half-failure leaves
3078
+ // the issue carrying both labels (visible, reconcilable); remove first, and a
3079
+ // half-failure drops it out of the pipeline entirely with nothing on it to
3080
+ // see. Its header makes the full argument.
3081
+ //
3082
+ // ## THE SECURITY PROPERTY: `to` is checked against the CONFIGURED labels
3083
+ //
3084
+ // This route lets an authenticated browser session write a label to a managed
3085
+ // repository. Unchecked, that is not "move a card" — it is "apply an
3086
+ // arbitrary label to any issue in any managed repo", which is a different and
3087
+ // much larger capability than the gesture implies (`good first issue`,
3088
+ // `security`, a label some other automation gates on). So `to` must be one of
3089
+ // the labels the OPERATOR configured under `autonomy.stages` — every
3090
+ // `enter` / `running` / `on_success` / `on_failure` across every stage — and
3091
+ // anything else is a 400, before a single GitHub call. `from` is checked the
3092
+ // same way, since it names a label we would REMOVE. The one extra value is
3093
+ // the empty string, meaning "off the board": remove `from`, add nothing.
3094
+ //
3095
+ // ## It writes a label AND, on the two build columns, dispatches
3096
+ //
3097
+ // A drag onto a stage's `enter` or `running` column is the same instruction
3098
+ // as the Dispatch button above, made with a different gesture, so it crosses
3099
+ // the SAME gate with the same standing: `route: "api"`, `senderIsBot: false`,
3100
+ // because a browser session is a human by construction. The two TERMINAL
3101
+ // columns (`on_success` / `on_failure`) and `""` move the card and start
3102
+ // nothing — "done" is not a request to build, and `on_failure` is also the
3103
+ // budget-exhausted comment's de-dup key, which a dispatch here would fight.
3104
+ //
3105
+ // **The bot skip is NOT relaxed, and this is the paragraph to read before
3106
+ // changing any of it.** `resolveBuildTrigger`'s `already-built` branch still
3107
+ // hard-skips a BOT re-label, which is what stops label ping-pong — a stage
3108
+ // observer's own write re-triggering the stage it just left. What changed is
3109
+ // that this route no longer *relies* on that webhook chain to start a build:
3110
+ // it asks the gate directly, as the person who dragged. Previously it did
3111
+ // rely on it, and the cost was invisible from the UI — our own label write
3112
+ // arrives with `senderIsBot: true`, so re-dragging an already-built issue
3113
+ // (every guardrails failure, every `agent-blocked` card) wrote the label and
3114
+ // started NOTHING, silently, with no affordance on the card saying why.
3115
+ //
3116
+ // ## The ORDER differs by column, and the reason is a race
3117
+ //
3118
+ // Only `stage.enter` is matched by the router's `stageForLabel`, so only an
3119
+ // `enter` write echoes back to us as a dispatchable webhook. Writing it and
3120
+ // THEN dispatching opens a real window: between our `addLabels` and
3121
+ // `createRun` the echo arrives, reads `alreadyBuilt: false` and
3122
+ // `runInFlight: false` — so the bot skip never even applies — and dispatches
3123
+ // a second time. `simple.ts` then reuses the run row (it dedups only a
3124
+ // QUEUED one), which is two agents in one workspace on one branch.
3125
+ //
3126
+ // So on the `enter` column we cross the gate FIRST. On a dispatch verdict the
3127
+ // gate's own guard 2 has already advanced the issue to `running`, so no
3128
+ // `enter` label is ever written, no echo is ever emitted, and there is
3129
+ // exactly one gate crossing per gesture — closed structurally, with no lock
3130
+ // and no new state. The card lands in the `running` column rather than the
3131
+ // one it was dropped on; `landedLabel` says so, and that is the truth of it.
3132
+ // On a SKIP verdict the label is written as dragged, so the drag still moves
3133
+ // the card and the reason travels back to render on it.
3134
+ //
3135
+ // The `running` column keeps the simpler write-then-gate order: it has no
3136
+ // echo, so it has no race. Dispatching there is not a convenience — the sweep
3137
+ // excludes the `running` label by design (`issue-discovery.ts`), so a card
3138
+ // dropped there with no run behind it is stranded permanently.
3139
+ app.post("/issues/:owner/:repo/:number/stage", async (c) => {
3140
+ const { owner, repo: name } = c.req.param();
3141
+ const repo = `${owner}/${name}`;
3142
+ const issueNumber = Number.parseInt(c.req.param("number"), 10);
3143
+ if (!Number.isInteger(issueNumber) || issueNumber <= 0) {
3144
+ return c.json({ error: `invalid issue number: ${c.req.param("number")}` }, 400);
3145
+ }
3146
+ // The same allowlist every other repo-touching path is gated on, checked
3147
+ // before anything is read or written against the repo.
3148
+ if (!isManagedRepo(repo)) {
3149
+ return c.json({ error: `${repo} is not a managed repository` }, 403);
3150
+ }
3151
+ const github = config.github ?? null;
3152
+ if (!github) {
3153
+ return c.json({ error: "stage moves are not configured" }, 503);
3154
+ }
3155
+ const body = (await c.req.json().catch(() => ({})));
3156
+ const to = typeof body?.to === "string" ? body.to.trim() : undefined;
3157
+ const from = typeof body?.from === "string" && body.from.trim() ? body.from.trim() : undefined;
3158
+ if (to === undefined) {
3159
+ return c.json({ error: "`to` is required (a configured stage label, or \"\" to unstage)" }, 400);
3160
+ }
3161
+ // THE ALLOW-LIST. Every label any configured stage names, in any position.
3162
+ // Built from `autonomy.stages` rather than from `stage-labels.ts`'s
3163
+ // constants so an operator who renamed a stage's labels moves this surface
3164
+ // with them — and an operator who configured no stages at all gets a
3165
+ // refusal rather than a write, which is the right failure for a feature
3166
+ // that is inert out of the box.
3167
+ const configuredLabels = new Set();
3168
+ for (const stage of Object.values(getAutonomyConfig().stages)) {
3169
+ for (const label of [stage.enter, stage.running, stage.on_success, stage.on_failure]) {
3170
+ if (label)
3171
+ configuredLabels.add(label);
3172
+ }
3173
+ }
3174
+ // `""` is legal for `to` only — it means "off the board". As a `from` it
3175
+ // would be meaningless (there is nothing to take off), and `from` is
3176
+ // already absent in that case.
3177
+ if (to !== "" && !configuredLabels.has(to)) {
3178
+ return c.json({ error: `\`${to}\` is not a configured stage label, so it may not be applied here` }, 400);
3179
+ }
3180
+ if (from !== undefined && !configuredLabels.has(from)) {
3181
+ return c.json({ error: `\`${from}\` is not a configured stage label, so it may not be removed here` }, 400);
3182
+ }
3183
+ // ── THE LIVE RE-READ ────────────────────────────────────────────────────
3184
+ //
3185
+ // Never the cached board snapshot, for the reason the dispatch route above
3186
+ // spells out: the board is stale by up to `BOARD_TTL_MS` (two minutes) by
3187
+ // design, which is the right trade for RENDERING a card and the wrong one
3188
+ // for acting on it. A failed read is a 502 rather than a write made blind —
3189
+ // the decision below turns on labels, and guessing at them is how the hold
3190
+ // loses a race it must never lose.
3191
+ let live;
3192
+ try {
3193
+ live = await github.getIssue(owner, name, issueNumber);
3194
+ }
3195
+ catch (err) {
3196
+ log.warn("Board stage move could not read the issue", { repo, issueNumber, from, to, err });
3197
+ return c.json({ error: `could not read ${repo}#${issueNumber} from GitHub`, moved: false }, 502);
3198
+ }
3199
+ const labels = (live.labels ?? [])
3200
+ .map((l) => (typeof l === "string" ? l : l?.name ?? ""))
3201
+ .filter(Boolean);
3202
+ const targetId = issueTriggerId(repo, issueNumber);
3203
+ const by = actorFromContext(c) ?? "admin";
3204
+ // THE HOLD OUTRANKS A DRAG, exactly as it outranks every other surface. A
3205
+ // maintainer who applied it has said "stay off this subject", and a drag is
3206
+ // not an exception to that — it is the same request as the dispatch button,
3207
+ // made with a different gesture. Recorded as loudly as a success, per the
3208
+ // `pr.retry` precedent, and answered with the same sentence every other
3209
+ // surface gives: `holdReply` names the label, because the fix is to remove
3210
+ // it and a reason code would not say so.
3211
+ const holdLabel = getHoldLabel();
3212
+ const held = labels.includes(holdLabel) ? holdLabel : null;
3213
+ if (held) {
3214
+ await recordActivityFor(c, db, {
3215
+ action: "issue.stage",
3216
+ targetType: "issue",
3217
+ targetId,
3218
+ outcome: "denied",
3219
+ detail: {
3220
+ ...(from ? { from } : {}),
3221
+ to,
3222
+ advanced: false,
3223
+ removed: false,
3224
+ reason: "on-hold",
3225
+ },
3226
+ });
3227
+ return c.json({ moved: false, reason: holdReply(held), held, dispatched: false }, 409);
3228
+ }
3229
+ // ── "Off the board" — the one move `advanceStage` cannot express ─────────
3230
+ //
3231
+ // Its whole contract is built around the ADD (add first, and only then the
3232
+ // remove), so it answers `no-target-label` for an empty `to` rather than
3233
+ // performing a bare removal. That is right for the dispatch path, which
3234
+ // never wants one. Here it is a real gesture: dragging a card out of the
3235
+ // pipeline. So this branch removes directly — the single site in this file
3236
+ // that touches a label without going through that module, and it is safe
3237
+ // to do so precisely because there is no ordering to get wrong.
3238
+ if (to === "") {
3239
+ if (!from) {
3240
+ // Nothing named, nothing to take off. A no-op, not an error: the card
3241
+ // is already where the caller asked for it to be.
3242
+ await recordActivityFor(c, db, {
3243
+ action: "issue.stage",
3244
+ targetType: "issue",
3245
+ targetId,
3246
+ detail: { to, advanced: false, removed: false, reason: "already-unstaged" },
3247
+ });
3248
+ return c.json({ moved: true, advanced: false, removed: false, dispatched: false });
3249
+ }
3250
+ let removed = true;
3251
+ let reason;
3252
+ try {
3253
+ await github.removeLabel(owner, name, issueNumber, from);
3254
+ }
3255
+ catch (err) {
3256
+ // Unlike a failed remove AFTER a successful add, nothing at all moved
3257
+ // here — but it is still not an error the caller can act on differently,
3258
+ // so it reports the same granular shape rather than a status code. The
3259
+ // card redraws where it was, which is the truth.
3260
+ removed = false;
3261
+ reason = "remove-failed";
3262
+ log.warn("Board stage move could not unstage the issue", {
3263
+ repo,
3264
+ issueNumber,
3265
+ from,
3266
+ err,
3267
+ });
3268
+ }
3269
+ await recordActivityFor(c, db, {
3270
+ action: "issue.stage",
3271
+ targetType: "issue",
3272
+ targetId,
3273
+ outcome: removed ? "ok" : "error",
3274
+ detail: { from, to, advanced: false, removed, ...(reason ? { reason } : {}) },
3275
+ });
3276
+ invalidateBoard(repo);
3277
+ return c.json({ moved: removed, advanced: false, removed, dispatched: false });
3278
+ }
3279
+ log.info("board stage move", { repo, issueNumber, from, to, by });
3280
+ // ── IS THIS GESTURE A REQUEST TO BUILD? ─────────────────────────────────
3281
+ const slotMatch = stageSlotForLabel(to);
3282
+ const stages = getAutonomyConfig().stages;
3283
+ const matchedStage = slotMatch?.kind === "match" ? stages[slotMatch.stage] : undefined;
3284
+ // Every reason this gesture MOVES the card but starts nothing. Each is a
3285
+ // sentence a card can render, not a bare code, and the order is
3286
+ // most-specific-first so the answer names the real obstacle.
3287
+ const dispatchRefusal = (() => {
3288
+ if (slotMatch === null)
3289
+ return `unconfigured-label: \`${to}\` names no autonomy stage`;
3290
+ if (slotMatch.kind === "ambiguous") {
3291
+ return (`ambiguous-stage: \`${to}\` is claimed by ${slotMatch.stages.join(", ")}, ` +
3292
+ `so which build to start is undecidable`);
3293
+ }
3294
+ if (slotMatch.slot !== "enter" && slotMatch.slot !== "running") {
3295
+ return (`terminal-column: \`${to}\` is the \`${slotMatch.slot}\` label of ` +
3296
+ `\`${slotMatch.stage}\`, which ends a build rather than starting one`);
3297
+ }
3298
+ if (!matchedStage)
3299
+ return `unknown-stage: \`${slotMatch.stage}\` is not in \`autonomy.stages\``;
3300
+ if (!config.dispatchWorkflow)
3301
+ return "dispatch-not-configured: this deployment has no runner wired";
3302
+ // The pipeline builds ISSUES. A pull request reached through the issues
3303
+ // API would cross a gate keyed on issue facts and dispatch a build
3304
+ // against a branch nobody asked to rebuild — the same refusal the
3305
+ // dispatch button makes. The MOVE still stands; PR cards live on the
3306
+ // board and dragging one between columns is legitimate.
3307
+ if (live.pull_request)
3308
+ return "not-an-issue: the pipeline builds issues, and this is a pull request";
3309
+ // A drop that changes no label is not an instruction. The client has a
3310
+ // same-column no-op, but it is computed from a board snapshot up to
3311
+ // BOARD_TTL_MS stale, so `from` is often wrong and the same column gets
3312
+ // re-dropped. This one reads the LIVE labels, and it is what keeps a
3313
+ // gesture with no menu and no confirm step from being drop-spam that
3314
+ // bills.
3315
+ if (labels.includes(to))
3316
+ return `already-in-stage: ${repo}#${issueNumber} already carries \`${to}\``;
3317
+ if (!isIssueRoutableWorkflow(matchedStage.workflow)) {
3318
+ return (`unroutable-workflow: \`${matchedStage.workflow}\` is not reachable from an ` +
3319
+ `issue route (${ISSUE_DISPATCH_ROUTE_KEYS.join(", ")})`);
3320
+ }
3321
+ return undefined;
3322
+ })();
3323
+ // The PROJECTED label set — what is true of the issue AFTER this move, not
3324
+ // before it. The gate reads labels for the hold and for the
3325
+ // budget-exhausted comment de-dup, and both are questions about the issue
3326
+ // as it will be.
3327
+ const projected = [...new Set(labels.filter((l) => l !== from).concat(to ? [to] : []))];
3328
+ let dispatched = false;
3329
+ let dispatchReason = dispatchRefusal;
3330
+ let dispatchStage;
3331
+ const crossGate = async (stageName) => {
3332
+ const gate = await applyBuildDispatchGate({ repo, issueNumber, labels: projected, route: "api", senderIsBot: false, stage: stageName }, { db, github });
3333
+ dispatchReason = gate.reason;
3334
+ return gate;
3335
+ };
3336
+ // Fire-and-forget, exactly like the dispatch button: a build takes minutes
3337
+ // and the dashboard is waiting on this response.
3338
+ const fireDispatch = (stageName, workflow, gates) => {
3339
+ dispatched = true;
3340
+ dispatchStage = stageName;
3341
+ config.dispatchWorkflow(workflow, {
3342
+ repo,
3343
+ issueNumber,
3344
+ title: live.title,
3345
+ body: live.body ?? "",
3346
+ labels: projected,
3347
+ _triggerType: "api",
3348
+ // `_stage` names the stage for `stage-observer.ts` — drop it and every
3349
+ // board-started build strands on the running label forever.
3350
+ // `_autonomous` is what `build-gate.ts` counts for
3351
+ // `maxConcurrentBuilds` and what `simple.ts` reads for `on_merge`.
3352
+ _stage: stageName,
3353
+ _autonomous: true,
3354
+ ...(gates ? { _autonomyGates: gates } : {}),
3355
+ sender: by,
3356
+ triggeredBy: by,
3357
+ }).catch((err) => {
3358
+ log.error("board stage dispatch failed", { repo, issueNumber, stage: stageName, err });
3359
+ });
3360
+ };
3361
+ // ── GATE FIRST ON THE ENTRY COLUMN ──────────────────────────────────────
3362
+ //
3363
+ // See the route header. Crossing before the write is what stops our own
3364
+ // `enter` label echoing back as a second dispatch; on a dispatch verdict
3365
+ // guard 2 has already moved the issue to `running`, so we never write
3366
+ // `enter` at all.
3367
+ const gateFirst = dispatchRefusal === undefined && slotMatch?.kind === "match" && slotMatch.slot === "enter";
3368
+ if (gateFirst && slotMatch?.kind === "match" && matchedStage) {
3369
+ const gate = await crossGate(slotMatch.stage);
3370
+ if (gate.decision === "dispatch") {
3371
+ // Guard 2 wrote `running` and 404-swallowed the `enter` removal. All
3372
+ // that is left is the label the card was dragged OFF — best-effort, on
3373
+ // the same argument `advanceStage` makes: the run row is the fact and
3374
+ // the labels are its projection, so a GitHub blip must not undo a
3375
+ // dispatch that has already been decided.
3376
+ let removed = false;
3377
+ const stale = from && from !== matchedStage.running ? from : undefined;
3378
+ if (stale) {
3379
+ try {
3380
+ await github.removeLabel(owner, name, issueNumber, stale);
3381
+ removed = true;
3382
+ }
3383
+ catch (err) {
3384
+ log.warn("board stage move could not remove the previous label", {
3385
+ repo,
3386
+ issueNumber,
3387
+ from: stale,
3388
+ err,
3389
+ });
3390
+ }
3391
+ }
3392
+ fireDispatch(slotMatch.stage, matchedStage.workflow, gate.gates);
3393
+ invalidateBoard(repo);
3394
+ await recordActivityFor(c, db, {
3395
+ action: "issue.stage",
3396
+ targetType: "issue",
3397
+ targetId,
3398
+ detail: {
3399
+ ...(from ? { from } : {}),
3400
+ to,
3401
+ advanced: true,
3402
+ removed,
3403
+ dispatched: true,
3404
+ ...(dispatchReason ? { dispatchReason: String(dispatchReason).slice(0, 200) } : {}),
3405
+ },
3406
+ });
3407
+ return c.json({
3408
+ moved: true,
3409
+ advanced: true,
3410
+ removed,
3411
+ dispatched: true,
3412
+ stage: slotMatch.stage,
3413
+ // Where the card ACTUALLY landed. Guard 2 advanced it to the running
3414
+ // column, so the SPA must place it there rather than springing back.
3415
+ landedLabel: matchedStage.running,
3416
+ ...(dispatchReason ? { dispatchReason } : {}),
3417
+ });
3418
+ }
3419
+ // The gate said no. Fall through: the label is written as dragged, the
3420
+ // card moves, and the reason travels back to render on it.
3421
+ }
3422
+ const result = await advanceStage({ owner, repo: name, issueNumber, from, to }, { github });
3423
+ // A failed ADD means NOTHING happened — `advanceStage` deliberately does not
3424
+ // attempt the remove in that case, so the issue is still wearing `from` and
3425
+ // still in its previous stage. That is a true statement about it, and the
3426
+ // honest answer to the caller is that the move did not happen.
3427
+ if (!result.added) {
3428
+ await recordActivityFor(c, db, {
3429
+ action: "issue.stage",
3430
+ targetType: "issue",
3431
+ targetId,
3432
+ outcome: "error",
3433
+ detail: {
3434
+ ...(from ? { from } : {}),
3435
+ to,
3436
+ advanced: false,
3437
+ removed: false,
3438
+ reason: String(result.reason ?? "add-failed").slice(0, 200),
3439
+ },
3440
+ });
3441
+ return c.json({
3442
+ error: `could not apply \`${to}\` to ${repo}#${issueNumber}`,
3443
+ moved: false,
3444
+ reason: result.reason,
3445
+ }, 502);
3446
+ }
3447
+ // The `running` column dispatches AFTER the write — it has no webhook echo
3448
+ // and therefore no race. `gateFirst` guards against crossing twice when the
3449
+ // entry path already asked and was refused.
3450
+ if (!gateFirst && dispatchRefusal === undefined && slotMatch?.kind === "match" && matchedStage) {
3451
+ const gate = await crossGate(slotMatch.stage);
3452
+ if (gate.decision === "dispatch") {
3453
+ fireDispatch(slotMatch.stage, matchedStage.workflow, gate.gates);
3454
+ }
3455
+ }
3456
+ // A failed REMOVE is not an error. The issue now carries BOTH labels, which
3457
+ // is the tolerable half of that module's asymmetry: visible, reconcilable by
3458
+ // hand or by the next advance, and a later stage wins wherever the pair is
3459
+ // read. So the move stands and the granular result travels back — the card
3460
+ // will redraw in its new column with the stale label still attached, which
3461
+ // is exactly what is true of it.
3462
+ await recordActivityFor(c, db, {
3463
+ action: "issue.stage",
3464
+ targetType: "issue",
3465
+ targetId,
3466
+ detail: {
3467
+ ...(from ? { from } : {}),
3468
+ to,
3469
+ advanced: result.advanced,
3470
+ removed: result.removed,
3471
+ dispatched,
3472
+ ...(dispatchReason ? { dispatchReason: String(dispatchReason).slice(0, 200) } : {}),
3473
+ ...(result.reason ? { reason: result.reason } : {}),
3474
+ },
3475
+ });
3476
+ // The freshness lever. Without it the card keeps rendering its pre-move
3477
+ // column for up to the full TTL, so the drag springs back and the obvious
3478
+ // next move is to drag it again.
3479
+ invalidateBoard(repo);
3480
+ return c.json({
3481
+ moved: true,
3482
+ advanced: result.advanced,
3483
+ removed: result.removed,
3484
+ // Stated rather than omitted, on both answers. `dispatchReason` carries
3485
+ // WHY when nothing started — a terminal column, a budget ceiling, a run
3486
+ // already in flight — and is deliberately a separate field from `reason`,
3487
+ // which belongs to the LABEL outcome (`remove-failed`) and answers a
3488
+ // different question.
3489
+ dispatched,
3490
+ ...(dispatchStage ? { stage: dispatchStage } : {}),
3491
+ ...(dispatchReason ? { dispatchReason } : {}),
3492
+ ...(result.reason ? { reason: result.reason } : {}),
3493
+ });
2564
3494
  });
2565
3495
  return app;
2566
3496
  }