@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/machine.js CHANGED
@@ -7,7 +7,8 @@ const { spawnSync } = require("child_process");
7
7
  const MACHINE = require("../templates/machine.json");
8
8
 
9
9
  const SKILLS_AGENT_ID = { claude: "claude-code", codex: "codex", cursor: "cursor" };
10
- const SKILL_DIR = { claude: ".claude/skills", codex: ".agents/skills", cursor: ".cursor/skills" };
10
+ // Where each agent finds user-level skills. The skills CLI puts Cursor's in ~/.agents/skills.
11
+ const SKILL_DIRS = { claude: [".claude/skills"], codex: [".agents/skills"], cursor: [".cursor/skills", ".agents/skills"] };
11
12
  const AGENT_CLI = {
12
13
  claude: { bin: "claude", cmd: "curl -fsSL https://claude.ai/install.sh | bash", login: "claude" },
13
14
  codex: { bin: "codex", cmd: "curl -fsSL https://chatgpt.com/codex/install.sh | sh", login: "codex login" },
@@ -38,26 +39,29 @@ function projectHeader(repoRoot) {
38
39
  return `[projects.${tomlQuoted(repoRoot)}]`;
39
40
  }
40
41
 
41
- function repoTrusted(text, repoRoot) {
42
- const header = projectHeader(repoRoot);
42
+ // "trusted", "named" (the config has an entry for this repo that does not trust it) or "absent".
43
+ // TOML forbids defining a table twice, so only an absent project may be appended.
44
+ function trustState(text, repoRoot) {
45
+ const keys = [tomlQuoted(repoRoot), `'${repoRoot}'`].map((k) => k.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|");
46
+ const header = new RegExp(`^\\[\\s*projects\\s*\\.\\s*(?:${keys})\\s*\\]\\s*(?:#.*)?$`);
47
+ const asKey = new RegExp(`^(?:\\[?\\s*projects\\s*\\.\\s*)?(?:${keys})\\s*[.=\\]]`);
43
48
  let inTable = false;
49
+ let state = "absent";
44
50
  for (const line of String(text).split(/\r?\n/)) {
45
51
  const trimmed = line.trim();
46
- if (trimmed.startsWith("[")) {
47
- inTable = trimmed === header;
48
- continue;
49
- }
50
- if (inTable && trimmed === 'trust_level = "trusted"') return true;
52
+ if (header.test(trimmed) || asKey.test(trimmed)) state = "named";
53
+ if (trimmed.startsWith("[")) inTable = header.test(trimmed);
54
+ else if (inTable && /^trust_level\s*=\s*(["'])trusted\1\s*(?:#.*)?$/.test(trimmed)) return "trusted";
51
55
  }
52
- return false;
56
+ return state;
53
57
  }
54
58
 
55
59
  function skillVisible(exists, home, agent, name) {
56
- return exists(path.join(home, SKILL_DIR[agent], name));
60
+ return SKILL_DIRS[agent].some((dir) => exists(path.join(home, dir, name)));
57
61
  }
58
62
 
59
63
  // items: { id, label, status: "ok" | "missing", kind: "run" | "edit" | "manual", cmd?, hint?, apply?, detect? }
60
- function plan({ agents, modules, repoRoot, env = realEnv() }) {
64
+ function plan({ agents, modules, repoRoot, extraSkills = false, env = realEnv() }) {
61
65
  const { platform, home, have, exists, read } = env;
62
66
  if (platform !== "darwin" && platform !== "linux") {
63
67
  throw new Error(`machine setup supports macOS and Linux only (this is ${platform})`);
@@ -65,15 +69,17 @@ function plan({ agents, modules, repoRoot, env = realEnv() }) {
65
69
  const items = [];
66
70
  const item = (id, label, ok, rest) => items.push({ id, label, status: ok ? "ok" : "missing", ...rest });
67
71
 
68
- // User-level skills (pinned lists): installed once for all selected agents.
72
+ // User-level skills, from a fixed commit: installed once for all selected agents.
69
73
  const skillAgents = agents.map((a) => SKILLS_AGENT_ID[a]).join(" ");
70
- for (const [source, names] of Object.entries(MACHINE.skills)) {
74
+ for (const [source, { commit, core, extra }] of Object.entries(MACHINE.skills)) {
75
+ const names = extraSkills ? [...core, ...extra] : core;
76
+ if (!names.length) continue;
71
77
  const unseen = () => names.filter((n) => agents.some((a) => !skillVisible(exists, home, a, n)));
72
78
  const missing = unseen();
73
79
  item(`skills:${source}`, `${source} skills (${names.length - missing.length}/${names.length} installed)`, missing.length === 0, {
74
80
  kind: "run",
75
81
  summary: `install ${missing.length} skill${missing.length === 1 ? "" : "s"} from ${source} with \`npx skills add\` (full command: ccwf init --machine-only --dry-run)`,
76
- cmd: `npx -y skills add ${source} -g -a ${skillAgents} -s ${missing.join(" ")} -y`,
82
+ cmd: `npx -y skills@${MACHINE.skillsCli} add ${source}@${commit} -g -a ${skillAgents} -s ${missing.join(" ")} -y`,
77
83
  detect: () => unseen().length === 0,
78
84
  });
79
85
  }
@@ -124,14 +130,19 @@ function plan({ agents, modules, repoRoot, env = realEnv() }) {
124
130
  if (agents.includes("codex") && repoRoot) {
125
131
  const file = path.join(home, ".codex", "config.toml");
126
132
  const header = projectHeader(repoRoot);
127
- item("codex-trust", "Codex trusts this repo", repoTrusted(read(file) ?? "", repoRoot), {
128
- kind: "edit",
129
- hint: `add ${header} trust_level = "trusted" to ~/.codex/config.toml`,
133
+ const state = trustState(read(file) ?? "", repoRoot);
134
+ const byHand = `~/.codex/config.toml already has an entry for ${repoRoot}; to trust it, set trust_level = "trusted" there`;
135
+ item("codex-trust", "Codex trusts this repo", state === "trusted", {
136
+ kind: state === "named" ? "manual" : "edit",
137
+ hint: state === "named" ? byHand : `add ${header} trust_level = "trusted" to ~/.codex/config.toml`,
130
138
  apply: () => {
131
139
  fs.mkdirSync(path.dirname(file), { recursive: true });
132
140
  let cur = "";
133
141
  if (fs.existsSync(file)) {
134
142
  cur = fs.readFileSync(file, "utf8");
143
+ const now = trustState(cur, repoRoot);
144
+ if (now === "trusted") return;
145
+ if (now === "named") throw new Error(byHand);
135
146
  fs.copyFileSync(file, `${file}.bak`);
136
147
  }
137
148
  fs.writeFileSync(file, `${cur}${cur === "" || cur.endsWith("\n") ? "" : "\n"}\n${header}\ntrust_level = "trusted"\n`);
@@ -141,6 +152,40 @@ function plan({ agents, modules, repoRoot, env = realEnv() }) {
141
152
  return items;
142
153
  }
143
154
 
155
+ // The model ids an agent CLI offers, as text; null when it cannot say. Claude has no such list.
156
+ function listModels(agent) {
157
+ const cmd = { codex: ["codex", "debug", "models"], cursor: ["cursor-agent", "--list-models"] }[agent];
158
+ if (!cmd) return null;
159
+ const r = spawnSync(cmd[0], cmd.slice(1), { encoding: "utf8", timeout: 20000, maxBuffer: 64 << 20, stdio: ["ignore", "pipe", "ignore"] });
160
+ return r.status === 0 ? r.stdout : null;
161
+ }
162
+
163
+ function modelIds(agent, text) {
164
+ if (!text) return [];
165
+ if (agent === "cursor") return [...text.matchAll(/^(\S+) - /gm)].map((m) => m[1]);
166
+ try {
167
+ return JSON.parse(text).models.map((m) => m.slug);
168
+ } catch {
169
+ return [];
170
+ }
171
+ }
172
+
173
+ // Rows of workers.conf whose model the installed CLI does not list: that worker could not start.
174
+ function rosterProblems(conf, list = listModels) {
175
+ const known = {};
176
+ const problems = [];
177
+ for (const line of conf.split("\n")) {
178
+ if (!line.trim() || line.trim().startsWith("#")) continue;
179
+ const [name, agent, model, effort] = line.trim().split(/\s+/);
180
+ if (agent !== "codex" && agent !== "cursor") continue;
181
+ const ids = (known[agent] ??= modelIds(agent, list(agent)));
182
+ // Same id pane.sh builds: cursor model ids end with the effort, unless the row says "-".
183
+ const id = agent === "cursor" && effort !== "-" ? `${model}-${!effort || effort === "auto" ? "medium" : effort}` : model;
184
+ if (ids.length && !ids.includes(id)) problems.push(`worker ${name}: ${agent} does not list model ${id}`);
185
+ }
186
+ return problems;
187
+ }
188
+
144
189
  function loginHints(agents) {
145
190
  return [...agents.map((a) => AGENT_CLI[a].login), "gh auth login"];
146
191
  }
@@ -164,4 +209,4 @@ function run(items, exec = (cmd) => spawnSync("sh", ["-c", cmd], { stdio: "inher
164
209
  return results;
165
210
  }
166
211
 
167
- module.exports = { plan, run, loginHints, realEnv };
212
+ module.exports = { plan, run, loginHints, realEnv, rosterProblems };
package/lib/merge.js CHANGED
@@ -1,4 +1,5 @@
1
1
  "use strict";
2
+ const { isDeepStrictEqual } = require("util");
2
3
  // Pure text merges. Each returns the new text; calling twice with the same input is a no-op.
3
4
 
4
5
  const STYLES = {
@@ -25,20 +26,23 @@ function upsertBlock(text, id, body, style = "md") {
25
26
  if (missingMarker(text, id, style)) return text;
26
27
  const begin = STYLES[style](id, "begin");
27
28
  const end = STYLES[style](id, "end");
28
- const block = `${begin}\n${body.trimEnd()}\n${end}`;
29
29
  const re = new RegExp(`${escapeRe(begin)}[\\s\\S]*?${escapeRe(end)}`);
30
- if (re.test(text)) return text.replace(re, () => block);
31
- const sep = text === "" ? "" : text.endsWith("\n\n") ? "" : text.endsWith("\n") ? "\n" : "\n\n";
32
- return `${text}${sep}${block}\n`;
30
+ // The block takes the line endings around it: those of its own first line, else of the file's.
31
+ const at = re.exec(text);
32
+ const nl = /^[^\n]*\r\n/.test(at ? at[0] : text) ? "\r\n" : "\n";
33
+ const block = `${begin}\n${body.trimEnd()}\n${end}`.replace(/\r?\n/g, nl);
34
+ if (at) return text.replace(re, () => block);
35
+ const sep = text === "" || text.endsWith(nl + nl) ? "" : text.endsWith("\n") ? nl : nl + nl;
36
+ return `${text}${sep}${block}${nl}`;
33
37
  }
34
38
 
35
- // The text between the markers of block `id`, or null when the block is not there.
39
+ // The text between the markers of block `id` with \n line endings, or null when the block is not there.
36
40
  function getBlock(text, id, style = "md") {
37
41
  if (missingMarker(text, id, style)) return null;
38
42
  const begin = STYLES[style](id, "begin");
39
43
  const end = STYLES[style](id, "end");
40
- const m = new RegExp(`${escapeRe(begin)}\\n([\\s\\S]*?)\\n?${escapeRe(end)}`).exec(text);
41
- return m ? m[1] : null;
44
+ const m = new RegExp(`${escapeRe(begin)}[ \\t]*\\r?\\n([\\s\\S]*?)(?:\\r?\\n)?${escapeRe(end)}`).exec(text);
45
+ return m ? m[1].replace(/\r\n/g, "\n") : null;
42
46
  }
43
47
 
44
48
  function removeBlock(text, id, style = "md") {
@@ -47,10 +51,47 @@ function removeBlock(text, id, style = "md") {
47
51
  return text.replace(new RegExp(`\\n?${escapeRe(begin)}[\\s\\S]*?${escapeRe(end)}\\n?`), "\n");
48
52
  }
49
53
 
50
- // True when a `[table]` header exists outside the managed block `id` (the user owns it).
51
- function hasTableOutsideBlock(text, id, table) {
52
- const outside = removeBlock(text, id, "hash");
53
- return new RegExp(`^\\s*\\[${escapeRe(table)}\\]`, "m").test(outside);
54
+ // A TOML key at the start of `s` as its parts (`a."b.c" . d` -> a, b.c, d) and the text after it, or null.
55
+ function tomlKey(s) {
56
+ const parts = [];
57
+ let rest = s;
58
+ for (;;) {
59
+ const m = /^\s*(?:([A-Za-z0-9_-]+)|"((?:[^"\\]|\\.)*)"|'([^']*)')\s*/.exec(rest);
60
+ if (!m) return null;
61
+ parts.push(m[1] ?? m[2] ?? m[3]);
62
+ rest = rest.slice(m[0].length);
63
+ if (rest[0] !== ".") return { parts, rest };
64
+ rest = rest.slice(1);
65
+ }
66
+ }
67
+
68
+ // True when the user defines `table` (a dotted name) outside the managed block `id`, so that ccwf adding
69
+ // it would make the file invalid: the table itself, one of its `keys` as a sub-table, or the same thing
70
+ // written as an inline table or dotted key. Other sub-tables are fine beside it.
71
+ function hasTableOutsideBlock(text, id, table, keys = []) {
72
+ const want = table.split(".");
73
+ const starts = (a, b) => b.every((p, i) => a[i] === p); // a begins with b
74
+ let header = [];
75
+ let quotes = null; // inside a multi-line string
76
+ for (const line of removeBlock(text, id, "hash").split(/\r?\n/)) {
77
+ const wasInside = quotes;
78
+ for (const [q] of line.matchAll(/"""|\'\'\'/g)) quotes = quotes === null ? q : quotes === q ? null : quotes;
79
+ if (wasInside || /^\s*(#|$)/.test(line)) continue;
80
+ const open = /^\s*\[\[?/.exec(line);
81
+ if (open) {
82
+ const k = tomlKey(line.slice(open[0].length));
83
+ if (!k || !/^\]\]?\s*(#.*)?$/.test(k.rest)) continue; // a line of an array
84
+ header = k.parts;
85
+ if (starts(header, want) && (header.length === want.length || keys.includes(header[want.length]))) return true;
86
+ continue;
87
+ }
88
+ if (header.length >= want.length || !starts(want, header)) continue;
89
+ const k = tomlKey(line);
90
+ if (!k || k.rest[0] !== "=") continue;
91
+ const full = [...header, ...k.parts];
92
+ if (starts(full, want) || starts(want, full)) return true;
93
+ }
94
+ return false;
54
95
  }
55
96
 
56
97
  function isPlainObject(v) {
@@ -95,7 +136,10 @@ function mergeJson(text, patch, label = "JSON file", union = []) {
95
136
  const have = getPath(data, path);
96
137
  setPath(p, path, [...new Set([...(Array.isArray(have) ? have : []), ...add])]);
97
138
  }
98
- return JSON.stringify(deepMerge(data, p), null, 2) + "\n";
139
+ const before = JSON.parse(JSON.stringify(data));
140
+ deepMerge(data, p);
141
+ if (text.trim() !== "" && isDeepStrictEqual(data, before)) return text; // keep the user's formatting
142
+ return JSON.stringify(data, null, 2) + "\n";
99
143
  }
100
144
 
101
145
  module.exports = { upsertBlock, getBlock, removeBlock, hasTableOutsideBlock, mergeJson, missingMarker };
package/lib/modules.js CHANGED
@@ -54,7 +54,7 @@ const CONF = ".agents/skills/verify-ui/verify-ui.conf";
54
54
  // CLAUDE.md is skipped when it is AGENTS.md (a symlink) or the import is already there.
55
55
  function skipClaudeImport(ins) {
56
56
  try {
57
- if (fs.realpathSync(ins.abs("CLAUDE.md")) === fs.realpathSync(ins.abs("AGENTS.md"))) return true;
57
+ if (ins.real("CLAUDE.md") === ins.real("AGENTS.md")) return true;
58
58
  } catch {}
59
59
  const cur = ins.read("CLAUDE.md");
60
60
  return cur !== null && cur.includes("@AGENTS.md");
@@ -92,10 +92,31 @@ function parseConf(text) {
92
92
  return out;
93
93
  }
94
94
 
95
- // A site list is comma-separated domains: letters, digits, hyphens and dots.
95
+ // A site list is comma-separated domains: letters, digits, hyphens and dots, with *. in front for subdomains.
96
96
  function validSiteList(value) {
97
97
  const label = "[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?";
98
- return new RegExp(`^(?:${label})(?:\\.(?:${label}))*(?:,(?:${label})(?:\\.(?:${label}))*)*$`).test(value);
98
+ const site = `(?:\\*\\.)?${label}(?:\\.${label})*`;
99
+ return new RegExp(`^${site}(?:,${site})*$`).test(value);
100
+ }
101
+
102
+ // The first checks.conf: the scripts package.json already has. The user's file from then on.
103
+ function checksConf(ins) {
104
+ let scripts = {};
105
+ try {
106
+ scripts = JSON.parse(ins.read("package.json")).scripts || {};
107
+ } catch {} // none, or not readable: the user fills in the file
108
+ const locks = { "pnpm-lock.yaml": "pnpm", "yarn.lock": "yarn", "bun.lock": "bun", "bun.lockb": "bun" };
109
+ const lock = Object.keys(locks).find((f) => ins.read(f) !== null);
110
+ const line = (when, name) => `${when} ${lock ? locks[lock] : "npm"} run ${name}`;
111
+ const real = (name) => typeof scripts[name] === "string" && !/no test specified/.test(scripts[name]);
112
+ return [
113
+ "# Checks for .agents/guardrails/check.sh, one per line. The line is run by sh from the repo root.",
114
+ "# always <command> before each commit too: keep it fast (lint, types)",
115
+ "# full <command> when a ticket is finished and in CI (build, tests)",
116
+ "# A command must end by itself (no watch mode). Commit this file: workers may not change it.",
117
+ ...["lint", "typecheck", "type-check"].filter(real).map((n) => line("always", n)),
118
+ ...["build", "test"].filter(real).map((n) => line("full", n)),
119
+ ].join("\n") + "\n";
99
120
  }
100
121
 
101
122
  const MODULES = {
@@ -138,12 +159,22 @@ const MODULES = {
138
159
  const { ins, agents, params } = ctx;
139
160
  installSkill(ctx, "agent-browser");
140
161
  installSkill(ctx, "verify-ui");
141
- mcp(ctx, "chrome-devtools", "npx", CHROME_ARGS, `[mcp_servers.chrome-devtools]\ncommand = "npx"\nargs = [${CHROME_ARGS.map((a) => `"${a}"`).join(", ")}]`);
162
+ mcp(ctx, "chrome-devtools", "npx", CHROME_ARGS, `[mcp_servers.chrome-devtools]\ncommand = "npx"\nargs = [${CHROME_ARGS.map((a) => `"${a}"`).join(", ")}]\nenv_vars = ["CCWF_BROWSER"]`);
142
163
  if (agents.includes("claude")) ins.json(".claude/settings.json", { enabledMcpjsonServers: ["chrome-devtools"] }, ["enabledMcpjsonServers"]);
143
164
  if (agents.includes("cursor")) ins.json(".cursor/cli.json", JSON.parse(tpl("cursor-cli.json")), ["permissions.allow", "permissions.deny"]);
144
165
  ins.block("AGENTS.md", "browser", blockBody("browser", params));
145
166
  },
146
167
  },
168
+ guardrails: {
169
+ desc: "one check script (project commands, secrets) for workers, git commits and CI",
170
+ optional: true,
171
+ run(ctx) {
172
+ const { ins } = ctx;
173
+ ins.owned(".agents/guardrails/check.sh", tpl("guardrails", "check.sh"), 0o755);
174
+ ins.seed(".agents/guardrails/checks.conf", checksConf(ins));
175
+ ins.block("AGENTS.md", "guardrails", blockBody("guardrails", ctx.params));
176
+ },
177
+ },
147
178
  workers: {
148
179
  desc: "orchestrate-workers skill (needs herdr + hc)",
149
180
  run(ctx) {
@@ -190,9 +221,10 @@ function sync(ctx, modules) {
190
221
  }
191
222
 
192
223
  const ORDER = Object.keys(MODULES);
224
+ const DEFAULT_MODULES = ORDER.filter((m) => !MODULES[m].optional);
193
225
 
194
226
  const WORKER_NAMES = ["alpha", "beta", "gamma", "delta"];
195
- const DEFAULT_MODEL = { claude: "claude-sonnet-5-5", codex: "gpt-5-codex", cursor: "grok-4.7" };
227
+ const DEFAULT_MODEL = { claude: "claude-sonnet-5-5", codex: "gpt-6.2-sol", cursor: "grok-4.7" };
196
228
 
197
229
  function defaultRoster(agents) {
198
230
  return WORKER_NAMES.map((n, i) => {
@@ -205,4 +237,4 @@ function makeParams({ agents }) {
205
237
  return { agents, vars: { DATE: new Date().toISOString().slice(0, 10), ROSTER: defaultRoster(agents) } };
206
238
  }
207
239
 
208
- module.exports = { MODULES, ORDER, AGENTS, makeParams, sync, TEMPLATES, CONF, parseConf, validSiteList };
240
+ module.exports = { MODULES, ORDER, DEFAULT_MODULES, AGENTS, makeParams, sync, TEMPLATES, CONF, parseConf, validSiteList };
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ // The templates of an older ccwf, read from its published package. `update` needs the exact text ccwf
3
+ // last wrote to merge well, and a fresh clone has neither the local copy nor, after a merge, the commit.
4
+ const fs = require("fs");
5
+ const os = require("os");
6
+ const path = require("path");
7
+ const { spawnSync } = require("child_process");
8
+ const pkg = require("../package.json");
9
+
10
+ const VERSION = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
11
+
12
+ // Every template file of `version` as text, or [] when it cannot be had (offline, never published).
13
+ // The package is only unpacked and read, never run.
14
+ function publishedTemplates(version) {
15
+ if (!VERSION.test(version || "")) return []; // it comes from a file in the repo
16
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ccwf-old-"));
17
+ try {
18
+ const npm = ["pack", `${pkg.name}@${version}`, "--pack-destination", dir, "--ignore-scripts", "--silent", "--fetch-retries=0", "--fetch-timeout=15000"];
19
+ if (spawnSync("npm", npm, { cwd: dir, stdio: "ignore", timeout: 30000 }).status !== 0) return [];
20
+ const tgz = fs.readdirSync(dir).find((f) => f.endsWith(".tgz"));
21
+ if (!tgz || spawnSync("tar", ["-xzf", tgz], { cwd: dir, stdio: "ignore" }).status !== 0) return [];
22
+ return files(path.join(dir, "package", "templates")).map((f) => fs.readFileSync(f, "utf8"));
23
+ } catch {
24
+ return [];
25
+ } finally {
26
+ fs.rmSync(dir, { recursive: true, force: true });
27
+ }
28
+ }
29
+
30
+ function files(dir) {
31
+ return fs.readdirSync(dir, { withFileTypes: true }).flatMap((e) => {
32
+ const p = path.join(dir, e.name);
33
+ return e.isDirectory() ? files(p) : e.isFile() ? [p] : [];
34
+ });
35
+ }
36
+
37
+ // True when version `a` is newer than `b` (a prerelease comes before its release).
38
+ function newer(a, b) {
39
+ if (!VERSION.test(a || "") || !VERSION.test(b || "")) return false;
40
+ const split = (v) => {
41
+ const [core, ...pre] = v.split("-");
42
+ return { core: core.split(".").map(Number), pre: pre.join("-") };
43
+ };
44
+ const x = split(a);
45
+ const y = split(b);
46
+ for (let i = 0; i < 3; i++) if (x.core[i] !== y.core[i]) return x.core[i] > y.core[i];
47
+ if (!x.pre || !y.pre) return !x.pre && !!y.pre;
48
+ return x.pre.localeCompare(y.pre, "en", { numeric: true }) > 0;
49
+ }
50
+
51
+ module.exports = { publishedTemplates, newer };
package/lib/stats.js ADDED
@@ -0,0 +1,110 @@
1
+ "use strict";
2
+ // `ccwf stats`: what the worker scripts recorded (templates/skills/orchestrate-workers/runlog.sh), per worker model.
3
+ const fs = require("fs");
4
+ const path = require("path");
5
+ const { spawnSync } = require("child_process");
6
+
7
+ function readEvents(root) {
8
+ const r = spawnSync("git", ["rev-parse", "--git-common-dir"], { cwd: root, encoding: "utf8" });
9
+ if (r.status !== 0) throw new Error("not a git repo: worker runs are recorded in its .git folder");
10
+ let text;
11
+ try {
12
+ text = fs.readFileSync(path.join(path.resolve(root, r.stdout.trim()), "ccwf", "runs.jsonl"), "utf8");
13
+ } catch (err) {
14
+ if (err.code === "ENOENT") return [];
15
+ throw err;
16
+ }
17
+ return text.split("\n").flatMap((line) => {
18
+ try {
19
+ return line ? [JSON.parse(line)] : [];
20
+ } catch {
21
+ return []; // a line cut off by a crash
22
+ }
23
+ });
24
+ }
25
+
26
+ function median(values) {
27
+ if (!values.length) return null;
28
+ const s = [...values].sort((a, b) => a - b);
29
+ return (s[(s.length - 1) >> 1] + s[s.length >> 1]) / 2;
30
+ }
31
+
32
+ function summarise(events) {
33
+ const runs = new Map();
34
+ const lastRun = new Map(); // ticket -> the run that worked on it last
35
+ const doneBy = new Map(); // ticket -> the run that had it when it was set to done
36
+ const reviewers = new Map();
37
+ for (const e of events) {
38
+ const run = runs.get(e.run);
39
+ if (e.e === "start") {
40
+ const r = { ...e, turns: [], sentback: 0, gates: 0, conflicts: 0, rc: null };
41
+ runs.set(e.run, r);
42
+ if (e.ticket) lastRun.set(e.ticket, r);
43
+ } else if (e.e === "turn" && run) run.turns.push(e);
44
+ else if (e.e === "sentback" && run) run.sentback++;
45
+ else if (e.e === "gate" && run) run.gates++;
46
+ else if (e.e === "merge" && run) run.conflicts += e.result === "conflict" ? 1 : 0;
47
+ else if (e.e === "end" && run) run.rc = e.rc;
48
+ else if (e.e === "status") {
49
+ if (e.status === "done" && lastRun.has(e.ticket)) doneBy.set(e.ticket, lastRun.get(e.ticket));
50
+ else if (e.status !== "done") doneBy.delete(e.ticket);
51
+ } else if (e.e === "review") {
52
+ const key = `${e.agent} ${e.model}`;
53
+ if (!reviewers.has(key)) reviewers.set(key, { agent: e.agent, model: e.model, reviews: 0, withFindings: 0, noVerdict: 0 });
54
+ const r = reviewers.get(key);
55
+ r.reviews++;
56
+ if (e.verdict === "findings") r.withFindings++;
57
+ else if (e.verdict !== "pass") r.noVerdict++;
58
+ }
59
+ }
60
+ const done = new Set(doneBy.values());
61
+ const groups = new Map();
62
+ for (const r of runs.values()) {
63
+ const folder = r.tree === "worktree" ? "own" : "shared";
64
+ const key = [r.agent, r.model, r.effort, folder].join(" ");
65
+ if (!groups.has(key)) groups.set(key, { agent: r.agent, model: r.model, effort: r.effort, folder, all: [] });
66
+ groups.get(key).all.push(r);
67
+ }
68
+ const workers = [...groups.values()].map(({ all, ...who }) => {
69
+ // It ended with an error before finishing a turn: a wrong model id or login, not the model's work.
70
+ const failed = (r) => r.rc !== null && r.rc !== 0 && !r.turns.length && !r.sentback;
71
+ const ran = all.filter((r) => !failed(r));
72
+ const checksFailed = (r) => r.sentback + r.turns.filter((t) => t.checks === "failed").length;
73
+ const extra = (r) => Math.max(0, r.turns.length - 1);
74
+ const sum = (f) => ran.reduce((n, r) => n + f(r), 0);
75
+ return {
76
+ ...who,
77
+ runs: ran.length,
78
+ done: ran.filter((r) => done.has(r)).length,
79
+ firstTry: ran.filter((r) => done.has(r) && !checksFailed(r) && !extra(r)).length,
80
+ minutesToFinish: median(ran.filter((r) => r.turns.length).map((r) => (r.turns[0].t - r.t) / 60)),
81
+ fixRounds: sum(extra),
82
+ checksFailed: sum(checksFailed),
83
+ gates: sum((r) => r.gates),
84
+ conflicts: sum((r) => r.conflicts),
85
+ failedStarts: all.length - ran.length,
86
+ };
87
+ });
88
+ return { workers: workers.sort((a, b) => b.runs - a.runs), reviews: [...reviewers.values()] };
89
+ }
90
+
91
+ function table(rows) {
92
+ const width = rows[0].map((_, i) => Math.max(...rows.map((r) => String(r[i]).length)));
93
+ return rows.map((r) => " " + r.map((c, i) => (i < 4 ? String(c).padEnd(width[i]) : String(c).padStart(width[i]))).join(" ").trimEnd()).join("\n");
94
+ }
95
+
96
+ function print(root, asJson) {
97
+ const s = summarise(readEvents(root));
98
+ if (asJson) return console.log(JSON.stringify(s, null, 2));
99
+ if (!s.workers.length && !s.reviews.length) return console.log("no worker runs recorded yet (orchestrate-workers writes them to .git/ccwf/runs.jsonl)");
100
+ if (s.workers.length) {
101
+ const head = ["agent", "model", "effort", "folder", "runs", "done", "first try", "min to finish", "fix rounds", "checks failed", "prompts", "conflicts", "failed starts"];
102
+ const row = (w) => [w.agent, w.model, w.effort, w.folder, w.runs, w.done, w.firstTry, w.minutesToFinish === null ? "-" : w.minutesToFinish.toFixed(1), w.fixRounds, w.checksFailed, w.gates, w.conflicts, w.failedStarts];
103
+ console.log(table([head, ...s.workers.map(row)]));
104
+ console.log("\nfirst try: done with no fix round and no failed check. min to finish: median, from the start to the end of the first turn");
105
+ console.log("that passed or gave up, waiting for you included. Tickets differ in size: compare models only over many runs.");
106
+ }
107
+ for (const r of s.reviews) console.log(`\nreviewer ${r.agent} ${r.model}: ${r.reviews} reviews, ${r.withFindings} with findings${r.noVerdict ? `, ${r.noVerdict} without a verdict` : ""}`);
108
+ }
109
+
110
+ module.exports = { print, summarise };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mayurdluffy/ccwf",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
4
4
  "description": "One command to set up skills, MCP servers, shared memory and rules for Claude Code, Codex and Cursor in any repo",
5
5
  "main": "bin/ccwf.js",
6
6
  "bin": {
@@ -35,7 +35,7 @@
35
35
  "access": "public"
36
36
  },
37
37
  "engines": {
38
- "node": ">=18.0.0"
38
+ "node": ">=22.0.0"
39
39
  },
40
40
  "files": [
41
41
  "bin/",
@@ -6,7 +6,7 @@ Every feature and every bug fix that can be seen in a browser, whether the chang
6
6
  - **Bug:** first reproduce it as a failing scenario, then fix, then keep the scenario as the regression test.
7
7
 
8
8
  - **Start with the `verify-ui` skill** (`.agents/skills/verify-ui`): `probe.sh <path>` prints a page's health (uncaught errors, console, failed and API requests, vitals, interactive elements) in one call; `run.sh <dir>` runs ticket scenarios as a regression suite (behaviour, accessibility, screenshot baselines; a scenario that passes only on a rerun is reported as flaky); `PLAYBOOK.md` maps each browser symptom to one command. Evidence is saved under `.scratch/.verify-out/` (git-ignored). Base URL and allowed sites are in `.agents/skills/verify-ui/verify-ui.conf`; the skill asks for them on first use, then run `npx @mayurdluffy/ccwf sync`.
9
- - **Show, debug or act on a page with the user** through the `chrome-devtools` MCP. In Herdr this drives the Browser panel in the calling agent’s space. Start the dev server before connecting. The wrapper opens an allowed starting tab when needed. For new pages in Herdr, run `npx @mayurdluffy/ccwf chrome-mcp --open <allowed-url>` with the same ccwf version as the project MCP entry, then select the new page in MCP. Use `navigate_page`, `take_snapshot`, `click`, `fill`, console, network and performance tools. Reconnect via `/mcp` in Claude Code or restart the MCP client after a browser restart. Outside Herdr the server launches isolated Chrome. Both modes apply the project's allowed sites.
9
+ - **Show, debug or act on a page with the user** through the `chrome-devtools` MCP. It opens the system's Chrome in its own window, with a profile kept per project, so logins persist between sessions; the user can watch and take over. Start the dev server first, then `new_page` or `navigate_page` to it. Use `take_snapshot`, `click`, `fill`, console, network and performance tools. The first agent to start on this project holds that profile until it exits; any other agent, and every worker, gets a separate temporary browser without those logins. Only the project's allowed sites load.
10
10
  - **Scripted and headless checks** use verify-ui or agent-browser in a dedicated session. Get an ID with `agent-browser session id --scope worktree --prefix task`, then pass `--session <id>` to every command. `open <url>` → `snapshot -i -c` → act on refs → `console` → `close`.
11
11
  - **Dev server**: start it as a background process and stop it by its ID; never `pkill`/`killall`.
12
- - **Allowed sites** come from `ALLOWED_DOMAINS` in `verify-ui.conf` and are enforced by `--allowedUrlPattern` for Chrome DevTools MCP and by `AGENT_BROWSER_ALLOWED_DOMAINS` for agent-browser (Claude: `.claude/settings.json`; Codex: `.codex/config.toml`; Cursor: prefix agent-browser commands with it, the `verify-ui` scripts set it themselves). Never visit a site that is not listed; ask the user to add it.
12
+ - **Allowed sites** come from `ALLOWED_DOMAINS` in `verify-ui.conf` (`example.com` is that host only, `*.example.com` includes its subdomains) and are enforced by `--allowedUrlPattern` for Chrome DevTools MCP and by `AGENT_BROWSER_ALLOWED_DOMAINS` for agent-browser (Claude: `.claude/settings.json`; Codex: `.codex/config.toml`; Cursor: prefix agent-browser commands with it, the `verify-ui` scripts set it themselves). Never visit a site that is not listed; ask the user to add it.
@@ -0,0 +1,7 @@
1
+ ## Checks
2
+
3
+ `.agents/guardrails/check.sh` runs this project's checks (the commands in `.agents/guardrails/checks.conf`) and looks for new secrets. Work is finished only when it passes.
4
+
5
+ - Run it before you say that a task is done, and report its result. On `FAIL`, fix the cause.
6
+ - Never weaken a check to pass: do not edit `checks.conf`, skip a test or use `--no-verify`. If a check is wrong, say so and ask the user.
7
+ - On `SECRET`, remove the value and tell the user. Never print it or commit it.
@@ -24,7 +24,7 @@ States: **Active** (being built), **Queued** (spec and tickets ready, not starte
24
24
  Ticket files are the source of truth for status, so counts are read, not stored here. From the repo root:
25
25
 
26
26
  ```sh
27
- for d in .scratch/*/issues; do echo "== $d"; grep -h '^\*\*Status:\*\*' "$d"/*.md | sort | uniq -c; done
27
+ for d in .scratch/*/issues; do echo "== $d"; sed -nE 's/^(\*\*)?Status:(\*\*)? *//p' "$d"/*.md | sort | uniq -c; done
28
28
  ```
29
29
 
30
30
  Then open the active effort's `progress.md` and read its `## Resume` section: it holds the next action, what is waiting on the user, and the environment checklist.
@@ -7,7 +7,7 @@ Issues and specs for this repo live as markdown files in `.scratch/`.
7
7
  - One feature per directory: `.scratch/<feature-slug>/`
8
8
  - The spec is `.scratch/<feature-slug>/spec.md`
9
9
  - Implementation issues are one file per ticket at `.scratch/<feature-slug>/issues/<NN>-<slug>.md`, numbered from `01`, never a single combined tickets file
10
- - Triage state is recorded as a `Status:` line near the top of each issue file (see `triage-labels.md` for the role strings)
10
+ - Triage state is recorded as a `**Status:**` line near the top of each issue file (see `triage-labels.md` for the role strings)
11
11
  - Comments and conversation history append to the bottom of the file under a `## Comments` heading
12
12
 
13
13
  ## When a skill says "publish to the issue tracker"
@@ -23,8 +23,8 @@ Read the file at the referenced path. The user will normally pass the path or th
23
23
  Used by `/wayfinder`. The **map** is a file with one **child** file per ticket.
24
24
 
25
25
  - **Map**: `.scratch/<effort>/map.md` (the Notes / Decisions-so-far / Fog body).
26
- - **Child ticket**: `.scratch/<effort>/issues/NN-<slug>.md`, numbered from `01`, with the question in the body. A `Type:` line records the ticket type (`research`/`prototype`/`grilling`/`task`); a `Status:` line records `claimed`/`resolved`.
27
- - **Blocking**: a `Blocked by: NN, NN` line near the top. A ticket is unblocked when every file it lists is `resolved`.
26
+ - **Child ticket**: `.scratch/<effort>/issues/NN-<slug>.md`, numbered from `01`, with the question in the body. A `**Type:**` line records the ticket type (`research`/`prototype`/`grilling`/`task`); a `**Status:**` line records `claimed`/`resolved`.
27
+ - **Blocking**: a `**Blocked by:** NN, NN` line near the top (ticket numbers only, or `None`). A ticket is unblocked when every file it lists is `resolved`.
28
28
  - **Frontier**: scan `.scratch/<effort>/issues/` for files that are open, unblocked, and unclaimed; first by number wins.
29
- - **Claim**: set `Status: claimed` and save before any work.
30
- - **Resolve**: append the answer under an `## Answer` heading, set `Status: resolved`, then append a context pointer (gist + link) to the map's Decisions-so-far in `map.md`.
29
+ - **Claim**: set `**Status:** claimed` and save before any work.
30
+ - **Resolve**: append the answer under an `## Answer` heading, set `**Status:** resolved`, then append a context pointer (gist + link) to the map's Decisions-so-far in `map.md`.
@@ -1,6 +1,6 @@
1
1
  # Setup: tools and skills
2
2
 
3
- `npx @mayurdluffy/ccwf init` checks everything below, shows what is missing, and installs it after one confirmation. `--yes` skips the confirmation: it runs vendor install scripts from the network and installs skills from the current head of third-party repos. This page says what each piece is and how to install it by hand if the script fails. Supported: macOS and Linux; Claude Code, Codex and Cursor.
3
+ `npx @mayurdluffy/ccwf@latest init` checks everything below, shows what is missing, and installs it after one confirmation. `--yes` skips the confirmation: it runs vendor install scripts from the network and installs third-party skills from fixed commits. This page says what each piece is and how to install it by hand if the script fails. Supported: macOS and Linux; Claude Code, Codex and Cursor.
4
4
 
5
5
  ## 1. Before `ccwf`: codebase-memory (once per repo)
6
6
 
@@ -18,7 +18,7 @@ Rules: one cache for all repos (never set `CBM_CACHE_DIR` per repo), no global C
18
18
 
19
19
  | Piece | Why | By hand |
20
20
  |---|---|---|
21
- | User-level skills: `mattpocock/skills` (pinned list in `ccwf`) and `vercel-labs/skills` `find-skills` | the planning skills (`grill-with-docs`, `to-spec`, `to-tickets`, `tdd`, `code-review`, ...) | `npx -y skills add mattpocock/skills -g -a claude-code codex cursor -s <names> -y` |
21
+ | User-level skills from `mattpocock/skills`, at a commit fixed in `ccwf` | the planning skills (`grill-with-docs`, `to-spec`, `to-tickets`, `tdd`, `code-review`, ...) | `npx @mayurdluffy/ccwf@latest init --machine-only --dry-run` prints the command. `--extra-skills` adds the ones this workflow does not use. Installed skills are never changed |
22
22
  | `agent-browser` | browser automation for `verify-ui` | `npm i -g agent-browser && agent-browser install` (Linux: add `--with-deps`) |
23
23
  | `herdr` + `hc` | terminal tabs for worker agents (`orchestrate-workers`) | `curl -fsSL https://releases.herdr.dev/app/install.sh \| sh`; check with `hc --version` |
24
24
  | `gh`, `ffmpeg` | PRs; screen recordings of bugs | macOS: `brew install gh ffmpeg`; Linux: your package manager |
@@ -43,6 +43,6 @@ Log in once per agent (not scriptable): `claude`, `codex login`, `cursor-agent l
43
43
 
44
44
  ## 5. Keeping it healthy
45
45
 
46
- - `npx @mayurdluffy/ccwf doctor` — checks tools, skills and files; offers to fix.
47
- - `npx @mayurdluffy/ccwf update` — re-render from a newer `ccwf`; files you edited are merged with the new version (your text kept, overlaps marked `<<<<<<< current` / `>>>>>>> incoming`). After it, run `.agents/skills/orchestrate-workers/grid.sh --rebuild` once the workers are idle.
48
- - `npx @mayurdluffy/ccwf eject <skill>` — stop `ccwf` from managing a skill you changed.
46
+ - `npx @mayurdluffy/ccwf@latest doctor` — checks tools, skills, files and the models in `workers.conf`; offers to fix. `--check` only reports, and exits 1 on problems.
47
+ - `npx @mayurdluffy/ccwf@latest update` — re-render from a newer `ccwf`; files you edited are merged with the new version (your text kept, overlaps marked `<<<<<<< current` / `>>>>>>> incoming`). After it, run `.agents/skills/orchestrate-workers/grid.sh --rebuild` once the workers are idle.
48
+ - `npx @mayurdluffy/ccwf@latest eject <skill>` — stop `ccwf` from managing a skill you changed.
@@ -26,7 +26,7 @@ Turns the conversation into a spec file: `.scratch/<feature>/spec.md`. No new in
26
26
 
27
27
  ## 3. Split: `/to-tickets`
28
28
 
29
- Breaks the spec into small vertical tickets, one file each: `.scratch/<feature>/issues/<NN>-<slug>.md`, with a `Status:` line and `Blocked by:` edges. Labels and tracker rules: `issue-tracker.md`, `triage-labels.md`. Add the feature to `docs/FEATURES.md` as Planned.
29
+ Breaks the spec into small vertical tickets, one file each: `.scratch/<feature>/issues/<NN>-<slug>.md`, with a `**Status:**` line and a `**Blocked by:**` line (ticket numbers, or `None`). Labels and tracker rules: `issue-tracker.md`, `triage-labels.md`. Add the feature to `docs/FEATURES.md` as Planned.
30
30
 
31
31
  ## 4. Build: `/orchestrate-workers`
32
32
 
@@ -34,13 +34,13 @@ One coding agent is the **orchestrator**; it does not write feature code. Up to
34
34
 
35
35
  1. Confirm the worker roster (`.agents/skills/orchestrate-workers/workers.conf`) with you.
36
36
  2. Pick a wave of unblocked tickets that don't edit the same files; assign one per worker.
37
- 3. Wait for each worker; approve safe permission prompts.
37
+ 3. Wait for each worker; approve safe permission prompts. With the `guardrails` module, a finished worker's project checks run by themselves, and it is sent back once if they fail.
38
38
  4. Review each finished ticket (standards and spec), send defects back to the same worker.
39
39
  5. `verify-ui` checks anything visible in a real browser (page health, scenario files per ticket).
40
40
  6. **You check** anything a person should judge (UI, security) and say go.
41
41
  7. Commit with the `commit` skill (Conventional Commits, one per ticket), mark tickets done, update `docs/FEATURES.md`, start the next wave.
42
42
 
43
- State lives in the ticket `Status:` lines and `.scratch/<feature>/progress.md`, so a new session resumes from the files.
43
+ State lives in the ticket `**Status:**` lines and `.scratch/<feature>/progress.md`, so a new session resumes from the files.
44
44
 
45
45
  ## Along the way
46
46