@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/dist/site.mjs CHANGED
@@ -317,13 +317,20 @@ async function compare(argv) {
317
317
  cleanup();
318
318
  }
319
319
  }
320
+ /** What `factory site stop` says: a kept comparison is always two sites,
321
+ * this branch's and the base's. */
322
+ export function stopMessage(stopped) {
323
+ return stopped
324
+ ? "Stopped the 2 sites site compare --keep left running."
325
+ : "No sites were left running.";
326
+ }
320
327
  export async function run(argv) {
321
328
  const [command, ...rest] = argv;
322
329
  try {
323
330
  if (command === "compare")
324
331
  return await compare(rest);
325
332
  if (command === "stop") {
326
- stopKept(repoRoot());
333
+ console.log(stopMessage(stopKept(repoRoot())));
327
334
  return 0;
328
335
  }
329
336
  console.error("Usage: factory site compare | site stop");
package/dist/status.d.mts CHANGED
@@ -51,8 +51,9 @@ export type Style = {
51
51
  columns?: Columns;
52
52
  };
53
53
  export declare const PLAIN: Style;
54
- /** A terminal unless NO_COLOR is set to anything (no-color.org). */
55
- export declare function styleFor(isTTY: boolean | undefined, columns: number | undefined, noColor: string | undefined): Style;
54
+ /** Colors, links, and fitting to the window go together, where `colorOn`
55
+ * says the output is colored. */
56
+ export declare function styleFor(color: boolean, columns: number | undefined): Style;
56
57
  /** One reviewer's row under its card: a mark that carries the result
57
58
  * without color, the name, the model, the result, how long it ran, and its
58
59
  * cost in subscription dollars. */
@@ -96,5 +97,7 @@ export type Deps = {
96
97
  * frame as tall as the window. */
97
98
  export declare function frame(lines: string[]): string;
98
99
  export declare function main(argv: string[], d: Deps): Promise<number>;
100
+ /** The style for what `run` prints to stdout. */
101
+ export declare const terminalStyle: () => Style;
99
102
  /** `factory status [--watch]`, and `factory session-start`'s second half. */
100
103
  export declare function run(argv: string[]): Promise<number>;
package/dist/status.mjs CHANGED
@@ -11,6 +11,7 @@
11
11
  // The repository and the board come from the factory's settings, whose
12
12
  // loader needs dependencies installed; before npm ci the hook prints
13
13
  // nothing.
14
+ import { colorOn, painter } from "./lib/color.mjs";
14
15
  import { setTimeout as sleep } from "node:timers/promises";
15
16
  import { NO_DEPENDENCIES, SettingsError, loadSettings, targetOf, } from "./config.mjs";
16
17
  import { appSessionLink } from "./lib/gh.mjs";
@@ -114,26 +115,14 @@ watch = watchOf("own-server", 5), columns = DEFAULT_COLUMNS) {
114
115
  return { rows, closed };
115
116
  }
116
117
  export const PLAIN = { color: false, width: null };
117
- /** A terminal unless NO_COLOR is set to anything (no-color.org). */
118
- export function styleFor(isTTY, columns, noColor) {
119
- return isTTY && !noColor ? { color: true, width: columns ?? 80 } : PLAIN;
118
+ /** Colors, links, and fitting to the window go together, where `colorOn`
119
+ * says the output is colored. */
120
+ export function styleFor(color, columns) {
121
+ return color ? { color: true, width: columns ?? 80 } : PLAIN;
120
122
  }
121
123
  const ESC = "\x1B";
122
- const SGR = {
123
- bold: 1,
124
- dim: 2,
125
- underline: 4,
126
- red: 31,
127
- green: 32,
128
- yellow: 33,
129
- magenta: 35,
130
- cyan: 36,
131
- white: 37,
132
- brightBlue: 94,
133
- brightWhite: 97,
134
- };
135
124
  const GROUPS = [
136
- { name: "Backlog", color: "brightWhite" },
125
+ { name: "Backlog", color: "whiteBright" },
137
126
  { name: "In refinement", color: "yellow" },
138
127
  { name: "Ready", color: "green" },
139
128
  { name: "In progress", color: "cyan" },
@@ -149,7 +138,7 @@ const width = (segs) => segs.reduce((n, s) => n + [...s.text].length, 0);
149
138
  function paint(text, style, ...codes) {
150
139
  if (!style.color || codes.length === 0)
151
140
  return text;
152
- return `${ESC}[${codes.map((c) => SGR[c]).join(";")}m${text}${ESC}[0m`;
141
+ return painter(true)(codes, text);
153
142
  }
154
143
  function render(segs, style) {
155
144
  return segs
@@ -324,7 +313,7 @@ export function formatRows({ rows, closed }, now, withClosed = true, style = PLA
324
313
  {
325
314
  name: UNLINKED,
326
315
  label: UNLINKED,
327
- color: "brightWhite",
316
+ color: "whiteBright",
328
317
  cells: cells.filter((c) => c.row.kind === "pull"),
329
318
  always: false,
330
319
  },
@@ -342,7 +331,7 @@ export function formatRows({ rows, closed }, now, withClosed = true, style = PLA
342
331
  ? paint(c.session, style, "bold", "yellow")
343
332
  : render(sessionSegs(c.session, c.row.derived, style.links), style);
344
333
  lines.push((INDENT +
345
- paint(render([{ text: c.number, url: c.url }], style), style, "brightBlue") +
334
+ paint(render([{ text: c.number, url: c.url }], style), style, "blueBright") +
346
335
  pad(c.number, numW) +
347
336
  GAP +
348
337
  render(title, style) +
@@ -373,7 +362,7 @@ export function formatRows({ rows, closed }, now, withClosed = true, style = PLA
373
362
  text: `#${r.number}`,
374
363
  url: linkTo("ticket", style, r.number),
375
364
  },
376
- ], style), style, "brightBlue"))
365
+ ], style), style, "blueBright"))
377
366
  .join(", ")}`);
378
367
  return lines;
379
368
  }
@@ -484,6 +473,8 @@ export async function main(argv, d) {
484
473
  await d.sleep(WATCH_MS);
485
474
  }
486
475
  }
476
+ /** The style for what `run` prints to stdout. */
477
+ export const terminalStyle = () => styleFor(colorOn(), process.stdout.columns);
487
478
  /** `factory status [--watch]`, and `factory session-start`'s second half. */
488
479
  export async function run(argv) {
489
480
  const code = await main(argv, {
@@ -506,7 +497,7 @@ export async function run(argv) {
506
497
  process.exit(130);
507
498
  });
508
499
  },
509
- style: () => styleFor(process.stdout.isTTY, process.stdout.columns, process.env.NO_COLOR),
500
+ style: terminalStyle,
510
501
  settings: () => loadSettings(),
511
502
  env: process.env,
512
503
  });
package/dist/sync.d.mts CHANGED
@@ -1,3 +1,4 @@
1
+ import { type Paint } from "./lib/color.mts";
1
2
  import { type Resolved, type Settings } from "./config.mts";
2
3
  import { type Replaced } from "./preset.mts";
3
4
  /** The package's own folder: the parent of `src/`, or of `dist/` once
@@ -111,6 +112,10 @@ export declare function main(argv: string[], d: {
111
112
  defaultBranch: (s: Settings) => Promise<string | null>;
112
113
  out: (line: string) => void;
113
114
  err: (line: string) => void;
115
+ paint?: Paint;
116
+ /** Whether a person ran it, so a sync that changes nothing says so;
117
+ * `init` and the preset commands run it inside their own output. */
118
+ announce?: boolean;
114
119
  }): Promise<number>;
115
120
  /** The sync of the repository at `root`. */
116
121
  export declare const syncDeps: (root: string) => {
@@ -122,5 +127,6 @@ export declare const syncDeps: (root: string) => {
122
127
  out: (line: string) => void;
123
128
  err: (line: string) => void;
124
129
  };
125
- export declare function run(argv: string[]): Promise<number>;
130
+ /** `announce` is false when `init` runs the sync inside its own output. */
131
+ export declare function run(argv: string[], announce?: boolean): Promise<number>;
126
132
  export {};
package/dist/sync.mjs CHANGED
@@ -14,6 +14,7 @@
14
14
  // the rules' numbers, and the default branch's name in the push triggers.
15
15
  // Edit the source in the package, never the copy. A file the lock lists that the package no longer has is
16
16
  // deleted. Nothing else is.
17
+ import { colorOn, painter, plain } from "./lib/color.mjs";
17
18
  import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync, } from "node:fs";
18
19
  import { dirname, join, relative, sep } from "node:path";
19
20
  import { fileURLToPath } from "node:url";
@@ -587,6 +588,7 @@ export function differences(root, p) {
587
588
  }
588
589
  export async function main(argv, d) {
589
590
  const check = argv.includes("--check");
591
+ const paint = d.paint ?? plain;
590
592
  let r;
591
593
  try {
592
594
  if (check) {
@@ -617,12 +619,15 @@ export async function main(argv, d) {
617
619
  const p = await plan(d.pkg, d.root, r, branch);
618
620
  const differ = differences(d.root, p);
619
621
  if (check) {
620
- if (differ.length === 0)
622
+ if (differ.length === 0) {
623
+ d.out(`${paint("green", "✓")} The factory's files match the settings.`);
621
624
  return 0;
622
- d.err("the factory's files are out of sync:");
625
+ }
626
+ const n = differ.length;
627
+ d.err(`${paint("red", "✗")} ${n} of the factory's files ${n === 1 ? "doesn't" : "don't"} match the settings:`);
623
628
  for (const path of differ)
624
629
  d.err(` ${path}`);
625
- d.err("Run `npx --no-install factory sync` and commit the result.");
630
+ d.err("Run factory sync and commit what it writes.");
626
631
  return 1;
627
632
  }
628
633
  for (const line of [...p.kept, ...p.dropped])
@@ -640,6 +645,8 @@ export async function main(argv, d) {
640
645
  d.out(`wrote ${path}`);
641
646
  }
642
647
  }
648
+ if (differ.length === 0 && d.announce)
649
+ d.out("The factory's files already match the settings. Nothing changed.");
643
650
  return 0;
644
651
  }
645
652
  /** The sync of the repository at `root`. */
@@ -652,6 +659,11 @@ export const syncDeps = (root) => ({
652
659
  out: (line) => console.log(line),
653
660
  err: (line) => console.error(line),
654
661
  });
655
- export async function run(argv) {
656
- return main(argv, syncDeps(repoRoot()));
662
+ /** `announce` is false when `init` runs the sync inside its own output. */
663
+ export async function run(argv, announce = true) {
664
+ return main(argv, {
665
+ ...syncDeps(repoRoot()),
666
+ paint: painter(colorOn()),
667
+ announce,
668
+ });
657
669
  }
@@ -0,0 +1,84 @@
1
+ import type { Agent } from "./agent/types.mts";
2
+ import type { Ask } from "./init.mts";
3
+ import type { Check } from "./setup.mts";
4
+ import type { Tickets } from "./tickets/types.mts";
5
+ /** The factory fields a refined ticket has, in the order its body has them. */
6
+ export declare const FACTORY_FIELDS: readonly [{
7
+ readonly key: "decisions";
8
+ readonly heading: "Decisions";
9
+ readonly holds: "the questions refinement settled, and what was chosen";
10
+ }, {
11
+ readonly key: "spec";
12
+ readonly heading: "Spec";
13
+ readonly holds: "what a change users will notice must do, line by line";
14
+ }, {
15
+ readonly key: "acceptance-criteria";
16
+ readonly heading: "Acceptance criteria";
17
+ readonly holds: "what must be true for any other ticket to be done";
18
+ }, {
19
+ readonly key: "for-the-builder";
20
+ readonly heading: "For the builder";
21
+ readonly holds: "how to build it, as a design and a list of tasks";
22
+ }];
23
+ export type FactoryKey = (typeof FACTORY_FIELDS)[number]["key"];
24
+ /** Each ticket-side key under `tickets.fields`, in settings order, with
25
+ * the ticket field that holds it, or null for the description. */
26
+ export type FieldMapping = Record<string, string | null>;
27
+ /** The heading a key stands for: the factory's own, or the key with its
28
+ * hyphens as spaces and its first letter capitalized. */
29
+ export declare function headingOf(key: string): string;
30
+ /** The key a heading stands for: lowercase, with hyphens for spaces. */
31
+ export declare const keyOf: (heading: string) => string;
32
+ /** A ticket's document taken apart: the description, and each named ticket
33
+ * field's text, or null to clear it. */
34
+ export declare function split(body: string, mapping: FieldMapping): {
35
+ description: string;
36
+ values: Record<string, string | null>;
37
+ } | {
38
+ error: string;
39
+ };
40
+ /** A ticket's document: its description with each ticket field's text under
41
+ * its key's heading, before the first later heading the description has. */
42
+ export declare function join(description: string, values: Record<string, string>, mapping: FieldMapping, labels: readonly string[]): string;
43
+ /** The agent's answer for a factory field no ticket field fits. A token,
44
+ * so a ticket field called "Description" stays usable. */
45
+ export declare const DESCRIPTION = "__description__";
46
+ export declare const TIMEOUT_MS = 60000;
47
+ /** Each factory field's ticket field, or null for the description. */
48
+ export type Suggestion = Record<FactoryKey, string | null>;
49
+ export declare function prompt(fields: readonly TicketFieldInfo[]): string;
50
+ /** A field as the prompt and the checks need it. */
51
+ export type TicketFieldInfo = {
52
+ name: string;
53
+ description: string | null;
54
+ };
55
+ export declare function schema(fields: readonly TicketFieldInfo[]): object;
56
+ /** The suggestion the agent's answer gives, or the reason it can't be
57
+ * used, the first that applies in the order the issue lists them. */
58
+ export declare function check(answer: unknown, fields: readonly TicketFieldInfo[], repository: string): {
59
+ suggestion: Suggestion;
60
+ } | {
61
+ reason: string;
62
+ };
63
+ /** The table of each factory field's ticket field. */
64
+ export declare function table(suggestion: Suggestion): string[];
65
+ export type FieldStepDeps = {
66
+ ask: Ask;
67
+ out: (line: string) => void;
68
+ agent: Agent;
69
+ /** The agent's registered label, which every line names it by. */
70
+ label: string;
71
+ };
72
+ /** The field step: the four factory fields' lines to write under
73
+ * `tickets.fields`, or 1 when init stops. */
74
+ export declare function suggestFields(d: FieldStepDeps, o: {
75
+ repository: string;
76
+ fields: readonly TicketFieldInfo[];
77
+ /** The ticket system's label, when its fields show text as typed. */
78
+ plainText: string | null;
79
+ }): Promise<[FactoryKey, string][] | 1>;
80
+ /** The checks `factory doctor` and `init` end with: that each ticket field
81
+ * the settings name exists and holds text. None when they name none. */
82
+ export declare function fieldChecks(tickets: Tickets, mapping: FieldMapping, repository: string,
83
+ /** The ticket system's registered label. */
84
+ label: string): Promise<Check[]>;
@@ -0,0 +1,374 @@
1
+ import { listed } from "./lib/listed.mjs";
2
+ /** The factory fields a refined ticket has, in the order its body has them. */
3
+ export const FACTORY_FIELDS = [
4
+ {
5
+ key: "decisions",
6
+ heading: "Decisions",
7
+ holds: "the questions refinement settled, and what was chosen",
8
+ },
9
+ {
10
+ key: "spec",
11
+ heading: "Spec",
12
+ holds: "what a change users will notice must do, line by line",
13
+ },
14
+ {
15
+ key: "acceptance-criteria",
16
+ heading: "Acceptance criteria",
17
+ holds: "what must be true for any other ticket to be done",
18
+ },
19
+ {
20
+ key: "for-the-builder",
21
+ heading: "For the builder",
22
+ holds: "how to build it, as a design and a list of tasks",
23
+ },
24
+ ];
25
+ const MOCKUPS = "mockups";
26
+ /** Spec and Acceptance criteria may share a ticket field: a ticket has one. */
27
+ const SHARED = ["spec", "acceptance-criteria"];
28
+ /** The heading a key stands for: the factory's own, or the key with its
29
+ * hyphens as spaces and its first letter capitalized. */
30
+ export function headingOf(key) {
31
+ const own = FACTORY_FIELDS.find((f) => f.key === key);
32
+ if (own)
33
+ return own.heading;
34
+ const words = key.replace(/-/g, " ");
35
+ return words.charAt(0).toUpperCase() + words.slice(1);
36
+ }
37
+ /** The key a heading stands for: lowercase, with hyphens for spaces. */
38
+ export const keyOf = (heading) => heading.trim().toLowerCase().replace(/\s+/g, "-");
39
+ /** Each line, with the key of the level-two heading it is, outside fenced
40
+ * code, or null. */
41
+ function headings(lines) {
42
+ let fence = null;
43
+ return lines.map((line) => {
44
+ const mark = /^\s*(```+|~~~+)/.exec(line)?.[1];
45
+ if (fence === null && mark) {
46
+ fence = mark;
47
+ return null;
48
+ }
49
+ if (fence !== null) {
50
+ if (mark?.[0] === fence[0] && mark.length >= fence.length)
51
+ fence = null;
52
+ return null;
53
+ }
54
+ const h = /^## (.+?)\s*$/.exec(line);
55
+ return h ? keyOf(h[1]) : null;
56
+ });
57
+ }
58
+ /** Lines with the blank ones at either end taken off. */
59
+ function trimmed(lines) {
60
+ let a = 0;
61
+ let b = lines.length;
62
+ while (a < b && !lines[a].trim())
63
+ a++;
64
+ while (b > a && !lines[b - 1].trim())
65
+ b--;
66
+ return lines.slice(a, b);
67
+ }
68
+ /** Pieces of text as a document: separated by one blank line, ending in
69
+ * a newline. */
70
+ const document = (pieces) => pieces
71
+ .map(trimmed)
72
+ .filter((p) => p.length)
73
+ .map((p) => p.join("\n"))
74
+ .join("\n\n") + "\n";
75
+ const named = (mapping) => Object.entries(mapping).filter((e) => e[1] !== null && e[1] !== undefined);
76
+ /** A ticket's document taken apart: the description, and each named ticket
77
+ * field's text, or null to clear it. */
78
+ export function split(body, mapping) {
79
+ const lines = body.split(/\r?\n/);
80
+ const keys = headings(lines);
81
+ const fieldOf = new Map(named(mapping));
82
+ const enders = new Set([
83
+ ...FACTORY_FIELDS.map((f) => f.key),
84
+ MOCKUPS,
85
+ ...Object.keys(mapping),
86
+ ]);
87
+ const kept = [[]];
88
+ const sections = new Map();
89
+ let into = null;
90
+ for (const [i, line] of lines.entries()) {
91
+ const key = keys[i];
92
+ if (key !== null && key !== undefined && enders.has(key)) {
93
+ if (fieldOf.has(key)) {
94
+ into = key;
95
+ sections.set(key, [...(sections.get(key) ?? []), ""]);
96
+ continue;
97
+ }
98
+ into = null;
99
+ kept.push([]);
100
+ }
101
+ if (into === null)
102
+ kept.at(-1).push(line);
103
+ else
104
+ sections.get(into).push(line);
105
+ }
106
+ const shared = fieldOf.get(SHARED[0]);
107
+ if (shared !== undefined &&
108
+ shared === fieldOf.get(SHARED[1]) &&
109
+ SHARED.every((k) => sections.has(k)))
110
+ return {
111
+ error: `Spec and Acceptance criteria both go in ${shared}, and the file has both: keep one.`,
112
+ };
113
+ const values = {};
114
+ for (const [key, field] of fieldOf) {
115
+ const text = sections.get(key);
116
+ if (text !== undefined)
117
+ values[field] = trimmed(text).join("\n");
118
+ else if (!(field in values))
119
+ values[field] = null;
120
+ }
121
+ const description = document(kept);
122
+ return { description: body.trim() ? description : body, values };
123
+ }
124
+ /** The order of the sections a body has: a heading of the repository's own
125
+ * first, in settings order, then the factory's. */
126
+ const ORDER = [
127
+ "decisions",
128
+ "spec",
129
+ "acceptance-criteria",
130
+ MOCKUPS,
131
+ "for-the-builder",
132
+ ];
133
+ /** A ticket's document: its description with each ticket field's text under
134
+ * its key's heading, before the first later heading the description has. */
135
+ export function join(description, values, mapping, labels) {
136
+ const order = [
137
+ ...Object.keys(mapping).filter((k) => !ORDER.includes(k)),
138
+ ...ORDER,
139
+ ];
140
+ const pairs = named(mapping);
141
+ const shared = pairs.filter(([k]) => SHARED.includes(k)).length === 2 &&
142
+ mapping.spec === mapping["acceptance-criteria"];
143
+ const reads = shared
144
+ ? labels.includes("spec")
145
+ ? "spec"
146
+ : "acceptance-criteria"
147
+ : null;
148
+ let lines = description.replace(/\n+$/, "").split("\n");
149
+ const add = pairs
150
+ .filter(([k]) => !(shared && SHARED.includes(k) && k !== reads))
151
+ .map(([k, field]) => [k, values[field] ?? ""])
152
+ .filter(([, text]) => text.trim())
153
+ .sort(([a], [b]) => order.indexOf(a) - order.indexOf(b));
154
+ for (const [key, text] of add) {
155
+ const rank = order.indexOf(key);
156
+ const at = headings(lines).findIndex((k) => k !== null && order.indexOf(k) > rank);
157
+ const section = [`## ${headingOf(key)}`, "", ...trimmed(text.split("\n"))];
158
+ lines =
159
+ at === -1
160
+ ? [...lines, "", ...section]
161
+ : [...lines.slice(0, at), ...section, "", ...lines.slice(at)];
162
+ }
163
+ return document([lines]);
164
+ }
165
+ /** The agent's answer for a factory field no ticket field fits. A token,
166
+ * so a ticket field called "Description" stays usable. */
167
+ export const DESCRIPTION = "__description__";
168
+ export const TIMEOUT_MS = 60_000;
169
+ const KEYS = FACTORY_FIELDS.map((f) => f.key);
170
+ const HEADING = Object.fromEntries(FACTORY_FIELDS.map((f) => [f.key, f.heading]));
171
+ export function prompt(fields) {
172
+ return [
173
+ "A software factory refines each ticket into parts, each under its own heading:",
174
+ ...FACTORY_FIELDS.map((f) => `- ${f.key} (${f.heading}): ${f.holds}`),
175
+ "",
176
+ "The tickets have these text fields:",
177
+ ...fields.map((f) => `- ${f.name}${f.description ? `: ${f.description}` : ""}`),
178
+ "",
179
+ "For each part, say which one of the text fields should hold it.",
180
+ `Answer ${DESCRIPTION} for a part no field clearly fits: it then stays in the ticket's description. Don't pick the nearest field when none fits.`,
181
+ "Give each field to at most one part, except that spec and acceptance-criteria may share one, since a ticket has only one of them.",
182
+ "Answer with a JSON object with each of the four parts as a key.",
183
+ ].join("\n");
184
+ }
185
+ export function schema(fields) {
186
+ const one = {
187
+ type: "string",
188
+ enum: [...fields.map((f) => f.name), DESCRIPTION],
189
+ };
190
+ return {
191
+ type: "object",
192
+ properties: Object.fromEntries(KEYS.map((k) => [k, one])),
193
+ required: KEYS,
194
+ };
195
+ }
196
+ /** Whether two factory fields may hold one ticket field. */
197
+ const mayShare = (a, b) => SHARED.includes(a) && SHARED.includes(b) && a !== b;
198
+ /** The suggestion the agent's answer gives, or the reason it can't be
199
+ * used, the first that applies in the order the issue lists them. */
200
+ export function check(answer, fields, repository) {
201
+ const form = { reason: "it did not answer in the form asked for" };
202
+ if (typeof answer !== "object" || answer === null || Array.isArray(answer))
203
+ return form;
204
+ const raw = answer;
205
+ const given = KEYS.filter((k) => typeof raw[k] === "string");
206
+ for (const k of given) {
207
+ const v = raw[k];
208
+ if (v !== DESCRIPTION && !fields.some((f) => f.name === v))
209
+ return {
210
+ reason: `it named ${v}, which ${repository}'s tickets don't have`,
211
+ };
212
+ }
213
+ for (const [i, a] of given.entries())
214
+ for (const b of given.slice(i + 1))
215
+ if (raw[a] !== DESCRIPTION && raw[a] === raw[b] && !mayShare(a, b))
216
+ return {
217
+ reason: `it put ${raw[a]} in both ${HEADING[a]} and ${HEADING[b]}`,
218
+ };
219
+ const missing = KEYS.find((k) => raw[k] === undefined);
220
+ if (missing)
221
+ return { reason: `it left out ${HEADING[missing]}` };
222
+ if (given.length < KEYS.length)
223
+ return form;
224
+ return {
225
+ suggestion: Object.fromEntries(KEYS.map((k) => [k, raw[k] === DESCRIPTION ? null : raw[k]])),
226
+ };
227
+ }
228
+ const shownIn = (field) => field ?? "the description";
229
+ /** The table of each factory field's ticket field. */
230
+ export function table(suggestion) {
231
+ const pad = (label) => ` ${label.padEnd(22)}`;
232
+ return [
233
+ `${pad("Factory field")}Ticket field`,
234
+ ...KEYS.map((k) => pad(HEADING[k]) + shownIn(suggestion[k])),
235
+ ];
236
+ }
237
+ /** The factory field that already holds `field`, other than `key` and the
238
+ * one it may share with, or null. */
239
+ function holding(field, key, s) {
240
+ return (KEYS.find((k) => k !== key && s[k] === field && !mayShare(k, key)) ?? null);
241
+ }
242
+ /** "Change some": the factory fields you pick, then a ticket field for
243
+ * each, until no two share one they may not. */
244
+ async function changeSome(d, suggestion, fields) {
245
+ const s = { ...suggestion };
246
+ let picked = [];
247
+ for (;;) {
248
+ picked = await d.ask.checkbox("Which factory fields do you want to change?", KEYS.map((k) => ({
249
+ name: `${HEADING[k]}: ${shownIn(s[k])}`,
250
+ value: k,
251
+ checked: picked.includes(k),
252
+ })));
253
+ let clash = false;
254
+ for (const key of KEYS.filter((k) => picked.includes(k))) {
255
+ const v = await d.ask.select(`Where does ${HEADING[key]} go?`, [
256
+ { name: "The description", value: DESCRIPTION },
257
+ ...fields.map((f) => ({ name: f.name, value: `field:${f.name}` })),
258
+ ], s[key] === null ? DESCRIPTION : `field:${s[key]}`);
259
+ const field = v === DESCRIPTION ? null : v.slice(6);
260
+ const other = field === null ? null : holding(field, key, s);
261
+ if (other) {
262
+ d.out(`${field} already holds ${HEADING[other]}. Pick another ticket field for ${HEADING[key]}.`);
263
+ clash = true;
264
+ break;
265
+ }
266
+ s[key] = field;
267
+ }
268
+ if (!clash)
269
+ return s;
270
+ }
271
+ }
272
+ /** The field step: the four factory fields' lines to write under
273
+ * `tickets.fields`, or 1 when init stops. */
274
+ export async function suggestFields(d, o) {
275
+ d.out("");
276
+ d.out(`${o.repository}'s tickets have the text fields ${listed(o.fields.map((f) => f.name))}.`);
277
+ d.out(`Asking ${d.label} which of them should hold each of the factory's fields...`);
278
+ const got = await d.agent.answer({
279
+ prompt: prompt(o.fields),
280
+ schema: schema(o.fields),
281
+ timeoutMs: TIMEOUT_MS,
282
+ });
283
+ const checked = "timedOut" in got
284
+ ? { reason: `it took longer than ${TIMEOUT_MS / 1000} seconds` }
285
+ : "failed" in got
286
+ ? {
287
+ reason: got.failed.error === null
288
+ ? `it failed with exit code ${got.failed.code}`
289
+ : `it failed: ${got.failed.error}`,
290
+ }
291
+ : check(got.answer, o.fields, o.repository);
292
+ if ("reason" in checked) {
293
+ d.out(`${d.label}'s answer could not be used: ${checked.reason}.`);
294
+ d.out("Run factory init again, or write tickets.fields in .claude/factory.yaml yourself.");
295
+ d.out("Nothing changed.");
296
+ return 1;
297
+ }
298
+ let suggestion = checked.suggestion;
299
+ for (;;) {
300
+ d.out("");
301
+ for (const line of table(suggestion))
302
+ d.out(line);
303
+ d.out("");
304
+ d.out("Your own text stays in the description.");
305
+ if (o.plainText)
306
+ d.out(`${o.plainText} shows a field's text as typed, without Markdown formatting.`);
307
+ d.out("");
308
+ const use = await d.ask.select("Use these ticket fields?", [
309
+ { name: "Yes", value: "yes" },
310
+ { name: "Change some", value: "change" },
311
+ { name: "No: keep everything in the description", value: "no" },
312
+ ], "yes");
313
+ if (use === "no")
314
+ return KEYS.map((k) => [k, "none"]);
315
+ if (use === "yes")
316
+ return KEYS.map((k) => [k, suggestion[k] ?? "none"]);
317
+ suggestion = await changeSome(d, suggestion, o.fields);
318
+ }
319
+ }
320
+ const FIX = "Create the field, or change tickets.fields in .claude/factory.yaml";
321
+ /** The checks `factory doctor` and `init` end with: that each ticket field
322
+ * the settings name exists and holds text. None when they name none. */
323
+ export async function fieldChecks(tickets, mapping, repository,
324
+ /** The ticket system's registered label. */
325
+ label) {
326
+ const wanted = named(mapping);
327
+ if (!wanted.length)
328
+ return [];
329
+ if (!tickets.fields)
330
+ return [
331
+ {
332
+ state: "fail",
333
+ text: `${label} has no ticket fields, which tickets.fields names`,
334
+ fix: FIX,
335
+ },
336
+ ];
337
+ let known;
338
+ try {
339
+ known = await tickets.fields.list();
340
+ }
341
+ catch (e) {
342
+ return [
343
+ {
344
+ state: "fail",
345
+ text: `${repository}'s ticket fields can be read`,
346
+ fix: (e instanceof Error ? e.message : String(e)).split("\n")[0],
347
+ },
348
+ ];
349
+ }
350
+ const failed = [];
351
+ for (const [key, name] of wanted) {
352
+ const field = known.find((f) => f.name === name);
353
+ if (!field)
354
+ failed.push({
355
+ state: "fail",
356
+ text: `${repository}'s tickets have no field called ${name}, which tickets.fields.${key} names`,
357
+ fix: FIX,
358
+ });
359
+ else if (!field.text)
360
+ failed.push({
361
+ state: "fail",
362
+ text: `${name}, which tickets.fields.${key} names, doesn't hold text`,
363
+ fix: FIX,
364
+ });
365
+ }
366
+ return failed.length
367
+ ? failed
368
+ : [
369
+ {
370
+ state: "pass",
371
+ text: `${repository}'s tickets have every field the settings name`,
372
+ },
373
+ ];
374
+ }