@mnaimfaizy/agent-kit 1.0.0-beta.15 → 1.0.0-beta.16

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.
Files changed (110) hide show
  1. package/README.md +1 -1
  2. package/package.json +1 -1
  3. package/src/cli.mjs +314 -4
  4. package/src/doctor.mjs +53 -1
  5. package/src/exec.mjs +14 -5
  6. package/src/factory/budget/budget.mjs +259 -0
  7. package/src/factory/build/command.mjs +321 -0
  8. package/src/factory/build/factory.mjs +473 -0
  9. package/src/factory/build/findings.mjs +55 -0
  10. package/src/factory/build/host.mjs +230 -0
  11. package/src/factory/build/notes.mjs +191 -0
  12. package/src/factory/build/pull-request.mjs +74 -0
  13. package/src/factory/bundle.mjs +146 -0
  14. package/src/factory/checks/allowed-paths.mjs +50 -0
  15. package/src/factory/checks/plan-header.mjs +296 -0
  16. package/src/factory/checks/qa.mjs +85 -0
  17. package/src/factory/checks/review.mjs +73 -0
  18. package/src/factory/checks/security.mjs +50 -0
  19. package/src/factory/checks/stage-check.mjs +89 -0
  20. package/src/factory/claims/command.mjs +187 -0
  21. package/src/factory/claims/release.mjs +111 -0
  22. package/src/factory/decision/answers.mjs +103 -0
  23. package/src/factory/decision/command.mjs +64 -0
  24. package/src/factory/decision/plan.mjs +99 -0
  25. package/src/factory/decision/request.mjs +116 -0
  26. package/src/factory/doctor/files.mjs +329 -0
  27. package/src/factory/doctor/index.mjs +56 -0
  28. package/src/factory/doctor/local.mjs +497 -0
  29. package/src/factory/doctor/orchestrate.mjs +146 -0
  30. package/src/factory/engine/lease.mjs +146 -0
  31. package/src/factory/engine/local-engine.mjs +177 -0
  32. package/src/factory/engine/lockfile.mjs +64 -0
  33. package/src/factory/engine/workflow-engine.mjs +124 -0
  34. package/src/factory/gate/comment.mjs +88 -0
  35. package/src/factory/gate/config.mjs +57 -0
  36. package/src/factory/gate/gate-core.mjs +250 -0
  37. package/src/factory/gate/guarded.mjs +17 -0
  38. package/src/factory/gate/reads.mjs +105 -0
  39. package/src/factory/gate/task.mjs +193 -0
  40. package/src/factory/gate/trip-reads.mjs +82 -0
  41. package/src/factory/gate/trip.mjs +87 -0
  42. package/src/factory/init/blueprint.mjs +174 -0
  43. package/src/factory/init/index.mjs +337 -0
  44. package/src/factory/labels/evidence.mjs +162 -0
  45. package/src/factory/labels/moves.mjs +32 -0
  46. package/src/factory/labels/reconcile.mjs +267 -0
  47. package/src/factory/labels/revert.mjs +87 -0
  48. package/src/factory/labels/timeline.mjs +72 -0
  49. package/src/factory/labels/voided.mjs +59 -0
  50. package/src/factory/limits/harness.mjs +39 -0
  51. package/src/factory/limits/limits.mjs +123 -0
  52. package/src/factory/merge/command.mjs +172 -0
  53. package/src/factory/outbox/check.mjs +240 -0
  54. package/src/factory/outbox/rulings.mjs +195 -0
  55. package/src/factory/plan/command.mjs +66 -0
  56. package/src/factory/plan/comment.mjs +156 -0
  57. package/src/factory/plan/publish.mjs +149 -0
  58. package/src/factory/plan/risk.mjs +153 -0
  59. package/src/factory/qa/command.mjs +163 -0
  60. package/src/factory/records/engine-record.mjs +133 -0
  61. package/src/factory/records/main.mjs +96 -0
  62. package/src/factory/records/record.mjs +226 -0
  63. package/src/factory/records/sink.mjs +57 -0
  64. package/src/factory/report/build.mjs +92 -0
  65. package/src/factory/report/command.mjs +80 -0
  66. package/src/factory/report/facts.mjs +226 -0
  67. package/src/factory/report/gate-section.mjs +122 -0
  68. package/src/factory/report/metrics.mjs +111 -0
  69. package/src/factory/report/reads.mjs +246 -0
  70. package/src/factory/report/render.mjs +121 -0
  71. package/src/factory/report/rollout.mjs +154 -0
  72. package/src/factory/review/command.mjs +182 -0
  73. package/src/factory/run/awake.mjs +70 -0
  74. package/src/factory/run/collect.mjs +77 -0
  75. package/src/factory/run/command.mjs +490 -0
  76. package/src/factory/run/gh.mjs +46 -0
  77. package/src/factory/run/launch.mjs +47 -0
  78. package/src/factory/run/pipelines.mjs +261 -0
  79. package/src/factory/run/raw.mjs +96 -0
  80. package/src/factory/run/restart.mjs +83 -0
  81. package/src/factory/run/s3.mjs +193 -0
  82. package/src/factory/run/secrets.mjs +142 -0
  83. package/src/factory/run/teardown.mjs +242 -0
  84. package/src/factory/run/token.mjs +68 -0
  85. package/src/factory/security/command.mjs +157 -0
  86. package/src/factory/setup/app.mjs +122 -0
  87. package/src/factory/setup/command.mjs +409 -0
  88. package/src/factory/setup/labels.mjs +25 -0
  89. package/src/factory/setup/reads.mjs +129 -0
  90. package/src/factory/setup/writes.mjs +126 -0
  91. package/src/factory/snapshot/write.mjs +176 -0
  92. package/src/factory/stop/command.mjs +136 -0
  93. package/src/factory/sweep/actions-main.mjs +117 -0
  94. package/src/factory/sweep/command.mjs +65 -0
  95. package/src/factory/sweep/knobs.mjs +78 -0
  96. package/src/factory/sweep/marker-version.mjs +15 -0
  97. package/src/factory/sweep/markers.mjs +112 -0
  98. package/src/factory/sweep/overlap.mjs +24 -0
  99. package/src/factory/sweep/run.mjs +198 -0
  100. package/src/factory/sweep/shell.mjs +394 -0
  101. package/src/factory/sweep/split.mjs +104 -0
  102. package/src/factory/sweep/states.mjs +87 -0
  103. package/src/factory/sweep/sweep-core.mjs +1781 -0
  104. package/src/factory/tracker/github.mjs +674 -0
  105. package/src/factory/tracker/operations.mjs +153 -0
  106. package/src/factory/upgrade/index.mjs +83 -0
  107. package/src/init.mjs +62 -24
  108. package/src/kit-owned-paths.mjs +1 -1
  109. package/src/stage.mjs +19 -0
  110. package/src/upgrade.mjs +39 -7
@@ -0,0 +1,674 @@
1
+ // The tracker adapter's `github` mapping. It is the only place the sweep's
2
+ // input is read and its writes applied (spec #500, Modules). It runs `gh` as an
3
+ // argument array through the `gh` function it is given, so no string from an
4
+ // issue is ever parsed as shell syntax, and a test swaps in a fake.
5
+ //
6
+ // `gh(args)` returns `{ status, stdout, stderr }`.
7
+ //
8
+ // One sweep reads the tracker with ONE GraphQL query (every factory state in
9
+ // one request) plus the head statuses of the pull requests it names.
10
+
11
+ import { OPERATIONS } from "./operations.mjs";
12
+ import { STATES, stateLabel } from "../sweep/states.mjs";
13
+ import { releaseClaimBody } from "../sweep/markers.mjs";
14
+ import { writeStageCheck } from "../checks/stage-check.mjs";
15
+
16
+ const TRACKER_PAGE = 100;
17
+ /** What the Factory control issue's body carries: init's marker (CONTROL_MARKER_PATTERN in init/blueprint.mjs), or the previous version's with no `v`. */
18
+ const CONTROL_MARKER = /<!-- factory:control(?: v=1)? -->/;
19
+ /** Pages of 100 comments `readControl` reads before it gives up (so 10,000 comments). */
20
+ const CONTROL_MAX_PAGES = 100;
21
+
22
+ /** How many native blockers (GitHub's "blocked by") the read takes of one issue. */
23
+ const BLOCKERS_PAGE = 50;
24
+
25
+ /** The one read: an aliased `issues(labels:)` field per state, so no search index lags a fresh label. */
26
+ export function buildReadQuery() {
27
+ const fields = STATES.map(
28
+ (state, i) =>
29
+ // `ready-to-merge` also reads closed issues, newest first: a pull request a person
30
+ // merged closes its issue, and the gate records that as `merged`.
31
+ `s${i}: issues(first: ${TRACKER_PAGE}, ${state === "ready-to-merge" ? "states: [OPEN, CLOSED], orderBy: { field: UPDATED_AT, direction: DESC }" : "states: OPEN"}, labels: [${JSON.stringify(stateLabel(state))}]) { pageInfo { hasNextPage } nodes { ...F } }`,
32
+ ).join("\n ");
33
+ return `query($owner: String!, $name: String!) {
34
+ repository(owner: $owner, name: $name) {
35
+ ${fields}
36
+ }
37
+ }
38
+ fragment F on Issue {
39
+ number
40
+ title
41
+ state
42
+ body
43
+ author { login }
44
+ labels(first: 50) { nodes { name } }
45
+ blockedBy(first: ${BLOCKERS_PAGE}) { totalCount nodes { number state } }
46
+ subIssues(first: 1) { totalCount }
47
+ comments(last: ${TRACKER_PAGE}) { totalCount nodes { databaseId author { login } editor { login } body createdAt } }
48
+ timelineItems(last: ${TRACKER_PAGE}, itemTypes: [LABELED_EVENT, UNLABELED_EVENT]) { nodes { __typename ... on LabeledEvent { createdAt actor { login } label { name } } ... on UnlabeledEvent { createdAt actor { login } label { name } } } }
49
+ closedByPullRequestsReferences(first: 10, includeClosedPrs: true) { nodes { number state headRefName headRefOid commits(last: 1) { nodes { commit { statusCheckRollup { state } } } } } }
50
+ }`;
51
+ }
52
+
53
+ /** The sweep's read, from the GraphQL response. */
54
+ export function parseReadResponse(data) {
55
+ const repo = data?.data?.repository;
56
+ if (!repo) throw new Error("tracker read: the GraphQL response has no repository");
57
+ const byNumber = new Map();
58
+ const truncated = [];
59
+ STATES.forEach((state, i) => {
60
+ const field = repo[`s${i}`];
61
+ if (!field) throw new Error(`tracker read: the response has no field for ${state}`);
62
+ if (field.pageInfo?.hasNextPage) truncated.push(stateLabel(state));
63
+ for (const node of field.nodes ?? []) {
64
+ if (byNumber.has(node.number)) continue;
65
+ byNumber.set(node.number, {
66
+ number: node.number,
67
+ title: node.title ?? "",
68
+ state: node.state ?? "OPEN",
69
+ body: node.body ?? "",
70
+ ...(node.author?.login ? { author: node.author.login } : {}),
71
+ labels: (node.labels?.nodes ?? []).map((l) => l.name),
72
+ // GitHub's native "blocked by" edges, each with its state (#507). Omitted when the
73
+ // read did not ask; `blockedByTruncated` when the issue has more than were read.
74
+ ...(node.blockedBy
75
+ ? {
76
+ blockedBy: (node.blockedBy.nodes ?? []).map((b) => ({
77
+ number: b.number,
78
+ state: b.state ?? "OPEN",
79
+ })),
80
+ ...((node.blockedBy.totalCount ?? 0) > (node.blockedBy.nodes ?? []).length
81
+ ? { blockedByTruncated: true }
82
+ : {}),
83
+ }
84
+ : {}),
85
+ // How many sub-issues the issue has: a spec issue has them (#507).
86
+ ...(node.subIssues ? { subIssueCount: node.subIssues.totalCount ?? 0 } : {}),
87
+ commentsTruncated: (node.comments?.totalCount ?? 0) > TRACKER_PAGE,
88
+ comments: (node.comments?.nodes ?? []).map((c) => ({
89
+ id: c.databaseId,
90
+ author: c.author?.login ?? "",
91
+ body: c.body ?? "",
92
+ createdAt: c.createdAt,
93
+ // The last person to edit it, when anyone did (ADR 0038: edited evidence is void).
94
+ ...(c.editor?.login ? { editor: c.editor.login } : {}),
95
+ })),
96
+ // Who added and removed each label, oldest first (ADR 0038): the actor of a move.
97
+ ...(node.timelineItems
98
+ ? {
99
+ timeline: (node.timelineItems.nodes ?? [])
100
+ .filter((e) => e?.label?.name)
101
+ .map((e) => ({
102
+ kind: e.__typename === "UnlabeledEvent" ? "unlabeled" : "labeled",
103
+ label: e.label.name,
104
+ actor: e.actor?.login ?? "",
105
+ at: e.createdAt,
106
+ })),
107
+ }
108
+ : {}),
109
+ pulls: (node.closedByPullRequestsReferences?.nodes ?? []).map((p) => ({
110
+ number: p.number,
111
+ state: p.state,
112
+ branch: p.headRefName ?? "",
113
+ head: p.headRefOid,
114
+ // The head commit's checks and statuses together: SUCCESS, FAILURE,
115
+ // ERROR, PENDING or EXPECTED; null when it has none yet.
116
+ ci: p.commits?.nodes?.[0]?.commit?.statusCheckRollup?.state ?? null,
117
+ })),
118
+ });
119
+ }
120
+ });
121
+ return { issues: [...byNumber.values()].sort((a, b) => a.number - b.number), truncated };
122
+ }
123
+
124
+ /**
125
+ * @param {{ gh: (args: string[]) => { status: number | null, stdout: string, stderr: string }, repo: string }} deps
126
+ */
127
+ export function createGithubTracker({ gh, repo }) {
128
+ const [owner, name] = repo.split("/");
129
+ if (!owner || !name || repo.split("/").length !== 2) {
130
+ throw new Error(`repository must be owner/name, got ${JSON.stringify(repo)}`);
131
+ }
132
+ const run = (args, input) => {
133
+ const result = gh(args, input);
134
+ if (result.status !== 0) {
135
+ throw new Error(
136
+ `gh ${args.slice(0, 3).join(" ")} failed: ${String(result.stderr).trim().slice(0, 300)}`,
137
+ );
138
+ }
139
+ return result.stdout;
140
+ };
141
+ const json = (args, input) => JSON.parse(run(args, input) || "null");
142
+ const api = (path, ...rest) => run(["api", path, ...rest]);
143
+ const issuePath = (n) => `repos/${repo}/issues/${Number(n)}`;
144
+
145
+ const tracker = {
146
+ repo,
147
+ operations: OPERATIONS,
148
+
149
+ readState() {
150
+ const data = json([
151
+ "api",
152
+ "graphql",
153
+ "-f",
154
+ `query=${buildReadQuery()}`,
155
+ "-f",
156
+ `owner=${owner}`,
157
+ "-f",
158
+ `name=${name}`,
159
+ ]);
160
+ return parseReadResponse(data);
161
+ },
162
+
163
+ /**
164
+ * `{ [sha]: [{ context, state, description, creator, createdAt }] }` for each distinct
165
+ * head, newest first, every status and not just the latest of each context:
166
+ * a status that someone else writes after the engine's must not hide it.
167
+ */
168
+ readHeadStatuses(shas) {
169
+ const out = {};
170
+ for (const sha of [...new Set(shas)]) {
171
+ if (!/^[0-9a-f]{40}$/.test(sha))
172
+ throw new Error(`not a commit sha: ${JSON.stringify(sha)}`);
173
+ const pages = json([
174
+ "api",
175
+ `repos/${repo}/commits/${sha}/statuses?per_page=100`,
176
+ "--paginate",
177
+ "--slurp",
178
+ ]);
179
+ out[sha] = (Array.isArray(pages) ? pages.flat() : []).map((s) => ({
180
+ context: s.context,
181
+ state: s.state,
182
+ description: s.description ?? "",
183
+ creator: s.creator?.login ?? "",
184
+ createdAt: s.created_at,
185
+ }));
186
+ }
187
+ return out;
188
+ },
189
+
190
+ /**
191
+ * The logins among `logins` that have write access to the repository
192
+ * (admin or write; maintain counts as write there): the people whose
193
+ * reply to a Decision Request counts. A login GitHub does not know as a
194
+ * collaborator (a bot, a stranger) is not one; any other failure throws,
195
+ * so a flaky read is never taken for "no write access".
196
+ */
197
+ readWriters(logins) {
198
+ const writers = [];
199
+ for (const login of [...new Set(logins)]) {
200
+ if (!/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/.test(login)) continue;
201
+ const result = gh([
202
+ "api",
203
+ `repos/${repo}/collaborators/${login}/permission`,
204
+ "--jq",
205
+ ".permission",
206
+ ]);
207
+ if (result.status === 0) {
208
+ if (["admin", "write"].includes(result.stdout.trim())) writers.push(login);
209
+ } else if (!/\b404\b|Not Found|not a user/i.test(String(result.stderr))) {
210
+ throw new Error(
211
+ `gh api collaborators failed: ${String(result.stderr).trim().slice(0, 300)}`,
212
+ );
213
+ }
214
+ }
215
+ return writers;
216
+ },
217
+
218
+ /**
219
+ * What the merge gate reads of one pull request: its state (`MERGED` when a
220
+ * person merged it), head, base branch, every changed path (a rename counts
221
+ * both names), the changed lines and whether GitHub can merge it cleanly
222
+ * (`true`, `false`, or `null` while GitHub still works it out). A diff cut
223
+ * short by GitHub's limit throws, so a partial diff is never judged.
224
+ */
225
+ readPull(number) {
226
+ const d = json(["api", `repos/${repo}/pulls/${Number(number)}`]);
227
+ const pages =
228
+ json([
229
+ "api",
230
+ `repos/${repo}/pulls/${Number(number)}/files?per_page=100`,
231
+ "--paginate",
232
+ "--slurp",
233
+ ]) ?? [];
234
+ const files = pages.flat();
235
+ if (files.length < (d.changed_files ?? 0))
236
+ throw new Error(`only ${files.length} of ${d.changed_files} files were returned`);
237
+ return {
238
+ number: d.number,
239
+ state: d.merged ? "MERGED" : d.state === "open" ? "OPEN" : "CLOSED",
240
+ head: d.head?.sha,
241
+ base: d.base?.ref,
242
+ mergeable: d.mergeable === true || d.mergeable === false ? d.mergeable : null,
243
+ files: [
244
+ ...new Set(files.flatMap((f) => [f.filename, f.previous_filename].filter(Boolean))),
245
+ ],
246
+ lines: (d.additions ?? 0) + (d.deletions ?? 0),
247
+ };
248
+ },
249
+
250
+ /** `base...head`: how far `head` is ahead of and behind `base`, and the files that differ. */
251
+ readCompare(base, head) {
252
+ const d = json([
253
+ "api",
254
+ `repos/${repo}/compare/${encodeURIComponent(base)}...${encodeURIComponent(head)}`,
255
+ ]);
256
+ const files = d?.files ?? [];
257
+ // The compare API lists at most 300 files: more than that is not a whole diff.
258
+ if (files.length >= 300) throw new Error("the comparison lists 300 files or more");
259
+ return {
260
+ aheadBy: d.ahead_by,
261
+ behindBy: d.behind_by,
262
+ files: [
263
+ ...new Set(files.flatMap((f) => [f.filename, f.previous_filename].filter(Boolean))),
264
+ ],
265
+ };
266
+ },
267
+
268
+ /** The status contexts the ruleset on a branch requires (a `factory/*` context is never one). */
269
+ readRequiredContexts(branch) {
270
+ // Every page: a branch with more than 30 rules would otherwise lose the required
271
+ // contexts of the later ones.
272
+ const pages = json([
273
+ "api",
274
+ `repos/${repo}/rules/branches/${encodeURIComponent(branch)}`,
275
+ "--paginate",
276
+ "--slurp",
277
+ ]);
278
+ if (!Array.isArray(pages) || !pages.every(Array.isArray))
279
+ throw new Error("the ruleset read is not a list");
280
+ const rules = pages.flat();
281
+ return [
282
+ ...new Set(
283
+ rules
284
+ .filter((r) => r.type === "required_status_checks")
285
+ .flatMap((r) => (r.parameters?.required_status_checks ?? []).map((c) => c.context)),
286
+ ),
287
+ ].filter((c) => typeof c === "string" && !c.startsWith("factory/"));
288
+ },
289
+
290
+ /**
291
+ * The checks and statuses on a commit, by name: `{ state, contexts: [{ name, state }] }` with each
292
+ * state `success`, `failure` or `pending` (and `at`, when it started, so the newest of a name can be told). `expression` is a sha or a ref such as `refs/heads/main`.
293
+ */
294
+ readChecks(expression) {
295
+ const data = json([
296
+ "api",
297
+ "graphql",
298
+ "-f",
299
+ `query=query($owner: String!, $name: String!, $expr: String!) { repository(owner: $owner, name: $name) { object(expression: $expr) { ... on Commit { statusCheckRollup { state contexts(first: 100) { pageInfo { hasNextPage } nodes { __typename ... on CheckRun { name status conclusion startedAt } ... on StatusContext { context state createdAt } } } } } } } }`,
300
+ "-f",
301
+ `owner=${owner}`,
302
+ "-f",
303
+ `name=${name}`,
304
+ "-f",
305
+ `expr=${expression}`,
306
+ ]);
307
+ const rollup = data?.data?.repository?.object?.statusCheckRollup;
308
+ if (!rollup) throw new Error(`no checks are recorded on ${expression}`);
309
+ if (rollup.contexts?.pageInfo?.hasNextPage)
310
+ throw new Error(`${expression} has more than 100 checks`);
311
+ const norm = (done, ok) => (!done ? "pending" : ok ? "success" : "failure");
312
+ const contexts = (rollup.contexts?.nodes ?? []).map((n) =>
313
+ n.__typename === "CheckRun"
314
+ ? {
315
+ name: n.name,
316
+ state: norm(
317
+ n.status === "COMPLETED",
318
+ ["SUCCESS", "NEUTRAL", "SKIPPED"].includes(n.conclusion),
319
+ ),
320
+ ...(n.startedAt ? { at: n.startedAt } : {}),
321
+ }
322
+ : {
323
+ name: n.context,
324
+ state:
325
+ n.state === "SUCCESS"
326
+ ? "success"
327
+ : n.state === "PENDING" || n.state === "EXPECTED"
328
+ ? "pending"
329
+ : "failure",
330
+ ...(n.createdAt ? { at: n.createdAt } : {}),
331
+ },
332
+ );
333
+ return {
334
+ state:
335
+ rollup.state === "SUCCESS"
336
+ ? "success"
337
+ : rollup.state === "PENDING" || rollup.state === "EXPECTED"
338
+ ? "pending"
339
+ : "failure",
340
+ contexts,
341
+ };
342
+ },
343
+
344
+ /**
345
+ * The Factory control issue and its comments, each with who last edited it (a person
346
+ * clearing the gate's trip marker is the editor): `{ number, comments: [{ id, author,
347
+ * editor, body, createdAt }] }`, or null when no open issue opened by a writer carries the control marker.
348
+ * Every comment is read, 100 a page, up to CONTROL_MAX_PAGES pages. A failed or truncated read throws.
349
+ */
350
+ readControl() {
351
+ const pages =
352
+ json(["api", `repos/${repo}/issues?state=open&per_page=100`, "--paginate", "--slurp"]) ??
353
+ [];
354
+ // Oldest marker issue first, and only one opened by a person with write or admin access:
355
+ // anyone else could open an issue with the marker and plant a lease or a trip.
356
+ const candidates = pages
357
+ .flat()
358
+ .filter((i) => !i.pull_request && CONTROL_MARKER.test(String(i.body ?? "")))
359
+ .sort((a, b) => Number(a.number) - Number(b.number));
360
+ const writers = candidates.length
361
+ ? new Set(tracker.readWriters(candidates.map((i) => i.user?.login ?? "")))
362
+ : new Set();
363
+ const control = candidates.find((i) => writers.has(i.user?.login));
364
+ if (!control) return null;
365
+ // Every comment is read, oldest first, by cursor: the trip marker, a live lease and the
366
+ // day's budget notice can each sit anywhere. A page that fails, or an issue past the cap,
367
+ // throws: a truncated list is never returned, so the trip reads as unreadable (shadow).
368
+ const nodes = [];
369
+ let after = null;
370
+ for (let page = 0; ; page += 1) {
371
+ if (page >= CONTROL_MAX_PAGES) {
372
+ throw new Error(
373
+ `the control issue has more than ${CONTROL_MAX_PAGES * TRACKER_PAGE} comments: its comments could not be read in full`,
374
+ );
375
+ }
376
+ const data = json([
377
+ "api",
378
+ "graphql",
379
+ "-f",
380
+ `query=query($owner: String!, $name: String!, $number: Int!, $after: String) { repository(owner: $owner, name: $name) { issue(number: $number) { comments(first: ${TRACKER_PAGE}, after: $after) { pageInfo { hasNextPage endCursor } nodes { databaseId author { login } editor { login } body createdAt } } } } }`,
381
+ "-f",
382
+ `owner=${owner}`,
383
+ "-f",
384
+ `name=${name}`,
385
+ "-F",
386
+ `number=${Number(control.number)}`,
387
+ ...(after === null ? [] : ["-f", `after=${after}`]),
388
+ ]);
389
+ const comments = data?.data?.repository?.issue?.comments;
390
+ if (!Array.isArray(comments?.nodes)) {
391
+ throw new Error("the control issue's comments could not be read");
392
+ }
393
+ nodes.push(...comments.nodes);
394
+ if (typeof comments.pageInfo?.hasNextPage !== "boolean") {
395
+ throw new Error("the control issue's comments could not be read in full");
396
+ }
397
+ if (!comments.pageInfo.hasNextPage) break;
398
+ after = comments.pageInfo.endCursor;
399
+ if (typeof after !== "string" || !after) {
400
+ throw new Error("the control issue's comments could not be read in full");
401
+ }
402
+ }
403
+ return {
404
+ number: control.number,
405
+ comments: nodes.map((c) => ({
406
+ id: c.databaseId,
407
+ author: c.author?.login ?? "",
408
+ editor: c.editor?.login ?? null,
409
+ body: c.body ?? "",
410
+ createdAt: c.createdAt,
411
+ })),
412
+ };
413
+ },
414
+
415
+ /**
416
+ * The release comments (#515) of every issue, closed ones too, posted or edited since `sinceIso`
417
+ * (the Daily cap sums the day's): `[{ issue, id, author, body, createdAt, updatedAt }]`. Only
418
+ * comments that carry the release marker are kept. A failed read throws.
419
+ */
420
+ readReleases(sinceIso) {
421
+ if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/.test(String(sinceIso))) {
422
+ throw new Error(`not a UTC time: ${JSON.stringify(sinceIso)}`);
423
+ }
424
+ const pages =
425
+ json([
426
+ "api",
427
+ `repos/${repo}/issues/comments?since=${sinceIso}&per_page=100`,
428
+ "--paginate",
429
+ "--slurp",
430
+ ]) ?? [];
431
+ return pages
432
+ .flat()
433
+ .filter((c) => String(c.body ?? "").includes("<!-- factory:release "))
434
+ .map((c) => ({
435
+ issue: Number(
436
+ String(c.issue_url ?? "")
437
+ .split("/")
438
+ .pop(),
439
+ ),
440
+ id: c.id,
441
+ author: c.user?.login ?? "",
442
+ body: c.body ?? "",
443
+ createdAt: c.created_at,
444
+ updatedAt: c.updated_at,
445
+ }));
446
+ },
447
+
448
+ /** Asks GitHub to merge the base into a pull request's branch, only if the head is still `expectedHead`. */
449
+ updateBranch(number, expectedHead) {
450
+ api(
451
+ `repos/${repo}/pulls/${Number(number)}/update-branch`,
452
+ "-X",
453
+ "PUT",
454
+ "-f",
455
+ `expected_head_sha=${expectedHead}`,
456
+ );
457
+ },
458
+
459
+ /** Writes one Stage check on a commit (the gate's carry-over). */
460
+ writeStageCheck(sha, check) {
461
+ writeStageCheck({ gh: (args) => gh(args), repo, sha, check });
462
+ },
463
+
464
+ setState(issue, from, to) {
465
+ api(`${issuePath(issue)}/labels`, "-X", "POST", "-f", `labels[]=${stateLabel(to)}`);
466
+ api(`${issuePath(issue)}/labels/${encodeURIComponent(stateLabel(from))}`, "-X", "DELETE");
467
+ },
468
+
469
+ /** Adds, then removes, labels in one revert: the issue is never left with none. */
470
+ revertLabels(issue, { add = [], remove = [] }) {
471
+ for (const label of add) {
472
+ api(`${issuePath(issue)}/labels`, "-X", "POST", "-f", `labels[]=${label}`);
473
+ }
474
+ for (const label of remove) tracker.removeLabel(issue, label);
475
+ },
476
+
477
+ /** Removes one label; a label that is not there is done. */
478
+ removeLabel(issue, label) {
479
+ const result = gh([
480
+ "api",
481
+ "-X",
482
+ "DELETE",
483
+ `${issuePath(issue)}/labels/${encodeURIComponent(label)}`,
484
+ ]);
485
+ if (result.status !== 0 && !/HTTP 404|Label does not exist/i.test(String(result.stderr))) {
486
+ throw new Error(`gh api labels failed: ${String(result.stderr).trim().slice(0, 300)}`);
487
+ }
488
+ },
489
+
490
+ /** Adds one login to an issue's assignees (the Orchestrate engine's Claims, spec #500). */
491
+ addAssignee(issue, login) {
492
+ if (!/^[A-Za-z0-9-]+$/.test(String(login))) {
493
+ throw new Error(`not a login: ${JSON.stringify(login)}`);
494
+ }
495
+ run(["api", "-X", "POST", `${issuePath(issue)}/assignees`, "-f", `assignees[]=${login}`]);
496
+ },
497
+
498
+ /** Writes a Claim comment; returns its id. */
499
+ claim(issue, body) {
500
+ return tracker.comment(issue, body);
501
+ },
502
+
503
+ /** The issue's comments again, fresh and complete: `[{ id, author, body, createdAt }]`. */
504
+ readComments(issue) {
505
+ const pages = json(["api", `${issuePath(issue)}/comments`, "--paginate", "--slurp"]) ?? [];
506
+ return pages.flat().map((c) => ({
507
+ id: c.id,
508
+ author: c.user?.login ?? "",
509
+ body: c.body ?? "",
510
+ createdAt: c.created_at,
511
+ }));
512
+ },
513
+
514
+ readClaim(issue) {
515
+ return tracker.readComments(issue);
516
+ },
517
+
518
+ /** The issue's body and label names. */
519
+ readIssue(issue) {
520
+ const data = json(["api", issuePath(issue)]);
521
+ return {
522
+ body: data?.body ?? "",
523
+ labels: (data?.labels ?? []).map((l) => (typeof l === "string" ? l : l.name)),
524
+ };
525
+ },
526
+
527
+ /** Posts a comment, the body on stdin so its size never meets the argument limit; `{ id, url }`. */
528
+ postComment(issue, body) {
529
+ const data = json(
530
+ ["api", "-X", "POST", `${issuePath(issue)}/comments`, "--input", "-"],
531
+ JSON.stringify({ body }),
532
+ );
533
+ return { id: data.id, url: data.html_url };
534
+ },
535
+
536
+ editComment(commentId, body) {
537
+ run(
538
+ [
539
+ "api",
540
+ "-X",
541
+ "PATCH",
542
+ `repos/${repo}/issues/comments/${Number(commentId)}`,
543
+ "--input",
544
+ "-",
545
+ ],
546
+ JSON.stringify({ body }),
547
+ );
548
+ },
549
+
550
+ /** A file's text on `ref`, or null when it is not there. Any other failure throws. */
551
+ readFile(path, ref) {
552
+ const result = gh([
553
+ "api",
554
+ "-H",
555
+ "Accept: application/vnd.github.raw",
556
+ `repos/${repo}/contents/${path}?ref=${encodeURIComponent(ref)}`,
557
+ ]);
558
+ if (result.status === 0) return result.stdout;
559
+ if (/\b404\b|Not Found/i.test(String(result.stderr))) return null;
560
+ throw new Error(`gh api contents failed: ${String(result.stderr).trim().slice(0, 300)}`);
561
+ },
562
+
563
+ release(commentId, reason) {
564
+ const path = `repos/${repo}/issues/comments/${Number(commentId)}`;
565
+ const current = json(["api", path]);
566
+ const body = releaseClaimBody(current.body ?? "", reason);
567
+ if (body !== current.body) api(path, "-X", "PATCH", "-f", `body=${body}`);
568
+ },
569
+
570
+ comment(issue, body) {
571
+ return json(["api", `${issuePath(issue)}/comments`, "-X", "POST", "-f", `body=${body}`]).id;
572
+ },
573
+
574
+ /**
575
+ * Creates an issue (title, body and labels in one request, so it never exists half labelled)
576
+ * and attaches it to `parent` as a native sub-issue (a plan's split, #508). Returns `{ number }`.
577
+ */
578
+ createSubIssue(parent, { title, body, labels }) {
579
+ const created = json(
580
+ ["api", "-X", "POST", `repos/${repo}/issues`, "--input", "-"],
581
+ JSON.stringify({ title, body, labels }),
582
+ );
583
+ tracker.addSubIssue(parent, created.number, created.id);
584
+ return { number: created.number };
585
+ },
586
+
587
+ /** The database id GitHub's dependency and sub-issue endpoints take for an issue number. */
588
+ issueId(number) {
589
+ const id = json(["api", issuePath(number)])?.id;
590
+ if (!Number.isInteger(id)) throw new Error(`issue #${number} has no id`);
591
+ return id;
592
+ },
593
+
594
+ /** Attaches `child` to `parent` as a sub-issue; one that is already attached is done. */
595
+ addSubIssue(parent, child, childId) {
596
+ const result = gh(
597
+ ["api", "-X", "POST", `${issuePath(parent)}/sub_issues`, "--input", "-"],
598
+ JSON.stringify({ sub_issue_id: childId ?? tracker.issueId(child) }),
599
+ );
600
+ if (
601
+ result.status !== 0 &&
602
+ !/already|duplicate|one parent/i.test(`${result.stderr}${result.stdout}`)
603
+ ) {
604
+ throw new Error(`gh api sub_issues failed: ${String(result.stderr).trim().slice(0, 300)}`);
605
+ }
606
+ },
607
+
608
+ /** Makes `blocker` block `issue` (GitHub's "blocked by"), unless it already does. */
609
+ addBlockedBy(issue, blocker) {
610
+ const path = `${issuePath(issue)}/dependencies/blocked_by`;
611
+ const blocking = (json(["api", path, "--paginate", "--slurp"]) ?? []).flat();
612
+ if (blocking.some((b) => b.number === Number(blocker))) return;
613
+ json(
614
+ ["api", "-X", "POST", path, "--input", "-"],
615
+ JSON.stringify({ issue_id: tracker.issueId(blocker) }),
616
+ );
617
+ },
618
+
619
+ /**
620
+ * A split's parent as the close-out reads it: `{ number, state, comments, children }`, the
621
+ * comments with their last editor and each sub-issue with `merged` (closed, and carrying
622
+ * `factory:merged`). More sub-issues than one page holds throws: a partial list is never judged.
623
+ */
624
+ readSplitParent(number) {
625
+ const data = json([
626
+ "api",
627
+ "graphql",
628
+ "-f",
629
+ "query=query($owner: String!, $name: String!, $number: Int!) { repository(owner: $owner, name: $name) { issue(number: $number) { number state comments(last: 100) { nodes { databaseId author { login } editor { login } body createdAt } } subIssues(first: 100) { pageInfo { hasNextPage } nodes { number state labels(first: 50) { nodes { name } } } } } } }",
630
+ "-f",
631
+ `owner=${owner}`,
632
+ "-f",
633
+ `name=${name}`,
634
+ "-F",
635
+ `number=${Number(number)}`,
636
+ ]);
637
+ const issue = data?.data?.repository?.issue;
638
+ if (!issue) throw new Error(`#${number} could not be read`);
639
+ if (issue.subIssues?.pageInfo?.hasNextPage) {
640
+ throw new Error(`#${number} has more than 100 sub-issues`);
641
+ }
642
+ return {
643
+ number: issue.number,
644
+ state: issue.state ?? "OPEN",
645
+ comments: (issue.comments?.nodes ?? []).map((c) => ({
646
+ id: c.databaseId,
647
+ author: c.author?.login ?? "",
648
+ body: c.body ?? "",
649
+ createdAt: c.createdAt,
650
+ ...(c.editor?.login ? { editor: c.editor.login } : {}),
651
+ })),
652
+ children: (issue.subIssues?.nodes ?? []).map((c) => ({
653
+ number: c.number,
654
+ state: c.state,
655
+ merged:
656
+ c.state === "CLOSED" &&
657
+ (c.labels?.nodes ?? []).some((l) => l.name === stateLabel("merged")),
658
+ })),
659
+ };
660
+ },
661
+
662
+ /** Closes an issue as completed, then says why in one comment. */
663
+ closeIssue(issue, comment) {
664
+ // Closed first: a close that fails is tried again by the next sweep without a second comment.
665
+ api(issuePath(issue), "-X", "PATCH", "-f", "state=closed", "-f", "state_reason=completed");
666
+ tracker.comment(issue, comment);
667
+ },
668
+
669
+ defaultBranch() {
670
+ return run(["api", `repos/${repo}`, "--jq", ".default_branch"]).trim();
671
+ },
672
+ };
673
+ return tracker;
674
+ }