@davidbyoung/software-factory 0.1.2 → 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 (120) hide show
  1. package/README.md +20 -20
  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/agent/claude-code.d.mts +3 -0
  7. package/dist/agent/claude-code.mjs +89 -0
  8. package/dist/agent/index.d.mts +2 -0
  9. package/dist/agent/index.mjs +5 -0
  10. package/dist/board.mjs +1 -1
  11. package/dist/cli.mjs +46 -4
  12. package/dist/code-host/github-setup.d.mts +5 -0
  13. package/dist/code-host/github-setup.mjs +133 -0
  14. package/dist/code-host/github.mjs +4 -0
  15. package/dist/code-host/index.d.mts +1 -1
  16. package/dist/code-host/index.mjs +2 -1
  17. package/dist/code-host/types.d.mts +2 -0
  18. package/dist/commands.d.mts +16 -0
  19. package/dist/commands.mjs +129 -0
  20. package/dist/config.d.mts +87 -20
  21. package/dist/config.mjs +344 -89
  22. package/dist/deps.d.mts +7 -4
  23. package/dist/deps.mjs +20 -9
  24. package/dist/doctor.d.mts +9 -16
  25. package/dist/doctor.mjs +71 -68
  26. package/dist/explain.d.mts +4 -0
  27. package/dist/explain.mjs +174 -0
  28. package/dist/guard-commit.d.mts +7 -2
  29. package/dist/guard-commit.mjs +58 -21
  30. package/dist/init.d.mts +12 -14
  31. package/dist/init.mjs +194 -136
  32. package/dist/lib/default-branch.d.mts +35 -0
  33. package/dist/lib/default-branch.mjs +117 -0
  34. package/dist/lib/has-command.d.mts +5 -0
  35. package/dist/lib/has-command.mjs +8 -0
  36. package/dist/lib/listed.d.mts +2 -0
  37. package/dist/lib/listed.mjs +4 -0
  38. package/dist/lib/refined-check.d.mts +7 -0
  39. package/dist/lib/refined-check.mjs +76 -0
  40. package/dist/lib/work-status.d.mts +12 -2
  41. package/dist/lib/work-status.mjs +14 -3
  42. package/dist/parts.d.mts +18 -15
  43. package/dist/parts.mjs +15 -43
  44. package/dist/patch-coverage.d.mts +13 -0
  45. package/dist/patch-coverage.mjs +73 -0
  46. package/dist/poller.d.mts +20 -3
  47. package/dist/poller.mjs +62 -15
  48. package/dist/pr-watch.d.mts +3 -2
  49. package/dist/pr-watch.mjs +22 -5
  50. package/dist/pr.mjs +34 -2
  51. package/dist/remove.d.mts +11 -0
  52. package/dist/remove.mjs +156 -0
  53. package/dist/runner/github-actions.d.mts +1 -1
  54. package/dist/runner/github-actions.mjs +12 -0
  55. package/dist/runner/index.d.mts +1 -1
  56. package/dist/runner/index.mjs +2 -1
  57. package/dist/runner/setup.d.mts +2 -0
  58. package/dist/runner/setup.mjs +22 -0
  59. package/dist/runner/types.d.mts +3 -0
  60. package/dist/runner/types.mjs +0 -2
  61. package/dist/session-start.d.mts +23 -13
  62. package/dist/session-start.mjs +56 -44
  63. package/dist/setup.d.mts +98 -0
  64. package/dist/setup.mjs +3 -0
  65. package/dist/site/servers.d.mts +6 -2
  66. package/dist/site/servers.mjs +14 -9
  67. package/dist/site.mjs +2 -2
  68. package/dist/status.d.mts +4 -4
  69. package/dist/status.mjs +8 -7
  70. package/dist/sync.d.mts +26 -2
  71. package/dist/sync.mjs +177 -13
  72. package/dist/ticket.mjs +19 -1
  73. package/dist/tickets/github-setup.d.mts +2 -0
  74. package/dist/tickets/github-setup.mjs +50 -0
  75. package/dist/tickets/github.mjs +0 -2
  76. package/dist/tickets/index.mjs +2 -1
  77. package/dist/tickets/transport.mjs +1 -3
  78. package/dist/tickets/types.mjs +0 -2
  79. package/dist/tool-names.d.mts +11 -0
  80. package/dist/tool-names.mjs +20 -0
  81. package/dist/tools.d.mts +56 -0
  82. package/dist/tools.mjs +76 -0
  83. package/docs/builds.md +111 -59
  84. package/docs/cli.md +106 -69
  85. package/docs/configuration.md +489 -171
  86. package/docs/design.md +18 -5
  87. package/docs/developing.md +179 -73
  88. package/docs/existing-repo.md +25 -12
  89. package/docs/github/by-hand.md +334 -0
  90. package/docs/github/reference.md +76 -67
  91. package/docs/github/setup.md +105 -286
  92. package/docs/glossary.md +18 -7
  93. package/docs/limitations.md +39 -12
  94. package/docs/plugins.md +305 -56
  95. package/docs/quick-start.md +85 -100
  96. package/docs/removing.md +37 -17
  97. package/docs/skills.md +121 -62
  98. package/docs/updating.md +150 -9
  99. package/docs/workflow.md +23 -19
  100. package/package.json +1 -1
  101. package/poller.Dockerfile +10 -18
  102. package/review.md +20 -11
  103. package/rules.md +36 -30
  104. package/settings.schema.json +313 -69
  105. package/skills/factory-address-review/SKILL.md +50 -30
  106. package/skills/factory-build/SKILL.md +76 -23
  107. package/skills/factory-deps/SKILL.md +46 -21
  108. package/skills/factory-design/SKILL.md +17 -8
  109. package/skills/factory-diagnose/SKILL.md +22 -20
  110. package/skills/factory-mutate/SKILL.md +38 -24
  111. package/skills/factory-refine/SKILL.md +55 -31
  112. package/skills/factory-resolve-conflicts/SKILL.md +76 -34
  113. package/skills/factory-trace/SKILL.md +80 -0
  114. package/workflows/factory-build.yml +6 -5
  115. package/workflows/factory-conflicts.yml +8 -8
  116. package/workflows/factory-deps-auto-merge.yml +3 -2
  117. package/workflows/factory-deps.yml +1 -1
  118. package/workflows/factory-poller.yml +46 -0
  119. package/workflows/factory-review.yml +1 -1
  120. 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
@@ -1,27 +1,20 @@
1
- import { type CodeHost } from "./code-host/index.mts";
2
1
  import { type Settings } from "./config.mts";
3
- import { type Runner } from "./runner/index.mts";
4
- import { type Tickets } from "./tickets/index.mts";
5
- export type Check = {
6
- state: "pass" | "fail" | "off";
7
- text: string;
8
- /** What to do about a failure. */
9
- fix?: string;
10
- };
2
+ import type { Check } from "./setup.mts";
3
+ import { type Registry } from "./tools.mts";
4
+ export type { Check } from "./setup.mts";
11
5
  export type DoctorDeps = {
12
6
  settings: () => Promise<Settings>;
13
- /** The paths a sync would change. */
14
- 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[];
15
10
  /** The version installed, and the one the repository's lock records. */
16
11
  versions: () => {
17
12
  installed: string;
18
13
  locked: string | null;
19
14
  };
20
- open: (s: Settings) => {
21
- codeHost: CodeHost;
22
- runner: Runner;
23
- tickets: Tickets | Promise<Tickets>;
24
- };
15
+ root: string;
16
+ hasCommand: (name: string) => boolean;
17
+ tools: Registry;
25
18
  out: (line: string) => void;
26
19
  };
27
20
  export declare function checks(d: DoctorDeps): Promise<Check[]>;
package/dist/doctor.mjs CHANGED
@@ -6,18 +6,19 @@
6
6
  // being set.
7
7
  import { readFileSync } from "node:fs";
8
8
  import { join } from "node:path";
9
- import { boardConfigOf, inspectBoard } from "./board.mjs";
10
- import { openCodeHost } from "./code-host/index.mjs";
11
9
  import { defaultDeps, loadSettings, repoRoot, } from "./config.mjs";
12
- import { neededSecrets, PART_TEXT, PARTS, partsOn } from "./parts.mjs";
13
- import { openRunner } from "./runner/index.mjs";
10
+ import { hasCommand } from "./lib/has-command.mjs";
11
+ import { neededSecrets, PART_TEXT, PARTS, partsOn, } from "./parts.mjs";
12
+ import { branchDeps, CANNOT_TELL, needDefaultBranch, NoDefaultBranch, } from "./lib/default-branch.mjs";
14
13
  import { differences, LOCK, PACKAGE, plan } from "./sync.mjs";
15
- import { openTickets } from "./tickets/index.mjs";
14
+ import { inUse, secretSteps, TOOLS } from "./tools.mjs";
16
15
  const SYNC = "Run npx --no-install factory sync";
17
16
  const INIT = "Run npx --no-install factory init";
18
17
  const message = (e) => (e instanceof Error ? e.message : String(e));
19
18
  /** -1, 0, or 1 as version `a` is older than, the same as, or newer than `b`. */
20
19
  function compareVersions(a, b) {
20
+ if (a === b)
21
+ return 0;
21
22
  const pa = a.split(/[.-]/).map(Number);
22
23
  const pb = b.split(/[.-]/).map(Number);
23
24
  for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
@@ -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)
@@ -64,23 +72,32 @@ export async function checks(d) {
64
72
  text: `Version ${installed} is installed, but the repository records ${locked}`,
65
73
  fix: compareVersions(installed, locked) < 0 ? "Run npm ci" : SYNC,
66
74
  });
67
- const { codeHost, runner, tickets } = d.open(s);
68
- try {
69
- out.push({
70
- state: "pass",
71
- text: `Signed in to the code host as ${await codeHost.signedInAs()}`,
72
- });
73
- }
74
- catch (e) {
75
- out.push({
76
- state: "fail",
77
- text: "Signed in to the code host",
78
- fix: message(e),
79
- });
80
- }
75
+ const chosen = {
76
+ codeHost: s.codeHost.type,
77
+ tickets: s.tickets.type,
78
+ runner: s.builds.runner,
79
+ agent: Object.keys(d.tools.agent)[0],
80
+ };
81
+ const opened = {
82
+ codeHost: d.tools.codeHost[chosen.codeHost].open(s.repository),
83
+ runner: d.tools.runner[chosen.runner].open(s.repository),
84
+ tickets: await d.tools.tickets[chosen.tickets].open({ repository: s.repository, board: s.tickets.board }, s),
85
+ };
86
+ const context = (parts) => ({
87
+ repository: s.repository,
88
+ root: d.root,
89
+ parts: new Set(parts),
90
+ chosen,
91
+ settings: s,
92
+ hasCommand: d.hasCommand,
93
+ opened,
94
+ });
95
+ const [agent, codeHost, tickets, runner] = inUse(d.tools, chosen);
96
+ out.push(...((await codeHost.setup.checks?.({ ...context([]), secrets: null })) ??
97
+ []));
81
98
  let secrets;
82
99
  try {
83
- secrets = await runner.secretNames();
100
+ secrets = await opened.runner.secretNames();
84
101
  }
85
102
  catch (e) {
86
103
  secrets = null;
@@ -90,8 +107,19 @@ export async function checks(d) {
90
107
  fix: message(e),
91
108
  });
92
109
  }
93
- const on = partsOn(s, secrets ?? []);
94
- const needed = neededSecrets(on);
110
+ const cloudNeeds = secretSteps(d.tools, context(["cloud"])).flatMap((x) => x.step.needs.filter((n) => n.part === "cloud"));
111
+ const on = partsOn(s, secrets ?? [], cloudNeeds);
112
+ const needed = neededSecrets(on, secretSteps(d.tools, context(on)));
113
+ const secretLine = (anyOf, forWhat) => {
114
+ const found = anyOf.find((n) => secrets.includes(n));
115
+ return found
116
+ ? { state: "pass", text: `${found} is set, for ${forWhat}` }
117
+ : {
118
+ state: "fail",
119
+ text: `${anyOf.join(" or ")} is not set, for ${forWhat}`,
120
+ fix: INIT,
121
+ };
122
+ };
95
123
  for (const part of PARTS) {
96
124
  if (!on.has(part)) {
97
125
  out.push({ state: "off", text: `${PART_TEXT[part].name}: off` });
@@ -100,41 +128,21 @@ export async function checks(d) {
100
128
  if (secrets === null)
101
129
  continue;
102
130
  const forPart = PART_TEXT[part].name.replace(/^./, (c) => c.toLowerCase());
103
- for (const need of needed.filter((n) => n.part === part)) {
104
- const found = need.anyOf.find((n) => secrets.includes(n));
105
- out.push(found
106
- ? { state: "pass", text: `${found} is set, for ${forPart}` }
107
- : {
108
- state: "fail",
109
- text: `${need.anyOf.join(" or ")} is not set, for ${forPart}`,
110
- fix: INIT,
111
- });
112
- }
113
- }
114
- if (s.tickets.board !== null) {
115
- const number = s.tickets.board;
116
- try {
117
- const board = await (await tickets).board.read();
118
- const { problems } = inspectBoard(board.fields, boardConfigOf(s));
119
- out.push(problems.length === 0
120
- ? {
121
- state: "pass",
122
- text: `Board ${number} has every column the settings name`,
123
- }
124
- : {
125
- state: "fail",
126
- text: `Board ${number}: ${problems.join("; ")}`,
127
- fix: INIT,
128
- });
129
- }
130
- catch (e) {
131
- out.push({
132
- state: "fail",
133
- text: `Board ${number} can be read`,
134
- fix: message(e),
135
- });
136
- }
131
+ for (const need of needed.filter((n) => n.part === part))
132
+ out.push(secretLine(need.anyOf, forPart));
137
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
+ });
141
+ if (secrets !== null)
142
+ for (const need of needed.filter((n) => n.part === null))
143
+ out.push(secretLine(need.anyOf, need.tool));
144
+ for (const tool of [tickets, runner, agent])
145
+ out.push(...((await tool.setup.checks?.({ ...context(on), secrets })) ?? []));
138
146
  return out;
139
147
  }
140
148
  /** One check as a line: a tick, a cross with what to do, or a dash for a
@@ -159,7 +167,7 @@ export function doctorDeps(root = repoRoot()) {
159
167
  const settings = () => loadSettings(defaultDeps(root));
160
168
  return {
161
169
  settings,
162
- outOfStep: (s) => differences(root, plan(PACKAGE, root, s)),
170
+ outOfStep: async (s) => differences(root, plan(PACKAGE, root, s, await needDefaultBranch(branchDeps(root)))),
163
171
  versions: () => {
164
172
  const installed = JSON.parse(readFileSync(join(PACKAGE, "package.json"), "utf8")).version;
165
173
  let locked = null;
@@ -172,14 +180,9 @@ export function doctorDeps(root = repoRoot()) {
172
180
  }
173
181
  return { installed, locked };
174
182
  },
175
- open: (s) => ({
176
- codeHost: openCodeHost(s.repository, s.codeHost.type),
177
- runner: openRunner(s.repository, s.builds.runner),
178
- tickets: openTickets(s, {
179
- repository: s.repository,
180
- board: s.tickets.board,
181
- }).then((o) => o.tickets),
182
- }),
183
+ root,
184
+ hasCommand,
185
+ tools: TOOLS,
183
186
  out: (l) => console.log(l),
184
187
  };
185
188
  }
@@ -0,0 +1,4 @@
1
+ import { type Settings } from "./config.mts";
2
+ /** `exists` says whether a path from the root exists, for the plug-ins the
3
+ * factory uses where the settings name none. */
4
+ export declare function explainLines(s: Settings, raw: unknown, exists: (path: string) => boolean): Promise<string[]>;
@@ -0,0 +1,174 @@
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, SLOT_SHAPE, SLOTS, } from "./config.mjs";
5
+ const isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
6
+ /** Whether the file sets `path`, each step a key into the raw file. A
7
+ * block written as one word, such as `code-host: github`, sets its `type`. */
8
+ function sets(raw, path) {
9
+ let at = raw;
10
+ for (const key of path) {
11
+ if (typeof at === "string" && key === "type")
12
+ return true;
13
+ if (!isObj(at) || !(key in at))
14
+ return false;
15
+ at = at[key];
16
+ }
17
+ return true;
18
+ }
19
+ /** `exists` says whether a path from the root exists, for the plug-ins the
20
+ * factory uses where the settings name none. */
21
+ export async function explainLines(s, raw, exists) {
22
+ const { stringify } = await import("yaml");
23
+ const value = (v) => stringify(v, { lineWidth: 0 }).trim();
24
+ const lines = [];
25
+ const pad = (depth) => " ".repeat(depth);
26
+ /** One key, its value printed under it when it is a list or a block. */
27
+ const put = (path, v, depth = path.length - 1) => {
28
+ const key = path.at(-1);
29
+ const byDefault = !sets(raw, path);
30
+ if (Array.isArray(v) && v.length && typeof v[0] !== "object") {
31
+ lines.push({ text: `${pad(depth)}${key}:`, byDefault });
32
+ for (const item of v)
33
+ lines.push({ text: `${pad(depth + 1)}- ${value(item)}`, byDefault });
34
+ return;
35
+ }
36
+ lines.push({ text: `${pad(depth)}${key}: ${value(v)}`, byDefault });
37
+ };
38
+ const block = (path) => lines.push({
39
+ text: `${pad(path.length - 1)}${path.at(-1)}:`,
40
+ byDefault: false,
41
+ });
42
+ const comment = (depth, text) => lines.push({ text: `${pad(depth)}# ${text}`, byDefault: false });
43
+ put(["version"], s.version);
44
+ put(["repository"], s.repository);
45
+ block(["tickets"]);
46
+ put(["tickets", "type"], s.tickets.type);
47
+ for (const [k, v] of Object.entries(s.tickets.options))
48
+ put(["tickets", k], v);
49
+ if (s.tickets.board === null)
50
+ comment(1, "board: none (default)");
51
+ else {
52
+ put(["tickets", "board"], s.tickets.board);
53
+ block(["tickets", "columns"]);
54
+ for (const [k, v] of Object.entries(s.tickets.columns))
55
+ put(["tickets", "columns", k], v ?? "none");
56
+ block(["tickets", "fields"]);
57
+ for (const [k, v] of Object.entries(s.tickets.fields))
58
+ put(["tickets", "fields", k], v ?? "none");
59
+ }
60
+ put(["code-host"], s.codeHost.type);
61
+ block(["builds"]);
62
+ put(["builds", "trigger"], s.builds.trigger);
63
+ put(["builds", "runner"], s.builds.runner);
64
+ if (s.builds.trigger === "github-action")
65
+ put(["builds", "poll-minutes"], s.builds.pollMinutes);
66
+ else
67
+ comment(1, "poll-minutes: only with trigger github-action");
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)");
89
+ else {
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 slot holds what `factory plugins` prints for it: the settings'
96
+ // own plug-ins, 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 slot of SLOTS.filter((x) => SLOT_SHAPE[x].phase === phase)) {
102
+ const { key, list } = SLOT_SHAPE[slot];
103
+ const path = ["plugins", phase, key];
104
+ const found = used.filter((p) => p.slot === slot);
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
+ }
128
+ }
129
+ }
130
+ block(["auto-merge"]);
131
+ put(["auto-merge", "allow"], s.autoMerge.allow);
132
+ put(["auto-merge", "deny"], s.autoMerge.deny);
133
+ put(["auto-merge", "commands"], s.autoMerge.commands);
134
+ if (s.ciReview === null)
135
+ comment(0, "ci-review: off");
136
+ else {
137
+ block(["ci-review"]);
138
+ put(["ci-review", "commands"], s.ciReview.commands);
139
+ }
140
+ if (s.site === null)
141
+ comment(0, "site: off");
142
+ else {
143
+ const site = s.site;
144
+ block(["site"]);
145
+ put(["site", "start"], site.start);
146
+ put(["site", "url"], site.url);
147
+ if (site.designGuide === null)
148
+ comment(1, "design-guide: none (default)");
149
+ else
150
+ put(["site", "design-guide"], site.designGuide);
151
+ if (site.pages === null)
152
+ comment(1, "pages: found by the factory (default)");
153
+ else
154
+ put(["site", "pages"], site.pages);
155
+ put(["site", "widths"], site.widths);
156
+ put(["site", "hide"], site.hide);
157
+ put(["site", "checks"], site.checks);
158
+ put(["site", "max-pages"], site.maxPages);
159
+ put(["site", "start-minutes"], site.startMinutes);
160
+ put(["site", "accessibility"], site.accessibility);
161
+ put(["site", "new-values"], site.newValues);
162
+ }
163
+ block(["session-minutes"]);
164
+ for (const [k, v] of Object.entries(s.sessionMinutes))
165
+ put(["session-minutes", k], v);
166
+ block(["rules"]);
167
+ put(["rules", "small-change-lines"], s.rules.smallChangeLines);
168
+ put(["rules", "review-rounds"], s.rules.reviewRounds);
169
+ // Each default's mark lines up with the others, two spaces past the
170
+ // longest line that carries one.
171
+ const marked = lines.filter((l) => l.byDefault);
172
+ const at = Math.max(0, ...marked.map((l) => l.text.length)) + 2;
173
+ return lines.map((l) => l.byDefault ? `${l.text.padEnd(at)}# default` : l.text);
174
+ }
@@ -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"));