@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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cm-workflow",
3
- "version": "0.11.0",
3
+ "version": "0.12.0",
4
4
  "description": "Spec-driven product development workflow for Codex: external research, PRD, implementation, read-only feature testing, review, QA, fixes, refactors, and documentation.",
5
5
  "author": {
6
6
  "name": "cm-workflow maintainers",
package/AGENTS.md CHANGED
@@ -73,3 +73,5 @@ Read the relevant files under `.claude/rules/` when modifying shell scripts, doc
73
73
  - **审查范围不能反向扩大执行权限**:为让 Learning 写回进入 review package,可以扩展 review baseline,但 developer request 必须继续使用原业务 scope;否则审查所需的可见性会意外变成修改项目指令的授权。来源:F05 runner Learning writeback;证据:`experiments/js-orchestration/task-runner.mjs`、`experiments/js-orchestration/task-runner.test.mjs` 的 review-scope/developer-scope 分离与 no-new 夹带拒绝用例。[已结构化]
74
74
  - **Handoff 定稿必须早于独立 Review**:`handoff_sha256` 绑定交接文件的精确字节;补写 Learning evidence 或 `changed_files` 后,先前生成的 Review 必须失效并在最终 handoff 上重做,不能复用旧批准。来源:F05 runner-owned Learning handoff;证据:`experiments/js-orchestration/cm-ai-conversation-entry.test.mjs` 的 handoff 后置 Review 组合用例。[已结构化]
75
75
  - **持久格式新增必填证据要保留在途恢复**:给 journal/checkpoint 增加新必填证据时,必须区分新记录与升级前合法历史,并用迁移回归证明旧状态仍能沿唯一完成路径走完;不能只让 replay 解析成功,却在后续门禁永久阻断。来源:F05 task-start Learning 应用记录;证据:`experiments/js-orchestration/task-runner.test.mjs` 的 pre-application checkpoint 恢复完成用例。[已结构化]
76
+
77
+ - **Git 只读命令仍可能执行目标配置**:对不执行目标代码的安全扫描,Git 程序本身也须限定为项目外可信路径,并关闭 fsmonitor 与全部 clean/process/required filter;不能仅靠 no-ext-diff/no-textconv。来源:cm-security 独立 Review;证据:`scripts/cm-security.test.mjs` 的过滤器及项目内 Git marker 夹具。[已结构化]
package/CHANGELOG.md CHANGED
@@ -1,11 +1,18 @@
1
1
  # 更新日志
2
2
 
3
3
  按版本记录用户可感知的新增、优化与修复;最新内容放在最前面。
4
- 尚未正式发布的改动放在「未发布」,本地插件升级不代表 npm 已发布。
4
+ 尚未进入发版候选的改动放在「未发布」;版本条目记录该版本的交付内容,npm 发布状态以注册表为准。
5
5
 
6
6
  ## 未发布
7
7
 
8
- 暂无新增条目。
8
+ 暂无。
9
+
10
+ ## 0.12.0 — 2026-09-16
11
+
12
+ - 新增 `cm-security`:默认扫描主分支差异与已跟踪未提交修改,支持 `--all`;结合业务地图复核安全问题,保留工具缺失与未覆盖范围;不自动修复、安装或上传。
13
+
14
+ - `cm-check` 默认查询 npm 稳定版,有新版就升级已管理的 CM 安装,再从升级后的目录检查;无需另加升级参数。
15
+ - 离线明确提示无法确认最新版;源码仓库和其他包管理器的安装保留原管理方式;底层机械检查保持只读,避免 CI 和安装流程递归升级。
9
16
 
10
17
  ## 0.11.0 — 2026-09-16
11
18
 
@@ -47,5 +54,5 @@
47
54
  ## 维护方式
48
55
 
49
56
  - 开发或修复完成后,将用户可感知的变化补到「未发布」,不逐条复制内部提交记录。
50
- - 正式发布时,将对应条目移到新版本标题下,并记录实际发布日期。
57
+ - 准备发版时,将对应条目移到目标版本标题下并标注计划日期;发布后核对实际日期,npm 状态以注册表为准。
51
58
  - 本文件先补录 0.10.6 及之后的变化;更早版本和实现细节查阅 Git 提交历史。
package/README.md CHANGED
@@ -15,6 +15,19 @@
15
15
 
16
16
  [快速开始](#快速开始codex) · [升级旧版本](#升级旧版本) · [选择命令](#选择命令) · [支持范围](#支持范围) · [使用手册](docs/user-guide.md) · [更新日志](CHANGELOG.md)
17
17
 
18
+ ## 最近更新
19
+
20
+ **0.12.0**
21
+
22
+ - **安全扫描**:新增 `cm-security`,结合业务地图检查代码改动,输出漏洞候选、业务影响和未检查范围。
23
+ - **自动升级**:`cm-check` 默认检查新版并升级受支持的已管理安装;离线或不支持自动升级时明确提示。
24
+
25
+ **0.11.0**
26
+
27
+ - **影响分析与单测**:`cm-test` 自动分析分支差异和单测覆盖率;明确要求“补齐单测”后,继续补测、重跑与审查。
28
+
29
+ [查看完整更新日志 →](CHANGELOG.md)
30
+
18
31
  ## 从需求到交付
19
32
 
20
33
  AI 写完代码以后,你还需要知道:需求是否对齐、测试是否真正执行、修改是否经过独立审查,以及中断后该从哪里继续。CM Workflow 把这些要求放进同一条开发流程。
@@ -70,7 +83,7 @@ $cm-check
70
83
 
71
84
  仓库直接分发 Skills 和脚本,无需在仓库根目录运行 `npm install` 或构建。完整安装行为、覆盖范围和卸载说明见[安装指南](docs/installation.md)。
72
85
 
73
- 需要固定版本时可使用 `npx @aibyzero/cm-workflow@0.11.0 install`,请在 CM Workflow 源码仓库以外的目录执行,例如用户主目录。npm 安装入口复用原安装器,要求与覆盖范围见[安装指南](docs/installation.md#npm-installation-macos-codex)。
86
+ 需要固定版本时可使用 `npx @aibyzero/cm-workflow@0.12.0 install`,请在 CM Workflow 源码仓库以外的目录执行,例如用户主目录。npm 安装入口复用原安装器,要求与覆盖范围见[安装指南](docs/installation.md#npm-installation-macos-codex)。
74
87
 
75
88
  ## 升级旧版本
76
89
 
@@ -102,7 +115,7 @@ git pull --ff-only origin main
102
115
 
103
116
  ## 选择命令
104
117
 
105
- 以下是八个核心入口。Codex 使用 `$cm-*`,Claude Code 使用 `/cm-*`。
118
+ 以下是九个核心入口。Codex 使用 `$cm-*`,Claude Code 使用 `/cm-*`。
106
119
 
107
120
  | 你想做什么 | Codex 入口 | 产出或下一步 |
108
121
  | --- | --- | --- |
@@ -110,6 +123,7 @@ git pull --ff-only origin main
110
123
  | 第一次接管已有仓库 | `$cm-init` | 建立项目上下文与规范 |
111
124
  | 把需求拆成可开发任务 | `$cm-prd {specs路径}` | 需求、设计、任务和审批材料 |
112
125
  | 执行已经确认的规格 | `$cm-ai {specs路径} {项目路径}` | 实现、审查、QA 与交付记录 |
126
+ | 安全扫描与业务复核 | `$cm-security`(全量用 `--all`) | 漏洞候选、业务影响与未检查范围 |
113
127
  | 测试已有功能 | `$cm-test {项目路径}` | 分层测试结果与证据 |
114
128
  | 修复可复现缺陷 | `$cm-fix {specs路径} {项目路径} {问题}` | 红灯测试、最小修复、回归验证 |
115
129
  | 整理结构并保持行为 | `$cm-refactor` | 按行为等价约束分批重构 |
package/VERSION CHANGED
@@ -1 +1 @@
1
- 0.11.0
1
+ 0.12.0
@@ -0,0 +1,3 @@
1
+ # /cm:security — Claude Code macOS/Linux 兼容入口
2
+
3
+ 读取 `~/.claude/skills/cm-security/SKILL.md`,将 `$ARGUMENTS` 原样作为用户输入,严格执行该 Skill。Skill 是唯一规则源;本文件不定义业务流程。如 Skill 不存在,提示重新安装 CM Workflow。
@@ -61,6 +61,18 @@ flowchart LR
61
61
 
62
62
  ## Runtime compatibility
63
63
 
64
+ Full `cm-check` first runs `scripts/cm-check-update.mjs`: query the fixed public
65
+ npm package, compare stable versions, download the exact version with lifecycle
66
+ scripts disabled into a temporary directory, and reuse the existing installer.
67
+ It recognizes the Codex personal managed installation/cache and the Claude managed
68
+ root, checks the installed version, then selects that root for mechanical and
69
+ semantic checks. Source checkouts and other package managers are not overwritten;
70
+ offline results retain an explicit freshness gap. Supported automatic writes are
71
+ macOS Codex and POSIX Claude; other platforms report the installation limitation.
72
+ The update lock serializes this preflight only; callers must finish other active
73
+ CM tasks before upgrading. The host and low-level checkers stay read-only, so
74
+ installer/CI checks cannot trigger a recursive update or drift their snapshot.
75
+
64
76
  Codex discovers the plugin through `.codex-plugin/plugin.json` and calls Skills
65
77
  directly. Claude Code invokes the same Skills as `/cm-*` on every platform.
66
78
  The macOS/Linux installer also maps the three-line compatibility wrappers to
@@ -192,3 +204,13 @@ Explicit test supplementation uses prepare/verify source snapshots and exact
192
204
  test paths; verification returns REVIEW_REQUIRED, with independent review still
193
205
  required. N3 and cm-fix reuse this check before their final handoff. No coverage
194
206
  tool installation, product repair, commit or release is implied.
207
+
208
+ ## Security scan entry
209
+
210
+ `skills/cm-security` delegates bounded snapshot scanning to `scripts/cm-security.mjs`
211
+ and `runtime/js/cm-security/scan.mjs`. It reuses cm-test main-ref selection without
212
+ fetching, includes tracked working/index changes, and keeps optional Gitleaks,
213
+ Semgrep local rules and OSV offline scanning behind an adapter. Source and project
214
+ scanner configuration are never executed. Symlinks/protected paths/limits are explicit
215
+ gaps. The current host reviews business boundaries and checks the source digest again;
216
+ scanner output is candidate evidence, never a task-completion or release gate.
@@ -45,7 +45,19 @@ Existing installs require confirmation. For an intentional unattended upgrade:
45
45
  ./install-codex.sh --yes
46
46
  ```
47
47
 
48
- Start a new Codex thread after installation, then run `$cm-check`. To derive a
48
+ Start a new Codex thread after installation, then run `$cm-check`. Full `cm-check`
49
+ queries npm's stable `latest` and automatically upgrades a supported managed
50
+ installation before checking the returned root. It reuses the existing installer
51
+ with `--yes`; no additional upgrade flag or confirmation is needed. Other Skills
52
+ load the new version in a new session. Finish other active CM tasks before updating.
53
+ Offline checks explicitly leave the latest version unknown. Source checkouts and
54
+ other package managers (including Pi/BYZ) retain their installation method; they
55
+ are not overwritten. Automatic installation supports macOS Codex's personal local
56
+ marketplace and macOS/Linux Claude. Other platforms report the limitation and use
57
+ their documented installer. A request to check without upgrading skips this step.
58
+ The low-level runtime checker and JS check host remain read-only for CI/install use.
59
+
60
+ To derive a
49
61
  test-case draft from an implemented feature, use
50
62
  `$cm-test {project} {feature} --generate-cases`; to verify it without modifying
51
63
  source, use `$cm-test`. The installed manual is available at
@@ -61,7 +73,7 @@ Install or upgrade with the same command:
61
73
  npx @aibyzero/cm-workflow@latest install
62
74
  ```
63
75
 
64
- To pin a version, use `npx @aibyzero/cm-workflow@0.11.0 install` from outside
76
+ To pin a version, use `npx @aibyzero/cm-workflow@0.12.0 install` from outside
65
77
  the CM Workflow source checkout (for example, your home directory). Inside a
66
78
  checkout with the same package name and version, npm can select the local
67
79
  uninstalled package and report `cm-workflow: command not found`.
@@ -31,6 +31,12 @@
31
31
 
32
32
  安装后必须新开会话,再运行 `$cm-check`。如果检查通过,就不需要每次任务都重复执行它。
33
33
 
34
+ `cm-check` 默认先查 npm 稳定版,有新版就升级已管理的插件,再检查升级后的目录,
35
+ 不需要另加参数或再次确认。升级后其他 Skills 需新开会话加载。离线时继续本地检查,
36
+ 但会明确提示“无法确认最新版”。源码仓库、Pi/BYZ 等其他管理器安装保留原方式,
37
+ 自动升级当前支持 macOS Codex 个人本地市场和 macOS/Linux Claude。
38
+ 有其他 CM 任务在运行时先结束或暂停;临时只想检查,可说“cm-check,只检查,不升级”。
39
+
34
40
  `cm-ai` 的新任务默认使用 JS Workflow,无需额外指定执行方式。它要求 Node.js 24.14+;
35
41
  macOS 已有本地验证,Linux 尚缺目标环境验证,原生 Windows 尚不支持。
36
42
  已有运行按原执行方式续接,升级不自动迁移旧任务;新任务只有明确选择旧兼容流程才走兼容入口。
@@ -56,7 +62,7 @@ JS 缺少运行条件时会报告缺口,不会静默切回旧流程。默认
56
62
  | 已确认是缺陷 | `$cm-fix …` | **是** | 查看红灯测试、修复和回归结果 |
57
63
  | 只想改善代码结构 | `$cm-refactor …` | **是**,但不得改变行为 | 查看等价性验证和审查结果 |
58
64
  | 想讨论方案、研究问题或查论文 | `$external-expert …` | 否 | 查看外部原始回答、本地裁决与待验证项 |
59
- | 安装或入口不正常 | `$cm-check` | 否,只检查 | 按检查结果修复安装或配置 |
65
+ | 安装或入口不正常 | `$cm-check` | 自动升级 CM 安装,不改业务代码 | 查看升级与自检结果 |
60
66
 
61
67
  ### 不想记命令,也可以直接描述目标
62
68
 
@@ -352,7 +358,7 @@ $cm-refactor ~/projects/my-app-specs ~/code/my-app 拆分过大的订单服务
352
358
 
353
359
  | 入口 | 主要输入 | 主要产出 | 关键边界 |
354
360
  | --- | --- | --- | --- |
355
- | `$cm-check` | 当前安装 | 机械与语义检查报告 | 只报告,不自动修复 |
361
+ | `$cm-check` | 当前安装 | 版本更新 + 机械与语义检查报告 | 默认升级已管理插件,不自动修业务或配置 |
356
362
  | `$cm-idea` | 一句话点子 | 可交付 PRD | 不自动进入 `$cm-prd` |
357
363
  | `$cm-init` | 当前代码项目 | `AGENTS.md`、兼容规则、代码库上下文 | 不实现业务功能 |
358
364
  | `$cm-prd` | specs 的 `docs/` | requirements、design、tasks、可选测试合同 | 在人工审查处停止 |
@@ -531,3 +537,18 @@ $external-expert 你的问题
531
537
  - [安装指南](installation.md):Codex、Claude Code 与 Windows 安装细节。
532
538
  - [架构说明](architecture.md):状态真相、审查通道与测试合同。
533
539
  - [README](../README.md):项目定位、能力全景与维护入口。
540
+
541
+ ## 主动安全检查
542
+
543
+ ```text
544
+ $cm-security
545
+ $cm-security --all
546
+ $cm-security {项目路径} --semgrep-rules {外部本地规则文件} --osv-db {外部缓存目录}
547
+ ```
548
+
549
+ 默认检查当前分支相对主分支的差异及已跟踪未提交修改;`--all` 检查全部已跟踪文件。
550
+ 先读业务地图,再运行现有本地工具并复核鉴权、注入、文件/命令/网络边界。
551
+ 扫描不自动安装工具、下载规则/数据库、修改代码或发布;工具缺失会继续可做的复核,
552
+ 结果明确标记部分覆盖。未跟踪文件、受保护路径、Git 历史不在默认扫描范围。
553
+ 报告给出位置、业务影响、证据、修复建议与未检查项。工具结果不等于安全保证;
554
+ 需要修复时再明确交给 cm-fix。详细参数见 `skills/cm-security/references/scan-contract.md`。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aibyzero/cm-workflow",
3
- "version": "0.11.0",
3
+ "version": "0.12.0",
4
4
  "description": "Spec-driven business development workflow for Pi, Codex, and Claude Code",
5
5
  "license": "MIT",
6
6
  "publishConfig": {
@@ -50,6 +50,7 @@
50
50
  "./skills/cm-init",
51
51
  "./skills/cm-prd",
52
52
  "./skills/cm-refactor",
53
+ "./skills/cm-security",
53
54
  "./skills/cm-test"
54
55
  ],
55
56
  "prompts": [
@@ -0,0 +1,263 @@
1
+ // Local scanner adapter: project content is data, never executable configuration.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import os from 'node:os';
5
+ import crypto from 'node:crypto';
6
+ import {spawnSync} from 'node:child_process';
7
+ import {inspectBranchComparison} from '../cm-test/branch-impact.mjs';
8
+
9
+ const need=(condition,code)=>{if(!condition)throw new Error(code);};
10
+ const hash=value=>crypto.createHash('sha256').update(value).digest('hex');
11
+ const decode=value=>new TextDecoder('utf-8',{fatal:true}).decode(value);
12
+ const inside=(root,file)=>file===root||file.startsWith(root+path.sep);
13
+ const safe=file=>typeof file==='string'&&file.length>0&&!/[\x00-\x1f\\]/.test(file)
14
+ &&!path.isAbsolute(file)&&file.split('/').every(p=>p&&p!=='.'&&p!=='..'&&p!=='.git');
15
+ const cleanPath=project=>(process.env.PATH??'').split(path.delimiter).filter(directory=>{
16
+ if(!directory||!path.isAbsolute(directory))return false;
17
+ try{return !inside(project,fs.realpathSync(directory));}catch{return false;}
18
+ }).join(path.delimiter);
19
+ const environment=(home,project)=>({PATH:cleanPath(project),HOME:home,USERPROFILE:home,
20
+ TMPDIR:home,TMP:home,TEMP:home,LANG:'C.UTF-8',LC_ALL:'C.UTF-8',
21
+ ...(process.env.SystemRoot?{SystemRoot:process.env.SystemRoot}:{}),
22
+ GIT_NO_REPLACE_OBJECTS:'1',GIT_NO_LAZY_FETCH:'1',GIT_TERMINAL_PROMPT:'0',
23
+ GIT_CONFIG_NOSYSTEM:'1',GIT_CONFIG_GLOBAL:os.devNull});
24
+ const git=(project,args,optional=false)=>{
25
+ // Git status/diff can run clean/process filters. Suppress every configured driver,
26
+ // including required=true, in addition to fsmonitor, external diff and textconv.
27
+ let boundary=project;
28
+ for(let current=project;;current=path.dirname(current)){
29
+ if(fs.existsSync(path.join(current,'.git'))){boundary=current;break;}
30
+ if(path.dirname(current)===current)break;
31
+ }
32
+ const bin=executable('git',boundary);need(bin,'external_git_required');
33
+ const env=environment(os.tmpdir(),boundary);
34
+ const common=['--no-optional-locks','-c','core.fsmonitor=false','-C',project];
35
+ const config=spawnSync(bin,[...common,'config','--name-only','--get-regexp','^filter\\..*\\.(clean|process|required)$'],
36
+ {env,timeout:10000,maxBuffer:1024*1024});
37
+ need(!config.error&&[0,1].includes(config.status),'git_config_read_failed');
38
+ const disabled=[];
39
+ for(const key of decode(config.stdout).split('\n').filter(Boolean)){
40
+ need(/^filter\.[^\x00-\x1f]+\.(clean|process|required)$/.test(key),'unsafe_filter_config');
41
+ disabled.push('-c',`${key}=${key.endsWith('.required')?'false':''}`);
42
+ }
43
+ const result=spawnSync(bin,[...common,...disabled,...args],{env,timeout:10000,maxBuffer:16*1024*1024});
44
+ if(optional&&!result.error&&result.status!==0)return null;
45
+ need(!result.error&&result.status===0,'git_read_failed');return result.stdout;
46
+ };
47
+ const paths=bytes=>decode(bytes).split('\0').filter(Boolean);
48
+ const protectedPath=file=>/(^|\/)(?:\.env(?:\..*)?|credentials[^/]*|id_rsa|id_ed25519)(\/|$)|\.(?:pem|key|p12|pfx)$/i.test(file);
49
+ const controlPath=file=>/(^|\/)(?:\.gitignore|\.gitleaks[^/]*|\.semgrep[^/]*|osv-scanner\.toml|\.gitmodules)$/.test(file);
50
+ const maps=['docs/architecture.md','docs/codebase-context/00-index.md','docs/codebase-context/07-business-logic.md'];
51
+ const locks=/(^|\/)(?:package-lock\.json|npm-shrinkwrap\.json|pnpm-lock\.yaml|yarn\.lock|poetry\.lock|Pipfile\.lock|requirements[^/]*\.txt|Cargo\.lock|go\.sum|Gemfile\.lock|composer\.lock|packages\.lock\.json)$/;
52
+
53
+ // Refuse symlink ancestors, even when their target happens to remain inside the project.
54
+ function workingFile(project,file){
55
+ let current=project;
56
+ for(const part of file.split('/')){
57
+ current=path.join(current,part);
58
+ let stat;try{stat=fs.lstatSync(current);}catch(error){if(error.code==='ENOENT')return {kind:'deleted'};throw error;}
59
+ if(stat.isSymbolicLink())return {kind:'symlink'};
60
+ }
61
+ const stat=fs.lstatSync(current);
62
+ if(!stat.isFile())return {kind:'non_regular'};
63
+ if(stat.size>1024*1024)return {kind:'oversize'};
64
+ const fd=fs.openSync(current,fs.constants.O_RDONLY|(fs.constants.O_NOFOLLOW??0));
65
+ try{
66
+ need(inside(project,fs.realpathSync(current)),'source_path_changed');
67
+ const bytes=fs.readFileSync(fd);need(bytes.length<=1024*1024,'source_size_changed');
68
+ return {kind:'file',bytes};
69
+ }finally{fs.closeSync(fd);}
70
+ }
71
+
72
+ export function inventory(project,{all=false}={}){
73
+ project=fs.realpathSync(project);
74
+ need(fs.realpathSync(decode(git(project,['rev-parse','--show-toplevel'])).trim())===project,'project_root_required');
75
+ const comparison=all?{head:decode(git(project,['rev-parse','HEAD'])).trim(),mode:'all'}:inspectBranchComparison(project,git);
76
+ const index=new Map();
77
+ for(const entry of paths(git(project,['ls-files','--stage','-z']))){
78
+ const m=entry.match(/^(\d{6}) ([a-f0-9]+) ([0-3])\t([\s\S]+)$/);
79
+ need(m&&safe(m[4]),'unsupported_git_path');need(m[3]==='0','unmerged_index');
80
+ index.set(m[4],{mode:m[1],oid:m[2]});
81
+ }
82
+ const selected=all?[...index.keys()]:[...new Set([
83
+ ...paths(git(project,['diff','--name-only','-z','--no-renames','--no-ext-diff','--no-textconv',comparison.base,comparison.head,'--'])),
84
+ ...paths(git(project,['diff','--name-only','-z','--no-renames','--no-ext-diff','--no-textconv','HEAD','--'])),
85
+ ...paths(git(project,['diff','--cached','--name-only','-z','--no-renames','--no-ext-diff','--no-textconv','HEAD','--']))])];
86
+ need(selected.length<=2000,'scope_limit_2000');need(selected.every(safe),'unsupported_git_path');
87
+ const files=[],gaps=[],state=[];let budget=50*1024*1024;
88
+ for(const file of selected.sort()){
89
+ const entry=index.get(file);
90
+ state.push({file,index:entry??null});
91
+ if(protectedPath(file)){gaps.push({path:file,reason:'protected_path_not_read'});continue;}
92
+ const work=entry?workingFile(project,file):{kind:'deleted'};
93
+ state.push({file,kind:work.kind,hash:work.bytes?hash(work.bytes):null});
94
+ if(controlPath(file)){gaps.push({path:file,reason:'scanner_control_excluded_review_manually'});continue;}
95
+ if(work.kind==='file'){
96
+ budget-=work.bytes.length;need(budget>=0,'scope_limit_50mb');
97
+ files.push({path:file,revision:'worktree',bytes:work.bytes,sha256:hash(work.bytes)});
98
+ }else gaps.push({path:file,reason:work.kind==='deleted'?'deleted_review_baseline':work.kind});
99
+ if(entry&&!['100644','100755'].includes(entry.mode)){
100
+ gaps.push({path:file,reason:'index_non_regular'});continue;
101
+ }
102
+ if(entry){
103
+ // Compare raw Git blob bytes, without invoking repository conversion filters.
104
+ const oid=work.bytes?crypto.createHash(entry.oid.length===40?'sha1':'sha256')
105
+ .update(`blob ${work.bytes.length}\0`).update(work.bytes).digest('hex'):null;
106
+ if(oid===entry.oid)continue;
107
+ const size=Number(decode(git(project,['cat-file','-s',entry.oid])).trim());
108
+ if(size>1024*1024){gaps.push({path:file,reason:'index_oversize'});continue;}
109
+ const bytes=git(project,['cat-file','blob',entry.oid]);
110
+ if(!work.bytes||!bytes.equals(work.bytes)){
111
+ budget-=bytes.length;need(budget>=0,'scope_limit_50mb');
112
+ files.push({path:file,revision:'index',bytes,sha256:hash(bytes)});
113
+ }
114
+ }
115
+ }
116
+ const untracked=paths(git(project,['ls-files','--others','--exclude-standard','-z'])).length;
117
+ const mapEvidence=maps.map(file=>{
118
+ const tracked=index.get(file);
119
+ if(!tracked||!['100644','100755'].includes(tracked.mode))return {path:file,status:'untracked_or_nonregular_excluded',sha256:null};
120
+ const work=workingFile(project,file);
121
+ return {path:file,status:work.kind,sha256:work.bytes?hash(work.bytes):null};
122
+ });
123
+ const identity={comparison:{...comparison,dirty:false},state,mapEvidence};
124
+ return {project,comparison,selected,files,gaps,untracked,mapEvidence,digest:hash(JSON.stringify(identity))};
125
+ }
126
+
127
+ function executable(name,project){
128
+ for(const directory of (process.env.PATH??'').split(path.delimiter)){
129
+ if(!directory||!path.isAbsolute(directory))continue;
130
+ for(const suffix of process.platform==='win32'?['.exe','']:['']){
131
+ try{
132
+ const file=fs.realpathSync(path.join(directory,name+suffix));
133
+ if(inside(project,file)||!fs.statSync(file).isFile())continue;
134
+ fs.accessSync(file,fs.constants.X_OK);return file;
135
+ }catch{}
136
+ }
137
+ }
138
+ return null;
139
+ }
140
+
141
+ function checkedConfig(file,project){
142
+ const real=fs.realpathSync(file);
143
+ need(!inside(project,real)&&fs.statSync(real).isFile(),'rules_must_be_external_regular_file');
144
+ need(fs.statSync(real).size<=1024*1024,'rules_size_limit');return fs.readFileSync(real);
145
+ }
146
+
147
+ // Never retain scanner snippets, messages, secrets, stdout/stderr, or arbitrary result paths.
148
+ export function normalize(tool,data,files,root){
149
+ const findings=[];
150
+ const locate=(value,line=1)=>{
151
+ need(typeof value==='string','invalid_result_path');
152
+ const absolute=path.resolve(root,value);
153
+ const relative=path.relative(root,absolute).split(path.sep).join('/');
154
+ const match=files.find(f=>`${f.revision}/${f.path}`===relative);
155
+ need(match&&Number.isInteger(line)&&line>0&&line<=match.bytes.toString('utf8').split('\n').length,'invalid_result_location');
156
+ return {path:match.path,revision:match.revision,line};
157
+ };
158
+ const add=(location,rule,severity)=>{
159
+ need(typeof rule==='string'&&/^[a-zA-Z0-9_.:/-]{1,200}$/.test(rule),'invalid_rule_id');
160
+ findings.push({...location,tool,rule,severity,verification:'candidate'});
161
+ };
162
+ if(tool==='gitleaks'){
163
+ need(Array.isArray(data),'invalid_gitleaks_json');
164
+ for(const row of data)add(locate(row.File,row.StartLine),row.RuleID,'high');
165
+ }else if(tool==='semgrep'){
166
+ need(Array.isArray(data.results)&&Array.isArray(data.errors)&&data.paths&&Array.isArray(data.paths.scanned),'invalid_semgrep_json');
167
+ need(data.errors.length===0,'semgrep_scan_errors');
168
+ for(const row of data.results)add(locate(row.path,row.start?.line),row.check_id,
169
+ ({ERROR:'high',WARNING:'medium',INFO:'low'})[row.extra?.severity]??'unknown');
170
+ // All copied files must be accounted for; language/rule exclusions remain visible.
171
+ const scanned=new Set(data.paths.scanned.map(f=>path.resolve(root,f)));
172
+ return {findings,unscanned:files.filter(f=>!scanned.has(path.join(root,f.revision,f.path))).map(f=>({path:f.path,revision:f.revision}))};
173
+ }else{
174
+ need(Array.isArray(data.results),'invalid_osv_json');
175
+ for(const result of data.results){
176
+ need(Array.isArray(result.packages),'invalid_osv_packages');
177
+ const location=locate(result.source?.path);
178
+ for(const pkg of result.packages){
179
+ need(Array.isArray(pkg.vulnerabilities),'invalid_osv_vulnerabilities');
180
+ for(const item of pkg.vulnerabilities)add(location,item.id,'unknown');
181
+ }
182
+ }
183
+ }
184
+ return {findings,unscanned:[]};
185
+ }
186
+
187
+ function runTool(bin,args,options){
188
+ const result=spawnSync(bin,args,{...options,detached:process.platform!=='win32',killSignal:'SIGKILL'});
189
+ // On POSIX, also stop helper processes when a scanner times out or exits early.
190
+ if(process.platform!=='win32'&&result.pid){try{process.kill(-result.pid,'SIGKILL');}catch{}}
191
+ return result;
192
+ }
193
+
194
+ export function scan(project,options={}){
195
+ const before=inventory(project,options);
196
+ const report={schemaVersion:1,scope:options.all?'all-tracked':'branch-and-tracked-dirty',
197
+ comparison:before.comparison,digest:before.digest,selected:before.selected,
198
+ files:before.files.map(({bytes,...file})=>file),gaps:[...before.gaps],
199
+ untrackedExcluded:before.untracked,businessMaps:before.mapEvidence,
200
+ tools:[],findings:[],aiReview:'pending',coverage:'PARTIAL',result:'NO_FINDINGS',sourceUnchanged:null};
201
+ if(options.inventoryOnly)return report;
202
+ const temp=fs.mkdtempSync(path.join(os.tmpdir(),'cm-security-'));
203
+ const root=path.join(temp,'source'),home=path.join(temp,'home');
204
+ fs.mkdirSync(root);fs.mkdirSync(home);
205
+ try{
206
+ for(const file of before.files){
207
+ const target=path.join(root,file.revision,file.path);
208
+ fs.mkdirSync(path.dirname(target),{recursive:true});fs.writeFileSync(target,file.bytes,{mode:0o600});
209
+ }
210
+ for(const name of ['gitleaks','semgrep','osv-scanner']){
211
+ const tool=name==='osv-scanner'?'osv':name;
212
+ const row={tool,status:'NOT_RUN',reason:null};report.tools.push(row);
213
+ if(!before.files.length){row.reason='no_scannable_files';continue;}
214
+ const bin=executable(name,before.project);
215
+ if(!bin){row.reason='tool_missing';continue;}
216
+ const env={...environment(home,before.project),SEMGREP_SEND_METRICS:'off',SEMGREP_ENABLE_VERSION_CHECK:'0'};
217
+ let args;
218
+ if(tool==='gitleaks')args=['dir',root,'--redact=100','--no-banner','--no-color','--ignore-gitleaks-allow',
219
+ '--report-format','json','--report-path',path.join(temp,'gitleaks.json')];
220
+ if(tool==='semgrep'){
221
+ if(!options.semgrepRules){row.reason='local_rules_required';continue;}
222
+ const config=path.join(temp,'rules.yaml');
223
+ const rules=checkedConfig(options.semgrepRules,before.project);row.rulesSha256=hash(rules);
224
+ fs.writeFileSync(config,rules,{mode:0o600});
225
+ args=['scan','--config',config,'--metrics=off','--disable-version-check','--no-git-ignore','--disable-nosem',
226
+ '--json','--quiet','--no-rewrite-rule-ids','--timeout','10','--max-target-bytes','1048576',root];
227
+ }
228
+ if(tool==='osv'){
229
+ if(!before.files.some(f=>locks.test(f.path))){row.reason='no_supported_lockfile_selected';continue;}
230
+ if(!options.osvDb){row.reason='offline_database_required';continue;}
231
+ const db=fs.realpathSync(options.osvDb);need(!inside(before.project,db)&&fs.statSync(db).isDirectory(),'external_database_required');
232
+ env.OSV_SCANNER_LOCAL_DB_CACHE_DIRECTORY=db;
233
+ args=['scan','source','--offline','--format','json','--recursive',root];
234
+ }
235
+ const version=runTool(bin,tool==='gitleaks'?['version']:['--version'],{cwd:home,env,timeout:10000,maxBuffer:64*1024});
236
+ row.version=version.stdout?.toString().match(/\b\d+\.\d+\.\d+\b/)?.[0]??'unknown';
237
+ const result=runTool(bin,args,{cwd:home,env,timeout:options.timeoutMs??60000,maxBuffer:8*1024*1024,killSignal:'SIGKILL'});
238
+ row.exitCode=result.status;
239
+ if(result.error||![0,1].includes(result.status)){
240
+ row.status='ERROR';row.reason=result.error?.code==='ETIMEDOUT'?'timeout':'execution_failed';continue;
241
+ }
242
+ try{
243
+ const bytes=tool==='gitleaks'?fs.readFileSync(path.join(temp,'gitleaks.json')):result.stdout;
244
+ need(bytes.length<=8*1024*1024,'report_size_limit');
245
+ const parsed=normalize(tool,JSON.parse(bytes.toString('utf8')),before.files,root);
246
+ need(result.status!==1||parsed.findings.length>0,'nonzero_without_findings');
247
+ row.status=parsed.findings.length?'FINDINGS':'NO_FINDINGS';
248
+ row.unscanned=parsed.unscanned;report.findings.push(...parsed.findings);
249
+ if(parsed.unscanned.length)row.reason='unscanned_files';
250
+ if(tool==='osv')row.reason='offline_database_freshness_and_ecosystem_coverage_unverified';
251
+ }catch{
252
+ row.status='ERROR';row.reason='invalid_or_incomplete_report';
253
+ }
254
+ }
255
+ const after=inventory(before.project,options);
256
+ report.sourceUnchanged=after.digest===before.digest;
257
+ if(!report.sourceUnchanged)report.gaps.push({reason:'source_changed'});
258
+ report.result=report.findings.length?'FINDINGS':'NO_FINDINGS';
259
+ if(!report.sourceUnchanged)report.result='BLOCKED';
260
+ if(report.sourceUnchanged&&!before.selected.length)report.result='NO_CHANGES';
261
+ return report;
262
+ }finally{fs.rmSync(temp,{recursive:true,force:true});}
263
+ }
@@ -5,7 +5,7 @@ import {need,json,shape,digest} from '../cm-ai/effect-contract.mjs';
5
5
 
6
6
  const decode=bytes=>new TextDecoder('utf-8',{fatal:true}).decode(bytes);
7
7
  const git=(project,args,optional=false)=>{
8
- const result=spawnSync('git',['--no-optional-locks','-C',project,...args],{
8
+ const result=spawnSync('git',['--no-optional-locks','-c','core.fsmonitor=false','-C',project,...args],{
9
9
  env:{...process.env,GIT_NO_REPLACE_OBJECTS:'1',GIT_NO_LAZY_FETCH:'1'},timeout:10000,maxBuffer:8*1024*1024});
10
10
  if(optional&&!result.error&&result.status!==0)return null;
11
11
  need(!result.error&&result.status===0,'cm_test_git_unavailable');return result.stdout;
@@ -18,7 +18,13 @@ const text=value=>typeof value==='string'&&value.trim().length>0;
18
18
  const safePath=value=>text(value)&&!value.includes('\0')&&!value.includes('\\')
19
19
  &&value.split('/').every(part=>part&&part!=='.'&&part!=='..');
20
20
 
21
- export function inspectBranchComparison(project){
21
+ export function inspectBranchComparison(project,readGit=git){
22
+ // Security consumers may inject a reader with a stricter executable/config boundary.
23
+ const git=readGit;
24
+ const line=(root,args,optional=false)=>{
25
+ const bytes=git(root,args,optional);return bytes===null?null:decode(bytes).trim();
26
+ };
27
+ const commit=(root,ref)=>line(root,['rev-parse','--verify',`${ref}^{commit}`],true);
22
28
  const top=line(project,['rev-parse','--show-toplevel'],true);
23
29
  need(top!==null,'cm_test_git_required');
24
30
  need(fs.realpathSync(top)===project,'cm_test_project_root_required');
@@ -275,6 +275,11 @@ for module in \
275
275
  require_file "runtime/js/cm-ai/$module"
276
276
  done
277
277
  require_file "scripts/cm-check-runtime.ps1"
278
+ require_file "scripts/cm-security.mjs"
279
+ require_file "scripts/cm-security.test.mjs"
280
+ require_file "runtime/js/cm-security/scan.mjs"
281
+ require_file "scripts/cm-check-update.mjs"
282
+ require_file "scripts/cm-check-update.test.mjs"
278
283
  require_file "scripts/cm-release-smoke.sh"
279
284
  require_file "scripts/cm-ai-admission.mjs"
280
285
  require_file "scripts/cm-ai-run.mjs"
@@ -575,7 +580,7 @@ for consumer in \
575
580
  fail "external-expert AUTO routing is not wired into $consumer"
576
581
  done
577
582
 
578
- for name in cm-idea cm-init cm-prd cm-ai cm-test cm-fix cm-refactor cm-check; do
583
+ for name in cm-idea cm-init cm-prd cm-ai cm-test cm-security cm-fix cm-refactor cm-check; do
579
584
  require_file "skills/$name/SKILL.md"
580
585
  require_file "compat/claude-commands/$name.md"
581
586
  wrapper="$ROOT/compat/claude-commands/$name.md"