@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
package/dist/deps.mjs CHANGED
@@ -6,7 +6,8 @@
6
6
  // npx --no-install factory deps --any # exits 0 when one is open, 1 when none, 2 when it could not tell
7
7
  //
8
8
  // A failed read exits 1 with the error, or 2 with `--any`.
9
- import { reachOf } from "./config.mjs";
9
+ import { reachOf, repoRoot } from "./config.mjs";
10
+ import { branchDeps, needDefaultBranch } from "./lib/default-branch.mjs";
10
11
  import { openCodeHost } from "./code-host/index.mjs";
11
12
  const SHEPHERD_MARK = "<!-- factory-deps -->";
12
13
  const PASSED = ["success", "skipped", "neutral"];
@@ -16,8 +17,9 @@ export function isMajor(title) {
16
17
  const match = /from v?(\d+)\S* to v?(\d+)/.exec(title);
17
18
  return match !== null && match[1] !== match[2];
18
19
  }
19
- /** What the skill does with a bump, in the order its steps take them. */
20
- export function nextStep(bump) {
20
+ /** What the skill does with a bump, in the order its steps take them.
21
+ * `branch` is the default branch, which a conflicting bump merges. */
22
+ export function nextStep(bump, branch) {
21
23
  if (bump.mergeableState === "unknown")
22
24
  return "leave: state not computed yet";
23
25
  if (bump.checks.some((c) => c.status !== "completed"))
@@ -26,7 +28,7 @@ export function nextStep(bump) {
26
28
  return "stop: two earlier fixes did not turn CI green";
27
29
  const steps = [];
28
30
  if (bump.mergeableState === "dirty")
29
- steps.push("merge main (step 2)");
31
+ steps.push(`merge ${branch} (step 2)`);
30
32
  if (failing(bump).length > 0)
31
33
  steps.push(`fix ${failing(bump).join(", ")} (step 3)`);
32
34
  if (bump.major)
@@ -66,13 +68,13 @@ export function checksLine(bump) {
66
68
  ].filter(Boolean);
67
69
  return `checks: ${parts.join("; ")}`;
68
70
  }
69
- export function formatBump(bump) {
71
+ export function formatBump(bump, branch) {
70
72
  return [
71
73
  `#${bump.number} ${bump.title}`,
72
74
  ` ${bump.major ? "major" : "minor or patch"}; head ${bump.head} at ${bump.sha.slice(0, 7)}; mergeable ${bump.mergeableState}; auto-merge ${bump.autoMerge ? "on" : "off"}`,
73
75
  ` ${checksLine(bump)}`,
74
76
  ` earlier shepherd comments: ${bump.shepherdComments}`,
75
- ` next: ${nextStep(bump)}`,
77
+ ` next: ${nextStep(bump, branch)}`,
76
78
  ];
77
79
  }
78
80
  async function readBump(p, number) {
@@ -94,7 +96,9 @@ async function readBump(p, number) {
94
96
  .length,
95
97
  };
96
98
  }
97
- export async function main(p, out, argv = []) {
99
+ /** `defaultBranch` gives the default branch's name, and rejects when it
100
+ * cannot be told. It is asked only when a pull request is listed. */
101
+ export async function main(p, out, argv, defaultBranch) {
98
102
  try {
99
103
  const pulls = (await p.listOpen())
100
104
  .filter((pull) => pull.author === "dependabot[bot]")
@@ -109,8 +113,9 @@ export async function main(p, out, argv = []) {
109
113
  out("no open Dependabot pull requests");
110
114
  return 0;
111
115
  }
116
+ const branch = await defaultBranch();
112
117
  for (const pull of pulls) {
113
- formatBump(await readBump(p, pull.number)).forEach((l) => out(l));
118
+ formatBump(await readBump(p, pull.number), branch).forEach((l) => out(l));
114
119
  }
115
120
  return 0;
116
121
  }
@@ -122,5 +127,11 @@ export async function main(p, out, argv = []) {
122
127
  /** `factory deps`. */
123
128
  export async function run(argv = []) {
124
129
  const { repository, codeHost } = await reachOf(process.env);
125
- return main(openCodeHost(repository, codeHost), (line) => console.log(line), argv);
130
+ const p = openCodeHost(repository, codeHost);
131
+ // The code host is already open, so it is the one asked where the
132
+ // checkout does not say.
133
+ return main(p, (line) => console.log(line), argv, () => needDefaultBranch({
134
+ ...branchDeps(repoRoot()),
135
+ host: () => p.defaultBranch(),
136
+ }));
126
137
  }
package/dist/doctor.d.mts CHANGED
@@ -4,8 +4,9 @@ import { type Registry } from "./tools.mts";
4
4
  export type { Check } from "./setup.mts";
5
5
  export type DoctorDeps = {
6
6
  settings: () => Promise<Settings>;
7
- /** The paths a sync would change. */
8
- outOfStep: (s: Settings) => string[];
7
+ /** The paths a sync would change. It rejects with NoDefaultBranch when
8
+ * the default branch, which the sync writes, cannot be told. */
9
+ outOfStep: (s: Settings) => Promise<string[]> | string[];
9
10
  /** The version installed, and the one the repository's lock records. */
10
11
  versions: () => {
11
12
  installed: string;
package/dist/doctor.mjs CHANGED
@@ -9,6 +9,7 @@ import { join } from "node:path";
9
9
  import { defaultDeps, loadSettings, repoRoot, } from "./config.mjs";
10
10
  import { hasCommand } from "./lib/has-command.mjs";
11
11
  import { neededSecrets, PART_TEXT, PARTS, partsOn, } from "./parts.mjs";
12
+ import { branchDeps, CANNOT_TELL, needDefaultBranch, NoDefaultBranch, } from "./lib/default-branch.mjs";
12
13
  import { differences, LOCK, PACKAGE, plan } from "./sync.mjs";
13
14
  import { inUse, secretSteps, TOOLS } from "./tools.mjs";
14
15
  const SYNC = "Run npx --no-install factory sync";
@@ -38,13 +39,20 @@ export async function checks(d) {
38
39
  return [{ state: "fail", text: "The settings are valid", fix: message(e) }];
39
40
  }
40
41
  out.push({ state: "pass", text: "The settings are valid" });
41
- const differ = d.outOfStep(s);
42
- out.push(differ.length === 0
42
+ let differ = null;
43
+ try {
44
+ differ = await d.outOfStep(s);
45
+ }
46
+ catch (e) {
47
+ if (!(e instanceof NoDefaultBranch))
48
+ throw e;
49
+ }
50
+ out.push(differ?.length === 0
43
51
  ? { state: "pass", text: "The factory's files match the settings" }
44
52
  : {
45
53
  state: "fail",
46
54
  text: "The factory's files match the settings",
47
- fix: `${differ.length} differ. ${SYNC}`,
55
+ fix: differ ? `${differ.length} differ. ${SYNC}` : CANNOT_TELL,
48
56
  });
49
57
  const { installed, locked } = d.versions();
50
58
  if (locked === null)
@@ -123,6 +131,13 @@ export async function checks(d) {
123
131
  for (const need of needed.filter((n) => n.part === part))
124
132
  out.push(secretLine(need.anyOf, forPart));
125
133
  }
134
+ // A gate is no part and fails no check: it is shown as off, since a
135
+ // build cannot finish without one.
136
+ if (s.commands.gate.length === 0)
137
+ out.push({
138
+ state: "off",
139
+ text: "commands.gate is not set: a build cannot finish until it is",
140
+ });
126
141
  if (secrets !== null)
127
142
  for (const need of needed.filter((n) => n.part === null))
128
143
  out.push(secretLine(need.anyOf, need.tool));
@@ -152,7 +167,7 @@ export function doctorDeps(root = repoRoot()) {
152
167
  const settings = () => loadSettings(defaultDeps(root));
153
168
  return {
154
169
  settings,
155
- outOfStep: (s) => differences(root, plan(PACKAGE, root, s)),
170
+ outOfStep: async (s) => differences(root, plan(PACKAGE, root, s, await needDefaultBranch(branchDeps(root)))),
156
171
  versions: () => {
157
172
  const installed = JSON.parse(readFileSync(join(PACKAGE, "package.json"), "utf8")).version;
158
173
  let locked = null;
@@ -1,2 +1,4 @@
1
- import type { Settings } from "./config.mts";
2
- export declare function explainLines(s: Settings, raw: unknown): Promise<string[]>;
1
+ import { type Settings } from "./config.mts";
2
+ /** `exists` says whether a path from the root exists, for the plugins the
3
+ * factory uses where the settings name none. */
4
+ export declare function explainLines(s: Settings, raw: unknown, exists: (path: string) => boolean): Promise<string[]>;
package/dist/explain.mjs CHANGED
@@ -1,3 +1,7 @@
1
+ // `factory config explain`: the settings as `.claude/factory.yaml` would
2
+ // read with every default written out, each line the file does not set
3
+ // marked `# default`, so any line can be copied into the file.
4
+ import { PHASES, pluginsOf, ROLE_SHAPE, ROLES, } from "./config.mjs";
1
5
  const isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
2
6
  /** Whether the file sets `path`, each step a key into the raw file. A
3
7
  * block written as one word, such as `code-host: github`, sets its `type`. */
@@ -12,7 +16,9 @@ function sets(raw, path) {
12
16
  }
13
17
  return true;
14
18
  }
15
- export async function explainLines(s, raw) {
19
+ /** `exists` says whether a path from the root exists, for the plugins the
20
+ * factory uses where the settings name none. */
21
+ export async function explainLines(s, raw, exists) {
16
22
  const { stringify } = await import("yaml");
17
23
  const value = (v) => stringify(v, { lineWidth: 0 }).trim();
18
24
  const lines = [];
@@ -59,36 +65,77 @@ export async function explainLines(s, raw) {
59
65
  put(["builds", "poll-minutes"], s.builds.pollMinutes);
60
66
  else
61
67
  comment(1, "poll-minutes: only with trigger github-action");
62
- put(["specs"], s.specs);
63
- put(["before-commit"], s.beforeCommit);
64
- put(["build-setup"], s.buildSetup);
65
- if (!s.plugins.length)
66
- put(["plugins"], []);
68
+ if (s.specs === "openspec") {
69
+ block(["specs"]);
70
+ put(["specs", "type"], s.specs);
71
+ put(["specs", "check"], s.specCheck);
72
+ }
73
+ else
74
+ put(["specs"], s.specs);
75
+ block(["commands"]);
76
+ put(["commands", "build-setup"], s.commands.buildSetup);
77
+ put(["commands", "before-commit"], s.commands.beforeCommit);
78
+ put(["commands", "gate"], s.commands.gate);
79
+ for (const [key, command] of [
80
+ ["test-one", s.commands.testOne],
81
+ ["end-to-end", s.commands.endToEnd],
82
+ ])
83
+ if (command === null)
84
+ comment(1, `${key}: none (default)`);
85
+ else
86
+ put(["commands", key], command);
87
+ if (s.commands.coverage === null)
88
+ comment(1, "coverage: none (default)");
67
89
  else {
68
- block(["plugins"]);
69
- for (const p of s.plugins) {
70
- lines.push({ text: ` - ${p.kind}: ${value(p.name)}`, byDefault: false });
71
- lines.push({ text: ` role: ${p.role}`, byDefault: false });
72
- for (const [k, list] of [
73
- ["files", p.files],
74
- ["labels", p.labels],
75
- ])
76
- if (list.length) {
77
- lines.push({ text: ` ${k}:`, byDefault: false });
78
- for (const item of list)
79
- lines.push({ text: ` - ${value(item)}`, byDefault: false });
80
- }
90
+ block(["commands", "coverage"]);
91
+ put(["commands", "coverage", "run"], s.commands.coverage.run);
92
+ put(["commands", "coverage", "report"], s.commands.coverage.report);
93
+ }
94
+ put(["commands", "relock"], s.commands.relock);
95
+ // Each role holds what `factory plugins` prints for it: the settings'
96
+ // own plugins, or the factory's where they name none.
97
+ const used = pluginsOf(s, exists);
98
+ block(["plugins"]);
99
+ for (const phase of PHASES) {
100
+ block(["plugins", phase]);
101
+ for (const role of ROLES.filter((x) => ROLE_SHAPE[x].phase === phase)) {
102
+ const { key, list } = ROLE_SHAPE[role];
103
+ const path = ["plugins", phase, key];
104
+ const found = used.filter((p) => p.role === role);
105
+ if (!found.length) {
106
+ if (list)
107
+ put(path, []);
108
+ else
109
+ comment(2, `${key}: none (default)`);
110
+ continue;
111
+ }
112
+ const byDefault = !sets(raw, path);
113
+ const add = (depth, text) => lines.push({ text: `${pad(depth)}${text}`, byDefault });
114
+ add(2, `${key}:`);
115
+ for (const p of found) {
116
+ add(3, `${list ? "- " : ""}${p.kind}: ${value(p.name)}`);
117
+ const under = list ? 4 : 3;
118
+ for (const [k, items] of [
119
+ ["files", p.files],
120
+ ["labels", p.labels],
121
+ ])
122
+ if (items.length) {
123
+ add(under, `${k}:`);
124
+ for (const item of items)
125
+ add(under + 1, `- ${value(item)}`);
126
+ }
127
+ }
81
128
  }
82
129
  }
83
130
  block(["auto-merge"]);
84
131
  put(["auto-merge", "allow"], s.autoMerge.allow);
85
132
  put(["auto-merge", "deny"], s.autoMerge.deny);
86
133
  put(["auto-merge", "commands"], s.autoMerge.commands);
87
- if (s.ciReview === null)
88
- comment(0, "ci-review: off");
134
+ if (s.prReview === null)
135
+ comment(0, "pr-review: off");
89
136
  else {
90
- block(["ci-review"]);
91
- put(["ci-review", "commands"], s.ciReview.commands);
137
+ block(["pr-review"]);
138
+ put(["pr-review", "commands"], s.prReview.commands);
92
139
  }
93
140
  if (s.site === null)
94
141
  comment(0, "site: off");
@@ -1,3 +1,4 @@
1
+ import { type Sources } from "./lib/default-branch.mts";
1
2
  export type HookInput = {
2
3
  cwd?: string;
3
4
  tool_input?: {
@@ -36,6 +37,10 @@ export declare function gitCalls(cmd: string, cwd: string): GitCall[];
36
37
  * session's hook runs the copy in the folder the session opened, whichever
37
38
  * worktree the commit is in, and each copy reads only the settings it knows. */
38
39
  export declare function ownLauncher(top: string): string | null;
40
+ /** The default branch of the checkout at `top`, from the sources allowed,
41
+ * or null when none of them answers. */
42
+ export type BranchOf = (top: string, sources: Sources) => Promise<string | null>;
39
43
  /** The block message for this Bash call, or null to let it through. Writes
40
- * the failing gate command's output to `err` first. */
41
- export declare function checkCommit(input: HookInput, err: (text: string) => void): Promise<string | null>;
44
+ * the failing gate command's output to `err` first. `defaultOf` stands in
45
+ * for the default branch's sources in tests. */
46
+ export declare function checkCommit(input: HookInput, err: (text: string) => void, defaultOf?: BranchOf): Promise<string | null>;
@@ -1,14 +1,23 @@
1
1
  // PreToolUse hook for Bash, run as `factory guard commit` or within
2
- // `factory guard`. Blocks commits and pushes on main, force pushes, adding
3
- // the owner's override label, and any commit the fast half of the gate would
4
- // fail: the before-commit commands in `.claude/factory.yaml`. A block is
5
- // exit 2, which stops the call and shows the message to Claude.
2
+ // `factory guard`. Blocks commits and pushes on the default branch, force
3
+ // pushes, adding the owner's override label, and any commit the fast half of
4
+ // the gate would fail: the `commands.before-commit` commands in
5
+ // `.claude/factory.yaml`. A block is exit 2, which stops the call and shows
6
+ // the message to Claude.
7
+ //
8
+ // The default branch is whatever the repository calls it
9
+ // (`lib/default-branch.mts`). In a checkout with the factory's settings,
10
+ // every source may answer, and a commit or push is blocked when none does.
11
+ // Any other checkout is not the factory's to govern: there the guard reads
12
+ // `origin/HEAD` alone, asks nobody, and lets the call through when it is
13
+ // not set.
6
14
  import { execFileSync, spawnSync } from "node:child_process";
7
15
  import { existsSync, realpathSync } from "node:fs";
8
16
  import { homedir } from "node:os";
9
17
  import { dirname, isAbsolute, join, relative } from "node:path";
10
18
  import { fileURLToPath } from "node:url";
11
19
  import { defaultDeps, loadSettings, settingsPath } from "./config.mjs";
20
+ import { branchDeps, CANNOT_TELL, defaultBranch, } from "./lib/default-branch.mjs";
12
21
  /** Heredoc bodies and quoted strings blanked, so a commit message, grep
13
22
  * pattern, or file body that mentions "git push -f" or "main" is not read as
14
23
  * part of a command. A quoted single word is unquoted instead: the shell
@@ -134,9 +143,23 @@ export function ownLauncher(top) {
134
143
  return null;
135
144
  }
136
145
  }
146
+ const branchOf = (top, sources) => defaultBranch(branchDeps(top), sources);
147
+ /** The checkout `dir` is in, or `dir` itself when it is in none. */
148
+ function checkoutOf(dir) {
149
+ try {
150
+ return toplevel(dir);
151
+ }
152
+ catch {
153
+ return dir;
154
+ }
155
+ }
156
+ const literal = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
157
+ /** Whether a push names `branch` as where it pushes to. */
158
+ const pushesTo = (segment, branch) => new RegExp(String.raw `\s(\S*:)?(refs\/heads\/)?${literal(branch)}(\s|$)`).test(segment);
137
159
  /** The block message for this Bash call, or null to let it through. Writes
138
- * the failing gate command's output to `err` first. */
139
- export async function checkCommit(input, err) {
160
+ * the failing gate command's output to `err` first. `defaultOf` stands in
161
+ * for the default branch's sources in tests. */
162
+ export async function checkCommit(input, err, defaultOf = branchOf) {
140
163
  const raw = input.tool_input?.command ?? "";
141
164
  const cwd = input.cwd ?? ".";
142
165
  if (addsOverride(raw))
@@ -144,32 +167,46 @@ export async function checkCommit(input, err) {
144
167
  const calls = gitCalls(blankQuoted(raw), cwd);
145
168
  if (calls.length === 0)
146
169
  return null;
147
- for (const { dir } of calls) {
170
+ // Each call's own checkout says what its default branch is, asked once
171
+ // per checkout.
172
+ const defaults = new Map();
173
+ const pushedTo = [];
174
+ for (const { kind, segment, dir } of calls) {
175
+ const top = checkoutOf(dir);
176
+ if (!defaults.has(top)) {
177
+ const governed = existsSync(settingsPath(top));
178
+ const name = await defaultOf(top, governed ? "all" : "origin-head");
179
+ if (name === null && governed)
180
+ return CANNOT_TELL;
181
+ defaults.set(top, name);
182
+ }
183
+ const name = defaults.get(top);
184
+ if (!name)
185
+ continue;
148
186
  const branch = spawnSync("git", ["-C", dir, "branch", "--show-current"], {
149
187
  encoding: "utf8",
150
188
  }).stdout;
151
- if (branch?.trim() === "main")
152
- return "main is checked out. Create a branch from origin/main first.";
189
+ if (branch?.trim() === name)
190
+ return `${name} is checked out. Create a branch from origin/${name} first.`;
191
+ if (kind === "push")
192
+ pushedTo.push({ segment, branch: name });
153
193
  }
154
194
  const pushes = calls.filter((c) => c.kind === "push").map((c) => c.segment);
155
195
  if (pushes.some((p) => /\s(--force|-f)(\s|$)|\s\+\S/.test(p)))
156
196
  return "force push. Use --force-with-lease if a rewrite is really intended.";
157
- if (pushes.some((p) => /\s(\S*:)?(refs\/heads\/)?main(\s|$)/.test(p)))
158
- return "pushing to main. main only changes through a merged pull request.";
159
- // The fast half of the gate: the before-commit commands in the commit's
160
- // own checkout's settings, in order, stopping at the first that fails.
197
+ const toDefault = pushedTo.find((p) => pushesTo(p.segment, p.branch));
198
+ if (toDefault)
199
+ return `pushing to ${toDefault.branch}. ${toDefault.branch} only changes through a merged pull request.`;
200
+ // The fast half of the gate: the `commands.before-commit` commands in the
201
+ // commit's own checkout's settings, in order, stopping at the first that
202
+ // fails.
161
203
  // Settings that cannot be read block the commit, as a failing command
162
204
  // would.
163
205
  const commit = calls.find((c) => c.kind === "commit");
164
206
  if (!commit)
165
207
  return null;
166
- let top = commit.dir;
167
- try {
168
- top = toplevel(commit.dir);
169
- }
170
- catch {
171
- // Not a checkout: read the settings where the commit runs.
172
- }
208
+ // Where the commit is in no checkout, the settings are read where it runs.
209
+ const top = checkoutOf(commit.dir);
173
210
  const own = ownLauncher(top);
174
211
  if (own) {
175
212
  const r = spawnSync("node", [own, "guard", "commit"], {
@@ -188,7 +225,7 @@ export async function checkCommit(input, err) {
188
225
  return null;
189
226
  let commands;
190
227
  try {
191
- commands = (await loadSettings(defaultDeps(top))).beforeCommit;
228
+ commands = (await loadSettings(defaultDeps(top))).commands.beforeCommit;
192
229
  }
193
230
  catch (e) {
194
231
  err(lastLines(e instanceof Error ? e.message : String(e)).join("\n"));
package/dist/init.d.mts CHANGED
@@ -29,8 +29,10 @@ export type InitDeps = {
29
29
  remote: () => string | null;
30
30
  tools: Registry;
31
31
  sync: () => Promise<number>;
32
- /** The files a sync with these settings would write or delete. */
33
- syncChanges: (settingsText: string) => string[];
32
+ /** The files a sync with these settings would write or delete. `host`
33
+ * asks the code host for the default branch, where the checkout does not
34
+ * say. It rejects with NoDefaultBranch when nobody can tell. */
35
+ syncChanges: (settingsText: string, host: () => Promise<string>) => Promise<string[]> | string[];
34
36
  /** Runs a command attached to the terminal, as `claude setup-token`. */
35
37
  interactive: (argv: string[]) => Promise<number>;
36
38
  hasCommand: (name: string) => boolean;
package/dist/init.mjs CHANGED
@@ -15,6 +15,7 @@ import { builtOf, secretSteps, TOOLS, } from "./tools.mjs";
15
15
  import { NeedsScopeError } from "./code-host/types.mjs";
16
16
  import { columnsOf, fieldNamesOf, parseSettings, POLL_MINUTES, repoRoot, SETTINGS_FILE, SettingsError, } from "./config.mjs";
17
17
  import { checks as doctorChecks, doctorDeps, line } from "./doctor.mjs";
18
+ import { branchDeps, needDefaultBranch, NoDefaultBranch, } from "./lib/default-branch.mjs";
18
19
  import { hasCommand, noTerminal } from "./lib/has-command.mjs";
19
20
  import { DEFAULT_RUNNER } from "./runner/index.mjs";
20
21
  import { listed } from "./lib/listed.mjs";
@@ -249,7 +250,7 @@ export async function main(_argv, d) {
249
250
  }
250
251
  // The settings as they will stand, keeping every other key and comment.
251
252
  if (!doc.has("version"))
252
- doc.set("version", 1);
253
+ doc.set("version", 2);
253
254
  if (!doc.has("repository"))
254
255
  doc.set("repository", repository);
255
256
  // A tool other than the one a setting defaults to is written down.
@@ -276,10 +277,10 @@ export async function main(_argv, d) {
276
277
  remove(doc, ["auto-merge", "allow"]);
277
278
  // The review is on while its setting is written; the sync writes its
278
279
  // workflow then, and removes it once the setting is gone.
279
- if (parts.has("review") && !doc.has("ci-review"))
280
- doc.setIn(["ci-review", "commands"], []);
280
+ if (parts.has("review") && !doc.has("pr-review"))
281
+ doc.setIn(["pr-review", "commands"], []);
281
282
  if (!parts.has("review"))
282
- doc.delete("ci-review");
283
+ doc.delete("pr-review");
283
284
  // The ticket system's own values: asked for once, and taken out with
284
285
  // the part that needed them.
285
286
  const values = (ps) => (d.tools.tickets[chosen.tickets].setup.steps?.(context(ps)) ?? []).filter((s) => s.kind === "value");
@@ -329,10 +330,12 @@ export async function main(_argv, d) {
329
330
  ];
330
331
  let syncs;
331
332
  try {
332
- syncs = d.syncChanges(newText);
333
+ syncs = await d.syncChanges(newText, () => codeHost.defaultBranch());
333
334
  }
334
335
  catch (e) {
335
- d.out(`The settings would not be valid: ${message(e)}`);
336
+ d.out(e instanceof NoDefaultBranch
337
+ ? e.message
338
+ : `The settings would not be valid: ${message(e)}`);
336
339
  return 1;
337
340
  }
338
341
  const toStore = [
@@ -493,6 +496,10 @@ export async function main(_argv, d) {
493
496
  ` FACTORY_BOARD_NUMBER=${board}`,
494
497
  " FACTORY_BOARD_TOKEN=the access token you just made",
495
498
  ].join("\n"));
499
+ // Init asks for no command, so a gate is the owner's to add: without one
500
+ // `factory gate` fails, and a build cannot finish.
501
+ if (!settings?.commands.gate.length)
502
+ left.push(`Add the commands that check a change, under commands.gate in ${SETTINGS_FILE}`);
496
503
  left.push("Commit this on a branch, open a pull request, and merge it.");
497
504
  d.out("Nothing is committed. Left to do:");
498
505
  left.forEach((step, i) => d.out(` ${i + 1}. ${step}`));
@@ -547,10 +554,13 @@ export async function run(argv) {
547
554
  },
548
555
  tools: TOOLS,
549
556
  sync: async () => (await import("./sync.mjs")).run([]),
550
- syncChanges: (text) => {
557
+ // The settings are not written yet, so the code host asked is the one
558
+ // setup has just opened, not the one a settings file names.
559
+ syncChanges: async (text, host) => {
551
560
  const raw = parseDocument(text).toJS();
552
561
  const s = parseSettings(raw, (p) => existsSync(join(root, p)));
553
- return differences(root, syncPlan(PACKAGE, root, s));
562
+ const branch = await needDefaultBranch({ ...branchDeps(root), host });
563
+ return differences(root, syncPlan(PACKAGE, root, s, branch));
554
564
  },
555
565
  interactive: async (argv2) => spawnSync(argv2[0], argv2.slice(1), { stdio: "inherit" }).status ?? 1,
556
566
  hasCommand,
@@ -0,0 +1,35 @@
1
+ /** A git command's exit, and what it printed. */
2
+ export type Git = (args: string[]) => {
3
+ ok: boolean;
4
+ out: string;
5
+ };
6
+ /** Git, run in `cwd`, with its errors dropped. */
7
+ export declare const gitIn: (cwd: string) => Git;
8
+ export type Deps = {
9
+ env: Record<string, string | undefined>;
10
+ /** Reads the event file of a workflow run. */
11
+ readFile: (path: string) => string;
12
+ git: Git;
13
+ /** The code host's answer. It rejects when the host cannot be asked. */
14
+ host: () => Promise<string>;
15
+ };
16
+ /** What a caller lets answer: every source, or `origin/HEAD` alone, for a
17
+ * caller that must ask nobody and assume nothing. */
18
+ export type Sources = "all" | "origin-head";
19
+ export declare const CANNOT_TELL = "Could not tell the default branch. Run: git remote set-head origin --auto";
20
+ /** Thrown where a command cannot go on without the default branch. */
21
+ export declare class NoDefaultBranch extends Error {
22
+ constructor();
23
+ }
24
+ /** The default branch's name, or null when no source the caller allows
25
+ * answers. */
26
+ export declare function defaultBranch(d: Deps, sources?: Sources): Promise<string | null>;
27
+ /** The default branch's name, for a command that cannot go on without it. */
28
+ export declare function needDefaultBranch(d: Deps, sources?: Sources): Promise<string>;
29
+ /** The sources of the checkout at `root`. The code host is the one the
30
+ * checkout's settings name, and is loaded only when it is asked, so a
31
+ * caller that runs before every command stays quick. */
32
+ export declare const branchDeps: (root: string, env?: Record<string, string | undefined>) => Deps;
33
+ export declare function main(argv: string[], d: Deps, out: (line: string) => void, err: (line: string) => void): Promise<number>;
34
+ /** `factory default-branch`. */
35
+ export declare function run(argv: string[]): Promise<number>;