@davidbyoung/software-factory 0.1.10 → 0.1.12

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 (83) hide show
  1. package/agents/factory-e2e-reviewer.md +1 -1
  2. package/agents/factory-test-reviewer.md +1 -1
  3. package/agents/factory-ticket-readiness.md +20 -15
  4. package/agents/factory-ui-reviewer.md +2 -2
  5. package/dist/board.d.mts +8 -8
  6. package/dist/board.mjs +53 -37
  7. package/dist/build.d.mts +4 -0
  8. package/dist/build.mjs +9 -4
  9. package/dist/cli.mjs +25 -5
  10. package/dist/code-host/github.mjs +11 -4
  11. package/dist/code-host/types.d.mts +8 -2
  12. package/dist/commands.d.mts +7 -2
  13. package/dist/commands.mjs +96 -17
  14. package/dist/config.d.mts +3 -4
  15. package/dist/config.mjs +7 -8
  16. package/dist/init.d.mts +11 -0
  17. package/dist/init.mjs +56 -1
  18. package/dist/lib/clock.d.mts +3 -1
  19. package/dist/lib/clock.mjs +12 -6
  20. package/dist/lib/pull-tickets.d.mts +15 -0
  21. package/dist/lib/pull-tickets.mjs +12 -0
  22. package/dist/lib/usage.d.mts +3 -1
  23. package/dist/lib/usage.mjs +4 -2
  24. package/dist/lib/work-status.d.mts +28 -24
  25. package/dist/lib/work-status.mjs +21 -35
  26. package/dist/merge-policy.mjs +7 -3
  27. package/dist/poller.d.mts +3 -3
  28. package/dist/poller.mjs +18 -14
  29. package/dist/pr.d.mts +26 -6
  30. package/dist/pr.mjs +92 -28
  31. package/dist/review-tickets.d.mts +12 -0
  32. package/dist/review-tickets.mjs +59 -0
  33. package/dist/review-verdict.d.mts +22 -4
  34. package/dist/review-verdict.mjs +55 -17
  35. package/dist/reviewers.d.mts +7 -4
  36. package/dist/reviewers.mjs +19 -12
  37. package/dist/runner/github-actions.mjs +6 -7
  38. package/dist/runner/types.d.mts +7 -6
  39. package/dist/specs/index.d.mts +6 -0
  40. package/dist/specs/index.mjs +15 -0
  41. package/dist/specs/openspec.d.mts +2 -0
  42. package/dist/specs/openspec.mjs +78 -0
  43. package/dist/specs/types.d.mts +53 -0
  44. package/dist/specs/types.mjs +4 -0
  45. package/dist/status.d.mts +17 -7
  46. package/dist/status.mjs +35 -23
  47. package/dist/sync.d.mts +4 -0
  48. package/dist/sync.mjs +14 -1
  49. package/dist/ticket.d.mts +15 -7
  50. package/dist/ticket.mjs +128 -61
  51. package/dist/tickets/github-access.d.mts +5 -0
  52. package/dist/tickets/github-access.mjs +22 -0
  53. package/dist/tickets/github.d.mts +10 -2
  54. package/dist/tickets/github.mjs +76 -20
  55. package/dist/tickets/index.d.mts +7 -1
  56. package/dist/tickets/index.mjs +15 -1
  57. package/dist/tickets/types.d.mts +63 -30
  58. package/dist/tickets/types.mjs +13 -3
  59. package/dist/tool-names.d.mts +2 -0
  60. package/dist/tool-names.mjs +3 -0
  61. package/dist/tools.d.mts +2 -0
  62. package/dist/tools.mjs +3 -0
  63. package/docs/builds.md +4 -1
  64. package/docs/cli.md +30 -11
  65. package/docs/configuration.md +51 -39
  66. package/docs/developing.md +115 -62
  67. package/docs/existing-repo.md +4 -3
  68. package/docs/github/reference.md +1 -1
  69. package/docs/github/setup.md +20 -3
  70. package/docs/glossary.md +7 -6
  71. package/docs/limitations.md +8 -5
  72. package/docs/plugins.md +6 -6
  73. package/docs/updating.md +18 -0
  74. package/docs/workflow.md +25 -8
  75. package/package.json +1 -1
  76. package/review.md +11 -11
  77. package/rules.md +52 -42
  78. package/skills/factory-address-review/SKILL.md +44 -42
  79. package/skills/factory-build/SKILL.md +71 -72
  80. package/skills/factory-refine/SKILL.md +31 -23
  81. package/skills/factory-resolve-conflicts/SKILL.md +12 -10
  82. package/workflows/factory-build.yml +6 -5
  83. package/workflows/factory-claude-review.yml +38 -1
@@ -115,34 +115,27 @@ export function hasCostMarker(body) {
115
115
  return linesOutsideFences(body).some((line) => COST_LINE.test(line));
116
116
  }
117
117
  /** The cost markers in one comment, read as markers are: each on a line of
118
- * its own, outside a fenced code block. Only the owner's account, which the
119
- * agents post as, and the pull request review's bot count; the owner's comments count
120
- * only with the agent mark. */
121
- export function parseCosts(comment, owner) {
122
- const fromAgent = comment.author === owner && comment.body.includes(AGENT_MARK);
123
- if (!fromAgent && comment.author !== CI_BOT)
118
+ * its own, outside a fenced code block. A comment counts when it carries the
119
+ * agent mark, whoever posted it, as a claim or a release does, or when the
120
+ * pull request review's bot posted it. */
121
+ export function parseCosts(comment) {
122
+ if (!comment.body.includes(AGENT_MARK) && comment.author !== CI_BOT)
124
123
  return [];
125
124
  return linesOutsideFences(comment.body).flatMap((line) => {
126
125
  const match = COST_LINE.exec(line);
127
126
  return match ? [Number(match[1])] : [];
128
127
  });
129
128
  }
130
- /** Whether a pull request's body says it builds this issue, as "Closes #N"
131
- * or "Part of #N". */
132
- export function buildsIssue(body, number) {
133
- return new RegExp(`\\b(?:closes|part of) #${number}(?!\\d)`, "i").test(body);
134
- }
135
129
  /** The issue's Cost: every cost marker on it and on each pull request, open,
136
130
  * merged, or closed, that builds it, to the cent. Null when there are none. */
137
- export function issueCost(issue, pulls, owner) {
131
+ export function issueCost(issue, pulls) {
138
132
  const comments = [
139
133
  ...issue.comments,
140
134
  ...pulls
141
- .filter((pull) => pull.closes.includes(issue.number) ||
142
- buildsIssue(pull.body, issue.number))
135
+ .filter((pull) => pull.closes.includes(issue.key) || pull.partOf.includes(issue.key))
143
136
  .flatMap((pull) => pull.comments ?? []),
144
137
  ];
145
- const costs = comments.flatMap((c) => parseCosts(c, owner));
138
+ const costs = comments.flatMap((c) => parseCosts(c));
146
139
  if (costs.length === 0)
147
140
  return null;
148
141
  return Math.round(costs.reduce((a, b) => a + b, 0) * 100) / 100;
@@ -182,10 +175,10 @@ export function parseRuns(comment) {
182
175
  export const STUCK_AFTER_MS = 2 * 60 * 60 * 1000;
183
176
  export const isStuck = (run, now) => run.result === "running" &&
184
177
  now.getTime() - Date.parse(run.start) > STUCK_AFTER_MS;
178
+ // Comments with the same time keep the order the ticket system returned
179
+ // them in: the sort is stable, and their IDs are opaque.
185
180
  function byTime(a, b) {
186
- const at = Date.parse(a.createdAt);
187
- const bt = Date.parse(b.createdAt);
188
- return at !== bt ? at - bt : a.id - b.id;
181
+ return Date.parse(a.createdAt) - Date.parse(b.createdAt);
189
182
  }
190
183
  export function markedComments(comments) {
191
184
  return [...comments]
@@ -222,17 +215,10 @@ export function workState(comments) {
222
215
  }
223
216
  return { live, lastLive, start };
224
217
  }
225
- /** Whether a pull request's body says it builds part of the follow-ups
226
- * issue, as "Part of #N". A plain mention, such as a build linking the issue
227
- * it added a line to, does not count. */
228
- export function buildsPartOf(body, number) {
229
- return new RegExp(`\\bpart of #${number}(?!\\d)`, "i").test(body);
230
- }
231
218
  /** The pull requests that put this issue In review. */
232
219
  export function reviewingPulls(issue, pulls) {
233
- return pulls.filter((pull) => pull.closes.includes(issue.number) ||
234
- (issue.labels.includes("follow-up") &&
235
- buildsPartOf(pull.body, issue.number)));
220
+ return pulls.filter((pull) => pull.closes.includes(issue.key) ||
221
+ (issue.labels.includes("follow-up") && pull.partOf.includes(issue.key)));
236
222
  }
237
223
  const READY_RESETS = new Set([
238
224
  "released",
@@ -444,7 +430,7 @@ const waiting = (columns) => `The card stays ${cardAt("In progress", columns)},
444
430
  const again = (issue, columns) => {
445
431
  const ready = columns.Ready?.[0] ?? null;
446
432
  if (ready === null)
447
- return `To try again, tell a session to build #${issue}, or run \`factory build ${issue}\`.`;
433
+ return `To try again, tell a session to build ${issue.ref}, or run \`factory build ${issue.key}\`.`;
448
434
  return `Move it to ${ready} to try again.`;
449
435
  };
450
436
  export function commentBody(c, columns = DEFAULT_COLUMNS) {
@@ -462,8 +448,8 @@ export function commentBody(c, columns = DEFAULT_COLUMNS) {
462
448
  return mark("waiting", withCost("Refinement is waiting on you: the questions are in the comment above.", c.cost));
463
449
  case "refined": {
464
450
  const sentence = ready === null
465
- ? `Refinement is done. This board has no column for approving a build: tell a session to build #${c.issue}, or run \`factory build ${c.issue}\`.`
466
- : `Refinement is done. The card stays ${cardAt("In refinement", columns)} until it moves to ${ready}, which starts a build in GitHub Actions: move it there, or ask this session to. To build it on your machine instead, tell a local session to work #${c.issue}.`;
451
+ ? `Refinement is done. This board has no column for approving a build: tell a session to build ${c.issue.ref}, or run \`factory build ${c.issue.key}\`.`
452
+ : `Refinement is done. The card stays ${cardAt("In refinement", columns)} until it moves to ${ready}, which starts a build in GitHub Actions: move it there, or ask this session to. To build it on your machine instead, tell a local session to work ${c.issue.ref}.`;
467
453
  const before = c.before?.trimEnd();
468
454
  const lead = [before, c.cost].filter(Boolean).join("\n\n");
469
455
  return mark("refined", lead ? `${lead}\n\n${sentence}` : sentence);
@@ -477,8 +463,8 @@ export function commentBody(c, columns = DEFAULT_COLUMNS) {
477
463
  case "stopped": {
478
464
  const head = `Stopped without a pull request: ${c.reason}. ${WAITING}`;
479
465
  const tail = c.where === "actions"
480
- ? `Run \`factory build ${c.issue}\` to try again${ready === null ? "." : `, or move it to ${ready}.`}`
481
- : `Tell a session to work #${c.issue} again${ready === null ? "." : `, or move it to ${ready} to build it in GitHub Actions.`}`;
466
+ ? `Run \`factory build ${c.issue.key}\` to try again${ready === null ? "." : `, or move it to ${ready}.`}`
467
+ : `Tell a session to work ${c.issue.ref} again${ready === null ? "." : `, or move it to ${ready} to build it in GitHub Actions.`}`;
482
468
  return mark("released", withCost(`${head} ${tail}`, c.cost));
483
469
  }
484
470
  case "ended":
@@ -491,7 +477,7 @@ export function commentBody(c, columns = DEFAULT_COLUMNS) {
491
477
  return mark("partial", `Pull request #${c.pull} merged part of these follow-ups. The unchecked lines wait for the next build; the card is back in ${columnFor("Backlog", columns)}.`);
492
478
  case "pull-closed":
493
479
  return mark("released", ready === null
494
- ? `Pull request #${c.pull} was closed without merging. ${WAITING} Tell a session to build #${c.issue}, or run \`factory build ${c.issue}\`, to rebuild it, or ask a session to refine it first.`
480
+ ? `Pull request #${c.pull} was closed without merging. ${WAITING} Tell a session to build ${c.issue.ref}, or run \`factory build ${c.issue.key}\`, to rebuild it, or ask a session to refine it first.`
495
481
  : `Pull request #${c.pull} was closed without merging. ${WAITING} Move it to ${ready} to rebuild it, or ask a session to refine it first.`);
496
482
  }
497
483
  }
@@ -511,8 +497,8 @@ export function toSnapshot(tickets, pulls, now, donePulls = []) {
511
497
  /** A ticket's card, its column read as the state that column shows. A
512
498
  * card with no Status has none; one in a column no state names is
513
499
  * "Unmapped". */
514
- export const cardOf = (board, number, columns = DEFAULT_COLUMNS) => {
515
- const item = board.items.get(number);
500
+ export const cardOf = (board, key, columns = DEFAULT_COLUMNS) => {
501
+ const item = board.items.get(key);
516
502
  if (!item)
517
503
  return null;
518
504
  const status = item.status === null
@@ -12,6 +12,7 @@ import { spawnSync } from "node:child_process";
12
12
  import { loadSettings } from "./config.mjs";
13
13
  import { openCodeHost } from "./code-host/index.mjs";
14
14
  import { matchesAny } from "./lib/glob.mjs";
15
+ import { processFiles } from "./specs/index.mjs";
15
16
  /** The code host's changed files under those names. */
16
17
  export const inGithubNames = (files) => files.map(({ path, previousPath, status }) => ({
17
18
  filename: path,
@@ -23,10 +24,13 @@ export const inGithubNames = (files) => files.map(({ path, previousPath, status
23
24
  export const AUTOMATIC = "merge: automatic";
24
25
  export const MANUAL = "merge: manual";
25
26
  /** The factory's own files, held whatever the settings allow: a pull request
26
- * must not be able to change how pull requests are judged. */
27
- const FACTORY_FILES = /^(\.github|\.claude)\/|(^|\/)(CLAUDE|AGENTS)\.md$|^openspec\/config\.yaml$/;
27
+ * must not be able to change how pull requests are judged. Every spec tool's
28
+ * process files are among them, whichever the settings name, since a pull
29
+ * request could change that setting too. */
30
+ const FACTORY_FILES = /^(\.github|\.claude)\/|(^|\/)(CLAUDE|AGENTS)\.md$/;
31
+ const SPEC_TOOL_FILES = new Set(processFiles());
28
32
  function classifyPath(path, policy) {
29
- if (FACTORY_FILES.test(path))
33
+ if (FACTORY_FILES.test(path) || SPEC_TOOL_FILES.has(path))
30
34
  return "the factory's own files";
31
35
  if (matchesAny(path, policy.deny))
32
36
  return "held by auto-merge.deny";
package/dist/poller.d.mts CHANGED
@@ -3,10 +3,10 @@ import { type Settings } from "./config.mts";
3
3
  import { type Columns, type Board, type RepoSnapshot } from "./lib/work-status.mts";
4
4
  import type { CodeHost } from "./code-host/types.mts";
5
5
  import type { Runner } from "./runner/types.mts";
6
- import { type Tickets } from "./tickets/types.mts";
6
+ import { type Key, type Tickets } from "./tickets/types.mts";
7
7
  export declare const FIRE_LIMIT = 20;
8
- /** The open issues the shared derivation puts in Ready, oldest number first. */
9
- export declare function selectToStart(snapshot: RepoSnapshot, board: Board, columns?: Columns): number[];
8
+ /** The open issues the shared derivation puts in Ready, in key order. */
9
+ export declare function selectToStart(snapshot: RepoSnapshot, board: Board, columns?: Columns): Key[];
10
10
  export declare function startMarker(): string;
11
11
  /** The columns the poller reads a board by. It runs with no settings file,
12
12
  * so it is told the one name it needs, the column that approves a build:
package/dist/poller.mjs CHANGED
@@ -29,18 +29,19 @@ import { githubCodeHost } from "./code-host/github.mjs";
29
29
  import { BUILD_WORKFLOW, githubActionsRunner, } from "./runner/github-actions.mjs";
30
30
  import { githubTickets } from "./tickets/github.mjs";
31
31
  import { HttpError, fetchTransport, statusOf } from "./tickets/transport.mjs";
32
- import { boardOf } from "./tickets/types.mjs";
32
+ import { boardOf, compareKeys, } from "./tickets/types.mjs";
33
+ import { linkPulls } from "./lib/pull-tickets.mjs";
33
34
  const MINUTE = 60_000;
34
35
  const HOUR = 60 * MINUTE;
35
36
  export const FIRE_LIMIT = 20;
36
37
  const FIRE_TIMEOUT_MS = 30_000;
37
- /** The open issues the shared derivation puts in Ready, oldest number first. */
38
+ /** The open issues the shared derivation puts in Ready, in key order. */
38
39
  export function selectToStart(snapshot, board, columns = DEFAULT_COLUMNS) {
39
40
  return snapshot.issues
40
41
  .filter((issue) => issue.state === "open" &&
41
- derive(issue, cardOf(board, issue.number, columns), snapshot.pulls, columns).status === "Ready")
42
- .map((issue) => issue.number)
43
- .sort((a, b) => a - b);
42
+ derive(issue, cardOf(board, issue.key, columns), snapshot.pulls, columns).status === "Ready")
43
+ .map((issue) => issue.key)
44
+ .sort(compareKeys);
44
45
  }
45
46
  export function startMarker() {
46
47
  return `st_${randomBytes(6).toString("hex")}`;
@@ -128,8 +129,10 @@ async function readAll(tickets, codeHost, d) {
128
129
  tickets.readAll({ board: true }),
129
130
  codeHost.open(),
130
131
  ]);
132
+ // The poller reaches GitHub alone, so the code host's links are the
133
+ // tickets' own.
131
134
  return {
132
- snapshot: toSnapshot(read, open, new Date(d.now())),
135
+ snapshot: toSnapshot(read, linkPulls(open, tickets, true), new Date(d.now())),
133
136
  board: boardOf(read),
134
137
  };
135
138
  }
@@ -182,20 +185,21 @@ export async function tick(d, state) {
182
185
  state.lastHeartbeat = d.now();
183
186
  }
184
187
  for (const issue of ready) {
188
+ const ref = tickets.ref(issue);
185
189
  try {
186
190
  const blockers = await tickets.blockers.list(issue);
187
191
  const open = blockers.filter((b) => b.state === "open");
188
192
  if (open.length) {
189
- d.log(`#${issue} waits on ${open.map((b) => `#${b.number}`).join(", ")}`);
193
+ d.log(`${ref} waits on ${open.map((b) => tickets.ref(b.key)).join(", ")}`);
190
194
  continue;
191
195
  }
192
196
  }
193
197
  catch (error) {
194
- d.log(`#${issue} skipped: its blockers could not be read (${String(error)})`);
198
+ d.log(`${ref} skipped: its blockers could not be read (${String(error)})`);
195
199
  continue;
196
200
  }
197
201
  if (!capAllows(fired, d.now())) {
198
- d.log(`#${issue} waits: ${FIRE_LIMIT} builds started in the last hour`);
202
+ d.log(`${ref} waits: ${FIRE_LIMIT} builds started in the last hour`);
199
203
  continue;
200
204
  }
201
205
  const marker = d.marker();
@@ -203,26 +207,26 @@ export async function tick(d, state) {
203
207
  await tickets.comment(issue, commentBody({ kind: "started", marker }, columns));
204
208
  }
205
209
  catch (error) {
206
- d.log(`#${issue} not started: the start comment failed (${String(error)})`);
210
+ d.log(`${ref} not started: the start comment failed (${String(error)})`);
207
211
  continue;
208
212
  }
209
213
  fired.push(d.now());
210
214
  const outcome = await dispatch(runner, d.defaultBranch, issue);
211
215
  if (outcome.ok) {
212
- d.log(`#${issue} started ${marker}: dispatched ${BUILD_WORKFLOW}`);
216
+ d.log(`${ref} started ${marker}: dispatched ${BUILD_WORKFLOW}`);
213
217
  continue;
214
218
  }
215
- d.log(`#${issue} dispatch failed: ${outcome.status} (${outcome.reason})`);
219
+ d.log(`${ref} dispatch failed: ${outcome.status} (${outcome.reason})`);
216
220
  try {
217
221
  await tickets.comment(issue, commentBody({
218
222
  kind: "dispatch-failed",
219
- issue,
223
+ issue: { key: issue, ref },
220
224
  status: outcome.status,
221
225
  reason: outcome.reason,
222
226
  }, columns));
223
227
  }
224
228
  catch (error) {
225
- d.log(`#${issue} dispatch-failure comment failed (${String(error)})`);
229
+ d.log(`${ref} dispatch-failure comment failed (${String(error)})`);
226
230
  }
227
231
  }
228
232
  }
package/dist/pr.d.mts CHANGED
@@ -2,6 +2,8 @@
2
2
  import { type Check } from "./pr-watch.mts";
3
3
  import { type CodeHost, type Pull, type PullComment, type Review, type Thread } from "./code-host/index.mts";
4
4
  import { type Run, type Runner } from "./runner/index.mts";
5
+ import type { Tickets } from "./tickets/types.mts";
6
+ import { type CostDeps } from "./ticket.mts";
5
7
  export type Deps = {
6
8
  /** The repository, as owner/name, from the factory's settings. */
7
9
  repository: string;
@@ -15,11 +17,26 @@ export type Deps = {
15
17
  now?: () => number;
16
18
  /** For GITHUB_ACTIONS, which says GraphQL is open without asking. */
17
19
  env?: Record<string, string | undefined>;
20
+ /** The settings' ticket system, and whether the code host's own links
21
+ * count (`lib/pull-tickets.mts`), for `closes`. */
22
+ tickets?: () => Promise<{
23
+ tickets: Tickets;
24
+ own: boolean;
25
+ }>;
26
+ /** The session's cost clock, for `cost`. */
27
+ cost?: CostDeps;
18
28
  };
29
+ /** The tickets a pull request builds, as the factory counts them. */
30
+ export declare function pullTickets(d: Deps, pr: number): Promise<{
31
+ tickets: Tickets;
32
+ links: import("./tickets/types.mts").Links;
33
+ }>;
19
34
  export declare function withAgentMark(body: string): string;
20
35
  export type Report = {
21
36
  pull: Pull;
22
- ownerLogin: string;
37
+ /** The authors among the reviews and the threads' last comments who can
38
+ * write to the repository. */
39
+ approvers: string[];
23
40
  reviewRun: {
24
41
  status: string;
25
42
  conclusion: string | null;
@@ -30,10 +47,10 @@ export type Report = {
30
47
  threads: Thread[];
31
48
  checks: Check[];
32
49
  };
33
- /** The owner's review bodies still to answer: submitted after the last
50
+ /** An approver's review bodies still to answer: submitted after the last
34
51
  * conversation comment carrying the agent mark, a sweep's own comments
35
52
  * aside. */
36
- export declare function ownerReviewsToWork(r: Report): Review[];
53
+ export declare function approverReviewsToWork(r: Report): Review[];
37
54
  /** A review is coming for this head only on a pull request the Claude review
38
55
  * workflow runs on. */
39
56
  export declare function reviewExpected(pull: Pull): boolean;
@@ -44,11 +61,11 @@ export declare function newestRuns(runs: Run[]): Run[];
44
61
  /** A conversation comment as `pr comments` lists it: ID, author, time, and
45
62
  * its first line. */
46
63
  export declare function commentLine(c: PullComment): string;
47
- /** Whether the owner's review has something in it to work, and if not,
48
- * why: "closed", "someone else's review", or "the factory's own reply". An
64
+ /** Whether an approver's review has something in it to work, and if not,
65
+ * why: "closed", "not an approver's", or "the factory's own reply". An
49
66
  * empty body counts for nothing, since the factory's reply is a review with
50
67
  * an empty body and one comment carrying the marker. */
51
- export declare function reviewPending(p: CodeHost, pr: number, reviewId: number, owner: string): Promise<{
68
+ export declare function reviewPending(p: CodeHost, pr: number, reviewId: number): Promise<{
52
69
  pending: true;
53
70
  } | {
54
71
  pending: false;
@@ -63,3 +80,6 @@ export declare function conflicting(p: CodeHost, sleepFor: (ms: number) => Promi
63
80
  export declare function main(argv: string[], d: Deps): Promise<number>;
64
81
  /** `factory pr ...`. */
65
82
  export declare function run(argv: string[]): Promise<number>;
83
+ /** What `run` gives `main`, for the repository and the code host and
84
+ * runner named. */
85
+ export declare function prDeps(repository: string, codeHost: string, runner: string): Deps;
package/dist/pr.mjs CHANGED
@@ -6,13 +6,15 @@
6
6
  // npx --no-install factory pr reply N COMMENT_ID --body-file FILE
7
7
  // npx --no-install factory pr resolve N COMMENT_ID
8
8
  // npx --no-install factory pr ready N # refuses an unverified commit when git signs
9
- // npx --no-install factory pr closes N # issues the pull request closes
9
+ // npx --no-install factory pr closes N # the tickets the pull request closes, by key
10
+ // npx --no-install factory pr cost N # notes this session's cost on the pull request
10
11
  // npx --no-install factory pr wait-checks N # every check on HEAD
11
- // npx --no-install factory pr review-pending N REVIEW # exits 0 when the owner's review needs an answer
12
+ // npx --no-install factory pr review-pending N REVIEW # exits 0 when an approver's review needs an answer
12
13
  // npx --no-install factory pr conflicts # the pull requests the conflict sweep takes
13
14
  // npx --no-install factory pr open --title TITLE --body-file FILE [--base BRANCH] [--ready]
14
15
  // npx --no-install factory pr view N --field FIELD # one field of a pull request
15
16
  // npx --no-install factory pr review N REVIEW # a review's author, body, and line comments
17
+ // npx --no-install factory pr comments N [--from-approvers] # conversation comments, or only an approver's
16
18
  // npx --no-install factory pr unverified N # the commits not shown as signed
17
19
  // npx --no-install factory pr failed N # each failed job's log, and a failed check's own report
18
20
  // npx --no-install factory pr review-again N # a fresh review of the same commit
@@ -23,29 +25,45 @@
23
25
  import { execFileSync } from "node:child_process";
24
26
  import { readFileSync } from "node:fs";
25
27
  import { setTimeout as sleep } from "node:timers/promises";
26
- import { reachOf } from "./config.mjs";
27
- import { AGENT_MARK } from "./lib/work-status.mjs";
28
+ import { loadSettings, reachOf } from "./config.mjs";
29
+ import { openTickets } from "./tickets/index.mjs";
30
+ import { ownLinks, ticketsOf } from "./lib/pull-tickets.mjs";
31
+ import { readClock, writeClock } from "./lib/clock.mjs";
32
+ import { measureSession, projectsDir } from "./lib/usage.mjs";
33
+ import { AGENT_MARK, commentBody } from "./lib/work-status.mjs";
28
34
  import { changedLines, parseLcov, uncovered } from "./patch-coverage.mjs";
29
35
  import { toChecks } from "./pr-watch.mjs";
30
36
  import { openCodeHost, } from "./code-host/index.mjs";
31
37
  import { openRunner } from "./runner/index.mjs";
32
38
  import { refuseBareTags, refuseOverride } from "./guard-ticket-text.mjs";
39
+ import { takeCost } from "./ticket.mjs";
40
+ /** The tickets a pull request builds, as the factory counts them. */
41
+ export async function pullTickets(d, pr) {
42
+ if (!d.tickets)
43
+ throw new Error("No ticket system to read links with.");
44
+ const { tickets, own } = await d.tickets();
45
+ const pull = await d.codeHost.get(pr);
46
+ return {
47
+ tickets,
48
+ links: ticketsOf({ body: pull.body, closes: own ? await d.codeHost.closes(pr) : [] }, tickets, own),
49
+ };
50
+ }
33
51
  export function withAgentMark(body) {
34
52
  return body.includes(AGENT_MARK)
35
53
  ? body
36
54
  : `${body.trimEnd()}\n\n${AGENT_MARK}`;
37
55
  }
38
56
  const SKIP_AS_LAST = /<!-- (conflict-fix|session-handoff) -->|conflict-stop/;
39
- /** The owner's review bodies still to answer: submitted after the last
57
+ /** An approver's review bodies still to answer: submitted after the last
40
58
  * conversation comment carrying the agent mark, a sweep's own comments
41
59
  * aside. */
42
- export function ownerReviewsToWork(r) {
60
+ export function approverReviewsToWork(r) {
43
61
  const answered = r.conversation
44
62
  .filter((c) => c.body.includes(AGENT_MARK) && !SKIP_AS_LAST.test(c.body))
45
63
  .map((c) => c.createdAt)
46
64
  .sort()
47
65
  .at(-1);
48
- return r.reviews.filter((review) => review.author === r.ownerLogin &&
66
+ return r.reviews.filter((review) => r.approvers.includes(review.author) &&
49
67
  review.body.trim() !== "" &&
50
68
  !review.body.includes(AGENT_MARK) &&
51
69
  (!answered || review.submittedAt > answered));
@@ -87,16 +105,18 @@ export function formatReport(r) {
87
105
  }
88
106
  else
89
107
  lines.push("summary: none for this head");
90
- const owner = ownerReviewsToWork(r);
91
- lines.push(`owner review bodies to answer: ${owner.length}`);
92
- for (const review of owner)
108
+ const toAnswer = approverReviewsToWork(r);
109
+ lines.push(`approver review bodies to answer: ${toAnswer.length}`);
110
+ for (const review of toAnswer)
93
111
  lines.push(` - review ${review.id} at ${review.submittedAt}: ${firstLine(review.body)}`);
94
112
  const open = r.threads.filter((t) => !t.isResolved);
95
113
  lines.push(`unresolved threads: ${open.length}`);
96
114
  for (const t of open) {
97
115
  const last = t.comments.at(-1);
98
- const ownerTurn = last?.author === r.ownerLogin && !last.body.includes(AGENT_MARK);
99
- lines.push(` - ${t.commentId} on ${t.path}:${t.line ?? "?"}${t.isOutdated ? " (outdated)" : ""} by ${t.comments[0]?.author ?? "?"}${ownerTurn ? ", owner's turn" : ""}: ${firstLine(t.comments[0]?.body ?? "")}`);
116
+ const approverTurn = last !== undefined &&
117
+ r.approvers.includes(last.author) &&
118
+ !last.body.includes(AGENT_MARK);
119
+ lines.push(` - ${t.commentId} on ${t.path}:${t.line ?? "?"}${t.isOutdated ? " (outdated)" : ""} by ${t.comments[0]?.author ?? "?"}${approverTurn ? ", approver's turn" : ""}: ${firstLine(t.comments[0]?.body ?? "")}`);
100
120
  }
101
121
  lines.push("checks:");
102
122
  if (r.checks.length === 0)
@@ -117,6 +137,13 @@ async function readPull(p, pr, d) {
117
137
  await d.sleep(10_000);
118
138
  }
119
139
  }
140
+ /** The distinct names among `authors` that can write to the repository,
141
+ * asking the code host once for each. Rejects when it cannot say. */
142
+ async function writers(p, authors) {
143
+ const distinct = [...new Set(authors)];
144
+ const can = await Promise.all(distinct.map((a) => p.canWrite(a)));
145
+ return distinct.filter((_, i) => can[i]);
146
+ }
120
147
  async function readReport(p, pr, d) {
121
148
  const pull = await readPull(p, pr, d);
122
149
  const sha = pull.head.sha;
@@ -132,10 +159,15 @@ async function readReport(p, pr, d) {
132
159
  .filter((c) => c.author === "github-actions[bot]" &&
133
160
  c.body.includes(`claude-review sha=${sha}`))
134
161
  .at(-1) ?? null;
162
+ const authors = [
163
+ ...reviews.map((review) => review.author),
164
+ ...threads
165
+ .filter((t) => !t.isResolved)
166
+ .flatMap((t) => t.comments.at(-1)?.author ?? []),
167
+ ];
135
168
  return {
136
169
  pull,
137
- // The owner is the part of the repository before the slash.
138
- ownerLogin: d.repository.split("/")[0],
170
+ approvers: await writers(p, authors),
139
171
  reviewRun: runs[0] ?? null,
140
172
  summary,
141
173
  conversation,
@@ -210,7 +242,7 @@ const FIELDS = {
210
242
  };
211
243
  /** How many lines of a failed job's log `failed` prints, from its end. */
212
244
  const LOG_TAIL = 200;
213
- const USAGE = `Usage: npx --no-install factory pr state [N] [--wait] | threads N [--all] | reply N COMMENT_ID --body-file FILE | resolve N COMMENT_ID | ready N | closes N | for-branch BRANCH | wait-checks N | comments N [--author LOGIN] [--contains TEXT] [--json] | comment N --body-file FILE | comment-view ID | label N --add LABEL | --remove LABEL | review-pending N REVIEW | conflicts | open --title TITLE --body-file FILE [--base BRANCH] [--ready] | view N --field ${Object.keys(FIELDS).join("|")} | review N REVIEW | unverified N | uncovered [BASE] [LCOV] | failed N | review-again N`;
245
+ const USAGE = `Usage: npx --no-install factory pr state [N] [--wait] | threads N [--all] | reply N COMMENT_ID --body-file FILE | resolve N COMMENT_ID | ready N | closes N | cost N | for-branch BRANCH | wait-checks N | comments N [--author LOGIN] [--contains TEXT] [--from-approvers] [--json] | comment N --body-file FILE | comment-view ID | label N --add LABEL | --remove LABEL | review-pending N REVIEW | conflicts | open --title TITLE --body-file FILE [--base BRANCH] [--ready] | view N --field ${Object.keys(FIELDS).join("|")} | review N REVIEW | unverified N | uncovered [BASE] [LCOV] | failed N | review-again N`;
214
246
  function option(args, name) {
215
247
  const at = args.indexOf(name);
216
248
  if (at === -1)
@@ -243,11 +275,11 @@ function gitSigns(d) {
243
275
  return false;
244
276
  }
245
277
  }
246
- /** Whether the owner's review has something in it to work, and if not,
247
- * why: "closed", "someone else's review", or "the factory's own reply". An
278
+ /** Whether an approver's review has something in it to work, and if not,
279
+ * why: "closed", "not an approver's", or "the factory's own reply". An
248
280
  * empty body counts for nothing, since the factory's reply is a review with
249
281
  * an empty body and one comment carrying the marker. */
250
- export async function reviewPending(p, pr, reviewId, owner) {
282
+ export async function reviewPending(p, pr, reviewId) {
251
283
  const pull = await p.get(pr);
252
284
  if (pull.state !== "open")
253
285
  return {
@@ -257,8 +289,8 @@ export async function reviewPending(p, pr, reviewId, owner) {
257
289
  const review = (await p.reviews(pr)).find((r) => r.id === reviewId);
258
290
  if (!review)
259
291
  throw new Error(`No review ${reviewId} on #${pr}.`);
260
- if (review.author !== owner)
261
- return { pending: false, why: `review ${reviewId} is someone else's` };
292
+ if (!(await p.canWrite(review.author)))
293
+ return { pending: false, why: `review ${reviewId} is not an approver's` };
262
294
  const { body } = review;
263
295
  if (body.trim() !== "" && !body.includes(AGENT_MARK))
264
296
  return { pending: true };
@@ -267,7 +299,7 @@ export async function reviewPending(p, pr, reviewId, owner) {
267
299
  return { pending: true };
268
300
  return {
269
301
  pending: false,
270
- why: `review ${reviewId} is the factory's own reply: nothing of the owner's in it`,
302
+ why: `review ${reviewId} is the factory's own reply: nothing of an approver's in it`,
271
303
  };
272
304
  }
273
305
  const CONFLICT_READS = 5;
@@ -379,7 +411,18 @@ export async function main(argv, d) {
379
411
  const [pr] = numbers;
380
412
  if (!pr)
381
413
  throw new Error(USAGE);
382
- d.out((await p.closes(pr)).join(" "));
414
+ d.out((await pullTickets(d, pr)).links.closes.join(" "));
415
+ return 0;
416
+ }
417
+ case "cost": {
418
+ const [pr] = numbers;
419
+ if (!pr || !d.cost)
420
+ throw new Error(USAGE);
421
+ // Read first: a number that is no pull request leaves the clock.
422
+ await p.get(pr);
423
+ const note = takeCost(`#${pr}`, d.cost);
424
+ await p.comment(pr, commentBody({ kind: "cost", cost: note }));
425
+ d.out("posted");
383
426
  return 0;
384
427
  }
385
428
  case "wait-checks": {
@@ -394,9 +437,7 @@ export async function main(argv, d) {
394
437
  const [pr, review] = numbers;
395
438
  if (!pr || !review)
396
439
  throw new Error(USAGE);
397
- const result = await reviewPending(p, pr, review,
398
- // The owner is the part of the repository before the slash.
399
- d.repository.split("/")[0]);
440
+ const result = await reviewPending(p, pr, review);
400
441
  if (result.pending) {
401
442
  d.out("pending");
402
443
  return 0;
@@ -419,8 +460,12 @@ export async function main(argv, d) {
419
460
  throw new Error(USAGE);
420
461
  const author = option(rest, "--author");
421
462
  const contains = option(rest, "--contains");
422
- const kept = (await p.comments(pr)).filter((c) => (author === undefined || c.author === author) &&
463
+ let kept = (await p.comments(pr)).filter((c) => (author === undefined || c.author === author) &&
423
464
  (contains === undefined || c.body.includes(contains)));
465
+ if (rest.includes("--from-approvers")) {
466
+ const can = await writers(p, kept.map((c) => c.author));
467
+ kept = kept.filter((c) => can.includes(c.author));
468
+ }
424
469
  if (rest.includes("--json"))
425
470
  d.out(JSON.stringify(kept.map(inGithubNames), null, 2));
426
471
  else
@@ -592,7 +637,12 @@ export async function main(argv, d) {
592
637
  /** `factory pr ...`. */
593
638
  export async function run(argv) {
594
639
  const { repository, codeHost, runner } = await reachOf(process.env);
595
- return main(argv, {
640
+ return main(argv, prDeps(repository, codeHost, runner));
641
+ }
642
+ /** What `run` gives `main`, for the repository and the code host and
643
+ * runner named. */
644
+ export function prDeps(repository, codeHost, runner) {
645
+ return {
596
646
  repository,
597
647
  codeHost: openCodeHost(repository, codeHost),
598
648
  runner: openRunner(repository, runner),
@@ -607,5 +657,19 @@ export async function run(argv) {
607
657
  stdio: ["ignore", "pipe", "pipe"],
608
658
  }),
609
659
  env: process.env,
610
- });
660
+ tickets: async () => {
661
+ const settings = await loadSettings();
662
+ const { tickets } = await openTickets(settings, {
663
+ repository,
664
+ board: null,
665
+ });
666
+ return { tickets, own: ownLinks(settings) };
667
+ },
668
+ cost: {
669
+ env: process.env,
670
+ now: () => new Date(),
671
+ clock: { read: readClock, write: writeClock },
672
+ measure: (session, since) => measureSession(projectsDir(process.env), session, since),
673
+ },
674
+ };
611
675
  }
@@ -0,0 +1,12 @@
1
+ import { type Links, type Tickets } from "./tickets/types.mts";
2
+ export type Deps = {
3
+ /** The tickets pull request N builds, as `factory pr closes` reads them. */
4
+ pull: (pr: number) => Promise<{
5
+ tickets: Tickets;
6
+ links: Links;
7
+ }>;
8
+ out: (line: string) => void;
9
+ };
10
+ export declare function main(argv: string[], d: Deps): Promise<number>;
11
+ /** `factory review tickets N`. */
12
+ export declare function run(argv: string[]): Promise<number>;
@@ -0,0 +1,59 @@
1
+ // Prints the tickets a pull request builds, for its review: each one it
2
+ // closes, then each it builds part of, as a `## ` heading with the ticket's
3
+ // written form and title, then its body.
4
+ //
5
+ // npx --no-install factory review tickets N
6
+ //
7
+ // The review workflow runs it from the base commit's install and hands the
8
+ // reviewer its output, so a pull request cannot change what its own review
9
+ // is told the tickets say.
10
+ import { reachOf } from "./config.mjs";
11
+ import { prDeps, pullTickets } from "./pr.mjs";
12
+ import { NotFoundError, } from "./tickets/types.mjs";
13
+ const USAGE = "Usage: factory review tickets N";
14
+ export async function main(argv, d) {
15
+ const pr = Number(argv[0]);
16
+ if (argv.length !== 1 || !Number.isInteger(pr) || pr <= 0) {
17
+ console.error(USAGE);
18
+ return 2;
19
+ }
20
+ try {
21
+ const { tickets, links } = await d.pull(pr);
22
+ const keys = [
23
+ ...links.closes,
24
+ ...links.partOf.filter((k) => !links.closes.includes(k)),
25
+ ];
26
+ for (const [i, key] of keys.entries()) {
27
+ if (i > 0)
28
+ d.out("");
29
+ const ref = tickets.ref(key);
30
+ try {
31
+ const ticket = await tickets.read(key);
32
+ d.out(`## ${ref} ${ticket.title}`);
33
+ d.out("");
34
+ d.out(ticket.body.trimEnd());
35
+ }
36
+ catch (error) {
37
+ if (!(error instanceof NotFoundError))
38
+ throw error;
39
+ d.out(`## ${ref}`);
40
+ d.out("");
41
+ d.out("Not found.");
42
+ }
43
+ }
44
+ return 0;
45
+ }
46
+ catch (error) {
47
+ console.error(error instanceof Error ? error.message : String(error));
48
+ return 1;
49
+ }
50
+ }
51
+ /** `factory review tickets N`. */
52
+ export async function run(argv) {
53
+ const { repository, codeHost, runner } = await reachOf(process.env);
54
+ const deps = prDeps(repository, codeHost, runner);
55
+ return main(argv, {
56
+ pull: (n) => pullTickets(deps, n),
57
+ out: (line) => console.log(line),
58
+ });
59
+ }