@aibyzero/cm-workflow 0.16.6 → 0.16.8

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 (90) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +29 -0
  3. package/README.md +32 -1
  4. package/VERSION +1 -1
  5. package/assets/readme/workflow-recovery-detailed.png +0 -0
  6. package/assets/readme/workflow-stages-detailed.png +0 -0
  7. package/docs/installation.md +1 -1
  8. package/docs/js-workflow-control.md +84 -9
  9. package/docs/user-guide.md +104 -0
  10. package/package.json +1 -1
  11. package/runtime/js/cm-ai/cm-ai-admission.mjs +37 -11
  12. package/runtime/js/cm-ai/cm-ai-context-refresh.mjs +9 -5
  13. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +56 -17
  14. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +172 -33
  15. package/runtime/js/cm-ai/codex-review-adapter.mjs +2 -1
  16. package/runtime/js/cm-ai/developer-adapter.mjs +8 -5
  17. package/runtime/js/cm-ai/drive-bootstrap.mjs +2 -2
  18. package/runtime/js/cm-ai/drive-core.mjs +17 -4
  19. package/runtime/js/cm-ai/durable-runner-state.mjs +29 -0
  20. package/runtime/js/cm-ai/execution-store.mjs +4 -2
  21. package/runtime/js/cm-ai/host-conversation-execution.mjs +11 -3
  22. package/runtime/js/cm-ai/host-documentation.mjs +2 -2
  23. package/runtime/js/cm-ai/host-qa-executor.mjs +89 -19
  24. package/runtime/js/cm-ai/host-session.mjs +46 -6
  25. package/runtime/js/cm-ai/host-tool-bridge.mjs +15 -3
  26. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +4 -2
  27. package/runtime/js/cm-ai/log-rows.mjs +36 -0
  28. package/runtime/js/cm-ai/operator-guidance.mjs +3 -0
  29. package/runtime/js/cm-ai/reviewed-deliveries.mjs +29 -6
  30. package/runtime/js/cm-ai/task-runner.mjs +6 -1
  31. package/runtime/js/cm-fix/cause-package.mjs +37 -8
  32. package/runtime/js/cm-fix/diagnosis.mjs +43 -0
  33. package/runtime/js/cm-fix/execution.mjs +189 -148
  34. package/runtime/js/cm-fix/finish.mjs +2 -19
  35. package/runtime/js/cm-fix/investigation.mjs +25 -9
  36. package/runtime/js/cm-fix/log-events.mjs +29 -0
  37. package/runtime/js/cm-fix/metrics.mjs +3 -2
  38. package/runtime/js/cm-fix/progress.mjs +3 -1
  39. package/runtime/js/cm-prd/analysis.mjs +5 -2
  40. package/runtime/js/cm-prd/review-host.mjs +2 -1
  41. package/runtime/js/cm-test/recovery.mjs +4 -4
  42. package/runtime/js/notify-run.mjs +26 -0
  43. package/runtime/js/notify.mjs +388 -0
  44. package/runtime/model-efficiency.md +17 -0
  45. package/scripts/cm-ai-admission.mjs +14 -3
  46. package/scripts/cm-ai-batch-drive.mjs +2 -2
  47. package/scripts/cm-ai-batch-host.mjs +7 -2
  48. package/scripts/cm-ai-batch-run.mjs +11 -2
  49. package/scripts/cm-ai-batch-run.test.mjs +9 -1
  50. package/scripts/cm-ai-drive.mjs +18 -4
  51. package/scripts/cm-ai-drive.test.mjs +30 -0
  52. package/scripts/cm-ai-feature-selection.test.mjs +178 -0
  53. package/scripts/cm-ai-fix-run-delivery.test.mjs +138 -0
  54. package/scripts/cm-ai-host.mjs +20 -8
  55. package/scripts/cm-ai-host.test.mjs +88 -0
  56. package/scripts/cm-ai-project-qa-gate.test.mjs +71 -4
  57. package/scripts/cm-ai-protected-scope.test.mjs +194 -0
  58. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +77 -4
  59. package/scripts/cm-ai-run.mjs +36 -5
  60. package/scripts/cm-fix-abandon.test.mjs +89 -3
  61. package/scripts/cm-fix-cause-package.test.mjs +33 -0
  62. package/scripts/cm-fix-drive.mjs +9 -1
  63. package/scripts/cm-fix-host.mjs +1 -1
  64. package/scripts/cm-fix-large-log.test.mjs +113 -0
  65. package/scripts/cm-fix-rediagnosis.test.mjs +71 -4
  66. package/scripts/cm-host-qa-executor.test.mjs +429 -3
  67. package/scripts/cm-log-event.mjs +53 -6
  68. package/scripts/cm-notify.test.mjs +468 -0
  69. package/scripts/cm-patrol.mjs +83 -0
  70. package/scripts/cm-patrol.test.mjs +161 -0
  71. package/scripts/cm-prd-host.mjs +13 -2
  72. package/scripts/cm-prd-host.test.mjs +4 -0
  73. package/scripts/cm-prd-review-host.test.mjs +17 -0
  74. package/scripts/cm-prd-session-recovery.test.mjs +44 -2
  75. package/scripts/cm-prd-task-grouping.test.mjs +206 -0
  76. package/scripts/cm-review-scope-recovery.test.mjs +5 -3
  77. package/scripts/cm-test-branch-impact.test.mjs +11 -0
  78. package/scripts/cm-token-report.mjs +497 -0
  79. package/scripts/cm-token-report.test.mjs +346 -0
  80. package/skills/cm-ai/SKILL.md +7 -3
  81. package/skills/cm-ai/references/N1-init.md +1 -1
  82. package/skills/cm-ai/references/N6-qa-eval.md +2 -2
  83. package/skills/cm-ai/references/js-host-modes.md +90 -0
  84. package/skills/cm-ai/references/js-host-qa-recovery.md +110 -0
  85. package/skills/cm-ai/references/js-host-recovery.md +199 -0
  86. package/skills/cm-ai/references/js-host.md +69 -330
  87. package/skills/cm-fix/SKILL.md +2 -0
  88. package/skills/cm-fix/references/js-host.md +16 -9
  89. package/skills/cm-prd/SKILL.md +7 -4
  90. package/skills/cm-prd/references/spec-self-check.md +3 -1
@@ -10,7 +10,7 @@ import path from 'node:path';
10
10
  import {spawnSync} from 'node:child_process';
11
11
  import {fileURLToPath} from 'node:url';
12
12
  import {REVIEWED_HANDOFF_HINT} from '../runtime/js/cm-ai/host-handoff.mjs';
13
- import {readRunDefinition,openControlRun,createCodexExecution} from './cm-ai-run.mjs';
13
+ import {readRunDefinition,openControlRun,createCodexExecution,assertCreatableScope} from './cm-ai-run.mjs';
14
14
  import {createConversationExecution as executionFor} from '../runtime/js/cm-ai/host-conversation-execution.mjs';
15
15
  import {createHostToolBridge} from '../runtime/js/cm-ai/host-tool-bridge.mjs';
16
16
  import {serveCmAiHost,parseHostInputLimit,inputLimitReason} from '../runtime/js/cm-ai/host-session.mjs';
@@ -46,12 +46,12 @@ export function readBootstrapConfiguration(file){
46
46
  const refuse=(ok,code,reason)=>{if(!ok)throw Object.assign(new Error(code),{code,reason});};
47
47
  const REASONED_CODES=['supersede_unavailable','supersede_code_drift','handoff_exists','browser_capability_required',
48
48
  'browser_capability_unavailable','invalid_arguments','fingerprint_mismatch','task_selection_mismatch','review_configuration_required',
49
- 'spec_rebind_refused','spec_rebind_unavailable'];
49
+ 'spec_rebind_refused','spec_rebind_unavailable','protected_scope'];
50
50
  const fixLocalPermissions=new Map(['red-test','baseline','regression','learning-writeback','walkthrough','finish','abandon',
51
51
  'abandon-review','test-author','repair','cause-review','final-review']
52
52
  .map(name=>[`--allow-qa-fix-${name}`,`--allow-${name}`]));
53
53
 
54
- const usage='cm-ai-host.mjs serve --config RUN_DEFINITION.json --mode create|resume --host-context ID --allow-development --review-config PATH (required at create; resume passes the same file) [--original-host-context ID] [--runtime codex|claude] [--input-limit BYTES] [--failover] [--allow-review-attempt 1|2] [--allow-abandon-review] [--allow-abandon-effect] [--allow-bootstrap-review-recovery] [--workflow-config PATH] [--allow-qa] [--browser-qa available|unavailable]\nInput limit is transport-only: integer 65536-4194304 bytes, default 65536; it bounds every input line and every tool reply, and may change on resume. A longer line stops the session with request_too_large. Review config is {model,preflight[,disabledSkills][,timeoutMs]}; timeoutMs is the reviewer transport budget in milliseconds (integer 1-3600000, default 900000), independent of protected mode and outside the authorized configuration digest. --browser-qa declares interactive QA capability for applicable carriers including browser and ios-simulator.\nNew runs: --external-models [--external-models-config FILE] freezes one pair per actual external provider; resume reads only its snapshot. preflight --config RUN_DEFINITION.json --external-provider codex|claude uses the saved pair.\ncm-ai-host.mjs preflight --config RUN_DEFINITION.json --review-model MODEL [--runtime codex|claude] (synthetic loopback only)';
54
+ const usage='cm-ai-host.mjs serve --config RUN_DEFINITION.json --mode create|resume --host-context ID --allow-development --review-config PATH (required at create; resume passes the same file) [--original-host-context ID] [--runtime codex|claude] [--review-runtime codex|claude] [--feature N.slug] [--input-limit BYTES] [--failover] [--allow-review-attempt 1|2] [--allow-abandon-review] [--allow-abandon-effect] [--allow-bootstrap-review-recovery] [--workflow-config PATH] [--allow-qa] [--browser-qa available|unavailable]\nInput limit is transport-only: integer 65536-4194304 bytes, default 65536; it bounds every input line and every tool reply, and may change on resume. A longer line stops the session with request_too_large. Review config is {model,preflight[,disabledSkills][,timeoutMs]}; timeoutMs is the reviewer transport budget in milliseconds (integer 1-3600000, default 900000), independent of protected mode and outside the authorized configuration digest. --browser-qa declares interactive QA capability for applicable carriers including browser and ios-simulator.\nNew runs: --external-models [--external-models-config FILE] freezes one pair per actual external provider; resume reads only its snapshot. preflight --config RUN_DEFINITION.json --external-provider codex|claude uses the saved pair.\ncm-ai-host.mjs preflight --config RUN_DEFINITION.json --review-model MODEL [--runtime codex|claude] (synthetic loopback only)';
55
55
 
56
56
  export function formatClaudeModelHint(config,version=null){
57
57
  const marker=config?.preflight?.request_checks?.find(check=>check?.model_recognized===false);
@@ -187,7 +187,7 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
187
187
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('Protected current-session invalid_result means local value/Learning validation failed before file writes. Fix the reply, keep the same configuration, host identity and runId, restart with --mode resume and advance: blocked/developer_result_invalid retries develop at the same attempt. no_new_lesson requires reason:null (dogfood incident: nonempty reason previously wrote files then stranded the run as unknown). Already-applied proposals must match expected disk hashes; conflicts block as protected_edit_stale. Worker exceptions/timeouts and old unknown history are not retryable.\n');
188
188
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('New cm-ai runs carry approved specification data in developer requests and review packages: task/verification, all AC lines, design (64 KiB UTF-8 maximum, truncated:true above it), task-related test cases and manifest hashes. Sources must match .cm-specs-status.specFiles or spec_drift blocks. requirements may be [] or additional code-project files; specs never become writable scope. Legacy runs/packages retain their original representation. Dogfood: separate specs/code roots previously left developers and reviewers without task/interface contracts.\n');
189
189
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('Completed fixture_completed runs originally without QA may explicitly attach N6 once on --mode resume with --workflow-config (non-null qa) and --allow-qa. Original definition, scope, requirements, identity and non-workflow configuration must match. The immutable qa-attached journal record binds the full resumed config fingerprint; later resumes require that same configuration and fresh --allow-qa. qa still requests qa_assess; no automatic decision or repeated development/Review. Dogfood: missing workflow at create previously stranded mandatory feature QA.\n');
190
- if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('--rerun-unknown-qa requires --mode resume and fresh --allow-qa with the original workflow config. Only an unfinished QA invocation whose recorded case results are all PASS and which has no fixed execution report may be abandoned and rerun under a new testRunId at the same qaRound. The abandoned record lists partial_pass_cases; every case is rerun and old PASS evidence is history only. FAIL/BLOCKED results and unclosed resources remain blocked; no complete is fabricated.\n');
190
+ if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('--rerun-unknown-qa requires --mode resume and fresh --allow-qa with the original workflow config. Only an unfinished QA invocation whose recorded case results are all PASS and which has no fixed execution report may be abandoned and rerun under a new testRunId at the same qaRound. The abandoned record lists partial_pass_cases; every case is rerun and old PASS evidence is history only. FAIL/BLOCKED results and unclosed resources remain blocked; no complete is fabricated. Exception: a call stopped as a whole (qa_execution_timeout) with no report and no FAIL, whose every case_blocked is a host request timeout (host_request_timeout: true; an older row without that field needs the full qa.timeoutMs elapsed since case_start plus an operator --qa-environment-failure REASON attesting no session answer, recorded verbatim as legacy_timeout_attestation, otherwise qa_environment_failure_required) and never session-declared, is superseded (reason host_request_timeout) and rerun at qaRound+1; --rerun-blocked-qa on it is refused as qa_rerun_unknown_qa_required.\n');
191
191
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('--rerun-blocked-qa requires --mode resume, the original --workflow-config and fresh --allow-qa. Only the latest completed BLOCKED invocation with zero failures and exclusively host/environment evidence gaps can be superseded: browser evidenceProblem, failed cleanup, environment mismatch, host timeout or a host-declared BLOCKED answer; logic INSUFFICIENT_EVIDENCE or blocked only by a mapped command without exit code; QA commands that produced no exit code (timeout, killed, spawn/output failure). Missing/deferred command rows ([需确认], commands-unavailable, no-applicable-cases, no browser capability) and source drift are excluded. A new testRunId reruns every case at qaRound+1 (maximum 3, the shared QA round budget); superseded and start link previous_test_run_id. The flag is consumed once, never persisted; no development/Review/task replay or new QA decision. Do not combine with --rerun-unknown-qa.\n');
192
192
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('For a QA decision an older host recorded as blocked/host_request_timeout, --rerun-blocked-qa instead re-asks qa_assess once and appends a decision linked by previous_decision_id; history is kept (current hosts report a missed qa_assess window as retryable rejected/qa_decision_timeout and record nothing). --qa-environment-failure REASON (with --rerun-blocked-qa, single line, at most 500 UTF-8 bytes) declares that the non-zero QA command exits of the latest completed FAIL came from the environment: only command exits and logic cases failed solely by them qualify, never browser FAIL or CONTRADICTED; the superseded row records reason, failed_cases and blocked_cases. Every rerun reuses the three-round QA budget. Single-task host only.\n');
193
193
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('--allow-abandon-review: resume 原 run 后发送 abandon_review,request.reason 必须是单行且不超过 500 UTF-8 字节。操作员先确认旧 host 与 review 进程已退出;旗标只消费一次,不写入配置。\n');
@@ -223,7 +223,7 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
223
223
  const extra=new Map();
224
224
  for(let index=8;index<argv.length;index++){
225
225
  const name=argv[index];refuse(!extra.has(name),'invalid_arguments',`参数重复:${name}`);
226
- refuse(['--execution-optimizations','--external-models','--external-models-config','--verification-precheck','--revise-qa-config','--qa-config-revision-reason','--qa-environment-failure','--supersede-reviewed-evidence','--supersede-reason','--accept-superseded-code-drift','--rebind-spec-material','--spec-rebind-reason','--original-host-context','--bootstrap-config','--allow-bootstrap-write','--protected-conversation-config','--protected-config','--allow-provider-development-attempt','--review-config','--allow-review-attempt','--allow-abandon-review','--allow-abandon-effect','--allow-bootstrap-review-recovery','--workflow-config','--allow-qa','--browser-qa','--rerun-unknown-qa','--rerun-blocked-qa','--runtime','--input-limit','--failover','--qa-fix-owner-config','--qa-fix-template-config','--qa-fix-review-config','--allow-qa-fix-start','--auto-qa-fix',...fixLocalPermissions.keys()].includes(name),'invalid_arguments',`未知参数:${name}`);
226
+ refuse(['--execution-optimizations','--external-models','--external-models-config','--verification-precheck','--revise-qa-config','--qa-config-revision-reason','--qa-environment-failure','--supersede-reviewed-evidence','--supersede-reason','--accept-superseded-code-drift','--rebind-spec-material','--spec-rebind-reason','--original-host-context','--bootstrap-config','--allow-bootstrap-write','--protected-conversation-config','--protected-config','--allow-provider-development-attempt','--review-config','--allow-review-attempt','--allow-abandon-review','--allow-abandon-effect','--allow-bootstrap-review-recovery','--workflow-config','--allow-qa','--browser-qa','--rerun-unknown-qa','--rerun-blocked-qa','--runtime','--review-runtime','--feature','--input-limit','--failover','--qa-fix-owner-config','--qa-fix-template-config','--qa-fix-review-config','--allow-qa-fix-start','--auto-qa-fix',...fixLocalPermissions.keys()].includes(name),'invalid_arguments',`未知参数:${name}`);
227
227
  if(['--execution-optimizations','--external-models','--verification-precheck','--supersede-reviewed-evidence','--accept-superseded-code-drift','--rebind-spec-material','--allow-bootstrap-write','--allow-qa','--allow-abandon-review','--allow-abandon-effect','--allow-bootstrap-review-recovery','--rerun-unknown-qa','--rerun-blocked-qa','--failover','--allow-qa-fix-start','--auto-qa-fix',...fixLocalPermissions.keys()].includes(name))extra.set(name,true);
228
228
  else{refuse(typeof argv[index+1]==='string'&&!argv[index+1].startsWith('--'),'invalid_arguments',`${name} 需要一个值`);extra.set(name,argv[++index]);}
229
229
  }
@@ -254,7 +254,7 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
254
254
  workflow===null?'--allow-qa 需要同时提供 --workflow-config':'--allow-qa 需要 --workflow-config 中的 qa 不为 null;本运行没有 QA 时去掉 --allow-qa');
255
255
  need(!(extra.has('--rerun-unknown-qa')&&extra.has('--rerun-blocked-qa')),'qa_recovery_authorization_required');
256
256
  need(!(extra.has('--rerun-unknown-qa')||extra.has('--rerun-blocked-qa'))||(argv[4]==='resume'&&extra.has('--allow-qa')),'qa_recovery_authorization_required');
257
- need(!extra.has('--qa-environment-failure')||extra.has('--rerun-blocked-qa'),'qa_recovery_authorization_required');
257
+ need(!extra.has('--qa-environment-failure')||extra.has('--rerun-blocked-qa')||extra.has('--rerun-unknown-qa'),'qa_recovery_authorization_required');
258
258
  const hasFix=extra.has('--qa-fix-owner-config')||extra.has('--qa-fix-template-config');
259
259
  need(!(extra.has('--qa-fix-owner-config')&&extra.has('--qa-fix-template-config')),'invalid_fix_config');
260
260
  need(!extra.has('--allow-qa-fix-start')||hasFix,'qa_fix_source_required');
@@ -262,13 +262,25 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
262
262
  need(!extra.has('--auto-qa-fix')||(extra.has('--qa-fix-template-config')&&extra.has('--allow-qa-fix-start')),'qa_fix_auto_authorization_required');
263
263
  need(![...fixLocalPermissions.keys()].some(flag=>extra.has(flag))||extra.has('--allow-qa-fix-start'),'qa_fix_start_authorization_required');
264
264
  need(!extra.has('--allow-provider-development-attempt')||extra.has('--protected-config'),'protected_configuration_required');
265
+ refuse(!(extra.has('--review-runtime')&&(extra.has('--protected-config')||extra.has('--external-models'))),'invalid_arguments',
266
+ '--review-runtime 只用于普通当前会话宿主;--protected-config 与 --external-models 按 roles 自行选择审查端');
265
267
  refuse(!(extra.has('--protected-config')&&extra.has('--protected-conversation-config')),'invalid_arguments','--protected-config 与 --protected-conversation-config 不能同时使用');
266
268
  const protection=extra.has('--protected-conversation-config')?readConversationProtection(extra.get('--protected-conversation-config')):null;
267
269
  const bootstrap=extra.has('--bootstrap-config')?readBootstrapConfiguration(extra.get('--bootstrap-config')):null;
268
270
  need(!extra.has('--allow-bootstrap-write')||bootstrap!==null,'bootstrap_configuration_required');
269
271
  // Checked before the definition is read so the conflict is reported on its own.
270
272
  need(!(extra.has('--failover')&&extra.has('--protected-config')),'failover_unsupported_in_protected_mode');
271
- const definition=readRunDefinition(argv[2]);
273
+ let definition=readRunDefinition(argv[2]);
274
+ // --feature binds an explicit batch choice into the run definition, exactly
275
+ // as a printed featureSelection does; resume must repeat it (fingerprint).
276
+ if(extra.has('--feature')){
277
+ refuse(extra.get('--feature')===definition.feature&&(!definition.featureSelection
278
+ ||definition.featureSelection.feature===definition.feature),'invalid_arguments',
279
+ `--feature ${extra.get('--feature')} 必须与运行定义的 feature ${definition.feature} 一致`);
280
+ definition={...definition,featureSelection:{version:1,feature:definition.feature}};
281
+ }
282
+ // Before any frozen model/policy configuration, execution or journal write.
283
+ if(argv[4]==='create'&&bootstrap===null)assertCreatableScope(definition.scope);
272
284
  const boundRuntime=extra.get('--runtime')??'codex';
273
285
  const routes=extra.has('--protected-config')?resolveProtectedRuntimes(loadConfig({projectRoot:definition.codeProject}),boundRuntime):{reviewerRuntime:boundRuntime};
274
286
  const executionPolicy=readLaunchExecutionPolicy({definition,mode:argv[4],enabled:extra.has('--execution-optimizations')});
@@ -329,7 +341,7 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
329
341
  execution=extra.has('--protected-config')
330
342
  ?await protectedExecutionFor(definition,argv[6],extra,review,argv[4],workflow,bridge,bootstrap,externalModels,executionPolicy)
331
343
  :executionFor(definition,argv[6],bridge,review,allowedAttempt,workflow,extra.has('--allow-qa'),runtime,
332
- {...(executionPolicy?{executionPolicy}:{}),...(externalModels?{externalModels}:{}),...(extra.has('--verification-precheck')?{verificationPrecheck:true}:{}),...(extra.has('--original-host-context')?{originalHostContextId:extra.get('--original-host-context')}:{}),...(protection?{protection}:{}),...(bootstrap?{bootstrap:{...bootstrap,allowWrite:extra.has('--allow-bootstrap-write')}}:{})});
344
+ {...(extra.has('--review-runtime')?{reviewRuntime:extra.get('--review-runtime')}:{}),...(executionPolicy?{executionPolicy}:{}),...(externalModels?{externalModels}:{}),...(extra.has('--verification-precheck')?{verificationPrecheck:true}:{}),...(extra.has('--original-host-context')?{originalHostContextId:extra.get('--original-host-context')}:{}),...(protection?{protection}:{}),...(bootstrap?{bootstrap:{...bootstrap,allowWrite:extra.has('--allow-bootstrap-write')}}:{})});
333
345
  run=await openControlRun(definition,argv[4],execution,{qaConfigRevision,rerunUnknownQa:extra.has('--rerun-unknown-qa'),rerunBlockedQa:extra.has('--rerun-blocked-qa'),qaEnvironmentFailure:extra.get('--qa-environment-failure')??null,supersedeReason:extra.get('--supersede-reason')??null,acceptSupersededCodeDrift:extra.has('--accept-superseded-code-drift'),allowAbandonReview:extra.has('--allow-abandon-review'),allowAbandonEffect:extra.has('--allow-abandon-effect'),allowBootstrapReviewRecovery:extra.has('--allow-bootstrap-review-recovery'),specRebindReason:extra.get('--spec-rebind-reason')??null});
334
346
  }
335
347
  if(run.blocked){output.write(JSON.stringify({outcome:'blocked',admission:run.blocked})+'\n');return 1;}
@@ -184,6 +184,23 @@ test('host create reports the offending unsupported file on stderr before transp
184
184
  }finally{fs.rmSync(f.root,{recursive:true,force:true});}
185
185
  });
186
186
 
187
+ test('host create refuses a scope with AGENTS.md and lists the protected paths before any journal exists',async()=>{
188
+ const f=fixture(),lines=[],output=[];
189
+ try{
190
+ const definition=JSON.parse(fs.readFileSync(f.config,'utf8'));
191
+ fs.writeFileSync(f.config,JSON.stringify({...definition,scope:['target.mjs','AGENTS.md','.claude/rules/security.md']}));
192
+ fs.writeFileSync(path.join(f.codeProject,'AGENTS.md'),'# rules\n');
193
+ const exit=await hostMain(launchArgs(f),{input:{},output:{write(value){output.push(value);}},error:{write(value){lines.push(value);}}});
194
+ assert.equal(exit,1);assert.deepEqual(output,[]);
195
+ const error=JSON.parse(lines.join('').trim().split('\n').at(-1)).error;
196
+ assert.equal(error.code,'protected_scope');
197
+ assert.match(error.reason,/AGENTS\.md、\.claude\/rules\/security\.md/);
198
+ assert.doesNotMatch(error.reason,/target\.mjs/);
199
+ // No init, no intent, no execution directory, no review record of any kind.
200
+ assert.equal(fs.existsSync(path.join(f.specsDir,'.reviews')),false);
201
+ }finally{fs.rmSync(f.root,{recursive:true,force:true});}
202
+ });
203
+
187
204
  function runCli(f,mode,action='create'){
188
205
  return new Promise((resolve,reject)=>{
189
206
  const args=[...launchArgs(f)];args[4]=action;
@@ -1250,3 +1267,74 @@ test('#11 #31 protected driver deletes, sets the executable bit, creates new fil
1250
1267
  assert.equal(changes.get('new/Legacy.swift').after.mode,0o644);
1251
1268
  }finally{fs.rmSync(f.root,{recursive:true,force:true});}
1252
1269
  });
1270
+
1271
+ // Explicit batch choice (2026-10-06 AI潮 6.api-native-reading before 5.author-column).
1272
+ const withEarlierPendingFeature=f=>{
1273
+ const early=path.join(f.specsDir,'0.early');fs.mkdirSync(early);
1274
+ for(const name of ['requirements.md','design.md'])fs.writeFileSync(path.join(early,name),'# Early\n');
1275
+ fs.writeFileSync(path.join(early,'tasks.md'),'- [ ] T-001: earlier batch, after this one\n');
1276
+ fs.writeFileSync(path.join(f.specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:['0.early','1.work'],specFiles:buildManifest(f.specsDir)}));
1277
+ };
1278
+ const serveOnce=(f,extra,mode='create')=>{
1279
+ const args=[...launchArgs(f)];args[4]=mode;
1280
+ const out=spawnSync(process.execPath,[cli,...args,...extra],{encoding:'utf8',timeout:20000,
1281
+ input:[request('status')].map(JSON.stringify).join('\n')+'\n'});
1282
+ return {...out,rows:out.stdout.trim().split('\n').filter(Boolean).map(JSON.parse)};
1283
+ };
1284
+ test('host --feature creates a later approved feature run; without it the original task_selection_mismatch stays',()=>{
1285
+ const f=fixture();
1286
+ try{
1287
+ withEarlierPendingFeature(f);
1288
+ const refused=serveOnce(f,[]);
1289
+ assert.equal(refused.status,1);assert.match(refused.stderr,/task_selection_mismatch/);assert.match(refused.stderr,/--feature 1\.work/);
1290
+ const wrong=serveOnce(f,['--feature','0.early']);
1291
+ assert.equal(wrong.status,1);assert.match(wrong.stderr,/invalid_arguments/);
1292
+ assert.equal(fs.existsSync(path.join(f.specsDir,'.reviews','.execution',identity.runId)),false);
1293
+ const created=serveOnce(f,['--feature','1.work']);
1294
+ assert.equal(created.status,0,created.stderr);
1295
+ assert.equal(created.rows[0].type,'host_ready');
1296
+ assert.equal(created.rows.find(row=>row.requestId==='status').result.identity.taskId,'T-001');
1297
+ const resumed=serveOnce(f,['--feature','1.work'],'resume');
1298
+ assert.equal(resumed.status,0,resumed.stderr);assert.equal(resumed.rows[0].type,'host_ready');
1299
+ // The choice is bound into the run: resuming without it is a different run.
1300
+ const unbound=serveOnce(f,[],'resume');
1301
+ assert.equal(unbound.status,1);assert.match(unbound.stderr,/fingerprint_mismatch/);
1302
+ assert.match(fs.readFileSync(path.join(f.specsDir,'0.early','tasks.md'),'utf8'),/- \[ \] T-001/);
1303
+ }finally{fs.rmSync(f.root,{recursive:true,force:true});}
1304
+ });
1305
+
1306
+ // Kept from the 0.16.6 project patch: runs T-001..T-003 of that batch were
1307
+ // created with --runtime codex --review-runtime claude and resume only with it.
1308
+ const crossToolRoles='version: 1\nruntimes: {available: both}\nroles:\n coder: {adapter: codex-cli, source: subscription}\n reviewer: {adapter: claude-cli, source: subscription}\n';
1309
+ test('--review-runtime binds the other tool as reviewer and must be repeated on resume',async()=>{
1310
+ const f=fixture(),bridge=createHostToolBridge();
1311
+ try{
1312
+ fs.writeFileSync(path.join(f.codeProject,'.cm-workflow.yml'),crossToolRoles);
1313
+ const definition=readRunDefinition(f.config);
1314
+ const {claudeReviewFingerprint}=await import('../runtime/js/cm-ai/worker-claude.mjs');
1315
+ const model='fixture';const review={model,disabledSkills:[],preflight:{passed:true,provider:'claude',
1316
+ config_fingerprint:claudeReviewFingerprint({cwd:f.codeProject,model}),prompt_transport:'stdin'}};
1317
+ const make=options=>createConversationExecution(definition,'native-host-fixture',bridge,review,null,null,false,'codex',options);
1318
+ const original=make({reviewRuntime:'claude'});
1319
+ assert.equal(original.developer.provider,'codex');assert.equal(original.reviewers[0].provider,'claude');
1320
+ assert.equal(original.configuration.reviewRuntime,'claude');
1321
+ const first=await openControlRun(definition,'create',original);first.close();
1322
+ const resumed=await openControlRun(definition,'resume',make({reviewRuntime:'claude'}));resumed.close();
1323
+ await assert.rejects(openControlRun(definition,'resume',make({})),{code:'fingerprint_mismatch'});
1324
+ assert.throws(()=>make({reviewRuntime:'codex'}),{code:'runtime_selection_mismatch'});
1325
+ assert.throws(()=>make({reviewRuntime:'other'}),{code:'invalid_runtime'});
1326
+ assert.throws(()=>createConversationExecution(definition,'native-host-fixture',bridge,{...review,preflight:{}},1,null,false,'codex',{reviewRuntime:'claude'}),{code:'tool_preflight_missing'});
1327
+ }finally{bridge.close();fs.rmSync(f.root,{recursive:true,force:true});}
1328
+ });
1329
+ test('ordinary CLI accepts --review-runtime claude under a Codex host and refuses an invalid runtime before any journal',()=>{
1330
+ for(const reviewRuntime of ['claude','other']){
1331
+ const f=fixture();
1332
+ try{
1333
+ fs.writeFileSync(path.join(f.codeProject,'.cm-workflow.yml'),crossToolRoles);
1334
+ const out=serveOnce(f,['--runtime','codex','--review-runtime',reviewRuntime]);
1335
+ if(reviewRuntime==='claude'){assert.equal(out.status,0,out.stderr);assert.equal(out.rows[0].type,'host_ready');}
1336
+ else{assert.equal(out.status,1);assert.match(out.stderr,/invalid_runtime/);
1337
+ assert.equal(fs.existsSync(path.join(f.specsDir,'.reviews','.execution',identity.runId)),false);}
1338
+ }finally{fs.rmSync(f.root,{recursive:true,force:true});}
1339
+ }
1340
+ });
@@ -5,6 +5,7 @@ import assert from 'node:assert/strict';
5
5
  import fs from 'node:fs';
6
6
  import os from 'node:os';
7
7
  import path from 'node:path';
8
+ import {fileURLToPath,pathToFileURL} from 'node:url';
8
9
  import {buildManifest} from './cm-spec-manifest.mjs';
9
10
  import {openControlRun} from './cm-ai-run.mjs';
10
11
  import {createCodexDeveloperRun} from '../runtime/js/cm-ai/codex-developer-adapter.mjs';
@@ -48,7 +49,7 @@ function project(){
48
49
  const state={browserUp:false,documentation:0,reviews:new Map()};
49
50
  const logHome=path.join(specsDir,'.reviews','host-log-mirror');
50
51
  const environment={kind:'web',carrier:'browser',target:'fixture',scope:'local'};
51
- const execution=(feature,{write,retrospective=noLesson,verdict=()=>'approved',decision=null})=>({
52
+ const execution=(feature,{write,retrospective=noLesson,verdict=()=>'approved',decision=null,browser=null,createExecutor=createHostQaExecutor})=>({
52
53
  configuration:{kind:'synthetic-host-v1',hostContextId:'control',workflow:{qa:{commands:[],environment},documentationPaths:[],applicableAgentFiles:[]}},
53
54
  timeoutMs:5000,excludedContexts:['control'],
54
55
  developer:{provider:'codex',requestedModel:'fixture',contextId:'developer',run:createCodexDeveloperRun({requestedModel:'fixture',worker:async()=>{
@@ -75,12 +76,12 @@ function project(){
75
76
  status:'completed',reason:'Documentation checked',at:'2026-09-28T00:00:00Z'};}},
76
77
  qaDecisionProvider:{timeoutMs:1000,decide:async binding=>({decisionId:`qa-${binding.identity.runId}`,identity:binding.identity,
77
78
  packageDigest:binding.packageDigest,status:'triggered',reason:'feature_complete',score:null,at:'2026-09-28T00:00:00Z',...decision})},
78
- qaExecutor:createHostQaExecutor({specsDir,codeProject,feature,requirements:['requirements.md'],runtime:'codex',
79
+ qaExecutor:createExecutor({specsDir,codeProject,feature,requirements:['requirements.md'],runtime:'codex',
79
80
  commands:[{id:'unit',command:[process.execPath,'--check','a.mjs'],caseIds:[]}],environment,timeoutMs:60000,logHome,
80
- browser:async browserRequest=>{
81
+ browser:browser??(async browserRequest=>{
81
82
  if(!state.browserUp)return {verdict:'BLOCKED',evidence:[],environment:browserRequest.environment,cleanup:'failed'};
82
83
  const shot=path.join(specsDir,'.reviews','tc-001.txt');fs.writeFileSync(shot,'observed');
83
- return {verdict:'PASS',evidence:[shot],environment:browserRequest.environment,cleanup:'not_needed'};}})});
84
+ return {verdict:'PASS',evidence:[shot],environment:browserRequest.environment,cleanup:'not_needed'};})})});
84
85
  const definition=(feature,taskId,scope)=>({version:1,specsDir,codeProject,feature,
85
86
  identity:{repositoryId:'gate-fixture',runId:`run-${taskId}`,taskId,attempt:1},scope,requirements:['requirements.md']});
86
87
  const advance=async(def,exec,mode,options)=>{
@@ -137,6 +138,72 @@ test('#17 an earlier feature whose QA is BLOCKED keeps the project from run_done
137
138
  assert.equal(status(p).state,'run_done');
138
139
  });
139
140
 
141
+ // The executor as released before dropped-task cases were left out: the current
142
+ // module with that one rule neutralized, imported from a temporary copy.
143
+ async function releasedQaExecutor(){
144
+ const source=fileURLToPath(new URL('../runtime/js/cm-ai/host-qa-executor.mjs',import.meta.url));
145
+ const rule='const dropped=new Set(context.dropped);',text=fs.readFileSync(source,'utf8');
146
+ assert.equal(text.split(rule).length,2,'the dropped-task rule is where this fixture expects it');
147
+ const base=pathToFileURL(path.dirname(source)+path.sep).href;
148
+ const released=text.replace(rule,'const dropped=new Set();')
149
+ .replace(/'\.\.\/\.\.\/\.\.\//g,`'${new URL('../../../',base).href}`).replace(/from '\.\//g,`from '${base}`);
150
+ const file=path.join(fs.mkdtempSync(path.join(isolated,'released-')),'host-qa-executor.mjs');fs.writeFileSync(file,released);
151
+ return (await import(pathToFileURL(file).href)).createHostQaExecutor;
152
+ }
153
+
154
+ // 2026-10-08 aihot: 5.author-column's feature-completion QA (run author-column-T-010) asked the
155
+ // session about cases bound only to [DROPPED] tasks; they stayed BLOCKED and the project gate then
156
+ // held api-native-reading-T-008's finish. Recovery: --rerun-blocked-qa on the original run, then resume.
157
+ test('#17 an earlier BLOCKED round over dropped-task cases is recovered on its original run; the later run then finishes',async()=>{
158
+ const p=project();
159
+ const feature=path.join(p.specsDir,'1.work'),log=path.join(p.specsDir,'运行日志.jsonl');
160
+ const rows=()=>fs.readFileSync(log,'utf8').trim().split('\n').map(JSON.parse);
161
+ const contract=JSON.parse(fs.readFileSync(path.join(feature,'test-cases.json')));
162
+ // TC-001 is the live task's case; TC-002 (non-blocking browser) and TC-003 (blocking logic) are bound only to dropped T-001.
163
+ contract.cases.push({...contract.cases[0],id:'TC-002',blocking:false,taskIds:['T-001']},
164
+ {...contract.cases[0],id:'TC-003',kind:'logic',taskIds:['T-001']});
165
+ fs.writeFileSync(path.join(feature,'test-cases.json'),JSON.stringify(contract));
166
+ fs.writeFileSync(path.join(feature,'tasks.md'),'- [ ] ~~T-001: column work~~ `[DROPPED v2: 数据源未定,暂缓]`\n- [ ] T-002: fixture\n');
167
+ p.reapprove();
168
+ const asked=[];
169
+ const firstExecution=createExecutor=>p.execution('1.work',{createExecutor,
170
+ write:()=>fs.writeFileSync(path.join(p.codeProject,'a.mjs'),'export const a=1;\n'),
171
+ browser:async request=>{
172
+ asked.push(request.case.id);
173
+ // The feature is hidden: the session can only answer BLOCKED for the dropped task's case.
174
+ if(request.case.id!=='TC-001')return {verdict:'BLOCKED',evidence:[],environment:request.environment,cleanup:'not_needed'};
175
+ const shot=path.join(p.specsDir,'.reviews',`${request.case.id}-${asked.length}.txt`);fs.writeFileSync(shot,'observed');
176
+ return {verdict:'PASS',evidence:[shot],environment:request.environment,cleanup:'not_needed'};}});
177
+ const blocked=await p.advance(p.first,firstExecution(await releasedQaExecutor()),'create');
178
+ assert.equal(blocked.code,'qa_result_blocked',JSON.stringify(blocked));assert.deepEqual(asked,['TC-001','TC-002']);
179
+ const oldComplete=rows().find(row=>row.phase==='complete'&&row.run_id==='run-T-002');
180
+ assert.deepEqual([oldComplete.result,oldComplete.case_count,oldComplete.passed,oldComplete.blocked],['BLOCKED',4,2,2]);
181
+ // The recorded round is not reinterpreted: the project gate still reads it as BLOCKED.
182
+ const last=p.definition('2.next','T-003',['b.mjs']);
183
+ const lastExecution=()=>p.execution('2.next',{write:()=>fs.writeFileSync(path.join(p.codeProject,'b.mjs'),'export const b=1;\n')});
184
+ const refused=await p.advance(last,lastExecution(),'create');
185
+ assert.equal(refused.code,'project_qa_not_passed',JSON.stringify(refused));
186
+ assert.deepEqual(refused.outstandingQa,[{feature:'1.work',runId:'run-T-002',taskId:'T-002',attempt:1,status:'qa_blocked'}]);
187
+ const history=fs.readFileSync(log,'utf8'),oldReport=fs.readFileSync(oldComplete.report);
188
+ // Its BLOCKED cases (a session BLOCKED answer, a logic case without a host) are rerun-eligible.
189
+ const recovered=await p.advance(p.first,firstExecution(),'resume',{rerunBlockedQa:true});
190
+ assert.equal(recovered.code,'run_done',JSON.stringify(recovered));
191
+ assert.deepEqual(asked,['TC-001','TC-002','TC-001'],'the dropped task case is never asked again');
192
+ assert(fs.readFileSync(log,'utf8').startsWith(history));assert.deepEqual(fs.readFileSync(oldComplete.report),oldReport);
193
+ const superseded=rows().find(row=>row.phase==='superseded');
194
+ assert.equal(superseded.previous_test_run_id,oldComplete.operation_id);assert.deepEqual(superseded.blocked_cases,['TC-002','TC-003']);
195
+ const start=rows().filter(row=>row.phase==='start'&&row.run_id==='run-T-002').at(-1);
196
+ assert.equal(start.attempt,2);assert.equal(start.previous_test_run_id,oldComplete.operation_id);
197
+ assert.deepEqual(start.dropped_task_cases,[{id:'TC-002',taskIds:['T-001']},{id:'TC-003',taskIds:['T-001']}]);
198
+ const complete=rows().filter(row=>row.phase==='complete'&&row.run_id==='run-T-002').at(-1);
199
+ assert.deepEqual([complete.result,complete.case_count,complete.passed],['PASS',2,2]);
200
+ const notApplicable=fs.readFileSync(complete.report,'utf8').split(/^## /m).find(part=>part.startsWith('not_applicable\n'));
201
+ assert.deepEqual(JSON.parse(notApplicable.slice('not_applicable\n'.length)).map(item=>[item.id,item.verdict,item.reason]),
202
+ [['TC-002','NOT_APPLICABLE','bound only to dropped tasks: T-001'],['TC-003','NOT_APPLICABLE','bound only to dropped tasks: T-001']]);
203
+ const finished=await p.advance(last,lastExecution(),'resume');
204
+ assert.equal(finished.code,'run_done',JSON.stringify(finished));assert.equal(status(p).state,'run_done');
205
+ });
206
+
140
207
  test('#18 unreviewed tampering with the earlier task file still requires correction review and names the file',async()=>{
141
208
  const p=project();
142
209
  await p.advance(p.first,p.firstExecution(),'create');
@@ -0,0 +1,194 @@
1
+ // A task scope with project rules or workflow evidence (AGENTS.md, .claude/,
2
+ // tasks.md, .cm-*) can never be developed: the developer adapter refuses it
3
+ // before any provider runs. Regression for the 2026-10-06 dogfood T-006 run,
4
+ // which a pre-gate host stranded at unknown/execution_error with no exit.
5
+ import nodeTest from 'node:test';
6
+ import assert from 'node:assert/strict';
7
+ import fs from 'node:fs';
8
+ import os from 'node:os';
9
+ import path from 'node:path';
10
+ import {digest,requestFor} from '../runtime/js/cm-ai/effect-contract.mjs';
11
+ import {protectedScopePaths,validateDeveloperScope} from '../runtime/js/cm-ai/developer-adapter.mjs';
12
+ import {readRunnerHistory,runnerStatus} from '../runtime/js/cm-ai/durable-runner-state.mjs';
13
+ import {assertNoUnrecordedPriorCode,prepareReviewedEvidenceSupersession} from '../runtime/js/cm-ai/reviewed-evidence-supersede.mjs';
14
+ import {assertCreatableScope,openControlRun,validateRunDefinition} from './cm-ai-run.mjs';
15
+ import {createCmAiBatch} from './cm-ai-batch-run.mjs';
16
+ import {operatorGuidance} from '../runtime/js/cm-ai/operator-guidance.mjs';
17
+ import {isSupportedExecutionPlatform} from '../runtime/js/cm-ai/execution-platform.mjs';
18
+
19
+ const skip=!isSupportedExecutionPlatform();
20
+ const test=(name,fn)=>nodeTest(name,{skip},fn);
21
+ const PROTECTED=['AGENTS.md','.claude/rules/security.md'];
22
+ // The T-006 production shape: a task-learning (V3) run of a numbered feature.
23
+ const FEATURE='6.api-native-reading';
24
+
25
+ test('protected scope paths are listed by the same rule the developer adapter enforces',()=>{
26
+ const scope=['src/app.js',...PROTECTED,'docs/CLAUDE.md','specs/tasks.md','.cm-workflow.yml','.codex/config.toml'];
27
+ assert.deepEqual(protectedScopePaths(scope),[...PROTECTED,'docs/CLAUDE.md','specs/tasks.md','.cm-workflow.yml','.codex/config.toml']);
28
+ assert.deepEqual(protectedScopePaths(['src/app.js','docs/agents-guide.md']),[]);
29
+ for(const file of protectedScopePaths(scope))assert.throws(()=>validateDeveloperScope(['src/app.js',file]),{code:'protected_scope'});
30
+ assert.doesNotThrow(()=>validateDeveloperScope(['src/app.js','docs/agents-guide.md']));
31
+ });
32
+
33
+ function projectFixture(t){
34
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-protected-create-')));
35
+ t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
36
+ const specsDir=path.join(root,'specs'),codeProject=path.join(root,'code');
37
+ fs.mkdirSync(path.join(specsDir,FEATURE),{recursive:true});fs.mkdirSync(codeProject);
38
+ fs.writeFileSync(path.join(specsDir,FEATURE,'tasks.md'),'- [ ] T-006: fixture\n');
39
+ fs.writeFileSync(path.join(codeProject,'AGENTS.md'),'# rules\n');
40
+ return {root,specsDir,codeProject};
41
+ }
42
+ const reviewsAbsent=f=>assert.equal(fs.existsSync(path.join(f.specsDir,'.reviews')),false,'a refused create must leave no .reviews/.execution');
43
+
44
+ test('create refuses a scope with AGENTS.md before any journal, listing only the protected paths',async t=>{
45
+ const f=projectFixture(t);
46
+ const definition=validateRunDefinition({version:1,specsDir:f.specsDir,codeProject:f.codeProject,feature:FEATURE,
47
+ identity:{repositoryId:'fixture',runId:'api-native-reading-T-006',taskId:'T-006',attempt:1},
48
+ scope:['src/app.js',...PROTECTED],requirements:[]});
49
+ assert.throws(()=>assertCreatableScope(definition.scope),error=>error.code==='protected_scope'
50
+ &&error.paths.join()===PROTECTED.join()&&error.reason.includes('AGENTS.md、.claude/rules/security.md')&&!error.reason.includes('src/app.js'));
51
+ await assert.rejects(openControlRun(definition,'create'),error=>error.code==='protected_scope'&&error.reason.includes('AGENTS.md'));
52
+ reviewsAbsent(f);
53
+ assert.doesNotThrow(()=>assertCreatableScope(['src/app.js','docs/agents-guide.md']));
54
+ });
55
+
56
+ test('a batch refuses a member to be created with a protected scope before it locks, logs or opens any run',t=>{
57
+ const f=projectFixture(t);let opened=0;
58
+ const configuration={version:1,repositoryId:'fixture',batchId:'protected-scope-batch',specsDir:f.specsDir,codeProject:f.codeProject,
59
+ tasks:[{feature:FEATURE,taskId:'T-005',scope:['src/app.js'],requirements:[]},
60
+ {feature:FEATURE,taskId:'T-006',scope:['src/tab.js',...PROTECTED],requirements:[]}]};
61
+ assert.throws(()=>createCmAiBatch({configuration,executionFor:async()=>{opened++;return {};},logHome:path.join(f.root,'logs')}),
62
+ error=>error.code==='protected_scope'&&error.reason.startsWith(`${FEATURE}/T-006: `)&&error.reason.includes('.claude/rules/security.md'));
63
+ assert.equal(opened,0);reviewsAbsent(f);
64
+ assert.equal(fs.existsSync(path.join(f.specsDir,'运行日志.jsonl')),false);assert.equal(fs.existsSync(path.join(f.root,'logs')),false);
65
+ // A bootstrap rule task keeps its own instruction targets (host-bootstrap checks its business scope).
66
+ assert.doesNotThrow(()=>createCmAiBatch({configuration,executionFor:async()=>({}),logHome:path.join(f.root,'logs'),
67
+ bootstrapKeys:[`${FEATURE}/T-006`]}));
68
+ });
69
+
70
+ async function runnerFixture(t,scope){
71
+ const {createTaskRunner}=await import('../runtime/js/cm-ai/task-runner.mjs');
72
+ const {openTaskExecutionStore}=await import('../runtime/js/cm-ai/task-owner.mjs');
73
+ const temp=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-protected-scope-')));
74
+ const root=path.join(temp,'code'),specsRoot=path.join(temp,'specs'),reviewsDir=path.join(specsRoot,'.reviews');
75
+ fs.mkdirSync(path.join(root,'.claude','rules'),{recursive:true});fs.mkdirSync(reviewsDir,{recursive:true});
76
+ fs.mkdirSync(path.join(specsRoot,FEATURE));
77
+ const tasksPath=path.join(specsRoot,FEATURE,'tasks.md');fs.writeFileSync(tasksPath,'- [ ] T-006: fixture\n');
78
+ for(const [file,content] of Object.entries({'code.js':'old\n','requirements.md':'fixture\n','AGENTS.md':'# rules\n',
79
+ '.claude/rules/security.md':'# security\n'}))fs.writeFileSync(path.join(root,file),content);
80
+ const identity={repositoryId:'fixture',runId:'api-native-reading-T-006',taskId:'T-006',attempt:1};
81
+ const owner={tasksPath,feature:'api-native-reading',specsRoot,identity:{repositoryId:identity.repositoryId,runId:identity.runId},
82
+ fingerprints:{workflow:digest('protected-scope'),config:digest('fixture'),inputs:digest('original')},create:true};
83
+ let store=openTaskExecutionStore(owner),developerCalls=0,developerRun=()=>{throw new Error('developer must not run');};
84
+ const options={root,identity,scope,requirements:['requirements.md'],excludedContexts:['main'],timeoutMs:1000,
85
+ developer:{provider:'claude',requestedModel:'current-session',contextId:'cm-conversation-author',
86
+ run:(...args)=>{developerCalls++;return developerRun(...args);}},
87
+ reviewers:[{id:'reviewer',adapterId:'claude-review-adapter',provider:'claude',requestedModel:'fixture',allowed:true,
88
+ available:true,contexts:['review-1','review-2'],run:()=>{throw new Error('reviewer must not run');}}],
89
+ check:()=>{throw new Error('checks must not run');},
90
+ taskCompletion:{reviewsDir,handoffs:[1,2].map(n=>path.join(reviewsDir,`api-native-reading-T-006-a${n}-handoff.json`))},
91
+ taskLearning:{feature:FEATURE,hostHandoff:true},
92
+ reviewInvocation:{developerThreadId:'actual-developer',excludedThreadIds:['actual-main'],
93
+ authorize:()=>{throw new Error('review must not be authorized');}}};
94
+ const make=mode=>createTaskRunner({...options,persistence:{store,mode,version:3}});
95
+ const statePath=path.join(reviewsDir,'.execution',identity.runId,'state.json');
96
+ const reopen=()=>{store.close();store=openTaskExecutionStore({...owner,create:false});return make('resume');};
97
+ t.after(()=>{store.close();fs.rmSync(temp,{recursive:true,force:true});});
98
+ const files=[{scope:'project',path:'AGENTS.md',sha256:digest('agents')}];
99
+ const learningInput={version:1,workflow:'cm-ai',phase:'task_learning_input',feature:FEATURE,identity,
100
+ learningDigest:digest({version:1,feature:FEATURE,identity,files}),learningFiles:files};
101
+ const develop=(id='develop-1')=>({version:1,id,identity,kind:'develop',learningInput});
102
+ return {identity,options,statePath,root,specsRoot,tasksPath,develop,make:()=>make('create'),resume:()=>make('resume'),reopen,records:()=>store.snapshot().records,
103
+ developerCalls:()=>developerCalls,setDeveloper:fn=>{developerRun=fn;},close:()=>store.close(),
104
+ reopenStore:()=>{store=openTaskExecutionStore({...owner,create:false});}};
105
+ }
106
+ function rechain(records){
107
+ let previousDigest=null;
108
+ for(const row of records){row.previousDigest=previousDigest;const {digest:old,...body}=row;row.digest=digest(body);previousDigest=row.digest;}
109
+ return records;
110
+ }
111
+
112
+ test('a protected scope blocks before dispatch as a definite blocked/protected_scope, never unknown',async t=>{
113
+ const f=await runnerFixture(t,['code.js',...PROTECTED]);
114
+ const result=await f.make().executeEffect(f.develop());
115
+ assert.equal(result.state,'blocked');assert.equal(result.code,'protected_scope');
116
+ for(const file of PROTECTED)assert(result.reason.includes(file),result.reason);
117
+ assert.equal(f.developerCalls(),0);assert.deepEqual(result.calls,[]);
118
+ assert.deepEqual(f.records().map(row=>row.payload.type),['init','effect-intent','effect-checkpoint']);
119
+ // The block replays as recorded, is terminal, and a later develop is refused without dispatch.
120
+ const resumed=f.reopen();
121
+ assert.equal(resumed.status().state,'blocked');assert.equal(resumed.status().code,'protected_scope');
122
+ const retry=await resumed.executeEffect(f.develop('develop-2'));
123
+ assert.equal(retry.outcome,'rejected');assert.equal(retry.code,'stage_mismatch');assert.equal(f.developerCalls(),0);
124
+ const guidance=operatorGuidance({workflow:'cm-ai',identity:f.identity,state:'blocked',code:'protected_scope',pendingAction:'none'});
125
+ assert.equal(guidance.recoveryOperation,null);assert.match(guidance.nextStep,/新 runId/);
126
+ });
127
+
128
+ // Rewrite the new checkpoint into the exact shape a pre-gate host journaled for
129
+ // T-006: the adapter's refusal escaped as unknown/execution_error with one
130
+ // started developer call that never returned (state.json of 2026-10-05).
131
+ function strandLikeT006(f){
132
+ const state=JSON.parse(fs.readFileSync(f.statePath,'utf8')),records=state.records;
133
+ const init=records[0].payload,intent=records[1].payload.effect,last=records[2];
134
+ const session=init.session,original=init.baseline,config=init.config;
135
+ const request=requestFor({invocationId:`${session}.1`,identity:{...config.identity,attempt:1},role:'developer',
136
+ provider:config.developer.provider,requestedModel:config.developer.requestedModel,contextId:config.developer.contextId,
137
+ payload:{scope:config.scope,requirements:original.files.filter(file=>config.requirements.includes(file.path)),priorReview:null,
138
+ learningInput:intent.learningInput}});
139
+ const call={invocationId:request.invocationId,contextId:config.developer.contextId,provider:config.developer.provider,
140
+ requestedModel:config.developer.requestedModel,effectiveModel:'unknown',channel:'fixture',started:true,terminal:'unknown',
141
+ requestDigest:request.requestDigest,resultDigest:null};
142
+ const checkpoint={...last.payload.checkpoint,state:'unknown',code:'execution_error',reason:null,sequence:1,calls:[call]};
143
+ checkpoint.cache=[{effect:intent,digest:digest(intent),result:runnerStatus(checkpoint,config)}];
144
+ records[2]={...last,payload:{...last.payload,checkpoint}};
145
+ const {revision,...body}=state;body.records=rechain(records);
146
+ f.close();fs.writeFileSync(f.statePath,JSON.stringify({...body,revision:digest(body)})+'\n',{mode:0o600});f.reopenStore();
147
+ return call;
148
+ }
149
+
150
+ test('a stranded T-006 journal replays as blocked/protected_scope and its records stay byte for byte',async t=>{
151
+ const f=await runnerFixture(t,['code.js',...PROTECTED]);
152
+ await f.make().executeEffect(f.develop());
153
+ const call=strandLikeT006(f);
154
+ const legacyBytes=fs.readFileSync(f.statePath);
155
+ const records=JSON.parse(legacyBytes).records;
156
+ assert.deepEqual(records.map(row=>row.payload.type),['init','effect-intent','effect-checkpoint']);
157
+ assert.equal(records[2].payload.checkpoint.state,'unknown');assert.equal(records[2].payload.checkpoint.code,'execution_error');
158
+ // Before this fix the same records had no exit: unknown, reconcile, and no pending intent to abandon.
159
+ const history=readRunnerHistory(records,records[0].payload.config,3);
160
+ assert.equal(history.pending,null);assert.equal(history.pendingAbandonable,false);
161
+ assert.equal(history.state.state,'blocked');assert.equal(history.state.code,'protected_scope');
162
+ for(const file of PROTECTED)assert(history.state.reason.includes(file),history.state.reason);
163
+ const resumed=f.resume();
164
+ const status=resumed.status();
165
+ assert.equal(status.state,'blocked');assert.equal(status.code,'protected_scope');
166
+ assert.deepEqual(status.calls,[call]);
167
+ const retry=await resumed.executeEffect(f.develop('develop-2'));
168
+ assert.equal(retry.outcome,'rejected');assert.equal(f.developerCalls(),0);
169
+ // abandon_effect is not needed and still refuses: there is no pending intent.
170
+ assert.equal(resumed.abandonEffect({allowed:true,reason:'protected scope'}).outcome,'rejected');
171
+ assert.equal(records[2].payload.checkpoint.learningResult,null);
172
+ // The exit: a new run by the original gates. Both read the stranded journal and admit it.
173
+ f.close();
174
+ const next={specsDir:f.specsRoot,codeProject:f.root,feature:FEATURE,tasksPath:f.tasksPath,
175
+ identity:{...f.identity,runId:'api-native-reading-T-006-r2'}};
176
+ assert.doesNotThrow(()=>assertNoUnrecordedPriorCode(next));
177
+ const supersession=prepareReviewedEvidenceSupersession({...next,reason:'scope 移除受保护规则文件后重建'});
178
+ assert.deepEqual(supersession.previousRunIds,[f.identity.runId]);
179
+ f.reopenStore();
180
+ assert.deepEqual(fs.readFileSync(f.statePath),legacyBytes);
181
+ });
182
+
183
+ test('the same unknown developer shape without a protected scope is still unknown',async t=>{
184
+ const f=await runnerFixture(t,['code.js']);
185
+ f.setDeveloper(()=>{throw new Error('adapter failure');});
186
+ const result=await f.make().executeEffect(f.develop());
187
+ assert.equal(result.state,'unknown');assert.equal(result.code,'execution_error');assert.equal(f.developerCalls(),1);
188
+ // The genuine pre-gate shape has the same call fields the T-006 rewrite uses.
189
+ assert.deepEqual(Object.keys(result.calls[0]),['invocationId','contextId','provider','requestedModel','effectiveModel',
190
+ 'channel','started','terminal','requestDigest','resultDigest']);
191
+ assert.equal(result.calls[0].terminal,'unknown');assert.equal(result.calls[0].resultDigest,null);
192
+ const resumed=f.reopen();
193
+ assert.equal(resumed.status().state,'unknown');assert.equal(resumed.status().code,'execution_error');
194
+ });