@aibyzero/cm-workflow 0.11.0 → 0.13.2

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 (130) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +3 -0
  3. package/CHANGELOG.md +64 -3
  4. package/README.md +45 -3
  5. package/VERSION +1 -1
  6. package/compat/claude-commands/cm-runtime.md +3 -0
  7. package/compat/claude-commands/cm-security.md +3 -0
  8. package/docs/architecture.md +22 -0
  9. package/docs/installation.md +56 -2
  10. package/docs/js-workflow-control.md +63 -6
  11. package/docs/runtime-failover.md +97 -0
  12. package/docs/user-guide.md +60 -3
  13. package/install-codex.sh +5 -0
  14. package/install.ps1 +10 -2
  15. package/install.sh +5 -0
  16. package/package.json +3 -1
  17. package/runtime/js/cm-ai/claude-developer-proposal.schema.json +151 -0
  18. package/runtime/js/cm-ai/claude-review-stream.mjs +69 -8
  19. package/runtime/js/cm-ai/claude-tool-preview.mjs +6 -4
  20. package/runtime/js/cm-ai/cm-ai-admission.mjs +38 -16
  21. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +44 -17
  22. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +105 -12
  23. package/runtime/js/cm-ai/codex-config.mjs +6 -0
  24. package/runtime/js/cm-ai/codex-review-adapter.mjs +6 -2
  25. package/runtime/js/cm-ai/developer-adapter.mjs +41 -16
  26. package/runtime/js/cm-ai/durable-runner-state.mjs +72 -15
  27. package/runtime/js/cm-ai/effect-contract.mjs +10 -1
  28. package/runtime/js/cm-ai/fix-code-association.mjs +4 -1
  29. package/runtime/js/cm-ai/host-conversation-execution.mjs +112 -27
  30. package/runtime/js/cm-ai/host-documentation.mjs +4 -2
  31. package/runtime/js/cm-ai/host-qa-executor.mjs +17 -4
  32. package/runtime/js/cm-ai/host-qa-policy.mjs +6 -3
  33. package/runtime/js/cm-ai/host-role-routing.mjs +9 -5
  34. package/runtime/js/cm-ai/host-tool-bridge.mjs +10 -7
  35. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +9 -4
  36. package/runtime/js/cm-ai/host.mjs +1 -1
  37. package/runtime/js/cm-ai/provider-review-observation.mjs +8 -4
  38. package/runtime/js/cm-ai/qa-attachment.mjs +30 -0
  39. package/runtime/js/cm-ai/review-package.mjs +76 -18
  40. package/runtime/js/cm-ai/review-runner.mjs +15 -3
  41. package/runtime/js/cm-ai/runtime-failover.mjs +75 -0
  42. package/runtime/js/cm-ai/specification-material.mjs +98 -0
  43. package/runtime/js/cm-ai/task-runner.mjs +57 -20
  44. package/runtime/js/cm-ai/worker-claude-developer.mjs +174 -0
  45. package/runtime/js/cm-ai/worker-claude.mjs +18 -5
  46. package/runtime/js/cm-ai/worker-codex-developer.mjs +15 -4
  47. package/runtime/js/cm-ai/worker-codex.mjs +8 -12
  48. package/runtime/js/cm-init/draft-generation.mjs +24 -4
  49. package/runtime/js/cm-init/draft-inspection.mjs +29 -1
  50. package/runtime/js/cm-prd/session.mjs +19 -2
  51. package/runtime/js/cm-prd/summary.mjs +46 -20
  52. package/runtime/js/cm-security/scan.mjs +263 -0
  53. package/runtime/js/cm-test/branch-impact.mjs +8 -2
  54. package/runtime/review.md +11 -1
  55. package/runtime/workflow-config.md +39 -2
  56. package/runtime/workflow-routing.md +6 -1
  57. package/scripts/cm-ai-admission.test.mjs +99 -0
  58. package/scripts/cm-ai-batch-host.test.mjs +4 -1
  59. package/scripts/cm-ai-batch-run.test.mjs +7 -1
  60. package/scripts/cm-ai-bootstrap.test.mjs +2 -1
  61. package/scripts/cm-ai-fix-integration.test.mjs +2 -1
  62. package/scripts/cm-ai-host.mjs +81 -12
  63. package/scripts/cm-ai-host.test.mjs +520 -5
  64. package/scripts/cm-ai-multi-root.test.mjs +9 -3
  65. package/scripts/cm-ai-nested-execution.test.mjs +11 -4
  66. package/scripts/cm-ai-review-timeout.test.mjs +226 -0
  67. package/scripts/cm-ai-run.mjs +40 -13
  68. package/scripts/cm-ai-run.test.mjs +45 -9
  69. package/scripts/cm-check-host.test.mjs +1 -1
  70. package/scripts/cm-check-runtime.sh +56 -1
  71. package/scripts/cm-check-update.mjs +200 -0
  72. package/scripts/cm-check-update.test.mjs +186 -0
  73. package/scripts/cm-claude-developer-worker.test.mjs +236 -0
  74. package/scripts/cm-claude-probe.test.mjs +64 -1
  75. package/scripts/cm-claude-review-stream.test.mjs +236 -1
  76. package/scripts/cm-claude-worker.test.mjs +110 -1
  77. package/scripts/cm-codex-developer-adapter.test.mjs +50 -2
  78. package/scripts/cm-codex-developer-worker.test.mjs +84 -1
  79. package/scripts/cm-codex-review-progress.test.mjs +34 -6
  80. package/scripts/cm-failover.mjs +288 -0
  81. package/scripts/cm-failover.test.mjs +184 -0
  82. package/scripts/cm-host-qa-executor.test.mjs +277 -0
  83. package/scripts/cm-host-tool-bridge.test.mjs +31 -0
  84. package/scripts/cm-init-draft-generation.test.mjs +62 -0
  85. package/scripts/cm-init-draft-inspection.test.mjs +76 -0
  86. package/scripts/cm-init-host.mjs +4 -4
  87. package/scripts/cm-init-host.test.mjs +12 -7
  88. package/scripts/cm-init-session.test.mjs +50 -0
  89. package/scripts/cm-log-event.mjs +34 -5
  90. package/scripts/cm-prd-completion.test.mjs +2 -2
  91. package/scripts/cm-prd-host.mjs +39 -3
  92. package/scripts/cm-prd-host.test.mjs +52 -0
  93. package/scripts/cm-prd-review-gate.mjs +11 -2
  94. package/scripts/cm-prd-review-gate.test.mjs +62 -0
  95. package/scripts/cm-prd-session-recovery.test.mjs +167 -0
  96. package/scripts/cm-prd-summary.test.mjs +147 -0
  97. package/scripts/cm-review-dependency-snapshot.test.mjs +10 -0
  98. package/scripts/cm-review-inventory.test.mjs +189 -0
  99. package/scripts/cm-review-schema.test.mjs +35 -1
  100. package/scripts/cm-review-scope-recovery.test.mjs +63 -0
  101. package/scripts/cm-runtime-edit.mjs +104 -0
  102. package/scripts/cm-runtime-failover.test.mjs +130 -0
  103. package/scripts/cm-runtime-install.mjs +42 -0
  104. package/scripts/cm-runtime.mjs +113 -0
  105. package/scripts/cm-runtime.test.mjs +117 -0
  106. package/scripts/cm-security.mjs +32 -0
  107. package/scripts/cm-security.test.mjs +203 -0
  108. package/scripts/cm-spec-manifest.mjs +24 -21
  109. package/scripts/cm-spec-manifest.test.mjs +19 -0
  110. package/scripts/cm-workflow-config.mjs +113 -5
  111. package/scripts/cm-workflow-config.test.mjs +124 -1
  112. package/scripts/fixtures/prd-review-gate-python-oracle.py +18 -2
  113. package/scripts/test-cm-prd-review-gate.py +30 -0
  114. package/scripts/test-shell-compat.sh +34 -0
  115. package/scripts/validate-public-repo.py +7 -1
  116. package/skills/cm-ai/references/N4-review.md +5 -4
  117. package/skills/cm-ai/references/js-host.md +36 -2
  118. package/skills/cm-check/SKILL.md +49 -8
  119. package/skills/cm-check/references/js-host.md +4 -1
  120. package/skills/cm-init/SKILL.md +4 -0
  121. package/skills/cm-init/references/js-host.md +2 -0
  122. package/skills/cm-init/references/runtime-declaration.md +26 -0
  123. package/skills/cm-prd/SKILL.md +3 -3
  124. package/skills/cm-prd/references/js-change-recovery.md +24 -3
  125. package/skills/cm-prd/references/summary-card.md +7 -0
  126. package/skills/cm-runtime/SKILL.md +32 -0
  127. package/skills/cm-security/SKILL.md +55 -0
  128. package/skills/cm-security/references/scan-contract.md +43 -0
  129. package/templates/auto-update/cm-update.sh +1 -1
  130. package/templates/cm-workflow.yml +16 -0
@@ -9,6 +9,10 @@ fail() {
9
9
  FAILURES=$((FAILURES + 1))
10
10
  }
11
11
 
12
+ warn() {
13
+ echo "WARN: $*" >&2
14
+ }
15
+
12
16
  require_file() {
13
17
  [ -f "$ROOT/$1" ] || fail "missing $1"
14
18
  }
@@ -275,6 +279,11 @@ for module in \
275
279
  require_file "runtime/js/cm-ai/$module"
276
280
  done
277
281
  require_file "scripts/cm-check-runtime.ps1"
282
+ require_file "scripts/cm-security.mjs"
283
+ require_file "scripts/cm-security.test.mjs"
284
+ require_file "runtime/js/cm-security/scan.mjs"
285
+ require_file "scripts/cm-check-update.mjs"
286
+ require_file "scripts/cm-check-update.test.mjs"
278
287
  require_file "scripts/cm-release-smoke.sh"
279
288
  require_file "scripts/cm-ai-admission.mjs"
280
289
  require_file "scripts/cm-ai-run.mjs"
@@ -296,6 +305,23 @@ require_file "scripts/cm-task-gate.py"
296
305
  require_file "scripts/test-task-gate.py"
297
306
  require_file "scripts/cm-workflow-config.mjs"
298
307
  require_file "scripts/cm-workflow-config.test.mjs"
308
+ # Group 4: user runtimes.yml producers <-> authoritative consumer.
309
+ for asset in scripts/cm-runtime.mjs scripts/cm-runtime-edit.mjs scripts/cm-runtime-install.mjs scripts/cm-runtime.test.mjs skills/cm-init/references/runtime-declaration.md; do
310
+ require_file "$asset"
311
+ done
312
+ grep -Fq 'userRuntimesPath' "$ROOT/scripts/cm-runtime.mjs" &&
313
+ grep -Fq 'writeUserRuntime' "$ROOT/scripts/cm-runtime-install.mjs" &&
314
+ grep -Fq 'runtimes.yml' "$ROOT/scripts/cm-workflow-config.mjs" &&
315
+ grep -Fq 'loadUserRuntimes()' "$ROOT/scripts/cm-workflow-config.mjs" &&
316
+ grep -Fq 'runtimes_source' "$ROOT/skills/cm-init/references/runtime-declaration.md" ||
317
+ fail "user runtimes.yml producer/consumer pairing is incomplete"
318
+ if [ "$MODE" = "plugin" ]; then
319
+ for installer in install.sh install.ps1 install-codex.sh; do
320
+ grep -Fq 'scripts/cm-runtime-install.mjs' "$ROOT/$installer" ||
321
+ fail "user runtimes.yml prompt not wired in $installer"
322
+ done
323
+ fi
324
+
299
325
  require_file "scripts/cm_workflow_config.py"
300
326
  require_file "scripts/test-workflow-config.py"
301
327
  require_file "scripts/validate-test-cases.mjs"
@@ -352,6 +378,35 @@ if [ -n "$NODE_BIN" ]; then
352
378
  "$NODE_BIN" "$ROOT/scripts/cm-workflow-config.mjs" --project "$PROJECT_PATH" ||
353
379
  fail "project workflow config validation failed"
354
380
  fi
381
+ # Runtime declaration vs. this machine. The declaration is the user's word;
382
+ # the probe only says whether a CLI resolves (never whether quota is usable).
383
+ # Roles whose adapter names the other runtime are declared, not dispatched.
384
+ effective_json=""
385
+ if [ -n "$CONFIG_PATH" ]; then
386
+ effective_json=$("$NODE_BIN" "$ROOT/scripts/cm-workflow-config.mjs" --project "$PROJECT_PATH" --config "$CONFIG_PATH" --print-effective 2>/dev/null || true)
387
+ else
388
+ effective_json=$("$NODE_BIN" "$ROOT/scripts/cm-workflow-config.mjs" --project "$PROJECT_PATH" --print-effective 2>/dev/null || true)
389
+ fi
390
+ if [ -n "$effective_json" ]; then
391
+ declared=$(printf '%s' "$effective_json" | "$NODE_BIN" -e 'let d="";process.stdin.on("data",c=>d+=c).on("end",()=>{const j=JSON.parse(d);process.stdout.write(String(j.runtimes&&j.runtimes.available||"unknown"));})' 2>/dev/null || echo unknown)
392
+ if [ "$declared" != "unknown" ]; then
393
+ probe_json=$("$NODE_BIN" "$ROOT/scripts/cm-failover.mjs" probe --json 2>/dev/null || true)
394
+ missing=$(printf '%s' "$probe_json" | "$NODE_BIN" -e 'let d="";process.stdin.on("data",c=>d+=c).on("end",()=>{let j={runtimes:[]};try{j=JSON.parse(d);}catch{}const want=process.argv[1]==="both"?["codex","claude"]:[process.argv[1]];const ok=new Set(j.runtimes.filter(r=>r.available).map(r=>r.runtime));process.stdout.write(want.filter(r=>!ok.has(r)).join(" "));})' "$declared" 2>/dev/null || true)
395
+ for rt in $missing; do
396
+ warn "runtimes.available 声明 ${declared},但本机 ${rt} CLI 不可解析(可解析≠配额可用)"
397
+ done
398
+ current_runtime="${CM_RUNTIME:-codex}"
399
+ for role in coder reviewer; do
400
+ if [ -n "$CONFIG_PATH" ]; then
401
+ role_json=$("$NODE_BIN" "$ROOT/scripts/cm-workflow-config.mjs" --project "$PROJECT_PATH" --config "$CONFIG_PATH" --role "$role" --runtime "$current_runtime" --print-role 2>/dev/null || true)
402
+ else
403
+ role_json=$("$NODE_BIN" "$ROOT/scripts/cm-workflow-config.mjs" --project "$PROJECT_PATH" --role "$role" --runtime "$current_runtime" --print-role 2>/dev/null || true)
404
+ fi
405
+ role_line=$(printf '%s' "$role_json" | "$NODE_BIN" -e 'let d="";process.stdin.on("data",c=>d+=c).on("end",()=>{let j={};try{j=JSON.parse(d);}catch{}const tag=j.route_state==="declared-adapter"?"(已声明未派发)":"";process.stdout.write(`${j.role||"?"}: adapter=${j.adapter||"?"} route_state=${j.route_state||"?"}${tag}`);})' 2>/dev/null || true)
406
+ [ -n "$role_line" ] && echo "runtime declaration [${declared}] ${role_line}"
407
+ done
408
+ fi
409
+ fi
355
410
  fi
356
411
  else
357
412
  fail "Node.js 18+ is required for CM workflow config validation"
@@ -575,7 +630,7 @@ for consumer in \
575
630
  fail "external-expert AUTO routing is not wired into $consumer"
576
631
  done
577
632
 
578
- for name in cm-idea cm-init cm-prd cm-ai cm-test cm-fix cm-refactor cm-check; do
633
+ for name in cm-idea cm-init cm-prd cm-ai cm-test cm-security cm-fix cm-refactor cm-check cm-runtime; do
579
634
  require_file "skills/$name/SKILL.md"
580
635
  require_file "compat/claude-commands/$name.md"
581
636
  wrapper="$ROOT/compat/claude-commands/$name.md"
@@ -0,0 +1,200 @@
1
+ #!/usr/bin/env node
2
+ // Upgrade preflight only. The check host and mechanical checker remain read-only.
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import https from 'node:https';
7
+ import {spawnSync} from 'node:child_process';
8
+ import {fileURLToPath, pathToFileURL} from 'node:url';
9
+
10
+ const PACKAGE = '@aibyzero/cm-workflow';
11
+ const REGISTRY = 'https://registry.npmjs.org/';
12
+ const stable = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?![\s\S])/;
13
+ export function compareVersions(a, b) {
14
+ if (!stable.test(a) || !stable.test(b)) throw new Error('Expected a stable X.Y.Z version');
15
+ const left = a.split('.').map(BigInt), right = b.split('.').map(BigInt);
16
+ for (let i = 0; i < 3; i++) if (left[i] !== right[i]) return left[i] > right[i] ? 1 : -1;
17
+ return 0;
18
+ }
19
+
20
+ export function latestVersion() {
21
+ return new Promise((resolve, reject) => {
22
+ const request = https.get(`${REGISTRY}@aibyzero%2fcm-workflow/latest`, response => {
23
+ let data = '';
24
+ if (response.statusCode !== 200) {
25
+ response.resume(); reject(new Error('Registry query failed')); return;
26
+ }
27
+ response.setEncoding('utf8');
28
+ response.on('data', chunk => {
29
+ data += chunk;
30
+ if (Buffer.byteLength(data) > 1024 * 1024) request.destroy(new Error('Registry response too large'));
31
+ });
32
+ response.on('error', reject);
33
+ response.on('end', () => {
34
+ try {
35
+ const value = JSON.parse(data);
36
+ if (value.name !== PACKAGE || !stable.test(value.version)) throw new Error('Invalid package metadata');
37
+ resolve(value.version);
38
+ } catch (error) { reject(error); }
39
+ });
40
+ });
41
+ const deadline = setTimeout(() => request.destroy(new Error('Registry query timed out')), 10000);
42
+ request.on('close', () => clearTimeout(deadline));
43
+ request.on('error', reject);
44
+ });
45
+ }
46
+
47
+ function versionAt(root, runtime) {
48
+ const file = path.join(root, runtime === 'claude' ? 'templates/cm-VERSION' : 'VERSION');
49
+ const stat = fs.lstatSync(file);
50
+ if (!stat.isFile() || stat.nlink !== 1) throw new Error('Version file must be an owned regular file');
51
+ const version = fs.readFileSync(file, 'utf8').trim();
52
+ compareVersions(version, version);
53
+ return version;
54
+ }
55
+
56
+ function regularFile(file) {
57
+ const stat = fs.lstatSync(file);
58
+ if (!stat.isFile() || stat.nlink !== 1) throw new Error('Expected an owned regular file');
59
+ }
60
+
61
+ function optionalRegularFile(file) {
62
+ try { regularFile(file); return true; }
63
+ catch (error) { if (error.code === 'ENOENT') return false; throw error; }
64
+ }
65
+
66
+ // Reject redirected installation trees, including a redirected ancestor below HOME.
67
+ function ownedDirectory(dir, home, allowMissing = false) {
68
+ const relative = path.relative(home, dir);
69
+ if (relative.startsWith(`..${path.sep}`) || relative === '..' || path.isAbsolute(relative)) {
70
+ throw new Error('Automatic upgrade requires an installation inside HOME');
71
+ }
72
+ let cursor = home;
73
+ for (const segment of relative.split(path.sep).filter(Boolean)) {
74
+ cursor = path.join(cursor, segment);
75
+ let stat;
76
+ try { stat = fs.lstatSync(cursor); }
77
+ catch (error) { if (allowMissing && error.code === 'ENOENT') return; throw error; }
78
+ if (!stat.isDirectory()) throw new Error('Installation path must not contain symlinks');
79
+ }
80
+ }
81
+
82
+ export async function updateInstallation({skillDir, runtime}, {
83
+ env = process.env, platform = process.platform, query = latestVersion, run = spawnSync,
84
+ } = {}) {
85
+ let root, current, latest, lock, temporary;
86
+ const result = (status, reason, workflowRoot = root, installed = current) =>
87
+ ({status, reason, current, latest, installed, workflowRoot});
88
+ try {
89
+ if (!['codex', 'claude'].includes(runtime) || !path.isAbsolute(skillDir)) throw new Error('Invalid invocation');
90
+ root = fs.realpathSync(path.resolve(skillDir, '../..'));
91
+ if (fs.realpathSync(skillDir) !== path.join(root, 'skills/cm-check')) throw new Error('Invalid Skill root');
92
+ regularFile(path.join(root, 'skills/cm-check/SKILL.md'));
93
+ // Source checkouts use VERSION even when invoked from Claude.
94
+ const versionRuntime = fs.existsSync(path.join(root, 'VERSION')) ? 'codex' : runtime;
95
+ current = versionAt(root, versionRuntime);
96
+ try { latest = await query(); compareVersions(latest, latest); }
97
+ catch { return result('offline', 'Cannot confirm the latest npm version; continue local checks with this limitation.'); }
98
+
99
+ for (const key of ['HOME', runtime === 'codex' ? 'CODEX_HOME' : 'CLAUDE_HOME']) {
100
+ if (env[key] && !path.isAbsolute(env[key])) throw new Error(`${key} must be an absolute path`);
101
+ }
102
+ const home = fs.realpathSync(env.HOME || os.homedir());
103
+ const target = runtime === 'codex' ? path.join(home, 'plugins/cm-workflow') :
104
+ path.resolve(env.CLAUDE_HOME || path.join(home, '.claude'));
105
+ const codexHome = path.resolve(env.CODEX_HOME || path.join(home, '.codex'));
106
+ const cache = path.join(codexHome, 'plugins/cache');
107
+ const cacheParts = path.relative(cache, root).split(path.sep);
108
+ const marketplaceFile = path.join(home, '.agents/plugins/marketplace.json');
109
+ let marketplaceName;
110
+ if (runtime === 'codex') {
111
+ ownedDirectory(codexHome, home, true);
112
+ ownedDirectory(path.dirname(marketplaceFile), home, true);
113
+ }
114
+ if (runtime === 'codex' && optionalRegularFile(marketplaceFile)) {
115
+ marketplaceName = JSON.parse(fs.readFileSync(marketplaceFile, 'utf8')).name;
116
+ }
117
+ const knownCache = runtime === 'codex' && cacheParts.length === 3 &&
118
+ typeof marketplaceName === 'string' && cacheParts[0] === marketplaceName && cacheParts[1] === 'cm-workflow';
119
+ if (fs.existsSync(path.join(root, '.git')) || (root !== target && !knownCache)) {
120
+ return result('unmanaged', 'Source checkout or another package manager: report available version without replacing this installation.');
121
+ }
122
+ ownedDirectory(root, home);
123
+ ownedDirectory(target, home);
124
+ if (fs.existsSync(path.join(target, '.git'))) throw new Error('Managed destination contains a source checkout');
125
+ const installed = versionAt(target, runtime);
126
+ if (compareVersions(installed, current) < 0) throw new Error('Managed installation is older than the active Skill; refuse downgrade');
127
+ if (compareVersions(installed, latest) >= 0) {
128
+ return result(installed === latest ? 'current' : 'ahead', 'Using the verified managed installation.', target, installed);
129
+ }
130
+ if (platform === 'win32' || (runtime === 'codex' && platform !== 'darwin')) {
131
+ return result('blocked', 'Automatic npm upgrade supports macOS Codex and POSIX Claude; use the documented platform installer.');
132
+ }
133
+ // A second cm-check must not race an installation. Never remove another run's lock.
134
+ const lockPath = `${target}.cm-check-update.lock`;
135
+ fs.mkdirSync(lockPath); lock = lockPath;
136
+ ownedDirectory(target, home);
137
+ if (fs.existsSync(path.join(target, '.git'))) throw new Error('Managed destination contains a source checkout');
138
+ const lockedVersion = versionAt(target, runtime);
139
+ if (compareVersions(lockedVersion, current) < 0) throw new Error('Managed version changed; refuse downgrade');
140
+ if (compareVersions(lockedVersion, latest) >= 0) {
141
+ return result(lockedVersion === latest ? 'current' : 'ahead', 'Installation changed before locking; using its newer version.', target, lockedVersion);
142
+ }
143
+ temporary = fs.mkdtempSync(path.join(os.tmpdir(), 'cm-check-update-'));
144
+ const installEnv = {...env, HOME: home,
145
+ ...(runtime === 'codex' ? {CODEX_HOME: codexHome} : {CLAUDE_HOME: target})};
146
+ const npmEnv = Object.fromEntries(Object.entries(installEnv).filter(([key]) => !/^npm_config_/i.test(key)));
147
+ const config = path.join(temporary, 'user.npmrc'), globalConfig = path.join(temporary, 'global.npmrc');
148
+ fs.writeFileSync(config, ''); fs.writeFileSync(globalConfig, '');
149
+ const downloaded = run('npm', ['install', `${PACKAGE}@${latest}`, '--prefix', temporary,
150
+ '--ignore-scripts', '--no-audit', '--no-fund', '--no-save', '--package-lock=false',
151
+ `--registry=${REGISTRY}`, `--@aibyzero:registry=${REGISTRY}`,
152
+ `--userconfig=${config}`, `--globalconfig=${globalConfig}`, '--cache', path.join(temporary, 'cache')],
153
+ {cwd: temporary, env: npmEnv, encoding: 'utf8', timeout: 120000, maxBuffer: 1024 * 1024});
154
+ if (downloaded.error || downloaded.signal || downloaded.status !== 0) throw new Error('npm package download failed; installation was not started');
155
+ const source = path.join(temporary, 'node_modules/@aibyzero/cm-workflow');
156
+ const metadata = JSON.parse(fs.readFileSync(path.join(source, 'package.json'), 'utf8'));
157
+ if (metadata.name !== PACKAGE || metadata.version !== latest || versionAt(source, 'codex') !== latest) {
158
+ throw new Error('Downloaded package identity/version mismatch');
159
+ }
160
+ const installer = path.join(source, runtime === 'codex' ? 'install-codex.sh' : 'install.sh');
161
+ regularFile(installer);
162
+ ownedDirectory(target, home);
163
+ if (fs.existsSync(path.join(target, '.git')) || versionAt(target, runtime) !== lockedVersion) {
164
+ throw new Error('Installation changed during download; rerun the check');
165
+ }
166
+ if (runtime === 'codex') {
167
+ ownedDirectory(codexHome, home, true);
168
+ ownedDirectory(path.dirname(marketplaceFile), home, true);
169
+ optionalRegularFile(marketplaceFile);
170
+ }
171
+ const installedResult = run('/bin/bash', [installer, '--yes'], {cwd: source, env: installEnv, stdio: ['ignore', 2, 2]});
172
+ if (installedResult.error || installedResult.signal || installedResult.status !== 0) {
173
+ throw new Error('Installer failed; inspect installer output and its rollback result');
174
+ }
175
+ ownedDirectory(target, home);
176
+ if (versionAt(target, runtime) !== latest) throw new Error('Installer exited successfully but installed version does not match');
177
+ regularFile(path.join(target, 'scripts/cm-check-host.mjs'));
178
+ regularFile(path.join(target, 'skills/cm-check/SKILL.md'));
179
+ return result('updated', 'Upgrade verified; check the returned root and start a new session for other Skills.', target, latest);
180
+ } catch (error) {
181
+ return result('blocked', error.message);
182
+ } finally {
183
+ if (temporary) fs.rmSync(temporary, {recursive: true, force: true});
184
+ if (lock) fs.rmdirSync(lock);
185
+ }
186
+ }
187
+
188
+ const ownFile = fileURLToPath(import.meta.url);
189
+ if (process.argv[1] && pathToFileURL(fs.realpathSync(process.argv[1])).href === import.meta.url) {
190
+ const args = process.argv.slice(2);
191
+ if (args.length !== 4 || args[0] !== '--skill-dir' || args[2] !== '--runtime' ||
192
+ path.resolve(args[1], '../../scripts/cm-check-update.mjs') !== ownFile) {
193
+ console.error('Usage: node cm-check-update.mjs --skill-dir ABS --runtime codex|claude (from that installation)');
194
+ process.exitCode = 2;
195
+ } else {
196
+ const report = await updateInstallation({skillDir: args[1], runtime: args[3]});
197
+ console.log(JSON.stringify(report));
198
+ process.exitCode = report.status === 'blocked' ? 1 : 0;
199
+ }
200
+ }
@@ -0,0 +1,186 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import {compareVersions, updateInstallation} from './cm-check-update.mjs';
7
+
8
+ function fixture(t, runtime = 'codex') {
9
+ const home = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'cm-update-test-')));
10
+ t.after(() => fs.rmSync(home, {recursive: true, force: true}));
11
+ const root = path.join(home, runtime === 'codex' ? 'plugins/cm-workflow' : '.claude');
12
+ const write = (file, value) => { fs.mkdirSync(path.dirname(file), {recursive: true}); fs.writeFileSync(file, value); };
13
+ const versionFile = runtime === 'codex' ? 'VERSION' : 'templates/cm-VERSION';
14
+ write(path.join(root, versionFile), '0.10.6\n');
15
+ write(path.join(root, 'skills/cm-check/SKILL.md'), '# cm-check');
16
+ write(path.join(root, 'scripts/cm-check-host.mjs'), '// host');
17
+ if (runtime === 'codex') write(path.join(home, '.agents/plugins/marketplace.json'), '{"name":"personal"}');
18
+ const calls = [];
19
+ const state = {home, root, write, calls, latest: '0.11.0', installerStatus: 0, writeVersion: true};
20
+ state.options = {env: {HOME: home, npm_config_registry: 'https://invalid.example'}, platform: 'darwin',
21
+ query: async () => state.latest,
22
+ run: (command, args, options) => {
23
+ calls.push({command, args, options});
24
+ if (command === 'npm') {
25
+ const source = path.join(options.cwd, 'node_modules/@aibyzero/cm-workflow');
26
+ write(path.join(source, 'package.json'), JSON.stringify({name: '@aibyzero/cm-workflow', version: state.latest}));
27
+ write(path.join(source, 'VERSION'), state.latest);
28
+ write(path.join(source, runtime === 'codex' ? 'install-codex.sh' : 'install.sh'), '# installer');
29
+ return {status: 0};
30
+ }
31
+ if (state.writeVersion) write(path.join(root, versionFile), state.latest);
32
+ return {status: state.installerStatus};
33
+ }};
34
+ state.input = {skillDir: path.join(root, 'skills/cm-check'), runtime};
35
+ return state;
36
+ }
37
+
38
+ test('stable version ordering is numeric and rejects tags, prereleases and shell input', () => {
39
+ assert.equal(compareVersions('0.11.0', '0.9.99'), 1);
40
+ assert.equal(compareVersions('1.0.0', '1.0.0'), 0);
41
+ assert.equal(compareVersions('0.11.0', '1.0.0'), -1);
42
+ for (const version of ['latest', '01.2.3', '1.0.0-beta', '1.0.0;touch nope', '1.0.0\n']) {
43
+ assert.throws(() => compareVersions(version, '1.0.0'));
44
+ }
45
+ });
46
+
47
+ for (const runtime of ['codex', 'claude']) test(`${runtime}: default upgrade uses pinned npm and existing installer, then verifies disk`, async t => {
48
+ const f = fixture(t, runtime);
49
+ const report = await updateInstallation(f.input, f.options);
50
+ assert.equal(report.status, 'updated');
51
+ assert.equal(report.installed, '0.11.0');
52
+ assert.equal(report.workflowRoot, f.root);
53
+ assert.equal(f.calls.length, 2);
54
+ assert.ok(f.calls[0].args.includes('@aibyzero/cm-workflow@0.11.0'));
55
+ assert.ok(f.calls[0].args.includes('--ignore-scripts'));
56
+ assert.ok(f.calls[0].args.includes('--@aibyzero:registry=https://registry.npmjs.org/'));
57
+ assert.equal(f.calls[0].options.env.npm_config_registry, undefined);
58
+ assert.equal(f.calls[1].args[1], '--yes');
59
+ assert.equal(f.calls[1].options.stdio[0], 'ignore');
60
+ assert.equal(fs.existsSync(f.calls[0].options.cwd), false);
61
+ assert.equal(fs.existsSync(`${f.root}.cm-check-update.lock`), false);
62
+ });
63
+
64
+ for (const latest of ['0.10.6', '0.9.0']) test(`no download when latest ${latest} is equal or older`, async t => {
65
+ const f = fixture(t); f.latest = latest;
66
+ assert.equal((await updateInstallation(f.input, f.options)).status, latest === '0.10.6' ? 'current' : 'ahead');
67
+ assert.equal(f.calls.length, 0);
68
+ });
69
+
70
+ test('offline or invalid registry metadata permits local checks but never claims current', async t => {
71
+ const f = fixture(t);
72
+ for (const query of [async () => {throw new Error('network');}, async () => '1.0.0-beta']) {
73
+ const report = await updateInstallation(f.input, {...f.options, query});
74
+ assert.equal(report.status, 'offline');
75
+ assert.equal(report.workflowRoot, f.root);
76
+ }
77
+ assert.equal(f.calls.length, 0);
78
+ });
79
+
80
+ test('source checkout and unknown package managers are never overwritten', async t => {
81
+ const f = fixture(t);
82
+ f.write(path.join(f.root, '.git'), 'gitdir: elsewhere');
83
+ assert.equal((await updateInstallation(f.input, f.options)).status, 'unmanaged');
84
+ fs.unlinkSync(path.join(f.root, '.git'));
85
+ const moved = path.join(f.home, 'source'); fs.renameSync(f.root, moved);
86
+ assert.equal((await updateInstallation({...f.input, skillDir: path.join(moved, 'skills/cm-check')}, f.options)).status, 'unmanaged');
87
+ assert.equal(f.calls.length, 0);
88
+ });
89
+
90
+ test('old active cache checks newer managed installation without reinstalling or downgrading', async t => {
91
+ const f = fixture(t);
92
+ const cache = path.join(f.home, '.codex/plugins/cache/personal/cm-workflow/old');
93
+ f.write(path.join(cache, 'VERSION'), '0.10.6');
94
+ f.write(path.join(cache, 'skills/cm-check/SKILL.md'), '# old');
95
+ f.write(path.join(f.root, 'VERSION'), '0.11.0');
96
+ const input = {...f.input, skillDir: path.join(cache, 'skills/cm-check')};
97
+ const report = await updateInstallation(input, f.options);
98
+ assert.equal(report.status, 'current'); assert.equal(report.workflowRoot, f.root);
99
+ assert.equal(report.installed, '0.11.0'); assert.equal(f.calls.length, 0);
100
+ f.write(path.join(cache, 'VERSION'), '0.12.0');
101
+ assert.equal((await updateInstallation(input, f.options)).status, 'blocked');
102
+ });
103
+
104
+ test('another upgrade completed before locking cannot be downgraded by stale registry data', async t => {
105
+ const f = fixture(t), mkdir = fs.mkdirSync;
106
+ t.mock.method(fs, 'mkdirSync', (dir, options) => {
107
+ if (dir === `${f.root}.cm-check-update.lock`) fs.writeFileSync(path.join(f.root, 'VERSION'), '0.12.0');
108
+ return mkdir(dir, options);
109
+ });
110
+ const report = await updateInstallation(f.input, f.options);
111
+ assert.equal(report.status, 'ahead'); assert.equal(report.installed, '0.12.0');
112
+ assert.equal(f.calls.length, 0);
113
+ });
114
+
115
+ test('an external installer changing the version during download blocks the stale installer', async t => {
116
+ const f = fixture(t), run = f.options.run;
117
+ f.options.run = (...args) => {
118
+ const result = run(...args);
119
+ f.write(path.join(f.root, 'VERSION'), '0.12.0');
120
+ return result;
121
+ };
122
+ assert.equal((await updateInstallation(f.input, f.options)).status, 'blocked');
123
+ assert.equal(f.calls.length, 1);
124
+ assert.equal(fs.readFileSync(path.join(f.root, 'VERSION'), 'utf8'), '0.12.0');
125
+ });
126
+
127
+ for (const [runtime, key] of [['codex', 'HOME'], ['codex', 'CODEX_HOME'], ['claude', 'CLAUDE_HOME']]) {
128
+ test(`relative ${key} cannot redirect installation when cwd changes`, async t => {
129
+ const f = fixture(t, runtime); f.options.env[key] = '.';
130
+ const report = await updateInstallation(f.input, f.options);
131
+ assert.equal(report.status, 'blocked'); assert.match(report.reason, /absolute path/);
132
+ assert.equal(f.calls.length, 0);
133
+ });
134
+ }
135
+
136
+ test('redirected marketplace ancestor is rejected even before its JSON file exists', async t => {
137
+ const f = fixture(t), outside = path.join(f.home, 'redirected');
138
+ fs.rmSync(path.join(f.home, '.agents'), {recursive: true}); fs.mkdirSync(outside);
139
+ fs.symlinkSync(outside, path.join(f.home, '.agents'), 'dir');
140
+ const report = await updateInstallation(f.input, f.options);
141
+ assert.equal(report.status, 'blocked'); assert.equal(f.calls.length, 0);
142
+ assert.deepEqual(fs.readdirSync(outside), []);
143
+ });
144
+
145
+ test('marketplace symlink introduced during download cannot redirect the installer', async t => {
146
+ const f = fixture(t), run = f.options.run;
147
+ f.options.run = (...args) => {
148
+ const result = run(...args), file = path.join(f.home, '.agents/plugins/marketplace.json');
149
+ fs.unlinkSync(file); fs.symlinkSync(path.join(f.home, 'not-created.json'), file);
150
+ return result;
151
+ };
152
+ assert.equal((await updateInstallation(f.input, f.options)).status, 'blocked');
153
+ assert.equal(f.calls.length, 1);
154
+ assert.equal(fs.existsSync(path.join(f.home, 'not-created.json')), false);
155
+ });
156
+
157
+ for (const mode of ['failure', 'false-success', 'download-failure', 'wrong-package', 'lock', 'unsupported', 'symlink']) {
158
+ test(`upgrade ${mode} is blocked without claiming success`, async t => {
159
+ const f = fixture(t);
160
+ if (mode === 'failure') { f.installerStatus = 1; f.writeVersion = false; }
161
+ if (mode === 'false-success') f.writeVersion = false;
162
+ if (mode === 'download-failure') f.options.run = () => ({status: 1});
163
+ if (mode === 'wrong-package') {
164
+ const run = f.options.run;
165
+ f.options.run = (...args) => {
166
+ const result = run(...args);
167
+ f.write(path.join(args[2].cwd, 'node_modules/@aibyzero/cm-workflow/package.json'), '{"name":"other","version":"0.11.0"}');
168
+ return result;
169
+ };
170
+ }
171
+ if (mode === 'lock') fs.mkdirSync(`${f.root}.cm-check-update.lock`);
172
+ if (mode === 'unsupported') f.options.platform = 'win32';
173
+ if (mode === 'symlink') {
174
+ const destination = path.join(f.home, 'redirected'); fs.renameSync(f.root, destination);
175
+ fs.symlinkSync(destination, f.root, 'dir');
176
+ // A canonical root outside the managed path is explicitly unmanaged.
177
+ assert.equal((await updateInstallation(f.input, f.options)).status, 'unmanaged');
178
+ assert.equal(f.calls.length, 0); return;
179
+ }
180
+ const report = await updateInstallation(f.input, f.options);
181
+ assert.equal(report.status, 'blocked');
182
+ assert.equal(fs.readFileSync(path.join(f.root, 'VERSION'), 'utf8').trim(), '0.10.6');
183
+ if (mode === 'lock') assert.equal(fs.existsSync(`${f.root}.cm-check-update.lock`), true);
184
+ else assert.equal(fs.existsSync(`${f.root}.cm-check-update.lock`), false);
185
+ });
186
+ }