@aibyzero/cm-workflow 0.16.2 → 0.16.4

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 (155) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +4 -0
  3. package/CHANGELOG.md +147 -0
  4. package/README.md +44 -3
  5. package/VERSION +1 -1
  6. package/docs/installation.md +1 -1
  7. package/docs/js-workflow-control.md +46 -7
  8. package/docs/next-steps.md +100 -0
  9. package/docs/untested-branches.md +24 -18
  10. package/package.json +1 -1
  11. package/runtime/js/cm-ai/claude-review-stream.mjs +18 -0
  12. package/runtime/js/cm-ai/claude-tool-preview.mjs +45 -6
  13. package/runtime/js/cm-ai/cm-ai-admission.mjs +7 -1
  14. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +22 -12
  15. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +70 -5
  16. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +5 -5
  17. package/runtime/js/cm-ai/drive-core.mjs +68 -0
  18. package/runtime/js/cm-ai/durable-runner-state.mjs +42 -9
  19. package/runtime/js/cm-ai/effect-contract.mjs +4 -3
  20. package/runtime/js/cm-ai/execution-snapshot.mjs +40 -0
  21. package/runtime/js/cm-ai/host-conversation-execution.mjs +8 -5
  22. package/runtime/js/cm-ai/host-handoff.mjs +9 -14
  23. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +12 -7
  24. package/runtime/js/cm-ai/host-session.mjs +10 -3
  25. package/runtime/js/cm-ai/host.mjs +1 -1
  26. package/runtime/js/cm-ai/qa-config-revision.mjs +85 -0
  27. package/runtime/js/cm-ai/review-evidence-file.mjs +18 -1
  28. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +144 -0
  29. package/runtime/js/cm-ai/reviewed-evidence-supersession-record.mjs +34 -0
  30. package/runtime/js/cm-ai/task-runner.mjs +41 -8
  31. package/runtime/js/cm-ai/worker-claude-developer.mjs +16 -7
  32. package/runtime/js/cm-fix/cause-invocation.mjs +9 -5
  33. package/runtime/js/cm-fix/cause-package.mjs +21 -0
  34. package/runtime/js/cm-fix/dossier.mjs +40 -1
  35. package/runtime/js/cm-fix/execution.mjs +360 -83
  36. package/runtime/js/cm-fix/host.mjs +7 -3
  37. package/runtime/js/cm-fix/layout.mjs +14 -6
  38. package/runtime/js/cm-fix/progress.mjs +14 -0
  39. package/runtime/js/cm-fix/protected-edits.mjs +1 -1
  40. package/runtime/js/cm-fix/red-test.mjs +7 -6
  41. package/runtime/js/cm-fix/regression-evidence.mjs +6 -3
  42. package/runtime/js/cm-fix/regression.mjs +16 -10
  43. package/runtime/js/cm-fix/repair.mjs +16 -13
  44. package/runtime/js/cm-fix/test-author.mjs +2 -1
  45. package/runtime/js/cm-fix/test-extension.mjs +45 -0
  46. package/runtime/js/cm-prd/accepted-design.mjs +28 -9
  47. package/runtime/js/cm-prd/analysis.mjs +68 -16
  48. package/runtime/js/cm-prd/change.mjs +21 -1
  49. package/runtime/js/cm-prd/draft-save.mjs +96 -2
  50. package/runtime/js/cm-prd/failed-correction.mjs +51 -0
  51. package/runtime/js/cm-prd/inputs-replaced.mjs +122 -0
  52. package/runtime/js/cm-prd/review-correction.mjs +3 -0
  53. package/runtime/js/cm-prd/review-disposition.mjs +33 -15
  54. package/runtime/js/cm-prd/review-findings.mjs +2 -2
  55. package/runtime/js/cm-prd/review-host.mjs +2 -0
  56. package/runtime/js/cm-prd/review-preparation.mjs +28 -1
  57. package/runtime/js/cm-prd/review-publication.mjs +4 -2
  58. package/runtime/js/cm-prd/self-check-revision.mjs +81 -0
  59. package/runtime/js/cm-prd/session.mjs +5 -5
  60. package/runtime/js/cm-prd/split-design.mjs +67 -0
  61. package/runtime/js/cm-prd/summary.mjs +57 -10
  62. package/runtime/js/cm-refactor/workflow.mjs +100 -19
  63. package/runtime/js/specs-status.mjs +6 -2
  64. package/scripts/cm-ai-admission.mjs +2 -0
  65. package/scripts/cm-ai-batch-drive.mjs +251 -0
  66. package/scripts/cm-ai-batch-drive.test.mjs +159 -0
  67. package/scripts/cm-ai-batch-host.mjs +13 -5
  68. package/scripts/cm-ai-batch-host.test.mjs +25 -0
  69. package/scripts/cm-ai-contracts.test.mjs +30 -0
  70. package/scripts/cm-ai-conversation-entry-ops.test.mjs +62 -0
  71. package/scripts/cm-ai-drive.mjs +335 -0
  72. package/scripts/cm-ai-drive.test.mjs +258 -0
  73. package/scripts/cm-ai-fix-integration.test.mjs +1 -1
  74. package/scripts/cm-ai-host.mjs +48 -20
  75. package/scripts/cm-ai-host.test.mjs +79 -0
  76. package/scripts/cm-ai-qa-config-revision.test.mjs +328 -0
  77. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +255 -0
  78. package/scripts/cm-ai-qa-fix-policy.test.mjs +79 -0
  79. package/scripts/cm-ai-review-timeout.test.mjs +30 -0
  80. package/scripts/cm-ai-run.mjs +59 -11
  81. package/scripts/cm-ai-runner-error-code-regression.test.mjs +29 -0
  82. package/scripts/cm-ai-session-chain.test.mjs +261 -0
  83. package/scripts/cm-ai-supersede.test.mjs +320 -0
  84. package/scripts/cm-check-drive.mjs +94 -0
  85. package/scripts/cm-check-drive.test.mjs +78 -0
  86. package/scripts/cm-check-entry.mjs +13 -2
  87. package/scripts/cm-check-host.mjs +2 -2
  88. package/scripts/cm-check-host.test.mjs +103 -0
  89. package/scripts/cm-check-runtime.sh +15 -6
  90. package/scripts/cm-claude-developer-worker.test.mjs +40 -1
  91. package/scripts/cm-claude-probe.test.mjs +117 -2
  92. package/scripts/cm-claude-review-stream.test.mjs +43 -0
  93. package/scripts/cm-fix-abandon.test.mjs +383 -0
  94. package/scripts/cm-fix-cause-package.test.mjs +31 -1
  95. package/scripts/cm-fix-cross-session-host.test.mjs +17 -5
  96. package/scripts/cm-fix-drive.mjs +168 -0
  97. package/scripts/cm-fix-drive.test.mjs +117 -0
  98. package/scripts/cm-fix-escalation.test.mjs +214 -0
  99. package/scripts/cm-fix-execution.test.mjs +26 -0
  100. package/scripts/cm-fix-host.mjs +4 -2
  101. package/scripts/cm-fix-observation-dossier.test.mjs +34 -9
  102. package/scripts/cm-fix-qa-source.test.mjs +3 -3
  103. package/scripts/cm-fix-session-chain.test.mjs +244 -0
  104. package/scripts/cm-fix-test-extension.test.mjs +246 -0
  105. package/scripts/cm-fix-visual-carrier.test.mjs +66 -0
  106. package/scripts/cm-host-handoff.test.mjs +37 -0
  107. package/scripts/cm-idea-drive.mjs +99 -0
  108. package/scripts/cm-idea-drive.test.mjs +50 -0
  109. package/scripts/cm-init-drive.mjs +191 -0
  110. package/scripts/cm-init-drive.test.mjs +59 -0
  111. package/scripts/cm-log-event.mjs +9 -0
  112. package/scripts/cm-prd-completion.test.mjs +30 -2
  113. package/scripts/cm-prd-design-phase.test.mjs +355 -15
  114. package/scripts/cm-prd-drive.mjs +314 -0
  115. package/scripts/cm-prd-drive.test.mjs +164 -0
  116. package/scripts/cm-prd-host.mjs +46 -17
  117. package/scripts/cm-prd-inputs-replaced.test.mjs +237 -0
  118. package/scripts/cm-prd-review-disposition.test.mjs +133 -7
  119. package/scripts/cm-prd-review-gate.mjs +23 -4
  120. package/scripts/cm-prd-self-check-revision.test.mjs +302 -0
  121. package/scripts/cm-prd-summary.test.mjs +79 -4
  122. package/scripts/cm-refactor-drive.mjs +237 -0
  123. package/scripts/cm-refactor-drive.test.mjs +77 -0
  124. package/scripts/cm-refactor-gaps.test.mjs +276 -0
  125. package/scripts/cm-refactor-host.test.mjs +1 -48
  126. package/scripts/cm-refactor-judge-revision.test.mjs +253 -0
  127. package/scripts/cm-specs-status.test.mjs +19 -0
  128. package/scripts/cm-test-drive.mjs +132 -0
  129. package/scripts/cm-test-drive.test.mjs +91 -0
  130. package/scripts/cm-test-session.test.mjs +117 -0
  131. package/scripts/correction-check.test.mjs +38 -0
  132. package/scripts/fixtures/claude-model-marker.mjs +6 -0
  133. package/scripts/fixtures/claude-review-process.mjs +7 -0
  134. package/scripts/fixtures/cm-refactor.mjs +56 -0
  135. package/scripts/test-shell-compat.sh +67 -0
  136. package/skills/cm-ai/SKILL.md +1 -1
  137. package/skills/cm-ai/references/N4-review.md +2 -0
  138. package/skills/cm-ai/references/N8-finish.md +1 -0
  139. package/skills/cm-ai/references/js-host.md +85 -3
  140. package/skills/cm-check/SKILL.md +6 -1
  141. package/skills/cm-check/references/js-host.md +4 -2
  142. package/skills/cm-fix/SKILL.md +11 -4
  143. package/skills/cm-fix/references/js-host.md +67 -2
  144. package/skills/cm-fix/references/test-extension.md +57 -0
  145. package/skills/cm-idea/references/js-host.md +2 -0
  146. package/skills/cm-init/references/js-host.md +2 -0
  147. package/skills/cm-prd/SKILL.md +8 -8
  148. package/skills/cm-prd/references/js-change-recovery.md +71 -0
  149. package/skills/cm-prd/references/js-host.md +64 -2
  150. package/skills/cm-prd/references/spec-self-check.md +14 -2
  151. package/skills/cm-refactor/SKILL.md +5 -0
  152. package/skills/cm-refactor/references/js-batch.md +3 -1
  153. package/skills/cm-refactor/references/js-host.md +49 -0
  154. package/skills/cm-test/references/js-host.md +5 -0
  155. package/skills/cm-test/references/unit-coverage.md +2 -2
@@ -1,3 +1,4 @@
1
+ import {readQaConfigRevision} from './qa-config-revision.mjs';
1
2
  // Host-only S3b2b journal grammar. Data validation grants no provider authority.
2
3
  import {digest,need,shape,id,text,hex,json,validIdentity,validTaskLearningInput,validCallTimeout,validBlockedReason,requestFor} from './effect-contract.mjs';
3
4
  import {readReviewBaseline,readReviewPackage,reviewSpecsPath} from './review-package.mjs';
@@ -14,6 +15,7 @@ import {readBootstrapEvidence,validateBootstrapReviewPackage} from './host-boots
14
15
  import {validateCodeProjectPaths,assertCodeProjectSelections} from './code-projects.mjs';
15
16
 
16
17
  const LIMIT=16*1024*1024;
18
+ export const MAX_AI_JOINED_HOSTS=16;
17
19
  const same=(a,b)=>need(digest(a)===digest(b),'runner_history_mismatch');
18
20
  const prefix=(a,b)=>{need(b.length>=a.length,'runner_history_mismatch');same(a,b.slice(0,a.length));};
19
21
  const uuid=s=>need(typeof s==='string' && /^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/.test(s),'runner_session');
@@ -477,7 +479,10 @@ export function readRunnerHistory(raw,config,version=1) {
477
479
  const completion=version>=2?completionConfig(config,version):null;
478
480
  let original,session,state,pending=null,beforeIntent=null,controlCount=0,controls={},completeIntentDigest=null,transaction=null;
479
481
  let invocation={registration:null,started:null,result:null};
480
- const acceptedFixes=[];let qaAttachment=null;
482
+ const acceptedFixes=[],joinedHosts=[],reviewerThreads=[];let qaAttachment=null,qaRevision=null,joinedForInvocation=false,supersession=null;
483
+ const reviewConfig=(calls=[])=>({...config,reviewInvocation:{...config.reviewInvocation,
484
+ excludedThreadIds:reviewExclusions({excludedThreadIds:[...config.reviewInvocation.excludedThreadIds,...joinedHosts]},
485
+ calls,config.developer.contextId)}});
481
486
  for(const [index,r] of records.entries()) {
482
487
  boundRunnerRecord(r,index+1);
483
488
  if(version>=2)fullEnvelope(r,index,index?records[index-1].digest:null);
@@ -500,7 +505,12 @@ export function readRunnerHistory(raw,config,version=1) {
500
505
  same(original.specsPath??null,completion?reviewSpecsPath(config.root,completion.owner.specsRoot):null);
501
506
  same(original.rootDigest,digestRoot(config.root));state=initialRunnerState(config,session,version);continue;
502
507
  }
503
- if(p.type==='effect-intent') {
508
+ if(version===3&&p.type==='evidence-superseded') {
509
+ shape(p,[...common,'record']);
510
+ need(r.kind==='result'&&index===1&&pending===null&&state.state==='ready'&&supersession===null,'supersede_record_invalid');
511
+ supersession=readEvidenceSupersession(p.record,{feature:config.taskLearning.feature,
512
+ taskId:config.identity.taskId,newRunId:config.identity.runId});
513
+ } else if(p.type==='effect-intent') {
504
514
  shape(p,[...common,'effect']);need(r.kind==='intent' && pending===null,'runner_intent');
505
515
  const e=p.effect;shape(e,['version','id','identity','kind',...(Object.hasOwn(e,'learningInput')?['learningInput']:[])]);
506
516
  validIdentity(e.identity);id(e.id);
@@ -510,18 +520,29 @@ export function readRunnerHistory(raw,config,version=1) {
510
520
  same(e.identity,{...config.identity,attempt:state.attempt});need(e.version===1 && stageAllowed(e.kind,state.state,state.code),'runner_stage');
511
521
  need(completedEffectCount(state.cache)<6 && !state.cache.some(c=>c.effect.id===e.id),'runner_cache');
512
522
  pending=e;beforeIntent=structuredClone(state);controls={};completeIntentDigest=e.kind==='complete'?r.digest:null;
513
- invocation={registration:null,started:null,result:null};
523
+ invocation={registration:null,started:null,result:null};joinedForInvocation=false;
524
+ } else if(version===3&&p.type==='host-joined') {
525
+ shape(p,[...common,'hostContextId']);id(p.hostContextId);
526
+ // Only one join in a pending review effect, before registration. A crash
527
+ // after this record is a valid unknown prefix; opening never adds a join.
528
+ need(r.kind==='result'&&pending?.kind==='review'&&!invocation.registration&&!joinedForInvocation
529
+ &&!controls.cancelled&&!controls.workflowError,'runner_invocation');
530
+ need(![config.reviewInvocation.developerThreadId,...config.reviewInvocation.excludedThreadIds,
531
+ ...joinedHosts].includes(p.hostContextId),'runner_invocation');
532
+ need(![config.developer.contextId,...config.reviewers.flatMap(r=>r.contexts),...reviewerThreads]
533
+ .includes(p.hostContextId),'not_independent');
534
+ need(joinedHosts.length<MAX_AI_JOINED_HOSTS,'host_limit');
535
+ joinedHosts.push(p.hostContextId);joinedForInvocation=true;
514
536
  } else if(version===3&&p.type==='review-invocation-registered') {
515
537
  need(r.kind==='intent'&&pending?.kind==='review'&&!invocation.registration,'runner_invocation');
516
- invocation.registration=readRegistration(p,beforeIntent,pending,config,session);
538
+ invocation.registration=readRegistration(p,beforeIntent,pending,reviewConfig(),session);
517
539
  } else if(version===3&&p.type==='review-invocation-started') {
518
540
  need(r.kind==='result'&&invocation.registration&&!invocation.started&&!invocation.result,'runner_invocation');
519
- invocation.started=readStarted(p,invocation.registration,pending,{...config,reviewInvocation:{...config.reviewInvocation,
520
- excludedThreadIds:reviewExclusions(config.reviewInvocation,beforeIntent.calls,config.developer.contextId)}});
541
+ invocation.started=readStarted(p,invocation.registration,pending,reviewConfig(beforeIntent.calls));
542
+ reviewerThreads.push(invocation.started);
521
543
  } else if(version===3&&p.type==='review-invocation-result') {
522
544
  need(r.kind==='result'&&invocation.registration&&!invocation.result,'runner_invocation');
523
- invocation.result=readInvocationResult(p,invocation.registration,invocation.started,pending,{...config,reviewInvocation:{...config.reviewInvocation,
524
- excludedThreadIds:reviewExclusions(config.reviewInvocation,beforeIntent.calls,config.developer.contextId)}});
545
+ invocation.result=readInvocationResult(p,invocation.registration,invocation.started,pending,reviewConfig(beforeIntent.calls));
525
546
  if(invocation.result.outcome==='cancelled')need(controls.cancelled===true,'runner_control');
526
547
  } else if(p.type==='effect-checkpoint') {
527
548
  shape(p,[...common,'effectId','checkpoint']);need(r.kind==='result' && pending && p.effectId===pending.id,'runner_checkpoint');
@@ -550,7 +571,18 @@ export function readRunnerHistory(raw,config,version=1) {
550
571
  } else if(version===3&&p.type==='qa-attached') {
551
572
  shape(p,[...common,'record']);
552
573
  need(r.kind==='result'&&pending===null&&state.state==='fixture_completed','qa_attach_not_completed');
574
+ need(qaRevision===null,'qa_revision_chain_invalid');
553
575
  need(qaAttachment===null,'qa_attachment_duplicate');qaAttachment=readQaAttachment(p.record);
576
+ } else if(version===3&&p.type==='qa-config-revised') {
577
+ shape(p,[...common,'record']);
578
+ need(r.kind==='result'&&pending===null&&state.state==='fixture_completed','qa_revision_not_completed');
579
+ const revision=readQaConfigRevision(p.record);
580
+ need(revision.packageDigest===state.reviewPackage.packageDigest&&revision.taskAttempt===state.attempt,'package_mismatch');
581
+ if(qaRevision)need(revision.fromFingerprint===qaRevision.toFingerprint
582
+ &&revision.invariantDigest===qaRevision.invariantDigest
583
+ &&revision.previousQaDigest===qaRevision.qaDigest&&revision.qaRound>qaRevision.qaRound,'qa_revision_chain_invalid');
584
+ else need(revision.fromFingerprint===(qaAttachment?.qaFingerprint??completion.fingerprints.config),'qa_revision_chain_invalid');
585
+ qaRevision=revision;
554
586
  } else if(version===3&&p.type==='qa-fix-accepted') {
555
587
  shape(p,[...common,'record']);need(r.kind==='result'&&pending===null&&state.state==='fixture_completed','fix_parent_not_completed');
556
588
  acceptedFixes.push(validateAcceptedFix({record:p.record,previous:acceptedFixes,
@@ -568,10 +600,11 @@ export function readRunnerHistory(raw,config,version=1) {
568
600
  if(pending){state.state='unknown';state.code='reconciliation_required';
569
601
  if(version===3&&invocation.registration)state.reviewInvocation={registration:invocation.registration.record,
570
602
  started:invocation.started,result:invocation.result};}
571
- return {original,session,state,pending,acceptedFixes,qaAttachment,...(version>=2?{transaction}:{})};
603
+ return {original,session,state,pending,acceptedFixes,qaAttachment,...(version===3?{joinedHosts,reviewerThreads,supersession}:{}),...(version>=2?{transaction}:{})};
572
604
  }
573
605
  // Baseline rootDigest uses bytes of the canonical root, not JSON string encoding.
574
606
  import {createHash} from 'node:crypto';
575
607
  import {readQaAttachment} from './qa-attachment.mjs';
608
+ import {readEvidenceSupersession} from './reviewed-evidence-supersession-record.mjs';
576
609
  import fs from 'node:fs';
577
610
  const digestRoot=root=>createHash('sha256').update(fs.realpathSync(root)).digest('hex');
@@ -172,6 +172,7 @@ export function reviewExclusions(invocation,calls,developerContextId){
172
172
  // Host configuration allows 32 exclusions. FIX second-round review additionally
173
173
  // excludes the cause reviewer, first implementation reviewer and logical context.
174
174
  // Preserve that full union; ordinary two-author-attempt callers still fit.
175
- // A run resumed in a new session adds that session's host context to the union,
176
- // so the bound carries one entry more than a single-session run ever needs.
177
- export const MAX_REVIEW_EXCLUSIONS=36;
175
+ // A run resumed in new sessions adds each session that joined it, plus the one
176
+ // running now, to the union: up to 16 joined sessions and the live one on top of
177
+ // the single-session bound.
178
+ export const MAX_REVIEW_EXCLUSIONS=36+17;
@@ -0,0 +1,40 @@
1
+ // Read-only evidence discovery. The writer must still independently reopen with
2
+ // reconstructed expected fingerprints and acquire its normal ownership lock.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import {digest,need,shape,id,hex,json} from './effect-contract.mjs';
6
+ export function readExecutionSnapshot({specsRoot,identity}){
7
+ shape(identity,['repositoryId','runId']);Object.values(identity).forEach(id);
8
+ need(path.isAbsolute(specsRoot)&&fs.realpathSync(specsRoot)===specsRoot,'unsupported_path');
9
+ let dir=specsRoot;
10
+ for(const [index,part] of ['.reviews','.execution',identity.runId].entries()){
11
+ dir=path.join(dir,part);const stat=fs.lstatSync(dir);
12
+ need(stat.isDirectory()&&!stat.isSymbolicLink()&&(index===0||(stat.mode&0o077)===0),'unsupported_path');
13
+ }
14
+ const file=path.join(dir,'state.json'),before=fs.lstatSync(file);
15
+ need(before.isFile()&&!before.isSymbolicLink()&&before.nlink===1&&(before.mode&0o077)===0
16
+ &&before.size<=16*1024*1024,'unsupported_file');
17
+ const fd=fs.openSync(file,fs.constants.O_RDONLY|fs.constants.O_NOFOLLOW);
18
+ let bytes;
19
+ try{
20
+ bytes=fs.readFileSync(fd);const after=fs.fstatSync(fd),current=fs.lstatSync(file);
21
+ need([after,current].every(s=>['dev','ino','size','mtimeMs','ctimeMs'].every(k=>s[k]===before[k]))
22
+ &&bytes.length===before.size,'snapshot_changed');
23
+ }finally{fs.closeSync(fd);}
24
+ const raw=JSON.parse(bytes.toString('utf8')),v=json(raw,16*1024*1024);
25
+ need(Buffer.from(JSON.stringify(raw)+'\n').equals(bytes),'store_corrupt');
26
+ shape(v,['version','identity','fingerprints','records','revision']);
27
+ need(v.version===1&&digest(v.identity)===digest(identity),'identity_mismatch');
28
+ shape(v.fingerprints,['workflow','config','inputs']);Object.values(v.fingerprints).forEach(hex);
29
+ need(Array.isArray(v.records)&&v.records.length<=1024,'limit_exceeded');
30
+ let previous=null;const ids=new Set();
31
+ for(const [index,r] of v.records.entries()){
32
+ shape(r,['version','seq','id','kind','payload','previousDigest','digest']);id(r.id);hex(r.digest);
33
+ json(r.payload,1024*1024);
34
+ const {digest:checksum,...body}=r;
35
+ need(r.version===1&&r.seq===index+1&&r.previousDigest===previous&&!ids.has(r.id)
36
+ &&['intent','result','cancel','commit-intent','commit-result','finalized'].includes(r.kind)
37
+ &&digest(body)===checksum,'store_corrupt');previous=checksum;ids.add(r.id);
38
+ }
39
+ const {revision,...body}=v;need(digest(body)===revision,'store_corrupt');return v;
40
+ }
@@ -93,7 +93,7 @@ export function resolveReviewTimeout(review,protection){
93
93
  }
94
94
  export function createConversationExecution(definition,hostContextId,bridge,review=null,allowedAttempt=null,workflow=null,allowQa=false,runtime='codex',options={}){
95
95
  definition=json(definition);workflow=workflow===null?null:json(workflow);options=json(options);
96
- shape(options,[...['protection','batchWorkflowsDigest','qaLogHome','bootstrap','providerDevelopment','parallelMember','verificationPrecheck'].filter(key=>Object.hasOwn(options,key))]);
96
+ shape(options,[...['originalHostContextId','protection','batchWorkflowsDigest','qaLogHome','bootstrap','providerDevelopment','parallelMember','verificationPrecheck'].filter(key=>Object.hasOwn(options,key))]);
97
97
  need(!Object.hasOwn(options,'verificationPrecheck')||typeof options.verificationPrecheck==='boolean','invalid_input');
98
98
  const parallelMember=options.parallelMember??false;need(typeof parallelMember==='boolean','invalid_input');
99
99
  const provider=options.providerDevelopment??null;
@@ -123,11 +123,14 @@ export function createConversationExecution(definition,hostContextId,bridge,revi
123
123
  need(allowedAttempts.length<=2&&new Set(allowedAttempts).size===allowedAttempts.length
124
124
  &&allowedAttempts.every(value=>value===1||value===2),'invalid_review_attempt');
125
125
  const author='cm-conversation-author',reviewContexts=['cm-conversation-review-1','cm-conversation-review-2'];
126
- id(hostContextId);need(![author,...reviewContexts].includes(hostContextId),'not_independent');
126
+ const durableHostContextId=options.originalHostContextId??hostContextId;
127
+ for(const context of [hostContextId,durableHostContextId]){
128
+ id(context);need(![author,...reviewContexts].includes(context),'not_independent');
129
+ }
127
130
  // Keep the unverified native permissions boundary intact for this first host
128
131
  // slice too. A transport is not physical protection of nested specs.
129
132
  need(protection||!definition.specsDir.startsWith(definition.codeProject+path.sep),'nested_specs_protection_required');
130
- const configuration={kind:'cm-current-conversation-v1',...(parallelMember?{parallelMember}:{}),definitionDigest:digest(definition),hostContextId,
133
+ const configuration={kind:'cm-current-conversation-v1',...(parallelMember?{parallelMember}:{}),definitionDigest:digest(definition),hostContextId:durableHostContextId,
131
134
  ...(runtime==='claude'?{runtime}:{}),
132
135
  ...(provider?{providerDevelopment:{model:provider.model,coderRuntime,reviewerRuntime}}:{}),
133
136
  ...(protection?{protection}:{}),
@@ -189,7 +192,7 @@ export function createConversationExecution(definition,hostContextId,bridge,revi
189
192
  }catch{/* diagnostics never change the verdict */}
190
193
  return {satisfied:verdict.satisfied};
191
194
  }:null;
192
- const execution={configuration,timeoutMs:provider?protection.timeoutMs:1800000,excludedContexts:[hostContextId],hostDecision:null,applicableAgentFiles:[],
195
+ const execution={configuration,timeoutMs:provider?protection.timeoutMs:1800000,excludedContexts:[durableHostContextId],hostDecision:null,applicableAgentFiles:[],
193
196
  ...(verificationGate?{verificationGate}:{}),
194
197
  ...(bootstrap?{bootstrap}:{}),
195
198
  ...(provider?{developmentAttempt:provider.attempt}:{}),
@@ -287,7 +290,7 @@ export function createConversationExecution(definition,hostContextId,bridge,revi
287
290
  return reviewerRuntime==='codex'?createCodexReviewRun(codexWorker(selectedOptions))(request,control)
288
291
  :createClaudeReviewRun(claudeWorker(selectedOptions))(request,control);
289
292
  }}],
290
- reviewInvocation:{developerThreadId:author,excludedThreadIds:[hostContextId],
293
+ reviewInvocation:{developerThreadId:author,excludedThreadIds:[durableHostContextId],hostContextId,
291
294
  authorize:authority?.authorize??(()=>({status:'denied',code:'permission_denied'}))},
292
295
  };
293
296
  if(definition.codeProjects)execution.applicableAgentFiles=[...new Set([...execution.applicableAgentFiles,
@@ -3,9 +3,15 @@ import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import {randomUUID,createHash} from 'node:crypto';
5
5
  import {createReviewPackage,verifyReviewPackage} from './review-package.mjs';
6
+ import {supersedeWorkflowFile} from './review-evidence-file.mjs';
6
7
  import {implementationSha256,loadHandoff} from '../../../scripts/cm-task-gate.mjs';
7
8
  import {digest,json,shape,text,need} from './effect-contract.mjs';
8
9
 
10
+ export const REVIEWED_HANDOFF_HINT='仅 QA 卡住时,配置错误用 --revise-qa-config PREVIOUS.json --qa-config-revision-reason … 恢复原运行,宿主或环境证据不足用 --rerun-blocked-qa。确需重跑任务时,用 --supersede-reviewed-evidence --supersede-reason … 新建运行。';
11
+ function reviewedHandoffConflict(){
12
+ const error=new Error('handoff_exists');error.code='handoff_exists';error.reason=REVIEWED_HANDOFF_HINT;throw error;
13
+ }
14
+
9
15
  function prepareHostHandoff(raw){
10
16
  const input=json(raw,16*1024*1024);
11
17
  shape(input,['root','baseline','checks','handoffPath',...(Object.hasOwn(input,'evidence')?['evidence']:[])]);
@@ -78,18 +84,6 @@ function reviewConsumedHandoff(parent,name,attempt){
78
84
  return lines.slice(1,end).some(line=>line.trim()===`handoff: ${name}`);
79
85
  }
80
86
 
81
- // Archive by link-then-unlink so the bytes survive a crash between the two steps.
82
- function supersedeHandoff(parent,handoffPath,existing){
83
- const archive=path.join(parent,'.superseded');
84
- fs.mkdirSync(archive,{recursive:true,mode:0o700});
85
- const stamp=createHash('sha256').update(existing).digest('hex').slice(0,16);
86
- const target=path.join(archive,`${path.basename(handoffPath)}.${stamp}`);
87
- try{fs.linkSync(handoffPath,target);}catch(error){if(error.code!=='EEXIST')throw error;}
88
- fs.unlinkSync(handoffPath);
89
- const dir=fs.openSync(archive,fs.constants.O_RDONLY);
90
- try{fs.fsyncSync(dir);}finally{fs.closeSync(dir);}
91
- }
92
-
93
87
  // Publish with no-replace semantics, resolving only the collisions that are
94
88
  // provably safe to resolve. Returns nothing; throws on a conflict it may not touch.
95
89
  function publishHandoff(parent,handoffPath,temp,bytes,attempt){
@@ -100,8 +94,9 @@ function publishHandoff(parent,handoffPath,temp,bytes,attempt){
100
94
  const existing=fs.readFileSync(handoffPath);
101
95
  // Republishing identical bytes is the crash-after-link case, already published.
102
96
  if(existing.equals(bytes))return;
103
- need(!reviewConsumedHandoff(parent,path.basename(handoffPath),attempt),'handoff_exists');
104
- supersedeHandoff(parent,handoffPath,existing);
97
+ if(reviewConsumedHandoff(parent,path.basename(handoffPath),attempt))reviewedHandoffConflict();
98
+ // Crash-after-link retries stamp the checked bytes; a second read could change the archive name.
99
+ supersedeWorkflowFile(parent,path.basename(handoffPath),existing);
105
100
  fs.linkSync(temp,handoffPath);
106
101
  }
107
102
 
@@ -6,7 +6,8 @@ import {createFixHost} from '../cm-fix/host.mjs';
6
6
  import {bindQaFixDefinition} from './qa-fix-definition.mjs';
7
7
  import {digest,id,json,need,shape,validIdentity,hex} from './effect-contract.mjs';
8
8
 
9
- export function createQaFixOwnerHost({parent,reopenParent,fix=null,template=null,allowStart=false,autoFix=false,fixExecution={},fixPermissions=[],fixAuthorities={}}){
9
+ export function createQaFixOwnerHost({parent,reopenParent,hostContextId,parentHostContextId,fix=null,template=null,allowStart=false,autoFix=false,fixExecution={},fixPermissions=[],fixAuthorities={}}){
10
+ id(hostContextId);id(parentHostContextId);
10
11
  need((fix===null)!==(template===null),'invalid_fix_config');
11
12
  let definition=null;
12
13
  const fixedTemplate=template===null?null:json(template,64*1024);
@@ -42,7 +43,7 @@ export function createQaFixOwnerHost({parent,reopenParent,fix=null,template=null
42
43
  busy=true;try{return await current.host.handle(request);}finally{busy=false;}
43
44
  }
44
45
  const value=json(request);shape(value,['version','requestId','operation','identity','packageDigest','testRunId',
45
- ...(request.operation==='fix_action'?['fixOperation']:[])]);
46
+ ...(request.operation==='fix_action'?['fixOperation',...(request.fixOperation==='abandon_step'&&Object.hasOwn(request,'reason')?['reason']:[])]:[])]);
46
47
  need(value.version===1,'invalid_input');id(value.requestId);validIdentity(value.identity);hex(value.packageDigest);id(value.testRunId);
47
48
  if(fixedTemplate)definition=bindQaFixDefinition({template:fixedTemplate,identity:value.identity,
48
49
  packageDigest:value.packageDigest,testRunId:value.testRunId});
@@ -54,7 +55,7 @@ export function createQaFixOwnerHost({parent,reopenParent,fix=null,template=null
54
55
  const acting=value.operation==='fix_action';
55
56
  if(acting)need(['red_test','baseline','author_tests','repair','regression','retrospective','learning_writeback',
56
57
  'handoff','final_review_package','final_review','publish_review','check_n5','post_review_regression',
57
- 'publish_dossier','walkthrough','finish','prepare_revision','cause_review_package','cause_review'].includes(value.fixOperation),'fix_operation_unavailable');
58
+ 'publish_dossier','walkthrough','finish','prepare_revision','cause_review_package','cause_review','abandon_step'].includes(value.fixOperation),'fix_operation_unavailable');
58
59
  need(!(advancing||acting)||allowStart,'qa_fix_start_authorization_required');
59
60
  busy=true;let child=null,released=false,result;
60
61
  try{
@@ -63,18 +64,22 @@ export function createQaFixOwnerHost({parent,reopenParent,fix=null,template=null
63
64
  &&digest(status.identity)===digest(value.identity),'qa_fix_parent_not_completed');
64
65
  switching=true;current.close();current=null;released=true;
65
66
  const existing=fs.existsSync(path.join(definition.specsRoot,'.reviews','.execution',definition.identity.runId));
66
- child=openFixExecution({...definition,create:advancing&&!existing},advancing||acting?fixExecution:{});
67
+ // Only a new store needs a creator check. Existing configuration is
68
+ // immutable and checked against its own stored fingerprint by cm-fix.
69
+ if(advancing&&!existing)need([hostContextId,parentHostContextId].includes(definition.configuration.hostContextId),'qa_fix_host_mismatch');
70
+ child=openFixExecution({...definition,hostContextId,create:advancing&&!existing},advancing||acting?fixExecution:{});
67
71
  activeChild=child;
68
72
  let actionResult;
69
73
  if(advancing||acting){
70
74
  const host=createFixHost({owner:child,config:{...definition.configuration,specsRoot:definition.specsRoot,identity:definition.identity},
71
75
  runtime:definition.configuration.runtime??'codex',permissions:[...permissions,'--allow-reproduction'],...fixAuthorities});
72
76
  actionResult=running?await host.run(value.requestId)
73
- :await host.handle({requestId:value.requestId,operation:advancing?'advance':value.fixOperation});
77
+ :await host.handle({requestId:value.requestId,operation:advancing?'advance':value.fixOperation,
78
+ ...(value.fixOperation==='abandon_step'?{reason:value.reason}:{})});
74
79
  }
75
- // Original observing finish intentionally closes its owner. Preserve
80
+ // Original observation/escalation finish intentionally closes its owner. Preserve
76
81
  // that successful incomplete exit without reading a closed store.
77
- if(acting&&value.fixOperation==='finish'&&actionResult?.observationRunEnded===true)
82
+ if(actionResult?.observationRunEnded===true||actionResult?.escalationRunEnded===true)
78
83
  return json({outcome:'blocked',code:'qa_fix_incomplete',fixStage:actionResult.stage,actionResult},12*1024*1024);
79
84
  const observed=child.status();
80
85
  result=observed.stage==='completed'&&observed.completionEligible===true
@@ -1,9 +1,16 @@
1
1
  // JSONL transport only. The existing host/runner owns decisions and durable state.
2
- import {executionDiagnostic} from './effect-contract.mjs';
2
+ import {executionDiagnostic,need} from './effect-contract.mjs';
3
3
 
4
4
  const LIMIT=64*1024;
5
- const operationNames=new Set(['recover_final_review','advance','start','plan_design','promote_design','select_design_reviews','status','fix_status','fix_advance','fix_action','fix_run','decision','complete','qa','qa_result','prepare_revision','prepare_save',
6
- 'context_refresh','finish','completion_evidence','run_finalize','review_findings','review_disposition','save_draft','save_design','correct_findings','prepare_summary','publish_summary','inspect_correction','resume_correction','cancel','resume','cause_review_package','cause_review','red_test','baseline','author_tests','repair','regression','retrospective','learning_writeback','handoff','final_review_package','final_review','publish_review','check_n5','post_review_regression','publish_dossier','walkthrough']);
5
+ export function parseHostInputLimit(raw){
6
+ if(raw===undefined)return LIMIT;
7
+ const value=Number(raw);
8
+ need(typeof raw==='string'&&/^[1-9][0-9]*$/.test(raw)&&Number.isSafeInteger(value)
9
+ &&value>=LIMIT&&value<=4*1024*1024,'invalid_arguments');
10
+ return value;
11
+ }
12
+ const operationNames=new Set(['replace_inputs','read_batch','recover_final_review','abandon_step','advance','start','plan_design','promote_design','select_design_reviews','status','fix_status','fix_advance','fix_action','fix_run','decision','complete','qa','qa_result','prepare_revision','prepare_save',
13
+ 'context_refresh','finish','completion_evidence','run_finalize','review_findings','review_disposition','save_draft','save_design','correct_findings','prepare_summary','publish_summary','inspect_correction','resume_correction','cancel','resume','prepare_judge_revision','cause_review_package','cause_review','red_test','baseline','author_tests','repair','regression','retrospective','learning_writeback','handoff','final_review_package','final_review','publish_review','check_n5','post_review_regression','publish_dossier','walkthrough']);
7
14
 
8
15
  // Which contract codes may reach the peer is a deliberate boundary: the host
9
16
  // exposes chosen ones as a blocked result with a reason and redacts the rest to
@@ -16,5 +16,5 @@ export function createCmAiHost(options) {
16
16
  ...(qaExecutor===undefined?{}:{qaExecutor}),
17
17
  ...(documentationProvider===undefined?{}:{documentationProvider}),
18
18
  ...(qaDecisionProvider===undefined?{}:{qaDecisionProvider})});
19
- return Object.freeze({handle:entry.handle,inspectFixAssociation:runner.inspectFixAssociation,acceptCompletedFix:runner.acceptCompletedFix,attachQa:runner.attachQa});
19
+ return Object.freeze({handle:entry.handle,inspectFixAssociation:runner.inspectFixAssociation,acceptCompletedFix:runner.acceptCompletedFix,attachQa:runner.attachQa,reviseQa:runner.reviseQa,supersedeEvidence:runner.supersedeEvidence});
20
20
  }
@@ -0,0 +1,85 @@
1
+ // Explicit QA-only configuration succession. No development state is replaced.
2
+ import {digest,json,shape,need,hex,id,text} from './effect-contract.mjs';
3
+ import {createHostQaExecutor} from './host-qa-executor.mjs';
4
+ import {validateHostWorkflowConfiguration} from './host-workflow-capabilities.mjs';
5
+ import {preQaConfigurations,readQaAttachment} from './qa-attachment.mjs';
6
+
7
+ const workflow=material=>material.execution?.workflow?.configuration??material.execution?.workflow;
8
+ export function qaConfigurationSlice(material){
9
+ const qa=workflow(material)?.qa,executor=material.qaExecutor,c=executor?.configuration;
10
+ need(qa&&c?.kind==='cm-host-qa-executor-v1','qa_revision_configuration_required');
11
+ return json({qa,mode:executor.mode,caseCount:executor.caseCount,timeoutMs:executor.timeoutMs,
12
+ executor:{commands:c.commands,environment:c.environment,timeoutMs:c.timeoutMs,
13
+ commandsPlan:c.plan.commands,modes:c.plan.modes}});
14
+ }
15
+ function withQaConfiguration(material,slice){
16
+ const result=structuredClone(json(material)),c=result.qaExecutor.configuration;
17
+ workflow(result).qa=slice.qa;
18
+ Object.assign(result.qaExecutor,{mode:slice.mode,caseCount:slice.caseCount,timeoutMs:slice.timeoutMs});
19
+ Object.assign(c,{commands:slice.executor.commands,environment:slice.executor.environment,timeoutMs:slice.executor.timeoutMs});
20
+ Object.assign(c.plan,{commands:slice.executor.commandsPlan,modes:slice.executor.modes});
21
+ return result;
22
+ }
23
+ export function qaInvariantDigest(material){
24
+ return digest(withQaConfiguration(material,{qa:null,mode:null,caseCount:null,timeoutMs:null,
25
+ executor:{commands:null,environment:null,timeoutMs:null,commandsPlan:null,modes:null}}));
26
+ }
27
+ export function previousQaMaterial(material,previousWorkflow){
28
+ qaConfigurationSlice(material);
29
+ const prior=validateHostWorkflowConfiguration(previousWorkflow),current=workflow(material);
30
+ need(prior.qa!==null,'qa_revision_configuration_required');
31
+ need(digest({...prior,qa:null})===digest({...current,qa:null}),'fingerprint_mismatch');
32
+ const result=structuredClone(json(material)),{kind,plan,capabilities,...configuration}=result.qaExecutor.configuration;
33
+ need(kind==='cm-host-qa-executor-v1','qa_revision_configuration_required');
34
+ // Rebuild the old plan using the same executor validator and unchanged project
35
+ // policy. These callbacks are capability markers and are never dispatched.
36
+ const executor=createHostQaExecutor({...configuration,commands:prior.qa.commands,environment:prior.qa.environment,
37
+ ...(capabilities.logic?{logic:()=>{}}:{}),...(capabilities.browser?{browser:()=>{}}:{})});
38
+ result.qaExecutor={version:1,mode:executor.mode,caseCount:executor.caseCount,timeoutMs:executor.timeoutMs,configuration:executor.configuration};
39
+ workflow(result).qa=prior.qa;
40
+ need(qaInvariantDigest(result)===qaInvariantDigest(material),'fingerprint_mismatch');
41
+ return result;
42
+ }
43
+ export function readQaConfigRevision(raw){
44
+ const r=json(raw);
45
+ shape(r,['version','fromFingerprint','toFingerprint','invariantDigest','previousQaDigest','qaDigest','reason','hostContextId',
46
+ 'revisedAt','packageDigest','testRunId','qaRound','taskAttempt']);
47
+ need(r.version===1,'qa_revision_invalid');
48
+ for(const key of ['fromFingerprint','toFingerprint','invariantDigest','packageDigest','previousQaDigest','qaDigest'])hex(r[key]);
49
+ need(r.fromFingerprint!==r.toFingerprint&&r.previousQaDigest!==r.qaDigest,'qa_revision_unchanged');
50
+ id(r.hostContextId);id(r.testRunId);text(r.reason);
51
+ need(r.reason.trim().length>0&&r.reason.length<=500&&!/[\r\n\0]/.test(r.reason),'qa_revision_authorization_required');
52
+ need(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ$/.test(r.revisedAt)&&Number.isFinite(Date.parse(r.revisedAt)),'qa_revision_invalid');
53
+ need([1,2].includes(r.taskAttempt),'qa_revision_invalid');
54
+ need(Number.isInteger(r.qaRound)&&r.qaRound>=1&&r.qaRound<3,'qa_round_invalid');
55
+ return r;
56
+ }
57
+ export function qaRevisionChain(snapshot){
58
+ let fingerprint=snapshot.fingerprints.config,invariant=null,attached=false;const revisions=[];
59
+ for(const row of snapshot.records){
60
+ if(row.payload.type==='qa-attached'){
61
+ need(!attached,'qa_attachment_duplicate');attached=true;
62
+ need(revisions.length===0,'qa_revision_chain_invalid');fingerprint=readQaAttachment(row.payload.record).qaFingerprint;
63
+ }
64
+ if(row.payload.type!=='qa-config-revised')continue;
65
+ const r=readQaConfigRevision(row.payload.record);
66
+ need(r.fromFingerprint===fingerprint&&(invariant===null||r.invariantDigest===invariant)
67
+ &&(!revisions.length||(r.previousQaDigest===revisions.at(-1).qaDigest
68
+ &&r.qaRound>revisions.at(-1).qaRound)),'qa_revision_chain_invalid');
69
+ fingerprint=r.toFingerprint;invariant=r.invariantDigest;revisions.push(r);
70
+ }
71
+ return {fingerprint,revisions};
72
+ }
73
+ export function verifyQaRevisionMaterial(snapshot,material,prior=null){
74
+ const {fingerprint,revisions}=qaRevisionChain(snapshot);
75
+ const candidate=prior??material;
76
+ need(digest(candidate)===fingerprint,'fingerprint_mismatch');
77
+ if(revisions.length){
78
+ need(qaInvariantDigest(material)===revisions.at(-1).invariantDigest,'fingerprint_mismatch');
79
+ need(digest(qaConfigurationSlice(candidate))===revisions.at(-1).qaDigest,'fingerprint_mismatch');
80
+ }else{
81
+ const attached=snapshot.records.some(row=>row.payload.type==='qa-attached');
82
+ need((attached?preQaConfigurations(candidate):[candidate]).some(p=>digest(p)===snapshot.fingerprints.config),'fingerprint_mismatch');
83
+ }
84
+ return revisions;
85
+ }
@@ -1,7 +1,7 @@
1
1
  // Immutable file projection shared by review publishers, not an approval issuer.
2
2
  import fs from 'node:fs';
3
3
  import path from 'node:path';
4
- import {randomUUID} from 'node:crypto';
4
+ import {randomUUID,createHash} from 'node:crypto';
5
5
  import {need} from './effect-contract.mjs';
6
6
 
7
7
  export function writeReviewEvidence({reviewsDir,name,bytes,validate=()=>{},inspectOnly=false,exclusive=false}){
@@ -36,3 +36,20 @@ export function writeImmutableWorkflowFile({reviewsDir,name,bytes,validate=()=>{
36
36
  try{fs.unlinkSync(temp);}catch(error){if(error.code!=='ENOENT')throw error;}
37
37
  }
38
38
  }
39
+
40
+ // Move a workflow file aside without ever deleting its bytes: link into
41
+ // .superseded/ under a content-hash stamp, then unlink the original, so a crash
42
+ // between the two steps leaves both copies rather than neither. Callers decide
43
+ // *whether* a file may be superseded — this only knows how.
44
+ export function supersedeWorkflowFile(dir,name,existing){
45
+ const source=path.join(dir,name),archive=path.join(dir,'.superseded');
46
+ existing??=fs.readFileSync(source);
47
+ fs.mkdirSync(archive,{recursive:true,mode:0o700});
48
+ const stamp=createHash('sha256').update(existing).digest('hex').slice(0,16);
49
+ const target=path.join(archive,`${name}.${stamp}`);
50
+ try{fs.linkSync(source,target);}catch(error){if(error.code!=='EEXIST')throw error;}
51
+ fs.unlinkSync(source);
52
+ const fd=fs.openSync(archive,fs.constants.O_RDONLY);
53
+ try{fs.fsyncSync(fd);}finally{fs.closeSync(fd);}
54
+ return target;
55
+ }
@@ -0,0 +1,144 @@
1
+ // Explicit restart boundary. Discovery reads old stores as immutable snapshots;
2
+ // only the new runner may record the authorization and move named projections.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import {createHash} from 'node:crypto';
6
+ import {spawnSync} from 'node:child_process';
7
+ import {fileURLToPath} from 'node:url';
8
+ import {readExecutionSnapshot} from './execution-snapshot.mjs';
9
+ import {readRunnerHistory} from './durable-runner-state.mjs';
10
+ import {supersedeWorkflowFile} from './review-evidence-file.mjs';
11
+ import {need,digest} from './effect-contract.mjs';
12
+ import {readEvidenceSupersession,supersedableEvidenceName} from './reviewed-evidence-supersession-record.mjs';
13
+ import {scanRows} from './cm-ai-qa-log.mjs';
14
+ import {parseCmAiTaskLine} from './cm-ai-admission.mjs';
15
+
16
+ const writer=fileURLToPath(new URL('../../../scripts/cm-log-event.py',import.meta.url));
17
+ const unavailable=reason=>{const error=new Error('supersede_unavailable');error.code='supersede_unavailable';error.reason=reason;throw error;};
18
+ const hash=bytes=>createHash('sha256').update(bytes).digest('hex');
19
+
20
+ function taskChecked(tasksPath,taskId){
21
+ const body=fs.readFileSync(tasksPath,'utf8');
22
+ const rows=body.split(/\r?\n/).map(parseCmAiTaskLine).filter(task=>task?.id===taskId);
23
+ if(rows.length!==1)unavailable('tasks.md 中任务身份不唯一或不存在');
24
+ return rows[0].completed;
25
+ }
26
+
27
+ function qaTerminal(specsDir,runId,taskId){
28
+ const log=path.join(specsDir,'运行日志.jsonl');if(!fs.existsSync(log))return 'never_finished';
29
+ let result='never_finished';
30
+ scanRows(log,row=>{
31
+ if(row.workflow!=='cm-ai'||row.run_id!==runId||row.task!==taskId)return;
32
+ if(row.event==='run_done')result='completed';
33
+ else if(result!=='completed'&&row.event==='test_run'&&row.phase==='complete')result=row.result;
34
+ });
35
+ return result;
36
+ }
37
+
38
+ function evidenceNames(reviewsDir,feature,taskId){
39
+ return fs.readdirSync(reviewsDir,{withFileTypes:true}).filter(entry=>entry.isFile()
40
+ &&supersedableEvidenceName(entry.name,feature,taskId))
41
+ .map(entry=>entry.name).sort();
42
+ }
43
+
44
+ export function oldWriterOpen(execution,runId,{lsofPath}={}){
45
+ // Inspect descriptor ownership without opening the old SQLite store.
46
+ const writerFile=path.join(execution,runId,'writer.sqlite');
47
+ const lsof=lsofPath??['/usr/sbin/lsof','/usr/bin/lsof'].find(file=>fs.existsSync(file));
48
+ if(lsof){
49
+ const result=spawnSync(lsof,['-F','p','--',writerFile],
50
+ {timeout:10000,maxBuffer:64*1024,encoding:'utf8'});
51
+ const diagnostics=(result.stderr??'').split(/\r?\n/).filter(line=>line.trim()&&!/^lsof: WARNING:/.test(line));
52
+ if(result.error||result.signal||![0,1].includes(result.status)||diagnostics.length)
53
+ unavailable(`无法核对旧运行 ${runId} 的 writer 状态`);
54
+ if(result.status===0&&!/^p\d+$/m.test(result.stdout))unavailable(`无法核对旧运行 ${runId} 的 writer 状态`);
55
+ return result.status===0;
56
+ }
57
+ const fuser='/usr/bin/fuser';
58
+ if(process.platform==='linux'&&fs.existsSync(fuser)){
59
+ const result=spawnSync(fuser,[writerFile],{timeout:3000,maxBuffer:64*1024,encoding:'utf8'});
60
+ if(result.error||result.signal||![0,1].includes(result.status))
61
+ unavailable(`无法核对旧运行 ${runId} 的 writer 状态`);
62
+ if(result.status===0&&!/\b\d+\b/.test(result.stdout))unavailable(`无法核对旧运行 ${runId} 的 writer 状态`);
63
+ return result.status===0;
64
+ }
65
+ unavailable(`缺少核对旧运行 ${runId} writer 占用的本地工具`);
66
+ }
67
+
68
+ export function prepareReviewedEvidenceSupersession({specsDir,codeProject,feature,identity,reason,tasksPath}){
69
+ if(typeof reason!=='string'||!reason.trim()||Buffer.byteLength(reason,'utf8')>500||/[\r\n\0]/.test(reason))
70
+ unavailable('必须提供单行且不超过 500 字节的 --supersede-reason');
71
+ if(taskChecked(tasksPath,identity.taskId))unavailable('tasks.md 已将任务标为完成;若 QA BLOCKED 后确需重跑,先将该任务改回 - [ ],再以 --supersede-reviewed-evidence 和 --supersede-reason 创建新运行');
72
+ const reviewsDir=path.join(specsDir,'.reviews');
73
+ if(!fs.existsSync(reviewsDir))unavailable('没有可替换的旧任务证据');
74
+ const execution=path.join(reviewsDir,'.execution');
75
+ const previousRunIds=[];
76
+ if(fs.existsSync(execution))for(const entry of fs.readdirSync(execution,{withFileTypes:true})){
77
+ if(!entry.isDirectory()||entry.name===identity.runId)continue;
78
+ const stateFile=path.join(execution,entry.name,'state.json');
79
+ if(!fs.existsSync(stateFile))continue;
80
+ let snapshot;
81
+ try{snapshot=readExecutionSnapshot({specsRoot:specsDir,
82
+ identity:{repositoryId:identity.repositoryId,runId:entry.name}});}
83
+ catch(error){if(error.code==='identity_mismatch')continue;throw error;}
84
+ const first=snapshot.records[0]?.payload;
85
+ if(first?.config?.identity?.taskId!==identity.taskId||first?.config?.taskLearning?.feature!==feature)continue;
86
+ if(first.config.identity.repositoryId!==identity.repositoryId||first.config.identity.runId!==entry.name
87
+ ||first.config.root!==codeProject||first.config.completion?.owner?.specsRoot!==specsDir
88
+ ||first.config.completion?.owner?.tasksPath!==tasksPath)
89
+ unavailable(`旧运行 ${entry.name} 的任务身份或路径不匹配`);
90
+ if(first.version!==3)unavailable(`旧运行 ${entry.name} 的 journal 版本无法验证`);
91
+ const history=readRunnerHistory(snapshot.records,first.config,3);
92
+ if(history.pending||!['blocked','cancelled','unknown','fixture_completed'].includes(history.state.state))
93
+ unavailable(`旧运行 ${entry.name} 仍可继续或有未结操作`);
94
+ if(oldWriterOpen(execution,entry.name))unavailable(`旧运行 ${entry.name} 的 writer 仍被进程持有`);
95
+ const qa=qaTerminal(specsDir,entry.name,identity.taskId);
96
+ if(history.state.state==='fixture_completed'&&!['BLOCKED','never_finished'].includes(qa))
97
+ unavailable(`旧运行 ${entry.name} 已完成或 QA 已通过`);
98
+ previousRunIds.push(entry.name);
99
+ }
100
+ if(!previousRunIds.length)unavailable('没有同 feature、task 的旧运行');
101
+ const names=evidenceNames(reviewsDir,feature,identity.taskId);
102
+ if(!names.length)unavailable('没有可归档的旧任务证据');
103
+ const files=names.map(name=>{
104
+ const p=path.join(reviewsDir,name),stat=fs.lstatSync(p);
105
+ if(!stat.isFile()||stat.isSymbolicLink()||stat.nlink!==1)unavailable(`证据文件不可安全归档:${name}`);
106
+ return {name,sha256:hash(fs.readFileSync(p))};
107
+ });
108
+ return readEvidenceSupersession({version:1,feature,taskId:identity.taskId,newRunId:identity.runId,
109
+ previousRunIds:previousRunIds.sort(),reason,files,authorizedAt:new Date().toISOString()});
110
+ }
111
+
112
+ export function archiveReviewedEvidence(reviewsDir,raw){
113
+ const record=readEvidenceSupersession(raw);
114
+ const archive=path.join(reviewsDir,'.superseded');
115
+ for(const file of record.files){
116
+ const source=path.join(reviewsDir,file.name),target=path.join(archive,`${file.name}.${file.sha256.slice(0,16)}`);
117
+ let archived=false;
118
+ if(fs.existsSync(target)){
119
+ const stat=fs.lstatSync(target);
120
+ need(stat.isFile()&&!stat.isSymbolicLink()&&hash(fs.readFileSync(target))===file.sha256,'supersede_archive_conflict');
121
+ archived=true;
122
+ }
123
+ if(fs.existsSync(source)){
124
+ const stat=fs.lstatSync(source);
125
+ need(stat.isFile()&&!stat.isSymbolicLink()&&stat.nlink<=2,'supersede_file_changed');
126
+ if(hash(fs.readFileSync(source))===file.sha256)supersedeWorkflowFile(reviewsDir,file.name);
127
+ else need(archived,'supersede_file_changed'); // New run has already published its own bytes.
128
+ }
129
+ need(fs.existsSync(target)&&hash(fs.readFileSync(target))===file.sha256,'supersede_archive_missing');
130
+ }
131
+ return record;
132
+ }
133
+
134
+ export function recordEvidenceSupersession({specsDir,codeProject,identity,record,logHome}){
135
+ const data={node:'N3',feature:record.feature,task:record.taskId,
136
+ previous_run_count:record.previousRunIds.length,file_count:record.files.length,
137
+ record_digest:digest(record),reason:record.reason};
138
+ const args=[writer,'--workflow','cm-ai','--event','supersede','--runtime','codex',
139
+ '--project-root',codeProject,'--specs-dir',specsDir,'--run-id',identity.runId,
140
+ '--at',record.authorizedAt,'--detail','显式归档旧任务证据','--data-json',JSON.stringify(data)];
141
+ const result=spawnSync('python3',args,{timeout:10000,maxBuffer:1024*1024,
142
+ ...(logHome?{env:{...process.env,CM_WORKFLOW_LOG_HOME:logHome}}:{})});
143
+ need(!result.error&&result.status===0,'supersede_log_failed');
144
+ }