claude-everything-workflow 0.2.8 → 0.2.10

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 (44) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/.codex-plugin/plugin.json +1 -1
  3. package/AGENTS.md +11 -18
  4. package/README.md +2 -0
  5. package/README.zh-CN.md +2 -0
  6. package/agents/e2e-runner.md +1 -1
  7. package/evals/routing-scenarios.json +252 -0
  8. package/harness/manifest.json +2 -28
  9. package/hooks/check-console-log.js +2 -2
  10. package/package.json +4 -2
  11. package/rules/01-base.md +2 -2
  12. package/rules/02-implementation.md +7 -6
  13. package/rules/05-git-workflow.md +4 -6
  14. package/rules/common/agent-orchestration.md +1 -1
  15. package/rules/common/pr-automation.md +1 -1
  16. package/rules/common/testing.md +2 -2
  17. package/scripts/eval-scenarios.js +108 -0
  18. package/scripts/install-rules.js +266 -19
  19. package/scripts/install.ps1 +42 -15
  20. package/scripts/install.sh +31 -12
  21. package/scripts/legacy-common-rule-hashes.json +6 -1
  22. package/scripts/retired-skill-files.json +7 -0
  23. package/scripts/verify/install-rules.test.js +158 -24
  24. package/scripts/verify/metadata-checks.js +7 -8
  25. package/scripts/verify/repository-checks.js +44 -368
  26. package/scripts/verify/scenario-checks.js +108 -0
  27. package/scripts/verify/scenario-checks.test.js +97 -0
  28. package/scripts/verify/workflow-checks.js +85 -586
  29. package/scripts/verify-harness.js +2 -0
  30. package/skills/README.md +2 -4
  31. package/skills/feature-acceptance/SKILL.md +8 -8
  32. package/skills/{e2e-testing/SKILL.md → feature-acceptance/references/e2e-testing.md} +3 -9
  33. package/skills/implement/SKILL.md +2 -0
  34. package/skills/{subagent-driven-development/SKILL.md → implement/references/parallel-delivery.md} +7 -9
  35. package/skills/implement/references/ticket-delivery.md +1 -1
  36. package/skills/using-superpowers/SKILL.md +24 -103
  37. package/rules/07-forbidden.md +0 -20
  38. package/rules/08-specialty-rules-index.md +0 -18
  39. package/rules/09-first-principles-adversarial-testing.md +0 -30
  40. package/scripts/verify/continuation-checks.test.js +0 -101
  41. package/scripts/verify/grilling-spec-gate-checks.js +0 -297
  42. package/scripts/verify/workflow-ownership-fixtures.js +0 -371
  43. package/scripts/verify/workflow-ownership.js +0 -780
  44. /package/skills/{e2e-testing → feature-acceptance}/references/playwright-patterns.md +0 -0
@@ -0,0 +1,108 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+
4
+ /**
5
+ * 可选真实模型路由场景评测脚本(不进入 CI,需本地已登录 claude 或 codex CLI)。
6
+ * 用法:
7
+ * node scripts/eval-scenarios.js --host claude --limit 5
8
+ * node scripts/eval-scenarios.js --host codex --id bug-diagnosis
9
+ */
10
+
11
+ const fs = require("node:fs");
12
+ const path = require("node:path");
13
+ const os = require("node:os");
14
+ const { spawnSync } = require("node:child_process");
15
+
16
+ const root = path.resolve(__dirname, "..");
17
+ const scenariosPath = path.join(root, "evals/routing-scenarios.json");
18
+
19
+ function parseArgs(argv) {
20
+ const opts = { host: "claude", limit: Infinity, id: null, dryRun: false };
21
+ for (let i = 0; i < argv.length; i += 1) {
22
+ const arg = argv[i];
23
+ if (arg === "--host") opts.host = argv[++i];
24
+ else if (arg === "--limit") opts.limit = Number(argv[++i]);
25
+ else if (arg === "--id") opts.id = argv[++i];
26
+ else if (arg === "--dry-run") opts.dryRun = true;
27
+ else if (arg === "-h" || arg === "--help") {
28
+ console.log("Usage: node scripts/eval-scenarios.js [--host claude|codex] [--limit N] [--id <id>] [--dry-run]");
29
+ process.exit(0);
30
+ } else {
31
+ throw new Error(`Unknown option: ${arg}`);
32
+ }
33
+ }
34
+ if (!["claude", "codex"].includes(opts.host)) {
35
+ throw new Error(`Unsupported --host: ${opts.host}`);
36
+ }
37
+ return opts;
38
+ }
39
+
40
+ function buildEvalPrompt(scenario) {
41
+ return [
42
+ "这是一个只读工作流路由测试:只做选路,不执行下方用户请求,不修改任何文件。",
43
+ "根据本仓库的 AGENTS.md、工作流路由、Skill 说明和它们引用的规则,判断分发后由哪个文件直接负责用户当前要做的事。只查工作流文档,不查场景题库、测试、评测脚本或提交记录。",
44
+ "通用路由器只负责转交时,沿分发继续判断;路由器自己完成请求时,可以是答案。多阶段任务按当前要解决的具体问题选负责方。配套参考资料和后续步骤不作为本次目标。",
45
+ "只输出一个 JSON 对象,target 填该 Skill 或规则的完整仓库相对文件路径(包含文件名);无需进入工程流程时填字符串 NONE。不要加 Markdown 围栏。",
46
+ "",
47
+ `用户请求:${scenario.prompt}`,
48
+ ].join("\n");
49
+ }
50
+
51
+ function runHost(host, prompt) {
52
+ const options = { cwd: root, encoding: "utf8", timeout: 120000 };
53
+ if (host === "claude") {
54
+ const result = spawnSync("claude", ["-p", "--output-format", "text", prompt], options);
55
+ return { result, answer: result.stdout };
56
+ }
57
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "cew-eval-"));
58
+ try {
59
+ const finalMessage = path.join(dir, "answer.json");
60
+ const result = spawnSync("codex", ["exec", "--output-last-message", finalMessage, prompt], options);
61
+ const answer = result.status === 0 && fs.existsSync(finalMessage) ? fs.readFileSync(finalMessage, "utf8") : "";
62
+ return { result, answer };
63
+ } finally {
64
+ fs.rmSync(dir, { recursive: true, force: true });
65
+ }
66
+ }
67
+
68
+ function selectedTarget(answer) {
69
+ try {
70
+ const value = JSON.parse(answer);
71
+ return typeof value?.target === "string" ? value.target : null;
72
+ } catch (error) {
73
+ if (error instanceof SyntaxError) return null;
74
+ throw error;
75
+ }
76
+ }
77
+
78
+ function main() {
79
+ const opts = parseArgs(process.argv.slice(2));
80
+ const data = JSON.parse(fs.readFileSync(scenariosPath, "utf8"));
81
+ let list = data.scenarios;
82
+ if (opts.id) list = list.filter((s) => s.id === opts.id);
83
+ if (Number.isFinite(opts.limit)) list = list.slice(0, opts.limit);
84
+
85
+ let passed = 0;
86
+ for (const scenario of list) {
87
+ const evalPrompt = buildEvalPrompt(scenario);
88
+ if (opts.dryRun) {
89
+ console.log(`[dry-run] ${scenario.id} -> expected: ${scenario.expectedTarget || "NONE"}`);
90
+ passed += 1;
91
+ continue;
92
+ }
93
+ const { result, answer } = runHost(opts.host, evalPrompt);
94
+ const expected = scenario.expectedTarget ?? "NONE";
95
+ const selected = selectedTarget(answer);
96
+ const ok = result.status === 0 && selected === expected;
97
+ if (ok) passed += 1;
98
+ console.log(`${ok ? "PASS" : "FAIL"} ${scenario.id} (expected: ${scenario.expectedTarget || "NONE"})`);
99
+ if (!ok) {
100
+ const diagnostic = result.error?.message || result.stderr || "";
101
+ console.log(` exit=${result.status} target=${JSON.stringify(selected)} ${diagnostic.trim().slice(0, 200)}`);
102
+ }
103
+ }
104
+ console.log(`\nSummary: ${passed}/${list.length} passed.`);
105
+ if (passed !== list.length) process.exitCode = 1;
106
+ }
107
+
108
+ main();
@@ -4,12 +4,32 @@
4
4
  const fs = require("node:fs");
5
5
  const path = require("node:path");
6
6
  const crypto = require("node:crypto");
7
+ const os = require("node:os");
8
+ const { spawnSync } = require("node:child_process");
9
+
10
+ const CODEX_RULE_BASE = ".cew-rule-state/02-implementation.base.md";
11
+ const CODEX_RULE_INCOMING = ".cew-rule-state/02-implementation.incoming.md";
12
+
13
+ const BACKUP_ROOT_NAME = ".cew-backups";
14
+ const LEGACY_TOP_LEVEL_BAK = /^(?:CLAUDE\.md|AGENTS\.md|settings\.json)\.bak\..+$/;
15
+ const LEGACY_RULE_BAK = /\.md\.bak\..+$/;
7
16
 
8
17
  const digest = (content) => crypto.createHash("sha256")
9
18
  .update(content.toString("utf8").replace(/\r\n/g, "\n")).digest("hex");
10
19
 
11
- // Only cross-task policies belong in Claude's automatically loaded rules directory.
12
- const claudeResidentRules = new Set(["01-base.md", "05-git-workflow.md", "07-forbidden.md"]);
20
+ function defaultBackupId() {
21
+ const d = new Date();
22
+ const pad = (n) => String(n).padStart(2, "0");
23
+ return `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;
24
+ }
25
+
26
+ // Top-level rules stay in Claude's auto-loaded rules/; common/* loads on demand from references/rules/.
27
+ const claudeResidentRules = new Set(["01-base.md", "02-implementation.md", "05-git-workflow.md"]);
28
+ const retiredTopLevelRules = [
29
+ "07-forbidden.md",
30
+ "08-specialty-rules-index.md",
31
+ "09-first-principles-adversarial-testing.md",
32
+ ];
13
33
 
14
34
  // Check the root and every descendant before touching a managed file; do not follow links.
15
35
  function checkedPath(root, relative) {
@@ -30,20 +50,114 @@ function checkedPath(root, relative) {
30
50
  return target;
31
51
  }
32
52
 
33
- function copyRule({ source, root, relative, dryRun, log }) {
53
+ function replaceFile(file, content, mode = 0o600) {
54
+ fs.mkdirSync(path.dirname(file), { recursive: true });
55
+ const temp = file + ".tmp-" + crypto.randomUUID();
56
+ try {
57
+ fs.writeFileSync(temp, content, { flag: "wx", mode });
58
+ fs.renameSync(temp, file);
59
+ } finally {
60
+ fs.rmSync(temp, { force: true });
61
+ }
62
+ }
63
+
64
+ function copyRule({ source, root, relative, backupId, dryRun, log, merged }) {
34
65
  const target = checkedPath(root, relative);
35
- const content = fs.readFileSync(source);
66
+ const content = merged ?? fs.readFileSync(source);
36
67
  if (fs.existsSync(target)) {
37
68
  const previous = fs.readFileSync(target);
38
69
  if (content.equals(previous)) return;
39
- const backup = checkedPath(root, relative + ".bak." + digest(previous));
70
+ const backup = checkedPath(root, path.posix.join(BACKUP_ROOT_NAME, backupId, relative));
40
71
  log(`${dryRun ? "[dry-run] " : ""}备份规则: ${backup}`);
41
- if (!dryRun && !fs.existsSync(backup)) fs.copyFileSync(target, backup, fs.constants.COPYFILE_EXCL);
72
+ if (!dryRun) {
73
+ fs.mkdirSync(path.dirname(backup), { recursive: true });
74
+ fs.copyFileSync(target, backup);
75
+ }
42
76
  }
43
77
  log(`${dryRun ? "[dry-run] " : ""}安装规则: ${target}`);
44
78
  if (!dryRun) {
45
79
  fs.mkdirSync(path.dirname(target), { recursive: true });
46
- fs.copyFileSync(source, target);
80
+ if (merged) replaceFile(target, merged, fs.statSync(target).mode);
81
+ else fs.copyFileSync(source, target);
82
+ }
83
+ }
84
+
85
+ // Git only sees disposable copies. A conflict, invalid text or missing Git leaves the live rule untouched.
86
+ function mergeRuleText(local, base, incoming) {
87
+ const scratch = fs.mkdtempSync(path.join(os.tmpdir(), "cew-rule-merge-"));
88
+ try {
89
+ const paths = [];
90
+ for (const [name, bytes] of [["local", local], ["base", base], ["incoming", incoming]]) {
91
+ const text = bytes.toString("utf8");
92
+ if (text.includes("\0") || !Buffer.from(text).equals(bytes)) return null;
93
+ const file = path.join(scratch, name);
94
+ fs.writeFileSync(file, text.replace(/\r\n/g, "\n"));
95
+ paths.push(file);
96
+ }
97
+ const result = spawnSync("git", ["merge-file", "-p", "--", ...paths], { cwd: scratch });
98
+ if (result.status !== 0 || result.error) return null;
99
+ const crlf = local.includes("\r\n") && !local.toString("utf8").replace(/\r\n/g, "").includes("\n");
100
+ return crlf ? Buffer.from(result.stdout.toString("utf8").replace(/\n/g, "\r\n")) : result.stdout;
101
+ } finally {
102
+ fs.rmSync(scratch, { recursive: true, force: true });
103
+ }
104
+ }
105
+
106
+ function installCodexImplementationRule(options, knownHashes) {
107
+ const { source, root, relative, dryRun, log } = options;
108
+ const target = checkedPath(root, relative);
109
+ const base = checkedPath(root, CODEX_RULE_BASE);
110
+ const incoming = checkedPath(root, CODEX_RULE_INCOMING);
111
+ const previous = fs.existsSync(base) ? fs.readFileSync(base) : null;
112
+ const local = fs.existsSync(target) ? fs.readFileSync(target) : null;
113
+ const next = fs.readFileSync(source);
114
+ const localHash = local && digest(local);
115
+ const pristine = !local || localHash === digest(next) ||
116
+ (previous ? localHash === digest(previous) : knownHashes.includes(localHash));
117
+
118
+ if (pristine) {
119
+ copyRule(options);
120
+ } else if (previous && digest(previous) !== digest(next)) {
121
+ const merged = mergeRuleText(local, previous, next);
122
+ if (!merged) {
123
+ log(`${dryRun ? "[dry-run] " : ""}无法自动合并,保留个人规则 ${target}。请对照 ${incoming} 手动合并,再用它更新基线 ${base}。`);
124
+ if (!dryRun) replaceFile(incoming, next);
125
+ return;
126
+ }
127
+ copyRule({ ...options, merged });
128
+ } else {
129
+ log(`保留 Codex 个人实现规则: ${target}`);
130
+ }
131
+ if (!dryRun) {
132
+ if (!previous || !previous.equals(next)) replaceFile(base, next);
133
+ fs.rmSync(incoming, { force: true });
134
+ }
135
+ }
136
+
137
+ function installPromotedRule({ source, root, relative, knownHashes, backupId, dryRun, log }) {
138
+ const oldPath = checkedPath(root, `references/rules/${relative}`);
139
+ const destination = `rules/${relative}`;
140
+ const resident = checkedPath(root, destination);
141
+ const distributed = new Set([...knownHashes, digest(fs.readFileSync(source))]);
142
+ const personalContent = (file) => {
143
+ if (!fs.existsSync(file)) return null;
144
+ const content = fs.readFileSync(file);
145
+ return distributed.has(digest(content)) ? null : content;
146
+ };
147
+ const residentPolicy = personalContent(resident);
148
+ const oldPolicy = personalContent(oldPath);
149
+ if (residentPolicy) {
150
+ log(`保留常驻个人规则: ${resident}`);
151
+ if (oldPolicy && !residentPolicy.equals(oldPolicy)) {
152
+ log(`保留内容不同的个人参考副本: ${oldPath}`);
153
+ return;
154
+ }
155
+ } else {
156
+ copyRule({ source: oldPolicy ? oldPath : source, root, relative: destination, backupId, dryRun, log });
157
+ }
158
+ if (fs.existsSync(oldPath)) {
159
+ log(`${dryRun ? "[dry-run] " : ""}移除已迁入常驻目录的规则: ${oldPath}`);
160
+ if (!dryRun) fs.unlinkSync(oldPath);
47
161
  }
48
162
  }
49
163
 
@@ -51,7 +165,8 @@ function retireRule({ source, root, relative, knownHashes, dryRun, log }) {
51
165
  const target = checkedPath(root, relative);
52
166
  if (!fs.existsSync(target)) return;
53
167
  const hash = digest(fs.readFileSync(target));
54
- if (hash !== digest(fs.readFileSync(source)) && !knownHashes.includes(hash)) {
168
+ const matchesSource = source && fs.existsSync(source) && hash === digest(fs.readFileSync(source));
169
+ if (!matchesSource && !knownHashes.includes(hash)) {
55
170
  log(`保留个人修改,仍可能自动加载: ${target}`);
56
171
  return;
57
172
  }
@@ -59,7 +174,70 @@ function retireRule({ source, root, relative, knownHashes, dryRun, log }) {
59
174
  if (!dryRun) fs.unlinkSync(target);
60
175
  }
61
176
 
62
- function installRules({ sourceRoot, installRoot, host, dryRun = false, log = console.log }) {
177
+ function archiveLegacyBackups(root, relDir, pattern, recursive, dryRun, log) {
178
+ const dir = checkedPath(root, relDir);
179
+ if (!fs.existsSync(dir)) return;
180
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
181
+ if (entry.isSymbolicLink()) continue;
182
+ const childRel = relDir === "." ? entry.name : path.posix.join(relDir, entry.name);
183
+ if (entry.isDirectory()) {
184
+ if (recursive) archiveLegacyBackups(root, childRel, pattern, true, dryRun, log);
185
+ } else if (entry.isFile() && pattern.test(entry.name)) {
186
+ const target = checkedPath(root, childRel);
187
+ const archive = checkedPath(root, path.join(BACKUP_ROOT_NAME, "legacy", childRel));
188
+ log(`${dryRun ? "[dry-run] " : ""}归档历史备份: ${target}`);
189
+ if (dryRun) continue;
190
+ fs.mkdirSync(path.dirname(archive), { recursive: true });
191
+ try {
192
+ fs.copyFileSync(target, archive, fs.constants.COPYFILE_EXCL);
193
+ } catch (error) {
194
+ if (error.code !== "EEXIST") throw error;
195
+ if (!fs.readFileSync(target).equals(fs.readFileSync(archive))) continue;
196
+ }
197
+ fs.unlinkSync(target);
198
+ }
199
+ }
200
+ }
201
+
202
+ // Snapshots are sparse. Only retire a file after seeing a newer backup of the same path.
203
+ function pruneSupersededFiles(snapshot, relative, seen, dryRun, log) {
204
+ const dir = checkedPath(snapshot, relative);
205
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
206
+ const child = path.join(relative, entry.name);
207
+ if (entry.isDirectory()) {
208
+ pruneSupersededFiles(snapshot, child, seen, dryRun, log);
209
+ } else if (entry.isFile()) {
210
+ if (seen.has(child)) {
211
+ const file = checkedPath(snapshot, child);
212
+ log(`${dryRun ? "[dry-run] " : ""}清理已有较新副本的备份: ${file}`);
213
+ if (!dryRun) fs.unlinkSync(file);
214
+ }
215
+ seen.add(child);
216
+ }
217
+ }
218
+ if (!dryRun && fs.readdirSync(dir).length === 0) fs.rmdirSync(dir);
219
+ }
220
+
221
+ function finalizeBackups({ installRoot, dryRun = false, log = console.log }) {
222
+ const root = path.resolve(installRoot);
223
+ if (!fs.existsSync(root)) return;
224
+ archiveLegacyBackups(root, ".", LEGACY_TOP_LEVEL_BAK, false, dryRun, log);
225
+ archiveLegacyBackups(root, "rules", LEGACY_RULE_BAK, true, dryRun, log);
226
+ archiveLegacyBackups(root, "references/rules", LEGACY_RULE_BAK, true, dryRun, log);
227
+
228
+ const backupRoot = checkedPath(root, BACKUP_ROOT_NAME);
229
+ if (!fs.existsSync(backupRoot)) return;
230
+ const snapshots = fs.readdirSync(backupRoot, { withFileTypes: true })
231
+ .filter((entry) => entry.isDirectory() && /^\d{14}$/.test(entry.name))
232
+ .map((entry) => entry.name)
233
+ .sort().reverse();
234
+ const seen = new Set();
235
+ for (const snapshot of snapshots) {
236
+ pruneSupersededFiles(checkedPath(backupRoot, snapshot), "", seen, dryRun, log);
237
+ }
238
+ }
239
+
240
+ function installRules({ sourceRoot, installRoot, host, backupId = defaultBackupId(), dryRun = false, log = console.log }) {
63
241
  if (!["claude-code", "codex"].includes(host)) throw new Error(`Invalid host: ${host}`);
64
242
  const root = path.resolve(installRoot);
65
243
  const rulesRoot = path.join(sourceRoot, "rules");
@@ -71,32 +249,101 @@ function installRules({ sourceRoot, installRoot, host, dryRun = false, log = con
71
249
  .filter((entry) => entry.isFile() && entry.name.endsWith(".md"))
72
250
  .map((entry) => `common/${entry.name}`);
73
251
  const installedOnDemand = (relative) => host === "claude-code" && !claudeResidentRules.has(relative);
252
+ const promoted = (relative) => host === "claude-code" && relative === "02-implementation.md";
74
253
  // Validate all managed destinations before the first write, including upgrade cleanup paths.
254
+ checkedPath(root, BACKUP_ROOT_NAME);
255
+ if (host === "codex") {
256
+ checkedPath(root, CODEX_RULE_BASE);
257
+ checkedPath(root, CODEX_RULE_INCOMING);
258
+ }
75
259
  for (const relative of [...files, ...commonFiles]) {
76
260
  checkedPath(root, `rules/${relative}`);
77
- if (installedOnDemand(relative)) {
261
+ if (installedOnDemand(relative) || promoted(relative)) {
78
262
  checkedPath(root, `references/rules/${relative}`);
79
263
  }
80
264
  }
265
+ for (const retired of retiredTopLevelRules) {
266
+ checkedPath(root, `rules/${retired}`);
267
+ if (host === "claude-code") checkedPath(root, `references/rules/${retired}`);
268
+ }
81
269
  for (const relative of [...files, ...commonFiles]) {
82
270
  const source = path.join(rulesRoot, relative);
271
+ if (host === "codex" && relative === "02-implementation.md") {
272
+ installCodexImplementationRule({ source, root, relative: `rules/${relative}`, backupId, dryRun, log },
273
+ legacy.files[relative] || []);
274
+ continue;
275
+ }
276
+ if (promoted(relative)) {
277
+ installPromotedRule({ source, root, relative, knownHashes: legacy.files[relative] || [], backupId, dryRun, log });
278
+ continue;
279
+ }
83
280
  const cold = installedOnDemand(relative);
84
- copyRule({ source, root, relative: `${cold ? "references/rules" : "rules"}/${relative}`, dryRun, log });
85
- if (cold) retireRule({ source, root, relative: `rules/${relative}`,
86
- knownHashes: legacy.files[relative] || [], dryRun, log });
281
+ copyRule({ source, root, relative: `${cold ? "references/rules" : "rules"}/${relative}`, backupId, dryRun, log });
282
+ if (cold) {
283
+ retireRule({
284
+ source, root, relative: `rules/${relative}`,
285
+ knownHashes: legacy.files[relative] || [], dryRun, log,
286
+ });
287
+ }
288
+ }
289
+ for (const retired of retiredTopLevelRules) {
290
+ const knownHashes = legacy.files[retired] || [];
291
+ retireRule({ source: null, root, relative: `rules/${retired}`, knownHashes, dryRun, log });
292
+ if (host === "claude-code") {
293
+ retireRule({ source: null, root, relative: `references/rules/${retired}`, knownHashes, dryRun, log });
294
+ }
87
295
  }
88
296
  }
89
297
 
90
- module.exports = { installRules };
298
+ module.exports = { BACKUP_ROOT_NAME, installRules, finalizeBackups };
299
+
300
+ function parseCli(argv) {
301
+ let dryRun = false;
302
+ let backupId;
303
+ let finalize = false;
304
+ const positional = [];
305
+ for (let i = 0; i < argv.length; i += 1) {
306
+ const arg = argv[i];
307
+ if (arg === "--dry-run") {
308
+ dryRun = true;
309
+ } else if (arg === "--finalize-backups") {
310
+ finalize = true;
311
+ } else if (arg === "--backup-id") {
312
+ backupId = argv[++i];
313
+ if (!backupId || backupId.includes("/") || backupId.includes("\\") || backupId.includes("..")) {
314
+ throw new Error("Invalid --backup-id");
315
+ }
316
+ } else if (arg.startsWith("-")) {
317
+ throw new Error(`Unknown option: ${arg}`);
318
+ } else {
319
+ positional.push(arg);
320
+ }
321
+ }
322
+ return { dryRun, backupId, finalize, positional };
323
+ }
91
324
 
92
325
  if (require.main === module) {
93
- const [host, installRoot, ...options] = process.argv.slice(2);
94
326
  try {
95
- if (!installRoot || options.some((option) => option !== "--dry-run")) {
96
- throw new Error("Usage: install-rules.js <claude-code|codex> <install-root> [--dry-run]");
327
+ const { dryRun, backupId, finalize, positional } = parseCli(process.argv.slice(2));
328
+ if (finalize) {
329
+ const [installRoot] = positional;
330
+ if (!installRoot || positional.length !== 1) {
331
+ throw new Error("Usage: install-rules.js --finalize-backups <install-root> [--backup-id <id>] [--dry-run]");
332
+ }
333
+ finalizeBackups({ installRoot, backupId, dryRun });
334
+ } else {
335
+ const [host, installRoot] = positional;
336
+ if (!host || !installRoot || positional.length !== 2) {
337
+ throw new Error("Usage: install-rules.js <claude-code|codex> <install-root> [--backup-id <id>] [--dry-run]");
338
+ }
339
+ installRules({
340
+ sourceRoot: path.resolve(__dirname, ".."),
341
+ installRoot,
342
+ host,
343
+ backupId: backupId || defaultBackupId(),
344
+ dryRun,
345
+ });
97
346
  }
98
- installRules({ sourceRoot: path.resolve(__dirname, ".."), installRoot, host,
99
- dryRun: options.includes("--dry-run") });
100
347
  } catch (error) {
101
348
  process.stderr.write(`${error.message}\n`);
102
349
  process.exitCode = 1;
@@ -22,6 +22,7 @@ if (-not $HomeDir) {
22
22
 
23
23
  $InstallClaude = -not $CodexOnly
24
24
  $InstallCodex = -not $ClaudeOnly
25
+ $BackupId = Get-Date -Format 'yyyyMMddHHmmss'
25
26
 
26
27
  function Invoke-InstallCommand {
27
28
  param(
@@ -40,7 +41,8 @@ function Invoke-InstallCommand {
40
41
  function Backup-IfChanged {
41
42
  param(
42
43
  [string]$Source,
43
- [string]$Destination
44
+ [string]$Destination,
45
+ [string]$InstallRoot
44
46
  )
45
47
 
46
48
  if (-not (Test-Path -LiteralPath $Destination)) {
@@ -53,8 +55,19 @@ function Backup-IfChanged {
53
55
  return
54
56
  }
55
57
 
56
- $backup = "$Destination.bak.$(Get-Date -Format 'yyyyMMddHHmmss')"
58
+ $backupRoot = Join-Path $InstallRoot ".cew-backups"
59
+ $existingBackupRoot = Get-Item -LiteralPath $backupRoot -Force -ErrorAction SilentlyContinue
60
+ if ($null -ne $existingBackupRoot -and ($existingBackupRoot.Attributes -band [IO.FileAttributes]::ReparsePoint)) {
61
+ throw "Refusing symlinked backup directory: $backupRoot"
62
+ }
63
+
64
+ $relative = [IO.Path]::GetFileName($Destination)
65
+ $backupDir = Join-Path $backupRoot $BackupId
66
+ $backup = Join-Path $backupDir $relative
57
67
  Write-Host "Backup: $Destination -> $backup"
68
+ Invoke-InstallCommand `
69
+ -Description "New-Item -ItemType Directory '$backupDir'" `
70
+ -Action { New-Item -ItemType Directory -Path $backupDir -Force | Out-Null }
58
71
  Invoke-InstallCommand `
59
72
  -Description "Copy-Item '$Destination' '$backup'" `
60
73
  -Action { Copy-Item -LiteralPath $Destination -Destination $backup -Force }
@@ -63,10 +76,11 @@ function Backup-IfChanged {
63
76
  function Copy-ConfigFile {
64
77
  param(
65
78
  [string]$Source,
66
- [string]$Destination
79
+ [string]$Destination,
80
+ [string]$InstallRoot
67
81
  )
68
82
 
69
- Backup-IfChanged -Source $Source -Destination $Destination
83
+ Backup-IfChanged -Source $Source -Destination $Destination -InstallRoot $InstallRoot
70
84
  Invoke-InstallCommand `
71
85
  -Description "Copy-Item '$Source' '$Destination'" `
72
86
  -Action { Copy-Item -LiteralPath $Source -Destination $Destination -Force }
@@ -75,10 +89,11 @@ function Copy-ConfigFile {
75
89
  function Copy-ClaudeSettings {
76
90
  param(
77
91
  [string]$Source,
78
- [string]$Destination
92
+ [string]$Destination,
93
+ [string]$InstallRoot
79
94
  )
80
95
 
81
- Backup-IfChanged -Source $Source -Destination $Destination
96
+ Backup-IfChanged -Source $Source -Destination $Destination -InstallRoot $InstallRoot
82
97
 
83
98
  if ($DryRun) {
84
99
  Write-Host "[dry-run] Merge '$Source' into '$Destination' preserving existing user hooks, env and mcpServers"
@@ -145,19 +160,18 @@ function Remove-PackageOnlyPaths {
145
160
  "scripts\install.ps1",
146
161
  "scripts\install-rules.js",
147
162
  "scripts\legacy-common-rule-hashes.json",
163
+ "scripts\eval-scenarios.js",
148
164
  "scripts\verify-harness.js",
149
165
  "scripts\verify\core.js",
150
- "scripts\verify\grilling-spec-gate-checks.js",
151
166
  "scripts\verify\metadata-checks.js",
152
167
  "scripts\verify\repository-checks.js",
153
168
  "scripts\verify\runtime-checks.js",
154
169
  "scripts\verify\workflow-checks.js",
155
- "scripts\verify\workflow-ownership-fixtures.js",
156
- "scripts\verify\workflow-ownership.js",
170
+ "scripts\verify\scenario-checks.js",
171
+ "scripts\verify\scenario-checks.test.js",
157
172
  "scripts\verify\skill-manifest-checks.js",
158
173
  "scripts\verify\skill-manifest-checks.test.js",
159
174
  "scripts\verify\skill-invocation.test.js",
160
- "scripts\verify\continuation-checks.test.js",
161
175
  "scripts\verify\install-rules.test.js",
162
176
  "scripts\verify\learning.test.js",
163
177
  "scripts\verify\plugin-distribution.test.js"
@@ -284,14 +298,15 @@ function Install-ClaudeWorkflow {
284
298
  -Action { New-Item -ItemType Directory -Path $dest -Force | Out-Null }
285
299
 
286
300
  Remove-ObsoleteWorkflowPaths -Destination $dest
287
- Copy-ConfigFile -Source (Join-Path $RootDir "CLAUDE.md") -Destination (Join-Path $dest "CLAUDE.md")
288
- Copy-ConfigFile -Source (Join-Path $RootDir "AGENTS.md") -Destination (Join-Path $dest "AGENTS.md")
301
+ Copy-ConfigFile -Source (Join-Path $RootDir "CLAUDE.md") -Destination (Join-Path $dest "CLAUDE.md") -InstallRoot $dest
302
+ Copy-ConfigFile -Source (Join-Path $RootDir "AGENTS.md") -Destination (Join-Path $dest "AGENTS.md") -InstallRoot $dest
289
303
  $settingsPath = Join-Path $dest "settings.json"
290
- Copy-ClaudeSettings -Source (Join-Path $RootDir "settings.json") -Destination $settingsPath
304
+ Copy-ClaudeSettings -Source (Join-Path $RootDir "settings.json") -Destination $settingsPath -InstallRoot $dest
291
305
  Install-SharedDirs -Destination $dest
292
306
  Install-WorkflowRules -Destination $dest -HostName "claude-code"
293
307
  Remove-RetiredSkills -Destination $dest
294
308
  Remove-PackageOnlyPaths -Destination $dest
309
+ Complete-WorkflowBackups -Destination $dest
295
310
  }
296
311
 
297
312
  function Install-CodexWorkflow {
@@ -303,17 +318,18 @@ function Install-CodexWorkflow {
303
318
  -Action { New-Item -ItemType Directory -Path $dest -Force | Out-Null }
304
319
 
305
320
  Remove-ObsoleteWorkflowPaths -Destination $dest
306
- Copy-ConfigFile -Source (Join-Path $RootDir "AGENTS.md") -Destination (Join-Path $dest "AGENTS.md")
321
+ Copy-ConfigFile -Source (Join-Path $RootDir "AGENTS.md") -Destination (Join-Path $dest "AGENTS.md") -InstallRoot $dest
307
322
  Install-SharedDirs -Destination $dest
308
323
  Install-WorkflowRules -Destination $dest -HostName "codex"
309
324
  Remove-RetiredSkills -Destination $dest
310
325
  Remove-PackageOnlyPaths -Destination $dest
326
+ Complete-WorkflowBackups -Destination $dest
311
327
  }
312
328
 
313
329
  function Install-WorkflowRules {
314
330
  param([string]$Destination, [string]$HostName)
315
331
 
316
- $ruleArgs = @((Join-Path $RootDir "scripts\install-rules.js"), $HostName, $Destination)
332
+ $ruleArgs = @((Join-Path $RootDir "scripts\install-rules.js"), $HostName, $Destination, "--backup-id", $BackupId)
317
333
  if ($DryRun) { $ruleArgs += "--dry-run" }
318
334
  & node @ruleArgs
319
335
  if ($LASTEXITCODE -ne 0) {
@@ -321,6 +337,17 @@ function Install-WorkflowRules {
321
337
  }
322
338
  }
323
339
 
340
+ function Complete-WorkflowBackups {
341
+ param([string]$Destination)
342
+
343
+ $backupArgs = @((Join-Path $RootDir "scripts\install-rules.js"), "--finalize-backups", $Destination, "--backup-id", $BackupId)
344
+ if ($DryRun) { $backupArgs += "--dry-run" }
345
+ & node @backupArgs
346
+ if ($LASTEXITCODE -ne 0) {
347
+ throw "Backup finalization failed with exit code $LASTEXITCODE"
348
+ }
349
+ }
350
+
324
351
  if ($InstallClaude) {
325
352
  Test-InstallRoot -Destination (Join-Path $HomeDir ".claude")
326
353
  }