@davidbyoung/software-factory 0.1.3 → 0.1.4

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 (72) 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 +29 -2
  7. package/dist/commands.d.mts +16 -0
  8. package/dist/commands.mjs +129 -0
  9. package/dist/config.d.mts +61 -13
  10. package/dist/config.mjs +267 -65
  11. package/dist/deps.d.mts +7 -4
  12. package/dist/deps.mjs +20 -9
  13. package/dist/doctor.d.mts +3 -2
  14. package/dist/doctor.mjs +19 -4
  15. package/dist/explain.d.mts +4 -2
  16. package/dist/explain.mjs +66 -19
  17. package/dist/guard-commit.d.mts +7 -2
  18. package/dist/guard-commit.mjs +58 -21
  19. package/dist/init.d.mts +4 -2
  20. package/dist/init.mjs +15 -5
  21. package/dist/lib/default-branch.d.mts +35 -0
  22. package/dist/lib/default-branch.mjs +117 -0
  23. package/dist/lib/refined-check.d.mts +7 -0
  24. package/dist/lib/refined-check.mjs +76 -0
  25. package/dist/patch-coverage.d.mts +13 -0
  26. package/dist/patch-coverage.mjs +73 -0
  27. package/dist/pr-watch.d.mts +3 -2
  28. package/dist/pr-watch.mjs +22 -5
  29. package/dist/pr.mjs +34 -2
  30. package/dist/session-start.d.mts +23 -13
  31. package/dist/session-start.mjs +56 -44
  32. package/dist/site/servers.d.mts +6 -2
  33. package/dist/site/servers.mjs +14 -9
  34. package/dist/site.mjs +2 -2
  35. package/dist/sync.d.mts +8 -2
  36. package/dist/sync.mjs +40 -6
  37. package/dist/ticket.mjs +19 -1
  38. package/docs/builds.md +8 -8
  39. package/docs/cli.md +82 -45
  40. package/docs/configuration.md +455 -139
  41. package/docs/design.md +17 -4
  42. package/docs/developing.md +37 -6
  43. package/docs/existing-repo.md +8 -6
  44. package/docs/github/by-hand.md +23 -10
  45. package/docs/github/reference.md +19 -14
  46. package/docs/github/setup.md +12 -9
  47. package/docs/glossary.md +13 -3
  48. package/docs/limitations.md +27 -2
  49. package/docs/plugins.md +302 -48
  50. package/docs/quick-start.md +36 -8
  51. package/docs/removing.md +1 -1
  52. package/docs/skills.md +101 -52
  53. package/docs/updating.md +148 -3
  54. package/docs/workflow.md +13 -10
  55. package/package.json +1 -1
  56. package/review.md +20 -11
  57. package/rules.md +22 -18
  58. package/settings.schema.json +289 -69
  59. package/skills/factory-address-review/SKILL.md +50 -30
  60. package/skills/factory-build/SKILL.md +75 -22
  61. package/skills/factory-deps/SKILL.md +46 -21
  62. package/skills/factory-design/SKILL.md +17 -8
  63. package/skills/factory-diagnose/SKILL.md +22 -20
  64. package/skills/factory-mutate/SKILL.md +38 -24
  65. package/skills/factory-refine/SKILL.md +55 -31
  66. package/skills/factory-resolve-conflicts/SKILL.md +76 -34
  67. package/skills/factory-trace/SKILL.md +3 -2
  68. package/workflows/factory-build.yml +1 -1
  69. package/workflows/factory-conflicts.yml +8 -8
  70. package/workflows/factory-deps.yml +1 -1
  71. package/workflows/factory-review.yml +1 -1
  72. package/skills/factory-address-review/patch-coverage.py +0 -68
@@ -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 plug-in'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
+ }
@@ -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,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 {};
@@ -1,45 +1,43 @@
1
1
  // The SessionStart hook, run as `factory session-start`. Its output opens
2
2
  // the session's context, so work left on another branch is visible before
3
3
  // anything new starts: the checkout's state, the local branches with work
4
- // not on origin/main, then each ticket's state.
5
- import { spawnSync } from "node:child_process";
4
+ // not on the default branch, then each ticket's state.
6
5
  import { readFileSync } from "node:fs";
7
6
  import { join } from "node:path";
8
- export const gitIn = (cwd) => (args) => {
9
- const r = spawnSync("git", args, {
10
- cwd,
11
- encoding: "utf8",
12
- stdio: ["ignore", "pipe", "ignore"],
13
- });
14
- return { ok: r.status === 0, out: r.stdout ?? "" };
15
- };
16
- /** Each local branch but main with work origin/main lacks, as
17
- * "NAME (N commits not on origin/main)". Pull requests are squash-merged, so
18
- * a merged branch still has commits main lacks: it counts as merged when
19
- * merging it into main would change nothing. */
20
- export function unmergedBranches(git) {
21
- const mainTree = git(["rev-parse", "origin/main^{tree}"]).out.trim();
7
+ import { branchDeps, CANNOT_TELL, defaultBranch, gitIn, } from "./lib/default-branch.mjs";
8
+ export { gitIn };
9
+ /** Each local branch but the default one, `branch`, with work
10
+ * origin/BRANCH lacks, as "NAME (N commits not on origin/BRANCH)". Pull
11
+ * requests are squash-merged, so a merged branch still has commits the
12
+ * default branch lacks: it counts as merged when merging it into the
13
+ * default branch would change nothing. */
14
+ export function unmergedBranches(git, branch) {
15
+ const base = `origin/${branch}`;
16
+ const baseTree = git(["rev-parse", `${base}^{tree}`]).out.trim();
22
17
  const branches = git([
23
18
  "for-each-ref",
24
19
  "--format=%(refname:short)",
25
20
  "refs/heads",
26
21
  ])
27
22
  .out.split("\n")
28
- .filter((b) => b && b !== "main");
23
+ .filter((b) => b && b !== branch);
29
24
  const found = [];
30
25
  for (const b of branches) {
31
- const merged = git(["merge-tree", "--write-tree", "origin/main", b]);
32
- if (merged.ok && merged.out.split("\n")[0] === mainTree)
26
+ const merged = git(["merge-tree", "--write-tree", base, b]);
27
+ if (merged.ok && merged.out.split("\n")[0] === baseTree)
33
28
  continue;
34
- const count = Number(git(["rev-list", "--count", `origin/main..${b}`]).out.trim() || 0);
29
+ const count = Number(git(["rev-list", "--count", `${base}..${b}`]).out.trim() || 0);
35
30
  if (count > 0)
36
- found.push(`${b} (${count} commits not on origin/main)`);
31
+ found.push(`${b} (${count} commits not on ${base})`);
37
32
  }
38
33
  return found;
39
34
  }
40
- /** What the hook prints before the tickets' state. */
41
- export function repositoryState(git) {
42
- git(["fetch", "-q", "origin", "main"]);
35
+ /** What the hook prints before the tickets' state. `branch` is the default
36
+ * branch, or null when it could not be told: then no branch is compared
37
+ * with anything, and the line that names the fix stands in for the list. */
38
+ export function repositoryState(git, branch) {
39
+ if (branch !== null)
40
+ git(["fetch", "-q", "origin", branch]);
43
41
  const lines = [
44
42
  "## Repository state at session start",
45
43
  "",
@@ -48,9 +46,11 @@ export function repositoryState(git) {
48
46
  "```",
49
47
  "",
50
48
  ];
51
- const unmerged = unmergedBranches(git);
49
+ if (branch === null)
50
+ return [...lines, CANNOT_TELL];
51
+ const unmerged = unmergedBranches(git, branch);
52
52
  if (unmerged.length) {
53
- lines.push("Local branches with work not on origin/main:", "", ...unmerged.map((b) => `- ${b}`), "", "Mention any of these to the user before starting work on another branch.");
53
+ lines.push(`Local branches with work not on origin/${branch}:`, "", ...unmerged.map((b) => `- ${b}`), "", "Mention any of these to the user before starting work on another branch.");
54
54
  }
55
55
  return lines;
56
56
  }
@@ -86,6 +86,15 @@ export function installBehind(dir) {
86
86
  }
87
87
  return null;
88
88
  }
89
+ export async function main(d) {
90
+ const branch = await defaultBranch(d.branch).catch(() => null);
91
+ d.out(repositoryState(gitIn(d.dir), branch).join("\n"));
92
+ const behind = installBehind(d.dir);
93
+ if (behind)
94
+ d.out(`\n${behind}\n`);
95
+ return d.tickets();
96
+ }
97
+ /** `factory session-start`. */
89
98
  export async function run() {
90
99
  const dir = process.env.CLAUDE_PROJECT_DIR || process.cwd();
91
100
  try {
@@ -94,22 +103,25 @@ export async function run() {
94
103
  catch {
95
104
  return 0;
96
105
  }
97
- console.log(repositoryState(gitIn(dir)).join("\n"));
98
- const behind = installBehind(dir);
99
- if (behind)
100
- console.log(`\n${behind}\n`);
101
- // What each ticket's board card says, and who is working on it. The status
102
- // command enforces its own time limit, since a hook the harness kills
103
- // prints nothing.
104
- const error = console.error;
105
- console.error = () => { };
106
- try {
107
- return await (await import("./status.mjs")).run(["--hook"]);
108
- }
109
- catch {
110
- return 0;
111
- }
112
- finally {
113
- console.error = error;
114
- }
106
+ return main({
107
+ dir,
108
+ branch: branchDeps(dir),
109
+ out: (text) => console.log(text),
110
+ // What each ticket's board card says, and who is working on it. The
111
+ // status command enforces its own time limit, since a hook the harness
112
+ // kills prints nothing.
113
+ tickets: async () => {
114
+ const error = console.error;
115
+ console.error = () => { };
116
+ try {
117
+ return await (await import("./status.mjs")).run(["--hook"]);
118
+ }
119
+ catch {
120
+ return 0;
121
+ }
122
+ finally {
123
+ console.error = error;
124
+ }
125
+ },
126
+ });
115
127
  }
@@ -1,3 +1,4 @@
1
+ import { type Deps as BranchDeps } from "../lib/default-branch.mts";
1
2
  export declare class SiteError extends Error {
2
3
  }
3
4
  export type Running = {
@@ -25,8 +26,11 @@ export declare function startSite(opts: {
25
26
  * that stops the others. */
26
27
  export declare function startSites(sites: Parameters<typeof startSite>[0][], pids: number[]): Promise<Running[]>;
27
28
  export declare function stopProcess(pid: number): void;
28
- /** Whether the repository is a git checkout with this ref. */
29
- export declare const defaultBranch: (root: string) => string;
29
+ /** The ref a comparison's base is started from when none is given: the
30
+ * default branch, as `origin` has it, or the checkout's own branch of that
31
+ * name where there is no such ref, as in a checkout with no remote. It
32
+ * fails, naming the fix, when the default branch cannot be told. */
33
+ export declare function defaultBase(root: string, d?: BranchDeps): Promise<string>;
30
34
  /** A detached worktree of `ref` in a temporary folder, with its dependencies
31
35
  * installed when it has a lockfile. Returns its path. */
32
36
  export declare function addWorktree(root: string, ref: string): string;
@@ -6,6 +6,7 @@ import { createServer } from "node:net";
6
6
  import { closeSync, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, rmSync, writeFileSync, } from "node:fs";
7
7
  import { tmpdir } from "node:os";
8
8
  import { join } from "node:path";
9
+ import { branchDeps, CANNOT_TELL, defaultBranch, } from "../lib/default-branch.mjs";
9
10
  export class SiteError extends Error {
10
11
  }
11
12
  /** A port nothing is listening on. */
@@ -80,15 +81,19 @@ export function stopProcess(pid) {
80
81
  }
81
82
  }
82
83
  }
83
- /** Whether the repository is a git checkout with this ref. */
84
- export const defaultBranch = (root) => {
85
- try {
86
- return execFileSync("git", ["symbolic-ref", "--short", "refs/remotes/origin/HEAD"], { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
87
- }
88
- catch {
89
- return "origin/main";
90
- }
91
- };
84
+ /** The ref a comparison's base is started from when none is given: the
85
+ * default branch, as `origin` has it, or the checkout's own branch of that
86
+ * name where there is no such ref, as in a checkout with no remote. It
87
+ * fails, naming the fix, when the default branch cannot be told. */
88
+ export async function defaultBase(root, d = branchDeps(root)) {
89
+ const name = await defaultBranch(d);
90
+ if (name === null)
91
+ throw new SiteError(CANNOT_TELL);
92
+ const remote = `refs/remotes/origin/${name}`;
93
+ return d.git(["rev-parse", "--verify", "--quiet", remote]).ok
94
+ ? `origin/${name}`
95
+ : name;
96
+ }
92
97
  /** A detached worktree of `ref` in a temporary folder, with its dependencies
93
98
  * installed when it has a lockfile. Returns its path. */
94
99
  export function addWorktree(root, ref) {
package/dist/site.mjs CHANGED
@@ -17,7 +17,7 @@ import { crawl, normalize, sitemapPaths } from "./site/pages.mjs";
17
17
  import { changedWithoutNoise, classify, diff, } from "./site/pixels.mjs";
18
18
  import { encode, launch, measureView, shoot, } from "./site/capture.mjs";
19
19
  import { addToCensus, AXE_TAGS, emptyCensus, formatFinding, newValues, newViolations, sidewaysScroll, } from "./site/measure.mjs";
20
- import { addWorktree, defaultBranch, freePort, keep, removeWorktree, SiteError, startSites, stopKept, stopProcess, } from "./site/servers.mjs";
20
+ import { addWorktree, defaultBase, freePort, keep, removeWorktree, SiteError, startSites, stopKept, stopProcess, } from "./site/servers.mjs";
21
21
  const slug = (p) => p.replace(/^\/|\/$/g, "").replace(/\W+/g, "-") || "home";
22
22
  async function text(url) {
23
23
  try {
@@ -261,7 +261,7 @@ async function compare(argv) {
261
261
  after = given.after;
262
262
  }
263
263
  else {
264
- const base = flag(argv, "--base") ?? defaultBranch(root);
264
+ const base = flag(argv, "--base") ?? (await defaultBase(root));
265
265
  const [pa, pb] = [await freePort(), await freePort()];
266
266
  worktree = addWorktree(root, base);
267
267
  const common = { start: site.start, minutes: site.startMinutes };
package/dist/sync.d.mts CHANGED
@@ -11,6 +11,9 @@ type Has = (path: string) => boolean;
11
11
  /** The scheduled poller's workflow, its one `cron` line set to run every
12
12
  * `minutes`: on the hour for 60, every N minutes past it otherwise. */
13
13
  export declare function withSchedule(text: string, minutes: number, file: string): string;
14
+ /** A workflow with the one `branches:` line of its push trigger naming the
15
+ * default branch and nothing else. */
16
+ export declare function withDefaultBranch(text: string, name: string, file: string): string;
14
17
  /** A session workflow with the minutes its session may run, and its job 10
15
18
  * more, so the steps after the session still run before the job is
16
19
  * stopped. */
@@ -63,14 +66,17 @@ export type Plan = {
63
66
  /** Paths the lock lists that this version no longer writes. */
64
67
  remove: string[];
65
68
  };
66
- /** What a sync of `root` from `pkg` writes and deletes. */
67
- export declare function plan(pkg: string, root: string, s: Settings): Plan;
69
+ /** What a sync of `root` from `pkg` writes and deletes, in a repository
70
+ * whose default branch is `branch`. */
71
+ export declare function plan(pkg: string, root: string, s: Settings, branch: string): Plan;
68
72
  /** The paths whose content a sync would change, in the plan's order. */
69
73
  export declare function differences(root: string, p: Plan): string[];
70
74
  export declare function main(argv: string[], d: {
71
75
  root: string;
72
76
  pkg: string;
73
77
  settings: () => Promise<Settings>;
78
+ /** The repository's default branch, or null when it cannot be told. */
79
+ defaultBranch: () => Promise<string | null>;
74
80
  out: (line: string) => void;
75
81
  err: (line: string) => void;
76
82
  }): Promise<number>;