@oakgreencc/cambium 0.0.9 → 0.0.11
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 +107 -8
- package/package.json +2 -2
- package/src/config.mjs +17 -3
- package/src/dispatch-engine.mjs +135 -0
- package/src/github.mjs +140 -19
- package/src/graph-engine.mjs +17 -3
- package/src/graphs/dispatch.mjs +453 -0
- package/src/graphs/release.mjs +438 -0
- package/src/labels.mjs +1 -0
- package/src/marker.mjs +3 -1
- package/src/phases/dispatch.mjs +145 -0
- package/src/phases/release.mjs +1 -0
- package/src/phases/task.mjs +8 -1
- package/src/tick.mjs +8 -4
- package/src/workers.mjs +86 -18
|
@@ -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/labels.mjs
CHANGED
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,
|
|
@@ -41,7 +41,9 @@
|
|
|
41
41
|
* queued?: boolean,
|
|
42
42
|
* failedSha?: string | null,
|
|
43
43
|
* lastFailure?: string | null,
|
|
44
|
+
* triage?: { title?: string, acceptance?: string[] } | null,
|
|
44
45
|
* }} Marker
|
|
46
|
+
* `triage`: what the dispatch graph's triage added when it handed the issue to `q:task`; the task prompt shows it.
|
|
45
47
|
* @typedef {{ graph: string, entryNode: string, nodes?: Iterable<string> }} QueueOwner
|
|
46
48
|
*/
|
|
47
49
|
|
package/src/phases/dispatch.mjs
CHANGED
|
@@ -1,4 +1,11 @@
|
|
|
1
1
|
// @ts-check
|
|
2
|
+
/**
|
|
3
|
+
* The Dispatch phase's parts: the triage worker's prompt, its typed result and how cambium reads it from the
|
|
4
|
+
* worker's stream-json log. The `dispatch` graph (graphs/dispatch.mjs) runs them; the legacy engine keeps the
|
|
5
|
+
* stub below and leaves `q:intake` alone.
|
|
6
|
+
*/
|
|
7
|
+
import { z } from 'zod'
|
|
8
|
+
|
|
2
9
|
/**
|
|
3
10
|
* @typedef {{ repo: string, intake: import('../github.mjs').Issue[], capacity: number, now: number }} DispatchInput
|
|
4
11
|
* @typedef {(input: DispatchInput) => Promise<{ started: number[] }>} Dispatch
|
|
@@ -10,3 +17,141 @@ export async function dispatchNotBuilt() {
|
|
|
10
17
|
}
|
|
11
18
|
|
|
12
19
|
export const DISPATCH_NOT_BUILT = 'dispatch phase is not built yet; q:intake issues wait'
|
|
20
|
+
|
|
21
|
+
/** The verdict a triage worker ends with, as the last JSON block of its final message. */
|
|
22
|
+
export const TriageResult = z
|
|
23
|
+
.object({
|
|
24
|
+
verdict: z.enum(['actionable', 'needs-human', 'duplicate']),
|
|
25
|
+
duplicateOf: z.number().int().positive().optional(),
|
|
26
|
+
reason: z.string().trim().min(1),
|
|
27
|
+
title: z.string().trim().min(1).optional(),
|
|
28
|
+
acceptance: z.array(z.string().trim().min(1)).optional(),
|
|
29
|
+
})
|
|
30
|
+
.refine((r) => r.verdict !== 'duplicate' || r.duplicateOf !== undefined, {
|
|
31
|
+
message: 'a duplicate verdict needs duplicateOf',
|
|
32
|
+
path: ['duplicateOf'],
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
/** @typedef {z.infer<typeof TriageResult>} Triage */
|
|
36
|
+
|
|
37
|
+
/** @param {z.core.$ZodIssue} i */
|
|
38
|
+
const formatIssue = (i) => (i.path.length ? `${i.path.join('.')}: ${i.message}` : i.message)
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* The JSON in a final message: its last fenced block, else the whole text, else its outermost `{…}`.
|
|
42
|
+
* @param {string} text @returns {unknown} throws a SyntaxError-like Error when there is none
|
|
43
|
+
*/
|
|
44
|
+
function jsonIn(text) {
|
|
45
|
+
const fenced = [...text.matchAll(/```[a-zA-Z]*[ \t]*\n([\s\S]*?)```/g)].map((m) => m[1])
|
|
46
|
+
const candidates = fenced.length
|
|
47
|
+
? [fenced[fenced.length - 1]]
|
|
48
|
+
: [text, text.slice(text.indexOf('{'), text.lastIndexOf('}') + 1)]
|
|
49
|
+
/** @type {unknown} */
|
|
50
|
+
let last
|
|
51
|
+
for (const c of candidates) {
|
|
52
|
+
try {
|
|
53
|
+
return JSON.parse(c.trim())
|
|
54
|
+
} catch (err) {
|
|
55
|
+
last = err
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
throw new Error(
|
|
59
|
+
`no JSON result in the final message (${/** @type {Error} */ (last)?.message ?? 'empty'}): ${clip(text)}`,
|
|
60
|
+
)
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** @param {string} s */
|
|
64
|
+
const clip = (s, n = 300) => {
|
|
65
|
+
const one = s.replace(/\s+/g, ' ').trim()
|
|
66
|
+
return one.length > n ? `${one.slice(0, n)}…` : one || '(empty)'
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* The triage verdict from a worker's stdout (`claude -p --output-format stream-json`): the last `result` event's
|
|
71
|
+
* `result` text, its JSON, validated by {@link TriageResult}. Anything else is an error saying what was wrong.
|
|
72
|
+
*
|
|
73
|
+
* @param {string} log the stdout log text
|
|
74
|
+
* @param {number} issue the triaged issue, which cannot be its own duplicate
|
|
75
|
+
* @returns {{ ok: true, result: Triage } | { ok: false, error: string }}
|
|
76
|
+
*/
|
|
77
|
+
export function readTriage(log, issue) {
|
|
78
|
+
/** @type {any} */
|
|
79
|
+
let result = null
|
|
80
|
+
for (const line of log.split('\n')) {
|
|
81
|
+
if (!line.trim()) continue
|
|
82
|
+
try {
|
|
83
|
+
const e = JSON.parse(line)
|
|
84
|
+
if (e?.type === 'result') result = e
|
|
85
|
+
} catch {}
|
|
86
|
+
}
|
|
87
|
+
if (!result) return { ok: false, error: 'no result event in the worker log (killed, crashed or truncated)' }
|
|
88
|
+
if (typeof result.result !== 'string')
|
|
89
|
+
return { ok: false, error: `the worker ended without a final message (${result.subtype ?? 'no subtype'})` }
|
|
90
|
+
/** @type {unknown} */
|
|
91
|
+
let json
|
|
92
|
+
try {
|
|
93
|
+
json = jsonIn(result.result)
|
|
94
|
+
} catch (err) {
|
|
95
|
+
return { ok: false, error: /** @type {Error} */ (err).message }
|
|
96
|
+
}
|
|
97
|
+
const parsed = TriageResult.safeParse(json)
|
|
98
|
+
if (!parsed.success)
|
|
99
|
+
return { ok: false, error: `invalid triage result: ${parsed.error.issues.map(formatIssue).join('; ')}` }
|
|
100
|
+
if (parsed.data.verdict === 'duplicate' && parsed.data.duplicateOf === issue)
|
|
101
|
+
return { ok: false, error: `invalid triage result: duplicateOf: #${issue} cannot duplicate itself` }
|
|
102
|
+
return { ok: true, result: parsed.data }
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* The triage worker's prompt: one issue, one verdict. Adapted from the OpenRig seed's `inbox` and `intent-lead`
|
|
107
|
+
* roles and its culture (unattended, never ask and wait, CI is the acceptance gate, never `gh`).
|
|
108
|
+
*
|
|
109
|
+
* @param {{
|
|
110
|
+
* repo: string, baseBranch: string, issue: import('../github.mjs').Issue,
|
|
111
|
+
* queued: { number: number, title: string, labels: string[] }[], agentsMd: string | null,
|
|
112
|
+
* }} input
|
|
113
|
+
*/
|
|
114
|
+
export function triagePrompt({ repo, baseBranch, issue, queued, agentsMd }) {
|
|
115
|
+
const others = queued
|
|
116
|
+
.filter((q) => q.number !== issue.number)
|
|
117
|
+
.map((q) => `- #${q.number} ${q.title} (${q.labels.filter((l) => l.startsWith('q:')).join(', ') || 'no queue'})`)
|
|
118
|
+
.join('\n')
|
|
119
|
+
return `You are a triage worker started by cambium, the scheduler, in a read-only checkout of ${repo} at origin/${baseBranch}.
|
|
120
|
+
Nobody is watching this session and nobody will answer a question: never ask one and wait. Where you would ask a human, that is your verdict (needs-human).
|
|
121
|
+
|
|
122
|
+
Your one job: decide what happens to GitHub issue #${issue.number} (below), which is waiting in the intake queue. You do not do the work. You do not edit files, commit, publish, comment, label or close anything; cambium makes every move on your verdict.
|
|
123
|
+
|
|
124
|
+
Verdicts:
|
|
125
|
+
- actionable: a worker could do it unattended from what is written (plus what you add), and would know when it is done. It goes to the task queue. When the issue lacks a clear task or checkable acceptance criteria, give \`title\` (an imperative task title) and \`acceptance\` (checks a reviewer can verify; CI green is always required, so do not list only that). cambium posts them on the issue and hands them to the task worker.
|
|
126
|
+
- needs-human: too foggy to ticket; a decision only a human can make (direction, priority, money, access, policy); information you cannot find; or work that is not a code change in this repository. \`reason\` says exactly what the human must decide or supply.
|
|
127
|
+
- duplicate: the same work as another issue, open or closed. \`duplicateOf\` is that issue's number (never #${issue.number}); \`reason\` says why they are the same.
|
|
128
|
+
|
|
129
|
+
How to look:
|
|
130
|
+
- Read the code here (Read, Glob, Grep) to judge what the change touches and whether it already exists.
|
|
131
|
+
- Read an issue with \`graft issue read <n>\`; search with \`graft api GET '/search/issues?q=repo:${repo}+is:issue+<words>'\`. Never \`gh\`.
|
|
132
|
+
- Be quick: a verdict, not an investigation. When in doubt between actionable and needs-human, choose needs-human.
|
|
133
|
+
|
|
134
|
+
End your final message with exactly one fenced JSON block, and nothing after it:
|
|
135
|
+
\`\`\`json
|
|
136
|
+
{ "verdict": "actionable" | "needs-human" | "duplicate", "duplicateOf": 123, "reason": "…", "title": "…", "acceptance": ["…"] }
|
|
137
|
+
\`\`\`
|
|
138
|
+
\`duplicateOf\` only for duplicate; \`title\` and \`acceptance\` only for actionable, and optional. A missing or malformed block sends the issue to a human with the error.
|
|
139
|
+
${others ? `\nOther issues in cambium's queues right now:\n${others}\n` : ''}
|
|
140
|
+
--- Issue #${issue.number}: ${issue.title} (${issue.url})
|
|
141
|
+
${issue.body}
|
|
142
|
+
${agentsMd ? `\n--- AGENTS.md (the contract a task worker will follow)\n${agentsMd}` : ''}`
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* The comment triage leaves on an actionable issue.
|
|
147
|
+
* @param {{ reason: string, title?: string, acceptance?: string[] }} t
|
|
148
|
+
*/
|
|
149
|
+
export function triageComment({ reason, title, acceptance }) {
|
|
150
|
+
return [
|
|
151
|
+
`**Triage: actionable.** ${reason}`,
|
|
152
|
+
...(title ? ['', `**Task:** ${title}`] : []),
|
|
153
|
+
...(acceptance?.length ? ['', '**Acceptance checks**', ...acceptance.map((a) => `- [ ] ${a}`)] : []),
|
|
154
|
+
'',
|
|
155
|
+
'_Triaged by cambium; the task worker gets these with the issue body._',
|
|
156
|
+
].join('\n')
|
|
157
|
+
}
|
package/src/phases/release.mjs
CHANGED
|
@@ -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/phases/task.mjs
CHANGED
|
@@ -32,7 +32,14 @@ ${
|
|
|
32
32
|
}${marker.lastFailure ? `\nWhy the last attempt failed:\n\`\`\`\n${marker.lastFailure}\n\`\`\`\n` : ''}${history ? `\nHistory of this issue:\n${history}\n` : ''}
|
|
33
33
|
--- Issue #${issue.number}: ${issue.title} (${issue.url})
|
|
34
34
|
${issue.body}
|
|
35
|
-
${agentsMd ? `\n--- AGENTS.md\n${agentsMd}` : ''}`
|
|
35
|
+
${triageSection(marker.triage)}${agentsMd ? `\n--- AGENTS.md\n${agentsMd}` : ''}`
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** What triage added (dispatch graph), when it added anything. @param {import('../marker.mjs').Marker['triage']} t */
|
|
39
|
+
function triageSection(t) {
|
|
40
|
+
if (!t || (!t.title && !t.acceptance?.length)) return ''
|
|
41
|
+
const checks = (t.acceptance ?? []).map((a) => `- [ ] ${a}`).join('\n')
|
|
42
|
+
return `\n--- From triage (cambium's dispatch, also posted on the issue)\n${t.title ? `Task: ${t.title}\n` : ''}${checks ? `Acceptance checks:\n${checks}\n` : ''}`
|
|
36
43
|
}
|
|
37
44
|
|
|
38
45
|
/**
|