@aibyzero/cm-workflow 0.16.9 → 0.17.1

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 (165) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +4 -0
  3. package/CHANGELOG.md +18 -1
  4. package/CONTRIBUTING.md +47 -0
  5. package/README.md +16 -1
  6. package/VERSION +1 -1
  7. package/docs/architecture.md +29 -13
  8. package/docs/cm-control-policy-v2.md +331 -0
  9. package/docs/execution-optimizations.md +1 -1
  10. package/docs/external-models.md +3 -3
  11. package/docs/fixes/20261013-claude-preinit-ui-invalidate.md +48 -0
  12. package/docs/human-correction.md +5 -5
  13. package/docs/installation.md +1 -1
  14. package/docs/js-workflow-control.md +104 -85
  15. package/docs/next-steps.md +11 -0
  16. package/docs/untested-branches.md +2 -3
  17. package/docs/user-guide.md +3 -3
  18. package/package.json +1 -1
  19. package/runtime/js/cm-ai/claude-review-stream.mjs +12 -8
  20. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +13 -69
  21. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +10 -5
  22. package/runtime/js/cm-ai/control-policy.mjs +112 -0
  23. package/runtime/js/cm-ai/drive-bootstrap.mjs +11 -8
  24. package/runtime/js/cm-ai/drive-core.mjs +124 -25
  25. package/runtime/js/cm-ai/durable-runner-state.mjs +32 -126
  26. package/runtime/js/cm-ai/gate-bridge.mjs +4 -4
  27. package/runtime/js/cm-ai/host-check.mjs +3 -1
  28. package/runtime/js/cm-ai/host-conversation-execution.mjs +22 -20
  29. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +11 -2
  30. package/runtime/js/cm-ai/host-qa-policy.mjs +63 -21
  31. package/runtime/js/cm-ai/host-review-authority.mjs +2 -2
  32. package/runtime/js/cm-ai/host-review-file.mjs +1 -1
  33. package/runtime/js/cm-ai/host-session.mjs +41 -8
  34. package/runtime/js/cm-ai/host-stage-observer.mjs +26 -0
  35. package/runtime/js/cm-ai/host-tool-bridge.mjs +25 -9
  36. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +21 -10
  37. package/runtime/js/cm-ai/host.mjs +1 -2
  38. package/runtime/js/cm-ai/operator-guidance.mjs +57 -54
  39. package/runtime/js/cm-ai/review-package.mjs +16 -4
  40. package/runtime/js/cm-ai/reviewed-deliveries.mjs +1 -1
  41. package/runtime/js/cm-ai/task-runner.mjs +41 -101
  42. package/runtime/js/cm-init/review-evidence.mjs +3 -1
  43. package/runtime/js/cm-prd/review-host.mjs +1 -1
  44. package/runtime/js/cm-prd/review-publication.mjs +5 -3
  45. package/runtime/js/cm-prd/summary.mjs +27 -12
  46. package/runtime/js/cm-refactor/workflow.mjs +1 -1
  47. package/runtime/js/notify-send.mjs +15 -14
  48. package/runtime/js/notify.mjs +27 -4
  49. package/runtime/js/policy-binding-compat.mjs +2 -1
  50. package/runtime/review.md +61 -7
  51. package/runtime/task-gates.md +107 -9
  52. package/scripts/cm-ai-abandon-effect-position.test.mjs +1 -8
  53. package/scripts/cm-ai-answer-gap-driver.test.mjs +12 -12
  54. package/scripts/cm-ai-answer-gap-fixture.mjs +1 -8
  55. package/scripts/cm-ai-batch-drive.mjs +50 -31
  56. package/scripts/cm-ai-batch-drive.test.mjs +62 -19
  57. package/scripts/cm-ai-batch-host.mjs +39 -20
  58. package/scripts/cm-ai-batch-host.test.mjs +83 -47
  59. package/scripts/cm-ai-batch-run-fixture.mjs +6 -53
  60. package/scripts/cm-ai-batch-run-member-stops.test.mjs +0 -12
  61. package/scripts/cm-ai-batch-run.mjs +46 -14
  62. package/scripts/cm-ai-bootstrap-flow.test.mjs +1 -7
  63. package/scripts/cm-ai-bootstrap.test.mjs +2 -3
  64. package/scripts/cm-ai-control-launch.test.mjs +219 -0
  65. package/scripts/cm-ai-control-policy.test.mjs +192 -0
  66. package/scripts/cm-ai-control-v2-drive.test.mjs +270 -0
  67. package/scripts/cm-ai-develop-answer-invalid.test.mjs +1 -8
  68. package/scripts/cm-ai-develop-call-timeout.test.mjs +1 -8
  69. package/scripts/cm-ai-develop-driver-gaps.test.mjs +33 -20
  70. package/scripts/cm-ai-direct-review.test.mjs +348 -0
  71. package/scripts/cm-ai-documentation-sync-gap.test.mjs +3 -3
  72. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +57 -27
  73. package/scripts/cm-ai-drive.mjs +96 -54
  74. package/scripts/cm-ai-drive.test.mjs +46 -87
  75. package/scripts/cm-ai-fix-integration.test.mjs +3 -5
  76. package/scripts/cm-ai-fix-later-delivery.test.mjs +3 -6
  77. package/scripts/cm-ai-fix-run-delivery.test.mjs +3 -6
  78. package/scripts/cm-ai-host-cli-workflow.test.mjs +6 -10
  79. package/scripts/cm-ai-host-fixture.mjs +47 -16
  80. package/scripts/cm-ai-host-protected.test.mjs +35 -33
  81. package/scripts/cm-ai-host.mjs +103 -93
  82. package/scripts/cm-ai-host.test.mjs +34 -18
  83. package/scripts/cm-ai-launch-diagnostics.test.mjs +5 -3
  84. package/scripts/cm-ai-legacy-history.test.mjs +53 -0
  85. package/scripts/cm-ai-light-modules.test.mjs +4 -7
  86. package/scripts/cm-ai-multi-root.test.mjs +4 -4
  87. package/scripts/cm-ai-nested-execution.test.mjs +16 -19
  88. package/scripts/cm-ai-operator-guidance.test.mjs +56 -0
  89. package/scripts/cm-ai-progress.test.mjs +10 -8
  90. package/scripts/cm-ai-project-qa-gate.test.mjs +37 -10
  91. package/scripts/cm-ai-protected-scope.test.mjs +1 -2
  92. package/scripts/cm-ai-qa-config-revision.test.mjs +1 -9
  93. package/scripts/cm-ai-qa-fingerprint-config.test.mjs +12 -9
  94. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +18 -3
  95. package/scripts/cm-ai-qa-fixed-log.test.mjs +41 -0
  96. package/scripts/cm-ai-qa-recovery-args.test.mjs +7 -0
  97. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +3 -4
  98. package/scripts/cm-ai-review-drift-precedence.test.mjs +1 -1
  99. package/scripts/cm-ai-review-failure.test.mjs +13 -19
  100. package/scripts/cm-ai-review-timeout-config.test.mjs +3 -1
  101. package/scripts/cm-ai-review-timeout.test.mjs +35 -128
  102. package/scripts/cm-ai-run.mjs +78 -24
  103. package/scripts/cm-ai-run.test.mjs +11 -38
  104. package/scripts/cm-ai-selection-guard.test.mjs +2 -2
  105. package/scripts/cm-ai-session-chain.test.mjs +18 -15
  106. package/scripts/cm-ai-spec-rebind.test.mjs +14 -18
  107. package/scripts/cm-ai-supersede.test.mjs +3 -10
  108. package/scripts/cm-blocked-reason.test.mjs +2 -3
  109. package/scripts/cm-capability-gate.test.mjs +33 -1
  110. package/scripts/cm-check-drive-files.mjs +1 -1
  111. package/scripts/cm-check-host.test.mjs +1 -1
  112. package/scripts/cm-check-runtime.sh +1 -1
  113. package/scripts/cm-claude-probe.test.mjs +26 -0
  114. package/scripts/cm-claude-review-stream.test.mjs +36 -0
  115. package/scripts/cm-claude-worker.test.mjs +21 -3
  116. package/scripts/cm-controlled-correction.test.mjs +469 -0
  117. package/scripts/cm-drive-liveness.test.mjs +83 -0
  118. package/scripts/cm-external-batch-host.test.mjs +38 -17
  119. package/scripts/cm-external-model-host.test.mjs +1 -1
  120. package/scripts/cm-external-model-recovery.test.mjs +3 -9
  121. package/scripts/cm-external-qa-fix.test.mjs +1 -1
  122. package/scripts/cm-external-review-reconciliation.test.mjs +6 -24
  123. package/scripts/cm-fix-review-recovery.test.mjs +1 -1
  124. package/scripts/cm-host-diagnostic.test.mjs +33 -0
  125. package/scripts/cm-host-liveness.test.mjs +150 -0
  126. package/scripts/cm-host-qa-executor.test.mjs +1 -2
  127. package/scripts/cm-host-qa-policy.test.mjs +43 -16
  128. package/scripts/cm-host-review-authority.test.mjs +0 -31
  129. package/scripts/cm-host-stage-observer.test.mjs +41 -0
  130. package/scripts/cm-knowledge-closeout.test.mjs +3 -3
  131. package/scripts/cm-notify-command.test.mjs +54 -18
  132. package/scripts/cm-notify-read-drift.test.mjs +69 -4
  133. package/scripts/cm-notify.mjs +16 -4
  134. package/scripts/cm-notify.test.mjs +135 -29
  135. package/scripts/cm-patrol.test.mjs +3 -2
  136. package/scripts/cm-prd-drive.test.mjs +1 -1
  137. package/scripts/cm-prd-self-check-revision.test.mjs +15 -0
  138. package/scripts/cm-prd-session-recovery.test.mjs +5 -3
  139. package/scripts/cm-prd-summary.test.mjs +31 -0
  140. package/scripts/cm-release-smoke.sh +2 -14
  141. package/scripts/cm-task-gate-correction.test.mjs +69 -16
  142. package/scripts/cm-task-gate.mjs +368 -34
  143. package/scripts/cm-task-gate.py +2 -0
  144. package/scripts/cm-task-gate.test.mjs +252 -4
  145. package/scripts/cm-test-suite.mjs +109 -0
  146. package/scripts/cm-test-suite.test.mjs +162 -0
  147. package/scripts/fixtures/bootstrap-review-runner.mjs +1 -7
  148. package/scripts/fixtures/host-diagnostic.mjs +33 -0
  149. package/scripts/fixtures/native-gate-fixture.mjs +18 -0
  150. package/scripts/policy-binding-compat.test.mjs +4 -0
  151. package/skills/cm-ai/SKILL.md +8 -6
  152. package/skills/cm-ai/references/N3-execute-task.md +17 -2
  153. package/skills/cm-ai/references/N4-review.md +11 -21
  154. package/skills/cm-ai/references/N5-mark-done.md +1 -1
  155. package/skills/cm-ai/references/N6-qa-eval.md +49 -21
  156. package/skills/cm-ai/references/js-host-modes.md +35 -14
  157. package/skills/cm-ai/references/js-host-qa-recovery.md +60 -12
  158. package/skills/cm-ai/references/js-host-recovery.md +95 -47
  159. package/skills/cm-ai/references/js-host.md +98 -29
  160. package/skills/cm-fix/SKILL.md +12 -0
  161. package/skills/cm-init/references/js-host.md +1 -1
  162. package/skills/cm-prd/references/js-host.md +1 -1
  163. package/skills/cm-refactor/SKILL.md +12 -0
  164. package/runtime/js/cm-ai/review-dispatch-limits.mjs +0 -18
  165. package/scripts/cm-ai-review-dispatch-exit.test.mjs +0 -475
@@ -9,6 +9,9 @@ import {fileURLToPath} from 'node:url';
9
9
  import {inspectFixWalkthrough,readFixWalkthrough,fixWalkthroughBinding} from '../runtime/js/cm-fix/walkthrough.mjs';
10
10
  import {inspectFixRegressionFailure} from '../runtime/js/cm-fix/regression-evidence.mjs';
11
11
  import {taskDeclarations,approvedTaskGrammar,TASK_GRAMMAR} from '../runtime/js/spec-task-line.mjs';
12
+ import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
13
+ import {snapshot,rootPath,reviewSpecsPath,stableIgnorePolicy,stablePublicPolicy,stableSnapshotPolicy,
14
+ comparableFiles,validateStablePolicy,filePath,INVENTORY_COUNT,INVENTORY_LIMIT} from '../runtime/js/cm-ai/review-package.mjs';
12
15
 
13
16
  const TASK_RE=/^T-[A-Za-z0-9][A-Za-z0-9._-]*$/;
14
17
  const REVIEWERS=new Set(['codex-subagent','codex-cli','claude-cli','self-degraded']);
@@ -221,6 +224,90 @@ function verifyImplementationBinding(payload,{projectRoot=null,allowLegacyUnboun
221
224
  return true;
222
225
  }
223
226
 
227
+ const INVENTORY_BASELINE_LIMIT=64*1024*1024;
228
+ const INVENTORY_UNVERIFIED='未捕获编辑前基线,不保证清单完整,只保证已列文件的内容绑定';
229
+ function baselinePath(reviewsDir,feature,task){
230
+ requireFeature(feature);requireTaskId(task,'task');
231
+ const info=fs.lstatSync(reviewsDir);
232
+ if(!info.isDirectory()||info.isSymbolicLink())throw new GateError('baseline reviews directory must be real');
233
+ return path.join(fs.realpathSync(reviewsDir),`${feature}-${task}-baseline.json`);
234
+ }
235
+ function inventoryContext(projectRoot,reviewsDir){
236
+ if(!projectRoot)throw new GateError('inventory baseline requires --project-root');
237
+ const root=rootPath(path.resolve(projectRoot)),reviews=fs.realpathSync(reviewsDir);
238
+ const parent=path.dirname(reviews);
239
+ // A nested canonical .reviews lives inside the specs root. At the code root,
240
+ // exclude only .reviews, never the entire code tree. External specs map to null.
241
+ const specsRoot=path.basename(reviews)==='.reviews'&&parent.startsWith(root+path.sep)?parent:reviews;
242
+ return {root,specsPath:reviewSpecsPath(root,specsRoot)};
243
+ }
244
+ const inventoryFiles=(root,specsPath,policy)=>snapshot(root,specsPath,null,[],new Set(),policy,true)
245
+ .map(({path,sha256,size,mode})=>({path,sha256,size,mode:mode&0o111}));
246
+ export function captureBaseline({projectRoot,reviewsDir,feature,task}){
247
+ try{
248
+ const target=baselinePath(reviewsDir,feature,task);
249
+ try{fs.lstatSync(target);throw new GateError(`baseline already exists; refusing overwrite: ${target}`);}
250
+ catch(error){if(error.code!=='ENOENT')throw error;}
251
+ const {root,specsPath}=inventoryContext(projectRoot,reviewsDir),policy=stableIgnorePolicy(root);
252
+ const data={kind:'cm-task-inventory-baseline',identity:{feature,task},rootDigest:createHash('sha256').update(root).digest('hex'),
253
+ specsPath,ignorePolicy:stablePublicPolicy(policy),files:inventoryFiles(root,specsPath,policy),capturedAt:new Date().toISOString()};
254
+ const baseline={...data,baselineDigest:digest(data)},encoded=JSON.stringify(baseline,null,2)+'\n';
255
+ if(Buffer.byteLength(encoded)>INVENTORY_BASELINE_LIMIT)throw new GateError('limit_exceeded: baseline metadata');
256
+ fs.writeFileSync(target,encoded,{flag:'wx',mode:0o600});
257
+ return {gate:'capture-baseline',outcome:'captured',baseline:target,baseline_sha256:baseline.baselineDigest,files:baseline.files.length};
258
+ }catch(error){if(error instanceof GateError)throw error;throw new GateError(error.message);}
259
+ }
260
+ function readInventoryBaseline(file,{root,specsPath},feature,task){
261
+ try{
262
+ const text=new TextDecoder('utf8',{fatal:true}).decode(fileRevision(file,INVENTORY_BASELINE_LIMIT).bytes);
263
+ parseJsonStrict(text); // Reject duplicate keys before the ordinary numeric decoder.
264
+ const b=JSON.parse(text);
265
+ exactFields(b,['kind','identity','rootDigest','specsPath','ignorePolicy','files','capturedAt','baselineDigest'],'baseline');
266
+ exactFields(b.identity,['feature','task'],'baseline identity');
267
+ const {baselineDigest,...data}=b;
268
+ if(b.kind!=='cm-task-inventory-baseline'||b.identity.feature!==feature||b.identity.task!==task
269
+ ||b.rootDigest!==createHash('sha256').update(root).digest('hex')||b.specsPath!==specsPath||digest(data)!==baselineDigest
270
+ ||typeof b.capturedAt!=='string'||!/(?:Z|[+-]\d{2}:\d{2})$/.test(b.capturedAt)||Number.isNaN(Date.parse(b.capturedAt)))
271
+ throw new GateError('invalid inventory baseline identity or digest');
272
+ validateStablePolicy(b.ignorePolicy);
273
+ if(!Array.isArray(b.files)||b.files.length>INVENTORY_COUNT)throw new GateError('invalid inventory baseline files');
274
+ let previous=null,total=0;const aliases=new Set();
275
+ for(const f of b.files){
276
+ exactFields(f,['path','sha256','size','mode'],'baseline file');filePath(f.path);
277
+ if(previous!==null&&previous>=f.path||aliases.has(f.path.toLowerCase())
278
+ ||typeof f.sha256!=='string'||!/^([a-f0-9]{64})$/.test(f.sha256)
279
+ ||!Number.isSafeInteger(f.size)||f.size<0||!Number.isInteger(f.mode)||f.mode<0||(f.mode&0o111)!==f.mode
280
+ ||f.path==='.reviews'||f.path.startsWith('.reviews/')||specsPath!==null&&(f.path===specsPath||f.path.startsWith(specsPath+'/')))
281
+ throw new GateError('invalid inventory baseline file');
282
+ previous=f.path;aliases.add(f.path.toLowerCase());total+=f.size;
283
+ if(total>INVENTORY_LIMIT)throw new GateError('invalid inventory baseline budget');
284
+ }
285
+ return b;
286
+ }catch(error){throw new GateError(`invalid inventory baseline: ${error.message}`);}
287
+ }
288
+ function verifyInventory(payload,{projectRoot,reviewsDir,feature,task,allowLegacyUnbound=false}){
289
+ try{
290
+ const file=baselinePath(reviewsDir,feature,task);
291
+ try{fs.lstatSync(file);}catch(error){
292
+ if(error.code!=='ENOENT')throw error;
293
+ if(allowLegacyUnbound)return {inventory:'unverified',inventory_note:INVENTORY_UNVERIFIED};
294
+ throw new GateError('missing editing baseline; capture-baseline before edits; legacy recovery requires --allow-legacy-unbound');
295
+ }
296
+ const context=inventoryContext(projectRoot,reviewsDir),b=readInventoryBaseline(file,context,feature,task);
297
+ const policy=stableSnapshotPolicy(context.root,b.ignorePolicy);
298
+ const before=new Map(comparableFiles(b.files,policy,new Set()).map(f=>[f.path,f]));
299
+ const after=new Map(inventoryFiles(context.root,context.specsPath,policy).map(f=>[f.path,f]));
300
+ const changes=[...new Set([...before.keys(),...after.keys()])].sort().filter(p=>digest(before.get(p)??null)!==digest(after.get(p)??null));
301
+ const listed=new Set(payload.changed_files),actual=new Set(changes);
302
+ const omitted=changes.filter(p=>!listed.has(p)),extra=[...listed].filter(p=>!actual.has(p)).sort();
303
+ const show=paths=>paths.slice(0,20).join(', ')+(paths.length>20?` (+${paths.length-20} more)`:'');
304
+ if(omitted.length||extra.length)throw new GateError(`changed_files inventory mismatch; 改了但没列: ${show(omitted)||'(无)'}; 列了但没改: ${show(extra)||'(无)'}`);
305
+ const counts={added:0,modified:0,deleted:0};
306
+ for(const p of changes)counts[!before.has(p)?'added':!after.has(p)?'deleted':'modified']++;
307
+ return {inventory:'verified',inventory_counts:counts,baseline_sha256:b.baselineDigest};
308
+ }catch(error){if(error instanceof GateError)throw error;throw new GateError(error.message);}
309
+ }
310
+
224
311
  function sameSet(actual,expected){
225
312
  return actual.size===expected.size&&[...actual].every(item=>expected.has(item));
226
313
  }
@@ -341,13 +428,14 @@ export function validateReview(review,{task,attempt,handoff,changedFiles}){
341
428
  const reviewRound=integerHeader(header.round,'review attempt and round');
342
429
  if(reviewAttempt!==BigInt(attempt)||reviewRound!==BigInt(attempt))
343
430
  throw new GateError('review attempt and round must match the handoff attempt');
344
- if(!REVIEWERS.has(header.reviewer))throw new GateError(`unsupported reviewer channel: ${header.reviewer}`);
431
+ // Source declarations only: validate spelling and consistency, not reviewer identity.
432
+ if(!REVIEWERS.has(header.reviewer))throw new GateError(`unsupported reviewer source declaration: ${header.reviewer}`);
345
433
  const independent=header.independent.toLowerCase();
346
- if(!['true','false'].includes(independent))throw new GateError('review independent must be true or false');
434
+ if(!['true','false'].includes(independent))throw new GateError('review independent declaration must be true or false');
347
435
  if(header.reviewer==='self-degraded'&&independent!=='false')
348
436
  throw new GateError('self-degraded review must declare independent: false');
349
437
  if(header.reviewer!=='self-degraded'&&independent!=='true')
350
- throw new GateError('independent review channel must declare independent: true');
438
+ throw new GateError('reviewer source declaration must declare independent: true');
351
439
  if(!VERDICTS.has(header.verdict))throw new GateError(`unsupported review verdict: ${header.verdict}`);
352
440
  const blocking=integerHeader(header.blocking_findings,'review blocking_findings');
353
441
  if(blocking<0n)throw new GateError('review blocking_findings must not be negative');
@@ -472,8 +560,9 @@ function verifyLearningRecord(payload,projectRoot){
472
560
  throw new GateError('Learning requires a content-bound handoff');
473
561
  }
474
562
 
475
- // A single explicitly authorized human continuation after a blocked second
476
- // round. The ordinary two-attempt chain and original evidence stay intact.
563
+ // A single correction continuation after a declared blocked second round.
564
+ // Source declarations do not prove human approval or reviewer independence.
565
+ // The ordinary two-attempt chain and original evidence stay intact.
477
566
  function correctionPaths(reviewsDir,feature,task){
478
567
  requireFeature(feature);requireTaskId(task,'task');
479
568
  const info=fs.lstatSync(reviewsDir);
@@ -499,7 +588,7 @@ function correctionHistory({reviewsDir,feature,task,projectRoot}){
499
588
  const review=reviewPath(reviewsDir,feature,task,2);
500
589
  const header=validateReview(review,{task,attempt:2,handoff,changedFiles:payload.changed_files});
501
590
  if(header.verdict!=='blocked'||header.independent!=='true')
502
- throw new GateError('human correction requires an independent blocked round 2');
591
+ throw new GateError('human correction requires blocked round 2 declaring independent: true');
503
592
  const files=[expectedHandoff(reviewsDir,feature,task,1),reviewPath(reviewsDir,feature,task,1),handoff,review];
504
593
  const revisions=files.map(file=>fileRevision(file,PREPARATION_FILE_LIMIT));
505
594
  requireRevisions(revisions);
@@ -513,10 +602,11 @@ function boundCorrectionHandoff(handoff,task,projectRoot){
513
602
  return payload;
514
603
  }
515
604
  export function prepareHumanCorrection(selectors){
516
- const {reviewsDir,feature,task,handoff,projectRoot,humanAuthorized,reason}=selectors;
517
- if(humanAuthorized!==true)throw new GateError('human correction requires explicit human authorization');
605
+ const {reviewsDir,feature,task,handoff,projectRoot,reason}=selectors;
518
606
  if(typeof reason!=='string'||!reason.trim()||reason.length>2000)
519
607
  throw new GateError('human correction requires a concrete bounded reason');
608
+ return withCorrectionPreparation(selectors,()=>{
609
+ noCorrectionEvidence(controlledCorrectionPaths(reviewsDir,feature,task),{includeOrphan:false});
520
610
  const paths=correctionPaths(reviewsDir,feature,task);
521
611
  absent(paths.record);absent(paths.review);absent(paths.receipt);
522
612
  const original=correctionHistory(selectors),draft=fileRevision(handoff,PREPARATION_FILE_LIMIT);
@@ -525,20 +615,23 @@ export function prepareHumanCorrection(selectors){
525
615
  throw new GateError('human correction must retain the full original reviewed file scope');
526
616
  requireRevisions([...original.revisions,draft]);
527
617
  // Permit only an identical orphan handoff after interruption before record
528
- // creation. Published authorization/review/receipt are never overwritten.
618
+ // creation. Published source record/review/receipt are never overwritten.
529
619
  try{absent(paths.handoff);fs.writeFileSync(paths.handoff,draft.bytes,{flag:'wx',mode:0o600});}
530
620
  catch(error){
531
621
  if(error instanceof GateError&&!fs.existsSync(paths.record)&&fileRevision(paths.handoff,PREPARATION_FILE_LIMIT).bytes.equals(draft.bytes)){}
532
622
  else throw error;
533
623
  }
624
+ // Keep the legacy source label for record compatibility; it is not verified approval.
534
625
  const record={version:1,protocol:'cm-human-correction',feature,task,attempt:2,
535
626
  authorization:'explicit-human-confirmation',at:new Date().toISOString(),reason:reason.trim(),
536
627
  history:original.history,handoff_sha256:sha256(paths.handoff)};
537
628
  requireRevisions(original.revisions);
538
629
  boundCorrectionHandoff(paths.handoff,task,projectRoot);
630
+ noCorrectionEvidence(controlledCorrectionPaths(reviewsDir,feature,task),{includeOrphan:false});
539
631
  fs.writeFileSync(paths.record,JSON.stringify(record,null,2)+'\n',{flag:'wx',mode:0o600});
540
632
  return {outcome:'ready_for_correction_review',correction:paths.record,handoff:paths.handoff,
541
633
  review:paths.review,correction_sha256:sha256(paths.record),attempt:2};
634
+ });
542
635
  }
543
636
  function inspectHumanCorrection(selectors){
544
637
  const {reviewsDir,feature,task,correction,handoff,projectRoot}=selectors;
@@ -552,7 +645,7 @@ function inspectHumanCorrection(selectors){
552
645
  ||record.attempt!==2n||record.authorization!=='explicit-human-confirmation'
553
646
  ||typeof record.reason!=='string'||!record.reason.trim()||record.reason.length>2000
554
647
  ||typeof record.at!=='string'||!/(?:Z|[+-]\d{2}:\d{2})$/.test(record.at)||Number.isNaN(Date.parse(record.at)))
555
- throw new GateError('invalid human correction authorization record');
648
+ throw new GateError('invalid human correction source declaration record');
556
649
  const original=correctionHistory(selectors);
557
650
  if(canonical(record.history)!==canonical(original.history))throw new GateError('human correction history changed');
558
651
  const payload=boundCorrectionHandoff(paths.handoff,task,projectRoot);
@@ -569,7 +662,7 @@ export function publishHumanCorrectionReview(selectors){
569
662
  const pinned=fileRevision(paths.review,PREPARATION_FILE_LIMIT);
570
663
  const header=validateReview(paths.review,{task:selectors.task,attempt:2,handoff:paths.handoff,changedFiles:payload.changed_files});
571
664
  if(header.independent!=='true'||header.correction_sha256!==correctionDigest)
572
- throw new GateError('human correction requires fresh independent review bound to the correction record');
665
+ throw new GateError('human correction requires review declaring independent: true bound to the correction record');
573
666
  requireRevisions([pinned]);
574
667
  inspectHumanCorrection(selectors);
575
668
  const receipt={version:1,protocol:'cm-human-correction-review',correction_sha256:correctionDigest,
@@ -579,10 +672,11 @@ export function publishHumanCorrectionReview(selectors){
579
672
  }
580
673
  function checkHumanCorrection(selectors,stage){
581
674
  const {paths,payload,correctionDigest}=inspectHumanCorrection(selectors);
675
+ const inventory=selectors.inventory==='required'?verifyInventory(payload,selectors):{};
582
676
  if(stage==='n4'){
583
677
  absent(paths.receipt);
584
678
  return {gate:'n4',task:selectors.task,attempt:2,outcome:'ready_for_review',content_bound:true,
585
- handoff_sha256:sha256(paths.handoff),correction_sha256:correctionDigest};
679
+ handoff_sha256:sha256(paths.handoff),correction_sha256:correctionDigest,...inventory};
586
680
  }
587
681
  const pinned=fileRevision(paths.review,PREPARATION_FILE_LIMIT);
588
682
  const result=validateReview(paths.review,{task:selectors.task,attempt:2,handoff:paths.handoff,changedFiles:payload.changed_files});
@@ -596,11 +690,243 @@ function checkHumanCorrection(selectors,stage){
596
690
  if(result.verdict!=='approved'||result.independent!=='true')throw new GateError('human correction remains blocked');
597
691
  requireRevisions([pinned,receiptRevision]);
598
692
  return {gate:'n5',task:selectors.task,attempt:2,outcome:'approved',review:paths.review,
599
- content_bound:true,correction_sha256:correctionDigest};
693
+ content_bound:true,correction_sha256:correctionDigest,...inventory};
694
+ }
695
+
696
+ // Provenance is a declaration of who selected this bounded continuation. It is
697
+ // neither authenticated identity nor authorization, and never a review verdict.
698
+ function controlledCorrectionPaths(reviewsDir,feature,task){
699
+ const root=path.dirname(correctionPaths(reviewsDir,feature,task).record);
700
+ const prefix=path.join(root,`${feature}-${task}-controlled-correction`);
701
+ return {record:prefix+'.json',handoff:prefix+'-handoff.json',review:prefix+'.md',receipt:prefix+'-receipt.json'};
702
+ }
703
+ function noCorrectionEvidence(paths,{includeOrphan=true}={}){
704
+ for(const [kind,file] of Object.entries(paths)){
705
+ if(kind==='handoff'&&!includeOrphan)continue;
706
+ try{fs.lstatSync(file);throw new GateError('a correction continuation already exists; another continuation is forbidden');}
707
+ catch(error){if(error.code!=='ENOENT')throw error;}
708
+ }
709
+ }
710
+ function withCorrectionPreparation(selectors,action){
711
+ const {reviewsDir,feature,task}=selectors;
712
+ const lock=path.join(path.dirname(correctionPaths(reviewsDir,feature,task).record),`${feature}-${task}-correction-prepare.lock`);
713
+ let descriptor;
714
+ try{descriptor=fs.openSync(lock,fs.constants.O_WRONLY|fs.constants.O_CREAT|fs.constants.O_EXCL|fs.constants.O_NOFOLLOW,0o600);}
715
+ catch(error){
716
+ if(error.code==='EEXIST')throw new GateError(`blocked: correction preparation lock already exists; verify owner exit and reconcile retained evidence before removing ${lock}`);
717
+ throw error;
718
+ }
719
+ const owner=fs.fstatSync(descriptor,{bigint:true});
720
+ try{
721
+ fs.writeFileSync(descriptor,JSON.stringify({version:1,protocol:'cm-correction-prepare-lock',pid:process.pid,at:new Date().toISOString()})+'\n');
722
+ return action();
723
+ }finally{
724
+ try{
725
+ const current=fs.lstatSync(lock,{bigint:true});
726
+ if(!current.isFile()||current.isSymbolicLink()||current.nlink!==1n||current.dev!==owner.dev||current.ino!==owner.ino)
727
+ throw new GateError('blocked: correction preparation lock ownership changed; retained for reconciliation');
728
+ fs.unlinkSync(lock);
729
+ }finally{fs.closeSync(descriptor);}
730
+ }
731
+ }
732
+ function controlledCorrectionPayload(handoff,task,projectRoot,original){
733
+ const payload=boundCorrectionHandoff(handoff,task,projectRoot);
734
+ if(!sameSet(new Set(original.payload.changed_files),new Set(payload.changed_files)))
735
+ throw new GateError('controlled correction must retain the full original reviewed file scope');
736
+ if(payload.implementation_sha256===original.payload.implementation_sha256)
737
+ throw new GateError('controlled correction requires an actual implementation revision after blocked round 2');
738
+ return payload;
739
+ }
740
+ // This utility finishes through the compatibility writer, which cannot adopt a
741
+ // retained JS run. Refuse before preparing evidence that it could never consume.
742
+ function assertCompatibilityCorrectionOwner(reviewsDir){
743
+ const requested=path.resolve(reviewsDir),directory=fs.lstatSync(requested);
744
+ if(path.basename(requested)!=='.reviews'||!directory.isDirectory()||directory.isSymbolicLink())
745
+ throw new GateError('task ownership requires the canonical real non-symlink .reviews directory');
746
+ const local=fs.realpathSync(reviewsDir),roots=new Set([local]);
747
+ const binding=path.join(local,'.cm-task-owner.json');
748
+ let hasBinding=false;try{fs.lstatSync(binding);hasBinding=true;}catch(error){if(error.code!=='ENOENT')throw error;}
749
+ if(hasBinding){
750
+ const owner=parseJsonStrict(new TextDecoder('utf8',{fatal:true}).decode(fileRevision(binding,16384).bytes));
751
+ exactFields(owner,['version','tasksPath','specsRoot'],'task owner');
752
+ if(owner.version!==1n||typeof owner.specsRoot!=='string'||typeof owner.tasksPath!=='string'
753
+ ||path.dirname(owner.tasksPath)!==path.dirname(local)||path.basename(owner.tasksPath)!=='tasks.md'
754
+ ||![path.dirname(local),path.dirname(path.dirname(local))].includes(owner.specsRoot))
755
+ throw new GateError('invalid task owner; controlled correction requires the compatibility writer');
756
+ roots.add(path.join(owner.specsRoot,'.reviews'));
757
+ }
758
+ for(const root of roots){
759
+ try{
760
+ const directory=fs.lstatSync(root);
761
+ if(path.basename(root)!=='.reviews'||!directory.isDirectory()||directory.isSymbolicLink())
762
+ throw new GateError('task ownership requires the canonical real non-symlink .reviews directory');
763
+ }catch(error){if(error.code==='ENOENT')continue;throw error;}
764
+ const execution=path.join(root,'.execution');
765
+ let names;
766
+ try{
767
+ const stat=fs.lstatSync(execution);
768
+ if(!stat.isDirectory()||stat.isSymbolicLink())throw new GateError('unsupported execution owner evidence');
769
+ names=fs.readdirSync(execution);
770
+ }catch(error){if(error.code==='ENOENT')continue;throw error;}
771
+ for(const name of names){
772
+ if(!['writer.sqlite','writer-ready.json'].includes(name))
773
+ throw new GateError('retained journal, JS run or unknown evidence blocks compatibility controlled correction');
774
+ const item=fs.lstatSync(path.join(execution,name));
775
+ if(!item.isFile()||item.isSymbolicLink()||item.nlink!==1||item.size>65536||(item.mode&0o077)!==0)
776
+ throw new GateError('unsupported compatibility writer evidence');
777
+ }
778
+ // Mirror the compatibility writer's own initialization contract (cm-task-gate.py
779
+ // posix_writer/writer_ready) read-only: evidence it would refuse to adopt must
780
+ // refuse preparation here, before any correction artifact exists.
781
+ const hasDatabase=names.includes('writer.sqlite'),hasReady=names.includes('writer-ready.json');
782
+ if(hasReady&&!hasDatabase)throw new GateError('missing writer database with retained execution evidence');
783
+ if(hasDatabase){
784
+ const content=fs.readFileSync(path.join(execution,'writer.sqlite'));
785
+ if(content.length===0||!hasReady)throw new GateError('incomplete writer database');
786
+ const expected=JSON.stringify({version:1,protocol:'cm-writer-ready',databaseDigest:createHash('sha256').update(content).digest('hex')})+'\n';
787
+ if(fs.readFileSync(path.join(execution,'writer-ready.json'),'utf8')!==expected)
788
+ throw new GateError('invalid writer readiness; refusing recovery/adoption');
789
+ }
790
+ }
791
+ }
792
+ export function prepareControlledCorrection(selectors){
793
+ const {reviewsDir,feature,task,handoff,projectRoot,decisionSource,reason}=selectors;
794
+ if(!['operator','model'].includes(decisionSource))
795
+ throw new GateError('controlled correction requires decision source: operator or model; source is provenance only');
796
+ if(typeof reason!=='string'||!reason.trim()||reason.length>2000)
797
+ throw new GateError('controlled correction requires a concrete bounded reason');
798
+ return withCorrectionPreparation(selectors,()=>{
799
+ assertCompatibilityCorrectionOwner(reviewsDir);
800
+ const paths=controlledCorrectionPaths(reviewsDir,feature,task);
801
+ noCorrectionEvidence(correctionPaths(reviewsDir,feature,task),{includeOrphan:false});
802
+ absent(paths.record);absent(paths.review);absent(paths.receipt);
803
+ const original=correctionHistory(selectors),draft=fileRevision(handoff,PREPARATION_FILE_LIMIT);
804
+ controlledCorrectionPayload(handoff,task,projectRoot,original);
805
+ requireRevisions([...original.revisions,draft]);
806
+ // The only recoverable orphan is the exact handoff written before the record.
807
+ try{absent(paths.handoff);fs.writeFileSync(paths.handoff,draft.bytes,{flag:'wx',mode:0o600});}
808
+ catch(error){
809
+ if(error instanceof GateError&&!fs.existsSync(paths.record)&&fileRevision(paths.handoff,PREPARATION_FILE_LIMIT).bytes.equals(draft.bytes)){}
810
+ else throw error;
811
+ }
812
+ const record={version:2,protocol:'cm-controlled-correction',feature,task,attempt:2,continuation:1,
813
+ decision_source:decisionSource,source_semantics:'provenance-only',at:new Date().toISOString(),reason:reason.trim(),
814
+ history:original.history,handoff_sha256:sha256(paths.handoff)};
815
+ requireRevisions(original.revisions);
816
+ controlledCorrectionPayload(paths.handoff,task,projectRoot,original);
817
+ assertCompatibilityCorrectionOwner(reviewsDir);
818
+ noCorrectionEvidence(correctionPaths(reviewsDir,feature,task),{includeOrphan:false});
819
+ fs.writeFileSync(paths.record,JSON.stringify(record,null,2)+'\n',{flag:'wx',mode:0o600});
820
+ return {outcome:'ready_for_correction_review',correction:paths.record,handoff:paths.handoff,
821
+ review:paths.review,correction_sha256:sha256(paths.record),attempt:2,continuation:1};
822
+ });
823
+ }
824
+ function inspectControlledCorrection(selectors){
825
+ const {reviewsDir,feature,task,correction,handoff,projectRoot}=selectors;
826
+ assertCompatibilityCorrectionOwner(reviewsDir);
827
+ const paths=controlledCorrectionPaths(reviewsDir,feature,task);
828
+ if(typeof correction!=='string'||typeof handoff!=='string'||path.resolve(correction)!==paths.record||path.resolve(handoff)!==paths.handoff)
829
+ throw new GateError('controlled correction must use its fixed evidence paths');
830
+ // A losing concurrent preparation may leave an unsealed handoff. That does
831
+ // not invalidate this already-published continuation; sealed peers do.
832
+ noCorrectionEvidence(correctionPaths(reviewsDir,feature,task),{includeOrphan:false});
833
+ const pinned=fileRevision(paths.record,PREPARATION_FILE_LIMIT);
834
+ const record=parseJsonStrict(new TextDecoder('utf8',{fatal:true}).decode(pinned.bytes));
835
+ exactFields(record,['version','protocol','feature','task','attempt','continuation','decision_source','source_semantics','at','reason','history','handoff_sha256'],'controlled correction');
836
+ if(record.version!==2n||record.protocol!=='cm-controlled-correction'||record.feature!==feature||record.task!==task
837
+ ||record.attempt!==2n||record.continuation!==1n||!['operator','model'].includes(record.decision_source)
838
+ ||record.source_semantics!=='provenance-only'
839
+ ||typeof record.reason!=='string'||!record.reason.trim()||record.reason.length>2000
840
+ ||typeof record.at!=='string'||!/(?:Z|[+-]\d{2}:\d{2})$/.test(record.at)||Number.isNaN(Date.parse(record.at)))
841
+ throw new GateError('invalid controlled correction provenance record');
842
+ const original=correctionHistory(selectors);
843
+ if(canonical(record.history)!==canonical(original.history))throw new GateError('controlled correction history changed');
844
+ const handoffRevision=fileRevision(paths.handoff,PREPARATION_FILE_LIMIT);
845
+ const payload=controlledCorrectionPayload(paths.handoff,task,projectRoot,original);
846
+ if(record.handoff_sha256!==createHash('sha256').update(handoffRevision.bytes).digest('hex'))
847
+ throw new GateError('controlled correction handoff changed');
848
+ requireRevisions([pinned,handoffRevision,...original.revisions]);
849
+ return {paths,payload,record,correctionDigest:createHash('sha256').update(pinned.bytes).digest('hex')};
850
+ }
851
+ function controlledCorrectionReview(selectors,inspected){
852
+ const {paths,payload,record,correctionDigest}=inspected;
853
+ const header=validateReview(paths.review,{task:selectors.task,attempt:2,handoff:paths.handoff,changedFiles:payload.changed_files});
854
+ if(header.independent!=='true'||header.correction_sha256!==correctionDigest||Date.parse(header.at)<Date.parse(record.at))
855
+ throw new GateError('controlled correction requires fresh independent review bound to the correction record');
856
+ // Version 2 bodies use an exhaustive structured findings contract. Prose
857
+ // containing a zero-findings phrase cannot erase an active finding.
858
+ let result;
859
+ try{result=parseJsonStrict(parseReview(paths.review).body);}
860
+ catch{throw new GateError('controlled correction review requires a strict structured findings JSON body');}
861
+ exactFields(result,['conclusion','findings','resolved_findings'],'controlled correction structured findings');
862
+ if(!Array.isArray(result.findings)||!Array.isArray(result.resolved_findings))
863
+ throw new GateError('controlled correction structured findings must be arrays');
864
+ const ids=new Set();
865
+ for(const finding of [...result.findings,...result.resolved_findings]){
866
+ exactFields(finding,['id','priority','evidence'],'controlled correction structured finding');
867
+ requireString(finding.id,'controlled correction finding id');
868
+ requireString(finding.evidence,'controlled correction finding evidence');
869
+ if(!['P0','P1','P2','P3'].includes(finding.priority)||ids.has(finding.id))
870
+ throw new GateError('controlled correction findings require unique ids and P0-P3 priorities');
871
+ ids.add(finding.id);
872
+ }
873
+ if(integerHeader(header.blocking_findings,'review blocking_findings')!==BigInt(result.findings.length))
874
+ throw new GateError('controlled correction finding count does not match blocking_findings');
875
+ if(header.verdict==='approved'&&(result.conclusion!=='Zero findings.'||result.findings.length!==0))
876
+ throw new GateError('controlled correction approved review must have zero active findings');
877
+ if(header.verdict!=='approved'&&result.conclusion!=='Blocking findings.')
878
+ throw new GateError('controlled correction blocked review must declare Blocking findings.');
879
+ return header;
880
+ }
881
+ export function publishControlledCorrectionReview(selectors){
882
+ const inspected=inspectControlledCorrection(selectors),{paths,correctionDigest}=inspected;
883
+ absent(paths.receipt);
884
+ const pinned=fileRevision(paths.review,PREPARATION_FILE_LIMIT);
885
+ const header=controlledCorrectionReview(selectors,inspected);
886
+ requireRevisions([pinned]);
887
+ inspectControlledCorrection(selectors);
888
+ const receipt={version:2,protocol:'cm-controlled-correction-review',correction_sha256:correctionDigest,
889
+ review_sha256:createHash('sha256').update(pinned.bytes).digest('hex'),verdict:header.verdict};
890
+ fs.writeFileSync(paths.receipt,JSON.stringify(receipt,null,2)+'\n',{flag:'wx',mode:0o600});
891
+ return {outcome:header.verdict,receipt:paths.receipt};
892
+ }
893
+ function checkControlledCorrection(selectors,stage){
894
+ const inspected=inspectControlledCorrection(selectors),{paths,payload,correctionDigest}=inspected;
895
+ const inventory=selectors.inventory==='required'?verifyInventory(payload,selectors):{};
896
+ if(stage==='n4'){
897
+ absent(paths.receipt);
898
+ return {gate:'n4',task:selectors.task,attempt:2,continuation:1,outcome:'ready_for_review',content_bound:true,
899
+ handoff_sha256:sha256(paths.handoff),correction_sha256:correctionDigest,...inventory};
900
+ }
901
+ const pinned=fileRevision(paths.review,PREPARATION_FILE_LIMIT);
902
+ const result=controlledCorrectionReview(selectors,inspected);
903
+ const receiptRevision=fileRevision(paths.receipt,PREPARATION_FILE_LIMIT);
904
+ const receipt=parseJsonStrict(new TextDecoder('utf8',{fatal:true}).decode(receiptRevision.bytes));
905
+ exactFields(receipt,['version','protocol','correction_sha256','review_sha256','verdict'],'controlled correction receipt');
906
+ if(receipt.version!==2n||receipt.protocol!=='cm-controlled-correction-review'
907
+ ||receipt.correction_sha256!==correctionDigest||receipt.review_sha256!==sha256(paths.review)||receipt.verdict!==result.verdict)
908
+ throw new GateError('controlled correction review or receipt changed');
909
+ if(result.verdict!=='approved')throw new GateError('controlled correction remains blocked');
910
+ requireRevisions([pinned,receiptRevision]);
911
+ return {gate:'n5',task:selectors.task,attempt:2,continuation:1,outcome:'approved',review:paths.review,
912
+ content_bound:true,correction_sha256:correctionDigest,...inventory};
913
+ }
914
+ function selectedCorrectionPaths(selectors){
915
+ const {reviewsDir,feature,task,correction}=selectors;
916
+ const controlled=controlledCorrectionPaths(reviewsDir,feature,task);
917
+ return typeof correction==='string'&&path.resolve(correction)===controlled.record
918
+ ?controlled:correctionPaths(reviewsDir,feature,task);
919
+ }
920
+ function checkCorrection(selectors,stage){
921
+ const paths=selectedCorrectionPaths(selectors);
922
+ return paths.record.endsWith('-controlled-correction.json')
923
+ ?checkControlledCorrection(selectors,stage):checkHumanCorrection(selectors,stage);
600
924
  }
601
925
 
602
- export function checkN4({handoff,reviewsDir,feature,task,projectRoot=null,allowLegacyUnbound=false,requireLearning=false,correction=null}){
603
- if(correction!==null)return checkHumanCorrection({handoff,reviewsDir,feature,task,projectRoot,correction},'n4');
926
+ // Only compatibility CLI entries opt into inventory validation. Library callers
927
+ // retain the original content-binding contract and exact result shape.
928
+ export function checkN4({handoff,reviewsDir,feature,task,projectRoot=null,allowLegacyUnbound=false,requireLearning=false,correction=null,inventory=null}){
929
+ if(correction!==null)return checkCorrection({handoff,reviewsDir,feature,task,projectRoot,correction,allowLegacyUnbound,inventory},'n4');
604
930
  requireTaskId(task,'task');
605
931
  const payload=loadHandoff(handoff,{task});
606
932
  if(payload.status!=='ready_for_review')throw new GateError('N4 requires a ready_for_review handoff');
@@ -609,11 +935,12 @@ export function checkN4({handoff,reviewsDir,feature,task,projectRoot=null,allowL
609
935
  requireExpectedHandoff(handoff,{reviewsDir,feature,task,attempt});
610
936
  validateAttemptChain(reviewsDir,feature,task,attempt,payload,projectRoot);
611
937
  const contentBound=verifyImplementationBinding(payload,{projectRoot,allowLegacyUnbound});
612
- return {gate:'n4',task,attempt,outcome:'ready_for_review',handoff_sha256:sha256(handoff),content_bound:contentBound};
938
+ const inventoryResult=inventory==='required'?verifyInventory(payload,{projectRoot,reviewsDir,feature,task,allowLegacyUnbound}):{};
939
+ return {gate:'n4',task,attempt,outcome:'ready_for_review',handoff_sha256:sha256(handoff),content_bound:contentBound,...inventoryResult};
613
940
  }
614
941
 
615
- export function checkN5({handoff,reviewsDir,feature,task,projectRoot=null,allowLegacyUnbound=false,requireLearning=false,correction=null}){
616
- if(correction!==null)return checkHumanCorrection({handoff,reviewsDir,feature,task,projectRoot,correction},'n5');
942
+ export function checkN5({handoff,reviewsDir,feature,task,projectRoot=null,allowLegacyUnbound=false,requireLearning=false,correction=null,inventory=null}){
943
+ if(correction!==null)return checkCorrection({handoff,reviewsDir,feature,task,projectRoot,correction,allowLegacyUnbound,inventory},'n5');
617
944
  requireTaskId(task,'task');
618
945
  const payload=loadHandoff(handoff,{task});
619
946
  if(payload.status!=='ready_for_review')throw new GateError('N5 requires a ready_for_review handoff');
@@ -622,12 +949,13 @@ export function checkN5({handoff,reviewsDir,feature,task,projectRoot=null,allowL
622
949
  requireExpectedHandoff(handoff,{reviewsDir,feature,task,attempt});
623
950
  validateAttemptChain(reviewsDir,feature,task,attempt,payload,projectRoot);
624
951
  const contentBound=verifyImplementationBinding(payload,{projectRoot,allowLegacyUnbound});
952
+ const inventoryResult=inventory==='required'?verifyInventory(payload,{projectRoot,reviewsDir,feature,task,allowLegacyUnbound}):{};
625
953
  const review=reviewPath(reviewsDir,feature,task,attempt);
626
954
  const result=validateReview(review,{task,attempt,handoff,changedFiles:payload.changed_files});
627
955
  if(result.verdict!=='approved')throw new GateError(`N5 requires verdict: approved, got ${result.verdict}`);
628
956
  if(result.independent.toLowerCase()!=='true')
629
- throw new GateError('N5 requires independent: true; self-degraded evidence is diagnostic only');
630
- return {gate:'n5',task,attempt,outcome:'approved',review:fs.realpathSync(review),content_bound:contentBound};
957
+ throw new GateError('N5 requires an independent: true source declaration; self-degraded evidence is diagnostic only');
958
+ return {gate:'n5',task,attempt,outcome:'approved',review:fs.realpathSync(review),content_bound:contentBound,...inventoryResult};
631
959
  }
632
960
 
633
961
  function statIdentity(info){
@@ -684,7 +1012,7 @@ function pinApproval(selectors){
684
1012
  }
685
1013
  }
686
1014
  if(selectors.correction){
687
- const paths=correctionPaths(reviewsDir,feature,task);
1015
+ const paths=selectedCorrectionPaths(selectors);
688
1016
  for(const file of [paths.record,paths.review,paths.receipt])revisions.push(fileRevision(file,preparationReadLimit));
689
1017
  }
690
1018
  const approval={...checkN5(selectors)};
@@ -934,21 +1262,24 @@ export function checkParallelWrite({repo,assignment}){
934
1262
  return {gate:'parallel-write',outcome:'isolated',assignments:result};
935
1263
  }
936
1264
 
937
- function usage(){return 'usage: cm-task-gate.mjs {validate-handoff|hash-implementation|check-n4|check-n5|prepare-mark-done|verify-mark-done-plan|prepare-human-correction|publish-human-correction-review|check-parallel-write} [options]';}
1265
+ function usage(){return 'usage: cm-task-gate.mjs {capture-baseline|validate-handoff|hash-implementation|check-n4|check-n5|prepare-mark-done|verify-mark-done-plan|prepare-human-correction|publish-human-correction-review|prepare-controlled-correction|publish-controlled-correction-review|check-parallel-write} [options]';}
938
1266
 
939
1267
  function parseCli(argv){
940
1268
  if(argv.length===0||argv.includes('--help')||argv.includes('-h'))return {help:true};
941
1269
  const command=argv[0];
942
- if(!['validate-handoff','hash-implementation','check-n4','check-n5','prepare-mark-done','verify-mark-done-plan','mark-done-locked','prepare-human-correction','publish-human-correction-review','check-parallel-write'].includes(command))
1270
+ if(!['capture-baseline','validate-handoff','hash-implementation','check-n4','check-n5','prepare-mark-done','verify-mark-done-plan','mark-done-locked','prepare-human-correction','publish-human-correction-review','prepare-controlled-correction','publish-controlled-correction-review','check-parallel-write'].includes(command))
943
1271
  throw new GateError('unsupported command');
944
1272
  const allowed=command==='validate-handoff'?new Set(['--handoff','--task','--attempt'])
1273
+ :command==='capture-baseline'?new Set(['--project-root','--reviews-dir','--feature','--task'])
945
1274
  :command==='hash-implementation'?new Set(['--project-root','--file'])
946
1275
  :command==='check-parallel-write'?new Set(['--repo','--assignment'])
947
1276
  :new Set(['--handoff','--reviews-dir','--feature','--task','--project-root','--allow-legacy-unbound','--require-learning','--correction',
948
- ...(command==='prepare-human-correction'?['--human-authorized','--reason']:[]),
1277
+ ...(command==='prepare-human-correction'?['--reason']:[]),
1278
+ ...(command==='prepare-controlled-correction'?['--decision-source','--reason']:[]),
949
1279
  ...(['prepare-mark-done','verify-mark-done-plan','mark-done-locked'].includes(command)?['--tasks']:[]),
950
1280
  ...(['verify-mark-done-plan','mark-done-locked'].includes(command)?['--expected-plan-digest']:[])]);
951
1281
  const required=command==='validate-handoff'?new Set(['--handoff','--task','--attempt'])
1282
+ :command==='capture-baseline'?new Set(['--project-root','--reviews-dir','--feature','--task'])
952
1283
  :command==='hash-implementation'?new Set(['--project-root','--file'])
953
1284
  :command==='check-parallel-write'?new Set(['--repo','--assignment'])
954
1285
  :new Set(['--handoff','--reviews-dir','--feature','--task',
@@ -958,15 +1289,15 @@ function parseCli(argv){
958
1289
  for(let index=1;index<argv.length;){
959
1290
  const flag=argv[index];
960
1291
  if(!allowed.has(flag))throw new GateError('invalid arguments');
961
- if(flag==='--allow-legacy-unbound'||flag==='--require-learning'||flag==='--human-authorized'){
962
- const key=flag==='--human-authorized'?'humanAuthorized':flag==='--require-learning'?'requireLearning':'allowLegacyUnbound';
1292
+ if(flag==='--allow-legacy-unbound'||flag==='--require-learning'){
1293
+ const key=flag==='--require-learning'?'requireLearning':'allowLegacyUnbound';
963
1294
  if(Object.hasOwn(values,key))throw new GateError(`duplicate argument: ${flag}`);
964
1295
  values[key]=true;index++;continue;
965
1296
  }
966
1297
  const value=argv[index+1];if(value===undefined)throw new GateError('invalid arguments');
967
1298
  const key={'--handoff':'handoff','--reviews-dir':'reviewsDir','--feature':'feature','--task':'task','--attempt':'attempt',
968
1299
  '--tasks':'tasksPath','--expected-plan-digest':'expectedPlanDigest','--repo':'repo','--assignment':'assignment',
969
- '--project-root':'projectRoot','--file':'file','--correction':'correction','--reason':'reason'}[flag];
1300
+ '--project-root':'projectRoot','--file':'file','--correction':'correction','--reason':'reason','--decision-source':'decisionSource'}[flag];
970
1301
  if(['assignment','file'].includes(key)){
971
1302
  if(!Object.hasOwn(values,key))values[key]=[];
972
1303
  values[key].push(value);
@@ -979,7 +1310,7 @@ function parseCli(argv){
979
1310
  for(const flag of required){
980
1311
  const key={'--handoff':'handoff','--reviews-dir':'reviewsDir','--feature':'feature','--task':'task','--attempt':'attempt',
981
1312
  '--tasks':'tasksPath','--expected-plan-digest':'expectedPlanDigest','--repo':'repo','--assignment':'assignment',
982
- '--project-root':'projectRoot','--file':'file','--correction':'correction','--reason':'reason'}[flag];
1313
+ '--project-root':'projectRoot','--file':'file','--correction':'correction','--reason':'reason','--decision-source':'decisionSource'}[flag];
983
1314
  if(!Object.hasOwn(values,key))throw new GateError(`missing argument: ${flag}`);
984
1315
  }
985
1316
  if(Object.hasOwn(values,'attempt')){
@@ -998,15 +1329,18 @@ export function main(argv=process.argv.slice(2),environment=process.env){
998
1329
  requireTaskId(args.task,'task');
999
1330
  const payload=loadHandoff(args.handoff,{task:args.task,attempt:args.attempt});
1000
1331
  result={gate:'handoff',task:payload.task_id,attempt:payload.attempt,outcome:payload.status};
1001
- }else if(args.command==='hash-implementation')result={gate:'implementation-hash',
1332
+ }else if(args.command==='capture-baseline')result=captureBaseline(args);
1333
+ else if(args.command==='hash-implementation')result={gate:'implementation-hash',
1002
1334
  implementation_sha256:implementationSha256(args.projectRoot,args.file),changed_files:[...args.file].sort((left,right)=>Buffer.compare(Buffer.from(left),Buffer.from(right)))};
1003
1335
  else if(args.command==='prepare-human-correction')result=prepareHumanCorrection(args);
1004
1336
  else if(args.command==='publish-human-correction-review')result=publishHumanCorrectionReview(args);
1005
- else if(args.command==='check-n4')result=checkN4(args);
1006
- else if(args.command==='check-n5')result=checkN5(args);
1007
- else if(args.command==='prepare-mark-done')result=prepareMarkDone(args);
1008
- else if(args.command==='verify-mark-done-plan')result=verifyMarkDonePlan(args,args.expectedPlanDigest);
1009
- else if(args.command==='mark-done-locked')result=markDoneLocked(args,args.expectedPlanDigest,environment);
1337
+ else if(args.command==='prepare-controlled-correction')result=prepareControlledCorrection(args);
1338
+ else if(args.command==='publish-controlled-correction-review')result=publishControlledCorrectionReview(args);
1339
+ else if(args.command==='check-n4')result=checkN4({...args,inventory:'required'});
1340
+ else if(args.command==='check-n5')result=checkN5({...args,inventory:'required'});
1341
+ else if(args.command==='prepare-mark-done')result=prepareMarkDone({...args,inventory:'required'});
1342
+ else if(args.command==='verify-mark-done-plan')result=verifyMarkDonePlan({...args,inventory:'required'},args.expectedPlanDigest);
1343
+ else if(args.command==='mark-done-locked')result=markDoneLocked({...args,inventory:'required'},args.expectedPlanDigest,environment);
1010
1344
  else result=checkParallelWrite(args);
1011
1345
  }catch(error){
1012
1346
  process.stderr.write(`ERROR: ${error.message}\n`);return error instanceof GateError?1:2;
@@ -296,6 +296,8 @@ def mark_done(raw_arguments: Sequence[str]) -> dict[str, object]:
296
296
 
297
297
 
298
298
  def main(argv: Sequence[str] | None = None) -> int:
299
+ sys.stdout.reconfigure(encoding="utf-8")
300
+ sys.stderr.reconfigure(encoding="utf-8")
299
301
  raw_arguments = list(argv) if argv is not None else sys.argv[1:]
300
302
  if not raw_arguments or raw_arguments[0] != "mark-done":
301
303
  result = run_js(raw_arguments)