@aibyzero/cm-workflow 0.16.4 → 0.16.6

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 (283) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +22 -0
  3. package/CHANGELOG.md +57 -0
  4. package/README.md +22 -4
  5. package/THIRD_PARTY_NOTICES.md +9 -0
  6. package/VERSION +1 -1
  7. package/docs/architecture.md +43 -0
  8. package/docs/execution-optimizations.md +33 -0
  9. package/docs/external-models.md +114 -0
  10. package/docs/fixes/.reviews/20260929-bootstrap-unchanged-review-r1.md +7 -0
  11. package/docs/fixes/.reviews/20260930-develop-package-limit-recovery-r4.md +9 -0
  12. package/docs/fixes/20260929-bootstrap-rule-refresh-conflict.md +22 -0
  13. package/docs/fixes/20260929-bootstrap-unchanged-review.md +26 -0
  14. package/docs/fixes/20260930-develop-package-limit-recovery.md +65 -0
  15. package/docs/human-correction.md +31 -0
  16. package/docs/installation.md +48 -7
  17. package/docs/js-workflow-control.md +293 -33
  18. package/docs/live-evidence-drivers.md +62 -0
  19. package/docs/next-steps.md +15 -10
  20. package/docs/runtime-failover.md +1 -1
  21. package/docs/untested-branches.md +27 -4
  22. package/docs/user-guide.md +23 -8
  23. package/install-codex.sh +28 -11
  24. package/package.json +1 -1
  25. package/runtime/js/cm-ai/accepted-fix.mjs +23 -5
  26. package/runtime/js/cm-ai/bootstrap-feature.mjs +15 -0
  27. package/runtime/js/cm-ai/claude-review-adapter.mjs +7 -4
  28. package/runtime/js/cm-ai/claude-review-stream.mjs +12 -0
  29. package/runtime/js/cm-ai/claude-tool-preview.mjs +4 -4
  30. package/runtime/js/cm-ai/cm-ai-admission.mjs +115 -41
  31. package/runtime/js/cm-ai/cm-ai-context-refresh.mjs +3 -2
  32. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +208 -34
  33. package/runtime/js/cm-ai/cm-ai-learning-handoff-writer.mjs +11 -9
  34. package/runtime/js/cm-ai/cm-ai-learning-writer.mjs +22 -5
  35. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +181 -57
  36. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +15 -58
  37. package/runtime/js/cm-ai/codex-config.mjs +3 -2
  38. package/runtime/js/cm-ai/codex-review-adapter.mjs +56 -17
  39. package/runtime/js/cm-ai/committed-rule-basis.mjs +76 -0
  40. package/runtime/js/cm-ai/developer-adapter.mjs +6 -2
  41. package/runtime/js/cm-ai/diagnostic-reason.mjs +10 -0
  42. package/runtime/js/cm-ai/drive-bootstrap.mjs +315 -0
  43. package/runtime/js/cm-ai/drive-core.mjs +47 -9
  44. package/runtime/js/cm-ai/durable-runner-state.mjs +413 -56
  45. package/runtime/js/cm-ai/effect-abandon-log.mjs +19 -0
  46. package/runtime/js/cm-ai/effect-contract.mjs +44 -2
  47. package/runtime/js/cm-ai/execution-policy.mjs +58 -0
  48. package/runtime/js/cm-ai/execution-store-limits.mjs +18 -0
  49. package/runtime/js/cm-ai/execution-store.mjs +6 -4
  50. package/runtime/js/cm-ai/external-group-models.mjs +53 -0
  51. package/runtime/js/cm-ai/external-model-launch.mjs +23 -0
  52. package/runtime/js/cm-ai/external-models.mjs +52 -0
  53. package/runtime/js/cm-ai/external-run-guard.mjs +96 -0
  54. package/runtime/js/cm-ai/fix-code-association.mjs +171 -18
  55. package/runtime/js/cm-ai/host-bootstrap.mjs +126 -29
  56. package/runtime/js/cm-ai/host-check.mjs +30 -4
  57. package/runtime/js/cm-ai/host-conversation-execution.mjs +66 -20
  58. package/runtime/js/cm-ai/host-handoff.mjs +13 -6
  59. package/runtime/js/cm-ai/host-progress.mjs +80 -0
  60. package/runtime/js/cm-ai/host-project-execution.mjs +16 -11
  61. package/runtime/js/cm-ai/host-qa-executor.mjs +23 -9
  62. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +23 -6
  63. package/runtime/js/cm-ai/host-qa-policy.mjs +16 -7
  64. package/runtime/js/cm-ai/host-session.mjs +12 -4
  65. package/runtime/js/cm-ai/host-tool-bridge.mjs +1 -1
  66. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +16 -5
  67. package/runtime/js/cm-ai/host.mjs +1 -1
  68. package/runtime/js/cm-ai/knowledge-closeout.mjs +56 -0
  69. package/runtime/js/cm-ai/launch-mismatch.mjs +42 -0
  70. package/runtime/js/cm-ai/legacy-model-run-preview.mjs +24 -0
  71. package/runtime/js/cm-ai/legacy-model-settings.mjs +59 -0
  72. package/runtime/js/cm-ai/live-evidence.mjs +96 -0
  73. package/runtime/js/cm-ai/log-rows.mjs +21 -0
  74. package/runtime/js/cm-ai/model-configuration-file.mjs +63 -0
  75. package/runtime/js/cm-ai/model_configuration_write.py +214 -0
  76. package/runtime/js/cm-ai/native-usage-log.mjs +26 -0
  77. package/runtime/js/cm-ai/operator-guidance.mjs +86 -0
  78. package/runtime/js/cm-ai/owned-process-cleanup.mjs +22 -0
  79. package/runtime/js/cm-ai/project-qa-gate.mjs +84 -0
  80. package/runtime/js/cm-ai/provider-review-observation.mjs +68 -9
  81. package/runtime/js/cm-ai/provider-usage.mjs +39 -0
  82. package/runtime/js/cm-ai/qa-config-revision.mjs +44 -10
  83. package/runtime/js/cm-ai/review-abandon-log.mjs +21 -0
  84. package/runtime/js/cm-ai/review-package.mjs +438 -31
  85. package/runtime/js/cm-ai/review-presentation.mjs +45 -0
  86. package/runtime/js/cm-ai/review-reconciliation.mjs +20 -0
  87. package/runtime/js/cm-ai/review-runner.mjs +47 -1
  88. package/runtime/js/cm-ai/reviewed-deliveries.mjs +97 -0
  89. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +104 -10
  90. package/runtime/js/cm-ai/reviewed-evidence-supersession-record.mjs +42 -3
  91. package/runtime/js/cm-ai/specification-material.mjs +154 -12
  92. package/runtime/js/cm-ai/status-projection.mjs +93 -0
  93. package/runtime/js/cm-ai/task-commit.mjs +2 -2
  94. package/runtime/js/cm-ai/task-runner.mjs +658 -75
  95. package/runtime/js/cm-ai/tool-preview.mjs +8 -4
  96. package/runtime/js/cm-ai/worker-claude-developer.mjs +16 -7
  97. package/runtime/js/cm-ai/worker-claude.mjs +63 -19
  98. package/runtime/js/cm-ai/worker-codex-developer.mjs +15 -9
  99. package/runtime/js/cm-ai/worker-codex.mjs +45 -19
  100. package/runtime/js/cm-fix/cause-evidence.mjs +5 -3
  101. package/runtime/js/cm-fix/cause-invocation.mjs +6 -3
  102. package/runtime/js/cm-fix/cause-package.mjs +10 -1
  103. package/runtime/js/cm-fix/execution.mjs +279 -52
  104. package/runtime/js/cm-fix/final-review.mjs +18 -10
  105. package/runtime/js/cm-fix/host-review.mjs +32 -9
  106. package/runtime/js/cm-fix/host.mjs +6 -1
  107. package/runtime/js/cm-fix/layout.mjs +1 -1
  108. package/runtime/js/cm-fix/progress.mjs +5 -0
  109. package/runtime/js/cm-fix/protected-edits.mjs +15 -4
  110. package/runtime/js/cm-fix/qa-source.mjs +6 -4
  111. package/runtime/js/cm-fix/review-reconciliation.mjs +64 -0
  112. package/runtime/js/cm-prd/analysis.mjs +2 -1
  113. package/runtime/js/cm-prd/change.mjs +28 -10
  114. package/runtime/js/cm-prd/draft.mjs +5 -2
  115. package/runtime/js/cm-prd/response-recovery.mjs +23 -0
  116. package/runtime/js/cm-prd/review-preparation.mjs +10 -3
  117. package/runtime/js/cm-prd/review-publication.mjs +27 -15
  118. package/runtime/js/cm-prd/review-time.mjs +29 -0
  119. package/runtime/js/cm-prd/self-check.mjs +6 -3
  120. package/runtime/js/cm-prd/session.mjs +53 -6
  121. package/runtime/js/cm-prd/summary.mjs +3 -1
  122. package/runtime/js/cm-prd/validation-reason.mjs +20 -0
  123. package/runtime/js/cm-security/finalize.mjs +32 -0
  124. package/runtime/js/spec-task-line.mjs +117 -0
  125. package/runtime/js/specs-status.mjs +10 -3
  126. package/runtime/review.md +5 -0
  127. package/runtime/task-gates.md +6 -0
  128. package/runtime/workflow-config.md +10 -1
  129. package/scripts/cm-ai-abandon-effect-position.test.mjs +201 -0
  130. package/scripts/cm-ai-admission.mjs +18 -11
  131. package/scripts/cm-ai-admission.test.mjs +65 -1
  132. package/scripts/cm-ai-batch-drive.mjs +135 -34
  133. package/scripts/cm-ai-batch-drive.test.mjs +209 -3
  134. package/scripts/cm-ai-batch-host.mjs +63 -24
  135. package/scripts/cm-ai-batch-host.test.mjs +2 -1
  136. package/scripts/cm-ai-batch-run.mjs +101 -34
  137. package/scripts/cm-ai-batch-run.test.mjs +56 -5
  138. package/scripts/cm-ai-bootstrap-driver-preflight.test.mjs +45 -0
  139. package/scripts/cm-ai-bootstrap-flow.test.mjs +159 -0
  140. package/scripts/cm-ai-bootstrap-merge.test.mjs +162 -0
  141. package/scripts/cm-ai-bootstrap.test.mjs +174 -89
  142. package/scripts/cm-ai-conversation-entry-ops.test.mjs +97 -2
  143. package/scripts/cm-ai-develop-driver-gaps.test.mjs +924 -0
  144. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +468 -0
  145. package/scripts/cm-ai-drive-timeout.test.mjs +17 -0
  146. package/scripts/cm-ai-drive.mjs +526 -60
  147. package/scripts/cm-ai-drive.test.mjs +336 -10
  148. package/scripts/cm-ai-fix-later-delivery.test.mjs +383 -0
  149. package/scripts/cm-ai-host.mjs +142 -43
  150. package/scripts/cm-ai-host.test.mjs +232 -12
  151. package/scripts/cm-ai-launch-diagnostics.test.mjs +142 -0
  152. package/scripts/cm-ai-multi-root.test.mjs +9 -3
  153. package/scripts/cm-ai-operator-guidance.test.mjs +94 -0
  154. package/scripts/cm-ai-progress.test.mjs +521 -0
  155. package/scripts/cm-ai-project-qa-gate.test.mjs +308 -0
  156. package/scripts/cm-ai-qa-config-revision.test.mjs +187 -15
  157. package/scripts/cm-ai-qa-fingerprint-config.test.mjs +157 -0
  158. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +27 -2
  159. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +400 -0
  160. package/scripts/cm-ai-review-drift-precedence.test.mjs +90 -0
  161. package/scripts/cm-ai-review-failure.test.mjs +977 -0
  162. package/scripts/cm-ai-review-timeout-config.test.mjs +29 -7
  163. package/scripts/cm-ai-review-timeout.test.mjs +199 -4
  164. package/scripts/cm-ai-run.mjs +206 -62
  165. package/scripts/cm-ai-run.test.mjs +6 -4
  166. package/scripts/cm-ai-runner-error-code-regression.test.mjs +219 -0
  167. package/scripts/cm-ai-selection-guard.test.mjs +100 -0
  168. package/scripts/cm-ai-session-chain.test.mjs +7 -3
  169. package/scripts/cm-ai-spec-rebind.test.mjs +481 -0
  170. package/scripts/cm-ai-supersede.test.mjs +571 -17
  171. package/scripts/cm-ai-verification-gate.test.mjs +2 -1
  172. package/scripts/cm-bootstrap-review-recovery.test.mjs +70 -0
  173. package/scripts/cm-capability-gate.test.mjs +21 -2
  174. package/scripts/cm-check-drive.test.mjs +2 -1
  175. package/scripts/cm-check-host.test.mjs +1 -1
  176. package/scripts/cm-check-runtime.sh +12 -1
  177. package/scripts/cm-claude-developer-worker.test.mjs +3 -1
  178. package/scripts/cm-claude-install-layout.test.mjs +26 -0
  179. package/scripts/cm-claude-probe.test.mjs +10 -2
  180. package/scripts/cm-claude-review-stream.test.mjs +25 -0
  181. package/scripts/cm-claude-worker.test.mjs +11 -4
  182. package/scripts/cm-codex-developer-worker.test.mjs +4 -2
  183. package/scripts/cm-codex-plugin-metadata.py +83 -0
  184. package/scripts/cm-codex-plugin-metadata.test.mjs +55 -0
  185. package/scripts/cm-efficiency-checks.test.mjs +37 -0
  186. package/scripts/cm-efficiency-diagnostics.test.mjs +74 -0
  187. package/scripts/cm-efficiency-offline.mjs +35 -0
  188. package/scripts/cm-efficiency-policy.test.mjs +48 -0
  189. package/scripts/cm-efficiency-presentation.test.mjs +35 -0
  190. package/scripts/cm-efficiency-response.test.mjs +117 -0
  191. package/scripts/cm-efficiency-usage.test.mjs +148 -0
  192. package/scripts/cm-external-batch-host.test.mjs +157 -0
  193. package/scripts/cm-external-fix-host.test.mjs +281 -0
  194. package/scripts/cm-external-fix-reconciliation.test.mjs +105 -0
  195. package/scripts/cm-external-group-models.test.mjs +60 -0
  196. package/scripts/cm-external-model-host.test.mjs +180 -0
  197. package/scripts/cm-external-model-recovery.test.mjs +108 -0
  198. package/scripts/cm-external-models.test.mjs +89 -0
  199. package/scripts/cm-external-process-cleanup.test.mjs +71 -0
  200. package/scripts/cm-external-qa-fix.test.mjs +170 -0
  201. package/scripts/cm-external-review-reconciliation.test.mjs +314 -0
  202. package/scripts/cm-failover.mjs +8 -8
  203. package/scripts/cm-fix-abandon.test.mjs +123 -5
  204. package/scripts/cm-fix-cause-package.test.mjs +2 -0
  205. package/scripts/cm-fix-drive.mjs +70 -23
  206. package/scripts/cm-fix-drive.test.mjs +36 -1
  207. package/scripts/cm-fix-final-review.test.mjs +11 -6
  208. package/scripts/cm-fix-host.mjs +24 -14
  209. package/scripts/cm-fix-protected-edits.test.mjs +12 -0
  210. package/scripts/cm-fix-rediagnosis.test.mjs +168 -0
  211. package/scripts/cm-fix-review-budget.test.mjs +147 -0
  212. package/scripts/cm-fixture-process-cleanup.test.mjs +95 -0
  213. package/scripts/cm-host-check.test.mjs +6 -3
  214. package/scripts/cm-host-qa-executor.test.mjs +213 -17
  215. package/scripts/cm-host-session-diagnostic.test.mjs +10 -0
  216. package/scripts/cm-interactive-qa-diagnostic.test.mjs +53 -0
  217. package/scripts/cm-knowledge-closeout.test.mjs +160 -0
  218. package/scripts/cm-live-evidence.test.mjs +64 -0
  219. package/scripts/cm-log-event.mjs +25 -2
  220. package/scripts/cm-log-event.py +15 -0
  221. package/scripts/cm-log-event.test.mjs +31 -0
  222. package/scripts/cm-model-setup.mjs +79 -0
  223. package/scripts/cm-prd-completion.test.mjs +75 -0
  224. package/scripts/cm-prd-draft.test.mjs +14 -0
  225. package/scripts/cm-prd-drive.mjs +32 -11
  226. package/scripts/cm-prd-drive.test.mjs +15 -0
  227. package/scripts/cm-prd-gate-diagnostic.test.mjs +100 -0
  228. package/scripts/cm-prd-host.mjs +13 -4
  229. package/scripts/cm-prd-review-gate.mjs +126 -81
  230. package/scripts/cm-prd-review-gate.test.mjs +105 -1
  231. package/scripts/cm-prd-review-preparation.test.mjs +15 -0
  232. package/scripts/cm-prd-review-publication.test.mjs +6 -0
  233. package/scripts/cm-prd-self-check.test.mjs +6 -0
  234. package/scripts/cm-prd-summary.test.mjs +9 -0
  235. package/scripts/cm-release-smoke.sh +5 -1
  236. package/scripts/cm-review-dependency-snapshot.test.mjs +15 -0
  237. package/scripts/cm-review-inventory.test.mjs +253 -1
  238. package/scripts/cm-runtime-i18n.mjs +15 -4
  239. package/scripts/cm-runtime-install.mjs +8 -4
  240. package/scripts/cm-runtime.mjs +116 -23
  241. package/scripts/cm-runtime.test.mjs +121 -12
  242. package/scripts/cm-security.test.mjs +32 -0
  243. package/scripts/cm-spec-manifest.mjs +28 -10
  244. package/scripts/cm-spec-manifest.test.mjs +8 -4
  245. package/scripts/cm-spec-task-line.test.mjs +138 -0
  246. package/scripts/cm-specs-status.test.mjs +12 -1
  247. package/scripts/cm-task-gate-correction.test.mjs +117 -0
  248. package/scripts/cm-task-gate.mjs +164 -20
  249. package/scripts/cm-task-gate.py +2 -1
  250. package/scripts/cm-test-branch-impact.test.mjs +6 -3
  251. package/scripts/cm-test-drive.mjs +10 -4
  252. package/scripts/cm-test-drive.test.mjs +14 -1
  253. package/scripts/cm-tool-preview-context.test.mjs +12 -0
  254. package/scripts/cm-usage-report.py +22 -3
  255. package/scripts/cm-workflow-config.mjs +10 -1
  256. package/scripts/fixtures/bootstrap-review-runner.mjs +102 -0
  257. package/scripts/fixtures/claude-review-process.mjs +1 -0
  258. package/scripts/fixtures/live-evidence-driver.mjs +35 -0
  259. package/scripts/fixtures/process-cleanup.mjs +101 -0
  260. package/scripts/test-cm-log-event.py +2 -0
  261. package/scripts/test-cm-native-usage.py +62 -0
  262. package/scripts/test-cm-prd-review-gate.py +2 -1
  263. package/scripts/test-external-model-setup.py +91 -0
  264. package/scripts/test-model-configuration-write.py +201 -0
  265. package/scripts/test-npm-install.py +11 -2
  266. package/scripts/test-scan-public-safety.py +1 -1
  267. package/scripts/test-spec-manifest.py +16 -8
  268. package/scripts/test-task-gate.py +2 -2
  269. package/scripts/test-workflow-config.py +1 -0
  270. package/scripts/validate-public-repo.py +1 -0
  271. package/skills/cm-ai/SKILL.md +2 -2
  272. package/skills/cm-ai/references/N1-init.md +1 -1
  273. package/skills/cm-ai/references/N8-finish.md +5 -0
  274. package/skills/cm-ai/references/js-host.md +270 -43
  275. package/skills/cm-ai/references/knowledge-closeout.md +90 -0
  276. package/skills/cm-fix/SKILL.md +1 -1
  277. package/skills/cm-fix/references/js-host.md +52 -3
  278. package/skills/cm-prd/references/js-change-recovery.md +1 -1
  279. package/skills/cm-prd/references/js-host.md +6 -0
  280. package/skills/cm-runtime/SKILL.md +29 -6
  281. package/skills/cm-security/SKILL.md +4 -2
  282. package/skills/cm-security/references/scan-contract.md +1 -0
  283. package/templates/cm-workflow.yml +1 -1
@@ -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,181 @@ 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
+ };
214
+ // Historical runner checkpoints did not carry a typed failure origin. Accept
215
+ // only messages produced by this snapshot builder when recovering an old
216
+ // unknown/limit_exceeded; a generic JSON/provider limit is not package evidence.
217
+ export function reviewMaterialLimitReason(reason){
218
+ if(typeof reason!=='string'||!reason.startsWith('limit_exceeded: '))return false;
219
+ const suffixes=[`file bytes > ${FILE_LIMIT}`,`file count > ${FILE_COUNT}`,
220
+ `file count > ${INVENTORY_COUNT}`,`inventory bytes > ${INVENTORY_LIMIT}`,
221
+ `material file count > ${FILE_COUNT}`,'instruction search depth > 32','directory depth > 32'];
222
+ return suffixes.some(detail=>reason.endsWith(` (${detail})`))
223
+ ||new RegExp(` \\(material bytes \\d+\\+\\d+ > ${SNAPSHOT_LIMIT}; scope, requirements and AGENTS\\.md content count\\)$`).test(reason);
224
+ }
42
225
  const fail = code => { const error=new Error(code); error.code=code; throw error; };
43
226
  const need = (condition,code='invalid_input') => { if(!condition) fail(code); };
44
227
  const record = v => v!==null && typeof v==='object' && !Array.isArray(v);
@@ -121,7 +304,8 @@ function readFile(root,p,includeContent=true,limit=FILE_LIMIT,contentLimit=limit
121
304
  return {path:p,type:'file',mode:Number(before.mode & 0o7777n),size:offset,
122
305
  sha256:hash.digest('hex'),...(includeContent?{contentBase64:Buffer.concat(chunks).toString('base64')}:{})};
123
306
  } catch(error) {
124
- if(['unsupported_file','limit_exceeded','snapshot_changed'].includes(error.code))throw error;
307
+ if(['unsupported_file','limit_exceeded','snapshot_changed'].includes(error.code))throw diagnostic(error.code,p,
308
+ error.code==='limit_exceeded'?`file bytes > ${limit}`:'');
125
309
  fail('read_failed');
126
310
  } finally { if(fd!==undefined) fs.closeSync(fd); }
127
311
  }
@@ -132,26 +316,40 @@ export function reviewSpecsPath(root,specsRoot) {
132
316
  need(root!==specsRoot&&!root.startsWith(specsRoot+path.sep),'overlapping_roots');
133
317
  return specsRoot.startsWith(root+path.sep)?filePath(path.relative(root,specsRoot).split(path.sep).join('/')):null;
134
318
  }
135
- function snapshot(root,specsPath=null,projectPaths=null,retainedPaths=[],selected=null) {
319
+ function snapshot(root,specsPath=null,projectPaths=null,retainedPaths=[],selected=null,policy=null) {
136
320
  if(specsPath!==null){
137
321
  const target=path.join(root,specsPath);
138
322
  need(fs.realpathSync(target)===target&&fs.lstatSync(target).isDirectory(),'unsupported_path');
139
323
  }
140
- const files=[],seen=new Set(); let total=0,materialBytes=0,materialCount=0;
324
+ const files=[],seen=new Set(); let total=0,materialBytes=0,materialCount=0,visitedSpecs=false;
141
325
  function add(p,s){
142
- need(s.isFile()&&!s.isSymbolicLink()&&s.nlink===1,'unsupported_file');
326
+ if(!s.isFile()||s.isSymbolicLink()||s.nlink!==1)throw diagnostic('unsupported_file',p);
143
327
  const includeContent=selected===null||materialPath(p,selected);
144
328
  const countLimit=selected===null?FILE_COUNT:INVENTORY_COUNT;
145
329
  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');
330
+ if(files.length>=countLimit)throw diagnostic('limit_exceeded',p,`file count > ${countLimit}`);
331
+ if(total+s.size>byteLimit)throw diagnostic('limit_exceeded',p,`inventory bytes > ${byteLimit}`);
332
+ if(includeContent&&materialCount>=FILE_COUNT)
333
+ throw diagnostic('limit_exceeded',p,`material file count > ${FILE_COUNT}`);
334
+ if(includeContent&&materialBytes+s.size>SNAPSHOT_LIMIT)
335
+ throw diagnostic('limit_exceeded',p,`material bytes ${materialBytes}+${s.size} > ${SNAPSHOT_LIMIT}; scope, requirements and AGENTS.md content count`);
148
336
  const f=readFile(root,p,includeContent,includeContent?Math.min(FILE_LIMIT,SNAPSHOT_LIMIT-materialBytes):byteLimit-total);
149
337
  total+=f.size;
150
338
  if(includeContent){materialBytes+=f.size;materialCount++;}
151
339
  files.push(f);
152
340
  }
341
+ function retainIgnoredInstructions(dir,depth=0){
342
+ if(depth>32)throw diagnostic('limit_exceeded',dir,'instruction search depth > 32');
343
+ let names;try{names=fs.readdirSync(path.join(root,dir)).sort();}catch{throw diagnostic('read_failed',dir);}
344
+ for(const name of names){
345
+ const p=dir+'/'+name;
346
+ let stat;try{stat=fs.lstatSync(path.join(root,p));}catch{throw diagnostic('read_failed',p);}
347
+ if(name==='AGENTS.md')add(p,stat);
348
+ else if(stat.isDirectory()&&!stat.isSymbolicLink())retainIgnoredInstructions(p,depth+1);
349
+ }
350
+ }
153
351
  function walk(rel='',depth=0,codeRoot='') {
154
- need(depth<=32,'limit_exceeded');
352
+ if(depth>32)throw diagnostic('limit_exceeded',rel,`directory depth > 32`);
155
353
  let names;
156
354
  try { names=fs.readdirSync(path.join(root,rel)).sort(); } catch { fail('read_failed'); }
157
355
  for(const name of names) {
@@ -162,9 +360,29 @@ function snapshot(root,specsPath=null,projectPaths=null,retainedPaths=[],selecte
162
360
  // Scope and requirement paths still cannot select any .git entry.
163
361
  if(p===(codeRoot?codeRoot+'/.git':'.git') && !s.isSymbolicLink()
164
362
  && (s.isDirectory() || (s.isFile() && s.nlink===1))) continue;
363
+ const protectedPath=selected?.has(p)||retainedPaths.includes(p)||name==='AGENTS.md'
364
+ ||specsPath!==null&&(specsPath===p||specsPath.startsWith(p+'/'))
365
+ ||[...selected??[],...retainedPaths,...policy?.agentPaths??[]].some(item=>item===p||item.startsWith(p+'/'));
366
+ const gitIgnored=policy?.ignored.has(p)||[...policy?.ignoredDirectories??[]].some(dir=>p.startsWith(dir+'/'));
367
+ const builtinIgnored=p.split('/').some(part=>junkDirectories.has(part.toLowerCase()));
368
+ if(policy&&!protectedPath&&(junkFile(name)||builtinIgnored
369
+ ||gitIgnored)){
370
+ // Git's ignored AGENTS path query protects deeper instructions without
371
+ // entering generated output. Without Git, search names only so an
372
+ // instruction can never be silently excluded by the fixed junk list.
373
+ if(s.isDirectory()){
374
+ if(policy.gitSourceDigest===null)retainIgnoredInstructions(p);
375
+ else{
376
+ const instruction=p+'/AGENTS.md';
377
+ try{add(instruction,fs.lstatSync(path.join(root,instruction)));}
378
+ catch(error){if(error.code!=='ENOENT')throw error;}
379
+ }
380
+ }
381
+ continue;
382
+ }
165
383
  filePath(p);
166
384
  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;}
385
+ if(p===specsPath){need(s.isDirectory()&&!s.isSymbolicLink(),'unsupported_path');visitedSpecs=true;continue;}
168
386
  // Never follow a dependency-root symlink. Old baselines that captured
169
387
  // these files still verify their original material instead of dropping it.
170
388
  if(s.isDirectory()&&(dependencyDirectories.has(name.toLowerCase())||isCocoaPodsRoot(path.join(root,p)))
@@ -173,7 +391,7 @@ function snapshot(root,specsPath=null,projectPaths=null,retainedPaths=[],selecte
173
391
  else add(p,s);
174
392
  }
175
393
  }
176
- if(projectPaths===null)walk();
394
+ if(projectPaths===null){walk();if(specsPath!==null)need(visitedSpecs,'protected_specs');}
177
395
  else{
178
396
  const roots=projectPaths.map(prefix=>path.join(root,prefix));
179
397
  resolveCodeProjects(root,roots);
@@ -187,12 +405,58 @@ function snapshot(root,specsPath=null,projectPaths=null,retainedPaths=[],selecte
187
405
  }
188
406
  return files.sort((a,b)=>a.path<b.path?-1:a.path>b.path?1:0);
189
407
  }
408
+ export function captureReviewInventory(root,baseline){
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
+ return snapshot(root,baseline.specsPath??null,baseline.codeProjectPaths??null,
414
+ stable?[]:baseline.files.map(file=>file.path),new Set(),policy)
415
+ .map(file=>({path:file.path,sha256:file.sha256}));
416
+ }
417
+ // withMode also reports permission-only changes; the mode is part of a reviewed
418
+ // file record. The default keeps the historical content-only comparison.
419
+ export function compareReviewInventoryToBaseline(root,baseline,{withMode=false}={}){
420
+ validBaseline(baseline);
421
+ const stable=baseline.ignorePolicy?.version===2;
422
+ const policy=stable?stableSnapshotPolicy(root,baseline.ignorePolicy)
423
+ :Object.hasOwn(baseline,'ignorePolicy')?ignorePolicy(root):null;
424
+ const before=stable?comparableFiles(baseline.files,policy,new Set([...baseline.scope,...baseline.requirements])):baseline.files;
425
+ const after=snapshot(root,baseline.specsPath??null,baseline.codeProjectPaths??null,
426
+ stable?[]:baseline.files.map(file=>file.path),new Set(),policy);
427
+ const key=file=>withMode?`${file.sha256}:${file.mode}`:file.sha256;
428
+ const previous=new Map(before.map(file=>[file.path,key(file)]));
429
+ const current=new Map(after.map(file=>[file.path,key(file)]));
430
+ const records=new Map(after.map(file=>[file.path,file]));
431
+ return [...new Set([...previous.keys(),...current.keys()])].filter(p=>previous.get(p)!==current.get(p))
432
+ .map(p=>({path:p,sha256:records.get(p)?.sha256??null,...(withMode?{mode:records.get(p)?.mode??null}:{})}));
433
+ }
434
+ export function compareReviewBaseline(current,expected){
435
+ if(digest(current)===digest(expected))return true;
436
+ const stable=current.ignorePolicy?.version===2&&expected.ignorePolicy?.version===2;
437
+ const useGit=stable&&expected.ignorePolicy.mode!=='builtin_limit';
438
+ const policy=stable?{ignored:new Set(useGit?[...current.ignorePolicy.ignoredPaths,...expected.ignorePolicy.ignoredPaths]:[]),
439
+ ignoredDirectories:new Set(useGit?[...current.ignorePolicy.ignoredDirectories,...expected.ignorePolicy.ignoredDirectories]:[])}:null;
440
+ const protectedPaths=new Set([...expected.scope,...expected.requirements]);
441
+ const before=new Map((stable?comparableFiles(expected.files,policy,protectedPaths):expected.files).map(file=>[file.path,digest(file)]));
442
+ const after=new Map((stable?comparableFiles(current.files,policy,protectedPaths):current.files).map(file=>[file.path,digest(file)]));
443
+ const paths=[...new Set([...before.keys(),...after.keys()])].filter(p=>before.get(p)!==after.get(p)).sort();
444
+ if(!stable&&digest(current.ignorePolicy??null)!==digest(expected.ignorePolicy??null))paths.push(...policyDifferencePaths(current.ignorePolicy,expected.ignorePolicy));
445
+ if(stable){
446
+ const metadata=value=>{const {ignorePolicy,files,baselineDigest,...rest}=value;return rest;};
447
+ if(digest(metadata(current))!==digest(metadata(expected)))paths.push('baseline metadata');
448
+ }
449
+ if(stable&&!paths.length)return true;
450
+ if(!paths.length)paths.push('baseline metadata');
451
+ const error=new Error(`package_mismatch: ${paths.slice(0,20).join(', ')}${paths.length>20?` (+${paths.length-20} more)`:''}`);
452
+ error.code='package_mismatch';error.paths=paths;throw error;
453
+ }
190
454
  const sealed = (data,key) => {
191
455
  const result={...data,[key]:digest(data)};
192
456
  need(Buffer.byteLength(JSON.stringify(result))<=8*1024*1024,'limit_exceeded');
193
457
  return freeze(result);
194
458
  };
195
- export function captureReviewBaseline(options) {
459
+ export function captureReviewBaseline(options,legacy=false,policyVersion=2,baselinePolicy=null) {
196
460
  const v=plain(options); keys(v,['root','identity','scope','requirements',
197
461
  ...['specsRoot','codeProjectPaths','bootstrapRequirements','specification','version'].filter(key=>Object.hasOwn(v,key))]); identityCheck(v.identity);
198
462
  const version=v.version??2;need([1,2].includes(version));
@@ -218,7 +482,12 @@ export function captureReviewBaseline(options) {
218
482
  if(specsPath!==null)validateProjectSpecs(specsPath,projectPaths);
219
483
  assertCodeProjectSelections(projectPaths,[...scope,...requirements],{allowInstructions:true});
220
484
  }
221
- const files=snapshot(root,specsPath,projectPaths,[],version===1?null:new Set([...scope,...requirements]));
485
+ need([1,2].includes(policyVersion));
486
+ if(baselinePolicy!==null){need(policyVersion===2);validateStablePolicy(baselinePolicy);}
487
+ const policy=legacy||version===1?null:policyVersion===1?ignorePolicy(root)
488
+ :stableIgnorePolicy(root,baselinePolicy?.mode==='builtin_limit');
489
+ const snapshotPolicy=baselinePolicy===null?policy:stableSnapshotPolicy(root,baselinePolicy,policy);
490
+ const files=snapshot(root,specsPath,projectPaths,[],version===1?null:new Set([...scope,...requirements]),snapshotPolicy);
222
491
  need(requirements.every(p=>files.some(f=>f.path===p)),'read_failed');
223
492
  for(const p of scope) {
224
493
  const absolute=path.join(root,p);
@@ -228,7 +497,8 @@ export function captureReviewBaseline(options) {
228
497
  scope,requirements,files,...(specsPath===null?{}:{specsPath}),
229
498
  ...(projectPaths===null?{}:{codeProjectPaths:projectPaths}),
230
499
  ...(bootstrap===null?{}:{bootstrapRequirements:bootstrap}),
231
- ...(specification===null?{}:{specification,specificationRoot:v.specification.specsRoot})},'baselineDigest');
500
+ ...(specification===null?{}:{specification,specificationRoot:v.specification.specsRoot}),
501
+ ...(policy===null?{}:{ignorePolicy:policyVersion===1?publicPolicy(policy):stablePublicPolicy(policy)})},'baselineDigest');
232
502
  }
233
503
 
234
504
  // Bounded selected-file material for pre-implementation reviews; no whole-tree scan.
@@ -310,20 +580,20 @@ function inventoryList(b) {
310
580
  if(material.length)fileList(material);
311
581
  need(Buffer.byteLength(JSON.stringify(b))<=8*1024*1024,'limit_exceeded');
312
582
  }
313
- const bootstrapPaths=['0.bootstrap/design.md','0.bootstrap/requirements.md'];
583
+ const bootstrapPaths=feature=>[`${feature}/design.md`,`${feature}/requirements.md`];
314
584
  function validBootstrapRequirements(value,published=false){
315
585
  keys(value,['feature','files',published?'rootDigest':'specsRoot']);
316
- need(value.feature==='0.bootstrap','bootstrap_requirements_invalid');
586
+ need(value.feature===identifyApprovedBootstrapFeature([value.feature]),'bootstrap_requirements_invalid');
317
587
  if(published)hex(value.rootDigest);
318
588
  else need(typeof value.specsRoot==='string'&&path.isAbsolute(value.specsRoot)
319
589
  &&path.resolve(value.specsRoot)===value.specsRoot&&!value.specsRoot.includes('\0'),'unsupported_path');
320
590
  fileList(value.files);
321
- need(digest(value.files.map(file=>file.path))===digest(bootstrapPaths)
591
+ need(digest(value.files.map(file=>file.path))===digest(bootstrapPaths(value.feature))
322
592
  &&value.files.every(file=>file.size>0),'bootstrap_requirements_invalid');
323
593
  }
324
594
  function currentBootstrapRequirements(value){
325
595
  need(fs.realpathSync(value.specsRoot)===value.specsRoot,'unsupported_path');
326
- const files=readReviewSourceFiles(value.specsRoot,bootstrapPaths);
596
+ const files=readReviewSourceFiles(value.specsRoot,bootstrapPaths(value.feature));
327
597
  need(digest(files)===digest(value.files),'bootstrap_requirements_changed');
328
598
  return {feature:value.feature,files:value.files,rootDigest:sha(value.specsRoot)};
329
599
  }
@@ -333,8 +603,19 @@ export function readReviewSourceRecords(raw){
333
603
  function validBaseline(b) {
334
604
  try {
335
605
  keys(b,['version','kind','identity','rootDigest','scope','requirements','files','baselineDigest',
336
- ...['specsPath','codeProjectPaths','bootstrapRequirements','specification','specificationRoot'].filter(key=>Object.hasOwn(b,key))]);
606
+ ...['specsPath','codeProjectPaths','bootstrapRequirements','specification','specificationRoot','ignorePolicy'].filter(key=>Object.hasOwn(b,key))]);
337
607
  need([1,2].includes(b.version) && b.kind==='cm-review-baseline'); identityCheck(b.identity); hex(b.rootDigest);
608
+ if(Object.hasOwn(b,'ignorePolicy')){
609
+ if(b.ignorePolicy.version===2)validateStablePolicy(b.ignorePolicy);
610
+ else{
611
+ keys(b.ignorePolicy,['version','builtinDigest','gitSourceDigest','gitSources','gitConfigDigest','gitWorktreeDigest']);
612
+ need(b.ignorePolicy.version===1);hex(b.ignorePolicy.builtinDigest);
613
+ need(b.ignorePolicy.gitSourceDigest===null||/^[a-f0-9]{64}$/.test(b.ignorePolicy.gitSourceDigest));
614
+ need(b.ignorePolicy.gitConfigDigest===null||/^[a-f0-9]{64}$/.test(b.ignorePolicy.gitConfigDigest));
615
+ need(b.ignorePolicy.gitWorktreeDigest===null||/^[a-f0-9]{64}$/.test(b.ignorePolicy.gitWorktreeDigest));
616
+ validatePolicySources(b.ignorePolicy.gitSources);
617
+ }
618
+ }
338
619
  need(Object.hasOwn(b,'specification')===Object.hasOwn(b,'specificationRoot'));
339
620
  if(Object.hasOwn(b,'specification')){
340
621
  readSpecificationMaterial(b.specification,b.identity.taskId);
@@ -355,7 +636,7 @@ function validBaseline(b) {
355
636
  const {baselineDigest,...data}=b; hex(baselineDigest); need(digest(data)===baselineDigest);
356
637
  } catch { fail('invalid_baseline'); }
357
638
  }
358
- function validChecks(checks) {
639
+ export function validChecks(checks) {
359
640
  need(Array.isArray(checks) && checks.length>0);
360
641
  need(Buffer.byteLength(JSON.stringify(checks))<=64*1024,'limit_exceeded');
361
642
  const ids=new Set();
@@ -383,21 +664,55 @@ function validChecks(checks) {
383
664
  || c.outcome==='unavailable' && c.exitCode===null);
384
665
  }
385
666
  }
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);
667
+ // The one selection a review package snapshot uses: its policy, retained paths
668
+ // and material (scope, requirements, earlier material and every AGENTS.md).
669
+ const packagePolicy=(root,b)=>b.ignorePolicy?.version===2?stableSnapshotPolicy(root,b.ignorePolicy)
670
+ :Object.hasOwn(b,'ignorePolicy')?ignorePolicy(root):null;
671
+ function packageSnapshot(root,b,policy){
672
+ const selected=b.version===1?null:new Set([...b.scope,...b.requirements,
673
+ ...b.files.filter(f=>Object.hasOwn(f,'contentBase64')).map(f=>f.path)]);
674
+ return snapshot(root,b.specsPath??null,b.codeProjectPaths??null,b.ignorePolicy?.version===2?[]:b.files.map(f=>f.path),selected,policy);
675
+ }
676
+ // Read-only: path and size of every material body a package built from the
677
+ // current tree would carry. Callers use it to refuse a delivery before writing it.
678
+ export function reviewMaterialSizes(options){
679
+ const v=plain(options);keys(v,['root','baseline']);const b=v.baseline;validBaseline(b);
680
+ const root=rootPath(v.root);need(sha(root)===b.rootDigest,'invalid_baseline');
681
+ return freeze(packageSnapshot(root,b,packagePolicy(root,b)).filter(f=>Object.hasOwn(f,'contentBase64'))
682
+ .map(f=>({path:f.path,size:f.size})));
683
+ }
684
+ // Validation, specification, policy and bootstrap material a package is built
685
+ // with, shared by the real and the projected package so both use one assembly.
686
+ function packageContext(v){
687
+ const b=v.baseline;validBaseline(b); validChecks(v.checks);
389
688
  const specification=Object.hasOwn(b,'specification')?verifySpecificationMaterial(b):null;
390
689
  const root=rootPath(v.root); need(sha(root)===b.rootDigest,'invalid_baseline');
690
+ const stable=b.ignorePolicy?.version===2;
691
+ const policy=packagePolicy(root,b);
692
+ if(policy&&!stable&&digest(publicPolicy(policy))!==digest(b.ignorePolicy)){
693
+ const changed=policyDifferencePaths(publicPolicy(policy),b.ignorePolicy);
694
+ throw diagnostic('package_mismatch',changed.join(', ')||'ignore policy','ignore policy changed');
695
+ }
391
696
  const bootstrap=Object.hasOwn(b,'bootstrapRequirements')?currentBootstrapRequirements(b.bootstrapRequirements):null;
392
697
  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=[];
698
+ return {b,root,stable,policy,specification,bootstrap};
699
+ }
700
+ function assemblePackage({b,stable,policy,specification,bootstrap},files,checks,handoff){
701
+ const protectedPaths=new Set([...b.scope,...b.requirements]);
702
+ const before=new Map((stable?comparableFiles(b.files,policy,protectedPaths):b.files).map(f=>[f.path,f]));
703
+ const after=new Map(files.map(f=>[f.path,f]));
704
+ const changes=[],violations=[];
397
705
  for(const p of [...new Set([...before.keys(),...after.keys()])].sort()) {
398
706
  const old=before.get(p)??null,current=after.get(p)??null;
399
707
  if(digest(old)===digest(current))continue;
400
- need(b.scope.includes(p),'out_of_scope'); changes.push({path:p,before:old,after:current});
708
+ if(!b.scope.includes(p)){violations.push({path:p,newFile:old===null&&current!==null});continue;}
709
+ changes.push({path:p,before:old,after:current});
710
+ }
711
+ if(violations.length){
712
+ const shown=violations.slice(0,20).map(item=>item.path.length>300?`${item.path.slice(0,300)}…`:item.path);
713
+ const error=new Error(`out_of_scope: ${shown.join(', ')}${violations.length>20?` (+${violations.length-20} more)`:''}`);
714
+ error.code='out_of_scope';error.violations=violations;
715
+ throw error;
401
716
  }
402
717
  need(changes.length>0,'empty_changes');
403
718
  const changedPaths=new Set(changes.map(change=>change.path));
@@ -405,16 +720,50 @@ export function createReviewPackage(options) {
405
720
  .map(p=>({path:p,sha256:after.get(p).sha256}));
406
721
  const requirements=b.requirements.map(p=>{ need(after.has(p),'read_failed'); return after.get(p); });
407
722
  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,
723
+ baseIdentity:b.baselineDigest,scope:b.scope,changes,unchangedScope,requirements,checks,
409
724
  ...(Object.hasOwn(b,'codeProjectPaths')?{codeProjectPaths:b.codeProjectPaths,
410
725
  instructions:files.filter(file=>file.path.split('/').at(-1)==='AGENTS.md')}:{}),
411
726
  ...(bootstrap===null?{}:{bootstrapRequirements:bootstrap}),
412
727
  ...(specification===null?{}:{specification}),
413
- ...(Object.hasOwn(v,'handoffPath')?{handoff:readHandoffSnapshot(v.handoffPath)}:{}),
414
- artifactDigest:digest(changes),requirementsDigest:digest(requirements),checksDigest:digest(v.checks)},'packageDigest');
728
+ ...(handoff===null?{}:{handoff:handoff()}),
729
+ ...(policy===null?{}:{ignorePolicy:stable?b.ignorePolicy:publicPolicy(policy)}),
730
+ artifactDigest:digest(changes),requirementsDigest:digest(requirements),checksDigest:digest(checks)},'packageDigest');
415
731
  need(Buffer.byteLength(JSON.stringify(pkg))<=8*1024*1024,'limit_exceeded');
416
732
  return pkg;
417
733
  }
734
+ export function createReviewPackage(options) {
735
+ const v=plain(options); keys(v,['root','baseline','checks',...(Object.hasOwn(v,'handoffPath')?['handoffPath']:[])]);
736
+ const context=packageContext(v);
737
+ return assemblePackage(context,packageSnapshot(context.root,context.b,context.policy),v.checks,
738
+ Object.hasOwn(v,'handoffPath')?()=>readHandoffSnapshot(v.handoffPath):null);
739
+ }
740
+ // Read-only: the package the current tree would give once the listed scope files
741
+ // are replaced ({path,contentBase64,mode}, or contentBase64 null to delete),
742
+ // assembled by the same code as createReviewPackage. Nothing is written. The
743
+ // handoff is only known once it exists, so the projection carries none.
744
+ export function projectedReviewPackage(options){
745
+ const v=plain(options);keys(v,['root','baseline','checks','scopeFiles',...(Object.hasOwn(v,'handoff')?['handoff']:[])]);
746
+ const context=packageContext(v);need(Array.isArray(v.scopeFiles),'invalid_input');
747
+ const files=new Map(packageSnapshot(context.root,context.b,context.policy).map(file=>[file.path,file]));
748
+ for(const item of v.scopeFiles){
749
+ keys(item,['path','contentBase64','mode']);need(context.b.scope.includes(item.path),'out_of_scope');
750
+ if(item.contentBase64===null){need(item.mode===null);files.delete(item.path);continue;}
751
+ need(typeof item.contentBase64==='string'&&Number.isInteger(item.mode)&&item.mode>=0&&item.mode<=0o7777);
752
+ const bytes=Buffer.from(item.contentBase64,'base64');need(bytes.toString('base64')===item.contentBase64);
753
+ files.set(item.path,{path:item.path,type:'file',mode:item.mode,size:bytes.length,sha256:sha(bytes),contentBase64:item.contentBase64});
754
+ }
755
+ // A projected handoff ({name,contentBase64,mode}) takes the record shape the
756
+ // package reads back from the published file.
757
+ let handoff=null;
758
+ if(Object.hasOwn(v,'handoff')){
759
+ keys(v.handoff,['name','contentBase64','mode']);const name=filePath(v.handoff.name);need(!name.includes('/'));
760
+ need(Number.isInteger(v.handoff.mode)&&v.handoff.mode>=0&&v.handoff.mode<=0o7777);
761
+ const bytes=Buffer.from(v.handoff.contentBase64,'base64');need(bytes.toString('base64')===v.handoff.contentBase64);
762
+ const record={path:name,type:'file',mode:v.handoff.mode,size:bytes.length,sha256:sha(bytes),contentBase64:v.handoff.contentBase64};
763
+ handoff=()=>record;
764
+ }
765
+ return assemblePackage(context,[...files.values()].sort((a,b)=>a.path<b.path?-1:a.path>b.path?1:0),v.checks,handoff);
766
+ }
418
767
  function validPackage(p) {
419
768
  try {
420
769
  keys(p,['version','kind','identity','rootDigest','baseIdentity','scope','changes','requirements',
@@ -423,7 +772,18 @@ function validPackage(p) {
423
772
  ...(Object.hasOwn(p,'specification')?['specification']:[]),
424
773
  ...(Object.hasOwn(p,'handoff')?['handoff']:[]),
425
774
  ...(Object.hasOwn(p,'codeProjectPaths')?['codeProjectPaths','instructions']:[]),
426
- ...(Object.hasOwn(p,'bootstrapRequirements')?['bootstrapRequirements']:[])]);
775
+ ...(Object.hasOwn(p,'bootstrapRequirements')?['bootstrapRequirements']:[]),
776
+ ...(Object.hasOwn(p,'ignorePolicy')?['ignorePolicy']:[])]);
777
+ if(Object.hasOwn(p,'ignorePolicy')){
778
+ if(p.ignorePolicy.version===2)validateStablePolicy(p.ignorePolicy);
779
+ else{
780
+ keys(p.ignorePolicy,['version','builtinDigest','gitSourceDigest','gitSources','gitConfigDigest','gitWorktreeDigest']);need(p.ignorePolicy.version===1);
781
+ hex(p.ignorePolicy.builtinDigest);need(p.ignorePolicy.gitSourceDigest===null||/^[a-f0-9]{64}$/.test(p.ignorePolicy.gitSourceDigest));
782
+ need(p.ignorePolicy.gitConfigDigest===null||/^[a-f0-9]{64}$/.test(p.ignorePolicy.gitConfigDigest));
783
+ need(p.ignorePolicy.gitWorktreeDigest===null||/^[a-f0-9]{64}$/.test(p.ignorePolicy.gitWorktreeDigest));
784
+ validatePolicySources(p.ignorePolicy.gitSources);
785
+ }
786
+ }
427
787
  if(Object.hasOwn(p,'handoff')) {
428
788
  fileRecord(p.handoff);need(!p.handoff.path.includes('/')&&p.handoff.size<=256*1024);
429
789
  }
@@ -481,6 +841,7 @@ export function verifyReviewPackage(options) {
481
841
  need(v.reviewPackage.packageDigest===v.expectedDigest,'package_mismatch');
482
842
  need(Object.hasOwn(v.reviewPackage,'specification')===Object.hasOwn(v.baseline,'specification'),'package_mismatch');
483
843
  need(Object.hasOwn(v.reviewPackage,'handoff')===Object.hasOwn(v,'handoffPath'),'package_mismatch');
844
+ need(digest(v.reviewPackage.ignorePolicy??null)===digest(v.baseline.ignorePolicy??null),'package_mismatch');
484
845
  let current=createReviewPackage({root:v.root,baseline:v.baseline,checks:v.checks,
485
846
  ...(Object.hasOwn(v,'handoffPath')?{handoffPath:v.handoffPath}:{})});
486
847
  // Rebuild the historical representation for legacy receipts, without rewriting them.
@@ -488,10 +849,56 @@ export function verifyReviewPackage(options) {
488
849
  const {unchangedScope,packageDigest,...legacy}=current;
489
850
  current=sealed(legacy,'packageDigest');
490
851
  }
491
- need(current.packageDigest===v.expectedDigest,'package_mismatch');
852
+ if(current.packageDigest!==v.expectedDigest)throw packageMismatch(current,v.reviewPackage);
492
853
  return freeze({outcome:'matched',packageDigest:current.packageDigest});
493
854
  }
494
855
 
856
+ // Completion repeats checks after review. Their diagnostic prose may vary, but
857
+ // every reviewed file, scope and handoff byte and every check result must agree.
858
+ export function verifyCompletionReviewPackage(options) {
859
+ const v=plain(options);keys(v,['root','baseline','checks','reviewPackage','expectedDigest',
860
+ ...(Object.hasOwn(v,'handoffPath')?['handoffPath']:[])]);
861
+ hex(v.expectedDigest);validBaseline(v.baseline);validPackage(v.reviewPackage);
862
+ need(v.reviewPackage.packageDigest===v.expectedDigest,'package_mismatch');
863
+ need(Object.hasOwn(v.reviewPackage,'specification')===Object.hasOwn(v.baseline,'specification'),'package_mismatch');
864
+ need(Object.hasOwn(v.reviewPackage,'handoff')===Object.hasOwn(v,'handoffPath'),'package_mismatch');
865
+ need(digest(v.reviewPackage.ignorePolicy??null)===digest(v.baseline.ignorePolicy??null),'package_mismatch');
866
+ let current=createReviewPackage({root:v.root,baseline:v.baseline,checks:v.checks,
867
+ ...(Object.hasOwn(v,'handoffPath')?{handoffPath:v.handoffPath}:{})});
868
+ if(!Object.hasOwn(v.reviewPackage,'unchangedScope')){
869
+ const {unchangedScope,packageDigest,...legacy}=current;
870
+ current=sealed(legacy,'packageDigest');
871
+ }
872
+ const withoutChecks=({checks,checksDigest,packageDigest,...fields})=>fields;
873
+ if(digest(withoutChecks(current))!==digest(withoutChecks(v.reviewPackage)))throw packageMismatch(current,v.reviewPackage);
874
+ const checkIdentities=checks=>checks.map(c=>c.kind==='visual'
875
+ ?{id:c.id,kind:c.kind}
876
+ :{id:c.id,command:c.command});
877
+ need(digest(checkIdentities(current.checks))===digest(checkIdentities(v.reviewPackage.checks)),'package_mismatch');
878
+ const checkResults=checks=>checks.map(c=>c.kind==='visual'
879
+ ?{outcome:c.outcome}
880
+ :{outcome:c.outcome,exitCode:c.exitCode});
881
+ need(digest(checkResults(current.checks))===digest(checkResults(v.reviewPackage.checks)),'completion_checks_changed');
882
+ const visualCarriers=checks=>checks.filter(c=>c.kind==='visual').map(c=>({before:c.before,after:c.after}));
883
+ need(digest(visualCarriers(current.checks))===digest(visualCarriers(v.reviewPackage.checks)),'package_mismatch');
884
+ return freeze({outcome:'matched',packageDigest:v.expectedDigest});
885
+ }
886
+
887
+ function packageMismatch(current,reviewed){
888
+ const paths=new Set();
889
+ for(const field of ['changes','unchangedScope','requirements','instructions']){
890
+ const before=new Map((reviewed[field]??[]).map(item=>[item.path,digest(item)]));
891
+ const after=new Map((current[field]??[]).map(item=>[item.path,digest(item)]));
892
+ for(const p of new Set([...before.keys(),...after.keys()]))if(before.get(p)!==after.get(p))paths.add(p);
893
+ }
894
+ if(digest(current.handoff??null)!==digest(reviewed.handoff??null))paths.add(current.handoff?.path??reviewed.handoff?.path??'handoff');
895
+ if(digest(current.ignorePolicy??null)!==digest(reviewed.ignorePolicy??null))
896
+ policyDifferencePaths(current.ignorePolicy,reviewed.ignorePolicy).forEach(p=>paths.add(p));
897
+ if(!paths.size)paths.add('review package metadata');
898
+ const names=[...paths].sort();const error=new Error(`package_mismatch: ${names.slice(0,20).join(', ')}${names.length>20?` (+${names.length-20} more)`:''}`);
899
+ error.code='package_mismatch';error.paths=names;return error;
900
+ }
901
+
495
902
  // The host supplies this separate specs-root file; workers never select it.
496
903
  // Reuse the bounded no-follow snapshot reader and store bytes, not a live path.
497
904
  function readHandoffSnapshot(p) {