@aibyzero/cm-workflow 0.16.0 → 0.16.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +61 -0
  3. package/README.md +2 -2
  4. package/VERSION +1 -1
  5. package/docs/installation.md +1 -1
  6. package/docs/js-workflow-control.md +8 -2
  7. package/docs/untested-branches.md +73 -0
  8. package/package.json +1 -1
  9. package/runtime/js/cm-ai/checklist-coverage.mjs +70 -0
  10. package/runtime/js/cm-ai/effect-contract.mjs +37 -3
  11. package/runtime/js/cm-ai/host-conversation-execution.mjs +37 -1
  12. package/runtime/js/cm-ai/metrics-table.mjs +22 -0
  13. package/runtime/js/cm-ai/review-package.mjs +29 -3
  14. package/runtime/js/cm-ai/task-runner.mjs +10 -4
  15. package/runtime/js/cm-fix/cause-invocation.mjs +17 -4
  16. package/runtime/js/cm-fix/execution.mjs +41 -24
  17. package/runtime/js/cm-fix/final-review.mjs +18 -11
  18. package/runtime/js/cm-fix/finish.mjs +14 -1
  19. package/runtime/js/cm-fix/layout.mjs +26 -0
  20. package/runtime/js/cm-fix/metrics.mjs +2 -4
  21. package/runtime/js/cm-fix/walkthrough.mjs +8 -2
  22. package/runtime/js/cm-refactor/workflow.mjs +3 -2
  23. package/runtime/js/cm-security/scan.mjs +7 -1
  24. package/scripts/audit-untested-enums.mjs +59 -0
  25. package/scripts/cm-ai-checklist-coverage.test.mjs +116 -0
  26. package/scripts/cm-ai-execution-diagnostic.test.mjs +25 -0
  27. package/scripts/cm-ai-verification-gate.test.mjs +18 -0
  28. package/scripts/cm-fix-cross-session-host.test.mjs +100 -0
  29. package/scripts/cm-fix-execution.test.mjs +74 -0
  30. package/scripts/cm-fix-host.mjs +11 -5
  31. package/scripts/cm-fix-metrics.test.mjs +32 -0
  32. package/scripts/cm-fix-repair-owner.test.mjs +22 -18
  33. package/scripts/cm-release-smoke.sh +14 -0
  34. package/scripts/cm-review-dependency-snapshot.test.mjs +85 -0
  35. package/scripts/cm-review-inventory.test.mjs +42 -0
  36. package/scripts/cm-security.test.mjs +24 -0
  37. package/skills/cm-fix/references/js-host.md +18 -1
  38. package/templates/auto-update/cm-update.sh +51 -0
@@ -66,3 +66,28 @@ test('an error whose code cannot be read still collapses without throwing', () =
66
66
  try{assert.equal(failureCode(hostile),'execution_error');}
67
67
  finally{process.stderr.write=original;}
68
68
  });
69
+
70
+ // 光有失败码不够用:像 fix_closeout_unavailable 这种,同一个码在四个地方都会抛,
71
+ // 而对端只看得到一句笼统的 host_request_failed。诊断里得说清是哪一处拦的,
72
+ // 否则只能把宿主复制一份、自己加打印去找——这正是今天实际发生过的事。
73
+ test('a contract refusal names where it was raised, as a runtime-relative location', async () => {
74
+ const {validateCauseReviewer}=await import('../runtime/js/cm-fix/cause-invocation.mjs');
75
+ let raised;
76
+ try{ validateCauseReviewer({reviewerId:'r',adapterId:'a',provider:'codex',
77
+ requestedModel:'m',contextId:'same-host',excludedThreadIds:[]},'same-host'); }
78
+ catch(error){ raised=error; }
79
+ assert.equal(raised.code,'invalid_cause_reviewer');
80
+ const detail=executionDiagnostic(raised);
81
+ assert.equal(detail.code,'invalid_cause_reviewer');
82
+ // 指到真正的现场,而不是 need 自己所在的 effect-contract
83
+ assert.match(detail.origin,/^cm-fix\/cause-invocation\.mjs:\d+$/);
84
+ // 相对 runtime 根,不带绝对路径,免得把用户名之类带出去
85
+ assert.equal(detail.origin.includes('/Users/'),false);
86
+ // 塌缩那条 stderr 诊断同样带上
87
+ assert.match(collapse(raised),/"origin":"cm-fix\/cause-invocation\.mjs:\d+"/);
88
+ });
89
+
90
+ test('a location is only reported for our own runtime, never a caller file', () => {
91
+ // 测试文件不在 runtime 下,构造出来的错误不该被安上位置。
92
+ assert.deepEqual(executionDiagnostic(named('x',{code:'EBADF'})),{code:'EBADF'});
93
+ });
@@ -96,3 +96,21 @@ test('the batch driver decides retryability from the shared predicate', async ()
96
96
  assert.equal(developmentRetryable({state:'blocked',code:'package_mismatch'}),false);
97
97
  assert.equal(developmentRetryable({state:'unknown',code:'verification_precheck_failed'}),false);
98
98
  });
99
+
100
+ // The gate is fed by task-runner, and the previous version sent only the
101
+ // verification section. Unit tests on the validator alone could not see that,
102
+ // which is exactly how the description requirements slipped through to the
103
+ // independent review. Assert the payload the runner actually builds.
104
+ test('the gate receives both the task description and the verification section', async () => {
105
+ const {default:fs}=await import('node:fs');
106
+ const source=fs.readFileSync(new URL('../runtime/js/cm-ai/task-runner.mjs',import.meta.url),'utf8');
107
+ const body=/async function verificationSatisfied\(checks\) \{([\s\S]*?)\n \}/.exec(source);
108
+ assert.notEqual(body,null,'verificationSatisfied not found');
109
+ assert.match(body[1],/specification\?\.task\?\.description/);
110
+ assert.match(body[1],/specification\?\.task\?\.verification/);
111
+ // Both must reach the payload, each only when actually written.
112
+ assert.match(body[1],/written\(description\)\?\{description\}/);
113
+ assert.match(body[1],/written\(verification\)\?\{verification\}/);
114
+ // The gate steps aside only when neither exists.
115
+ assert.match(body[1],/if\(!written\(verification\)&&!written\(description\)\)return true;/);
116
+ });
@@ -0,0 +1,100 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import {execFileSync} from 'node:child_process';
4
+ import fs from 'node:fs';
5
+ import os from 'node:os';
6
+ import path from 'node:path';
7
+
8
+ import {fixHostContexts, validateCauseReviewer} from '../runtime/js/cm-fix/cause-invocation.mjs';
9
+ import {validateReviewDispatchGrant} from '../runtime/js/cm-ai/durable-runner-state.mjs';
10
+ import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
11
+
12
+ const DURABLE = '01a0bfd9-e7c3-7fa2-9808-206649615754';
13
+ const LIVE = '01a0c2b5-c2e2-7af1-8831-d6702c9a0d16';
14
+ const reviewer = {reviewerId: 'fix-cause-reviewer', adapterId: 'codex-cause-review-adapter', provider: 'codex',
15
+ requestedModel: 'gpt-6-astra', contextId: 'fix-cause-review-context', excludedThreadIds: []};
16
+
17
+ test('the durable host always comes first and a second one is optional', () => {
18
+ assert.deepEqual(fixHostContexts({hostContextId: DURABLE}), [DURABLE]);
19
+ assert.deepEqual(fixHostContexts({hostContextId: DURABLE, hostContextIds: [DURABLE, LIVE]}), [DURABLE, LIVE]);
20
+ // The resumed session can never displace the session the run is bound to.
21
+ // A malformed id is refused by the shared id() validator, a malformed set by
22
+ // this function's own bound; both are refusals, so accept either code.
23
+ const refused = error => ['invalid_host_context', 'invalid_input'].includes(error.code);
24
+ for (const hosts of [[LIVE, DURABLE], [LIVE], [DURABLE, DURABLE], [DURABLE, LIVE, 'third'], [],
25
+ [DURABLE, ''], [DURABLE, null], 'not-an-array'])
26
+ assert.throws(() => fixHostContexts({hostContextId: DURABLE, hostContextIds: hosts}),
27
+ refused, JSON.stringify(hosts));
28
+ });
29
+
30
+ test('a resumed session is a host, so it cannot also be the reviewer', () => {
31
+ assert.deepEqual(validateCauseReviewer(reviewer, [DURABLE, LIVE]), reviewer);
32
+ for (const host of [DURABLE, LIVE])
33
+ assert.throws(() => validateCauseReviewer({...reviewer, contextId: host}, [DURABLE, LIVE]),
34
+ {code: 'invalid_cause_reviewer'}, host);
35
+ // Excluding a host does not launder it into an acceptable reviewer either.
36
+ assert.throws(() => validateCauseReviewer({...reviewer, contextId: LIVE, excludedThreadIds: [LIVE]},
37
+ [DURABLE, LIVE]), {code: 'invalid_cause_reviewer'});
38
+ assert.throws(() => validateCauseReviewer(reviewer, [DURABLE, LIVE, 'third']), {code: 'invalid_cause_reviewer'});
39
+ });
40
+
41
+ // This is the claim the whole change rests on: the live session signs new grants
42
+ // while the durable session's old grants still replay. Neither may be widened
43
+ // into accepting a host the run never had.
44
+ test('a grant signed by either host is accepted and a third host is not', () => {
45
+ const request = {identity: {repositoryId: 'wue', runId: 'r', taskId: 'T-001', attempt: 1},
46
+ invocationId: 'invocation-1', requestDigest: digest({request: 1}), contextId: reviewer.contextId};
47
+ const issuedAt = 1_700_000_000_000;
48
+ const grantFor = hostContextId => {
49
+ const body = {version: 1, kind: 'cm-review-dispatch-grant', grantId: 'grant-1',
50
+ adapterId: reviewer.adapterId, invocationId: request.invocationId, requestDigest: request.requestDigest,
51
+ identity: request.identity, reviewerId: reviewer.reviewerId, logicalContextId: request.contextId,
52
+ packageDigest: digest({pkg: 1}), hostContextId, decisionId: 'decision-1', decision: 'approved',
53
+ issuedAt, expiresAt: issuedAt + 60000};
54
+ return {...body, grantDigest: digest(body)};
55
+ };
56
+ const expected = {request, reviewerId: reviewer.reviewerId, adapterId: reviewer.adapterId,
57
+ packageDigest: digest({pkg: 1}), hostContextIds: [DURABLE, LIVE],
58
+ authorizationAt: issuedAt, registeredAt: issuedAt + 1};
59
+ for (const host of [DURABLE, LIVE])
60
+ assert.equal(validateReviewDispatchGrant(grantFor(host), expected).hostContextId, host);
61
+ assert.throws(() => validateReviewDispatchGrant(grantFor('01a0c2b5-0000-0000-0000-000000000000'), expected),
62
+ {code: 'runner_grant'});
63
+ // A single-host run keeps refusing the session that never owned it.
64
+ assert.throws(() => validateReviewDispatchGrant(grantFor(LIVE), {...expected, hostContextIds: [DURABLE]}),
65
+ {code: 'runner_grant'});
66
+ });
67
+
68
+ // The flag exists so a new session can declare the old one. It must not become a
69
+ // way to plant an arbitrary host onto a run being created.
70
+ test('--original-host-context is refused when creating a run', () => {
71
+ const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'cm-fix-cross-')));
72
+ try {
73
+ const cwd = path.join(root, 'code');
74
+ fs.mkdirSync(cwd);
75
+ fs.writeFileSync(path.join(cwd, 'value.mjs'), 'export const value=1;');
76
+ const config = path.join(root, 'controls.json');
77
+ fs.writeFileSync(config, JSON.stringify({specsRoot: null, identity: {repositoryId: 'fixture',
78
+ runId: 'cross-session', taskId: 'T-FIX-cross', attempt: 1}, defect: 'Synthetic defect for the flag check',
79
+ reproduction: {cwd, command: [process.execPath, '-e', "process.stderr.write('BUG');process.exit(3)"],
80
+ expectedFailure: {exitCode: 3, outputIncludes: 'BUG'}, timeoutMs: 1000}}));
81
+ const host = fileURLToPathname(new URL('./cm-fix-host.mjs', import.meta.url));
82
+ const run = extra => {
83
+ try {
84
+ return execFileSync(process.execPath, [host, 'serve', '--config', config, ...extra],
85
+ {input: '', encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe']});
86
+ } catch (error) { return `${error.stdout ?? ''}${error.stderr ?? ''}`; }
87
+ };
88
+ assert.match(run(['--mode', 'create', '--host-context', LIVE, '--allow-reproduction',
89
+ '--original-host-context', DURABLE]), /fix_original_host_context_unavailable/);
90
+ // Creating without it gets past that refusal, which is what proves the refusal is
91
+ // the flag and not the rest of the launch. How far past depends on the host: the
92
+ // durable store needs Node >= 24.14, and CI validates on 22, where the platform
93
+ // gate stops the launch later in openFixExecution. Either outcome clears the flag
94
+ // check above it; only fix_original_host_context_unavailable would not.
95
+ assert.match(run(['--mode', 'create', '--host-context', LIVE, '--allow-reproduction']),
96
+ /host_ready|unsupported_platform/);
97
+ } finally { fs.rmSync(root, {recursive: true, force: true}); }
98
+ });
99
+
100
+ function fileURLToPathname(url) { return decodeURIComponent(url.pathname); }
@@ -92,3 +92,77 @@ test('legacy observation without attempts can publish, finish and resume without
92
92
  assert.equal(fs.readFileSync(path.join(cwd,'visits'),'utf8'),'1');
93
93
  }finally{owner.close();}
94
94
  }));
95
+
96
+ const reviewer={reviewerId:'fix-cause-reviewer',adapterId:'codex-cause-review-adapter',provider:'codex',
97
+ requestedModel:'gpt-6-astra',contextId:'fix-cause-review-context',excludedThreadIds:[]};
98
+ const statePath=options=>path.join(options.specsRoot,'.reviews','.execution',identity.runId,'state.json');
99
+
100
+ test('a later session resumes the original run without rewriting its records',()=>fixture(async(options,cwd)=>{
101
+ const bridge=createHostToolBridge();
102
+ bridge.attach(row=>{if(row.type==='host_request')bridge.accept({type:'host_result',sessionId:row.sessionId,
103
+ callId:row.callId,requestDigest:row.requestDigest,result:cause});});
104
+ let owner=openFixExecution(options,{bridge});
105
+ try{assert.equal((await owner.advance({authorized:true})).stage,'red_test_required');}finally{owner.close();}
106
+ const before=fs.readFileSync(statePath(options));
107
+ // The chat session that created the run is gone; the durable record keeps it.
108
+ owner=openFixExecution({...options,create:false,hostContextId:'actual-resumed-host'},{bridge});
109
+ try{
110
+ assert.equal((await owner.advance()).stage,'red_test_required');
111
+ assert.equal(fs.readFileSync(path.join(cwd,'visits'),'utf8'),'1');
112
+ }finally{owner.close();bridge.close();}
113
+ assert.deepEqual(fs.readFileSync(statePath(options)),before);
114
+ assert.equal(JSON.parse(before).records[0].payload.configuration.hostContextId,'actual-fixture-host');
115
+ }));
116
+
117
+ test('resuming never rewrites the durable host or accepts a reviewer-shaped session',()=>fixture(async(options)=>{
118
+ const configuration={...options.configuration,causeReview:reviewer};
119
+ openFixExecution({...options,configuration}).close();
120
+ // Moving the durable host is still a different run configuration.
121
+ assert.throws(()=>openFixExecution({...options,configuration,create:false,
122
+ configuration:{...configuration,hostContextId:'other-host'}}),{code:'fingerprint_mismatch'});
123
+ // A resumed session is still a host, so it cannot be the independent reviewer.
124
+ assert.throws(()=>openFixExecution({...options,configuration,create:false,
125
+ hostContextId:reviewer.contextId}),{code:'invalid_cause_reviewer'});
126
+ openFixExecution({...options,configuration,create:false,hostContextId:'actual-resumed-host'}).close();
127
+ }));
128
+
129
+ // 证据文件名由任务 slug 和轮次拼出来,跟 runId 无关,所以两次运行用同一个 taskId
130
+ // 就会写同一批文件。这个冲突原本要等红灯测试去发布输出时才炸——那时候 intent
131
+ // 已经登记,运行直接留在 unknown 且不可重派。名字在建运行时全都算得出来。
132
+ test('a run whose evidence filenames are already taken is refused before anything is recorded',()=>fixture(async(options)=>{
133
+ const reviews=path.join(options.specsRoot,'.reviews');
134
+ fs.mkdirSync(reviews,{recursive:true,mode:0o700});
135
+ const taken=path.join(reviews,`fix-demo-${identity.taskId}-r1.md`);
136
+ fs.writeFileSync(taken,'another run already published under this task id');
137
+ assert.throws(()=>openFixExecution(options),{code:'fix_evidence_name_taken'});
138
+ // 拒绝发生在任何记录之前:没有留下半个运行
139
+ assert.equal(fs.existsSync(path.join(reviews,'.execution',identity.runId)),false);
140
+ // 换一个任务编号就能正常建起来,说明拦的是重名而不是别的
141
+ const renamed={...options,identity:{...identity,taskId:'T-FIX-demo-two'}};
142
+ openFixExecution(renamed).close();
143
+ // 已经建起来的运行,恢复时不会被自己写下的证据挡住
144
+ fs.writeFileSync(path.join(reviews,'fix-demo-two-T-FIX-demo-two-r1.md'),'its own evidence');
145
+ openFixExecution({...renamed,create:false}).close();
146
+ }));
147
+
148
+ // 走查声明的模块必须和诊断结论对得上。这条规矩一直有,但原来只在走查那一步才查
149
+ // ——那已经在花钱做完独立审查之后,整轮白跑。诊断一落盘就判得出来。
150
+ test('a walkthrough that does not line up with the diagnosis stops right after diagnosis',async()=>{
151
+ for(const [modules,expected] of [[['value','not-diagnosed'],'walkthrough_configuration_mismatch'],
152
+ [['value'],'red_test_required']])
153
+ await fixture(async(options)=>{
154
+ const bridge=createHostToolBridge();
155
+ bridge.attach(row=>{if(row.type==='host_request')bridge.accept({type:'host_result',sessionId:row.sessionId,
156
+ callId:row.callId,requestDigest:row.requestDigest,result:cause});});
157
+ const configuration={...options.configuration,walkthrough:{timeoutMs:2000,
158
+ flows:[{id:'value-flow',modules,steps:['Exercise the repaired value'],expected:['Value is 2'],
159
+ kind:'commands',command:[process.execPath,'-e','0']}]}};
160
+ const owner=openFixExecution({...options,configuration},{bridge});
161
+ try{
162
+ const status=await owner.advance({authorized:true});
163
+ assert.equal(status.stage,expected,JSON.stringify(modules));
164
+ // 诊断照常留底,停住不等于把证据弄丢
165
+ assert.equal(status.diagnosis.status,'diagnosed');
166
+ }finally{owner.close();bridge.close();}
167
+ });
168
+ });
@@ -11,7 +11,7 @@ import {id,json,need,shape,digest} from '../runtime/js/cm-ai/effect-contract.mjs
11
11
  import {readConversationReviewConfiguration} from './cm-ai-host.mjs';
12
12
  import {createFixReviewHost} from '../runtime/js/cm-fix/host-review.mjs';
13
13
 
14
- const usage='cm-fix-host.mjs serve --config PATH --mode create|resume --host-context ID --allow-reproduction [--runtime codex|claude] [--review-config PATH] [--allow-cause-review] [--allow-final-review] [--allow-test-author] [--allow-red-test] [--allow-baseline] [--allow-repair] [--allow-regression] [--allow-learning-writeback]\nCodex or Claude current-host operations: advance, cause_review_package, cause_review, author_tests, red_test, baseline, repair, regression, retrospective, learning_writeback, handoff, final_review_package, final_review, publish_review, check_n5, post_review_regression, status, cancel. Runtime defaults to codex; claude uses its own matching diagnostic receipt and cannot reuse Codex preflight or disabledSkills settings. Runtime selection is bound to recovery; switching providers requires a separate run. This selects existing adapters, not permission to call them. Each write/check needs its respective launch flag and configuration. Test authoring, repair, cause and final review dispatch require matching existing stdin diagnostics; diagnostic alone is not authorization. Passing regression stops at handoff_required. The read-only retrospective operation yields handoff_ready or learning_writeback_required. learning_writeback requires its own flag, preserves project instructions and includes AGENTS.md in the review scope; it does not authorize provider calls. handoff publishes the fixed specs-local handoff with Learning evidence and moves to final_review_required; no provider is called and no task is completed. final_review_package is read-only and returns the final content-bound review package. final_review requires its own flag and matching diagnostics; observations do not complete the task. publish_review projects the registered result into the existing review file; it does not dispatch or complete tasks. check_n5 runs the original Learning-aware gate; post_review_regression requires --allow-regression and reaches closeout_required, not completion.';
14
+ const usage='cm-fix-host.mjs serve --config PATH --mode create|resume --host-context ID --allow-reproduction [--original-host-context ID] [--runtime codex|claude] [--review-config PATH] [--allow-cause-review] [--allow-final-review] [--allow-test-author] [--allow-red-test] [--allow-baseline] [--allow-repair] [--allow-regression] [--allow-learning-writeback]\nCodex or Claude current-host operations: advance, cause_review_package, cause_review, author_tests, red_test, baseline, repair, regression, retrospective, learning_writeback, handoff, final_review_package, final_review, publish_review, check_n5, post_review_regression, status, cancel. Runtime defaults to codex; claude uses its own matching diagnostic receipt and cannot reuse Codex preflight or disabledSkills settings. Runtime selection is bound to recovery; switching providers requires a separate run. This selects existing adapters, not permission to call them. Each write/check needs its respective launch flag and configuration. Test authoring, repair, cause and final review dispatch require matching existing stdin diagnostics; diagnostic alone is not authorization. Passing regression stops at handoff_required. The read-only retrospective operation yields handoff_ready or learning_writeback_required. learning_writeback requires its own flag, preserves project instructions and includes AGENTS.md in the review scope; it does not authorize provider calls. handoff publishes the fixed specs-local handoff with Learning evidence and moves to final_review_required; no provider is called and no task is completed. final_review_package is read-only and returns the final content-bound review package. final_review requires its own flag and matching diagnostics; observations do not complete the task. publish_review projects the registered result into the existing review file; it does not dispatch or complete tasks. check_n5 runs the original Learning-aware gate; post_review_regression requires --allow-regression and reaches closeout_required, not completion.';
15
15
 
16
16
  export async function main(argv=process.argv.slice(2),{input=process.stdin,output=process.stdout,error=process.stderr,reviewWorkerFactory=null}={}){
17
17
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('Omit specsRoot or use null for a bare project: the same owner stores archives in docs/fixes and reviews in docs/fixes/.reviews, uses the original no-specs log mode, and skips METRICS. No specs skeleton is created. Visual-only reproduction/redTest may use kind:visual with cwd, timeoutMs, before:{path,sha256,kind:screenshot|video,description}, reason explaining why automated red cannot be written, environment, steps and expected; redTest also has testFiles:[]. No testAuthor or fake red/green command. Repair/regression/review/finish permissions remain mandatory. qa_browser returns actual after carrier metadata; missing evidence blocks.\n');
@@ -20,8 +20,8 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
20
20
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('recover_final_review requires --allow-final-review-recovery and exact latest invocationId/packageDigest, previousInvocationStopped:true, and a nonempty reason. The legacy first continuation remains once-only. A further continuation additionally requires a fresh startup --final-review-recovery-invocation ID matching the latest unknown invocation, authorizing exactly one new call. Confirm the previous process stopped; this is a trusted host acknowledgment, not an automatic liveness check. Preparation dispatches nothing. Later final_review requires recovery permission and --allow-final-review; additional cycles require the same invocation binding after restart. Old records, task attempt, reviewed package and the original Review/N5/finish remain unchanged. No automatic retry, cancelled/complete-verdict recovery, missing-thread recovery, business-revision recovery or source-drift bypass. status adds a read-only progress projection, not authorization or current-source verification.\n');
21
21
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('N6 child configuration may include qaSource {feature, identity, packageDigest, testRunId, handoffDigest}; derive the separate fixed child identity with qaFixIdentity. It requires --allow-qa-fix in addition to existing action flags. Close the parent host first: the original specs-wide owner lock is shared. Creation/resume rechecks the current failed round, project, report and policy; the source is bound to the original fix configuration. This does not resume the parent or automatically rerun QA, and does not authorize provider calls, installation or Git.\n');
22
22
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('Second-round retrospective uses the cumulative original baseline, including previously authored tests and Learning scope. It persists the current round reflection and reaches revision_handoff_ready or revision_learning_writeback_required; neither state completes the task or publishes a new handoff. From revision_handoff_ready, handoff publishes a separate a2 handoff containing cumulative changes, current reflection, original red evidence and prior review/Learning history; final_review_package then reads that bound package. Pending Learning blocks publication. final_review requires --allow-final-review, uses fresh-thread exclusions and carries prior findings; publish_review writes the original r2 evidence and review log, and check_n5 runs the original Learning-aware gate. Approval reaches revision_post_review_regression_required, not completion.\n');
23
- if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('prepare_revision requires --allow-repair and either a published first-round changes_requested review or an approved first-round review followed by a package-bound walkthrough result of failed. The latter preserves the approved verdict and carries separate walkthrough failure evidence; passed, blocked, unknown, or drifted evidence cannot authorize this repair. An approved first-round review followed by package-bound post-review regression defect_remaining or regressed can also prepare the second repair when all baseline commands produced complete results. The regression commands must match the first reviewed handoff; passed, inconclusive, unavailable or partial evidence is refused. Regression and walkthrough failure feedback are mutually exclusive and neither replaces the next independent review. It rereads project Learning and persists the second-round preparation in the original store, preserving first-round evidence. repair then uses the original business scope and findings with separate second-round records. regression requires --allow-regression and reruns the original test commands against the second repair, preserving the original red evidence. Success reaches revision_handoff_required, not completion; handoff and final_review use the second-round package; review evidence publication and N5 are connected; post_review_regression requires --allow-regression and reaches revision_closeout_required after the original checks; walkthrough requires --allow-walkthrough and binds the second-round package and identity; finish reuses the original closeout with --allow-finish and delivery:diff, preserving first-round history and recording completion for attempt 2. Second-round learning_writeback requires --allow-learning-writeback, includes the resulting AGENTS.md in the cumulative review package and preserves prior Learning history; pending or unknown writeback cannot advance to handoff. A lost repair or regression result stays unknown and is not redispatched.\n');
24
- if(argv.length===1&&['--help','-h'].includes(argv[0])){output.write(usage+'\nAdditional operation: publish_dossier writes a private immutable fixes/YYYYMMDD-slug.md closeout snapshot; missing evidence is explicit and the task remains incomplete. In observation it writes the recorded reproduction summary and expected evidence to the same fixes archive, preserving its date across restart and refusing user-content conflicts; it does not repair or complete the task. In observation, finish with --allow-finish records run_done as observing and releases the owner lock without task_done or metrics; end the existing transport with host_close or EOF. resume accepts evidenceFiles (1-3 explicit specs-local files) and binds them to the prior observing exit and dossier without resetting task attempt. It reaches observation_resume_prepared; evidence drift blocks continuation. advance from prepared rereads Learning and reruns the original reproduction command, then passes selected evidence references to the original diagnosis capability. Recovery uses separate records without resetting attempt; unknown outcomes are not redispatched. Unreproduced, blocked or still-insufficient evidence stays incomplete. Before resumed execution, the original resume log binds the observation exit and selected evidence digests, restoring the same run to running without a new task start. Recovered handoffs bind exact selected evidence bytes and pre-observation history under the original size and review gates; legacy recovered handoffs lacking that material remain readable but cannot claim current review coverage. Recovered closeout preserves the exact observation archive prefix and original filename, appends the recovery results, and uses the existing finish gate; user-modified continuations are refused. If recovery still cannot reproduce the defect or diagnosis still needs evidence, publish_dossier appends the latest observation and authorized finish records a second bound observing exit without task completion or metrics. After a recorded observing exit, resume can bind another explicit evidence selection to the latest exit and archive. Observation cycles retain prior records and archive bytes, do not reset task attempts or review rounds, and require separately authorized advance; unknown outcomes are not retried. Multi-cycle handoffs include the exact prior archive under the original size limit. walkthrough requires configured module-mapped flows and --allow-walkthrough; it runs declared commands or uses existing qa_browser/qa_logic host capabilities. Static support cannot pass a walkthrough. Browser execution remains limited to the authorized current-host environment; no install or provider authority is implied.\nRepair completion via finish requires --allow-finish, existing delivery:diff, reviewed diagnosis, modern handoff and passed walkthrough. It rechecks the original N5 gate, finalizes the generated dossier, records reviewed lessons, task_done, metrics and run_done. It resumes partial closeout without redispatch and refuses user-modified dossier conflicts. Branch/MR delivery still requires separate authorization; this command does not execute Git.\n');return 0;}
23
+ if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('prepare_revision requires --allow-repair and either a published first-round changes_requested review or an approved first-round review followed by a package-bound walkthrough result of failed. The latter preserves the approved verdict and carries separate walkthrough failure evidence; passed, blocked, unknown, or drifted evidence cannot authorize this repair. An approved first-round review followed by package-bound post-review regression defect_remaining or regressed can also prepare the second repair when all baseline commands produced complete results. The regression commands must match the first reviewed handoff; passed, inconclusive, unavailable or partial evidence is refused. Regression and walkthrough failure feedback are mutually exclusive and neither replaces the next independent review. It rereads project Learning and persists the second-round preparation in the original store, preserving first-round evidence. repair then uses the original business scope and findings with separate second-round records. regression requires --allow-regression and reruns the original test commands against the second repair, preserving the original red evidence. Success reaches revision_handoff_required, not completion; handoff and final_review use the second-round package; review evidence publication and N5 are connected; post_review_regression requires --allow-regression and reaches revision_closeout_required after the original checks; walkthrough requires --allow-walkthrough and binds the second-round package and identity; finish reuses the original closeout with --allow-finish, preserving first-round history and recording completion for attempt 2. Second-round learning_writeback requires --allow-learning-writeback, includes the resulting AGENTS.md in the cumulative review package and preserves prior Learning history; pending or unknown writeback cannot advance to handoff. A lost repair or regression result stays unknown and is not redispatched.\n');
24
+ if(argv.length===1&&['--help','-h'].includes(argv[0])){output.write(usage+'\nAdditional operation: publish_dossier writes a private immutable fixes/YYYYMMDD-slug.md closeout snapshot; missing evidence is explicit and the task remains incomplete. In observation it writes the recorded reproduction summary and expected evidence to the same fixes archive, preserving its date across restart and refusing user-content conflicts; it does not repair or complete the task. In observation, finish with --allow-finish records run_done as observing and releases the owner lock without task_done or metrics; end the existing transport with host_close or EOF. resume accepts evidenceFiles (1-3 explicit specs-local files) and binds them to the prior observing exit and dossier without resetting task attempt. It reaches observation_resume_prepared; evidence drift blocks continuation. advance from prepared rereads Learning and reruns the original reproduction command, then passes selected evidence references to the original diagnosis capability. Recovery uses separate records without resetting attempt; unknown outcomes are not redispatched. Unreproduced, blocked or still-insufficient evidence stays incomplete. Before resumed execution, the original resume log binds the observation exit and selected evidence digests, restoring the same run to running without a new task start. Recovered handoffs bind exact selected evidence bytes and pre-observation history under the original size and review gates; legacy recovered handoffs lacking that material remain readable but cannot claim current review coverage. Recovered closeout preserves the exact observation archive prefix and original filename, appends the recovery results, and uses the existing finish gate; user-modified continuations are refused. If recovery still cannot reproduce the defect or diagnosis still needs evidence, publish_dossier appends the latest observation and authorized finish records a second bound observing exit without task completion or metrics. After a recorded observing exit, resume can bind another explicit evidence selection to the latest exit and archive. Observation cycles retain prior records and archive bytes, do not reset task attempts or review rounds, and require separately authorized advance; unknown outcomes are not retried. Multi-cycle handoffs include the exact prior archive under the original size limit. walkthrough requires configured module-mapped flows and --allow-walkthrough; it runs declared commands or uses existing qa_browser/qa_logic host capabilities. Static support cannot pass a walkthrough. Browser execution remains limited to the authorized current-host environment; no install or provider authority is implied.\nRepair completion via finish requires --allow-finish, a reviewed diagnosis, a modern handoff and a passed walkthrough. It accepts any configured policies.delivery and only requires that the mode stay unchanged while completion records are written; Git delivery is a separate logged event, not a precondition. It rechecks the original N5 gate, finalizes the generated dossier, records reviewed lessons, task_done, metrics and run_done. It resumes partial closeout without redispatch and refuses user-modified dossier conflicts. Branch/MR delivery still requires separate authorization; this command does not execute Git.\n');return 0;}
25
25
  let owner,bridge;
26
26
  try{
27
27
  need(argv.length>=8&&argv[0]==='serve'&&argv[1]==='--config'&&argv[3]==='--mode'
@@ -29,10 +29,15 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
29
29
  need(['create','resume'].includes(argv[4]),'invalid_arguments');id(argv[6]);
30
30
  const extra=new Map();
31
31
  for(let index=8;index<argv.length;index++){
32
- const flag=argv[index];need(!extra.has(flag)&&['--runtime','--review-config','--final-review-recovery-invocation','--allow-qa-fix','--allow-cause-review','--allow-final-review','--allow-final-review-recovery','--allow-red-test','--allow-baseline','--allow-test-author','--allow-repair','--allow-regression','--allow-learning-writeback','--allow-walkthrough','--allow-finish'].includes(flag),'invalid_arguments');
32
+ const flag=argv[index];need(!extra.has(flag)&&['--runtime','--review-config','--original-host-context','--final-review-recovery-invocation','--allow-qa-fix','--allow-cause-review','--allow-final-review','--allow-final-review-recovery','--allow-red-test','--allow-baseline','--allow-test-author','--allow-repair','--allow-regression','--allow-learning-writeback','--allow-walkthrough','--allow-finish'].includes(flag),'invalid_arguments');
33
33
  if(flag.startsWith('--allow-'))extra.set(flag,true);
34
34
  else{need(typeof argv[index+1]==='string'&&!argv[index+1].startsWith('--'),'invalid_arguments');extra.set(flag,argv[++index]);}
35
35
  }
36
+ // A run created in an earlier session keeps that session in its durable record.
37
+ // Resume declares it here so the stored fingerprint and history still match,
38
+ // while --host-context stays the real current session for every live decision.
39
+ const originalHostContext=extra.get('--original-host-context')??null;
40
+ if(originalHostContext!==null){id(originalHostContext);need(argv[4]==='resume','fix_original_host_context_unavailable');}
36
41
  const recoveryInvocationId=extra.get('--final-review-recovery-invocation')??null;
37
42
  if(recoveryInvocationId!==null){id(recoveryInvocationId);need(extra.has('--allow-final-review-recovery'),'fix_review_recovery_authorization_required');}
38
43
  const runtime=extra.get('--runtime')??'codex';need(['codex','claude'].includes(runtime),'invalid_runtime');
@@ -61,7 +66,8 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
61
66
  permissions:[...extra.keys()],workerFactory:reviewWorkerFactory});
62
67
  bridge=createHostToolBridge();
63
68
  owner=openFixExecution({specsRoot:config.specsRoot??null,identity:config.identity,create:argv[4]==='create',
64
- configuration:{hostContextId:argv[6],defect:config.defect,reproduction:config.reproduction,
69
+ hostContextId:argv[6],
70
+ configuration:{hostContextId:originalHostContext??argv[6],defect:config.defect,reproduction:config.reproduction,
65
71
  ...(Object.hasOwn(config,'protectSpecs')?{protectSpecs:config.protectSpecs}:{}),
66
72
  ...(Object.hasOwn(config,'qaSource')?{qaSource:config.qaSource}:{}),
67
73
  ...(runtime==='claude'?{runtime}:{}),
@@ -56,3 +56,35 @@ test('FIX metrics projects completed log evidence, preserves content, deduplicat
56
56
  assert.throws(()=>appendFixMetrics(options,control));assert.equal(fs.readFileSync(path.join(root,'fixes',dossierFile),'utf8'),body);
57
57
  }finally{fs.rmSync(root,{recursive:true,force:true});}
58
58
  });
59
+
60
+ // 「Codex拦截」在 N4-review.md 里被明确记为「保持原列顺序,语义升级为独立审查拦截」,
61
+ // 也就是同一列改个名。但表头是整行精确匹配,于是任何改名前就存在的 METRICS.md 都会被
62
+ // 硬拒,收尾整个走不完,而且没有迁移路径。
63
+ test('FIX metrics appends under the renamed legacy header instead of refusing the file',()=>{
64
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'fix-metrics-legacy-')));
65
+ try{
66
+ fs.mkdirSync(path.join(root,'fixes'));
67
+ const dossierFile='20260907-value.md',body='Synthetic completed dossier, fixture only.\n';
68
+ fs.writeFileSync(path.join(root,'fixes',dossierFile),body);
69
+ const identity={repositoryId:'fixture',runId:'metrics-legacy',taskId:'T-FIX-value',attempt:1};
70
+ const common={workflow:'cm-fix',node:'FIX',repository_id:identity.repositoryId,run_id:identity.runId,task:identity.taskId,attempt:1};
71
+ const events=[{...common,event:'task_start',at:'2026-09-07T01:00:00Z',event_id:'start'},
72
+ {...common,event:'review',phase:'complete',review_kind:'implementation',round:1,result:'approved',finding_count:0,package_digest:'a'.repeat(64),event_id:'review'},
73
+ {...common,event:'task_done',at:'2026-09-07T01:01:00Z',event_id:'done',result:'completed',dossier_file:`fixes/${dossierFile}`,
74
+ dossier_sha256:createHash('sha256').update(body).digest('hex'),package_digest:'a'.repeat(64),walkthrough_result:'passed'}];
75
+ fs.writeFileSync(path.join(root,'运行日志.jsonl'),events.map(row=>JSON.stringify(row)).join('\n')+'\n');
76
+ const legacy='| 任务 | Feature | 开始 | 结束 | 审查轮次 | Codex拦截 | QA | 人工介入(次:原因) |';
77
+ const existing=`User notes stay.\n\n${legacy}\n| --- | --- | --- | --- | --- | --- | --- | --- |\n| T-other | other | a | b | 1 | 0 | — | 0 |\n`;
78
+ fs.writeFileSync(path.join(root,'METRICS.md'),existing);
79
+ const options={specsRoot:root,identity,dossierFile},control={assertOwned(){}};
80
+ const written=appendFixMetrics(options,control);
81
+ const bytes=fs.readFileSync(written.path,'utf8');
82
+ assert(bytes.startsWith(existing),'用户原有内容必须一字不动');
83
+ assert(bytes.includes(written.line),'新行要追加进同一张表');
84
+ assert(!bytes.includes('独立审查拦截'),'不擅自改写用户文件里的表头');
85
+ assert.equal(appendFixMetrics(options,control).deduplicated,true);
86
+ // 认得出的旧表头才放行;真正不是这张表的文件照旧拒绝。
87
+ fs.writeFileSync(path.join(root,'METRICS.md'),'User custom table, not recognized.\n');
88
+ assert.throws(()=>appendFixMetrics(options,control),{code:'metrics_table_invalid'});
89
+ }finally{fs.rmSync(root,{recursive:true,force:true});}
90
+ });
@@ -19,13 +19,17 @@ import {startFixRun} from '../runtime/js/cm-fix/start.mjs';
19
19
  import {readProjectInstructionContext} from '../runtime/js/cm-ai/cm-ai-context-refresh.mjs';
20
20
 
21
21
  test('durable repair registers before write, preserves cause approval history and never redispatches lost results',async()=>{
22
- for(const mode of ['revision','revision-approved','revision-lost','normal','lost','cause','cause-map','unfixed','regression-intent','lesson','retrospective-lost','lesson-intent','lesson-pending','handoff-forged','handoff-legacy','handoff-large']){
22
+ for(const mode of ['revision','revision-approved','revision-draft-mr','revision-lost','normal','lost','cause','cause-map','unfixed','regression-intent','lesson','retrospective-lost','lesson-intent','lesson-pending','handoff-forged','handoff-legacy','handoff-large']){
23
23
  const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'fix-repair-owner-')));
24
24
  const cwd=path.join(root,'code'),specsRoot=path.join(root,'specs');fs.mkdirSync(cwd);fs.mkdirSync(specsRoot);
25
25
  fs.writeFileSync(path.join(cwd,'value.mjs'),'export const value=1;');
26
26
  fs.writeFileSync(path.join(cwd,'red.mjs'),"import {value} from './value.mjs';if(value!==2){console.error('BUG');process.exit(1)}");
27
27
  fs.writeFileSync(path.join(cwd,'existing.mjs'),"import {value} from './value.mjs';if(typeof value!=='number')process.exit(1)");
28
- if(mode==='revision-approved')fs.writeFileSync(path.join(cwd,'.cm-workflow.json'),JSON.stringify({version:1,policies:{delivery:'diff'}}));
28
+ // 收尾只关心「交付模式没在中途变过」,不关心它是哪一种:Git 是单独的 delivery
29
+ // 事件,不是 task_done 的前提。draft-mr 是 cm-init 给带 remote 的仓库生成的默认值。
30
+ const approvedRevision=['revision-approved','revision-draft-mr'].includes(mode);
31
+ if(approvedRevision)fs.writeFileSync(path.join(cwd,'.cm-workflow.json'),
32
+ JSON.stringify({version:1,policies:{delivery:mode==='revision-draft-mr'?'draft-mr':'diff'}}));
29
33
  const identity={repositoryId:'fixture',runId:'repair-owner',taskId:'T-FIX-owner',attempt:1};
30
34
  const mapPaths=mode==='cause-map'?['docs/codebase-context/00-index.md','docs/codebase-context/07-business-logic.md','docs/codebase-context/09-changelog.md']:[];
31
35
  const mapPlan='Create partial value map; cover value.mjs only; other modules unverified.';
@@ -37,7 +41,7 @@ test('durable repair registers before write, preserves cause approval history an
37
41
  repair:{scope:['value.mjs',...mapPaths],requirements:['value.mjs']},...(mode.startsWith('cause')||mode.startsWith('revision')?{causeReview:reviewer}:{})}};
38
42
  if(mode==='handoff-large')options.configuration.redTest.command=[process.execPath,'-e',
39
43
  "import('./value.mjs').then(({value})=>{if(value!==2){process.stderr.write('BUG'+'x'.repeat(128*1024-3));process.exitCode=1;}});//"+'x'.repeat(31*1024)];
40
- if(mode==='revision-approved')options.configuration.walkthrough={timeoutMs:2000,flows:[{id:'value-flow',modules:['one'],steps:['Read corrected value'],expected:['Value is 2'],kind:'commands',command:[process.execPath,'red.mjs']}]};
44
+ if(approvedRevision)options.configuration.walkthrough={timeoutMs:2000,flows:[{id:'value-flow',modules:['one'],steps:['Read corrected value'],expected:['Value is 2'],kind:'commands',command:[process.execPath,'red.mjs']}]};
41
45
  const authority=createHostReviewAuthority({hostContextId:'fixture-host',reviewerId:reviewer.reviewerId,adapterId:reviewer.adapterId,decide:async()=>({status:'approved'})});
42
46
  const causeReview={authorize:authority.authorize,run:createCauseReviewRun(async({prompt},{onEvent})=>{
43
47
  const data=JSON.parse(prompt.split('<cm-review-data-json>\n')[1]);
@@ -47,7 +51,7 @@ test('durable repair registers before write, preserves cause approval history an
47
51
  },'codex')};
48
52
  const learning={contextDigest:digest([]),files:[],application:{contextDigest:digest([]),status:'no_relevant_lesson',summary:'No project instructions in synthetic fixture'}};
49
53
  const prepare=async()=>{
50
- if(mode!=='revision-approved'||!fs.existsSync(path.join(cwd,'AGENTS.md')))return learning;
54
+ if(!approvedRevision||!fs.existsSync(path.join(cwd,'AGENTS.md')))return learning;
51
55
  const files=readProjectInstructionContext(cwd,[]).map(({content,...metadata})=>metadata);
52
56
  return {files,contextDigest:digest(files),application:{contextDigest:digest(files),status:'applied',summary:'Preserve reviewed first-round lessons'}};
53
57
  };
@@ -55,14 +59,14 @@ test('durable repair registers before write, preserves cause approval history an
55
59
  bridge.attach(row=>{
56
60
  if(row.type!=='host_request')return;
57
61
  let result={status:'diagnosed',rootCause:'Wrong constant',affectedPaths:['value.mjs'],affectedModules:['one'],crossLayer:mode.startsWith('cause'),plan:mode==='cause-map'?mapPlan:'Correct constant'};
58
- if(mode==='revision-approved')result.investigation={discardedAlternatives:[],boundaryAnalysis:null};
62
+ if(approvedRevision)result.investigation={discardedAlternatives:[],boundaryAnalysis:null};
59
63
  if(row.kind==='fix_retrospective'){
60
64
  const state=JSON.parse(fs.readFileSync(path.join(specsRoot,'.reviews','.execution',identity.runId,'state.json')));
61
65
  assert.equal(state.records.at(-1).id,row.payload.identity.attempt===2?'fix-revision-retrospective-intent':'fix-retrospective-intent');retrospectives++;
62
66
  if(mode==='retrospective-lost'){bridge.close();return;}
63
67
  result=mode.startsWith('lesson')?{status:mode==='lesson-pending'?'writeback_pending':'lesson_candidate',candidates:[{classification:'structured',trigger:'Wrong constant',action:'Keep regression check',evidence:['red.mjs']}],reason:mode==='lesson-pending'?'Human assessment required':null}
64
68
  :{status:'no_new_lesson',candidates:[],reason:null};
65
- if(mode==='revision-approved')result={status:'lesson_candidate',candidates:[{classification:'structured',trigger:row.payload.identity.attempt===2?'Second repair boundary':'First repair boundary',action:'Keep value regression',evidence:['red.mjs']}],reason:null};
69
+ if(approvedRevision)result={status:'lesson_candidate',candidates:[{classification:'structured',trigger:row.payload.identity.attempt===2?'Second repair boundary':'First repair boundary',action:'Keep value regression',evidence:['red.mjs']}],reason:null};
66
70
  }
67
71
  if(row.kind==='fix_repair'){
68
72
  const state=JSON.parse(fs.readFileSync(path.join(specsRoot,'.reviews','.execution',identity.runId,'state.json')));
@@ -86,7 +90,7 @@ test('durable repair registers before write, preserves cause approval history an
86
90
  // Compare settled state with reopened state when checking durable recovery.
87
91
  const settled=async pending=>{await pending;return owner.status();};
88
92
  try{
89
- if(mode==='revision-approved')startFixRun({specsRoot,identity,configuration:options.configuration});
93
+ if(approvedRevision)startFixRun({specsRoot,identity,configuration:options.configuration});
90
94
  await owner.advance({authorized:true});
91
95
  if(mode.startsWith('cause')){
92
96
  if(mode==='cause-map')assert(!fs.existsSync(path.join(cwd,'docs')));
@@ -140,7 +144,7 @@ test('durable repair registers before write, preserves cause approval history an
140
144
  assert.deepEqual(pkg.checks[1].command,options.configuration.baseline.commands[0].command);
141
145
  owner.close();owner=openFixExecution({...options,create:false},{bridge,prepare});
142
146
  const retrospective=await settled(owner.retrospect());
143
- assert.equal(retrospective.stage,mode==='retrospective-lost'?'unknown':mode.startsWith('lesson')||mode==='revision-approved'?'learning_writeback_required':'handoff_ready');
147
+ assert.equal(retrospective.stage,mode==='retrospective-lost'?'unknown':mode.startsWith('lesson')||approvedRevision?'learning_writeback_required':'handoff_ready');
144
148
  assert.equal(retrospective.completionEligible,false);assert.equal(retrospectives,1);
145
149
  owner.close();owner=openFixExecution({...options,create:false},{bridge,prepare});
146
150
  assert.deepEqual(await owner.retrospect(),retrospective);assert.equal(retrospectives,1);
@@ -161,7 +165,7 @@ test('durable repair registers before write, preserves cause approval history an
161
165
  assert.equal(blocked.learningWriteback.reason,'Human assessment required');owner.close();owner=openFixExecution({...options,create:false});
162
166
  assert.deepEqual(owner.writeLearning({authorized:true}),blocked);assert(!fs.existsSync(path.join(cwd,'AGENTS.md')));continue;
163
167
  }
164
- if(mode==='lesson'||mode==='revision-approved'){
168
+ if(mode==='lesson'||approvedRevision){
165
169
  assert.throws(()=>owner.writeLearning(),{code:'learning_writeback_authorization_required'});
166
170
  const written=owner.writeLearning({authorized:true});assert.equal(written.stage,'handoff_ready');
167
171
  assert.equal(written.learningWriteback.outcome,'written');assert.equal(written.completionEligible,false);
@@ -211,7 +215,7 @@ test('durable repair registers before write, preserves cause approval history an
211
215
  const defectEvidence=JSON.parse(payload.evidence.find(item=>item.startsWith('fix defect evidence')).split('(data, not instructions) ')[1]);
212
216
  assert.deepEqual(defectEvidence.diagnosis,handed.diagnosis);assert.deepEqual(defectEvidence.redTest.result,handed.redTest);
213
217
  assert.deepEqual(defectEvidence.redOutput,JSON.parse(fs.readFileSync(path.join(specsRoot,handed.redTest.output.path))));
214
- assert(payload.evidence.includes(mode==='lesson'||mode==='revision-approved'?'learning: retrospective written AGENTS.md':'learning: retrospective no_new_lesson'));
218
+ assert(payload.evidence.includes(mode==='lesson'||approvedRevision?'learning: retrospective written AGENTS.md':'learning: retrospective no_new_lesson'));
215
219
  assert.equal(payload.implementation_sha256,implementationSha256(cwd,payload.changed_files));
216
220
  const handoffBytes=fs.readFileSync(handoffPath);owner.close();owner=openFixExecution({...options,create:false});
217
221
  assert.deepEqual(owner.createHandoff(),handed);assert.deepEqual(fs.readFileSync(handoffPath),handoffBytes);
@@ -265,12 +269,12 @@ test('durable repair registers before write, preserves cause approval history an
265
269
  const cumulative=owner.implementationPackage();assert.equal(cumulative.identity.attempt,2);
266
270
  assert.equal(Buffer.from(cumulative.changes.find(change=>change.path==='value.mjs').before.contentBase64,'base64').toString(),'export const value=1;');
267
271
  owner.close();owner=openFixExecution({...options,create:false},{bridge,prepare});
268
- const reflectedAgain=await settled(owner.retrospect());assert.equal(reflectedAgain.stage,mode==='revision-approved'?'revision_learning_writeback_required':'revision_handoff_ready');
272
+ const reflectedAgain=await settled(owner.retrospect());assert.equal(reflectedAgain.stage,approvedRevision?'revision_learning_writeback_required':'revision_handoff_ready');
269
273
  assert.equal(reflectedAgain.revisionRetrospective.identity.attempt,2);assert.equal(retrospectives,2);
270
274
  assert.equal(reflectedAgain.revisionRetrospective.packageDigest,cumulative.packageDigest);assert.equal(reflectedAgain.completionEligible,false);
271
275
  owner.close();owner=openFixExecution({...options,create:false});assert.deepEqual(owner.status(),reflectedAgain);
272
276
  assert.deepEqual(await owner.retrospect(),reflectedAgain);assert.equal(retrospectives,2);
273
- if(mode==='revision-approved'){
277
+ if(approvedRevision){
274
278
  assert.throws(()=>owner.writeLearning(),{code:'learning_writeback_authorization_required'});
275
279
  assert.equal(owner.createHandoff().stage,'revision_learning_writeback_required');
276
280
  const written=owner.writeLearning({authorized:true});assert.equal(written.stage,'revision_handoff_ready');
@@ -286,7 +290,7 @@ test('durable repair registers before write, preserves cause approval history an
286
290
  const secondPath=path.join(specsRoot,'.reviews','fix-owner-T-FIX-owner-a2-handoff.json');
287
291
  const secondBytes=fs.readFileSync(secondPath),secondHandoff=loadHandoff(secondPath,{task:identity.taskId,attempt:2});
288
292
  assert(secondHandoff.evidence.some(item=>item.startsWith('fix prior review')&&item.includes('F1')));
289
- if(mode==='revision-approved'){assert(secondHandoff.evidence.includes('learning: retrospective written AGENTS.md'));assert(secondHandoff.changed_files.includes('AGENTS.md'));}
293
+ if(approvedRevision){assert(secondHandoff.evidence.includes('learning: retrospective written AGENTS.md'));assert(secondHandoff.changed_files.includes('AGENTS.md'));}
290
294
  assert.deepEqual(fs.readFileSync(handoffPath),handoffBytes);assert.equal(handedAgain.completionEligible,false);
291
295
  const reviewAgain=owner.finalReviewPackage();assert.equal(reviewAgain.identity.attempt,2);assert.equal(reviewAgain.handoff.sha256,handedAgain.revisionHandoff.handoffSha256);
292
296
  assert.equal(Buffer.from(reviewAgain.changes.find(change=>change.path==='value.mjs').before.contentBase64,'base64').toString(),'export const value=1;');
@@ -300,15 +304,15 @@ test('durable repair registers before write, preserves cause approval history an
300
304
  for(const event of [{event:'thread.started',provider_thread:'second-revision-reviewer'},{event:'turn.started',item_type:null},
301
305
  {event:'item.completed',item_type:'agent_message'},{event:'turn.completed',item_type:null},{event:'process_closed',exit_code:0,signal:null,timed_out:false}])assert.equal(onEvent(event),true);
302
306
  return {status:'succeeded',value:{...request.payload.priorReview,packageDigest:reviewAgain.packageDigest,examinedPaths:reviewPaths(reviewAgain),
303
- ...(mode==='revision-approved'?{verdict:'approved',findings:[]}: {})}};
307
+ ...(approvedRevision?{verdict:'approved',findings:[]}: {})}};
304
308
  }}});
305
309
  assert.equal((await owner.reviewFinal()).stage,'revision_final_review_evidence_required');
306
- const reviewedAgain=owner.publishReview();assert.equal(reviewedAgain.stage,mode==='revision-approved'?'revision_completion_gate_required':'revision_review_limit_reached');
310
+ const reviewedAgain=owner.publishReview();assert.equal(reviewedAgain.stage,approvedRevision?'revision_completion_gate_required':'revision_review_limit_reached');
307
311
  assert.equal(reviewedAgain.completionEligible,false);assert.equal(calls,2);
308
312
  owner.close();owner=openFixExecution({...options,create:false});assert.deepEqual(owner.status(),reviewedAgain);
309
313
  assert.deepEqual(await owner.reviewFinal(),reviewedAgain);assert.equal(calls,2);
310
314
  await assert.rejects(owner.prepareRevision({authorized:true}),{code:'fix_revision_unavailable'});
311
- if(mode==='revision-approved'){
315
+ if(approvedRevision){
312
316
  const gated=owner.checkCompletionGate();assert.equal(gated.stage,'revision_post_review_regression_required');
313
317
  assert.equal(gated.revisionN5.gate.attempt,2);assert.equal(gated.completionEligible,false);
314
318
  const reviewPath=path.join(specsRoot,'.reviews','fix-owner-T-FIX-owner-r2.md'),reviewBytes=fs.readFileSync(reviewPath);
@@ -355,8 +359,8 @@ test('durable repair registers before write, preserves cause approval history an
355
359
  assert(archive.includes('先前轮次(历史记录,不替代当前审查)'));assert(archive.includes('changes_requested'));
356
360
  assert(fs.readFileSync(path.join(specsRoot,'METRICS.md'),'utf8').includes('| 2 | 1 |'));
357
361
  }
358
- fs.appendFileSync(path.join(cwd,'value.mjs'),' ');assert.equal(owner.status().stage,mode==='revision-approved'?'revision_learning_writeback_evidence_required':'revision_repair_evidence_required');
359
- if(mode==='revision-approved'){assert.equal(owner.status().completionEligible,false);assert.equal(owner.status().completionHistory.runDoneEventIds.length,1);}
362
+ fs.appendFileSync(path.join(cwd,'value.mjs'),' ');assert.equal(owner.status().stage,approvedRevision?'revision_learning_writeback_evidence_required':'revision_repair_evidence_required');
363
+ if(approvedRevision){assert.equal(owner.status().completionEligible,false);assert.equal(owner.status().completionHistory.runDoneEventIds.length,1);}
360
364
  assert.deepEqual(owner.status().revision,revised.revision);continue;
361
365
  }
362
366
  if(mode==='cause'){
@@ -43,6 +43,20 @@ for candidate in python3 python; do
43
43
  done
44
44
  [ -n "$PYTHON_BIN" ] || blocked "Python 3.9+ not found"
45
45
 
46
+ # CI 覆盖不到的那一批:它们要启动 Codex 沙箱,而在 GitHub 托管机器上 bubblewrap
47
+ # 建不了网络隔离(bwrap: loopback: Failed RTM_NEWADDR),装上 codex 也没用。
48
+ # 这个脚本上面已经要求本机装了 codex,所以这里是它们唯一稳定的落点——发版必过。
49
+ # 名单要和 .github/workflows/ci.yml 的 js-tests 排除名单保持一致。
50
+ printf '%s\n' '==> Running the Codex-sandbox tests that CI cannot host'
51
+ ( cd "$ROOT" && node --test \
52
+ scripts/cm-ai-batch-host.test.mjs \
53
+ scripts/cm-ai-bootstrap.test.mjs \
54
+ scripts/cm-ai-host.test.mjs \
55
+ scripts/cm-ai-multi-root.test.mjs \
56
+ scripts/cm-ai-nested-execution.test.mjs \
57
+ scripts/cm-fix-protected-edits.test.mjs \
58
+ scripts/cm-host-check.test.mjs )
59
+
46
60
  printf '%s\n' '==> Validating the public Pi/BYZ package manifest'
47
61
  "$PYTHON_BIN" "$ROOT/scripts/validate-public-repo.py"
48
62