@mayurdluffy/ccwf 0.5.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 (38) hide show
  1. package/README.md +19 -13
  2. package/lib/chrome-mcp.js +63 -13
  3. package/lib/index.js +171 -64
  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/SKILL.md +5 -4
  35. package/templates/skills/verify-ui/ab.sh +9 -0
  36. package/templates/skills/verify-ui/lib.sh +59 -0
  37. package/templates/skills/verify-ui/probe.sh +6 -3
  38. package/templates/skills/verify-ui/run.sh +21 -7
package/README.md CHANGED
@@ -3,19 +3,19 @@
3
3
  [![npm](https://img.shields.io/npm/v/@mayurdluffy/ccwf?logo=npm)](https://www.npmjs.com/package/@mayurdluffy/ccwf)
4
4
  [![License](https://img.shields.io/badge/license-MIT-blue.svg)](https://opensource.org/licenses/MIT)
5
5
 
6
- One command that sets up the same agent system on any computer and in any repo, for **Claude Code, Codex and Cursor** (only those three; macOS and Linux).
6
+ One command that sets up the same agent system on any computer and in any repo, for **Claude Code, Codex and Cursor** (only those three; macOS and Linux). Needs Node 22 or newer.
7
7
 
8
8
  ```bash
9
9
  cd your-repo
10
10
  npx @mayurdluffy/cbm-cli install --agents claude,codex,cursor # code-graph MCP first (see docs/agents/setup.md after init)
11
- npx @mayurdluffy/ccwf init # tools + user-level skills + project files
11
+ npx @mayurdluffy/ccwf@latest init # tools + user-level skills + project files
12
12
  ```
13
13
 
14
- `init` shows what is missing on your machine, installs it after one confirmation, then writes the project files. `--yes` skips the question: it runs vendor install scripts from the network and installs skills from the current head of third-party repos. Re-running is safe: your own text and config keys are kept. `--force` overwrites only files ccwf owns, never seeded docs.
14
+ `init` shows what is missing on your machine, installs it after one confirmation, then writes the project files. `--yes` skips the question: it runs vendor install scripts from the network and installs third-party skills from fixed commits. Re-running is safe: your own text and config keys are kept. `--force` overwrites only files ccwf owns, never seeded docs. A config ccwf cannot merge (a comment in `.mcp.json`, for example) stops it before it writes anything.
15
15
 
16
16
  ## What you get
17
17
 
18
- **On the machine (once):** the pinned user-level skills (`mattpocock/skills`, `find-skills`), `agent-browser`, `herdr` + `hc`, `gh`, `ffmpeg`, the Claude / Codex / Cursor CLIs you pick, and Codex trust for the repo. Chrome and logins are checked and explained, not installed.
18
+ **On the machine (once):** the 15 user-level skills this workflow uses (`mattpocock/skills`, at a commit fixed in ccwf; `--extra-skills` adds 24 more), `agent-browser`, `herdr` + `hc`, `gh`, `ffmpeg`, the Claude / Codex / Cursor CLIs you pick, and Codex trust for the repo. Chrome and logins are checked and explained, not installed.
19
19
 
20
20
  **In the repo (committed):**
21
21
 
@@ -25,7 +25,8 @@ npx @mayurdluffy/ccwf init # tools + user-level skills + project files
25
25
  | `memory` | `.agent-memory/MEMORY.md` + rules |
26
26
  | `tracking` | `docs/ROADMAP.md` (session entry point: product, order of work, efforts with their `progress.md`), empty `docs/GLOSSARY.md`, `DECISIONS.md`, `FEATURES.md`, `BACKLOG.md`, `adr/`, `learnings/` + `save-learning` skill + rules; `docs/agents/{domain,issue-tracker,triage-labels}.md` |
27
27
  | `browser` | `agent-browser` + `verify-ui` skills, `chrome-devtools` MCP, `.cursor/cli.json`, Claude MCP approval and allowed sites |
28
- | `workers` | `orchestrate-workers` skill (a `workers` tab of four panes in the orchestrator's own herdr space, `hc` reference, `workers.conf`) |
28
+ | `guardrails` (only when asked for: `ccwf add guardrails`) | `.agents/guardrails/check.sh` runs your project's checks from `checks.conf` and looks for new secrets. The same script serves workers (a finished one is sent back once if it fails), git commits (`--install-hook`) and CI (`--all`) |
29
+ | `workers` | `orchestrate-workers` skill (a `workers` tab of four panes in the orchestrator's own herdr space, `hc` reference, `workers.conf`). A `reviewer` row in `workers.conf` turns on an independent review of every ticket. `isolation worktree` gives each worker a folder of its own, which is deleted once its work is merged |
29
30
 
30
31
  Skills live in `.agents/skills/` (Codex, Cursor); Claude Code gets symlinks in `.claude/skills/`. Files are written only for the agents you select.
31
32
 
@@ -39,13 +40,14 @@ A skill that needs project settings asks you the first time it runs and saves th
39
40
 
40
41
  | Command | What it does |
41
42
  |---|---|
42
- | `ccwf init` | machine setup + repo setup (`--agents`, `--modules`, `--project-only`, `--machine-only`, `--yes`, `--dry-run`, `--force`, `--dir`) |
43
+ | `ccwf init` | machine setup + repo setup; a repo that has ccwf keeps its modules (add one with `--modules` or `ccwf add`) (`--agents`, `--modules`, `--project-only`, `--machine-only`, `--yes`, `--dry-run`, `--force`, `--dir`) |
43
44
  | `ccwf add <module>` | add a module |
44
45
  | `ccwf update` | the only command that re-renders templates from this ccwf version; files you edited are merged, not overwritten (see below) |
45
46
  | `ccwf sync` | push skill settings into agent configs and add navigation rules; does not re-render templates |
46
- | `ccwf doctor` | check tools, skills and files; offer to fix |
47
+ | `ccwf doctor` | check tools, skills and files; offer to install what is missing and to run `update` (`--yes` does both). `--check` changes nothing and exits 1 on problems |
48
+ | `ccwf stats` | worker runs in this repo per model and folder mode: done, first try, time, fix rounds, failed checks (`--json`). Recorded in `.git/ccwf/runs.jsonl` on your computer only, without prompts or code |
47
49
  | `ccwf eject <skill>` | stop managing a skill you changed |
48
- | `ccwf status` | installed modules, drifted files |
50
+ | `ccwf status` | installed modules; files, managed blocks, settings and links that differ. `--check` exits 1 when something is missing or broken; your edits do not count |
49
51
 
50
52
  State is in `.ccwf.json` (choices and a hash of every file, managed block and seeded doc ccwf wrote). Commit it.
51
53
 
@@ -58,26 +60,27 @@ npx @mayurdluffy/ccwf@latest update
58
60
  `update` brings in new skills, scripts, rules and docs and keeps everything you wrote:
59
61
 
60
62
  - **Your own text in `AGENTS.md`** (domain notes, anything outside the `<!-- ccwf:begin/end -->` markers) is never touched. If you edited inside a managed block, your edit is merged with the new block.
61
- - **Files ccwf owns** (skills, scripts, guides): untouched ones are replaced; ones you edited are merged 3-way against the version ccwf last wrote (kept in `.git/ccwf/base/`, or found in git history after a fresh clone).
63
+ - **Files ccwf owns** (skills, scripts, guides): untouched ones are replaced; ones you edited are merged 3-way against the version ccwf last wrote (kept in `.git/ccwf/base/`, or found in git history or the published package after a fresh clone). Files a new version no longer has are removed if you never edited them.
62
64
  - **Seeded docs** (`docs/GLOSSARY.md`, `DECISIONS.md`, ...): new template lines are merged in; your entries stay. `workers.conf` (your roster) is never re-rendered.
63
65
  - Where your edit and the new version change the same lines, the file gets git-style markers (`<<<<<<< current` / `=======` / `>>>>>>> incoming (ccwf X)`) and a warning; `ccwf status` lists files that still have them, and `update` skips them until you resolve them.
64
66
  - `--dry-run` shows what would change (`*` merged, `x` conflict); `--force` replaces files ccwf owns instead of merging; `ccwf eject <skill>` stops managing a skill.
67
+ - An older ccwf refuses to write to a repo set up by a newer one (`--force` overrides).
65
68
 
66
69
  ## What a first run looks like
67
70
 
68
71
  ```text
69
- $ npx @mayurdluffy/ccwf init
72
+ $ npx @mayurdluffy/ccwf@latest init
70
73
  + AGENTS.md
71
74
  + .agents/skills/commit/SKILL.md
72
75
  ...
73
76
  repo: 40 created, 0 updated, 0 unchanged, 0 skipped
74
77
  machine:
75
- ✗ mattpocock/skills skills (0/38 installed)
78
+ ✗ mattpocock/skills skills (0/15 installed)
76
79
  ✓ gh (GitHub CLI)
77
80
  ✗ Codex trusts this repo
78
81
 
79
82
  Will run:
80
- - install 38 skills from mattpocock/skills with `npx skills add` (full command: ccwf init --machine-only --dry-run)
83
+ - install 15 skills from mattpocock/skills with `npx skills add` (full command: ccwf init --machine-only --dry-run)
81
84
  - add [projects."/path/to/repo"] trust_level = "trusted" to ~/.codex/config.toml
82
85
  Install all? [Y/n]:
83
86
  ```
@@ -91,6 +94,7 @@ Then follow `docs/agents/workflow.md` in your repo. Commit `.ccwf.json` and the
91
94
  | `skipped: not a terminal; re-run with --yes` | run `ccwf init --yes` from a terminal script, or install by hand from `docs/agents/setup.md` |
92
95
  | `warning: <file>: your edits and the new version overlap` | resolve the `<<<<<<< current` / `>>>>>>> incoming` markers in that file, then commit |
93
96
  | `warning: <file>: merged without the previous ccwf version` | no record of what ccwf wrote last time: your lines and the new lines were combined; read the file once |
97
+ | `this repo was set up by ccwf X and this is Y` | `npx` ran an older copy: use `npx @mayurdluffy/ccwf@latest` |
94
98
  | `... already defined by hand, skipped` | you wrote that config table yourself; ccwf leaves it alone |
95
99
  | `next: codebase-memory is not set up here` | run `npx @mayurdluffy/cbm-cli install --agents claude,codex,cursor`, then `ccwf sync` |
96
100
  | anything else | `ccwf doctor` checks tools, skills and files and offers to fix them |
@@ -104,6 +108,8 @@ Then follow `docs/agents/workflow.md` in your repo. Commit `.ccwf.json` and the
104
108
 
105
109
  `node scripts/harvest.js <repo> --terms yourproduct` diffs a working repo's skills against `templates/skills/`, flags project-specific lines, and with `--apply` copies the clean ones. Not published to npm.
106
110
 
111
+ Before and after changing a skill, run its tasks in [evals/](evals/README.md). They use paid agent sessions and never run in CI.
112
+
107
113
  ## Releasing
108
114
 
109
115
  Push a tag `vX.Y.Z`; `.github/workflows/publish.yml` publishes with npm trusted publishing (OIDC), so no npm token is stored in the repo.
@@ -114,7 +120,7 @@ Issues and PRs are welcome; see [CONTRIBUTING.md](CONTRIBUTING.md).
114
120
 
115
121
  ## Agent browser
116
122
 
117
- Chrome DevTools MCP opens the system's Chrome when an agent first needs it: a visible window with a profile of its own per project under `~/.cache/ccwf/chrome/`, so logins persist and your everyday Chrome profile is never touched. A second agent on the same project, while the first holds that profile, gets a temporary isolated profile. URL patterns from verify-ui.conf apply in both cases. Run `ccwf chrome-mcp --print` to inspect the launch command. The pinned MCP requires Node 20.19+, 22.12+, or newer supported releases and Chrome 149+ for URL restrictions.
123
+ Chrome DevTools MCP opens the system's Chrome when an agent first needs it: a visible window with a profile of its own per project under `~/.cache/ccwf/chrome/`, so logins persist and your everyday Chrome profile is never touched. The first agent to start on a project holds that profile until it exits; other agents on the same project, and all workers, get a temporary isolated one. URL patterns from verify-ui.conf apply in both cases. Run `ccwf chrome-mcp --print` to inspect the launch command. The pinned MCP requires Node 20.19+, 22.12+, or newer supported releases and Chrome 149+ for URL restrictions.
118
124
 
119
125
  ## License
120
126
 
package/lib/chrome-mcp.js CHANGED
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  const { spawn } = require("node:child_process");
3
3
  const { createHash } = require("node:crypto");
4
+ const { existsSync, readlinkSync, unlinkSync } = require("node:fs");
4
5
  const fs = require("node:fs/promises");
5
6
  const { isIP } = require("node:net");
6
7
  const os = require("node:os");
@@ -9,15 +10,18 @@ const { CONF, parseConf, validSiteList } = require("./modules");
9
10
 
10
11
  const CHROME_MCP = "chrome-devtools-mcp@1.14.0";
11
12
 
13
+ // Means the same as the list does for agent-browser: a host is that host only, and *.example.com is
14
+ // example.com with its subdomains.
12
15
  function urlPatterns(sites) {
13
16
  if (!validSiteList(sites)) throw new Error("verify-ui.conf: invalid ALLOWED_DOMAINS site list");
14
- return [...new Set(sites.toLowerCase().split(","))].flatMap((site) => {
17
+ return [...new Set(sites.toLowerCase().split(","))].flatMap((entry) => {
18
+ const site = entry.replace(/^\*\./, "");
15
19
  if (site === "localhost" || isIP(site)) return [`http://${site}:*/*`, `https://${site}:*/*`];
16
- const hosts = [site, `*.${site}`];
20
+ const hosts = entry === site ? [site] : [site, `*.${site}`];
17
21
  const protocols = site.endsWith(".local") || site.endsWith(".localhost") || !site.includes(".")
18
22
  ? ["https", "http"] : ["https"];
19
23
  return protocols.flatMap((protocol) => hosts.map((host) => `${protocol}://${host}/*`));
20
- });
24
+ }).filter((pattern, i, all) => all.indexOf(pattern) === i);
21
25
  }
22
26
 
23
27
  async function projectConfig(root) {
@@ -27,34 +31,80 @@ async function projectConfig(root) {
27
31
  return parseConf(config);
28
32
  }
29
33
 
34
+ // An agent may start the server from a subfolder: the project is the nearest folder above with
35
+ // .ccwf.json, looked for up to the repo's top. Without one, the start folder itself.
36
+ function projectRoot(start) {
37
+ for (let dir = path.resolve(start); ; dir = path.dirname(dir)) {
38
+ if (existsSync(path.join(dir, ".ccwf.json"))) return dir;
39
+ if (existsSync(path.join(dir, ".git")) || dir === path.dirname(dir)) return path.resolve(start);
40
+ }
41
+ }
42
+
43
+ function alive(pid) {
44
+ if (!Number.isInteger(pid) || pid < 1) return false;
45
+ try { process.kill(pid, 0); return true; }
46
+ catch (err) { return err.code === "EPERM"; }
47
+ }
48
+
30
49
  // Chrome holds a profile with a SingletonLock symlink to "<host>-<pid>".
31
50
  async function profileInUse(dir) {
32
51
  let target;
33
52
  try { target = await fs.readlink(path.join(dir, "SingletonLock")); }
34
53
  catch (err) { if (err.code === "ENOENT") return false; throw err; }
35
- const pid = Number(target.slice(target.lastIndexOf("-") + 1));
36
- if (!Number.isInteger(pid) || pid < 1) return false;
37
- try { process.kill(pid, 0); return true; }
38
- catch (err) { return err.code === "EPERM"; }
54
+ return alive(Number(target.slice(target.lastIndexOf("-") + 1)));
55
+ }
56
+
57
+ // One wrapper per project holds the profile from its start, because Chrome itself only locks it on
58
+ // the first browser call. The lease is a symlink to the holder's pid (created in one step, like
59
+ // Chrome's own lock); a dead holder's lease is moved aside, never deleted in place, so two agents
60
+ // that both find it stale cannot both win.
61
+ async function takeLease(file) {
62
+ const mine = String(process.pid);
63
+ for (let attempt = 0; attempt < 5; attempt++) {
64
+ try {
65
+ await fs.symlink(mine, file);
66
+ process.once("exit", () => {
67
+ try { if (readlinkSync(file) === mine) unlinkSync(file); } catch {}
68
+ });
69
+ return true;
70
+ } catch (err) { if (err.code !== "EEXIST") throw err; }
71
+ let holder;
72
+ try { holder = await fs.readlink(file); }
73
+ catch (err) { if (err.code === "ENOENT") continue; throw err; }
74
+ if (alive(Number(holder))) return false;
75
+ const aside = `${file}.${mine}`;
76
+ try { await fs.rename(file, aside); }
77
+ catch (err) { if (err.code === "ENOENT") continue; throw err; }
78
+ const moved = await fs.readlink(aside);
79
+ await fs.unlink(aside);
80
+ if (moved !== holder) { // another agent took over in between: give its lease back
81
+ await fs.symlink(moved, file).catch(() => {});
82
+ return false;
83
+ }
84
+ }
85
+ return false;
39
86
  }
40
87
 
41
88
  // Like Antigravity's agent browser: the system Chrome, visible, launched on the first browser
42
- // tool call, with a profile of its own per project so logins persist between sessions. A second
43
- // agent on a profile Chrome already holds gets a throwaway one instead of a launch error.
44
- async function command(root, { cacheHome = process.env.XDG_CACHE_HOME || path.join(os.homedir(), ".cache") } = {}) {
89
+ // tool call, with a profile of its own per project so logins persist between sessions. A worker
90
+ // (CCWF_BROWSER=isolated) and a second agent on the same project get a throwaway one instead.
91
+ // `lease` keeps the profile for this process; without it the command is only worked out.
92
+ async function command(root, { lease = false, cacheHome = process.env.XDG_CACHE_HOME || path.join(os.homedir(), ".cache") } = {}) {
45
93
  const conf = await projectConfig(root);
46
94
  const patterns = urlPatterns(conf.ALLOWED_DOMAINS || "localhost");
47
95
  const id = createHash("sha256").update(path.resolve(root)).digest("hex").slice(0, 12);
48
96
  const profile = path.join(cacheHome, "ccwf", "chrome", `${path.basename(path.resolve(root))}-${id}`);
49
97
  await fs.mkdir(profile, { recursive: true, mode: 0o700 });
50
98
  await fs.chmod(profile, 0o700);
51
- const browser = await profileInUse(profile) ? ["--isolated"] : ["--userDataDir", profile];
99
+ const own = process.env.CCWF_BROWSER !== "isolated" && !(await profileInUse(profile)) && (!lease || await takeLease(`${profile}.lease`));
100
+ const browser = own ? ["--userDataDir", profile] : ["--isolated"];
52
101
  return ["npx", "-y", CHROME_MCP, ...browser,
53
102
  "--allowedUrlPattern", ...patterns, "--no-usage-statistics", "--no-performance-crux"];
54
103
  }
55
104
 
56
- async function run(root, print) {
57
- const [program, ...args] = await command(root);
105
+ async function run(start, print) {
106
+ const root = projectRoot(start);
107
+ const [program, ...args] = await command(root, { lease: !print });
58
108
  if (print) {
59
109
  console.log([program, ...args].map((arg) => /^[\w./@:-]+$/.test(arg) ? arg : `'${arg}'`).join(" "));
60
110
  return;
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
 
@@ -23,47 +27,50 @@ Usage: ccwf <command> [options]
23
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", "help", "version"]);
43
- const VALUED = new Set(["agents", "modules", "dir"]);
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)) {
@@ -317,8 +420,12 @@ async function main(argv = process.argv.slice(2)) {
317
420
  if (opts.help || !cmd || cmd === "help") return console.log(HELP);
318
421
  const root = path.resolve(opts.dir || process.cwd());
319
422
  if (cmd === "chrome-mcp") return require("./chrome-mcp").run(root, opts.print);
320
- if (cmd === "status") return status(root);
321
- if (cmd === "doctor") return doctor(opts, root);
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);