@oakgreencc/cambium 0.0.17 → 0.0.19

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
@@ -37,7 +37,7 @@ Every command takes `--config <file>`; the default is `$CAMBIUM_CONFIG`, then `~
37
37
 
38
38
  Each step is bounded by `stepTimeoutSeconds`. A step that throws or times out is logged and recorded in the heartbeat, and the tick moves on. Nothing waits on a worker.
39
39
 
40
- 1. **Read.** One GraphQL query per repo (`graft graphql`): open issues with any `q:` label, open and recently merged PRs on `agent/*` with their check rollup, merge-queue state and the issues they close.
40
+ 1. **Read.** One GraphQL query per repo (`graft graphql`): open issues with any `q:` label, open and recently merged PRs on `agent/*` with their check rollup, merge-queue state and the issues they close. GitHub links closing references only for a PR into the default branch, so cambium also reads `Closes/Fixes/Resolves #n` from the PR body, fetching issues the first query did not read in one more. A worker's PR that names no issue (found by its branch) gets `Closes #n` added at submission.
41
41
  2. **Reconcile.** For each tracked worker: alive and under its wall-clock cap → nothing. Over the cap → kill its process group. Gone → exit check (a PR on its branch, or closing its issue, that is open or merged and not still on the commit CI already failed) → `submitted`; otherwise requeue with the stderr tail (a failed prepare step requeues as `spawn-failed`). Then the worktree is torn down if `graft status` says GitHub holds everything in it, else kept with a `warn` saying why.
42
42
  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`.
43
43
  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.
@@ -45,7 +45,7 @@ Each step is bounded by `stepTimeoutSeconds`. A step that throws or times out is
45
45
  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.
46
46
  7. **Heartbeat.** Write the state file.
47
47
 
48
- 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
+ A requeue is `q:task` with attempt + 1, or, once `maxAttempts` are spent, `q:human` + `why:budget`. Who merges a Task PR is the repo's `merge` setting ([Merging](#merging)): by default not cambium (a merge queue, auto-merge or a human); with `"merge": "green"` cambium merges it once CI is green. The other merge cambium asks for is an approved promotion PR, through `graft pr merge`; see [The release graphs](#the-release-graphs).
49
49
 
50
50
  ## State on GitHub
51
51
 
@@ -103,6 +103,7 @@ One JSON file. Everything but `repos` is optional; these are the defaults:
103
103
  "dispatch": { "cap": 0, "wallClockMinutes": 15, "maxTurns": 50, "maxAttempts": 3, "maxRounds": 3 }
104
104
  },
105
105
  "mergeQueueMinutes": 120,
106
+ "merge": "none",
106
107
  "priorityLabels": ["priority:critical", "priority:high", "priority:medium", "priority:low"],
107
108
  "release": { "enabled": false, "time": "06:00" },
108
109
  "paths": {
@@ -123,6 +124,7 @@ One JSON file. Everything but `repos` is optional; these are the defaults:
123
124
  - The daemon re-reads the file before every tick, so caps, limits, `tickSeconds`, `repos`, priority labels, `release` and `worker` take effect without a restart (logged as `config reloaded: <keys>`). `host`, `engine`, `paths`, `logs` and `graft` are baked in at start: a change to them logs `restart cambium to apply` once and is not applied. A file that does not load, or has no `repos`, keeps the running config and logs one warning until it is fixed.
124
125
  - `repos[].path` is a local clone; worktrees are added from it and `graft` runs in it.
125
126
  - `graft.app` is the App cambium acts as (`GRAFT_APP` for its own `graft` calls); `worker.graftApp` the one workers act as. Neither leaks into the other.
127
+ - `merge` (top level, or per repo in `repos[]`): who merges a Task PR. See [Merging](#merging).
126
128
  - `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). Only `"graph"` runs the [`dispatch` graph](#the-dispatch-graph) (gated by `phases.dispatch.cap`); legacy leaves `q:intake` alone.
127
129
  - Setting `paths.home` moves every default path under it.
128
130
  - `release.time` is host-local `HH:MM`.
@@ -246,29 +248,37 @@ flowchart TD
246
248
  n0["start-worker"]
247
249
  n1{{"worker-running"}}
248
250
  n2{{"ci-running"}}
249
- n3{{"merge-queue"}}
250
- n4["close-out"]
251
- n5["requeue"]
252
- n6["to-human"]
251
+ n3["merge"]
252
+ n4{{"merging"}}
253
+ n5{{"merge-queue"}}
254
+ n6["close-out"]
255
+ n7["requeue"]
256
+ n8["to-human"]
253
257
  end_(("end"))
254
258
  start_ --> n0
255
259
  n0 -->|"started"| n1
256
- n0 -->|"budgetSpent"| n6
257
- n0 --> n5
260
+ n0 -->|"budgetSpent"| n8
261
+ n0 --> n7
258
262
  n1 -->|"issueGone"| end_
259
263
  n1 -->|"submitted"| n2
260
- n1 --> n5
261
- n2 -->|"merged"| n4
262
- n2 -->|"inMergeQueue"| n3
263
- n2 -->|"stalled"| n6
264
- n2 --> n5
265
- n3 -->|"merged"| n4
266
- n3 -->|"stalled"| n6
267
- n3 --> n5
268
- n5 -->|"attemptsLeft"| n0
269
- n5 --> n6
270
- n4 --> end_
264
+ n1 --> n7
265
+ n2 -->|"merged"| n6
266
+ n2 -->|"inMergeQueue"| n5
267
+ n2 -->|"green"| n3
268
+ n2 -->|"stalled"| n8
269
+ n2 --> n7
270
+ n3 --> n4
271
+ n4 -->|"merged"| n6
272
+ n4 -->|"green"| n3
273
+ n4 -->|"stalled"| n8
274
+ n4 --> n7
275
+ n5 -->|"merged"| n6
276
+ n5 -->|"stalled"| n8
277
+ n5 --> n7
278
+ n7 -->|"attemptsLeft"| n0
279
+ n7 --> n8
271
280
  n6 --> end_
281
+ n8 --> end_
272
282
  ```
273
283
 
274
284
  Generated by `toMermaid(task)`; a test keeps this copy current. Boxes are step nodes, hexagons are waits.
@@ -278,17 +288,28 @@ Generated by `toMermaid(task)`; a test keeps this copy current. Boxes are step n
278
288
  | `start-worker` | step | `q:task` | no |
279
289
  | `worker-running` | wait | `q:task` | yes |
280
290
  | `ci-running` | wait | none | no |
291
+ | `merge` | step | none | no |
292
+ | `merging` | wait | none | no |
281
293
  | `merge-queue` | wait | none | no |
282
294
  | `close-out` | step | none | no |
283
295
  | `requeue` | step | `q:task` | no |
284
296
  | `to-human` | step | `q:human` | no |
285
297
 
286
298
  - **Labels are a projection.** Each node declares its queue label and whether it holds `running`. When an issue lands on a node, the marker is written first, then the labels come from `move()` (`labels.mjs`) with that declaration.
287
- - **Where a turn starts.** Reconcile polls `worker-running` for every tracked worker. Watch polls `ci-running` / `merge-queue` for agent PRs whose issue is in no queue; a merged PR goes to `close-out` wherever the issue is, as in the stage tick. Sweep sends a stale `running` lease to its node's `recover` (default: `requeue`). Schedule is the gate on the entry node: caps and priority pick the issues, each starts at `start-worker`.
299
+ - **Where a turn starts.** Reconcile polls `worker-running` for every tracked worker. Watch polls `ci-running` / `merging` / `merge-queue` for agent PRs whose issue is in no queue; a merged PR goes to `close-out` wherever the issue is, as in the stage tick. Sweep sends a stale `running` lease to its node's `recover` (default: `requeue`). Schedule is the gate on the entry node: caps and priority pick the issues, each starts at `start-worker`.
288
300
  - **Where a turn stops.** At a wait that is not ready, on entering a wait (it is polled next tick; `merge-queue` is polled on entry, so a stall is caught in the same pass), on reaching `start-worker` again (only Schedule admits it), or at the end.
289
301
  - **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.
290
302
  - **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.
291
303
 
304
+ ## Merging
305
+
306
+ Neither of our repos runs a GitHub merge queue (it costs), so `merge` says who merges a Task PR, per repo (`repos[].merge`, falling back to the top-level `merge`):
307
+
308
+ - `"none"` (default): not cambium. A merge queue, auto-merge or a human merges it; `mergeQueueMinutes` after submission an unmerged PR sends its issue to `q:human` (`stalled`).
309
+ - `"green"`: cambium merges it. Needs `engine: "graph"` (config refuses it on legacy). When `ci-running` sees the PR's checks `SUCCESS`, with no auto-merge armed and not in a merge queue, it goes to `merge`: `graft pr merge <n> --auto`, so graft's merge policy (bases, protected paths, a red base) still decides: a clean PR merges now, otherwise auto-merge is armed. Then `merging` waits for the merge. A refusal is recorded in the marker (`mergeRefusal`, history `merge-refused`) and asked again on a new head or after 10 minutes. Red CI still requeues, and `mergeQueueMinutes` still stalls to `q:human`.
310
+
311
+ The worker prompt says which: "Green: stop; cambium merges the PR once CI is green" or "…the PR is merged outside this session".
312
+
292
313
  ## The dispatch graph
293
314
 
294
315
  With `"engine": "graph"` and `phases.dispatch.cap > 0`, each `q:intake` issue is triaged by a one-shot `claude -p` worker (`src/graphs/dispatch.mjs`, steps in `src/dispatch-engine.mjs`, prompt and result in `src/phases/dispatch.mjs`), then moved to `q:task`, moved to `q:human`, or closed as a duplicate.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oakgreencc/cambium",
3
- "version": "0.0.17",
3
+ "version": "0.0.19",
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",
@@ -51,7 +51,7 @@
51
51
  "@opentelemetry/sdk-metrics": "^3.1.1",
52
52
  "@opentelemetry/sdk-trace": "^3.1.1",
53
53
  "zod": "^4.6.7",
54
- "@oakgreencc/mycelium": "0.0.0"
54
+ "@oakgreencc/mycelium": "0.0.6"
55
55
  },
56
56
  "devDependencies": {
57
57
  "@langchain/core": "^1.4.1",
package/src/config.mjs CHANGED
@@ -12,7 +12,11 @@ import { join, resolve } from 'node:path'
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
14
  * `from === to`.
15
- * @typedef {{ slug: string, path: string, baseBranch: string, release: RepoRelease }} Repo
15
+ * @typedef {'none' | 'green'} MergePolicy
16
+ * Who merges a Task PR. `none`: not cambium (a merge queue, auto-merge, or a human; past `mergeQueueMinutes`
17
+ * the issue goes to `q:human`). `green`: cambium, once its checks are green, through `graft pr merge --auto`
18
+ * (so graft's merge policy still decides). `green` needs `engine: "graph"`.
19
+ * @typedef {{ slug: string, path: string, baseBranch: string, release: RepoRelease, merge: MergePolicy }} Repo
16
20
  * @typedef {{ cap: number, wallClockMinutes: number, maxTurns: number, maxAttempts: number }} PhaseCaps
17
21
  * @typedef {{
18
22
  * host: string,
@@ -22,6 +26,7 @@ import { join, resolve } from 'node:path'
22
26
  * repos: Repo[],
23
27
  * phases: { task: PhaseCaps, dispatch: PhaseCaps & { maxRounds: number } },
24
28
  * mergeQueueMinutes: number,
29
+ * merge: MergePolicy,
25
30
  * priorityLabels: string[],
26
31
  * release: { enabled: boolean, time: string },
27
32
  * paths: { home: string, db: string, heartbeat: string, logs: string },
@@ -32,6 +37,9 @@ import { join, resolve } from 'node:path'
32
37
  * }} Config
33
38
  */
34
39
 
40
+ /** @type {readonly MergePolicy[]} */
41
+ const MERGE_POLICIES = Object.freeze(['none', 'green'])
42
+
35
43
  export const DEFAULT_HOME = join(homedir(), '.cambium')
36
44
 
37
45
  /** @param {string} home @returns {Config} */
@@ -47,6 +55,7 @@ export function defaults(home = DEFAULT_HOME) {
47
55
  dispatch: { cap: 0, wallClockMinutes: 15, maxTurns: 50, maxAttempts: 3, maxRounds: 3 },
48
56
  },
49
57
  mergeQueueMinutes: 120,
58
+ merge: 'none',
50
59
  priorityLabels: ['priority:critical', 'priority:high', 'priority:medium', 'priority:low'],
51
60
  release: { enabled: false, time: '06:00' },
52
61
  paths: {
@@ -103,8 +112,13 @@ export function resolveConfig(raw = {}) {
103
112
  ...r.release,
104
113
  }
105
114
  if (!/^\d{2}:\d{2}$/.test(release.time)) throw new Error(`config: repo ${r.slug} release.time must be HH:MM`)
106
- return { slug: r.slug, path: untilde(r.path), baseBranch, release }
115
+ const merge = r.merge ?? config.merge
116
+ if (!MERGE_POLICIES.includes(merge))
117
+ throw new Error(`config: repo ${r.slug} merge must be "none" or "green", got ${JSON.stringify(merge)}`)
118
+ return { slug: r.slug, path: untilde(r.path), baseBranch, release, merge }
107
119
  })
120
+ if (!MERGE_POLICIES.includes(config.merge))
121
+ throw new Error(`config: merge must be "none" or "green", got ${JSON.stringify(config.merge)}`)
108
122
  const wenv = config.worker.env
109
123
  if (
110
124
  !wenv ||
@@ -117,6 +131,9 @@ export function resolveConfig(raw = {}) {
117
131
  if (!(Number(config.update.checkMinutes) >= 5)) throw new Error('config: update.checkMinutes must be at least 5')
118
132
  if (config.engine !== 'legacy' && config.engine !== 'graph')
119
133
  throw new Error(`config: engine must be "legacy" or "graph", got ${JSON.stringify(config.engine)}`)
134
+ const merging = config.repos.filter((r) => r.merge === 'green')
135
+ if (merging.length && config.engine !== 'graph')
136
+ throw new Error(`config: merge "green" (${merging.map((r) => r.slug).join(', ')}) needs engine "graph"`)
120
137
  return config
121
138
  }
122
139
 
package/src/github.mjs CHANGED
@@ -47,10 +47,12 @@ import { Q, QUEUE_LABELS } from './labels.mjs'
47
47
  * editPull(slug: string, number: number, change: { title: string, body: string }): Promise<void>,
48
48
  * closePull(slug: string, number: number, comment: string): Promise<void>,
49
49
  * mergePull(slug: string, number: number): Promise<void>,
50
+ * linkIssue(slug: string, pr: number, issue: number): Promise<void>,
50
51
  * }} GitHub
52
+ * `linkIssue`: put `Closes #<issue>` at the top of the PR's body, so the PR names the issue it closes.
51
53
  */
52
54
 
53
- const PR_FIELDS = `number url headRefName state headRefOid isInMergeQueue
55
+ const PR_FIELDS = `number url headRefName state headRefOid isInMergeQueue body
54
56
  headRef { id }
55
57
  autoMergeRequest { enabledAt }
56
58
  closingIssuesReferences(first: 5) { nodes { ...I } }
@@ -93,6 +95,26 @@ fragment P on PullRequest {
93
95
  comments(first: 100) { nodes { databaseId body author { login } } }
94
96
  }`
95
97
 
98
+ /** GitHub's closing keywords before a same-repo `#n` (graft's closing-refs.mjs, without cross-repo refs). */
99
+ const CLOSING = /\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\b\s*:?\s+#(\d+)\b/gi
100
+
101
+ /**
102
+ * The issues a PR body says it closes. GitHub links these (`closingIssuesReferences`) only for a PR into the
103
+ * DEFAULT branch, so a repo whose agents target another base (sektorapp: `develop`) gets nothing from GitHub;
104
+ * cambium reads the body itself.
105
+ * @param {string | null | undefined} body @returns {number[]}
106
+ */
107
+ export function bodyCloses(body) {
108
+ return [...new Set([...(body ?? '').matchAll(CLOSING)].map((m) => Number(m[1])))]
109
+ }
110
+
111
+ /** The issues `numbers`, by alias, for {@link addIssues}. @param {number[]} numbers */
112
+ export const issuesQuery = (numbers) =>
113
+ `query($owner: String!, $name: String!) { repository(owner: $owner, name: $name) { ${numbers
114
+ .map((n) => `i${n}: issueOrPullRequest(number: ${n}) { __typename ... on Issue { ...I } }`)
115
+ .join(' ')} } }
116
+ ${SNAPSHOT_QUERY.slice(SNAPSHOT_QUERY.indexOf('fragment I on Issue'), SNAPSHOT_QUERY.indexOf('fragment P on'))}`
117
+
96
118
  const FAILED = new Set(['FAILURE', 'ERROR', 'TIMED_OUT', 'CANCELLED', 'ACTION_REQUIRED', 'STARTUP_FAILURE'])
97
119
 
98
120
  /**
@@ -156,6 +178,38 @@ function normalizeRelease(repo, { from, to }, botLogin) {
156
178
  }
157
179
  }
158
180
 
181
+ /** An issue node → {@link Issue}. @param {any} n @param {string | null} botLogin @returns {Issue} */
182
+ function toIssue(n, botLogin) {
183
+ return {
184
+ number: n.number,
185
+ title: n.title ?? '',
186
+ url: n.url ?? '',
187
+ state: n.state,
188
+ createdAt: n.createdAt,
189
+ body: n.body ?? '',
190
+ labels: labelsOf(n),
191
+ stateComment: stateCommentOf(n, botLogin),
192
+ }
193
+ }
194
+
195
+ /** The PRs' closed issues the snapshot has not read. @param {Snapshot} snap @returns {number[]} */
196
+ export const unreadCloses = (snap) => [...new Set(snap.prs.flatMap((p) => p.closes).filter((n) => !snap.issues.has(n)))]
197
+
198
+ /**
199
+ * Add the answer to {@link issuesQuery} to the snapshot; a number that is not an issue (a PR, or gone) is dropped
200
+ * from every PR's `closes`.
201
+ * @param {Snapshot} snap @param {any} data @param {number[]} asked @param {string | null} [botLogin]
202
+ */
203
+ export function addIssues(snap, data, asked, botLogin = null) {
204
+ const repo = (data?.data ?? data)?.repository ?? {}
205
+ for (const n of asked) {
206
+ const node = repo[`i${n}`]
207
+ if (node?.__typename === 'Issue') snap.issues.set(n, toIssue(node, botLogin))
208
+ }
209
+ for (const p of snap.prs) p.closes = p.closes.filter((n) => snap.issues.has(n))
210
+ return snap
211
+ }
212
+
159
213
  /**
160
214
  * GraphQL `data` → {@link Snapshot}. Only `agent/*` PRs are kept.
161
215
  *
@@ -170,18 +224,7 @@ export function normalize(data, { botLogin = null, release = null } = {}) {
170
224
  /** @type {Map<number, Issue>} */
171
225
  const issues = new Map()
172
226
  const addIssue = (/** @type {any} */ n) => {
173
- if (!issues.has(n.number)) {
174
- issues.set(n.number, {
175
- number: n.number,
176
- title: n.title ?? '',
177
- url: n.url ?? '',
178
- state: n.state,
179
- createdAt: n.createdAt,
180
- body: n.body ?? '',
181
- labels: labelsOf(n),
182
- stateComment: stateCommentOf(n, botLogin),
183
- })
184
- }
227
+ if (!issues.has(n.number)) issues.set(n.number, toIssue(n, botLogin))
185
228
  return n.number
186
229
  }
187
230
  for (const n of [...(repo.issues?.nodes ?? []), ...(repo.awaiting?.nodes ?? [])]) addIssue(n)
@@ -208,7 +251,7 @@ export function normalize(data, { botLogin = null, release = null } = {}) {
208
251
  autoMerge: Boolean(p.autoMergeRequest),
209
252
  checks: rollup?.state ?? null,
210
253
  failing,
211
- closes: (p.closingIssuesReferences?.nodes ?? []).map(addIssue),
254
+ closes: [...new Set([...(p.closingIssuesReferences?.nodes ?? []).map(addIssue), ...bodyCloses(p.body)])],
212
255
  })
213
256
  }
214
257
  return { issues, prs, ...(release ? { release: normalizeRelease(repo, release, botLogin) } : {}) }
@@ -262,7 +305,18 @@ export function graftGitHub({ config, exec: run = exec }) {
262
305
  const branches = release ?? { from: '', to: '' }
263
306
  const vars = JSON.stringify({ owner, name, labels: QUEUE_LABELS, release: Boolean(release), ...branches })
264
307
  const data = await json(graft(slug, ['graphql', SNAPSHOT_QUERY, '--vars', vars]))
265
- return normalize(data, { botLogin: config.graft.botLogin, release })
308
+ const snap = normalize(data, { botLogin: config.graft.botLogin, release })
309
+ const unread = unreadCloses(snap)
310
+ if (!unread.length) return snap
311
+ // Issues named only in PR bodies (in no queue): one more query, for those.
312
+ const ask = (/** @type {number[]} */ ns) =>
313
+ json(graft(slug, ['graphql', issuesQuery(ns), '--vars', JSON.stringify({ owner, name })]))
314
+ // A number that resolves to nothing fails the whole query: then one at a time, skipping those.
315
+ const more = await ask(unread).catch(async () => {
316
+ const one = await Promise.all(unread.map((n) => ask([n]).catch(() => null)))
317
+ return { repository: Object.assign({}, ...one.map((d) => d?.repository ?? {})) }
318
+ })
319
+ return addIssues(snap, more, unread, config.graft.botLogin)
266
320
  },
267
321
  async label(slug, number, { add, remove }) {
268
322
  if (!add.length && !remove.length) return
@@ -312,5 +366,12 @@ export function graftGitHub({ config, exec: run = exec }) {
312
366
  async mergePull(slug, number) {
313
367
  await graft(slug, ['pr', 'merge', String(number), '--auto'])
314
368
  },
369
+ async linkIssue(slug, pr, issue) {
370
+ const path = `/repos/${slug}/pulls/${pr}`
371
+ const { body } = await json(graft(slug, ['api', 'GET', path]))
372
+ if (bodyCloses(body).includes(issue)) return
373
+ const linked = `Closes #${issue}${body ? `\n\n${body}` : ''}`
374
+ await graft(slug, ['api', 'PATCH', path, '--body', JSON.stringify({ body: linked })])
375
+ },
315
376
  }
316
377
  }
@@ -159,6 +159,9 @@ async function reconcile(deps, ctx) {
159
159
  )
160
160
  }
161
161
 
162
+ /** The waits Watch drives: an open PR on its way to a merge. */
163
+ const WATCHED = new Set(['ci-running', 'merging', 'merge-queue'])
164
+
162
165
  /** @param {Deps} deps @param {Ctx} ctx */
163
166
  async function watch(deps, ctx) {
164
167
  for (const [slug, snap] of ctx.snaps) {
@@ -180,7 +183,7 @@ async function watch(deps, ctx) {
180
183
  const at = locate(issue, ctx.now)
181
184
  if (!at) return
182
185
  if (at.note) return restart(deps, ctx, slug, issue, at.note)
183
- if (at.node === 'ci-running' || at.node === 'merge-queue') return drive(deps, ctx, subject, at)
186
+ if (WATCHED.has(at.node)) return drive(deps, ctx, subject, at)
184
187
  // Out of every queue with an open PR, but resting elsewhere (a queue label removed by hand): watch the PR
185
188
  // from where it is, as the legacy Watch does.
186
189
  const node = markerOf(issue).queued ? 'merge-queue' : 'ci-running'
@@ -13,7 +13,7 @@ import { branchName } from '../convention.mjs'
13
13
  import { failureSummary, iso, key, markerOf, MIN, setLabels, setMarker } from '../issue-state.mjs'
14
14
  import { move, Q, WHY } from '../labels.mjs'
15
15
  import { withHistory } from '../marker.mjs'
16
- import { prFor, taskExit, taskPrompt } from '../phases/task.mjs'
16
+ import { linkIssue, prFor, taskExit, taskPrompt } from '../phases/task.mjs'
17
17
  import { PREPARE_FAILED_LINE } from '../prepare.mjs'
18
18
  import { traceWorker } from '../tracing.mjs'
19
19
 
@@ -110,6 +110,7 @@ const PrIn = z.object({ pr: z.number().int().nullable(), branch: z.string().null
110
110
  const PrOut = z.discriminatedUnion('to', [
111
111
  z.object({ to: z.literal('merged'), pr: z.number().int() }),
112
112
  z.object({ to: z.literal('queued'), pr: z.number().int(), branch: z.string() }),
113
+ z.object({ to: z.literal('merge'), pr: z.number().int(), branch: z.string() }),
113
114
  z.object({ to: z.literal('human'), ...failure }),
114
115
  z.object({ to: z.literal('requeue'), ...failure }),
115
116
  ])
@@ -122,6 +123,7 @@ const issueGone = (/** @type {{ exit: string }} */ o) => o.exit === 'gone'
122
123
  const submitted = (/** @type {{ exit: string }} */ o) => o.exit === 'submitted'
123
124
  const merged = (/** @type {{ to: string }} */ o) => o.to === 'merged'
124
125
  const inMergeQueue = (/** @type {{ to: string }} */ o) => o.to === 'queued'
126
+ const green = (/** @type {{ to: string }} */ o) => o.to === 'merge'
125
127
  const stalled = (/** @type {{ to: string }} */ o) => o.to === 'human'
126
128
  const attemptsLeft = (/** @type {{ to: string }} */ o) => o.to === 'start'
127
129
 
@@ -164,6 +166,21 @@ function stall(ctx, pr, m) {
164
166
  })
165
167
  }
166
168
 
169
+ /** How long a refused merge holds before cambium asks again on the same head (a red base clears without a push). */
170
+ export const MERGE_RETRY_MINUTES = 10
171
+
172
+ /**
173
+ * Green, and cambium merges this repo's PRs (`merge: "green"`): nothing armed yet, and no refusal on this head
174
+ * within {@link MERGE_RETRY_MINUTES}.
175
+ * @param {TaskCtx} ctx @param {PullRequest} pr @param {Marker} m
176
+ */
177
+ function mergeDue(ctx, pr, m) {
178
+ const repo = ctx.config.repos.find((r) => r.slug === ctx.subject.slug)
179
+ if (repo?.merge !== 'green' || pr.checks !== 'SUCCESS' || pr.autoMerge || pr.inMergeQueue) return false
180
+ const r = m.mergeRefusal
181
+ return !r || r.sha !== pr.headSha || ctx.tick.now - Date.parse(r.at) > MERGE_RETRY_MINUTES * MIN
182
+ }
183
+
167
184
  /** Delete a merged PR's branch once per tick. @param {TaskCtx} ctx @param {PullRequest} pr */
168
185
  export async function deleteMergedBranch(ctx, pr) {
169
186
  const deleted = ctx.subject.deleted ?? new Set()
@@ -245,7 +262,16 @@ const startWorker = declare(
245
262
  // This node's cambium.node span, so Claude Code's own spans (when worker.env turns them on) join the trace.
246
263
  env: ctx.traceparent ? { TRACEPARENT: ctx.traceparent } : undefined,
247
264
  buildPrompt: (agentsMd) =>
248
- taskPrompt({ repo: slug, issue, marker, branch, pr, agentsMd, maxAttempts: caps.maxAttempts }),
265
+ taskPrompt({
266
+ repo: slug,
267
+ issue,
268
+ marker,
269
+ branch,
270
+ pr,
271
+ agentsMd,
272
+ maxAttempts: caps.maxAttempts,
273
+ merge: repo.merge,
274
+ }),
249
275
  })
250
276
  } catch (err) {
251
277
  // The claim already put the marker at worker-running; the failure is this node's.
@@ -370,6 +396,7 @@ const ciRunning = declare(
370
396
  const red = redCi(pr, m)
371
397
  if (red) return { ready: true, output: red }
372
398
  if (pr.inMergeQueue) return { ready: true, output: { to: 'queued', pr: pr.number, branch: pr.branch } }
399
+ if (mergeDue(ctx, pr, m)) return { ready: true, output: { to: 'merge', pr: pr.number, branch: pr.branch } }
373
400
  const late = stall(ctx, pr, m)
374
401
  return late ? { ready: true, output: late } : { ready: false }
375
402
  },
@@ -391,6 +418,87 @@ const ciRunning = declare(
391
418
  input: { pr: input.pr, branch: input.branch },
392
419
  })
393
420
  ctx.log('info', `submitted PR #${input.pr}; watching CI`, { repo: ctx.subject.slug, issue: ctx.subject.number })
421
+ await linkIssue(ctx, ctx.subject.slug, prOf(ctx, input), ctx.subject.number)
422
+ },
423
+ },
424
+ )
425
+
426
+ const MergeIn = z.object({ pr: z.number().int(), branch: z.string() })
427
+
428
+ const merge = declare(
429
+ defineNode({
430
+ name: 'merge',
431
+ input: MergeIn,
432
+ output: z.object({ pr: z.number().int(), branch: z.string(), refused: z.string().nullable() }),
433
+ /**
434
+ * Green: merge through `graft pr merge --auto` (a merge now when the PR is clean, else auto-merge), so graft's
435
+ * merge policy decides. A refusal is not a failure of the work: `merging` holds and asks again later.
436
+ * @param {z.infer<typeof MergeIn>} input @param {TaskCtx} ctx
437
+ */
438
+ run: async (input, ctx) => {
439
+ try {
440
+ await ctx.github.mergePull(ctx.subject.slug, input.pr)
441
+ return { ...input, refused: null }
442
+ } catch (err) {
443
+ return { ...input, refused: `merge refused: ${/** @type {Error} */ (err)?.message ?? err}` }
444
+ }
445
+ },
446
+ }),
447
+ { queue: null, running: false },
448
+ )
449
+
450
+ const MergingIn = PrIn.extend({ refused: z.string().nullable().optional() })
451
+
452
+ const merging = declare(
453
+ defineWait({
454
+ name: 'merging',
455
+ input: MergingIn,
456
+ output: PrOut,
457
+ /**
458
+ * Merged → close out. Red → requeue. Due again (a refusal on an older head, or one past the retry window) →
459
+ * merge. Otherwise hold until `mergeQueueMinutes` after submission.
460
+ * @param {z.infer<typeof MergingIn>} input @param {TaskCtx} ctx
461
+ */
462
+ poll: async (input, ctx) => {
463
+ const issue = issueOf(ctx)
464
+ const pr = prOf(ctx, input)
465
+ if (!pr) return { ready: false }
466
+ if (pr.state === 'MERGED') return { ready: true, output: { to: 'merged', pr: pr.number } }
467
+ if (pr.state !== 'OPEN' || issue.state !== 'OPEN') return { ready: false }
468
+ const m = markerOf(issue)
469
+ const red = redCi(pr, m)
470
+ if (red) return { ready: true, output: red }
471
+ if (m.mergeRefusal && mergeDue(ctx, pr, m))
472
+ return { ready: true, output: { to: 'merge', pr: pr.number, branch: pr.branch } }
473
+ const late = stall(ctx, pr, m)
474
+ return late ? { ready: true, output: late } : { ready: false }
475
+ },
476
+ }),
477
+ {
478
+ queue: null,
479
+ running: false,
480
+ /** @param {z.infer<typeof MergeIn> & { refused: string | null }} input @param {TaskCtx} ctx */
481
+ enter: async (input, ctx) => {
482
+ const { slug } = ctx.subject
483
+ const issue = issueOf(ctx)
484
+ const m = markerOf(issue)
485
+ const pr = prOf(ctx, input)
486
+ const at = iso(ctx.tick.now)
487
+ const { refused } = input
488
+ await land(ctx, 'merging', {
489
+ ...withHistory(m, {
490
+ at,
491
+ attempt: m.attempt,
492
+ outcome: refused ? 'merge-refused' : 'merge-armed',
493
+ pr: input.pr,
494
+ ...(refused ? { reason: refused } : {}),
495
+ }),
496
+ mergeRefusal: refused ? { sha: pr?.headSha ?? null, at, reason: refused } : null,
497
+ lastFailure: refused ?? m.lastFailure ?? null,
498
+ input: { pr: input.pr, branch: input.branch },
499
+ })
500
+ if (refused) ctx.log('warn', refused.split('\n')[0], { repo: slug, issue: issue.number })
501
+ else ctx.log('info', `merging PR #${input.pr}`, { repo: slug, issue: issue.number })
394
502
  },
395
503
  },
396
504
  )
@@ -539,7 +647,7 @@ export const task = defineGraph({
539
647
  name: 'task',
540
648
  version: 1,
541
649
  entry: { queue: Q.task, node: 'start-worker', input: () => ({}) },
542
- nodes: [startWorker, workerRunning, ciRunning, mergeQueue, closeOut, requeue, toHuman],
650
+ nodes: [startWorker, workerRunning, ciRunning, merge, merging, mergeQueue, closeOut, requeue, toHuman],
543
651
  edges: [
544
652
  ['start-worker', 'worker-running', started],
545
653
  ['start-worker', 'to-human', budgetSpent],
@@ -549,8 +657,14 @@ export const task = defineGraph({
549
657
  ['worker-running', 'requeue'],
550
658
  ['ci-running', 'close-out', merged],
551
659
  ['ci-running', 'merge-queue', inMergeQueue],
660
+ ['ci-running', 'merge', green],
552
661
  ['ci-running', 'to-human', stalled],
553
662
  ['ci-running', 'requeue'],
663
+ ['merge', 'merging'],
664
+ ['merging', 'close-out', merged],
665
+ ['merging', 'merge', green],
666
+ ['merging', 'to-human', stalled],
667
+ ['merging', 'requeue'],
554
668
  ['merge-queue', 'close-out', merged],
555
669
  ['merge-queue', 'to-human', stalled],
556
670
  ['merge-queue', 'requeue'],
@@ -584,6 +698,6 @@ export const TASK_QUEUES = {
584
698
  /** The input a resting node resumes with, rebuilt from the marker. @param {string} node @param {Marker} m */
585
699
  export function inputFor(node, m) {
586
700
  if (node === 'worker-running') return { branch: m.branch, attempt: m.attempt }
587
- if (node === 'ci-running' || node === 'merge-queue') return { pr: m.pr, branch: m.branch }
701
+ if (node === 'ci-running' || node === 'merging' || node === 'merge-queue') return { pr: m.pr, branch: m.branch }
588
702
  return {}
589
703
  }
package/src/marker.mjs CHANGED
@@ -41,8 +41,10 @@
41
41
  * queued?: boolean,
42
42
  * failedSha?: string | null,
43
43
  * lastFailure?: string | null,
44
+ * mergeRefusal?: { sha: string | null, at: string, reason: string } | null,
44
45
  * triage?: { title?: string, acceptance?: string[] } | null,
45
46
  * }} Marker
47
+ * `mergeRefusal`: the last `graft pr merge` cambium was refused (task graph `merge`), and on which head.
46
48
  * `triage`: what the dispatch graph's triage added when it handed the issue to `q:task`; the task prompt shows it.
47
49
  * @typedef {{ graph: string, entryNode: string, nodes?: Iterable<string> }} QueueOwner
48
50
  */
@@ -3,9 +3,11 @@
3
3
  * @param {{
4
4
  * repo: string, issue: import('../github.mjs').Issue, marker: import('../marker.mjs').Marker,
5
5
  * branch: string, pr: import('../github.mjs').PullRequest | null, agentsMd: string | null, maxAttempts: number,
6
+ * merge: import('../config.mjs').MergePolicy,
6
7
  * }} input
7
8
  */
8
- export function taskPrompt({ repo, issue, marker, branch, pr, agentsMd, maxAttempts }) {
9
+ export function taskPrompt({ repo, issue, marker, branch, pr, agentsMd, maxAttempts, merge }) {
10
+ const merges = merge === 'green' ? 'cambium merges the PR once CI is green' : 'the PR is merged outside this session'
9
11
  const history = marker.history
10
12
  .map(
11
13
  (h) =>
@@ -19,7 +21,7 @@ Your contract (the repository's AGENTS.md, four points):
19
21
  1. Task: GitHub issue #${issue.number} (below). Its acceptance checks are the definition of done.
20
22
  2. Verify: \`pnpm verify\` (lint + tests). Green means committable; the pre-commit hook runs the same command.
21
23
  3. Push: \`graft publish ${branch} "<conventional commit message>" --paths <a,b> --pr "<title>" --closes ${issue.number}\`. Never \`git commit\`, \`git push\`, \`git fetch\` or \`git pull\`.
22
- 4. Done: \`graft ci wait ${branch}\`. Green: stop, the PR merges through the queue. Red: read why (\`graft jobs <run>\`), fix, publish again.
24
+ 4. Done: \`graft ci wait ${branch}\`. Green: stop; ${merges}. Red: read why (\`graft jobs <run>\`), fix, publish again.
23
25
 
24
26
  Rules:
25
27
  - Publish to exactly the branch \`${branch}\` and pass \`--closes ${issue.number}\`: that is how cambium finds your PR.
@@ -70,3 +72,29 @@ export function taskExit(pr, marker = {}) {
70
72
  reason: pr ? `PR #${pr.number} was closed without merging` : 'worker exited without a published PR',
71
73
  }
72
74
  }
75
+
76
+ /**
77
+ * Make a submitted PR name its issue (`Closes #n`) when it does not: Watch finds a PR's issue through the PR's
78
+ * closing references, so a PR matched only by branch at exit would otherwise never be watched (no merge, no
79
+ * stall). A failure is logged, not fatal: the submission stands.
80
+ *
81
+ * @param {{ github: import('../github.mjs').GitHub, log: (level: string, msg: string, where?: object) => void }} deps
82
+ * @param {string} slug @param {import('../github.mjs').PullRequest | null | undefined} pr @param {number} issue
83
+ */
84
+ export async function linkIssue(deps, slug, pr, issue) {
85
+ if (!pr || pr.closes.includes(issue)) return
86
+ try {
87
+ await deps.github.linkIssue(slug, pr.number, issue)
88
+ pr.closes.push(issue)
89
+ deps.log('info', `PR #${pr.number} did not name its issue; added Closes #${issue}`, { repo: slug, issue })
90
+ } catch (err) {
91
+ deps.log(
92
+ 'warn',
93
+ `could not add Closes #${issue} to PR #${pr.number}: ${/** @type {Error} */ (err)?.message ?? err}`,
94
+ {
95
+ repo: slug,
96
+ issue,
97
+ },
98
+ )
99
+ }
100
+ }
package/src/tick.mjs CHANGED
@@ -10,7 +10,7 @@ import { byPriorityThenAge, move, Q, queueOf, RUNNING, WHY } from './labels.mjs'
10
10
  import { withHistory } from './marker.mjs'
11
11
  import { failureSummary, iso, key, markerOf, MIN, setLabels, setMarker } from './issue-state.mjs'
12
12
  import { GRAPH_ENGINE } from './graph-engine.mjs'
13
- import { prFor, taskExit, taskPrompt } from './phases/task.mjs'
13
+ import { linkIssue, 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'
@@ -289,6 +289,7 @@ export async function finish(deps, ctx, w, snap) {
289
289
  await setLabels(deps, w.repo, issue, move(issue.labels, null))
290
290
  ctx.touched.add(key(w.repo, w.issue))
291
291
  deps.log('info', `submitted PR #${pr.number}; watching CI`, { repo: w.repo, issue: w.issue })
292
+ await linkIssue(deps, w.repo, pr, w.issue)
292
293
  } else {
293
294
  const tail = deps.spawner.tail(w.stderr, 15)
294
295
  const reason = `${'reason' in verdict ? verdict.reason : 'worker failed'}${tail ? `\n--- stderr (last lines, ${w.stderr})\n${tail}` : ''}`
@@ -531,7 +532,16 @@ export async function startTask(deps, ctx, slug, issue, snap, { foreground = fal
531
532
  maxTurns: caps.maxTurns,
532
533
  foreground,
533
534
  buildPrompt: (agentsMd) =>
534
- taskPrompt({ repo: slug, issue, marker, branch, pr, agentsMd, maxAttempts: caps.maxAttempts }),
535
+ taskPrompt({
536
+ repo: slug,
537
+ issue,
538
+ marker,
539
+ branch,
540
+ pr,
541
+ agentsMd,
542
+ maxAttempts: caps.maxAttempts,
543
+ merge: repo.merge,
544
+ }),
535
545
  })
536
546
  } catch (err) {
537
547
  await requeue(deps, ctx, slug, issue, {