@davidbyoung/software-factory 0.1.11 → 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 (56) hide show
  1. package/agents/factory-e2e-reviewer.md +1 -1
  2. package/agents/factory-test-reviewer.md +1 -1
  3. package/agents/factory-ui-reviewer.md +2 -2
  4. package/dist/board.d.mts +7 -7
  5. package/dist/board.mjs +50 -33
  6. package/dist/build.d.mts +4 -0
  7. package/dist/build.mjs +9 -4
  8. package/dist/cli.mjs +8 -1
  9. package/dist/code-host/github.mjs +9 -4
  10. package/dist/code-host/types.d.mts +4 -2
  11. package/dist/commands.d.mts +1 -1
  12. package/dist/commands.mjs +15 -6
  13. package/dist/lib/clock.d.mts +3 -1
  14. package/dist/lib/clock.mjs +12 -6
  15. package/dist/lib/pull-tickets.d.mts +15 -0
  16. package/dist/lib/pull-tickets.mjs +12 -0
  17. package/dist/lib/usage.d.mts +3 -1
  18. package/dist/lib/usage.mjs +4 -2
  19. package/dist/lib/work-status.d.mts +23 -19
  20. package/dist/lib/work-status.mjs +14 -27
  21. package/dist/poller.d.mts +3 -3
  22. package/dist/poller.mjs +18 -14
  23. package/dist/pr.d.mts +18 -0
  24. package/dist/pr.mjs +54 -7
  25. package/dist/review-tickets.d.mts +12 -0
  26. package/dist/review-tickets.mjs +59 -0
  27. package/dist/reviewers.d.mts +7 -4
  28. package/dist/reviewers.mjs +19 -12
  29. package/dist/runner/github-actions.mjs +6 -7
  30. package/dist/runner/types.d.mts +7 -6
  31. package/dist/status.d.mts +17 -7
  32. package/dist/status.mjs +35 -23
  33. package/dist/sync.d.mts +4 -0
  34. package/dist/sync.mjs +14 -1
  35. package/dist/ticket.d.mts +13 -7
  36. package/dist/ticket.mjs +94 -60
  37. package/dist/tickets/github.d.mts +10 -2
  38. package/dist/tickets/github.mjs +74 -20
  39. package/dist/tickets/index.d.mts +7 -1
  40. package/dist/tickets/index.mjs +15 -1
  41. package/dist/tickets/types.d.mts +59 -30
  42. package/dist/tickets/types.mjs +13 -3
  43. package/docs/cli.md +11 -7
  44. package/docs/configuration.md +1 -1
  45. package/docs/developing.md +16 -8
  46. package/docs/github/reference.md +1 -1
  47. package/docs/plugins.md +6 -6
  48. package/package.json +1 -1
  49. package/review.md +11 -11
  50. package/rules.md +18 -14
  51. package/skills/factory-address-review/SKILL.md +4 -3
  52. package/skills/factory-build/SKILL.md +25 -19
  53. package/skills/factory-refine/SKILL.md +1 -1
  54. package/skills/factory-resolve-conflicts/SKILL.md +4 -3
  55. package/workflows/factory-build.yml +6 -5
  56. package/workflows/factory-claude-review.yml +38 -1
@@ -1,4 +1,4 @@
1
- import type { Board, Ticket, TicketComment } from "../tickets/types.mts";
1
+ import type { Board, Key, Ticket, TicketComment } from "../tickets/types.mts";
2
2
  export type { Board, BoardField, BoardItem } from "../tickets/types.mts";
3
3
  export declare const AGENT_MARK = "<!-- agent -->";
4
4
  export declare const STATUSES: readonly ["Backlog", "In refinement", "Ready", "In progress", "In review", "Done"];
@@ -79,9 +79,6 @@ export declare function hasCostMarker(body: string): boolean;
79
79
  * agent mark, whoever posted it, as a claim or a release does, or when the
80
80
  * pull request review's bot posted it. */
81
81
  export declare function parseCosts(comment: IssueComment): number[];
82
- /** Whether a pull request's body says it builds this issue, as "Closes #N"
83
- * or "Part of #N". */
84
- export declare function buildsIssue(body: string, number: number): boolean;
85
82
  /** The issue's Cost: every cost marker on it and on each pull request, open,
86
83
  * merged, or closed, that builds it, to the cent. Null when there are none. */
87
84
  export declare function issueCost(issue: Issue, pulls: PullRequest[]): number | null;
@@ -129,8 +126,13 @@ export type PullRequest = {
129
126
  number: number;
130
127
  createdAt: string;
131
128
  body: string;
132
- /** Issue numbers GitHub links as closed by this pull request. */
133
- closes: number[];
129
+ /** The tickets it closes when it merges. The code host fills it with its
130
+ * own links, and `linkPulls` (`lib/pull-tickets.mts`) with what the
131
+ * factory counts. */
132
+ closes: Key[];
133
+ /** The tickets its body says it builds part of, once `linkPulls` has
134
+ * read it; empty before. */
135
+ partOf: Key[];
134
136
  isDraft: boolean;
135
137
  checks: string | null;
136
138
  openThreads: number;
@@ -151,10 +153,6 @@ export type Derived = {
151
153
  /** Open pull requests that put the issue In review. */
152
154
  pulls: number[];
153
155
  };
154
- /** Whether a pull request's body says it builds part of the follow-ups
155
- * issue, as "Part of #N". A plain mention, such as a build linking the issue
156
- * it added a line to, does not count. */
157
- export declare function buildsPartOf(body: string, number: number): boolean;
158
156
  /** The pull requests that put this issue In review. */
159
157
  export declare function reviewingPulls(issue: Issue, pulls: PullRequest[]): PullRequest[];
160
158
  /** The page of an Actions run, from the board's or the view's session: the
@@ -177,7 +175,7 @@ export type Watch = {
177
175
  export declare function watchOf(trigger: "own-server" | "github-action" | "manual", pollMinutes: number): Watch | null;
178
176
  /** Ready for longer than the poller takes, with no start: it should have
179
177
  * fired. */
180
- export declare function isNotStarted(derived: Derived, openBlockers: number[], now: Date, minutes?: number): boolean;
178
+ export declare function isNotStarted(derived: Derived, openBlockers: Key[], now: Date, minutes?: number): boolean;
181
179
  /** A claim or start over 24 hours old with no pull request, which the
182
180
  * nightly sync clears. Null when there is nothing to clear. */
183
181
  export declare function toClear(issue: Issue, pulls: PullRequest[], now: Date): {
@@ -195,6 +193,12 @@ export type Identity = {
195
193
  };
196
194
  /** The comments sessions, the poller, and the sync post: one visible
197
195
  * sentence, then its marker line and the agent mark. */
196
+ /** A ticket as a comment names it: its key, for a command, and its written
197
+ * form, for prose. */
198
+ export type Named = {
199
+ key: Key;
200
+ ref: string;
201
+ };
198
202
  export type CommentKind = {
199
203
  kind: "refining";
200
204
  who: Identity;
@@ -203,7 +207,7 @@ export type CommentKind = {
203
207
  cost?: string;
204
208
  } | {
205
209
  kind: "refined";
206
- issue: number;
210
+ issue: Named;
207
211
  before?: string;
208
212
  cost?: string;
209
213
  } | {
@@ -211,7 +215,7 @@ export type CommentKind = {
211
215
  marker: string;
212
216
  } | {
213
217
  kind: "dispatch-failed";
214
- issue: number;
218
+ issue: Named;
215
219
  status: string;
216
220
  reason: string;
217
221
  } | {
@@ -220,7 +224,7 @@ export type CommentKind = {
220
224
  } | {
221
225
  kind: "stopped";
222
226
  where: SessionKind;
223
- issue: number;
227
+ issue: Named;
224
228
  reason: string;
225
229
  cost?: string;
226
230
  } | {
@@ -228,21 +232,21 @@ export type CommentKind = {
228
232
  cost: string;
229
233
  } | {
230
234
  kind: "ended";
231
- issue: number;
235
+ issue: Named;
232
236
  } | {
233
237
  kind: "cleared-claim";
234
- issue: number;
238
+ issue: Named;
235
239
  since: string;
236
240
  } | {
237
241
  kind: "cleared-start";
238
- issue: number;
242
+ issue: Named;
239
243
  since: string;
240
244
  } | {
241
245
  kind: "follow-ups-merged";
242
246
  pull: number;
243
247
  } | {
244
248
  kind: "pull-closed";
245
- issue: number;
249
+ issue: Named;
246
250
  pull: number;
247
251
  };
248
252
  export declare function commentBody(c: CommentKind, columns?: Columns): string;
@@ -261,4 +265,4 @@ export declare function toSnapshot(tickets: Issue[], pulls: PullRequest[], now:
261
265
  /** A ticket's card, its column read as the state that column shows. A
262
266
  * card with no Status has none; one in a column no state names is
263
267
  * "Unmapped". */
264
- export declare const cardOf: (board: Board, number: number, columns?: Columns) => BoardCard | null;
268
+ export declare const cardOf: (board: Board, key: Key, columns?: Columns) => BoardCard | null;
@@ -126,19 +126,13 @@ export function parseCosts(comment) {
126
126
  return match ? [Number(match[1])] : [];
127
127
  });
128
128
  }
129
- /** Whether a pull request's body says it builds this issue, as "Closes #N"
130
- * or "Part of #N". */
131
- export function buildsIssue(body, number) {
132
- return new RegExp(`\\b(?:closes|part of) #${number}(?!\\d)`, "i").test(body);
133
- }
134
129
  /** The issue's Cost: every cost marker on it and on each pull request, open,
135
130
  * merged, or closed, that builds it, to the cent. Null when there are none. */
136
131
  export function issueCost(issue, pulls) {
137
132
  const comments = [
138
133
  ...issue.comments,
139
134
  ...pulls
140
- .filter((pull) => pull.closes.includes(issue.number) ||
141
- buildsIssue(pull.body, issue.number))
135
+ .filter((pull) => pull.closes.includes(issue.key) || pull.partOf.includes(issue.key))
142
136
  .flatMap((pull) => pull.comments ?? []),
143
137
  ];
144
138
  const costs = comments.flatMap((c) => parseCosts(c));
@@ -181,10 +175,10 @@ export function parseRuns(comment) {
181
175
  export const STUCK_AFTER_MS = 2 * 60 * 60 * 1000;
182
176
  export const isStuck = (run, now) => run.result === "running" &&
183
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.
184
180
  function byTime(a, b) {
185
- const at = Date.parse(a.createdAt);
186
- const bt = Date.parse(b.createdAt);
187
- return at !== bt ? at - bt : a.id - b.id;
181
+ return Date.parse(a.createdAt) - Date.parse(b.createdAt);
188
182
  }
189
183
  export function markedComments(comments) {
190
184
  return [...comments]
@@ -221,17 +215,10 @@ export function workState(comments) {
221
215
  }
222
216
  return { live, lastLive, start };
223
217
  }
224
- /** Whether a pull request's body says it builds part of the follow-ups
225
- * issue, as "Part of #N". A plain mention, such as a build linking the issue
226
- * it added a line to, does not count. */
227
- export function buildsPartOf(body, number) {
228
- return new RegExp(`\\bpart of #${number}(?!\\d)`, "i").test(body);
229
- }
230
218
  /** The pull requests that put this issue In review. */
231
219
  export function reviewingPulls(issue, pulls) {
232
- return pulls.filter((pull) => pull.closes.includes(issue.number) ||
233
- (issue.labels.includes("follow-up") &&
234
- 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)));
235
222
  }
236
223
  const READY_RESETS = new Set([
237
224
  "released",
@@ -443,7 +430,7 @@ const waiting = (columns) => `The card stays ${cardAt("In progress", columns)},
443
430
  const again = (issue, columns) => {
444
431
  const ready = columns.Ready?.[0] ?? null;
445
432
  if (ready === null)
446
- 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}\`.`;
447
434
  return `Move it to ${ready} to try again.`;
448
435
  };
449
436
  export function commentBody(c, columns = DEFAULT_COLUMNS) {
@@ -461,8 +448,8 @@ export function commentBody(c, columns = DEFAULT_COLUMNS) {
461
448
  return mark("waiting", withCost("Refinement is waiting on you: the questions are in the comment above.", c.cost));
462
449
  case "refined": {
463
450
  const sentence = ready === null
464
- ? `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}\`.`
465
- : `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}.`;
466
453
  const before = c.before?.trimEnd();
467
454
  const lead = [before, c.cost].filter(Boolean).join("\n\n");
468
455
  return mark("refined", lead ? `${lead}\n\n${sentence}` : sentence);
@@ -476,8 +463,8 @@ export function commentBody(c, columns = DEFAULT_COLUMNS) {
476
463
  case "stopped": {
477
464
  const head = `Stopped without a pull request: ${c.reason}. ${WAITING}`;
478
465
  const tail = c.where === "actions"
479
- ? `Run \`factory build ${c.issue}\` to try again${ready === null ? "." : `, or move it to ${ready}.`}`
480
- : `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.`}`;
481
468
  return mark("released", withCost(`${head} ${tail}`, c.cost));
482
469
  }
483
470
  case "ended":
@@ -490,7 +477,7 @@ export function commentBody(c, columns = DEFAULT_COLUMNS) {
490
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)}.`);
491
478
  case "pull-closed":
492
479
  return mark("released", ready === null
493
- ? `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.`
494
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.`);
495
482
  }
496
483
  }
@@ -510,8 +497,8 @@ export function toSnapshot(tickets, pulls, now, donePulls = []) {
510
497
  /** A ticket's card, its column read as the state that column shows. A
511
498
  * card with no Status has none; one in a column no state names is
512
499
  * "Unmapped". */
513
- export const cardOf = (board, number, columns = DEFAULT_COLUMNS) => {
514
- const item = board.items.get(number);
500
+ export const cardOf = (board, key, columns = DEFAULT_COLUMNS) => {
501
+ const item = board.items.get(key);
515
502
  if (!item)
516
503
  return null;
517
504
  const status = item.status === null
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,7 +17,20 @@ 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;
@@ -65,3 +80,6 @@ export declare function conflicting(p: CodeHost, sleepFor: (ms: number) => Promi
65
80
  export declare function main(argv: string[], d: Deps): Promise<number>;
66
81
  /** `factory pr ...`. */
67
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,7 +6,8 @@
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
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
@@ -24,13 +25,29 @@
24
25
  import { execFileSync } from "node:child_process";
25
26
  import { readFileSync } from "node:fs";
26
27
  import { setTimeout as sleep } from "node:timers/promises";
27
- import { reachOf } from "./config.mjs";
28
- 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";
29
34
  import { changedLines, parseLcov, uncovered } from "./patch-coverage.mjs";
30
35
  import { toChecks } from "./pr-watch.mjs";
31
36
  import { openCodeHost, } from "./code-host/index.mjs";
32
37
  import { openRunner } from "./runner/index.mjs";
33
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
+ }
34
51
  export function withAgentMark(body) {
35
52
  return body.includes(AGENT_MARK)
36
53
  ? body
@@ -225,7 +242,7 @@ const FIELDS = {
225
242
  };
226
243
  /** How many lines of a failed job's log `failed` prints, from its end. */
227
244
  const LOG_TAIL = 200;
228
- 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] [--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`;
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`;
229
246
  function option(args, name) {
230
247
  const at = args.indexOf(name);
231
248
  if (at === -1)
@@ -394,7 +411,18 @@ export async function main(argv, d) {
394
411
  const [pr] = numbers;
395
412
  if (!pr)
396
413
  throw new Error(USAGE);
397
- 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");
398
426
  return 0;
399
427
  }
400
428
  case "wait-checks": {
@@ -609,7 +637,12 @@ export async function main(argv, d) {
609
637
  /** `factory pr ...`. */
610
638
  export async function run(argv) {
611
639
  const { repository, codeHost, runner } = await reachOf(process.env);
612
- 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 {
613
646
  repository,
614
647
  codeHost: openCodeHost(repository, codeHost),
615
648
  runner: openRunner(repository, runner),
@@ -624,5 +657,19 @@ export async function run(argv) {
624
657
  stdio: ["ignore", "pipe", "pipe"],
625
658
  }),
626
659
  env: process.env,
627
- });
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
+ };
628
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
+ }
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { type Tickets } from "./tickets/types.mts";
2
+ import { type Key, type Tickets } from "./tickets/types.mts";
3
3
  import { type Clock } from "./lib/clock.mts";
4
4
  import { type ReviewerRun } from "./lib/work-status.mts";
5
5
  export type HookInput = {
@@ -12,7 +12,7 @@ export type HookInput = {
12
12
  /** What the hook remembers between its runs: the comment it posted, and the
13
13
  * rows it shows. */
14
14
  export type State = {
15
- commentId: number | null;
15
+ commentId: string | null;
16
16
  runs: ReviewerRun[];
17
17
  };
18
18
  export type Deps = {
@@ -24,8 +24,8 @@ export type Deps = {
24
24
  /** The text of a file, or null when it cannot be read. */
25
25
  readFile: (path: string) => string | null;
26
26
  state: {
27
- read: (session: string, issue: number) => State;
28
- write: (session: string, issue: number, state: State) => void;
27
+ read: (session: string, issue: Key) => State;
28
+ write: (session: string, issue: Key, state: State) => void;
29
29
  };
30
30
  /** Runs `work` while no other hook of this session edits the comment. */
31
31
  locked: <T>(session: string, work: () => Promise<T>) => Promise<T>;
@@ -50,5 +50,8 @@ export declare function resultText(run: ReviewerRun, now: Date): string;
50
50
  * note already includes what the reviewers spent. */
51
51
  export declare function commentFor(session: string, runs: ReviewerRun[], now: Date): string;
52
52
  export declare function main(event: string, input: HookInput, agentsDir: string, d: Deps): Promise<number>;
53
+ /** A state file's text as the state; none when there is no file or it
54
+ * cannot be read. */
55
+ export declare function parseState(text: string | null): State;
53
56
  /** `factory reviewers start|stop`, with the hook's input on stdin. */
54
57
  export declare function run(argv: string[]): Promise<number>;
@@ -234,11 +234,28 @@ export async function main(event, input, agentsDir, d) {
234
234
  catch (error) {
235
235
  const why = error instanceof Error ? error.message : String(error);
236
236
  d.out(JSON.stringify({
237
- systemMessage: `The ${reviewer} run was not recorded${issue === null ? "" : ` on #${issue}`}: ${why.split("\n")[0].slice(0, 200)}`,
237
+ systemMessage: `The ${reviewer} run was not recorded${issue === null ? "" : ` on ticket ${issue}`}: ${why.split("\n")[0].slice(0, 200)}`,
238
238
  }));
239
239
  }
240
240
  return 0;
241
241
  }
242
+ /** A state file's text as the state; none when there is no file or it
243
+ * cannot be read. */
244
+ export function parseState(text) {
245
+ try {
246
+ if (!text)
247
+ return { commentId: null, runs: [] };
248
+ const state = JSON.parse(text);
249
+ // State written before comment IDs were text holds a number.
250
+ return {
251
+ ...state,
252
+ commentId: state.commentId === null ? null : String(state.commentId),
253
+ };
254
+ }
255
+ catch {
256
+ return { commentId: null, runs: [] };
257
+ }
258
+ }
242
259
  const statePath = (session, issue) => join(commonDir(), `reviewer-runs-${session}-${issue}.json`);
243
260
  /** A lock directory beside the state, since reviewers run in parallel. One
244
261
  * older than a minute was left by a hook that died, and is taken over. */
@@ -293,17 +310,7 @@ export async function run(argv) {
293
310
  clock: readClock,
294
311
  readFile: read,
295
312
  state: {
296
- read: (session, issue) => {
297
- const text = read(statePath(session, issue));
298
- try {
299
- return text
300
- ? JSON.parse(text)
301
- : { commentId: null, runs: [] };
302
- }
303
- catch {
304
- return { commentId: null, runs: [] };
305
- }
306
- },
313
+ read: (session, issue) => parseState(read(statePath(session, issue))),
307
314
  write: (session, issue, state) => writeFileSync(statePath(session, issue), JSON.stringify(state)),
308
315
  },
309
316
  locked,