@aibyzero/cm-workflow 0.11.0 → 0.13.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +3 -0
  3. package/CHANGELOG.md +64 -3
  4. package/README.md +45 -3
  5. package/VERSION +1 -1
  6. package/compat/claude-commands/cm-runtime.md +3 -0
  7. package/compat/claude-commands/cm-security.md +3 -0
  8. package/docs/architecture.md +22 -0
  9. package/docs/installation.md +56 -2
  10. package/docs/js-workflow-control.md +63 -6
  11. package/docs/runtime-failover.md +97 -0
  12. package/docs/user-guide.md +60 -3
  13. package/install-codex.sh +5 -0
  14. package/install.ps1 +10 -2
  15. package/install.sh +5 -0
  16. package/package.json +3 -1
  17. package/runtime/js/cm-ai/claude-developer-proposal.schema.json +151 -0
  18. package/runtime/js/cm-ai/claude-review-stream.mjs +69 -8
  19. package/runtime/js/cm-ai/claude-tool-preview.mjs +6 -4
  20. package/runtime/js/cm-ai/cm-ai-admission.mjs +38 -16
  21. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +44 -17
  22. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +105 -12
  23. package/runtime/js/cm-ai/codex-config.mjs +6 -0
  24. package/runtime/js/cm-ai/codex-review-adapter.mjs +6 -2
  25. package/runtime/js/cm-ai/developer-adapter.mjs +41 -16
  26. package/runtime/js/cm-ai/durable-runner-state.mjs +72 -15
  27. package/runtime/js/cm-ai/effect-contract.mjs +10 -1
  28. package/runtime/js/cm-ai/fix-code-association.mjs +4 -1
  29. package/runtime/js/cm-ai/host-conversation-execution.mjs +112 -27
  30. package/runtime/js/cm-ai/host-documentation.mjs +4 -2
  31. package/runtime/js/cm-ai/host-qa-executor.mjs +17 -4
  32. package/runtime/js/cm-ai/host-qa-policy.mjs +6 -3
  33. package/runtime/js/cm-ai/host-role-routing.mjs +9 -5
  34. package/runtime/js/cm-ai/host-tool-bridge.mjs +10 -7
  35. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +9 -4
  36. package/runtime/js/cm-ai/host.mjs +1 -1
  37. package/runtime/js/cm-ai/provider-review-observation.mjs +8 -4
  38. package/runtime/js/cm-ai/qa-attachment.mjs +30 -0
  39. package/runtime/js/cm-ai/review-package.mjs +76 -18
  40. package/runtime/js/cm-ai/review-runner.mjs +15 -3
  41. package/runtime/js/cm-ai/runtime-failover.mjs +75 -0
  42. package/runtime/js/cm-ai/specification-material.mjs +98 -0
  43. package/runtime/js/cm-ai/task-runner.mjs +57 -20
  44. package/runtime/js/cm-ai/worker-claude-developer.mjs +174 -0
  45. package/runtime/js/cm-ai/worker-claude.mjs +18 -5
  46. package/runtime/js/cm-ai/worker-codex-developer.mjs +15 -4
  47. package/runtime/js/cm-ai/worker-codex.mjs +8 -12
  48. package/runtime/js/cm-init/draft-generation.mjs +24 -4
  49. package/runtime/js/cm-init/draft-inspection.mjs +29 -1
  50. package/runtime/js/cm-prd/session.mjs +19 -2
  51. package/runtime/js/cm-prd/summary.mjs +46 -20
  52. package/runtime/js/cm-security/scan.mjs +263 -0
  53. package/runtime/js/cm-test/branch-impact.mjs +8 -2
  54. package/runtime/review.md +11 -1
  55. package/runtime/workflow-config.md +39 -2
  56. package/runtime/workflow-routing.md +6 -1
  57. package/scripts/cm-ai-admission.test.mjs +99 -0
  58. package/scripts/cm-ai-batch-host.test.mjs +4 -1
  59. package/scripts/cm-ai-batch-run.test.mjs +7 -1
  60. package/scripts/cm-ai-bootstrap.test.mjs +2 -1
  61. package/scripts/cm-ai-fix-integration.test.mjs +2 -1
  62. package/scripts/cm-ai-host.mjs +81 -12
  63. package/scripts/cm-ai-host.test.mjs +520 -5
  64. package/scripts/cm-ai-multi-root.test.mjs +9 -3
  65. package/scripts/cm-ai-nested-execution.test.mjs +11 -4
  66. package/scripts/cm-ai-review-timeout.test.mjs +226 -0
  67. package/scripts/cm-ai-run.mjs +40 -13
  68. package/scripts/cm-ai-run.test.mjs +45 -9
  69. package/scripts/cm-check-host.test.mjs +1 -1
  70. package/scripts/cm-check-runtime.sh +56 -1
  71. package/scripts/cm-check-update.mjs +200 -0
  72. package/scripts/cm-check-update.test.mjs +186 -0
  73. package/scripts/cm-claude-developer-worker.test.mjs +236 -0
  74. package/scripts/cm-claude-probe.test.mjs +64 -1
  75. package/scripts/cm-claude-review-stream.test.mjs +236 -1
  76. package/scripts/cm-claude-worker.test.mjs +110 -1
  77. package/scripts/cm-codex-developer-adapter.test.mjs +50 -2
  78. package/scripts/cm-codex-developer-worker.test.mjs +84 -1
  79. package/scripts/cm-codex-review-progress.test.mjs +34 -6
  80. package/scripts/cm-failover.mjs +288 -0
  81. package/scripts/cm-failover.test.mjs +184 -0
  82. package/scripts/cm-host-qa-executor.test.mjs +277 -0
  83. package/scripts/cm-host-tool-bridge.test.mjs +31 -0
  84. package/scripts/cm-init-draft-generation.test.mjs +62 -0
  85. package/scripts/cm-init-draft-inspection.test.mjs +76 -0
  86. package/scripts/cm-init-host.mjs +4 -4
  87. package/scripts/cm-init-host.test.mjs +12 -7
  88. package/scripts/cm-init-session.test.mjs +50 -0
  89. package/scripts/cm-log-event.mjs +34 -5
  90. package/scripts/cm-prd-completion.test.mjs +2 -2
  91. package/scripts/cm-prd-host.mjs +39 -3
  92. package/scripts/cm-prd-host.test.mjs +52 -0
  93. package/scripts/cm-prd-review-gate.mjs +11 -2
  94. package/scripts/cm-prd-review-gate.test.mjs +62 -0
  95. package/scripts/cm-prd-session-recovery.test.mjs +167 -0
  96. package/scripts/cm-prd-summary.test.mjs +147 -0
  97. package/scripts/cm-review-dependency-snapshot.test.mjs +10 -0
  98. package/scripts/cm-review-inventory.test.mjs +189 -0
  99. package/scripts/cm-review-schema.test.mjs +35 -1
  100. package/scripts/cm-review-scope-recovery.test.mjs +63 -0
  101. package/scripts/cm-runtime-edit.mjs +104 -0
  102. package/scripts/cm-runtime-failover.test.mjs +130 -0
  103. package/scripts/cm-runtime-install.mjs +42 -0
  104. package/scripts/cm-runtime.mjs +113 -0
  105. package/scripts/cm-runtime.test.mjs +117 -0
  106. package/scripts/cm-security.mjs +32 -0
  107. package/scripts/cm-security.test.mjs +203 -0
  108. package/scripts/cm-spec-manifest.mjs +24 -21
  109. package/scripts/cm-spec-manifest.test.mjs +19 -0
  110. package/scripts/cm-workflow-config.mjs +113 -5
  111. package/scripts/cm-workflow-config.test.mjs +124 -1
  112. package/scripts/fixtures/prd-review-gate-python-oracle.py +18 -2
  113. package/scripts/test-cm-prd-review-gate.py +30 -0
  114. package/scripts/test-shell-compat.sh +34 -0
  115. package/scripts/validate-public-repo.py +7 -1
  116. package/skills/cm-ai/references/N4-review.md +5 -4
  117. package/skills/cm-ai/references/js-host.md +36 -2
  118. package/skills/cm-check/SKILL.md +49 -8
  119. package/skills/cm-check/references/js-host.md +4 -1
  120. package/skills/cm-init/SKILL.md +4 -0
  121. package/skills/cm-init/references/js-host.md +2 -0
  122. package/skills/cm-init/references/runtime-declaration.md +26 -0
  123. package/skills/cm-prd/SKILL.md +3 -3
  124. package/skills/cm-prd/references/js-change-recovery.md +24 -3
  125. package/skills/cm-prd/references/summary-card.md +7 -0
  126. package/skills/cm-runtime/SKILL.md +32 -0
  127. package/skills/cm-security/SKILL.md +55 -0
  128. package/skills/cm-security/references/scan-contract.md +43 -0
  129. package/templates/auto-update/cm-update.sh +1 -1
  130. package/templates/cm-workflow.yml +16 -0
@@ -2,13 +2,25 @@
2
2
  import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import crypto from 'node:crypto';
5
+ import {isDeepStrictEqual} from 'node:util';
5
6
  import {freeze,need} from '../cm-ai/effect-contract.mjs';
7
+ import {CONFIG_FILENAMES,ConfigError,findConfig,loadConfig,runtimesSource} from '../../../scripts/cm-workflow-config.mjs';
6
8
 
7
9
  const rules=new Set(['coding-style','testing','security','git-workflow','frontend','miniprogram',
8
10
  'backend-api','database','smart-contract','finance']);
9
11
  const allowed=file=>file==='AGENTS.md'||file==='.claude/CLAUDE.md'
12
+ ||CONFIG_FILENAMES.includes(file)
10
13
  ||(/^\.claude\/rules\/([a-z-]+)\.md$/.test(file)&&rules.has(file.slice(14,-3)));
11
14
  const sha=bytes=>crypto.createHash('sha256').update(bytes).digest('hex');
15
+ const preservedConfig=config=>{
16
+ const preserved=structuredClone(config);
17
+ delete preserved.runtimes;
18
+ for(const role of ['coder','reviewer']){
19
+ delete preserved.roles[role].adapter;
20
+ delete preserved.roles[role].source;
21
+ }
22
+ return preserved;
23
+ };
12
24
 
13
25
  export function readCmInitSource(root,file){
14
26
  need(typeof file==='string'&&file.split('/').every(part=>part&&part!=='.'&&part!=='..')
@@ -37,7 +49,7 @@ export function inspectCmInitDraft({project,documents}){
37
49
  need(typeof project==='string'&&path.isAbsolute(project),'init_project_path_invalid');
38
50
  const root=fs.realpathSync(project);
39
51
  need(fs.statSync(root).isDirectory(),'init_project_path_invalid');
40
- need(Array.isArray(documents)&&documents.length>=2&&documents.length<=12,'init_draft_invalid');
52
+ need(Array.isArray(documents)&&documents.length>=2&&documents.length<=13,'init_draft_invalid');
41
53
  const byPath=new Map();
42
54
  for(const document of documents){
43
55
  need(document&&typeof document==='object'&&!Array.isArray(document)
@@ -52,6 +64,22 @@ export function inspectCmInitDraft({project,documents}){
52
64
  const before=readCmInitSource(root,file),after=Buffer.from(content);
53
65
  changes.push({path:file,action:before===null?'create':before.equals(after)?'unchanged':'modify',
54
66
  beforeSha256:before===null?null:sha(before),afterSha256:sha(after)});
67
+ if(CONFIG_FILENAMES.includes(file)){
68
+ try{
69
+ findConfig(root); // Preserve the shared ambiguity check even for a proposed new target.
70
+ const parse=text=>loadConfig({projectRoot:root,configPath:path.join(root,file),text});
71
+ const config=parse(content);
72
+ if(runtimesSource(config)!=='project')issues.push({path:file,code:'runtimes_declaration_missing'});
73
+ if(before!==null){
74
+ const previous=parse(before.toString('utf8'));
75
+ if(!isDeepStrictEqual(preservedConfig(previous),preservedConfig(config)))
76
+ issues.push({path:file,code:'existing_config_fields_changed'});
77
+ }
78
+ }catch(error){
79
+ if(!(error instanceof ConfigError))throw error;
80
+ issues.push({path:file,code:'workflow_config_invalid',message:error.message});
81
+ }
82
+ }
55
83
  if(file==='.claude/CLAUDE.md'&&content.replace(/\r\n/g,'\n').replace(/\n$/,'').split('\n').length>150)
56
84
  issues.push({path:file,code:'claude_line_limit'});
57
85
  // Only the compatibility entry's standalone @rules imports are covered here.
@@ -52,17 +52,34 @@ export function openPrdSession({specs,sessionId,identity}){
52
52
  replay(){need(state.active!==null,'prd_nothing_to_resume');cursor=0;return json(state.active,12*1024*1024);},
53
53
  commit(checkpoint){state.checkpoint=checkpoint;state.active=null;save();},
54
54
  checkpoint(checkpoint){state.checkpoint=checkpoint;save();},
55
+ abandon(resolution){
56
+ need(resolution!==null&&typeof resolution==='object'&&!Array.isArray(resolution)
57
+ &&resolution.abandon===true&&!Object.hasOwn(resolution,'result')
58
+ &&Object.keys(resolution).every(key=>['callId','requestDigest','abandon','evidence'].includes(key)),'prd_recovery_binding');
59
+ need(typeof resolution.evidence==='string'&&resolution.evidence.trim(),'prd_recovery_evidence_required');
60
+ const active=state.active,call=active?.calls.find(item=>item.callId===resolution.callId);
61
+ need(call&&call.requestDigest===resolution.requestDigest&&!Object.hasOwn(call,'result'),'prd_recovery_binding');
62
+ need(!active.calls.some(item=>item.kind==='prd_review'),'prd_review_recovery_required');
63
+ const decision={operation:active.request.operation,kind:call.kind,callId:call.callId,
64
+ evidence:{sha256:digest(resolution.evidence),length:resolution.evidence.length}};
65
+ state.checkpoint=active.before;state.active=null;cursor=0;save();return decision;
66
+ },
55
67
  async call(kind,payload,signal,perform){
56
68
  need(state.active!==null,'prd_operation_required');const index=cursor++,input=json({kind,payload},12*1024*1024);
69
+ const active=state.active;
57
70
  const previous=state.active.calls[index];
58
71
  if(previous){need(previous.requestDigest===digest(input),'prd_replay_inputs_changed');
59
72
  need(Object.hasOwn(previous,'result'),'prd_host_result_unknown');return previous.result;}
60
73
  need(!state.active.calls.some(call=>!Object.hasOwn(call,'result')),'prd_host_result_unknown');
61
74
  const call={callId:randomUUID(),requestDigest:digest(input),...input};state.active.calls.push(call);save();
62
- const result=json(await perform({...payload,recovery:{sessionId,callId:call.callId,requestDigest:call.requestDigest}},signal),1024*1024);
75
+ const response=await perform({...payload,recovery:{sessionId,callId:call.callId,requestDigest:call.requestDigest}},signal);
76
+ need(!signal.aborted&&state.active===active,'cancelled');
77
+ const result=json(response,1024*1024);
63
78
  call.result=result;save();return result;
64
79
  },
65
- resolve({callId,requestDigest,result,evidence}){
80
+ resolve(resolution){
81
+ need(resolution!==null&&typeof resolution==='object'&&!Object.hasOwn(resolution,'abandon'),'prd_recovery_binding');
82
+ const {callId,requestDigest,result,evidence}=resolution;
66
83
  need(typeof evidence==='string'&&evidence.trim(),'prd_recovery_evidence_required');
67
84
  const call=state.active?.calls.find(item=>item.callId===callId);
68
85
  need(call&&call.requestDigest===requestDigest&&!Object.hasOwn(call,'result'),'prd_recovery_binding');
@@ -12,13 +12,17 @@ import {need,json,shape,digest} from '../cm-ai/effect-contract.mjs';
12
12
  import {prdDesignRiskSignals} from './design-risk.mjs';
13
13
  const sha=bytes=>createHash('sha256').update(bytes).digest('hex');
14
14
 
15
- export function inspectPrdSummaryEvidence(specs){
15
+ export function inspectPrdSummaryEvidence(specs,{currentFeatures}={}){
16
16
  need(path.isAbsolute(specs)&&fs.realpathSync(specs)===specs,'prd_summary_root_invalid');
17
17
  const specFiles=buildManifest(specs),names=[...new Set(specFiles.map(item=>item.path.split('/')[0]))];
18
+ need(currentFeatures===undefined||(Array.isArray(currentFeatures)&&currentFeatures.length>0
19
+ &&new Set(currentFeatures).size===currentFeatures.length&&currentFeatures.every(name=>names.includes(name))),
20
+ 'prd_summary_scope_unknown');
18
21
  const slugs=new Set(),features=[],documents=[],evidenceFiles=[];
19
22
  const statusBytes=readCmInitSource(specs,'.cm-specs-status');
20
23
  if(statusBytes!==null)evidenceFiles.push({path:'.cm-specs-status',sha256:sha(statusBytes)});
21
24
  for(const directory of names){
25
+ const historical=currentFeatures!==undefined&&!currentFeatures.includes(directory);
22
26
  need(/^[1-9]\d*\.[a-z0-9]+(?:-[a-z0-9]+)*$/.test(directory),'prd_summary_feature_invalid');
23
27
  const slug=directory.replace(/^\d+\./,'');need(!slugs.has(slug),'prd_summary_slug_collision');slugs.add(slug);
24
28
  const files=specFiles.filter(item=>item.path.startsWith(directory+'/')).map(item=>{
@@ -36,32 +40,45 @@ export function inspectPrdSummaryEvidence(specs){
36
40
  }
37
41
  const args={stage,feature:slug,evidence:path.join(specs,prefix+'-r1.md'),receipt:path.join(specs,prefix+'-disposition.json')};
38
42
  const gate=inspectPrdReview(args);
39
- let findings=null;
40
- if(['resume_disposition','completed'].includes(gate.outcome))findings=inspectPrdFindings({specs,stage,feature:directory});
41
- if(gate.outcome==='completed'){
42
- const receipt=JSON.parse(readCmInitSource(specs,prefix+'-disposition.json').toString('utf8'));
43
- const expected=stage==='design'?[`${directory}/design.md`]:files.map(item=>`${directory}/${item.path}`).sort();
44
- need(digest(receipt.artifacts.map(item=>item.path).sort())===digest(expected),'prd_summary_receipt_coverage');
43
+ let findings=null,archiveIssue={};
44
+ try{
45
+ if(['resume_disposition','completed'].includes(gate.outcome))findings=inspectPrdFindings({specs,stage,feature:directory});
46
+ if(gate.outcome==='completed'){
47
+ const receipt=JSON.parse(readCmInitSource(specs,prefix+'-disposition.json').toString('utf8'));
48
+ const expected=stage==='design'?[`${directory}/design.md`]:files.map(item=>`${directory}/${item.path}`).sort();
49
+ need(digest(receipt.artifacts.map(item=>item.path).sort())===digest(expected),'prd_summary_receipt_coverage');
50
+ }
51
+ }catch(error){
52
+ if(!historical)throw error;
53
+ const original=readCmInitSource(specs,prefix+'-r1.md');
54
+ archiveIssue={archive:original!==null&&!/\n```json\n[^\n]+\n```\n$/.test(original.toString('utf8'))?'legacy_format':'unavailable',
55
+ reason:error.message};
45
56
  }
57
+ if(historical&&gate.outcome!=='completed'&&(stage==='split'||gate.outcome!=='dispatch_once'))
58
+ archiveIssue={archive:archiveIssue.archive??'receipt_missing',
59
+ reason:[archiveIssue.reason,'prd_summary_receipt_missing'].filter(Boolean).join('; ')};
46
60
  reviews[stage]={gate,independent:findings?.independent??null,verdict:findings?.verdict??null,
47
- findings:findings?.findings??[],source:findings?.source??null};
61
+ findings:findings?.findings??[],source:findings?.source??null,...archiveIssue};
48
62
  }
49
63
  let cases={total:0,user:0,generated:0};
50
64
  const contract=files.find(item=>item.path==='test-cases.json');
51
65
  if(contract){const data=JSON.parse(contract.content);need(Array.isArray(data.cases),'prd_summary_cases_invalid');
52
66
  cases={total:data.cases.length,user:data.cases.filter(item=>item.origin==='user').length,
53
67
  generated:data.cases.filter(item=>item.origin==='generated').length};}
54
- features.push({directory,reviews,cases});
68
+ features.push({directory,reviews,cases,...(currentFeatures===undefined?{}:{historical})});
55
69
  }
56
- const mechanical=checkPrdDraftMechanics({draftDigest:digest(evidenceFiles),features:documents});
57
- return json({specs,specFiles,features,documents,mechanical,evidenceFiles},1024*1024);
70
+ const mechanical=checkPrdDraftMechanics({draftDigest:digest(evidenceFiles),
71
+ features:documents.filter(item=>currentFeatures===undefined||currentFeatures.includes(item.directory))});
72
+ return json({specs,specFiles,features,documents,mechanical,evidenceFiles,
73
+ ...(currentFeatures===undefined?{}:{currentFeatures})},1024*1024);
58
74
  }
59
75
 
60
76
  export function publishPrdAwaitingReview({specs,summary,writeEnabled,recover=false}){
61
77
  need(writeEnabled===true,'prd_summary_write_not_enabled');
62
78
  need(summary.status==='human_summary_prepared'&&summary.readyForAwaitingReview===true
63
79
  &&summary.blockers.length===0,'prd_summary_not_ready');
64
- const before=inspectPrdSummaryEvidence(specs);
80
+ const scope={currentFeatures:summary.currentFeatures};
81
+ const before=inspectPrdSummaryEvidence(specs,scope);
65
82
  const existing=readCmInitSource(specs,'.cm-specs-status');
66
83
  if(recover&&existing!==null){
67
84
  const value=JSON.parse(existing);
@@ -81,7 +98,7 @@ export function publishPrdAwaitingReview({specs,summary,writeEnabled,recover=fal
81
98
  const temporary=path.join(specs,`.cm-prd-status-${randomUUID()}`);let fd;
82
99
  try{
83
100
  fd=fs.openSync(temporary,'wx',0o600);fs.writeFileSync(fd,bytes);fs.fsyncSync(fd);fs.closeSync(fd);fd=undefined;
84
- need(digest(inspectPrdSummaryEvidence(specs))===summary.evidenceDigest,'prd_summary_inputs_changed');
101
+ need(digest(inspectPrdSummaryEvidence(specs,scope))===summary.evidenceDigest,'prd_summary_inputs_changed');
85
102
  fs.renameSync(temporary,target);
86
103
  const dir=fs.openSync(specs,'r');try{fs.fsyncSync(dir);}finally{fs.closeSync(dir);}
87
104
  need(readCmInitSource(specs,'.cm-specs-status')?.equals(bytes),'prd_summary_status_unknown');
@@ -95,20 +112,27 @@ export function publishPrdAwaitingReview({specs,summary,writeEnabled,recover=fal
95
112
  const requiredSignals=prdDesignRiskSignals;
96
113
  export function createPrdSummaryOwner({summarize}){
97
114
  need(typeof summarize==='function','prd_summary_host_required');
98
- return async(specs,signal)=>{
99
- need(!signal.aborted,'cancelled');const evidence=inspectPrdSummaryEvidence(specs),evidenceDigest=digest(evidence);
115
+ return async(specs,options={},signal=new AbortController().signal)=>{
116
+ // Preserve the original (specs, signal) API for existing consumers.
117
+ if(typeof options.aborted==='boolean'){signal=options;options={};}
118
+ const scope={currentFeatures:Array.isArray(options.currentFeatures)?options.currentFeatures.slice():options.currentFeatures};
119
+ need(!signal.aborted,'cancelled');const evidence=inspectPrdSummaryEvidence(specs,scope),evidenceDigest=digest(evidence);
100
120
  const details=json(await summarize({evidence,evidenceDigest,
101
- instructions:'Prepare original cm-prd Step 11 human summary. Read actual source/context as needed. Return {evidenceDigest,deliveryForm,estimatedTime,openQuestions,risks,contextScope,platformReadiness,uiBaseline,designRisk:[{feature,signals:{greenfieldAdr,architectureOrDataFlow,newRuntimeDependencyOrToolchain,publicContractDataOrSecurity,fiveOrMoreFunctions},evidence:[specific references]}]}. Signals are booleans and must cover original Step 9.5 criteria; unknown facts must remain explicit in openQuestions/risks, never infer approval. All descriptive fields are non-empty strings. Do not claim review or tests beyond supplied evidence, write files, dispatch reviewers/providers, approve specs or start development.'},signal),64*1024);
121
+ instructions:'Prepare original cm-prd Step 11 human summary. Read actual source/context as needed. Return {evidenceDigest,deliveryForm,estimatedTime,openQuestions,risks,contextScope,platformReadiness,uiBaseline,designRisk:[{feature,signals:{greenfieldAdr,architectureOrDataFlow,newRuntimeDependencyOrToolchain,publicContractDataOrSecurity,fiveOrMoreFunctions},evidence:[specific references]}]}. designRisk must cover exactly the current features (historical !== true); historical reviews are registration notes only, never new blockers. Signals are booleans and must cover original Step 9.5 criteria; unknown facts must remain explicit in openQuestions/risks, never infer approval. All descriptive fields are non-empty strings. Do not claim review or tests beyond supplied evidence, write files, dispatch reviewers/providers, approve specs or start development.'},signal),64*1024);
102
122
  need(!signal.aborted,'cancelled');
103
123
  shape(details,['evidenceDigest','deliveryForm','estimatedTime','openQuestions','risks','contextScope','platformReadiness','uiBaseline','designRisk']);
104
124
  need(details.evidenceDigest===evidenceDigest,'prd_summary_binding');
105
125
  for(const field of ['deliveryForm','estimatedTime','openQuestions','risks','contextScope','platformReadiness','uiBaseline'])
106
126
  need(typeof details[field]==='string'&&details[field].trim(),'prd_summary_details_invalid');
107
- need(Array.isArray(details.designRisk)&&details.designRisk.length===evidence.features.length,'prd_summary_risk_coverage');
108
- const seen=new Set(),blockers=[];
127
+ const current=evidence.features.filter(item=>!item.historical),historical=evidence.features.filter(item=>item.historical);
128
+ need(Array.isArray(details.designRisk)&&details.designRisk.length===current.length,'prd_summary_risk_coverage');
129
+ const seen=new Set(),blockers=[],notes=[];
130
+ for(const feature of historical)for(const [stage,review] of Object.entries(feature.reviews)){
131
+ if(review.archive)notes.push(`历史 feature ${feature.directory}:${stage} 审查${review.archive==='legacy_format'?'为旧版归档':review.archive==='receipt_missing'?'缺少处置回执':'归档不可用'}${review.reason.includes('prd_summary_receipt_missing')&&review.archive!=='receipt_missing'?',无处置回执':''},已登记未重审(${review.reason})`);
132
+ }
109
133
  for(const risk of details.designRisk){
110
134
  shape(risk,['feature','signals','evidence']);shape(risk.signals,requiredSignals);
111
- const feature=evidence.features.find(item=>item.directory===risk.feature);
135
+ const feature=current.find(item=>item.directory===risk.feature);
112
136
  need(feature&&!seen.has(risk.feature)&&requiredSignals.every(key=>typeof risk.signals[key]==='boolean')
113
137
  &&Array.isArray(risk.evidence)&&risk.evidence.length&&risk.evidence.every(item=>typeof item==='string'&&item.trim()),'prd_summary_risk_invalid');seen.add(risk.feature);
114
138
  const {design,split}=feature.reviews;
@@ -119,12 +143,14 @@ export function createPrdSummaryOwner({summarize}){
119
143
  blockers.push(`${risk.feature}: existing_design_attempt_unresolved`);
120
144
  }
121
145
  if(evidence.mechanical.status==='failed')blockers.push('mechanical_self_check_failed');
122
- need(digest(inspectPrdSummaryEvidence(specs))===evidenceDigest,'prd_summary_inputs_changed');
146
+ need(digest(inspectPrdSummaryEvidence(specs,scope))===evidenceDigest,'prd_summary_inputs_changed');
123
147
  const checklist=['跨feature产物不重复','依赖完整且无环','AC可验证','功能粒度合规且每feature≤15任务',
124
148
  '开放问题和敏感决策已经人工确认','交付形态符合需求','存在原型时功能与交互覆盖完整'];
125
149
  const totals=evidence.mechanical.features.reduce((sum,item)=>({tasks:sum.tasks+item.tasks,
126
150
  acceptanceCriteria:sum.acceptanceCriteria+item.acceptanceCriteria}),{tasks:0,acceptanceCriteria:0});
127
151
  const summary=json({status:'human_summary_prepared',evidenceDigest,details,features:evidence.features,totals,
152
+ ...(evidence.currentFeatures===undefined?{}:{currentFeatures:evidence.currentFeatures}),
153
+ notes,historicalSummary:`历史 feature:${historical.length} 个已登记,${historical.filter(item=>Object.values(item.reviews).some(review=>review.archive)).length} 个含旧版归档说明`,
128
154
  mechanicalSelfCheck:evidence.mechanical,blockers,checklist:checklist.map(text=>({text,checked:false})),
129
155
  specFiles:evidence.specFiles,publicationInput:evidence.evidenceFiles,readyForAwaitingReview:blockers.length===0,
130
156
  next:'human_review_then_explicit_cm_ai',completionAuthorized:false},1024*1024);
@@ -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');
package/runtime/review.md CHANGED
@@ -17,6 +17,7 @@ work independently.
17
17
  When a project configures a `reviewer` role, resolve it through
18
18
  `runtime/workflow-routing.md` before selecting the review channel. Record the
19
19
  requested adapter/model alias and `route_state` as decision metadata only.
20
+ `cli-dispatch` proves a process was created, not a successful independent review.
20
21
  `declared-adapter` is not proof that a second backend reviewed the diff; the
21
22
  fresh-context and independence rules below still apply.
22
23
  `managed-adapter` identifies a callable boundary, not proof that a call occurred.
@@ -43,11 +44,16 @@ At task start, record the existing working-tree status and the task's intended f
43
44
 
44
45
  Do not send the whole working tree merely because it is convenient.
45
46
 
47
+ New `cm-review-package` version 1 packages include `unchangedScope`: sorted `{path, sha256}` entries for existing, unchanged scope files, bound into `packageDigest` without adding their bodies. These paths belong in `examinedPaths` and may receive evidence-backed findings, but must not be used to require changes to unchanged files or infer contents from hashes. Legacy packages without this field retain their original digest, path set and receipt verification.
48
+
49
+ New cm-ai runs additionally bind `specification` into the baseline, developer request and `packageDigest`: feature, task description/verification, all acceptance criteria, design excerpt (up to 64 KiB UTF-8, `truncated:true` above that), task-related test cases and approved source hashes. Review implementation against these ACs and interface contracts. Source paths are relative to the specs root, not writable code scope or extra examinedPaths. Hashes use the existing manifest normalization for runtime task/AC checkboxes. Missing optional test-cases.json yields an empty list and three sources. Live source/approval drift blocks as `spec_drift`, including reapproval of a different contract during a run; material is never silently refreshed. Historical baselines/packages without specification retain their original digest and receipt/completion rules. (Dogfood: separate specs/code roots previously hid the task and interface contracts from both developer and reviewer.)
50
+
46
51
  ## Channel order
47
52
 
48
53
  1. `codex-subagent`: spawn a fresh reviewer/subagent with the runtime's no-history/fresh-context option (for example `fork_turns: none`) and provide only the review package. Ask for concrete failure scenarios, ordered by severity, and require an explicit zero-findings result when applicable.
49
54
  2. `codex-cli`: if subagents are unavailable, run `codex review` only when the task changes are isolated from unrelated dirty work (clean pre-task tree or isolated worktree/commit).
50
- 3. Neither independent path is safe: pause new implementation or leave existing work pending review. `self-degraded` is diagnostic only; it cannot authorize N5 or successful completion, even if its legacy verdict says `approved`.
55
+ 3. `claude-cli`: when selected by the project declaration, the protected host must actually spawn a fresh Claude reviewer and recover its registered V3 receipt before recording `independent: true`. A two-provider declaration requires coder and reviewer on different providers; a single-provider declaration uses a fresh context on that provider.
56
+ 4. The selected independent path is unavailable: pause new implementation or leave existing work pending review. `self-degraded` is diagnostic only; it cannot authorize N5 or successful completion, even if its legacy verdict says `approved`.
51
57
 
52
58
  Do not wait for two degraded tasks or limit this pause to high-risk work. Channel
53
59
  unavailability is not a code finding or an implementation review round; record
@@ -66,6 +72,8 @@ Installed CLI has passed this local request-surface probe. It uses the same boun
66
72
  directory for CLAUDE_CODE_TMPDIR and stops after the first valid message request. Probe-induced
67
73
  termination is not user cancellation or a successful review; real model review remains unverified.
68
74
  Do not handcraft a passing diagnostic or approval to bypass readiness evidence.
75
+ Claude review streams accept `system/api_retry`, `hook_started`, `hook_response` and `commands_changed` only as `onNotice` summaries, sharing a 32-notice limit with `rate_limit_event`; they never enter observation or advance the verdict stage, and unknown system subtypes still fail closed (2026-09-17 dogfood: a transient API retry was misclassified as `unexpected_event`).
76
+ `system/thinking_tokens` has a separate 4096-event budget and remains subject to the worker's total 1,000,000-byte output cap; it emits no observation or notice and never advances the verdict stage (2026-09-17 dogfood: an 88-heartbeat review exceeded the former 64-event cap). The 4097th heartbeat fails with `unexpected_event`; output overflow retains `output_limit`.
69
77
 
70
78
  ## Review scope
71
79
 
@@ -82,6 +90,8 @@ findings 后运行对应规格自检;未解决项进入摘要卡由人审,
82
90
  两阶段必须用 `scripts/cm-prd-review-gate.py` 保存 disposition 回执:r1 已存在但回执
83
91
  缺失时只恢复 finding 处置,不得重新调用 reviewer;回执完成后不得重审。任何 r2 文件
84
92
  或 r1 内容哈希漂移都由门禁阻断。
93
+ PRD artifact 回执先比对原始字节,仅 Markdown 中 `tasks.md` 的任务、`requirements.md` 的 AC 运行期 `[x]`/`[X]` 可复用规格清单规则规范化为 `[ ]` 后匹配;代码块、其他正文与 JSON 仍精确比对。
94
+ 命中时只读返回 `runtimeMarksNormalized:true`,经摘要 `reviews[stage].gate` 透传;当前草稿处置与摘要发布快照仍绑定原始字节(2026-09-17 真实项目 dogfood:已开发 specs 目录新增 feature 时摘要被历史 `[x]` 阻断)。
85
95
 
86
96
  - Maximum two review rounds per task.
87
97
  - Round 1 `changes_requested` returns to N3 and produces attempt 2 plus a new