@mayurdluffy/ccwf 0.4.0 → 0.6.0

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 (39) hide show
  1. package/README.md +20 -14
  2. package/lib/chrome-mcp.js +73 -66
  3. package/lib/index.js +173 -66
  4. package/lib/installer.js +115 -30
  5. package/lib/machine.js +63 -18
  6. package/lib/merge.js +56 -12
  7. package/lib/modules.js +38 -6
  8. package/lib/published.js +51 -0
  9. package/lib/stats.js +110 -0
  10. package/package.json +2 -2
  11. package/templates/blocks/browser.md +2 -2
  12. package/templates/blocks/guardrails.md +7 -0
  13. package/templates/docs/ROADMAP.md +1 -1
  14. package/templates/docs/agents/issue-tracker.md +5 -5
  15. package/templates/docs/agents/setup.md +5 -5
  16. package/templates/docs/agents/workflow.md +3 -3
  17. package/templates/guardrails/check.sh +100 -0
  18. package/templates/machine.json +53 -43
  19. package/templates/skills/commit/SKILL.md +1 -1
  20. package/templates/skills/orchestrate-workers/SKILL.md +46 -16
  21. package/templates/skills/orchestrate-workers/approve.sh +5 -1
  22. package/templates/skills/orchestrate-workers/assign.sh +2 -0
  23. package/templates/skills/orchestrate-workers/checks.sh +17 -0
  24. package/templates/skills/orchestrate-workers/claude-worker-settings.json +6 -2
  25. package/templates/skills/orchestrate-workers/end.sh +5 -2
  26. package/templates/skills/orchestrate-workers/grid.sh +2 -0
  27. package/templates/skills/orchestrate-workers/pane.sh +19 -4
  28. package/templates/skills/orchestrate-workers/review.sh +68 -0
  29. package/templates/skills/orchestrate-workers/runlog.sh +23 -0
  30. package/templates/skills/orchestrate-workers/tickets.sh +94 -0
  31. package/templates/skills/orchestrate-workers/watch.sh +64 -13
  32. package/templates/skills/orchestrate-workers/workers.conf +4 -0
  33. package/templates/skills/orchestrate-workers/worktree.sh +160 -0
  34. package/templates/skills/verify-ui/PLAYBOOK.md +1 -1
  35. package/templates/skills/verify-ui/SKILL.md +5 -4
  36. package/templates/skills/verify-ui/ab.sh +9 -0
  37. package/templates/skills/verify-ui/lib.sh +59 -0
  38. package/templates/skills/verify-ui/probe.sh +6 -3
  39. package/templates/skills/verify-ui/run.sh +21 -7
package/lib/index.js CHANGED
@@ -3,14 +3,18 @@ const fs = require("fs");
3
3
  const os = require("os");
4
4
  const path = require("path");
5
5
  const readline = require("readline/promises");
6
+ const util = require("util");
6
7
  const { Installer, sha } = require("./installer");
7
8
  const { hasConflict } = require("./merge3");
8
- const { MODULES, ORDER, AGENTS, makeParams, sync } = require("./modules");
9
+ const { getBlock } = require("./merge");
10
+ const { newer } = require("./published");
11
+ const { MODULES, ORDER, DEFAULT_MODULES, AGENTS, TEMPLATES, makeParams, sync } = require("./modules");
9
12
  const machine = require("./machine");
10
13
  const pkg = require("../package.json");
11
14
 
12
15
  const MANIFEST = ".ccwf.json";
13
- const STATE_MARK = { created: "+", updated: "~", merged: "*", conflict: "x", unchanged: "=", skipped: "!" };
16
+ const WORKERS_CONF = ".agents/skills/orchestrate-workers/workers.conf";
17
+ const STATE_MARK = { created: "+", updated: "~", merged: "*", conflict: "x", removed: "-", unchanged: "=", skipped: "!" };
14
18
 
15
19
  const HELP = `ccwf ${pkg.version} — agent setup for Claude Code, Codex and Cursor (macOS, Linux)
16
20
 
@@ -20,50 +24,53 @@ Usage: ccwf <command> [options]
20
24
  add <module> add one module to an initialised repo
21
25
  update the only command that re-renders templates from this ccwf version; files you edited are merged
22
26
  sync push skill settings and add navigation rules; does not re-render templates
23
- chrome-mcp serve the project’s Chrome DevTools MCP (--print shows its command, --open URL opens an allowed tab)
27
+ chrome-mcp serve the project’s Chrome DevTools MCP (--print shows its command)
24
28
  doctor check tools, skills and files; offer to fix what is missing
25
29
  eject <skill> stop managing a skill you changed
30
+ stats worker runs per model: done, time, fix rounds, failed checks (--json)
26
31
  status show installed modules and drifted files
27
32
 
28
33
  Modules: ${ORDER.join(", ")}
29
- ${ORDER.map((m) => ` ${m.padEnd(9)} ${MODULES[m].desc}`).join("\n")}
34
+ ${ORDER.map((m) => ` ${m.padEnd(9)} ${MODULES[m].desc}${MODULES[m].optional ? " (only when asked for)" : ""}`).join("\n")}
30
35
 
31
36
  Options:
32
37
  --agents a,b claude,codex,cursor (default: all)
33
- --modules a,b|all default: all
38
+ --modules a,b|all default: the ones the repo already has, or all but guardrails
39
+ --extra-skills also install the skills ccwf itself does not use
34
40
  --project-only skip machine setup
35
41
  --machine-only skip the repo
36
42
  --yes, -y no prompts (install everything missing)
37
43
  --dry-run show what would change, write and install nothing
38
- --force overwrite only files ccwf owns instead of merging, never seeded docs
44
+ --force overwrite only files ccwf owns instead of merging, never seeded docs;
45
+ also lets an older ccwf write to a repo set up by a newer one
46
+ --check status, doctor: change nothing, exit 1 when something is missing or broken
39
47
  --dir PATH target repo (default: current directory)
40
48
  -h, --help -v, --version`;
41
49
 
42
- const OPTIONS = new Set(["agents", "modules", "dir", "project-only", "machine-only", "yes", "dry-run", "force", "print", "open", "help", "version"]);
43
- const VALUED = new Set(["agents", "modules", "dir", "open"]);
44
- const SHORT = { y: "yes", h: "help", v: "version" };
50
+ const OPTIONS = {
51
+ ...Object.fromEntries(["agents", "modules", "dir"].map((k) => [k, { type: "string" }])),
52
+ ...Object.fromEntries(["project-only", "machine-only", "dry-run", "force", "print", "check", "extra-skills", "json"].map((k) => [k, { type: "boolean" }])),
53
+ yes: { type: "boolean", short: "y" },
54
+ help: { type: "boolean", short: "h" },
55
+ version: { type: "boolean", short: "v" },
56
+ };
45
57
 
46
58
  function parseArgs(argv) {
47
- const o = { _: [] };
48
- for (let i = 0; i < argv.length; i++) {
49
- const a = argv[i];
50
- if (a.startsWith("--")) {
51
- const [k, inline] = a.slice(2).split("=");
52
- if (!OPTIONS.has(k)) throw new Error(`unknown option: --${k}`);
53
- if (VALUED.has(k)) o[k] = inline ?? argv[++i];
54
- else o[k] = true;
55
- } else if (a.startsWith("-") && a !== "-") {
56
- const k = a.length === 2 ? SHORT[a[1]] : undefined;
57
- if (!k) throw new Error(`unknown option: ${a}`);
58
- o[k] = true;
59
- } else o._.push(a);
59
+ let parsed;
60
+ try {
61
+ parsed = util.parseArgs({ args: argv, options: OPTIONS, allowPositionals: true });
62
+ } catch (err) {
63
+ const unknown = err.code === "ERR_PARSE_ARGS_UNKNOWN_OPTION" && /'([^']+)'/.exec(err.message);
64
+ throw new Error(unknown ? `unknown option: ${unknown[1]}` : err.message.split("\n")[0]);
60
65
  }
61
- return o;
66
+ if (parsed.values.dir === "") throw new Error("--dir needs a folder");
67
+ return { ...parsed.values, _: parsed.positionals };
62
68
  }
63
69
 
64
70
  function list(v, all, what) {
65
71
  const items = v === "all" ? all : String(v).split(",").map((s) => s.trim()).filter(Boolean);
66
72
  const bad = items.filter((i) => !all.includes(i));
73
+ if (!items.length) throw new Error(`no ${what}s given (valid: ${all.join(", ")})`);
67
74
  if (bad.length) throw new Error(`unknown ${what}: ${bad.join(", ")} (valid: ${all.join(", ")})`);
68
75
  return items;
69
76
  }
@@ -83,7 +90,16 @@ function loadManifest(root) {
83
90
  }
84
91
 
85
92
  function saveManifest(root, data, version = pkg.version) {
86
- fs.writeFileSync(path.join(root, MANIFEST), JSON.stringify({ ...data, ccwf: version }, null, 2) + "\n");
93
+ const file = path.join(root, MANIFEST);
94
+ const next = `${file}.${process.pid}.tmp`;
95
+ fs.writeFileSync(next, JSON.stringify({ ...data, ccwf: version }, null, 2) + "\n");
96
+ fs.renameSync(next, file); // never a half-written manifest
97
+ }
98
+
99
+ // Writing older templates over newer ones would undo them without a word.
100
+ function refuseDowngrade(prev, force) {
101
+ if (force || !newer(prev?.ccwf, pkg.version)) return;
102
+ throw new Error(`this repo was set up by ccwf ${prev.ccwf} and this is ${pkg.version}; run \`npx ${pkg.name}@latest\` (or --force to go back to ${pkg.version})`);
87
103
  }
88
104
 
89
105
  async function confirm(question, def = true) {
@@ -99,7 +115,7 @@ async function confirm(question, def = true) {
99
115
 
100
116
  // One line per path: a file touched by several modules reports its strongest state.
101
117
  function collapse(log) {
102
- const rank = { unchanged: 0, skipped: 1, updated: 2, merged: 3, created: 4, conflict: 5 };
118
+ const rank = { unchanged: 0, skipped: 1, updated: 2, merged: 3, created: 4, removed: 5, conflict: 6 };
103
119
  const by = new Map();
104
120
  for (const { rel, state } of log) if (!by.has(rel) || rank[state] > rank[by.get(rel)]) by.set(rel, state);
105
121
  return [...by].map(([rel, state]) => ({ rel, state }));
@@ -110,7 +126,7 @@ function report(ins, dryRun) {
110
126
  for (const { rel, state } of log) if (state !== "unchanged") console.log(` ${STATE_MARK[state]} ${rel}`);
111
127
  const n = (s) => log.filter((l) => l.state === s).length;
112
128
  const merged = n("merged") + n("conflict") ? `, ${n("merged")} merged, ${n("conflict")} with conflicts` : "";
113
- console.log(`${dryRun ? "would change" : "repo"}: ${n("created")} created, ${n("updated")} updated${merged}, ${n("unchanged")} unchanged, ${n("skipped")} skipped`);
129
+ console.log(`${dryRun ? "would change" : "repo"}: ${n("created")} created, ${n("updated")} updated${merged}${n("removed") ? `, ${n("removed")} removed` : ""}, ${n("unchanged")} unchanged, ${n("skipped")} skipped`);
114
130
  for (const w of ins.warnings) console.log(` warning: ${w}`);
115
131
  }
116
132
 
@@ -166,14 +182,24 @@ function globalCbmFindings() {
166
182
 
167
183
  // ---- project ----
168
184
 
169
- function applyProject({ root, agents, modules, ejected, prev, dryRun, force }) {
170
- const ins = new Installer({ root, dryRun, force, ejected, version: pkg.version, ...tracked(prev) });
185
+ // Works out the changes; ins.commit() writes them.
186
+ function applyProject({ root, agents, modules, ejected, prev, dryRun, force, offline, prune }) {
187
+ const ins = new Installer({ root, dryRun, force, offline, ejected, version: pkg.version, oldVersion: prev?.ccwf, ...tracked(prev) });
171
188
  const ctx = { ins, agents, params: makeParams({ agents }) };
172
189
  for (const m of ORDER.filter((x) => modules.includes(x))) MODULES[m].run(ctx);
173
190
  const synced = sync(ctx, modules);
191
+ if (prune) ins.prune(shippedFiles());
174
192
  return { ins, synced };
175
193
  }
176
194
 
195
+ // Every path this version can write, for all agents and modules: what a repo leaves out is still shipped.
196
+ function shippedFiles() {
197
+ const ins = new Installer({ root: path.join(os.tmpdir(), "ccwf-none", String(process.pid)), dryRun: true });
198
+ const ctx = { ins, agents: AGENTS, params: makeParams({ agents: AGENTS }) };
199
+ for (const m of ORDER) MODULES[m].run(ctx);
200
+ return new Set(ins.log.map((l) => l.rel));
201
+ }
202
+
177
203
  function projectNextSteps(synced) {
178
204
  if (!synced.cbm) {
179
205
  console.log(" next: codebase-memory is not set up here. Run `npx @mayurdluffy/cbm-cli install --agents claude,codex,cursor`, then `npx @mayurdluffy/ccwf sync` (see docs/agents/setup.md)");
@@ -188,34 +214,39 @@ function projectNextSteps(synced) {
188
214
  // ---- machine ----
189
215
 
190
216
  async function machineSetup({ agents, modules, root, opts, fixOnly = false }) {
191
- const items = machine.plan({ agents, modules, repoRoot: root });
217
+ const items = machine.plan({ agents, modules, repoRoot: root, extraSkills: opts["extra-skills"] });
192
218
  const missing = items.filter((i) => i.status === "missing");
193
219
  console.log("machine:");
194
220
  for (const i of items) console.log(` ${i.status === "ok" ? "✓" : "✗"} ${i.label}`);
195
- if (missing.length === 0) return console.log(" everything is installed");
221
+ if (missing.length === 0) {
222
+ console.log(" everything is installed");
223
+ return 0;
224
+ }
196
225
 
197
226
  for (const i of missing.filter((m) => m.kind === "manual")) console.log(` by hand: ${i.hint}`);
198
227
  const todo = missing.filter((i) => i.kind !== "manual");
199
- if (todo.length === 0) return;
228
+ if (todo.length === 0 || opts.check) return missing.length;
200
229
 
201
230
  const dry = opts["dry-run"];
202
231
  console.log(dry ? "\nWould run:" : "\nWill run:");
203
232
  for (const i of todo) console.log(` - ${i.kind === "run" ? (dry ? i.cmd : i.summary || i.cmd) : i.hint}`);
204
- if (dry) return;
233
+ if (dry) return missing.length;
205
234
  const go = opts.yes || (await confirm("Install all?"));
206
235
  if (!go) {
207
236
  console.log(!process.stdin.isTTY && !opts.yes ? " skipped: not a terminal; re-run with --yes to install" : " skipped");
208
- return;
237
+ return missing.length;
209
238
  }
210
239
  for (const r of machine.run(todo)) console.log(` ${r.ok ? "installed" : "FAILED"}: ${r.id}${r.error ? ` (${r.error})` : ""}`);
211
240
  console.log(`\nLog in once (cannot be scripted): ${machine.loginHints(agents).join(" · ")}`);
212
241
  if (!fixOnly) console.log("Restart your coding agents so they see new skills.");
242
+ return 0;
213
243
  }
214
244
 
215
245
  // ---- commands ----
216
246
 
217
247
  async function install(cmd, opts, root) {
218
248
  const prev = loadManifest(root);
249
+ if (!opts["machine-only"]) refuseDowngrade(prev, opts.force);
219
250
  let agents;
220
251
  let modules;
221
252
  const ejected = prev?.ejected || [];
@@ -224,7 +255,7 @@ async function install(cmd, opts, root) {
224
255
  ({ agents, modules } = prev);
225
256
  } else {
226
257
  agents = list(opts.agents ?? (prev?.agents || AGENTS).join(","), AGENTS, "agent");
227
- modules = list(opts.modules ?? "all", ORDER, "module");
258
+ modules = list(opts.modules ?? (prev?.modules?.join(",") || DEFAULT_MODULES.join(",")), ORDER, "module");
228
259
  // Re-init keeps modules already installed, the same way add does.
229
260
  if (prev && (cmd === "add" || cmd === "init")) modules = [...new Set([...(prev.modules || []), ...modules])];
230
261
  if (!modules.includes("core")) modules.unshift("core");
@@ -233,11 +264,15 @@ async function install(cmd, opts, root) {
233
264
  let synced = { cbm: true };
234
265
  if (!opts["machine-only"]) {
235
266
  if (!fs.existsSync(path.join(root, ".git"))) console.log(" note: not a git repo root; ccwf works anyway, but `commit`/`orchestrate-workers` expect git");
236
- const r = applyProject({ root, agents, modules, ejected, prev, dryRun: opts["dry-run"], force: opts.force });
267
+ const r = applyProject({ root, agents, modules, ejected, prev, dryRun: opts["dry-run"], force: opts.force, prune: cmd === "update" });
237
268
  synced = r.synced;
269
+ r.ins.commit();
238
270
  if (cmd === "update" && prev.ccwf !== pkg.version) console.log(`update: ccwf ${prev.ccwf} -> ${pkg.version}`);
239
271
  report(r.ins, opts["dry-run"]);
240
272
  if (!opts["dry-run"]) saveManifest(root, { agents, modules, ejected, ...tracked(r.ins) });
273
+ if (modules.includes("guardrails") && !prev?.modules?.includes("guardrails")) {
274
+ console.log(" next: check the commands in .agents/guardrails/checks.conf and commit the folder. To run the quick ones before each commit: .agents/guardrails/check.sh --install-hook. In CI: .agents/guardrails/check.sh --all");
275
+ }
241
276
  }
242
277
  if (!opts["project-only"] && cmd === "init") await machineSetup({ agents, modules, root, opts });
243
278
  if (!opts["machine-only"]) projectNextSteps(synced);
@@ -246,10 +281,12 @@ async function install(cmd, opts, root) {
246
281
  async function runSync(opts, root) {
247
282
  const prev = loadManifest(root);
248
283
  if (!prev) throw new Error(`no ${MANIFEST} here; run \`ccwf init\` first`);
284
+ refuseDowngrade(prev, opts.force);
249
285
  // Settings and the navigation block only. Re-rendering templates is update's job.
250
286
  const ins = new Installer({ root, dryRun: opts["dry-run"], force: false, ejected: prev.ejected || [], version: pkg.version, ...tracked(prev) });
251
287
  const agents = prev.agents;
252
288
  const synced = sync({ ins, agents, params: makeParams({ agents }) }, prev.modules);
289
+ ins.commit();
253
290
  report(ins, opts["dry-run"]);
254
291
  if (!opts["dry-run"]) saveManifest(root, { ...prev, ...tracked(ins) }, prev.ccwf);
255
292
  console.log(`allowed sites: ${synced.domains}${synced.cbm ? " · codebase-memory rules: on" : ""}`);
@@ -261,53 +298,119 @@ function eject(opts, root) {
261
298
  const prev = loadManifest(root);
262
299
  if (!prev) throw new Error(`no ${MANIFEST} here; run \`ccwf init\` first`);
263
300
  const dir = `.agents/skills/${name}`;
264
- if (!name || !fs.existsSync(path.join(root, dir))) throw new Error(`usage: ccwf eject <skill> (no ${dir})`);
301
+ const skills = fs.readdirSync(path.join(TEMPLATES, "skills"));
302
+ if (!skills.includes(name)) throw new Error(`usage: ccwf eject <skill> (one of ${skills.join(", ")})`);
303
+ if (!fs.existsSync(path.join(root, dir))) throw new Error(`${dir} is not in this repo`);
265
304
  const ejected = [...new Set([...(prev.ejected || []), dir])];
266
305
  const files = Object.fromEntries(Object.entries(prev.files).filter(([rel]) => !rel.startsWith(dir + "/")));
267
- saveManifest(root, { ...prev, ejected, files });
306
+ saveManifest(root, { ...prev, ejected, files }, prev.ccwf);
268
307
  console.log(`ejected ${name}: ccwf no longer touches ${dir}/`);
269
308
  }
270
309
 
310
+ // What differs from what ccwf wrote. Edits to its files and blocks are allowed (update merges them);
311
+ // `problems` counts what is not: missing pieces, settings without ccwf's values, conflict markers.
312
+ function inspect(root, m) {
313
+ const lines = [];
314
+ let problems = 0;
315
+ const problem = (line) => {
316
+ problems++;
317
+ lines.push(line);
318
+ };
319
+ const read = (rel) => {
320
+ try {
321
+ return fs.readFileSync(path.join(root, rel), "utf8");
322
+ } catch {
323
+ return null;
324
+ }
325
+ };
326
+ const compare = (label, cur, hash) => {
327
+ if (cur === null) problem(`missing: ${label}`);
328
+ else if (sha(cur) !== hash) lines.push(`modified: ${label}`);
329
+ };
330
+ for (const [rel, hash] of Object.entries(m.files || {})) compare(rel, read(rel), hash);
331
+ for (const [key, hash] of Object.entries(m.blocks || {})) {
332
+ const at = key.lastIndexOf("#");
333
+ const rel = key.slice(0, at);
334
+ const body = getBlock(read(rel) ?? "", key.slice(at + 1), rel.endsWith(".toml") ? "hash" : "md");
335
+ compare(`${rel} (block ${key.slice(at + 1)})`, body === null ? null : body + "\n", hash);
336
+ }
337
+ // Settings and links are not in the manifest: work out what this version would write.
338
+ const same = m.ccwf === pkg.version;
339
+ try {
340
+ const { ins } = applyProject({ root, agents: m.agents, modules: m.modules, ejected: m.ejected || [], prev: m, dryRun: true, offline: true });
341
+ const odd = new Map(ins.log.filter((l) => l.kind !== "file" && l.state !== "unchanged").map((l) => [l.rel, l]));
342
+ for (const { rel, state, kind } of odd.values()) {
343
+ if (kind === "link") problem(`${state === "created" ? "missing link" : "not a link to ccwf's skill"}: ${rel}`);
344
+ else if (same) problem(`settings differ: ${rel}`);
345
+ }
346
+ } catch (err) {
347
+ problem(`cannot check the settings: ${err.message}`);
348
+ }
349
+ if (!same) lines.push(`not checked: agent settings (written by ccwf ${m.ccwf}, this is ${pkg.version})`);
350
+ const paths = [...new Set([...Object.keys(m.files || {}), ...Object.keys(m.seeds || {}), ...Object.keys(m.blocks || {}).map((k) => k.split("#")[0])])];
351
+ const conflicts = paths.filter((rel) => hasConflict(read(rel)));
352
+ for (const rel of conflicts) problem(`conflict markers: ${rel}`);
353
+ return { lines, problems, conflicts: conflicts.length };
354
+ }
355
+
356
+ // Prints the state of the repo and returns the number of problems.
271
357
  function status(root) {
272
358
  const m = loadManifest(root);
273
- if (!m) return console.log(`not initialised (no ${MANIFEST}); run \`ccwf init\``);
359
+ if (!m) {
360
+ console.log(`not initialised (no ${MANIFEST}); run \`ccwf init\``);
361
+ return 1;
362
+ }
274
363
  console.log(`ccwf ${m.ccwf} (installed) / ${pkg.version} (this package)`);
275
364
  console.log(`agents: ${m.agents.join(", ")}\nmodules: ${m.modules.join(", ")}`);
276
365
  if (m.ejected?.length) console.log(`ejected: ${m.ejected.join(", ")}`);
277
- let drift = 0;
278
- for (const [rel, hash] of Object.entries(m.files)) {
279
- let cur = null;
280
- try {
281
- cur = fs.readFileSync(path.join(root, rel), "utf8");
282
- } catch {}
283
- const state = cur === null ? "missing" : sha(cur) === hash ? null : "modified";
284
- if (state) {
285
- drift++;
286
- console.log(` ${state}: ${rel}`);
287
- }
366
+ const { lines, problems, conflicts } = inspect(root, m);
367
+ for (const l of lines) console.log(` ${l}`);
368
+ if (!lines.length) console.log("everything ccwf wrote is unchanged");
369
+ if (conflicts) console.log(`${conflicts} file(s) still have conflict markers from \`ccwf update\``);
370
+ return problems;
371
+ }
372
+
373
+ // Shows what update would change and offers to run it. Returns the number of problems left.
374
+ async function doctorFiles(m, opts, root) {
375
+ let r;
376
+ try {
377
+ refuseDowngrade(m, false);
378
+ r = applyProject({ root, agents: m.agents, modules: m.modules, ejected: m.ejected || [], prev: m, dryRun: true, prune: true });
379
+ } catch (err) {
380
+ console.log(`files:\n ✗ ${err.message}`);
381
+ return 1;
288
382
  }
289
- console.log(drift ? `${drift} file(s) differ from what ccwf wrote` : "all ccwf-owned files match");
290
- const paths = [...new Set([...Object.keys(m.files), ...Object.keys(m.seeds || {}), ...Object.keys(m.blocks || {}).map((k) => k.split("#")[0])])];
291
- const conflicts = paths.filter((rel) => {
292
- try {
293
- return hasConflict(fs.readFileSync(path.join(root, rel), "utf8"));
294
- } catch {
295
- return false;
296
- }
297
- });
298
- for (const rel of conflicts) console.log(` conflict markers: ${rel}`);
299
- if (conflicts.length) console.log(`${conflicts.length} file(s) still have conflict markers from \`ccwf update\``);
383
+ const changes = collapse(r.ins.log).filter((l) => l.state !== "unchanged" && l.state !== "skipped");
384
+ console.log("files:");
385
+ if (!changes.length) console.log(" ✓ nothing to update");
386
+ for (const { rel, state } of changes) console.log(` ${STATE_MARK[state]} ${rel}`);
387
+ let left = changes.length;
388
+ if (left && !opts.check && !opts["dry-run"] && (opts.yes || (await confirm("Run `ccwf update` to write these?")))) {
389
+ await install("update", { ...opts, force: false, "machine-only": false }, root);
390
+ return 0;
391
+ }
392
+ if (left) console.log(" run `ccwf update` to write these");
393
+ projectNextSteps(r.synced);
394
+ return left;
300
395
  }
301
396
 
302
397
  async function doctor(opts, root) {
303
398
  const m = loadManifest(root);
304
- if (m) status(root);
399
+ let problems = 0;
400
+ if (m) problems += status(root);
305
401
  else console.log(`(no ${MANIFEST} in ${root}: checking the machine only)`);
306
402
  console.log("");
307
403
  const agents = m?.agents || AGENTS;
308
404
  const modules = m?.modules || ORDER;
309
- await machineSetup({ agents, modules, root: m ? root : null, opts, fixOnly: true });
310
- if (m) projectNextSteps(applyProject({ root, agents, modules, ejected: m.ejected || [], prev: m, dryRun: true, force: false }).synced);
405
+ problems += await machineSetup({ agents, modules, root: m ? root : null, opts, fixOnly: true });
406
+ if (m && modules.includes("workers")) {
407
+ const conf = path.join(root, WORKERS_CONF);
408
+ const rows = fs.existsSync(conf) ? machine.rosterProblems(fs.readFileSync(conf, "utf8")) : [];
409
+ for (const p of rows) console.log(` warning: ${p}; change its row in ${WORKERS_CONF}`);
410
+ problems += rows.length;
411
+ }
412
+ if (m) problems += await doctorFiles(m, opts, root);
413
+ return problems;
311
414
  }
312
415
 
313
416
  async function main(argv = process.argv.slice(2)) {
@@ -316,9 +419,13 @@ async function main(argv = process.argv.slice(2)) {
316
419
  if (opts.version) return console.log(pkg.version);
317
420
  if (opts.help || !cmd || cmd === "help") return console.log(HELP);
318
421
  const root = path.resolve(opts.dir || process.cwd());
319
- if (cmd === "chrome-mcp") return require("./chrome-mcp").run(root, opts.print, opts.open);
320
- if (cmd === "status") return status(root);
321
- if (cmd === "doctor") return doctor(opts, root);
422
+ if (cmd === "chrome-mcp") return require("./chrome-mcp").run(root, opts.print);
423
+ if (cmd === "status" || cmd === "doctor") {
424
+ const problems = cmd === "status" ? status(root) : await doctor(opts, root);
425
+ if (opts.check && problems) process.exitCode = 1;
426
+ return;
427
+ }
428
+ if (cmd === "stats") return require("./stats").print(root, opts.json);
322
429
  if (cmd === "sync") return runSync(opts, root);
323
430
  if (cmd === "eject") return eject(opts, root);
324
431
  if (cmd === "init" || cmd === "update") return install(cmd, opts, root);
package/lib/installer.js CHANGED
@@ -5,19 +5,43 @@ const crypto = require("crypto");
5
5
  const { spawnSync } = require("child_process");
6
6
  const { upsertBlock, getBlock, mergeJson, hasTableOutsideBlock, missingMarker } = require("./merge");
7
7
  const { merge3, merge2, hasConflict } = require("./merge3");
8
+ const { publishedTemplates } = require("./published");
8
9
 
9
10
  const sha = (s) => crypto.createHash("sha256").update(s).digest("hex");
10
11
 
11
- // Applies file operations under `root`, records what it did, and never clobbers user edits.
12
+ // The path with links resolved, also when the file (or the target of a link) does not exist yet.
13
+ function realPath(p) {
14
+ try {
15
+ return fs.realpathSync(p);
16
+ } catch (err) {
17
+ if (err.code !== "ENOENT") throw err;
18
+ }
19
+ let target = null;
20
+ try {
21
+ target = fs.readlinkSync(p);
22
+ } catch {}
23
+ if (target !== null) return realPath(path.resolve(path.dirname(p), target));
24
+ const dir = path.dirname(p);
25
+ return dir === p ? p : path.join(realPath(dir), path.basename(p));
26
+ }
27
+
28
+ // Works out file operations under `root`, records what it did, and never clobbers user edits.
29
+ // Nothing is written before commit(), so a config that cannot be merged leaves the repo as it was.
12
30
  // When the user edited something ccwf wrote and the template changed too, the two are merged:
13
31
  // 3-way against the version ccwf last wrote when it can be found, else 2-way with conflict markers.
14
32
  class Installer {
15
- constructor({ root, dryRun = false, force = false, files = {}, blocks = {}, seeds = {}, ejected = [], version = "new" }) {
33
+ constructor({ root, dryRun = false, force = false, files = {}, blocks = {}, seeds = {}, ejected = [], version = "new", oldVersion = null, offline = false }) {
16
34
  this.root = root;
17
35
  this.ejected = ejected; // path prefixes the user took over (ccwf eject)
18
36
  this.dryRun = dryRun;
19
37
  this.force = force;
20
38
  this.version = version; // the ccwf version writing now, for conflict labels
39
+ this.oldVersion = oldVersion; // the ccwf version that wrote the repo, to look up its templates
40
+ this.offline = offline; // never ask the registry for them
41
+ this.writes = new Map(); // real path -> { content, mode }
42
+ this.links = []; // { rel, target }
43
+ this.removals = []; // rel
44
+ this.bases = new Set(); // contents to keep for the next merge
21
45
  this.files = { ...files }; // rel -> sha256 of the content ccwf last wrote
22
46
  this.blocks = { ...blocks }; // "rel#id" -> sha256 of the managed block body ccwf last wrote
23
47
  this.seeds = { ...seeds }; // rel -> sha256 of the seeded doc ccwf last wrote
@@ -29,23 +53,31 @@ class Installer {
29
53
  const r = spawnSync("git", args, { cwd: this.root, encoding: "utf8", maxBuffer: 64 << 20 });
30
54
  return r.status === 0 ? r.stdout : null;
31
55
  }
56
+ // The repo's shared .git folder: linked worktrees have one of their own, which the others do not see.
32
57
  gitDir() {
33
- if (this._gitDir === undefined) this._gitDir = this.git("rev-parse", "--absolute-git-dir")?.trim() || null;
58
+ if (this._gitDir === undefined) {
59
+ const dir = this.git("rev-parse", "--git-common-dir")?.trim();
60
+ this._gitDir = dir ? path.resolve(this.root, dir) : null;
61
+ }
34
62
  return this._gitDir;
35
63
  }
36
64
 
37
65
  // Keep a copy of what ccwf wrote, so the next update can merge against it (.git/ccwf/base/<sha>).
38
66
  remember(content) {
39
- const dir = this.gitDir();
40
- if (this.dryRun || !dir) return;
41
- const f = path.join(dir, "ccwf", "base", sha(content));
42
- if (fs.existsSync(f)) return;
43
- fs.mkdirSync(path.dirname(f), { recursive: true });
44
- fs.writeFileSync(f, content);
67
+ this.bases.add(content);
45
68
  }
46
69
 
47
- // The content ccwf last wrote (hash), from the local copy or else from the file's git history.
70
+ // The content ccwf last wrote (hash): the local copy, the file's git history, or the published package.
48
71
  recall(hash, rel, extract = (t) => t) {
72
+ return this.recallFromGit(hash, rel, extract) ?? this.recallPublished(hash);
73
+ }
74
+ recallPublished(hash) {
75
+ if (this.offline) return null;
76
+ this._published ??= publishedTemplates(this.oldVersion);
77
+ for (const text of this._published) for (const t of [text, text.trimEnd() + "\n"]) if (sha(t) === hash) return t;
78
+ return null;
79
+ }
80
+ recallFromGit(hash, rel, extract) {
49
81
  const dir = this.gitDir();
50
82
  if (!dir) return null;
51
83
  try {
@@ -81,24 +113,82 @@ class Installer {
81
113
  abs(rel) {
82
114
  return path.join(this.root, rel);
83
115
  }
116
+ real(rel) {
117
+ return realPath(this.abs(rel));
118
+ }
84
119
  read(rel) {
85
120
  try {
86
- return fs.readFileSync(this.abs(rel), "utf8");
121
+ return this.writes.get(this.real(rel))?.content ?? fs.readFileSync(this.abs(rel), "utf8");
87
122
  } catch {
88
123
  return null;
89
124
  }
90
125
  }
91
- note(rel, state) {
92
- this.log.push({ rel, state });
126
+ note(rel, state, kind = "file") {
127
+ this.log.push({ rel, state, kind });
93
128
  }
94
129
  warn(msg) {
95
130
  this.warnings.push(msg);
96
131
  }
97
132
  write(rel, content, mode) {
133
+ const key = this.real(rel);
134
+ this.writes.set(key, { content, mode: mode ?? this.writes.get(key)?.mode });
135
+ }
136
+
137
+ // Carry out what was worked out.
138
+ commit() {
98
139
  if (this.dryRun) return;
99
- fs.mkdirSync(path.dirname(this.abs(rel)), { recursive: true });
100
- fs.writeFileSync(this.abs(rel), content, mode ? { mode } : undefined);
101
- if (mode) fs.chmodSync(this.abs(rel), mode);
140
+ const dir = this.gitDir();
141
+ for (const content of dir ? this.bases : []) {
142
+ const f = path.join(dir, "ccwf", "base", sha(content));
143
+ if (fs.existsSync(f)) continue;
144
+ fs.mkdirSync(path.dirname(f), { recursive: true });
145
+ fs.writeFileSync(f, content);
146
+ }
147
+ for (const [file, { content, mode }] of this.writes) {
148
+ fs.mkdirSync(path.dirname(file), { recursive: true });
149
+ fs.writeFileSync(file, content, mode ? { mode } : undefined);
150
+ if (mode) fs.chmodSync(file, mode);
151
+ }
152
+ for (const { rel, target } of this.links) {
153
+ fs.mkdirSync(path.dirname(this.abs(rel)), { recursive: true });
154
+ try {
155
+ fs.symlinkSync(target, this.abs(rel), "dir");
156
+ } catch (err) {
157
+ throw new Error(`${rel}: could not create symlink (${err.code || err.message})`);
158
+ }
159
+ }
160
+ for (const rel of this.removals) this.removeNow(rel);
161
+ }
162
+
163
+ // Delete a file, the folders it leaves empty, and the Claude link to a skill that is gone with it.
164
+ removeNow(rel) {
165
+ fs.rmSync(this.abs(rel), { force: true });
166
+ try {
167
+ for (let d = path.dirname(rel); d !== "."; d = path.dirname(d)) fs.rmdirSync(this.abs(d));
168
+ } catch {} // not empty
169
+ const skill = /^\.agents\/skills\/([^/]+)\//.exec(rel)?.[1];
170
+ if (!skill || fs.existsSync(this.abs(`.agents/skills/${skill}`))) return;
171
+ const link = this.abs(`.claude/skills/${skill}`);
172
+ try {
173
+ if (fs.readlinkSync(link) === `../../.agents/skills/${skill}`) fs.unlinkSync(link);
174
+ } catch {}
175
+ }
176
+
177
+ // Files an older ccwf wrote that are not in `shipped` any more: removed when unedited, else left to the user.
178
+ prune(shipped) {
179
+ const top = realPath(this.root) + path.sep;
180
+ for (const [rel, hash] of Object.entries(this.files)) {
181
+ if (shipped.has(rel)) continue;
182
+ // The list is a file in the repo: never follow it, or a link, to somewhere else.
183
+ if (path.isAbsolute(rel) || !this.real(rel).startsWith(top)) continue;
184
+ const cur = this.read(rel);
185
+ delete this.files[rel];
186
+ if (cur === null) continue;
187
+ if (sha(cur) === hash) {
188
+ this.removals.push(rel);
189
+ this.note(rel, "removed");
190
+ } else this.warn(`${rel}: no longer part of ccwf; you edited it, so it stays. Delete it if you do not need it`);
191
+ }
102
192
  }
103
193
 
104
194
  // A file ccwf owns: replaced on update while it still matches what ccwf wrote; merged when the user edited it.
@@ -223,7 +313,9 @@ class Installer {
223
313
  // Codex TOML: a managed block, unless the user already defines the same table by hand.
224
314
  tomlBlock(rel, id, body, tables) {
225
315
  const cur = this.read(rel) ?? "";
226
- const clash = tables.find((t) => hasTableOutsideBlock(cur, id, t));
316
+ // A hand-written sub-table named like a key the body sets would define it a second time.
317
+ const keys = [...body.matchAll(/^([\w-]+)\s*=/gm)].map((m) => m[1]);
318
+ const clash = tables.find((t) => hasTableOutsideBlock(cur, id, t, keys));
227
319
  if (clash) {
228
320
  this.warn(`${rel}: [${clash}] already defined by hand, skipped ${id}`);
229
321
  return this.note(rel, "skipped");
@@ -235,10 +327,10 @@ class Installer {
235
327
  json(rel, patch, union = []) {
236
328
  const cur = this.read(rel) ?? "";
237
329
  const next = mergeJson(cur, patch, rel, union);
238
- if (next === cur) return this.note(rel, "unchanged");
330
+ if (next === cur) return this.note(rel, "unchanged", "json");
239
331
  const existed = cur !== "";
240
332
  this.write(rel, next);
241
- this.note(rel, existed ? "updated" : "created");
333
+ this.note(rel, existed ? "updated" : "created", "json");
242
334
  }
243
335
 
244
336
  // Relative symlink. A failure is an error for this skill; the files are not copied.
@@ -247,20 +339,13 @@ class Installer {
247
339
  try {
248
340
  cur = fs.readlinkSync(this.abs(rel));
249
341
  } catch {}
250
- if (cur === target) return this.note(rel, "unchanged");
342
+ if (cur === target) return this.note(rel, "unchanged", "link");
251
343
  if (fs.existsSync(this.abs(rel)) || cur !== null) {
252
344
  this.warn(`${rel}: already exists and is not the expected link, left as is`);
253
- return this.note(rel, "skipped");
254
- }
255
- if (!this.dryRun) {
256
- fs.mkdirSync(path.dirname(this.abs(rel)), { recursive: true });
257
- try {
258
- fs.symlinkSync(target, this.abs(rel), "dir");
259
- } catch (err) {
260
- throw new Error(`${rel}: could not create symlink (${err.code || err.message})`);
261
- }
345
+ return this.note(rel, "skipped", "link");
262
346
  }
263
- this.note(rel, "created");
347
+ this.links.push({ rel, target });
348
+ this.note(rel, "created", "link");
264
349
  }
265
350
  }
266
351