@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/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
 
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 };