@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,514 @@
1
+ #!/usr/bin/env node
2
+ // What is being refined or built, and by which session, in the terminal.
3
+ //
4
+ // npx --no-install factory status
5
+ // npx --no-install factory status --watch # read again every 15 seconds
6
+ // status --hook # the form `factory session-start` prints
7
+ //
8
+ // Reads the board as well as the repository, so the GitHub CLI needs the
9
+ // project scope once, which `factory ticket ready` also needs to write it:
10
+ // gh auth refresh -s project
11
+ // The repository and the board come from the factory's settings, whose
12
+ // loader needs dependencies installed; before npm ci the hook prints
13
+ // nothing.
14
+ import { setTimeout as sleep } from "node:timers/promises";
15
+ import { NO_DEPENDENCIES, SettingsError, loadSettings, targetOf, } from "./config.mjs";
16
+ import { appSessionLink } from "./lib/gh.mjs";
17
+ import { DEFAULT_COLUMNS, cardOf, derive, isNotStarted, isStale, isStuck, actionsRunLink, buildsPartOf, markedComments, parseRuns, toSnapshot, } from "./lib/work-status.mjs";
18
+ import { boardOf, readAll } from "./tickets/types.mjs";
19
+ import { openTickets } from "./tickets/index.mjs";
20
+ import { openCodeHost } from "./code-host/index.mjs";
21
+ import { openRunner } from "./runner/index.mjs";
22
+ import { subscriptionDollars } from "./lib/pricing.mjs";
23
+ import { dollars } from "./lib/usage.mjs";
24
+ import { minutes, resultText } from "./reviewers.mjs";
25
+ const HOOK_LIMIT_MS = 20_000;
26
+ const HOUR = 3600_000;
27
+ const RUN_STATUSES = new Set(["In refinement", "In progress", "In review"]);
28
+ /** Each reviewer's latest run on the issue since its current session began:
29
+ * the newest `refining` marker for a card In refinement, the newest claim
30
+ * for one In progress or In review. A run needs a session clock, which only
31
+ * those markers start, so a build's card does not carry its refinement's
32
+ * runs. */
33
+ export function cardRuns(issue, derived) {
34
+ if (!RUN_STATUSES.has(derived.status))
35
+ return [];
36
+ const kind = derived.status === "In refinement" ? "refining" : "claim";
37
+ const began = markedComments(issue.comments)
38
+ .filter((m) => m.marker.kind === kind)
39
+ .at(-1)?.createdAt;
40
+ if (!began)
41
+ return [];
42
+ const latest = new Map();
43
+ for (const run of issue.comments.flatMap(parseRuns)) {
44
+ if (Date.parse(run.start) < Date.parse(began))
45
+ continue;
46
+ const seen = latest.get(run.reviewer);
47
+ if (!seen || Date.parse(run.start) >= Date.parse(seen.start))
48
+ latest.set(run.reviewer, run);
49
+ }
50
+ return [...latest.values()].sort((a, b) => Date.parse(a.start) - Date.parse(b.start));
51
+ }
52
+ export function age(since, now) {
53
+ if (!since)
54
+ return "";
55
+ const minutes = Math.max(0, Math.floor((now.getTime() - Date.parse(since)) / 60_000));
56
+ if (minutes < 60)
57
+ return `${minutes}m`;
58
+ if (minutes < 48 * 60)
59
+ return `${Math.floor(minutes / 60)}h`;
60
+ return `${Math.floor(minutes / 1440)}d`;
61
+ }
62
+ export function isWatching(body, now) {
63
+ const written = /<!-- session-watching: (\S+) -->/.exec(body)?.[1];
64
+ return written !== undefined && now.getTime() - Date.parse(written) < HOUR;
65
+ }
66
+ /** One row per open issue, and one per open pull request that closes no
67
+ * issue and builds no part of the follow-ups, such as Dependabot's. */
68
+ export function toRows(snapshot, board, blockers, now,
69
+ /** Whether something starts builds from the board, so that a card left
70
+ * in Ready is worth flagging. False when builds.trigger is manual. */
71
+ watched = true, columns = DEFAULT_COLUMNS) {
72
+ const rows = [];
73
+ const closed = [];
74
+ const claimed = new Set();
75
+ for (const issue of snapshot.issues) {
76
+ const derived = derive(issue, cardOf(board, issue.number, columns), snapshot.pulls, columns);
77
+ const pulls = snapshot.pulls.filter((p) => derived.pulls.includes(p.number));
78
+ pulls.forEach((p) => claimed.add(p.number));
79
+ const flags = [];
80
+ if (isStale(derived, now))
81
+ flags.push("stale");
82
+ if (watched && isNotStarted(derived, blockers.get(issue.number) ?? [], now))
83
+ flags.push("not started, is the poller running?");
84
+ const row = {
85
+ number: issue.number,
86
+ kind: "issue",
87
+ title: issue.title,
88
+ derived,
89
+ pulls,
90
+ runs: cardRuns(issue, derived),
91
+ flags,
92
+ cost: board.items.get(issue.number)?.cost ?? null,
93
+ };
94
+ (derived.status === "Done" ? closed : rows).push(row);
95
+ }
96
+ for (const pull of snapshot.pulls) {
97
+ if (claimed.has(pull.number))
98
+ continue;
99
+ const followUps = snapshot.issues.filter((i) => i.labels.includes("follow-up") && buildsPartOf(pull.body, i.number));
100
+ if (pull.closes.length > 0 || followUps.length > 0)
101
+ continue;
102
+ rows.push({
103
+ number: pull.number,
104
+ kind: "pull",
105
+ title: `pull request by ${pull.author}`,
106
+ derived: null,
107
+ pulls: [pull],
108
+ runs: [],
109
+ flags: [],
110
+ cost: board.items.get(pull.number)?.cost ?? null,
111
+ });
112
+ }
113
+ return { rows, closed };
114
+ }
115
+ export const PLAIN = { color: false, width: null };
116
+ /** A terminal unless NO_COLOR is set to anything (no-color.org). */
117
+ export function styleFor(isTTY, columns, noColor) {
118
+ return isTTY && !noColor ? { color: true, width: columns ?? 80 } : PLAIN;
119
+ }
120
+ const ESC = "\x1B";
121
+ const SGR = {
122
+ bold: 1,
123
+ dim: 2,
124
+ underline: 4,
125
+ red: 31,
126
+ green: 32,
127
+ yellow: 33,
128
+ magenta: 35,
129
+ cyan: 36,
130
+ white: 37,
131
+ brightBlue: 94,
132
+ brightWhite: 97,
133
+ };
134
+ const GROUPS = [
135
+ { name: "Backlog", color: "brightWhite" },
136
+ { name: "In refinement", color: "yellow" },
137
+ { name: "Ready", color: "green" },
138
+ { name: "In progress", color: "cyan" },
139
+ { name: "In review", color: "magenta" },
140
+ ];
141
+ const UNLINKED = "Pull requests that close no issue";
142
+ const INDENT = " ";
143
+ const GAP = " ";
144
+ const MIN_TITLE = 20;
145
+ const HEADER = ["#", "Title", "Time in status", "Cost", "Session"];
146
+ const linkTo = (kind, style, n) => style.links?.[kind](n);
147
+ const width = (segs) => segs.reduce((n, s) => n + [...s.text].length, 0);
148
+ function paint(text, style, ...codes) {
149
+ if (!style.color || codes.length === 0)
150
+ return text;
151
+ return `${ESC}[${codes.map((c) => SGR[c]).join(";")}m${text}${ESC}[0m`;
152
+ }
153
+ function render(segs, style) {
154
+ return segs
155
+ .map((s) => s.url && style.color
156
+ ? `${ESC}]8;;${s.url}${ESC}\\${s.text}${ESC}]8;;${ESC}\\`
157
+ : s.text)
158
+ .join("");
159
+ }
160
+ /** Shortens the runs to `max` characters, ending in "…", when they are longer. */
161
+ function fit(segs, max) {
162
+ if (max === null || width(segs) <= max)
163
+ return segs;
164
+ const out = [];
165
+ let room = max - 1;
166
+ for (const seg of segs) {
167
+ if (room <= 0)
168
+ break;
169
+ const chars = [...seg.text].slice(0, room);
170
+ out.push({ ...seg, text: chars.join("") });
171
+ room -= chars.length;
172
+ }
173
+ const last = out[out.length - 1];
174
+ last.text = `${last.text.trimEnd()}…`;
175
+ return out;
176
+ }
177
+ const CHECKS = {
178
+ SUCCESS: "checks passing",
179
+ FAILURE: "checks failing",
180
+ ERROR: "checks failing",
181
+ PENDING: "checks pending",
182
+ EXPECTED: "checks pending",
183
+ };
184
+ /** The pull request's line under its row; a row that is the pull request
185
+ * already shows its number. */
186
+ function pullLine(pull, now, named, style) {
187
+ const parts = [
188
+ pull.isDraft ? "draft" : "ready for review",
189
+ pull.checks === null
190
+ ? "no checks"
191
+ : (CHECKS[pull.checks] ?? `checks ${pull.checks.toLowerCase()}`),
192
+ pull.openThreads === 0
193
+ ? "no open threads"
194
+ : `${pull.openThreads} open thread${pull.openThreads === 1 ? "" : "s"}`,
195
+ ];
196
+ if (isWatching(pull.body, now))
197
+ parts.push("a session is watching it");
198
+ const rest = parts.join(" · ");
199
+ return named
200
+ ? [
201
+ { text: "↳ Pull request " },
202
+ { text: `#${pull.number}`, url: linkTo("pull", style, pull.number) },
203
+ { text: ` · ${rest}` },
204
+ ]
205
+ : [{ text: `↳ ${rest}` }];
206
+ }
207
+ // The columns of a reviewer row, fixed so they line up in every card.
208
+ const RUN_NAME = 15;
209
+ const RUN_MODEL = 6;
210
+ const RUN_RESULT = 20;
211
+ const RUN_TIME = 11;
212
+ /** One reviewer's row under its card: a mark that carries the result
213
+ * without color, the name, the model, the result, how long it ran, and its
214
+ * cost in subscription dollars. */
215
+ export function runLine(run, now, style) {
216
+ const pad = (text, n) => text + " ".repeat(Math.max(0, n - [...text].length));
217
+ const stuck = isStuck(run, now);
218
+ const result = resultText(run, now);
219
+ const [mark, color] = stuck
220
+ ? ["?", "dim"]
221
+ : {
222
+ running: ["…", "yellow"],
223
+ passed: ["✓", "green"],
224
+ failed: ["✗", "red"],
225
+ "no verdict": ["?", "dim"],
226
+ }[run.result];
227
+ const parts = [
228
+ `${paint(mark, style, color)} ${pad(run.reviewer, RUN_NAME)}`,
229
+ paint(pad(run.model, RUN_MODEL), style, "dim"),
230
+ paint(stuck ? result : pad(result, RUN_RESULT), style, color),
231
+ ];
232
+ if (!stuck && run.result === "running")
233
+ parts.push(paint(`${minutes(run.start, now.toISOString())} so far`, style, "dim"));
234
+ else if (!stuck) {
235
+ const time = run.end ? minutes(run.start, run.end) : "";
236
+ const cost = run.cost === undefined ? "" : dollars(subscriptionDollars(run.cost));
237
+ parts.push(paint(pad(time, RUN_TIME), style, "dim"));
238
+ if (cost)
239
+ parts.push(paint(cost, style, "dim"));
240
+ }
241
+ return parts.join(GAP).trimEnd();
242
+ }
243
+ /** The board's Runs in, lowercased, before a session ID; a phrase such as
244
+ * "Waiting on you" as it is. A desktop app session's `local_…` ID shows as
245
+ * its UUID's first eight characters. */
246
+ export function sessionCell(derived) {
247
+ if (!derived?.session)
248
+ return "";
249
+ if (/[\s,]/.test(derived.session) || !derived.runsIn)
250
+ return derived.session;
251
+ const id = derived.session.replace(/^local_([^-]{8})-.*$/, "$1");
252
+ return `${derived.runsIn.toLowerCase()} ${id}`;
253
+ }
254
+ /** The Session cell, its session's ID linked to open that session in the
255
+ * desktop app when the app knows it, and an Actions run's to the run's
256
+ * page when the links are given. */
257
+ function sessionSegs(cell, derived, links) {
258
+ const session = derived?.session;
259
+ const run = derived && links ? actionsRunLink(derived, links.run) : null;
260
+ const url = run ?? (session === undefined ? null : appSessionLink(session));
261
+ const [where, id] = cell.split(" ");
262
+ return url && id !== undefined
263
+ ? [{ text: `${where} ` }, { text: id, url }]
264
+ : [{ text: cell }];
265
+ }
266
+ export function formatRows({ rows, closed }, now, withClosed = true, style = PLAIN) {
267
+ const lines = [];
268
+ if (rows.length === 0)
269
+ lines.push("Nothing open.");
270
+ else {
271
+ const cells = rows.map((row) => {
272
+ const url = linkTo(row.kind === "issue" ? "ticket" : "pull", style, row.number);
273
+ return {
274
+ row,
275
+ number: `#${row.number}`,
276
+ url,
277
+ time: age(row.derived?.since ?? null, now),
278
+ // Read from the board, never summed here, so it matches the card.
279
+ cost: row.cost === null ? "" : dollars(row.cost),
280
+ session: sessionCell(row.derived),
281
+ };
282
+ });
283
+ const col = (i, values) => Math.max(HEADER[i].length, ...values.map((v) => [...v].length));
284
+ const numW = col(0, cells.map((c) => c.number));
285
+ const timeW = col(2, cells.map((c) => c.time));
286
+ const costW = col(3, cells.map((c) => c.cost));
287
+ const sessionW = col(4, cells.map((c) => c.session));
288
+ const titleNatural = col(1, rows.map((r) => r.title));
289
+ const subIndent = INDENT.length + numW + GAP.length;
290
+ const titleW = style.width === null
291
+ ? titleNatural
292
+ : Math.max(MIN_TITLE, Math.min(titleNatural, style.width -
293
+ subIndent -
294
+ GAP.length -
295
+ timeW -
296
+ GAP.length -
297
+ costW -
298
+ GAP.length -
299
+ sessionW));
300
+ const subMax = style.width === null
301
+ ? null
302
+ : Math.max(MIN_TITLE, style.width - subIndent);
303
+ const pad = (text, n) => " ".repeat(Math.max(0, n - [...text].length));
304
+ const sub = " ".repeat(subIndent);
305
+ const head = (text, n = 0) => paint(text, style, "bold", "underline") + pad(text, n);
306
+ lines.push(INDENT +
307
+ [
308
+ head(HEADER[0], numW),
309
+ head(HEADER[1], titleW),
310
+ head(HEADER[2], timeW),
311
+ head(HEADER[3], costW),
312
+ head(HEADER[4]),
313
+ ].join(GAP));
314
+ const groups = [
315
+ ...GROUPS.map((g) => ({
316
+ ...g,
317
+ // The repository's column for the state, or the factory's own name
318
+ // where the board has none.
319
+ label: (style.columns ?? DEFAULT_COLUMNS)[g.name] ?? g.name,
320
+ cells: cells.filter((c) => c.row.kind === "issue" && c.row.derived?.status === g.name),
321
+ always: true,
322
+ })),
323
+ {
324
+ name: UNLINKED,
325
+ label: UNLINKED,
326
+ color: "brightWhite",
327
+ cells: cells.filter((c) => c.row.kind === "pull"),
328
+ always: false,
329
+ },
330
+ ];
331
+ for (const group of groups) {
332
+ if (!group.always && group.cells.length === 0)
333
+ continue;
334
+ const count = String(group.cells.length);
335
+ lines.push("", group.cells.length
336
+ ? `${paint(group.label, style, "bold", group.color)} ${paint(count, style, "dim")}`
337
+ : paint(`${group.label} ${count}`, style, "dim"));
338
+ for (const c of group.cells) {
339
+ const title = fit([{ text: c.row.title, url: c.url }], titleW);
340
+ const session = c.session === "Waiting on you"
341
+ ? paint(c.session, style, "bold", "yellow")
342
+ : render(sessionSegs(c.session, c.row.derived, style.links), style);
343
+ lines.push((INDENT +
344
+ paint(render([{ text: c.number, url: c.url }], style), style, "brightBlue") +
345
+ pad(c.number, numW) +
346
+ GAP +
347
+ render(title, style) +
348
+ pad(title.map((s) => s.text).join(""), titleW) +
349
+ GAP +
350
+ paint(c.time, style, "dim") +
351
+ pad(c.time, timeW) +
352
+ GAP +
353
+ c.cost +
354
+ pad(c.cost, costW) +
355
+ GAP +
356
+ session).trimEnd());
357
+ for (const pull of c.row.pulls)
358
+ lines.push(sub +
359
+ paint(render(fit(pullLine(pull, now, c.row.kind === "issue", style), subMax), style), style, "dim"));
360
+ for (const run of c.row.runs)
361
+ lines.push(sub + runLine(run, now, style));
362
+ for (const flag of c.row.flags)
363
+ lines.push(sub +
364
+ paint(render(fit([{ text: `⚠ ${flag}` }], subMax), style), style, "red"));
365
+ }
366
+ }
367
+ }
368
+ if (withClosed && closed.length > 0)
369
+ lines.push("", `${paint("Closed in the last 24 hours:", style, "dim")} ${closed
370
+ .map((r) => paint(render([
371
+ {
372
+ text: `#${r.number}`,
373
+ url: linkTo("ticket", style, r.number),
374
+ },
375
+ ], style), style, "brightBlue"))
376
+ .join(", ")}`);
377
+ return lines;
378
+ }
379
+ /** The one line a failed read prints. */
380
+ export function failureLine(error) {
381
+ const text = String(error);
382
+ if (/read:project|INSUFFICIENT_SCOPES|required scopes/i.test(text))
383
+ return "Work status: the GitHub CLI cannot read the board yet. Run: gh auth refresh -s project";
384
+ return `Work status: could not read GitHub (${text.split("\n")[0].slice(0, 200)})`;
385
+ }
386
+ export { targetOf } from "./config.mjs";
387
+ async function snapshotLines(source, target, now, hook, style = PLAIN) {
388
+ const links = {
389
+ ticket: (n) => source.tickets.address(n),
390
+ pull: (n) => source.pulls.address(n),
391
+ run: (id) => source.runner.runPage(id),
392
+ };
393
+ const [tickets, pulls] = await Promise.all([
394
+ readAll(source.tickets, { board: target.board !== null }),
395
+ source.pulls.open({ checks: true }),
396
+ ]);
397
+ const snapshot = toSnapshot(tickets, pulls, now);
398
+ const board = boardOf(tickets);
399
+ const blockers = new Map();
400
+ for (const issue of snapshot.issues) {
401
+ if (!source.tickets.blockers ||
402
+ derive(issue, cardOf(board, issue.number, target.columns), snapshot.pulls, target.columns).status !== "Ready")
403
+ continue;
404
+ const list = await source.tickets.blockers.list(issue.number);
405
+ blockers.set(issue.number, list.filter((b) => b.state === "open").map((b) => b.number));
406
+ }
407
+ return formatRows(toRows(snapshot, board, blockers, now, target.watched, target.columns), now, !hook, { ...style, links, columns: target.columns });
408
+ }
409
+ const WATCH_MS = 15_000;
410
+ // The alternate screen with the cursor hidden, and back.
411
+ const ENTER = `${ESC}[?1049h${ESC}[?25l`;
412
+ const LEAVE = `${ESC}[?25h${ESC}[?1049l`;
413
+ /** A frame that overwrites the one on screen: home, each line erased to its
414
+ * end, then everything below. No newline ends it, which would scroll a
415
+ * frame as tall as the window. */
416
+ export function frame(lines) {
417
+ return `${ESC}[H${lines.map((l) => `${l}${ESC}[K`).join("\n")}${ESC}[J`;
418
+ }
419
+ export async function main(argv, d) {
420
+ const hook = argv.includes("--hook");
421
+ let target;
422
+ let settings;
423
+ try {
424
+ settings = await d.settings();
425
+ target = targetOf(settings, d.env);
426
+ }
427
+ catch (error) {
428
+ if (!(error instanceof SettingsError))
429
+ throw error;
430
+ // Before npm ci the hook stays quiet.
431
+ if (!(hook && error.message === NO_DEPENDENCIES))
432
+ d.out(error.message);
433
+ return hook ? 0 : 1;
434
+ }
435
+ if (hook) {
436
+ const limit = d.sleep(HOOK_LIMIT_MS).then(() => "timeout");
437
+ const work = (async () => {
438
+ const source = await d.source(settings, target);
439
+ return [
440
+ "## Work in progress",
441
+ "",
442
+ "```",
443
+ ...(await snapshotLines(source, target, d.now(), true)),
444
+ "```",
445
+ ];
446
+ })().catch((error) => [failureLine(error)]);
447
+ const result = await Promise.race([work, limit]);
448
+ if (result === "timeout") {
449
+ d.out("Work status: GitHub did not answer within 20 seconds.");
450
+ }
451
+ else
452
+ result.forEach((line) => d.out(line));
453
+ return 0;
454
+ }
455
+ const watch = argv.includes("--watch");
456
+ let shown = "";
457
+ if (watch) {
458
+ d.write(ENTER);
459
+ d.onInterrupt(() => d.write(LEAVE));
460
+ }
461
+ // Opened once and kept while --watch draws; a failed open is tried again
462
+ // on the next draw.
463
+ let source = null;
464
+ for (;;) {
465
+ let lines;
466
+ let code = 0;
467
+ try {
468
+ source ??= await d.source(settings, target);
469
+ lines = await snapshotLines(source, target, d.now(), false, d.style?.() ?? PLAIN);
470
+ }
471
+ catch (error) {
472
+ lines = [failureLine(error)];
473
+ code = 1;
474
+ }
475
+ if (!watch) {
476
+ lines.forEach((line) => d.out(line));
477
+ return code;
478
+ }
479
+ const next = frame(lines);
480
+ if (next !== shown)
481
+ d.write(next);
482
+ shown = next;
483
+ await d.sleep(WATCH_MS);
484
+ }
485
+ }
486
+ /** `factory status [--watch]`, and `factory session-start`'s second half. */
487
+ export async function run(argv) {
488
+ const code = await main(argv, {
489
+ source: async (settings, target) => {
490
+ const { tickets } = await openTickets(settings, target);
491
+ return {
492
+ tickets,
493
+ pulls: openCodeHost(target.repository, settings.codeHost.type),
494
+ runner: openRunner(target.repository, settings.builds.runner),
495
+ };
496
+ },
497
+ now: () => new Date(),
498
+ out: (line) => console.log(line),
499
+ sleep,
500
+ write: (text) => process.stdout.write(text),
501
+ onInterrupt: (leave) => {
502
+ for (const signal of ["SIGINT", "SIGTERM"])
503
+ process.on(signal, () => {
504
+ leave();
505
+ process.exit(130);
506
+ });
507
+ },
508
+ style: () => styleFor(process.stdout.isTTY, process.stdout.columns, process.env.NO_COLOR),
509
+ settings: () => loadSettings(),
510
+ env: process.env,
511
+ });
512
+ // The hook's time limit leaves its read pending; exit rather than wait on it.
513
+ process.exit(code);
514
+ }
@@ -0,0 +1,59 @@
1
+ import { type Settings } from "./config.mts";
2
+ /** The package's own folder: the parent of `src/`, or of `dist/` once
3
+ * compiled. */
4
+ export declare const PACKAGE: string;
5
+ export declare const LOCK = ".claude/factory.lock";
6
+ export declare const SETTINGS_JSON = ".claude/settings.json";
7
+ export declare const CLAUDE_MD = "CLAUDE.md";
8
+ export declare const IMPORT_LINE = "@.claude/factory/rules.md";
9
+ /** Whether the repository has a file, by its path from the root. */
10
+ type Has = (path: string) => boolean;
11
+ /** A session workflow with the minutes its session may run, and its job 10
12
+ * more, so the steps after the session still run before the job is
13
+ * stopped. */
14
+ export declare function withMinutes(text: string, minutes: number, file: string): string;
15
+ /** Each copy, as [path in the package, path in the repository]. */
16
+ export declare function copies(pkg: string, s: Settings, has: Has): [string, string][];
17
+ /** The launcher's path from the repository's root: the package's own
18
+ * folder where it is inside the repository, as a workspace or installed,
19
+ * and where it would be installed otherwise. */
20
+ export declare function launcherPath(pkg: string, root: string, name: string): string;
21
+ type HookEntry = {
22
+ type: "command";
23
+ command: string;
24
+ timeout?: number;
25
+ statusMessage?: string;
26
+ };
27
+ type HookGroup = {
28
+ matcher?: string;
29
+ hooks: HookEntry[];
30
+ };
31
+ /** The five hook entries, one per event. */
32
+ export declare function factoryHooks(launcher: string): [string, HookGroup][];
33
+ /** `.claude/settings.json` with the entries that run the factory's launcher
34
+ * replaced by the five above, and attribution turned off unless the file
35
+ * sets its own. Every other entry stays, in its order. */
36
+ export declare function withHooks(text: string | null, launcher: string): string;
37
+ /** `CLAUDE.md` with the rules' import added when no line is that import. */
38
+ export declare function withImport(text: string | null): string;
39
+ export declare function lockText(version: string, files: string[]): string;
40
+ export declare function lockedFiles(text: string | null): string[];
41
+ export type Plan = {
42
+ /** Path from the root, and its text, for each file a sync writes. */
43
+ write: Map<string, string>;
44
+ /** Paths the lock lists that this version no longer writes. */
45
+ remove: string[];
46
+ };
47
+ /** What a sync of `root` from `pkg` writes and deletes. */
48
+ export declare function plan(pkg: string, root: string, s: Settings): Plan;
49
+ /** The paths whose content a sync would change, in the plan's order. */
50
+ export declare function differences(root: string, p: Plan): string[];
51
+ export declare function main(argv: string[], d: {
52
+ root: string;
53
+ pkg: string;
54
+ settings: () => Promise<Settings>;
55
+ out: (line: string) => void;
56
+ err: (line: string) => void;
57
+ }): Promise<number>;
58
+ export declare function run(argv: string[]): Promise<number>;
59
+ export {};