@oakgreencc/cambium 0.0.45 → 0.0.47

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
@@ -28,7 +28,7 @@ cambium status
28
28
  | `cambium resume` | Back to `running`. |
29
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
30
  | `cambium run <task\|pr\|dispatch> --issue <n> [--repo <owner/name>] [--follow]` | `engine: "graph"` only. `task`: 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. `pr`: the [PR graph](#the-pr-graph) for the issue's PR. `dispatch`: triage one `q:intake` issue with a foreground triage worker (the dispatch cap does not apply), read its verdict and end the [dispatch graph](#the-dispatch-graph); a tracked triage worker resumes at `triaging`. Stops at the first wait that is not ready; `--follow` re-reads and polls every `tickSeconds` until the graph ends. |
31
- | `cambium run release-prepare [--repo <owner/name>]` | `engine: "graph"` only. Run [release-prepare](#the-release-graphs) now, whatever `release.time`: close stale promotion PRs, open or refresh the promotion PR. Counts as the day's run. |
31
+ | `cambium run release-prepare [--repo <owner/name>]` | `engine: "graph"` only. Run [release-prepare](#the-release-graphs) now, whatever `release.time`: close stale promotion PRs, cut `release/<date>-N` at the newest green commit on `release.from` and open its PR. Counts as the day's run. |
32
32
  | `cambium run release-promote [--repo <owner/name>] [--issue <pr>]` | `engine: "graph"` only. A [release-promote](#the-release-graphs) turn for each `q:promote` promotion PR (or only `<pr>`): merge an approved one, close out a merged or closed one; report the rest as not ready. |
33
33
  | `cambium run rescue [--repo <owner/name>] [--issue <n>]` | `engine: "graph"` only. Without `--issue`: list the items the [rescue](#the-rescue-graph) sweep would find stuck now, with their symptoms (the cooldown aside); changes nothing. With it: rescue that item now with a foreground rescue worker, then carry out its verdict. |
34
34
  | `cambium gc [--dry-run] [--repo <owner/name>]` | Collect worktrees now; `--dry-run` only reports. See [Worktree GC](#worktree-gc). |
@@ -168,7 +168,7 @@ One JSON file. Everything but `repos` is optional; these are the defaults:
168
168
  - `phases.rescue.cap` (`engine: "graph"`; 0, the default, turns it off) and `rescue`: see [The rescue graph](#the-rescue-graph).
169
169
  - Setting `paths.home` moves every default path under it.
170
170
  - `release.time` is host-local `HH:MM`.
171
- - `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" } }`.
171
+ - `repos[].release` (`engine: "graph"`): `{ "enabled", "time", "from", "to", "check" }`. `enabled` and `time` default to the top-level `release`, `from` to the repo's `baseBranch`, `to` to `"main"`, `check` to the repo's `requiredCheck` (`null`: cut at the tip). 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" } }`.
172
172
 
173
173
  ### Target repo convention
174
174
 
@@ -492,7 +492,14 @@ flowchart TD
492
492
 
493
493
  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.
494
494
 
495
- `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>`).
495
+ `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>`), or by hand with `cambium run release-prepare`.
496
+
497
+ A promotion PR whose head is `from` itself changes under its reviewer: whatever merges while they read is in the merge. So `prepare` promotes a frozen cut:
498
+
499
+ - **Cut:** the newest commit on `from`'s first-parent line (50 back at most) whose `release.check` concluded green. A newer red or pending commit does not block an older green one.
500
+ - **Content:** `to` must hold nothing the cut lacks: an ancestor, or diverged only by empty merge commits (the last promotion's, which nothing merges back). Otherwise nothing opens and a warning is logged: merge `to` into `from` first.
501
+ - **Branch:** `release/YYYY-MM-DD-N` at the cut (host-local date), `N` one past the highest that day. Nobody pushes to it: a fix found in review lands on `from`, and the next run cuts again. The App needs to be allowed to create `release/**` branches.
502
+ - **Supersede:** an open promotion of the same cut is refreshed. One of an older cut (or with `from` itself as head) is closed with "Superseded by #N", after the new PR opens.
496
503
 
497
504
  ```mermaid
498
505
  flowchart TD
@@ -526,14 +533,14 @@ flowchart TD
526
533
 
527
534
  Generated by `toMermaid`; a test keeps these copies current.
528
535
 
529
- | Node | Graph | Kind | What it does |
530
- | ----------- | --------------- | ---- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
531
- | `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. |
532
- | `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. |
533
- | `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. |
534
- | `merging` | release-promote | wait | Holds while the PR is open. |
535
- | `promoted` | release-promote | step | Merged: marker done, `q:promote` off. |
536
- | `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. |
536
+ | Node | Graph | Kind | What it does |
537
+ | ----------- | --------------- | ---- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
538
+ | `cleanup` | release-prepare | step | Closes, with a comment, every open promotion PR (`from` or `release/*` → `to`, or carrying a release marker) older than 24 h; takes `q:promote` off. |
539
+ | `prepare` | release-prepare | step | `from` ahead of `to`: cuts `release/<date>-N` at the newest green commit, opens its PR listing the PRs it carries, labels it `q:promote`, writes the marker, closes the promotion it supersedes. Same cut open: refreshes it. Nothing to cut: a log line. |
540
+ | `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. |
541
+ | `merging` | release-promote | wait | Holds while the PR is open. |
542
+ | `promoted` | release-promote | step | Merged: marker done, `q:promote` off. |
543
+ | `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. |
537
544
 
538
545
  ### Awaiting promotion
539
546
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oakgreencc/cambium",
3
- "version": "0.0.45",
3
+ "version": "0.0.47",
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",
package/src/config.mjs CHANGED
@@ -8,10 +8,11 @@ import { homedir, hostname } from 'node:os'
8
8
  import { join, resolve } from 'node:path'
9
9
 
10
10
  /**
11
- * @typedef {{ enabled: boolean, time: string, from: string, to: string }} RepoRelease
11
+ * @typedef {{ enabled: boolean, time: string, from: string, to: string, check: string | null }} RepoRelease
12
12
  * The promotion PR (`engine: "graph"`): `from` (default: the repo's `baseBranch`) is promoted into `to`
13
13
  * (default `main`) once a day at `time`. `enabled`/`time` default to the top-level `release`. Off when
14
- * `from === to`.
14
+ * `from === to`. `check` (default: the repo's `requiredCheck`): the check that must be green on the `from`
15
+ * commit a release is cut at; `null` cuts at the tip.
15
16
  * @typedef {'none' | 'green'} MergePolicy
16
17
  * Who merges a Task PR. `none`: not cambium (a merge queue, auto-merge, or a human; past `mergeQueueMinutes`
17
18
  * the issue goes to `q:human`). `green`: cambium, once its checks are green, through `graft pr merge --auto`
@@ -151,21 +152,24 @@ export function resolveConfig(raw = {}) {
151
152
  throw new Error(`config: repo slug must be owner/name, got ${r?.slug}`)
152
153
  if (!r.path) throw new Error(`config: repo ${r.slug} needs "path" (a local clone)`)
153
154
  const baseBranch = r.baseBranch ?? 'main'
155
+ const requiredCheck = r.requiredCheck === undefined ? 'ci' : r.requiredCheck
156
+ if (requiredCheck !== null && (typeof requiredCheck !== 'string' || !requiredCheck))
157
+ throw new Error(`config: repo ${r.slug} requiredCheck must be a check name or null`)
154
158
  /** @type {RepoRelease} */
155
159
  const release = {
156
160
  enabled: config.release.enabled,
157
161
  time: config.release.time,
158
162
  from: baseBranch,
159
163
  to: 'main',
164
+ check: requiredCheck,
160
165
  ...r.release,
161
166
  }
162
167
  if (!/^\d{2}:\d{2}$/.test(release.time)) throw new Error(`config: repo ${r.slug} release.time must be HH:MM`)
168
+ if (release.check !== null && (typeof release.check !== 'string' || !release.check))
169
+ throw new Error(`config: repo ${r.slug} release.check must be a check name or null`)
163
170
  const merge = r.merge ?? config.merge
164
171
  if (!MERGE_POLICIES.includes(merge))
165
172
  throw new Error(`config: repo ${r.slug} merge must be "none" or "green", got ${JSON.stringify(merge)}`)
166
- const requiredCheck = r.requiredCheck === undefined ? 'ci' : r.requiredCheck
167
- if (requiredCheck !== null && (typeof requiredCheck !== 'string' || !requiredCheck))
168
- throw new Error(`config: repo ${r.slug} requiredCheck must be a check name or null`)
169
173
  return { slug: r.slug, path: untilde(r.path), baseBranch, release, merge, requiredCheck }
170
174
  })
171
175
  if (!MERGE_POLICIES.includes(config.merge))
package/src/github.mjs CHANGED
@@ -52,6 +52,13 @@ import { BASE_FIELDS, baseHealthOf } from './base-health.mjs'
52
52
  * issues: Map<number, Issue>, prs: PullRequest[], release?: Release | null,
53
53
  * base?: import('./base-health.mjs').BaseHealth,
54
54
  * }} Snapshot
55
+ * @typedef {{ sha: string, behind: number, url: string | null }} GreenCommit
56
+ * `behind`: how many first-parent commits the ref's tip is past it. `url`: the green run.
57
+ * @typedef {{
58
+ * status: 'ahead' | 'behind' | 'identical' | 'diverged', aheadBy: number, behindBy: number, files: number,
59
+ * commits: { sha: string, parents: string[], message: string }[],
60
+ * }} Range
61
+ * `files`: how many files differ between the merge base and `head`. `commits`: oldest first, at most 250.
55
62
  * `base`: the base branch's health, when the repo has a `requiredCheck`.
56
63
  * @typedef {{
57
64
  * read(slug: string): Promise<Snapshot>,
@@ -64,6 +71,10 @@ import { BASE_FIELDS, baseHealthOf } from './base-health.mjs'
64
71
  * openPull(slug: string, pr: { head: string, base: string, title: string, body: string }): Promise<{ number: number, url: string }>,
65
72
  * editPull(slug: string, number: number, change: { title: string, body: string }): Promise<void>,
66
73
  * closePull(slug: string, number: number, comment: string): Promise<void>,
74
+ * greenCommit(slug: string, ref: string, check: string | null, depth: number): Promise<GreenCommit | null>,
75
+ * compareRange(slug: string, base: string, head: string): Promise<Range>,
76
+ * branches(slug: string, prefix: string): Promise<string[]>,
77
+ * createBranch(slug: string, name: string, sha: string): Promise<void>,
67
78
  * mergePull(slug: string, number: number): Promise<void>,
68
79
  * behindBase(slug: string, number: number): Promise<{ behind: number, base: string }>,
69
80
  * updatePull(slug: string, number: number): Promise<void>,
@@ -72,6 +83,9 @@ import { BASE_FIELDS, baseHealthOf } from './base-health.mjs'
72
83
  * closedPulls(slug: string): Promise<PullRequest[]>,
73
84
  * readIssues(slug: string, numbers: number[]): Promise<Map<number, Issue>>,
74
85
  * }} GitHub
86
+ * `greenCommit`: the newest commit on `ref`'s first-parent line, at most `depth` back, whose `check` concluded
87
+ * success (`check` null: the tip). `compareRange`: GitHub's compare of `base...head`. `branches`: the branch
88
+ * names starting with `prefix`. `createBranch`: a new branch at `sha`.
75
89
  * `behindBase`: how many commits of its base the PR's head lacks, read live (not from the tick's snapshot), so a
76
90
  * merge earlier in the same tick counts. `updatePull`: merge the base into the PR (`graft pr update`).
77
91
  * `linkIssue`: put `Closes #<issue>` at the top of the PR's body, so the PR names the issue it closes.
@@ -480,6 +494,46 @@ export function graftGitHub({ config, exec: run = exec }) {
480
494
  const made = await json(graft(slug, ['api', 'POST', path, '--body', JSON.stringify({ head, base, title, body })]))
481
495
  return { number: made.number, url: made.html_url }
482
496
  },
497
+ async greenCommit(slug, ref, check, depth) {
498
+ let commit = await json(graft(slug, ['api', 'GET', `/repos/${slug}/commits/${encodeURIComponent(ref)}`]))
499
+ for (let behind = 0; commit && behind < depth; behind++) {
500
+ if (!check) return { sha: commit.sha, behind, url: null }
501
+ const path = `/repos/${slug}/commits/${commit.sha}/check-runs?check_name=${encodeURIComponent(check)}&per_page=100`
502
+ const runs = (await json(graft(slug, ['api', 'GET', path]))).check_runs ?? []
503
+ const newest = runs
504
+ .filter((/** @type {any} */ r) => r.name === check)
505
+ .reduce((/** @type {any} */ a, /** @type {any} */ r) => (a && a.id >= r.id ? a : r), null)
506
+ if (newest?.status === 'completed' && newest.conclusion === 'success')
507
+ return { sha: commit.sha, behind, url: newest.html_url ?? null }
508
+ const parent = commit.parents?.[0]?.sha
509
+ commit = parent ? await json(graft(slug, ['api', 'GET', `/repos/${slug}/commits/${parent}`])) : null
510
+ }
511
+ return null
512
+ },
513
+ async compareRange(slug, base, head) {
514
+ const path = `/repos/${slug}/compare/${encodeURIComponent(base)}...${encodeURIComponent(head)}`
515
+ const c = await json(graft(slug, ['api', 'GET', path]))
516
+ return {
517
+ status: c.status,
518
+ aheadBy: Number(c.ahead_by ?? 0),
519
+ behindBy: Number(c.behind_by ?? 0),
520
+ files: (c.files ?? []).length,
521
+ commits: (c.commits ?? []).map((/** @type {any} */ x) => ({
522
+ sha: x.sha,
523
+ parents: (x.parents ?? []).map((/** @type {any} */ p) => p.sha),
524
+ message: x.commit?.message ?? '',
525
+ })),
526
+ }
527
+ },
528
+ async branches(slug, prefix) {
529
+ const path = `/repos/${slug}/git/matching-refs/heads/${prefix}`
530
+ const refs = await json(graft(slug, ['api', 'GET', path, '--paginate']))
531
+ return refs.map((/** @type {any} */ r) => String(r.ref).replace(/^refs\/heads\//, ''))
532
+ },
533
+ async createBranch(slug, name, sha) {
534
+ const body = JSON.stringify({ ref: `refs/heads/${name}`, sha })
535
+ await graft(slug, ['api', 'POST', `/repos/${slug}/git/refs`, '--body', body])
536
+ },
483
537
  async editPull(slug, number, { title, body }) {
484
538
  await graft(slug, ['api', 'PATCH', `/repos/${slug}/pulls/${number}`, '--body', JSON.stringify({ title, body })])
485
539
  },
@@ -5,8 +5,20 @@
5
5
  * state comment on that PR, written through the same path as an issue's (issue-state.mjs).
6
6
  *
7
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.
8
+ * the store), or by hand (`cambium run release-prepare`). `cleanup` closes, with a comment, every open
9
+ * promotion PR older than 24 h; `prepare` cuts a release and opens its PR, labels it `q:promote` and exits.
10
+ *
11
+ * A promotion PR whose head is `from` itself changes under its reviewer: whatever merges while they read is in
12
+ * the merge. So `prepare` promotes a frozen cut:
13
+ *
14
+ * CUT the newest commit on `from`'s first-parent line whose `release.check` concluded green (`null`:
15
+ * the tip). A newer red or pending commit does not block an older green one.
16
+ * CONTENT `to` must hold nothing the cut lacks: an ancestor of it, or diverged only by empty merge
17
+ * commits (the last promotion's, which nothing merges back). Otherwise nothing is opened.
18
+ * BRANCH `release/YYYY-MM-DD-N` at the cut, `N` one past the highest that (local) day, never reused, and
19
+ * never pushed to: a fix found in review lands on `from`, and the next run cuts again.
20
+ * SUPERSEDE an open promotion of the same cut is refreshed; one of an older cut is closed, with a
21
+ * "Superseded by" comment, after the new PR opens.
10
22
  * - `release-promote`: `q:promote` is its queue. It enters at `merge` once the PR is approved, merges through
11
23
  * `graft pr merge --auto` (auto-merge, or a merge now when the PR is clean), waits at `merging`, and exits at
12
24
  * `promoted` (merged) or `abandoned` (closed unmerged), taking `q:promote` off.
@@ -83,24 +95,134 @@ async function land(ctx, pr, graph, node, marker, { status = 'waiting' } = {}) {
83
95
  await setLabels(ctx, slug, issue, move(pr.labels, decl.queue))
84
96
  }
85
97
 
86
- /** Open, and from `from` to `to` or carrying a release marker. @param {Release} r @param {PromotionPr} pr */
98
+ /** A release branch: `release/YYYY-MM-DD-N`. */
99
+ export const RELEASE_BRANCH = /^release\/(\d{4}-\d{2}-\d{2})-(\d+)$/
100
+
101
+ /** How many first-parent commits of `from` are searched for a green cut. */
102
+ export const CUT_DEPTH = 50
103
+
104
+ /**
105
+ * Open into `to` from `from` or a release branch, or carrying a release marker.
106
+ * @param {Release} r @param {PromotionPr} pr
107
+ */
87
108
  const isPromotion = (r, pr) =>
88
- (pr.head === r.from && pr.base === r.to) || Boolean(pr.stateComment?.marker.graph.startsWith('release-'))
109
+ (pr.base === r.to && (pr.head === r.from || RELEASE_BRANCH.test(pr.head))) ||
110
+ Boolean(pr.stateComment?.marker.graph.startsWith('release-'))
111
+
112
+ /** `YYYY-MM-DD` in the machine's local time. @param {number} ms */
113
+ export function localDate(ms) {
114
+ const d = new Date(ms)
115
+ const p = (/** @type {number} */ n) => String(n).padStart(2, '0')
116
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`
117
+ }
118
+
119
+ /**
120
+ * The next release branch for `date`: one past the highest that day, so a gap is never reused.
121
+ * @param {string} date `YYYY-MM-DD` @param {string[]} existing branch names
122
+ */
123
+ export function releaseName(date, existing) {
124
+ let max = 0
125
+ for (const name of existing) {
126
+ const m = RELEASE_BRANCH.exec(name)
127
+ if (m && m[1] === date) max = Math.max(max, Number(m[2]))
128
+ }
129
+ return `release/${date}-${max + 1}`
130
+ }
131
+
132
+ /**
133
+ * The PRs a range merged, from its first-parent line (newest commit back): GitHub merge commits (`Merge pull
134
+ * request #N from …`, title on the next line) and squash merges (`title (#N)`). A branch's own commits are off
135
+ * that line, so an issue named in one (`fix x (#123)`) is not taken for a PR. Oldest first, each once.
136
+ * @param {import('../github.mjs').Range['commits']} commits oldest first
137
+ * @returns {{ number: number, title: string }[]}
138
+ */
139
+ export function mergedPrs(commits) {
140
+ const bySha = new Map(commits.map((c) => [c.sha, c]))
141
+ /** @type {typeof commits} */
142
+ const line = []
143
+ for (let c = commits.at(-1); c && line.length < commits.length; c = bySha.get(c.parents[0])) line.unshift(c)
144
+ /** @type {Map<number, string>} */
145
+ const seen = new Map()
146
+ for (const { message } of line) {
147
+ const [subject, ...rest] = message.split('\n')
148
+ const merge = /^Merge pull request #(\d+) from \S+/.exec(subject)
149
+ const squash = merge ? null : /^(.*\S)\s+\(#(\d+)\)$/.exec(subject)
150
+ const number = Number(merge?.[1] ?? squash?.[2])
151
+ if (!number || seen.has(number)) continue
152
+ seen.set(number, merge ? (rest.map((l) => l.trim()).find(Boolean) ?? subject) : /** @type {any} */ (squash)[1])
153
+ }
154
+ return [...seen].map(([number, title]) => ({ number, title }))
155
+ }
156
+
157
+ /**
158
+ * @typedef {{ branch: string, sha: string, behind: number, url: string | null, check: string | null,
159
+ * aheadBy: number, merged: { number: number, title: string }[], truncated: boolean }} Cut
160
+ */
89
161
 
90
- /** The promotion PR's body: what `to` gets. @param {Release} r */
91
- export function promotionBody(r) {
162
+ /** The promotion PR's body: what `to` gets, and why this commit. @param {Release} r @param {Cut} cut */
163
+ export function promotionBody(r, cut) {
164
+ const why = cut.check
165
+ ? `the newest \`${r.from}\` commit with a green \`${cut.check}\`${cut.url ? ` ([run](${cut.url}))` : ''}`
166
+ : `the tip of \`${r.from}\``
92
167
  const lines = [
93
- `Promotes \`${r.from}\` → \`${r.to}\`: ${r.aheadBy} commit${r.aheadBy === 1 ? '' : 's'} ahead.`,
168
+ `Promotes \`${cut.branch}\` → \`${r.to}\`: ${cut.aheadBy} commit${cut.aheadBy === 1 ? '' : 's'} ahead.`,
94
169
  '',
95
- r.merged.length ? `Merged into \`${r.from}\` since \`${r.to}\`:` : `No merged PRs found in the commits ahead.`,
96
- ...r.merged.map((p) => `- #${p.number} ${p.title}`),
170
+ `Cut at ${cut.sha}, ${why}.` +
171
+ (cut.behind
172
+ ? ` \`${r.from}\` has ${cut.behind} newer commit${cut.behind === 1 ? '' : 's'} not in this cut.`
173
+ : ''),
97
174
  '',
98
- '_Opened by cambium (release-prepare). Approve it and cambium merges it (release-promote); ' +
175
+ cut.merged.length ? `Merged into \`${r.from}\` since \`${r.to}\`:` : `No merged PRs found in the commits ahead.`,
176
+ ...cut.merged.map((p) => `- #${p.number} ${p.title}`),
177
+ ...(cut.truncated ? ['', '_The list covers the oldest 250 commits of the range._'] : []),
178
+ '',
179
+ `_Opened by cambium (release-prepare). Nobody pushes to \`${cut.branch}\`: a fix lands on \`${r.from}\` and ` +
180
+ 'the next run cuts again. Approve it and cambium merges it (release-promote); ' +
99
181
  'an unmerged promotion PR is closed after 24 h._',
100
182
  ]
101
183
  return lines.join('\n')
102
184
  }
103
185
 
186
+ /**
187
+ * Where `r.from` should be cut, or why it should not: no green commit in reach, `to` already has it, or `to`
188
+ * holds content the cut lacks.
189
+ * @param {ReleaseCtx} ctx @param {Release} r
190
+ * @returns {Promise<{ cut: Omit<Cut, 'branch'> } | { reason: string, warn?: boolean }>}
191
+ */
192
+ async function findCut(ctx, r) {
193
+ const { slug, repo } = ctx.subject
194
+ const check = repo.release.check
195
+ const green = await ctx.github.greenCommit(slug, r.from, check, CUT_DEPTH)
196
+ if (!green)
197
+ return {
198
+ reason: `no commit in the last ${CUT_DEPTH} on \`${r.from}\` has a green \`${check}\`; nothing to promote`,
199
+ }
200
+ const range = await ctx.github.compareRange(slug, r.to, green.sha)
201
+ if (range.status === 'identical' || range.status === 'behind')
202
+ return { reason: `\`${r.to}\` already has ${green.sha.slice(0, 9)}; nothing to promote` }
203
+ if (range.status !== 'ahead') {
204
+ const back = await ctx.github.compareRange(slug, green.sha, r.to)
205
+ if (back.files > 0)
206
+ return {
207
+ warn: true,
208
+ reason:
209
+ `\`${r.to}\` holds content ${green.sha.slice(0, 9)} lacks (${range.behindBy} commits, ${back.files} files); ` +
210
+ `merge \`${r.to}\` into \`${r.from}\`, then promote`,
211
+ }
212
+ }
213
+ return {
214
+ cut: {
215
+ sha: green.sha,
216
+ behind: green.behind,
217
+ url: green.url,
218
+ check,
219
+ aheadBy: range.aheadBy,
220
+ merged: mergedPrs(range.commits),
221
+ truncated: range.aheadBy > range.commits.length,
222
+ },
223
+ }
224
+ }
225
+
104
226
  // ---- release-prepare
105
227
 
106
228
  const Empty = z.object({})
@@ -154,37 +276,47 @@ const prepare = declare(
154
276
  z.object({ to: z.literal('nothing'), reason: z.string() }),
155
277
  ]),
156
278
  /**
157
- * `from` ahead of `to`: open the promotion PR (or refresh the open one), label it `q:promote`, write the
158
- * marker. Nothing ahead: a log line.
279
+ * `from` ahead of `to`: cut a release (see the header), open its PR, label it `q:promote`, write the marker,
280
+ * then close the promotion it supersedes. Same cut already open: refresh it. Nothing to cut: a log line.
159
281
  * @param {z.infer<typeof Closed>} _ @param {ReleaseCtx} ctx
160
282
  */
161
283
  run: async (_, ctx) => {
162
284
  const { slug, release: r } = ctx.subject
163
- if (!r.aheadBy) {
164
- const reason =
285
+ /** @param {string} reason @param {boolean} [warn] */
286
+ const nothing = (reason, warn = false) => {
287
+ ctx.log(warn ? 'warn' : 'info', `release: ${reason}`, { repo: slug })
288
+ return /** @type {const} */ ({ to: 'nothing', reason })
289
+ }
290
+ if (!r.aheadBy)
291
+ return nothing(
165
292
  r.aheadBy === null
166
293
  ? `\`${r.to}\` not found; nothing to promote`
167
- : `\`${r.from}\` is not ahead of \`${r.to}\`; nothing to promote`
168
- ctx.log('info', `release: ${reason}`, { repo: slug })
169
- return { to: 'nothing', reason }
170
- }
171
- const title = `Promote ${r.from} → ${r.to}`
172
- const body = promotionBody(r)
294
+ : `\`${r.from}\` is not ahead of \`${r.to}\`; nothing to promote`,
295
+ )
296
+ const found = await findCut(ctx, r)
297
+ if (!('cut' in found)) return nothing(found.reason, found.warn)
173
298
  const at = iso(ctx.tick.now)
174
- const open = r.prs.find((p) => p.state === 'OPEN' && p.head === r.from && p.base === r.to)
175
- if (open) {
176
- await ctx.github.editPull(slug, open.number, { title, body })
177
- const m = markerOn(open, releasePrepare.name, 'prepare')
178
- const entry = { at, attempt: m.attempt, outcome: 'updated', pr: open.number }
299
+ const open = r.prs.filter((p) => p.state === 'OPEN' && isPromotion(r, p))
300
+ const same = open.find((p) => p.headSha === found.cut.sha && RELEASE_BRANCH.test(p.head))
301
+ if (same) {
302
+ const cut = { ...found.cut, branch: same.head }
303
+ const title = `Release ${same.head.slice('release/'.length)}`
304
+ await ctx.github.editPull(slug, same.number, { title, body: promotionBody(r, cut) })
305
+ const m = markerOn(same, releasePrepare.name, 'prepare')
306
+ const entry = { at, attempt: m.attempt, outcome: 'updated', pr: same.number }
179
307
  // Already in release-promote (approved, merging): keep its position, record the refresh.
180
308
  if (m.graph === releasePromote.name && m.status !== 'done') {
181
- await setMarker(ctx, slug, /** @type {any} */ (open), withHistory(m, entry))
182
- await setLabels(ctx, slug, /** @type {any} */ (open), move(open.labels, Q.promote))
183
- } else await land(ctx, open, releasePrepare, 'prepare', withHistory(m, entry), { status: 'done' })
184
- ctx.log('info', `release: refreshed promotion PR #${open.number}`, where(ctx, open.number))
185
- return { to: 'updated', pr: open.number }
309
+ await setMarker(ctx, slug, /** @type {any} */ (same), withHistory(m, entry))
310
+ await setLabels(ctx, slug, /** @type {any} */ (same), move(same.labels, Q.promote))
311
+ } else await land(ctx, same, releasePrepare, 'prepare', withHistory(m, entry), { status: 'done' })
312
+ ctx.log('info', `release: refreshed promotion PR #${same.number}`, where(ctx, same.number))
313
+ return { to: 'updated', pr: same.number }
186
314
  }
187
- const made = await ctx.github.openPull(slug, { head: r.from, base: r.to, title, body })
315
+ const branch = releaseName(localDate(ctx.tick.now), await ctx.github.branches(slug, 'release/'))
316
+ const cut = { ...found.cut, branch }
317
+ await ctx.github.createBranch(slug, branch, cut.sha)
318
+ const title = `Release ${branch.slice('release/'.length)}`
319
+ const made = await ctx.github.openPull(slug, { head: branch, base: r.to, title, body: promotionBody(r, cut) })
188
320
  /** @type {PromotionPr} */
189
321
  const pr = {
190
322
  number: made.number,
@@ -192,9 +324,9 @@ const prepare = declare(
192
324
  title,
193
325
  state: 'OPEN',
194
326
  createdAt: at,
195
- head: r.from,
327
+ head: branch,
196
328
  base: r.to,
197
- headSha: null,
329
+ headSha: cut.sha,
198
330
  labels: [],
199
331
  approved: false,
200
332
  autoMerge: false,
@@ -210,21 +342,41 @@ const prepare = declare(
210
342
  withHistory(m, { at, attempt: m.attempt, outcome: 'opened', pr: pr.number }),
211
343
  { status: 'done' },
212
344
  )
213
- ctx.log('info', `release: opened promotion PR #${pr.number} (${r.from} → ${r.to})`, where(ctx, pr.number))
345
+ ctx.log('info', `release: opened promotion PR #${pr.number} (${branch} → ${r.to})`, where(ctx, pr.number))
346
+ // The new PR first, so a failed open leaves the old promotion standing.
347
+ for (const old of open) {
348
+ const reason = `superseded by #${pr.number}`
349
+ if (old.stateComment) {
350
+ const om = old.stateComment.marker
351
+ await land(
352
+ ctx,
353
+ old,
354
+ releasePrepare,
355
+ 'cleanup',
356
+ withHistory(om, { at, attempt: om.attempt, outcome: 'superseded', reason }),
357
+ { status: 'done' },
358
+ )
359
+ } else if (old.labels.includes(Q.promote))
360
+ await setLabels(ctx, slug, /** @type {any} */ (old), move(old.labels, null))
361
+ await ctx.github.closePull(slug, old.number, `Superseded by #${pr.number}.`)
362
+ old.state = 'CLOSED'
363
+ ctx.log('info', `release: closed promotion PR #${old.number} (${reason})`, where(ctx, old.number))
364
+ }
214
365
  return { to: 'opened', pr: pr.number }
215
366
  },
216
367
  }),
217
368
  // The PR it opens waits in `q:promote`, release-promote's queue.
218
369
  {
219
370
  queue: Q.promote,
220
- about: 'When from is ahead of to, opens the promotion PR (or refreshes the open one) and labels it q:promote.',
371
+ about:
372
+ 'Cuts release/<date>-N at the newest green commit on from, opens its PR (superseding the open one), labels it q:promote.',
221
373
  },
222
374
  )
223
375
 
224
376
  /** Bump `version` when a node is removed or renamed. */
225
377
  export const releasePrepare = defineGraph({
226
378
  name: 'release-prepare',
227
- about: 'Once a day, opens or refreshes the promotion PR from the integration branch to the release branch.',
379
+ about: 'Once a day, cuts a release branch from the integration branch and opens its PR into the release branch.',
228
380
  version: 1,
229
381
  entry: { node: 'cleanup', input: () => ({}) },
230
382
  nodes: [cleanup, prepare],
@@ -25,6 +25,7 @@ Your contract (the repository's AGENTS.md, four points):
25
25
 
26
26
  Rules:
27
27
  - Publish to exactly the branch \`${branch}\` and pass \`--closes ${issue.number}\`: that is how cambium finds your PR.
28
+ - One PR per issue, into the default base: never \`--base\` another branch, and never a second, stacked PR. If the issue asks for staged PRs, do stage one only and say in the PR body what is left; cambium tracks one PR per issue and closes a second as a duplicate.
28
29
  - Do not touch labels or the issue body (\`graft issue label\` / \`graft issue edit\` are denied); cambium moves the queue.
29
30
  - Exiting without a published PR counts as a failed attempt.
30
31
  ${