@oakgreencc/cambium 0.0.27 → 0.0.28

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.
@@ -0,0 +1,420 @@
1
+ // @ts-check
2
+ /**
3
+ * The PR graph: what happens to an agent PR once its task graph has ended. Every tick, Watch (graph-engine.mjs)
4
+ * starts one turn at `assess` for each open agent PR whose CI has settled and whose issue has no Task queued or
5
+ * running; `assess` decides, one step acts, and the turn ends. No waits: the next tick assesses again.
6
+ *
7
+ * - merge: green and clean. Behind its base → update the branch (the new head's CI is the next tick's question);
8
+ * otherwise `graft pr merge --auto`. A refusal a human must clear → `q:human` + `why:approve`.
9
+ * - rework: red CI, a conflict, or changes requested → back to the task graph through `q:task`, with the PR's
10
+ * state as the reason (a fresh attempt budget, at most `phases.task.maxReworks` reworks). Red CI while the base
11
+ * is red (base-health.mjs) holds instead, except on the repair issue.
12
+ * - close: the issue is closed, or a newer agent PR closes the same issue → the PR is closed with a comment.
13
+ * - human: reworks spent, a merge only a human may make, or not merged within `mergeQueueMinutes`.
14
+ * - hold: nothing to do this tick (a refusal waiting out its retry window, a repo cambium does not merge).
15
+ *
16
+ * A merged PR (its issue still open) goes to `close-out`: the issue is closed and the branch deleted. The PR graph's state is the issue's
17
+ * marker (graph `pr`), like the task graph's.
18
+ *
19
+ * An issue already in `q:human` is the human's: the PR graph only takes it back to merge a PR that is green and
20
+ * clean (a worker's PR that landed after its issue was handed over), never to rework or close it.
21
+ */
22
+ import { z } from 'zod'
23
+ import { defineGraph, defineNode, END } from '../graph/index.mjs'
24
+ import { failureSummary, iso, markerOf, MIN, setMarker } from '../issue-state.mjs'
25
+ import { Q, WHY } from '../labels.mjs'
26
+ import { withHistory } from '../marker.mjs'
27
+ import { baseRed, isRepair } from '../base-health.mjs'
28
+ import { declare, failure, issueOf, landAt, nodeAt, snapOf, task } from './task.mjs'
29
+
30
+ /**
31
+ * @typedef {import('./task.mjs').TaskCtx} TaskCtx
32
+ * @typedef {import('../github.mjs').PullRequest} PullRequest
33
+ * @typedef {import('../marker.mjs').Marker} Marker
34
+ */
35
+
36
+ /** How long a refused merge holds before cambium asks again on the same head (a red base clears without a push). */
37
+ export const MERGE_RETRY_MINUTES = 10
38
+
39
+ /** graft's words for a refusal no retry clears (pr-policy.mjs): a human merges, approves, or fixes the policy. */
40
+ const NEEDS_HUMAN =
41
+ /a human merges it|hand the PR over|code owners' to approve|agents merge only into|lets no agent merge|does not parse/i
42
+
43
+ const Empty = z.object({})
44
+ const PrRef = z.object({ pr: z.number().int(), branch: z.string() })
45
+ const Human = z.object({ ...failure, why: z.string() })
46
+
47
+ /** The PR this turn is about. @param {TaskCtx} ctx */
48
+ function prOf(ctx) {
49
+ const { pr } = ctx.subject
50
+ if (!pr) throw new Error(`${ctx.subject.slug}#${ctx.subject.number}: the PR graph runs with a PR`)
51
+ return pr
52
+ }
53
+
54
+ /** @param {TaskCtx} ctx */
55
+ const repoOf = (ctx) => ctx.config.repos.find((r) => r.slug === ctx.subject.slug)
56
+
57
+ /** When the PR was submitted: the marker's `submittedAt`, else the PR's creation. @param {PullRequest} pr @param {Marker} m */
58
+ const submittedAt = (pr, m) => Date.parse(m.submittedAt ?? pr.createdAt ?? '') || null
59
+
60
+ /** A newer open agent PR that closes the same issue makes this one obsolete. @param {TaskCtx} ctx @param {PullRequest} pr */
61
+ function supersededBy(ctx, pr) {
62
+ const newer = snapOf(ctx).prs.filter(
63
+ (p) => p.state === 'OPEN' && p.number > pr.number && p.closes.includes(ctx.subject.number),
64
+ )
65
+ return newer.at(-1) ?? null
66
+ }
67
+
68
+ /** Why this PR needs a worker again, or null. @param {PullRequest} pr */
69
+ function reworkReason(pr) {
70
+ if (pr.checks === 'FAILURE' || pr.checks === 'ERROR') return { outcome: 'ci-red', reason: failureSummary(pr) }
71
+ if (pr.mergeable === 'CONFLICTING')
72
+ return {
73
+ outcome: 'conflict',
74
+ reason: `PR #${pr.number} conflicts with its base: bring the base in (\`graft advance ${pr.branch}\`, resolve, publish again).`,
75
+ }
76
+ if (pr.reviewDecision === 'CHANGES_REQUESTED')
77
+ return {
78
+ outcome: 'changes-requested',
79
+ reason: `A reviewer requested changes on PR #${pr.number}: read the reviews (\`graft pr view ${pr.number} --comments\`) and address them.`,
80
+ }
81
+ return null
82
+ }
83
+
84
+ // ---- Edge predicates (their names label the Mermaid edges)
85
+
86
+ const merged = (/** @type {{ to: string }} */ o) => o.to === 'merged'
87
+ const toMerge = (/** @type {{ to: string }} */ o) => o.to === 'merge'
88
+ const toRework = (/** @type {{ to: string }} */ o) => o.to === 'rework'
89
+ const toClose = (/** @type {{ to: string }} */ o) => o.to === 'close'
90
+ const toHumanInbox = (/** @type {{ to: string }} */ o) => o.to === 'human'
91
+ const needsApproval = (/** @type {{ to: string }} */ o) => o.to === 'human'
92
+ const reworksSpent = (/** @type {{ to: string }} */ o) => o.to === 'human'
93
+
94
+ // ---- Nodes
95
+
96
+ const Assessed = z.discriminatedUnion('to', [
97
+ z.object({ to: z.literal('merged'), pr: z.number().int() }),
98
+ z.object({ to: z.literal('merge'), pr: z.number().int(), branch: z.string() }),
99
+ z.object({ to: z.literal('rework'), ...failure, pr: z.number().int(), failedSha: z.string().nullable() }),
100
+ z.object({ to: z.literal('close'), pr: z.number().int(), reason: z.string() }),
101
+ z.object({ to: z.literal('human'), ...failure, why: z.string() }),
102
+ z.object({ to: z.literal('hold') }),
103
+ ])
104
+
105
+ const assess = declare(
106
+ defineNode({
107
+ name: 'assess',
108
+ input: Empty,
109
+ output: Assessed,
110
+ /** Decide, in order: merged, close, rework, merge, stall, hold. Reads only; the next node writes. @param {{}} _ @param {TaskCtx} ctx */
111
+ run: async (_, ctx) => {
112
+ const issue = issueOf(ctx)
113
+ const pr = prOf(ctx)
114
+ const m = markerOf(issue)
115
+ const human = issue.labels.includes(Q.human)
116
+ const hold = /** @type {const} */ ({ to: 'hold' })
117
+ const ref = { pr: pr.number, branch: pr.branch }
118
+ if (pr.state === 'MERGED') return { to: 'merged', pr: pr.number }
119
+
120
+ if (issue.state !== 'OPEN')
121
+ return { to: 'close', pr: pr.number, reason: `Issue #${issue.number} is closed, so this PR has nothing to do.` }
122
+ if (!human) {
123
+ const newer = supersededBy(ctx, pr)
124
+ if (newer) return { to: 'close', pr: pr.number, reason: `Superseded by #${newer.number} for #${issue.number}.` }
125
+ const why = reworkReason(pr)
126
+ // Red CI on a red base is most likely the base's (base-health.mjs): no rework is charged for it, and the PR
127
+ // is assessed again once the base is green. The repair issue's own PR is reworked as usual.
128
+ if (why?.outcome === 'ci-red' && baseRed(snapOf(ctx)) && !isRepair(issue)) return hold
129
+ if (why) return { to: 'rework', ...why, pr: pr.number, failedSha: pr.headSha }
130
+ }
131
+
132
+ const green =
133
+ pr.checks === 'SUCCESS' && pr.mergeable !== 'CONFLICTING' && pr.reviewDecision !== 'CHANGES_REQUESTED'
134
+ const r = m.mergeRefusal
135
+ const refusedHere = Boolean(r && r.sha === pr.headSha)
136
+ // In q:human because of a refusal on this head: the human's, until the head changes.
137
+ if (human && (!green || (refusedHere && m.graph === prGraph.name))) return hold
138
+ const merges = repoOf(ctx)?.merge === 'green'
139
+ if (green && merges && !pr.autoMerge && !pr.inMergeQueue) {
140
+ if (!refusedHere || !r || ctx.tick.now - Date.parse(r.at) > MERGE_RETRY_MINUTES * MIN)
141
+ return { to: 'merge', ...ref }
142
+ }
143
+ if (human) return hold
144
+
145
+ const since = submittedAt(pr, m)
146
+ const cap = ctx.config.mergeQueueMinutes
147
+ if (since !== null && ctx.tick.now - since > cap * MIN)
148
+ return {
149
+ to: 'human',
150
+ reason: `PR #${pr.number} not merged within ${cap} min of submission${r ? `. Last refusal: ${r.reason}` : ''}`,
151
+ outcome: 'stalled',
152
+ pr: pr.number,
153
+ why: WHY.approve,
154
+ }
155
+ return hold
156
+ },
157
+ }),
158
+ { queue: null, running: false },
159
+ )
160
+
161
+ const merge = declare(
162
+ defineNode({
163
+ name: 'merge',
164
+ input: PrRef,
165
+ output: z.discriminatedUnion('to', [
166
+ z.object({ to: z.literal('done') }),
167
+ z.object({ to: z.literal('human'), ...failure, why: z.string() }),
168
+ ]),
169
+ /**
170
+ * Behind its base (read live, so a merge earlier in this tick counts): update the branch instead; its green was
171
+ * earned on an older base, and two PRs green on the same base can be red together. Otherwise merge through
172
+ * `graft pr merge --auto`, so graft's merge policy decides. A refusal is recorded on the marker and asked
173
+ * again on a new head or after {@link MERGE_RETRY_MINUTES}; one only a human can clear goes to `q:human`.
174
+ * @param {z.infer<typeof PrRef>} input @param {TaskCtx} ctx
175
+ */
176
+ run: async (input, ctx) => {
177
+ const { slug } = ctx.subject
178
+ const issue = issueOf(ctx)
179
+ const pr = prOf(ctx)
180
+ const m = markerOf(issue)
181
+ const at = iso(ctx.tick.now)
182
+ /** @type {string} */
183
+ let outcome
184
+ /** @type {string | null} */
185
+ let note = null
186
+ /** @type {string | null} */
187
+ let refused = null
188
+ try {
189
+ const { behind, base } = await ctx.github.behindBase(slug, input.pr)
190
+ if (behind > 0) {
191
+ await ctx.github.updatePull(slug, input.pr)
192
+ outcome = 'branch-updated'
193
+ note = `PR #${input.pr} was ${behind} commit${behind === 1 ? '' : 's'} behind ${base}; updated it, merging once CI is green on the new head`
194
+ } else {
195
+ await ctx.github.mergePull(slug, input.pr)
196
+ outcome = 'merge-armed'
197
+ }
198
+ } catch (err) {
199
+ refused = `merge refused: ${/** @type {Error} */ (err)?.message ?? err}`
200
+ outcome = 'merge-refused'
201
+ }
202
+ const hold = refused ?? note
203
+ await landAt(prGraph, ctx, 'merge', {
204
+ ...withHistory(m, { at, attempt: m.attempt, outcome, pr: input.pr, ...(hold ? { reason: hold } : {}) }),
205
+ phase: 'task',
206
+ pr: input.pr,
207
+ branch: input.branch,
208
+ // An update holds like a refusal on the head it replaced: the new head is due as soon as it is green.
209
+ mergeRefusal: hold ? { sha: pr.headSha ?? null, at, reason: hold } : null,
210
+ lastFailure: refused ?? m.lastFailure ?? null,
211
+ input: null,
212
+ })
213
+ const where = { repo: slug, issue: issue.number }
214
+ if (refused && NEEDS_HUMAN.test(refused))
215
+ return { to: 'human', reason: refused, outcome: 'needs-approval', pr: input.pr, why: WHY.approve }
216
+ if (refused) ctx.log('warn', refused.split('\n')[0], where)
217
+ else if (note) ctx.log('info', note, where)
218
+ else ctx.log('info', `merging PR #${input.pr}`, where)
219
+ return { to: 'done' }
220
+ },
221
+ }),
222
+ { queue: null, running: false },
223
+ )
224
+
225
+ const ReworkIn = z.object({ ...failure, pr: z.number().int(), failedSha: z.string().nullable() })
226
+
227
+ const rework = declare(
228
+ defineNode({
229
+ name: 'rework',
230
+ input: ReworkIn,
231
+ output: z.discriminatedUnion('to', [
232
+ z.object({ to: z.literal('task') }),
233
+ z.object({ to: z.literal('human'), ...failure, why: z.string() }),
234
+ ]),
235
+ /**
236
+ * Back to the task graph at its entry, in `q:task`: attempt 1 of a fresh budget, `reworks` + 1, the PR and its
237
+ * branch kept, the reason as `lastFailure` (the worker's prompt shows it), the head as `failedSha` (a worker
238
+ * that pushes nothing new has not reworked it). Reworks spent → `q:human`.
239
+ * @param {z.infer<typeof ReworkIn>} what @param {TaskCtx} ctx
240
+ */
241
+ run: async (what, ctx) => {
242
+ const issue = issueOf(ctx)
243
+ const pr = prOf(ctx)
244
+ const m = markerOf(issue)
245
+ const max = ctx.config.phases.task.maxReworks
246
+ const done = m.reworks ?? 0
247
+ if (done >= max)
248
+ return {
249
+ to: 'human',
250
+ reason: `${max} rework${max === 1 ? '' : 's'} spent on PR #${pr.number}. Last: ${what.reason}`,
251
+ outcome: 'reworks-spent',
252
+ pr: pr.number,
253
+ why: WHY.budget,
254
+ }
255
+ const at = iso(ctx.tick.now)
256
+ await landAt(task, ctx, task.entry.node, {
257
+ ...withHistory(m, {
258
+ node: 'rework',
259
+ at,
260
+ attempt: m.attempt,
261
+ outcome: what.outcome,
262
+ reason: what.reason,
263
+ pr: pr.number,
264
+ }),
265
+ phase: 'task',
266
+ attempt: 1,
267
+ reworks: done + 1,
268
+ pr: pr.number,
269
+ branch: pr.branch,
270
+ lastFailure: what.reason,
271
+ failedSha: what.failedSha,
272
+ mergeRefusal: null,
273
+ host: null,
274
+ start: null,
275
+ input: null,
276
+ })
277
+ ctx.log('info', `rework ${done + 1}/${max} of PR #${pr.number}: ${what.reason.split('\n')[0]}`, {
278
+ repo: ctx.subject.slug,
279
+ issue: issue.number,
280
+ })
281
+ return { to: 'task' }
282
+ },
283
+ }),
284
+ { queue: Q.task, running: false },
285
+ )
286
+
287
+ const CloseIn = z.object({ pr: z.number().int(), reason: z.string() })
288
+
289
+ const closePr = declare(
290
+ defineNode({
291
+ name: 'close-pr',
292
+ input: CloseIn,
293
+ output: Empty,
294
+ /** Close the PR with the reason. The issue stays where it is; an open one gets a history entry. @param {z.infer<typeof CloseIn>} input @param {TaskCtx} ctx */
295
+ run: async (input, ctx) => {
296
+ const { slug } = ctx.subject
297
+ const issue = issueOf(ctx)
298
+ await ctx.github.closePull(slug, input.pr, `${input.reason} Closed by cambium.`)
299
+ prOf(ctx).state = 'CLOSED'
300
+ if (issue.state === 'OPEN') {
301
+ const m = markerOf(issue)
302
+ await setMarker(
303
+ ctx,
304
+ slug,
305
+ issue,
306
+ withHistory(m, {
307
+ node: 'close-pr',
308
+ at: iso(ctx.tick.now),
309
+ attempt: m.attempt,
310
+ outcome: 'pr-closed',
311
+ reason: input.reason,
312
+ pr: input.pr,
313
+ }),
314
+ )
315
+ }
316
+ ctx.log('info', `closed PR #${input.pr}: ${input.reason}`, { repo: slug, issue: issue.number })
317
+ return {}
318
+ },
319
+ }),
320
+ { queue: null, running: false },
321
+ )
322
+
323
+ /** Delete a merged PR's branch once per tick. @param {TaskCtx} ctx @param {PullRequest} pr */
324
+ export async function deleteMergedBranch(ctx, pr) {
325
+ const deleted = ctx.subject.deleted ?? new Set()
326
+ if (!pr.branchExists || deleted.has(pr.branch)) return
327
+ deleted.add(pr.branch)
328
+ await ctx.github.deleteBranch(ctx.subject.slug, pr.branch)
329
+ }
330
+
331
+ const closeOut = declare(
332
+ defineNode({
333
+ name: 'close-out',
334
+ input: z.object({ pr: z.number().int() }),
335
+ output: Empty,
336
+ /** Merged: done, out of every queue, issue closed, branch deleted. @param {{ pr: number }} input @param {TaskCtx} ctx */
337
+ run: async (input, ctx) => {
338
+ const { slug } = ctx.subject
339
+ const issue = issueOf(ctx)
340
+ if (issue.state === 'OPEN') {
341
+ const m = markerOf(issue)
342
+ await landAt(
343
+ prGraph,
344
+ ctx,
345
+ 'close-out',
346
+ {
347
+ ...withHistory(m, { at: iso(ctx.tick.now), attempt: m.attempt, outcome: 'merged', pr: input.pr }),
348
+ phase: 'task',
349
+ pr: input.pr,
350
+ host: null,
351
+ start: null,
352
+ input: null,
353
+ },
354
+ { status: 'done' },
355
+ )
356
+ await ctx.github.close(slug, issue.number, `Merged in #${input.pr}. Closed by cambium.`)
357
+ issue.state = 'CLOSED'
358
+ ctx.log('info', `PR #${input.pr} merged; closed`, { repo: slug, issue: issue.number })
359
+ }
360
+ const pr = ctx.subject.pr ?? snapOf(ctx).prs.find((p) => p.number === input.pr)
361
+ if (pr) await deleteMergedBranch(ctx, pr)
362
+ return {}
363
+ },
364
+ }),
365
+ { queue: null, running: false },
366
+ )
367
+
368
+ const toHuman = declare(
369
+ defineNode({
370
+ name: 'to-human',
371
+ input: Human,
372
+ output: Empty,
373
+ /** Into the Human Queue with a reason label. @param {z.infer<typeof Human>} what @param {TaskCtx} ctx */
374
+ run: async (what, ctx) => {
375
+ const { reason, outcome, pr, why } = what
376
+ const issue = issueOf(ctx)
377
+ const m = markerOf(issue)
378
+ await landAt(
379
+ prGraph,
380
+ ctx,
381
+ 'to-human',
382
+ {
383
+ ...withHistory(m, { ...nodeAt(what), at: iso(ctx.tick.now), attempt: m.attempt, outcome, reason, pr }),
384
+ phase: 'task',
385
+ lastFailure: reason,
386
+ host: null,
387
+ start: null,
388
+ input: null,
389
+ },
390
+ { extra: [why] },
391
+ )
392
+ ctx.log('warn', `→ q:human (${why}): ${reason.split('\n')[0]}`, { repo: ctx.subject.slug, issue: issue.number })
393
+ return {}
394
+ },
395
+ }),
396
+ { queue: Q.human, running: false },
397
+ )
398
+
399
+ /** The PR graph. Bump `version` when a node is removed or renamed. */
400
+ export const prGraph = defineGraph({
401
+ name: 'pr',
402
+ version: 1,
403
+ entry: { node: 'assess', input: () => ({}) },
404
+ nodes: [assess, merge, rework, closePr, closeOut, toHuman],
405
+ edges: [
406
+ ['assess', 'close-out', merged],
407
+ ['assess', 'merge', toMerge],
408
+ ['assess', 'rework', toRework],
409
+ ['assess', 'close-pr', toClose],
410
+ ['assess', 'to-human', toHumanInbox],
411
+ ['assess', END],
412
+ ['merge', 'to-human', needsApproval],
413
+ ['merge', END],
414
+ ['rework', 'to-human', reworksSpent],
415
+ ['rework', END],
416
+ ['close-pr', END],
417
+ ['close-out', END],
418
+ ['to-human', END],
419
+ ],
420
+ })