@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/init.d.mts CHANGED
@@ -1,7 +1,5 @@
1
- import { type CodeHost } from "./code-host/index.mts";
2
- import { type Check } from "./doctor.mts";
3
- import { type Runner } from "./runner/index.mts";
4
- import type { Tickets } from "./tickets/types.mts";
1
+ import { type Registry } from "./tools.mts";
2
+ import { type Check } from "./setup.mts";
5
3
  /** The questions init asks. Each is answered at the terminal, and in tests
6
4
  * from a script. */
7
5
  export type Ask = {
@@ -15,7 +13,9 @@ export type Ask = {
15
13
  select(message: string, choices: {
16
14
  name: string;
17
15
  value: string;
18
- }[]): Promise<string>;
16
+ }[],
17
+ /** The value chosen when the person picks nothing else. */
18
+ fallback?: string): Promise<string>;
19
19
  confirm(message: string, fallback: boolean): Promise<boolean>;
20
20
  /** Read without echoing what is typed. */
21
21
  secret(message: string): Promise<string>;
@@ -27,14 +27,12 @@ export type InitDeps = {
27
27
  out: (line: string) => void;
28
28
  /** The `origin` remote's address, or null without one. */
29
29
  remote: () => string | null;
30
- open: (repository: string) => {
31
- codeHost: CodeHost;
32
- runner: Runner;
33
- tickets: Tickets;
34
- };
30
+ tools: Registry;
35
31
  sync: () => Promise<number>;
36
- /** The files a sync with these settings would write or delete. */
37
- 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[];
38
36
  /** Runs a command attached to the terminal, as `claude setup-token`. */
39
37
  interactive: (argv: string[]) => Promise<number>;
40
38
  hasCommand: (name: string) => boolean;
@@ -50,8 +48,8 @@ export type InitDeps = {
50
48
  };
51
49
  /** The repository and code host a remote's address names, or null for one
52
50
  * on a code host the factory does not support. */
53
- export declare function parseRemote(url: string): {
54
- codeHost: "github";
51
+ export declare function parseRemote(url: string, tools?: Registry): {
52
+ codeHost: string;
55
53
  repository: string;
56
54
  } | null;
57
55
  export declare function main(_argv: string[], d: InitDeps): Promise<number>;
package/dist/init.mjs CHANGED
@@ -11,34 +11,24 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync
11
11
  import { tmpdir } from "node:os";
12
12
  import { dirname, join } from "node:path";
13
13
  import { isMap, parseDocument } from "yaml";
14
- import { openCodeHost } from "./code-host/index.mjs";
14
+ import { builtOf, secretSteps, TOOLS, } from "./tools.mjs";
15
15
  import { NeedsScopeError } from "./code-host/types.mjs";
16
- import { columnsOf, fieldNamesOf, parseSettings, repoRoot, SETTINGS_FILE, SettingsError, } from "./config.mjs";
17
- import { checks as doctorChecks, doctorDeps, line, } from "./doctor.mjs";
18
- import { AGENT_KEY, AGENT_TOKEN, neededSecrets, PART_TEXT, PARTS, partsOn, resolveParts, SIGNING_KEY, tokenNames, tokenNeeds, } from "./parts.mjs";
16
+ import { columnsOf, fieldNamesOf, parseSettings, POLL_MINUTES, repoRoot, SETTINGS_FILE, SettingsError, } from "./config.mjs";
17
+ import { checks as doctorChecks, doctorDeps, line } from "./doctor.mjs";
18
+ import { branchDeps, needDefaultBranch, NoDefaultBranch, } from "./lib/default-branch.mjs";
19
+ import { hasCommand, noTerminal } from "./lib/has-command.mjs";
20
+ import { DEFAULT_RUNNER } from "./runner/index.mjs";
21
+ import { listed } from "./lib/listed.mjs";
22
+ import { neededSecrets, PART_TEXT, PARTS, partsOn, resolveParts, SIGNING_KEY, } from "./parts.mjs";
19
23
  import { CONTEXT as REVIEW_VERDICT } from "./review-verdict.mjs";
20
- import { openRunner } from "./runner/index.mjs";
24
+ import { RULE } from "./setup.mjs";
21
25
  import { differences, PACKAGE, plan as syncPlan } from "./sync.mjs";
22
- import { githubTickets } from "./tickets/github.mjs";
23
- import { ghTransport } from "./tickets/transport.mjs";
24
- import { gh } from "./lib/gh.mjs";
25
26
  import { DEFAULT_COLUMNS } from "./lib/work-status.mjs";
26
- /** Today's one choice of each tool, by the name a setting gives it. */
27
- const TOOLS = {
28
- codeHost: { github: "GitHub" },
29
- tickets: { github: "GitHub Issues" },
30
- runner: { "github-actions": "GitHub Actions" },
31
- agent: "Claude Code",
32
- };
33
- /** The coding agent's command, and the one that makes its token. */
34
- const AGENT = {
35
- command: "claude",
36
- token: ["claude", "setup-token"],
37
- };
38
- /** The rule that requires the review's verdict, by name, so removing it is
39
- * deleting that one rule. */
40
- const RULE = "Software factory";
41
27
  const SIGNING_TITLE = "software factory builds";
28
+ /** Where each release's poller image is published. */
29
+ const POLLER_IMAGE = "ghcr.io/davidbyoung/software-factory-poller";
30
+ /** A month of runs at each interval the scheduled poller allows. */
31
+ const RUNS_A_MONTH = (minutes) => (30 * 24 * 60) / minutes;
42
32
  const AGAIN = "Run npx --no-install factory init again to add it.";
43
33
  /** The columns and fields the board sync uses: the settings' names where
44
34
  * they rename one, and none for one they set to none. */
@@ -62,23 +52,15 @@ function boardShape(s) {
62
52
  }
63
53
  /** The repository and code host a remote's address names, or null for one
64
54
  * on a code host the factory does not support. */
65
- export function parseRemote(url) {
66
- const match = /^(?:git@github\.com:|(?:https|ssh):\/\/(?:git@)?github\.com\/)([^/]+)\/([^/]+?)(?:\.git)?\/?$/.exec(url.trim());
67
- return match
68
- ? { codeHost: "github", repository: `${match[1]}/${match[2]}` }
69
- : null;
55
+ export function parseRemote(url, tools = TOOLS) {
56
+ for (const [name, host] of Object.entries(tools.codeHost)) {
57
+ const repository = host.repositoryOf(url);
58
+ if (repository)
59
+ return { codeHost: name, repository };
60
+ }
61
+ return null;
70
62
  }
71
63
  const message = (e) => (e instanceof Error ? e.message : String(e));
72
- /** Items as a sentence lists them: "a", "a and b", "a, b, and c". */
73
- const listed = (items) => items.length < 3
74
- ? items.join(" and ")
75
- : `${items.slice(0, -1).join(", ")}, and ${items.at(-1)}`;
76
- /** What a token must be able to do, in words. */
77
- const NEED_TEXT = {
78
- push: "push a branch",
79
- workflows: "change a workflow's file",
80
- board: "write the board",
81
- };
82
64
  /** Deletes a key, then any map the deletion left empty above it. */
83
65
  function remove(doc, path) {
84
66
  if (!doc.hasIn(path))
@@ -98,10 +80,10 @@ export async function main(_argv, d) {
98
80
  writeFileSync(at(path), text);
99
81
  };
100
82
  const remote = d.remote();
101
- const found = remote ? parseRemote(remote) : null;
83
+ const found = remote ? parseRemote(remote, d.tools) : null;
102
84
  if (!found) {
103
85
  d.out(remote
104
- ? `The origin remote, ${remote}, is not on a code host the factory supports: ${Object.values(TOOLS.codeHost).join(", ")}.`
86
+ ? `The origin remote, ${remote}, is not on a code host the factory supports: ${listed(Object.values(d.tools.codeHost).map((t) => t.label))}.`
105
87
  : "This is not a git repository with an origin remote. Run it in your repository's checkout.");
106
88
  return 1;
107
89
  }
@@ -112,7 +94,7 @@ export async function main(_argv, d) {
112
94
  let settings = null;
113
95
  if (settingsText !== null) {
114
96
  try {
115
- settings = parseSettings(doc.toJS(), (p) => existsSync(at(p)));
97
+ settings = parseSettings(doc.toJS(), (p) => existsSync(at(p)), builtOf(d.tools));
116
98
  }
117
99
  catch (e) {
118
100
  d.out(`${SETTINGS_FILE}: ${message(e)}`);
@@ -121,24 +103,70 @@ export async function main(_argv, d) {
121
103
  }
122
104
  }
123
105
  const hasPackage = existsSync(at("package.json"));
124
- const agentInstalled = d.hasCommand(AGENT.command);
106
+ // A kind with one tool is that tool; with several, the settings' choice,
107
+ // or one asked for below.
108
+ const only = (r) => {
109
+ const names = Object.keys(r);
110
+ return names.length === 1 ? names[0] : null;
111
+ };
112
+ const named = {
113
+ tickets: settings?.tickets.type ?? null,
114
+ runner: settings?.builds.runner ?? null,
115
+ };
116
+ const choice = {
117
+ tickets: only(d.tools.tickets) ?? named.tickets,
118
+ runner: only(d.tools.runner) ?? named.runner,
119
+ };
120
+ const agentName = Object.keys(d.tools.agent)[0];
121
+ const agent = d.tools.agent[agentName];
122
+ const shown = (kind) => {
123
+ const tools = d.tools[kind];
124
+ if (only(tools))
125
+ return tools[only(tools)].label;
126
+ return choice[kind]
127
+ ? `${tools[choice[kind]].label}, from your settings`
128
+ : "chosen below";
129
+ };
125
130
  d.out(`Setting up the software factory for ${repository}`);
126
131
  d.out("");
127
132
  d.out("Found");
128
133
  const row = (label, text) => d.out(` ${label.padEnd(14)} ${text}`);
129
- row("Code host", `${TOOLS.codeHost.github} (from your git remote)`);
130
- row("Tickets", TOOLS.tickets.github);
131
- row("Coding agent", agentInstalled
132
- ? TOOLS.agent
133
- : `${TOOLS.agent}, which is not installed: sessions and its token need it`);
134
- row("Cloud builds", TOOLS.runner["github-actions"]);
134
+ row("Code host", `${d.tools.codeHost[found.codeHost].label} (from your git remote)`);
135
+ row("Tickets", shown("tickets"));
136
+ row("Coding agent", agent.setup.found?.({ hasCommand: d.hasCommand }) ?? agent.label);
137
+ row("Cloud builds", shown("runner"));
135
138
  row("package.json", hasPackage ? "yes" : "none, so a private one will be created");
136
139
  row("Settings", settingsText === null ? "none yet" : SETTINGS_FILE);
137
140
  row("Board", settings?.tickets.board != null
138
141
  ? `${settings.tickets.board}, from your settings`
139
142
  : "none yet");
140
143
  d.out("");
141
- const { codeHost, runner, tickets } = d.open(repository);
144
+ const pick = async (kind, question) => {
145
+ const tools = d.tools[kind];
146
+ if (only(tools))
147
+ return only(tools);
148
+ const first = named[kind];
149
+ const names = Object.keys(tools).sort((a, b) => a === first ? -1 : b === first ? 1 : 0);
150
+ return d.ask.select(question, names.map((n) => ({ name: tools[n].label, value: n })));
151
+ };
152
+ const chosen = {
153
+ codeHost: found.codeHost,
154
+ tickets: await pick("tickets", "Which ticket system?"),
155
+ runner: await pick("runner", "Where do cloud builds run?"),
156
+ agent: agentName,
157
+ };
158
+ const codeHost = d.tools.codeHost[chosen.codeHost].open(repository);
159
+ const runner = d.tools.runner[chosen.runner].open(repository);
160
+ const tickets = await d.tools.tickets[chosen.tickets].open({ repository, board: null }, settings);
161
+ const context = (parts) => ({
162
+ repository,
163
+ root: d.root,
164
+ parts: new Set(parts),
165
+ chosen,
166
+ settings,
167
+ hasCommand: d.hasCommand,
168
+ opened: { codeHost, runner, tickets },
169
+ });
142
170
  let secrets;
143
171
  try {
144
172
  secrets = await runner.secretNames();
@@ -147,9 +175,11 @@ export async function main(_argv, d) {
147
175
  d.out(`Could not reach the code host: ${message(e)}`);
148
176
  return 1;
149
177
  }
150
- const before = partsOn(settings, secrets);
178
+ const isSet = (n) => secrets.includes(n);
179
+ const cloudNeeds = secretSteps(d.tools, context(["cloud"])).flatMap((s) => s.step.needs.filter((n) => n.part === "cloud"));
180
+ const before = partsOn(settings, secrets, cloudNeeds);
151
181
  const first = settingsText === null;
152
- const chosen = await d.ask.checkbox("Which parts do you want?", PARTS.map((part) => ({
182
+ const chosenParts = await d.ask.checkbox("Which parts do you want?", PARTS.map((part) => ({
153
183
  name: PART_TEXT[part].name,
154
184
  description: PART_TEXT[part].gives,
155
185
  value: part,
@@ -157,10 +187,11 @@ export async function main(_argv, d) {
157
187
  ? part === "review" || part === "board" || part === "cloud"
158
188
  : before.has(part),
159
189
  })));
160
- const resolved = resolveParts(before, new Set(chosen));
190
+ const resolved = resolveParts(before, new Set(chosenParts));
161
191
  const parts = resolved.parts;
162
192
  for (const note of resolved.notes)
163
193
  d.out(note);
194
+ const removed = PARTS.filter((p) => before.has(p) && !parts.has(p));
164
195
  // The board: the one in the settings, or one chosen now.
165
196
  const boardOps = tickets.board;
166
197
  let board = parts.has("board")
@@ -196,20 +227,50 @@ export async function main(_argv, d) {
196
227
  .split(",")
197
228
  .map((x) => x.trim())
198
229
  .filter(Boolean);
230
+ // Where the poller runs, asked only when the part is new: a re-run keeps
231
+ // what the settings say, as it does every value already set.
232
+ let trigger = settings?.builds.trigger ?? "manual";
233
+ let pollMinutes = null;
234
+ if (parts.has("from-board") && !before.has("from-board")) {
235
+ trigger = (await d.ask.select("Where does the poller run?", [
236
+ {
237
+ name: "A schedule on GitHub Actions, every 5 minutes, nothing to host",
238
+ value: "github-action",
239
+ },
240
+ { name: "A server you host, within a minute", value: "own-server" },
241
+ ]));
242
+ if (trigger === "github-action" &&
243
+ (await codeHost.isPrivate().catch(() => true))) {
244
+ d.out("Each run bills at least one Actions minute on a private repository.");
245
+ pollMinutes = Number(await d.ask.select("How often?", POLL_MINUTES.map((m) => ({
246
+ name: `Every ${m} minutes, ${RUNS_A_MONTH(m).toLocaleString("en-US")} runs a month`,
247
+ value: String(m),
248
+ })), "30"));
249
+ }
250
+ }
199
251
  // The settings as they will stand, keeping every other key and comment.
200
252
  if (!doc.has("version"))
201
- doc.set("version", 1);
253
+ doc.set("version", 2);
202
254
  if (!doc.has("repository"))
203
255
  doc.set("repository", repository);
256
+ // A tool other than the one a setting defaults to is written down.
257
+ if ((doc.getIn(["tickets", "type"]) ?? "github") !== chosen.tickets)
258
+ doc.setIn(["tickets", "type"], chosen.tickets);
259
+ if ((doc.getIn(["builds", "runner"]) ?? DEFAULT_RUNNER) !== chosen.runner)
260
+ doc.setIn(["builds", "runner"], chosen.runner);
204
261
  if (parts.has("board") && typeof board === "number")
205
262
  doc.setIn(["tickets", "board"], board);
206
263
  if (!parts.has("board"))
207
264
  for (const key of ["board", "columns", "fields"])
208
265
  remove(doc, ["tickets", key]);
209
266
  if (parts.has("from-board"))
210
- doc.setIn(["builds", "trigger"], "own-server");
267
+ doc.setIn(["builds", "trigger"], trigger);
211
268
  else if (before.has("from-board"))
212
269
  remove(doc, ["builds", "trigger"]);
270
+ if (pollMinutes !== null && pollMinutes !== 5)
271
+ doc.setIn(["builds", "poll-minutes"], pollMinutes);
272
+ if (!parts.has("from-board") || trigger !== "github-action")
273
+ remove(doc, ["builds", "poll-minutes"]);
213
274
  if (parts.has("auto-merge"))
214
275
  doc.setIn(["auto-merge", "allow"], allow);
215
276
  else
@@ -220,28 +281,43 @@ export async function main(_argv, d) {
220
281
  doc.setIn(["ci-review", "commands"], []);
221
282
  if (!parts.has("review"))
222
283
  doc.delete("ci-review");
284
+ // The ticket system's own values: asked for once, and taken out with
285
+ // the part that needed them.
286
+ const values = (ps) => (d.tools.tickets[chosen.tickets].setup.steps?.(context(ps)) ?? []).filter((s) => s.kind === "value");
287
+ for (const step of values(parts)) {
288
+ if (step.part !== null && !parts.has(step.part))
289
+ continue;
290
+ if (doc.hasIn(["tickets", step.key]))
291
+ continue;
292
+ doc.setIn(["tickets", step.key], await d.ask.input(step.ask, step.fallback ?? ""));
293
+ }
294
+ for (const step of values(removed))
295
+ if (step.part !== null && removed.includes(step.part))
296
+ remove(doc, ["tickets", step.key]);
223
297
  // The secrets: those the parts read that are not set, or all of them when
224
298
  // you choose to replace them.
225
- const needed = neededSecrets(parts);
226
- const alreadySet = [
227
- ...new Set(needed.flatMap((n) => n.anyOf.filter((x) => secrets.includes(x)))),
228
- ];
299
+ const steps = secretSteps(d.tools, context(parts));
300
+ const needed = neededSecrets(parts, steps);
301
+ const alreadySet = [...new Set(needed.flatMap((n) => n.anyOf.filter(isSet)))];
229
302
  let replace = false;
230
303
  if (alreadySet.length)
231
304
  replace = await d.ask.confirm(alreadySet.length === 1
232
305
  ? "1 secret these parts read is already set. Replace it?"
233
306
  : `${alreadySet.length} secrets these parts read are already set. Replace them?`, false);
234
- const missing = (names) => replace || !names.some((n) => secrets.includes(n));
235
- const wantsAgent = (parts.has("review") || parts.has("cloud")) &&
236
- missing([AGENT_TOKEN, AGENT_KEY]);
237
- const tokenTo = tokenNames(parts).filter((n) => missing([n]));
238
- const wantsKey = parts.has("signing") && missing([SIGNING_KEY]);
239
- const removed = PARTS.filter((p) => before.has(p) && !parts.has(p));
240
- const stillRead = new Set(neededSecrets(parts).flatMap((n) => n.anyOf));
307
+ const unmet = (step) => step.needs.some((n) => (n.part === null || parts.has(n.part)) && !n.anyOf.some(isSet));
308
+ const asked = steps
309
+ .filter(({ step }) => replace || unmet(step))
310
+ .map(({ step }) => ({
311
+ step,
312
+ names: step.storeAs.filter((n) => replace || !isSet(n)),
313
+ }))
314
+ .filter((a) => a.names.length > 0);
315
+ const wantsKey = parts.has("signing") && (replace || !isSet(SIGNING_KEY));
316
+ const stillRead = new Set(needed.flatMap((n) => n.anyOf));
241
317
  const deletable = [
242
- ...new Set(neededSecrets(new Set(removed))
318
+ ...new Set(neededSecrets(new Set(removed), secretSteps(d.tools, context(removed)))
243
319
  .flatMap((n) => n.anyOf)
244
- .filter((n) => secrets.includes(n) && !stillRead.has(n))),
320
+ .filter((n) => isSet(n) && !stillRead.has(n))),
245
321
  ];
246
322
  // The plan.
247
323
  const newText = String(doc);
@@ -254,15 +330,16 @@ export async function main(_argv, d) {
254
330
  ];
255
331
  let syncs;
256
332
  try {
257
- syncs = d.syncChanges(newText);
333
+ syncs = await d.syncChanges(newText, () => codeHost.defaultBranch());
258
334
  }
259
335
  catch (e) {
260
- 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)}`);
261
339
  return 1;
262
340
  }
263
341
  const toStore = [
264
- ...(wantsAgent ? [agentInstalled ? AGENT_TOKEN : AGENT_KEY] : []),
265
- ...tokenTo,
342
+ ...asked.flatMap((a) => a.names),
266
343
  ...(wantsKey ? [SIGNING_KEY] : []),
267
344
  ];
268
345
  d.out("");
@@ -326,62 +403,37 @@ export async function main(_argv, d) {
326
403
  const synced = await d.sync();
327
404
  if (synced !== 0)
328
405
  d.out("The sync failed, as above.");
329
- // The coding agent's token.
330
- if (wantsAgent) {
331
- let value = "";
332
- if (agentInstalled) {
333
- d.out("");
334
- d.out(`The coding agent's token: running ${AGENT.token.join(" ")}...`);
335
- await d.interactive(AGENT.token);
336
- value = await d.ask.secret("Paste the token it printed (leave empty to do this later):");
337
- }
338
- else {
339
- value = await d.ask.secret("Paste an API key from the Claude Console (leave empty to do this later):");
340
- }
341
- const secret = agentInstalled ? AGENT_TOKEN : AGENT_KEY;
342
- if (value) {
343
- await runner.setSecret(secret, value);
344
- d.out(`Stored as ${secret}.`);
345
- }
346
- else
347
- d.out(`No ${secret} stored. ${AGAIN}`);
348
- }
349
- // The one access token.
406
+ // Each tool's secrets, in the tools' order.
350
407
  let tokenAccount = null;
351
- if (tokenTo.length) {
352
- const scopes = codeHost.scopesFor(tokenNeeds(parts));
353
- const page = codeHost.newTokenPage(scopes, `software factory: ${repository}`);
354
- d.out("");
355
- d.out(`An access token: opening ${page}`);
356
- d.out(`Check that ${listed(scopes)} ${scopes.length === 1 ? "is" : "are"} ticked, choose an expiry, and generate it.`);
357
- d.openPage(page);
408
+ for (const { step, names } of asked) {
409
+ for (const l of step.intro)
410
+ d.out(l);
411
+ if (step.get && "page" in step.get)
412
+ d.openPage(step.get.page);
413
+ if (step.get && "command" in step.get)
414
+ await d.interactive(step.get.command);
358
415
  for (;;) {
359
- const value = await d.ask.secret("Paste it (leave empty to do this later):");
416
+ const value = await d.ask.secret(step.prompt);
360
417
  if (!value) {
361
- d.out(`No token stored. ${AGAIN}`);
418
+ d.out(`${step.skipped} ${AGAIN}`);
362
419
  break;
363
420
  }
364
- let owned;
365
- try {
366
- owned = await codeHost.tokenOwner(value);
367
- }
368
- catch (e) {
369
- d.out(`${message(e)}. Paste another.`);
370
- continue;
371
- }
372
- const lacking = owned.scopes
373
- ? scopes.filter((x) => !owned.scopes.includes(x))
374
- : [];
375
- if (lacking.length) {
376
- d.out(`That token lacks ${listed(lacking)}. Make one with every scope checked, and paste it.`);
377
- continue;
378
- }
379
- if (owned.scopes === null)
380
- d.out(`The code host does not say what this token may do: make sure it can ${listed(tokenNeeds(parts).map((n) => NEED_TEXT[n]))}.`);
381
- for (const n of tokenTo)
421
+ let checked = { lines: [] };
422
+ if (step.verify)
423
+ try {
424
+ checked = await step.verify(value);
425
+ }
426
+ catch (e) {
427
+ d.out(message(e));
428
+ continue;
429
+ }
430
+ for (const l of checked.lines)
431
+ d.out(l);
432
+ for (const n of names)
382
433
  await runner.setSecret(n, value);
383
- tokenAccount = owned.account;
384
- d.out(`It belongs to ${owned.account}. Stored as ${tokenTo.join(", ")}.`);
434
+ if (checked.account !== undefined)
435
+ tokenAccount = checked.account;
436
+ d.out(step.stored(names, checked.account));
385
437
  break;
386
438
  }
387
439
  }
@@ -434,14 +486,20 @@ export async function main(_argv, d) {
434
486
  const app = codeHost.reviewAppPage();
435
487
  if (parts.has("review") && app)
436
488
  left.push(`Install the app the review posts through: ${app}`);
437
- if (parts.has("from-board") && typeof board === "number")
489
+ if (parts.has("from-board") &&
490
+ trigger === "own-server" &&
491
+ typeof board === "number")
438
492
  left.push([
439
- "Host the poller, which starts a build when a card moves to Ready, with:",
493
+ `Run the poller's image, ${POLLER_IMAGE}:${d.packageVersion}, where you host it, with:`,
440
494
  ` FACTORY_REPOSITORY=${repository}`,
441
495
  ` FACTORY_BOARD_OWNER=${owner}`,
442
496
  ` FACTORY_BOARD_NUMBER=${board}`,
443
497
  " FACTORY_BOARD_TOKEN=the access token you just made",
444
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}`);
445
503
  left.push("Commit this on a branch, open a pull request, and merge it.");
446
504
  d.out("Nothing is committed. Left to do:");
447
505
  left.forEach((step, i) => d.out(` ${i + 1}. ${step}`));
@@ -457,13 +515,18 @@ async function terminalAsk() {
457
515
  const p = await import("@inquirer/prompts");
458
516
  return {
459
517
  checkbox: (message, choices) => p.checkbox({ message, choices }),
460
- select: (message, choices) => p.select({ message, choices }),
518
+ select: (message, choices, fallback) => p.select({ message, choices, default: fallback }),
461
519
  confirm: (message, fallback) => p.confirm({ message, default: fallback }),
462
520
  secret: (message) => p.password({ message, mask: "•" }),
463
521
  input: (message, fallback) => p.input({ message, default: fallback }),
464
522
  };
465
523
  }
466
524
  export async function run(argv) {
525
+ const terminal = noTerminal("init");
526
+ if (terminal) {
527
+ console.log(terminal);
528
+ return 1;
529
+ }
467
530
  let root;
468
531
  try {
469
532
  root = repoRoot();
@@ -489,23 +552,18 @@ export async function run(argv) {
489
552
  return null;
490
553
  }
491
554
  },
492
- open: (repository) => ({
493
- codeHost: openCodeHost(repository),
494
- runner: openRunner(repository),
495
- tickets: githubTickets({
496
- transport: ghTransport(gh),
497
- repository,
498
- board: null,
499
- }),
500
- }),
555
+ tools: TOOLS,
501
556
  sync: async () => (await import("./sync.mjs")).run([]),
502
- 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) => {
503
560
  const raw = parseDocument(text).toJS();
504
561
  const s = parseSettings(raw, (p) => existsSync(join(root, p)));
505
- return differences(root, syncPlan(PACKAGE, root, s));
562
+ const branch = await needDefaultBranch({ ...branchDeps(root), host });
563
+ return differences(root, syncPlan(PACKAGE, root, s, branch));
506
564
  },
507
565
  interactive: async (argv2) => spawnSync(argv2[0], argv2.slice(1), { stdio: "inherit" }).status ?? 1,
508
- hasCommand: (name) => !spawnSync(name, ["--version"], { stdio: "ignore" }).error,
566
+ hasCommand,
509
567
  openPage: (url) => {
510
568
  const opener = process.platform === "darwin"
511
569
  ? "open"
@@ -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>;