@davidbyoung/software-factory 0.1.3 → 0.1.5

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 (80) hide show
  1. package/README.md +12 -11
  2. package/actions/factory-agent/action.yml +1 -1
  3. package/agents/factory-e2e-reviewer.md +102 -0
  4. package/agents/factory-test-reviewer.md +26 -64
  5. package/agents/factory-ticket-readiness.md +14 -6
  6. package/dist/cli.mjs +28 -1
  7. package/dist/code-host/github-setup.mjs +1 -1
  8. package/dist/commands.d.mts +16 -0
  9. package/dist/commands.mjs +129 -0
  10. package/dist/config.d.mts +61 -13
  11. package/dist/config.mjs +271 -69
  12. package/dist/deps.d.mts +7 -4
  13. package/dist/deps.mjs +20 -9
  14. package/dist/doctor.d.mts +3 -2
  15. package/dist/doctor.mjs +19 -4
  16. package/dist/explain.d.mts +4 -2
  17. package/dist/explain.mjs +70 -23
  18. package/dist/guard-commit.d.mts +7 -2
  19. package/dist/guard-commit.mjs +58 -21
  20. package/dist/init.d.mts +4 -2
  21. package/dist/init.mjs +18 -8
  22. package/dist/lib/default-branch.d.mts +35 -0
  23. package/dist/lib/default-branch.mjs +117 -0
  24. package/dist/lib/refined-check.d.mts +7 -0
  25. package/dist/lib/refined-check.mjs +76 -0
  26. package/dist/lib/work-status.d.mts +2 -2
  27. package/dist/lib/work-status.mjs +4 -4
  28. package/dist/parts.d.mts +1 -1
  29. package/dist/parts.mjs +2 -2
  30. package/dist/patch-coverage.d.mts +13 -0
  31. package/dist/patch-coverage.mjs +73 -0
  32. package/dist/pr-watch.d.mts +3 -2
  33. package/dist/pr-watch.mjs +22 -5
  34. package/dist/pr.mjs +34 -2
  35. package/dist/review-cost.mjs +1 -1
  36. package/dist/review-tools.mjs +3 -3
  37. package/dist/session-start.d.mts +23 -13
  38. package/dist/session-start.mjs +56 -44
  39. package/dist/site/servers.d.mts +6 -2
  40. package/dist/site/servers.mjs +14 -9
  41. package/dist/site.mjs +2 -2
  42. package/dist/sync.d.mts +8 -2
  43. package/dist/sync.mjs +41 -7
  44. package/dist/ticket.mjs +19 -1
  45. package/docs/builds.md +8 -8
  46. package/docs/cli.md +82 -45
  47. package/docs/configuration.md +838 -565
  48. package/docs/design.md +17 -4
  49. package/docs/developing.md +44 -8
  50. package/docs/existing-repo.md +9 -7
  51. package/docs/github/by-hand.md +27 -14
  52. package/docs/github/reference.md +21 -16
  53. package/docs/github/setup.md +14 -11
  54. package/docs/glossary.md +14 -5
  55. package/docs/limitations.md +27 -2
  56. package/docs/plugins.md +307 -52
  57. package/docs/quick-start.md +37 -9
  58. package/docs/removing.md +2 -2
  59. package/docs/skills.md +103 -54
  60. package/docs/updating.md +149 -3
  61. package/docs/workflow.md +13 -10
  62. package/package.json +1 -1
  63. package/review.md +20 -11
  64. package/rules.md +23 -19
  65. package/settings.schema.json +292 -72
  66. package/skills/factory-address-review/SKILL.md +50 -30
  67. package/skills/factory-build/SKILL.md +76 -23
  68. package/skills/factory-deps/SKILL.md +46 -21
  69. package/skills/factory-design/SKILL.md +18 -9
  70. package/skills/factory-diagnose/SKILL.md +22 -20
  71. package/skills/factory-mutate/SKILL.md +38 -24
  72. package/skills/factory-refine/SKILL.md +55 -31
  73. package/skills/factory-resolve-conflicts/SKILL.md +76 -34
  74. package/skills/factory-trace/SKILL.md +3 -2
  75. package/workflows/factory-build.yml +1 -1
  76. package/workflows/factory-claude-review.yml +1 -1
  77. package/workflows/factory-conflicts.yml +8 -8
  78. package/workflows/factory-deps.yml +1 -1
  79. package/workflows/factory-review.yml +1 -1
  80. package/skills/factory-address-review/patch-coverage.py +0 -68
@@ -0,0 +1,117 @@
1
+ // The repository's default branch, by name, for everything that used to
2
+ // assume `main`. Each source is asked in turn, and the first to answer wins:
3
+ //
4
+ // 1. In a workflow run, the event's payload, which names it.
5
+ // 2. `origin/HEAD`, which a clone sets.
6
+ // 3. The code host. Its answer is written to `origin/HEAD`, so the next
7
+ // run asks nobody.
8
+ //
9
+ // A checkout with no `origin` remote has nobody to ask, and takes git's own
10
+ // default: `init.defaultBranch`, or `main`. With a remote and no answer,
11
+ // nothing is assumed: the caller stops with CANNOT_TELL.
12
+ //
13
+ // factory default-branch # prints the name, or exits 1 with the fix
14
+ import { spawnSync } from "node:child_process";
15
+ import { readFileSync } from "node:fs";
16
+ /** Git, run in `cwd`, with its errors dropped. */
17
+ export const gitIn = (cwd) => (args) => {
18
+ const r = spawnSync("git", args, {
19
+ cwd,
20
+ encoding: "utf8",
21
+ stdio: ["ignore", "pipe", "ignore"],
22
+ });
23
+ return { ok: r.status === 0, out: r.stdout ?? "" };
24
+ };
25
+ export const CANNOT_TELL = "Could not tell the default branch. Run: git remote set-head origin --auto";
26
+ /** Thrown where a command cannot go on without the default branch. */
27
+ export class NoDefaultBranch extends Error {
28
+ constructor() {
29
+ super(CANNOT_TELL);
30
+ }
31
+ }
32
+ /** The default branch a workflow run's event names, or null outside a run
33
+ * and for an event that names none. */
34
+ function fromEvent(d) {
35
+ const path = d.env.GITHUB_EVENT_PATH;
36
+ if (!path)
37
+ return null;
38
+ try {
39
+ const event = JSON.parse(d.readFile(path));
40
+ const name = event.repository?.default_branch;
41
+ return typeof name === "string" && name ? name : null;
42
+ }
43
+ catch {
44
+ return null;
45
+ }
46
+ }
47
+ /** The default branch's name, or null when no source the caller allows
48
+ * answers. */
49
+ export async function defaultBranch(d, sources = "all") {
50
+ if (sources === "all") {
51
+ const named = fromEvent(d);
52
+ if (named)
53
+ return named;
54
+ }
55
+ const head = d.git(["symbolic-ref", "--short", "refs/remotes/origin/HEAD"]);
56
+ const pointed = head.out.trim().replace(/^origin\//, "");
57
+ if (head.ok && pointed)
58
+ return pointed;
59
+ if (sources === "origin-head")
60
+ return null;
61
+ if (!d.git(["remote", "get-url", "origin"]).ok) {
62
+ const own = d.git(["config", "init.defaultBranch"]);
63
+ return (own.ok && own.out.trim()) || "main";
64
+ }
65
+ let name;
66
+ try {
67
+ name = (await d.host()).trim();
68
+ }
69
+ catch {
70
+ return null;
71
+ }
72
+ if (!name)
73
+ return null;
74
+ // Remembered, so the next run asks nobody. It can fail in a shallow or
75
+ // single-branch checkout, where the host is asked again next time.
76
+ d.git(["remote", "set-head", "origin", name]);
77
+ return name;
78
+ }
79
+ /** The default branch's name, for a command that cannot go on without it. */
80
+ export async function needDefaultBranch(d, sources = "all") {
81
+ const name = await defaultBranch(d, sources);
82
+ if (name === null)
83
+ throw new NoDefaultBranch();
84
+ return name;
85
+ }
86
+ /** The sources of the checkout at `root`. The code host is the one the
87
+ * checkout's settings name, and is loaded only when it is asked, so a
88
+ * caller that runs before every command stays quick. */
89
+ export const branchDeps = (root, env = process.env) => ({
90
+ env,
91
+ readFile: (path) => readFileSync(path, "utf8"),
92
+ git: gitIn(root),
93
+ host: async () => {
94
+ const { defaultDeps, loadSettings, reachOf } = await import("../config.mjs");
95
+ const { openCodeHost } = await import("../code-host/index.mjs");
96
+ const { repository, codeHost } = await reachOf(env, () => loadSettings(defaultDeps(root)));
97
+ return openCodeHost(repository, codeHost).defaultBranch();
98
+ },
99
+ });
100
+ export async function main(argv, d, out, err) {
101
+ if (argv.length > 0) {
102
+ err("Usage: factory default-branch");
103
+ return 2;
104
+ }
105
+ const name = await defaultBranch(d);
106
+ if (name === null) {
107
+ err(CANNOT_TELL);
108
+ return 1;
109
+ }
110
+ out(name);
111
+ return 0;
112
+ }
113
+ /** `factory default-branch`. */
114
+ export async function run(argv) {
115
+ const { repoRoot } = await import("../config.mjs");
116
+ return main(argv, branchDeps(repoRoot()), (line) => console.log(line), (line) => console.error(line));
117
+ }
@@ -0,0 +1,7 @@
1
+ /** Each part a build needs that the ticket's body lacks, as the line
2
+ * `factory ticket refined` prints for it; none when the ticket is sound.
3
+ * The follow-ups issue is sound whatever its body holds. A ticket without
4
+ * the `spec` label needs its decisions and at least one acceptance
5
+ * criterion. One with it needs its decisions, a spec with a capability
6
+ * and a numbered line, and the builder's design and tasks. */
7
+ export declare function missingParts(body: string, labels: string[]): string[];
@@ -0,0 +1,76 @@
1
+ // Whether a refined ticket's body is one a build can read: the check
2
+ // `factory ticket refined` makes before it posts the marker, for the
3
+ // factory's own refiner as for a plugin's. It reads headings only, never
4
+ // what a section says.
5
+ const SPEC_LABEL = "spec";
6
+ const FOLLOW_UP_LABEL = "follow-up";
7
+ /** The body's lines outside its fenced code blocks, so a sample body in a
8
+ * code block is not read as the ticket's own. */
9
+ function proseLines(body) {
10
+ const out = [];
11
+ let fence = null;
12
+ for (const line of body.split(/\r?\n/)) {
13
+ const mark = /^\s*(```+|~~~+)/.exec(line)?.[1];
14
+ if (fence === null && mark)
15
+ fence = mark[0];
16
+ else if (fence !== null && mark?.[0] === fence)
17
+ fence = null;
18
+ else if (fence === null)
19
+ out.push(line.trimEnd());
20
+ }
21
+ return out;
22
+ }
23
+ /** The lines under the heading `heading`, or null when the body has no such
24
+ * heading. They end at the next heading of its level or above, or at the
25
+ * body's end when `toEnd` is set. */
26
+ function under(lines, heading, toEnd = false) {
27
+ const at = lines.indexOf(heading);
28
+ if (at === -1)
29
+ return null;
30
+ const rest = lines.slice(at + 1);
31
+ if (toEnd)
32
+ return rest;
33
+ const end = rest.findIndex((line) => /^##? /.test(line));
34
+ return end === -1 ? rest : rest.slice(0, end);
35
+ }
36
+ /** Each part a build needs that the ticket's body lacks, as the line
37
+ * `factory ticket refined` prints for it; none when the ticket is sound.
38
+ * The follow-ups issue is sound whatever its body holds. A ticket without
39
+ * the `spec` label needs its decisions and at least one acceptance
40
+ * criterion. One with it needs its decisions, a spec with a capability
41
+ * and a numbered line, and the builder's design and tasks. */
42
+ export function missingParts(body, labels) {
43
+ if (labels.includes(FOLLOW_UP_LABEL))
44
+ return [];
45
+ const lines = proseLines(body);
46
+ const missing = [];
47
+ const need = (found, part) => {
48
+ if (!found)
49
+ missing.push(`missing: ${part}`);
50
+ };
51
+ need(lines.includes("## Decisions"), "## Decisions");
52
+ if (!labels.includes(SPEC_LABEL)) {
53
+ const criteria = under(lines, "## Acceptance criteria");
54
+ if (criteria === null)
55
+ need(false, "## Acceptance criteria");
56
+ else
57
+ need(criteria.some((line) => /^\s*([-*+]|\d+[.)])\s+\S/.test(line)), "a list item under ## Acceptance criteria");
58
+ return missing;
59
+ }
60
+ const spec = under(lines, "## Spec");
61
+ if (spec === null)
62
+ need(false, "## Spec");
63
+ else {
64
+ need(spec.some((line) => /^### \S.* \((new|modified)\)$/.test(line)), "a ### NAME (new) or ### NAME (modified) heading under ## Spec");
65
+ need(spec.some((line) => /^\d+\.\s+\S/.test(line)), "a numbered line under ## Spec");
66
+ }
67
+ // The tasks are grouped under level-two headings, as OpenSpec's tasks.md
68
+ // has them, so this section runs to the body's end.
69
+ const builder = under(lines, "## For the builder", true);
70
+ if (builder === null)
71
+ need(false, "## For the builder");
72
+ else
73
+ for (const heading of ["### Design", "### Tasks"])
74
+ need(builder.includes(heading), `${heading} under ## For the builder`);
75
+ return missing;
76
+ }
@@ -65,7 +65,7 @@ export type Marked = IssueComment & {
65
65
  /** The markers in one comment: each on a line of its own, outside a fenced
66
66
  * code block, in a comment that also carries the agent mark. */
67
67
  export declare function parseMarkers(body: string): Marker[];
68
- /** The account the CI review's summary is posted from. */
68
+ /** The account the pull request review's summary is posted from. */
69
69
  export declare const CI_BOT = "github-actions[bot]";
70
70
  /** Whether a body already carries a cost marker, read as `parseCosts` reads
71
71
  * one: on a line of its own, outside a fenced code block. A marker quoted in
@@ -73,7 +73,7 @@ export declare const CI_BOT = "github-actions[bot]";
73
73
  export declare function hasCostMarker(body: string): boolean;
74
74
  /** The cost markers in one comment, read as markers are: each on a line of
75
75
  * its own, outside a fenced code block. Only the owner's account, which the
76
- * agents post as, and the CI review's bot count; the owner's comments count
76
+ * agents post as, and the pull request review's bot count; the owner's comments count
77
77
  * only with the agent mark. */
78
78
  export declare function parseCosts(comment: IssueComment, owner: string): number[];
79
79
  /** Whether a pull request's body says it builds this issue, as "Closes #N"
@@ -101,10 +101,10 @@ export function parseMarkers(body) {
101
101
  }
102
102
  return found;
103
103
  }
104
- // Cost markers, which say what a session or a CI review spent at API list
104
+ // Cost markers, which say what a session or a pull request review spent at API list
105
105
  // prices: `<!-- cost: 3.41 session=ID -->` from a session,
106
- // `<!-- cost: 0.92 -->` from the CI review's summary.
107
- /** The account the CI review's summary is posted from. */
106
+ // `<!-- cost: 0.92 -->` from the pull request review's summary.
107
+ /** The account the pull request review's summary is posted from. */
108
108
  export const CI_BOT = "github-actions[bot]";
109
109
  const COST_LINE = /^<!-- cost: (\d+(?:\.\d+)?)(?: session=\S+)? -->$/;
110
110
  /** Whether a body already carries a cost marker, read as `parseCosts` reads
@@ -115,7 +115,7 @@ export function hasCostMarker(body) {
115
115
  }
116
116
  /** The cost markers in one comment, read as markers are: each on a line of
117
117
  * its own, outside a fenced code block. Only the owner's account, which the
118
- * agents post as, and the CI review's bot count; the owner's comments count
118
+ * agents post as, and the pull request review's bot count; the owner's comments count
119
119
  * only with the agent mark. */
120
120
  export function parseCosts(comment, owner) {
121
121
  const fromAgent = comment.author === owner && comment.body.includes(AGENT_MARK);
package/dist/parts.d.mts CHANGED
@@ -8,7 +8,7 @@ export declare const PART_TEXT: Record<Part, {
8
8
  gives: string;
9
9
  }>;
10
10
  /** The workflow that runs the automated review, which `factory sync`
11
- * writes while the settings have `ci-review`. */
11
+ * writes while the settings have `pr-review`. */
12
12
  export declare const REVIEW_WORKFLOW = ".github/workflows/factory-claude-review.yml";
13
13
  export declare const AGENT_TOKEN = "CLAUDE_CODE_OAUTH_TOKEN";
14
14
  export declare const AGENT_KEY = "ANTHROPIC_API_KEY";
package/dist/parts.mjs CHANGED
@@ -34,7 +34,7 @@ export const PART_TEXT = {
34
34
  },
35
35
  };
36
36
  /** The workflow that runs the automated review, which `factory sync`
37
- * writes while the settings have `ci-review`. */
37
+ * writes while the settings have `pr-review`. */
38
38
  export const REVIEW_WORKFLOW = ".github/workflows/factory-claude-review.yml";
39
39
  export const AGENT_TOKEN = "CLAUDE_CODE_OAUTH_TOKEN";
40
40
  export const AGENT_KEY = "ANTHROPIC_API_KEY";
@@ -48,7 +48,7 @@ export const SIGNING_KEY = "FACTORY_SIGNING_KEY";
48
48
  export function partsOn(s, secrets, cloudNeeds) {
49
49
  const has = (names) => names.some((n) => secrets.includes(n));
50
50
  const on = new Set();
51
- if (s?.ciReview)
51
+ if (s?.prReview)
52
52
  on.add("review");
53
53
  if (s?.tickets.board != null)
54
54
  on.add("board");
@@ -0,0 +1,13 @@
1
+ /** One file's uncovered lines: never run, and run with a branch not taken. */
2
+ export type FileCoverage = {
3
+ miss: Set<number>;
4
+ part: Set<number>;
5
+ };
6
+ /** An lcov report's uncovered lines, by each file's path from `cwd`. */
7
+ export declare function parseLcov(text: string, cwd: string): Map<string, FileCoverage>;
8
+ /** The line numbers a `git diff -U0` adds or changes, by file. */
9
+ export declare function changedLines(diff: string): Map<string, Set<number>>;
10
+ /** The lines to print: a header for each file with a changed line the
11
+ * report shows uncovered, then each such line. `source` gives a file's
12
+ * text, or null when it cannot be read. */
13
+ export declare function uncovered(coverage: Map<string, FileCoverage>, changed: Map<string, Set<number>>, source: (path: string) => string | null): string[];
@@ -0,0 +1,73 @@
1
+ // What `factory pr uncovered` prints: the lines a branch added or changed
2
+ // that its coverage report shows no test ran, or a branch never taken.
3
+ import { relative, resolve } from "node:path";
4
+ /** An lcov report's uncovered lines, by each file's path from `cwd`. */
5
+ export function parseLcov(text, cwd) {
6
+ const files = new Map();
7
+ let current = null;
8
+ for (const raw of text.split("\n")) {
9
+ const line = raw.trim();
10
+ if (line.startsWith("SF:")) {
11
+ current = { miss: new Set(), part: new Set() };
12
+ files.set(relative(cwd, resolve(cwd, line.slice(3))), current);
13
+ }
14
+ else if (current && line.startsWith("DA:")) {
15
+ const [number, hits] = line.slice(3).split(",");
16
+ if (hits === "0")
17
+ current.miss.add(Number(number));
18
+ }
19
+ else if (current && line.startsWith("BRDA:")) {
20
+ const [number, , , taken] = line.slice(5).split(",");
21
+ if (taken === "0" || taken === "-")
22
+ current.part.add(Number(number));
23
+ }
24
+ }
25
+ return files;
26
+ }
27
+ /** The line numbers a `git diff -U0` adds or changes, by file. */
28
+ export function changedLines(diff) {
29
+ const files = new Map();
30
+ let current = null;
31
+ for (const line of diff.split("\n")) {
32
+ if (line.startsWith("+++ ")) {
33
+ // A deleted file's new side is /dev/null, and adds nothing.
34
+ current = line.startsWith("+++ b/") ? new Set() : null;
35
+ if (current)
36
+ files.set(line.slice(6), current);
37
+ continue;
38
+ }
39
+ const hunk = /^@@ .* \+(\d+)(?:,(\d+))? @@/.exec(line);
40
+ if (!hunk || !current)
41
+ continue;
42
+ const start = Number(hunk[1]);
43
+ const count = hunk[2] === undefined ? 1 : Number(hunk[2]);
44
+ for (let n = start; n < start + count; n++)
45
+ current.add(n);
46
+ }
47
+ return files;
48
+ }
49
+ /** The lines to print: a header for each file with a changed line the
50
+ * report shows uncovered, then each such line. `source` gives a file's
51
+ * text, or null when it cannot be read. */
52
+ export function uncovered(coverage, changed, source) {
53
+ const out = [];
54
+ for (const path of [...changed.keys()].sort()) {
55
+ const report = coverage.get(path);
56
+ if (!report)
57
+ continue;
58
+ const lines = changed.get(path);
59
+ const found = [...new Set([...report.miss, ...report.part])]
60
+ .filter((n) => lines.has(n))
61
+ .sort((a, b) => a - b);
62
+ if (!found.length)
63
+ continue;
64
+ const text = source(path)?.split(/\r?\n/);
65
+ out.push(`=== ${path}`);
66
+ for (const n of found) {
67
+ const kind = report.miss.has(n) ? "MISS" : "PART";
68
+ const shown = text?.[n - 1]?.trim().slice(0, 110);
69
+ out.push(shown === undefined ? `${kind} ${n}:` : `${kind} ${n}: ${shown}`);
70
+ }
71
+ }
72
+ return out;
73
+ }
@@ -30,8 +30,9 @@ export type WatchEvent = {
30
30
  };
31
31
  export declare function toChecks(runs: CheckRun[], statuses: CommitStatus[]): Check[];
32
32
  /** What needs the session now and has not been reported. A closed pull
33
- * request ends the watch, so nothing else about it is news. */
34
- export declare function newEvents(snapshot: Snapshot, seen: Set<string>): WatchEvent[];
33
+ * request ends the watch, so nothing else about it is news. `branch` is the
34
+ * default branch, which a conflict's line names. */
35
+ export declare function newEvents(snapshot: Snapshot, seen: Set<string>, branch: string): WatchEvent[];
35
36
  export declare function withWatchMark(body: string, now: Date): string;
36
37
  export declare function withoutWatchMark(body: string): string;
37
38
  /** A mark goes stale after an hour, so a session that has gone stops holding
package/dist/pr-watch.mjs CHANGED
@@ -13,7 +13,8 @@ import { execFileSync } from "node:child_process";
13
13
  import { createHash } from "node:crypto";
14
14
  import { existsSync, readFileSync, rmSync, writeFileSync } from "node:fs";
15
15
  import { setTimeout as sleep } from "node:timers/promises";
16
- import { reachOf } from "./config.mjs";
16
+ import { reachOf, repoRoot } from "./config.mjs";
17
+ import { branchDeps, needDefaultBranch, NoDefaultBranch, } from "./lib/default-branch.mjs";
17
18
  import { openCodeHost, } from "./code-host/index.mjs";
18
19
  const FAILED_CONCLUSIONS = new Set([
19
20
  "failure",
@@ -63,8 +64,9 @@ function reviewIsOver(snapshot) {
63
64
  return run?.state === "failed";
64
65
  }
65
66
  /** What needs the session now and has not been reported. A closed pull
66
- * request ends the watch, so nothing else about it is news. */
67
- export function newEvents(snapshot, seen) {
67
+ * request ends the watch, so nothing else about it is news. `branch` is the
68
+ * default branch, which a conflict's line names. */
69
+ export function newEvents(snapshot, seen, branch) {
68
70
  if (snapshot.merged)
69
71
  return [{ key: "merged", line: "merged" }];
70
72
  if (snapshot.state !== "open")
@@ -74,7 +76,7 @@ export function newEvents(snapshot, seen) {
74
76
  if (snapshot.mergeableState === "dirty") {
75
77
  found.push({
76
78
  key: `conflict:${sha}`,
77
- line: `conflict with main at ${sha}`,
79
+ line: `conflict with ${branch} at ${sha}`,
78
80
  });
79
81
  }
80
82
  for (const check of snapshot.checks) {
@@ -198,13 +200,28 @@ async function main(argv) {
198
200
  await p.setBody(n, withoutWatchMark(body));
199
201
  return;
200
202
  }
203
+ // The code host is already open, so it is the one asked where the
204
+ // checkout does not say.
205
+ let branch;
206
+ try {
207
+ branch = await needDefaultBranch({
208
+ ...branchDeps(repoRoot()),
209
+ host: () => p.defaultBranch(),
210
+ });
211
+ }
212
+ catch (error) {
213
+ if (!(error instanceof NoDefaultBranch))
214
+ throw error;
215
+ console.error(error.message);
216
+ process.exit(1);
217
+ }
201
218
  const seenFile = execFileSync("git", ["rev-parse", "--git-path", `watch-pr-${pr}.json`], { encoding: "utf8" }).trim();
202
219
  const seen = new Set(existsSync(seenFile) ? JSON.parse(readFileSync(seenFile, "utf8")) : []);
203
220
  let failures = 0;
204
221
  for (;;) {
205
222
  try {
206
223
  const { snapshot, body } = await readSnapshot(p, n);
207
- const events = newEvents(snapshot, seen);
224
+ const events = newEvents(snapshot, seen, branch);
208
225
  if (snapshot.state !== "open") {
209
226
  rmSync(seenFile, { force: true });
210
227
  console.log(events.map((event) => event.line).join("\n"));
package/dist/pr.mjs CHANGED
@@ -25,6 +25,7 @@ import { readFileSync } from "node:fs";
25
25
  import { setTimeout as sleep } from "node:timers/promises";
26
26
  import { reachOf } from "./config.mjs";
27
27
  import { AGENT_MARK } from "./lib/work-status.mjs";
28
+ import { changedLines, parseLcov, uncovered } from "./patch-coverage.mjs";
28
29
  import { toChecks } from "./pr-watch.mjs";
29
30
  import { openCodeHost, } from "./code-host/index.mjs";
30
31
  import { openRunner } from "./runner/index.mjs";
@@ -209,7 +210,7 @@ const FIELDS = {
209
210
  };
210
211
  /** How many lines of a failed job's log `failed` prints, from its end. */
211
212
  const LOG_TAIL = 200;
212
- 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 | 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 | failed N | review-again N`;
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 | 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`;
213
214
  function option(args, name) {
214
215
  const at = args.indexOf(name);
215
216
  if (at === -1)
@@ -504,6 +505,31 @@ export async function main(argv, d) {
504
505
  }, null, 2));
505
506
  return 0;
506
507
  }
508
+ case "uncovered": {
509
+ if (rest.length > 2)
510
+ throw new Error(USAGE);
511
+ const [base, lcov = "coverage/lcov.info"] = rest;
512
+ let report;
513
+ try {
514
+ report = d.readFile(lcov);
515
+ }
516
+ catch {
517
+ d.out(`No coverage report at ${lcov}. Run the project's coverage command first.`);
518
+ return 1;
519
+ }
520
+ const from = base ?? `origin/${await p.defaultBranch()}`;
521
+ const diff = d.git(["diff", "-U0", `${from}...HEAD`]);
522
+ const source = (path) => {
523
+ try {
524
+ return d.readFile(path);
525
+ }
526
+ catch {
527
+ return null;
528
+ }
529
+ };
530
+ uncovered(parseLcov(report, process.cwd()), changedLines(diff), source).forEach((line) => d.out(line));
531
+ return 0;
532
+ }
507
533
  case "unverified": {
508
534
  const [pr] = numbers;
509
535
  if (!pr)
@@ -565,7 +591,13 @@ export async function run(argv) {
565
591
  sleep,
566
592
  out: (line) => console.log(line),
567
593
  readFile: (path) => readFileSync(path, "utf8"),
568
- git: (args) => execFileSync("git", args, { encoding: "utf8" }),
594
+ // A branch's whole diff, which `uncovered` reads, can pass Node's 1 MB.
595
+ // Git's own error is in the thrown message, so it is not printed twice.
596
+ git: (args) => execFileSync("git", args, {
597
+ encoding: "utf8",
598
+ maxBuffer: 256 << 20,
599
+ stdio: ["ignore", "pipe", "pipe"],
600
+ }),
569
601
  env: process.env,
570
602
  });
571
603
  }
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- // Adds what the CI review cost to its summary comment, after the review
2
+ // Adds what the pull request review cost to its summary comment, after the review
3
3
  // step of .github/workflows/factory-claude-review.yml:
4
4
  //
5
5
  // Review cost: $0.03 of the subscription ($0.92 at API list prices).
@@ -1,6 +1,6 @@
1
- // Prints the tools the CI review may use, as the one comma-separated value
1
+ // Prints the tools the pull request review may use, as the one comma-separated value
2
2
  // the review step passes to `--allowedTools`: the factory's own, then a
3
- // `Bash(COMMAND:*)` for each of the settings' `ci-review.commands`.
3
+ // `Bash(COMMAND:*)` for each of the settings' `pr-review.commands`.
4
4
  //
5
5
  // FACTORY_SETTINGS=base-settings.yaml npx --no-install factory review tools
6
6
  //
@@ -34,7 +34,7 @@ export function allowedTools(commands) {
34
34
  export async function run() {
35
35
  try {
36
36
  const s = await loadSettings();
37
- console.log(allowedTools(s.ciReview?.commands ?? []));
37
+ console.log(allowedTools(s.prReview?.commands ?? []));
38
38
  return 0;
39
39
  }
40
40
  catch (e) {
@@ -1,20 +1,30 @@
1
- type Git = (args: string[]) => {
2
- ok: boolean;
3
- out: string;
4
- };
5
- export declare const gitIn: (cwd: string) => Git;
6
- /** Each local branch but main with work origin/main lacks, as
7
- * "NAME (N commits not on origin/main)". Pull requests are squash-merged, so
8
- * a merged branch still has commits main lacks: it counts as merged when
9
- * merging it into main would change nothing. */
10
- export declare function unmergedBranches(git: Git): string[];
11
- /** What the hook prints before the tickets' state. */
12
- export declare function repositoryState(git: Git): string[];
1
+ import { gitIn, type Deps as BranchDeps, type Git } from "./lib/default-branch.mts";
2
+ export { gitIn };
3
+ /** Each local branch but the default one, `branch`, with work
4
+ * origin/BRANCH lacks, as "NAME (N commits not on origin/BRANCH)". Pull
5
+ * requests are squash-merged, so a merged branch still has commits the
6
+ * default branch lacks: it counts as merged when merging it into the
7
+ * default branch would change nothing. */
8
+ export declare function unmergedBranches(git: Git, branch: string): string[];
9
+ /** What the hook prints before the tickets' state. `branch` is the default
10
+ * branch, or null when it could not be told: then no branch is compared
11
+ * with anything, and the line that names the fix stands in for the list. */
12
+ export declare function repositoryState(git: Git, branch: string | null): string[];
13
13
  /** A line telling the person to run `npm ci` when `node_modules` is older
14
14
  * than `package-lock.json`, or null when it is current or there is no
15
15
  * lockfile. Without it, a command installed since the lockfile last changed,
16
16
  * such as `factory` once it became a workspace package, is missing and the
17
17
  * shell's "Permission denied" says nothing of why. */
18
18
  export declare function installBehind(dir: string): string | null;
19
+ export type Deps = {
20
+ /** The checkout the session starts in. */
21
+ dir: string;
22
+ /** The sources of the default branch's name. */
23
+ branch: BranchDeps;
24
+ out: (text: string) => void;
25
+ /** Prints each ticket's state, and gives the hook's exit. */
26
+ tickets: () => Promise<number>;
27
+ };
28
+ export declare function main(d: Deps): Promise<number>;
29
+ /** `factory session-start`. */
19
30
  export declare function run(): Promise<number>;
20
- export {};