@aibyzero/cm-workflow 0.16.9 → 0.17.0

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 (139) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +12 -0
  3. package/README.md +9 -1
  4. package/VERSION +1 -1
  5. package/docs/cm-control-policy-v2.md +331 -0
  6. package/docs/execution-optimizations.md +1 -1
  7. package/docs/external-models.md +3 -3
  8. package/docs/human-correction.md +5 -5
  9. package/docs/installation.md +1 -1
  10. package/docs/js-workflow-control.md +101 -84
  11. package/docs/next-steps.md +11 -0
  12. package/docs/untested-branches.md +2 -3
  13. package/docs/user-guide.md +3 -3
  14. package/package.json +1 -1
  15. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +13 -69
  16. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +10 -5
  17. package/runtime/js/cm-ai/control-policy.mjs +111 -0
  18. package/runtime/js/cm-ai/drive-bootstrap.mjs +11 -8
  19. package/runtime/js/cm-ai/durable-runner-state.mjs +32 -126
  20. package/runtime/js/cm-ai/gate-bridge.mjs +4 -4
  21. package/runtime/js/cm-ai/host-conversation-execution.mjs +22 -20
  22. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +11 -2
  23. package/runtime/js/cm-ai/host-qa-policy.mjs +63 -21
  24. package/runtime/js/cm-ai/host-review-authority.mjs +2 -2
  25. package/runtime/js/cm-ai/host-review-file.mjs +1 -1
  26. package/runtime/js/cm-ai/host-tool-bridge.mjs +3 -0
  27. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +21 -10
  28. package/runtime/js/cm-ai/host.mjs +1 -2
  29. package/runtime/js/cm-ai/operator-guidance.mjs +1 -24
  30. package/runtime/js/cm-ai/review-package.mjs +16 -4
  31. package/runtime/js/cm-ai/reviewed-deliveries.mjs +1 -1
  32. package/runtime/js/cm-ai/task-runner.mjs +36 -99
  33. package/runtime/js/cm-init/review-evidence.mjs +3 -1
  34. package/runtime/js/cm-prd/review-host.mjs +1 -1
  35. package/runtime/js/cm-prd/review-publication.mjs +5 -3
  36. package/runtime/js/cm-refactor/workflow.mjs +1 -1
  37. package/runtime/js/notify-send.mjs +15 -14
  38. package/runtime/js/notify.mjs +27 -4
  39. package/runtime/js/policy-binding-compat.mjs +2 -1
  40. package/runtime/review.md +52 -7
  41. package/runtime/task-gates.md +107 -9
  42. package/scripts/cm-ai-abandon-effect-position.test.mjs +1 -8
  43. package/scripts/cm-ai-answer-gap-driver.test.mjs +12 -12
  44. package/scripts/cm-ai-answer-gap-fixture.mjs +1 -8
  45. package/scripts/cm-ai-batch-drive.mjs +50 -31
  46. package/scripts/cm-ai-batch-drive.test.mjs +62 -19
  47. package/scripts/cm-ai-batch-host.mjs +39 -20
  48. package/scripts/cm-ai-batch-host.test.mjs +62 -38
  49. package/scripts/cm-ai-batch-run-fixture.mjs +6 -53
  50. package/scripts/cm-ai-batch-run-member-stops.test.mjs +0 -12
  51. package/scripts/cm-ai-batch-run.mjs +34 -8
  52. package/scripts/cm-ai-bootstrap-flow.test.mjs +1 -7
  53. package/scripts/cm-ai-bootstrap.test.mjs +2 -3
  54. package/scripts/cm-ai-control-launch.test.mjs +219 -0
  55. package/scripts/cm-ai-control-policy.test.mjs +124 -0
  56. package/scripts/cm-ai-control-v2-drive.test.mjs +270 -0
  57. package/scripts/cm-ai-develop-answer-invalid.test.mjs +1 -8
  58. package/scripts/cm-ai-develop-call-timeout.test.mjs +1 -8
  59. package/scripts/cm-ai-develop-driver-gaps.test.mjs +33 -20
  60. package/scripts/cm-ai-direct-review.test.mjs +348 -0
  61. package/scripts/cm-ai-documentation-sync-gap.test.mjs +3 -3
  62. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +54 -25
  63. package/scripts/cm-ai-drive.mjs +96 -54
  64. package/scripts/cm-ai-drive.test.mjs +43 -84
  65. package/scripts/cm-ai-fix-integration.test.mjs +3 -5
  66. package/scripts/cm-ai-fix-later-delivery.test.mjs +3 -6
  67. package/scripts/cm-ai-fix-run-delivery.test.mjs +3 -6
  68. package/scripts/cm-ai-host-cli-workflow.test.mjs +6 -10
  69. package/scripts/cm-ai-host-fixture.mjs +38 -10
  70. package/scripts/cm-ai-host-protected.test.mjs +35 -33
  71. package/scripts/cm-ai-host.mjs +103 -93
  72. package/scripts/cm-ai-host.test.mjs +19 -18
  73. package/scripts/cm-ai-launch-diagnostics.test.mjs +5 -3
  74. package/scripts/cm-ai-legacy-history.test.mjs +53 -0
  75. package/scripts/cm-ai-light-modules.test.mjs +4 -7
  76. package/scripts/cm-ai-multi-root.test.mjs +4 -4
  77. package/scripts/cm-ai-nested-execution.test.mjs +16 -19
  78. package/scripts/cm-ai-progress.test.mjs +10 -8
  79. package/scripts/cm-ai-project-qa-gate.test.mjs +37 -10
  80. package/scripts/cm-ai-protected-scope.test.mjs +1 -2
  81. package/scripts/cm-ai-qa-config-revision.test.mjs +1 -9
  82. package/scripts/cm-ai-qa-fingerprint-config.test.mjs +12 -9
  83. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +18 -3
  84. package/scripts/cm-ai-qa-fixed-log.test.mjs +41 -0
  85. package/scripts/cm-ai-qa-recovery-args.test.mjs +7 -0
  86. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +3 -4
  87. package/scripts/cm-ai-review-drift-precedence.test.mjs +1 -1
  88. package/scripts/cm-ai-review-failure.test.mjs +13 -19
  89. package/scripts/cm-ai-review-timeout-config.test.mjs +3 -1
  90. package/scripts/cm-ai-review-timeout.test.mjs +15 -128
  91. package/scripts/cm-ai-run.mjs +78 -24
  92. package/scripts/cm-ai-run.test.mjs +11 -38
  93. package/scripts/cm-ai-selection-guard.test.mjs +2 -2
  94. package/scripts/cm-ai-session-chain.test.mjs +18 -15
  95. package/scripts/cm-ai-spec-rebind.test.mjs +14 -18
  96. package/scripts/cm-ai-supersede.test.mjs +3 -10
  97. package/scripts/cm-blocked-reason.test.mjs +2 -3
  98. package/scripts/cm-capability-gate.test.mjs +33 -1
  99. package/scripts/cm-check-drive-files.mjs +1 -1
  100. package/scripts/cm-check-runtime.sh +1 -1
  101. package/scripts/cm-claude-worker.test.mjs +5 -3
  102. package/scripts/cm-controlled-correction.test.mjs +469 -0
  103. package/scripts/cm-external-batch-host.test.mjs +30 -11
  104. package/scripts/cm-external-model-host.test.mjs +1 -1
  105. package/scripts/cm-external-model-recovery.test.mjs +3 -9
  106. package/scripts/cm-external-qa-fix.test.mjs +1 -1
  107. package/scripts/cm-external-review-reconciliation.test.mjs +6 -24
  108. package/scripts/cm-fix-review-recovery.test.mjs +1 -1
  109. package/scripts/cm-host-qa-executor.test.mjs +1 -2
  110. package/scripts/cm-host-qa-policy.test.mjs +43 -16
  111. package/scripts/cm-host-review-authority.test.mjs +0 -31
  112. package/scripts/cm-knowledge-closeout.test.mjs +3 -3
  113. package/scripts/cm-notify-command.test.mjs +54 -18
  114. package/scripts/cm-notify-read-drift.test.mjs +69 -4
  115. package/scripts/cm-notify.mjs +16 -4
  116. package/scripts/cm-notify.test.mjs +91 -19
  117. package/scripts/cm-patrol.test.mjs +3 -2
  118. package/scripts/cm-task-gate-correction.test.mjs +69 -16
  119. package/scripts/cm-task-gate.mjs +368 -34
  120. package/scripts/cm-task-gate.py +2 -0
  121. package/scripts/cm-task-gate.test.mjs +252 -4
  122. package/scripts/fixtures/bootstrap-review-runner.mjs +1 -7
  123. package/scripts/fixtures/native-gate-fixture.mjs +18 -0
  124. package/scripts/policy-binding-compat.test.mjs +4 -0
  125. package/skills/cm-ai/SKILL.md +8 -6
  126. package/skills/cm-ai/references/N3-execute-task.md +17 -2
  127. package/skills/cm-ai/references/N4-review.md +11 -21
  128. package/skills/cm-ai/references/N5-mark-done.md +1 -1
  129. package/skills/cm-ai/references/N6-qa-eval.md +49 -21
  130. package/skills/cm-ai/references/js-host-modes.md +35 -14
  131. package/skills/cm-ai/references/js-host-qa-recovery.md +60 -12
  132. package/skills/cm-ai/references/js-host-recovery.md +95 -47
  133. package/skills/cm-ai/references/js-host.md +65 -28
  134. package/skills/cm-fix/SKILL.md +12 -0
  135. package/skills/cm-init/references/js-host.md +1 -1
  136. package/skills/cm-prd/references/js-host.md +1 -1
  137. package/skills/cm-refactor/SKILL.md +12 -0
  138. package/runtime/js/cm-ai/review-dispatch-limits.mjs +0 -18
  139. package/scripts/cm-ai-review-dispatch-exit.test.mjs +0 -475
@@ -41,9 +41,22 @@ function fixture(runtime='codex'){
41
41
  ...(runtime==='claude'?['--runtime','claude']:[])]};
42
42
  }
43
43
 
44
- function execute(f,approvals,{cancel=false}={}){
44
+ // Use an actual first-round review finding for a launch-only revision pause.
45
+ // The synthetic native process still emits its normal bound review observation.
46
+ function requestFirstRevision(f,taskIds){
47
+ const fake=path.join(f.root,'bin',f.runtime);
48
+ const first=`${JSON.stringify(taskIds)}.includes(data.reviewPackage.identity.taskId)&&data.reviewPackage.identity.attempt===1`;
49
+ const source=fs.readFileSync(fake,'utf8');
50
+ assert(source.includes("verdict:'approved'")&&source.includes('findings:[]'),'native review fixture must retain its known response fields');
51
+ fs.writeFileSync(fake,source
52
+ .replace("verdict:'approved'",`verdict:(${first})?'changes_requested':'approved'`)
53
+ .replace('findings:[]',`findings:(${first})?[{id:'F1',severity:'P2',path:'task'+Number(data.reviewPackage.identity.taskId.slice(-1))+'.mjs',message:'Recheck the export in a revision',evidence:'Synthetic first-round review finding'}]:[]`));
54
+ return taskIds.flatMap(taskId=>['--hold-revision',`1.work/${taskId}`]);
55
+ }
56
+
57
+ function execute(f,{cancel=false,args=[]}={}){
45
58
  return new Promise((resolve,reject)=>{
46
- const child=spawn(process.execPath,[cli,...f.args,...approvals.flatMap(value=>['--allow-review',value])],
59
+ const child=spawn(process.execPath,[cli,...f.args,...args],
47
60
  {env:f.env,stdio:['pipe','pipe','pipe']});
48
61
  let buffer='',stderr='',sessionId;const calls=[],rows=[];
49
62
  const timer=setTimeout(()=>{child.kill('SIGTERM');reject(Error('batch host timeout'));},Number(process.env.CM_TEST_FIXTURE_TIMEOUT_MS??60000));
@@ -69,7 +82,7 @@ function execute(f,approvals,{cancel=false}={}){
69
82
  assert.deepEqual(payload.request.payload.scope,f.batch.tasks[n-1].scope);
70
83
  assert.equal(payload.request.payload.specification.task.id,identity.taskId);
71
84
  assert.deepEqual(payload.request.payload.specification.sources,buildManifest(f.specsDir));
72
- const content=`export const value = ${40+n};\n`;
85
+ const content=`export const value = ${40+n};\n${identity.attempt===2?"// Revised after the independent review finding.\n":""}`;
73
86
  if(!f.protected)fs.writeFileSync(path.join(cwd,`task${n}.mjs`),content);
74
87
  respond(row,{status:'succeeded',value:{outcome:'implemented',application:{status:'no_relevant_lesson',note:null},
75
88
  retrospective:{status:'no_new_lesson',candidates:[],reason:null}},...(f.protected?{edits:
@@ -81,8 +94,7 @@ function execute(f,approvals,{cancel=false}={}){
81
94
  const result=spawnSync(command[0],command.slice(1));assert.equal(result.status,0);
82
95
  return {id:'syntax',command,outcome:'passed',exitCode:0,evidence:'Actual Node syntax check exited 0'};
83
96
  });respond(row,checks);
84
- }else if(row.kind==='qa_assess')respond(row,{scores:{scope:2,risk:2,accumulation:2,boundary:2},
85
- changes:{api:false,migration:false,authentication:false,authorization:false,payment:false}});
97
+ }else if(row.kind==='qa_assess')respond(row,{confirmed:true});
86
98
  else if(row.kind==='documentation_sync'){
87
99
  assert.equal(identity.taskId,'T-002');assert.deepEqual(payload.paths,['README.md']);
88
100
  fs.writeFileSync(path.join(f.codeProject,'README.md'),'# Exports 41 and 42\n');respond(row,{status:'completed'});
@@ -112,13 +124,16 @@ for(const runtime of ['codex','claude'])test(`${runtime} real batch host freezes
112
124
  const sent=path.join(f.root,'sent.jsonl'),fake=path.join(f.root,'bin',runtime);
113
125
  fs.writeFileSync(fake,fs.readFileSync(fake,'utf8').replace("import {randomUUID}",`import fs from 'node:fs';fs.appendFileSync(${JSON.stringify(sent)},JSON.stringify(process.argv.slice(2))+'\\n');\nimport {randomUUID}`));
114
126
  const review=JSON.parse(fs.readFileSync(f.review));review.effort=pair.effort;review.preflight.config_fingerprint=(runtime==='claude'?claudeReviewFingerprint:configFingerprint)({cwd:f.codeProject,...pair});fs.writeFileSync(f.review,JSON.stringify(review));f.args.push('--external-models');
115
- const first=await execute(f,[]);assert.equal(first.result.state,'awaiting_review',first.stderr+JSON.stringify(first.result));
127
+ const held=requestFirstRevision(f,['T-001']);
128
+ const first=await execute(f,{args:held});assert.equal(first.result.state,'changes_requested',first.stderr+JSON.stringify(first.result));
129
+ assert.equal(first.result.code,'revision_answer_required');assert.equal(first.result.identity.attempt,2);
130
+ assert.deepEqual(first.calls,['T-001:develop','T-001:check']);
116
131
  const {batchTaskRunId}=await import('./cm-ai-batch-run.mjs');const statePath=n=>path.join(f.specsDir,'.reviews','.execution',batchTaskRunId(f.batch.batchId,'1.work/T-00'+n),'state.json');
117
132
  assert(!fs.existsSync(statePath(2)));assert.deepEqual(JSON.parse(fs.readFileSync(statePath(1))).records[0].payload.config.externalModels,models);
118
133
  fs.writeFileSync(settings,'invalid new user defaults');
119
- const end=await execute(f,['1.work/T-001:1','1.work/T-002:1']);assert.equal(end.result.code,'run_done',end.stderr+JSON.stringify(end.result));
134
+ const end=await execute(f);assert.equal(end.result.code,'run_done',end.stderr+JSON.stringify(end.result));
120
135
  for(const n of [1,2])assert.deepEqual(JSON.parse(fs.readFileSync(statePath(n))).records[0].payload.config.externalModels,models);
121
- const calls=fs.readFileSync(sent,'utf8').trim().split('\n').map(JSON.parse);assert.equal(calls.length,2);
136
+ const calls=fs.readFileSync(sent,'utf8').trim().split('\n').map(JSON.parse);assert.equal(calls.length,3);
122
137
  for(const args of calls){if(runtime==='codex'){assert(args.includes('model_reasoning_effort="low"'));assert(args.includes('--ephemeral'));}else{assert(!args.includes('--effort'));assert(args.includes('--no-session-persistence'));}}
123
138
  const tracked=spawnSync('git',['-C',f.codeProject,'ls-files'],{encoding:'utf8'});assert(!tracked.stdout.includes('.cm-external-models-v1.json'));assert(!tracked.stdout.includes('.cm-model-config.lock'));
124
139
  }finally{fs.rmSync(f.root,{recursive:true,force:true});}
@@ -136,7 +151,7 @@ test('new parallel batch merges reviewed members without committing private bind
136
151
  const review=JSON.parse(fs.readFileSync(f.review));review.effort='low';review.preflight.config_fingerprint=configFingerprint({cwd:f.codeProject,model:'fixture',effort:'low'});fs.writeFileSync(f.review,JSON.stringify(review));f.args.push('--external-models');
137
152
  fs.writeFileSync(path.join(f.codeProject,'README.md'),'# Exports 41 and 42\n');
138
153
  for(const args of [['add','README.md'],['commit','-m','fixture documentation']])assert.equal(spawnSync('git',['-C',f.codeProject,...args]).status,0);
139
- const end=await execute(f,['1.work/T-001:1','1.work/T-002:1','1.work/T-003:1']);assert.equal(end.result.code,'run_done',end.stderr+JSON.stringify(end.result));
154
+ const end=await execute(f);assert.equal(end.result.code,'run_done',end.stderr+JSON.stringify(end.result));
140
155
  const tracked=spawnSync('git',['-C',f.codeProject,'ls-files'],{encoding:'utf8'}).stdout;assert(!tracked.includes('.cm-external-models-v1.json'));assert(!tracked.includes('.cm-model-config.lock'));
141
156
  for(const n of [1,2])assert(!fs.existsSync(path.join(f.root,'.cm-worktrees',f.batch.batchId.slice(0,8),'T-00'+n)));
142
157
  }finally{fs.rmSync(f.root,{recursive:true,force:true});}
@@ -145,12 +160,16 @@ test('new parallel batch merges reviewed members without committing private bind
145
160
  test('optimization-only serial batch freezes policy for later members after removing launch flag',async()=>{
146
161
  const f=fixture();f.args.push('--execution-optimizations');f.env.CM_WORKFLOW_HOME=path.join(f.root,'home');f.env.CM_WORKFLOW_LOG_HOME=path.join(f.root,'logs');
147
162
  try{
148
- const first=await execute(f,[]);assert.equal(first.result.state,'awaiting_review',first.stderr+JSON.stringify(first.result));
163
+ const held=requestFirstRevision(f,['T-001']);
164
+ const first=await execute(f,{args:held});assert.equal(first.result.state,'changes_requested',first.stderr+JSON.stringify(first.result));
165
+ assert.equal(first.result.code,'revision_answer_required');assert.equal(first.result.identity.attempt,2);
166
+ assert.deepEqual(first.calls,['T-001:develop','T-001:check']);
149
167
  const {batchTaskRunId}=await import('./cm-ai-batch-run.mjs');
150
168
  const statePath=n=>path.join(f.specsDir,'.reviews','.execution',batchTaskRunId(f.batch.batchId,'1.work/T-00'+n),'state.json');
169
+ assert(!fs.existsSync(statePath(2)));
151
170
  assert.deepEqual(JSON.parse(fs.readFileSync(statePath(1))).records[0].payload.config.executionPolicy,EXECUTION_POLICY_V1);
152
171
  f.args=f.args.filter(arg=>arg!=='--execution-optimizations');
153
- const end=await execute(f,['1.work/T-001:1','1.work/T-002:1']);assert.equal(end.result.code,'run_done',end.stderr+JSON.stringify(end.result));
172
+ const end=await execute(f);assert.equal(end.result.code,'run_done',end.stderr+JSON.stringify(end.result));
154
173
  for(const n of [1,2])assert.deepEqual(JSON.parse(fs.readFileSync(statePath(n))).records[0].payload.config.executionPolicy,EXECUTION_POLICY_V1);
155
174
  const tracked=spawnSync('git',['-C',f.codeProject,'ls-files'],{encoding:'utf8'});assert(!tracked.stdout.includes('.cm-external-models-v1.json'));
156
175
  }finally{fs.rmSync(f.root,{recursive:true,force:true});}
@@ -62,7 +62,7 @@ else for(const event of [{type:'thread.started',thread_id:dev?'fake-author':'fak
62
62
  const routes=resolveProtectedRuntimes(loadConfig({projectRoot:codeProject}),'codex');
63
63
  const execution=(selected=models,{legacy=false}={})=>createConversationExecution(definition,'fixture-host',bridge,
64
64
  legacy?((({effort,...rest})=>({...rest,model:'fixture-codex',preflight:{...rest.preflight,config_fingerprint:configFingerprint({cwd:codeProject,model:'fixture-codex'})}}))(review)):review,
65
- 1,null,false,'codex',{
65
+ null,null,false,'codex',{
66
66
  ...(efficiency?{executionPolicy:EXECUTION_POLICY_V1}:{}),
67
67
  ...(!legacy?{externalModels:selected}:{}),
68
68
  ...(!session?{protection,providerDevelopment:{model:legacy?'fixture-codex':selected.providers.codex.model,
@@ -9,15 +9,9 @@ import {openTaskExecutionStore} from '../runtime/js/cm-ai/task-owner.mjs';
9
9
  import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
10
10
  import {readRunnerHistory} from '../runtime/js/cm-ai/durable-runner-state.mjs';
11
11
  import {reviewPaths} from '../runtime/js/cm-ai/review-runner.mjs';
12
- import {writeHandoff,writeReview} from '../experiments/js-orchestration/native-gate-fixture.mjs';
12
+ import {writeHandoff,writeReview} from './fixtures/native-gate-fixture.mjs';
13
13
  import {acquireExternalRunGuard} from '../runtime/js/cm-ai/external-run-guard.mjs';
14
14
  import {memberSupersedeAdmitted} from './cm-ai-batch-run.mjs';
15
- const grant=(request,issuedAt)=>{
16
- const value={version:1,kind:'cm-review-dispatch-grant',grantId:'grant-'+request.invocationId,adapterId:'codex-review-adapter',
17
- invocationId:request.invocationId,requestDigest:request.requestDigest,identity:request.identity,reviewerId:'reviewer',logicalContextId:request.contextId,
18
- packageDigest:request.payload.reviewPackage.packageDigest,hostContextId:'host',decisionId:'decision-'+request.invocationId,decision:'approved',issuedAt,expiresAt:issuedAt+60000};
19
- return {...value,grantDigest:digest(value)};
20
- };
21
15
  async function fixture(fn,review,{strict=true,timeoutMs=2000,externalDeveloper=false,policyOnly=false}={}){
22
16
  const tmp=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-external-recovery-'))),root=path.join(tmp,'code'),specsRoot=path.join(tmp,'specs');
23
17
  fs.mkdirSync(root);fs.mkdirSync(specsRoot);fs.mkdirSync(path.join(specsRoot,'feature'));fs.mkdirSync(path.join(specsRoot,'.reviews'));
@@ -33,7 +27,7 @@ async function fixture(fn,review,{strict=true,timeoutMs=2000,externalDeveloper=f
33
27
  }},reviewers:[{id:'reviewer',adapterId:'codex-review-adapter',provider:'codex',requestedModel:'fixture',allowed:true,available:true,contexts:['review-1','review-2'],run:(request,control)=>{calls++;const result=review(request,control);if(result?.status==='succeeded')writeReview(path.join(specsRoot,'.reviews/feature-T-001-r'+request.identity.attempt+'.md'),path.join(specsRoot,'.reviews/feature-T-001-a'+request.identity.attempt+'-handoff.json'),request.identity.attempt,result.value.verdict);return result;}}],
34
28
  check:()=>[{id:'check',command:['controlled'],outcome:'passed',exitCode:0,evidence:'fixture'}],
35
29
  taskCompletion:{reviewsDir:path.join(specsRoot,'.reviews'),handoffs:[path.join(specsRoot,'.reviews/feature-T-001-a1-handoff.json'),path.join(specsRoot,'.reviews/feature-T-001-a2-handoff.json')]},
36
- reviewInvocation:{developerThreadId:'developer-thread',excludedThreadIds:['host'],hostContextId:'host',authorize:(request,{authorizationAt})=>grant(request,authorizationAt)}};
30
+ reviewInvocation:{developerThreadId:'developer-thread',excludedThreadIds:['host'],hostContextId:'host'}};
37
31
  const make=mode=>createTaskRunner({...options,persistence:{store,mode,version:3}});
38
32
  const reopen=()=>{store.close();store=openTaskExecutionStore({...owner,create:false});return make('resume');};
39
33
  const records=()=>store.snapshot().records;
@@ -110,7 +104,7 @@ test('valid changes_requested permits a fresh separately authorized second attem
110
104
  const runner=f.make();await runner.executeEffect(f.effect('develop'));assert.equal((await runner.executeEffect(f.effect('review'))).state,'changes_requested');
111
105
  await runner.executeEffect(f.effect('develop',2));assert.equal((await runner.executeEffect(f.effect('review',2))).state,'approved');
112
106
  const done=await runner.executeEffect(f.effect('complete',2));assert.equal(done.state,'fixture_completed',JSON.stringify(done));assert.equal(f.calls(),2);
113
- const registered=f.records().filter(row=>row.payload.type==='review-invocation-registered');assert.equal(registered.length,2);assert.notEqual(registered[0].payload.grant.invocationId,registered[1].payload.grant.invocationId);
107
+ const registered=f.records().filter(row=>row.payload.type==='review-invocation-registered');assert.equal(registered.length,2);assert.notEqual(registered[0].payload.binding.invocationId,registered[1].payload.binding.invocationId);
114
108
  assert.throws(()=>f.guard({identity:{repositoryId:'fixture',runId:'next-task-run',taskId:'T-002',attempt:1}}),{code:'external_prior_writer_active'});
115
109
  f.closeStore();
116
110
  const next=f.guard({identity:{repositoryId:'fixture',runId:'next-task-run',taskId:'T-002',attempt:1}});next.close();assert.equal(f.calls(),2);
@@ -58,7 +58,7 @@ async function fixture(t,{childHost=A,causeContext=null,lostCauseReviews=0,exter
58
58
  retrospective:{status:'no_new_lesson',candidates:[],reason:null}}};
59
59
  }};
60
60
  const executionFor=live=>{
61
- const execution=createConversationExecution(definition,live,bridge,review,1,workflow,true,'codex',
61
+ const execution=createConversationExecution(definition,live,bridge,review,null,workflow,true,'codex',
62
62
  live===A?{}:{originalHostContextId:A});
63
63
  execution.check=createHostCheck({cwd:codeProject,commands:[{id:'existing',command:[process.execPath,'existing.mjs']}]});
64
64
  execution.reviewers[0].run=async(request,{onEvent})=>{
@@ -25,13 +25,6 @@ import {createClaudeReviewRun} from '../runtime/js/cm-ai/claude-review-adapter.m
25
25
 
26
26
 
27
27
  const checks=[{id:'check',command:['synthetic'],outcome:'passed',exitCode:0,evidence:'fixture'}];
28
- const grantFor=(request,authorizationAt,change=grant=>grant)=>{
29
- const body={version:1,kind:'cm-review-dispatch-grant',grantId:`grant-${request.invocationId}`,adapterId:`${request.provider}-review-adapter`,
30
- invocationId:request.invocationId,requestDigest:request.requestDigest,identity:request.identity,
31
- reviewerId:'reviewer',logicalContextId:request.contextId,packageDigest:request.payload.reviewPackage.packageDigest,
32
- hostContextId:'actual-main',decisionId:'decision-1',decision:'approved',issuedAt:authorizationAt,expiresAt:authorizationAt+60000};
33
- change(body);return {...body,grantDigest:digest(body)};
34
- };
35
28
  const events=(onEvent,thread='actual-review')=>{
36
29
  onEvent({event:'thread.started',provider_thread:thread});
37
30
  onEvent({event:'turn.started',item_type:null});
@@ -40,7 +33,7 @@ const events=(onEvent,thread='actual-review')=>{
40
33
  onEvent({event:'process_closed',exit_code:0,signal:null,timed_out:false});
41
34
  };
42
35
 
43
- async function fixture(fn,{reviewRun,authorize,times,timeoutMs=1000,provider='codex'}={}) {
36
+ async function fixture(fn,{reviewRun,times,timeoutMs=1000,provider='codex'}={}) {
44
37
  const temp=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-review-v3-')));
45
38
  const root=path.join(temp,'code'),specsRoot=path.join(temp,'specs'),reviewsDir=path.join(specsRoot,'.reviews');
46
39
  fs.mkdirSync(root);fs.mkdirSync(reviewsDir,{recursive:true});
@@ -64,8 +57,7 @@ async function fixture(fn,{reviewRun,authorize,times,timeoutMs=1000,provider='co
64
57
  dispatches++;lateEvent=control.onEvent;return (reviewRun??defaultRun)(request,control);
65
58
  }}],check:()=>checks,
66
59
  taskCompletion:{reviewsDir,handoffs:[path.join(reviewsDir,'a1.json'),path.join(reviewsDir,'a2.json')]},
67
- reviewInvocation:{developerThreadId:'actual-developer',excludedThreadIds:['actual-main'],
68
- authorize:authorize??((request,{authorizationAt})=>grantFor(request,authorizationAt))}};
60
+ reviewInvocation:{developerThreadId:'actual-developer',excludedThreadIds:['actual-main']}};
69
61
  const make=mode=>{
70
62
  const old=Date.now,values=times?[...times]:null;if(values)Date.now=()=>values.length>1?values.shift():values[0];
71
63
  try{return createTaskRunner({...options,persistence:{store,mode,version:3}});}finally{Date.now=old;}
@@ -127,7 +119,7 @@ for(const provider of ['codex','claude'])test(`${provider} late terminal receipt
127
119
  assert.equal(f.dispatches(),1);
128
120
  },{timeoutMs:20,provider,reviewRun:lateReceiptRun({duplicate:true})}));
129
121
 
130
- test('reconciled provider failure spends the original one-retry budget and requires a fresh grant',()=>fixture(async f=>{
122
+ test('reconciled provider failure spends the original one-retry budget and requires a fresh request binding',()=>fixture(async f=>{
131
123
  const runner=f.make();await runner.executeEffect(f.effect('develop'));
132
124
  const first=await runner.executeEffect(f.effect('review'));
133
125
  const after=runner.reconcileReview({invocationId:first.reviewReconciliation.invocationId});
@@ -135,7 +127,7 @@ test('reconciled provider failure spends the original one-retry budget and requi
135
127
  const second=await runner.executeEffect(retryEffect(f));assert.equal(second.state,'unknown');
136
128
  const final=runner.reconcileReview({invocationId:second.reviewReconciliation.invocationId});
137
129
  assert.equal(final.state,'blocked');assert.equal(final.code,'review_provider_failed');assert.equal(f.dispatches(),2);
138
- assert.notEqual(first.reviewInvocation.registration.grant.grantDigest,second.reviewInvocation.registration.grant.grantDigest);
130
+ assert.notEqual(first.reviewInvocation.registration.binding.requestDigest,second.reviewInvocation.registration.binding.requestDigest);
139
131
  assert.equal((await runner.executeEffect({...retryEffect(f),id:'third-review'})).code,'stage_mismatch');
140
132
  assert.equal(f.dispatches(),2);assert.deepEqual(f.reopen().status(),final);
141
133
  },{timeoutMs:20,reviewRun:lateReceiptRun({failed:true})}));
@@ -147,7 +139,7 @@ test('replay rejects receipt or reconciliation bindings even when an attacker re
147
139
  const original=f.getStore().snapshot().records;
148
140
  for(const [type,key,value] of [
149
141
  ['review-invocation-receipt','invocationId','other-call'],['review-invocation-receipt','effectId','review-2'],
150
- ['review-invocation-receipt','registeredDigest',digest('other-grant')],
142
+ ['review-invocation-receipt','registeredDigest',digest('other-registration')],
151
143
  ['review-invocation-receipt','startedDigest',digest('other-thread')],
152
144
  ['review-invocation-receipt','resultDigest',digest('other-result')],
153
145
  ['review-invocation-reconciled','receiptDigest',digest('other-receipt')],
@@ -160,16 +152,6 @@ test('replay rejects receipt or reconciliation bindings even when an attacker re
160
152
  assert.deepEqual(f.getStore().snapshot().records,original);assert.equal(f.dispatches(),1);
161
153
  },{timeoutMs:20,reviewRun:lateReceiptRun()}));
162
154
 
163
- test('reconciliation is not dispatch approval and the original grant cannot authorize another invocation',()=>{
164
- let originalGrant;
165
- return fixture(async f=>{
166
- const runner=f.make();await runner.executeEffect(f.effect('develop'));
167
- const first=await runner.executeEffect(f.effect('review'));
168
- runner.reconcileReview({invocationId:first.reviewReconciliation.invocationId});
169
- assert.equal((await runner.executeEffect(retryEffect(f))).code,'authorization_invalid');
170
- assert.equal(f.dispatches(),1);
171
- },{timeoutMs:20,reviewRun:lateReceiptRun({failed:true}),authorize:(request,{authorizationAt})=>originalGrant??=grantFor(request,authorizationAt)});
172
- });
173
155
 
174
156
  for(const [name,change] of [
175
157
  ['only local exit',r=>{r.events=r.events.filter(e=>!['item.completed','turn.completed'].includes(e.event));r.result={status:'failed',code:'incomplete_result'};}],
@@ -241,7 +223,7 @@ setInterval(()=>{},1000);
241
223
  const retry=await resumed.executeEffect(retryEffect(f));assert.equal(retry.state,'unknown');
242
224
  const exhausted=resumed.reconcileReview({invocationId:retry.reviewReconciliation.invocationId});
243
225
  assert.equal(exhausted.state,'blocked');assert.equal(spawns,2);
244
- assert.notEqual(first.reviewInvocation.registration.grant.grantDigest,retry.reviewInvocation.registration.grant.grantDigest);
226
+ assert.notEqual(first.reviewInvocation.registration.binding.requestDigest,retry.reviewInvocation.registration.binding.requestDigest);
245
227
  }
246
228
  },{provider,timeoutMs:2000}));
247
229
 
@@ -180,7 +180,7 @@ test('one authorized CLI continuation preserves old history and reaches the orig
180
180
  await resumed.reviewFinal();assert.equal(f.calls(),2);assert.equal(f.repairs(),1);
181
181
  });
182
182
 
183
- for(const mode of ['loss-again','reuse-thread','approved','changes_requested'])test(`continuation refuses unsafe reuse: ${mode}`,{timeout:10000},async t=>{
183
+ for(const mode of ['loss-again','reuse-thread','approved','changes_requested'])test(`continuation refuses unsafe reuse: ${mode}`,{timeout:FIXTURE_TIMEOUT_MS},async t=>{
184
184
  const f=await fixture(t,mode);
185
185
  if(['approved','changes_requested'].includes(mode)){
186
186
  await f.cli([f.request],['--allow-final-review-recovery']).then(rows=>assert.equal(rows[0].error.code,'host_request_failed'));
@@ -84,8 +84,7 @@ for(const transport of ['synchronous','jsonl','coalesced-jsonl'])test(`incident
84
84
  const seen=[];
85
85
  const answer=row=>{
86
86
  seen.push(row.kind==='qa_assess'?row.kind:row.payload.case.id);
87
- if(row.kind==='qa_assess')return {scores:{scope:1,risk:1,accumulation:1,boundary:1},
88
- changes:{api:false,migration:false,authentication:false,authorization:false,payment:false}};
87
+ if(row.kind==='qa_assess')return {confirmed:true};
89
88
  if(row.kind==='qa_logic')return {verdict:'SUPPORTED',evidence:['Synthetic static observation']};
90
89
  const artifact=path.join(f.configuration.specsDir,'.reviews',`${row.payload.case.id}.txt`);
91
90
  fs.writeFileSync(artifact,'Synthetic browser evidence; no real browser');
@@ -4,26 +4,38 @@ import fs from 'node:fs';
4
4
  import os from 'node:os';
5
5
  import path from 'node:path';
6
6
  import {inspectCmAiQaTaskContext} from '../runtime/js/cm-ai/cm-ai-admission.mjs';
7
- import {createHostQaDecisionProvider,decideHostQaPolicy} from '../runtime/js/cm-ai/host-qa-policy.mjs';
7
+ import {createHostQaDecisionProvider,decideHostQaPolicy,readQaAssessment} from '../runtime/js/cm-ai/host-qa-policy.mjs';
8
8
 
9
- const low=()=>({scores:{scope:1,risk:1,accumulation:1,boundary:1},
10
- changes:{api:false,migration:false,authentication:false,authorization:false,payment:false}});
11
- test('N6 enforces mandatory triggers ahead of low scores and bounds the API merge exemption',()=>{
12
- const input={assessment:low(),pending:2,mergeEligible:false,unassessedTasks:1};
13
- assert.equal(decideHostQaPolicy(input).status,'skipped');
9
+ const low=()=>({confirmed:true});
10
+ const basePolicy=()=>({changedFiles:['src/ordinary.mjs'],criticalPaths:{},pending:2,mergeEligible:false,unassessedTasks:1});
11
+ test('N6 no_fixed_trigger is skipped with null score, without model risk inputs',()=>{
12
+ assert.deepEqual(decideHostQaPolicy(basePolicy()),{status:'skipped',score:null,reason:'no_fixed_trigger'});
13
+ const input=basePolicy();
14
14
  assert.equal(decideHostQaPolicy({...input,pending:0}).reason,'feature_complete');
15
15
  assert.equal(decideHostQaPolicy({...input,unassessedTasks:5}).reason,'five_tasks_without_qa');
16
- for(const field of Object.keys(input.assessment.changes)){
17
- const assessment=low();assessment.changes[field]=true;
18
- assert.equal(decideHostQaPolicy({...input,assessment}).status,'triggered',field);
16
+ });
17
+ test('N6 registered path matching triggers all categories and bounds API merge',()=>{
18
+ const input=basePolicy();
19
+ for(const name of ['migration','authentication','authorization','payment','api']){
20
+ const criticalPaths={[name]:['src/**/critical?.mjs']};
21
+ assert.deepEqual(decideHostQaPolicy({...input,criticalPaths,changedFiles:['src/critical1.mjs']}),
22
+ {status:'triggered',score:null,reason:name});
23
+ assert.equal(decideHostQaPolicy({...input,criticalPaths,changedFiles:['src/deep/critical2.mjs']}).reason,name);
24
+ assert.equal(decideHostQaPolicy({...input,criticalPaths,changedFiles:['src/critical12.mjs']}).status,'skipped');
19
25
  }
20
- const assessment=low();assessment.changes.api=true;
21
- assert.equal(decideHostQaPolicy({...input,assessment,pending:1,mergeEligible:true}).reason,'merged_to_feature_qa');
22
- assessment.changes.payment=true;
23
- assert.equal(decideHostQaPolicy({...input,assessment,pending:1,mergeEligible:true}).reason,'payment');
24
- const high=low();high.scores.risk=5;
25
- assert.deepEqual(decideHostQaPolicy({...input,assessment:high}),{status:'triggered',score:8,reason:'risk_score'});
26
- high.scores.risk=0;assert.throws(()=>decideHostQaPolicy({...input,assessment:high}),{code:'qa_assessment_invalid'});
26
+ const criticalPaths={api:['src/api/*'],payment:['src/pay.mjs'],migration:['db/schema.sql']};
27
+ assert.equal(decideHostQaPolicy({...input,criticalPaths,changedFiles:['src/api/a.mjs'],pending:1,mergeEligible:true}).reason,'merged_to_feature_qa');
28
+ assert.equal(decideHostQaPolicy({...input,criticalPaths,changedFiles:['src/api/deep/a.mjs']}).reason,'no_fixed_trigger');
29
+ assert.equal(decideHostQaPolicy({...input,criticalPaths,changedFiles:['db/schema.sql','src/pay.mjs','src/api/a.mjs'],pending:0,unassessedTasks:5}).reason,
30
+ 'feature_complete,migration,payment,five_tasks_without_qa,api');
31
+ assert.equal(decideHostQaPolicy({...input,criticalPaths,changedFiles:['src/pay.mjs','src/api/a.mjs'],pending:1,mergeEligible:true}).reason,'payment');
32
+ });
33
+ test('N6 rejects unsafe registry and paths rather than silently missing triggers',()=>{
34
+ const input=basePolicy();
35
+ for(const criticalPaths of [{unknown:['a']},{api:'a'},{api:['../a']},{api:['/a']},{api:['src/{a,b}.mjs']},{api:['src/[ab].mjs']},{api:['src/**x.mjs']},{api:['src\\a.mjs']}])
36
+ assert.throws(()=>decideHostQaPolicy({...input,criticalPaths}));
37
+ for(const changedFiles of [['../a'],['/a'],['a\\b'],['a','a'],['a//b']])
38
+ assert.throws(()=>decideHostQaPolicy({...input,changedFiles}));
27
39
  });
28
40
 
29
41
  test('N6 derives consecutive work from original task inventory and QA log without a counter store',async()=>{
@@ -53,6 +65,15 @@ test('N6 derives consecutive work from original task inventory and QA log withou
53
65
  const skips=rows.map(row=>({...row,status:'skipped',score:4}));
54
66
  fs.writeFileSync(log,[oldCurrent,...skips].map(row=>JSON.stringify(row)).join('\n')+'\n');
55
67
  assert.equal((await decide()).reason,'five_tasks_without_qa');assert.equal(seen.at(-1),5);
68
+ const sourced=createHostQaDecisionProvider({timeoutMs:1000,criticalPaths:{payment:['source.js']},assess:async request=>{
69
+ assert.deepEqual(request.changedFiles,{paths:['source.js'],source:'review_package'});
70
+ assert.deepEqual(request.criticalPaths,{payment:['source.js']});
71
+ assert.equal(Object.hasOwn(request,'scores'),false);assert.equal(Object.hasOwn(request,'changes'),false);
72
+ return {confirmed:true};}});
73
+ const sourceBinding={...binding,changedFiles:{paths:['source.js'],source:'review_package'}};
74
+ const sourcedDecision=await sourced.decide(sourceBinding,new AbortController().signal);
75
+ assert.equal(sourcedDecision.reason,'payment,five_tasks_without_qa');assert.equal(sourcedDecision.changedFilesSource,'review_package');
76
+ await assert.rejects(sourced.decide(binding,new AbortController().signal),{code:'qa_policy_unavailable'});
56
77
  const stale=createHostQaDecisionProvider({timeoutMs:1000,assess:async()=>{
57
78
  fs.writeFileSync(path.join(specsDir,feature,'tasks.md'),'- [x] T-005: task\n');return low();}});
58
79
  await assert.rejects(stale.decide(binding,new AbortController().signal),{code:'stale_qa'});
@@ -91,3 +112,9 @@ test('step30 unseen excludes closed features, includes other open features, and
91
112
  await decide();assert.equal(seen.at(-1),2);
92
113
  }finally{fs.rmSync(root,{recursive:true,force:true});}
93
114
  });
115
+
116
+ test('qa_assess confirms only inventory source and rejects self-reported scores or risk flags',()=>{
117
+ assert.deepEqual(readQaAssessment({confirmed:true}),{confirmed:true});
118
+ for(const value of [{confirmed:false},{confirmed:true,scores:{scope:5}},{confirmed:true,changes:{api:true}},
119
+ {scores:{scope:1,risk:1,accumulation:1,boundary:1},changes:{api:false}}])assert.throws(()=>readQaAssessment(value));
120
+ });
@@ -1,13 +1,11 @@
1
1
  import test from 'node:test';
2
2
  import assert from 'node:assert/strict';
3
3
  import {createHostReviewAuthority} from '../runtime/js/cm-ai/host-review-authority.mjs';
4
- import {createCmAiConversationEntry} from '../runtime/js/cm-ai/cm-ai-conversation-entry.mjs';
5
4
  import {validateReviewDispatchGrant} from '../runtime/js/cm-ai/durable-runner-state.mjs';
6
5
  import {requestFor} from '../runtime/js/cm-ai/effect-contract.mjs';
7
6
 
8
7
  const identity={repositoryId:'review-host',runId:'run',taskId:'T-001',attempt:1},packageDigest='a'.repeat(64);
9
8
  const binding={specsDir:'/specs',codeProject:'/code',feature:'1.work',identity,packageDigest};
10
- const operation=name=>({version:1,operation:name,requestId:name,identity,...(name==='decision'?{packageDigest}:{})});
11
9
  const request=requestFor({invocationId:'actual-request',identity,role:'reviewer',provider:'codex',
12
10
  requestedModel:'fixture',contextId:'review-context',payload:{reviewPackage:{packageDigest},priorReview:null}});
13
11
  const authority=decide=>createHostReviewAuthority({hostContextId:'host',reviewerId:'reviewer',adapterId:'codex-review-adapter',decide});
@@ -29,32 +27,3 @@ test('host decision issues one original grant only after the actual request exis
29
27
  {status:'denied',code:'permission_denied'},mode);
30
28
  }
31
29
  });
32
-
33
- for(const mode of ['approved','awaiting','denied','timeout','cancel','drift'])test(`dynamic review decision: ${mode}`,async()=>{
34
- let current={state:'awaiting_review',code:null,identity,packageDigest},effects=0,started,release;
35
- const ready=new Promise(resolve=>{started=resolve;});
36
- const runner={status:()=>current,run:async()=>current,
37
- cancel:()=>{current={...current,state:'cancelled',code:'cancelled',cancellationRequested:true};return current;},
38
- executeEffect:async()=>{effects++;return current;}};
39
- let decisions=0;
40
- const entry=createCmAiConversationEntry({specsDir:binding.specsDir,codeProject:binding.codeProject,
41
- feature:binding.feature,identity,runner,hostDecisionProvider:{timeoutMs:mode==='timeout'?10:1000,
42
- decide:async(got,signal)=>{
43
- decisions++;assert.deepEqual(got,binding);assert.equal(signal.aborted,false);started();
44
- if(mode==='cancel'||mode==='timeout')return new Promise(resolve=>{release=resolve;});
45
- if(mode==='drift')current={...current,packageDigest:'b'.repeat(64)};
46
- if(mode==='awaiting')return null;
47
- return mode==='denied'?{status:'denied',code:'permission_denied'}:{status:'approved'};
48
- }}});
49
- const running=entry.handle(operation('decision'));await ready;
50
- if(mode==='cancel')await entry.handle(operation('cancel'));
51
- const result=await running;
52
- if(release){release({status:'approved'});await Promise.resolve();}
53
- assert.equal(effects,mode==='approved'?1:0);
54
- const expected={approved:null,awaiting:'decision_required',denied:'permission_denied',
55
- timeout:'review_decision_timeout',cancel:'cancelled',drift:'stale_decision'};
56
- assert.equal(result.code,expected[mode]);
57
- current={state:'unknown',code:'reconciliation_required',identity,packageDigest};
58
- const historical=await entry.handle(operation('decision'));
59
- assert.equal(historical.state,'unknown');assert.equal(decisions,1,'unknown review must not ask for another decision');
60
- });
@@ -35,11 +35,11 @@ async function fixture(fn,{pending=false}={}){
35
35
  const stateFile=path.join(specsDir,'.reviews','.execution',identity.runId,'state.json');
36
36
  const definition={version:1,specsDir,codeProject,feature,identity,scope:['README.md'],requirements:[]};
37
37
  const execution=(enabled)=>({configuration:{kind:'synthetic-host-v1',...(enabled===undefined?{}:{workflow:{knowledgeCloseout:enabled}})},timeoutMs:1000,
38
- excludedContexts:['main'],hostDecision:null,check:()=>[],applicableAgentFiles:[],documentationProvider:{timeoutMs:1000,inspect:async()=>{throw Error('unexpected inspection');}},
38
+ excludedContexts:['main'],check:()=>[],applicableAgentFiles:[],documentationProvider:{timeoutMs:1000,inspect:async()=>{throw Error('unexpected inspection');}},
39
39
  developer:{provider:'codex',requestedModel:'fixture',contextId:'author',run:async()=>{throw Error('unexpected dispatch');}},
40
40
  reviewers:[{id:'reviewer',adapterId:'codex-review-adapter',provider:'codex',requestedModel:'fixture',allowed:true,available:true,
41
41
  contexts:['review-1','review-2'],run:async()=>{throw Error('unexpected review');}}],
42
- reviewInvocation:{developerThreadId:'author',excludedThreadIds:['main'],hostContextId:'main',authorize:async()=>{throw Error('unexpected grant');}}});
42
+ reviewInvocation:{developerThreadId:'author',excludedThreadIds:['main'],hostContextId:'main'}});
43
43
  try{return await fn({root,specsDir,codeProject,feature,definition,entry,seedQa,response,stateFile,execution,effects:()=>effects});}
44
44
  finally{fs.rmSync(root,{recursive:true,force:true});}
45
45
  }
@@ -124,7 +124,7 @@ test('real legacy init without closeout resumes byte-identically; explicit activ
124
124
  excludedContexts:execution.excludedContexts,developer:execution.developer,reviewers:execution.reviewers,reviewInvocation:execution.reviewInvocation,
125
125
  check:()=>[],timeoutMs:1000,taskCompletion:{reviewsDir:path.join(f.specsDir,'.reviews'),handoffs:[1,2].map(n=>path.join(f.specsDir,'.reviews',`fixture-T-001-a${n}-handoff.json`))},
126
126
  taskLearning:{feature:f.feature,hostHandoff:true},persistence:{store,mode:'create',version:3}},entry:{specsDir:f.specsDir,codeProject:f.codeProject,
127
- feature:f.feature,identity,hostDecision:null,applicableAgentFiles:[],documentationProvider:execution.documentationProvider}});}finally{store.close();}
127
+ feature:f.feature,identity,applicableAgentFiles:[],documentationProvider:execution.documentationProvider}});}finally{store.close();}
128
128
  const before=fs.readFileSync(f.stateFile);assert(!Object.hasOwn(JSON.parse(before).records[0].payload.config,'knowledgeCloseout'));
129
129
  const resumed=await openControlRun(f.definition,'resume',execution);resumed.close();assert.deepEqual(fs.readFileSync(f.stateFile),before);
130
130
  await assert.rejects(openControlRun(f.definition,'resume',f.execution(true)),{code:'closeout_policy_changed'});
@@ -157,17 +157,17 @@ test('bark and pushplus requests: fields, numeric code check, rejected responses
157
157
  assert.deepEqual(JSON.parse(server.seen.at(-1).body),{token:PUSH_SECRET,title:'t'.repeat(100),content:'正文',template:'txt',channel:'wechat'});
158
158
  });
159
159
 
160
- test('network failure, deadline (also while waiting on stdin) and unexpected errors exit 3 without details',async t=>{
160
+ test('network failure exits 3, the deadline (also while waiting on stdin) 5 and unexpected errors 6, without details',async t=>{
161
161
  const s=sandbox(t);
162
162
  s.write('notify-channel.conf','CHANNEL=bark\n');s.write('bark.env',`BARK_KEY=${BARK_SECRET}\n`);
163
163
  const server=await fakeServer(t,()=>{});// never answers
164
164
  let err=sink();
165
165
  let code=await runSender({env:s.env,home:s.home,stdin:endedStdin(),stdout:sink().stream,stderr:err.stream,request:server.request,deadlineMs:300});
166
- assert.equal(code,SEND_EXIT.network);assert.equal(err.text(),'cm-notify: 整次调用超过 1 秒,已放弃\n');
166
+ assert.equal(code,SEND_EXIT.deadline);assert.equal(err.text(),'cm-notify: 整次调用超过 1 秒,已放弃\n');
167
167
  err=sink();const silent=new PassThrough();t.after(()=>silent.destroy());
168
168
  const started=process.hrtime.bigint();
169
169
  code=await runSender({env:s.env,home:s.home,stdin:silent,stdout:sink().stream,stderr:err.stream,request:()=>{throw new Error('must not send');},deadlineMs:200});
170
- assert.equal(code,SEND_EXIT.network);assert.match(err.text(),/整次调用超过/);
170
+ assert.equal(code,SEND_EXIT.deadline);assert.match(err.text(),/整次调用超过/);
171
171
  assert(Number(process.hrtime.bigint()-started)/1e6<2000);
172
172
  // A line without EOF is enough: the sender does not wait for the stream to end.
173
173
  const open=new PassThrough();open.write('{"title":"x"}\n');t.after(()=>open.destroy());
@@ -175,11 +175,11 @@ test('network failure, deadline (also while waiting on stdin) and unexpected err
175
175
  assert.equal(code,0);
176
176
  err=sink();
177
177
  code=await runSender({env:s.env,home:s.home,stdin:endedStdin(),stdout:sink().stream,stderr:err.stream,request:()=>{throw new Error(`boom ${BARK_SECRET}`);}});
178
- assert.equal(code,SEND_EXIT.network);assert.equal(err.text(),'cm-notify: 意外错误(详情已隐藏,避免带出密钥)\n');
178
+ assert.equal(code,SEND_EXIT.unexpected);assert.equal(err.text(),'cm-notify: 意外错误(详情已隐藏,避免带出密钥)\n');
179
179
  err=sink();
180
180
  code=await runSender({env:s.env,home:s.home,stdin:endedStdin(),stdout:sink().stream,stderr:err.stream,
181
181
  request:(options,callback)=>http.request({...options,hostname:'127.0.0.1',port:1},callback)});
182
- assert.equal(code,SEND_EXIT.network);assert.equal(err.text(),'cm-notify: bark 请求失败或超时\n');
182
+ assert.equal(code,SEND_EXIT.network);assert.equal(err.text(),'cm-notify: bark 网络请求失败\n');
183
183
  });
184
184
 
185
185
  const [major,minor]=process.versions.node.split('.').map(Number);
@@ -338,7 +338,7 @@ test('test goes through the configured command, bypasses dedupe/limits, and repo
338
338
  assert.equal(s.log(),'','dry-run runs nothing');
339
339
  result=s.cli(['test']);// real sender, loopback port 1: refused connection, no external network
340
340
  assert.equal(result.status,SEND_EXIT.network,result.stderr);
341
- assert.equal(result.stdout,'渠道 bark:退出码 3,网络失败或超时。\n');
341
+ assert.equal(result.stdout,'渠道 bark:退出码 3,网络请求失败。\n');
342
342
  noSecret(result.stdout+result.stderr);noSecret(s.log(),'notify.log');
343
343
  assert.match(s.log(),/test cm-notify key=- test failed exit_3/);
344
344
  // A custom command receives the same contract as the runtime launcher.
@@ -402,12 +402,14 @@ fs.writeFileSync(${JSON.stringify(record)},JSON.stringify({options:process.env.N
402
402
  process.stdout.write('${BARK_SECRET}\\n');process.stderr.write('cm-notify: leaked ${BARK_SECRET}\\n');process.exit(${code});});`;
403
403
  // The installed managed sender itself is replaced: same command shape, output still never shown.
404
404
  const preload=path.join(s.root,'preload.cjs');fs.writeFileSync(preload,'// harmless for the manager itself\n');
405
- const words={0:'已被推送服务接受(不代表已送达)',2:'配置或密钥问题',3:'网络失败或超时',4:'服务端拒绝',7:'未知'};
405
+ // The replaced sender is no longer this plugin's copy: original words, 5/6 unknown, and an update hint.
406
+ const words={0:'已被推送服务接受(不代表已送达)',2:'配置或密钥问题',3:'网络失败或超时',4:'服务端拒绝',5:'未知',6:'未知',7:'未知'};
407
+ const staleHint='托管发送器与当前插件版本不同,退出码按旧含义解释;重新执行 /cm:notify bark 更新。';
406
408
  for(const [code,word] of Object.entries(words)){
407
409
  fs.writeFileSync(managedSenderPath(s.home),fake(code),{mode:0o600});
408
410
  const result=s.cli(['test'],{NODE_OPTIONS:`--require=${preload}`});
409
411
  assert.equal(result.status,Number(code),result.stderr);
410
- assert.equal(result.stdout,`渠道 bark:退出码 ${code},${word}。\n`);noSecret(result.stdout+result.stderr);
412
+ assert.equal(result.stdout,`渠道 bark:退出码 ${code},${word}。${staleHint}\n`);noSecret(result.stdout+result.stderr);
411
413
  assert.deepEqual(JSON.parse(fs.readFileSync(record,'utf8')),{options:null,execArgv:[]},'NODE_OPTIONS is not passed to the sender');
412
414
  }
413
415
  // Dry-run never runs the installed command.
@@ -423,7 +425,24 @@ process.stdout.write('${BARK_SECRET}\\n');process.stderr.write('cm-notify: leake
423
425
  s.write('notify.json',JSON.stringify({version:1,command:[process.execPath,managedSenderPath(s.home)]}));
424
426
  const result=await sendTest(s.home,{env:s.env,beforeSpawn:()=>s.write('notify.json',JSON.stringify({version:1,command:['/bin/sh','-c','exit 9']}))});
425
427
  assert.equal(result.exit,0);assert.deepEqual(JSON.parse(fs.readFileSync(record,'utf8')).execArgv,[]);
426
- assert.equal(formatTest(result),'渠道 bark:退出码 0,已被推送服务接受(不代表已送达)。');
428
+ assert.equal(result.senderCurrent,false);
429
+ assert.equal(formatTest(result),`渠道 bark:退出码 0,已被推送服务接受(不代表已送达)。${staleHint}`);
430
+ });
431
+
432
+ test('test explains 3/5/6 with the new words only for the current managed sender',()=>{
433
+ const current={kind:'managed',channel:'bark',dry:false,reason:null,senderCurrent:true};
434
+ assert.equal(formatTest({...current,exit:3}),'渠道 bark:退出码 3,网络请求失败。');
435
+ assert.equal(formatTest({...current,exit:5}),'渠道 bark:退出码 5,超过 12 秒期限(可能已送达)。');
436
+ assert.equal(formatTest({...current,exit:6}),'渠道 bark:退出码 6,意外错误。');
437
+ assert.equal(formatTest({...current,exit:7}),'渠道 bark:退出码 7,未知。');
438
+ // A custom or legacy command keeps the original meaning of its exit codes.
439
+ for(const [kind,who] of [['custom','自定义命令'],['legacy','渠道 bark']])for(const [exit,word] of [[3,'网络失败或超时'],[5,'未知'],[6,'未知']])
440
+ assert.equal(formatTest({kind,channel:'bark',dry:false,reason:null,exit}),`${who}:退出码 ${exit},${word}。`);
441
+ // An older managed sender: original words plus the update hint, also when the command did not end normally.
442
+ const stale={...current,senderCurrent:false},hint='托管发送器与当前插件版本不同,退出码按旧含义解释;重新执行 /cm:notify bark 更新。';
443
+ assert.equal(formatTest({...stale,exit:3}),`渠道 bark:退出码 3,网络失败或超时。${hint}`);
444
+ assert.equal(formatTest({...stale,exit:5}),`渠道 bark:退出码 5,未知。${hint}`);
445
+ assert.equal(formatTest({...stale,exit:null,reason:'timeout'}),`渠道 bark:命令没有正常结束(timeout),未知。${hint}`);
427
446
  });
428
447
 
429
448
  // Simulated slow reads: file-system calls of the sender replaced through its module API.
@@ -433,7 +452,7 @@ const delayedOps=({lstatMs=0,block=false,before}={})=>({open:fsp.open,lstat:asyn
433
452
  else if(lstatMs)await new Promise(resolve=>setTimeout(resolve,lstatMs));
434
453
  return fsp.lstat(file,options);}});
435
454
 
436
- test('slow reads (blocking or async) end with 3 on time; dry-run, --check and sends never return 0 after the budget',async t=>{
455
+ test('slow reads (blocking or async) end with 5 on time; dry-run, --check and sends never return 0 after the budget',async t=>{
437
456
  const s=sandbox(t);
438
457
  s.write('notify-channel.conf','CHANNEL=bark\n');s.write('bark.env',`BARK_KEY=${BARK_SECRET}\n`);
439
458
  let sent=0;const request=()=>{sent++;throw new Error('must not send');};
@@ -442,7 +461,7 @@ test('slow reads (blocking or async) end with 3 on time; dry-run, --check and se
442
461
  const err=sink(),out=sink();const begin=performance.now();
443
462
  const code=await runSender({argv,env:{...s.env,...env},home:s.home,stdin:endedStdin(),stdout:out.stream,stderr:err.stream,fileOps,request,deadlineMs});
444
463
  const took=performance.now()-begin,label=`${kind} ${argv} ${JSON.stringify(env)} ${deadlineMs}`;
445
- assert.equal(code,SEND_EXIT.network,label);assert.equal(out.text(),'',label);
464
+ assert.equal(code,SEND_EXIT.deadline,label);assert.equal(out.text(),'',label);
446
465
  assert.match(err.text(),/^cm-notify: 整次调用超过 1 秒,已放弃/,label);
447
466
  if(kind==='slowAsync')assert(took<deadlineMs+150,`${label} returned on time (${Math.round(took)} ms)`);
448
467
  }
@@ -454,16 +473,16 @@ test('slow reads (blocking or async) end with 3 on time; dry-run, --check and se
454
473
  const lastRead=argv.length||env.CM_NOTIFY_DRY_RUN?(argv.length?2:1):99;
455
474
  const code=await runSender({argv,env:{...s.env,...env},home:s.home,stdin:endedStdin(),stdout:out.stream,stderr:err.stream,deadlineMs:5000,
456
475
  clock:()=>now,request:(...args)=>{now=6000;return req(...args);},fileOps:delayedOps({before:()=>{if(++reads===lastRead)now=6000;}})});
457
- assert.equal(code,SEND_EXIT.network,`${argv} ${JSON.stringify(env)}`);assert.equal(out.text(),'');assert.match(err.text(),/整次调用超过 5 秒,已放弃/);
476
+ assert.equal(code,SEND_EXIT.deadline,`${argv} ${JSON.stringify(env)}`);assert.equal(out.text(),'');assert.match(err.text(),/整次调用超过 5 秒,已放弃/);
458
477
  }
459
- assert.equal(server0.seen.length,1,'the late send was accepted but is still reported as 3');
478
+ assert.equal(server0.seen.length,1,'the late send was accepted but is still reported as 5');
460
479
  // With enough budget the same slow read still sends.
461
480
  const server=await fakeServer(t,(req,res)=>json(res,200,{code:200}));
462
481
  const code=await runSender({env:s.env,home:s.home,stdin:endedStdin(),stdout:sink().stream,stderr:sink().stream,fileOps:kinds.blocking,request:server.request,deadlineMs:2000});
463
482
  assert.equal(code,0);assert.equal(server.seen.length,1);
464
483
  });
465
484
 
466
- test('the process entry arms a hard timer: a read that never settles still exits 3 at the deadline',async t=>{
485
+ test('the process entry arms a hard timer: a read that never settles still exits 5 at the deadline',async t=>{
467
486
  const s=sandbox(t);
468
487
  s.write('notify-channel.conf','CHANNEL=bark\n');s.write('bark.env',`BARK_KEY=${BARK_SECRET}\n`);
469
488
  const sender=new URL('../runtime/js/notify-send.mjs',import.meta.url).href;
@@ -475,12 +494,29 @@ runCli({argv:[],deadlineMs:300,softDeadlineMs:1e9,senderOptions:{fileOps:{open:f
475
494
  const begin=performance.now();
476
495
  const result=spawnSync(process.execPath,['--input-type=module','-e',script],{input:'{}\n',encoding:'utf8',env:{...s.env,...extra},timeout:10000});
477
496
  const took=performance.now()-begin;
478
- assert.equal(result.status,SEND_EXIT.network,result.stderr);assert.equal(result.stdout,'');
497
+ assert.equal(result.status,SEND_EXIT.deadline,result.stderr);assert.equal(result.stdout,'');
479
498
  assert.equal(result.stderr,'cm-notify: 整次调用超过 1 秒,已放弃\n');
480
499
  assert(took<3000,`exited on time (${Math.round(took)} ms)`);
481
500
  }
482
501
  });
483
502
 
503
+ test('process-level errors (uncaught exception, unhandled rejection) exit 6 with only the fixed line',t=>{
504
+ const s=sandbox(t);
505
+ s.write('notify-channel.conf','CHANNEL=bark\n');s.write('bark.env',`BARK_KEY=${BARK_SECRET}\n`);
506
+ const sender=new URL('../runtime/js/notify-send.mjs',import.meta.url).href;
507
+ const faults={uncaught:`setImmediate(()=>{throw new Error('boom ${BARK_SECRET}');});`,
508
+ rejection:`Promise.reject(new Error('boom ${BARK_SECRET}'));`};
509
+ for(const [kind,fault] of Object.entries(faults)){
510
+ // The read never settles and the deadline is far away, so only the process-level handler can end it.
511
+ const script=`import {runCli} from ${JSON.stringify(sender)};
512
+ import fsp from 'node:fs/promises';
513
+ runCli({argv:[],deadlineMs:8000,softDeadlineMs:1e9,senderOptions:{fileOps:{open:fsp.open,lstat:()=>{${fault}return new Promise(()=>{});}}}});`;
514
+ const result=spawnSync(process.execPath,['--input-type=module','-e',script],{input:'{}\n',encoding:'utf8',env:s.env,timeout:10000});
515
+ assert.equal(result.status,SEND_EXIT.unexpected,`${kind} ${result.stderr}`);assert.equal(result.stdout,'',kind);
516
+ assert.equal(result.stderr,'cm-notify: 意外错误(详情已隐藏,避免带出密钥)\n',kind);noSecret(result.stderr);
517
+ }
518
+ });
519
+
484
520
  test('off restores the previous notify.off.json when moving notify.json fails, and names the backup if that fails too',t=>{
485
521
  const s=sandbox(t);
486
522
  const on=JSON.stringify({version:1,command:['/bin/true'],waitMinutes:5}),old=JSON.stringify({version:1,command:['/bin/false'],note:'old off'});
@@ -629,12 +665,12 @@ test('time spent before the sender work counts toward the same 12 s budget',asyn
629
665
  // The start recorded at entry is honoured: time already spent leaves no budget for an exit 0.
630
666
  for(const argv of [['--check'],[]]){
631
667
  const result=run(`import {performance} from 'node:perf_hooks';runCli({argv:${JSON.stringify(argv)},startedAt:performance.now()-12050});`,{CM_NOTIFY_DRY_RUN:'1'});
632
- assert.equal(result.status,SEND_EXIT.network,`${argv} ${result.stderr}`);assert.equal(result.stdout,'');assert(result.took<5000);
668
+ assert.equal(result.status,SEND_EXIT.deadline,`${argv} ${result.stderr}`);assert.equal(result.stdout,'');assert(result.took<5000);
633
669
  }
634
- // 250 ms already spent, the slow read needs more than the 50 ms left: 3, never 0.
670
+ // 250 ms already spent, the slow read needs more than the 50 ms left: 5, never 0.
635
671
  const result=run(`import {performance} from 'node:perf_hooks';import fsp from 'node:fs/promises';
636
672
  runCli({argv:['--check'],deadlineMs:300,startedAt:performance.now()-250,senderOptions:{fileOps:{open:fsp.open,lstat:async(f,o)=>{await new Promise(r=>setTimeout(r,200));return fsp.lstat(f,o);}}}});`);
637
- assert.equal(result.status,SEND_EXIT.network,result.stderr);assert.equal(result.stdout,'');assert(result.took<3000);
673
+ assert.equal(result.status,SEND_EXIT.deadline,result.stderr);assert.equal(result.stdout,'');assert(result.took<3000);
638
674
  });
639
675
 
640
676
  test('entry is decided by import.meta.main alone: imported does nothing, unsupported Node exits 3, Windows is refused first',()=>{