@davidbyoung/software-factory 0.1.6 → 0.1.8

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 (50) hide show
  1. package/dist/agent/claude-code.d.mts +16 -0
  2. package/dist/agent/claude-code.mjs +75 -3
  3. package/dist/agent/index.d.mts +1 -1
  4. package/dist/agent/index.mjs +1 -1
  5. package/dist/agent/types.d.mts +24 -0
  6. package/dist/agent/types.mjs +3 -0
  7. package/dist/board.mjs +9 -11
  8. package/dist/code-host/github.mjs +4 -0
  9. package/dist/code-host/types.d.mts +2 -0
  10. package/dist/columns-suggest.d.mts +52 -0
  11. package/dist/columns-suggest.mjs +259 -0
  12. package/dist/config.d.mts +6 -1
  13. package/dist/config.mjs +45 -8
  14. package/dist/doctor.d.mts +3 -0
  15. package/dist/doctor.mjs +133 -5
  16. package/dist/explain.mjs +1 -1
  17. package/dist/init.mjs +155 -7
  18. package/dist/lib/work-status.d.mts +10 -7
  19. package/dist/lib/work-status.mjs +20 -19
  20. package/dist/npmrc.d.mts +29 -0
  21. package/dist/npmrc.mjs +98 -0
  22. package/dist/poller.mjs +2 -2
  23. package/dist/preset-commands.d.mts +0 -2
  24. package/dist/preset-commands.mjs +2 -12
  25. package/dist/preset.d.mts +4 -0
  26. package/dist/preset.mjs +10 -0
  27. package/dist/runner/github-actions.mjs +47 -10
  28. package/dist/runner/types.d.mts +13 -0
  29. package/dist/setup.d.mts +3 -1
  30. package/dist/status.mjs +1 -1
  31. package/dist/sync.d.mts +7 -0
  32. package/dist/sync.mjs +66 -2
  33. package/dist/ticket.mjs +1 -1
  34. package/dist/tickets/github.mjs +10 -2
  35. package/dist/tickets/types.d.mts +3 -0
  36. package/dist/tools.d.mts +4 -1
  37. package/dist/tools.mjs +9 -2
  38. package/docs/configuration.md +33 -5
  39. package/docs/design.md +15 -0
  40. package/docs/developing.md +15 -6
  41. package/docs/existing-repo.md +104 -31
  42. package/docs/github/by-hand.md +4 -0
  43. package/docs/github/reference.md +5 -0
  44. package/docs/github/setup.md +141 -8
  45. package/docs/limitations.md +0 -8
  46. package/docs/presets.md +5 -9
  47. package/docs/removing.md +2 -2
  48. package/package.json +1 -1
  49. package/settings.schema.json +45 -15
  50. package/skills/factory-deps/SKILL.md +4 -0
package/dist/npmrc.mjs ADDED
@@ -0,0 +1,98 @@
1
+ // What the factory reads from the repository's own `.npmrc`: the variables
2
+ // its sign-in lines read, which the workflows set from secrets of the same
3
+ // names, and the registries it names, which Dependabot has to know.
4
+ import { existsSync, readFileSync } from "node:fs";
5
+ import { join } from "node:path";
6
+ export const NPMRC = ".npmrc";
7
+ const SYNC = "npx --no-install factory sync";
8
+ const PUBLIC_REGISTRY = "https://registry.npmjs.org/";
9
+ const SIGN_IN = /:(_authToken|_auth|_password|username)$/;
10
+ /** npm's own pattern (`@npmcli/config`'s `env-replace.js`): an odd run of
11
+ * backslashes before `${` makes it text. */
12
+ const VARIABLE = /(?<!\\)(\\*)\$\{([^${}?]+)(\?)?\}/g;
13
+ /** The key and value of each setting line, as npm's `ini` reads them. */
14
+ function entries(text) {
15
+ const out = [];
16
+ for (const raw of text.split(/\r?\n/)) {
17
+ const line = raw.trim();
18
+ if (!line || line.startsWith("#") || line.startsWith(";"))
19
+ continue;
20
+ const at = line.indexOf("=");
21
+ if (at < 0)
22
+ continue;
23
+ const key = line.slice(0, at).trim();
24
+ let value = line.slice(at + 1).trim();
25
+ if (/^(".*"|'.*')$/.test(value))
26
+ value = value.slice(1, -1);
27
+ out.push({ key, value });
28
+ }
29
+ return out;
30
+ }
31
+ /** The variables a value reads. */
32
+ function variables(value) {
33
+ const out = [];
34
+ for (const m of value.matchAll(VARIABLE))
35
+ if (m[1].length % 2 === 0)
36
+ out.push(m[2]);
37
+ return out;
38
+ }
39
+ export function readNpmrc(text) {
40
+ const found = { names: [], signIns: [], registries: [] };
41
+ if (!text)
42
+ return found;
43
+ for (const { key, value } of entries(text)) {
44
+ if (key === "registry" || /^@[^:]+:registry$/.test(key)) {
45
+ if (!found.registries.includes(value))
46
+ found.registries.push(value);
47
+ continue;
48
+ }
49
+ if (!SIGN_IN.test(key))
50
+ continue;
51
+ for (const name of variables(value)) {
52
+ found.signIns.push({ name, key });
53
+ if (!found.names.includes(name))
54
+ found.names.push(name);
55
+ }
56
+ }
57
+ return found;
58
+ }
59
+ /** The `.npmrc` at the root, read; nothing when there is none. */
60
+ export function npmrcAt(root) {
61
+ const path = join(root, NPMRC);
62
+ return readNpmrc(existsSync(path) ? readFileSync(path, "utf8") : null);
63
+ }
64
+ /** Why a name can't be set from a secret, or null when it can. */
65
+ export function refusal(name) {
66
+ if (name === "GITHUB_TOKEN")
67
+ return null;
68
+ if (name.startsWith("GITHUB_"))
69
+ return `${NPMRC} reads \${${name}} to sign in, and GitHub refuses a secret whose name starts with GITHUB_. Rename it in ${NPMRC}, then run: ${SYNC}`;
70
+ if (["HOME", "PATH", "CI"].includes(name) || /^(RUNNER|ACTIONS)_/.test(name))
71
+ return `${NPMRC} reads \${${name}} to sign in, and the runner sets ${name} for itself. Rename it in ${NPMRC}, then run: ${SYNC}`;
72
+ return null;
73
+ }
74
+ /** The first refusal among the names, or null. */
75
+ export const firstRefusal = (n) => n.names.map(refusal).find((r) => r !== null) ?? null;
76
+ const bare = (url) => url.replace(/^[a-z]+:/i, "").replace(/\/+$/, "");
77
+ /** The registry a sign-in line is for: the registry URL whose host and
78
+ * path its key starts with, the longest when several do, or else the
79
+ * key's own `//host/path/`. */
80
+ export function addressOf(n, name) {
81
+ const key = n.signIns.find((s) => s.name === name)?.key ?? "";
82
+ const at = key.replace(SIGN_IN, "");
83
+ const match = n.registries
84
+ .filter((r) => at === bare(r) || at.startsWith(`${bare(r)}/`))
85
+ .sort((a, b) => bare(b).length - bare(a).length)[0];
86
+ return match ?? at;
87
+ }
88
+ /** The registries Dependabot has to be told, the public one aside. */
89
+ export const privateRegistries = (n) => n.registries.filter((r) => bare(r) !== bare(PUBLIC_REGISTRY));
90
+ /** The registry `.npmrc` sends a package's scope to, or null. */
91
+ export function npmrcRegistry(text, pkg) {
92
+ if (!text || !pkg.startsWith("@"))
93
+ return null;
94
+ const scope = pkg.split("/")[0];
95
+ const found = entries(text).find((e) => e.key === `${scope}:registry`);
96
+ return found ? found.value : null;
97
+ }
98
+ export { bare as bareRegistry };
package/dist/poller.mjs CHANGED
@@ -49,7 +49,7 @@ export function startMarker() {
49
49
  export function columnsFrom(env) {
50
50
  return {
51
51
  ...DEFAULT_COLUMNS,
52
- Ready: env.FACTORY_READY_COLUMN?.trim() || "Ready",
52
+ Ready: [env.FACTORY_READY_COLUMN?.trim() || "Ready"],
53
53
  };
54
54
  }
55
55
  /** What a refused dispatch's comment says GitHub answered: the status, and
@@ -224,7 +224,7 @@ export async function tick(d, state) {
224
224
  }
225
225
  }
226
226
  export function onceSettings(s) {
227
- return { board: s.tickets.board, ready: columnsOf(s).Ready };
227
+ return { board: s.tickets.board, ready: columnsOf(s).Ready?.[0] ?? null };
228
228
  }
229
229
  /** One pass, for a scheduled run: the board and the Ready column come from
230
230
  * the settings, the board's owner is the repository's, and only the token
@@ -34,8 +34,6 @@ export declare function installError(name: string, stderr: string, registry: str
34
34
  /** Whether a group in `.github/dependabot.yml` has the package as its only
35
35
  * pattern. */
36
36
  export declare function hasOwnGroup(text: string | null, pkg: string): Promise<boolean>;
37
- /** The registry `.npmrc` sends a package's scope to, or null. */
38
- export declare function npmrcRegistry(text: string | null, pkg: string): string | null;
39
37
  /** The lines `preset add` ends with for what Dependabot still needs. */
40
38
  export declare function nextLines(dependabot: string | null, npmrc: string | null, pkg: string): Promise<string[]>;
41
39
  export declare function add(argv: string[], d: PresetDeps): Promise<number>;
@@ -14,6 +14,7 @@ import { STATUS_CODES } from "node:http";
14
14
  import { dirname, join, relative, sep } from "node:path";
15
15
  import { filesDeps, parseChoices, repoRoot, resolveFiles, SETTINGS_FILE, SettingsError, } from "./config.mjs";
16
16
  import { CHOICES_FILE, choicesText, findPackage, LOCK_FILE, OWN, PLUGIN_LISTS, presetFaults, PRESET_FILE, readLock, shipped, shipsText, splitName, stable, staleMessages, } from "./preset.mjs";
17
+ import { npmrcRegistry } from "./npmrc.mjs";
17
18
  const isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
18
19
  const DEPENDABOT = ".github/dependabot.yml";
19
20
  // ---------------------------------------------------------------- Values
@@ -246,18 +247,6 @@ export async function hasOwnGroup(text, pkg) {
246
247
  g.patterns.length === 1 &&
247
248
  g.patterns[0] === pkg));
248
249
  }
249
- /** The registry `.npmrc` sends a package's scope to, or null. */
250
- export function npmrcRegistry(text, pkg) {
251
- if (!text || !pkg.startsWith("@"))
252
- return null;
253
- const scope = pkg.split("/")[0];
254
- for (const line of text.split("\n")) {
255
- const m = /^\s*(@[^:\s]+):registry\s*=\s*(\S+)\s*$/.exec(line);
256
- if (m && m[1] === scope)
257
- return m[2];
258
- }
259
- return null;
260
- }
261
250
  const bare = (url) => url.replace(/\/+$/, "");
262
251
  /** The lines `preset add` ends with for what Dependabot still needs. */
263
252
  export async function nextLines(dependabot, npmrc, pkg) {
@@ -856,6 +845,7 @@ export async function changes(argv, d) {
856
845
  version: "",
857
846
  presets: [],
858
847
  hash: null,
848
+ npmrcVariables: [],
859
849
  settings: {},
860
850
  overridden: {},
861
851
  files: [],
package/dist/preset.d.mts CHANGED
@@ -143,6 +143,8 @@ export type Lock = {
143
143
  version: string;
144
144
  }[];
145
145
  hash: string | null;
146
+ /** The variables `.npmrc`'s sign-in lines read at the last sync. */
147
+ npmrcVariables: string[];
146
148
  settings: Obj | null;
147
149
  overridden: Record<string, Replaced[]>;
148
150
  files: string[];
@@ -161,6 +163,8 @@ export type StaleDeps = {
161
163
  * undefined when there is no node_modules to look in. */
162
164
  installed: (pkg: string) => string | null | undefined;
163
165
  load: (t: string) => unknown;
166
+ /** The variables `.npmrc`'s sign-in lines read now. */
167
+ npmrcNames?: string[];
164
168
  };
165
169
  /** Why the lock is stale, the first of: missing, from an earlier release,
166
170
  * a settings file changed, a preset not installed, a preset at another
package/dist/preset.mjs CHANGED
@@ -9,6 +9,7 @@ import { dirname, join, relative, sep } from "node:path";
9
9
  import { DEFAULT_CODE_HOST } from "./code-host/index.mjs";
10
10
  import { ROLE_SHAPE, ROLES, SETTINGS_FILE, SETTINGS_KEYS } from "./config.mjs";
11
11
  import { BUILT } from "./tool-names.mjs";
12
+ import { NPMRC, refusal } from "./npmrc.mjs";
12
13
  export const PRESET_FILE = "factory-preset.yaml";
13
14
  export const CHOICES_FILE = ".claude/factory.choices.yaml";
14
15
  export const LOCK_FILE = ".claude/factory.lock";
@@ -509,6 +510,9 @@ export function readLock(text, load) {
509
510
  }))
510
511
  : [],
511
512
  hash: typeof d["settings-hash"] === "string" ? d["settings-hash"] : null,
513
+ npmrcVariables: Array.isArray(d["npmrc-variables"])
514
+ ? d["npmrc-variables"].map(String)
515
+ : [],
512
516
  settings: isObj(d.settings) ? d.settings : null,
513
517
  overridden: isObj(d.overridden)
514
518
  ? d.overridden
@@ -536,6 +540,12 @@ export function staleReason(d) {
536
540
  const choicesOnly = changed.includes(CHOICES_FILE) && !changed.includes(SETTINGS_FILE);
537
541
  return staleMessages.changed(choicesOnly ? CHOICES_FILE : SETTINGS_FILE);
538
542
  }
543
+ const names = d.npmrcNames ?? [];
544
+ const refused = names.map(refusal).find((r) => r !== null);
545
+ if (refused)
546
+ return refused;
547
+ if (names.join("\n") !== lock.npmrcVariables.join("\n"))
548
+ return staleMessages.changed(NPMRC);
539
549
  for (const p of lock.presets) {
540
550
  const v = d.installed(splitName(p.name).pkg);
541
551
  if (v === null)
@@ -11,6 +11,17 @@ const FAILED = ["failure", "timed_out", "startup_failure"];
11
11
  export function githubActionsRunner(o) {
12
12
  const t = o.transport;
13
13
  const API = `repos/${o.repository}`;
14
+ /** Every secret a listing names, page by page: the list is an object,
15
+ * not an array, so it is paged by hand. */
16
+ const secretsAt = async (path) => {
17
+ const all = [];
18
+ for (let page = 1;; page++) {
19
+ const listed = await t.rest("GET", `${path}?per_page=100&page=${page}`);
20
+ all.push(...listed.secrets);
21
+ if (listed.secrets.length < 100)
22
+ return all;
23
+ }
24
+ };
14
25
  const reviewsOf = async (sha) => (await t.rest("GET", `${API}/actions/workflows/${REVIEW_WORKFLOW}/runs?head_sha=${sha}&per_page=5`)).workflow_runs;
15
26
  return {
16
27
  async startBuild(ticket, branch) {
@@ -90,20 +101,46 @@ export function githubActionsRunner(o) {
90
101
  throw error;
91
102
  }
92
103
  },
93
- async secretNames() {
94
- // The list is an object, not an array, so it is paged by hand.
95
- const names = [];
96
- for (let page = 1;; page++) {
97
- const listed = await t.rest("GET", `${API}/actions/secrets?per_page=100&page=${page}`);
98
- names.push(...listed.secrets.map((x) => x.name));
99
- if (listed.secrets.length < 100)
100
- return names;
101
- }
102
- },
104
+ secretNames: async () => (await secretsAt(`${API}/actions/secrets`)).map((x) => x.name),
103
105
  async setSecret(name, value) {
104
106
  if (!o.cli)
105
107
  throw new Error("Storing a secret needs the GitHub CLI.");
106
108
  await o.cli(["secret", "set", name, "--repo", o.repository], value);
107
109
  },
110
+ dependabotSecretNames: async () => (await secretsAt(`${API}/dependabot/secrets`)).map((x) => x.name),
111
+ async setDependabotSecret(name, value) {
112
+ if (!o.cli)
113
+ throw new Error("Storing a secret needs the GitHub CLI.");
114
+ await o.cli(["secret", "set", name, "--app", "dependabot", "--repo", o.repository], value);
115
+ },
116
+ organizationSecretNames: async () => (await secretsAt(`${API}/actions/organization-secrets`)).map((x) => x.name),
117
+ async organizationDependabotSecretNames(isPrivate) {
118
+ const org = `orgs/${o.repository.split("/")[0]}/dependabot/secrets`;
119
+ try {
120
+ const names = [];
121
+ for (const s of await secretsAt(org)) {
122
+ if (s.visibility === "all" ||
123
+ (s.visibility === "private" && isPrivate))
124
+ names.push(s.name);
125
+ else if (s.visibility === "selected") {
126
+ for (let page = 1;; page++) {
127
+ const shared = await t.rest("GET", `${org}/${s.name}/repositories?per_page=100&page=${page}`);
128
+ if (shared.repositories.some((r) => r.full_name === o.repository)) {
129
+ names.push(s.name);
130
+ break;
131
+ }
132
+ if (shared.repositories.length < 100)
133
+ break;
134
+ }
135
+ }
136
+ }
137
+ return names;
138
+ }
139
+ catch (error) {
140
+ if (statusOf(error) !== null)
141
+ return null;
142
+ throw error;
143
+ }
144
+ },
108
145
  };
109
146
  }
@@ -60,4 +60,17 @@ export type Runner = {
60
60
  /** Stores a secret the runner's jobs can read. The value never appears
61
61
  * in a command's arguments or its output. */
62
62
  setSecret(name: string, value: string): Promise<void>;
63
+ /** The names of the secrets the runner gives a job that the dependency
64
+ * bot's pull request starts. */
65
+ dependabotSecretNames(): Promise<string[]>;
66
+ /** Stores a secret for those jobs, as `setSecret` does. */
67
+ setDependabotSecret(name: string, value: string): Promise<void>;
68
+ /** The names of the secrets the repository's organization shares with
69
+ * it. Not called on a repository a person owns. */
70
+ organizationSecretNames(): Promise<string[]>;
71
+ /** The names of the organization's secrets for the dependency bot that
72
+ * reach this repository, which private ones do only when it is private,
73
+ * or null when the organization will not list them. Not called on a
74
+ * repository a person owns. */
75
+ organizationDependabotSecretNames(isPrivate: boolean): Promise<string[] | null>;
63
76
  };
package/dist/setup.d.mts CHANGED
@@ -7,7 +7,9 @@ import type { Tickets } from "./tickets/types.mts";
7
7
  * removing it is deleting that one rule. */
8
8
  export declare const RULE = "Software factory";
9
9
  export type Check = {
10
- state: "pass" | "fail" | "off";
10
+ /** `unknown`: the check can't be made from the repository, and fails
11
+ * nothing. */
12
+ state: "pass" | "fail" | "off" | "unknown";
11
13
  text: string;
12
14
  /** What to do about a failure. */
13
15
  fix?: string;
package/dist/status.mjs CHANGED
@@ -317,7 +317,7 @@ export function formatRows({ rows, closed }, now, withClosed = true, style = PLA
317
317
  ...g,
318
318
  // The repository's column for the state, or the factory's own name
319
319
  // where the board has none.
320
- label: (style.columns ?? DEFAULT_COLUMNS)[g.name] ?? g.name,
320
+ label: (style.columns ?? DEFAULT_COLUMNS)[g.name]?.[0] ?? g.name,
321
321
  cells: cells.filter((c) => c.row.kind === "issue" && c.row.derived?.status === g.name),
322
322
  always: true,
323
323
  })),
package/dist/sync.d.mts CHANGED
@@ -19,6 +19,11 @@ export declare function withDefaultBranch(text: string, name: string, file: stri
19
19
  * more, so the steps after the session still run before the job is
20
20
  * stopped. */
21
21
  export declare function withMinutes(text: string, minutes: number, file: string): string;
22
+ /** A workflow whose jobs that install packages set each name in `names`
23
+ * from a secret of the same name, in the job's `env`, so every step that
24
+ * runs npm reads it, a composite action's included. With `GITHUB_TOKEN`
25
+ * among them, the workflow may also read packages. Only lines are added. */
26
+ export declare function withNpmEnv(text: string, names: string[], file: string): string;
22
27
  /** A copy with the rules' numbers the settings give in place of the
23
28
  * defaults. A phrase is replaced only when its number is not the default,
24
29
  * and must then match exactly once. */
@@ -66,6 +71,8 @@ export type LockParts = {
66
71
  version: string;
67
72
  }[];
68
73
  hash: string;
74
+ /** The variables `.npmrc`'s sign-in lines read. */
75
+ npmrcVariables: string[];
69
76
  /** The settings in effect, as `factory config explain` prints them. */
70
77
  settings: string[];
71
78
  overridden: Record<string, Replaced[]>;
package/dist/sync.mjs CHANGED
@@ -17,6 +17,7 @@
17
17
  import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync, } from "node:fs";
18
18
  import { dirname, join, relative, sep } from "node:path";
19
19
  import { fileURLToPath } from "node:url";
20
+ import { firstRefusal, npmrcAt } from "./npmrc.mjs";
20
21
  import { filesDeps, repoRoot, resolveFiles, RULE_NUMBERS, staleOf, defaultDeps, } from "./config.mjs";
21
22
  import { CHOICES_FILE, choicesText, settingsHash, staleChoices, } from "./preset.mjs";
22
23
  import { branchDeps, CANNOT_TELL, defaultBranch, } from "./lib/default-branch.mjs";
@@ -93,6 +94,56 @@ export function withMinutes(text, minutes, file) {
93
94
  const session = one(/^(\s+minutes: )\d+$/gm, minutes, text);
94
95
  return one(/^(\s+timeout-minutes: )\d+$/gm, minutes + 10, session);
95
96
  }
97
+ /** A workflow whose jobs that install packages set each name in `names`
98
+ * from a secret of the same name, in the job's `env`, so every step that
99
+ * runs npm reads it, a composite action's included. With `GITHUB_TOKEN`
100
+ * among them, the workflow may also read packages. Only lines are added. */
101
+ export function withNpmEnv(text, names, file) {
102
+ if (!names.length)
103
+ return text;
104
+ const lines = text.split("\n");
105
+ const jobsAt = lines.indexOf("jobs:");
106
+ if (jobsAt < 0)
107
+ return text;
108
+ const starts = lines
109
+ .map((l, i) => (i > jobsAt && /^ {2}[A-Za-z0-9_-]+:\s*$/.test(l) ? i : -1))
110
+ .filter((i) => i >= 0);
111
+ const entries = names.map((n) => ` ${n}: \${{ secrets.${n} }}`);
112
+ const inserts = [];
113
+ starts.forEach((start, k) => {
114
+ const end = starts[k + 1] ?? lines.length;
115
+ const job = lines.slice(start, end);
116
+ const installs = job.some((l) => (/\bnpm ci\b/.test(l) && !/^\s*#/.test(l)) ||
117
+ /^\s+uses: \.\/\.github\/actions\/factory-agent\s*$/.test(l));
118
+ if (!installs)
119
+ return;
120
+ const env = job.findIndex((l) => /^ {4}env:\s*$/.test(l));
121
+ const runsOn = job.findIndex((l) => /^ {4}runs-on:/.test(l));
122
+ const permissions = job.findIndex((l) => /^ {4}permissions:\s*$/.test(l));
123
+ if (names.includes("GITHUB_TOKEN") && permissions >= 0)
124
+ inserts.push({
125
+ at: start + permissions + 1,
126
+ lines: [" packages: read"],
127
+ });
128
+ if (env >= 0)
129
+ inserts.push({ at: start + env + 1, lines: entries });
130
+ else if (runsOn >= 0)
131
+ inserts.push({ at: start + runsOn + 1, lines: [" env:", ...entries] });
132
+ else
133
+ throw new Error(`${file}: expected a runs-on line in each job that installs, to set its env`);
134
+ });
135
+ if (!inserts.length)
136
+ return text;
137
+ if (names.includes("GITHUB_TOKEN")) {
138
+ const permissions = lines.indexOf("permissions:");
139
+ if (permissions < 0)
140
+ throw new Error(`${file}: expected a permissions block, to let GITHUB_TOKEN read packages`);
141
+ inserts.push({ at: permissions + 1, lines: [" packages: read"] });
142
+ }
143
+ for (const { at, lines: added } of inserts.sort((a, b) => b.at - a.at))
144
+ lines.splice(at, 0, ...added);
145
+ return lines.join("\n");
146
+ }
96
147
  const WORDS = [
97
148
  "zero",
98
149
  "one",
@@ -375,6 +426,9 @@ export function lockText(l) {
375
426
  ]
376
427
  : ["presets: []"]),
377
428
  `settings-hash: ${l.hash}`,
429
+ ...(l.npmrcVariables.length
430
+ ? ["npmrc-variables:", ...l.npmrcVariables.map((n) => ` - ${n}`)]
431
+ : ["npmrc-variables: []"]),
378
432
  "settings:",
379
433
  ...l.settings.map((line) => ` ${line}`),
380
434
  ...(replaced.length
@@ -451,19 +505,23 @@ export async function plan(pkg, root, r, branch) {
451
505
  const read = (p) => existsSync(join(root, p)) ? readFileSync(join(root, p), "utf8") : null;
452
506
  const write = new Map();
453
507
  const has = (p) => existsSync(join(root, p));
508
+ const npmrc = npmrcAt(root);
454
509
  for (const [from, to] of copies(pkg, s, has)) {
455
510
  const source = readFileSync(join(pkg, from), "utf8");
456
511
  const text = PUSH_WORKFLOWS.includes(from)
457
512
  ? withDefaultBranch(source, branch, from)
458
513
  : source;
459
514
  const kind = SESSION_WORKFLOWS[from.replace(/^workflows\//, "")];
460
- write.set(to, kind && from.startsWith("workflows/")
515
+ const written = kind && from.startsWith("workflows/")
461
516
  ? withMinutes(text, s.sessionMinutes[kind], from)
462
517
  : from === POLLER_WORKFLOW
463
518
  ? withSchedule(text, s.builds.pollMinutes, from)
464
519
  : from === AUTO_MERGE_WORKFLOW
465
520
  ? withPresetPackages(text, [...new Set(r.presets.map((p) => p.pkg))], from)
466
- : withRules(text, s.rules, from));
521
+ : withRules(text, s.rules, from);
522
+ write.set(to, from.startsWith("workflows/")
523
+ ? withNpmEnv(written, npmrc.names, from)
524
+ : written);
467
525
  }
468
526
  // A preset's agent or skill, unless the factory's own file or one the
469
527
  // repository wrote itself is at its path: those always stay.
@@ -499,6 +557,7 @@ export async function plan(pkg, root, r, branch) {
499
557
  version: manifest.version,
500
558
  presets: r.presets.map((p) => ({ name: p.name, version: p.version })),
501
559
  hash: settingsHash(r.ownText, chosen),
560
+ npmrcVariables: npmrc.names,
502
561
  settings,
503
562
  overridden: Object.fromEntries(r.resolution.overridden),
504
563
  files,
@@ -538,6 +597,11 @@ export async function main(argv, d) {
538
597
  }
539
598
  }
540
599
  r = await d.settings();
600
+ const refused = firstRefusal(npmrcAt(d.root));
601
+ if (refused) {
602
+ d.err(refused);
603
+ return 1;
604
+ }
541
605
  }
542
606
  catch (e) {
543
607
  d.err(e instanceof Error ? e.message : String(e));
package/dist/ticket.mjs CHANGED
@@ -222,7 +222,7 @@ async function moveToReady(issue, d) {
222
222
  throw new Error(`#${issue} is closed.`);
223
223
  if (d.board === null)
224
224
  throw new Error("The settings name no board.");
225
- const ready = d.config.columns.Ready;
225
+ const ready = d.config.columns.Ready?.[0] ?? null;
226
226
  if (ready === null)
227
227
  throw new Error(`This board has no column for ready. Tell a session to build #${issue}, or run factory build ${issue}.`);
228
228
  const board = need(d.tickets, "board");
@@ -215,6 +215,11 @@ export function githubTickets(o) {
215
215
  const t = o.transport;
216
216
  let lastBoard = null;
217
217
  const issue = (n) => found(`#${n}`, t.rest("GET", `${API}/issues/${n}`));
218
+ /** Board `number`'s Status field, or null when it has none. */
219
+ const statusField = async (number) => {
220
+ const answer = await t.graphql(STATUS_FIELD, { owner: o.boardOwner ?? repoOwner, number });
221
+ return answer.data.owner?.projectV2?.field ?? null;
222
+ };
218
223
  const readBoard = async () => {
219
224
  if (o.board === null)
220
225
  return { projectId: "", fields: [], items: new Map() };
@@ -370,9 +375,12 @@ export function githubTickets(o) {
370
375
  });
371
376
  return made.data.createProjectV2.projectV2.number;
372
377
  },
378
+ async columns(number) {
379
+ const field = await statusField(number);
380
+ return (field?.options ?? []).map((x) => x.name);
381
+ },
373
382
  async addColumns(number, columns) {
374
- const answer = await t.graphql(STATUS_FIELD, { owner: o.boardOwner ?? repoOwner, number });
375
- const field = answer.data.owner?.projectV2?.field;
383
+ const field = await statusField(number);
376
384
  if (!field)
377
385
  throw new Error(`Board ${number} has no Status field.`);
378
386
  const has = (name) => field.options.find((x) => sameName(x.name, name));
@@ -82,6 +82,9 @@ export type BoardOps = {
82
82
  /** Creates a board under the repository's owner, linked to the
83
83
  * repository, and returns its number. */
84
84
  create(title: string): Promise<number>;
85
+ /** Board `number`'s columns, its Status field's options in the board's
86
+ * order, or none when it has no Status field. */
87
+ columns(number: number): Promise<string[]>;
85
88
  /** Gives board `number` each of `columns` it lacks, the columns in that
86
89
  * order before any other it has, and returns the ones it added. */
87
90
  addColumns(number: number, columns: string[]): Promise<string[]>;
package/dist/tools.d.mts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { Agent } from "./agent/types.mts";
1
2
  import { type CodeHost } from "./code-host/index.mts";
2
3
  import type { Settings } from "./config.mts";
3
4
  import type { Part } from "./parts.mts";
@@ -27,7 +28,9 @@ export type Registry = {
27
28
  runner: Record<string, Tool & {
28
29
  open(repository: string): Runner;
29
30
  }>;
30
- agent: Record<string, Tool>;
31
+ agent: Record<string, Tool & {
32
+ agent: Agent;
33
+ }>;
31
34
  };
32
35
  export declare const TOOLS: Registry;
33
36
  /** The names and keys the settings accept, as `config.mts` checks them. */
package/dist/tools.mjs CHANGED
@@ -1,7 +1,8 @@
1
1
  // Every tool the factory has built, by kind and by the name a setting gives
2
2
  // it: how to open it, and its setup (`setup.mts`). `init`, `doctor`, and
3
3
  // `remove` take this as a parameter, so a test adds a tool of its own.
4
- import { claudeCodeSetup, DEFAULT_AGENT } from "./agent/index.mjs";
4
+ import { spawn } from "node:child_process";
5
+ import { claudeCodeAgent, claudeCodeSetup, DEFAULT_AGENT, } from "./agent/index.mjs";
5
6
  import { githubRepository, githubCodeHostSetup, } from "./code-host/github-setup.mjs";
6
7
  import { openCodeHost } from "./code-host/index.mjs";
7
8
  import { gh } from "./lib/gh.mjs";
@@ -42,7 +43,13 @@ export const TOOLS = {
42
43
  open: (repository) => openRunner(repository),
43
44
  },
44
45
  },
45
- agent: { [DEFAULT_AGENT]: { label: "Claude Code", setup: claudeCodeSetup } },
46
+ agent: {
47
+ [DEFAULT_AGENT]: {
48
+ label: "Claude Code",
49
+ setup: claudeCodeSetup,
50
+ agent: claudeCodeAgent(spawn),
51
+ },
52
+ },
46
53
  };
47
54
  /** The names and keys the settings accept, as `config.mts` checks them. */
48
55
  export function builtOf(r) {
@@ -202,7 +202,10 @@ The board has one column for each of the six
202
202
  [states](workflow.md#the-six-states) a ticket goes through. If your
203
203
  board's columns have the factory's names, write nothing here. If they have
204
204
  other names, or your board has fewer columns, say which column shows each
205
- state. A new GitHub Project starts with only Todo, In Progress, and Done,
205
+ state. `factory init` suggests this block when you choose a board without the
206
+ factory's columns: see
207
+ [You already have a board](existing-repo.md#you-already-have-a-board).
208
+ A new GitHub Project starts with only Todo, In Progress, and Done,
206
209
  so its settings would be:
207
210
 
208
211
  ```yaml
@@ -235,6 +238,24 @@ The factory's own names, used for any state you leave out, are:
235
238
  that state stays in the column of the state before it. With
236
239
  `review: none`, a ticket whose pull request is in review stays in In
237
240
  progress. Every state can be `none` except `backlog`.
241
+ - **A state can take a list of columns,** when more than one of yours
242
+ means it. `factory init` suggests one column for each state, so you
243
+ write a list yourself. A ticket in any of the columns is in that
244
+ state. When the factory moves a ticket into the state, it uses the
245
+ first, and a ticket already in any of them stays where it is:
246
+
247
+ ```yaml
248
+ tickets:
249
+ board: 7
250
+ columns:
251
+ backlog: Todo
252
+ # When a pull request opens, its ticket moves to Code review.
253
+ # One you moved to QA stays there.
254
+ review: [Code review, QA]
255
+ ```
256
+
257
+ `ready` takes one column, since only a ticket you approved goes there.
258
+
238
259
  - **A ticket never falls back into Ready,** since only a ticket you
239
260
  approved goes there, so the fallback skips it. With `building: none`
240
261
  alone, a ticket being built has no column of its own, the state before
@@ -248,10 +269,17 @@ The factory's own names, used for any state you leave out, are:
248
269
  needs the new name too: see `FACTORY_READY_COLUMN` in
249
270
  [Builds](builds.md#what-it-reads-from-its-environment).
250
271
 
251
- `factory config check` stops on a state it doesn't know, on
252
- `backlog: none`, on two states sharing one column, on `columns` without a
253
- `board`, and on `ready: none` when `builds.trigger` isn't `manual`. It
254
- doesn't read your board: `factory board check` does.
272
+ `factory config check` stops, naming the key, when `columns` has:
273
+
274
+ - a state it doesn't know;
275
+ - `backlog: none`;
276
+ - one column for two states;
277
+ - an empty list, or a list for `ready`;
278
+ - no `board` beside it;
279
+ - `ready: none` while [`builds.trigger`](#builds) isn't `manual`,
280
+ since then a build starts only from the ready column.
281
+
282
+ It doesn't read your board: `factory board check` does.
255
283
 
256
284
  #### `tickets.fields`
257
285
 
package/docs/design.md CHANGED
@@ -86,6 +86,21 @@ why a board's columns can be yours. Every extra shape of workflow is one
86
86
  more path each skill has to handle correctly, and a skill is instructions,
87
87
  which cannot be unit tested.
88
88
 
89
+ Your coding agent suggests which of your board's columns shows each
90
+ state once, when `factory init` sets up your board
91
+ ([You already have a board](existing-repo.md#you-already-have-a-board)).
92
+ After that it is an ordinary setting, read the same way every time.
93
+
94
+ A state can already take a list of column names.
95
+ [_Planned_](developing.md#what-is-built): other ticket systems, which
96
+ name their states differently and fit the same setting. Jira lets each kind of ticket, such
97
+ as a bug or a story, follow its own sequence of states; the factory
98
+ would move a ticket to the first listed name that its own sequence has.
99
+ Linear gives each team one sequence, which works as a board does. If a
100
+ name ever had to mean different states for different kinds of ticket,
101
+ an optional `columns-by-type` setting would hold only those exceptions,
102
+ and every settings file written before it would read the same.
103
+
89
104
  ## Small problems go on one checklist
90
105
 
91
106
  A session that notices a small problem adds a line to one follow-ups