@davidbyoung/software-factory 0.0.0-stage → 0.1.1

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 (141) hide show
  1. package/.claude-plugin/plugin.json +5 -0
  2. package/LICENSE +21 -0
  3. package/README.md +135 -2
  4. package/actions/factory-agent/action.yml +218 -0
  5. package/agents/factory-test-reviewer.md +129 -0
  6. package/agents/factory-ticket-readiness.md +107 -0
  7. package/agents/factory-ui-reviewer.md +160 -0
  8. package/bin/factory.js +45 -0
  9. package/bin/launch.js +67 -0
  10. package/dist/board.d.mts +128 -0
  11. package/dist/board.mjs +456 -0
  12. package/dist/build.d.mts +18 -0
  13. package/dist/build.mjs +60 -0
  14. package/dist/cli.d.mts +17 -0
  15. package/dist/cli.mjs +264 -0
  16. package/dist/code-host/github.d.mts +118 -0
  17. package/dist/code-host/github.mjs +419 -0
  18. package/dist/code-host/index.d.mts +9 -0
  19. package/dist/code-host/index.mjs +18 -0
  20. package/dist/code-host/types.d.mts +205 -0
  21. package/dist/code-host/types.mjs +12 -0
  22. package/dist/config.d.mts +166 -0
  23. package/dist/config.mjs +548 -0
  24. package/dist/deps.d.mts +32 -0
  25. package/dist/deps.mjs +126 -0
  26. package/dist/doctor.d.mts +34 -0
  27. package/dist/doctor.mjs +188 -0
  28. package/dist/guard-commit.d.mts +41 -0
  29. package/dist/guard-commit.mjs +209 -0
  30. package/dist/guard-permission.d.mts +15 -0
  31. package/dist/guard-permission.mjs +52 -0
  32. package/dist/guard-ticket-text.d.mts +27 -0
  33. package/dist/guard-ticket-text.mjs +288 -0
  34. package/dist/guard.d.mts +4 -0
  35. package/dist/guard.mjs +37 -0
  36. package/dist/init.d.mts +58 -0
  37. package/dist/init.mjs +556 -0
  38. package/dist/lib/clock.d.mts +14 -0
  39. package/dist/lib/clock.mjs +36 -0
  40. package/dist/lib/gh.d.mts +28 -0
  41. package/dist/lib/gh.mjs +92 -0
  42. package/dist/lib/glob.d.mts +2 -0
  43. package/dist/lib/glob.mjs +41 -0
  44. package/dist/lib/pricing.d.mts +25 -0
  45. package/dist/lib/pricing.mjs +77 -0
  46. package/dist/lib/usage.d.mts +34 -0
  47. package/dist/lib/usage.mjs +128 -0
  48. package/dist/lib/work-status.d.mts +251 -0
  49. package/dist/lib/work-status.mjs +510 -0
  50. package/dist/merge-policy.d.mts +66 -0
  51. package/dist/merge-policy.mjs +146 -0
  52. package/dist/parts.d.mts +39 -0
  53. package/dist/parts.mjs +138 -0
  54. package/dist/poller.d.mts +61 -0
  55. package/dist/poller.mjs +247 -0
  56. package/dist/pr-watch.d.mts +45 -0
  57. package/dist/pr-watch.mjs +244 -0
  58. package/dist/pr.d.mts +65 -0
  59. package/dist/pr.mjs +571 -0
  60. package/dist/review-cost.d.mts +18 -0
  61. package/dist/review-cost.mjs +95 -0
  62. package/dist/review-tools.d.mts +5 -0
  63. package/dist/review-tools.mjs +46 -0
  64. package/dist/review-verdict.d.mts +50 -0
  65. package/dist/review-verdict.mjs +171 -0
  66. package/dist/reviewers.d.mts +54 -0
  67. package/dist/reviewers.mjs +312 -0
  68. package/dist/runner/github-actions.d.mts +12 -0
  69. package/dist/runner/github-actions.mjs +97 -0
  70. package/dist/runner/index.d.mts +9 -0
  71. package/dist/runner/index.mjs +22 -0
  72. package/dist/runner/types.d.mts +60 -0
  73. package/dist/runner/types.mjs +7 -0
  74. package/dist/session-start.d.mts +20 -0
  75. package/dist/session-start.mjs +115 -0
  76. package/dist/site/capture.d.mts +44 -0
  77. package/dist/site/capture.mjs +114 -0
  78. package/dist/site/measure.d.mts +83 -0
  79. package/dist/site/measure.mjs +225 -0
  80. package/dist/site/pages.d.mts +10 -0
  81. package/dist/site/pages.mjs +71 -0
  82. package/dist/site/pixels.d.mts +47 -0
  83. package/dist/site/pixels.mjs +157 -0
  84. package/dist/site/servers.d.mts +47 -0
  85. package/dist/site/servers.mjs +141 -0
  86. package/dist/site.d.mts +60 -0
  87. package/dist/site.mjs +341 -0
  88. package/dist/status.d.mts +100 -0
  89. package/dist/status.mjs +514 -0
  90. package/dist/sync.d.mts +59 -0
  91. package/dist/sync.mjs +292 -0
  92. package/dist/ticket.d.mts +61 -0
  93. package/dist/ticket.mjs +562 -0
  94. package/dist/tickets/github.d.mts +128 -0
  95. package/dist/tickets/github.mjs +491 -0
  96. package/dist/tickets/index.d.mts +15 -0
  97. package/dist/tickets/index.mjs +27 -0
  98. package/dist/tickets/transport.d.mts +42 -0
  99. package/dist/tickets/transport.mjs +158 -0
  100. package/dist/tickets/types.d.mts +191 -0
  101. package/dist/tickets/types.mjs +76 -0
  102. package/docs/builds.md +227 -0
  103. package/docs/cli.md +221 -0
  104. package/docs/configuration.md +809 -0
  105. package/docs/design.md +106 -0
  106. package/docs/developing.md +400 -0
  107. package/docs/existing-repo.md +138 -0
  108. package/docs/github/reference.md +288 -0
  109. package/docs/github/setup.md +312 -0
  110. package/docs/glossary.md +106 -0
  111. package/docs/limitations.md +115 -0
  112. package/docs/plugins.md +192 -0
  113. package/docs/quick-start.md +222 -0
  114. package/docs/removing.md +76 -0
  115. package/docs/skills.md +270 -0
  116. package/docs/updating.md +108 -0
  117. package/docs/workflow.md +195 -0
  118. package/package.json +67 -4
  119. package/poller.Dockerfile +21 -0
  120. package/review.md +170 -0
  121. package/rules.md +313 -0
  122. package/settings.schema.json +411 -0
  123. package/skills/factory-address-review/SKILL.md +547 -0
  124. package/skills/factory-address-review/patch-coverage.py +68 -0
  125. package/skills/factory-build/SKILL.md +412 -0
  126. package/skills/factory-deps/SKILL.md +185 -0
  127. package/skills/factory-design/SKILL.md +159 -0
  128. package/skills/factory-diagnose/SKILL.md +93 -0
  129. package/skills/factory-mutate/SKILL.md +76 -0
  130. package/skills/factory-refine/SKILL.md +417 -0
  131. package/skills/factory-resolve-conflicts/SKILL.md +235 -0
  132. package/workflows/factory-board-sync.yml +91 -0
  133. package/workflows/factory-build.yml +72 -0
  134. package/workflows/factory-check.yml +37 -0
  135. package/workflows/factory-claude-review.yml +133 -0
  136. package/workflows/factory-conflicts.yml +69 -0
  137. package/workflows/factory-deps-auto-merge.yml +43 -0
  138. package/workflows/factory-deps.yml +59 -0
  139. package/workflows/factory-merge-policy.yml +121 -0
  140. package/workflows/factory-review-verdict.yml +54 -0
  141. package/workflows/factory-review.yml +75 -0
@@ -0,0 +1,562 @@
1
+ #!/usr/bin/env node
2
+ // The steps a session takes on an issue that are the same every time: claim
3
+ // it, check the claim still holds, stop, post a refinement marker, note what
4
+ // the session spent, and add a line to the follow-ups issue.
5
+ //
6
+ // npx --no-install factory ticket claim N
7
+ // npx --no-install factory ticket still-live N
8
+ // npx --no-install factory ticket stop N "one-line reason"
9
+ // npx --no-install factory ticket end N
10
+ // npx --no-install factory ticket refining|waiting N
11
+ // npx --no-install factory ticket refined N [--before-file FILE]
12
+ // npx --no-install factory follow-up FILE "what is wrong"
13
+ // npx --no-install factory ticket ready N
14
+ // npx --no-install factory ticket cost N
15
+ //
16
+ // And the reads and writes the skills make, through the ticket interface
17
+ // (`tickets/`), so no skill calls a ticket system itself:
18
+ //
19
+ // factory ticket view N [--field title|state|labels|body] [--json]
20
+ // factory ticket list [--label LABEL] [--title "TITLE"] [--json]
21
+ // factory ticket edit N [--title TITLE] [--body-file FILE [--attach FILE]...]
22
+ // factory ticket comment N --body-file FILE [--attach FILE]...
23
+ // factory ticket open --title TITLE --body-file FILE [--label LABEL]...
24
+ // factory ticket label N --add LABEL | --remove LABEL | --was-removed LABEL
25
+ // factory ticket link N
26
+ // factory ticket blockers N
27
+ // factory ticket block N --by M
28
+ // factory ticket unblock N --by M
29
+ // factory ticket supports GROUP
30
+ //
31
+ // The cost clock: `claim` and `refining` start the session's clock on N.
32
+ // `waiting`, `refined`, `stop`, and `cost` post what the session and its
33
+ // subagents spent, as a share of the subscription and at API list prices,
34
+ // since the clock started, or since the
35
+ // session started when it has none, then restart it. `cost` posts to issue
36
+ // or pull request N. The clock is keyed by CLAUDE_CODE_SESSION_ID, the ID the
37
+ // hooks receive and the transcript's file name.
38
+ //
39
+ // `ready` moves issue N's card to Ready when the owner asks a session to, so
40
+ // the sync and the poller treat it as the owner's own move. It is the one
41
+ // write to Status outside the sync, and needs the project scope:
42
+ // gh auth refresh -s project.
43
+ //
44
+ // `end` is a run's last step: it releases this session's claim when the claim
45
+ // is live and no open pull request links the ticket, and always exits 0.
46
+ //
47
+ // FILE is the file or page a follow-up is about, and leads its line. A
48
+ // failed read exits 1 with the error; every other outcome is the one line
49
+ // printed.
50
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
51
+ import { join } from "node:path";
52
+ import { setTimeout as sleep } from "node:timers/promises";
53
+ import { sessionIdentity } from "./lib/gh.mjs";
54
+ import { openCodeHost } from "./code-host/index.mjs";
55
+ import { openRunner } from "./runner/index.mjs";
56
+ import { loadSettings, targetOf } from "./config.mjs";
57
+ import { commentBody, sameName, reviewingPulls, workState, } from "./lib/work-status.mjs";
58
+ import { commonDir, readClock, writeClock } from "./lib/clock.mjs";
59
+ import { costNote, measureSession, projectsDir } from "./lib/usage.mjs";
60
+ import { boardConfigOf, checkFields } from "./board.mjs";
61
+ import { refuseBareTags, refuseOverride } from "./guard-ticket-text.mjs";
62
+ import { openTickets } from "./tickets/index.mjs";
63
+ import { GROUPS, need, supports, } from "./tickets/types.mjs";
64
+ export async function readComments(c, issue) {
65
+ return (await c.tickets.read(issue)).comments;
66
+ }
67
+ /** The cost note for what this session spent since its clock started, and
68
+ * the clock restarted from now. */
69
+ function takeCost(issue, d) {
70
+ const session = d.env.CLAUDE_CODE_SESSION_ID ?? "";
71
+ if (!session)
72
+ return costNote({ ok: false, reason: "CLAUDE_CODE_SESSION_ID is not set" }, issue, session);
73
+ const clock = d.clock.read(session);
74
+ const now = d.now().toISOString();
75
+ const note = costNote(measure(d, session, clock?.start ?? null), issue, session);
76
+ // Only claim and refining choose the issue: a note posted elsewhere, such
77
+ // as on a pull request, keeps the clock's.
78
+ d.clock.write(session, { issue: clock ? clock.issue : null, start: now });
79
+ return note;
80
+ }
81
+ function measure(d, session, since) {
82
+ try {
83
+ return d.measure(session, since);
84
+ }
85
+ catch (error) {
86
+ const reason = error instanceof Error ? error.message : String(error);
87
+ return {
88
+ ok: false,
89
+ reason: `its transcript could not be read (${reason})`,
90
+ };
91
+ }
92
+ }
93
+ function startClock(issue, d) {
94
+ const session = d.env.CLAUDE_CODE_SESSION_ID ?? "";
95
+ if (session)
96
+ d.clock.write(session, { issue, start: d.now().toISOString() });
97
+ }
98
+ async function post(c, issue, kind) {
99
+ return c.tickets.comment(issue, commentBody(kind, c.config.columns));
100
+ }
101
+ async function remove(c, commentId) {
102
+ await c.tickets.deleteComment(commentId);
103
+ }
104
+ /** What the ticket waits on that is still open; none when the ticket
105
+ * system records no blockers. */
106
+ export async function openBlockers(c, issue) {
107
+ if (!c.tickets.blockers)
108
+ return [];
109
+ const blockers = await c.tickets.blockers.list(issue);
110
+ return blockers.filter((b) => b.state === "open").map((b) => b.number);
111
+ }
112
+ /** The outcome of a claim, as `factory-build` reads it. */
113
+ export function claimOutcome(comments, mine) {
114
+ const { live } = workState(comments);
115
+ if (live?.id === mine)
116
+ return "claimed";
117
+ const holder = live && live.marker.kind === "claim" ? live.marker.id : "unknown";
118
+ return `held by ${holder}`;
119
+ }
120
+ async function claim(issue, who, d) {
121
+ // A run nobody is watching posts the stopped comment, so the card does not
122
+ // sit as "starting"; a session with a person at it just reports.
123
+ const stopUnattended = async (reason) => {
124
+ if (who.where === "actions")
125
+ await post(d, issue, {
126
+ kind: "stopped",
127
+ where: "actions",
128
+ issue,
129
+ reason,
130
+ });
131
+ };
132
+ let blockers;
133
+ try {
134
+ blockers = await openBlockers(d, issue);
135
+ }
136
+ catch (error) {
137
+ await stopUnattended("I could not read what this issue waits on").catch(() => { });
138
+ throw error;
139
+ }
140
+ if (blockers.length > 0) {
141
+ const list = blockers.map((n) => `#${n}`).join(", ");
142
+ await stopUnattended(`it waits on ${list}, which has to merge first`);
143
+ return `blocked by: ${list}`;
144
+ }
145
+ const mine = await post(d, issue, { kind: "claim", who });
146
+ await d.sleep(5000);
147
+ let comments;
148
+ try {
149
+ comments = await readComments(d, issue);
150
+ }
151
+ catch (error) {
152
+ await remove(d, mine).catch(() => { });
153
+ await stopUnattended("I could not read the claim back").catch(() => { });
154
+ throw error;
155
+ }
156
+ const outcome = claimOutcome(comments, mine);
157
+ if (outcome === "claimed") {
158
+ d.claimStore.write(issue, mine);
159
+ startClock(issue, d);
160
+ }
161
+ else
162
+ await remove(d, mine);
163
+ return outcome;
164
+ }
165
+ async function stillLive(issue, d) {
166
+ const mine = d.claimStore.read(issue);
167
+ if (mine === null)
168
+ return false;
169
+ return claimOutcome(await readComments(d, issue), mine) === "claimed";
170
+ }
171
+ /** Releases the claim this session holds on the ticket when no open pull
172
+ * request links it: `released`, `kept`, or `not live`. This session's claim
173
+ * is the one it stored, or the live one carrying its own place and ID. */
174
+ async function end(issue, who, d) {
175
+ const ticket = await d.tickets.read(issue);
176
+ const live = workState(ticket.comments).live;
177
+ const stored = d.claimStore.read(issue);
178
+ const mine = live !== null &&
179
+ live.marker.kind === "claim" &&
180
+ (live.id === stored ||
181
+ (live.marker.where === who.where && live.marker.id === who.id));
182
+ if (!mine)
183
+ return "not live";
184
+ const pulls = await d.openPulls(d.repository, d.codeHost);
185
+ if (reviewingPulls(ticket, pulls).length > 0)
186
+ return "kept";
187
+ await post(d, issue, { kind: "ended", issue });
188
+ return "released";
189
+ }
190
+ export function withLine(body, line) {
191
+ return `${body.trimEnd()}\n${line.trim()}\n`;
192
+ }
193
+ /** Adds a line to the open follow-ups issue, or opens the issue when none
194
+ * is open. The file leads the line, so each one names what it is about. */
195
+ async function followUp(file, text, d) {
196
+ const line = `- [ ] ${file}: ${text}`;
197
+ const open = (await d.tickets.listOpen()).filter((t) => t.labels.includes("follow-up"));
198
+ const [first] = open.sort((a, b) => a.number - b.number);
199
+ if (first) {
200
+ const issue = await d.tickets.read(first.number);
201
+ await d.tickets.writeBody(first.number, withLine(issue.body, line));
202
+ return `added to #${first.number}`;
203
+ }
204
+ const body = withLine('Small problems noticed while doing other work, one line each, built together once the owner approves this issue. See "Follow-ups" in `.claude/factory/rules.md`.\n', line);
205
+ const made = await d.tickets.open({
206
+ title: "Follow-ups",
207
+ labels: ["follow-up"],
208
+ body,
209
+ });
210
+ return `opened #${made}`;
211
+ }
212
+ /** Set the card's Status to Ready, as the owner would. */
213
+ async function moveToReady(issue, d) {
214
+ const found = await d.tickets.read(issue);
215
+ if (found.state !== "open")
216
+ throw new Error(`#${issue} is closed.`);
217
+ if (d.board === null)
218
+ throw new Error("The settings name no board.");
219
+ const ready = d.config.columns.Ready;
220
+ if (ready === null)
221
+ throw new Error(`This board has no column for ready. Tell a session to build #${issue}, or run factory build ${issue}.`);
222
+ const board = need(d.tickets, "board");
223
+ const read = await board.read();
224
+ const item = read.items.get(issue);
225
+ if (!item)
226
+ throw new Error(`#${issue} is not on the board.`);
227
+ if (item.status !== null && sameName(item.status, ready))
228
+ return;
229
+ const fields = checkFields(read.fields, d.config);
230
+ const option = fields.status.options?.find((o) => sameName(o.name, ready));
231
+ try {
232
+ await board.set(item.itemId, [
233
+ { field: fields.status.name, optionName: option?.name ?? ready },
234
+ ]);
235
+ }
236
+ catch (error) {
237
+ if (/INSUFFICIENT_SCOPES|required scopes/i.test(String(error)))
238
+ throw new Error("The GitHub CLI can read the board but not write it. Run: gh auth refresh -s project");
239
+ throw error;
240
+ }
241
+ }
242
+ /** The value after `name`, or undefined when it is absent; a usage error
243
+ * when it is present with nothing after it. */
244
+ function option(args, name) {
245
+ const at = args.indexOf(name);
246
+ if (at === -1)
247
+ return undefined;
248
+ const value = args[at + 1];
249
+ if (value === undefined || value.startsWith("--"))
250
+ throw new Error(USAGE);
251
+ return value;
252
+ }
253
+ /** Every value given for a repeatable option. */
254
+ function options(args, name) {
255
+ const values = [];
256
+ args.forEach((a, i) => {
257
+ if (a !== name)
258
+ return;
259
+ const value = args[i + 1];
260
+ if (value === undefined || value.startsWith("--"))
261
+ throw new Error(USAGE);
262
+ values.push(value);
263
+ });
264
+ return values;
265
+ }
266
+ /** A ticket for a reader: title, state, labels, body, and each comment with
267
+ * its ID and author. */
268
+ export function formatTicket(t) {
269
+ const lines = [
270
+ `#${t.number} ${t.title}`,
271
+ `state: ${t.state}`,
272
+ `labels: ${t.labels.join(", ") || "(none)"}`,
273
+ "",
274
+ t.body.trimEnd() || "(no body)",
275
+ ];
276
+ for (const c of t.comments)
277
+ lines.push("", `--- comment ${c.id} by ${c.author} at ${c.createdAt}`, c.body.trimEnd());
278
+ return lines;
279
+ }
280
+ const FIELDS = ["title", "state", "labels", "body"];
281
+ const READS_AND_WRITES = new Set([
282
+ "view",
283
+ "list",
284
+ "edit",
285
+ "comment",
286
+ "open",
287
+ "label",
288
+ "link",
289
+ "blockers",
290
+ "block",
291
+ "unblock",
292
+ "supports",
293
+ ]);
294
+ /** The commands that read or write a ticket for a skill. Null when
295
+ * `command` is not one of them. */
296
+ async function ticketCommand(command, args, d) {
297
+ const t = d.tickets;
298
+ const n = Number(args[0]);
299
+ const numbered = () => {
300
+ if (!Number.isInteger(n) || n <= 0)
301
+ throw new Error(USAGE);
302
+ return n;
303
+ };
304
+ const json = args.includes("--json");
305
+ switch (command) {
306
+ case "view": {
307
+ const ticket = await t.read(numbered());
308
+ const field = option(args, "--field");
309
+ if (json)
310
+ d.out(JSON.stringify(ticket, null, 2));
311
+ else if (field === undefined)
312
+ formatTicket(ticket).forEach(d.out);
313
+ else if (!FIELDS.includes(field))
314
+ throw new Error(`--field is one of ${FIELDS.join(", ")}.`);
315
+ else if (field === "labels")
316
+ ticket.labels.forEach(d.out);
317
+ else
318
+ d.out(String(ticket[field]));
319
+ return 0;
320
+ }
321
+ case "list": {
322
+ const label = option(args, "--label");
323
+ const title = option(args, "--title");
324
+ const kept = (await t.listOpen())
325
+ .filter((x) => label === undefined || x.labels.includes(label))
326
+ .filter((x) => title === undefined || x.title === title)
327
+ .sort((a, b) => a.number - b.number);
328
+ if (json)
329
+ d.out(JSON.stringify(kept, null, 2));
330
+ else
331
+ for (const x of kept)
332
+ d.out(`${x.number}\t${x.title}\t${x.labels.join(", ")}`);
333
+ return 0;
334
+ }
335
+ case "edit":
336
+ case "comment": {
337
+ const ticket = numbered();
338
+ const file = option(args, "--body-file");
339
+ const newTitle = command === "edit" ? option(args, "--title") : undefined;
340
+ if (!file && newTitle === undefined)
341
+ throw new Error(USAGE);
342
+ if (!file && options(args, "--attach").length)
343
+ throw new Error(USAGE);
344
+ if (newTitle !== undefined) {
345
+ refuseBareTags(newTitle);
346
+ await t.writeTitle(ticket, newTitle);
347
+ if (!file) {
348
+ d.out("edited");
349
+ return 0;
350
+ }
351
+ }
352
+ if (!file)
353
+ throw new Error(USAGE);
354
+ const attach = options(args, "--attach");
355
+ const body = d.readFile(file);
356
+ refuseBareTags(body);
357
+ const files = attach.length ? need(t, "attachments") : null;
358
+ if (command === "edit") {
359
+ if (files)
360
+ await files.writeBody(ticket, body, attach);
361
+ else
362
+ await t.writeBody(ticket, body);
363
+ d.out("edited");
364
+ }
365
+ else
366
+ d.out(String(files
367
+ ? await files.comment(ticket, body, attach)
368
+ : await t.comment(ticket, body)));
369
+ return 0;
370
+ }
371
+ case "open": {
372
+ const title = option(args, "--title");
373
+ const file = option(args, "--body-file");
374
+ if (!title || !file)
375
+ throw new Error(USAGE);
376
+ const body = d.readFile(file);
377
+ refuseBareTags(title);
378
+ refuseBareTags(body);
379
+ d.out(String(await t.open({ title, body, labels: options(args, "--label") })));
380
+ return 0;
381
+ }
382
+ case "label": {
383
+ const ticket = numbered();
384
+ const add = option(args, "--add");
385
+ const removed = option(args, "--remove");
386
+ const was = option(args, "--was-removed");
387
+ const given = [add, removed, was].filter((x) => x !== undefined);
388
+ if (given.length !== 1)
389
+ throw new Error(USAGE);
390
+ if (was !== undefined) {
391
+ const history = need(t, "label-history");
392
+ d.out((await history.wasRemoved(ticket, was)) ? "yes" : "no");
393
+ }
394
+ else if (add !== undefined) {
395
+ // GitHub labels a pull request through its ticket API too.
396
+ refuseOverride(add);
397
+ await t.addLabel(ticket, add);
398
+ d.out("added");
399
+ }
400
+ else {
401
+ await t.removeLabel(ticket, removed);
402
+ d.out("removed");
403
+ }
404
+ return 0;
405
+ }
406
+ case "link":
407
+ d.out(t.linkText(numbered()));
408
+ return 0;
409
+ case "blockers": {
410
+ const list = await need(t, "blockers").list(numbered());
411
+ for (const b of list)
412
+ d.out(`#${b.number} ${b.state}`);
413
+ return 0;
414
+ }
415
+ case "block":
416
+ case "unblock": {
417
+ const ticket = numbered();
418
+ const by = Number(option(args, "--by"));
419
+ if (!Number.isInteger(by) || by <= 0)
420
+ throw new Error(USAGE);
421
+ const blockers = need(t, "blockers");
422
+ if (command === "block")
423
+ await blockers.add(ticket, by);
424
+ else
425
+ await blockers.remove(ticket, by);
426
+ d.out(command === "block" ? "blocked" : "unblocked");
427
+ return 0;
428
+ }
429
+ default:
430
+ return null;
431
+ }
432
+ }
433
+ const USAGE = "Usage: npx --no-install factory ticket claim|still-live|stop|end|refining|waiting|refined|ready|cost|view|list|edit|comment|open|label|link|blockers|block|unblock|supports|follow-up ...";
434
+ export async function main(argv, deps) {
435
+ const [command, first, ...rest] = argv;
436
+ const issue = Number(first);
437
+ try {
438
+ // `supports` answers before anything is read: it names the groups.
439
+ const settings = await deps.settings();
440
+ const { repository, board } = targetOf(settings, deps.env);
441
+ const opened = await deps.open(settings, { repository, board });
442
+ const d = {
443
+ ...deps,
444
+ config: boardConfigOf(settings),
445
+ codeHost: settings.codeHost.type,
446
+ repository,
447
+ board,
448
+ ...opened,
449
+ };
450
+ if (command === "supports") {
451
+ if (!first || !GROUPS.includes(first))
452
+ throw new Error(`No group ${first ?? ""}: the groups are ${GROUPS.join(", ")}.`);
453
+ d.out(supports(d.tickets, first) ? "yes" : "no");
454
+ return 0;
455
+ }
456
+ if (command === "follow-up") {
457
+ if (!first || !rest[0])
458
+ throw new Error(USAGE);
459
+ d.out(await followUp(first, rest[0], d));
460
+ return 0;
461
+ }
462
+ const handled = await ticketCommand(command ?? "", first === undefined ? rest : [first, ...rest], d);
463
+ if (handled !== null)
464
+ return handled;
465
+ if (!command || !Number.isInteger(issue) || issue <= 0)
466
+ throw new Error(USAGE);
467
+ if (command === "still-live") {
468
+ const live = await stillLive(issue, d);
469
+ d.out(live ? "live" : "not live");
470
+ return live ? 0 : 3;
471
+ }
472
+ const who = sessionIdentity(d.env, d.runner(repository, settings.builds.runner));
473
+ switch (command) {
474
+ case "claim":
475
+ d.out(await claim(issue, who, d));
476
+ return 0;
477
+ case "stop": {
478
+ if (!rest[0])
479
+ throw new Error(USAGE);
480
+ if (!(await stillLive(issue, d))) {
481
+ d.out("not live; posted nothing");
482
+ return 3;
483
+ }
484
+ await post(d, issue, {
485
+ kind: "stopped",
486
+ where: who.where,
487
+ issue,
488
+ reason: rest[0],
489
+ cost: takeCost(issue, d),
490
+ });
491
+ d.out("released");
492
+ return 0;
493
+ }
494
+ case "end":
495
+ d.out(await end(issue, who, d));
496
+ return 0;
497
+ case "ready":
498
+ await moveToReady(issue, d);
499
+ d.out("ready");
500
+ return 0;
501
+ case "refining":
502
+ await post(d, issue, { kind: "refining", who });
503
+ startClock(issue, d);
504
+ break;
505
+ case "waiting":
506
+ await post(d, issue, { kind: "waiting", cost: takeCost(issue, d) });
507
+ break;
508
+ case "cost":
509
+ await post(d, issue, { kind: "cost", cost: takeCost(issue, d) });
510
+ break;
511
+ case "refined": {
512
+ const at = rest.indexOf("--before-file");
513
+ const before = at === -1 ? undefined : d.readFile(rest[at + 1]);
514
+ await post(d, issue, {
515
+ kind: "refined",
516
+ issue,
517
+ before,
518
+ cost: takeCost(issue, d),
519
+ });
520
+ break;
521
+ }
522
+ default:
523
+ throw new Error(USAGE);
524
+ }
525
+ d.out("posted");
526
+ return 0;
527
+ }
528
+ catch (error) {
529
+ // The steps print one line whatever happens; a read or write for a
530
+ // skill prints nothing on stdout, so nothing there reads as an answer.
531
+ if (!READS_AND_WRITES.has(command ?? ""))
532
+ deps.out(command === "claim" ? "could not read" : "failed");
533
+ console.error(error instanceof Error ? error.message : String(error));
534
+ return 1;
535
+ }
536
+ }
537
+ function claimPath(issue) {
538
+ return join(commonDir(), `work-claim-${issue}`);
539
+ }
540
+ /** `factory ticket ...` and `factory follow-up ...`. */
541
+ export async function run(argv) {
542
+ return main(argv, {
543
+ open: (settings, target) => openTickets(settings, target),
544
+ openPulls: (repository, codeHost) => openCodeHost(repository, codeHost).open(),
545
+ runner: (repository, name) => openRunner(repository, name),
546
+ settings: () => loadSettings(),
547
+ env: process.env,
548
+ sleep,
549
+ out: (line) => console.log(line),
550
+ readFile: (path) => readFileSync(path, "utf8"),
551
+ now: () => new Date(),
552
+ clock: { read: readClock, write: writeClock },
553
+ measure: (session, since) => measureSession(projectsDir(process.env), session, since),
554
+ claimStore: {
555
+ read: (issue) => {
556
+ const path = claimPath(issue);
557
+ return existsSync(path) ? Number(readFileSync(path, "utf8")) : null;
558
+ },
559
+ write: (issue, id) => writeFileSync(claimPath(issue), String(id)),
560
+ },
561
+ });
562
+ }
@@ -0,0 +1,128 @@
1
+ import type { Gh } from "../lib/gh.mts";
2
+ import { type Board, type BoardField, type NewField, type Ticket, type TicketComment, type Tickets } from "./types.mts";
3
+ import { type Transport } from "./transport.mts";
4
+ export type GithubOptions = {
5
+ transport: Transport;
6
+ /** owner/name */
7
+ repository: string;
8
+ /** The Project's number, or null with no board. */
9
+ board: number | null;
10
+ /** Who owns the Project; the repository's owner unless given. */
11
+ boardOwner?: string;
12
+ /** The GitHub CLI, for attachments, which have no API. Without it, the
13
+ * adapter has no attachments group. */
14
+ cli?: Gh;
15
+ /** The board's own names for the fields the sync reads, null for one it
16
+ * never writes. The factory's own names where not given. */
17
+ fieldNames?: {
18
+ session: string | null;
19
+ runsIn: string | null;
20
+ cost: string | null;
21
+ };
22
+ };
23
+ export declare const ISSUES_QUERY = "\nquery Tickets($owner: String!, $name: String!, $after: String) {\n repository(owner: $owner, name: $name) {\n open: issues(states: OPEN, first: 100, after: $after) {\n pageInfo { hasNextPage endCursor }\n nodes { ...issue }\n }\n closed: issues(states: CLOSED, first: 30, orderBy: {field: UPDATED_AT, direction: DESC}) {\n nodes { ...issue }\n }\n }\n}\nfragment issue on Issue {\n number title state closedAt body\n labels(first: 30) { nodes { name } }\n comments(last: 100) {\n nodes { databaseId createdAt body author { login } }\n }\n}";
24
+ type RawComments = {
25
+ nodes: {
26
+ databaseId: number;
27
+ createdAt: string;
28
+ body: string;
29
+ author: {
30
+ login: string;
31
+ } | null;
32
+ }[];
33
+ };
34
+ export type RawIssue = {
35
+ number: number;
36
+ title: string;
37
+ state: "OPEN" | "CLOSED";
38
+ closedAt: string | null;
39
+ body?: string | null;
40
+ labels: {
41
+ nodes: {
42
+ name: string;
43
+ }[];
44
+ };
45
+ comments: RawComments;
46
+ };
47
+ export type IssuesPage = {
48
+ data: {
49
+ repository: {
50
+ open: {
51
+ pageInfo: {
52
+ hasNextPage: boolean;
53
+ endCursor: string | null;
54
+ };
55
+ nodes: RawIssue[];
56
+ };
57
+ closed: {
58
+ nodes: RawIssue[];
59
+ };
60
+ };
61
+ };
62
+ };
63
+ export declare const toComments: (raw: RawComments | undefined) => TicketComment[];
64
+ export declare function fromRawIssue(raw: RawIssue): Ticket;
65
+ /** The tickets in every page of ISSUES_QUERY: the open ones, then the
66
+ * closed. */
67
+ export declare function fromIssuesPages(pages: IssuesPage[]): Ticket[];
68
+ export declare const BOARD_QUERY = "\nquery Board($owner: String!, $number: Int!, $after: String, $session: String!, $runsIn: String!, $cost: String!) {\n owner: repositoryOwner(login: $owner) {\n ... on ProjectV2Owner {\n projectV2(number: $number) {\n id\n title\n fields(first: 50) {\n nodes {\n ... on ProjectV2FieldCommon { id name dataType }\n ... on ProjectV2SingleSelectField { options { id name } }\n }\n }\n items(first: 100, after: $after) {\n pageInfo { hasNextPage endCursor }\n nodes {\n id\n content {\n ... on Issue { number repository { nameWithOwner } }\n }\n status: fieldValueByName(name: \"Status\") {\n ... on ProjectV2ItemFieldSingleSelectValue { name updatedAt }\n }\n session: fieldValueByName(name: $session) {\n ... on ProjectV2ItemFieldTextValue { text }\n }\n runsIn: fieldValueByName(name: $runsIn) {\n ... on ProjectV2ItemFieldSingleSelectValue { name }\n }\n cost: fieldValueByName(name: $cost) {\n ... on ProjectV2ItemFieldNumberValue { number }\n }\n }\n }\n }\n }\n }\n}";
69
+ type RawItem = {
70
+ id: string;
71
+ content: {
72
+ number?: number;
73
+ repository?: {
74
+ nameWithOwner: string;
75
+ };
76
+ } | null;
77
+ status: {
78
+ name?: string;
79
+ updatedAt?: string;
80
+ } | null;
81
+ session: {
82
+ text?: string;
83
+ } | null;
84
+ runsIn: {
85
+ name?: string;
86
+ } | null;
87
+ cost?: {
88
+ number?: number;
89
+ } | null;
90
+ };
91
+ export type BoardPage = {
92
+ data: {
93
+ owner: {
94
+ projectV2: {
95
+ id: string;
96
+ title?: string;
97
+ fields: {
98
+ nodes: BoardField[];
99
+ };
100
+ items: {
101
+ pageInfo: {
102
+ hasNextPage: boolean;
103
+ endCursor: string | null;
104
+ };
105
+ nodes: RawItem[];
106
+ };
107
+ } | null;
108
+ } | null;
109
+ };
110
+ };
111
+ export declare function toBoard(pages: BoardPage[], repository: string): Board;
112
+ /** The mutation that adds one field to a board, as a literal for the same
113
+ * reason as `setColumnsMutation`. */
114
+ export declare function addFieldMutation(project: string, field: NewField): string;
115
+ type StatusOption = {
116
+ id?: string;
117
+ name: string;
118
+ color: string;
119
+ description: string;
120
+ };
121
+ /** The mutation that sets a Status field's columns: GraphQL takes a list of
122
+ * objects only as a literal, so the strings are written as JSON, which is
123
+ * valid GraphQL. */
124
+ export declare function setColumnsMutation(field: string, options: StatusOption[]): string;
125
+ /** The id in the URL `gh issue comment` prints. */
126
+ export declare function commentIdFromUrl(url: string): number;
127
+ export declare function githubTickets(o: GithubOptions): Tickets;
128
+ export {};