@aibyzero/cm-workflow 0.16.3 → 0.16.5

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 (177) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +8 -0
  3. package/CHANGELOG.md +59 -0
  4. package/README.md +55 -3
  5. package/VERSION +1 -1
  6. package/docs/installation.md +21 -1
  7. package/docs/js-workflow-control.md +245 -33
  8. package/docs/next-steps.md +14 -24
  9. package/docs/runtime-failover.md +1 -1
  10. package/package.json +1 -1
  11. package/runtime/js/cm-ai/accepted-fix.mjs +23 -5
  12. package/runtime/js/cm-ai/bootstrap-feature.mjs +15 -0
  13. package/runtime/js/cm-ai/claude-review-stream.mjs +30 -0
  14. package/runtime/js/cm-ai/cm-ai-admission.mjs +116 -41
  15. package/runtime/js/cm-ai/cm-ai-context-refresh.mjs +3 -2
  16. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +137 -22
  17. package/runtime/js/cm-ai/cm-ai-learning-handoff-writer.mjs +11 -9
  18. package/runtime/js/cm-ai/cm-ai-learning-writer.mjs +22 -5
  19. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +180 -53
  20. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +2 -1
  21. package/runtime/js/cm-ai/codex-review-adapter.mjs +24 -4
  22. package/runtime/js/cm-ai/developer-adapter.mjs +6 -2
  23. package/runtime/js/cm-ai/diagnostic-reason.mjs +10 -0
  24. package/runtime/js/cm-ai/drive-bootstrap.mjs +305 -0
  25. package/runtime/js/cm-ai/drive-core.mjs +39 -7
  26. package/runtime/js/cm-ai/durable-runner-state.mjs +307 -53
  27. package/runtime/js/cm-ai/effect-abandon-log.mjs +19 -0
  28. package/runtime/js/cm-ai/effect-contract.mjs +44 -2
  29. package/runtime/js/cm-ai/execution-store-limits.mjs +18 -0
  30. package/runtime/js/cm-ai/execution-store.mjs +6 -4
  31. package/runtime/js/cm-ai/fix-code-association.mjs +171 -18
  32. package/runtime/js/cm-ai/host-bootstrap.mjs +68 -21
  33. package/runtime/js/cm-ai/host-conversation-execution.mjs +16 -4
  34. package/runtime/js/cm-ai/host-handoff.mjs +13 -6
  35. package/runtime/js/cm-ai/host-qa-executor.mjs +21 -7
  36. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +4 -4
  37. package/runtime/js/cm-ai/host-qa-policy.mjs +16 -7
  38. package/runtime/js/cm-ai/host-session.mjs +20 -5
  39. package/runtime/js/cm-ai/host-tool-bridge.mjs +1 -1
  40. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +13 -4
  41. package/runtime/js/cm-ai/host.mjs +1 -1
  42. package/runtime/js/cm-ai/launch-mismatch.mjs +42 -0
  43. package/runtime/js/cm-ai/log-rows.mjs +21 -0
  44. package/runtime/js/cm-ai/project-qa-gate.mjs +84 -0
  45. package/runtime/js/cm-ai/provider-review-observation.mjs +53 -9
  46. package/runtime/js/cm-ai/qa-config-revision.mjs +44 -10
  47. package/runtime/js/cm-ai/review-abandon-log.mjs +21 -0
  48. package/runtime/js/cm-ai/review-package.mjs +427 -31
  49. package/runtime/js/cm-ai/review-runner.mjs +47 -1
  50. package/runtime/js/cm-ai/reviewed-deliveries.mjs +97 -0
  51. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +104 -10
  52. package/runtime/js/cm-ai/reviewed-evidence-supersession-record.mjs +42 -3
  53. package/runtime/js/cm-ai/specification-material.mjs +154 -12
  54. package/runtime/js/cm-ai/task-commit.mjs +2 -2
  55. package/runtime/js/cm-ai/task-runner.mjs +502 -65
  56. package/runtime/js/cm-ai/worker-claude-developer.mjs +16 -7
  57. package/runtime/js/cm-fix/execution.mjs +109 -25
  58. package/runtime/js/cm-fix/host-review.mjs +7 -3
  59. package/runtime/js/cm-fix/host.mjs +3 -1
  60. package/runtime/js/cm-fix/progress.mjs +1 -0
  61. package/runtime/js/cm-fix/protected-edits.mjs +15 -4
  62. package/runtime/js/cm-fix/qa-source.mjs +6 -4
  63. package/runtime/js/cm-prd/analysis.mjs +2 -1
  64. package/runtime/js/cm-prd/change.mjs +28 -10
  65. package/runtime/js/cm-prd/draft.mjs +5 -2
  66. package/runtime/js/cm-prd/review-preparation.mjs +10 -3
  67. package/runtime/js/cm-prd/review-publication.mjs +4 -2
  68. package/runtime/js/cm-prd/self-check.mjs +6 -3
  69. package/runtime/js/cm-prd/summary.mjs +6 -2
  70. package/runtime/js/cm-prd/validation-reason.mjs +20 -0
  71. package/runtime/js/spec-task-line.mjs +117 -0
  72. package/runtime/js/specs-status.mjs +14 -3
  73. package/scripts/cm-ai-abandon-effect-position.test.mjs +201 -0
  74. package/scripts/cm-ai-admission.mjs +19 -10
  75. package/scripts/cm-ai-admission.test.mjs +65 -1
  76. package/scripts/cm-ai-batch-drive.mjs +93 -21
  77. package/scripts/cm-ai-batch-drive.test.mjs +171 -3
  78. package/scripts/cm-ai-batch-host.mjs +37 -13
  79. package/scripts/cm-ai-batch-host.test.mjs +26 -0
  80. package/scripts/cm-ai-batch-run.mjs +33 -10
  81. package/scripts/cm-ai-batch-run.test.mjs +56 -5
  82. package/scripts/cm-ai-bootstrap-driver-preflight.test.mjs +45 -0
  83. package/scripts/cm-ai-bootstrap-flow.test.mjs +158 -0
  84. package/scripts/cm-ai-bootstrap-merge.test.mjs +45 -0
  85. package/scripts/cm-ai-bootstrap.test.mjs +99 -7
  86. package/scripts/cm-ai-conversation-entry-ops.test.mjs +82 -2
  87. package/scripts/cm-ai-develop-driver-gaps.test.mjs +822 -0
  88. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +468 -0
  89. package/scripts/cm-ai-drive-timeout.test.mjs +17 -0
  90. package/scripts/cm-ai-drive.mjs +480 -47
  91. package/scripts/cm-ai-drive.test.mjs +247 -10
  92. package/scripts/cm-ai-fix-later-delivery.test.mjs +383 -0
  93. package/scripts/cm-ai-host.mjs +89 -25
  94. package/scripts/cm-ai-host.test.mjs +274 -12
  95. package/scripts/cm-ai-launch-diagnostics.test.mjs +142 -0
  96. package/scripts/cm-ai-multi-root.test.mjs +9 -3
  97. package/scripts/cm-ai-project-qa-gate.test.mjs +308 -0
  98. package/scripts/cm-ai-qa-config-revision.test.mjs +166 -15
  99. package/scripts/cm-ai-qa-fingerprint-config.test.mjs +157 -0
  100. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +27 -2
  101. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +400 -0
  102. package/scripts/cm-ai-review-drift-precedence.test.mjs +90 -0
  103. package/scripts/cm-ai-review-failure.test.mjs +917 -0
  104. package/scripts/cm-ai-review-timeout-config.test.mjs +29 -7
  105. package/scripts/cm-ai-review-timeout.test.mjs +199 -4
  106. package/scripts/cm-ai-run.mjs +160 -60
  107. package/scripts/cm-ai-run.test.mjs +4 -3
  108. package/scripts/cm-ai-runner-error-code-regression.test.mjs +219 -0
  109. package/scripts/cm-ai-selection-guard.test.mjs +100 -0
  110. package/scripts/cm-ai-session-chain.test.mjs +7 -3
  111. package/scripts/cm-ai-spec-rebind.test.mjs +481 -0
  112. package/scripts/cm-ai-supersede.test.mjs +571 -17
  113. package/scripts/cm-ai-verification-gate.test.mjs +2 -1
  114. package/scripts/cm-capability-gate.test.mjs +21 -2
  115. package/scripts/cm-check-drive.mjs +4 -3
  116. package/scripts/cm-check-drive.test.mjs +17 -1
  117. package/scripts/cm-check-entry.mjs +13 -2
  118. package/scripts/cm-check-host.mjs +2 -2
  119. package/scripts/cm-check-host.test.mjs +57 -1
  120. package/scripts/cm-check-runtime.sh +16 -7
  121. package/scripts/cm-claude-developer-worker.test.mjs +43 -2
  122. package/scripts/cm-claude-probe.test.mjs +9 -1
  123. package/scripts/cm-claude-review-stream.test.mjs +68 -0
  124. package/scripts/cm-claude-worker.test.mjs +11 -4
  125. package/scripts/cm-codex-developer-worker.test.mjs +4 -2
  126. package/scripts/cm-failover.mjs +8 -8
  127. package/scripts/cm-fix-abandon.test.mjs +123 -5
  128. package/scripts/cm-fix-cause-package.test.mjs +2 -0
  129. package/scripts/cm-fix-drive.mjs +45 -13
  130. package/scripts/cm-fix-drive.test.mjs +36 -1
  131. package/scripts/cm-fix-host.mjs +9 -6
  132. package/scripts/cm-fix-review-budget.test.mjs +141 -0
  133. package/scripts/cm-fixture-process-cleanup.test.mjs +95 -0
  134. package/scripts/cm-host-check.test.mjs +6 -3
  135. package/scripts/cm-host-qa-executor.test.mjs +192 -17
  136. package/scripts/cm-host-session-diagnostic.test.mjs +10 -0
  137. package/scripts/cm-interactive-qa-diagnostic.test.mjs +53 -0
  138. package/scripts/cm-log-event.mjs +17 -0
  139. package/scripts/cm-log-event.test.mjs +31 -0
  140. package/scripts/cm-prd-completion.test.mjs +105 -2
  141. package/scripts/cm-prd-draft.test.mjs +14 -0
  142. package/scripts/cm-prd-drive.mjs +13 -7
  143. package/scripts/cm-prd-drive.test.mjs +10 -0
  144. package/scripts/cm-prd-gate-diagnostic.test.mjs +100 -0
  145. package/scripts/cm-prd-review-gate.mjs +126 -81
  146. package/scripts/cm-prd-review-gate.test.mjs +105 -1
  147. package/scripts/cm-prd-review-preparation.test.mjs +15 -0
  148. package/scripts/cm-prd-review-publication.test.mjs +6 -0
  149. package/scripts/cm-prd-self-check.test.mjs +6 -0
  150. package/scripts/cm-prd-summary.test.mjs +40 -0
  151. package/scripts/cm-review-dependency-snapshot.test.mjs +15 -0
  152. package/scripts/cm-review-inventory.test.mjs +253 -1
  153. package/scripts/cm-spec-manifest.mjs +28 -10
  154. package/scripts/cm-spec-manifest.test.mjs +8 -4
  155. package/scripts/cm-spec-task-line.test.mjs +138 -0
  156. package/scripts/cm-specs-status.test.mjs +31 -1
  157. package/scripts/cm-task-gate.mjs +18 -10
  158. package/scripts/cm-task-gate.py +1 -1
  159. package/scripts/cm-test-branch-impact.test.mjs +6 -3
  160. package/scripts/fixtures/claude-review-process.mjs +1 -0
  161. package/scripts/fixtures/process-cleanup.mjs +99 -0
  162. package/scripts/test-cm-log-event.py +2 -0
  163. package/scripts/test-cm-prd-review-gate.py +2 -1
  164. package/scripts/test-npm-install.py +1 -1
  165. package/scripts/test-scan-public-safety.py +1 -1
  166. package/scripts/test-shell-compat.sh +67 -0
  167. package/scripts/test-spec-manifest.py +16 -8
  168. package/scripts/test-task-gate.py +2 -2
  169. package/scripts/test-workflow-config.py +1 -0
  170. package/scripts/validate-public-repo.py +1 -0
  171. package/skills/cm-ai/references/N1-init.md +1 -1
  172. package/skills/cm-ai/references/js-host.md +264 -40
  173. package/skills/cm-check/SKILL.md +6 -1
  174. package/skills/cm-check/references/js-host.md +3 -3
  175. package/skills/cm-fix/references/js-host.md +22 -1
  176. package/skills/cm-prd/references/js-change-recovery.md +30 -0
  177. package/skills/cm-prd/references/js-host.md +6 -0
@@ -0,0 +1,822 @@
1
+ // Develop answers and driver gaps found in the pre-release audit. Every test here
2
+ // drives the real driver/host processes; none needs the Codex sandbox, so CI runs them.
3
+ // Protected-mode flows that do reach the sandbox live in cm-ai-host.test.mjs.
4
+ import test,{after} from 'node:test';
5
+ import assert from 'node:assert/strict';
6
+ import fs from 'node:fs';
7
+ import os from 'node:os';
8
+ import path from 'node:path';
9
+ import crypto from 'node:crypto';
10
+ import {spawn,spawnSync} from 'node:child_process';
11
+ import {PassThrough,Writable} from 'node:stream';
12
+ import {fileURLToPath} from 'node:url';
13
+ import {buildManifest} from './cm-spec-manifest.mjs';
14
+ import {configFingerprint} from '../runtime/js/cm-ai/codex-config.mjs';
15
+ import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
16
+ import {applyProtectedEdits,protectedFixBridge} from '../runtime/js/cm-fix/protected-edits.mjs';
17
+ import {createHostToolBridge} from '../runtime/js/cm-ai/host-tool-bridge.mjs';
18
+ import {applyDevelopEdits} from './cm-ai-drive.mjs';
19
+ import {captureReviewBaseline} from '../runtime/js/cm-ai/review-package.mjs';
20
+ import {boundReviewText,reviewResultForPaths} from '../runtime/js/cm-ai/review-runner.mjs';
21
+ import {REVIEW_TEXT_LIMIT,JOURNAL_PAYLOAD_LIMIT} from '../runtime/js/cm-ai/effect-contract.mjs';
22
+ import {main as fixHostMain} from './cm-fix-host.mjs';
23
+
24
+ // Log mirrors and runtime declarations stay out of the invoking user's home.
25
+ const isolated=fs.mkdtempSync(path.join(os.tmpdir(),'cm-drive-gaps-home-'));
26
+ process.env.CM_WORKFLOW_HOME=path.join(isolated,'user');
27
+ process.env.CM_WORKFLOW_LOG_HOME=path.join(isolated,'logs');
28
+ after(()=>fs.rmSync(isolated,{recursive:true,force:true}));
29
+
30
+ const DRIVER=fileURLToPath(new URL('./cm-ai-drive.mjs',import.meta.url));
31
+ const HOST=fileURLToPath(new URL('./cm-ai-host.mjs',import.meta.url));
32
+ const BATCH_HOST=fileURLToPath(new URL('./cm-ai-batch-host.mjs',import.meta.url));
33
+ const DRIVE_CORE=new URL('../runtime/js/cm-ai/drive-core.mjs',import.meta.url).href;
34
+ const HOST_CHECK=new URL('../runtime/js/cm-ai/host-check.mjs',import.meta.url).href;
35
+ const REVIEWER=fileURLToPath(new URL('./fixtures/codex-review-process.mjs',import.meta.url));
36
+ const developValue={outcome:'implemented',application:{status:'no_relevant_lesson',note:null},
37
+ retrospective:{status:'no_new_lesson',candidates:[],reason:null}};
38
+
39
+ function fixture(t,{scope=['target.mjs'],runId='drive-gaps-run',files={}}={}){
40
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-drive-gaps-')));
41
+ t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
42
+ const specsDir=path.join(root,'specs5'),codeProject=path.join(root,'app'),feature='1.work';
43
+ const identity={repositoryId:'drive-gaps',runId,taskId:'T-001',attempt:1};
44
+ fs.mkdirSync(path.join(specsDir,feature),{recursive:true});fs.mkdirSync(codeProject);
45
+ for(const name of ['requirements.md','design.md'])fs.writeFileSync(path.join(specsDir,feature,name),'# Fixture\n');
46
+ fs.writeFileSync(path.join(specsDir,feature,'tasks.md'),'- [ ] T-001: fixture\n');
47
+ fs.writeFileSync(path.join(specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:[feature],specFiles:buildManifest(specsDir)}));
48
+ fs.writeFileSync(path.join(codeProject,'requirements.md'),'# Fixture\n');
49
+ for(const [file,content] of Object.entries(files)){
50
+ fs.mkdirSync(path.dirname(path.join(codeProject,file)),{recursive:true});
51
+ fs.writeFileSync(path.join(codeProject,file),content);fs.chmodSync(path.join(codeProject,file),0o644);
52
+ }
53
+ const config=path.join(root,'run.json');
54
+ fs.writeFileSync(config,JSON.stringify({version:1,specsDir,codeProject,feature,identity,scope,requirements:['requirements.md']}));
55
+ const answers=path.join(root,'answers');fs.mkdirSync(answers);
56
+ // create requires a bound review configuration; reviewer() replaces it with the
57
+ // same model and a real preflight, so the durable fingerprint is unchanged.
58
+ fs.writeFileSync(path.join(root,'review.json'),JSON.stringify({model:'fixture',preflight:{}}));
59
+ const bin=path.join(root,'bin');fs.mkdirSync(bin);
60
+ const env={...process.env,PATH:bin+path.delimiter+process.env.PATH,CM_WORKFLOW_HOME:path.join(root,'home'),
61
+ CM_WORKFLOW_LOG_HOME:path.join(root,'logs')};
62
+ const write=(name,value)=>fs.writeFileSync(path.join(answers,name),JSON.stringify(value));
63
+ const content=(name,bytes)=>fs.writeFileSync(path.join(answers,name),bytes);
64
+ const develop=(edits,name='develop.json')=>write(name,{status:'succeeded',value:developValue,edits});
65
+ const plan=(extra={})=>{const file=path.join(root,`plan-${Math.random().toString(36).slice(2)}.json`);
66
+ const value={config:'run.json',mode:'create',hostContext:'drive-host-a',
67
+ permissions:[],answers:'answers',checks:[{id:'noop',command:[process.execPath,'-e','0']}],...extra};
68
+ if(!value.permissions.includes('--review-config'))value.permissions=[...value.permissions,'--review-config','review.json'];
69
+ fs.writeFileSync(file,JSON.stringify(value));
70
+ return file;};
71
+ const drive=(file,operation,timeout=60000,umask=null)=>umask===null
72
+ ?spawnSync(process.execPath,[DRIVER,'--plan',file,operation],{encoding:'utf8',timeout,env})
73
+ :spawnSync('/bin/sh',['-c',`umask ${umask}; exec "$0" "$@"`,process.execPath,DRIVER,'--plan',file,operation],{encoding:'utf8',timeout,env});
74
+ const store=path.join(specsDir,'.reviews','.execution',runId,'state.json');
75
+ const reviewer=verdict=>{
76
+ let fake=fs.readFileSync(REVIEWER,'utf8');
77
+ if(verdict==='changes_requested')fake=fake.replace("verdict:'approved'","verdict:'changes_requested'")
78
+ .replace('findings:[]',"findings:[{id:'F1',severity:'P2',path:'"+scope[0]+"',message:'Revise',evidence:'Fixture finding'}]");
79
+ fs.writeFileSync(path.join(bin,'codex'),fake,{mode:0o700});
80
+ fs.writeFileSync(path.join(root,'review.json'),JSON.stringify({model:'fixture',preflight:{passed:true,
81
+ cli_model:'fixture',prompt_transport:'stdin',config_fingerprint:configFingerprint({cwd:codeProject,model:'fixture'})}}));
82
+ };
83
+ return {root,specsDir,codeProject,config,answers,bin,env,identity,write,content,develop,plan,drive,store,reviewer};
84
+ }
85
+ const result=run=>JSON.parse(run.stdout).result;
86
+ const records=f=>JSON.parse(fs.readFileSync(f.store,'utf8')).records;
87
+ const lastCheckpoint=f=>records(f).filter(row=>row.payload.type==='effect-checkpoint').at(-1).payload.checkpoint;
88
+ const noRun=f=>assert.equal(fs.existsSync(path.join(f.specsDir,'.reviews','.execution')),false,'preflight must not create a run');
89
+
90
+ // ---- #24 run ID length -------------------------------------------------------------------------
91
+ test('#24 a run ID shorter than 8 characters is refused before the driver launches a host',t=>{
92
+ const f=fixture(t,{runId:'short'});f.content('target.mjs','export const value = 42;\n');f.develop({'target.mjs':'target.mjs'});
93
+ const run=f.drive(f.plan(),'advance');
94
+ assert.equal(run.status,2,run.stderr);
95
+ assert.match(run.stderr,/runId.*8.*128/);
96
+ assert.equal(fs.existsSync(path.join(f.specsDir,'.reviews')),false);
97
+ });
98
+ test('#24 the host refuses a short run ID at create before writing any journal, and resume is unaffected',t=>{
99
+ const f=fixture(t,{runId:'short'});
100
+ const args=mode=>[HOST,'serve','--config',f.config,'--mode',mode,'--host-context','drive-host-a','--allow-development','--review-config',path.join(f.root,'review.json')];
101
+ const created=spawnSync(process.execPath,args('create'),{encoding:'utf8',input:'',timeout:30000,env:f.env});
102
+ assert.equal(created.status,1,created.stderr);
103
+ assert.match(created.stderr,/invalid_config: identity\.runId/);
104
+ assert.equal(fs.existsSync(path.join(f.specsDir,'.reviews','.execution','short')),false);
105
+ // The rule is a create-time rule: resume keeps its original path for existing journals.
106
+ const resumed=spawnSync(process.execPath,args('resume'),{encoding:'utf8',input:'',timeout:30000,env:f.env});
107
+ assert.equal(resumed.status,1,resumed.stderr);
108
+ assert.match(resumed.stderr,/store_missing/);
109
+ assert.doesNotMatch(resumed.stderr,/identity\.runId/);
110
+ });
111
+
112
+ // ---- #29 current attempt identity ---------------------------------------------------------------
113
+ test('#29 the single driver binds the current attempt for decision and complete after a revision',t=>{
114
+ const f=fixture(t);f.reviewer('changes_requested');
115
+ const review=['--review-config','review.json'];
116
+ f.content('a1.mjs','export const value = 42;\n');f.develop({'target.mjs':'a1.mjs'});
117
+ const first=f.drive(f.plan({permissions:review}),'advance');assert.equal(first.status,0,first.stderr);
118
+ assert.equal(result(first).state,'awaiting_review');
119
+ const decided=f.drive(f.plan({mode:'resume',permissions:[...review,'--allow-review-attempt','1'],
120
+ packageDigest:result(first).packageDigest,answers:undefined,checks:undefined}),'decision');
121
+ assert.equal(decided.status,0,decided.stderr);
122
+ assert.equal(result(decided).state,'changes_requested');assert.equal(result(decided).identity.attempt,2);
123
+ f.content('a2.mjs','export const value = 43;\n');f.develop({'target.mjs':'a2.mjs'},'develop-a2.json');f.reviewer('approved');
124
+ const second=f.drive(f.plan({mode:'resume',permissions:review}),'advance');assert.equal(second.status,0,second.stderr);
125
+ assert.equal(result(second).state,'awaiting_review');assert.equal(result(second).identity.attempt,2);
126
+ const packageDigest=result(second).packageDigest;
127
+ const approved=f.drive(f.plan({mode:'resume',permissions:[...review,'--allow-review-attempt','2'],packageDigest,
128
+ answers:undefined,checks:undefined}),'decision');
129
+ assert.equal(approved.status,0,approved.stderr);
130
+ assert.equal(result(approved).outcome,'advanced',approved.stdout);
131
+ assert.equal(result(approved).state,'approved');assert.equal(result(approved).identity.attempt,2);
132
+ const completed=f.drive(f.plan({mode:'resume',permissions:review,packageDigest}),'complete');
133
+ assert.equal(completed.status,0,completed.stderr);
134
+ assert.equal(result(completed).state,'fixture_completed',completed.stdout);
135
+ assert.equal(result(completed).identity.attempt,2);
136
+ assert.match(fs.readFileSync(path.join(f.specsDir,'1.work','tasks.md'),'utf8'),/\[x\] T-001/);
137
+ });
138
+
139
+ // ---- #11 deletion, executable bit, rename ------------------------------------------------------
140
+ const renameScope=['scripts/test.sh','old/Legacy.swift','new/Legacy.swift'];
141
+ const renameFiles={'scripts/test.sh':'#!/bin/sh\necho TEST SUCCEEDED\n','old/Legacy.swift':'// legacy\n'};
142
+ test('#11 a develop answer deletes, sets the executable bit and renames, and the package records mode and deletion',t=>{
143
+ const f=fixture(t,{scope:renameScope,files:renameFiles});
144
+ f.content('legacy.swift','// legacy\n');
145
+ f.develop({'scripts/test.sh':{mode:'0755'},'old/Legacy.swift':{delete:true},'new/Legacy.swift':'legacy.swift'});
146
+ // The task's own check runs the script directly, so it only passes with the executable bit.
147
+ // A private umask must not leak into new source files: they are created 0644.
148
+ const run=f.drive(f.plan({checks:[{id:'test',command:['./scripts/test.sh']}]}),'advance',60000,'077');
149
+ assert.equal(run.status,0,run.stderr);assert.equal(result(run).state,'awaiting_review',run.stdout);
150
+ assert.equal(fs.statSync(path.join(f.codeProject,'scripts/test.sh')).mode&0o777,0o755);
151
+ assert.equal(fs.existsSync(path.join(f.codeProject,'old/Legacy.swift')),false);
152
+ assert.equal(fs.statSync(path.join(f.codeProject,'new/Legacy.swift')).mode&0o777,0o644);
153
+ const changes=new Map(lastCheckpoint(f).reviewPackage.changes.map(change=>[change.path,change]));
154
+ assert.equal(changes.get('scripts/test.sh').before.mode,0o644);assert.equal(changes.get('scripts/test.sh').after.mode,0o755);
155
+ assert.equal(changes.get('scripts/test.sh').before.sha256,changes.get('scripts/test.sh').after.sha256);
156
+ assert.equal(changes.get('old/Legacy.swift').after,null);assert.equal(changes.get('old/Legacy.swift').before.size,10);
157
+ assert.equal(changes.get('new/Legacy.swift').before,null);assert.equal(changes.get('new/Legacy.swift').after.mode,0o644);
158
+ // The recorded mode is verified: dropping the bit after packaging is package drift, named by path.
159
+ fs.chmodSync(path.join(f.codeProject,'scripts/test.sh'),0o644);
160
+ const status=f.drive(f.plan({mode:'resume',answers:undefined,checks:undefined}),'status');
161
+ assert.equal(status.status,0,status.stderr);
162
+ assert.equal(result(status).state,'blocked');assert.equal(result(status).code,'review_package_changed');
163
+ assert.match(result(status).reason,/scripts\/test\.sh/);
164
+ });
165
+ for(const [name,edits,pattern] of [
166
+ ['mode outside 0644/0755',{'scripts/test.sh':{mode:'0777'}},/mode/],
167
+ ['numeric mode',{'scripts/test.sh':{file:'legacy.swift',mode:493}},/mode/],
168
+ ['delete:false',{'old/Legacy.swift':{delete:false}},/delete/],
169
+ ['delete with content',{'old/Legacy.swift':{delete:true,file:'legacy.swift'}},/delete/],
170
+ ['delete of a missing file',{'new/Legacy.swift':{delete:true}},/new\/Legacy\.swift/],
171
+ ['mode of a missing file',{'new/Legacy.swift':{mode:'0755'}},/new\/Legacy\.swift/],
172
+ ['unknown field',{'scripts/test.sh':{file:'legacy.swift',owner:'root'}},/develop\.json\.edits/],
173
+ ])test(`#11 invalid develop edit entry is refused before launch: ${name}`,t=>{
174
+ const f=fixture(t,{scope:renameScope,files:renameFiles});f.content('legacy.swift','// legacy\n');f.develop(edits);
175
+ const run=f.drive(f.plan(),'advance');
176
+ assert.equal(run.status,2,run.stderr);assert.match(run.stderr,/develop\.json\.edits/);assert.match(run.stderr,pattern);
177
+ noRun(f);
178
+ });
179
+
180
+ // ---- #19 limits and no-op deliveries before launch -----------------------------------------------
181
+ test('#19 a scope file above 1 MiB is refused before launch with its path and the limit',t=>{
182
+ const icon='Assets/AppIcon.appiconset/AppIcon.png';
183
+ const f=fixture(t,{scope:[icon,'Assets/AppIcon.appiconset/Contents.json']});
184
+ f.content('icon.png',crypto.randomBytes(1200*1024));f.content('contents.json','{"images":[]}\n');
185
+ f.develop({[icon]:'icon.png','Assets/AppIcon.appiconset/Contents.json':'contents.json'});
186
+ const run=f.drive(f.plan(),'advance');
187
+ assert.equal(run.status,2,run.stderr);
188
+ assert.match(run.stderr,/AppIcon\.png/);assert.match(run.stderr,/1048576/);
189
+ noRun(f);
190
+ });
191
+ test('#19 an unedited scope file above 1 MiB is refused before launch as well',t=>{
192
+ const f=fixture(t,{scope:['Assets/big.bin','target.mjs'],files:{'Assets/big.bin':crypto.randomBytes(1200*1024)}});
193
+ f.content('target.mjs','export const value = 42;\n');f.develop({'target.mjs':'target.mjs'});
194
+ const run=f.drive(f.plan(),'advance');
195
+ assert.equal(run.status,2,run.stderr);assert.match(run.stderr,/Assets\/big\.bin/);assert.match(run.stderr,/1048576/);
196
+ noRun(f);
197
+ });
198
+ test('#19 scope material above 2 MiB is refused before launch naming the files and the limit',t=>{
199
+ const shots=['01-light-zh','01-dark-zh','01-light-en','01-dark-en'].map(name=>`design/baseline/${name}.png`);
200
+ const f=fixture(t,{scope:shots});
201
+ shots.forEach((shot,index)=>f.content(`shot-${index}.png`,crypto.randomBytes(550*1024)));
202
+ f.develop(Object.fromEntries(shots.map((shot,index)=>[shot,`shot-${index}.png`])));
203
+ const run=f.drive(f.plan(),'advance');
204
+ assert.equal(run.status,2,run.stderr);
205
+ assert.match(run.stderr,/2097152/);assert.match(run.stderr,/design\/baseline\/01-/);
206
+ noRun(f);
207
+ });
208
+ for(const variant of ['empty edits','identical content'])test(`#19 a no-op develop answer is refused before launch: ${variant}`,t=>{
209
+ const f=fixture(t,{files:{'target.mjs':'export const value = 42;\n'}});
210
+ f.content('same.mjs','export const value = 42;\n');
211
+ f.develop(variant==='empty edits'?{}:{'target.mjs':'same.mjs'});
212
+ const run=f.drive(f.plan(),'advance');
213
+ assert.equal(run.status,2,run.stderr);assert.match(run.stderr,/没有任何改动/);
214
+ noRun(f);
215
+ });
216
+
217
+ test('#19 a lesson-only delivery is not refused as empty: its Learning writeback changes AGENTS.md',t=>{
218
+ const f=fixture(t,{files:{'target.mjs':'export const value = 42;\n'}});
219
+ f.write('develop.json',{status:'succeeded',value:{...developValue,retrospective:{status:'lesson_candidate',reason:null,
220
+ candidates:[{classification:'structured',trigger:'Fixture values need an explicit check',
221
+ action:'Run the syntax check before delivering',evidence:['target.mjs']}]}},edits:{}});
222
+ const run=f.drive(f.plan(),'advance');
223
+ assert.equal(run.status,0,run.stderr);assert.equal(result(run).state,'awaiting_review',run.stdout);
224
+ assert(lastCheckpoint(f).reviewPackage.changes.some(change=>change.path==='AGENTS.md'));
225
+ });
226
+ test('#11 direct edits are validated as a whole before the first write',t=>{
227
+ const f=fixture(t,{scope:['a.txt','gone.txt']});f.content('a.txt','a\n');
228
+ assert.throws(()=>applyDevelopEdits({'a.txt':'a.txt','gone.txt':{delete:true}},f.answers,f.codeProject,['a.txt','gone.txt']),/gone\.txt/);
229
+ assert.equal(fs.existsSync(path.join(f.codeProject,'a.txt')),false);
230
+ });
231
+ test('#11 the protected host refuses an invalid mode before any sandbox write',t=>{
232
+ const f=fixture(t,{files:{'target.mjs':'export const value = 42;\n'}});
233
+ const protection=path.join(f.root,'protection.json');
234
+ fs.writeFileSync(protection,JSON.stringify({checkCommands:[{id:'noop',command:['/usr/bin/true']}],timeoutMs:60000}));
235
+ for(const edit of [{content:'export const value = 43;\n',mode:'0777'},{content:null,mode:'0755'}]){
236
+ const wrapper=path.join(f.root,`protected-${Math.random().toString(36).slice(2)}.mjs`);
237
+ fs.writeFileSync(wrapper,`import {driveHost} from ${JSON.stringify(DRIVE_CORE)};
238
+ driveHost({host:${JSON.stringify(HOST)},args:['serve','--config',${JSON.stringify(f.config)},'--mode',${JSON.stringify(fs.existsSync(f.store)?'resume':'create')},
239
+ '--host-context','drive-host-a','--allow-development','--review-config',${JSON.stringify(path.join(f.root,'review.json'))},'--protected-conversation-config',${JSON.stringify(protection)}],
240
+ cwd:${JSON.stringify(f.codeProject)},operation:'advance',answers:{},request:{version:1,identity:${JSON.stringify(f.identity)}},
241
+ answerFor:async row=>row.kind==='develop'?{status:'succeeded',value:${JSON.stringify(developValue)},
242
+ edits:[{path:'target.mjs',beforeSha256:row.payload.expected['target.mjs'],...${JSON.stringify(edit)}}]}:null});`);
243
+ const run=spawnSync(process.execPath,[wrapper],{encoding:'utf8',timeout:60000,env:f.env});
244
+ assert.equal(run.status,0,run.stderr);
245
+ assert.equal(result(run).state,'blocked');assert.equal(result(run).code,'developer_result_invalid');
246
+ assert.equal(fs.readFileSync(path.join(f.codeProject,'target.mjs'),'utf8'),'export const value = 42;\n');
247
+ assert.equal(fs.statSync(path.join(f.codeProject,'target.mjs')).mode&0o777,0o644);
248
+ }
249
+ });
250
+ test('#10 an invalid --input-limit is refused by the driver before launch',t=>{
251
+ const f=fixture(t);f.content('target.mjs','export const value = 42;\n');f.develop({'target.mjs':'target.mjs'});
252
+ const run=f.drive(f.plan({permissions:['--input-limit','64k']}),'advance');
253
+ assert.equal(run.status,2,run.stderr);assert.match(run.stderr,/--input-limit/);noRun(f);
254
+ });
255
+ // A live session is not the driver: it can still deliver nothing. The runner must
256
+ // then leave a retryable develop block, not an unknown run.
257
+ function liveSession(f,{mode,write=false,act=write?"fs.writeFileSync(cwd+'/target.mjs','export const value = 43;\\n');":'',args=[],value=developValue}){
258
+ const wrapper=path.join(f.root,`live-${mode}-${Math.random().toString(36).slice(2)}.mjs`);
259
+ fs.writeFileSync(wrapper,`import fs from 'node:fs';
260
+ import {driveHost} from ${JSON.stringify(DRIVE_CORE)};
261
+ import {createHostCheck} from ${JSON.stringify(HOST_CHECK)};
262
+ const cwd=${JSON.stringify(f.codeProject)};
263
+ driveHost({host:${JSON.stringify(HOST)},args:['serve','--config',${JSON.stringify(f.config)},'--mode',${JSON.stringify(mode)},
264
+ '--host-context','drive-host-a','--allow-development',...${JSON.stringify(args.includes('--review-config')?args:['--review-config',path.join(f.root,'review.json'),...args])}],cwd,operation:'advance',answers:{},
265
+ request:{version:1,identity:${JSON.stringify(f.identity)}},
266
+ answerFor:async row=>{
267
+ if(row.kind==='develop'){
268
+ ${act}
269
+ return {status:'succeeded',value:${JSON.stringify(value)}};
270
+ }
271
+ if(row.kind==='check')return createHostCheck({cwd,commands:[{id:'noop',command:[process.execPath,'-e','0']}]})
272
+ ({identity:row.payload.identity},{signal:new AbortController().signal});
273
+ return null;
274
+ }});
275
+ `);
276
+ return spawnSync(process.execPath,[wrapper],{encoding:'utf8',timeout:60000,env:f.env});
277
+ }
278
+ test('#19 a live empty delivery blocks as a retryable develop_empty_changes and the retry reaches review',t=>{
279
+ const f=fixture(t,{files:{'target.mjs':'export const value = 42;\n'}});
280
+ const empty=liveSession(f,{mode:'create',write:false});assert.equal(empty.status,0,empty.stderr);
281
+ assert.equal(result(empty).state,'blocked',empty.stdout);assert.equal(result(empty).code,'develop_empty_changes');
282
+ assert.equal(result(empty).pendingAction,'resume');assert.match(result(empty).reason,/develop_empty_changes/);
283
+ const retried=liveSession(f,{mode:'resume',write:true});assert.equal(retried.status,0,retried.stderr);
284
+ assert.equal(result(retried).state,'awaiting_review',retried.stdout);
285
+ const intents=records(f).filter(row=>row.payload.type==='effect-intent').map(row=>row.payload.effect.id);
286
+ assert.deepEqual(intents,['develop-1','develop-1-retry-1']);
287
+ });
288
+ // Scope and requirements may overlap. A requirement must exist in every review
289
+ // package, so deleting one is refused before launch (Codex review of 6f005df).
290
+ test('#11 deleting a scope path that is also a requirement is refused before launch',t=>{
291
+ const f=fixture(t,{scope:['target.mjs','requirements.md']});
292
+ f.content('target.mjs','export const value = 42;\n');f.develop({'target.mjs':'target.mjs','requirements.md':{delete:true}});
293
+ const run=f.drive(f.plan(),'advance');
294
+ assert.equal(run.status,2,run.stderr);assert.match(run.stderr,/requirements\.md/);assert.match(run.stderr,/requirements/);
295
+ assert.equal(fs.readFileSync(path.join(f.codeProject,'requirements.md'),'utf8'),'# Fixture\n');
296
+ assert.equal(fs.existsSync(path.join(f.codeProject,'target.mjs')),false);
297
+ noRun(f);
298
+ });
299
+ test('#19 a live delivery that deletes an in-scope requirement blocks retryably and the restored retry reaches review',t=>{
300
+ const f=fixture(t,{scope:['target.mjs','requirements.md'],files:{'target.mjs':'export const value = 42;\n'}});
301
+ const broken=liveSession(f,{mode:'create',act:"fs.writeFileSync(cwd+'/target.mjs','export const value = 43;\\n');fs.unlinkSync(cwd+'/requirements.md');"});
302
+ assert.equal(broken.status,0,broken.stderr);
303
+ assert.equal(result(broken).state,'blocked',broken.stdout);assert.equal(result(broken).code,'develop_requirement_missing');
304
+ assert.equal(result(broken).pendingAction,'resume');assert.match(result(broken).reason,/requirements\.md/);
305
+ const restored=liveSession(f,{mode:'resume',act:"fs.writeFileSync(cwd+'/requirements.md','# Fixture\\n');"});
306
+ assert.equal(restored.status,0,restored.stderr);assert.equal(result(restored).state,'awaiting_review',restored.stdout);
307
+ const intents=records(f).filter(row=>row.payload.type==='effect-intent').map(row=>row.payload.effect.id);
308
+ assert.deepEqual(intents,['develop-1','develop-1-retry-1']);
309
+ });
310
+ test('#19 an out-of-scope write still wins over a missing requirement and stays unknown',t=>{
311
+ const f=fixture(t,{scope:['target.mjs','requirements.md'],files:{'target.mjs':'export const value = 42;\n'}});
312
+ const run=liveSession(f,{mode:'create',act:"fs.unlinkSync(cwd+'/requirements.md');fs.writeFileSync(cwd+'/outside.mjs','x');"});
313
+ assert.equal(run.status,1,run.stderr);
314
+ assert.equal(result(run).state,'unknown');assert.equal(result(run).code,'out_of_scope');
315
+ });
316
+ // Round 2 (Codex re-review of 304cbfb): a develop-gate block after a
317
+ // changes_requested review must be retryable at attempt 2 as it is at attempt 1.
318
+ function secondRound(f){
319
+ f.reviewer('changes_requested');
320
+ const review=['--review-config','review.json'];
321
+ f.content('a1.mjs','export const value = 42;\n');f.develop({'target.mjs':'a1.mjs'});
322
+ const first=f.drive(f.plan({permissions:review}),'advance');assert.equal(first.status,0,first.stderr);
323
+ const decided=f.drive(f.plan({mode:'resume',permissions:[...review,'--allow-review-attempt','1'],
324
+ packageDigest:result(first).packageDigest,answers:undefined,checks:undefined}),'decision');
325
+ assert.equal(decided.status,0,decided.stderr);assert.equal(result(decided).state,'changes_requested');
326
+ return review;
327
+ }
328
+ test('#19 a second-round develop whose checks fail retries in the same attempt after the fix',t=>{
329
+ const f=fixture(t),review=secondRound(f);
330
+ f.content('a2.mjs','export const value = 43;\n');f.develop({'target.mjs':'a2.mjs'},'develop-a2.json');
331
+ const failing=f.drive(f.plan({mode:'resume',permissions:review,
332
+ checks:[{id:'unit',command:[process.execPath,'-e','process.exit(3)']}]}),'advance');
333
+ assert.equal(failing.status,0,failing.stderr);
334
+ assert.equal(result(failing).state,'blocked',failing.stdout);assert.equal(result(failing).code,'develop_checks_not_passed');
335
+ assert.equal(result(failing).identity.attempt,2);assert.equal(result(failing).pendingAction,'resume');
336
+ const retried=f.drive(f.plan({mode:'resume',permissions:review}),'advance');
337
+ assert.equal(retried.status,0,retried.stderr);
338
+ assert.equal(result(retried).state,'awaiting_review',retried.stdout);assert.equal(result(retried).identity.attempt,2);
339
+ const intents=records(f).filter(row=>row.payload.type==='effect-intent'&&row.payload.effect.kind==='develop').map(row=>row.payload.effect.id);
340
+ assert.deepEqual(intents,['develop-1','develop-2','develop-2-retry-1']);
341
+ });
342
+ test('#19 a second-round delivery that deletes an in-scope requirement is recoverable at attempt 2',t=>{
343
+ const f=fixture(t,{scope:['target.mjs','requirements.md']}),review=secondRound(f);
344
+ const args=['--review-config',path.join(f.root,'review.json')];
345
+ const broken=liveSession(f,{mode:'resume',args,
346
+ act:"fs.writeFileSync(cwd+'/target.mjs','export const value = 43;\\n');fs.unlinkSync(cwd+'/requirements.md');"});
347
+ assert.equal(broken.status,0,broken.stderr);
348
+ assert.equal(result(broken).state,'blocked',broken.stdout);assert.equal(result(broken).code,'develop_requirement_missing');
349
+ assert.equal(result(broken).identity.attempt,2);
350
+ // The round-2 edit stays on disk; only the requirement is restored.
351
+ const restored=liveSession(f,{mode:'resume',args,act:"fs.writeFileSync(cwd+'/requirements.md','# Fixture\\n');"});
352
+ assert.equal(restored.status,0,restored.stderr);
353
+ assert.equal(result(restored).state,'awaiting_review',restored.stdout);assert.equal(result(restored).identity.attempt,2);
354
+ const changes=lastCheckpoint(f).reviewPackage.changes.map(change=>change.path);
355
+ assert.deepEqual(changes,['target.mjs']);
356
+ });
357
+ test('#19 review material counts every AGENTS.md the snapshot carries, not only ancestors',t=>{
358
+ // Two unrelated instruction files plus scope growth: 300+300+1000+900 KiB > 2 MiB.
359
+ const f=fixture(t,{scope:['target.mjs','big2.mjs'],files:{'a/AGENTS.md':'a'.repeat(300*1024),
360
+ 'b/AGENTS.md':'b'.repeat(300*1024),'target.mjs':'export const value = 1;\n'}});
361
+ f.content('grown.mjs','//'+'y'.repeat(1000*1024)+'\n');f.content('big2.mjs','//'+'z'.repeat(900*1024)+'\n');
362
+ f.develop({'target.mjs':'grown.mjs','big2.mjs':'big2.mjs'});
363
+ const run=f.drive(f.plan(),'advance');
364
+ assert.equal(run.status,2,run.stderr);
365
+ assert.match(run.stderr,/2097152/);assert.match(run.stderr,/[ab]\/AGENTS\.md/);
366
+ assert.equal(fs.readFileSync(path.join(f.codeProject,'target.mjs'),'utf8'),'export const value = 1;\n');
367
+ noRun(f);
368
+ });
369
+ // Journal record payloads are capped at 1 MiB (execution-store). A review package
370
+ // carries base64 content, so a delivery must fit that record, not only the
371
+ // review-package limits, or the checkpoint cannot be written after the files are.
372
+ const line=kib=>'//'+'x'.repeat(kib*1024)+'\n';
373
+ for(const kib of [700,800,1000])test(`#19 a ${kib} KiB delivery whose checkpoint exceeds the journal budget is refused before any write`,t=>{
374
+ const f=fixture(t,{files:{'target.mjs':'export const value = 1;\n'}});
375
+ f.content('big.mjs',line(kib));f.develop({'target.mjs':'big.mjs'});
376
+ const run=f.drive(f.plan(),'advance');
377
+ assert.equal(run.status,2,run.stderr);
378
+ assert.match(run.stderr,/target\.mjs/);assert.match(run.stderr,/1048576/);
379
+ assert.equal(fs.readFileSync(path.join(f.codeProject,'target.mjs'),'utf8'),'export const value = 1;\n');
380
+ noRun(f);
381
+ });
382
+ test('#19 a 500 KiB delivery still fits the journal and reaches review',t=>{
383
+ const f=fixture(t,{files:{'target.mjs':'export const value = 1;\n'}});
384
+ f.content('big.mjs',line(500));f.develop({'target.mjs':'big.mjs'});
385
+ const run=f.drive(f.plan(),'advance');
386
+ assert.equal(run.status,0,run.stderr);assert.equal(result(run).state,'awaiting_review',run.stdout);
387
+ });
388
+ test('#19 a create baseline too large for its journal record is refused by the driver before launch',t=>{
389
+ const f=fixture(t,{scope:['Assets/big.bin','target.mjs'],files:{'Assets/big.bin':crypto.randomBytes(800*1024)}});
390
+ f.content('target.mjs','export const value = 1;\n');f.develop({'target.mjs':'target.mjs'});
391
+ const run=f.drive(f.plan(),'advance');
392
+ assert.equal(run.status,2,run.stderr);assert.match(run.stderr,/Assets\/big\.bin/);assert.match(run.stderr,/1048576/);
393
+ assert.equal(fs.existsSync(path.join(f.codeProject,'target.mjs')),false);noRun(f);
394
+ });
395
+ test('#19 the host refuses an oversized create baseline before it creates any journal',t=>{
396
+ const f=fixture(t,{scope:['Assets/big.bin'],files:{'Assets/big.bin':crypto.randomBytes(800*1024)}});
397
+ const run=spawnSync(process.execPath,[HOST,'serve','--config',f.config,'--mode','create','--host-context','drive-host-a',
398
+ '--allow-development','--review-config',path.join(f.root,'review.json')],{encoding:'utf8',input:'',timeout:60000,env:f.env});
399
+ assert.equal(run.status,1,run.stderr);assert.match(run.stderr,/Assets\/big\.bin/);assert.match(run.stderr,/1048576/);
400
+ assert.equal(fs.existsSync(path.join(f.specsDir,'.reviews','.execution',f.identity.runId)),false);
401
+ });
402
+ test('#19 the runner refuses an init record that only the run metadata pushes over the journal limit',t=>{
403
+ // Size a scope file so the baseline alone fits one record but baseline plus
404
+ // the runner's own metadata does not: only the exact init check can see it.
405
+ const probe=fixture(t,{scope:['Assets/big.bin'],files:{'Assets/big.bin':Buffer.alloc(3,0x61)}});
406
+ const baselineBytes=f=>Buffer.byteLength(JSON.stringify(captureReviewBaseline({root:f.codeProject,specsRoot:f.specsDir,
407
+ identity:f.identity,scope:['Assets/big.bin'],requirements:['requirements.md'],specification:{specsRoot:f.specsDir,feature:'1.work'}})));
408
+ const created=spawnSync(process.execPath,[HOST,'serve','--config',probe.config,'--mode','create','--host-context','drive-host-a',
409
+ '--allow-development','--review-config',path.join(probe.root,'review.json')],{encoding:'utf8',input:'',timeout:60000,env:probe.env});
410
+ assert.equal(created.status,0,created.stderr);
411
+ const init=Buffer.byteLength(JSON.stringify(records(probe)[0].payload)),overhead=init-baselineBytes(probe);
412
+ assert(overhead>512,`metadata overhead ${overhead}`);
413
+ const target=1024*1024-Math.floor(overhead/2),base=baselineBytes(probe)-4;
414
+ const size=Math.floor((target-base)/4)*3;
415
+ const f=fixture(t,{scope:['Assets/big.bin'],files:{'Assets/big.bin':Buffer.alloc(size+3,0x61)}});
416
+ assert(baselineBytes(f)<=1024*1024&&baselineBytes(f)+overhead>1024*1024,`${baselineBytes(f)} + ${overhead}`);
417
+ const run=spawnSync(process.execPath,[HOST,'serve','--config',f.config,'--mode','create','--host-context','drive-host-a',
418
+ '--allow-development','--review-config',path.join(f.root,'review.json')],{encoding:'utf8',input:'',timeout:60000,env:f.env});
419
+ assert.equal(run.status,1,run.stderr);assert.match(run.stderr,/Assets\/big\.bin/);assert.match(run.stderr,/1048576/);
420
+ assert.equal(fs.existsSync(f.store)?records(f).length:0,0,'no journal record is written');
421
+ });
422
+ test('#19 a live delivery too large for its checkpoint blocks retryably and a smaller retry reaches review',t=>{
423
+ const f=fixture(t,{files:{'target.mjs':'export const value = 1;\n'}});
424
+ const big=liveSession(f,{mode:'create',act:`fs.writeFileSync(cwd+'/target.mjs','//'+'x'.repeat(800*1024)+'\\n');`});
425
+ assert.equal(big.status,0,big.stderr);
426
+ assert.equal(result(big).state,'blocked',big.stdout);assert.equal(result(big).code,'develop_package_too_large');
427
+ assert.equal(result(big).pendingAction,'resume');assert.match(result(big).reason,/target\.mjs/);assert.match(result(big).reason,/1048576/);
428
+ const small=liveSession(f,{mode:'resume',act:"fs.writeFileSync(cwd+'/target.mjs','export const value = 2;\\n');"});
429
+ assert.equal(small.status,0,small.stderr);assert.equal(result(small).state,'awaiting_review',small.stdout);
430
+ const intents=records(f).filter(row=>row.payload.type==='effect-intent').map(row=>row.payload.effect.id);
431
+ assert.deepEqual(intents,['develop-1','develop-1-retry-1']);
432
+ });
433
+ test('#19 a delivery whose develop checkpoint fits but leaves no room for review and completion is redone',t=>{
434
+ // Under the 1 MiB record on its own, over the budget that keeps room for the
435
+ // bounded review and completion checkpoints, which carry the same package again.
436
+ const f=fixture(t,{files:{'target.mjs':'export const value = 1;\n'}});
437
+ const run=liveSession(f,{mode:'create',act:`fs.writeFileSync(cwd+'/target.mjs','//'+'x'.repeat(700*1024)+'\\n');`});
438
+ assert.equal(run.status,0,run.stderr);
439
+ assert.equal(result(run).state,'blocked',run.stdout);assert.equal(result(run).code,'develop_package_too_large');
440
+ const [,bytes,budget]=/checkpoint would be (\d+) bytes, above (\d+)/.exec(result(run).reason).map(Number);
441
+ assert(bytes<=JOURNAL_PAYLOAD_LIMIT&&bytes>budget,`${bytes} ${budget}`);
442
+ assert.match(result(run).reason,/bounded review/);
443
+ });
444
+ // Codex review of 090d683: a valid reviewer result near the admitted package limit
445
+ // must still leave every later checkpoint persistable.
446
+ test('#19 a package admitted at the budget edge survives a maximal review through completion',t=>{
447
+ const f=fixture(t,{files:{'target.mjs':'export const value = 1;\n'}});f.reviewer('approved');
448
+ const cli=path.join(f.bin,'codex');
449
+ fs.writeFileSync(cli,fs.readFileSync(cli,'utf8').replace("findings:[],summary:'Synthetic process review, not model evidence'",
450
+ "findings:Array.from({length:40},(_,n)=>({id:'F'+n,severity:'P3',path:data.examinedPaths[0],message:'m'.repeat(2000),"
451
+ +"evidence:'e'.repeat(2000)})),summary:'s'.repeat(20000)"));
452
+ const args=['--review-config',path.join(f.root,'review.json')];
453
+ // Walk down from an oversized delivery using the runner's own figures. Base64
454
+ // carries 3 content bytes in 4; each redo adds about 5 KB to the frame and the
455
+ // reserve together, and all effects must stay within the six-effect limit.
456
+ let content=700*1024,admitted,budget,mode='create';
457
+ for(let round=0;round<3;round++){
458
+ admitted=liveSession(f,{mode,args,act:`fs.writeFileSync(cwd+'/target.mjs','//'+'x'.repeat(${content})+'\\n');`});mode='resume';
459
+ assert.equal(admitted.status,0,admitted.stderr);
460
+ if(result(admitted).state==='awaiting_review')break;
461
+ const [,bytes,limit]=/checkpoint would be (\d+) bytes, above (\d+)/.exec(result(admitted).reason).map(Number);
462
+ budget=limit;content-=Math.ceil((bytes-limit+8000)*3/4);
463
+ }
464
+ assert.equal(result(admitted).state,'awaiting_review',admitted.stdout);
465
+ const developed=Buffer.byteLength(JSON.stringify(records(f).at(-1).payload));
466
+ assert(developed<=budget&&developed>budget-8192,`${developed} vs ${budget}`);
467
+ const review=['--review-config','review.json'];
468
+ const decided=f.drive(f.plan({mode:'resume',permissions:[...review,'--allow-review-attempt','1'],
469
+ packageDigest:result(admitted).packageDigest,answers:undefined,checks:undefined}),'decision');
470
+ assert.equal(decided.status,0,decided.stderr);assert.equal(result(decided).state,'approved',decided.stdout);
471
+ const completed=f.drive(f.plan({mode:'resume',permissions:review,packageDigest:result(admitted).packageDigest}),'complete');
472
+ assert.equal(completed.status,0,completed.stderr);assert.equal(result(completed).state,'fixture_completed',completed.stdout);
473
+ const payloads=records(f).map(row=>Buffer.byteLength(JSON.stringify(row.payload)));
474
+ assert(Math.max(...payloads)<=JOURNAL_PAYLOAD_LIMIT,String(Math.max(...payloads)));
475
+ const receipt=records(f).filter(row=>row.payload.type==='effect-checkpoint').at(-1).payload.checkpoint.receipt.result;
476
+ const text=Buffer.byteLength(JSON.stringify(receipt))-Buffer.byteLength(JSON.stringify(receipt.examinedPaths));
477
+ assert(text<=REVIEW_TEXT_LIMIT&&text>REVIEW_TEXT_LIMIT-2048,String(text));assert.match(receipt.summary,/truncated/);
478
+ });
479
+ test('#19 review text over the limit is truncated by the documented rule and stays a valid review',()=>{
480
+ const pkg={packageDigest:'a'.repeat(64)},paths=['a.mjs','b.mjs'];
481
+ const long=n=>'z'.repeat(n);
482
+ const small={verdict:'approved',packageDigest:pkg.packageDigest,examinedPaths:paths,findings:[],summary:'ok'};
483
+ assert.equal(boundReviewText(small),small);
484
+ const approved={...small,findings:Array.from({length:40},(_,n)=>({id:`P${n}`,severity:'P3',path:'a.mjs',
485
+ message:long(3000),evidence:long(3000)})),summary:long(30000)};
486
+ const bounded=boundReviewText(approved),bytes=v=>Buffer.byteLength(JSON.stringify(v))-Buffer.byteLength(JSON.stringify(v.examinedPaths));
487
+ assert(bytes(bounded)<=REVIEW_TEXT_LIMIT);assert.equal(bounded.findings.length,40);
488
+ assert(bounded.findings.every(f=>f.message.endsWith('truncated to the review text limit]')));
489
+ assert.deepEqual(bounded.findings.map(f=>f.id),approved.findings.map(f=>f.id));
490
+ reviewResultForPaths(bounded,pkg,paths);
491
+ // The non-blocking finding comes first, so omitting "from the end" alone would keep it.
492
+ const requested={...small,verdict:'changes_requested',findings:[{id:'P3-first',severity:'P3',path:'a.mjs',message:'x',evidence:'y'},
493
+ ...Array.from({length:60},(_,n)=>({id:`B${n}-${'i'.repeat(100)}`,severity:'P1',path:'b.mjs',message:long(500),evidence:long(500)}))],summary:'s'};
494
+ const omitted=boundReviewText(requested);
495
+ assert(bytes(omitted)<=REVIEW_TEXT_LIMIT);assert(omitted.findings.length<61&&omitted.findings.some(f=>f.severity==='P1'));
496
+ assert(!omitted.findings.some(f=>f.id==='P3-first'),'non-blocking findings are omitted first');
497
+ assert.match(omitted.summary,new RegExp(`${61-omitted.findings.length} findings omitted`));
498
+ reviewResultForPaths(omitted,pkg,paths);
499
+ // The last blocking finding is never dropped: a result that cannot fit even then is refused.
500
+ const huge='d/'+'p'.repeat(14000)+'.mjs';
501
+ assert.equal(boundReviewText({...small,verdict:'changes_requested',examinedPaths:[huge],
502
+ findings:[{id:'B1',severity:'P1',path:huge,message:'m',evidence:'e'}],summary:'s'}),null);
503
+ });
504
+ // Codex review of 090d683: the handoff lists every changed path, so with many of
505
+ // them it is far larger than any fixed allowance. Around the budget edge the
506
+ // driver must never admit a delivery the runner then blocks for size.
507
+ // Find the runner's exact edge with a live delivery of this layout, then drive
508
+ // deliveries straddling it: each is refused before any write or reaches review.
509
+ function sweepEdge(t,{scope,files={},writeLayout,answerLayout,value=developValue}){
510
+ const probe=fixture(t,{scope,files});
511
+ const blocked=liveSession(probe,{mode:'create',act:writeLayout(700*1024),value});
512
+ const [,bytes,budget]=/checkpoint would be (\d+) bytes, above (\d+)/.exec(result(blocked).reason).map(Number);
513
+ const edge=700*1024-Math.ceil((bytes-budget)*3/4);
514
+ let admitted=0,refused=0;
515
+ for(let step=-4;step<=4;step++){
516
+ const f=fixture(t,{scope,files});answerLayout(f,edge+step*4096);
517
+ f.write('develop.json',{status:'succeeded',value,edits:f.edits});
518
+ const run=f.drive(f.plan(),'advance');
519
+ if(run.status===2){refused++;assert.match(run.stderr,/含 handoff/);noRun(f);continue;}
520
+ admitted++;assert.equal(run.status,0,run.stderr);
521
+ assert.equal(result(run).state,'awaiting_review',`${edge+step*4096}: ${run.stdout}`);
522
+ }
523
+ assert(admitted>0&&refused>0,`admitted ${admitted}, refused ${refused}`);
524
+ }
525
+ // Codex review of 090d683: the handoff lists every changed path, so with many of
526
+ // them it is far larger than any fixed allowance. Around the budget edge the
527
+ // driver must never admit a delivery the runner then blocks for size.
528
+ test('#19 with many changed paths the driver never admits a delivery the runner blocks for size',t=>{
529
+ const names=Array.from({length:200},(_,n)=>`src/generated/module-with-a-rather-long-descriptive-name-${String(n).padStart(3,'0')}.mjs`);
530
+ sweepEdge(t,{scope:['big.mjs',...names],
531
+ writeLayout:big=>`fs.mkdirSync(cwd+'/src/generated',{recursive:true});`
532
+ +`for(const name of ${JSON.stringify(names)})fs.writeFileSync(cwd+'/'+name,'export const v = '+name.length+';\\n');`
533
+ +`fs.writeFileSync(cwd+'/big.mjs','//'+'x'.repeat(${big})+'\\n');`,
534
+ answerLayout:(f,big)=>{
535
+ for(const name of names)f.content(name.replaceAll('/','_'),`export const v = ${name.length};\n`);
536
+ f.content('big-content.mjs','//'+'x'.repeat(big)+'\n');
537
+ f.edits=Object.fromEntries([['big.mjs','big-content.mjs'],...names.map(name=>[name,name.replaceAll('/','_')])]);
538
+ }});
539
+ });
540
+ // A lesson delivery also changes AGENTS.md through the Learning writeback; the
541
+ // driver projects that write with the writer's own merge.
542
+ test('#19 a lesson delivery near the edge is sized with its AGENTS.md writeback',t=>{
543
+ const lesson={...developValue,retrospective:{status:'lesson_candidate',reason:null,candidates:[{classification:'structured',
544
+ trigger:'Large fixture files need a size check',action:'Measure the delivery before writing it',evidence:['target.mjs']}]}};
545
+ const agents='# Project rules\n\n'+'- keep this rule\n'.repeat(3000);
546
+ sweepEdge(t,{scope:['target.mjs'],files:{'AGENTS.md':agents},value:lesson,
547
+ writeLayout:big=>`fs.writeFileSync(cwd+'/target.mjs','//'+'x'.repeat(${big})+'\\n');`,
548
+ answerLayout:(f,big)=>{f.content('big-content.mjs','//'+'x'.repeat(big)+'\n');f.edits={'target.mjs':'big-content.mjs'};}});
549
+ });
550
+ // Codex review of 36d860c: journaled reasons are limited to 8192 characters on
551
+ // replay. A reason listing many long paths must stay within it and replay.
552
+ const longPaths=Array.from({length:20},(_,n)=>`${'a'.repeat(200)}/${'b'.repeat(200)}/requirement-${String(n).padStart(2,'0')}.md`);
553
+ function assertReplayableReason(f,code){
554
+ const status=f.drive(f.plan({mode:'resume',answers:undefined,checks:undefined}),'status');
555
+ assert.equal(status.status,0,status.stderr);assert.equal(result(status).code,code);
556
+ const reason=result(status).reason;assert(reason.length<=8192,String(reason.length));assert(!/[\r\n\0]/.test(reason));
557
+ return reason;
558
+ }
559
+ test('#19 a requirement-missing reason over 20 long paths stays within the replay limit',t=>{
560
+ const files=Object.fromEntries(longPaths.map(file=>[file,'# requirement\n']));
561
+ const f=fixture(t,{scope:['target.mjs',...longPaths],files:{...files,'target.mjs':'export const value = 1;\n'}});
562
+ const definition=JSON.parse(fs.readFileSync(f.config,'utf8'));definition.requirements=['requirements.md',...longPaths];
563
+ fs.writeFileSync(f.config,JSON.stringify(definition));
564
+ const run=liveSession(f,{mode:'create',act:`fs.writeFileSync(cwd+'/target.mjs','export const value = 2;\\n');`
565
+ +`for(const file of ${JSON.stringify(longPaths)})fs.unlinkSync(cwd+'/'+file);`});
566
+ assert.equal(run.status,0,run.stderr);assert.equal(result(run).code,'develop_requirement_missing',run.stdout);
567
+ const reason=assertReplayableReason(f,'develop_requirement_missing');
568
+ for(const n of ['00','19'])assert.match(reason,new RegExp(`requirement-${n}\\.md`));
569
+ });
570
+ test('#19 a package-too-large reason with long changed paths stays within the replay limit',t=>{
571
+ const f=fixture(t,{scope:['target.mjs',...longPaths]});
572
+ const run=liveSession(f,{mode:'create',act:`for(const file of ${JSON.stringify(longPaths)}){fs.mkdirSync(cwd+'/'+file.slice(0,file.lastIndexOf('/')),{recursive:true});`
573
+ +`fs.writeFileSync(cwd+'/'+file,'//'+'y'.repeat(40*1024)+'\\n');}fs.writeFileSync(cwd+'/target.mjs','//'+'x'.repeat(700*1024)+'\\n');`});
574
+ assert.equal(run.status,0,run.stderr);assert.equal(result(run).code,'develop_package_too_large',run.stdout);
575
+ assertReplayableReason(f,'develop_package_too_large');
576
+ });
577
+ test('#19 bounded reasons list what fits and count the rest',async()=>{
578
+ const {boundedReason}=await import('../runtime/js/cm-ai/effect-contract.mjs');
579
+ const items=Array.from({length:50},(_,n)=>`${'p'.repeat(1000)}-${n}`);
580
+ const reason=boundedReason('head: ',items,'; tail');
581
+ assert(reason.length<=8192);assert.match(reason,/^head: /);assert.match(reason,/等 50 个; tail$/);
582
+ assert.equal(boundedReason('x: ',['a','b'],'.'),'x: a, b.');
583
+ assert(!/[\r\n\0]/.test(boundedReason('h',['a\nb','c\0d'],'')));
584
+ assert.match(boundedReason('',[`${'q'.repeat(500)}/name.md`],''),/…q+\/name\.md$/);
585
+ });
586
+ // Codex review of ee86753 asked for a retryable block when the task handoff
587
+ // exceeds its 256 KiB limit. Its inputs are already capped: changed files come
588
+ // from the scope in run.json (at most 64 KiB), check results from validChecks (at
589
+ // most 64 KiB of JSON), and Learning records from their own limits. This builds
590
+ // the largest handoff those caps allow with the real builders and keeps it under
591
+ // the limit, so the case cannot happen; raising any of those caps must revisit it.
592
+ test('#19 the largest handoff the input caps allow stays under the 256 KiB handoff limit',async t=>{
593
+ const {hostHandoffDocument}=await import('../runtime/js/cm-ai/host-handoff.mjs');
594
+ const {taskLearningHandoffBytes}=await import('../runtime/js/cm-ai/cm-ai-learning-handoff-writer.mjs');
595
+ const {validChecks}=await import('../runtime/js/cm-ai/review-package.mjs');
596
+ const {inspectCmAiTaskLearningInput,createCmAiTaskLearningApplication,createCmAiTaskLearningRetrospective}=
597
+ await import('../runtime/js/cm-ai/cm-ai-context-refresh.mjs');
598
+ const {validateRunDefinition,RUN_DEFINITION_LIMIT}=await import('./cm-ai-run.mjs');
599
+ const f=fixture(t);
600
+ // Largest scope a 64 KiB run.json can hold, 255 files plus AGENTS.md added by the writeback.
601
+ const definition=JSON.parse(fs.readFileSync(f.config,'utf8'));
602
+ const room=RUN_DEFINITION_LIMIT-Buffer.byteLength(JSON.stringify({...definition,scope:[]}));
603
+ const length=Math.floor(room/255)-3;
604
+ definition.scope=Array.from({length:255},(_,n)=>`${'q'.repeat(length-4)}${String(n).padStart(4,'0')}`);
605
+ assert(Buffer.byteLength(JSON.stringify(definition))<=RUN_DEFINITION_LIMIT);validateRunDefinition(definition);
606
+ // Largest check JSON: backslashes double in the check JSON and again in the handoff.
607
+ let low=1,high=70000;
608
+ const checkWith=size=>[{id:'c',command:['\\'.repeat(size)],outcome:'passed',exitCode:0,evidence:'e'}];
609
+ while(low<high){const middle=Math.ceil((low+high)/2);try{validChecks(checkWith(middle));low=middle;}catch{high=middle-1;}}
610
+ const checks=checkWith(low);
611
+ const identity={...f.identity,attempt:2};
612
+ const learningInput=inspectCmAiTaskLearningInput({specsDir:f.specsDir,codeProject:f.codeProject,feature:'1.work',
613
+ identity,applicableAgentFiles:[]},{admission:null,parallelSelection:null});
614
+ const binding={feature:'1.work',identity,learningDigest:learningInput.learningDigest};
615
+ const application=createCmAiTaskLearningApplication({...binding,status:'applied',note:'\\'.repeat(512)});
616
+ const retrospective=createCmAiTaskLearningRetrospective({...binding,status:'lesson_candidate',reason:null,
617
+ candidates:Array.from({length:3},(_,n)=>({classification:'structured',trigger:`${n}${'\\'.repeat(239)}`,
618
+ action:`${n}${'\\'.repeat(239)}`,evidence:Array.from({length:8},(_,e)=>`${'e'.repeat(500)}/${n}-${e}.md`)}))});
619
+ const {payload}=hostHandoffDocument({baseline:{identity},checks,
620
+ reviewPackage:{changes:definition.scope.map(file=>({path:file})),packageDigest:'0'.repeat(64)},implementationSha256:'0'.repeat(64)});
621
+ const handoff=taskLearningHandoffBytes({handoff:payload,feature:'1.work',identity,learningInput,application,retrospective,includeAgents:true});
622
+ assert(handoff.length<256*1024,`largest handoff ${handoff.length}`);
623
+ });
624
+ test('#19 a legacy unknown/empty_changes develop checkpoint still replays as unknown',t=>{
625
+ const f=fixture(t,{files:{'target.mjs':'export const value = 42;\n'}});
626
+ assert.equal(liveSession(f,{mode:'create',write:false}).status,0);
627
+ // Rewrite the new blocked checkpoint into exactly what the previous runner wrote
628
+ // for the same delivery: unknown/empty_changes with no reason, same frame otherwise.
629
+ const state=JSON.parse(fs.readFileSync(f.store,'utf8'));
630
+ const last=state.records.at(-1);assert.equal(last.payload.type,'effect-checkpoint');
631
+ const legacy=value=>{const {reason,...rest}=value;return {...rest,state:'unknown',code:'empty_changes'};};
632
+ const checkpoint=legacy(last.payload.checkpoint);
633
+ checkpoint.reason=null;
634
+ checkpoint.cache=checkpoint.cache.map(entry=>entry.effect.id===last.payload.effectId?{...entry,result:legacy(entry.result)}:entry);
635
+ const {digest:old,...body}=last;
636
+ const payload={...last.payload,checkpoint};
637
+ const record={...body,payload};record.digest=digest({...body,payload});
638
+ const {revision,...rest}=state;rest.records=[...state.records.slice(0,-1),record];
639
+ fs.writeFileSync(f.store,JSON.stringify({...rest,revision:digest(rest)})+'\n');
640
+ const status=f.drive(f.plan({mode:'resume',answers:undefined,checks:undefined}),'status');
641
+ assert.equal(status.status,1,status.stderr);
642
+ assert.equal(result(status).state,'unknown');assert.equal(result(status).code,'empty_changes');
643
+ assert.equal(result(status).pendingAction,'reconcile');
644
+ });
645
+
646
+ // ---- #10 input limit: bridge sizing, naming, fail-fast ------------------------------------------
647
+ function session(argv,{env,onRequest,finish}){
648
+ return new Promise((resolve,reject)=>{
649
+ const child=spawn(process.execPath,argv,{stdio:['pipe','pipe','pipe'],env});
650
+ let buffer='',stderr='';const rows=[];
651
+ const timer=setTimeout(()=>{child.kill('SIGKILL');reject(Error('session timed out: '+stderr));},60000);
652
+ child.stderr.on('data',chunk=>{stderr+=chunk;});
653
+ child.stdin.on('error',()=>{});
654
+ const send=value=>child.stdin.write(JSON.stringify(value)+'\n');
655
+ child.stdout.on('data',chunk=>{
656
+ buffer+=chunk;
657
+ for(let newline;(newline=buffer.indexOf('\n'))!==-1;){
658
+ const line=buffer.slice(0,newline);buffer=buffer.slice(newline+1);if(!line)continue;
659
+ const row=JSON.parse(line);rows.push(row);
660
+ if(row.type==='host_ready')send({requestId:'drive',operation:'advance',...(finish??{})});
661
+ else if(row.type==='host_request')onRequest(row,send,child);
662
+ else if(row.type==='host_response'&&row.accepted===false)child.stdin.end();
663
+ else if(row.requestId==='drive')child.stdin.end();
664
+ }
665
+ });
666
+ child.once('error',reject);
667
+ child.once('close',code=>{clearTimeout(timer);resolve({code,rows,stderr});});
668
+ });
669
+ }
670
+ const padded=(row,result)=>({type:'host_result',sessionId:row.sessionId,callId:row.callId,requestDigest:row.requestDigest,
671
+ result:{...result,pad:'x'.repeat(100*1024)}});
672
+ test('#10 the single host sizes the tool-bridge reply limit from --input-limit',async t=>{
673
+ const f=fixture(t);
674
+ const run=await session([HOST,'serve','--config',f.config,'--mode','create','--host-context','drive-host-a',
675
+ '--allow-development','--review-config',path.join(f.root,'review.json'),'--input-limit','1048576'],{env:f.env,finish:{version:1,identity:f.identity},
676
+ onRequest:(row,send)=>send(padded(row,{status:'succeeded',value:developValue}))});
677
+ const response=run.rows.find(row=>row.type==='host_response');
678
+ assert.equal(response.accepted,true,JSON.stringify(response));
679
+ // The oversized-but-allowed reply reached the developer contract, which rejects the
680
+ // extra field: a recorded develop result, not a session left waiting or unknown.
681
+ assert.equal(run.rows.find(row=>row.requestId==='drive').result.state,'blocked');
682
+ });
683
+ test('#10 a reply line above the single host input limit is named request_too_large',async t=>{
684
+ const f=fixture(t);
685
+ const run=await session([HOST,'serve','--config',f.config,'--mode','create','--host-context','drive-host-a',
686
+ '--allow-development','--review-config',path.join(f.root,'review.json')],{env:f.env,finish:{version:1,identity:f.identity},
687
+ onRequest:(row,send)=>send(padded(row,{status:'succeeded',value:developValue}))});
688
+ assert.equal(run.code,1,run.stderr);
689
+ assert.match(run.stderr,/"code":"request_too_large"/);assert.match(run.stderr,/65536/);assert.match(run.stderr,/--input-limit/);
690
+ assert.doesNotMatch(run.stderr,/host_launch_failed/);
691
+ });
692
+ function batchFixture(t){
693
+ const f=fixture(t);
694
+ for(const args of [['init','-b','main'],['config','user.name','Fixture'],['config','user.email','fixture@example.invalid'],['add','-A'],['commit','-m','baseline']]){
695
+ const run=spawnSync('git',['-C',f.codeProject,...args],{encoding:'utf8'});assert.equal(run.status,0,run.stderr);
696
+ }
697
+ const batch={version:1,repositoryId:'batch-gaps',batchId:'batch-gaps-run',specsDir:f.specsDir,codeProject:f.codeProject,
698
+ tasks:[{feature:'1.work',taskId:'T-001',scope:['target.mjs'],requirements:['requirements.md']}]};
699
+ fs.writeFileSync(path.join(f.root,'batch.json'),JSON.stringify({batch,workflows:{'1.work/T-001':null}}));
700
+ return f;
701
+ }
702
+ for(const limit of ['1048576',null])test(`#10 the batch host ${limit?'sizes the reply limit from --input-limit':'names request_too_large'}`,async t=>{
703
+ const f=batchFixture(t);
704
+ const run=await session([BATCH_HOST,'serve','--config',path.join(f.root,'batch.json'),'--host-context','batch-host-a',
705
+ '--allow-development','--review-config',path.join(f.root,'review.json'),...(limit?['--input-limit',limit]:[])],{env:f.env,
706
+ onRequest:(row,send)=>send(padded(row,{status:'succeeded',value:developValue}))});
707
+ if(limit){
708
+ assert.equal(run.rows.find(row=>row.type==='host_response')?.accepted,true,run.stderr);
709
+ assert.equal(run.rows.find(row=>row.requestId==='drive').result.state,'blocked');
710
+ }else{
711
+ assert.equal(run.code,1,run.stderr);assert.match(run.stderr,/"code":"request_too_large"/);
712
+ assert.doesNotMatch(run.stderr,/batch_host_failed/);
713
+ }
714
+ });
715
+ for(const limit of ['1048576',null])test(`#10 the fix host ${limit?'accepts --input-limit and sizes the reply limit':'names request_too_large'}`,async t=>{
716
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-drive-gaps-fix-')));
717
+ t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
718
+ const specsRoot=path.join(root,'specs'),cwd=path.join(root,'code');fs.mkdirSync(specsRoot);fs.mkdirSync(cwd);
719
+ const config=path.join(root,'config.json');
720
+ fs.writeFileSync(config,JSON.stringify({specsRoot,identity:{repositoryId:'fixture',runId:'fix-limit-run',taskId:'T-FIX-limit',attempt:1},
721
+ defect:'Synthetic defect',reproduction:{cwd,command:[process.execPath,'-e',"process.stderr.write('BUG');process.exit(3)"],
722
+ expectedFailure:{exitCode:3,outputIncludes:'BUG'},timeoutMs:2000}}));
723
+ const input=new PassThrough(),rows=[];let errors='',answered=false;
724
+ const send=value=>{if(!input.writableEnded)input.write(JSON.stringify(value)+'\n');};
725
+ const output=new Writable({write(chunk,encoding,callback){
726
+ for(const line of chunk.toString().split('\n').filter(Boolean)){
727
+ const row=JSON.parse(line);rows.push(row);
728
+ if(row.type==='host_ready')send({requestId:'advance',operation:'advance'});
729
+ if(row.type==='host_request'&&!answered){answered=true;send(padded(row,{contextDigest:row.payload.contextDigest,
730
+ status:'no_relevant_lesson',summary:'No lesson'}));}
731
+ if((row.type==='host_response'||row.requestId==='advance')&&!input.writableEnded)input.end();
732
+ }
733
+ callback();
734
+ }});
735
+ const error=new Writable({write(chunk,encoding,callback){errors+=chunk;callback();}});
736
+ const code=await fixHostMain(['serve','--config',config,'--mode','create','--host-context','fixture-host','--allow-reproduction',
737
+ ...(limit?['--input-limit',limit]:[])],{input,output,error});
738
+ if(limit){
739
+ assert.equal(rows.find(row=>row.type==='host_response')?.accepted,true,errors);
740
+ assert.equal(code,0,errors);
741
+ }else{
742
+ assert.equal(code,1);assert.match(errors,/"code":"request_too_large"/);assert.doesNotMatch(errors,/fix_host_failed/);
743
+ }
744
+ });
745
+ test('#10 the tool bridge names an oversized reply separately from a mismatched one',async()=>{
746
+ const bridge=createHostToolBridge({responseLimit:64*1024}),sent=[];
747
+ bridge.attach(row=>{if(row.type==='host_request')sent.push(row);});
748
+ const call=bridge.call('develop',{},new AbortController().signal);await new Promise(resolve=>setImmediate(resolve));
749
+ const row=sent[0],reply=result=>({type:'host_result',sessionId:row.sessionId,callId:row.callId,requestDigest:row.requestDigest,result});
750
+ assert.deepEqual(bridge.accept(reply({pad:'x'.repeat(64*1024)})),{accepted:false,code:'host_response_too_large'});
751
+ assert.deepEqual(bridge.accept({...reply({}),callId:'other'}),{accepted:false,code:'host_response_mismatch'});
752
+ assert.equal(bridge.accept(reply({ok:true})).accepted,true);assert.deepEqual(await call,{ok:true});bridge.close();
753
+ });
754
+ test('#10 the driver stops waiting when the host rejects a reply',t=>{
755
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-drive-gaps-reject-')));
756
+ t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
757
+ // A host that rejects every reply and only answers once its input closes.
758
+ const host=path.join(root,'rejecting-host.mjs'),wrapper=path.join(root,'drive.mjs');
759
+ fs.writeFileSync(host,`const out=row=>process.stdout.write(JSON.stringify(row)+'\\n');
760
+ out({type:'host_ready',sessionId:'s'});let text='';
761
+ process.stdin.on('data',chunk=>{text+=chunk;for(let at;(at=text.indexOf('\\n'))>=0;){const row=JSON.parse(text.slice(0,at));text=text.slice(at+1);
762
+ if(row.requestId==='drive')out({type:'host_request',sessionId:'s',callId:'c',requestDigest:'d',kind:'develop',payload:{}});
763
+ if(row.type==='host_result'){out({type:'host_response',accepted:false,code:'host_response_too_large'});
764
+ out({type:'host_request',sessionId:'s',callId:'c2',requestDigest:'d2',kind:'develop',payload:{}});}}});
765
+ // Even a result that is not itself a failure must not turn a rejected reply into success.
766
+ process.stdin.on('end',()=>{out({requestId:'drive',result:{state:'blocked',code:'failed'}});process.exit(0);});
767
+ `);
768
+ fs.writeFileSync(wrapper,`import {driveHost} from ${JSON.stringify(DRIVE_CORE)};
769
+ driveHost({host:${JSON.stringify(host)},args:[],cwd:${JSON.stringify(root)},operation:'advance',answers:{},
770
+ answerFor:async()=>({status:'succeeded',value:{}})});`);
771
+ const run=spawnSync(process.execPath,[wrapper],{encoding:'utf8',timeout:15000});
772
+ assert.notEqual(run.signal,'SIGTERM','driver kept waiting for a rejected reply');
773
+ assert.equal(run.status,1,run.stderr);
774
+ assert.match(run.stderr,/host_response_too_large/);assert.match(run.stderr,/--input-limit/);
775
+ // The ended session receives nothing more, and the host's own result is still reported.
776
+ assert.doesNotMatch(run.stderr,/ERR_STREAM_WRITE_AFTER_END|write after end/);
777
+ assert.equal(JSON.parse(run.stdout).result.state,'blocked');
778
+ });
779
+ test('#10 a protected develop reply above the input limit is refused before launch',t=>{
780
+ const f=fixture(t,{scope:['App.xcodeproj/project.pbxproj']});
781
+ fs.writeFileSync(path.join(f.root,'protection.json'),JSON.stringify({checkCommands:[{id:'noop',command:['/usr/bin/true']}],timeoutMs:60000}));
782
+ f.content('pbxproj.txt','// !$*UTF8*$!\n'+'\t\tA1D0000000000000000001 /* x */ = {isa = PBXBuildFile; };\n'.repeat(1500));
783
+ f.develop({'App.xcodeproj/project.pbxproj':'pbxproj.txt'});
784
+ const run=f.drive(f.plan({runtime:'claude',permissions:['--protected-conversation-config','protection.json'],checks:undefined}),'advance',30000);
785
+ assert.equal(run.status,2,run.stderr);
786
+ assert.match(run.stderr,/--input-limit/);assert.match(run.stderr,/65536/);
787
+ noRun(f);
788
+ });
789
+
790
+ // ---- #31 protected text mode --------------------------------------------------------------------
791
+ const png=Buffer.from('89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c4890000000d4944415478da63f8ffff3f0005fe02fea7d6a4a50000000049454e44ae426082','hex');
792
+ test('#31 protected mode refuses non-UTF-8 develop content before launch',t=>{
793
+ const f=fixture(t,{scope:['Assets/icon.png']});
794
+ fs.writeFileSync(path.join(f.root,'protection.json'),JSON.stringify({checkCommands:[{id:'noop',command:['/usr/bin/true']}],timeoutMs:60000}));
795
+ f.content('icon.png',png);f.develop({'Assets/icon.png':'icon.png'});
796
+ const run=f.drive(f.plan({runtime:'claude',permissions:['--protected-conversation-config','protection.json'],checks:undefined}),'advance',30000);
797
+ assert.equal(run.status,2,run.stderr);
798
+ assert.match(run.stderr,/UTF-8/);assert.match(run.stderr,/Assets\/icon\.png/);
799
+ noRun(f);
800
+ });
801
+ test('#31 protected text edits create new files 0644 and apply an explicit mode; cm-fix proposals keep their shape',async t=>{
802
+ const cwd=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-drive-gaps-edits-')));
803
+ t.after(()=>fs.rmSync(cwd,{recursive:true,force:true}));
804
+ fs.mkdirSync(path.join(cwd,'bin'));fs.writeFileSync(path.join(cwd,'bin','run'),'#!/bin/sh\n');fs.chmodSync(path.join(cwd,'bin','run'),0o644);
805
+ const sha=text=>crypto.createHash('sha256').update(text).digest('hex');
806
+ // The sandbox inherits the caller's umask; a private one must not make new source 0600.
807
+ const umask=process.umask(0o077);
808
+ try{applyProtectedEdits({cwd,scope:['new.txt','bin/run'],edits:[{path:'new.txt',beforeSha256:null,content:'new\n'},
809
+ {path:'bin/run',beforeSha256:sha('#!/bin/sh\n'),content:'#!/bin/sh\n',mode:'0755'}]});}
810
+ finally{process.umask(umask);}
811
+ assert.equal(fs.statSync(path.join(cwd,'new.txt')).mode&0o777,0o644);
812
+ assert.equal(fs.statSync(path.join(cwd,'bin','run')).mode&0o777,0o755);
813
+ assert.throws(()=>applyProtectedEdits({cwd,scope:['new.txt'],edits:[{path:'new.txt',beforeSha256:sha('new\n'),content:'x',mode:'0777'}]}),
814
+ {code:'protected_edit_invalid'});
815
+ assert.throws(()=>applyProtectedEdits({cwd,scope:['new.txt'],edits:[{path:'new.txt',beforeSha256:sha('new\n'),content:null,mode:'0755'}]}),
816
+ {code:'protected_edit_invalid'});
817
+ const bridge={call:async(kind,payload)=>({outcome:'repaired',edits:[{path:'new.txt',beforeSha256:payload.expected['new.txt'],content:'x\n',mode:'0755'}]})};
818
+ const fix=protectedFixBridge({bridge,cwd,specsRoot:path.join(cwd,'specs'),timeoutMs:1000});
819
+ await assert.rejects(fix.call('fix_repair',{codeProject:cwd,scope:['new.txt'],identity:{repositoryId:'r',runId:'fix-run-01',taskId:'T-1',attempt:1},
820
+ instructions:'Repair'},new AbortController().signal),{code:'invalid_input'});
821
+ assert.equal(fs.readFileSync(path.join(cwd,'new.txt'),'utf8'),'new\n');
822
+ });