@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
package/dist/board.mjs ADDED
@@ -0,0 +1,456 @@
1
+ #!/usr/bin/env node
2
+ // Keep the board's Status, Session, and Runs in fields in step with the
3
+ // marker comments, and Cost with the cost markers. Only this script writes
4
+ // them, with one exception:
5
+ // `factory ticket ready` sets Status to Ready when the owner asks a local
6
+ // session to, and the rules read that as the owner's own move.
7
+ //
8
+ // In .github/workflows/factory-board-sync.yml it runs in two steps, so the board's
9
+ // token reaches only the second:
10
+ // collect with the workflow's token: posts the comments a closed pull
11
+ // request or the nightly run calls for, then saves the repository
12
+ // apply with FACTORY_BOARD_TOKEN: reads the board, checks its fields, and
13
+ // writes what changed
14
+ //
15
+ // Locally, to see what it would set without writing anything:
16
+ // npx --no-install factory board --dry-run
17
+ // npx --no-install factory board --dry-run --fixture DIR --now ISO
18
+ // The second reads repo.json, as collect saves it, and board.json, the
19
+ // board's recorded GraphQL pages, from DIR instead of GitHub.
20
+ //
21
+ // Tickets and the board go through the ticket interface (`tickets/`); the
22
+ // pull requests through `code-host/`.
23
+ import { readFileSync, writeFileSync } from "node:fs";
24
+ import { join } from "node:path";
25
+ import { columnsOf, fieldNamesOf, loadSettings, } from "./config.mjs";
26
+ import { DEFAULT_COLUMNS, STATE_KEYS, cardOf, columnFor, sameName, statusOfColumn, commentBody, derive, buildsPartOf, issueCost, toClear, toSnapshot, actionsRunLink, } from "./lib/work-status.mjs";
27
+ import { subscriptionDollars } from "./lib/pricing.mjs";
28
+ import { openCodeHost } from "./code-host/index.mjs";
29
+ import { openRunner } from "./runner/index.mjs";
30
+ import { toBoard } from "./tickets/github.mjs";
31
+ import { openTickets } from "./tickets/index.mjs";
32
+ import { need, readAll, } from "./tickets/types.mjs";
33
+ export const DEFAULT_FIELDS = {
34
+ session: "Session",
35
+ runsIn: "Runs in",
36
+ cost: "Cost",
37
+ };
38
+ export const DEFAULT_BOARD = {
39
+ columns: DEFAULT_COLUMNS,
40
+ fields: DEFAULT_FIELDS,
41
+ };
42
+ /** The columns and fields the settings name. */
43
+ export function boardConfigOf(s) {
44
+ return { columns: columnsOf(s), fields: fieldNamesOf(s) };
45
+ }
46
+ const FIELD_KINDS = [
47
+ {
48
+ key: "session",
49
+ setting: "session",
50
+ label: "Session",
51
+ type: "TEXT",
52
+ typeName: "Text",
53
+ options: [],
54
+ },
55
+ {
56
+ key: "runsIn",
57
+ setting: "runs-in",
58
+ label: "Runs in",
59
+ type: "SINGLE_SELECT",
60
+ typeName: "a single select",
61
+ options: ["Local", "Actions"],
62
+ },
63
+ {
64
+ key: "cost",
65
+ setting: "cost",
66
+ label: "Cost",
67
+ type: "NUMBER",
68
+ typeName: "a Number",
69
+ options: [],
70
+ },
71
+ ];
72
+ /** What the factory will do with a board's fields: the problems that stop
73
+ * it, and what each field and column means. The sync never creates or
74
+ * changes a field. */
75
+ export function inspectBoard(fields, cfg = DEFAULT_BOARD) {
76
+ const problems = [];
77
+ const find = (name) => fields.find((f) => sameName(f.name, name));
78
+ const status = find("Status") ?? null;
79
+ const notes = [];
80
+ if (status?.dataType !== "SINGLE_SELECT") {
81
+ problems.push("the Status field is missing or not a single select");
82
+ }
83
+ else {
84
+ const names = (status.options ?? []).map((o) => o.name);
85
+ const missing = Object.keys(STATE_KEYS).flatMap((key) => {
86
+ const column = cfg.columns[STATE_KEYS[key]];
87
+ return column !== null && !names.some((n) => sameName(n, column))
88
+ ? [`${column} (tickets.columns.${key})`]
89
+ : [];
90
+ });
91
+ if (missing.length)
92
+ problems.push(`the Status field lacks ${missing.join(", ")}`);
93
+ for (const name of names)
94
+ if (statusOfColumn(name, cfg.columns) === null)
95
+ notes.push(`cards in "${name}" are left alone. No state names that column.`);
96
+ }
97
+ const out = { session: null, runsIn: null, cost: null };
98
+ const lines = [
99
+ { label: "Status", text: status ? "written" : "missing" },
100
+ ];
101
+ for (const kind of FIELD_KINDS) {
102
+ const name = cfg.fields[kind.key];
103
+ if (name === null) {
104
+ lines.push({ label: kind.label, text: "never written: set to none" });
105
+ continue;
106
+ }
107
+ const named = !sameName(name, DEFAULT_FIELDS[kind.key]);
108
+ const key = `tickets.fields.${kind.setting}`;
109
+ const field = find(name);
110
+ if (!field) {
111
+ if (named)
112
+ problems.push(`the ${name} field is missing or not ${kind.typeName} (${key})`);
113
+ else
114
+ lines.push({
115
+ label: kind.label,
116
+ text: `skipped: the board has no field named ${name}`,
117
+ });
118
+ continue;
119
+ }
120
+ const lacking = field.dataType !== kind.type
121
+ ? null
122
+ : kind.options.filter((o) => !(field.options ?? []).some((x) => sameName(x.name, o)));
123
+ if (field.dataType !== kind.type || lacking.length) {
124
+ const what = lacking && lacking.length
125
+ ? `lacks ${lacking.join(", ")}`
126
+ : `is not ${kind.typeName}`;
127
+ problems.push(named
128
+ ? `the ${name} field ${lacking?.length ? what : `is missing or not ${kind.typeName}`} (${key})`
129
+ : `the ${name} field ${what}: name another field in ${key}, or set it to none`);
130
+ continue;
131
+ }
132
+ out[kind.key] = field;
133
+ lines.push({ label: kind.label, text: "written" });
134
+ }
135
+ return { status, fields: out, lines, notes, problems };
136
+ }
137
+ /** The board's fields, or an error naming everything that is wrong with
138
+ * them. */
139
+ export function checkFields(fields, cfg = DEFAULT_BOARD) {
140
+ const found = inspectBoard(fields, cfg);
141
+ if (found.problems.length)
142
+ throw new Error(`The board: ${found.problems.join("; ")}.`);
143
+ return { status: found.status, ...found.fields };
144
+ }
145
+ /** The report `factory board check` prints: each state's column, each
146
+ * field, then the notes and problems. */
147
+ export function boardReport(number, board, cfg, settings) {
148
+ const found = inspectBoard(board.fields, cfg);
149
+ const pad = (label) => ` ${label.padEnd(10)} `;
150
+ const out = [
151
+ board.title ? `Board ${number}, "${board.title}"` : `Board ${number}`,
152
+ "",
153
+ ];
154
+ for (const key of Object.keys(STATE_KEYS)) {
155
+ const status = STATE_KEYS[key];
156
+ const column = cfg.columns[status];
157
+ out.push(pad(key) +
158
+ (column !== null
159
+ ? column
160
+ : key === "ready"
161
+ ? "no column: builds start only when you ask"
162
+ : `no column, shows in ${columnFor(status, cfg.columns)}`));
163
+ }
164
+ out.push("");
165
+ for (const line of found.lines)
166
+ out.push(pad(line.label) + line.text);
167
+ const ready = cfg.columns.Ready;
168
+ const extra = [
169
+ ...found.notes.map((n) => `Note: ${n}`),
170
+ ...(ready !== null &&
171
+ ready !== DEFAULT_COLUMNS.Ready &&
172
+ settings.builds.trigger !== "manual"
173
+ ? [`Note: The poller needs FACTORY_READY_COLUMN set to "${ready}".`]
174
+ : []),
175
+ ...found.problems.map((p) => `Problem: ${p}.`),
176
+ ];
177
+ if (extra.length)
178
+ out.push("", ...extra);
179
+ return out;
180
+ }
181
+ /** What each issue's fields should hold, and which writes get them there.
182
+ * A card's Session is an Actions run's page, which `runPage` gives for its
183
+ * ID, and any other session as it is. */
184
+ export function planSync(snapshot, board, repository, runPage, cfg = DEFAULT_BOARD) {
185
+ const owner = repository.split("/")[0];
186
+ const everyPull = [...snapshot.pulls, ...(snapshot.donePulls ?? [])];
187
+ const fields = checkFields(board.fields, cfg);
188
+ return snapshot.issues.map((issue) => {
189
+ const derived = derive(issue, cardOf(board, issue.number, cfg.columns), snapshot.pulls, cfg.columns);
190
+ const listPrice = issueCost(issue, everyPull, owner);
191
+ const cost = listPrice === null
192
+ ? null
193
+ : Math.round(subscriptionDollars(listPrice) * 100) / 100;
194
+ const item = board.items.get(issue.number);
195
+ const base = {
196
+ number: issue.number,
197
+ itemId: item?.itemId ?? null,
198
+ derived,
199
+ cost,
200
+ };
201
+ if (item?.status != null &&
202
+ statusOfColumn(item.status, cfg.columns) === null)
203
+ return { ...base, writes: [], unmapped: item.status };
204
+ const session = actionsRunLink(derived, runPage) ?? derived.session;
205
+ const runsIn = derived.runsIn;
206
+ const column = columnFor(derived.status, cfg.columns);
207
+ const option = fields.status.options?.find((o) => sameName(o.name, column));
208
+ const writes = [];
209
+ if (item?.status == null || !sameName(item.status, column))
210
+ writes.push({
211
+ field: fields.status.name,
212
+ optionName: option?.name ?? column,
213
+ });
214
+ if (fields.session && (item?.session ?? "") !== session)
215
+ writes.push(session
216
+ ? { field: fields.session.name, text: session }
217
+ : { field: fields.session.name, clear: true });
218
+ if (fields.runsIn && (item?.runsIn ?? "") !== runsIn) {
219
+ const runsInOption = fields.runsIn.options?.find((o) => sameName(o.name, runsIn));
220
+ writes.push(runsIn
221
+ ? {
222
+ field: fields.runsIn.name,
223
+ optionName: runsInOption?.name ?? runsIn,
224
+ }
225
+ : { field: fields.runsIn.name, clear: true });
226
+ }
227
+ if (fields.cost && (item?.cost ?? null) !== cost)
228
+ writes.push(cost === null
229
+ ? { field: fields.cost.name, clear: true }
230
+ : { field: fields.cost.name, number: cost });
231
+ return { ...base, writes };
232
+ });
233
+ }
234
+ export function logLine(plan) {
235
+ const d = plan.derived;
236
+ if (plan.unmapped !== undefined)
237
+ return `#${plan.number} card is in "${plan.unmapped}", which no state names (left alone)`;
238
+ const cost = plan.cost === null ? "(empty)" : plan.cost.toFixed(2);
239
+ const values = `Status=${d.status}, Session=${d.session || "(empty)"}, Runs in=${d.runsIn || "(empty)"}, Cost=${cost}`;
240
+ if (plan.writes.length === 0)
241
+ return `#${plan.number} ${values} (unchanged)`;
242
+ const added = plan.itemId ? "" : "added to the board; ";
243
+ return `#${plan.number} ${values} (${added}set ${plan.writes.map((w) => w.field).join(", ")})`;
244
+ }
245
+ /** The comments a closed pull request calls for: one on each issue it
246
+ * closes when it was not merged, and one on each open follow-ups issue it
247
+ * built part of without closing. */
248
+ export function closedPullComments(event, closes, openFollowUps, columns = DEFAULT_COLUMNS) {
249
+ if (event.action !== "closed")
250
+ return [];
251
+ const pull = event.pull_request;
252
+ const closedKind = (issue) => ({
253
+ kind: "pull-closed",
254
+ issue,
255
+ pull: pull.number,
256
+ });
257
+ const comments = [];
258
+ if (!pull.merged)
259
+ for (const issue of closes)
260
+ comments.push({ issue, body: commentBody(closedKind(issue), columns) });
261
+ for (const followUps of openFollowUps) {
262
+ if (closes.includes(followUps) || !buildsPartOf(pull.body ?? "", followUps))
263
+ continue;
264
+ comments.push({
265
+ issue: followUps,
266
+ body: commentBody(pull.merged
267
+ ? { kind: "follow-ups-merged", pull: pull.number }
268
+ : closedKind(followUps), columns),
269
+ });
270
+ }
271
+ return comments;
272
+ }
273
+ /** The nightly run's clears: claims and starts over 24 hours old with no
274
+ * pull request. */
275
+ export function nightlyComments(snapshot, now, columns = DEFAULT_COLUMNS) {
276
+ return snapshot.issues.flatMap((issue) => {
277
+ const clear = toClear(issue, snapshot.pulls, now);
278
+ if (!clear)
279
+ return [];
280
+ return [
281
+ {
282
+ issue: issue.number,
283
+ body: commentBody(clear.kind === "claim"
284
+ ? { kind: "cleared-claim", issue: issue.number, since: clear.since }
285
+ : {
286
+ kind: "cleared-start",
287
+ issue: issue.number,
288
+ since: clear.since,
289
+ }, columns),
290
+ },
291
+ ];
292
+ });
293
+ }
294
+ async function postAll(comments, d, dryRun) {
295
+ for (const c of comments) {
296
+ const first = c.body.split("\n")[0];
297
+ if (dryRun) {
298
+ d.out(`would comment on #${c.issue}: ${first}`);
299
+ continue;
300
+ }
301
+ await d.tickets.comment(c.issue, c.body);
302
+ d.out(`commented on #${c.issue}: ${first}`);
303
+ }
304
+ }
305
+ async function read(d) {
306
+ const [tickets, pulls] = await Promise.all([
307
+ readAll(d.tickets),
308
+ d.pulls.open({ costs: true }),
309
+ ]);
310
+ const donePulls = await d.pulls.linking(pulls.map((p) => p.number));
311
+ return { tickets, pulls, donePulls };
312
+ }
313
+ const snapshotOf = (saved, now) => toSnapshot(saved.tickets, saved.pulls, now, saved.donePulls);
314
+ async function collect(d, opts) {
315
+ let saved = await read(d);
316
+ let snapshot = snapshotOf(saved, d.now());
317
+ if (opts.eventName === "pull_request_target" && opts.event) {
318
+ const event = JSON.parse(d.readFile(opts.event));
319
+ if (event.action === "closed") {
320
+ const followUps = snapshot.issues
321
+ .filter((i) => i.state === "open" && i.labels.includes("follow-up"))
322
+ .map((i) => i.number);
323
+ const comments = closedPullComments(event, await d.pulls.closes(event.pull_request.number), followUps, d.config.columns);
324
+ await postAll(comments, d, opts.dryRun);
325
+ if (comments.length && !opts.dryRun) {
326
+ saved = await read(d);
327
+ snapshot = snapshotOf(saved, d.now());
328
+ }
329
+ }
330
+ }
331
+ if (opts.nightly) {
332
+ const comments = nightlyComments(snapshot, d.now(), d.config.columns);
333
+ await postAll(comments, d, opts.dryRun);
334
+ if (comments.length && !opts.dryRun)
335
+ saved = await read(d);
336
+ }
337
+ return saved;
338
+ }
339
+ /** Writes the board, through `board`: adds each ticket's card it lacks and
340
+ * sets the fields that changed. */
341
+ async function apply(saved, board, d, write) {
342
+ const inspected = inspectBoard(board.fields, d.config);
343
+ if (inspected.problems.length)
344
+ throw new Error(`The board: ${inspected.problems.join("; ")}.`);
345
+ for (const line of inspected.lines)
346
+ if (line.text.startsWith("skipped"))
347
+ d.out(`${line.label} ${line.text}`);
348
+ const plans = planSync(snapshotOf(saved, d.now()), board, d.repository, d.runPage, d.config);
349
+ for (const plan of plans) {
350
+ d.out(logLine(plan));
351
+ if (!write || plan.writes.length === 0)
352
+ continue;
353
+ const itemId = plan.itemId ?? (await write.add(plan.number));
354
+ await write.set(itemId, plan.writes);
355
+ }
356
+ }
357
+ function option(argv, name) {
358
+ const at = argv.indexOf(name);
359
+ return at === -1 ? undefined : argv[at + 1];
360
+ }
361
+ /** The board's number: FACTORY_BOARD_NUMBER where it is set, and
362
+ * otherwise `tickets.board` in the settings. */
363
+ async function projectNumber(d) {
364
+ if (d.env.FACTORY_BOARD_NUMBER) {
365
+ const number = Number(d.env.FACTORY_BOARD_NUMBER);
366
+ if (!Number.isInteger(number) || number < 1)
367
+ throw new Error("FACTORY_BOARD_NUMBER is not a board number.");
368
+ return number;
369
+ }
370
+ const board = (await d.settings()).tickets.board;
371
+ if (board === null)
372
+ throw new Error("tickets.board is not set.");
373
+ return board;
374
+ }
375
+ export async function main(argv, deps) {
376
+ const dryRun = argv.includes("--dry-run");
377
+ try {
378
+ const settings = await deps.settings();
379
+ const config = boardConfigOf(settings);
380
+ const repository = deps.env.GITHUB_REPOSITORY || settings.repository;
381
+ const runner = deps.runner(repository, settings.builds.runner);
382
+ const runPage = (id) => runner.runPage(id);
383
+ const fixture = option(argv, "--fixture");
384
+ if (argv[0] !== "collect" &&
385
+ argv[0] !== "apply" &&
386
+ argv[0] !== "check" &&
387
+ !dryRun)
388
+ throw new Error("Run collect, apply, or check, or --dry-run.");
389
+ if (fixture) {
390
+ const saved = JSON.parse(deps.readFile(join(fixture, "repo.json")));
391
+ const boardPages = JSON.parse(deps.readFile(join(fixture, "board.json")));
392
+ await apply(saved, toBoard(boardPages, repository), { ...deps, repository, config, runPage }, null);
393
+ return 0;
394
+ }
395
+ const board = argv[0] === "collect" ? null : await projectNumber(deps);
396
+ const opened = await deps.open(settings, { repository, board });
397
+ const d = { ...deps, config, repository, runPage, ...opened };
398
+ if (argv[0] === "collect") {
399
+ const out = option(argv, "--out");
400
+ if (!out)
401
+ throw new Error("collect needs --out FILE.");
402
+ const saved = await collect(d, {
403
+ event: option(argv, "--event"),
404
+ eventName: option(argv, "--event-name"),
405
+ nightly: option(argv, "--event-name") === "schedule",
406
+ dryRun,
407
+ });
408
+ d.writeFile(out, JSON.stringify(saved));
409
+ return 0;
410
+ }
411
+ const boardOps = need(d.tickets, "board");
412
+ if (argv[0] === "check") {
413
+ const found = await boardOps.read();
414
+ const number = await projectNumber(deps);
415
+ for (const line of boardReport(number, found, config, settings))
416
+ d.out(line);
417
+ return inspectBoard(found.fields, config).problems.length ? 1 : 0;
418
+ }
419
+ if (argv[0] === "apply") {
420
+ const input = option(argv, "--in");
421
+ if (!input)
422
+ throw new Error("apply needs --in FILE.");
423
+ if (!d.env.GH_TOKEN)
424
+ throw new Error("FACTORY_BOARD_TOKEN is not set.");
425
+ await apply(JSON.parse(d.readFile(input)), await boardOps.read(), d, dryRun ? null : boardOps);
426
+ return 0;
427
+ }
428
+ const saved = await collect(d, { nightly: false, dryRun: true });
429
+ await apply(saved, await boardOps.read(), d, null);
430
+ return 0;
431
+ }
432
+ catch (error) {
433
+ console.error(error instanceof Error ? error.message : String(error));
434
+ return 1;
435
+ }
436
+ }
437
+ /** `factory board collect` and `factory board apply`. */
438
+ export async function run(argv) {
439
+ const nowArg = option(argv, "--now");
440
+ return main(argv, {
441
+ open: async (settings, target) => {
442
+ const { tickets } = await openTickets(settings, target);
443
+ return {
444
+ tickets,
445
+ pulls: openCodeHost(target.repository, settings.codeHost.type),
446
+ };
447
+ },
448
+ runner: (repository, name) => openRunner(repository, name),
449
+ env: process.env,
450
+ now: () => (nowArg ? new Date(nowArg) : new Date()),
451
+ out: (line) => console.log(line),
452
+ readFile: (path) => readFileSync(path, "utf8"),
453
+ writeFile: (path, text) => writeFileSync(path, text),
454
+ settings: () => loadSettings(),
455
+ });
456
+ }
@@ -0,0 +1,18 @@
1
+ import { type Settings } from "./config.mts";
2
+ import { type CodeHost } from "./code-host/index.mts";
3
+ import { type Runner } from "./runner/index.mts";
4
+ export type Deps = {
5
+ settings: () => Promise<Settings>;
6
+ env: Record<string, string | undefined>;
7
+ /** The code host of that name, whose default branch a build runs on. */
8
+ codeHost: (repository: string, type: string) => CodeHost;
9
+ /** The runner of that name. */
10
+ runner: (repository: string, name: string) => Runner;
11
+ now: () => Date;
12
+ sleep: (ms: number) => Promise<unknown>;
13
+ out: (line: string) => void;
14
+ err: (line: string) => void;
15
+ };
16
+ export declare function main(argv: string[], d: Deps): Promise<number>;
17
+ /** `factory build N`. */
18
+ export declare function run(argv: string[]): Promise<number>;
package/dist/build.mjs ADDED
@@ -0,0 +1,60 @@
1
+ // Starts a build of a ticket on the runner, on the default branch, and
2
+ // prints the run's link.
3
+ //
4
+ // npx --no-install factory build N
5
+ //
6
+ // The runner may answer the start with no run, so the command looks for it.
7
+ // When none appears within 15 seconds it prints the link to the page that
8
+ // lists builds instead. A refused start exits 1 with the runner's error.
9
+ import { setTimeout as sleep } from "node:timers/promises";
10
+ import { loadSettings, targetOf } from "./config.mjs";
11
+ import { openCodeHost } from "./code-host/index.mjs";
12
+ import { openRunner } from "./runner/index.mjs";
13
+ const USAGE = "Usage: factory build N";
14
+ /** How long to look for the run, and how often. */
15
+ const FIND_FOR_MS = 15_000;
16
+ const EVERY_MS = 3_000;
17
+ export async function main(argv, d) {
18
+ const ticket = Number(argv[0]);
19
+ if (argv.length !== 1 || !Number.isInteger(ticket) || ticket <= 0) {
20
+ d.err(USAGE);
21
+ return 2;
22
+ }
23
+ try {
24
+ const settings = await d.settings();
25
+ const { repository } = targetOf(settings, d.env);
26
+ const runner = d.runner(repository, settings.builds.runner);
27
+ const branch = await d
28
+ .codeHost(repository, settings.codeHost.type)
29
+ .defaultBranch();
30
+ const since = d.now().getTime();
31
+ await runner.startBuild(ticket, branch);
32
+ let link = null;
33
+ for (;;) {
34
+ link = await runner.findBuild(ticket, since);
35
+ if (link || d.now().getTime() - since >= FIND_FOR_MS)
36
+ break;
37
+ await d.sleep(EVERY_MS);
38
+ }
39
+ d.out(`Started a build of #${ticket} in GitHub Actions:`);
40
+ d.out(link ?? runner.buildsPage());
41
+ return 0;
42
+ }
43
+ catch (error) {
44
+ d.err(error instanceof Error ? error.message : String(error));
45
+ return 1;
46
+ }
47
+ }
48
+ /** `factory build N`. */
49
+ export async function run(argv) {
50
+ return main(argv, {
51
+ settings: () => loadSettings(),
52
+ env: process.env,
53
+ codeHost: (repository, type) => openCodeHost(repository, type),
54
+ runner: (repository, name) => openRunner(repository, name),
55
+ now: () => new Date(),
56
+ sleep,
57
+ out: (line) => console.log(line),
58
+ err: (line) => console.error(line),
59
+ });
60
+ }
package/dist/cli.d.mts ADDED
@@ -0,0 +1,17 @@
1
+ type Run = (argv: string[]) => Promise<number | void>;
2
+ /** A command: the words that name it, what it takes, and how it runs. */
3
+ type Command = {
4
+ words: string[];
5
+ args: string;
6
+ run: Run;
7
+ };
8
+ export declare const COMMANDS: Command[];
9
+ export declare function usage(): string;
10
+ /** The command `argv` names, the longest match first, with the arguments
11
+ * left after its words; null when none matches. */
12
+ export declare function resolveCommand(argv: string[]): {
13
+ command: Command;
14
+ rest: string[];
15
+ } | null;
16
+ export declare function main(argv: string[]): Promise<number>;
17
+ export {};