@oakgreencc/cambium 0.0.37 → 0.0.39

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
@@ -40,11 +40,11 @@ Every command takes `--config <file>`; the default is `$CAMBIUM_CONFIG`, then `~
40
40
 
41
41
  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.
42
42
 
43
- 1. **Read.** One GraphQL query per repo (`graft graphql`): open issues with any `q:` label (100 per page; more pages follow the cursor, so a busy queue's newest issues are not invisible), open and recently merged PRs on `agent/*` with their check rollup, merge-queue state, `mergeable`, `reviewDecision` 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 (also the issue an open PR that closes none names by its branch, `agent/<n>-…`, for the [reaper](#upkeep)). A worker's PR that names no issue (found by its branch) gets `Closes #n` added at submission.
43
+ 1. **Read.** One GraphQL query per repo (`graft graphql`): open issues with any `q:` label (100 per page; more pages follow the cursor, so a busy queue's newest issues are not invisible), open and recently merged PRs on `agent/*` with their check rollup, merge-queue state, `mergeable`, `reviewDecision` and the issues they close. Each issue's newest 20 comments come with their time and author type, for [human replies](#the-dispatch-graph). 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 (also the issue an open PR that closes none names by its branch, `agent/<n>-…`, for the [reaper](#upkeep)). A worker's PR that names no issue (found by its branch) gets `Closes #n` added at submission.
44
44
  2. **Reconcile.** For each tracked worker: alive and under its wall-clock cap → nothing. Over the cap → terminate it: every process below `claude` (its Bash tools, a test run) is SIGKILLed at once, and `claude` gets SIGTERM, on which Claude Code ends its interaction span and flushes its exporter (a bare SIGKILL left `claude_code.*` spans orphaned under a root that was never exported). It usually exits within a second; still alive 30 s past the cap (and at least one tick later) → kill its process group and every descendant (Claude Code runs each Bash command in a group of its own, so a group kill alone left a test run loading the next attempt). 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 and no process has its cwd inside it (`lsof`; the worktree's own nx daemon excepted), else kept with a `warn` saying why. Teardown stops the worktree's nx daemon (nx keys each daemon to its workspace root, so no other checkout's is touched; left running, it served the next client from a deleted tree until `nx reset`), moves the tree to `<paths.home>/trash` with one rename, prunes git's record, and erases the trash in the background: a worktree with CocoaPods in it took `git worktree remove` past the step timeout.
45
45
  3. **Watch** (no agent). Graph engine: the [PR graph](#the-pr-graph), once per tick for each agent PR whose CI has settled and whose issue has no Task queued or running: merge, rework, close, or `q:human`. Legacy, 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`.
46
46
  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.
47
- 5. **Schedule.** Start Task workers for `q:task` issues without `running`, by priority label then age, up to `phases.task.cap` counted from live workers. A task requeued earlier in the same tick can start in that tick. Then, with `engine: "graph"` and `phases.dispatch.cap > 0`, start triage workers for `q:intake` issues the same way ([the dispatch graph](#the-dispatch-graph)).
47
+ 5. **Schedule.** Start Task workers for `q:task` issues without `running`, by priority label then age, up to `phases.task.cap` counted from live workers. A task requeued earlier in the same tick can start in that tick. Then, with `engine: "graph"` and `phases.dispatch.cap > 0`, first wake `q:human` and parked intake issues that have a human reply, then start triage workers for `q:intake` issues the same way ([the dispatch graph](#the-dispatch-graph)).
48
48
  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.
49
49
  7. **Upkeep** (graph engine). The hourly [reaper](#upkeep) of untracked agent PRs, then the daily [re-triage](#upkeep) of `q:human`.
50
50
  8. **Heartbeat.** Write the state file.
@@ -442,6 +442,7 @@ flowchart TD
442
442
  - **Defer, not a human.** A verdict that hangs on something a machine can check later (a CD run that has not happened, a release, a merge, a deploy) is `defer`, never `needs-human`: asking a human to verify what a machine can is what the factory exists to avoid. The issue rests at `deferred` with `deferUntil` (now + `recheckHours`, else `phases.dispatch.deferHours`, default 6) and `deferReason` in its marker; Schedule skips it until then, and the next triage gets the reason in its prompt ("check it now"). A defer is not a failed attempt. A deferred issue whose GitHub "blocked by" issues are all closed, at least one after it was deferred, is triaged again at the next tick instead of waiting for `deferUntil`. After `phases.dispatch.maxDefers` (default 8) it goes to `q:human` + `why:triage` with the last reason. While it waits it carries `wait:deferred`.
443
443
  - **Blocked by issues, not a timer.** A verdict that waits on other issues is `blocked` with `blockedBy: [n, …]`. cambium adds each as a GitHub "blocked by" link on the issue when it is missing, then parks it at `blocked` with `wait:blocked`, the open blockers in the marker's `blockedBy` and no `deferUntil`. Schedule never triages an intake issue with an open `blockedBy` issue, whoever linked it: one not yet at `blocked` (new, or deferred) is parked there first. The tick after the last blocker closes, the label comes off and the issue is triaged again, its earlier reason in the prompt. A blocked wait is not a defer and does not count toward `maxDefers`; a `blocked` verdict none of whose issues is open (closed, or the link failed) is a defer.
444
444
  - **`wait:*` labels.** Intake holds two kinds of issue: awaiting triage, and parked by it. `wait:deferred` and `wait:blocked` mark the parked ones (canopy shows them apart from Intake); Schedule adds or removes them each tick to match the marker and the blockers, and any queue move drops them.
445
+ - **A human reply wakes it.** Canopy's Inbox is read-only, so a human answers by commenting on the issue. A _human reply_ is a comment written after the issue entered its current state (the later of the marker's `enteredAt` and its last history `at`) whose author is not `graft.botLogin`, not the login that wrote the state comment, and not a `Bot`-type account; a comment carrying a state marker never counts. Read takes each issue's newest 20 comments with their `createdAt` and author type (`src/human-reply.mjs`). At Schedule, before parking: a `q:human` issue with any `why:*` but `why:approve` (as re-triage), no `running` and no tracked worker, with a human reply, goes back to `q:intake` without its `why:*`, at `start-triage`, attempt 1, history kept with a `human-reply` entry, and is triaged in the same tick when a slot is free. A parked issue (`deferred` / `blocked`) with a human reply is triaged now, whatever its `deferUntil` or open blockers: the human may be saying it is not waiting on anything. The triage prompt quotes the replies since the issue last waited (author, time, body; the newest 5, each cut at 2000 characters) as the answer to the needs-human, defer or blocked reason, which it quotes too; the rubric says such a reply usually makes it actionable, folded into `title` / `acceptance`, and needs-human again (saying what is still missing) if it leaves the question open. The marker carries that context (`reply`) until triage lands a verdict. No loops: cambium's own comments never count, and the verdict starts a new state, so a triage that answers needs-human again rests until the next human reply or the daily re-triage. The daily re-triage and a hand move to `q:intake` get the same quoting.
445
446
  - **Leaving intake.** If the issue is closed or relabelled while triage runs, the verdict is dropped and the checkout removed.
446
447
  - **Tracing.** Wired as in the task graph (see [Tracing](#tracing)): the driver's node and wait spans under a `cambium.issue` root that continues mycelium's intake span from the issue body, the triage worker's `TRACEPARENT` (its `start-triage` span), and its stream-json spans when `triaging` ends.
447
448
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oakgreencc/cambium",
3
- "version": "0.0.37",
3
+ "version": "0.0.39",
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.11"
54
+ "@oakgreencc/mycelium": "0.0.12"
55
55
  },
56
56
  "devDependencies": {
57
57
  "@langchain/core": "^1.4.1",
@@ -5,7 +5,10 @@
5
5
  *
6
6
  * - Reconcile: every tracked triage worker's issue at `triaging`.
7
7
  * - Sweep: a stale `running` lease on a `q:intake` issue runs `retry-triage`.
8
- * - Schedule: first parks: a `q:intake` issue without a lease that has an open GitHub `blockedBy` issue goes to the
8
+ * - Schedule: first wakes: a `q:human` issue (not `why:approve`) without a lease that has a human reply since it
9
+ * entered its state (human-reply.mjs) goes back to `q:intake` at `start-triage`, attempt 1, history kept (outcome
10
+ * `human-reply`); a parked intake issue (`deferred` / `blocked`) with one is triaged now, whatever its blockers or
11
+ * `deferUntil`. Then parks: a `q:intake` issue without a lease that has an open GitHub `blockedBy` issue goes to the
9
12
  * `blocked` node (`wait:blocked`) if it is not there yet, and every other one gets the `wait:*` label its marker
10
13
  * calls for (`wait:deferred` while its `deferUntil` is ahead, none once due or unblocked). Then `q:intake` issues
11
14
  * without a lease, by priority then age, up to `phases.dispatch.cap` counted from live triage workers, skipping
@@ -16,8 +19,10 @@
16
19
  */
17
20
  import { advance } from './graph/index.mjs'
18
21
  import { dispatch, lostLeaseOf, nodeOf, openBlockers } from './graphs/dispatch.mjs'
19
- import { setLabels } from './issue-state.mjs'
20
- import { byPriorityThenAge, Q, RUNNING, WAIT } from './labels.mjs'
22
+ import { iso, key, markerOf, setLabels, setMarker } from './issue-state.mjs'
23
+ import { byPriorityThenAge, move, Q, RUNNING, WAIT, WHY } from './labels.mjs'
24
+ import { newMarker, withHistory } from './marker.mjs'
25
+ import { humanReplies, stateSince } from './human-reply.mjs'
21
26
  import { each, staleLeases } from './tick.mjs'
22
27
  import { markerTrace, turnTracer } from './tracing.mjs'
23
28
 
@@ -124,8 +129,7 @@ export function intakeCandidates(deps, ctx) {
124
129
  issue.labels.includes(Q.intake) &&
125
130
  !issue.labels.includes(RUNNING) &&
126
131
  !store.worker(slug, issue.number) &&
127
- !deferredPast(issue, ctx.now) &&
128
- !openBlockers(issue).length
132
+ (replied(deps, issue) || (!deferredPast(issue, ctx.now) && !openBlockers(issue).length))
129
133
  )
130
134
  candidates.push({ slug, issue, snap })
131
135
  const order = byPriorityThenAge(config.priorityLabels)
@@ -183,6 +187,7 @@ async function park(deps, ctx) {
183
187
  restingIntake(deps, ctx),
184
188
  async (c) => {
185
189
  const { issue } = c
190
+ if (replied(deps, issue)) return
186
191
  const open = openBlockers(issue)
187
192
  const m = issue.stateComment?.marker
188
193
  const atBlocked = m?.graph === dispatch.name && m.node === 'blocked'
@@ -216,9 +221,70 @@ const unblockedSince = (blockers, since) =>
216
221
  blockers.every((b) => b.state === 'CLOSED') &&
217
222
  blockers.some((b) => !since || (!!b.closedAt && Date.parse(b.closedAt) > Date.parse(since)))
218
223
 
224
+ /**
225
+ * Parked at `deferred` or `blocked` with a human reply since: the human may be saying it is not waiting on anything,
226
+ * so triage looks now. Starting triage moves the marker on, so the same reply wakes it once.
227
+ * @param {Deps} deps @param {import('./github.mjs').Issue} issue
228
+ */
229
+ function replied(deps, issue) {
230
+ const m = issue.stateComment?.marker
231
+ if (!(m?.graph === dispatch.name && (m.node === 'deferred' || m.node === 'blocked'))) return false
232
+ return humanReplies(issue, { since: stateSince(m), botLogin: deps.config.graft.botLogin }).length > 0
233
+ }
234
+
235
+ /**
236
+ * Wake: every `q:human` issue (any `why:*` but `why:approve`, as re-triage) with no lease, no tracked worker and a
237
+ * human reply since it entered its state goes back to `q:intake` at `start-triage`, attempt 1, its history kept with
238
+ * a `human-reply` entry and the `reply` context the triage prompt quotes. The new state starts now, so the same
239
+ * reply never wakes it again: a triage that answers needs-human again rests until the next reply.
240
+ * @param {Deps} deps @param {Ctx} ctx
241
+ */
242
+ async function wake(deps, ctx) {
243
+ const botLogin = deps.config.graft.botLogin
244
+ for (const [slug, snap] of ctx.snaps)
245
+ await each(
246
+ deps,
247
+ [...snap.issues.values()].filter(
248
+ (i) =>
249
+ i.state === 'OPEN' &&
250
+ i.labels.includes(Q.human) &&
251
+ !i.labels.includes(WHY.approve) &&
252
+ !i.labels.includes(RUNNING) &&
253
+ !deps.store.worker(slug, i.number) &&
254
+ !ctx.touched.has(key(slug, i.number)),
255
+ ),
256
+ async (issue) => {
257
+ const m = markerOf(issue)
258
+ const since = stateSince(issue.stateComment?.marker)
259
+ const replies = humanReplies(issue, { since, botLogin })
260
+ if (!since || !replies.length) return
261
+ const at = iso(ctx.now)
262
+ const who = [...new Set(replies.map((r) => `@${r.author}`))].join(', ')
263
+ await setMarker(deps, slug, issue, {
264
+ ...newMarker({
265
+ graph: dispatch.name,
266
+ graphVersion: dispatch.version,
267
+ node: dispatch.entry.node,
268
+ phase: 'dispatch',
269
+ enteredAt: at,
270
+ traceparent: m.traceparent,
271
+ history: withHistory(m, { at, attempt: m.attempt, outcome: 'human-reply', reason: `reply from ${who}` })
272
+ .history,
273
+ }),
274
+ reply: { since, question: m.lastFailure ?? m.history.at(-1)?.reason ?? null },
275
+ })
276
+ await setLabels(deps, slug, issue, move(issue.labels, Q.intake))
277
+ ctx.touched.add(key(slug, issue.number))
278
+ deps.log('info', `human reply from ${who}: q:human → q:intake for triage`, { repo: slug, issue: issue.number })
279
+ },
280
+ (issue) => ({ repo: slug, issue: issue.number }),
281
+ )
282
+ }
283
+
219
284
  /** @param {Deps} deps @param {Ctx} ctx */
220
285
  async function schedule(deps, ctx) {
221
286
  if (deps.config.phases.dispatch.cap <= 0) return
287
+ await wake(deps, ctx)
222
288
  await park(deps, ctx)
223
289
  await each(
224
290
  deps,
package/src/github.mjs CHANGED
@@ -13,9 +13,13 @@ import { BASE_FIELDS, baseHealthOf } from './base-health.mjs'
13
13
  /**
14
14
  * @typedef {{
15
15
  * number: number, title: string, url: string, state: 'OPEN' | 'CLOSED', createdAt: string, body: string,
16
- * labels: string[], stateComment: { id: number, marker: import('./marker.mjs').Marker } | null,
17
- * blockedBy: Blocker[],
16
+ * labels: string[], stateComment: { id: number, marker: import('./marker.mjs').Marker, author?: string | null } | null,
17
+ * blockedBy: Blocker[], comments?: Comment[],
18
18
  * }} Issue
19
+ * `stateComment.author`: the login that wrote the state comment (cambium's). `comments`: the newest 20, oldest
20
+ * first, for human-reply detection (human-reply.mjs).
21
+ * @typedef {{ author: string | null, bot: boolean, createdAt: string, body: string }} Comment
22
+ * `bot`: GitHub says the author is a `Bot` (an App).
19
23
  * @typedef {{ number: number, state: 'OPEN' | 'CLOSED', closedAt: string | null }} Blocker
20
24
  * An issue GitHub records as blocking this one (the "blocked by" relationship).
21
25
  * @typedef {{ name: string, url: string | null, summary: string }} FailingCheck
@@ -108,6 +112,7 @@ fragment I on Issue {
108
112
  labels(first: 30) { nodes { name } }
109
113
  blockedBy(first: 20) { nodes { number state closedAt } }
110
114
  comments(first: 100) { nodes { databaseId body author { login } } }
115
+ recent: comments(last: 20) { nodes { createdAt body author { login __typename } } }
111
116
  }
112
117
  fragment P on PullRequest {
113
118
  number url title state createdAt headRefName baseRefName headRefOid reviewDecision
@@ -151,13 +156,19 @@ const FAILED = new Set(['FAILURE', 'ERROR', 'TIMED_OUT', 'CANCELLED', 'ACTION_RE
151
156
  /**
152
157
  * The first comment holding a marker (from `botLogin` only, when set). Issues and PRs alike.
153
158
  * @param {any} n an issue or PR node with `comments` @param {string | null} botLogin
154
- * @returns {{ id: number, marker: import('./marker.mjs').Marker } | null}
159
+ * @returns {{ id: number, marker: import('./marker.mjs').Marker, author: string | null } | null}
155
160
  */
156
161
  function stateCommentOf(n, botLogin) {
157
162
  const comment = (n.comments?.nodes ?? []).find(
158
163
  (/** @type {any} */ c) => parseMarker(c.body) && (!botLogin || c.author?.login === botLogin),
159
164
  )
160
- return comment ? { id: comment.databaseId, marker: /** @type {any} */ (parseMarker(comment.body)) } : null
165
+ return comment
166
+ ? {
167
+ id: comment.databaseId,
168
+ marker: /** @type {any} */ (parseMarker(comment.body)),
169
+ author: comment.author?.login ?? null,
170
+ }
171
+ : null
161
172
  }
162
173
 
163
174
  /** @param {any} n @returns {string[]} */
@@ -225,6 +236,12 @@ function toIssue(n, botLogin) {
225
236
  state: b.state === 'OPEN' ? 'OPEN' : 'CLOSED',
226
237
  closedAt: b.closedAt ?? null,
227
238
  })),
239
+ comments: (n.recent?.nodes ?? []).filter(Boolean).map((/** @type {any} */ c) => ({
240
+ author: c.author?.login ?? null,
241
+ bot: c.author?.__typename === 'Bot',
242
+ createdAt: c.createdAt ?? '',
243
+ body: c.body ?? '',
244
+ })),
228
245
  }
229
246
  }
230
247
 
@@ -14,6 +14,7 @@ import { iso, key, markerOf, MIN, setLabels, setMarker } from '../issue-state.mj
14
14
  import { move, Q, WAIT, WHY } from '../labels.mjs'
15
15
  import { newMarker, withHistory } from '../marker.mjs'
16
16
  import { readTriage, TriageResult, triageComment, triagePrompt } from '../phases/dispatch.mjs'
17
+ import { humanReplies, quoted, replyContextOf } from '../human-reply.mjs'
17
18
  import { traceWorker } from '../tracing.mjs'
18
19
  import { stopOverdue } from '../workers.mjs'
19
20
  import { task } from './task.mjs'
@@ -30,6 +31,8 @@ import { task } from './task.mjs'
30
31
 
31
32
  /** The nodes an issue in `q:intake` can rest at; a marker elsewhere starts triage over at attempt 1. */
32
33
  const INTAKE_NODES = new Set(['start-triage', 'triaging', 'retry-triage', 'deferred', 'blocked'])
34
+ /** The nodes before a verdict: the marker keeps its `reply` context through them; any other node drops it. */
35
+ const PRE_VERDICT = new Set(['start-triage', 'triaging', 'retry-triage'])
33
36
 
34
37
  /** The open issues among `issue`'s GitHub `blockedBy` links. @param {Issue} issue */
35
38
  export const openBlockers = (issue) => (issue.blockedBy ?? []).filter((b) => b.state === 'OPEN').map((b) => b.number)
@@ -64,6 +67,7 @@ async function land(ctx, node, marker, { extra = [], status = 'waiting' } = {})
64
67
  const decl = nodeOf(node)
65
68
  await setMarker(ctx, slug, issue, {
66
69
  ...graphMarker(marker),
70
+ ...(PRE_VERDICT.has(node) ? {} : { reply: null }),
67
71
  graph: dispatch.name,
68
72
  graphVersion: dispatch.version,
69
73
  phase: 'dispatch',
@@ -154,8 +158,12 @@ const startTriage = declare(
154
158
  } catch (err) {
155
159
  return { to: 'retry', reason: `could not start triage: ${errText(err)}`, outcome: 'spawn-failed' }
156
160
  }
161
+ // A human reply since the issue last waited (on a needs-human, defer or blocked reason) is the answer to it.
162
+ const reply = m0.reply ?? replyContextOf(markerOf(issue))
163
+ const replies = reply ? quoted(humanReplies(issue, { since: reply.since, botLogin: config.graft.botLogin })) : []
157
164
  await land(ctx, 'triaging', {
158
165
  ...m0,
166
+ reply,
159
167
  deferUntil: null,
160
168
  host: config.host,
161
169
  start: iso(ctx.tick.now),
@@ -189,8 +197,12 @@ const startTriage = declare(
189
197
  agentsMd,
190
198
  deferHours: caps.deferHours,
191
199
  deferred:
192
- m0.deferReason && !m0.blockedBy?.length ? { count: m0.defers ?? 0, reason: m0.deferReason } : null,
193
- blocked: m0.blockedBy?.length ? { by: m0.blockedBy, reason: m0.deferReason ?? '' } : null,
200
+ !replies.length && m0.deferReason && !m0.blockedBy?.length
201
+ ? { count: m0.defers ?? 0, reason: m0.deferReason }
202
+ : null,
203
+ blocked:
204
+ !replies.length && m0.blockedBy?.length ? { by: m0.blockedBy, reason: m0.deferReason ?? '' } : null,
205
+ replied: replies.length ? { question: reply?.question ?? null, replies } : null,
194
206
  }),
195
207
  })
196
208
  } catch (err) {
@@ -0,0 +1,78 @@
1
+ // @ts-check
2
+ /**
3
+ * Human replies: a comment on an issue, written after the issue entered its current state, by someone who is
4
+ * neither cambium nor a bot. A human answers a `q:human` question (or says a parked issue is not really blocked) by
5
+ * commenting; cambium sends the issue back to triage at once and quotes the reply in the triage prompt
6
+ * (dispatch-engine.mjs `wake`, graphs/dispatch.mjs `start-triage`).
7
+ */
8
+ import { parseMarker } from './marker.mjs'
9
+
10
+ /**
11
+ * @typedef {import('./github.mjs').Issue} Issue
12
+ * @typedef {import('./github.mjs').Comment} Comment
13
+ * @typedef {import('./marker.mjs').Marker} Marker
14
+ * @typedef {{ since: string, question: string | null }} ReplyContext
15
+ * What a reply answers: the state's start (replies after it count) and the reason the issue was waiting for.
16
+ */
17
+
18
+ /** A reply quoted in the triage prompt is cut to this many characters. */
19
+ export const REPLY_CHARS = 2000
20
+ /** At most this many replies are quoted, the newest. */
21
+ export const REPLIES_KEPT = 5
22
+
23
+ /**
24
+ * When the marker's issue entered its current state: the later of `enteredAt` and the last history `at` (a
25
+ * stage-era write can leave an old `enteredAt` behind a newer history entry). Null without either.
26
+ * @param {Marker | null | undefined} m @returns {string | null}
27
+ */
28
+ export function stateSince(m) {
29
+ if (!m) return null
30
+ const times = [m.enteredAt, m.history.at(-1)?.at].filter((t) => t && Number.isFinite(Date.parse(t)))
31
+ if (!times.length) return null
32
+ return /** @type {string} */ (
33
+ times.reduce((a, b) => (Date.parse(/** @type {string} */ (b)) > Date.parse(/** @type {string} */ (a)) ? b : a))
34
+ )
35
+ }
36
+
37
+ /**
38
+ * The human replies on `issue` written after `since`, oldest first. Never cambium's: not by `botLogin`, not by the
39
+ * login that wrote the state comment, not a `Bot`-type author, and not a comment carrying a state marker. No `since`:
40
+ * none (nothing to be a reply to).
41
+ * @param {Issue} issue @param {{ since: string | null, botLogin?: string | null }} o @returns {Comment[]}
42
+ */
43
+ export function humanReplies(issue, { since, botLogin = null }) {
44
+ if (!since) return []
45
+ const after = Date.parse(since)
46
+ if (!Number.isFinite(after)) return []
47
+ const self = new Set([botLogin, issue.stateComment?.author].filter(Boolean))
48
+ return (issue.comments ?? []).filter(
49
+ (c) => !!c.author && !c.bot && !self.has(c.author) && !parseMarker(c.body) && Date.parse(c.createdAt) > after,
50
+ )
51
+ }
52
+
53
+ /**
54
+ * The context a triage after `m` quotes replies against, or null when `m` is not waiting on anything: the
55
+ * dispatch graph's `deferred` / `blocked` (the defer or blocked reason), or any `to-human` (the needs-human reason).
56
+ * @param {Marker | null | undefined} m @returns {ReplyContext | null}
57
+ */
58
+ export function replyContextOf(m) {
59
+ if (!m || m.status === 'done') return null
60
+ const since = stateSince(m)
61
+ if (!since) return null
62
+ if (m.graph === 'dispatch' && (m.node === 'deferred' || m.node === 'blocked'))
63
+ return { since, question: m.deferReason ?? m.history.at(-1)?.reason ?? null }
64
+ if (m.node === 'to-human') return { since, question: m.lastFailure ?? m.history.at(-1)?.reason ?? null }
65
+ return null
66
+ }
67
+
68
+ /**
69
+ * The replies as the triage prompt quotes them: the newest {@link REPLIES_KEPT}, each cut to {@link REPLY_CHARS}.
70
+ * @param {Comment[]} replies @returns {{ author: string, at: string, body: string }[]}
71
+ */
72
+ export function quoted(replies) {
73
+ return replies.slice(-REPLIES_KEPT).map((c) => ({
74
+ author: c.author ?? 'unknown',
75
+ at: c.createdAt,
76
+ body: c.body.length > REPLY_CHARS ? `${c.body.slice(0, REPLY_CHARS)}… (cut)` : c.body,
77
+ }))
78
+ }
package/src/marker.mjs CHANGED
@@ -48,12 +48,15 @@
48
48
  * deferUntil?: string | null,
49
49
  * deferReason?: string | null,
50
50
  * blockedBy?: number[] | null,
51
+ * reply?: { since: string, question: string | null } | null,
51
52
  * }} Marker
52
53
  * `mergeRefusal`: the last `graft pr merge` cambium was refused (PR graph `merge`), and on which head.
53
54
  * `reworks`: how many times the PR graph sent this issue's PR back to a worker.
54
55
  * `defers`, `deferUntil`, `deferReason`: the dispatch graph's `deferred` node: how many times triage deferred, until
55
56
  * when, and what the next triage should check. At the `blocked` node `deferReason` is why and `blockedBy` the open
56
57
  * GitHub `blockedBy` issues it waits on (no `deferUntil`).
58
+ * `reply`: while triage is pending or running, what a human reply answers (human-reply.mjs): human comments after
59
+ * `since` are quoted in the triage prompt as the answer to `question`. Cleared when triage lands a verdict.
57
60
  * `triage`: what the dispatch graph's triage added when it handed the issue to `q:task`; the task prompt shows it.
58
61
  * @typedef {{ graph: string, entryNode: string, nodes?: Iterable<string> }} QueueOwner
59
62
  */
@@ -119,8 +119,10 @@ export function readTriage(log, issue) {
119
119
  * queued: { number: number, title: string, labels: string[] }[], agentsMd: string | null,
120
120
  * deferred?: { count: number, reason: string } | null, deferHours?: number,
121
121
  * blocked?: { by: number[], reason: string } | null,
122
+ * replied?: { question: string | null, replies: { author: string, at: string, body: string }[] } | null,
122
123
  * }} input
123
- * `blocked`: an earlier triage parked it on these issues, all closed now.
124
+ * `blocked`: an earlier triage parked it on these issues, all closed now. `replied`: a human commented since the
125
+ * issue last waited; `question` is what it waited on (the needs-human, defer or blocked reason).
124
126
  */
125
127
  export function triagePrompt({
126
128
  repo,
@@ -131,6 +133,7 @@ export function triagePrompt({
131
133
  deferred = null,
132
134
  deferHours = 6,
133
135
  blocked = null,
136
+ replied = null,
134
137
  }) {
135
138
  const others = queued
136
139
  .filter((q) => q.number !== issue.number)
@@ -154,6 +157,7 @@ How to look:
154
157
  - First, has it already been done? Its comments (\`graft api GET /repos/${repo}/issues/${issue.number}/comments\`) and its timeline (\`graft api GET '/repos/${repo}/issues/${issue.number}/timeline?per_page=100'\`: cross-referenced PRs, and whether they merged) often say so. A merged PR whose change is on ${baseBranch}, and nothing left of the issue, is obsolete; a PR still open or in CI is defer.
155
158
  - Does it already wait on other issues? Its GitHub "blocked by" links: \`graft api GET /repos/${repo}/issues/${issue.number}/dependencies/blocked_by\`. An open one, or prose naming an open issue it needs first, is blocked.
156
159
  - Read an issue with \`graft issue read <n>\`; search with \`graft api GET '/search/issues?q=repo:${repo}+is:issue+<words>'\`. Never \`gh\`.
160
+ - A human reply (quoted below, when there is one) answering the open question usually makes the issue actionable: fold the answer into \`title\` and \`acceptance\` so the task worker gets it with the issue. If the reply leaves the question open, the verdict is needs-human again, and \`reason\` says what is still missing.
157
161
  - Be quick: a verdict, not an investigation. When in doubt whether the work is clear enough to do, choose needs-human; when in doubt whether something is true, check it, or defer until it can be checked.
158
162
 
159
163
  End your final message with exactly one fenced JSON block, and nothing after it:
@@ -161,12 +165,27 @@ End your final message with exactly one fenced JSON block, and nothing after it:
161
165
  { "verdict": "actionable" | "needs-human" | "duplicate" | "obsolete" | "defer" | "blocked", "duplicateOf": 123, "blockedBy": [124], "recheckHours": 6, "reason": "…", "title": "…", "acceptance": ["…"] }
162
166
  \`\`\`
163
167
  \`duplicateOf\` only for duplicate; \`blockedBy\` only for blocked; \`recheckHours\` only for defer, and optional; \`title\` and \`acceptance\` only for actionable, and optional. A missing or malformed block sends the issue to a human with the error.
164
- ${deferred ? `\nThis is re-triage ${deferred.count + 1}: an earlier triage deferred it to check this:\n${deferred.reason}\nCheck it now. If it still cannot be checked, defer again.\n` : ''}${blocked ? `\nAn earlier triage found it blocked by ${blocked.by.map((n) => `#${n}`).join(', ')}, now closed:\n${blocked.reason}\nJudge it again now that they are done.\n` : ''}${others ? `\nOther issues in cambium's queues right now:\n${others}\n` : ''}
168
+ ${deferred ? `\nThis is re-triage ${deferred.count + 1}: an earlier triage deferred it to check this:\n${deferred.reason}\nCheck it now. If it still cannot be checked, defer again.\n` : ''}${blocked ? `\nAn earlier triage found it blocked by ${blocked.by.map((n) => `#${n}`).join(', ')}, now closed:\n${blocked.reason}\nJudge it again now that they are done.\n` : ''}${replied ? repliedNote(replied) : ''}${others ? `\nOther issues in cambium's queues right now:\n${others}\n` : ''}
165
169
  --- Issue #${issue.number}: ${issue.title} (${issue.url})
166
170
  ${issue.body}
167
171
  ${agentsMd ? `\n--- AGENTS.md (the contract a task worker will follow)\n${agentsMd}` : ''}`
168
172
  }
169
173
 
174
+ /**
175
+ * The prompt's section quoting the human replies as the answer to what the issue waited on.
176
+ * @param {NonNullable<Parameters<typeof triagePrompt>[0]['replied']>} r
177
+ */
178
+ function repliedNote({ question, replies }) {
179
+ const quote = (/** @type {string} */ s) =>
180
+ s
181
+ .split('\n')
182
+ .map((l) => `> ${l}`)
183
+ .join('\n')
184
+ return `\nAn earlier triage or step left it waiting on this:\n${quote(question ?? '(no reason recorded)')}\nA human has since replied on the issue. Read the reply as the answer to that:\n${replies
185
+ .map((r) => `\n@${r.author} at ${r.at}:\n${quote(r.body)}\n`)
186
+ .join('')}`
187
+ }
188
+
170
189
  /**
171
190
  * The comment triage leaves on an actionable issue.
172
191
  * @param {{ reason: string, title?: string, acceptance?: string[] }} t