@aibyzero/cm-workflow 0.11.0 → 0.13.2

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 (130) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +3 -0
  3. package/CHANGELOG.md +64 -3
  4. package/README.md +45 -3
  5. package/VERSION +1 -1
  6. package/compat/claude-commands/cm-runtime.md +3 -0
  7. package/compat/claude-commands/cm-security.md +3 -0
  8. package/docs/architecture.md +22 -0
  9. package/docs/installation.md +56 -2
  10. package/docs/js-workflow-control.md +63 -6
  11. package/docs/runtime-failover.md +97 -0
  12. package/docs/user-guide.md +60 -3
  13. package/install-codex.sh +5 -0
  14. package/install.ps1 +10 -2
  15. package/install.sh +5 -0
  16. package/package.json +3 -1
  17. package/runtime/js/cm-ai/claude-developer-proposal.schema.json +151 -0
  18. package/runtime/js/cm-ai/claude-review-stream.mjs +69 -8
  19. package/runtime/js/cm-ai/claude-tool-preview.mjs +6 -4
  20. package/runtime/js/cm-ai/cm-ai-admission.mjs +38 -16
  21. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +44 -17
  22. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +105 -12
  23. package/runtime/js/cm-ai/codex-config.mjs +6 -0
  24. package/runtime/js/cm-ai/codex-review-adapter.mjs +6 -2
  25. package/runtime/js/cm-ai/developer-adapter.mjs +41 -16
  26. package/runtime/js/cm-ai/durable-runner-state.mjs +72 -15
  27. package/runtime/js/cm-ai/effect-contract.mjs +10 -1
  28. package/runtime/js/cm-ai/fix-code-association.mjs +4 -1
  29. package/runtime/js/cm-ai/host-conversation-execution.mjs +112 -27
  30. package/runtime/js/cm-ai/host-documentation.mjs +4 -2
  31. package/runtime/js/cm-ai/host-qa-executor.mjs +17 -4
  32. package/runtime/js/cm-ai/host-qa-policy.mjs +6 -3
  33. package/runtime/js/cm-ai/host-role-routing.mjs +9 -5
  34. package/runtime/js/cm-ai/host-tool-bridge.mjs +10 -7
  35. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +9 -4
  36. package/runtime/js/cm-ai/host.mjs +1 -1
  37. package/runtime/js/cm-ai/provider-review-observation.mjs +8 -4
  38. package/runtime/js/cm-ai/qa-attachment.mjs +30 -0
  39. package/runtime/js/cm-ai/review-package.mjs +76 -18
  40. package/runtime/js/cm-ai/review-runner.mjs +15 -3
  41. package/runtime/js/cm-ai/runtime-failover.mjs +75 -0
  42. package/runtime/js/cm-ai/specification-material.mjs +98 -0
  43. package/runtime/js/cm-ai/task-runner.mjs +57 -20
  44. package/runtime/js/cm-ai/worker-claude-developer.mjs +174 -0
  45. package/runtime/js/cm-ai/worker-claude.mjs +18 -5
  46. package/runtime/js/cm-ai/worker-codex-developer.mjs +15 -4
  47. package/runtime/js/cm-ai/worker-codex.mjs +8 -12
  48. package/runtime/js/cm-init/draft-generation.mjs +24 -4
  49. package/runtime/js/cm-init/draft-inspection.mjs +29 -1
  50. package/runtime/js/cm-prd/session.mjs +19 -2
  51. package/runtime/js/cm-prd/summary.mjs +46 -20
  52. package/runtime/js/cm-security/scan.mjs +263 -0
  53. package/runtime/js/cm-test/branch-impact.mjs +8 -2
  54. package/runtime/review.md +11 -1
  55. package/runtime/workflow-config.md +39 -2
  56. package/runtime/workflow-routing.md +6 -1
  57. package/scripts/cm-ai-admission.test.mjs +99 -0
  58. package/scripts/cm-ai-batch-host.test.mjs +4 -1
  59. package/scripts/cm-ai-batch-run.test.mjs +7 -1
  60. package/scripts/cm-ai-bootstrap.test.mjs +2 -1
  61. package/scripts/cm-ai-fix-integration.test.mjs +2 -1
  62. package/scripts/cm-ai-host.mjs +81 -12
  63. package/scripts/cm-ai-host.test.mjs +520 -5
  64. package/scripts/cm-ai-multi-root.test.mjs +9 -3
  65. package/scripts/cm-ai-nested-execution.test.mjs +11 -4
  66. package/scripts/cm-ai-review-timeout.test.mjs +226 -0
  67. package/scripts/cm-ai-run.mjs +40 -13
  68. package/scripts/cm-ai-run.test.mjs +45 -9
  69. package/scripts/cm-check-host.test.mjs +1 -1
  70. package/scripts/cm-check-runtime.sh +56 -1
  71. package/scripts/cm-check-update.mjs +200 -0
  72. package/scripts/cm-check-update.test.mjs +186 -0
  73. package/scripts/cm-claude-developer-worker.test.mjs +236 -0
  74. package/scripts/cm-claude-probe.test.mjs +64 -1
  75. package/scripts/cm-claude-review-stream.test.mjs +236 -1
  76. package/scripts/cm-claude-worker.test.mjs +110 -1
  77. package/scripts/cm-codex-developer-adapter.test.mjs +50 -2
  78. package/scripts/cm-codex-developer-worker.test.mjs +84 -1
  79. package/scripts/cm-codex-review-progress.test.mjs +34 -6
  80. package/scripts/cm-failover.mjs +288 -0
  81. package/scripts/cm-failover.test.mjs +184 -0
  82. package/scripts/cm-host-qa-executor.test.mjs +277 -0
  83. package/scripts/cm-host-tool-bridge.test.mjs +31 -0
  84. package/scripts/cm-init-draft-generation.test.mjs +62 -0
  85. package/scripts/cm-init-draft-inspection.test.mjs +76 -0
  86. package/scripts/cm-init-host.mjs +4 -4
  87. package/scripts/cm-init-host.test.mjs +12 -7
  88. package/scripts/cm-init-session.test.mjs +50 -0
  89. package/scripts/cm-log-event.mjs +34 -5
  90. package/scripts/cm-prd-completion.test.mjs +2 -2
  91. package/scripts/cm-prd-host.mjs +39 -3
  92. package/scripts/cm-prd-host.test.mjs +52 -0
  93. package/scripts/cm-prd-review-gate.mjs +11 -2
  94. package/scripts/cm-prd-review-gate.test.mjs +62 -0
  95. package/scripts/cm-prd-session-recovery.test.mjs +167 -0
  96. package/scripts/cm-prd-summary.test.mjs +147 -0
  97. package/scripts/cm-review-dependency-snapshot.test.mjs +10 -0
  98. package/scripts/cm-review-inventory.test.mjs +189 -0
  99. package/scripts/cm-review-schema.test.mjs +35 -1
  100. package/scripts/cm-review-scope-recovery.test.mjs +63 -0
  101. package/scripts/cm-runtime-edit.mjs +104 -0
  102. package/scripts/cm-runtime-failover.test.mjs +130 -0
  103. package/scripts/cm-runtime-install.mjs +42 -0
  104. package/scripts/cm-runtime.mjs +113 -0
  105. package/scripts/cm-runtime.test.mjs +117 -0
  106. package/scripts/cm-security.mjs +32 -0
  107. package/scripts/cm-security.test.mjs +203 -0
  108. package/scripts/cm-spec-manifest.mjs +24 -21
  109. package/scripts/cm-spec-manifest.test.mjs +19 -0
  110. package/scripts/cm-workflow-config.mjs +113 -5
  111. package/scripts/cm-workflow-config.test.mjs +124 -1
  112. package/scripts/fixtures/prd-review-gate-python-oracle.py +18 -2
  113. package/scripts/test-cm-prd-review-gate.py +30 -0
  114. package/scripts/test-shell-compat.sh +34 -0
  115. package/scripts/validate-public-repo.py +7 -1
  116. package/skills/cm-ai/references/N4-review.md +5 -4
  117. package/skills/cm-ai/references/js-host.md +36 -2
  118. package/skills/cm-check/SKILL.md +49 -8
  119. package/skills/cm-check/references/js-host.md +4 -1
  120. package/skills/cm-init/SKILL.md +4 -0
  121. package/skills/cm-init/references/js-host.md +2 -0
  122. package/skills/cm-init/references/runtime-declaration.md +26 -0
  123. package/skills/cm-prd/SKILL.md +3 -3
  124. package/skills/cm-prd/references/js-change-recovery.md +24 -3
  125. package/skills/cm-prd/references/summary-card.md +7 -0
  126. package/skills/cm-runtime/SKILL.md +32 -0
  127. package/skills/cm-security/SKILL.md +55 -0
  128. package/skills/cm-security/references/scan-contract.md +43 -0
  129. package/templates/auto-update/cm-update.sh +1 -1
  130. package/templates/cm-workflow.yml +16 -0
@@ -0,0 +1,236 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import {spawn} from 'node:child_process';
7
+ import {claudeDeveloperWorker,claudeDeveloperArgs,validateClaudeProposal} from '../runtime/js/cm-ai/worker-claude-developer.mjs';
8
+ import {createProjectExecution} from '../runtime/js/cm-ai/host-project-execution.mjs';
9
+ import {buildClaudeDeveloperPrompt} from '../runtime/js/cm-ai/claude-developer-adapter.mjs';
10
+ import {protectedTextInstructions} from '../runtime/js/cm-ai/host-conversation-execution.mjs';
11
+ import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
12
+
13
+ const identity={repositoryId:'proposal-fixture',runId:'proposal-run',taskId:'T-001',attempt:1};
14
+ const proposal={status:'succeeded',value:{outcome:'implemented'},edits:[{path:'target.txt',beforeSha256:null,content:'safe text\n'}]};
15
+ function prompt(){
16
+ const body={version:1,invocationId:'dev-1',identity,role:'developer',provider:'claude',requestedModel:'fixture',
17
+ contextId:'author',payload:{scope:['target.txt'],requirements:[],priorReview:null}};
18
+ return buildClaudeDeveloperPrompt({...body,requestDigest:digest(body)})+protectedTextInstructions;
19
+ }
20
+ function fixture(t){
21
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-claude-development-')));
22
+ t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
23
+ return root;
24
+ }
25
+ function fakeWorker(cwd,{value=proposal,mode='normal',timeoutMs=3000,noticeEvents=[],noticeAt=1,onNotice,
26
+ resultFields={},toolName='Read',toolResultId='read-1',
27
+ assistantContent=[{type:'text',text:'proposal'}]}={}){
28
+ const source=`let input='';process.stdin.on('data',s=>input+=s);process.stdin.on('end',()=>{
29
+ if(!input.includes('Return {status,value,edits}'))process.exit(9);
30
+ if(${JSON.stringify(mode)}==='timeout'){setInterval(()=>{},1000);return;}
31
+ const session_id='synthetic-claude-developer';
32
+ const value=${JSON.stringify(value)};
33
+ const events=[{type:'system',subtype:'init',session_id}];
34
+ if(${JSON.stringify(mode)}==='read')events.push(
35
+ {type:'assistant',session_id,parent_tool_use_id:null,message:{role:'assistant',content:[{type:'tool_use',id:'read-1',name:${JSON.stringify(toolName)},input:{file_path:'target.txt'}}]}},
36
+ {type:'user',session_id,message:{role:'user',content:[{type:'tool_result',tool_use_id:${JSON.stringify(toolResultId)},content:'fixture text'}]}});
37
+ events.push({type:'assistant',session_id,parent_tool_use_id:null,message:{role:'assistant',content:
38
+ ${JSON.stringify(mode)}==='write'?[{type:'tool_use',id:'bad',name:'Write',input:{}}]:${JSON.stringify(assistantContent)}}},
39
+ {type:'result',session_id,subtype:${JSON.stringify(mode)}==='failed'?'error_during_execution':'success',
40
+ is_error:${JSON.stringify(mode)}==='failed',num_turns:1,result:JSON.stringify(value),...${JSON.stringify(resultFields)}});
41
+ events.splice(${JSON.stringify(noticeAt)},0,...${JSON.stringify(noticeEvents)});
42
+ for(const event of events)process.stdout.write(JSON.stringify(event)+'\\n');
43
+ });`;
44
+ return claudeDeveloperWorker({cwd,model:'fixture',timeoutMs,onNotice,spawnProcess:(cli,args,options)=>{
45
+ assert.equal(cli,'claude');assert.equal(options.shell,false);assert.equal(options.detached,true);
46
+ assert.deepEqual(args,claudeDeveloperArgs('fixture'));
47
+ assert.equal(args[args.indexOf('--tools')+1],'Read,Grep,Glob');
48
+ assert.equal(args[args.indexOf('--allowedTools')+1],'Read,Grep,Glob');
49
+ const index=args.indexOf('--json-schema');assert.ok(index>0);assert.equal(args.lastIndexOf('--json-schema'),index);
50
+ const schema=JSON.parse(args[index+1]);assert.equal(Object.hasOwn(schema,'$schema'),false);assert.equal(Object.hasOwn(schema,'$id'),false);
51
+ assert.deepEqual(schema.properties.status.enum,['succeeded','failed']);
52
+ assert.equal(args[args.indexOf('--permission-mode')+1],'dontAsk');
53
+ for(const key of ['NODE_OPTIONS','ANTHROPIC_BASE_URL','HTTP_PROXY','CLAUDE_CODE_USE_BEDROCK'])assert.equal(options.env[key],undefined);
54
+ return spawn(process.execPath,['-e',source],options);
55
+ }});
56
+ }
57
+ const rateLimit=(overrides={})=>({type:'rate_limit_event',session_id:'synthetic-claude-developer',
58
+ rate_limit_info:{status:'allowed',rateLimitType:'five_hour',resetsAt:123,active:true,reason:null,
59
+ nested:{raw:'private'},list:['private']},...overrides});
60
+ test('developer forwards scalar notices while preserving proposals and read-tool state',async t=>{
61
+ const root=fixture(t),events=[],control={signal:new AbortController().signal,onEvent:e=>events.push(e)};
62
+ const baseline=await fakeWorker(root)({prompt:prompt()},control);
63
+ for(const [mode,noticeAt,count] of [['normal',1,1],['normal',2,8],['read',2,8]]){
64
+ const notices=[],noticeEvents=Array.from({length:count},()=>rateLimit());
65
+ const result=await fakeWorker(root,{mode,noticeAt,noticeEvents,onNotice:n=>notices.push(n)})({prompt:prompt()},control);
66
+ assert.deepEqual(result,baseline);
67
+ assert.deepEqual(notices,Array.from({length:count},()=>({kind:'rate_limit',info:{status:'allowed',
68
+ rateLimitType:'five_hour',resetsAt:123,active:true,reason:null}})));
69
+ }
70
+ for(const onNotice of [undefined,()=>{throw Error('notice consumer');}]){
71
+ const result=await fakeWorker(root,{noticeEvents:[rateLimit()],onNotice})({prompt:prompt()},control);
72
+ assert.deepEqual(result,baseline);
73
+ }
74
+ assert.deepEqual(events,[]);assert.deepEqual(fs.readdirSync(root),[]);
75
+ });
76
+ const thinkingTokens=()=>({type:'system',subtype:'thinking_tokens',session_id:'synthetic-claude-developer',estimated_tokens:10});
77
+ const thoughts={type:'assistant',session_id:'synthetic-claude-developer',parent_tool_use_id:null,
78
+ message:{role:'assistant',content:[{type:'thinking',thinking:'private',signature:'sig'},{type:'redacted_thinking',data:'private'}]}};
79
+ test('developer thinking events preserve proposal and read tool pairing with developer schema',async t=>{
80
+ const root=fixture(t),control={signal:new AbortController().signal};
81
+ const baseline=await fakeWorker(root)({prompt:prompt()},control);
82
+ for(const [mode,noticeAt,count] of [['normal',1,2],['normal',2,64],['read',2,2]]){
83
+ const result=await fakeWorker(root,{mode,noticeAt,
84
+ noticeEvents:[rateLimit(),...Array.from({length:count},thinkingTokens),thoughts],
85
+ assistantContent:[...thoughts.message.content,{type:'text',text:'proposal'}]})({prompt:prompt()},control);
86
+ assert.deepEqual(result,baseline);
87
+ }
88
+ const mixed=await fakeWorker(root,{assistantContent:[...thoughts.message.content,
89
+ {type:'tool_use',id:'forbidden',name:'Bash',input:{}}]})({prompt:prompt()},control);
90
+ assert.equal(mixed.code,'unexpected_tool_or_content');
91
+ assert.deepEqual(fs.readdirSync(root),[]);
92
+ });
93
+ test('developer thinking preserves initial, terminal, count and unknown-system rejection',async t=>{
94
+ const root=fixture(t),control={signal:new AbortController().signal};
95
+ for(const [noticeEvents,noticeAt,code] of [
96
+ [Array.from({length:65},thinkingTokens),1,'unexpected_event'],
97
+ [[{...thinkingTokens(),subtype:'unknown'}],1,'unexpected_event'],
98
+ [[{...thinkingTokens(),subtype:'init'}],1,'unexpected_event'],
99
+ [[{...thinkingTokens(),session_id:'other'}],1,'session_mismatch'],
100
+ [[thinkingTokens()],0,'missing_init'],
101
+ [[thinkingTokens()],3,'invalid_event'],
102
+ ]){
103
+ const result=await fakeWorker(root,{noticeEvents,noticeAt})({prompt:prompt()},control);
104
+ assert.deepEqual(result,{status:'unknown',code});
105
+ }
106
+ const result=await fakeWorker(root,{assistantContent:thoughts.message.content})({prompt:prompt()},control);
107
+ assert.deepEqual(result,{status:'unknown',code:'unexpected_result'});
108
+ });
109
+ test('developer rejects mismatched, excessive, unknown and terminal rate limit events',async t=>{
110
+ const root=fixture(t);
111
+ for(const [noticeEvents,noticeAt,code,count] of [
112
+ [[rateLimit({session_id:'other'})],1,'session_mismatch',0],
113
+ [Array.from({length:9},()=>rateLimit()),1,'unexpected_event',8],
114
+ [[rateLimit({type:'foo_event'})],1,'unexpected_event',0],
115
+ [[rateLimit()],0,'missing_init',0],
116
+ [[rateLimit()],3,'invalid_event',0],
117
+ ]){
118
+ const notices=[],result=await fakeWorker(root,{noticeEvents,noticeAt,onNotice:n=>notices.push(n)})
119
+ ({prompt:prompt()},{signal:new AbortController().signal});
120
+ assert.deepEqual(result,{status:'unknown',code});assert.equal(notices.length,count);
121
+ }
122
+ assert.deepEqual(fs.readdirSync(root),[]);
123
+ });
124
+ for(const mode of ['normal','read'])test(`Claude ${mode} process returns a proposal without writing files`,async t=>{
125
+ const root=fixture(t),worker=fakeWorker(root,{mode});
126
+ const result=await worker({prompt:prompt()},{signal:new AbortController().signal});
127
+ assert.equal(result.status,'succeeded');assert.deepEqual(result.edits,proposal.edits);
128
+ assert.equal(result.providerThread,'synthetic-claude-developer');assert.deepEqual(fs.readdirSync(root),[]);
129
+ assert.equal((await worker({prompt:prompt()},{signal:new AbortController().signal})).code,'worker_dispatch_limit');
130
+ });
131
+ for(const [mode,code] of [['timeout','timeout'],['failed','provider_failed'],['write','unexpected_tool_or_content']])test(`Claude ${mode} fails closed`,async t=>{
132
+ const root=fixture(t),result=await fakeWorker(root,{mode,timeoutMs:mode==='timeout'?100:3000})({prompt:prompt()},{signal:new AbortController().signal});
133
+ assert.equal(result.code,code);assert.equal(result.status,mode==='failed'?'unavailable':'unknown');assert.deepEqual(fs.readdirSync(root),[]);
134
+ });
135
+ test('spawn throw and asynchronous missing executable are unavailable; aborted calls never spawn',async t=>{
136
+ const cwd=fixture(t);
137
+ for(const options of [{spawnProcess(){throw Error('fixture');}},{cli:path.join(cwd,'missing')}]){
138
+ const result=await claudeDeveloperWorker({cwd,model:'fixture',...options})({prompt:prompt()},{signal:new AbortController().signal});
139
+ assert.deepEqual(result,{status:'unavailable',code:'spawn_failed'});
140
+ }
141
+ const controller=new AbortController();controller.abort();
142
+ const result=await claudeDeveloperWorker({cwd,model:'fixture',spawnProcess(){assert.fail('spawn');}})({prompt:prompt()},{signal:controller.signal});
143
+ assert.equal(result.status,'cancelled');
144
+ });
145
+ for(const content of ['binary\0data','x'.repeat(65536),'bad\ud800text'])test(`invalid text proposal rejected (${content.length} characters)`,async t=>{
146
+ const cwd=fixture(t),value={...proposal,edits:[{...proposal.edits[0],content}]};
147
+ const result=await fakeWorker(cwd,{value})({prompt:prompt()},{signal:new AbortController().signal});
148
+ assert.notEqual(result.status,'succeeded');assert.deepEqual(fs.readdirSync(cwd),[]);
149
+ });
150
+ test('actual proposal cannot escape scope or use stale expected hashes at host commit',async t=>{
151
+ const root=fixture(t),codeProject=path.join(root,'code'),specsDir=path.join(codeProject,'specs');fs.mkdirSync(specsDir,{recursive:true});
152
+ const project=createProjectExecution({definition:{codeProject,specsDir},protection:{timeoutMs:3000,
153
+ checkCommands:[{id:'syntax',command:[process.execPath,'--version']}]}});
154
+ const scope=['target.txt'],expected=project.expected(scope),signal=new AbortController().signal;
155
+ for(const edit of [{path:'../escape',beforeSha256:null,content:'bad'},{path:'target.txt',beforeSha256:'0'.repeat(64),content:'bad'}]){
156
+ const result=await fakeWorker(codeProject,{value:{...proposal,edits:[edit]}})({prompt:prompt()},{signal});
157
+ assert.equal(result.status,'succeeded');
158
+ await assert.rejects(project.commit({scope,expected,identity,signal,edits:result.edits}),{code:edit.path==='target.txt'?'protected_edit_stale':'out_of_scope'});
159
+ assert(!fs.existsSync(path.join(codeProject,'target.txt')));assert(!fs.existsSync(path.join(root,'escape')));
160
+ }
161
+ });
162
+
163
+ test('developer arguments carry the dedicated schema and exact success/failure prompt',()=>{
164
+ const args=claudeDeveloperArgs('fixture');
165
+ const schema=JSON.parse(args[args.indexOf('--json-schema')+1]);
166
+ assert.deepEqual(schema,JSON.parse(fs.readFileSync(new URL('../runtime/js/cm-ai/claude-developer-proposal.schema.json',import.meta.url),'utf8')));
167
+ assert.deepEqual(schema.required,['status']);assert.equal(schema.additionalProperties,false);
168
+ assert.equal(schema.properties.edits.maxItems,64);
169
+ assert.match(protectedTextInstructions,/status must be exactly "succeeded" on success \(with value and edits\) or "failed" \(with code\)/);
170
+ assert.match(protectedTextInstructions,/structured output schema; never wrap it in markdown fences/);
171
+ });
172
+ test('developer pairs StructuredOutput and prefers its proposal over fenced text',async t=>{
173
+ const root=fixture(t),control={signal:new AbortController().signal};
174
+ for(const toolName of ['Read','Grep','Glob','StructuredOutput']){
175
+ const result=await fakeWorker(root,{mode:'read',toolName,
176
+ resultFields:{structured_output:proposal,result:'```json\n{"status":"ok"}\n```'}})({prompt:prompt()},control);
177
+ assert.deepEqual(result,{...proposal,providerThread:'synthetic-claude-developer'});
178
+ }
179
+ const mismatch=await fakeWorker(root,{mode:'read',toolName:'StructuredOutput',toolResultId:'unknown',
180
+ resultFields:{structured_output:proposal}})({prompt:prompt()},control);
181
+ assert.deepEqual(mismatch,{status:'unknown',code:'unexpected_tool_or_content'});
182
+ const unpaired=await fakeWorker(root,{assistantContent:[{type:'tool_use',id:'schema-1',name:'StructuredOutput',input:proposal}],
183
+ resultFields:{structured_output:proposal}})({prompt:prompt()},control);
184
+ assert.deepEqual(unpaired,{status:'unknown',code:'unexpected_result'});
185
+ for(const toolName of ['Bash','Write','Edit','Task','WebFetch']){
186
+ const result=await fakeWorker(root,{mode:'read',toolName,resultFields:{structured_output:proposal}})({prompt:prompt()},control);
187
+ assert.deepEqual(result,{status:'unknown',code:'unexpected_tool_or_content'});
188
+ }
189
+ assert.deepEqual(fs.readdirSync(root),[]);
190
+ });
191
+ test('developer explicitly classifies malformed fallback JSON and rejects invalid structured output',async t=>{
192
+ const root=fixture(t),control={signal:new AbortController().signal};
193
+ for(const result of ['```json\n'+JSON.stringify(proposal)+'\n```','{broken','']){
194
+ assert.deepEqual(await fakeWorker(root,{resultFields:{result}})({prompt:prompt()},control),
195
+ {status:'unknown',code:'invalid_output_json'});
196
+ }
197
+ for(const value of [{...proposal,status:'ok'},{status:'ok',code:'bad'}]){
198
+ assert.throws(()=>validateClaudeProposal(value),{code:'invalid_result'});
199
+ assert.deepEqual(await fakeWorker(root,{value})({prompt:prompt()},control),{status:'unknown',code:'invalid_result'});
200
+ }
201
+ for(const structured_output of [null,{status:'ok',code:'bad'}]){
202
+ assert.deepEqual(await fakeWorker(root,{resultFields:{structured_output}})({prompt:prompt()},control),
203
+ {status:'unknown',code:'invalid_result'});
204
+ }
205
+ const failed={status:'failed',code:'implementation_blocked'};
206
+ assert.deepEqual(await fakeWorker(root,{resultFields:{structured_output:failed}})({prompt:prompt()},control),
207
+ {...failed,providerThread:'synthetic-claude-developer'});
208
+ });
209
+ test('proposal validation preserves schema fields and strict success/failure branches',()=>{
210
+ const candidate={classification:'structured',trigger:'retry',action:'check',evidence:['target.txt']};
211
+ const learning={...proposal,value:{outcome:'implemented',application:{status:'applied',note:'checked'},
212
+ retrospective:{status:'lesson_candidate',candidates:[candidate],reason:null}}};
213
+ for(const valid of [proposal,{status:'failed',code:'blocked'},learning,
214
+ {...proposal,value:{outcome:'blocked'}},
215
+ {...proposal,value:{outcome:'implemented',application:{status:'no_relevant_lesson',note:null},
216
+ retrospective:{status:'no_new_lesson',candidates:[],reason:null}}},
217
+ {...learning,value:{...learning.value,retrospective:{status:'writeback_pending',candidates:[{...candidate,classification:'memory_only'}],reason:'pending'}}},
218
+ {...proposal,edits:Array.from({length:64},()=>({...proposal.edits[0],beforeSha256:'a'.repeat(64),content:null}))}]){
219
+ assert.deepEqual(validateClaudeProposal(valid),valid);
220
+ }
221
+ for(const invalid of [null,{},[],{status:'failed'}, {status:'failed',code:''},{status:'failed',code:1},
222
+ {status:'failed',code:'blocked',edits:[]},{status:'succeeded',value:proposal.value},
223
+ {...proposal,code:'extra'},{...proposal,value:{outcome:'ok'}},{...proposal,value:{outcome:'implemented',extra:true}},
224
+ {...proposal,value:{outcome:'implemented',application:{status:'unknown',note:null}}},
225
+ {...proposal,value:{outcome:'implemented',application:{status:'applied',note:42}}},
226
+ ...[{status:'unknown',candidates:[],reason:null},{status:'no_new_lesson',candidates:[],reason:1},
227
+ {status:'lesson_candidate',candidates:Array(4).fill(candidate),reason:null},
228
+ ...[{...candidate,classification:'other'},{...candidate,evidence:[42]},{...candidate,trigger:42},{...candidate,extra:true}]
229
+ .map(c=>({status:'lesson_candidate',candidates:[c],reason:null}))]
230
+ .map(retrospective=>({...proposal,value:{outcome:'implemented',retrospective}})),
231
+ {...proposal,edits:Array(65).fill(proposal.edits[0])},
232
+ ...[{path:''},{beforeSha256:'A'.repeat(64)},{beforeSha256:'a'.repeat(63)},{beforeSha256:1},{content:1},{extra:true}]
233
+ .map(edit=>({...proposal,edits:[{...proposal.edits[0],...edit}]}))]){
234
+ assert.throws(()=>validateClaudeProposal(invalid),undefined,JSON.stringify(invalid));
235
+ }
236
+ });
@@ -8,7 +8,69 @@ import {spawn} from 'node:child_process';
8
8
  import {fileURLToPath} from 'node:url';
9
9
  import {previewClaudeTools,claudeProbeSandbox} from '../runtime/js/cm-ai/claude-tool-preview.mjs';
10
10
 
11
- test('diagnostic stops the process after exactly one tool-free local request',
11
+ test('probe accepts only empty tools or one internal StructuredOutput tool',
12
+ {skip:process.platform!=='darwin'},async()=>{
13
+ for(const [tools,passed] of [[[],true],[[{name:'StructuredOutput'}],true],[[{name:'Bash'}],false],
14
+ [[{name:'StructuredOutput'},{name:'Bash'}],false],[[{name:'StructuredOutput'},{name:'StructuredOutput'}],false],
15
+ [[null],false],['StructuredOutput',false]]){
16
+ const source=`let input='';process.stdin.on('data',s=>input+=s);process.stdin.on('end',async()=>{
17
+ const response=await fetch(process.env.ANTHROPIC_BASE_URL+'/v1/messages',{method:'POST',
18
+ headers:{'x-api-key':'cm-synthetic-local-probe'},
19
+ body:JSON.stringify({model:'fixture',messages:[{role:'user',content:input}],tools:${JSON.stringify(tools)}})});
20
+ await response.text();process.exit(1);
21
+ });`;
22
+ const result=await previewClaudeTools({cwd:process.cwd(),model:'fixture',
23
+ spawnProcess:(command,args,options)=>spawn(command,[...args.slice(0,2),process.execPath,'-e',source],options)});
24
+ assert.equal(result.preflight.passed,passed,JSON.stringify(tools));
25
+ assert.equal(result.preflight.message_requests,1);
26
+ assert.equal(result.preflight.message_requests_expected,'1-2');
27
+ assert.equal(result.preflight.listener_closed,true);
28
+ assert.equal(result.preflight.request_checks[0].tools_allowed,passed);
29
+ assert.equal('tools_empty' in result.preflight.request_checks[0],false);
30
+ }
31
+ });
32
+
33
+ test('probe accepts at most two compliant requests and validates every request',
34
+ {skip:process.platform!=='darwin'},async t=>{
35
+ const empty={model:'fixture',tools:[]};
36
+ const structured={model:'fixture',tools:[{name:'StructuredOutput'}]};
37
+ const cases=[
38
+ ['two empty tool lists',[empty,empty],true],
39
+ ['two StructuredOutput tool lists',[structured,structured],true],
40
+ ['empty and StructuredOutput tool lists',[empty,structured],true],
41
+ ['second request includes Bash',[structured,{...empty,tools:[{name:'Bash'}]}],false],
42
+ ['second request changes model',[empty,{...empty,model:'different-model'}],false],
43
+ ['three compliant requests',[empty,structured,empty],false],
44
+ ];
45
+ for(const [name,requests,passed] of cases)await t.test(name,async()=>{
46
+ // Keep the fixture alive after SIGTERM so the worker's real cleanup captures
47
+ // the entire sequence deterministically, without delaying the probe's abort.
48
+ const source=`process.on('SIGTERM',()=>{});setInterval(()=>{},1000);
49
+ let input='';process.stdin.on('data',s=>input+=s);process.stdin.on('end',async()=>{
50
+ for(const request of ${JSON.stringify(requests)}){
51
+ const response=await fetch(process.env.ANTHROPIC_BASE_URL+'/v1/messages',{method:'POST',
52
+ headers:{'x-api-key':'cm-synthetic-local-probe'},
53
+ body:JSON.stringify({...request,messages:[{role:'user',content:input}]})});
54
+ await response.text();
55
+ }
56
+ });`;
57
+ const {preflight}=await previewClaudeTools({cwd:process.cwd(),model:'fixture',
58
+ spawnProcess:(command,args,options)=>spawn(command,[...args.slice(0,2),process.execPath,'-e',source],options)});
59
+ assert.equal(preflight.message_requests,requests.length);
60
+ assert.equal(preflight.local_requests,requests.length);
61
+ assert.equal(preflight.message_requests_expected,'1-2');
62
+ assert.equal(preflight.passed,passed);
63
+ assert.equal(preflight.stopped_by_probe,true);
64
+ assert.equal(preflight.process_code,'cancelled');
65
+ assert.equal(preflight.listener_closed,true);
66
+ assert.deepEqual(preflight.request_checks.map(checks=>checks.tools_allowed),
67
+ requests.map(request=>request.tools.every(tool=>tool.name==='StructuredOutput')));
68
+ assert.deepEqual(preflight.request_checks.map(checks=>checks.model_matches),
69
+ requests.map(request=>request.model==='fixture'));
70
+ });
71
+ });
72
+
73
+ test('diagnostic still accepts one tool-free message request from an older CLI',
12
74
  {skip:process.platform!=='darwin'},async()=>{
13
75
  const fixture=fileURLToPath(new URL('./fixtures/claude-review-process.mjs',import.meta.url));
14
76
  const result=await previewClaudeTools({cwd:process.cwd(),model:'fixture-plain-error',
@@ -19,6 +81,7 @@ test('diagnostic stops the process after exactly one tool-free local request',
19
81
  }});
20
82
  assert.equal(result.preflight.passed,true);assert.equal(result.preflight.local_requests,2);
21
83
  assert.equal(result.preflight.message_requests,1);
84
+ assert.equal(result.preflight.message_requests_expected,'1-2');
22
85
  assert.equal(result.preflight.stopped_by_probe,true);assert.equal(result.preflight.listener_closed,true);
23
86
  });
24
87
  test('probe sandbox denies sibling writes and connections to a different loopback port',
@@ -30,7 +30,7 @@ test('wrong session, tools, child agents, errors, repeated or incomplete termina
30
30
  m=>{m[1].message.content=[{type:'tool_use',name:'Bash'}];},
31
31
  m=>{m[1].parent_tool_use_id='child';},
32
32
  m=>{m[2].is_error=true;},
33
- m=>{m[2].num_turns=2;},
33
+ m=>{m[2].num_turns=21;},
34
34
  m=>{m[2].structured_output=null;},
35
35
  m=>{m.push(m[2]);},
36
36
  m=>{m.splice(1,1);},
@@ -43,3 +43,238 @@ test('wrong session, tools, child agents, errors, repeated or incomplete termina
43
43
  assert.throws(()=>stream.finish(), {code:'incomplete_result'});
44
44
  }
45
45
  });
46
+
47
+ const thinkingTokens = () => ({type:'system',subtype:'thinking_tokens',session_id:'fresh-review',estimated_tokens:10});
48
+ const assistant = content => ({...transcript()[1],message:{role:'assistant',content}});
49
+ const tool = (id,name='StructuredOutput') => ({type:'tool_use',id,name,input:{}});
50
+ const toolResult = (id,is_error=false) => ({type:'user',session_id:'fresh-review',
51
+ message:{role:'user',content:[{type:'tool_result',tool_use_id:id,is_error,content:'synthetic result'}]}});
52
+ function decode(messages) {
53
+ const stream=createClaudeReviewStream(()=>{});
54
+ messages.forEach(m=>stream.accept(m));
55
+ return stream.finish();
56
+ }
57
+ test('thinking and redacted thinking preserve stage before and after substantive output',()=>{
58
+ const [init,text,result]=transcript();
59
+ const thoughts=assistant([{type:'thinking',thinking:'private',signature:'sig'},{type:'redacted_thinking',data:'private'}]);
60
+ assert.equal(decode([init,rateLimit(),thinkingTokens(),thinkingTokens(),thoughts,text,result]).status,'succeeded');
61
+ assert.equal(decode([init,...Array.from({length:4096},thinkingTokens),
62
+ assistant([...thoughts.message.content,...text.message.content]),thoughts,result]).status,'succeeded');
63
+ assert.throws(()=>decode([init,thoughts,result]),{code:'unexpected_result'});
64
+ assert.throws(()=>decode([init,...Array.from({length:4097},thinkingTokens),text,result]),{code:'unexpected_event'});
65
+ for(const subtype of ['unknown','init'])assert.throws(()=>decode([init,{...thinkingTokens(),subtype}]),{code:'unexpected_event'});
66
+ assert.throws(()=>decode([init,{...thinkingTokens(),session_id:'other'}]),{code:'session_mismatch'});
67
+ assert.throws(()=>decode([thinkingTokens(),init]),{code:'missing_init'});
68
+ assert.throws(()=>decode([init,text,result,thinkingTokens()]),{code:'unexpected_event'});
69
+ });
70
+ test('paired rejected tool attempts and CLI StructuredOutput permit multiple turns',()=>{
71
+ const [init,text,result]=transcript();
72
+ const calls=[];
73
+ for(let i=0;i<16;i++)calls.push(assistant([tool(`denied-${i}`,i%2?'Bash':'Read')]),toolResult(`denied-${i}`,true));
74
+ const wire=[init,text,...calls,assistant([{type:'thinking',thinking:'private'},tool('output')]),toolResult('output'),
75
+ {...result,num_turns:20,result:'not JSON: structured_output takes precedence'}];
76
+ assert.equal(decode(wire).status,'succeeded');
77
+ assert.equal(decode([init,assistant([tool('bash','Bash')]),toolResult('bash',true),{...result,num_turns:2}]).status,'succeeded');
78
+ assert.throws(()=>decode([init,...calls,assistant([tool('denied-17','Glob')])]),{code:'unexpected_tool_or_content'});
79
+ });
80
+ test('non-StructuredOutput success or ambiguous result fails immediately, including mixed tool batches',()=>{
81
+ for(const name of ['Bash','bash','Read','Grep','Glob','LS','structuredoutput'])for(const flag of [false,undefined,null,'true']){
82
+ const stream=createClaudeReviewStream(()=>{});
83
+ stream.accept(transcript()[0]);stream.accept(assistant([tool('output'),tool('bad',name)]));
84
+ stream.accept(toolResult('output'));
85
+ const result=toolResult('bad',flag);
86
+ if(flag===undefined)delete result.message.content[0].is_error;
87
+ assert.throws(()=>stream.accept(result),{code:'unexpected_tool_or_content'});
88
+ assert.throws(()=>stream.finish(),{code:'incomplete_result'});
89
+ }
90
+ });
91
+ test('tool identities, result contents and unresolved calls fail closed',()=>{
92
+ const [init,,result]=transcript();
93
+ for(const extra of [
94
+ [toolResult('missing',true)],
95
+ [assistant([tool('a')]),toolResult('wrong')],
96
+ [assistant([tool('a')]),toolResult('a'),toolResult('a')],
97
+ [assistant([tool('a'),tool('a','Bash')])],
98
+ [assistant([tool('a')]),toolResult('a'),assistant([tool('a','Bash')])],
99
+ [assistant([{type:'image'}])],
100
+ [assistant([null])],
101
+ [{...toolResult('a'),message:{role:'user',content:[{type:'text',text:'tool succeeded'}]}}],
102
+ [{...toolResult('a'),message:{role:'user',content:[]}}],
103
+ ])assert.throws(()=>decode([init,...extra,result]),{code:'unexpected_tool_or_content'});
104
+ assert.throws(()=>decode([init,assistant([tool('pending')]),result]),{code:'unexpected_result'});
105
+ for(const num_turns of [0,-1,1.5,'2',21])assert.throws(()=>decode([...transcript().slice(0,2),{...result,num_turns}]),{code:'unexpected_result'});
106
+ for(const structured_output of [null,[],true,'{}'])assert.throws(()=>decode([
107
+ ...transcript().slice(0,2),{...result,structured_output,result:'{"verdict":"approved"}'},
108
+ ]),{code:'invalid_output_json'});
109
+ });
110
+
111
+ const rateLimit = (overrides={}) => ({type:'rate_limit_event',session_id:'fresh-review',
112
+ rate_limit_info:{status:'allowed',rateLimitType:'five_hour',resetsAt:123,active:true,reason:null,
113
+ nested:{text:'private provider payload'},list:['private provider payload']},...overrides});
114
+ const expectedNotice = {kind:'rate_limit',info:{status:'allowed',rateLimitType:'five_hour',
115
+ resetsAt:123,active:true,reason:null}};
116
+ test('rate limit notices preserve both output formats, stage and exact observer events',()=>{
117
+ const baseline=[],original=createClaudeReviewStream(e=>baseline.push(e));
118
+ transcript().forEach(m=>original.accept(m));
119
+ for(const structured of [true,false])for(const count of [1,8,32]){
120
+ const events=[],notices=[],stream=createClaudeReviewStream(e=>events.push(e),n=>notices.push(n));
121
+ const messages=transcript();
122
+ if(!structured){delete messages[2].structured_output;messages[2].result='{"verdict":"approved"}';}
123
+ stream.accept(messages[0]);
124
+ for(let i=0;i<count;i++){
125
+ if(i===1)stream.accept(messages[1]);
126
+ stream.accept(rateLimit());
127
+ }
128
+ if(count===1)stream.accept(messages[1]);
129
+ stream.accept(messages[2]);
130
+ assert.deepEqual(notices,Array.from({length:count},()=>expectedNotice));
131
+ assert.deepEqual(stream.finish(),original.finish());assert.deepEqual(events,baseline);
132
+ }
133
+ });
134
+ test('optional or throwing notice callbacks and non-object info do not affect results',()=>{
135
+ for(const callback of [undefined,null,()=>{throw Error('notice consumer');}]){
136
+ const stream=createClaudeReviewStream(()=>{},callback),messages=transcript();
137
+ stream.accept(messages[0]);stream.accept(rateLimit());
138
+ messages.slice(1).forEach(m=>stream.accept(m));assert.equal(stream.finish().status,'succeeded');
139
+ }
140
+ for(const info of [undefined,null,'raw text',['raw text'],{bad:Infinity,missing:undefined}]){
141
+ const notices=[],stream=createClaudeReviewStream(()=>{},n=>notices.push(n));
142
+ stream.accept(transcript()[0]);stream.accept(rateLimit({rate_limit_info:info}));
143
+ assert.deepEqual(notices,[{kind:'rate_limit',info:{}}]);
144
+ }
145
+ });
146
+ test('rate limit session, count, whitelist and terminal boundaries fail closed',()=>{
147
+ for(const [extra,code,count] of [
148
+ [[rateLimit({session_id:'other'})],'session_mismatch',0],
149
+ [[rateLimit({session_id:''})],'invalid_session',0],
150
+ [Array.from({length:33},()=>rateLimit()),'unexpected_event',32],
151
+ [[rateLimit({type:'foo_event'})],'unexpected_event',0],
152
+ ]){
153
+ const notices=[],stream=createClaudeReviewStream(()=>{},n=>notices.push(n));
154
+ stream.accept(transcript()[0]);
155
+ assert.throws(()=>extra.forEach(m=>stream.accept(m)),{code});assert.equal(notices.length,count);
156
+ assert.throws(()=>stream.finish(),{code:'incomplete_result'});
157
+ }
158
+ const before=createClaudeReviewStream(()=>{});
159
+ assert.throws(()=>before.accept(rateLimit()),{code:'missing_init'});
160
+ const after=createClaudeReviewStream(()=>{});
161
+ transcript().forEach(m=>after.accept(m));
162
+ assert.throws(()=>after.accept(rateLimit()),{code:'unexpected_event'});
163
+ const noAssistant=createClaudeReviewStream(()=>{}),messages=transcript();
164
+ noAssistant.accept(messages[0]);noAssistant.accept(rateLimit());
165
+ assert.throws(()=>noAssistant.accept(messages[2]),{code:'unexpected_result'});
166
+ const noCallback=createClaudeReviewStream(()=>{});
167
+ noCallback.accept(messages[0]);
168
+ for(let i=0;i<32;i++)noCallback.accept(rateLimit());
169
+ assert.throws(()=>noCallback.accept(rateLimit()),{code:'unexpected_event'});
170
+ });
171
+
172
+ const systemNotice = (subtype='api_retry',extra={}) => ({type:'system',subtype,session_id:'fresh-review',...extra});
173
+ function observe(messages,callback) {
174
+ const events=[],notices=[];
175
+ const stream=createClaudeReviewStream(e=>events.push(e),callback ?? (n=>notices.push(n)));
176
+ messages.forEach(m=>stream.accept(m));
177
+ return {result:stream.finish(),events,notices};
178
+ }
179
+ test('88-heartbeat dogfood event counts preserve structured findings and exact observation',()=>{
180
+ const [init,text,result]=transcript();
181
+ const value={verdict:'changes_requested',packageDigest:'a'.repeat(64),examinedPaths:['code.mjs'],
182
+ findings:Array.from({length:6},(_,i)=>({id:`F${i+1}`,severity:'P2',path:'code.mjs',
183
+ message:'Synthetic finding',evidence:'Synthetic evidence'})),summary:'Synthetic six findings'};
184
+ // Reconstruct the observed event counts, without private provider text.
185
+ const wire=[init,...Array.from({length:44},thinkingTokens),rateLimit(),
186
+ assistant([{type:'thinking',thinking:'synthetic',signature:'sig'}]),
187
+ assistant([tool('denied','Read')]),toolResult('denied',true),
188
+ ...Array.from({length:44},thinkingTokens),text,
189
+ assistant([tool('output')]),toolResult('output'),rateLimit(),
190
+ {...result,num_turns:4,structured_output:value,result:'structured output is authoritative'}];
191
+ const actual=observe(wire);
192
+ assert.deepEqual(actual.result,{status:'succeeded',value});
193
+ assert.deepEqual(actual.events,observe(transcript()).events);
194
+ assert.deepEqual(actual.notices,[expectedNotice,expectedNotice]);
195
+ });
196
+ test('thinking budget is cumulative across stages and cannot advance a verdict',()=>{
197
+ const [init,text,result]=transcript();
198
+ const half=Array.from({length:2048},thinkingTokens);
199
+ const actual=observe([init,...half,text,...half,result]);
200
+ assert.deepEqual(actual,observe(transcript()));
201
+ assert.throws(()=>decode([init,...half,text,...half,thinkingTokens(),result]),{code:'unexpected_event'});
202
+ assert.throws(()=>decode([init,...Array.from({length:4096},thinkingTokens),result]),{code:'unexpected_result'});
203
+ });
204
+ test('dogfood retry, thinking, StructuredOutput and rate limit sequence succeeds without extra observer events',()=>{
205
+ const [init,text,result]=transcript();
206
+ const actual=observe([init,systemNotice('api_retry',{attempt:1,max_retries:3,error_status:529,
207
+ retry_delay_ms:1000,error:'private error'}),thinkingTokens(),thinkingTokens(),text,
208
+ assistant([tool('output')]),toolResult('output'),rateLimit(),
209
+ {...result,result:'not JSON: structured_output is authoritative'}]);
210
+ const baseline=observe(transcript());
211
+ assert.deepEqual(actual.result,baseline.result);assert.deepEqual(actual.events,baseline.events);
212
+ assert.deepEqual(actual.notices,[{kind:'claude_system_notice',subtype:'api_retry',attempt:1,max_retries:3,error_status:529},expectedNotice]);
213
+ });
214
+ test('hook and commands notifications emit only allowlisted summaries at every nonterminal stage',()=>{
215
+ const [init,text,result]=transcript();
216
+ const subtypes=['hook_started','hook_response','commands_changed'];
217
+ const notices=subtypes.map(subtype=>systemNotice(subtype,{hook_name:'SessionStart:fixture',
218
+ output:'private output',stdout:'private stdout',stderr:'private stderr',commands:['private command'],
219
+ error:'private error',unknown:{verdict:'approved'}}));
220
+ const actual=observe([init,notices[0],text,assistant([tool('output')]),notices[1],toolResult('output'),notices[2],result]);
221
+ const baseline=observe(transcript());
222
+ assert.deepEqual(actual.result,baseline.result);assert.deepEqual(actual.events,baseline.events);
223
+ assert.deepEqual(actual.notices,subtypes.map(subtype=>({kind:'claude_system_notice',subtype,hook_name:'SessionStart:fixture'})));
224
+ for(const callback of [()=>{},()=>{throw Error('notice consumer');}]){
225
+ assert.deepEqual(observe([init,...notices,text,result],callback).result,baseline.result);
226
+ }
227
+ assert.deepEqual(decode([init,...notices,text,result]),baseline.result);
228
+ const malformed=observe([init,systemNotice('api_retry',{attempt:{text:'private'},max_retries:['private'],
229
+ error_status:Infinity,hook_name:{stdout:'private'}}),text,result]);
230
+ assert.deepEqual(malformed.notices,[{kind:'claude_system_notice',subtype:'api_retry'}]);
231
+ });
232
+ test('all system notices retain initialization, session, stage and terminal boundaries',()=>{
233
+ const [init,text,result]=transcript();
234
+ for(const subtype of ['api_retry','hook_started','hook_response','commands_changed']){
235
+ const notice=systemNotice(subtype);
236
+ assert.throws(()=>decode([notice,init,text,result]),{code:'missing_init'});
237
+ assert.throws(()=>decode([init,{...notice,session_id:'other'},text,result]),{code:'session_mismatch'});
238
+ assert.throws(()=>decode([init,{...notice,session_id:''},text,result]),{code:'invalid_session'});
239
+ assert.throws(()=>decode([init,notice,result]),{code:'unexpected_result'});
240
+ assert.throws(()=>decode([init,text,result,notice]),{code:'unexpected_event'});
241
+ assert.throws(()=>decode([init,notice]),{code:'incomplete_result'});
242
+ assert.throws(()=>decode([init,assistant([tool('bad','Bash')]),notice,toolResult('bad'),result]),{code:'unexpected_tool_or_content'});
243
+ }
244
+ for(const subtype of ['future_notice','API_RETRY','init',null,undefined]){
245
+ const notices=[],stream=createClaudeReviewStream(()=>{},n=>notices.push(n));
246
+ stream.accept(init);
247
+ assert.throws(()=>stream.accept({...systemNotice(),subtype}),{code:'unexpected_event'});
248
+ assert.deepEqual(notices,[]);
249
+ assert.throws(()=>stream.accept(systemNotice()),{code:'unexpected_event'});
250
+ }
251
+ });
252
+ test('rate limit and system notices share exactly 32 slots independent of thinking and callbacks',()=>{
253
+ const [init,text,result]=transcript();
254
+ const kinds=['api_retry','hook_started','hook_response','commands_changed','rate_limit'];
255
+ for(const mixed of [false,true]){
256
+ const notices=Array.from({length:32},(_,i)=>mixed&&i%5===4?rateLimit():systemNotice(kinds[mixed?i%5:i%4]));
257
+ const actual=observe([init,...notices,...Array.from({length:4096},thinkingTokens),text,result]);
258
+ assert.equal(actual.notices.length,32);assert.deepEqual(actual.result,decode(transcript()));
259
+ for(const extra of [rateLimit(),systemNotice()])for(const callbackEnabled of [true,false]){
260
+ const received=[],stream=createClaudeReviewStream(()=>{},callbackEnabled?n=>received.push(n):null);
261
+ [init,...notices,text].forEach(m=>stream.accept(m));
262
+ assert.throws(()=>stream.accept(extra),{code:'unexpected_event'});
263
+ assert.equal(received.length,callbackEnabled?32:0);
264
+ assert.throws(()=>stream.finish(),{code:'incomplete_result'});
265
+ }
266
+ }
267
+ });
268
+ test('exhausted retries do not decide success or suppress provider failure',()=>{
269
+ const [init,text,result]=transcript();
270
+ for(const attempt of [3,4]){
271
+ const notice=systemNotice('api_retry',{attempt,max_retries:3,error_status:529});
272
+ assert.deepEqual(decode([init,notice,text,result]),decode(transcript()));
273
+ for(const failed of [{...result,subtype:'error_during_execution',is_error:true},{...result,is_error:true}]){
274
+ const notices=[],stream=createClaudeReviewStream(()=>{},n=>notices.push(n));
275
+ [init,notice,text].forEach(m=>stream.accept(m));
276
+ assert.equal(notices.length,1);
277
+ assert.throws(()=>stream.accept(failed),{code:'provider_failed'});
278
+ }
279
+ }
280
+ });