@davidbyoung/software-factory 0.1.8 → 0.1.10

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 (69) hide show
  1. package/README.md +2 -0
  2. package/dist/agent/claude-code.mjs +15 -21
  3. package/dist/board.d.mts +20 -3
  4. package/dist/board.mjs +124 -38
  5. package/dist/cli.mjs +84 -9
  6. package/dist/code-host/github-setup.mjs +2 -2
  7. package/dist/code-host/github.d.mts +1 -1
  8. package/dist/code-host/github.mjs +29 -2
  9. package/dist/code-host/types.d.mts +16 -1
  10. package/dist/code-host/types.mjs +8 -0
  11. package/dist/columns-suggest.d.mts +25 -6
  12. package/dist/columns-suggest.mjs +119 -29
  13. package/dist/commands.d.mts +5 -2
  14. package/dist/commands.mjs +37 -12
  15. package/dist/config.d.mts +25 -3
  16. package/dist/config.mjs +159 -33
  17. package/dist/doctor.d.mts +6 -1
  18. package/dist/doctor.mjs +78 -18
  19. package/dist/explain.d.mts +5 -0
  20. package/dist/explain.mjs +36 -1
  21. package/dist/init.d.mts +10 -0
  22. package/dist/init.mjs +133 -31
  23. package/dist/lib/color.d.mts +11 -0
  24. package/dist/lib/color.mjs +15 -0
  25. package/dist/lib/gh.d.mts +6 -0
  26. package/dist/lib/gh.mjs +11 -1
  27. package/dist/lib/listed.d.mts +3 -2
  28. package/dist/lib/listed.mjs +5 -4
  29. package/dist/poller.d.mts +1 -1
  30. package/dist/poller.mjs +9 -6
  31. package/dist/pr.mjs +9 -1
  32. package/dist/preset-commands.d.mts +2 -0
  33. package/dist/preset-commands.mjs +18 -12
  34. package/dist/preset.mjs +3 -2
  35. package/dist/setup.d.mts +3 -0
  36. package/dist/site.d.mts +3 -0
  37. package/dist/site.mjs +8 -1
  38. package/dist/status.d.mts +5 -2
  39. package/dist/status.mjs +13 -22
  40. package/dist/sync.d.mts +7 -1
  41. package/dist/sync.mjs +17 -5
  42. package/dist/ticket-fields.d.mts +84 -0
  43. package/dist/ticket-fields.mjs +374 -0
  44. package/dist/ticket.d.mts +3 -0
  45. package/dist/ticket.mjs +35 -8
  46. package/dist/tickets/github-setup.mjs +1 -1
  47. package/dist/tickets/github.mjs +69 -0
  48. package/dist/tickets/index.d.mts +8 -1
  49. package/dist/tickets/index.mjs +67 -7
  50. package/dist/tickets/types.d.mts +27 -1
  51. package/dist/tickets/types.mjs +4 -0
  52. package/dist/tools.d.mts +1 -1
  53. package/docs/builds.md +26 -13
  54. package/docs/cli.md +73 -36
  55. package/docs/configuration.md +264 -59
  56. package/docs/design.md +10 -0
  57. package/docs/developing.md +49 -18
  58. package/docs/existing-repo.md +184 -34
  59. package/docs/github/by-hand.md +13 -1
  60. package/docs/github/setup.md +14 -2
  61. package/docs/presets.md +15 -3
  62. package/docs/quick-start.md +3 -3
  63. package/docs/skills.md +3 -1
  64. package/docs/updating.md +132 -5
  65. package/docs/workflow.md +1 -1
  66. package/package.json +4 -2
  67. package/settings.schema.json +82 -20
  68. package/skills/factory-build/SKILL.md +39 -7
  69. package/skills/factory-deps/SKILL.md +6 -4
package/README.md CHANGED
@@ -1,5 +1,7 @@
1
1
  # Software factory
2
2
 
3
+ [![Coverage](https://codecov.io/gh/davidbyoung/software-factory/graph/badge.svg)](https://codecov.io/gh/davidbyoung/software-factory)
4
+
3
5
  > **Early, and not yet for general use.** This is below 1.0: it changes
4
6
  > weekly, and any minor version may break what the one before it did,
5
7
  > without notice. Pin an exact version if you try it.
@@ -9,32 +9,26 @@ import { AGENT_KEY, AGENT_TOKEN } from "../parts.mjs";
9
9
  import { CLAUDE_MD, hasAnyFactoryHook, hasFactoryHooks, hasImport, SETTINGS_JSON, withoutHooks, withoutImport, } from "../sync.mjs";
10
10
  export const LABEL = "Claude Code";
11
11
  const COMMAND = "claude";
12
- const SYNC = "Run npx --no-install factory sync";
12
+ const SYNC = "Run factory sync";
13
13
  const READS = ["review", "cloud"];
14
14
  const read = (root, path) => existsSync(join(root, path)) ? readFileSync(join(root, path), "utf8") : null;
15
15
  export const claudeCodeSetup = {
16
- found: (c) => c.hasCommand(COMMAND)
17
- ? LABEL
18
- : `${LABEL}, which is not installed: sessions and its token need it`,
19
16
  steps: (c) => {
20
17
  const parts = READS.filter((p) => c.parts.has(p));
21
18
  if (!parts.length)
22
19
  return [];
23
- const installed = c.hasCommand(COMMAND);
24
- const name = installed ? AGENT_TOKEN : AGENT_KEY;
25
20
  return [
26
21
  {
27
22
  kind: "secret",
28
23
  needs: parts.map((part) => ({ part, anyOf: [AGENT_TOKEN, AGENT_KEY] })),
29
- storeAs: [name],
30
- intro: installed
31
- ? ["", `The coding agent's token: running ${COMMAND} setup-token...`]
32
- : [],
33
- get: installed ? { command: [COMMAND, "setup-token"] } : undefined,
34
- prompt: installed
35
- ? "Paste the token it printed (leave empty to do this later):"
36
- : "Paste an API key from the Claude Console (leave empty to do this later):",
37
- skipped: `No ${name} stored.`,
24
+ storeAs: [AGENT_TOKEN],
25
+ intro: [
26
+ "",
27
+ `The coding agent's token: running ${COMMAND} setup-token...`,
28
+ ],
29
+ get: { command: [COMMAND, "setup-token"] },
30
+ prompt: "Paste the token it printed (leave empty to do this later):",
31
+ skipped: `No ${AGENT_TOKEN} stored.`,
38
32
  stored: (names) => `Stored as ${names.join(", ")}.`,
39
33
  },
40
34
  ];
@@ -43,28 +37,28 @@ export const claudeCodeSetup = {
43
37
  hasImport(read(c.root, CLAUDE_MD))
44
38
  ? {
45
39
  state: "pass",
46
- text: `${LABEL}: ${CLAUDE_MD} imports the factory's rules`,
40
+ text: `${CLAUDE_MD} imports the factory's rules`,
47
41
  }
48
42
  : {
49
43
  state: "fail",
50
- text: `${LABEL}: ${CLAUDE_MD} imports the factory's rules`,
44
+ text: `${CLAUDE_MD} imports the factory's rules`,
51
45
  fix: SYNC,
52
46
  },
53
47
  hasFactoryHooks(read(c.root, SETTINGS_JSON))
54
48
  ? {
55
49
  state: "pass",
56
- text: `${LABEL}: ${SETTINGS_JSON} has the factory's hooks`,
50
+ text: `${SETTINGS_JSON} has the factory's hooks`,
57
51
  }
58
52
  : {
59
53
  state: "fail",
60
- text: `${LABEL}: ${SETTINGS_JSON} has the factory's hooks`,
54
+ text: `${SETTINGS_JSON} has the factory's hooks`,
61
55
  fix: SYNC,
62
56
  },
63
57
  c.hasCommand(COMMAND)
64
- ? { state: "pass", text: `${LABEL}: the ${COMMAND} command is installed` }
58
+ ? { state: "pass", text: `The ${COMMAND} command is installed` }
65
59
  : {
66
60
  state: "fail",
67
- text: `${LABEL}: the ${COMMAND} command is installed`,
61
+ text: `The ${COMMAND} command is installed`,
68
62
  fix: "Install Claude Code, then sign in",
69
63
  },
70
64
  ],
package/dist/board.d.mts CHANGED
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ import { type Paint } from "./lib/color.mts";
2
3
  import { type Settings } from "./config.mts";
3
4
  import { type Columns, type Board, type BoardField, type Derived, type PullRequest, type RepoSnapshot } from "./lib/work-status.mts";
4
5
  import { type Runner } from "./runner/index.mts";
@@ -47,9 +48,22 @@ export declare function inspectBoard(fields: BoardField[], cfg?: BoardConfig): I
47
48
  /** The board's fields, or an error naming everything that is wrong with
48
49
  * them. */
49
50
  export declare function checkFields(fields: BoardField[], cfg?: BoardConfig): Fields;
50
- /** The report `factory board check` prints: each state's column, each
51
- * field, then the notes and problems. */
52
- export declare function boardReport(number: number, board: Board, cfg: BoardConfig, settings: Pick<Settings, "builds">): string[];
51
+ /** A row of `factory board check`: a state, a column no state names, or a
52
+ * field the sync writes. `none` is a state whose column cannot be told,
53
+ * when the board has no Status field to read. */
54
+ export type BoardRow = {
55
+ state: "pass" | "fail" | "unknown" | "off" | "none";
56
+ key: string;
57
+ text: string;
58
+ };
59
+ /** What `factory board check` says of each state and each field. */
60
+ export declare function boardRows(fields: BoardField[], cfg: BoardConfig, settings: Pick<Settings, "builds">): {
61
+ columns: BoardRow[];
62
+ fields: BoardRow[];
63
+ };
64
+ /** The report `factory board check` prints: each state's column, then each
65
+ * field, under the setting each comes from. */
66
+ export declare function boardReport(number: number, board: Board, cfg: BoardConfig, settings: Pick<Settings, "builds">, paint?: Paint): string[];
53
67
  export type Plan = {
54
68
  number: number;
55
69
  itemId: string | null;
@@ -122,7 +136,10 @@ export type Deps = {
122
136
  * and the repository where FACTORY_BOARD_NUMBER and GITHUB_REPOSITORY do
123
137
  * not name them. */
124
138
  settings: () => Promise<Settings>;
139
+ paint?: Paint;
125
140
  };
126
141
  export declare function main(argv: string[], deps: Deps): Promise<number>;
142
+ /** The dependencies `run` gives `main`. */
143
+ export declare function boardDeps(argv: string[]): Deps;
127
144
  /** `factory board collect` and `factory board apply`. */
128
145
  export declare function run(argv: string[]): Promise<number>;
package/dist/board.mjs CHANGED
@@ -20,6 +20,7 @@
20
20
  //
21
21
  // Tickets and the board go through the ticket interface (`tickets/`); the
22
22
  // pull requests through `code-host/`.
23
+ import { colorOn, painter, plain, } from "./lib/color.mjs";
23
24
  import { readFileSync, writeFileSync } from "node:fs";
24
25
  import { join } from "node:path";
25
26
  import { columnsOf, fieldNamesOf, loadSettings, } from "./config.mjs";
@@ -139,41 +140,118 @@ export function checkFields(fields, cfg = DEFAULT_BOARD) {
139
140
  throw new Error(`The board: ${found.problems.join("; ")}.`);
140
141
  return { status: found.status, ...found.fields };
141
142
  }
142
- /** The report `factory board check` prints: each state's column, each
143
- * field, then the notes and problems. */
144
- export function boardReport(number, board, cfg, settings) {
145
- const found = inspectBoard(board.fields, cfg);
146
- const pad = (label) => ` ${label.padEnd(10)} `;
147
- const out = [
148
- board.title ? `Board ${number}, "${board.title}"` : `Board ${number}`,
149
- "",
143
+ const KIND_WORDS = {
144
+ TEXT: "text field",
145
+ SINGLE_SELECT: "single select field",
146
+ NUMBER: "number field",
147
+ };
148
+ /** What `factory board check` says of each state and each field. */
149
+ export function boardRows(fields, cfg, settings) {
150
+ const find = (name) => fields.find((f) => sameName(f.name, name));
151
+ const status = find("Status") ?? null;
152
+ const readable = status?.dataType === "SINGLE_SELECT";
153
+ const options = readable ? (status.options ?? []).map((o) => o.name) : [];
154
+ const ready = cfg.columns.Ready?.[0] ?? null;
155
+ const columns = Object.keys(STATE_KEYS).map((key) => {
156
+ const names = cfg.columns[STATE_KEYS[key]];
157
+ if (names === null)
158
+ return {
159
+ state: "off",
160
+ key,
161
+ text: key === "ready"
162
+ ? "none"
163
+ : `none, shows in ${columnFor(STATE_KEYS[key], cfg.columns)}`,
164
+ };
165
+ const joined = names.join(", ");
166
+ if (!readable)
167
+ return { state: "none", key, text: joined };
168
+ const missing = names.filter((n) => !options.some((o) => sameName(o, n)));
169
+ if (missing.length)
170
+ return {
171
+ state: "fail",
172
+ key,
173
+ text: `${joined}: no such column on the board${names.length > 1 ? `: ${missing.join(", ")}` : ""}`,
174
+ };
175
+ if (key === "ready" && settings.builds.trigger === "own-server")
176
+ return {
177
+ state: "unknown",
178
+ key,
179
+ text: `${joined}: the poller needs FACTORY_READY_COLUMN set to "${ready}"`,
180
+ };
181
+ return { state: "pass", key, text: joined };
182
+ });
183
+ for (const name of options)
184
+ if (statusOfColumn(name, cfg.columns) === null)
185
+ columns.push({
186
+ state: "unknown",
187
+ key: name,
188
+ text: "no state: left alone",
189
+ });
190
+ const rows = [
191
+ status === null
192
+ ? { state: "fail", key: "Status", text: "no such field" }
193
+ : readable
194
+ ? { state: "pass", key: "Status", text: "synced" }
195
+ : { state: "fail", key: "Status", text: "not a single select" },
150
196
  ];
151
- for (const key of Object.keys(STATE_KEYS)) {
152
- const status = STATE_KEYS[key];
153
- const column = cfg.columns[status];
154
- out.push(pad(key) +
155
- (column !== null
156
- ? column.join(", ")
157
- : key === "ready"
158
- ? "no column: builds start only when you ask"
159
- : `no column, shows in ${columnFor(status, cfg.columns)}`));
197
+ for (const kind of FIELD_KINDS) {
198
+ const name = cfg.fields[kind.key];
199
+ const key = kind.label;
200
+ if (name === null) {
201
+ rows.push({ state: "off", key, text: "off" });
202
+ continue;
203
+ }
204
+ const named = !sameName(name, DEFAULT_FIELDS[kind.key]);
205
+ const setting = `tickets.fields.${kind.setting}`;
206
+ const field = find(name);
207
+ if (!field) {
208
+ rows.push(named
209
+ ? { state: "fail", key, text: `no such field: ${name}` }
210
+ : { state: "unknown", key, text: "skipped: no such field" });
211
+ continue;
212
+ }
213
+ const wrong = field.dataType !== kind.type
214
+ ? `not a ${KIND_WORDS[kind.type]}`
215
+ : (() => {
216
+ const lacking = kind.options.filter((o) => !(field.options ?? []).some((x) => sameName(x.name, o)));
217
+ return lacking.length ? `lacks ${lacking.join(", ")}` : null;
218
+ })();
219
+ rows.push(wrong === null
220
+ ? { state: "pass", key, text: "synced" }
221
+ : {
222
+ state: "fail",
223
+ key,
224
+ text: named
225
+ ? `${name}: ${wrong}`
226
+ : `${wrong}: name another field in ${setting}, or set it to none`,
227
+ });
160
228
  }
161
- out.push("");
162
- for (const line of found.lines)
163
- out.push(pad(line.label) + line.text);
164
- const ready = cfg.columns.Ready?.[0] ?? null;
165
- const extra = [
166
- ...found.notes.map((n) => `Note: ${n}`),
167
- ...(ready !== null &&
168
- ready !== DEFAULT_COLUMNS.Ready[0] &&
169
- settings.builds.trigger === "own-server"
170
- ? [`Note: The poller needs FACTORY_READY_COLUMN set to "${ready}".`]
171
- : []),
172
- ...found.problems.map((p) => `Problem: ${p}.`),
229
+ return { columns, fields: rows };
230
+ }
231
+ const MARKS = {
232
+ pass: ["✓", "green"],
233
+ fail: ["✗", "red"],
234
+ unknown: ["?", "yellow"],
235
+ off: ["-", "dim"],
236
+ none: [" ", null],
237
+ };
238
+ /** The report `factory board check` prints: each state's column, then each
239
+ * field, under the setting each comes from. */
240
+ export function boardReport(number, board, cfg, settings, paint = plain) {
241
+ const rows = boardRows(board.fields, cfg, settings);
242
+ const row = (r) => {
243
+ const [mark, color] = MARKS[r.state];
244
+ return ` ${color ? paint(color, mark) : mark} ${r.key.padEnd(10)} ${r.text}`;
245
+ };
246
+ return [
247
+ board.title ? `Board ${number}, "${board.title}"` : `Board ${number}`,
248
+ "",
249
+ "tickets.columns",
250
+ ...rows.columns.map(row),
251
+ "",
252
+ "tickets.fields",
253
+ ...rows.fields.map(row),
173
254
  ];
174
- if (extra.length)
175
- out.push("", ...extra);
176
- return out;
177
255
  }
178
256
  /** What each issue's fields should hold, and which writes get them there.
179
257
  * A card's Session is an Actions run's page, which `runPage` gives for its
@@ -410,9 +488,12 @@ export async function main(argv, deps) {
410
488
  if (argv[0] === "check") {
411
489
  const found = await boardOps.read();
412
490
  const number = await projectNumber(deps);
413
- for (const line of boardReport(number, found, config, settings))
491
+ for (const line of boardReport(number, found, config, settings, d.paint))
414
492
  d.out(line);
415
- return inspectBoard(found.fields, config).problems.length ? 1 : 0;
493
+ const rows = boardRows(found.fields, config, settings);
494
+ return [...rows.columns, ...rows.fields].some((r) => r.state === "fail")
495
+ ? 1
496
+ : 0;
416
497
  }
417
498
  if (argv[0] === "apply") {
418
499
  const input = option(argv, "--in");
@@ -432,10 +513,10 @@ export async function main(argv, deps) {
432
513
  return 1;
433
514
  }
434
515
  }
435
- /** `factory board collect` and `factory board apply`. */
436
- export async function run(argv) {
516
+ /** The dependencies `run` gives `main`. */
517
+ export function boardDeps(argv) {
437
518
  const nowArg = option(argv, "--now");
438
- return main(argv, {
519
+ return {
439
520
  open: async (settings, target) => {
440
521
  const { tickets } = await openTickets(settings, target);
441
522
  return {
@@ -450,5 +531,10 @@ export async function run(argv) {
450
531
  readFile: (path) => readFileSync(path, "utf8"),
451
532
  writeFile: (path, text) => writeFileSync(path, text),
452
533
  settings: () => loadSettings(),
453
- });
534
+ paint: painter(colorOn()),
535
+ };
536
+ }
537
+ /** `factory board collect` and `factory board apply`. */
538
+ export async function run(argv) {
539
+ return main(argv, boardDeps(argv));
454
540
  }
package/dist/cli.mjs CHANGED
@@ -4,7 +4,7 @@
4
4
  //
5
5
  // factory COMMAND [ARGS]
6
6
  //
7
- // An unknown command, or none, prints the usage and exits 2.
7
+ // An unknown command, or none, prints the commands a person runs and exits 2.
8
8
  const TICKET_STEPS = [
9
9
  "refining",
10
10
  "waiting",
@@ -22,6 +22,7 @@ const TICKET_STEPS = [
22
22
  "open",
23
23
  "label",
24
24
  "link",
25
+ "branch",
25
26
  "blockers",
26
27
  "block",
27
28
  "unblock",
@@ -34,6 +35,7 @@ const PR_STEPS = [
34
35
  "resolve",
35
36
  "ready",
36
37
  "closes",
38
+ "for-branch",
37
39
  "comments",
38
40
  "comment",
39
41
  "comment-view",
@@ -85,6 +87,7 @@ const PR_ARGS = {
85
87
  label: "N --add LABEL | --remove LABEL",
86
88
  "review-pending": "N REVIEW",
87
89
  conflicts: "",
90
+ "for-branch": "BRANCH",
88
91
  uncovered: "[BASE] [LCOV]",
89
92
  };
90
93
  export const COMMANDS = [
@@ -203,6 +206,11 @@ export const COMMANDS = [
203
206
  args: "",
204
207
  run: async (argv) => (await import("./commands.mjs")).run(["specs-check", ...argv]),
205
208
  },
209
+ {
210
+ words: ["specs", "change-name"],
211
+ args: "N",
212
+ run: async (argv) => (await import("./commands.mjs")).run(["specs-change-name", ...argv]),
213
+ },
206
214
  {
207
215
  words: ["default-branch"],
208
216
  args: "",
@@ -284,14 +292,78 @@ export const COMMANDS = [
284
292
  run: async () => (await import("./guard.mjs")).run("ticket-text"),
285
293
  },
286
294
  ];
295
+ /** The commands a person runs, in the groups and words of docs/cli.md. */
296
+ const USAGE = [
297
+ [
298
+ "Setting up",
299
+ [
300
+ ["init", "Set a repository up, or turn a part on or off"],
301
+ [
302
+ "sync [--check]",
303
+ "Write the factory's files from your settings, or check they match",
304
+ ],
305
+ ["config check", "Check your settings"],
306
+ ["board check", "See how the factory reads your board"],
307
+ ["doctor", "Check everything, when something seems off"],
308
+ ],
309
+ ],
310
+ [
311
+ "Every day",
312
+ [
313
+ ["status [--watch]", "Each ticket's state and which session is on it"],
314
+ ["build N", "Build ticket N in the cloud"],
315
+ ["pr watch N", "Wait until pull request N needs you"],
316
+ ],
317
+ ],
318
+ [
319
+ "Now and then",
320
+ [
321
+ ["config get KEY", "Print one setting in effect"],
322
+ ["config explain", "Print every setting in effect, defaults included"],
323
+ ["plugins [ROLE]", "List the plugins the factory uses, by role"],
324
+ ["site compare", "Picture a website's pages before and after a change"],
325
+ ["site stop", "End the sites compare --keep left running"],
326
+ ["remove", "Take the factory out of this repository"],
327
+ ],
328
+ ],
329
+ [
330
+ "Presets",
331
+ [
332
+ ["preset add NAME", "Follow a preset"],
333
+ ["preset remove NAME", "Stop following one"],
334
+ ["preset choices", "See where two presets disagree, and choose"],
335
+ [
336
+ "preset choose KEY PRESET",
337
+ "Record one of those choices without questions",
338
+ ],
339
+ ["preset check", "Check a preset's own package before publishing it"],
340
+ ["preset changes REF", "See what a preset update changed since REF"],
341
+ ],
342
+ ],
343
+ [
344
+ "Your repository's commands",
345
+ [
346
+ ["gate", "Run the commands under commands.gate"],
347
+ ["test-one FILE [NAME]", "Run one test file, or one test in it"],
348
+ ["end-to-end FILE", "Run one end-to-end spec"],
349
+ ["specs check", "Check your written specs"],
350
+ ["specs change-name N", "Print the name of ticket N's spec change"],
351
+ ["default-branch", "Print the default branch's name"],
352
+ ],
353
+ ],
354
+ ];
355
+ const NAME_WIDTH = 21;
287
356
  export function usage() {
288
- const width = Math.max(...COMMANDS.map((c) => c.words.join(" ").length + 1 + c.args.length));
289
- return [
290
- "Usage: factory COMMAND [ARGS]",
291
- "",
292
- "Commands:",
293
- ...COMMANDS.map((c) => ` factory ${`${c.words.join(" ")} ${c.args}`.padEnd(width)}`).map((line) => line.trimEnd()),
294
- ].join("\n");
357
+ const lines = ["Usage: factory COMMAND"];
358
+ for (const [group, commands] of USAGE) {
359
+ lines.push("", group);
360
+ for (const [name, summary] of commands)
361
+ lines.push(...(name.length < NAME_WIDTH
362
+ ? [` ${name.padEnd(NAME_WIDTH)}${summary}`]
363
+ : [` ${name}`, ` ${" ".repeat(NAME_WIDTH)}${summary}`]));
364
+ }
365
+ lines.push("", 'The commands skills, hooks, and workflows run are under "Run for you" in docs/cli.md.');
366
+ return lines.join("\n");
295
367
  }
296
368
  /** The command `argv` names, the longest match first, with the arguments
297
369
  * left after its words; null when none matches. */
@@ -310,7 +382,10 @@ export async function main(argv) {
310
382
  // `guard` alone runs both guards, but `guard WORD` with a word that is
311
383
  // not a guard is a mistake, not a request for both.
312
384
  if (!found || (found.command.words.join(" ") === "guard" && found.rest[0])) {
313
- console.error(usage());
385
+ const asked = argv.length > 0 && argv[0] !== "--help" && argv[0] !== "-h";
386
+ console.error(asked
387
+ ? `factory has no command "${argv.join(" ")}".\n\n${usage()}`
388
+ : usage());
314
389
  return 2;
315
390
  }
316
391
  return (await found.command.run(found.rest)) ?? 0;
@@ -106,7 +106,7 @@ export const githubCodeHostSetup = {
106
106
  return [
107
107
  {
108
108
  state: "pass",
109
- text: `Signed in to the code host as ${await c.opened.codeHost.signedInAs()}`,
109
+ text: `Signed in as ${await c.opened.codeHost.signedInAs()}`,
110
110
  },
111
111
  ];
112
112
  }
@@ -114,7 +114,7 @@ export const githubCodeHostSetup = {
114
114
  return [
115
115
  {
116
116
  state: "fail",
117
- text: "Signed in to the code host",
117
+ text: "Signed in",
118
118
  fix: e instanceof Error ? e.message : String(e),
119
119
  },
120
120
  ];
@@ -1,4 +1,4 @@
1
- import type { Gh } from "../lib/gh.mts";
1
+ import { type Gh } from "../lib/gh.mts";
2
2
  import type { PullRequest } from "../lib/work-status.mts";
3
3
  import { type Transport } from "../tickets/transport.mts";
4
4
  import type { CodeHost, Thread } from "./types.mts";
@@ -1,6 +1,13 @@
1
+ // GitHub as the code host: pull requests, reviews, checks, and commit
2
+ // statuses. With `src/tickets/` and `src/runner/`, this is the only code
3
+ // that calls GitHub: every command reaches a pull request through here.
4
+ //
5
+ // GitHub serves a pull request's conversation comments and labels from its
6
+ // issues API, so those calls are here too, not in the ticket adapter.
7
+ import { GhError } from "../lib/gh.mjs";
1
8
  import { NotFoundError } from "../tickets/types.mjs";
2
9
  import { statusOf } from "../tickets/transport.mjs";
3
- import { NeedsScopeError } from "./types.mjs";
10
+ import { NeedsScopeError, NotSignedInError } from "./types.mjs";
4
11
  /** What a check wrote about its result: its title and its summary. */
5
12
  const reportOf = (output) => [output?.title, output?.summary].filter(Boolean).join("\n") || undefined;
6
13
  const endOf = (end) => ({
@@ -214,6 +221,19 @@ export function githubCodeHost(o) {
214
221
  const open = await t.rest("GET", `${API}/pulls?head=${owner}:${branch}&state=open`);
215
222
  return open[0]?.number ?? null;
216
223
  },
224
+ async lastForBranch(branch) {
225
+ const [newest] = await t.rest("GET", `${API}/pulls?head=${owner}:${encodeURIComponent(branch)}&state=all&sort=created&direction=desc&per_page=1`);
226
+ if (!newest)
227
+ return null;
228
+ return {
229
+ number: newest.number,
230
+ state: newest.state === "open"
231
+ ? "open"
232
+ : newest.merged_at
233
+ ? "merged"
234
+ : "closed",
235
+ };
236
+ },
217
237
  forCommit: async (sha) => (await t.rest("GET", `${API}/commits/${sha}/pulls`)).map(({ number, state }) => ({ number, state })),
218
238
  files: async (n) => (await list(`${API}/pulls/${n}/files?per_page=100`)).map((f) => ({
219
239
  path: f.filename,
@@ -348,7 +368,14 @@ export function githubCodeHost(o) {
348
368
  },
349
369
  address: (n) => `https://github.com/${o.repository}/pull/${n}`,
350
370
  async signedInAs() {
351
- return (await t.rest("GET", "user")).login;
371
+ try {
372
+ return (await t.rest("GET", "user")).login;
373
+ }
374
+ catch (e) {
375
+ if (statusOf(e) === 401 || (e instanceof GhError && e.exitCode === 4))
376
+ throw new NotSignedInError();
377
+ throw e;
378
+ }
352
379
  },
353
380
  async tokenOwner(token) {
354
381
  const response = await (o.fetch ?? fetch)("https://api.github.com/user", {
@@ -88,6 +88,12 @@ export type NewStatus = {
88
88
  description: string;
89
89
  link?: string;
90
90
  };
91
+ /** A pull request as `lastForBranch` finds it: `closed` is closed without
92
+ * merging. */
93
+ export type LastPull = {
94
+ number: number;
95
+ state: "open" | "merged" | "closed";
96
+ };
91
97
  /** A pull request to open: from the `head` branch into the `base` branch. */
92
98
  export type NewPull = {
93
99
  title: string;
@@ -112,6 +118,9 @@ export type CodeHost = {
112
118
  listOpen(): Promise<Pull[]>;
113
119
  /** The open pull request from this branch, or null. */
114
120
  forBranch(branch: string): Promise<number | null>;
121
+ /** The newest pull request from this branch, open or not, or null when
122
+ * none came from it. */
123
+ lastForBranch(branch: string): Promise<LastPull | null>;
115
124
  /** The pull requests that hold the commit, open or not. */
116
125
  forCommit(sha: string): Promise<{
117
126
  number: number;
@@ -172,7 +181,8 @@ export type CodeHost = {
172
181
  linking(skip?: number[]): Promise<PullRequest[]>;
173
182
  /** The address of a pull request's page. */
174
183
  address(pull: number): string;
175
- /** Who the code host's command-line tool is signed in as. */
184
+ /** Who the code host's command-line tool is signed in as. Rejects with
185
+ * NotSignedInError when it is signed in as nobody, or refused. */
176
186
  signedInAs(): Promise<string>;
177
187
  /** The account a token belongs to, and its scopes: null when the code
178
188
  * host does not say, as for a token with fine-grained permissions.
@@ -200,6 +210,11 @@ export type CodeHost = {
200
210
  /** What a token for the factory's jobs may need to do: push a branch,
201
211
  * change a workflow's file, and write the board. */
202
212
  export type TokenNeed = "push" | "workflows" | "board";
213
+ /** The code host's CLI is signed in as nobody, or its sign-in is
214
+ * refused. */
215
+ export declare class NotSignedInError extends Error {
216
+ constructor();
217
+ }
203
218
  /** A call the signed-in account's sign-in lacks the permission for. `fix`
204
219
  * is the command that asks for it. */
205
220
  export declare class NeedsScopeError extends Error {
@@ -1,3 +1,11 @@
1
+ /** The code host's CLI is signed in as nobody, or its sign-in is
2
+ * refused. */
3
+ export class NotSignedInError extends Error {
4
+ constructor() {
5
+ super("The code host's command-line tool is not signed in.");
6
+ this.name = "NotSignedInError";
7
+ }
8
+ }
1
9
  /** A call the signed-in account's sign-in lacks the permission for. `fix`
2
10
  * is the command that asks for it. */
3
11
  export class NeedsScopeError extends Error {
@@ -24,29 +24,48 @@ export declare function check(answer: unknown, columns: readonly string[], fromB
24
24
  export declare function toColumns(mapping: Mapping): Columns;
25
25
  /** The table of each state's column, as `factory board check` words it. */
26
26
  export declare function table(mapping: Mapping): string[];
27
- /** What `Yes` writes under `tickets.columns`: each state whose column is
28
- * not the factory's own name. */
27
+ /** What `Yes` writes under `tickets.columns`: every state, a column init
28
+ * adds by its factory name. */
29
29
  export declare function written(mapping: Mapping): [StateKey, string][];
30
+ /** Every state written with the factory's own name: a board init creates,
31
+ * one with no columns, and the answer No. */
32
+ export declare const FACTORY_LINES: [StateKey, string][];
30
33
  export type SuggestDeps = {
31
34
  ask: Ask;
32
35
  out: (line: string) => void;
33
36
  agent: Agent;
34
37
  /** The agent's registered label, which every line names it by. */
35
38
  label: string;
36
- hasCommand: (name: string) => boolean;
37
39
  };
38
40
  /** The board's columns, as init's first line about them says. */
39
41
  export declare const boardLine: (board: number, columns: readonly string[]) => string;
40
- /** The column step: the mapping's `tickets.columns` lines to write, none
41
- * for the factory's own columns, or 1 when init stops. */
42
+ /** The column step: the mapping's `tickets.columns` lines to write, or 1
43
+ * when init stops. */
42
44
  export declare function suggestColumns(d: SuggestDeps, o: {
43
45
  board: number;
44
46
  columns: readonly string[];
45
47
  fromBoard: boolean;
46
- }): Promise<[StateKey, string][] | "default" | 1>;
48
+ }): Promise<[StateKey, string][] | 1>;
47
49
  /** A ready column, asked for when builds from the board turn on and the
48
50
  * settings give ready none: one of the board's, or null to add Ready. */
49
51
  export declare function askReady(d: Pick<SuggestDeps, "ask" | "out">, o: {
50
52
  columns: readonly string[];
51
53
  current: Columns;
52
54
  }): Promise<string | null>;
55
+ /** A board with a column of each of the factory's names: init says so,
56
+ * shows them as the board spells them, and writes them. */
57
+ export declare function everyColumn(d: Pick<SuggestDeps, "out">, o: {
58
+ board: number;
59
+ columns: readonly string[];
60
+ }): [StateKey, string][];
61
+ /** A re-run's column step for a block that leaves states out. Each state
62
+ * left out takes the board's column of its factory name, when the board
63
+ * has one no written state names, since that is the column the factory
64
+ * read for it; any other is asked for. The lines to write for the states
65
+ * left out. */
66
+ export declare function fillColumns(d: Pick<SuggestDeps, "ask" | "out">, o: {
67
+ board: number;
68
+ columns: readonly string[];
69
+ written: Partial<Record<StateKey, readonly string[] | null>>;
70
+ fromBoard: boolean;
71
+ }): Promise<[StateKey, string][]>;