@aibyzero/cm-workflow 0.11.0 → 0.12.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.
@@ -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
+ }
@@ -0,0 +1,32 @@
1
+ #!/usr/bin/env node
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import {fileURLToPath} from 'node:url';
5
+ import {scan} from '../runtime/js/cm-security/scan.mjs';
6
+
7
+ export function main(argv){
8
+ let project=process.cwd();const options={};const seen=new Set();
9
+ for(let i=0;i<argv.length;i++){
10
+ const key=argv[i];
11
+ if(key==='--help')return {help:'cm-security.mjs [--project PATH] [--all] [--inventory] [--semgrep-rules EXTERNAL_FILE] [--osv-db EXTERNAL_CACHE_DIR]'};
12
+ if(seen.has(key))throw new Error('duplicate_argument');seen.add(key);
13
+ if(key==='--all')options.all=true;
14
+ else if(key==='--inventory')options.inventoryOnly=true;
15
+ else if(['--project','--semgrep-rules','--osv-db'].includes(key)){
16
+ const value=argv[++i];if(!value||value.startsWith('--'))throw new Error('argument_value_required');
17
+ if(key==='--project')project=value;
18
+ else options[key==='--semgrep-rules'?'semgrepRules':'osvDb']=value;
19
+ }else throw new Error('unknown_argument');
20
+ }
21
+ return scan(fs.realpathSync(project),options);
22
+ }
23
+ if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url)){
24
+ try{
25
+ const result=main(process.argv.slice(2));console.log(JSON.stringify(result,null,2));
26
+ process.exitCode=result.help?0:result.result==='BLOCKED'?2:result.findings?.length?1:result.result==='NO_CHANGES'?0:3;
27
+ }catch(error){
28
+ // Do not echo paths, input values, source snippets or scanner stderr from exceptions.
29
+ console.log(JSON.stringify({result:'BLOCKED',coverage:'PARTIAL',reason:/^[a-z0-9_]+$/.test(error.message)?error.message:'scan_failed'}));
30
+ process.exitCode=2;
31
+ }
32
+ }
@@ -0,0 +1,203 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import os from 'node:os';
6
+ import crypto from 'node:crypto';
7
+ import {fileURLToPath} from 'node:url';
8
+ import {spawnSync,execFileSync} from 'node:child_process';
9
+ import {inventory,scan,normalize} from '../runtime/js/cm-security/scan.mjs';
10
+ import {main} from './cm-security.mjs';
11
+
12
+ const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');
13
+ const gitBin=execFileSync('/bin/sh',['-c','command -v git'],{encoding:'utf8'}).trim();
14
+ function fixture(t){
15
+ const base=fs.mkdtempSync(path.join(os.tmpdir(),'cm-security-test-'));
16
+ const project=path.join(base,'project with spaces');fs.mkdirSync(project);
17
+ t.after(()=>fs.rmSync(base,{recursive:true,force:true}));
18
+ const git=(...args)=>execFileSync(gitBin,['-c','core.fsmonitor=false','-C',project,...args],{stdio:['ignore','pipe','pipe']}).toString();
19
+ const put=(file,text)=>{fs.mkdirSync(path.dirname(path.join(project,file)),{recursive:true});fs.writeFileSync(path.join(project,file),text);};
20
+ git('init','-b','main');git('config','user.name','Fixture');git('config','user.email','fixture@example.test');
21
+ put('app.py','print("base")\n');git('add','.');git('commit','-m','base');git('switch','-c','feature');
22
+ return {base,project,git,put};
23
+ }
24
+ function isolatedPath(t,f,programs={}){
25
+ const old=process.env.PATH,bin=path.join(f.base,'bin');fs.mkdirSync(bin);
26
+ fs.symlinkSync(gitBin,path.join(bin,'git'));
27
+ for(const [name,body] of Object.entries(programs))fs.writeFileSync(path.join(bin,name),`#!${process.execPath}\n${body}`,{mode:0o700});
28
+ process.env.PATH=bin;t.after(()=>{process.env.PATH=old;});
29
+ }
30
+ const fakeLeak=(body='')=>`
31
+ const fs=require('fs'),path=require('path'),args=process.argv.slice(2);
32
+ if(args.includes('--version')){console.log('9.0.0');process.exit(0);}
33
+ ${body}
34
+ `;
35
+
36
+ test('scope includes branch commits, working/index differences, deletes and renames; excludes untracked',t=>{
37
+ const f=fixture(t);f.put('app.py','print("feature")\n');f.put('renamed.py','ok\n');f.git('add','.');f.git('commit','-m','change');
38
+ f.git('mv','renamed.py','new name.py');f.put('app.py','print("staged")\n');f.git('add','app.py');f.put('app.py','print("worktree")\n');
39
+ f.put('untracked-private.txt','DO NOT READ');
40
+ const result=inventory(f.project);
41
+ assert.deepEqual(result.selected,['app.py','new name.py','renamed.py']);
42
+ assert.equal(result.untracked,1);assert.ok(!result.files.some(v=>v.path==='untracked-private.txt'));
43
+ assert.deepEqual(result.files.filter(v=>v.path==='app.py').map(v=>v.revision),['worktree','index']);
44
+ assert.ok(result.gaps.some(v=>v.path==='renamed.py'&&v.reason==='deleted_review_baseline'));
45
+ });
46
+
47
+ test('full scope works without main; ambiguous/missing branch base blocks default',t=>{
48
+ const f=fixture(t);f.git('branch','master');assert.throws(()=>inventory(f.project),/main_ambiguous/);
49
+ assert.equal(inventory(f.project,{all:true}).files.length,1);
50
+ f.git('branch','-D','main','master');assert.throws(()=>inventory(f.project),/main_missing/);
51
+ assert.equal(inventory(f.project,{all:true}).files.length,1);
52
+ });
53
+
54
+ test('no change is distinct from partial and missing tools do not pass',t=>{
55
+ const f=fixture(t);isolatedPath(t,f);
56
+ assert.equal(scan(f.project).result,'NO_CHANGES');f.put('app.py','changed\n');
57
+ const r=scan(f.project);assert.equal(r.coverage,'PARTIAL');assert.equal(r.sourceUnchanged,true);
58
+ assert.ok(r.tools.every(v=>v.reason==='tool_missing'));assert.equal(r.aiReview,'pending');
59
+ });
60
+
61
+ test('symlink ancestor, protected files and scanner controls are visible gaps',t=>{
62
+ const f=fixture(t);f.put('dir/file.py','ok');f.put('.env','private fixture');f.put('.gitleaks.toml','malicious rule');f.git('add','.');
63
+ fs.renameSync(path.join(f.project,'dir'),path.join(f.base,'outside'));
64
+ fs.symlinkSync(path.join(f.base,'outside'),path.join(f.project,'dir'));
65
+ const r=inventory(f.project,{all:true});
66
+ assert.ok(r.gaps.some(v=>v.path==='dir/file.py'&&v.reason==='symlink'));
67
+ assert.ok(r.gaps.some(v=>v.path==='.env'&&v.reason==='protected_path_not_read'));
68
+ assert.ok(r.gaps.some(v=>v.reason==='scanner_control_excluded_review_manually'));
69
+ assert.ok(!r.files.some(v=>v.path==='.env'||v.path==='.gitleaks.toml'));
70
+ assert.ok(!r.files.some(v=>v.path==='dir/file.py'&&v.revision==='worktree'));
71
+ });
72
+
73
+ test('source/config limits and malformed CLI are blocked',t=>{
74
+ const f=fixture(t);f.put('large.py',Buffer.alloc(1024*1024+1));f.git('add','.');
75
+ assert.ok(inventory(f.project).gaps.some(v=>v.reason==='oversize'));
76
+ assert.throws(()=>main(['--all','--all']),/duplicate/);
77
+ assert.throws(()=>main(['--project']),/required/);
78
+ assert.throws(()=>main(['--untrusted-shell-command']),/unknown/);
79
+ });
80
+
81
+ test('Git fsmonitor configuration never executes during main-ref or scope reads',t=>{
82
+ const f=fixture(t),marker=path.join(f.base,'called');
83
+ const monitor=path.join(f.base,'monitor');fs.writeFileSync(monitor,`#!/bin/sh\ntouch '${marker}'\n`,{mode:0o700});
84
+ f.git('config','core.fsmonitor',monitor);inventory(f.project);assert.ok(!fs.existsSync(marker));
85
+ });
86
+
87
+ test('normalization strips secrets and rejects foreign file/line references',()=>{
88
+ const files=[{path:'a.py',revision:'worktree',bytes:Buffer.from('a\nb\n')}];const base='/snapshot';
89
+ const r=normalize('gitleaks',[{File:'worktree/a.py',StartLine:1,RuleID:'generic-api-key',Secret:'DO_NOT_OUTPUT',Match:'DO_NOT_OUTPUT'}],files,base);
90
+ assert.equal(r.findings.length,1);assert.ok(!JSON.stringify(r).includes('DO_NOT_OUTPUT'));
91
+ for(const [File,StartLine] of [['../../outside',1],['worktree/a.py',99]]){
92
+ assert.throws(()=>normalize('gitleaks',[{File,StartLine,RuleID:'rule'}],files,base),/location/);
93
+ }
94
+ assert.throws(()=>normalize('semgrep',{results:[],errors:[{}],paths:{scanned:[]}},files,base),/errors/);
95
+ const s=normalize('semgrep',{results:[],errors:[],paths:{scanned:[]}},files,base);assert.equal(s.unscanned.length,1);
96
+ const o=normalize('osv',{results:[{source:{path:'worktree/a.py'},packages:[{vulnerabilities:[{id:'CVE-2099-1234',details:'DO_NOT_OUTPUT'}]}]}]},files,base);
97
+ assert.equal(o.findings[0].rule,'CVE-2099-1234');assert.ok(!JSON.stringify(o).includes('DO_NOT_OUTPUT'));
98
+ });
99
+
100
+ test('adapter clears secrets/config environment and returns safe findings',t=>{
101
+ const f=fixture(t);f.put('app.py','new\n');
102
+ const prior=process.env.GITLEAKS_CONFIG,priorSecret=process.env.CM_TEST_PRIVATE_VALUE;
103
+ process.env.GITLEAKS_CONFIG='malicious';process.env.CM_TEST_PRIVATE_VALUE='private';
104
+ t.after(()=>{if(prior===undefined)delete process.env.GITLEAKS_CONFIG;else process.env.GITLEAKS_CONFIG=prior;
105
+ if(priorSecret===undefined)delete process.env.CM_TEST_PRIVATE_VALUE;else process.env.CM_TEST_PRIVATE_VALUE=priorSecret;});
106
+ isolatedPath(t,f,{gitleaks:fakeLeak(`
107
+ if(process.env.GITLEAKS_CONFIG||process.env.CM_TEST_PRIVATE_VALUE)process.exit(8);
108
+ if(!args.includes('--redact=100')||!args.includes('--ignore-gitleaks-allow'))process.exit(9);
109
+ fs.writeFileSync(args[args.indexOf('--report-path')+1],JSON.stringify([{File:'worktree/app.py',StartLine:1,RuleID:'fixture-rule',Secret:'PRIVATE_VALUE'}]));
110
+ console.error('PRIVATE_VALUE');process.exit(1);`)});
111
+ const r=scan(f.project);assert.equal(r.result,'FINDINGS');assert.equal(r.findings.length,1);
112
+ assert.equal(r.sourceUnchanged,true);assert.ok(!JSON.stringify(r).includes('PRIVATE_VALUE'));
113
+ });
114
+
115
+ for(const [name,body,reason] of [
116
+ ['malformed',`fs.writeFileSync(args[args.indexOf('--report-path')+1],'{bad');`,'invalid_or_incomplete_report'],
117
+ ['empty-nonzero',`fs.writeFileSync(args[args.indexOf('--report-path')+1],'[]');process.exit(1);`,'invalid_or_incomplete_report'],
118
+ ['error',`console.error('sensitive-error');process.exit(2);`,'execution_failed'],
119
+ ['timeout',`while(true){}`,'timeout'],
120
+ ])test(`scanner ${name} cannot become a clean result`,t=>{
121
+ const f=fixture(t);f.put('app.py','new');isolatedPath(t,f,{gitleaks:fakeLeak(body)});
122
+ const r=scan(f.project,{timeoutMs:name==='timeout'?100:5000});
123
+ assert.equal(r.tools[0].status,'ERROR');assert.equal(r.tools[0].reason,reason);
124
+ assert.equal(r.coverage,'PARTIAL');assert.ok(!JSON.stringify(r).includes('sensitive-error'));
125
+ });
126
+
127
+ test('source mutation by a faulty external scanner blocks the result',t=>{
128
+ const f=fixture(t);f.put('app.py','new');
129
+ isolatedPath(t,f,{gitleaks:fakeLeak(`fs.writeFileSync(${JSON.stringify(path.join(f.project,'app.py'))},'changed again');fs.writeFileSync(args[args.indexOf('--report-path')+1],'[]');`)});
130
+ const r=scan(f.project);assert.equal(r.result,'BLOCKED');assert.equal(r.sourceUnchanged,false);
131
+ });
132
+
133
+ test('optional scanners require explicit local inputs and OSV remains offline',t=>{
134
+ const f=fixture(t);f.put('package-lock.json','{}\n');f.git('add','.');
135
+ const rules=path.join(f.base,'rules.yaml');fs.writeFileSync(rules,'rules: []');const db=path.join(f.base,'db');fs.mkdirSync(db);
136
+ isolatedPath(t,f,{
137
+ semgrep:fakeLeak(`if(!args.includes('--metrics=off')||!args.includes('--disable-nosem'))process.exit(8);console.log(JSON.stringify({results:[],errors:[],paths:{scanned:[]}}));`),
138
+ 'osv-scanner':fakeLeak(`if(!args.includes('--offline')||!process.env.OSV_SCANNER_LOCAL_DB_CACHE_DIRECTORY)process.exit(8);console.log(JSON.stringify({results:[]}));`),
139
+ });
140
+ let r=scan(f.project);assert.equal(r.tools[1].reason,'local_rules_required');assert.equal(r.tools[2].reason,'offline_database_required');
141
+ r=scan(f.project,{semgrepRules:rules,osvDb:db});assert.equal(r.tools[1].reason,'unscanned_files');
142
+ assert.equal(r.tools[2].reason,'offline_database_freshness_and_ecosystem_coverage_unverified');
143
+ f.put('rules.yaml','rules: []');assert.throws(()=>scan(f.project,{semgrepRules:path.join(f.project,'rules.yaml')}),/external/);
144
+ });
145
+
146
+ test('installed Gitleaks smoke: synthetic key, negative control, source unchanged, no raw secret',t=>{
147
+ const probe=spawnSync('gitleaks',['version'],{encoding:'utf8'});
148
+ if(probe.error||probe.status!==0){t.skip('Gitleaks not installed; adapter fixtures still run');return;}
149
+ const f=fixture(t),secret='gh'+'p_'+crypto.createHash('sha256').update('cm-security-inert-example').digest('hex').slice(0,36);
150
+ f.put('fixture.txt',`value = "${secret}"\n`);f.put('safe.py','import os\nvalue = os.getenv("ACCESS_TOKEN")\n');f.git('add','.');
151
+ const r=scan(f.project);
152
+ assert.equal(r.tools[0].status,'FINDINGS');assert.ok(r.findings.some(v=>v.path==='fixture.txt'));
153
+ assert.ok(!r.findings.some(v=>v.path==='safe.py'));assert.ok(!JSON.stringify(r).includes(secret));assert.equal(r.sourceUnchanged,true);
154
+ });
155
+
156
+ test('CLI returns a machine-readable blocked result without echoing bad arguments',()=>{
157
+ const r=spawnSync(process.execPath,[path.join(root,'scripts/cm-security.mjs'),'--arbitrary-sensitive-value'],{encoding:'utf8'});
158
+ assert.equal(r.status,2);assert.equal(JSON.parse(r.stdout).result,'BLOCKED');assert.ok(!r.stdout.includes('sensitive-value'));
159
+ });
160
+
161
+ test('clean/process filters cannot execute and required filters are disabled',t=>{
162
+ const f=fixture(t),marker=path.join(f.base,'filter-called');
163
+ const driver=path.join(f.base,'driver');fs.writeFileSync(driver,`#!/bin/sh\ntouch '${marker}'\ncat\n`,{mode:0o700});
164
+ f.put('.gitattributes','app.py filter=probe\n');f.git('add','.');f.git('commit','-m','attributes');
165
+ f.put('app.py','modified raw content\n');
166
+ f.git('config','filter.probe.clean',driver);f.git('config','filter.probe.required','true');
167
+ assert.ok(inventory(f.project).selected.includes('app.py'));assert.ok(!fs.existsSync(marker));
168
+ f.git('config','filter.probe.process',driver);
169
+ assert.ok(inventory(f.project).selected.includes('app.py'));assert.ok(!fs.existsSync(marker));
170
+ });
171
+
172
+ test('Git lookup skips project binaries and child PATH excludes project directories',t=>{
173
+ const f=fixture(t),marker=path.join(f.base,'git-called');
174
+ f.put('bin/git',`#!/bin/sh\ntouch '${marker}'\nexec '${gitBin}' "$@"\n`);fs.chmodSync(path.join(f.project,'bin/git'),0o700);
175
+ const old=process.env.PATH;process.env.PATH=path.join(f.project,'bin')+path.delimiter+old;t.after(()=>{process.env.PATH=old;});
176
+ inventory(f.project);assert.ok(!fs.existsSync(marker));
177
+ fs.mkdirSync(path.join(f.project,'nested'));
178
+ assert.throws(()=>inventory(path.join(f.project,'nested')),/root_required/);
179
+ assert.ok(!fs.existsSync(marker));
180
+ });
181
+
182
+ test('untracked and ignored business maps are never read or hashed',t=>{
183
+ const f=fixture(t);f.put('docs/architecture.md','private map');
184
+ let r=inventory(f.project,{all:true});assert.equal(r.mapEvidence[0].sha256,null);
185
+ assert.equal(r.mapEvidence[0].status,'untracked_or_nonregular_excluded');
186
+ f.put('.gitignore','docs/architecture.md\n');r=inventory(f.project,{all:true});assert.equal(r.mapEvidence[0].sha256,null);
187
+ });
188
+
189
+ test('deleted tracked paths cannot pull same-name untracked private content into a scan',t=>{
190
+ const f=fixture(t);f.git('rm','--cached','app.py');f.put('app.py','NEW_UNTRACKED_PRIVATE');
191
+ let r=inventory(f.project);assert.equal(r.untracked,1);assert.ok(!r.files.some(v=>v.path==='app.py'));
192
+ assert.ok(r.gaps.some(v=>v.path==='app.py'&&v.reason==='deleted_review_baseline'));
193
+ f.git('commit','-m','remove');r=inventory(f.project);assert.ok(!r.files.some(v=>v.path==='app.py'));
194
+ assert.ok(!JSON.stringify(r).includes('NEW_UNTRACKED_PRIVATE'));
195
+ });
196
+
197
+ test('empty initial scope never overrides concurrent source drift with NO_CHANGES',t=>{
198
+ const f=fixture(t);isolatedPath(t,f);
199
+ const original=fs.mkdtempSync;
200
+ fs.mkdtempSync=(...args)=>{const result=original(...args);f.put('app.py','changed during scan');return result;};
201
+ try{const r=scan(f.project);assert.equal(r.sourceUnchanged,false);assert.equal(r.result,'BLOCKED');}
202
+ finally{fs.mkdtempSync=original;}
203
+ });
@@ -16,6 +16,7 @@ CORE_SKILLS = (
16
16
  "cm-prd",
17
17
  "cm-ai",
18
18
  "cm-test",
19
+ "cm-security",
19
20
  "cm-fix",
20
21
  "cm-refactor",
21
22
  "cm-check",
@@ -162,7 +163,7 @@ def main() -> int:
162
163
  pi_manifest = {}
163
164
  expected_pi_skills = [f"./skills/{name}" for name in sorted(CORE_SKILLS)]
164
165
  if pi_manifest.get("skills") != expected_pi_skills:
165
- fail("Pi package skills must expose exactly the eight core Skills", failures)
166
+ fail("Pi package skills must expose exactly the registered core Skills", failures)
166
167
  if pi_manifest.get("prompts") != ["./compat/claude-commands"]:
167
168
  fail("Pi package prompts must point to ./compat/claude-commands", failures)
168
169