@oakgreencc/cambium 0.0.8 → 0.0.10

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
@@ -2,7 +2,7 @@
2
2
 
3
3
  The scheduler daemon. Every tick it reads the `q:*` queues from GitHub, starts headless `claude -p` workers in their own worktrees up to a cap, watches their PRs through CI and the merge queue, and makes every queue transition itself. GitHub is the truth; local SQLite only remembers which processes it started.
4
4
 
5
- This is the **Task phase** MVP. Dispatch and the daily Release run are seams (see [Follow-ups](#follow-ups)).
5
+ This is the **Task phase** MVP. Dispatch is a seam; Release runs as graphs on `engine: "graph"` and is a seam on the legacy engine (see [Follow-ups](#follow-ups)).
6
6
 
7
7
  Runtime dependencies: `zod` (the [graph module](#graph-module-preview)) and OpenTelemetry via `@oakgreencc/mycelium` (loaded only when [tracing](#tracing) is on); Node ≥ 22.13 (`node:sqlite`). GitHub access goes through [`graft`](../graft), which must be on `PATH`.
8
8
 
@@ -41,10 +41,10 @@ Each step is bounded by `stepTimeoutSeconds`. A step that throws or times out is
41
41
  3. **Watch** (no agent), for agent PRs whose issue is in no queue: merged → close the issue, delete the branch; red → requeue with the failing checks' summaries; left the merge queue without merging → requeue; not merged `mergeQueueMinutes` after submission → `q:human`.
42
42
  4. **Sweep.** An issue labelled `running` with this host (or no host) in its marker and no tracked worker → requeue. This is what makes losing the SQLite file cost one requeue.
43
43
  5. **Schedule.** Start Task workers for `q:task` issues without `running`, by priority label then age, up to `phases.task.cap` counted from live workers. A task requeued earlier in the same tick can start in that tick.
44
- 6. **Release.** Once a day at `release.time` when `release.enabled`; the run itself is a seam.
44
+ 6. **Release.** Legacy: once a day at `release.time` when `release.enabled`; the run itself is a seam. Graph: the [release graphs](#the-release-graphs), per repo.
45
45
  7. **Heartbeat.** Write the state file.
46
46
 
47
- A requeue is `q:task` with attempt + 1, or, once `maxAttempts` are spent, `q:human` + `why:budget`. cambium never merges: the merge queue and auto-merge do.
47
+ A requeue is `q:task` with attempt + 1, or, once `maxAttempts` are spent, `q:human` + `why:budget`. The Task phase never merges: the merge queue and auto-merge do. (The one merge cambium asks for is an approved promotion PR, through `graft pr merge`; see [The release graphs](#the-release-graphs).)
48
48
 
49
49
  ## State on GitHub
50
50
 
@@ -120,6 +120,7 @@ One JSON file. Everything but `repos` is optional; these are the defaults:
120
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).
121
121
  - Setting `paths.home` moves every default path under it.
122
122
  - `release.time` is host-local `HH:MM`.
123
+ - `repos[].release` (`engine: "graph"`): `{ "enabled", "time", "from", "to" }`. `enabled` and `time` default to the top-level `release`, `from` to the repo's `baseBranch`, `to` to `"main"`. A repo whose `from` equals `to` has no promotion PR. Example: `{ "slug": "o/app", "path": "~/app", "baseBranch": "develop", "release": { "enabled": true, "time": "06:00", "from": "develop", "to": "main" } }`.
123
124
 
124
125
  ### Target repo convention
125
126
 
@@ -274,6 +275,57 @@ Generated by `toMermaid(task)`; a test keeps this copy current. Boxes are step n
274
275
  - **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
276
  - **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
277
 
278
+ ## The release graphs
279
+
280
+ With `"engine": "graph"` the tick's Release step runs two graphs (`src/graphs/release.mjs`) for every repo whose `release` is on. Their subject is the **promotion PR**, which promotes the repo's integration branch to its release branch (`release.from` → `release.to`, e.g. `develop` → `main`). The marker (v2) is cambium's state comment on that PR, written through the same path as an issue's.
281
+
282
+ `release-prepare` has a clock entry: once a day at the repo's `release.time` (`releaseDue`, last run in the store under `release.lastRun:<slug>`).
283
+
284
+ ```mermaid
285
+ flowchart TD
286
+ start_(["start"])
287
+ n0["cleanup"]
288
+ n1["prepare"]
289
+ end_(("end"))
290
+ start_ --> n0
291
+ n0 --> n1
292
+ n1 --> end_
293
+ ```
294
+
295
+ `release-promote` sits in `q:promote` and enters at `merge` once the promotion PR is approved (`reviewDecision`, or the latest reviews).
296
+
297
+ ```mermaid
298
+ flowchart TD
299
+ start_(["q:promote"])
300
+ n0["merge"]
301
+ n1{{"merging"}}
302
+ n2["promoted"]
303
+ n3["abandoned"]
304
+ end_(("end"))
305
+ start_ --> n0
306
+ n0 -->|"armed"| n1
307
+ n0 --> end_
308
+ n1 -->|"merged"| n2
309
+ n1 --> n3
310
+ n2 --> end_
311
+ n3 --> end_
312
+ ```
313
+
314
+ Generated by `toMermaid`; a test keeps these copies current.
315
+
316
+ | Node | Graph | Kind | What it does |
317
+ | ----------- | --------------- | ---- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
318
+ | `cleanup` | release-prepare | step | Closes, with a comment, every open promotion PR (`from` → `to`, or carrying a release marker) older than 24 h; takes `q:promote` off. |
319
+ | `prepare` | release-prepare | step | `from` ahead of `to`: opens the promotion PR (or refreshes the open one) with the PRs merged into `from` since `to`, labels it `q:promote`, writes the marker. Nothing ahead: a log line. |
320
+ | `merge` | release-promote | step | `graft pr merge <n> --auto`: graft's merge policy, auto-merge, or a merge now when the PR is clean. A refusal is recorded on the marker and not retried on the same head. |
321
+ | `merging` | release-promote | wait | Holds while the PR is open. |
322
+ | `promoted` | release-promote | step | Merged: marker done, `q:promote` off. |
323
+ | `abandoned` | release-promote | step | Closed unmerged: marker done, `q:promote` off. A `q:promote` PR closed or merged before it was approved goes here (or to `promoted`) too. |
324
+
325
+ - **No timeouts.** Neither graph has one; the daily `cleanup` is the only 24 h rule.
326
+ - **Read.** With a repo's release on, the snapshot query also asks (in the same query) for the open PRs from `from` to `to`, the PRs labelled `q:promote`, and `to`'s comparison with `from` (`aheadBy`, and the merged PRs on the last 100 commits ahead).
327
+ - **Legacy.** `engine: "legacy"` keeps the stub.
328
+
277
329
  ## Graph module (preview)
278
330
 
279
331
  `@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)).
@@ -316,6 +368,26 @@ const { transitions, reason, node, input } = await advance(g, { node: 'open-pr',
316
368
  - **`toMermaid(graph)`** renders a flowchart: boxes for steps, hexagons for waits, conditional edges labelled with `when`'s function name.
317
369
  - **`opts.instrument(visit, step)`** (optional) wraps each node visit: `visit` is `{ node, kind: 'node' | 'wait', input }`; `step(extraCtx?)` runs the node (or poll) and picks the edge, returning the transition, or `null` for a wait that is not ready, and throws on a node error. `extraCtx` is merged into that node's `ctx`. Return what `step` returned. Without it, `advance` behaves exactly as before. [`advanceHooks`](#tracing) is the tracing implementation.
318
370
 
371
+ ### LangGraph interop
372
+
373
+ `@oakgreencc/cambium/graph/langgraph` converts graphs to and from [LangGraph](https://docs.langchain.com/oss/javascript/langgraph/overview). LangGraph is not a cambium dependency: install `@langchain/langgraph` and `@langchain/core` yourself (an optional peer dependency). The module does not import LangGraph at load time; `toLangGraph` imports it when called, or takes the module as `{ langgraph }`.
374
+
375
+ ```js
376
+ import { Command, MemorySaver } from '@langchain/langgraph'
377
+ import { fromLangGraph, pollWait, toLangGraph } from '@oakgreencc/cambium/graph/langgraph'
378
+
379
+ const app = (await toLangGraph(g)).compile({ checkpointer: new MemorySaver() })
380
+ const config = { configurable: { thread_id: 'owner/repo#42' }, context: ctx }
381
+ let out = await app.invoke({ subject, last: { issue: 7 } }, config)
382
+ const waiting = out.__interrupt__?.[0]?.value // { waiting: 'ci', input: { pr: 1 } }
383
+ const polled = await pollWait(g, waiting, ctx)
384
+ if (polled.ready) out = await app.invoke(new Command({ resume: polled.output }), config)
385
+ ```
386
+
387
+ - **`toLangGraph(graph, { langgraph }?)`** resolves to an uncompiled `StateGraph` over `{ subject, last, outputs }`: `last` is the next node's input, `outputs` each node's latest output by name, and `subject` what edges see (it is checkpointed, so keep it serializable). Nodes get the run's `context` (plus `signal`) as `ctx`. Each node is `addNode(name, fn, { input })`, its input schema being the node's own on `last`; `fn` validates, runs, picks the edge and applies its `map`, so `last` is already the next input. A wait calls `interrupt({ waiting, input })`; resume it with the ready poll's `output` (`pollWait` runs the poll; a not-ready poll never reaches LangGraph). Edges are `addConditionalEdges`, trying `when` in order; `END` is LangGraph's `END`. Errors are `GraphNodeError`s.
388
+ - **`fromLangGraph(compiled, { name, input, output })`** is a `defineNode` whose `run` invokes the compiled graph with the validated input as its input state and validates the final state against `output`. An imported graph cannot wait: `interrupt()` inside it fails the node with an error saying so.
389
+ - Not carried over: `entry.queue`, `version` and the task graph's per-node declarations (`queue`, `running`, `enter`, `pollOnEntry`, `recover`), which belong to cambium's runtime; a driver applies them around the interrupts, as the differential test in `test/langgraph.test.mjs` does.
390
+
319
391
  ## Tracing
320
392
 
321
393
  `src/tracing.mjs` is OpenTelemetry for cambium, configured only by the standard `OTEL_*` variables with `service.name=cambium`. It reuses mycelium's `createTracing` (same packages, same on/off rule): **on only when `OTEL_EXPORTER_OTLP_ENDPOINT` or `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` is set**, unless `OTEL_SDK_DISABLED=true` or `OTEL_TRACES_EXPORTER=none`; otherwise nothing is imported and every call is a no-op. Metrics follow the same rule for their signal (`OTEL_EXPORTER_OTLP_METRICS_ENDPOINT`, `OTEL_METRICS_EXPORTER`). With an endpoint but no collector, shutdown can take ~8 s; set `OTEL_EXPORTER_OTLP_TIMEOUT=2000` for the daemon.
@@ -430,7 +502,7 @@ Without Jaeger running the collector still writes the files; the Jaeger exporter
430
502
  Seams that exist, typed, and do nothing yet:
431
503
 
432
504
  - **Dispatch** (`src/phases/dispatch.mjs`): `Dispatch(input: { repo, intake, capacity, now }) → { started }`. Reached only when `phases.dispatch.cap > 0`; the stub starts nothing and logs that `q:intake` waits.
433
- - **Release** (`src/phases/release.mjs`): `Release(input: { repo, now }) → { done, note }`. The once-a-day schedule (`releaseDue`) is real and recorded in the store; the run returns `{ done: false }`.
505
+ - **Release**, legacy engine only (`src/phases/release.mjs`): `Release(input: { repo, now }) → { done, note }`. The once-a-day schedule (`releaseDue`) is real and recorded in the store; the run returns `{ done: false }`. The graph engine runs the [release graphs](#the-release-graphs).
434
506
  - Conditional (ETag) reads, so an unchanged poll is free against the rate limit; GraphQL has no ETag, so this needs a REST probe in front of the query.
435
507
  - More than 100 queued issues or open PRs per repo, and state comments beyond an issue's first 100 comments: the read is one page.
436
508
  - Spend caps per worker (turns and wall clock are enforced today).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oakgreencc/cambium",
3
- "version": "0.0.8",
3
+ "version": "0.0.10",
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",
@@ -26,6 +26,7 @@
26
26
  },
27
27
  "exports": {
28
28
  "./graph": "./src/graph/index.mjs",
29
+ "./graph/langgraph": "./src/graph/langgraph.mjs",
29
30
  "./package.json": "./package.json"
30
31
  },
31
32
  "files": [
@@ -52,6 +53,18 @@
52
53
  "zod": "^4.6.7",
53
54
  "@oakgreencc/mycelium": "0.0.0"
54
55
  },
56
+ "devDependencies": {
57
+ "@langchain/core": "^1.4.1",
58
+ "@langchain/langgraph": "^1.7.5"
59
+ },
60
+ "peerDependencies": {
61
+ "@langchain/langgraph": "^1.7.5"
62
+ },
63
+ "peerDependenciesMeta": {
64
+ "@langchain/langgraph": {
65
+ "optional": true
66
+ }
67
+ },
55
68
  "scripts": {
56
69
  "lint": "biome check .",
57
70
  "test": "node --test 'test/*.test.mjs'"
package/src/config.mjs CHANGED
@@ -8,7 +8,11 @@ import { homedir, hostname } from 'node:os'
8
8
  import { join, resolve } from 'node:path'
9
9
 
10
10
  /**
11
- * @typedef {{ slug: string, path: string, baseBranch: string }} Repo
11
+ * @typedef {{ enabled: boolean, time: string, from: string, to: string }} RepoRelease
12
+ * The promotion PR (`engine: "graph"`): `from` (default: the repo's `baseBranch`) is promoted into `to`
13
+ * (default `main`) once a day at `time`. `enabled`/`time` default to the top-level `release`. Off when
14
+ * `from === to`.
15
+ * @typedef {{ slug: string, path: string, baseBranch: string, release: RepoRelease }} Repo
12
16
  * @typedef {{ cap: number, wallClockMinutes: number, maxTurns: number, maxAttempts: number }} PhaseCaps
13
17
  * @typedef {{
14
18
  * host: string,
@@ -82,15 +86,25 @@ export function resolveConfig(raw = {}) {
82
86
  /** @type {Config} */
83
87
  const config = merge(defaults(home), raw)
84
88
  for (const k of /** @type {const} */ (['home', 'db', 'heartbeat', 'logs'])) config.paths[k] = untilde(config.paths[k])
89
+ if (!/^\d{2}:\d{2}$/.test(config.release.time)) throw new Error(`config: release.time must be HH:MM`)
85
90
  config.repos = (config.repos ?? []).map((r) => {
86
91
  if (!r?.slug || !/^[^/\s]+\/[^/\s]+$/.test(r.slug))
87
92
  throw new Error(`config: repo slug must be owner/name, got ${r?.slug}`)
88
93
  if (!r.path) throw new Error(`config: repo ${r.slug} needs "path" (a local clone)`)
89
- return { slug: r.slug, path: untilde(r.path), baseBranch: r.baseBranch ?? 'main' }
94
+ const baseBranch = r.baseBranch ?? 'main'
95
+ /** @type {RepoRelease} */
96
+ const release = {
97
+ enabled: config.release.enabled,
98
+ time: config.release.time,
99
+ from: baseBranch,
100
+ to: 'main',
101
+ ...r.release,
102
+ }
103
+ if (!/^\d{2}:\d{2}$/.test(release.time)) throw new Error(`config: repo ${r.slug} release.time must be HH:MM`)
104
+ return { slug: r.slug, path: untilde(r.path), baseBranch, release }
90
105
  })
91
106
  if (config.engine !== 'legacy' && config.engine !== 'graph')
92
107
  throw new Error(`config: engine must be "legacy" or "graph", got ${JSON.stringify(config.engine)}`)
93
- if (!/^\d{2}:\d{2}$/.test(config.release.time)) throw new Error(`config: release.time must be HH:MM`)
94
108
  return config
95
109
  }
96
110
 
package/src/github.mjs CHANGED
@@ -7,7 +7,7 @@
7
7
  */
8
8
  import { spawn } from 'node:child_process'
9
9
  import { parseMarker } from './marker.mjs'
10
- import { QUEUE_LABELS } from './labels.mjs'
10
+ import { Q, QUEUE_LABELS } from './labels.mjs'
11
11
 
12
12
  /**
13
13
  * @typedef {{
@@ -20,13 +20,32 @@ import { QUEUE_LABELS } from './labels.mjs'
20
20
  * branchExists: boolean, inMergeQueue: boolean, autoMerge: boolean,
21
21
  * checks: 'SUCCESS' | 'FAILURE' | 'ERROR' | 'PENDING' | 'EXPECTED' | null, failing: FailingCheck[], closes: number[],
22
22
  * }} PullRequest
23
- * @typedef {{ issues: Map<number, Issue>, prs: PullRequest[] }} Snapshot
23
+ * @typedef {{
24
+ * number: number, url: string, title: string, state: 'OPEN' | 'MERGED' | 'CLOSED', createdAt: string,
25
+ * head: string, base: string, headSha: string | null, labels: string[], approved: boolean, autoMerge: boolean,
26
+ * stateComment: { id: number, marker: import('./marker.mjs').Marker } | null,
27
+ * }} PromotionPr
28
+ * A promotion PR (`from` → `to`, or labelled `q:promote`). Its state comment is a PR (issue) comment, so it
29
+ * goes through the same marker read/write path as an issue's. `approved`: `reviewDecision` is APPROVED, or
30
+ * (no decision against it) a latest review approves and none requests changes.
31
+ * @typedef {{
32
+ * from: string, to: string, aheadBy: number | null, merged: { number: number, title: string }[],
33
+ * prs: PromotionPr[],
34
+ * }} Release
35
+ * The repo's promotion state (when its `release` is on): how far `from` is ahead of `to` (null: `to` does not
36
+ * exist), the PRs merged into `from` since `to` (oldest first, from the last 100 commits ahead), and the
37
+ * promotion PRs: open ones from `from` to `to` plus any (open, merged or closed) still labelled `q:promote`.
38
+ * @typedef {{ issues: Map<number, Issue>, prs: PullRequest[], release?: Release | null }} Snapshot
24
39
  * @typedef {{
25
40
  * read(slug: string): Promise<Snapshot>,
26
41
  * label(slug: string, number: number, change: { add: string[], remove: string[] }): Promise<void>,
27
42
  * writeState(slug: string, number: number, commentId: number | null, body: string): Promise<number>,
28
43
  * close(slug: string, number: number, body: string): Promise<void>,
29
44
  * deleteBranch(slug: string, branch: string): Promise<void>,
45
+ * openPull(slug: string, pr: { head: string, base: string, title: string, body: string }): Promise<{ number: number, url: string }>,
46
+ * editPull(slug: string, number: number, change: { title: string, body: string }): Promise<void>,
47
+ * closePull(slug: string, number: number, comment: string): Promise<void>,
48
+ * mergePull(slug: string, number: number): Promise<void>,
30
49
  * }} GitHub
31
50
  */
32
51
 
@@ -40,39 +59,116 @@ const PR_FIELDS = `number url headRefName state headRefOid isInMergeQueue
40
59
  ... on StatusContext { context state targetUrl description }
41
60
  } } } } } }`
42
61
 
43
- /** One query per repo per tick: the queued issues and the agent PRs with their checks. */
44
- export const SNAPSHOT_QUERY = `query($owner: String!, $name: String!, $labels: [String!]) {
62
+ /**
63
+ * One query per repo per tick: the queued issues and the agent PRs with their checks; with `$release`, also the
64
+ * promotion PRs and how far `$from` is ahead of `$to` (see {@link Release}).
65
+ */
66
+ export const SNAPSHOT_QUERY = `query($owner: String!, $name: String!, $labels: [String!], $release: Boolean!, $from: String!, $to: String!) {
45
67
  repository(owner: $owner, name: $name) {
46
68
  issues(labels: $labels, states: OPEN, first: 100, orderBy: { field: CREATED_AT, direction: ASC }) { nodes { ...I } }
47
69
  open: pullRequests(states: OPEN, first: 100, orderBy: { field: UPDATED_AT, direction: DESC }) { nodes { ${PR_FIELDS} } }
48
70
  merged: pullRequests(states: MERGED, first: 30, orderBy: { field: UPDATED_AT, direction: DESC }) { nodes { ${PR_FIELDS} } }
71
+ promoteRef: pullRequests(headRefName: $from, baseRefName: $to, states: OPEN, first: 10) @include(if: $release) { nodes { ...P } }
72
+ promoteLabelled: pullRequests(labels: ["${Q.promote}"], first: 10, orderBy: { field: UPDATED_AT, direction: DESC }) @include(if: $release) { nodes { ...P } }
73
+ toRef: ref(qualifiedName: $to) @include(if: $release) {
74
+ compare(headRef: $from) {
75
+ aheadBy
76
+ commits(last: 100) { nodes { associatedPullRequests(first: 3) { nodes { number title baseRefName state } } } }
77
+ }
78
+ }
49
79
  }
50
80
  }
51
81
  fragment I on Issue {
52
82
  number title url state createdAt body
53
83
  labels(first: 30) { nodes { name } }
54
84
  comments(first: 100) { nodes { databaseId body author { login } } }
85
+ }
86
+ fragment P on PullRequest {
87
+ number url title state createdAt headRefName baseRefName headRefOid reviewDecision
88
+ autoMergeRequest { enabledAt }
89
+ latestReviews(first: 20) { nodes { state } }
90
+ labels(first: 30) { nodes { name } }
91
+ comments(first: 100) { nodes { databaseId body author { login } } }
55
92
  }`
56
93
 
57
94
  const FAILED = new Set(['FAILURE', 'ERROR', 'TIMED_OUT', 'CANCELLED', 'ACTION_REQUIRED', 'STARTUP_FAILURE'])
58
95
 
96
+ /**
97
+ * The first comment holding a marker (from `botLogin` only, when set). Issues and PRs alike.
98
+ * @param {any} n an issue or PR node with `comments` @param {string | null} botLogin
99
+ * @returns {{ id: number, marker: import('./marker.mjs').Marker } | null}
100
+ */
101
+ function stateCommentOf(n, botLogin) {
102
+ const comment = (n.comments?.nodes ?? []).find(
103
+ (/** @type {any} */ c) => parseMarker(c.body) && (!botLogin || c.author?.login === botLogin),
104
+ )
105
+ return comment ? { id: comment.databaseId, marker: /** @type {any} */ (parseMarker(comment.body)) } : null
106
+ }
107
+
108
+ /** @param {any} n @returns {string[]} */
109
+ const labelsOf = (n) => (n.labels?.nodes ?? []).map((/** @type {any} */ l) => l.name)
110
+
111
+ /**
112
+ * The `$release` part of the answer → {@link Release}.
113
+ * @param {any} repo @param {{ from: string, to: string }} branches @param {string | null} botLogin
114
+ * @returns {Release}
115
+ */
116
+ function normalizeRelease(repo, { from, to }, botLogin) {
117
+ /** @type {Map<number, PromotionPr>} */
118
+ const prs = new Map()
119
+ for (const p of [...(repo.promoteRef?.nodes ?? []), ...(repo.promoteLabelled?.nodes ?? [])]) {
120
+ if (!p || prs.has(p.number)) continue
121
+ const reviews = (p.latestReviews?.nodes ?? []).map((/** @type {any} */ r) => r.state)
122
+ prs.set(p.number, {
123
+ number: p.number,
124
+ url: p.url ?? '',
125
+ title: p.title ?? '',
126
+ state: p.state,
127
+ createdAt: p.createdAt,
128
+ head: p.headRefName,
129
+ base: p.baseRefName,
130
+ headSha: p.headRefOid ?? null,
131
+ labels: labelsOf(p),
132
+ approved:
133
+ p.reviewDecision === 'APPROVED' ||
134
+ (p.reviewDecision !== 'CHANGES_REQUESTED' &&
135
+ reviews.includes('APPROVED') &&
136
+ !reviews.includes('CHANGES_REQUESTED')),
137
+ autoMerge: Boolean(p.autoMergeRequest),
138
+ stateComment: stateCommentOf(p, botLogin),
139
+ })
140
+ }
141
+ const compare = repo.toRef?.compare ?? null
142
+ /** @type {Map<number, { number: number, title: string }>} */
143
+ const merged = new Map()
144
+ for (const c of compare?.commits?.nodes ?? [])
145
+ for (const p of c?.associatedPullRequests?.nodes ?? [])
146
+ if (p.baseRefName === from && p.state === 'MERGED' && !merged.has(p.number))
147
+ merged.set(p.number, { number: p.number, title: p.title ?? '' })
148
+ return {
149
+ from,
150
+ to,
151
+ aheadBy: compare ? (compare.aheadBy ?? 0) : null,
152
+ merged: [...merged.values()],
153
+ prs: [...prs.values()],
154
+ }
155
+ }
156
+
59
157
  /**
60
158
  * GraphQL `data` → {@link Snapshot}. Only `agent/*` PRs are kept.
61
159
  *
62
160
  * @param {any} data
63
- * @param {{ botLogin?: string | null }} [opts] when set, only that login's markers count
161
+ * @param {{ botLogin?: string | null, release?: { from: string, to: string } | null }} [opts]
162
+ * `botLogin`: when set, only that login's markers count. `release`: the branches the query asked about.
64
163
  * @returns {Snapshot}
65
164
  */
66
- export function normalize(data, { botLogin = null } = {}) {
165
+ export function normalize(data, { botLogin = null, release = null } = {}) {
67
166
  const repo = (data?.data ?? data)?.repository
68
167
  if (!repo) throw new Error('snapshot: no repository in the answer')
69
168
  /** @type {Map<number, Issue>} */
70
169
  const issues = new Map()
71
170
  const addIssue = (/** @type {any} */ n) => {
72
171
  if (!issues.has(n.number)) {
73
- const comment = (n.comments?.nodes ?? []).find(
74
- (/** @type {any} */ c) => parseMarker(c.body) && (!botLogin || c.author?.login === botLogin),
75
- )
76
172
  issues.set(n.number, {
77
173
  number: n.number,
78
174
  title: n.title ?? '',
@@ -80,10 +176,8 @@ export function normalize(data, { botLogin = null } = {}) {
80
176
  state: n.state,
81
177
  createdAt: n.createdAt,
82
178
  body: n.body ?? '',
83
- labels: (n.labels?.nodes ?? []).map((/** @type {any} */ l) => l.name),
84
- stateComment: comment
85
- ? { id: comment.databaseId, marker: /** @type {any} */ (parseMarker(comment.body)) }
86
- : null,
179
+ labels: labelsOf(n),
180
+ stateComment: stateCommentOf(n, botLogin),
87
181
  })
88
182
  }
89
183
  return n.number
@@ -115,7 +209,7 @@ export function normalize(data, { botLogin = null } = {}) {
115
209
  closes: (p.closingIssuesReferences?.nodes ?? []).map(addIssue),
116
210
  })
117
211
  }
118
- return { issues, prs }
212
+ return { issues, prs, ...(release ? { release: normalizeRelease(repo, release, botLogin) } : {}) }
119
213
  }
120
214
 
121
215
  /**
@@ -159,9 +253,12 @@ export function graftGitHub({ config, exec: run = exec }) {
159
253
  return {
160
254
  async read(slug) {
161
255
  const [owner, name] = slug.split('/')
162
- const vars = JSON.stringify({ owner, name, labels: QUEUE_LABELS })
256
+ const r = config.repos.find((x) => x.slug === slug)?.release
257
+ const release = r?.enabled && r.from !== r.to ? { from: r.from, to: r.to } : null
258
+ const branches = release ?? { from: '', to: '' }
259
+ const vars = JSON.stringify({ owner, name, labels: QUEUE_LABELS, release: Boolean(release), ...branches })
163
260
  const data = await json(graft(slug, ['graphql', SNAPSHOT_QUERY, '--vars', vars]))
164
- return normalize(data, { botLogin: config.graft.botLogin })
261
+ return normalize(data, { botLogin: config.graft.botLogin, release })
165
262
  },
166
263
  async label(slug, number, { add, remove }) {
167
264
  if (!add.length && !remove.length) return
@@ -188,5 +285,21 @@ export function graftGitHub({ config, exec: run = exec }) {
188
285
  async deleteBranch(slug, branch) {
189
286
  await graft(slug, ['api', 'DELETE', `/repos/${slug}/git/refs/heads/${branch}`])
190
287
  },
288
+ async openPull(slug, { head, base, title, body }) {
289
+ const path = `/repos/${slug}/pulls`
290
+ const made = await json(graft(slug, ['api', 'POST', path, '--body', JSON.stringify({ head, base, title, body })]))
291
+ return { number: made.number, url: made.html_url }
292
+ },
293
+ async editPull(slug, number, { title, body }) {
294
+ await graft(slug, ['api', 'PATCH', `/repos/${slug}/pulls/${number}`, '--body', JSON.stringify({ title, body })])
295
+ },
296
+ async closePull(slug, number, comment) {
297
+ await graft(slug, ['issue', 'comment', String(number), '--body-file', '-'], comment)
298
+ await graft(slug, ['api', 'PATCH', `/repos/${slug}/pulls/${number}`, '--body', '{"state":"closed"}'])
299
+ },
300
+ // Through graft's merge policy, as an agent's merge would: auto-merge, or a merge now when the PR is clean.
301
+ async mergePull(slug, number) {
302
+ await graft(slug, ['pr', 'merge', String(number), '--auto'])
303
+ },
191
304
  }
192
305
  }
@@ -16,7 +16,7 @@ import { check, END, GraphNodeError } from './define.mjs'
16
16
  */
17
17
 
18
18
  /** @param {unknown} err @param {string} node @param {'run' | 'poll' | 'edge'} phase */
19
- const asNodeError = (err, node, phase) =>
19
+ export const asNodeError = (err, node, phase) =>
20
20
  err instanceof GraphNodeError
21
21
  ? err
22
22
  : new GraphNodeError(node, phase, String(/** @type {any} */ (err)?.message ?? err), { cause: err })
@@ -94,7 +94,7 @@ export async function advance(graph, at, ctx = {}, opts = {}) {
94
94
  * The first edge out of `from` whose `when` matches `output`; a node with no outgoing edges goes to END.
95
95
  * @param {import('./define.mjs').Graph} graph @param {string} from @param {unknown} output @param {unknown} subject
96
96
  */
97
- function pick(graph, from, output, subject) {
97
+ export function pick(graph, from, output, subject) {
98
98
  let any = false
99
99
  for (const [i, [f, to, when, map]] of graph.edges.entries()) {
100
100
  if (f !== from) continue
@@ -0,0 +1,200 @@
1
+ // @ts-check
2
+ /**
3
+ * `@oakgreencc/cambium/graph/langgraph`: LangGraph interop for cambium graphs.
4
+ *
5
+ * LangGraph is not a dependency of cambium: install `@langchain/langgraph` (and its peer `@langchain/core`)
6
+ * yourself to use this module. Nothing here imports it at load time; {@link toLangGraph} imports it when called,
7
+ * unless you pass the module in as `{ langgraph }`.
8
+ *
9
+ * - Export, {@link toLangGraph}: a cambium graph as an uncompiled `StateGraph` whose state is
10
+ * `{ subject, last, outputs }`. A wait node calls `interrupt({ waiting, input })`; resume it with what its
11
+ * `poll` returned as `output` ({@link pollWait} runs the poll for you).
12
+ * - Import, {@link fromLangGraph}: a compiled LangGraph graph as one cambium step node.
13
+ */
14
+ import { randomUUID } from 'node:crypto'
15
+ import { asNodeError, pick } from './advance.mjs'
16
+ import { check, defineNode, END, GraphNodeError } from './define.mjs'
17
+
18
+ /**
19
+ * @typedef {import('./define.mjs').Graph} Graph
20
+ * @typedef {import('./define.mjs').StandardSchema} StandardSchema
21
+ * @typedef {{ subject: unknown, last: unknown, outputs: Record<string, unknown> }} State
22
+ * `last` is the input of the node about to run: the previous node's output, through its edge's `map`.
23
+ * `outputs` holds each node's latest output, by node name.
24
+ * @typedef {{ waiting: string, input: unknown }} Waiting The value a wait node passes to `interrupt()`.
25
+ * @typedef {typeof import('@langchain/langgraph')} LangGraphModule
26
+ */
27
+
28
+ /** @param {LangGraphModule | undefined} injected @returns {Promise<LangGraphModule>} */
29
+ async function load(injected) {
30
+ if (injected) return injected
31
+ try {
32
+ return await import('@langchain/langgraph')
33
+ } catch (err) {
34
+ throw new Error('toLangGraph needs @langchain/langgraph (and @langchain/core): install them alongside cambium', {
35
+ cause: err,
36
+ })
37
+ }
38
+ }
39
+
40
+ /**
41
+ * The ctx a node gets: LangGraph's run `context` (`invoke(input, { context })`), with the run's `signal`.
42
+ * @param {any} config @returns {Record<string, unknown>}
43
+ */
44
+ const ctxOf = (config) => {
45
+ const ctx = config?.context ?? {}
46
+ return { ...ctx, signal: config?.signal ?? ctx.signal }
47
+ }
48
+
49
+ /**
50
+ * `graph` as an uncompiled LangGraph `StateGraph`. Compile it with a checkpointer when the graph has waits.
51
+ *
52
+ * - State: `{ subject, last, outputs }`. Start a run with `{ subject, last: <entry input> }`; `subject` is what
53
+ * edge `when`/`map` see (cambium's advance passes `ctx.subject`), so it is checkpointed and must be serializable.
54
+ * - Nodes get `{ ...context, signal }` as ctx, where `context` is the run's `invoke(…, { context })`.
55
+ * - A step node validates `last`, runs, validates its output, picks its edge as advance does, and writes
56
+ * `outputs[name]` and `last` (the chosen edge's `map` is applied here: a LangGraph router cannot write state).
57
+ * - A wait node validates `last` and calls `interrupt({ waiting: name, input })`; the resume value is the
58
+ * ready poll's `output`, validated against the wait's output schema. Not-ready polls never reach LangGraph:
59
+ * poll outside ({@link pollWait}) and resume only when ready.
60
+ * - Edges: `addConditionalEdges(from, router)`, the router trying `when` in order on `outputs[from]`; a node with
61
+ * no outgoing edges goes to LangGraph's END. Errors are thrown as cambium's `GraphNodeError`.
62
+ *
63
+ * @param {Graph} graph
64
+ * @param {{ langgraph?: LangGraphModule }} [opts] the `@langchain/langgraph` module, instead of importing it
65
+ */
66
+ export async function toLangGraph(graph, opts = {}) {
67
+ const lg = await load(opts.langgraph)
68
+ const { Annotation, StateGraph, START, interrupt } = lg
69
+ const LG_END = lg.END
70
+ const State = Annotation.Root({
71
+ subject: Annotation(),
72
+ last: Annotation(),
73
+ outputs: Annotation({
74
+ reducer: (/** @type {Record<string, unknown>} */ a, /** @type {Record<string, unknown>} */ b) => ({ ...a, ...b }),
75
+ default: () => ({}),
76
+ }),
77
+ })
78
+ const sg = new StateGraph(State)
79
+ const Any = {
80
+ '~standard': { version: 1, vendor: 'cambium', validate: (/** @type {unknown} */ value) => ({ value }) },
81
+ }
82
+
83
+ for (const node of graph.nodes) {
84
+ const { name } = node
85
+ /** @param {unknown} output @param {unknown} subject */
86
+ const settle = (output, subject) => {
87
+ let next
88
+ try {
89
+ ;({ next } = pick(graph, name, output, subject))
90
+ } catch (err) {
91
+ throw asNodeError(err, name, 'edge')
92
+ }
93
+ return { last: next, outputs: { [name]: output } }
94
+ }
95
+ /** @param {State} state @param {any} config */
96
+ const fn =
97
+ node.kind === 'wait'
98
+ ? async (state) => {
99
+ const input = await check(node.input, state.last, name, 'input')
100
+ const resumed = interrupt(/** @type {Waiting} */ ({ waiting: name, input }))
101
+ return settle(await check(node.output, resumed, name, 'output'), state.subject)
102
+ }
103
+ : async (state, config) => {
104
+ const input = await check(node.input, state.last, name, 'input')
105
+ let out
106
+ try {
107
+ out = await node.run(input, ctxOf(config))
108
+ } catch (err) {
109
+ throw asNodeError(err, name, 'run')
110
+ }
111
+ return settle(await check(node.output, out, name, 'output'), state.subject)
112
+ }
113
+ sg.addNode(name, fn, { input: new lg.StateSchema({ subject: Any, last: node.input }) })
114
+ }
115
+
116
+ sg.addEdge(START, /** @type {any} */ (graph.entry.node))
117
+ /** @type {Map<string, import('./define.mjs').Edge[]>} */
118
+ const out = new Map()
119
+ for (const e of graph.edges) out.set(e[0], [...(out.get(e[0]) ?? []), e])
120
+ const target = (/** @type {string} */ to) => (to === END ? LG_END : to)
121
+ for (const node of graph.nodes) {
122
+ const edges = out.get(node.name)
123
+ if (!edges) {
124
+ sg.addEdge(/** @type {any} */ (node.name), LG_END)
125
+ continue
126
+ }
127
+ const ends = [...new Set(edges.map(([, to]) => target(to)))]
128
+ /** @param {State} state */
129
+ const router = (state) => {
130
+ const o = state.outputs[node.name]
131
+ for (const [, to, when] of edges) if (!when || when(o, state.subject)) return target(to)
132
+ throw new GraphNodeError(node.name, 'edge', 'no edge matched the output')
133
+ }
134
+ sg.addConditionalEdges(/** @type {any} */ (node.name), router, /** @type {any} */ (ends))
135
+ }
136
+ return sg
137
+ }
138
+
139
+ /**
140
+ * Poll the wait a LangGraph run is interrupted at: `{ ready: true, output }` means resume with
141
+ * `new Command({ resume: output })`; `{ ready: false }` means leave the thread where it is.
142
+ * @param {Graph} graph @param {Waiting} waiting the interrupt's value @param {Record<string, unknown>} [ctx]
143
+ * @returns {Promise<import('./define.mjs').PollResult>}
144
+ */
145
+ export async function pollWait(graph, waiting, ctx = {}) {
146
+ const node = graph.nodes.find((n) => n.name === waiting?.waiting)
147
+ if (node?.kind !== 'wait') throw new Error(`graph "${graph.name}" has no wait node "${waiting?.waiting}"`)
148
+ const input = await check(node.input, waiting.input, node.name, 'input')
149
+ let polled
150
+ try {
151
+ polled = await node.poll(input, ctx)
152
+ } catch (err) {
153
+ throw asNodeError(err, node.name, 'poll')
154
+ }
155
+ if (typeof polled?.ready !== 'boolean')
156
+ throw new GraphNodeError(node.name, 'poll', 'poll must return { ready: false } or { ready: true, output }')
157
+ return polled
158
+ }
159
+
160
+ /** @param {unknown} err */
161
+ const isInterrupt = (err) =>
162
+ /** @type {any} */ (err)?.name === 'GraphInterrupt' ||
163
+ /** @type {any} */ (err)?.lc_error_code === 'MISSING_CHECKPOINTER'
164
+
165
+ /**
166
+ * A compiled LangGraph graph as one cambium step node: `run` invokes it with the node's validated input as the
167
+ * graph's input state (passing ctx's `signal`), and its final state is validated against `output`.
168
+ *
169
+ * An imported graph cannot wait: an `interrupt()` inside it fails the node with an error saying so (with or
170
+ * without a checkpointer). Its own nodes stay opaque; they are closures over its state.
171
+ *
172
+ * @param {{ invoke: (input: any, config?: any) => Promise<any> }} compiled
173
+ * @param {{ name: string, input: StandardSchema, output: StandardSchema }} def
174
+ */
175
+ export function fromLangGraph(compiled, { name, input, output }) {
176
+ if (typeof compiled?.invoke !== 'function') throw new Error(`fromLangGraph "${name}": expected a compiled graph`)
177
+ const interrupted = () =>
178
+ new Error(
179
+ `imported LangGraph graph "${name}" called interrupt(); cambium runs imported graphs to completion and cannot resume them, so model the wait as a cambium wait node instead`,
180
+ )
181
+ return defineNode({
182
+ name,
183
+ input,
184
+ output,
185
+ run: async (value, ctx) => {
186
+ let result
187
+ try {
188
+ result = await compiled.invoke(value, {
189
+ signal: ctx?.signal,
190
+ configurable: { thread_id: `cambium:${name}:${randomUUID()}` },
191
+ })
192
+ } catch (err) {
193
+ if (isInterrupt(err)) throw interrupted()
194
+ throw err
195
+ }
196
+ if (Array.isArray(result?.__interrupt__) && result.__interrupt__.length) throw interrupted()
197
+ return result
198
+ },
199
+ })
200
+ }
@@ -0,0 +1,438 @@
1
+ // @ts-check
2
+ /**
3
+ * Release as two graphs (`engine: "graph"`), replacing the `phases/release.mjs` stub there. Their subject is the
4
+ * repo's promotion PR, `release.from` → `release.to` (e.g. `develop` → `main`), and the marker (v2) is cambium's
5
+ * state comment on that PR, written through the same path as an issue's (issue-state.mjs).
6
+ *
7
+ * - `release-prepare`: a clock entry, once a day at the repo's `release.time` (`releaseDue`, with the last run in
8
+ * the store). `cleanup` closes, with a comment, every open promotion PR older than 24 h; `prepare` opens the
9
+ * promotion PR (or refreshes the open one) when `from` is ahead of `to`, labels it `q:promote` and exits.
10
+ * - `release-promote`: `q:promote` is its queue. It enters at `merge` once the PR is approved, merges through
11
+ * `graft pr merge --auto` (auto-merge, or a merge now when the PR is clean), waits at `merging`, and exits at
12
+ * `promoted` (merged) or `abandoned` (closed unmerged), taking `q:promote` off.
13
+ *
14
+ * Neither graph has a timeout: the daily cleanup is the only 24 h rule.
15
+ */
16
+ import { z } from 'zod'
17
+ import { advance, defineGraph, defineNode, defineWait, END } from '../graph/index.mjs'
18
+ import { iso, setLabels, setMarker } from '../issue-state.mjs'
19
+ import { move, Q } from '../labels.mjs'
20
+ import { effectivePosition, newMarker, withHistory } from '../marker.mjs'
21
+ import { releaseDue } from '../phases/release.mjs'
22
+
23
+ /**
24
+ * @typedef {import('../github.mjs').PromotionPr} PromotionPr
25
+ * @typedef {import('../github.mjs').Release} Release
26
+ * @typedef {import('../marker.mjs').Marker} Marker
27
+ * @typedef {{ slug: string, repo: import('../config.mjs').Repo, release: Release, pr?: PromotionPr }} ReleaseSubject
28
+ * One repo's turn; `pr` is the promotion PR a `release-promote` turn is about.
29
+ * @typedef {import('../tick.mjs').Deps & { tick: import('../tick.mjs').Ctx, subject: ReleaseSubject }} ReleaseCtx
30
+ * @typedef {{ queue: string | null, enter?: (input: any, ctx: ReleaseCtx) => Promise<void> }} Declared
31
+ * `queue`: the label a PR resting here carries. `enter`: the write that lands a PR on this wait.
32
+ */
33
+
34
+ const DAY = 24 * 60 * 60 * 1000
35
+
36
+ /**
37
+ * @template {import('../graph/define.mjs').GraphNode} N @param {N} node @param {Declared} decl
38
+ * @returns {N & Declared}
39
+ */
40
+ const declare = (node, decl) => Object.freeze({ ...node, ...decl })
41
+
42
+ /** @param {ReleaseCtx} ctx */
43
+ function prOf(ctx) {
44
+ const { pr } = ctx.subject
45
+ if (!pr) throw new Error(`${ctx.subject.slug}: no promotion PR in this turn`)
46
+ return pr
47
+ }
48
+
49
+ /** @param {ReleaseCtx} ctx @param {number} pr */
50
+ const where = (ctx, pr) => ({ repo: ctx.subject.slug, issue: pr })
51
+
52
+ /** A PR's marker, or a fresh one for a release graph. @param {PromotionPr} pr @param {string} graph @param {string} node */
53
+ const markerOn = (pr, graph, node) =>
54
+ pr.stateComment?.marker ?? newMarker({ graph, node, phase: 'release', pr: pr.number })
55
+
56
+ /** Release markers carry none of the stage tick's fields. @param {Marker} m */
57
+ const releaseMarker = (m) =>
58
+ /** @type {Marker} */ (Object.fromEntries(Object.entries(m).filter(([k]) => k !== 'stage')))
59
+
60
+ /**
61
+ * Put `pr` at `node` of `graph`: the marker first, then the labels `node` declares, via `move()`.
62
+ * @param {ReleaseCtx} ctx @param {PromotionPr} pr @param {import('../graph/define.mjs').Graph} graph @param {string} node
63
+ * @param {Marker} marker @param {{ status?: Marker['status'] }} [opts]
64
+ */
65
+ async function land(ctx, pr, graph, node, marker, { status = 'waiting' } = {}) {
66
+ const { slug } = ctx.subject
67
+ const decl = /** @type {Declared} */ (/** @type {unknown} */ (graph.nodes.find((n) => n.name === node)))
68
+ // The PR's state comment is an issue comment: setMarker / setLabels take the PR as the issue.
69
+ const issue = /** @type {import('../github.mjs').Issue} */ (/** @type {unknown} */ (pr))
70
+ await setMarker(ctx, slug, issue, {
71
+ ...releaseMarker(marker),
72
+ graph: graph.name,
73
+ graphVersion: graph.version,
74
+ node,
75
+ status,
76
+ pr: pr.number,
77
+ enteredAt: iso(ctx.tick.now),
78
+ })
79
+ await setLabels(ctx, slug, issue, move(pr.labels, decl.queue))
80
+ }
81
+
82
+ /** Open, and from `from` to `to` or carrying a release marker. @param {Release} r @param {PromotionPr} pr */
83
+ const isPromotion = (r, pr) =>
84
+ (pr.head === r.from && pr.base === r.to) || Boolean(pr.stateComment?.marker.graph.startsWith('release-'))
85
+
86
+ /** The promotion PR's body: what `to` gets. @param {Release} r */
87
+ export function promotionBody(r) {
88
+ const lines = [
89
+ `Promotes \`${r.from}\` → \`${r.to}\`: ${r.aheadBy} commit${r.aheadBy === 1 ? '' : 's'} ahead.`,
90
+ '',
91
+ r.merged.length ? `Merged into \`${r.from}\` since \`${r.to}\`:` : `No merged PRs found in the commits ahead.`,
92
+ ...r.merged.map((p) => `- #${p.number} ${p.title}`),
93
+ '',
94
+ '_Opened by cambium (release-prepare). Approve it and cambium merges it (release-promote); ' +
95
+ 'an unmerged promotion PR is closed after 24 h._',
96
+ ]
97
+ return lines.join('\n')
98
+ }
99
+
100
+ // ---- release-prepare
101
+
102
+ const Empty = z.object({})
103
+ const Closed = z.object({ closed: z.array(z.number().int()) })
104
+
105
+ const cleanup = declare(
106
+ defineNode({
107
+ name: 'cleanup',
108
+ input: Empty,
109
+ output: Closed,
110
+ /** Close every open promotion PR older than 24 h, with a comment. @param {{}} _ @param {ReleaseCtx} ctx */
111
+ run: async (_, ctx) => {
112
+ const { slug, release: r } = ctx.subject
113
+ /** @type {number[]} */
114
+ const closed = []
115
+ for (const pr of r.prs) {
116
+ if (pr.state !== 'OPEN' || !isPromotion(r, pr)) continue
117
+ if (ctx.tick.now - Date.parse(pr.createdAt) <= DAY) continue
118
+ const age = Math.floor((ctx.tick.now - Date.parse(pr.createdAt)) / (60 * 60 * 1000))
119
+ const reason = `not merged within 24 h (opened ${age} h ago); a fresh promotion PR replaces it`
120
+ if (pr.stateComment) {
121
+ const m = pr.stateComment.marker
122
+ await land(
123
+ ctx,
124
+ pr,
125
+ releasePrepare,
126
+ 'cleanup',
127
+ withHistory(m, { at: iso(ctx.tick.now), attempt: m.attempt, outcome: 'stale-closed', reason }),
128
+ { status: 'done' },
129
+ )
130
+ } else if (pr.labels.includes(Q.promote))
131
+ await setLabels(ctx, slug, /** @type {any} */ (pr), move(pr.labels, null))
132
+ await ctx.github.closePull(slug, pr.number, `Closed by cambium: ${reason}.`)
133
+ pr.state = 'CLOSED'
134
+ closed.push(pr.number)
135
+ ctx.log('info', `release: closed stale promotion PR #${pr.number}`, where(ctx, pr.number))
136
+ }
137
+ return { closed }
138
+ },
139
+ }),
140
+ { queue: null },
141
+ )
142
+
143
+ const prepare = declare(
144
+ defineNode({
145
+ name: 'prepare',
146
+ input: Closed,
147
+ output: z.discriminatedUnion('to', [
148
+ z.object({ to: z.literal('opened'), pr: z.number().int() }),
149
+ z.object({ to: z.literal('updated'), pr: z.number().int() }),
150
+ z.object({ to: z.literal('nothing'), reason: z.string() }),
151
+ ]),
152
+ /**
153
+ * `from` ahead of `to`: open the promotion PR (or refresh the open one), label it `q:promote`, write the
154
+ * marker. Nothing ahead: a log line.
155
+ * @param {z.infer<typeof Closed>} _ @param {ReleaseCtx} ctx
156
+ */
157
+ run: async (_, ctx) => {
158
+ const { slug, release: r } = ctx.subject
159
+ if (!r.aheadBy) {
160
+ const reason =
161
+ r.aheadBy === null
162
+ ? `\`${r.to}\` not found; nothing to promote`
163
+ : `\`${r.from}\` is not ahead of \`${r.to}\`; nothing to promote`
164
+ ctx.log('info', `release: ${reason}`, { repo: slug })
165
+ return { to: 'nothing', reason }
166
+ }
167
+ const title = `Promote ${r.from} → ${r.to}`
168
+ const body = promotionBody(r)
169
+ const at = iso(ctx.tick.now)
170
+ const open = r.prs.find((p) => p.state === 'OPEN' && p.head === r.from && p.base === r.to)
171
+ if (open) {
172
+ await ctx.github.editPull(slug, open.number, { title, body })
173
+ const m = markerOn(open, releasePrepare.name, 'prepare')
174
+ const entry = { at, attempt: m.attempt, outcome: 'updated', pr: open.number }
175
+ // Already in release-promote (approved, merging): keep its position, record the refresh.
176
+ if (m.graph === releasePromote.name && m.status !== 'done') {
177
+ await setMarker(ctx, slug, /** @type {any} */ (open), withHistory(m, entry))
178
+ await setLabels(ctx, slug, /** @type {any} */ (open), move(open.labels, Q.promote))
179
+ } else await land(ctx, open, releasePrepare, 'prepare', withHistory(m, entry), { status: 'done' })
180
+ ctx.log('info', `release: refreshed promotion PR #${open.number}`, where(ctx, open.number))
181
+ return { to: 'updated', pr: open.number }
182
+ }
183
+ const made = await ctx.github.openPull(slug, { head: r.from, base: r.to, title, body })
184
+ /** @type {PromotionPr} */
185
+ const pr = {
186
+ number: made.number,
187
+ url: made.url,
188
+ title,
189
+ state: 'OPEN',
190
+ createdAt: at,
191
+ head: r.from,
192
+ base: r.to,
193
+ headSha: null,
194
+ labels: [],
195
+ approved: false,
196
+ autoMerge: false,
197
+ stateComment: null,
198
+ }
199
+ r.prs.push(pr)
200
+ const m = markerOn(pr, releasePrepare.name, 'prepare')
201
+ await land(
202
+ ctx,
203
+ pr,
204
+ releasePrepare,
205
+ 'prepare',
206
+ withHistory(m, { at, attempt: m.attempt, outcome: 'opened', pr: pr.number }),
207
+ { status: 'done' },
208
+ )
209
+ ctx.log('info', `release: opened promotion PR #${pr.number} (${r.from} → ${r.to})`, where(ctx, pr.number))
210
+ return { to: 'opened', pr: pr.number }
211
+ },
212
+ }),
213
+ // The PR it opens waits in `q:promote`, release-promote's queue.
214
+ { queue: Q.promote },
215
+ )
216
+
217
+ /** Bump `version` when a node is removed or renamed. */
218
+ export const releasePrepare = defineGraph({
219
+ name: 'release-prepare',
220
+ version: 1,
221
+ entry: { node: 'cleanup', input: () => ({}) },
222
+ nodes: [cleanup, prepare],
223
+ edges: [
224
+ ['cleanup', 'prepare'],
225
+ ['prepare', END],
226
+ ],
227
+ })
228
+
229
+ // ---- release-promote
230
+
231
+ const PrIn = z.object({ pr: z.number().int() })
232
+
233
+ const armed = (/** @type {{ to: string }} */ o) => o.to === 'armed'
234
+ const merged = (/** @type {{ to: string }} */ o) => o.to === 'merged'
235
+
236
+ const merge = declare(
237
+ defineNode({
238
+ name: 'merge',
239
+ input: PrIn,
240
+ output: z.discriminatedUnion('to', [
241
+ z.object({ to: z.literal('armed'), pr: z.number().int() }),
242
+ z.object({ to: z.literal('refused'), reason: z.string() }),
243
+ ]),
244
+ /**
245
+ * The PR is approved: merge it through `graft pr merge --auto`. A refusal stays here, recorded with the head
246
+ * it was refused on; the gate does not retry that head.
247
+ * @param {z.infer<typeof PrIn>} input @param {ReleaseCtx} ctx
248
+ */
249
+ run: async (input, ctx) => {
250
+ const pr = prOf(ctx)
251
+ // TRACING (follow-up): a span per merge attempt here, parented on the PR marker's traceparent.
252
+ try {
253
+ await ctx.github.mergePull(ctx.subject.slug, input.pr)
254
+ } catch (err) {
255
+ const reason = `merge refused: ${/** @type {Error} */ (err)?.message ?? err}`
256
+ const m = markerOn(pr, releasePromote.name, 'merge')
257
+ await land(ctx, pr, releasePromote, 'merge', {
258
+ ...withHistory(m, { at: iso(ctx.tick.now), attempt: m.attempt, outcome: 'merge-refused', reason }),
259
+ lastFailure: reason,
260
+ failedSha: pr.headSha,
261
+ input: { pr: input.pr },
262
+ })
263
+ ctx.log('warn', `release: ${reason.split('\n')[0]}`, where(ctx, input.pr))
264
+ return { to: 'refused', reason }
265
+ }
266
+ return { to: 'armed', pr: input.pr }
267
+ },
268
+ }),
269
+ { queue: Q.promote },
270
+ )
271
+
272
+ const merging = declare(
273
+ defineWait({
274
+ name: 'merging',
275
+ input: PrIn,
276
+ output: z.object({ to: z.enum(['merged', 'closed']), pr: z.number().int() }),
277
+ /** Merged or closed unmerged; open: hold (no timeout). @param {z.infer<typeof PrIn>} input @param {ReleaseCtx} ctx */
278
+ poll: async (input, ctx) => {
279
+ const { state } = prOf(ctx)
280
+ if (state === 'MERGED') return { ready: true, output: { to: 'merged', pr: input.pr } }
281
+ if (state === 'CLOSED') return { ready: true, output: { to: 'closed', pr: input.pr } }
282
+ return { ready: false }
283
+ },
284
+ }),
285
+ {
286
+ queue: Q.promote,
287
+ /** @param {{ pr: number }} input @param {ReleaseCtx} ctx */
288
+ enter: async (input, ctx) => {
289
+ const pr = prOf(ctx)
290
+ const m = markerOn(pr, releasePromote.name, 'merging')
291
+ await land(ctx, pr, releasePromote, 'merging', {
292
+ ...withHistory(m, { at: iso(ctx.tick.now), attempt: m.attempt, outcome: 'merge-armed', pr: input.pr }),
293
+ lastFailure: null,
294
+ input: { pr: input.pr },
295
+ })
296
+ ctx.log('info', `release: merging promotion PR #${input.pr}`, where(ctx, input.pr))
297
+ },
298
+ },
299
+ )
300
+
301
+ /** @param {'promoted' | 'abandoned'} name @param {string} outcome @param {string} said */
302
+ const exit = (name, outcome, said) =>
303
+ declare(
304
+ defineNode({
305
+ name,
306
+ input: PrIn,
307
+ output: Empty,
308
+ /** @param {z.infer<typeof PrIn>} input @param {ReleaseCtx} ctx */
309
+ run: async (input, ctx) => {
310
+ const pr = prOf(ctx)
311
+ const m = markerOn(pr, releasePromote.name, name)
312
+ await land(
313
+ ctx,
314
+ pr,
315
+ releasePromote,
316
+ name,
317
+ { ...withHistory(m, { at: iso(ctx.tick.now), attempt: m.attempt, outcome, pr: input.pr }), input: null },
318
+ { status: 'done' },
319
+ )
320
+ ctx.log('info', `release: promotion PR #${input.pr} ${said}`, where(ctx, input.pr))
321
+ return {}
322
+ },
323
+ }),
324
+ { queue: null },
325
+ )
326
+
327
+ /** Bump `version` when a node is removed or renamed. */
328
+ export const releasePromote = defineGraph({
329
+ name: 'release-promote',
330
+ version: 1,
331
+ entry: { queue: Q.promote, node: 'merge' },
332
+ nodes: [
333
+ merge,
334
+ merging,
335
+ exit('promoted', 'merged', 'merged'),
336
+ exit('abandoned', 'closed-unmerged', 'closed without merging'),
337
+ ],
338
+ edges: [
339
+ ['merge', 'merging', armed],
340
+ ['merge', END],
341
+ ['merging', 'promoted', merged],
342
+ ['merging', 'abandoned'],
343
+ ['promoted', END],
344
+ ['abandoned', END],
345
+ ],
346
+ })
347
+
348
+ /** `q:promote` belongs to release-promote. */
349
+ export const RELEASE_QUEUES = {
350
+ [Q.promote]: {
351
+ graph: releasePromote.name,
352
+ entryNode: releasePromote.entry.node,
353
+ nodes: releasePromote.nodes.map((n) => n.name),
354
+ },
355
+ }
356
+
357
+ // ---- Driving them (the tick's Release step)
358
+
359
+ /**
360
+ * Advance `graph` from `at`, one transition at a time, writing a wait's `enter` when an edge lands on it. Stops
361
+ * at END, at a wait that is not ready, or on entering a wait (polled next tick). A node error is rethrown.
362
+ *
363
+ * @param {import('../graph/define.mjs').Graph} graph @param {ReleaseCtx} ctx
364
+ * @param {{ node: string, input: unknown }} at
365
+ */
366
+ async function drive(graph, ctx, at) {
367
+ let pos = at
368
+ for (;;) {
369
+ // TRACING (follow-up): pass tracing.mjs `advanceHooks` as `instrument` here, as the task graph will.
370
+ const r = await advance(graph, pos, ctx, { maxTransitions: 1 })
371
+ if (r.error) throw r.error.cause instanceof Error ? r.error.cause : r.error
372
+ const t = r.transitions[0]
373
+ const next = /** @type {(import('../graph/define.mjs').GraphNode & Declared) | undefined} */ (
374
+ graph.nodes.find((n) => n.name === r.node)
375
+ )
376
+ if (t && t.to !== END) await next?.enter?.(t.next, ctx)
377
+ if (r.reason !== 'limit' || next?.kind === 'wait') return
378
+ pos = { node: r.node, input: r.input }
379
+ }
380
+ }
381
+
382
+ /**
383
+ * Where a `q:promote` PR's turn starts, or null for none. Merged or closed: `merging`, which exits. Open: the
384
+ * marker's `merging`, else the entry once the PR is approved, unless a merge was already refused on this head.
385
+ * @param {PromotionPr} pr @returns {{ node: string, input: { pr: number } } | null}
386
+ */
387
+ export function promoteStart(pr) {
388
+ if (!pr.labels.includes(Q.promote)) return null
389
+ const marker = pr.stateComment?.marker ?? null
390
+ const input = { pr: pr.number }
391
+ if (pr.state !== 'OPEN') return { node: 'merging', input }
392
+ const pos = effectivePosition(pr.labels, marker, RELEASE_QUEUES)
393
+ if (pos?.node === 'merging' && !pos.reset) return { node: 'merging', input }
394
+ if (!pr.approved) return null
395
+ const refusedHere = !pos?.reset && pos?.node === 'merge' && marker?.lastFailure && marker.failedSha === pr.headSha
396
+ return refusedHere ? null : { node: releasePromote.entry.node, input }
397
+ }
398
+
399
+ /** The store key for a repo's last release-prepare run. @param {string} slug */
400
+ export const lastRunKey = (slug) => `release.lastRun:${slug}`
401
+
402
+ /**
403
+ * The tick's Release step on `engine: "graph"`, per repo with `release` on (and `from` ≠ `to`): release-prepare
404
+ * when it is due, then a release-promote turn for each `q:promote` PR. One repo's failure is logged; the rest
405
+ * still run.
406
+ *
407
+ * @param {import('../tick.mjs').Deps} deps @param {import('../tick.mjs').Ctx} tick
408
+ */
409
+ export async function releaseGraphs(deps, tick) {
410
+ for (const repo of deps.config.repos) {
411
+ const { enabled, time, from, to } = repo.release
412
+ const release = tick.snaps.get(repo.slug)?.release
413
+ if (!enabled || from === to || !release) continue
414
+ /** @param {PromotionPr} [pr] @returns {ReleaseCtx} */
415
+ const ctxFor = (pr) => ({ ...deps, tick, subject: { slug: repo.slug, repo, release, pr } })
416
+ try {
417
+ const last = deps.store.get(lastRunKey(repo.slug))
418
+ if (releaseDue(tick.now, last === null ? null : Number(last), time)) {
419
+ deps.store.set(lastRunKey(repo.slug), String(tick.now))
420
+ await drive(releasePrepare, ctxFor(), { node: releasePrepare.entry.node, input: {} })
421
+ }
422
+ } catch (err) {
423
+ deps.log('error', `release-prepare: ${/** @type {Error} */ (err)?.message ?? err}`, { repo: repo.slug })
424
+ }
425
+ for (const pr of [...release.prs]) {
426
+ const at = promoteStart(pr)
427
+ if (!at) continue
428
+ try {
429
+ await drive(releasePromote, ctxFor(pr), at)
430
+ } catch (err) {
431
+ deps.log('error', `release-promote: ${/** @type {Error} */ (err)?.message ?? err}`, {
432
+ repo: repo.slug,
433
+ issue: pr.number,
434
+ })
435
+ }
436
+ }
437
+ }
438
+ }
package/src/marker.mjs CHANGED
@@ -31,7 +31,7 @@
31
31
  * traceparent: string | null,
32
32
  * enteredAt: string | null,
33
33
  * history: HistoryEntry[],
34
- * phase: 'task' | 'dispatch',
34
+ * phase: 'task' | 'dispatch' | 'release',
35
35
  * stage?: Stage,
36
36
  * pr: number | null,
37
37
  * branch: string | null,
@@ -1,4 +1,5 @@
1
1
  // @ts-check
2
+ /** The legacy engine's Release seam. `engine: "graph"` runs graphs/release.mjs instead; `releaseDue` serves both. */
2
3
  /** @typedef {(input: { repo: import('../config.mjs').Repo, now: number }) => Promise<{ done: boolean, note: string }>} Release */
3
4
 
4
5
  /** @param {number} now @param {number | null} lastRun @param {string} time host-local HH:MM */
package/src/tick.mjs CHANGED
@@ -14,6 +14,7 @@ import { prFor, taskExit, taskPrompt } from './phases/task.mjs'
14
14
  import { branchName } from './convention.mjs'
15
15
  import { PREPARE_FAILED_LINE } from './prepare.mjs'
16
16
  import { releaseDue, releaseNotBuilt } from './phases/release.mjs'
17
+ import { releaseGraphs } from './graphs/release.mjs'
17
18
  import { DISPATCH_NOT_BUILT, dispatchNotBuilt } from './phases/dispatch.mjs'
18
19
 
19
20
  /**
@@ -560,10 +561,12 @@ export async function startTask(deps, ctx, slug, issue, snap, { foreground = fal
560
561
  return { ...started, attempt: marker.attempt }
561
562
  }
562
563
 
563
- // ---- Release (once a day, no agent): schedule is real, the run is a seam.
564
+ // ---- Release (no agent). Legacy: once a day, the run is a seam. Graph: the release-prepare / release-promote
565
+ // graphs (graphs/release.mjs), per repo.
564
566
 
565
567
  /** @param {Deps} deps @param {Ctx} ctx */
566
568
  async function release(deps, ctx) {
569
+ if (deps.config.engine === 'graph') return releaseGraphs(deps, ctx)
567
570
  const { config, store } = deps
568
571
  if (!config.release.enabled) return
569
572
  const last = store.get('release.lastRun')