@davidbyoung/software-factory 0.1.5 → 0.1.6

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 (43) hide show
  1. package/README.md +9 -8
  2. package/dist/cli.mjs +12 -0
  3. package/dist/config.d.mts +57 -3
  4. package/dist/config.mjs +268 -18
  5. package/dist/deps.d.mts +6 -4
  6. package/dist/deps.mjs +29 -7
  7. package/dist/doctor.d.mts +3 -0
  8. package/dist/doctor.mjs +7 -4
  9. package/dist/explain.d.mts +12 -1
  10. package/dist/explain.mjs +47 -32
  11. package/dist/init.mjs +6 -4
  12. package/dist/lib/default-branch.d.mts +1 -1
  13. package/dist/lib/default-branch.mjs +2 -2
  14. package/dist/preset-commands.d.mts +65 -0
  15. package/dist/preset-commands.mjs +1148 -0
  16. package/dist/preset.d.mts +169 -0
  17. package/dist/preset.mjs +550 -0
  18. package/dist/remove.mjs +34 -1
  19. package/dist/session-start.d.mts +3 -0
  20. package/dist/session-start.mjs +12 -1
  21. package/dist/sync.d.mts +42 -7
  22. package/dist/sync.mjs +165 -31
  23. package/docs/builds.md +12 -11
  24. package/docs/cli.md +21 -2
  25. package/docs/configuration.md +65 -13
  26. package/docs/developing.md +9 -2
  27. package/docs/github/by-hand.md +5 -5
  28. package/docs/github/reference.md +2 -17
  29. package/docs/github/setup.md +1 -1
  30. package/docs/glossary.md +12 -2
  31. package/docs/limitations.md +3 -0
  32. package/docs/plugins.md +16 -5
  33. package/docs/presets.md +410 -0
  34. package/docs/quick-start.md +20 -17
  35. package/docs/skills.md +21 -16
  36. package/docs/updating.md +14 -7
  37. package/docs/workflow.md +12 -13
  38. package/package.json +1 -1
  39. package/settings.schema.json +52 -3
  40. package/skills/factory-deps/SKILL.md +23 -12
  41. package/skills/factory-design/SKILL.md +1 -1
  42. package/skills/factory-resolve-conflicts/SKILL.md +6 -0
  43. package/workflows/factory-claude-review.yml +7 -2
@@ -0,0 +1,550 @@
1
+ // Presets: npm packages of settings, agents, and skills that several
2
+ // repositories share. `.claude/factory.yaml` names them under `presets`,
3
+ // and `factory sync` combines the factory's defaults, each preset in the
4
+ // order listed, and the repository's own settings into the lock, with
5
+ // where each value came from. Every other command reads the lock.
6
+ import { createHash } from "node:crypto";
7
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
8
+ import { dirname, join, relative, sep } from "node:path";
9
+ import { DEFAULT_CODE_HOST } from "./code-host/index.mjs";
10
+ import { ROLE_SHAPE, ROLES, SETTINGS_FILE, SETTINGS_KEYS } from "./config.mjs";
11
+ import { BUILT } from "./tool-names.mjs";
12
+ export const PRESET_FILE = "factory-preset.yaml";
13
+ export const CHOICES_FILE = ".claude/factory.choices.yaml";
14
+ export const LOCK_FILE = ".claude/factory.lock";
15
+ /** The layer name of the repository's own settings. */
16
+ export const OWN = SETTINGS_FILE;
17
+ export const SYNC = "npx --no-install factory sync";
18
+ const isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
19
+ /** One value as text that is the same for equal values, whatever the order
20
+ * of a block's keys. */
21
+ export function stable(v) {
22
+ if (Array.isArray(v))
23
+ return `[${v.map(stable).join(",")}]`;
24
+ if (isObj(v))
25
+ return `{${Object.keys(v)
26
+ .sort()
27
+ .map((k) => `${JSON.stringify(k)}:${stable(v[k])}`)
28
+ .join(",")}}`;
29
+ return JSON.stringify(v) ?? "undefined";
30
+ }
31
+ // ---------------------------------------------------------------- Finding
32
+ /** A preset's package and the folder in it: `@acme/p/node` is the folder
33
+ * `node` of the package `@acme/p`. */
34
+ export function splitName(name) {
35
+ const parts = name.split("/");
36
+ const n = name.startsWith("@") ? 2 : 1;
37
+ return {
38
+ pkg: parts.slice(0, n).join("/"),
39
+ folder: parts.slice(n).join("/"),
40
+ };
41
+ }
42
+ /** A package's folder and version, found as Node finds it from `root`, or
43
+ * null when it is not installed. */
44
+ export function findPackage(root, pkg) {
45
+ for (let at = root;; at = dirname(at)) {
46
+ const manifest = join(at, "node_modules", pkg, "package.json");
47
+ if (existsSync(manifest)) {
48
+ const { version } = JSON.parse(readFileSync(manifest, "utf8"));
49
+ return { dir: dirname(manifest), version: String(version) };
50
+ }
51
+ if (dirname(at) === at)
52
+ return null;
53
+ }
54
+ }
55
+ export class PresetError extends Error {
56
+ }
57
+ /** The preset NAME as installed from `root`. Throws a PresetError saying
58
+ * what to do when it is not installed, or is no preset. */
59
+ export function findPreset(root, name) {
60
+ const { pkg, folder } = splitName(name);
61
+ const found = findPackage(root, pkg);
62
+ if (!found)
63
+ throw new PresetError(`${name}: not installed. Run: npm ci`);
64
+ const dir = folder ? join(found.dir, folder) : found.dir;
65
+ if (!existsSync(join(dir, PRESET_FILE)))
66
+ throw new PresetError(`${name}: no ${PRESET_FILE} in node_modules/${pkg}${folder ? `/${folder}` : ""}`);
67
+ return { name, pkg, folder, dir, version: found.version };
68
+ }
69
+ function walk(dir, base = dir) {
70
+ if (!existsSync(dir))
71
+ return [];
72
+ return readdirSync(dir)
73
+ .sort()
74
+ .flatMap((name) => {
75
+ const path = join(dir, name);
76
+ return statSync(path).isDirectory()
77
+ ? walk(path, base)
78
+ : [relative(base, path).split(sep).join("/")];
79
+ });
80
+ }
81
+ /** The agents and skills a preset in `dir` ships, each as the path it is
82
+ * written to in a repository and the file it comes from. */
83
+ export function shipped(dir) {
84
+ const agents = walk(join(dir, "agents"))
85
+ .filter((f) => !f.includes("/") && f.endsWith(".md"))
86
+ .map((f) => [
87
+ `.claude/agents/${f}`,
88
+ join(dir, "agents", f),
89
+ ]);
90
+ const skills = walk(join(dir, "skills"))
91
+ .filter((f) => f.includes("/"))
92
+ .map((f) => [
93
+ `.claude/skills/${f}`,
94
+ join(dir, "skills", f),
95
+ ]);
96
+ return [...agents, ...skills];
97
+ }
98
+ /** How many agents and skills a preset ships, as `preset check` says it. */
99
+ export function shipsText(dir) {
100
+ const files = shipped(dir).map(([to]) => to);
101
+ const agents = files.filter((f) => f.startsWith(".claude/agents/")).length;
102
+ const skills = new Set(files
103
+ .filter((f) => f.startsWith(".claude/skills/"))
104
+ .map((f) => f.split("/")[2])).size;
105
+ if (!agents && !skills)
106
+ return "no agents or skills";
107
+ const n = (k, one) => `${k} ${one}${k === 1 ? "" : "s"}`;
108
+ return `${n(agents, "agent")}, ${n(skills, "skill")}`;
109
+ }
110
+ // ---------------------------------------------------------------- Checking
111
+ /** The keys no preset can set: each decides who a session takes
112
+ * instructions from or what merges without a person. */
113
+ export const OWN_ONLY = [
114
+ "repository",
115
+ "auto-merge.allow",
116
+ "auto-merge.commands",
117
+ ];
118
+ /** The list roles' paths, such as `plugins.build.reviewers`. */
119
+ export const PLUGIN_LISTS = ROLES.filter((r) => ROLE_SHAPE[r].list).map((r) => `plugins.${ROLE_SHAPE[r].phase}.${ROLE_SHAPE[r].key}`);
120
+ /** The first key a block has that the settings do not know, as `factory
121
+ * config check` words it: `KEY: unknown key`. */
122
+ export function unknownKey(raw) {
123
+ const visit = (v, path, shown) => {
124
+ const allowed = SETTINGS_KEYS[path];
125
+ if (!allowed || !isObj(v))
126
+ return null;
127
+ const extra = path === "tickets" && typeof v.type === "string"
128
+ ? (BUILT.tickets[v.type] ?? [])
129
+ : [];
130
+ for (const [k, value] of Object.entries(v)) {
131
+ const at = path ? `${path}.${k}` : k;
132
+ const show = shown ? `${shown}.${k}` : k;
133
+ if (!allowed.includes(k) && !extra.includes(k))
134
+ return `${show}: unknown key`;
135
+ const inner = SETTINGS_KEYS[`${at}[]`] && Array.isArray(value)
136
+ ? value
137
+ .map((item, i) => visit(item, `${at}[]`, `${show}[${i}]`))
138
+ .find(Boolean)
139
+ : visit(value, at, show);
140
+ if (inner)
141
+ return inner;
142
+ }
143
+ return null;
144
+ };
145
+ return visit(raw, "", "");
146
+ }
147
+ /** What is wrong with a preset's own settings, each as `KEY: MESSAGE`,
148
+ * before it is combined with any other layer. */
149
+ export function presetFaults(raw) {
150
+ const faults = [];
151
+ if (!isObj(raw)) {
152
+ faults.push({
153
+ key: "version",
154
+ message: "must be 2",
155
+ kind: "unknown",
156
+ });
157
+ return faults;
158
+ }
159
+ if (raw.version !== 2)
160
+ faults.push({ key: "version", message: "must be 2", kind: "unknown" });
161
+ for (const key of OWN_ONLY) {
162
+ const [a, b] = key.split(".");
163
+ const at = b ? (isObj(raw[a]) ? raw[a][b] : undefined) : raw[a];
164
+ if (at !== undefined)
165
+ faults.push({
166
+ key,
167
+ message: "a preset can't set this",
168
+ kind: "own-only",
169
+ });
170
+ }
171
+ if (raw.presets !== undefined)
172
+ faults.push({
173
+ key: "presets",
174
+ message: "a preset can't name another preset",
175
+ kind: "presets",
176
+ });
177
+ for (const path of PLUGIN_LISTS) {
178
+ const list = get(raw, path);
179
+ if (Array.isArray(list))
180
+ list.forEach((item, i) => {
181
+ if (isObj(item) && "off" in item)
182
+ faults.push({
183
+ key: `${path}[${i}]`,
184
+ message: "off: only .claude/factory.yaml can leave a plugin out",
185
+ kind: "off",
186
+ });
187
+ });
188
+ }
189
+ const unknown = unknownKey(raw);
190
+ if (unknown) {
191
+ const at = unknown.indexOf(": ");
192
+ faults.push({
193
+ key: unknown.slice(0, at),
194
+ message: unknown.slice(at + 2),
195
+ kind: "unknown",
196
+ });
197
+ }
198
+ return faults;
199
+ }
200
+ function get(raw, path) {
201
+ let at = raw;
202
+ for (const part of path.split(".")) {
203
+ if (!isObj(at))
204
+ return undefined;
205
+ at = at[part];
206
+ }
207
+ return at;
208
+ }
209
+ export const itemKey = (path, item) => `${path}[${stable(item)}]`;
210
+ const STEPS = new Set([
211
+ "commands.gate",
212
+ "commands.before-commit",
213
+ "commands.build-setup",
214
+ ]);
215
+ const VALUES = new Set([
216
+ "pr-review.commands",
217
+ "auto-merge.allow",
218
+ "auto-merge.deny",
219
+ "auto-merge.commands",
220
+ "site.pages",
221
+ "site.widths",
222
+ "site.checks",
223
+ "site.hide",
224
+ ]);
225
+ const TYPED = {
226
+ tickets: "github",
227
+ specs: "none",
228
+ "code-host": DEFAULT_CODE_HOST,
229
+ };
230
+ const LISTS = new Set(PLUGIN_LISTS);
231
+ /** A block is merged key by key: every path the settings give keys for,
232
+ * but a role that takes one plugin, which is one value. */
233
+ const isBlock = (path) => path in SETTINGS_KEYS &&
234
+ !ROLES.some((r) => !ROLE_SHAPE[r].list &&
235
+ path === `plugins.${ROLE_SHAPE[r].phase}.${ROLE_SHAPE[r].key}`);
236
+ /** The layers combined, the later over the earlier, with
237
+ * `.claude/factory.yaml` last. */
238
+ export function combine(c) {
239
+ const r = {
240
+ raw: {},
241
+ sources: new Map(),
242
+ overridden: new Map(),
243
+ disagreements: [],
244
+ setBy: new Map(),
245
+ files: new Map(),
246
+ kept: [],
247
+ };
248
+ const single = (key, es, same = stable, shown = (e) => e.value) => {
249
+ const own = es.find((e) => e.layer === OWN);
250
+ const presets = es.filter((e) => e.layer !== OWN);
251
+ for (const e of presets) {
252
+ const set = r.setBy.get(key) ?? new Set();
253
+ set.add(e.layer);
254
+ r.setBy.set(key, set);
255
+ }
256
+ let winner;
257
+ if (own) {
258
+ winner = own;
259
+ r.sources.set(key, presets.length
260
+ ? { from: OWN, over: presets.map((e) => e.layer) }
261
+ : { from: OWN });
262
+ }
263
+ else {
264
+ const named = c.choices[key];
265
+ const chosen = presets.find((e) => e.layer === named);
266
+ winner = chosen ?? presets.at(-1);
267
+ const others = presets.filter((e) => same(e.value) !== same(winner.value));
268
+ if (others.length) {
269
+ r.sources.set(key, {
270
+ from: winner.layer,
271
+ state: chosen ? "chosen" : "not-chosen",
272
+ over: [...new Set(others.map((e) => e.layer))],
273
+ });
274
+ r.disagreements.push({
275
+ key,
276
+ values: presets.map((e) => ({ from: e.layer, value: shown(e) })),
277
+ applies: winner.layer,
278
+ chosen: Boolean(chosen),
279
+ });
280
+ }
281
+ else
282
+ r.sources.set(key, { from: winner.layer });
283
+ }
284
+ const replaced = es
285
+ .filter((e) => e !== winner)
286
+ .map((e) => ({ from: e.layer, value: shown(e) }));
287
+ if (replaced.length)
288
+ r.overridden.set(key, replaced);
289
+ return winner;
290
+ };
291
+ const merge = (path, es) => {
292
+ if (path in TYPED) {
293
+ const typeOf = (v) => typeof v === "string" ? v : isObj(v) ? v.type : undefined;
294
+ let current = TYPED[path];
295
+ let start = 0;
296
+ es.forEach((e, i) => {
297
+ const t = typeOf(e.value);
298
+ if (t === undefined)
299
+ return;
300
+ if (t !== current)
301
+ start = i;
302
+ current = t;
303
+ });
304
+ if (start > 0)
305
+ r.overridden.set(path, es.slice(0, start).map((e) => ({ from: e.layer, value: e.value })));
306
+ return block(path, es.slice(start).map((e) => ({
307
+ ...e,
308
+ value: typeof e.value === "string" ? { type: e.value } : e.value,
309
+ })));
310
+ }
311
+ if (LISTS.has(path))
312
+ return plugins(path, es);
313
+ if (VALUES.has(path))
314
+ return values(path, es);
315
+ if (STEPS.has(path) || !isBlock(path))
316
+ return single(path, es).value;
317
+ return block(path, es);
318
+ };
319
+ const block = (path, es) => {
320
+ // A value that is not a block is left for the settings' own check to
321
+ // name, from the last layer that wrote one.
322
+ const odd = es.filter((e) => e.value !== null && !isObj(e.value));
323
+ if (odd.length)
324
+ return single(path, es).value;
325
+ const keys = [
326
+ ...new Set(es.flatMap((e) => Object.keys(e.value ?? {}))),
327
+ ];
328
+ const out = {};
329
+ for (const k of keys) {
330
+ const at = path ? `${path}.${k}` : k;
331
+ const sub = es
332
+ .filter((e) => isObj(e.value) && k in e.value)
333
+ .map((e) => ({ layer: e.layer, value: e.value[k] }));
334
+ out[k] = merge(at, sub);
335
+ }
336
+ return out;
337
+ };
338
+ const values = (path, es) => {
339
+ const odd = es.find((e) => !Array.isArray(e.value));
340
+ if (odd)
341
+ return single(path, es).value;
342
+ const out = [];
343
+ const seen = new Set();
344
+ for (const e of es)
345
+ for (const item of e.value) {
346
+ const k = stable(item);
347
+ if (seen.has(k))
348
+ continue;
349
+ seen.add(k);
350
+ out.push(item);
351
+ r.sources.set(itemKey(path, item), { from: e.layer });
352
+ }
353
+ const layers = [...new Set(es.map((e) => e.layer))];
354
+ r.sources.set(path, layers.length === 1 ? { from: layers[0] } : { from: "" });
355
+ return out;
356
+ };
357
+ const plugins = (path, es) => {
358
+ const odd = es.find((e) => !Array.isArray(e.value));
359
+ if (odd)
360
+ return single(path, es).value;
361
+ const groups = new Map();
362
+ const nameOf = (item, i) => isObj(item) &&
363
+ (typeof item.agent === "string" || typeof item.skill === "string")
364
+ ? String(item.agent ?? item.skill)
365
+ : `\0${i}`;
366
+ for (const e of es)
367
+ e.value.forEach((item, i) => {
368
+ const name = nameOf(item, `${e.layer}${i}`);
369
+ groups.set(name, [
370
+ ...(groups.get(name) ?? []),
371
+ { layer: e.layer, value: item },
372
+ ]);
373
+ });
374
+ const out = [];
375
+ for (const [name, group] of groups) {
376
+ if (name.startsWith("\0")) {
377
+ out.push(group[0].value);
378
+ continue;
379
+ }
380
+ const own = group.find((e) => e.layer === OWN);
381
+ if (own &&
382
+ isObj(own.value) &&
383
+ own.value.off === true &&
384
+ group.length === 1)
385
+ throw new PresetError(`${path}: ${name}: off, but no preset names it`);
386
+ out.push(single(`${path}.${name}`, group).value);
387
+ }
388
+ r.sources.set(path, { from: "" });
389
+ return out;
390
+ };
391
+ r.raw = block("", c.layers.map((l) => ({ layer: l.name, value: l.raw })));
392
+ // The files the presets ship: the factory's own and the repository's own
393
+ // stay, and two presets' files are chosen as a single value is.
394
+ const byPath = new Map();
395
+ for (const l of c.layers)
396
+ for (const [to, from] of c.ships?.get(l.name) ?? [])
397
+ byPath.set(to, [
398
+ ...(byPath.get(to) ?? []),
399
+ { layer: l.name, value: from },
400
+ ]);
401
+ const read = c.read ?? ((f) => readFileSync(f, "utf8"));
402
+ const pkgPath = (file) => {
403
+ const at = file.lastIndexOf(`${sep}node_modules${sep}`);
404
+ return at < 0
405
+ ? file
406
+ : file
407
+ .slice(at + 14)
408
+ .split(sep)
409
+ .join("/");
410
+ };
411
+ for (const [to, es] of byPath) {
412
+ const last = es.at(-1).layer;
413
+ if (c.factoryFile?.(to)) {
414
+ r.kept.push(`kept ${to}, the factory's own, over ${last}`);
415
+ continue;
416
+ }
417
+ if (c.ownFile?.(to)) {
418
+ r.kept.push(`kept ${to}, this repository's own, over ${last}`);
419
+ continue;
420
+ }
421
+ const winner = single(to, es, (v) => read(String(v)), (e) => pkgPath(String(e.value)));
422
+ r.files.set(to, { from: winner.layer, source: String(winner.value) });
423
+ }
424
+ return r;
425
+ }
426
+ /** The mark `factory config explain` gives a value from `source`, or null
427
+ * for none: a value only `.claude/factory.yaml` sets has none. */
428
+ export function markText(source) {
429
+ if (!source)
430
+ return "default";
431
+ if (source.from === "")
432
+ return null;
433
+ if (source.from === OWN)
434
+ return source.over?.length ? `over ${source.over.join(" and ")}` : null;
435
+ if (source.state === "chosen")
436
+ return `${source.from}, chosen over ${source.over.join(" and ")}`;
437
+ if (source.state === "not-chosen")
438
+ return `${source.from}, not chosen yet`;
439
+ return source.from;
440
+ }
441
+ // ---------------------------------------------------------------- Choices
442
+ export const CHOICES_HEADER = [
443
+ "# Written by `factory preset add`, `remove`, and `choices`: which preset",
444
+ "# wins where two presets set the same thing. Change it with",
445
+ "# `npx --no-install factory preset choices`.",
446
+ ];
447
+ /** The choices file's text, or null when it holds no choice. */
448
+ export function choicesText(choices) {
449
+ const keys = Object.keys(choices);
450
+ if (!keys.length)
451
+ return null;
452
+ return [
453
+ ...CHOICES_HEADER,
454
+ ...keys.map((k) => `${k}: ${JSON.stringify(choices[k])}`),
455
+ "",
456
+ ].join("\n");
457
+ }
458
+ /** Each choice a sync drops, with why: its preset is no longer listed, or
459
+ * no longer sets its key. */
460
+ export function staleChoices(choices, presets, setBy) {
461
+ return Object.entries(choices).flatMap(([key, name]) => !presets.includes(name)
462
+ ? [{ key, reason: `${name} is no longer in presets` }]
463
+ : !setBy.get(key)?.has(name)
464
+ ? [{ key, reason: `${name} no longer sets it` }]
465
+ : []);
466
+ }
467
+ // ---------------------------------------------------------------- The lock
468
+ /** `sha256:` and the hex SHA-256 of the settings file, a NUL byte, then the
469
+ * choices file, or nothing for a missing file. */
470
+ export function settingsHash(own, choices) {
471
+ const h = createHash("sha256");
472
+ h.update(own ?? "");
473
+ h.update("\0");
474
+ h.update(choices ?? "");
475
+ return `sha256:${h.digest("hex")}`;
476
+ }
477
+ export const staleMessages = {
478
+ missing: `${LOCK_FILE} is missing. Run: ${SYNC}`,
479
+ earlier: `${LOCK_FILE} is from an earlier version of the factory. Run: ${SYNC}`,
480
+ changed: (file) => `${file} changed since the last sync. Run: ${SYNC}`,
481
+ notInstalled: (name) => `${name} is in ${LOCK_FILE} but not installed. Run: npm ci`,
482
+ /** An older install is behind a pull: npm ci brings it up. A newer one
483
+ * is an update: the sync records it. */
484
+ version: (name, installed, locked) => `${name} is ${installed} in node_modules but ${locked} in ${LOCK_FILE}. Run: ${older(installed, locked) ? "npm ci" : SYNC}`,
485
+ unreadable: `${LOCK_FILE} can't be read. Run: ${SYNC}`,
486
+ };
487
+ /** Whether version `a` is older than `b`, number by number. */
488
+ function older(a, b) {
489
+ const pa = a.split(/[.-]/).map(Number);
490
+ const pb = b.split(/[.-]/).map(Number);
491
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
492
+ const [x, y] = [pa[i] ?? 0, pb[i] ?? 0];
493
+ if (x !== y)
494
+ return x < y;
495
+ }
496
+ return false;
497
+ }
498
+ /** The lock's text read as YAML. A lock from an earlier release has no
499
+ * `settings`, and reads with it null. */
500
+ export function readLock(text, load) {
501
+ const o = load(text);
502
+ const d = isObj(o) ? o : {};
503
+ return {
504
+ version: String(d.version ?? ""),
505
+ presets: Array.isArray(d.presets)
506
+ ? d.presets.filter(isObj).map((p) => ({
507
+ name: String(p.name),
508
+ version: String(p.version),
509
+ }))
510
+ : [],
511
+ hash: typeof d["settings-hash"] === "string" ? d["settings-hash"] : null,
512
+ settings: isObj(d.settings) ? d.settings : null,
513
+ overridden: isObj(d.overridden)
514
+ ? d.overridden
515
+ : {},
516
+ files: Array.isArray(d.files) ? d.files.map(String) : [],
517
+ };
518
+ }
519
+ /** Why the lock is stale, the first of: missing, from an earlier release,
520
+ * a settings file changed, a preset not installed, a preset at another
521
+ * version. Null when it is current. */
522
+ export function staleReason(d) {
523
+ if (d.lock === null)
524
+ return staleMessages.missing;
525
+ let lock;
526
+ try {
527
+ lock = readLock(d.lock, d.load);
528
+ }
529
+ catch {
530
+ return staleMessages.unreadable;
531
+ }
532
+ if (!lock.settings)
533
+ return staleMessages.earlier;
534
+ if (lock.hash !== settingsHash(d.own, d.choices)) {
535
+ const changed = d.changed();
536
+ const choicesOnly = changed.includes(CHOICES_FILE) && !changed.includes(SETTINGS_FILE);
537
+ return staleMessages.changed(choicesOnly ? CHOICES_FILE : SETTINGS_FILE);
538
+ }
539
+ for (const p of lock.presets) {
540
+ const v = d.installed(splitName(p.name).pkg);
541
+ if (v === null)
542
+ return staleMessages.notInstalled(p.name);
543
+ }
544
+ for (const p of lock.presets) {
545
+ const v = d.installed(splitName(p.name).pkg);
546
+ if (typeof v === "string" && v !== p.version)
547
+ return staleMessages.version(p.name, v, p.version);
548
+ }
549
+ return null;
550
+ }
package/dist/remove.mjs CHANGED
@@ -11,6 +11,7 @@ import { listed } from "./lib/listed.mjs";
11
11
  import { SIGNING_KEY } from "./parts.mjs";
12
12
  import { OVERRIDE } from "./review-verdict.mjs";
13
13
  import { LOCK, PACKAGE } from "./sync.mjs";
14
+ import { CHOICES_FILE } from "./preset.mjs";
14
15
  import { builtOf, inUse, TOOLS } from "./tools.mjs";
15
16
  const LABELS = [
16
17
  "merge: automatic",
@@ -19,6 +20,35 @@ const LABELS = [
19
20
  "follow-up",
20
21
  "spec",
21
22
  ];
23
+ /** The agents and skills the lock lists that presets shipped, a skill as
24
+ * its folder, and the packages of the presets it records. */
25
+ async function presetParts(root) {
26
+ const at = join(root, LOCK);
27
+ if (!existsSync(at))
28
+ return { files: [], packages: [] };
29
+ const { load } = await import("js-yaml");
30
+ const { readLock, splitName } = await import("./preset.mjs");
31
+ let lock;
32
+ try {
33
+ lock = readLock(readFileSync(at, "utf8"), load);
34
+ }
35
+ catch {
36
+ return { files: [], packages: [] };
37
+ }
38
+ const files = new Set();
39
+ for (const f of lock.files) {
40
+ const agent = /^\.claude\/agents\/(?!factory-)[^/]+\.md$/.test(f);
41
+ const skill = /^\.claude\/skills\/(?!factory-)([^/]+)\//.exec(f);
42
+ if (agent)
43
+ files.add(f);
44
+ else if (skill)
45
+ files.add(`.claude/skills/${skill[1]}`);
46
+ }
47
+ return {
48
+ files: [...files].filter((p) => existsSync(join(root, p))),
49
+ packages: [...new Set(lock.presets.map((p) => splitName(p.name).pkg))],
50
+ };
51
+ }
22
52
  /** The factory's own files and folders, each a path from the root. */
23
53
  function factoryFiles(root) {
24
54
  const named = (dir, match) => existsSync(join(root, dir))
@@ -30,6 +60,7 @@ function factoryFiles(root) {
30
60
  return [
31
61
  SETTINGS_FILE,
32
62
  LOCK,
63
+ CHOICES_FILE,
33
64
  ".claude/factory",
34
65
  ...named(".claude/skills", /^factory-/),
35
66
  ...named(".claude/agents", /^factory-.*\.md$/),
@@ -75,7 +106,8 @@ export async function main(_argv, d) {
75
106
  },
76
107
  };
77
108
  const tools = inUse(d.tools, chosen);
78
- const deletes = factoryFiles(d.root);
109
+ const shipped = await presetParts(d.root);
110
+ const deletes = [...factoryFiles(d.root), ...shipped.files];
79
111
  const changes = tools.flatMap((t) => t.setup.unconfigure?.(context) ?? []);
80
112
  if (deletes.length === 0 && changes.length === 0) {
81
113
  d.out("Nothing of the factory's is here.");
@@ -121,6 +153,7 @@ export async function main(_argv, d) {
121
153
  : []),
122
154
  `Delete whichever of the labels ${listed(LABELS)} exist, if you do not want their history: deleting one takes it off every ticket`,
123
155
  `Run npm uninstall ${d.packageName}`,
156
+ ...shipped.packages.map((p) => `Run npm uninstall ${p}`),
124
157
  "Commit this on a branch, open a pull request, and merge it",
125
158
  ];
126
159
  d.out("");
@@ -24,6 +24,9 @@ export type Deps = {
24
24
  out: (text: string) => void;
25
25
  /** Prints each ticket's state, and gives the hook's exit. */
26
26
  tickets: () => Promise<number>;
27
+ /** Why the lock is stale, or null when it is current or there is no
28
+ * factory here. */
29
+ stale?: () => Promise<string | null>;
27
30
  };
28
31
  export declare function main(d: Deps): Promise<number>;
29
32
  /** `factory session-start`. */
@@ -2,7 +2,7 @@
2
2
  // the session's context, so work left on another branch is visible before
3
3
  // anything new starts: the checkout's state, the local branches with work
4
4
  // not on the default branch, then each ticket's state.
5
- import { readFileSync } from "node:fs";
5
+ import { existsSync, readFileSync } from "node:fs";
6
6
  import { join } from "node:path";
7
7
  import { branchDeps, CANNOT_TELL, defaultBranch, gitIn, } from "./lib/default-branch.mjs";
8
8
  export { gitIn };
@@ -92,6 +92,11 @@ export async function main(d) {
92
92
  const behind = installBehind(d.dir);
93
93
  if (behind)
94
94
  d.out(`\n${behind}\n`);
95
+ // A stale lock stops every command but `factory sync`, so the session is
96
+ // told now, and starts anyway.
97
+ const stale = await d.stale?.().catch(() => null);
98
+ if (stale)
99
+ d.out(`\n${stale}\n`);
95
100
  return d.tickets();
96
101
  }
97
102
  /** `factory session-start`. */
@@ -107,6 +112,12 @@ export async function run() {
107
112
  dir,
108
113
  branch: branchDeps(dir),
109
114
  out: (text) => console.log(text),
115
+ stale: async () => {
116
+ const { defaultDeps, SETTINGS_FILE, staleOf } = await import("./config.mjs");
117
+ if (!existsSync(join(dir, SETTINGS_FILE)))
118
+ return null;
119
+ return staleOf(defaultDeps(dir));
120
+ },
110
121
  // What each ticket's board card says, and who is working on it. The
111
122
  // status command enforces its own time limit, since a hook the harness
112
123
  // kills prints nothing.