@aibyzero/cm-workflow 0.16.4 → 0.16.5

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 (167) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +8 -0
  3. package/CHANGELOG.md +50 -0
  4. package/README.md +12 -1
  5. package/VERSION +1 -1
  6. package/docs/installation.md +21 -1
  7. package/docs/js-workflow-control.md +245 -33
  8. package/docs/runtime-failover.md +1 -1
  9. package/package.json +1 -1
  10. package/runtime/js/cm-ai/accepted-fix.mjs +23 -5
  11. package/runtime/js/cm-ai/bootstrap-feature.mjs +15 -0
  12. package/runtime/js/cm-ai/claude-review-stream.mjs +12 -0
  13. package/runtime/js/cm-ai/cm-ai-admission.mjs +115 -41
  14. package/runtime/js/cm-ai/cm-ai-context-refresh.mjs +3 -2
  15. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +137 -22
  16. package/runtime/js/cm-ai/cm-ai-learning-handoff-writer.mjs +11 -9
  17. package/runtime/js/cm-ai/cm-ai-learning-writer.mjs +22 -5
  18. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +180 -53
  19. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +2 -1
  20. package/runtime/js/cm-ai/codex-review-adapter.mjs +24 -4
  21. package/runtime/js/cm-ai/developer-adapter.mjs +6 -2
  22. package/runtime/js/cm-ai/diagnostic-reason.mjs +10 -0
  23. package/runtime/js/cm-ai/drive-bootstrap.mjs +305 -0
  24. package/runtime/js/cm-ai/drive-core.mjs +39 -7
  25. package/runtime/js/cm-ai/durable-runner-state.mjs +307 -53
  26. package/runtime/js/cm-ai/effect-abandon-log.mjs +19 -0
  27. package/runtime/js/cm-ai/effect-contract.mjs +44 -2
  28. package/runtime/js/cm-ai/execution-store-limits.mjs +18 -0
  29. package/runtime/js/cm-ai/execution-store.mjs +6 -4
  30. package/runtime/js/cm-ai/fix-code-association.mjs +171 -18
  31. package/runtime/js/cm-ai/host-bootstrap.mjs +68 -21
  32. package/runtime/js/cm-ai/host-conversation-execution.mjs +16 -4
  33. package/runtime/js/cm-ai/host-handoff.mjs +13 -6
  34. package/runtime/js/cm-ai/host-qa-executor.mjs +21 -7
  35. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +4 -4
  36. package/runtime/js/cm-ai/host-qa-policy.mjs +16 -7
  37. package/runtime/js/cm-ai/host-session.mjs +12 -4
  38. package/runtime/js/cm-ai/host-tool-bridge.mjs +1 -1
  39. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +13 -4
  40. package/runtime/js/cm-ai/host.mjs +1 -1
  41. package/runtime/js/cm-ai/launch-mismatch.mjs +42 -0
  42. package/runtime/js/cm-ai/log-rows.mjs +21 -0
  43. package/runtime/js/cm-ai/project-qa-gate.mjs +84 -0
  44. package/runtime/js/cm-ai/provider-review-observation.mjs +53 -9
  45. package/runtime/js/cm-ai/qa-config-revision.mjs +44 -10
  46. package/runtime/js/cm-ai/review-abandon-log.mjs +21 -0
  47. package/runtime/js/cm-ai/review-package.mjs +427 -31
  48. package/runtime/js/cm-ai/review-runner.mjs +47 -1
  49. package/runtime/js/cm-ai/reviewed-deliveries.mjs +97 -0
  50. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +104 -10
  51. package/runtime/js/cm-ai/reviewed-evidence-supersession-record.mjs +42 -3
  52. package/runtime/js/cm-ai/specification-material.mjs +154 -12
  53. package/runtime/js/cm-ai/task-commit.mjs +2 -2
  54. package/runtime/js/cm-ai/task-runner.mjs +502 -65
  55. package/runtime/js/cm-fix/execution.mjs +109 -25
  56. package/runtime/js/cm-fix/host-review.mjs +7 -3
  57. package/runtime/js/cm-fix/host.mjs +3 -1
  58. package/runtime/js/cm-fix/progress.mjs +1 -0
  59. package/runtime/js/cm-fix/protected-edits.mjs +15 -4
  60. package/runtime/js/cm-fix/qa-source.mjs +6 -4
  61. package/runtime/js/cm-prd/analysis.mjs +2 -1
  62. package/runtime/js/cm-prd/change.mjs +28 -10
  63. package/runtime/js/cm-prd/draft.mjs +5 -2
  64. package/runtime/js/cm-prd/review-preparation.mjs +10 -3
  65. package/runtime/js/cm-prd/review-publication.mjs +4 -2
  66. package/runtime/js/cm-prd/self-check.mjs +6 -3
  67. package/runtime/js/cm-prd/summary.mjs +3 -1
  68. package/runtime/js/cm-prd/validation-reason.mjs +20 -0
  69. package/runtime/js/spec-task-line.mjs +117 -0
  70. package/runtime/js/specs-status.mjs +10 -3
  71. package/scripts/cm-ai-abandon-effect-position.test.mjs +201 -0
  72. package/scripts/cm-ai-admission.mjs +18 -11
  73. package/scripts/cm-ai-admission.test.mjs +65 -1
  74. package/scripts/cm-ai-batch-drive.mjs +92 -20
  75. package/scripts/cm-ai-batch-drive.test.mjs +164 -3
  76. package/scripts/cm-ai-batch-host.mjs +27 -11
  77. package/scripts/cm-ai-batch-host.test.mjs +2 -1
  78. package/scripts/cm-ai-batch-run.mjs +33 -10
  79. package/scripts/cm-ai-batch-run.test.mjs +56 -5
  80. package/scripts/cm-ai-bootstrap-driver-preflight.test.mjs +45 -0
  81. package/scripts/cm-ai-bootstrap-flow.test.mjs +158 -0
  82. package/scripts/cm-ai-bootstrap-merge.test.mjs +45 -0
  83. package/scripts/cm-ai-bootstrap.test.mjs +99 -7
  84. package/scripts/cm-ai-conversation-entry-ops.test.mjs +82 -2
  85. package/scripts/cm-ai-develop-driver-gaps.test.mjs +822 -0
  86. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +468 -0
  87. package/scripts/cm-ai-drive-timeout.test.mjs +17 -0
  88. package/scripts/cm-ai-drive.mjs +479 -47
  89. package/scripts/cm-ai-drive.test.mjs +240 -10
  90. package/scripts/cm-ai-fix-later-delivery.test.mjs +383 -0
  91. package/scripts/cm-ai-host.mjs +84 -25
  92. package/scripts/cm-ai-host.test.mjs +232 -12
  93. package/scripts/cm-ai-launch-diagnostics.test.mjs +142 -0
  94. package/scripts/cm-ai-multi-root.test.mjs +9 -3
  95. package/scripts/cm-ai-project-qa-gate.test.mjs +308 -0
  96. package/scripts/cm-ai-qa-config-revision.test.mjs +166 -15
  97. package/scripts/cm-ai-qa-fingerprint-config.test.mjs +157 -0
  98. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +27 -2
  99. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +400 -0
  100. package/scripts/cm-ai-review-drift-precedence.test.mjs +90 -0
  101. package/scripts/cm-ai-review-failure.test.mjs +917 -0
  102. package/scripts/cm-ai-review-timeout-config.test.mjs +29 -7
  103. package/scripts/cm-ai-review-timeout.test.mjs +199 -4
  104. package/scripts/cm-ai-run.mjs +160 -60
  105. package/scripts/cm-ai-run.test.mjs +4 -3
  106. package/scripts/cm-ai-runner-error-code-regression.test.mjs +219 -0
  107. package/scripts/cm-ai-selection-guard.test.mjs +100 -0
  108. package/scripts/cm-ai-session-chain.test.mjs +7 -3
  109. package/scripts/cm-ai-spec-rebind.test.mjs +481 -0
  110. package/scripts/cm-ai-supersede.test.mjs +571 -17
  111. package/scripts/cm-ai-verification-gate.test.mjs +2 -1
  112. package/scripts/cm-capability-gate.test.mjs +21 -2
  113. package/scripts/cm-check-drive.test.mjs +1 -1
  114. package/scripts/cm-check-host.test.mjs +1 -1
  115. package/scripts/cm-check-runtime.sh +1 -1
  116. package/scripts/cm-claude-developer-worker.test.mjs +3 -1
  117. package/scripts/cm-claude-probe.test.mjs +9 -1
  118. package/scripts/cm-claude-review-stream.test.mjs +25 -0
  119. package/scripts/cm-claude-worker.test.mjs +11 -4
  120. package/scripts/cm-codex-developer-worker.test.mjs +4 -2
  121. package/scripts/cm-failover.mjs +8 -8
  122. package/scripts/cm-fix-abandon.test.mjs +123 -5
  123. package/scripts/cm-fix-cause-package.test.mjs +2 -0
  124. package/scripts/cm-fix-drive.mjs +45 -13
  125. package/scripts/cm-fix-drive.test.mjs +36 -1
  126. package/scripts/cm-fix-host.mjs +9 -6
  127. package/scripts/cm-fix-review-budget.test.mjs +141 -0
  128. package/scripts/cm-fixture-process-cleanup.test.mjs +95 -0
  129. package/scripts/cm-host-check.test.mjs +6 -3
  130. package/scripts/cm-host-qa-executor.test.mjs +192 -17
  131. package/scripts/cm-host-session-diagnostic.test.mjs +10 -0
  132. package/scripts/cm-interactive-qa-diagnostic.test.mjs +53 -0
  133. package/scripts/cm-log-event.mjs +17 -0
  134. package/scripts/cm-log-event.test.mjs +31 -0
  135. package/scripts/cm-prd-completion.test.mjs +75 -0
  136. package/scripts/cm-prd-draft.test.mjs +14 -0
  137. package/scripts/cm-prd-gate-diagnostic.test.mjs +100 -0
  138. package/scripts/cm-prd-review-gate.mjs +126 -81
  139. package/scripts/cm-prd-review-gate.test.mjs +105 -1
  140. package/scripts/cm-prd-review-preparation.test.mjs +15 -0
  141. package/scripts/cm-prd-review-publication.test.mjs +6 -0
  142. package/scripts/cm-prd-self-check.test.mjs +6 -0
  143. package/scripts/cm-prd-summary.test.mjs +9 -0
  144. package/scripts/cm-review-dependency-snapshot.test.mjs +15 -0
  145. package/scripts/cm-review-inventory.test.mjs +253 -1
  146. package/scripts/cm-spec-manifest.mjs +28 -10
  147. package/scripts/cm-spec-manifest.test.mjs +8 -4
  148. package/scripts/cm-spec-task-line.test.mjs +138 -0
  149. package/scripts/cm-specs-status.test.mjs +12 -1
  150. package/scripts/cm-task-gate.mjs +18 -10
  151. package/scripts/cm-task-gate.py +1 -1
  152. package/scripts/cm-test-branch-impact.test.mjs +6 -3
  153. package/scripts/fixtures/claude-review-process.mjs +1 -0
  154. package/scripts/fixtures/process-cleanup.mjs +99 -0
  155. package/scripts/test-cm-log-event.py +2 -0
  156. package/scripts/test-cm-prd-review-gate.py +2 -1
  157. package/scripts/test-npm-install.py +1 -1
  158. package/scripts/test-scan-public-safety.py +1 -1
  159. package/scripts/test-spec-manifest.py +16 -8
  160. package/scripts/test-task-gate.py +2 -2
  161. package/scripts/test-workflow-config.py +1 -0
  162. package/scripts/validate-public-repo.py +1 -0
  163. package/skills/cm-ai/references/N1-init.md +1 -1
  164. package/skills/cm-ai/references/js-host.md +261 -42
  165. package/skills/cm-fix/references/js-host.md +22 -1
  166. package/skills/cm-prd/references/js-change-recovery.md +1 -1
  167. package/skills/cm-prd/references/js-host.md +6 -0
@@ -3,18 +3,26 @@
3
3
  import fs from 'node:fs';
4
4
  import path from 'node:path';
5
5
  import { createHash } from 'node:crypto';
6
+ import os from 'node:os';
7
+ import {spawnSync} from 'node:child_process';
6
8
  import { digest } from './contracts.mjs';
7
9
  import {captureSpecificationMaterial,readSpecificationMaterial,verifySpecificationMaterial} from './specification-material.mjs';
8
10
  import {resolveCodeProjects,validateCodeProjectPaths,
9
11
  codeProjectInstructionPaths,assertCodeProjectSelections} from './code-projects.mjs';
12
+ import {identifyApprovedBootstrapFeature} from './bootstrap-feature.mjs';
10
13
 
11
14
  const FILE_LIMIT=1024*1024, SNAPSHOT_LIMIT=2*1024*1024, FILE_COUNT=256;
15
+ // Read-only view for callers that must refuse an oversized delivery before it is written.
16
+ export const REVIEW_MATERIAL_LIMITS=Object.freeze({file:FILE_LIMIT,total:SNAPSHOT_LIMIT,count:FILE_COUNT});
12
17
  // Inventory budgets bound scanning, independently of the much smaller review body.
13
18
  const INVENTORY_COUNT=10000, INVENTORY_LIMIT=1024*1024*1024;
19
+ const IGNORE_COUNT=10000, IGNORE_BYTES=1024*1024;
14
20
  const materialPath=(p,selected)=>selected.has(p)||p.split('/').at(-1)==='AGENTS.md';
15
21
  // Fixed dependency/cache directories, not caller-controlled business exclusions.
16
22
  // Keep this narrower than the discovery scanner: dist/build may be authored files.
17
23
  const dependencyDirectories=new Set(['.venv','node_modules','__pycache__','.pytest_cache','.ruff_cache']);
24
+ const junkDirectories=new Set(['.appledouble','xcuserdata','.build','.swiftpm','deriveddata']);
25
+ const junkFile=name=>name==='.DS_Store'||name.startsWith('._')||name==='Thumbs.db'||name.endsWith('.xcuserstate');
18
26
  const inDependencyDirectory=p=>p.split('/').slice(0,-1).some(part=>dependencyDirectories.has(part.toLowerCase()));
19
27
  // CocoaPods installs ios/Pods as a generated tree whose headers are symlinks.
20
28
  // It is a dependency root like node_modules, but every other dependency root
@@ -39,6 +47,170 @@ const inCocoaPodsTree=(root,p)=>{
39
47
  return parts.slice(0,-1).some((part,index)=>isCocoaPodsRoot(path.join(root,...parts.slice(0,index+1))));
40
48
  };
41
49
  const sha = bytes => createHash('sha256').update(bytes).digest('hex');
50
+ const inside=(root,p)=>p===root||p.startsWith(root+path.sep);
51
+ function trustedGit(root){
52
+ for(const directory of (process.env.PATH??'').split(path.delimiter)){
53
+ if(!directory||!path.isAbsolute(directory))continue;
54
+ try {const bin=fs.realpathSync(path.join(directory,process.platform==='win32'?'git.exe':'git'));
55
+ if(!inside(root,bin)&&fs.statSync(bin).isFile()){fs.accessSync(bin,fs.constants.X_OK);return bin;}
56
+ }catch{}
57
+ }
58
+ return null;
59
+ }
60
+ function gitIgnore(root,legacy=false){
61
+ const bin=trustedGit(root);if(!bin)return null;
62
+ const safePath=(process.env.PATH??'').split(path.delimiter).filter(dir=>{
63
+ if(!dir||!path.isAbsolute(dir))return false;
64
+ try{return !inside(root,fs.realpathSync(dir));}catch{return false;}
65
+ }).join(path.delimiter);
66
+ const env={PATH:safePath,HOME:os.tmpdir(),USERPROFILE:os.tmpdir(),TMPDIR:os.tmpdir(),TMP:os.tmpdir(),TEMP:os.tmpdir(),
67
+ LANG:'C.UTF-8',LC_ALL:'C.UTF-8',GIT_NO_REPLACE_OBJECTS:'1',GIT_NO_LAZY_FETCH:'1',GIT_TERMINAL_PROMPT:'0',
68
+ GIT_CONFIG_NOSYSTEM:'1',GIT_CONFIG_GLOBAL:os.devNull};
69
+ const run=args=>spawnSync(bin,['--no-optional-locks','-c','core.fsmonitor=false','-C',root,...args],
70
+ {env,timeout:10000,maxBuffer:16*1024*1024});
71
+ const ruleBytes=file=>{
72
+ let fd;
73
+ try{
74
+ const before=fs.lstatSync(file,{bigint:true});
75
+ if(!before.isFile()||before.isSymbolicLink()||before.nlink!==1n||before.size>1024n*1024n)throw Error('unsafe_ignore_rule');
76
+ fd=fs.openSync(file,fs.constants.O_RDONLY|(fs.constants.O_NOFOLLOW??0));
77
+ if(statKey(before)!==statKey(fs.fstatSync(fd,{bigint:true})))throw Error('unsafe_ignore_rule');
78
+ const bytes=Buffer.alloc(Number(before.size)+1),count=fs.readSync(fd,bytes,0,bytes.length,0);
79
+ if(count!==Number(before.size)||statKey(before)!==statKey(fs.fstatSync(fd,{bigint:true}))
80
+ ||statKey(before)!==statKey(fs.lstatSync(file,{bigint:true})))throw Error('unsafe_ignore_rule');
81
+ return bytes.subarray(0,count);
82
+ }finally{if(fd!==undefined)fs.closeSync(fd);}
83
+ };
84
+ try {
85
+ const top=run(['rev-parse','--show-toplevel']);
86
+ if(top.error||top.status!==0)return null;
87
+ const worktree=fs.realpathSync(top.stdout.toString('utf8').trim());
88
+ if(!inside(worktree,root))return null;
89
+ const result=run(['ls-files','--others','--ignored','--exclude-standard','--directory','-z']);
90
+ const agents=run(['ls-files','--cached','--others','--exclude-standard','-z','--','AGENTS.md','**/AGENTS.md']);
91
+ const ignoredAgents=run(['ls-files','--others','--ignored','--exclude-standard','-z','--','AGENTS.md','**/AGENTS.md']);
92
+ const rules=run(['ls-files','--cached','--others','--exclude-standard','-z','--','.gitignore','**/.gitignore']);
93
+ const ignoredRules=run(['ls-files','--others','--ignored','--exclude-standard','-z','--','.gitignore','**/.gitignore']);
94
+ const config=run(['config','--local','--list','--null']);
95
+ const excludesFile=run(['config',...(legacy?['--local']:[]),'--path','--get','core.excludesfile']);
96
+ if([result,agents,ignoredAgents,rules,ignoredRules,config].some(row=>row.error||row.status!==0)
97
+ ||excludesFile.error||![0,1].includes(excludesFile.status))return null;
98
+ const entries=result.stdout.toString('utf8').split('\0').filter(Boolean);
99
+ const ignoredDirectories=new Set(entries.filter(p=>p.endsWith('/')).map(p=>p.slice(0,-1)));
100
+ const ignored=new Set(entries
101
+ .map(p=>p.endsWith('/')?p.slice(0,-1):p));
102
+ const agentPaths=new Set([agents,ignoredAgents].flatMap(row=>row.stdout.toString('utf8').split('\0').filter(Boolean)));
103
+ const names=[...new Set([rules,ignoredRules].flatMap(row=>row.stdout.toString('utf8').split('\0').filter(Boolean)))].sort();
104
+ const input=names.map(name=>[name,sha(ruleBytes(path.join(root,name)))]);
105
+ // Git resolves rules from the worktree root down to this code root. Bind
106
+ // every ancestor, including absent files, so a later rule cannot silently
107
+ // change the checked surface of a split-root project.
108
+ for(let directory=worktree;inside(directory,root)&&directory!==root;directory=path.join(directory,path.relative(directory,root).split(path.sep)[0])){
109
+ const file=path.join(directory,'.gitignore');
110
+ input.push([`ancestor:${path.relative(worktree,file)}`,fs.existsSync(file)?sha(ruleBytes(file)):null]);
111
+ }
112
+ let coreExcludesFile=null;
113
+ if(excludesFile.status===0){
114
+ const configured=excludesFile.stdout.toString('utf8').trim();
115
+ if(!configured||!path.isAbsolute(configured))return null;
116
+ coreExcludesFile={valueDigest:sha(configured),sha256:fs.existsSync(configured)?sha(ruleBytes(configured)):null};
117
+ input.push(['core.excludesFile',coreExcludesFile.sha256]);
118
+ }
119
+ const gitDir=run(['rev-parse','--absolute-git-dir']);
120
+ if(gitDir.error||gitDir.status!==0)return null;
121
+ const exclude=path.join(gitDir.stdout.toString('utf8').trim(),'info','exclude');
122
+ if(fs.existsSync(exclude))input.push(['.git/info/exclude',sha(ruleBytes(exclude))]);
123
+ return {ignored,ignoredDirectories,agentPaths,coreExcludesFile,sources:input.map(([name,hash])=>({path:name,sha256:hash})),
124
+ configDigest:sha(config.stdout),worktreeDigest:sha(worktree),
125
+ sourceDigest:digest({rules:input,config:sha(config.stdout),worktree:sha(worktree)})};
126
+ }catch{return null;}
127
+ }
128
+ function ignorePolicy(root){
129
+ const git=gitIgnore(root,true);
130
+ return {version:1,builtinDigest:digest({directories:[...junkDirectories].sort(),files:['.DS_Store','._*','Thumbs.db','*.xcuserstate']}),
131
+ gitSourceDigest:git?.sourceDigest??null,gitSources:git?.sources??null,
132
+ gitConfigDigest:git?.configDigest??null,gitWorktreeDigest:git?.worktreeDigest??null,
133
+ ignored:git?.ignored??new Set(),
134
+ ignoredDirectories:git?.ignoredDirectories??new Set(),agentPaths:git?.agentPaths??new Set()};
135
+ }
136
+ const builtinDigest=()=>digest({directories:[...junkDirectories].sort(),files:['.DS_Store','._*','Thumbs.db','*.xcuserstate']});
137
+ // Version 2 records decisions, not mutable rule inputs. The size bound is part
138
+ // of the decision: an oversized Git inventory uses only the fixed junk list.
139
+ function stableIgnorePolicy(root,builtinOnly=false){
140
+ const git=builtinOnly?null:gitIgnore(root);
141
+ const ignoredPaths=git?[...git.ignored].sort():[];
142
+ const ignoredDirectories=git?[...git.ignoredDirectories].sort():[];
143
+ let bounded=ignoredPaths.length<=IGNORE_COUNT
144
+ &&Buffer.byteLength(JSON.stringify([ignoredPaths,ignoredDirectories]))<=IGNORE_BYTES;
145
+ if(bounded)try{[...ignoredPaths,...ignoredDirectories].forEach(filePath);}catch{bounded=false;}
146
+ const mode=builtinOnly?'builtin_limit':!git?'builtin':bounded?'git':'builtin_limit';
147
+ return {version:2,builtinDigest:builtinDigest(),mode,
148
+ ignoredPaths:mode==='git'?ignoredPaths:[],
149
+ ignoredDirectories:mode==='git'?ignoredDirectories:[],
150
+ coreExcludesFile:mode==='git'?git.coreExcludesFile:null,
151
+ ignored:new Set(mode==='git'?ignoredPaths:[]),
152
+ agentPaths:git?.agentPaths??new Set(),gitSourceDigest:mode==='git'?git.sourceDigest:null};
153
+ }
154
+ const stablePublicPolicy=policy=>({version:2,builtinDigest:policy.builtinDigest,mode:policy.mode,
155
+ ignoredPaths:policy.ignoredPaths,ignoredDirectories:policy.ignoredDirectories,
156
+ coreExcludesFile:policy.coreExcludesFile});
157
+ function stableSnapshotPolicy(root,baseline,current=stableIgnorePolicy(root,baseline.mode==='builtin_limit')){
158
+ return {ignored:new Set([...baseline.ignoredPaths,...current.ignoredPaths]),
159
+ ignoredDirectories:new Set([...baseline.ignoredDirectories,...current.ignoredDirectories]),
160
+ agentPaths:current.agentPaths,gitSourceDigest:current.gitSourceDigest};
161
+ }
162
+ function ignoredByPolicy(p,policy){
163
+ return policy.ignored.has(p)||[...policy.ignoredDirectories].some(dir=>p.startsWith(dir+'/'))
164
+ ||junkFile(p.split('/').at(-1))||p.split('/').some(part=>junkDirectories.has(part.toLowerCase()));
165
+ }
166
+ function comparableFiles(files,policy,protectedPaths){
167
+ return files.filter(file=>protectedPaths.has(file.path)||file.path.split('/').at(-1)==='AGENTS.md'
168
+ ||!ignoredByPolicy(file.path,policy));
169
+ }
170
+ const publicPolicy=policy=>({version:policy.version,builtinDigest:policy.builtinDigest,
171
+ gitSourceDigest:policy.gitSourceDigest,gitSources:policy.gitSources,
172
+ gitConfigDigest:policy.gitConfigDigest,gitWorktreeDigest:policy.gitWorktreeDigest});
173
+ function validatePolicySources(value){
174
+ need(value===null||Array.isArray(value)&&value.length<=10000);
175
+ if(value===null)return;
176
+ const seen=new Set();
177
+ for(const row of value){keys(row,['path','sha256']);
178
+ need(typeof row.path==='string'&&row.path.length>0&&row.path.length<=4096
179
+ &&!/[\r\n\0]/.test(row.path)&&!seen.has(row.path));seen.add(row.path);
180
+ need(row.sha256===null||/^[a-f0-9]{64}$/.test(row.sha256));}
181
+ }
182
+ function validateStablePolicy(value){
183
+ keys(value,['version','builtinDigest','mode','ignoredPaths','ignoredDirectories','coreExcludesFile']);
184
+ need(value.version===2);hex(value.builtinDigest);
185
+ need(['git','builtin','builtin_limit'].includes(value.mode));
186
+ for(const field of ['ignoredPaths','ignoredDirectories']){
187
+ need(Array.isArray(value[field])&&value[field].length<=IGNORE_COUNT);
188
+ let previous=null;
189
+ for(const p of value[field]){
190
+ filePath(p);need(previous===null||previous<p);previous=p;
191
+ }
192
+ }
193
+ need(Buffer.byteLength(JSON.stringify([value.ignoredPaths,value.ignoredDirectories]))<=IGNORE_BYTES);
194
+ need(value.mode==='git'||value.ignoredPaths.length===0&&value.ignoredDirectories.length===0);
195
+ if(value.coreExcludesFile!==null){
196
+ need(value.mode==='git');keys(value.coreExcludesFile,['valueDigest','sha256']);
197
+ hex(value.coreExcludesFile.valueDigest);
198
+ need(value.coreExcludesFile.sha256===null||/^[a-f0-9]{64}$/.test(value.coreExcludesFile.sha256));
199
+ }
200
+ }
201
+ function policyDifferencePaths(current,expected){
202
+ const before=new Map((expected?.gitSources??[]).map(row=>[row.path,row.sha256]));
203
+ const after=new Map((current?.gitSources??[]).map(row=>[row.path,row.sha256]));
204
+ const changed=[...new Set([...before.keys(),...after.keys()])].filter(p=>before.get(p)!==after.get(p));
205
+ if(current?.builtinDigest!==expected?.builtinDigest)changed.push('built-in ignore list');
206
+ if(current?.gitConfigDigest!==expected?.gitConfigDigest)changed.push('.git/config');
207
+ if(current?.gitWorktreeDigest!==expected?.gitWorktreeDigest)changed.push('Git worktree root');
208
+ if(current?.gitSourceDigest!==expected?.gitSourceDigest&&!changed.length)changed.push('Git ignore policy');
209
+ return changed.sort().slice(0,20);
210
+ }
211
+ const diagnostic=(code,p,detail='')=>{
212
+ const error=new Error(`${code}: ${p}${detail?` (${detail})`:''}`);error.code=code;error.paths=[p];return error;
213
+ };
42
214
  const fail = code => { const error=new Error(code); error.code=code; throw error; };
43
215
  const need = (condition,code='invalid_input') => { if(!condition) fail(code); };
44
216
  const record = v => v!==null && typeof v==='object' && !Array.isArray(v);
@@ -121,7 +293,8 @@ function readFile(root,p,includeContent=true,limit=FILE_LIMIT,contentLimit=limit
121
293
  return {path:p,type:'file',mode:Number(before.mode & 0o7777n),size:offset,
122
294
  sha256:hash.digest('hex'),...(includeContent?{contentBase64:Buffer.concat(chunks).toString('base64')}:{})};
123
295
  } catch(error) {
124
- if(['unsupported_file','limit_exceeded','snapshot_changed'].includes(error.code))throw error;
296
+ if(['unsupported_file','limit_exceeded','snapshot_changed'].includes(error.code))throw diagnostic(error.code,p,
297
+ error.code==='limit_exceeded'?`file bytes > ${limit}`:'');
125
298
  fail('read_failed');
126
299
  } finally { if(fd!==undefined) fs.closeSync(fd); }
127
300
  }
@@ -132,26 +305,40 @@ export function reviewSpecsPath(root,specsRoot) {
132
305
  need(root!==specsRoot&&!root.startsWith(specsRoot+path.sep),'overlapping_roots');
133
306
  return specsRoot.startsWith(root+path.sep)?filePath(path.relative(root,specsRoot).split(path.sep).join('/')):null;
134
307
  }
135
- function snapshot(root,specsPath=null,projectPaths=null,retainedPaths=[],selected=null) {
308
+ function snapshot(root,specsPath=null,projectPaths=null,retainedPaths=[],selected=null,policy=null) {
136
309
  if(specsPath!==null){
137
310
  const target=path.join(root,specsPath);
138
311
  need(fs.realpathSync(target)===target&&fs.lstatSync(target).isDirectory(),'unsupported_path');
139
312
  }
140
- const files=[],seen=new Set(); let total=0,materialBytes=0,materialCount=0;
313
+ const files=[],seen=new Set(); let total=0,materialBytes=0,materialCount=0,visitedSpecs=false;
141
314
  function add(p,s){
142
- need(s.isFile()&&!s.isSymbolicLink()&&s.nlink===1,'unsupported_file');
315
+ if(!s.isFile()||s.isSymbolicLink()||s.nlink!==1)throw diagnostic('unsupported_file',p);
143
316
  const includeContent=selected===null||materialPath(p,selected);
144
317
  const countLimit=selected===null?FILE_COUNT:INVENTORY_COUNT;
145
318
  const byteLimit=selected===null?SNAPSHOT_LIMIT:INVENTORY_LIMIT;
146
- need(files.length<countLimit&&total+s.size<=byteLimit,'limit_exceeded');
147
- if(includeContent)need(materialCount<FILE_COUNT&&materialBytes+s.size<=SNAPSHOT_LIMIT,'limit_exceeded');
319
+ if(files.length>=countLimit)throw diagnostic('limit_exceeded',p,`file count > ${countLimit}`);
320
+ if(total+s.size>byteLimit)throw diagnostic('limit_exceeded',p,`inventory bytes > ${byteLimit}`);
321
+ if(includeContent&&materialCount>=FILE_COUNT)
322
+ throw diagnostic('limit_exceeded',p,`material file count > ${FILE_COUNT}`);
323
+ if(includeContent&&materialBytes+s.size>SNAPSHOT_LIMIT)
324
+ throw diagnostic('limit_exceeded',p,`material bytes ${materialBytes}+${s.size} > ${SNAPSHOT_LIMIT}; scope, requirements and AGENTS.md content count`);
148
325
  const f=readFile(root,p,includeContent,includeContent?Math.min(FILE_LIMIT,SNAPSHOT_LIMIT-materialBytes):byteLimit-total);
149
326
  total+=f.size;
150
327
  if(includeContent){materialBytes+=f.size;materialCount++;}
151
328
  files.push(f);
152
329
  }
330
+ function retainIgnoredInstructions(dir,depth=0){
331
+ if(depth>32)throw diagnostic('limit_exceeded',dir,'instruction search depth > 32');
332
+ let names;try{names=fs.readdirSync(path.join(root,dir)).sort();}catch{throw diagnostic('read_failed',dir);}
333
+ for(const name of names){
334
+ const p=dir+'/'+name;
335
+ let stat;try{stat=fs.lstatSync(path.join(root,p));}catch{throw diagnostic('read_failed',p);}
336
+ if(name==='AGENTS.md')add(p,stat);
337
+ else if(stat.isDirectory()&&!stat.isSymbolicLink())retainIgnoredInstructions(p,depth+1);
338
+ }
339
+ }
153
340
  function walk(rel='',depth=0,codeRoot='') {
154
- need(depth<=32,'limit_exceeded');
341
+ if(depth>32)throw diagnostic('limit_exceeded',rel,`directory depth > 32`);
155
342
  let names;
156
343
  try { names=fs.readdirSync(path.join(root,rel)).sort(); } catch { fail('read_failed'); }
157
344
  for(const name of names) {
@@ -162,9 +349,29 @@ function snapshot(root,specsPath=null,projectPaths=null,retainedPaths=[],selecte
162
349
  // Scope and requirement paths still cannot select any .git entry.
163
350
  if(p===(codeRoot?codeRoot+'/.git':'.git') && !s.isSymbolicLink()
164
351
  && (s.isDirectory() || (s.isFile() && s.nlink===1))) continue;
352
+ const protectedPath=selected?.has(p)||retainedPaths.includes(p)||name==='AGENTS.md'
353
+ ||specsPath!==null&&(specsPath===p||specsPath.startsWith(p+'/'))
354
+ ||[...selected??[],...retainedPaths,...policy?.agentPaths??[]].some(item=>item===p||item.startsWith(p+'/'));
355
+ const gitIgnored=policy?.ignored.has(p)||[...policy?.ignoredDirectories??[]].some(dir=>p.startsWith(dir+'/'));
356
+ const builtinIgnored=p.split('/').some(part=>junkDirectories.has(part.toLowerCase()));
357
+ if(policy&&!protectedPath&&(junkFile(name)||builtinIgnored
358
+ ||gitIgnored)){
359
+ // Git's ignored AGENTS path query protects deeper instructions without
360
+ // entering generated output. Without Git, search names only so an
361
+ // instruction can never be silently excluded by the fixed junk list.
362
+ if(s.isDirectory()){
363
+ if(policy.gitSourceDigest===null)retainIgnoredInstructions(p);
364
+ else{
365
+ const instruction=p+'/AGENTS.md';
366
+ try{add(instruction,fs.lstatSync(path.join(root,instruction)));}
367
+ catch(error){if(error.code!=='ENOENT')throw error;}
368
+ }
369
+ }
370
+ continue;
371
+ }
165
372
  filePath(p);
166
373
  const alias=p.toLowerCase(); need(!seen.has(alias),'unsupported_path'); seen.add(alias);
167
- if(p===specsPath){need(s.isDirectory()&&!s.isSymbolicLink(),'unsupported_path');continue;}
374
+ if(p===specsPath){need(s.isDirectory()&&!s.isSymbolicLink(),'unsupported_path');visitedSpecs=true;continue;}
168
375
  // Never follow a dependency-root symlink. Old baselines that captured
169
376
  // these files still verify their original material instead of dropping it.
170
377
  if(s.isDirectory()&&(dependencyDirectories.has(name.toLowerCase())||isCocoaPodsRoot(path.join(root,p)))
@@ -173,7 +380,7 @@ function snapshot(root,specsPath=null,projectPaths=null,retainedPaths=[],selecte
173
380
  else add(p,s);
174
381
  }
175
382
  }
176
- if(projectPaths===null)walk();
383
+ if(projectPaths===null){walk();if(specsPath!==null)need(visitedSpecs,'protected_specs');}
177
384
  else{
178
385
  const roots=projectPaths.map(prefix=>path.join(root,prefix));
179
386
  resolveCodeProjects(root,roots);
@@ -187,12 +394,58 @@ function snapshot(root,specsPath=null,projectPaths=null,retainedPaths=[],selecte
187
394
  }
188
395
  return files.sort((a,b)=>a.path<b.path?-1:a.path>b.path?1:0);
189
396
  }
397
+ export function captureReviewInventory(root,baseline){
398
+ validBaseline(baseline);
399
+ const stable=baseline.ignorePolicy?.version===2;
400
+ const policy=stable?stableSnapshotPolicy(root,baseline.ignorePolicy)
401
+ :Object.hasOwn(baseline,'ignorePolicy')?ignorePolicy(root):null;
402
+ return snapshot(root,baseline.specsPath??null,baseline.codeProjectPaths??null,
403
+ stable?[]:baseline.files.map(file=>file.path),new Set(),policy)
404
+ .map(file=>({path:file.path,sha256:file.sha256}));
405
+ }
406
+ // withMode also reports permission-only changes; the mode is part of a reviewed
407
+ // file record. The default keeps the historical content-only comparison.
408
+ export function compareReviewInventoryToBaseline(root,baseline,{withMode=false}={}){
409
+ validBaseline(baseline);
410
+ const stable=baseline.ignorePolicy?.version===2;
411
+ const policy=stable?stableSnapshotPolicy(root,baseline.ignorePolicy)
412
+ :Object.hasOwn(baseline,'ignorePolicy')?ignorePolicy(root):null;
413
+ const before=stable?comparableFiles(baseline.files,policy,new Set([...baseline.scope,...baseline.requirements])):baseline.files;
414
+ const after=snapshot(root,baseline.specsPath??null,baseline.codeProjectPaths??null,
415
+ stable?[]:baseline.files.map(file=>file.path),new Set(),policy);
416
+ const key=file=>withMode?`${file.sha256}:${file.mode}`:file.sha256;
417
+ const previous=new Map(before.map(file=>[file.path,key(file)]));
418
+ const current=new Map(after.map(file=>[file.path,key(file)]));
419
+ const records=new Map(after.map(file=>[file.path,file]));
420
+ return [...new Set([...previous.keys(),...current.keys()])].filter(p=>previous.get(p)!==current.get(p))
421
+ .map(p=>({path:p,sha256:records.get(p)?.sha256??null,...(withMode?{mode:records.get(p)?.mode??null}:{})}));
422
+ }
423
+ export function compareReviewBaseline(current,expected){
424
+ if(digest(current)===digest(expected))return true;
425
+ const stable=current.ignorePolicy?.version===2&&expected.ignorePolicy?.version===2;
426
+ const useGit=stable&&expected.ignorePolicy.mode!=='builtin_limit';
427
+ const policy=stable?{ignored:new Set(useGit?[...current.ignorePolicy.ignoredPaths,...expected.ignorePolicy.ignoredPaths]:[]),
428
+ ignoredDirectories:new Set(useGit?[...current.ignorePolicy.ignoredDirectories,...expected.ignorePolicy.ignoredDirectories]:[])}:null;
429
+ const protectedPaths=new Set([...expected.scope,...expected.requirements]);
430
+ const before=new Map((stable?comparableFiles(expected.files,policy,protectedPaths):expected.files).map(file=>[file.path,digest(file)]));
431
+ const after=new Map((stable?comparableFiles(current.files,policy,protectedPaths):current.files).map(file=>[file.path,digest(file)]));
432
+ const paths=[...new Set([...before.keys(),...after.keys()])].filter(p=>before.get(p)!==after.get(p)).sort();
433
+ if(!stable&&digest(current.ignorePolicy??null)!==digest(expected.ignorePolicy??null))paths.push(...policyDifferencePaths(current.ignorePolicy,expected.ignorePolicy));
434
+ if(stable){
435
+ const metadata=value=>{const {ignorePolicy,files,baselineDigest,...rest}=value;return rest;};
436
+ if(digest(metadata(current))!==digest(metadata(expected)))paths.push('baseline metadata');
437
+ }
438
+ if(stable&&!paths.length)return true;
439
+ if(!paths.length)paths.push('baseline metadata');
440
+ const error=new Error(`package_mismatch: ${paths.slice(0,20).join(', ')}${paths.length>20?` (+${paths.length-20} more)`:''}`);
441
+ error.code='package_mismatch';error.paths=paths;throw error;
442
+ }
190
443
  const sealed = (data,key) => {
191
444
  const result={...data,[key]:digest(data)};
192
445
  need(Buffer.byteLength(JSON.stringify(result))<=8*1024*1024,'limit_exceeded');
193
446
  return freeze(result);
194
447
  };
195
- export function captureReviewBaseline(options) {
448
+ export function captureReviewBaseline(options,legacy=false,policyVersion=2,baselinePolicy=null) {
196
449
  const v=plain(options); keys(v,['root','identity','scope','requirements',
197
450
  ...['specsRoot','codeProjectPaths','bootstrapRequirements','specification','version'].filter(key=>Object.hasOwn(v,key))]); identityCheck(v.identity);
198
451
  const version=v.version??2;need([1,2].includes(version));
@@ -218,7 +471,12 @@ export function captureReviewBaseline(options) {
218
471
  if(specsPath!==null)validateProjectSpecs(specsPath,projectPaths);
219
472
  assertCodeProjectSelections(projectPaths,[...scope,...requirements],{allowInstructions:true});
220
473
  }
221
- const files=snapshot(root,specsPath,projectPaths,[],version===1?null:new Set([...scope,...requirements]));
474
+ need([1,2].includes(policyVersion));
475
+ if(baselinePolicy!==null){need(policyVersion===2);validateStablePolicy(baselinePolicy);}
476
+ const policy=legacy||version===1?null:policyVersion===1?ignorePolicy(root)
477
+ :stableIgnorePolicy(root,baselinePolicy?.mode==='builtin_limit');
478
+ const snapshotPolicy=baselinePolicy===null?policy:stableSnapshotPolicy(root,baselinePolicy,policy);
479
+ const files=snapshot(root,specsPath,projectPaths,[],version===1?null:new Set([...scope,...requirements]),snapshotPolicy);
222
480
  need(requirements.every(p=>files.some(f=>f.path===p)),'read_failed');
223
481
  for(const p of scope) {
224
482
  const absolute=path.join(root,p);
@@ -228,7 +486,8 @@ export function captureReviewBaseline(options) {
228
486
  scope,requirements,files,...(specsPath===null?{}:{specsPath}),
229
487
  ...(projectPaths===null?{}:{codeProjectPaths:projectPaths}),
230
488
  ...(bootstrap===null?{}:{bootstrapRequirements:bootstrap}),
231
- ...(specification===null?{}:{specification,specificationRoot:v.specification.specsRoot})},'baselineDigest');
489
+ ...(specification===null?{}:{specification,specificationRoot:v.specification.specsRoot}),
490
+ ...(policy===null?{}:{ignorePolicy:policyVersion===1?publicPolicy(policy):stablePublicPolicy(policy)})},'baselineDigest');
232
491
  }
233
492
 
234
493
  // Bounded selected-file material for pre-implementation reviews; no whole-tree scan.
@@ -310,20 +569,20 @@ function inventoryList(b) {
310
569
  if(material.length)fileList(material);
311
570
  need(Buffer.byteLength(JSON.stringify(b))<=8*1024*1024,'limit_exceeded');
312
571
  }
313
- const bootstrapPaths=['0.bootstrap/design.md','0.bootstrap/requirements.md'];
572
+ const bootstrapPaths=feature=>[`${feature}/design.md`,`${feature}/requirements.md`];
314
573
  function validBootstrapRequirements(value,published=false){
315
574
  keys(value,['feature','files',published?'rootDigest':'specsRoot']);
316
- need(value.feature==='0.bootstrap','bootstrap_requirements_invalid');
575
+ need(value.feature===identifyApprovedBootstrapFeature([value.feature]),'bootstrap_requirements_invalid');
317
576
  if(published)hex(value.rootDigest);
318
577
  else need(typeof value.specsRoot==='string'&&path.isAbsolute(value.specsRoot)
319
578
  &&path.resolve(value.specsRoot)===value.specsRoot&&!value.specsRoot.includes('\0'),'unsupported_path');
320
579
  fileList(value.files);
321
- need(digest(value.files.map(file=>file.path))===digest(bootstrapPaths)
580
+ need(digest(value.files.map(file=>file.path))===digest(bootstrapPaths(value.feature))
322
581
  &&value.files.every(file=>file.size>0),'bootstrap_requirements_invalid');
323
582
  }
324
583
  function currentBootstrapRequirements(value){
325
584
  need(fs.realpathSync(value.specsRoot)===value.specsRoot,'unsupported_path');
326
- const files=readReviewSourceFiles(value.specsRoot,bootstrapPaths);
585
+ const files=readReviewSourceFiles(value.specsRoot,bootstrapPaths(value.feature));
327
586
  need(digest(files)===digest(value.files),'bootstrap_requirements_changed');
328
587
  return {feature:value.feature,files:value.files,rootDigest:sha(value.specsRoot)};
329
588
  }
@@ -333,8 +592,19 @@ export function readReviewSourceRecords(raw){
333
592
  function validBaseline(b) {
334
593
  try {
335
594
  keys(b,['version','kind','identity','rootDigest','scope','requirements','files','baselineDigest',
336
- ...['specsPath','codeProjectPaths','bootstrapRequirements','specification','specificationRoot'].filter(key=>Object.hasOwn(b,key))]);
595
+ ...['specsPath','codeProjectPaths','bootstrapRequirements','specification','specificationRoot','ignorePolicy'].filter(key=>Object.hasOwn(b,key))]);
337
596
  need([1,2].includes(b.version) && b.kind==='cm-review-baseline'); identityCheck(b.identity); hex(b.rootDigest);
597
+ if(Object.hasOwn(b,'ignorePolicy')){
598
+ if(b.ignorePolicy.version===2)validateStablePolicy(b.ignorePolicy);
599
+ else{
600
+ keys(b.ignorePolicy,['version','builtinDigest','gitSourceDigest','gitSources','gitConfigDigest','gitWorktreeDigest']);
601
+ need(b.ignorePolicy.version===1);hex(b.ignorePolicy.builtinDigest);
602
+ need(b.ignorePolicy.gitSourceDigest===null||/^[a-f0-9]{64}$/.test(b.ignorePolicy.gitSourceDigest));
603
+ need(b.ignorePolicy.gitConfigDigest===null||/^[a-f0-9]{64}$/.test(b.ignorePolicy.gitConfigDigest));
604
+ need(b.ignorePolicy.gitWorktreeDigest===null||/^[a-f0-9]{64}$/.test(b.ignorePolicy.gitWorktreeDigest));
605
+ validatePolicySources(b.ignorePolicy.gitSources);
606
+ }
607
+ }
338
608
  need(Object.hasOwn(b,'specification')===Object.hasOwn(b,'specificationRoot'));
339
609
  if(Object.hasOwn(b,'specification')){
340
610
  readSpecificationMaterial(b.specification,b.identity.taskId);
@@ -355,7 +625,7 @@ function validBaseline(b) {
355
625
  const {baselineDigest,...data}=b; hex(baselineDigest); need(digest(data)===baselineDigest);
356
626
  } catch { fail('invalid_baseline'); }
357
627
  }
358
- function validChecks(checks) {
628
+ export function validChecks(checks) {
359
629
  need(Array.isArray(checks) && checks.length>0);
360
630
  need(Buffer.byteLength(JSON.stringify(checks))<=64*1024,'limit_exceeded');
361
631
  const ids=new Set();
@@ -383,21 +653,55 @@ function validChecks(checks) {
383
653
  || c.outcome==='unavailable' && c.exitCode===null);
384
654
  }
385
655
  }
386
- export function createReviewPackage(options) {
387
- const v=plain(options); keys(v,['root','baseline','checks',...(Object.hasOwn(v,'handoffPath')?['handoffPath']:[])]); const b=v.baseline;
388
- validBaseline(b); validChecks(v.checks);
656
+ // The one selection a review package snapshot uses: its policy, retained paths
657
+ // and material (scope, requirements, earlier material and every AGENTS.md).
658
+ const packagePolicy=(root,b)=>b.ignorePolicy?.version===2?stableSnapshotPolicy(root,b.ignorePolicy)
659
+ :Object.hasOwn(b,'ignorePolicy')?ignorePolicy(root):null;
660
+ function packageSnapshot(root,b,policy){
661
+ const selected=b.version===1?null:new Set([...b.scope,...b.requirements,
662
+ ...b.files.filter(f=>Object.hasOwn(f,'contentBase64')).map(f=>f.path)]);
663
+ return snapshot(root,b.specsPath??null,b.codeProjectPaths??null,b.ignorePolicy?.version===2?[]:b.files.map(f=>f.path),selected,policy);
664
+ }
665
+ // Read-only: path and size of every material body a package built from the
666
+ // current tree would carry. Callers use it to refuse a delivery before writing it.
667
+ export function reviewMaterialSizes(options){
668
+ const v=plain(options);keys(v,['root','baseline']);const b=v.baseline;validBaseline(b);
669
+ const root=rootPath(v.root);need(sha(root)===b.rootDigest,'invalid_baseline');
670
+ return freeze(packageSnapshot(root,b,packagePolicy(root,b)).filter(f=>Object.hasOwn(f,'contentBase64'))
671
+ .map(f=>({path:f.path,size:f.size})));
672
+ }
673
+ // Validation, specification, policy and bootstrap material a package is built
674
+ // with, shared by the real and the projected package so both use one assembly.
675
+ function packageContext(v){
676
+ const b=v.baseline;validBaseline(b); validChecks(v.checks);
389
677
  const specification=Object.hasOwn(b,'specification')?verifySpecificationMaterial(b):null;
390
678
  const root=rootPath(v.root); need(sha(root)===b.rootDigest,'invalid_baseline');
679
+ const stable=b.ignorePolicy?.version===2;
680
+ const policy=packagePolicy(root,b);
681
+ if(policy&&!stable&&digest(publicPolicy(policy))!==digest(b.ignorePolicy)){
682
+ const changed=policyDifferencePaths(publicPolicy(policy),b.ignorePolicy);
683
+ throw diagnostic('package_mismatch',changed.join(', ')||'ignore policy','ignore policy changed');
684
+ }
391
685
  const bootstrap=Object.hasOwn(b,'bootstrapRequirements')?currentBootstrapRequirements(b.bootstrapRequirements):null;
392
686
  if(bootstrap!==null)need(reviewSpecsPath(root,b.bootstrapRequirements.specsRoot)===(b.specsPath??null),'bootstrap_requirements_mismatch');
393
- const selected=b.version===1?null:new Set([...b.scope,...b.requirements,
394
- ...b.files.filter(f=>Object.hasOwn(f,'contentBase64')).map(f=>f.path)]);
395
- const files=snapshot(root,b.specsPath??null,b.codeProjectPaths??null,b.files.map(f=>f.path),selected),before=new Map(b.files.map(f=>[f.path,f])),after=new Map(files.map(f=>[f.path,f]));
396
- const changes=[];
687
+ return {b,root,stable,policy,specification,bootstrap};
688
+ }
689
+ function assemblePackage({b,stable,policy,specification,bootstrap},files,checks,handoff){
690
+ const protectedPaths=new Set([...b.scope,...b.requirements]);
691
+ const before=new Map((stable?comparableFiles(b.files,policy,protectedPaths):b.files).map(f=>[f.path,f]));
692
+ const after=new Map(files.map(f=>[f.path,f]));
693
+ const changes=[],violations=[];
397
694
  for(const p of [...new Set([...before.keys(),...after.keys()])].sort()) {
398
695
  const old=before.get(p)??null,current=after.get(p)??null;
399
696
  if(digest(old)===digest(current))continue;
400
- need(b.scope.includes(p),'out_of_scope'); changes.push({path:p,before:old,after:current});
697
+ if(!b.scope.includes(p)){violations.push({path:p,newFile:old===null&&current!==null});continue;}
698
+ changes.push({path:p,before:old,after:current});
699
+ }
700
+ if(violations.length){
701
+ const shown=violations.slice(0,20).map(item=>item.path.length>300?`${item.path.slice(0,300)}…`:item.path);
702
+ const error=new Error(`out_of_scope: ${shown.join(', ')}${violations.length>20?` (+${violations.length-20} more)`:''}`);
703
+ error.code='out_of_scope';error.violations=violations;
704
+ throw error;
401
705
  }
402
706
  need(changes.length>0,'empty_changes');
403
707
  const changedPaths=new Set(changes.map(change=>change.path));
@@ -405,16 +709,50 @@ export function createReviewPackage(options) {
405
709
  .map(p=>({path:p,sha256:after.get(p).sha256}));
406
710
  const requirements=b.requirements.map(p=>{ need(after.has(p),'read_failed'); return after.get(p); });
407
711
  const pkg=sealed({version:1,kind:'cm-review-package',identity:b.identity,rootDigest:b.rootDigest,
408
- baseIdentity:b.baselineDigest,scope:b.scope,changes,unchangedScope,requirements,checks:v.checks,
712
+ baseIdentity:b.baselineDigest,scope:b.scope,changes,unchangedScope,requirements,checks,
409
713
  ...(Object.hasOwn(b,'codeProjectPaths')?{codeProjectPaths:b.codeProjectPaths,
410
714
  instructions:files.filter(file=>file.path.split('/').at(-1)==='AGENTS.md')}:{}),
411
715
  ...(bootstrap===null?{}:{bootstrapRequirements:bootstrap}),
412
716
  ...(specification===null?{}:{specification}),
413
- ...(Object.hasOwn(v,'handoffPath')?{handoff:readHandoffSnapshot(v.handoffPath)}:{}),
414
- artifactDigest:digest(changes),requirementsDigest:digest(requirements),checksDigest:digest(v.checks)},'packageDigest');
717
+ ...(handoff===null?{}:{handoff:handoff()}),
718
+ ...(policy===null?{}:{ignorePolicy:stable?b.ignorePolicy:publicPolicy(policy)}),
719
+ artifactDigest:digest(changes),requirementsDigest:digest(requirements),checksDigest:digest(checks)},'packageDigest');
415
720
  need(Buffer.byteLength(JSON.stringify(pkg))<=8*1024*1024,'limit_exceeded');
416
721
  return pkg;
417
722
  }
723
+ export function createReviewPackage(options) {
724
+ const v=plain(options); keys(v,['root','baseline','checks',...(Object.hasOwn(v,'handoffPath')?['handoffPath']:[])]);
725
+ const context=packageContext(v);
726
+ return assemblePackage(context,packageSnapshot(context.root,context.b,context.policy),v.checks,
727
+ Object.hasOwn(v,'handoffPath')?()=>readHandoffSnapshot(v.handoffPath):null);
728
+ }
729
+ // Read-only: the package the current tree would give once the listed scope files
730
+ // are replaced ({path,contentBase64,mode}, or contentBase64 null to delete),
731
+ // assembled by the same code as createReviewPackage. Nothing is written. The
732
+ // handoff is only known once it exists, so the projection carries none.
733
+ export function projectedReviewPackage(options){
734
+ const v=plain(options);keys(v,['root','baseline','checks','scopeFiles',...(Object.hasOwn(v,'handoff')?['handoff']:[])]);
735
+ const context=packageContext(v);need(Array.isArray(v.scopeFiles),'invalid_input');
736
+ const files=new Map(packageSnapshot(context.root,context.b,context.policy).map(file=>[file.path,file]));
737
+ for(const item of v.scopeFiles){
738
+ keys(item,['path','contentBase64','mode']);need(context.b.scope.includes(item.path),'out_of_scope');
739
+ if(item.contentBase64===null){need(item.mode===null);files.delete(item.path);continue;}
740
+ need(typeof item.contentBase64==='string'&&Number.isInteger(item.mode)&&item.mode>=0&&item.mode<=0o7777);
741
+ const bytes=Buffer.from(item.contentBase64,'base64');need(bytes.toString('base64')===item.contentBase64);
742
+ files.set(item.path,{path:item.path,type:'file',mode:item.mode,size:bytes.length,sha256:sha(bytes),contentBase64:item.contentBase64});
743
+ }
744
+ // A projected handoff ({name,contentBase64,mode}) takes the record shape the
745
+ // package reads back from the published file.
746
+ let handoff=null;
747
+ if(Object.hasOwn(v,'handoff')){
748
+ keys(v.handoff,['name','contentBase64','mode']);const name=filePath(v.handoff.name);need(!name.includes('/'));
749
+ need(Number.isInteger(v.handoff.mode)&&v.handoff.mode>=0&&v.handoff.mode<=0o7777);
750
+ const bytes=Buffer.from(v.handoff.contentBase64,'base64');need(bytes.toString('base64')===v.handoff.contentBase64);
751
+ const record={path:name,type:'file',mode:v.handoff.mode,size:bytes.length,sha256:sha(bytes),contentBase64:v.handoff.contentBase64};
752
+ handoff=()=>record;
753
+ }
754
+ return assemblePackage(context,[...files.values()].sort((a,b)=>a.path<b.path?-1:a.path>b.path?1:0),v.checks,handoff);
755
+ }
418
756
  function validPackage(p) {
419
757
  try {
420
758
  keys(p,['version','kind','identity','rootDigest','baseIdentity','scope','changes','requirements',
@@ -423,7 +761,18 @@ function validPackage(p) {
423
761
  ...(Object.hasOwn(p,'specification')?['specification']:[]),
424
762
  ...(Object.hasOwn(p,'handoff')?['handoff']:[]),
425
763
  ...(Object.hasOwn(p,'codeProjectPaths')?['codeProjectPaths','instructions']:[]),
426
- ...(Object.hasOwn(p,'bootstrapRequirements')?['bootstrapRequirements']:[])]);
764
+ ...(Object.hasOwn(p,'bootstrapRequirements')?['bootstrapRequirements']:[]),
765
+ ...(Object.hasOwn(p,'ignorePolicy')?['ignorePolicy']:[])]);
766
+ if(Object.hasOwn(p,'ignorePolicy')){
767
+ if(p.ignorePolicy.version===2)validateStablePolicy(p.ignorePolicy);
768
+ else{
769
+ keys(p.ignorePolicy,['version','builtinDigest','gitSourceDigest','gitSources','gitConfigDigest','gitWorktreeDigest']);need(p.ignorePolicy.version===1);
770
+ hex(p.ignorePolicy.builtinDigest);need(p.ignorePolicy.gitSourceDigest===null||/^[a-f0-9]{64}$/.test(p.ignorePolicy.gitSourceDigest));
771
+ need(p.ignorePolicy.gitConfigDigest===null||/^[a-f0-9]{64}$/.test(p.ignorePolicy.gitConfigDigest));
772
+ need(p.ignorePolicy.gitWorktreeDigest===null||/^[a-f0-9]{64}$/.test(p.ignorePolicy.gitWorktreeDigest));
773
+ validatePolicySources(p.ignorePolicy.gitSources);
774
+ }
775
+ }
427
776
  if(Object.hasOwn(p,'handoff')) {
428
777
  fileRecord(p.handoff);need(!p.handoff.path.includes('/')&&p.handoff.size<=256*1024);
429
778
  }
@@ -481,6 +830,7 @@ export function verifyReviewPackage(options) {
481
830
  need(v.reviewPackage.packageDigest===v.expectedDigest,'package_mismatch');
482
831
  need(Object.hasOwn(v.reviewPackage,'specification')===Object.hasOwn(v.baseline,'specification'),'package_mismatch');
483
832
  need(Object.hasOwn(v.reviewPackage,'handoff')===Object.hasOwn(v,'handoffPath'),'package_mismatch');
833
+ need(digest(v.reviewPackage.ignorePolicy??null)===digest(v.baseline.ignorePolicy??null),'package_mismatch');
484
834
  let current=createReviewPackage({root:v.root,baseline:v.baseline,checks:v.checks,
485
835
  ...(Object.hasOwn(v,'handoffPath')?{handoffPath:v.handoffPath}:{})});
486
836
  // Rebuild the historical representation for legacy receipts, without rewriting them.
@@ -488,10 +838,56 @@ export function verifyReviewPackage(options) {
488
838
  const {unchangedScope,packageDigest,...legacy}=current;
489
839
  current=sealed(legacy,'packageDigest');
490
840
  }
491
- need(current.packageDigest===v.expectedDigest,'package_mismatch');
841
+ if(current.packageDigest!==v.expectedDigest)throw packageMismatch(current,v.reviewPackage);
492
842
  return freeze({outcome:'matched',packageDigest:current.packageDigest});
493
843
  }
494
844
 
845
+ // Completion repeats checks after review. Their diagnostic prose may vary, but
846
+ // every reviewed file, scope and handoff byte and every check result must agree.
847
+ export function verifyCompletionReviewPackage(options) {
848
+ const v=plain(options);keys(v,['root','baseline','checks','reviewPackage','expectedDigest',
849
+ ...(Object.hasOwn(v,'handoffPath')?['handoffPath']:[])]);
850
+ hex(v.expectedDigest);validBaseline(v.baseline);validPackage(v.reviewPackage);
851
+ need(v.reviewPackage.packageDigest===v.expectedDigest,'package_mismatch');
852
+ need(Object.hasOwn(v.reviewPackage,'specification')===Object.hasOwn(v.baseline,'specification'),'package_mismatch');
853
+ need(Object.hasOwn(v.reviewPackage,'handoff')===Object.hasOwn(v,'handoffPath'),'package_mismatch');
854
+ need(digest(v.reviewPackage.ignorePolicy??null)===digest(v.baseline.ignorePolicy??null),'package_mismatch');
855
+ let current=createReviewPackage({root:v.root,baseline:v.baseline,checks:v.checks,
856
+ ...(Object.hasOwn(v,'handoffPath')?{handoffPath:v.handoffPath}:{})});
857
+ if(!Object.hasOwn(v.reviewPackage,'unchangedScope')){
858
+ const {unchangedScope,packageDigest,...legacy}=current;
859
+ current=sealed(legacy,'packageDigest');
860
+ }
861
+ const withoutChecks=({checks,checksDigest,packageDigest,...fields})=>fields;
862
+ if(digest(withoutChecks(current))!==digest(withoutChecks(v.reviewPackage)))throw packageMismatch(current,v.reviewPackage);
863
+ const checkIdentities=checks=>checks.map(c=>c.kind==='visual'
864
+ ?{id:c.id,kind:c.kind}
865
+ :{id:c.id,command:c.command});
866
+ need(digest(checkIdentities(current.checks))===digest(checkIdentities(v.reviewPackage.checks)),'package_mismatch');
867
+ const checkResults=checks=>checks.map(c=>c.kind==='visual'
868
+ ?{outcome:c.outcome}
869
+ :{outcome:c.outcome,exitCode:c.exitCode});
870
+ need(digest(checkResults(current.checks))===digest(checkResults(v.reviewPackage.checks)),'completion_checks_changed');
871
+ const visualCarriers=checks=>checks.filter(c=>c.kind==='visual').map(c=>({before:c.before,after:c.after}));
872
+ need(digest(visualCarriers(current.checks))===digest(visualCarriers(v.reviewPackage.checks)),'package_mismatch');
873
+ return freeze({outcome:'matched',packageDigest:v.expectedDigest});
874
+ }
875
+
876
+ function packageMismatch(current,reviewed){
877
+ const paths=new Set();
878
+ for(const field of ['changes','unchangedScope','requirements','instructions']){
879
+ const before=new Map((reviewed[field]??[]).map(item=>[item.path,digest(item)]));
880
+ const after=new Map((current[field]??[]).map(item=>[item.path,digest(item)]));
881
+ for(const p of new Set([...before.keys(),...after.keys()]))if(before.get(p)!==after.get(p))paths.add(p);
882
+ }
883
+ if(digest(current.handoff??null)!==digest(reviewed.handoff??null))paths.add(current.handoff?.path??reviewed.handoff?.path??'handoff');
884
+ if(digest(current.ignorePolicy??null)!==digest(reviewed.ignorePolicy??null))
885
+ policyDifferencePaths(current.ignorePolicy,reviewed.ignorePolicy).forEach(p=>paths.add(p));
886
+ if(!paths.size)paths.add('review package metadata');
887
+ const names=[...paths].sort();const error=new Error(`package_mismatch: ${names.slice(0,20).join(', ')}${names.length>20?` (+${names.length-20} more)`:''}`);
888
+ error.code='package_mismatch';error.paths=names;return error;
889
+ }
890
+
495
891
  // The host supplies this separate specs-root file; workers never select it.
496
892
  // Reuse the bounded no-follow snapshot reader and store bytes, not a live path.
497
893
  function readHandoffSnapshot(p) {