@aibyzero/cm-workflow 0.10.6 → 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.
Files changed (53) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +2 -0
  3. package/CHANGELOG.md +58 -0
  4. package/README.md +17 -3
  5. package/VERSION +1 -1
  6. package/compat/claude-commands/cm-security.md +3 -0
  7. package/docs/architecture.md +62 -1
  8. package/docs/installation.md +14 -2
  9. package/docs/user-guide.md +31 -3
  10. package/install-codex.sh +1 -1
  11. package/package.json +3 -1
  12. package/runtime/js/cm-ai/host-tool-bridge.mjs +1 -1
  13. package/runtime/js/cm-ai/review-result.schema.json +0 -1
  14. package/runtime/js/cm-fix/execution.mjs +2 -2
  15. package/runtime/js/cm-fix/repair.mjs +6 -2
  16. package/runtime/js/cm-security/scan.mjs +263 -0
  17. package/runtime/js/cm-test/branch-impact.mjs +151 -0
  18. package/runtime/js/cm-test/host.mjs +28 -8
  19. package/runtime/js/cm-test/unit-coverage.mjs +206 -0
  20. package/runtime/project-context.md +6 -0
  21. package/scripts/cm-check-runtime.sh +23 -1
  22. package/scripts/cm-check-update.mjs +200 -0
  23. package/scripts/cm-check-update.test.mjs +186 -0
  24. package/scripts/cm-fix-repair-owner.test.mjs +24 -6
  25. package/scripts/cm-fix-repair.test.mjs +9 -2
  26. package/scripts/cm-fix-review-baseline.test.mjs +19 -1
  27. package/scripts/cm-release-smoke.sh +3 -0
  28. package/scripts/cm-review-schema.test.mjs +15 -0
  29. package/scripts/cm-security.mjs +32 -0
  30. package/scripts/cm-security.test.mjs +203 -0
  31. package/scripts/cm-test-branch-impact.test.mjs +186 -0
  32. package/scripts/cm-test-entry.mjs +6 -1
  33. package/scripts/cm-test-host.mjs +2 -2
  34. package/scripts/cm-unit-coverage.mjs +16 -0
  35. package/scripts/cm-unit-coverage.test.mjs +126 -0
  36. package/scripts/validate-public-repo.py +2 -1
  37. package/skills/cm-ai/references/N3-execute-task.md +12 -1
  38. package/skills/cm-ai/references/N8-finish.md +5 -4
  39. package/skills/cm-check/SKILL.md +44 -7
  40. package/skills/cm-check/references/js-host.md +4 -1
  41. package/skills/cm-doc-syncer/SKILL.md +22 -3
  42. package/skills/cm-fix/SKILL.md +11 -2
  43. package/skills/cm-fix/references/js-host.md +4 -0
  44. package/skills/cm-prd/SKILL.md +3 -3
  45. package/skills/cm-prd/references/context-scope.md +17 -13
  46. package/skills/cm-security/SKILL.md +55 -0
  47. package/skills/cm-security/references/scan-contract.md +43 -0
  48. package/skills/cm-test/SKILL.md +24 -7
  49. package/skills/cm-test/references/branch-impact.md +70 -0
  50. package/skills/cm-test/references/js-host.md +14 -2
  51. package/skills/cm-test/references/unit-coverage.md +97 -0
  52. package/skills/codebase-context/SKILL.md +11 -24
  53. package/skills/codebase-context/references/writeback.md +66 -0
@@ -0,0 +1,206 @@
1
+ // Fresh project-runner evidence, intersected with the selected Git diff.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import {spawnSync} from 'node:child_process';
5
+ import {randomUUID} from 'node:crypto';
6
+ import {need,json,digest} from '../cm-ai/effect-contract.mjs';
7
+ import {createHostCheck} from '../cm-ai/host-check.mjs';
8
+ import {inspectDeclaredTestCommand} from './declared-command.mjs';
9
+ import {inspectBranchComparison} from './branch-impact.mjs';
10
+ import {inside,canonicalFuture,snapshotSource,sourceChanges,readSourceFiles} from './source-snapshot.mjs';
11
+
12
+ const relative=value=>typeof value==='string'&&value.length>0&&!value.includes('\\')&&!value.includes('\0')
13
+ &&value.split('/').every(part=>part&&part!=='.'&&part!=='..');
14
+ const git=(project,args)=>{
15
+ const r=spawnSync('git',['--no-optional-locks','-C',project,...args],{encoding:'utf8',timeout:10000,maxBuffer:8*1024*1024,
16
+ env:{...process.env,GIT_NO_REPLACE_OBJECTS:'1',GIT_NO_LAZY_FETCH:'1'}});
17
+ need(!r.error&&r.status===0,'coverage_git_failed');return r.stdout;
18
+ };
19
+ const count=value=>{need(Number.isSafeInteger(value)&&value>=0,'coverage_count_invalid');return value;};
20
+ const number=value=>{need(/^\d+$/.test(value),'coverage_count_invalid');return count(Number(value));};
21
+ const line=value=>{need(Number.isSafeInteger(value)&&value>0,'coverage_line_invalid');return value;};
22
+ const metric=(total,covered)=>({total,covered,percent:total?Math.round(covered/total*10000)/100:null});
23
+
24
+ export function parseUnitCoverage(text,format,project){
25
+ const files=new Map();
26
+ function get(name){
27
+ need(typeof name==='string'&&!name.includes('\0'),'coverage_path_invalid');
28
+ const full=path.resolve(project,name);
29
+ if(!inside(project,full))return null;
30
+ const key=path.relative(project,full).split(path.sep).join('/');
31
+ need(relative(key),'coverage_path_invalid');
32
+ if(!files.has(key))files.set(key,{lines:new Map(),branches:new Map(),branchData:true});return files.get(key);
33
+ }
34
+ const add=(map,key,hits)=>map.set(key,(map.get(key)??0)+count(hits));
35
+ if(format==='lcov'){
36
+ let current=null,record=false,declaredBranches=null,recordBranches=new Set();
37
+ for(const row of text.split(/\r?\n/)){
38
+ if(row.startsWith('SF:')){
39
+ need(!record,'coverage_record_invalid');current=get(row.slice(3));record=true;declaredBranches=null;recordBranches=new Set();
40
+ }else if(row==='end_of_record'){
41
+ need(record,'coverage_record_invalid');
42
+ if(current)current.branchData&&=declaredBranches===null?recordBranches.size>0:declaredBranches===recordBranches.size;
43
+ record=false;current=null;
44
+ }
45
+ else if(row.startsWith('DA:')){
46
+ need(record,'coverage_record_invalid');const parts=row.slice(3).split(',');need(parts.length>=2,'coverage_record_invalid');
47
+ const n=line(number(parts[0])),hits=number(parts[1]);if(current)add(current.lines,n,hits);
48
+ }else if(row.startsWith('BRDA:')){
49
+ need(record,'coverage_record_invalid');const [n,block,branch,hits,...extra]=row.slice(5).split(',');
50
+ need(extra.length===0&&block&&branch&&hits!==undefined,'coverage_record_invalid');
51
+ const start=line(number(n)),value=hits==='-'?0:number(hits);
52
+ const key=`${start}:${block}:${branch}`;recordBranches.add(key);if(current)add(current.branches,key,value);
53
+ }else if(row.startsWith('BRF:')){
54
+ need(record&&declaredBranches===null,'coverage_record_invalid');declaredBranches=number(row.slice(4));
55
+ }
56
+ }
57
+ need(!record,'coverage_record_invalid');
58
+ }else if(format==='istanbul'){
59
+ const report=JSON.parse(text);need(report&&typeof report==='object'&&!Array.isArray(report),'coverage_report_invalid');
60
+ for(const [name,item] of Object.entries(report)){
61
+ need(item&&item.statementMap&&item.s&&item.branchMap&&item.b,'coverage_report_invalid');
62
+ const file=get(item.path??name);if(!file)continue;
63
+ for(const [id,statement] of Object.entries(item.statementMap)){
64
+ const n=line(statement.start?.line),hits=count(item.s[id]);
65
+ // Istanbul's line coverage uses the maximum statement hit on that line.
66
+ file.lines.set(n,Math.max(file.lines.get(n)??0,hits));
67
+ }
68
+ for(const [id,branch] of Object.entries(item.branchMap)){
69
+ need(Array.isArray(item.b[id])&&Array.isArray(branch.locations)&&item.b[id].length===branch.locations.length,'coverage_report_invalid');
70
+ item.b[id].forEach((hits,index)=>add(file.branches,`${line(branch.line??branch.loc?.start?.line)}:${id}:${index}`,hits));
71
+ }
72
+ }
73
+ }else need(false,'coverage_format_unsupported');
74
+ need(files.size>0,'coverage_report_empty');return files;
75
+ }
76
+
77
+ export function changedUnitLines(project,{base,head,target='head',scope=[]}){
78
+ need(['head','working-tree'].includes(target)&&Array.isArray(scope)&&scope.every(relative),'coverage_target_invalid');
79
+ const revisions=target==='head'?[base,head]:[base];
80
+ let names=git(project,['diff','--name-only','-z','--diff-filter=ACMRT','--no-renames','--ignore-submodules=none',...revisions,'--']).split('\0').filter(Boolean);
81
+ if(target==='working-tree'){
82
+ need(scope.length>0,'coverage_worktree_scope_required');
83
+ const untracked=new Set(git(project,['ls-files','--others','--exclude-standard','-z']).split('\0').filter(Boolean));
84
+ names=[...new Set([...names.filter(file=>scope.includes(file)),...scope.filter(file=>untracked.has(file))])];
85
+ }
86
+ need(names.length<=2000&&names.every(relative),'coverage_diff_invalid');
87
+ return names.map(file=>{
88
+ const patch=git(project,['diff','--unified=0','--no-ext-diff','--no-textconv','--no-renames','--ignore-submodules=none',...revisions,'--',`:(literal)${file}`]);
89
+ const lines=new Set();
90
+ for(const match of patch.matchAll(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/gm)){
91
+ const start=Number(match[1]),size=Number(match[2]??1);need(size<=100000,'coverage_diff_limit');
92
+ for(let n=start;n<start+size;n++)lines.add(n);
93
+ }
94
+ if(target==='working-tree'&&!patch){
95
+ const full=path.join(project,file);need(fs.realpathSync(full)===full&&fs.lstatSync(full).isFile(),'coverage_source_invalid');
96
+ const bytes=fs.readFileSync(full);need(bytes.length<=1024*1024&&!bytes.includes(0),'coverage_source_invalid');
97
+ bytes.toString('utf8').split('\n').forEach((_,i)=>lines.add(i+1));
98
+ }
99
+ return {path:file,lines:[...lines].sort((a,b)=>a-b)};
100
+ });
101
+ }
102
+
103
+ export function summarizeUnitCoverage(changes,files,exclusions=[]){
104
+ need(Array.isArray(exclusions)&&exclusions.every(item=>relative(item.path)&&typeof item.reason==='string'&&item.reason.trim()),'coverage_exclusions_invalid');
105
+ const rows=[];let total=0,covered=0,branches=0,coveredBranches=0;
106
+ for(const change of changes){
107
+ const exclusion=exclusions.find(item=>item.path===change.path);
108
+ if(exclusion){rows.push({path:change.path,status:'excluded',reason:exclusion.reason});continue;}
109
+ const measured=files.get(change.path);
110
+ if(!measured){rows.push({path:change.path,status:'missing',changedLines:change.lines});continue;}
111
+ const selected=change.lines.filter(n=>measured.lines.has(n));
112
+ const missing=selected.filter(n=>measured.lines.get(n)===0),unmapped=change.lines.filter(n=>!measured.lines.has(n));
113
+ const branchRows=[...measured.branches].filter(([key])=>change.lines.includes(Number(key.split(':')[0])));
114
+ const uncoveredBranches=branchRows.filter(([,hits])=>hits===0).map(([key])=>key);
115
+ total+=selected.length;covered+=selected.length-missing.length;branches+=branchRows.length;coveredBranches+=branchRows.length-uncoveredBranches.length;
116
+ rows.push({path:change.path,status:unmapped.length||!measured.branchData?'partial':'measured',uncoveredLines:missing,unmappedLines:unmapped,
117
+ branchStatus:!measured.branchData?'missing':branchRows.length?'measured':'not_applicable',
118
+ lines:metric(selected.length,selected.length-missing.length),branches:metric(branchRows.length,branchRows.length-uncoveredBranches.length),uncoveredBranches});
119
+ }
120
+ const incomplete=rows.some(row=>['missing','partial'].includes(row.status));
121
+ const branchGaps=rows.filter(row=>row.status==='missing'||row.branchStatus==='missing').map(row=>row.path);
122
+ const branchMetric=metric(branches,coveredBranches);
123
+ return {status:incomplete?'PARTIAL':total?'MEASURED':'NOT_APPLICABLE',lines:metric(total,covered),
124
+ branches:{...branchMetric,percent:branchGaps.length?null:branchMetric.percent,measuredPercent:branchMetric.percent},branchGaps,files:rows,
125
+ note:'Percentages cover mapped changed lines/branches only; missing files and unmapped lines are not proven covered. Branch percent is unknown when branch data is missing; measuredPercent is the measured subset only. Coverage is not business correctness.'};
126
+ }
127
+
128
+ function outputBoundary(project,relativeDir){
129
+ need(relative(relativeDir)&&(relativeDir==='coverage'||relativeDir.startsWith('docs/test-reports/')),'coverage_output_invalid');
130
+ const directory=path.join(project,relativeDir);need(canonicalFuture(directory)===directory,'coverage_output_invalid');
131
+ need(!git(project,['ls-files','-z','--',`:(literal)${relativeDir}`]).trim(),'coverage_output_tracked');return directory;
132
+ }
133
+ const fingerprint=file=>{
134
+ if(!fs.existsSync(file))return null;
135
+ const stat=fs.lstatSync(file);need(stat.isFile()&&!stat.isSymbolicLink()&&stat.nlink===1&&fs.realpathSync(file)===file&&stat.size<=32*1024*1024,'coverage_report_invalid');
136
+ return {hash:digest(fs.readFileSync(file).toString('base64')),mtime:stat.mtimeMs,ctime:stat.ctimeMs,ino:stat.ino};
137
+ };
138
+
139
+ export async function runUnitCoverage(config){
140
+ const project=fs.realpathSync(config.project),comparison=inspectBranchComparison(project);
141
+ const target=config.target??'head';
142
+ if(config.comparison)need(config.comparison.base===comparison.base&&config.comparison.head===comparison.head,'coverage_comparison_changed');
143
+ const selection={base:comparison.base,head:comparison.head,target,scope:config.scope??[]};
144
+ const changes=changedUnitLines(project,selection);
145
+ const common={schemaVersion:1,comparison,target,changes,completionAuthorized:false};
146
+ if(!changes.length)return {...common,status:'NO_CHANGES',testsExecuted:false};
147
+ if(!config.command)return {...common,status:'NOT_MEASURED',reason:'No existing declared unit-coverage command; do not estimate percentages or install tools.',testsExecuted:false};
148
+ const outputDir=outputBoundary(project,config.outputDir);
149
+ need(relative(config.report)&&inside(outputDir,path.join(project,config.report)),'coverage_report_path_invalid');
150
+ const report=path.join(project,config.report),before=snapshotSource(project,outputDir);
151
+ if(target==='head'){
152
+ const dirty=git(project,['diff','--name-only','-z','--ignore-submodules=none',comparison.head,'--']).split('\0').filter(Boolean);
153
+ const untracked=git(project,['ls-files','--others','--exclude-standard','-z']).split('\0').filter(Boolean);
154
+ const auditFiles=config.auditFiles??[];
155
+ need(Array.isArray(auditFiles)&&auditFiles.length<=64&&auditFiles.every(file=>relative(file)
156
+ &&/^docs\/test-reports\/.+\.(?:md|json|jsonl)$/.test(file)&&before.files[file]?.sha256),'coverage_audit_files_invalid');
157
+ if(config.supplement){
158
+ need(config.supplement.project===project,'unit_baseline_invalid');verifyUnitSupplement(config.supplement);
159
+ }
160
+ need(dirty.every(file=>config.supplement?.tests.includes(file)),'coverage_dirty_head');
161
+ need(untracked.every(file=>inside(outputDir,path.join(project,file))||auditFiles.includes(file)
162
+ ||config.supplement?.tests.includes(file)),'coverage_untracked_head');
163
+ }
164
+ const declaration=config.command.declaration;
165
+ need(declaration&&relative(declaration.path),'coverage_declaration_required');
166
+ const sources=readSourceFiles(project,[declaration.path],before);
167
+ inspectDeclaredTestCommand(config.command,sources);
168
+ const old=fingerprint(report),identity={repositoryId:'cm-test',runId:`unit-${randomUUID()}`,taskId:'coverage',attempt:1};
169
+ const check=createHostCheck({cwd:project,commands:[{id:config.command.id,command:config.command.command}],timeoutMs:config.timeoutMs??60000});
170
+ const [observed]=await check({identity},{signal:new AbortController().signal});
171
+ outputBoundary(project,config.outputDir);
172
+ const changed=sourceChanges(before,snapshotSource(project,outputDir));
173
+ need(changed.length===0,'coverage_source_changed');
174
+ const current=inspectBranchComparison(project);
175
+ need(current.base===comparison.base&&current.head===comparison.head&&current.baseRef===comparison.baseRef,'coverage_comparison_changed');
176
+ if(observed.outcome!=='passed')return {...common,status:observed.outcome==='failed'?'TESTS_FAILED':'BLOCKED',observed,testsExecuted:observed.exitCode!==null};
177
+ const fresh=fingerprint(report);need(fresh&&digest(fresh)!==digest(old),'coverage_report_not_fresh');
178
+ const format=config.format??(report.endsWith('.json')?'istanbul':'lcov');
179
+ const result=summarizeUnitCoverage(changes,parseUnitCoverage(fs.readFileSync(report,'utf8'),format,project),config.exclusions??[]);
180
+ return {...common,...result,observed,testsExecuted:true,report,reportDigest:fresh.hash,sourceDigest:before.digest};
181
+ }
182
+
183
+ // Test-only authoring is a separately authorized continuation, never implied by analysis.
184
+ export function prepareUnitSupplement(config){
185
+ need(config.authorized===true,'unit_supplement_authorization_required');
186
+ const project=fs.realpathSync(config.project),tests=config.tests;
187
+ need(Array.isArray(tests)&&tests.length>0&&tests.length<=64&&new Set(tests).size===tests.length&&tests.every(file=>relative(file)
188
+ &&/(^|\/)(?:tests?|__tests__)\/|(?:^|\/)test_[^/]+\.py$|(?:\.test|\.spec)\.[^/]+$|_test\.(?:go|rs)$/.test(file)
189
+ &&!/(^|\/)(?:\.git|\.claude|\.codex|\.env[^/]*|AGENTS\.md|credentials[^/]*)(\/|$)/i.test(file)),'unit_test_scope_invalid');
190
+ const outputDir=outputBoundary(project,config.outputDir??'coverage');
191
+ for(const file of tests)need(canonicalFuture(path.join(project,file))===path.join(project,file)&&!inside(outputDir,path.join(project,file)),'unit_test_scope_invalid');
192
+ const baseline={schemaVersion:1,project,tests,outputDir,before:snapshotSource(project,outputDir),completionAuthorized:false};
193
+ return json({...baseline,baselineDigest:digest(baseline)},8*1024*1024);
194
+ }
195
+
196
+ export function verifyUnitSupplement(baseline){
197
+ need(baseline.schemaVersion===1&&baseline.completionAuthorized===false,'unit_baseline_invalid');
198
+ const {baselineDigest,...binding}=baseline;need(digest(binding)===baselineDigest,'unit_baseline_invalid');
199
+ const after=snapshotSource(baseline.project,baseline.outputDir),changed=sourceChanges(baseline.before,after);
200
+ need(after.gitState?.head===baseline.before.gitState?.head&&after.gitState?.index===baseline.before.gitState?.index,'unit_git_changed');
201
+ need(changed.length>0&&changed.every(file=>baseline.tests.includes(file)),'unit_supplement_out_of_scope');
202
+ // Existing tests may be extended; deletion is never a successful supplement.
203
+ for(const file of changed)need(after.files[file]&&!after.files[file].missing&&fs.existsSync(path.join(baseline.project,file))
204
+ &&fs.lstatSync(path.join(baseline.project,file)).isFile(),'unit_test_missing');
205
+ return json({status:'REVIEW_REQUIRED',changedFiles:changed,sourceDigest:after.digest,completionAuthorized:false});
206
+ }
@@ -21,6 +21,12 @@ Read context in this order:
21
21
  3. Only the `.claude/rules/*.md` files relevant to the current task, plus `coding-style.md`, `testing.md`, and `security.md` when present.
22
22
  4. The target specs files named by the active workflow.
23
23
 
24
+ Before business-code implementation or repair, apply the read-only freshness check in
25
+ `../skills/codebase-context/references/writeback.md`: verify the relevant map against
26
+ current code, including uncommitted changes. A missing, old, partial or wrong-project
27
+ map does not trigger a full scan; establish the affected chain before editing code.
28
+ Map writes remain within approved scope and happen before independent Review.
29
+
24
30
  When `AGENTS.md` and `.claude/CLAUDE.md` disagree, follow the more specific instruction that applies to the current path, unless it weakens a safety boundary. Record material conflicts in the task report.
25
31
 
26
32
  For each authorized development task or bug fix, also read `project-learning.md`.
@@ -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"
@@ -330,6 +335,8 @@ if [ -n "$NODE_BIN" ]; then
330
335
  fail "cm global log fixture failed"
331
336
  "$NODE_BIN" --test "$ROOT/scripts/cm-ai-admission.test.mjs" ||
332
337
  fail "cm-ai product admission fixture failed"
338
+ "$NODE_BIN" --test "$ROOT/scripts/cm-review-schema.test.mjs" ||
339
+ fail "review provider schema compatibility fixture failed"
333
340
  CM_PYTHON_BIN="$PYTHON_BIN" "$NODE_BIN" --test "$ROOT/scripts/cm-workflow-config.test.mjs" ||
334
341
  fail "cm workflow config fixture failed"
335
342
  CM_PYTHON_BIN="$PYTHON_BIN" "$NODE_BIN" --test "$ROOT/scripts/cm-task-gate.test.mjs" ||
@@ -573,7 +580,7 @@ for consumer in \
573
580
  fail "external-expert AUTO routing is not wired into $consumer"
574
581
  done
575
582
 
576
- 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
577
584
  require_file "skills/$name/SKILL.md"
578
585
  require_file "compat/claude-commands/$name.md"
579
586
  wrapper="$ROOT/compat/claude-commands/$name.md"
@@ -653,6 +660,21 @@ if grep -Fq '按 `codebase-context` skill dev 模式加载 10 份文档' \
653
660
  fail "cm-prd still unconditionally loads all codebase-context documents"
654
661
  fi
655
662
 
663
+ require_file "skills/codebase-context/references/writeback.md"
664
+ for consumer in \
665
+ skills/codebase-context/SKILL.md \
666
+ skills/cm-fix/SKILL.md \
667
+ skills/cm-fix/references/js-host.md \
668
+ skills/cm-doc-syncer/SKILL.md \
669
+ skills/cm-ai/references/N3-execute-task.md \
670
+ skills/cm-ai/references/N8-finish.md; do
671
+ grep -Fq 'references/writeback.md' "$ROOT/$consumer" ||
672
+ fail "business map writeback contract is not wired into $consumer"
673
+ done
674
+ if grep -Fq '不存在则跳过' "$ROOT/skills/cm-ai/references/N8-finish.md"; then
675
+ fail "N8 still silently skips missing business maps"
676
+ fi
677
+
656
678
  require_file "skills/cm-prd/references/phase-timing.md"
657
679
  grep -Fq 'references/phase-timing.md' "$ROOT/skills/cm-prd/SKILL.md" &&
658
680
  grep -Fq 'prd-context' "$ROOT/skills/cm-prd/references/phase-timing.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
+ }