@oakgreencc/cambium 0.0.7 → 0.0.8

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.
package/README.md CHANGED
@@ -19,15 +19,16 @@ cambium status
19
19
 
20
20
  ## Commands
21
21
 
22
- | Command | What |
23
- | ---------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
24
- | `cambium start [--once]` | Foreground daemon, one tick every `tickSeconds`. SIGTERM/SIGINT stop it after the current tick; workers keep running and are re-adopted on restart. One daemon per database. |
25
- | `cambium status [--json]` | Mode, last tick, queue counts, workers, failed steps. Exit 1 when there is no heartbeat or it is older than 3 ticks. |
26
- | `cambium pause` | Read and heartbeat only: no transitions, no starts. Running workers are left alone. |
27
- | `cambium drain` | Reconcile, watch and sweep as usual; start nothing new. |
28
- | `cambium resume` | Back to `running`. |
29
- | `cambium run task --issue <n> [--repo <owner/name>]` | Claim one open `q:task` issue, run its worker in the foreground, then make the same transition the daemon would. |
30
- | `cambium install [--dry-run]` | Write the launchd agent (`KeepAlive`, `RunAtLoad`) for `start --config <this config>`; `--dry-run` prints it. It does not call `launchctl`; it prints the command. |
22
+ | Command | What |
23
+ | ------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
24
+ | `cambium start [--once]` | Foreground daemon, one tick every `tickSeconds`. SIGTERM/SIGINT stop it after the current tick; workers keep running and are re-adopted on restart. One daemon per database. |
25
+ | `cambium status [--json]` | Mode, last tick, queue counts, workers, failed steps. Exit 1 when there is no heartbeat or it is older than 3 ticks. |
26
+ | `cambium pause` | Read and heartbeat only: no transitions, no starts. Running workers are left alone. |
27
+ | `cambium drain` | Reconcile, watch and sweep as usual; start nothing new. |
28
+ | `cambium resume` | Back to `running`. |
29
+ | `cambium run task --issue <n> [--repo <owner/name>]` | Claim one open `q:task` issue, run its worker in the foreground, then make the same transition the daemon would. |
30
+ | `cambium run <graph> --issue <n> [--repo <owner/name>] [--follow]` | `engine: "graph"` only (`task` is the one graph today). Advance one issue through the graph runtime in the foreground: a `q:task` issue without a lease starts with a foreground worker; anything else resumes where its marker rests. Stops at the first wait that is not ready; `--follow` re-reads and polls every `tickSeconds` until the graph ends. |
31
+ | `cambium install [--dry-run]` | Write the launchd agent (`KeepAlive`, `RunAtLoad`) for `start --config <this config>`; `--dry-run` prints it. It does not call `launchctl`; it prints the command. |
31
32
 
32
33
  Every command takes `--config <file>`; the default is `$CAMBIUM_CONFIG`, then `~/.cambium/config.json`.
33
34
 
@@ -91,6 +92,7 @@ One JSON file. Everything but `repos` is optional; these are the defaults:
91
92
  ```json
92
93
  {
93
94
  "host": "<os.hostname()>",
95
+ "engine": "legacy",
94
96
  "tickSeconds": 30,
95
97
  "stepTimeoutSeconds": 20,
96
98
  "repos": [{ "slug": "oakgreencc/monorepo", "path": "~/OGCC/monorepo", "baseBranch": "main" }],
@@ -115,6 +117,7 @@ One JSON file. Everything but `repos` is optional; these are the defaults:
115
117
 
116
118
  - `repos[].path` is a local clone; worktrees are added from it and `graft` runs in it.
117
119
  - `graft.app` is the App cambium acts as (`GRAFT_APP` for its own `graft` calls); `worker.graftApp` the one workers act as. Neither leaks into the other.
120
+ - `engine` picks how the Task phase runs: `"legacy"` (the stage tick, the default) or `"graph"` (the [`task` graph](#the-task-graph)). Both make the same moves; see [The task graph](#the-task-graph).
118
121
  - Setting `paths.home` moves every default path under it.
119
122
  - `release.time` is host-local `HH:MM`.
120
123
 
@@ -218,9 +221,62 @@ Written at the end of every tick to `paths.heartbeat` (default `~/.cambium/state
218
221
 
219
222
  The mode lives in the SQLite file (`paths.db`, table `control`), so `cambium status --json` returns `{ "mode", "heartbeat" }` even when the daemon is down. The daemon's own log is `<paths.logs>/cambium.log` (one `.1` kept); launchd's stderr goes to `<paths.logs>/cambium.launchd.err.log`.
220
223
 
224
+ ## The task graph
225
+
226
+ With `"engine": "graph"` the tick's Task-phase steps (Reconcile, Watch, Sweep, Schedule) drive the `task` graph (`src/graphs/task.mjs`) instead of the stage tick in `src/tick.mjs`. The default stays `"legacy"`; flipping it and deleting the legacy path is a follow-up.
227
+
228
+ ```mermaid
229
+ flowchart TD
230
+ start_(["q:task"])
231
+ n0["start-worker"]
232
+ n1{{"worker-running"}}
233
+ n2{{"ci-running"}}
234
+ n3{{"merge-queue"}}
235
+ n4["close-out"]
236
+ n5["requeue"]
237
+ n6["to-human"]
238
+ end_(("end"))
239
+ start_ --> n0
240
+ n0 -->|"started"| n1
241
+ n0 -->|"budgetSpent"| n6
242
+ n0 --> n5
243
+ n1 -->|"issueGone"| end_
244
+ n1 -->|"submitted"| n2
245
+ n1 --> n5
246
+ n2 -->|"merged"| n4
247
+ n2 -->|"inMergeQueue"| n3
248
+ n2 -->|"stalled"| n6
249
+ n2 --> n5
250
+ n3 -->|"merged"| n4
251
+ n3 -->|"stalled"| n6
252
+ n3 --> n5
253
+ n5 -->|"attemptsLeft"| n0
254
+ n5 --> n6
255
+ n4 --> end_
256
+ n6 --> end_
257
+ ```
258
+
259
+ Generated by `toMermaid(task)`; a test keeps this copy current. Boxes are step nodes, hexagons are waits.
260
+
261
+ | Node | Kind | Queue label | Holds `running` |
262
+ | ---------------- | ---- | ----------- | --------------- |
263
+ | `start-worker` | step | `q:task` | no |
264
+ | `worker-running` | wait | `q:task` | yes |
265
+ | `ci-running` | wait | none | no |
266
+ | `merge-queue` | wait | none | no |
267
+ | `close-out` | step | none | no |
268
+ | `requeue` | step | `q:task` | no |
269
+ | `to-human` | step | `q:human` | no |
270
+
271
+ - **Labels are a projection.** Each node declares its queue label and whether it holds `running`. When an issue lands on a node, the marker is written first, then the labels come from `move()` (`labels.mjs`) with that declaration.
272
+ - **Where a turn starts.** Reconcile polls `worker-running` for every tracked worker. Watch polls `ci-running` / `merge-queue` for agent PRs whose issue is in no queue; a merged PR goes to `close-out` wherever the issue is, as in the stage tick. Sweep sends a stale `running` lease to its node's `recover` (default: `requeue`). Schedule is the gate on the entry node: caps and priority pick the issues, each starts at `start-worker`.
273
+ - **Where a turn stops.** At a wait that is not ready, on entering a wait (it is polled next tick; `merge-queue` is polled on entry, so a stall is caught in the same pass), on reaching `start-worker` again (only Schedule admits it), or at the end.
274
+ - **Markers.** The graph writes marker v2 without `stage`: `node` is where the issue rests. `merge-queue` is the stage tick's `submitted` with `queued: true`, and a stage-era marker in that state resumes at `merge-queue`. A marker whose node the current graph version no longer has restarts at `start-worker` with a `graph-changed` history entry.
275
+ - **Same moves.** Every scenario in `test/tick.test.mjs` runs on both engines; the test compares their GitHub calls in order (markers semantically, not by rendered text), worker starts with their prompts, kills, teardowns and logs.
276
+
221
277
  ## Graph module (preview)
222
278
 
223
- `@oakgreencc/cambium/graph` is the start of typed workflows: nodes with schemas, edges as data, and a loop that advances a position through them. Nothing in the tick uses it yet.
279
+ `@oakgreencc/cambium/graph` is the start of typed workflows: nodes with schemas, edges as data, and a loop that advances a position through them. The Task phase runs on it with `engine: "graph"` ([The task graph](#the-task-graph)).
224
280
 
225
281
  ```js
226
282
  import { z } from 'zod'
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oakgreencc/cambium",
3
- "version": "0.0.7",
3
+ "version": "0.0.8",
4
4
  "description": "The scheduler daemon: reads the q:* queues from GitHub every tick, runs headless claude workers in their own worktrees up to a cap, and makes every queue transition itself.",
5
5
  "license": "AGPL-3.0-only",
6
6
  "type": "module",
@@ -50,7 +50,7 @@
50
50
  "@opentelemetry/sdk-metrics": "^3.1.1",
51
51
  "@opentelemetry/sdk-trace": "^3.1.1",
52
52
  "zod": "^4.6.7",
53
- "@oakgreencc/mycelium": "0.0.5"
53
+ "@oakgreencc/mycelium": "0.0.0"
54
54
  },
55
55
  "scripts": {
56
56
  "lint": "biome check .",
package/src/cli.mjs CHANGED
@@ -13,6 +13,7 @@ import { acquireLock, readHeartbeat, realDeps, runDaemon } from './daemon.mjs'
13
13
  import { plist, plistPath } from './launchd.mjs'
14
14
  import { openStore } from './store.mjs'
15
15
  import { finish, newCtx, startTask } from './tick.mjs'
16
+ import { runIssue } from './graph-engine.mjs'
16
17
 
17
18
  export const VERSION = '0.0.0'
18
19
 
@@ -25,6 +26,9 @@ export const HELP = `cambium ${VERSION} — the scheduler daemon
25
26
  cambium drain reconcile and watch, start no new workers
26
27
  cambium run task --issue <n> [--repo <owner/name>]
27
28
  claim one q:task issue, run its worker in the foreground, transition
29
+ cambium run <graph> --issue <n> [--repo <owner/name>] [--follow]
30
+ engine "graph": advance the issue in the foreground to the first wait
31
+ that is not ready; --follow keeps polling until the graph ends
28
32
  cambium install [--dry-run] write the launchd agent (KeepAlive); --dry-run prints it
29
33
 
30
34
  Common: --config <file> (default $CAMBIUM_CONFIG, then ~/.cambium/config.json)`
@@ -45,6 +49,7 @@ const has = (argv, name) => argv.includes(name)
45
49
  * deps?: (config: import('./config.mjs').Config) => import('./tick.mjs').Deps,
46
50
  * signal?: AbortSignal,
47
51
  * now?: () => number,
52
+ * sleep?: (ms: number) => Promise<void>,
48
53
  * }} IO
49
54
  */
50
55
 
@@ -141,15 +146,21 @@ function status(config, io, json) {
141
146
 
142
147
  /**
143
148
  * `run task --issue N`: one Task phase in the foreground, with the daemon's
144
- * claim and transitions, so the daemon sees the same state afterwards.
149
+ * claim and transitions, so the daemon sees the same state afterwards. On
150
+ * `engine: "graph"`, `run <graph> --issue N [--follow]` runs the graph runtime
151
+ * in the foreground instead (graph-engine.mjs `runIssue`).
145
152
  *
146
153
  * @param {import('./config.mjs').Config} config @param {string[]} argv @param {IO} io
147
154
  * @param {(config: import('./config.mjs').Config) => import('./tick.mjs').Deps} depsFor
148
155
  */
149
156
  async function runOne(config, argv, io, depsFor) {
150
157
  const n = Number(flag(argv, '--issue'))
151
- if (argv[0] !== 'task' || !Number.isInteger(n) || n <= 0)
152
- return fail(io, 'usage: cambium run task --issue <n> [--repo <owner/name>]')
158
+ const graph = argv[0]
159
+ if (!graph || graph.startsWith('-') || !Number.isInteger(n) || n <= 0)
160
+ return fail(io, 'usage: cambium run <graph> --issue <n> [--repo <owner/name>] [--follow]')
161
+ const follow = has(argv, '--follow')
162
+ if (config.engine === 'legacy' && (graph !== 'task' || follow))
163
+ return fail(io, `engine "legacy" runs only \`run task --issue <n>\`; set "engine": "graph" for graphs and --follow`)
153
164
  const slug = flag(argv, '--repo') ?? (config.repos.length === 1 ? config.repos[0].slug : undefined)
154
165
  if (!slug || !config.repos.some((r) => r.slug === slug))
155
166
  return fail(
@@ -157,6 +168,10 @@ async function runOne(config, argv, io, depsFor) {
157
168
  `--repo must name one of the configured repos: ${config.repos.map((r) => r.slug).join(', ') || '(none)'}`,
158
169
  )
159
170
  const deps = depsFor(config)
171
+ if (config.engine === 'graph') {
172
+ const r = await runIssue(deps, { graph, slug, number: n, follow, out: io.out, sleep: io.sleep, signal: io.signal })
173
+ return r.ok ? 0 : fail(io, /** @type {string} */ (r.error))
174
+ }
160
175
  if (deps.store.worker(slug, n)) return fail(io, `${slug}#${n} already has a tracked worker`)
161
176
  const snap = await deps.github.read(slug)
162
177
  const issue = snap.issues.get(n)
package/src/config.mjs CHANGED
@@ -12,6 +12,7 @@ import { join, resolve } from 'node:path'
12
12
  * @typedef {{ cap: number, wallClockMinutes: number, maxTurns: number, maxAttempts: number }} PhaseCaps
13
13
  * @typedef {{
14
14
  * host: string,
15
+ * engine: 'legacy' | 'graph',
15
16
  * tickSeconds: number,
16
17
  * stepTimeoutSeconds: number,
17
18
  * repos: Repo[],
@@ -32,6 +33,7 @@ export const DEFAULT_HOME = join(homedir(), '.cambium')
32
33
  export function defaults(home = DEFAULT_HOME) {
33
34
  return {
34
35
  host: hostname(),
36
+ engine: 'legacy',
35
37
  tickSeconds: 30,
36
38
  stepTimeoutSeconds: 20,
37
39
  repos: [],
@@ -86,6 +88,8 @@ export function resolveConfig(raw = {}) {
86
88
  if (!r.path) throw new Error(`config: repo ${r.slug} needs "path" (a local clone)`)
87
89
  return { slug: r.slug, path: untilde(r.path), baseBranch: r.baseBranch ?? 'main' }
88
90
  })
91
+ if (config.engine !== 'legacy' && config.engine !== 'graph')
92
+ throw new Error(`config: engine must be "legacy" or "graph", got ${JSON.stringify(config.engine)}`)
89
93
  if (!/^\d{2}:\d{2}$/.test(config.release.time)) throw new Error(`config: release.time must be HH:MM`)
90
94
  return config
91
95
  }
@@ -0,0 +1,289 @@
1
+ // @ts-check
2
+ /**
3
+ * `engine: "graph"`: the Task-phase steps of the tick, driven through the `task` graph (graphs/task.mjs).
4
+ *
5
+ * The tick keeps its shape (Reconcile → Watch → Sweep → Schedule) so both engines make the same moves in the
6
+ * same order; each step only chooses where an issue's turn starts:
7
+ *
8
+ * - Reconcile: every tracked worker's issue at `worker-running`.
9
+ * - Watch: issues resting at `ci-running` / `merge-queue` (from the marker); a merged PR goes to `close-out`
10
+ * from wherever the issue is.
11
+ * - Sweep: a stale `running` lease runs its node's `recover` (default: `requeue`).
12
+ * - Schedule: the gate on the entry node. Caps and priority pick the issues; each starts at `start-worker`.
13
+ *
14
+ * A turn ({@link drive}) advances one transition at a time and stops when it reaches the entry node again (only
15
+ * Schedule admits entries), when it enters a wait (polled next tick, unless the wait is `pollOnEntry`), at END,
16
+ * or at a wait that is not ready.
17
+ */
18
+ import { advance, END } from './graph/index.mjs'
19
+ import { deleteMergedBranch, inputFor, lostLeaseOf, nodeOf, task, TASK_QUEUES, TERMINAL } from './graphs/task.mjs'
20
+ import { iso, key, markerOf, setLabels, setMarker } from './issue-state.mjs'
21
+ import { effectivePosition, graphVersionDecision, withHistory } from './marker.mjs'
22
+ import { each, newCtx, staleLeases, taskCandidates, watched, watchPairs } from './tick.mjs'
23
+ import { move, Q } from './labels.mjs'
24
+
25
+ /**
26
+ * @typedef {import('./tick.mjs').Deps} Deps
27
+ * @typedef {import('./tick.mjs').Ctx} Ctx
28
+ * @typedef {import('./graphs/task.mjs').Subject} Subject
29
+ * @typedef {import('./graphs/task.mjs').Position} Position
30
+ * @typedef {import('./graph/advance.mjs').Transition} Transition
31
+ * @typedef {{ transitions: Transition[], reason: 'waiting' | 'gated' | 'end', node: string, input: unknown }} Turn
32
+ */
33
+
34
+ /** @param {Deps} deps @param {Ctx} ctx @param {Subject} subject @returns {import('./graphs/task.mjs').TaskCtx} */
35
+ const taskCtx = (deps, ctx, subject) => ({ ...deps, tick: ctx, subject })
36
+
37
+ /**
38
+ * One issue's turn from `at`. A node error is rethrown as the node's own error (the step logs it, as the legacy
39
+ * tick does); a worker whose `worker-running` was left is torn down only after the turn's writes succeeded.
40
+ *
41
+ * @param {Deps} deps @param {Ctx} ctx @param {Subject} subject @param {Position} at
42
+ * @returns {Promise<Turn>}
43
+ */
44
+ export async function drive(deps, ctx, subject, at) {
45
+ const c = taskCtx(deps, ctx, subject)
46
+ /** @type {Transition[]} */
47
+ const transitions = []
48
+ let pos = at
49
+ /** @type {Turn['reason']} */
50
+ let reason
51
+ for (;;) {
52
+ const r = await advance(task, pos, c, { maxTransitions: 1 })
53
+ if (r.error) throw r.error.cause instanceof Error ? r.error.cause : r.error
54
+ transitions.push(...r.transitions)
55
+ const t = r.transitions[0]
56
+ if (t && t.to !== END) await nodeOf(t.to).enter?.(t.next, c)
57
+ pos = { node: r.node, input: r.input }
58
+ if (r.reason !== 'limit') {
59
+ reason = r.reason === 'waiting' ? 'waiting' : 'end'
60
+ break
61
+ }
62
+ if (r.node === task.entry.node) {
63
+ reason = 'gated'
64
+ break
65
+ }
66
+ const next = nodeOf(r.node)
67
+ if (next.kind === 'wait' && !next.pollOnEntry) {
68
+ reason = 'waiting'
69
+ break
70
+ }
71
+ }
72
+ if (transitions.some((t) => t.from === 'worker-running')) await releaseWorker(deps, subject)
73
+ return { transitions, reason, ...pos }
74
+ }
75
+
76
+ /** The worker row goes, then its worktree (kept, with a warning, when it holds local-only work). @param {Deps} deps @param {Subject} s */
77
+ async function releaseWorker(deps, s) {
78
+ const w = deps.store.worker(s.slug, s.number)
79
+ if (!w) return
80
+ deps.store.removeWorker(s.slug, s.number)
81
+ const repo = deps.config.repos.find((r) => r.slug === s.slug)
82
+ if (!repo) return
83
+ const t = await deps.spawner.cleanup({ repo, worktree: w.worktree, branch: w.branch })
84
+ if (!t.removed) deps.log('warn', `kept worktree ${w.worktree}: ${t.reason}`, { repo: s.slug, issue: s.number })
85
+ }
86
+
87
+ /**
88
+ * Where an issue rests in the task graph, from its labels and marker: the label wins (marker.mjs
89
+ * `effectivePosition`), a stage-era `submitted` that the merge queue holds is `merge-queue`, and a node the
90
+ * current graph version no longer has restarts at the entry (with a `graph-changed` history note).
91
+ *
92
+ * @param {import('./github.mjs').Issue} issue @param {number} now
93
+ * @returns {(Position & { note?: import('./marker.mjs').HistoryEntry }) | null} null: not in the task graph
94
+ */
95
+ export function locate(issue, now) {
96
+ const marker = issue.stateComment?.marker ?? null
97
+ const pos = effectivePosition(issue.labels, marker, TASK_QUEUES)
98
+ if (!pos || pos.graph !== task.name) return null
99
+ if (pos.reset || !marker) return { node: task.entry.node, input: {} }
100
+ const v = graphVersionDecision(marker, {
101
+ version: task.version,
102
+ nodes: task.nodes.map((n) => n.name),
103
+ entryNode: task.entry.node,
104
+ at: iso(now),
105
+ })
106
+ if (v.action === 'restart') return { node: v.node, input: {}, note: v.note }
107
+ const node = pos.node === 'ci-running' && marker.queued ? 'merge-queue' : pos.node
108
+ return { node, input: inputFor(node, marker) }
109
+ }
110
+
111
+ /**
112
+ * A marker whose node is gone from the graph: back to `q:task` at the entry, with the note in its history.
113
+ * @param {Deps} deps @param {Ctx} ctx @param {string} slug @param {import('./github.mjs').Issue} issue
114
+ * @param {import('./marker.mjs').HistoryEntry} note
115
+ */
116
+ async function restart(deps, ctx, slug, issue, note) {
117
+ const m = markerOf(issue)
118
+ await setMarker(deps, slug, issue, {
119
+ ...withHistory(m, note),
120
+ graph: task.name,
121
+ graphVersion: task.version,
122
+ node: task.entry.node,
123
+ status: 'waiting',
124
+ host: null,
125
+ start: null,
126
+ input: null,
127
+ })
128
+ await setLabels(deps, slug, issue, move(issue.labels, Q.task))
129
+ ctx.touched.add(key(slug, issue.number))
130
+ deps.log('info', note.reason ?? 'graph changed; restarting', { repo: slug, issue: issue.number })
131
+ }
132
+
133
+ // ---- The Task-phase steps
134
+
135
+ /** @param {Deps} deps @param {Ctx} ctx */
136
+ async function reconcile(deps, ctx) {
137
+ await each(
138
+ deps,
139
+ deps.store.workers(),
140
+ async (w) => {
141
+ const snap = ctx.snaps.get(w.repo)
142
+ const subject = { slug: w.repo, number: w.issue, snap, issue: snap?.issues.get(w.issue) }
143
+ await drive(deps, ctx, subject, { node: 'worker-running', input: { branch: w.branch, attempt: w.attempt } })
144
+ },
145
+ (w) => ({ repo: w.repo, issue: w.issue }),
146
+ )
147
+ }
148
+
149
+ /** @param {Deps} deps @param {Ctx} ctx */
150
+ async function watch(deps, ctx) {
151
+ for (const [slug, snap] of ctx.snaps) {
152
+ /** @type {Set<string>} */
153
+ const deleted = new Set()
154
+ await each(
155
+ deps,
156
+ watchPairs(snap),
157
+ async ([pr, issue]) => {
158
+ if (ctx.touched.has(key(slug, issue.number))) return
159
+ /** @type {Subject} */
160
+ const subject = { slug, number: issue.number, snap, issue, pr, deleted }
161
+ if (pr.state === 'MERGED') {
162
+ if (issue.state === 'OPEN') await drive(deps, ctx, subject, { node: 'close-out', input: { pr: pr.number } })
163
+ else await deleteMergedBranch(taskCtx(deps, ctx, subject), pr)
164
+ return
165
+ }
166
+ if (pr.state !== 'OPEN' || issue.state !== 'OPEN' || !watched(deps, slug, issue)) return
167
+ const at = locate(issue, ctx.now)
168
+ if (at?.note) return restart(deps, ctx, slug, issue, at.note)
169
+ if (at?.node === 'ci-running' || at?.node === 'merge-queue') await drive(deps, ctx, subject, at)
170
+ },
171
+ ([, issue]) => ({ repo: slug, issue: issue.number }),
172
+ )
173
+ }
174
+ }
175
+
176
+ /** @param {Deps} deps @param {Ctx} ctx */
177
+ async function sweep(deps, ctx) {
178
+ for (const [slug, snap] of ctx.snaps)
179
+ await each(
180
+ deps,
181
+ staleLeases(deps, ctx, slug, snap),
182
+ async (issue) => {
183
+ const subject = { slug, number: issue.number, snap, issue }
184
+ const c = taskCtx(deps, ctx, subject)
185
+ const at = locate(issue, ctx.now)
186
+ const recover = (at && nodeOf(at.node).recover) || defaultRecover
187
+ await drive(deps, ctx, subject, recover(c))
188
+ },
189
+ (issue) => ({ repo: slug, issue: issue.number }),
190
+ )
191
+ }
192
+
193
+ /** @param {Deps} deps @param {Ctx} ctx */
194
+ async function scheduleTasks(deps, ctx) {
195
+ await each(
196
+ deps,
197
+ taskCandidates(deps, ctx),
198
+ async (c) => {
199
+ const subject = { slug: c.slug, number: c.issue.number, snap: c.snap, issue: c.issue }
200
+ await drive(deps, ctx, subject, { node: task.entry.node, input: {} })
201
+ },
202
+ (c) => ({ repo: c.slug, issue: c.issue.number }),
203
+ )
204
+ }
205
+
206
+ /** A stale lease at a node without its own `recover`: requeue. @param {import('./graphs/task.mjs').TaskCtx} c */
207
+ const defaultRecover = (c) => ({ node: 'requeue', input: lostLeaseOf(c) })
208
+
209
+ /** @type {import('./tick.mjs').Engine} */
210
+ export const GRAPH_ENGINE = { reconcile, watch, sweep, scheduleTasks }
211
+
212
+ // ---- `cambium run <graph> --issue <n> [--follow]`
213
+
214
+ /** Graphs `cambium run` knows, by name. */
215
+ export const GRAPHS = { [task.name]: task }
216
+
217
+ /**
218
+ * The graph runtime in the foreground for one issue. A `q:task` issue without a lease starts at the entry with a
219
+ * foreground worker, whose exit is awaited; anything else resumes where its marker rests. Stops at the first wait
220
+ * that is not ready, unless `follow`, which re-reads and polls again every `tickSeconds` until the graph ends.
221
+ *
222
+ * @param {Deps} deps
223
+ * @param {{
224
+ * graph: string, slug: string, number: number, follow?: boolean,
225
+ * out: (line: string) => void, sleep?: (ms: number) => Promise<void>, signal?: AbortSignal,
226
+ * }} opts
227
+ * @returns {Promise<{ ok: boolean, error?: string }>}
228
+ */
229
+ export async function runIssue(deps, { graph, slug, number, follow = false, out, sleep = delay, signal }) {
230
+ if (!Object.hasOwn(GRAPHS, graph))
231
+ return { ok: false, error: `unknown graph "${graph}"; known: ${Object.keys(GRAPHS).join(', ')}` }
232
+ /** @type {Set<number>} */
233
+ const reaped = new Set()
234
+ let first = true
235
+ for (;;) {
236
+ const ctx = newCtx(deps)
237
+ const snap = await deps.github.read(slug)
238
+ ctx.snaps.set(slug, snap)
239
+ const issue = snap.issues.get(number)
240
+ if (issue?.state !== 'OPEN') {
241
+ if (first) return { ok: false, error: `${slug}#${number} is not an open issue` }
242
+ return report(out, slug, number, issue)
243
+ }
244
+ const worker = deps.store.worker(slug, number)
245
+ const fresh = issue.labels.includes(Q.task) && !issue.labels.includes('running') && !worker
246
+ const located = fresh
247
+ ? { node: task.entry.node, input: {} }
248
+ : worker
249
+ ? { node: 'worker-running', input: { branch: worker.branch, attempt: worker.attempt } }
250
+ : locate(issue, ctx.now)
251
+ if (!located || TERMINAL.has(located.node)) {
252
+ if (first) return { ok: false, error: `${slug}#${number} has nothing to run in the ${graph} graph` }
253
+ return report(out, slug, number, issue)
254
+ }
255
+ if (located.note) await restart(deps, ctx, slug, issue, located.note)
256
+ /** @type {Subject} */
257
+ const subject = { slug, number, snap, issue, foreground: true, reaped }
258
+ const turn = located.note ? null : await drive(deps, ctx, subject, located)
259
+ if (subject.started) {
260
+ const s = subject.started
261
+ out(`worker pid ${s.pid} in ${s.worktree}\n stdout ${s.stdout}\n stderr ${s.stderr}`)
262
+ const code = await s.exited
263
+ out(`worker exited ${code}`)
264
+ reaped.add(s.pid)
265
+ first = false
266
+ continue
267
+ }
268
+ if (first && fresh && !follow)
269
+ return { ok: false, error: `${slug}#${number} was not started; see its state comment` }
270
+ first = false
271
+ if (turn?.reason === 'end' || !follow || signal?.aborted) return report(out, slug, number, issue)
272
+ await sleep(deps.config.tickSeconds * 1000)
273
+ if (signal?.aborted) return report(out, slug, number, issue)
274
+ }
275
+ }
276
+
277
+ /** @param {number} ms */
278
+ const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
279
+
280
+ /**
281
+ * @param {(line: string) => void} out @param {string} slug @param {number} n
282
+ * @param {import('./github.mjs').Issue | undefined} issue
283
+ */
284
+ function report(out, slug, n, issue) {
285
+ const m = issue?.state === 'OPEN' ? issue.stateComment?.marker : null
286
+ const where = m ? `${m.node}${m.status === 'waiting' ? '' : ` (${m.status})`}` : 'closed'
287
+ out(`${slug}#${n}: ${where} · labels ${issue?.labels.join(', ') || '(none)'}`)
288
+ return { ok: true }
289
+ }