@aibyzero/cm-workflow 0.16.9 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +12 -0
  3. package/README.md +9 -1
  4. package/VERSION +1 -1
  5. package/docs/cm-control-policy-v2.md +331 -0
  6. package/docs/execution-optimizations.md +1 -1
  7. package/docs/external-models.md +3 -3
  8. package/docs/human-correction.md +5 -5
  9. package/docs/installation.md +1 -1
  10. package/docs/js-workflow-control.md +101 -84
  11. package/docs/next-steps.md +11 -0
  12. package/docs/untested-branches.md +2 -3
  13. package/docs/user-guide.md +3 -3
  14. package/package.json +1 -1
  15. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +13 -69
  16. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +10 -5
  17. package/runtime/js/cm-ai/control-policy.mjs +111 -0
  18. package/runtime/js/cm-ai/drive-bootstrap.mjs +11 -8
  19. package/runtime/js/cm-ai/durable-runner-state.mjs +32 -126
  20. package/runtime/js/cm-ai/gate-bridge.mjs +4 -4
  21. package/runtime/js/cm-ai/host-conversation-execution.mjs +22 -20
  22. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +11 -2
  23. package/runtime/js/cm-ai/host-qa-policy.mjs +63 -21
  24. package/runtime/js/cm-ai/host-review-authority.mjs +2 -2
  25. package/runtime/js/cm-ai/host-review-file.mjs +1 -1
  26. package/runtime/js/cm-ai/host-tool-bridge.mjs +3 -0
  27. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +21 -10
  28. package/runtime/js/cm-ai/host.mjs +1 -2
  29. package/runtime/js/cm-ai/operator-guidance.mjs +1 -24
  30. package/runtime/js/cm-ai/review-package.mjs +16 -4
  31. package/runtime/js/cm-ai/reviewed-deliveries.mjs +1 -1
  32. package/runtime/js/cm-ai/task-runner.mjs +36 -99
  33. package/runtime/js/cm-init/review-evidence.mjs +3 -1
  34. package/runtime/js/cm-prd/review-host.mjs +1 -1
  35. package/runtime/js/cm-prd/review-publication.mjs +5 -3
  36. package/runtime/js/cm-refactor/workflow.mjs +1 -1
  37. package/runtime/js/notify-send.mjs +15 -14
  38. package/runtime/js/notify.mjs +27 -4
  39. package/runtime/js/policy-binding-compat.mjs +2 -1
  40. package/runtime/review.md +52 -7
  41. package/runtime/task-gates.md +107 -9
  42. package/scripts/cm-ai-abandon-effect-position.test.mjs +1 -8
  43. package/scripts/cm-ai-answer-gap-driver.test.mjs +12 -12
  44. package/scripts/cm-ai-answer-gap-fixture.mjs +1 -8
  45. package/scripts/cm-ai-batch-drive.mjs +50 -31
  46. package/scripts/cm-ai-batch-drive.test.mjs +62 -19
  47. package/scripts/cm-ai-batch-host.mjs +39 -20
  48. package/scripts/cm-ai-batch-host.test.mjs +62 -38
  49. package/scripts/cm-ai-batch-run-fixture.mjs +6 -53
  50. package/scripts/cm-ai-batch-run-member-stops.test.mjs +0 -12
  51. package/scripts/cm-ai-batch-run.mjs +34 -8
  52. package/scripts/cm-ai-bootstrap-flow.test.mjs +1 -7
  53. package/scripts/cm-ai-bootstrap.test.mjs +2 -3
  54. package/scripts/cm-ai-control-launch.test.mjs +219 -0
  55. package/scripts/cm-ai-control-policy.test.mjs +124 -0
  56. package/scripts/cm-ai-control-v2-drive.test.mjs +270 -0
  57. package/scripts/cm-ai-develop-answer-invalid.test.mjs +1 -8
  58. package/scripts/cm-ai-develop-call-timeout.test.mjs +1 -8
  59. package/scripts/cm-ai-develop-driver-gaps.test.mjs +33 -20
  60. package/scripts/cm-ai-direct-review.test.mjs +348 -0
  61. package/scripts/cm-ai-documentation-sync-gap.test.mjs +3 -3
  62. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +54 -25
  63. package/scripts/cm-ai-drive.mjs +96 -54
  64. package/scripts/cm-ai-drive.test.mjs +43 -84
  65. package/scripts/cm-ai-fix-integration.test.mjs +3 -5
  66. package/scripts/cm-ai-fix-later-delivery.test.mjs +3 -6
  67. package/scripts/cm-ai-fix-run-delivery.test.mjs +3 -6
  68. package/scripts/cm-ai-host-cli-workflow.test.mjs +6 -10
  69. package/scripts/cm-ai-host-fixture.mjs +38 -10
  70. package/scripts/cm-ai-host-protected.test.mjs +35 -33
  71. package/scripts/cm-ai-host.mjs +103 -93
  72. package/scripts/cm-ai-host.test.mjs +19 -18
  73. package/scripts/cm-ai-launch-diagnostics.test.mjs +5 -3
  74. package/scripts/cm-ai-legacy-history.test.mjs +53 -0
  75. package/scripts/cm-ai-light-modules.test.mjs +4 -7
  76. package/scripts/cm-ai-multi-root.test.mjs +4 -4
  77. package/scripts/cm-ai-nested-execution.test.mjs +16 -19
  78. package/scripts/cm-ai-progress.test.mjs +10 -8
  79. package/scripts/cm-ai-project-qa-gate.test.mjs +37 -10
  80. package/scripts/cm-ai-protected-scope.test.mjs +1 -2
  81. package/scripts/cm-ai-qa-config-revision.test.mjs +1 -9
  82. package/scripts/cm-ai-qa-fingerprint-config.test.mjs +12 -9
  83. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +18 -3
  84. package/scripts/cm-ai-qa-fixed-log.test.mjs +41 -0
  85. package/scripts/cm-ai-qa-recovery-args.test.mjs +7 -0
  86. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +3 -4
  87. package/scripts/cm-ai-review-drift-precedence.test.mjs +1 -1
  88. package/scripts/cm-ai-review-failure.test.mjs +13 -19
  89. package/scripts/cm-ai-review-timeout-config.test.mjs +3 -1
  90. package/scripts/cm-ai-review-timeout.test.mjs +15 -128
  91. package/scripts/cm-ai-run.mjs +78 -24
  92. package/scripts/cm-ai-run.test.mjs +11 -38
  93. package/scripts/cm-ai-selection-guard.test.mjs +2 -2
  94. package/scripts/cm-ai-session-chain.test.mjs +18 -15
  95. package/scripts/cm-ai-spec-rebind.test.mjs +14 -18
  96. package/scripts/cm-ai-supersede.test.mjs +3 -10
  97. package/scripts/cm-blocked-reason.test.mjs +2 -3
  98. package/scripts/cm-capability-gate.test.mjs +33 -1
  99. package/scripts/cm-check-drive-files.mjs +1 -1
  100. package/scripts/cm-check-runtime.sh +1 -1
  101. package/scripts/cm-claude-worker.test.mjs +5 -3
  102. package/scripts/cm-controlled-correction.test.mjs +469 -0
  103. package/scripts/cm-external-batch-host.test.mjs +30 -11
  104. package/scripts/cm-external-model-host.test.mjs +1 -1
  105. package/scripts/cm-external-model-recovery.test.mjs +3 -9
  106. package/scripts/cm-external-qa-fix.test.mjs +1 -1
  107. package/scripts/cm-external-review-reconciliation.test.mjs +6 -24
  108. package/scripts/cm-fix-review-recovery.test.mjs +1 -1
  109. package/scripts/cm-host-qa-executor.test.mjs +1 -2
  110. package/scripts/cm-host-qa-policy.test.mjs +43 -16
  111. package/scripts/cm-host-review-authority.test.mjs +0 -31
  112. package/scripts/cm-knowledge-closeout.test.mjs +3 -3
  113. package/scripts/cm-notify-command.test.mjs +54 -18
  114. package/scripts/cm-notify-read-drift.test.mjs +69 -4
  115. package/scripts/cm-notify.mjs +16 -4
  116. package/scripts/cm-notify.test.mjs +91 -19
  117. package/scripts/cm-patrol.test.mjs +3 -2
  118. package/scripts/cm-task-gate-correction.test.mjs +69 -16
  119. package/scripts/cm-task-gate.mjs +368 -34
  120. package/scripts/cm-task-gate.py +2 -0
  121. package/scripts/cm-task-gate.test.mjs +252 -4
  122. package/scripts/fixtures/bootstrap-review-runner.mjs +1 -7
  123. package/scripts/fixtures/native-gate-fixture.mjs +18 -0
  124. package/scripts/policy-binding-compat.test.mjs +4 -0
  125. package/skills/cm-ai/SKILL.md +8 -6
  126. package/skills/cm-ai/references/N3-execute-task.md +17 -2
  127. package/skills/cm-ai/references/N4-review.md +11 -21
  128. package/skills/cm-ai/references/N5-mark-done.md +1 -1
  129. package/skills/cm-ai/references/N6-qa-eval.md +49 -21
  130. package/skills/cm-ai/references/js-host-modes.md +35 -14
  131. package/skills/cm-ai/references/js-host-qa-recovery.md +60 -12
  132. package/skills/cm-ai/references/js-host-recovery.md +95 -47
  133. package/skills/cm-ai/references/js-host.md +65 -28
  134. package/skills/cm-fix/SKILL.md +12 -0
  135. package/skills/cm-init/references/js-host.md +1 -1
  136. package/skills/cm-prd/references/js-host.md +1 -1
  137. package/skills/cm-refactor/SKILL.md +12 -0
  138. package/runtime/js/cm-ai/review-dispatch-limits.mjs +0 -18
  139. package/scripts/cm-ai-review-dispatch-exit.test.mjs +0 -475
@@ -5,6 +5,8 @@ creating a second task-state database. `tasks.md` remains the authoritative
5
5
  business-task state. Handoffs and review files are content-bound evidence under the
6
6
  existing `{SPECS_DIR}/.reviews/` domain.
7
7
 
8
+ CM 门禁检查来源声明的格式、任务与轮次、材料摘要、当前文件和执行记录的一致性,用于防手滑与过期证据。来源声明不验证审查者身份或实际人工交互;门禁不承诺抵抗拥有完整文件写权限和 shell 能力的会话造假。fresh 上下文、审查结果、检查通过和完成复查仍是正常工作流路径的完成条件。发布、部署、资金及其他范围外动作继续遵守其单独确认要求。
9
+
8
10
  ## Implementation handoff
9
11
 
10
12
  The active cm-ai Skill passes `--require-learning` to `check-n4` and the existing
@@ -15,6 +17,42 @@ The flag checks record completeness, not the truth of an agent's statement; inde
15
17
  review still verifies the actual work. Legacy callers remain compatible without this
16
18
  flag, and the persistent runner retains its existing structured Learning checks.
17
19
 
20
+ Inventory verification is enabled only by the compatibility command-line entry.
21
+ `main()` passes the internal function option `inventory: 'required'` to `check-n4`,
22
+ `check-n5`, `prepare-mark-done`, `verify-mark-done-plan` and `mark-done-locked`.
23
+ Completion preparation and rechecks forward the same selectors to N5, including
24
+ human corrections. This is not a CLI flag. Exported library functions default to
25
+ the original result fields and errors without inventory checks; JS task completion,
26
+ cm-fix and cm-refactor retain their own review-package baselines.
27
+
28
+ Before compatibility N3 edits any file, the main executor captures the task's starting inventory:
29
+
30
+ ```bash
31
+ node {CM_WORKFLOW_ROOT}/scripts/cm-task-gate.mjs capture-baseline \
32
+ --project-root {CODE_PROJECT} \
33
+ --reviews-dir {SPECS_DIR}/.reviews \
34
+ --feature {FEATURE_SLUG} --task {T-xxx}
35
+ ```
36
+
37
+ This writes `{feature}-{task}-baseline.json` under the reviews directory. It seals
38
+ identity, canonical-root digest, stable ignore policy, relative file paths, SHA-256,
39
+ byte sizes and executable bits with a whole-record digest; it stores no file bodies.
40
+ The existing review-package scanner excludes dependencies, fixed junk, Git-ignored
41
+ paths and specs. A nested canonical `.reviews` parent is the specs subtree; when
42
+ `.reviews` is at the code root only that directory is excluded. Any other directory
43
+ that merely shares the `.reviews` name is ordinary code and stays in the inventory.
44
+ External specs do not enter the code root.
45
+ The same baseline/current ignore union filters both sides; AGENTS.md remains checked.
46
+ When Git ignore policy is unavailable (as may happen on Windows), scanning falls back to built-in rules; Git-ignored files count as changes and must be listed or handled before the gate can pass.
47
+ Capture refuses beyond 10,000 files or 1 GiB of inventory bytes, names the triggering
48
+ file and writes no partial baseline. Capture cannot prove it preceded an edit;
49
+ executors and independent reviewers must verify that ordering.
50
+
51
+ An existing baseline is never overwritten. If it is wrong, a human must delete
52
+ that file, capture again, and add one `decision` line to the authoritative run log.
53
+ Attempt 2 reuses attempt 1's baseline; changes accumulate from the task start.
54
+ This compatibility command supports one `--project-root`, not `codeProjectPaths`.
55
+
18
56
  For attempt 1 or 2, N3 writes:
19
57
 
20
58
  ```text
@@ -36,7 +74,7 @@ portable across macOS, Linux, and Windows.
36
74
  Before writing a new handoff, hash the exact `changed_files` set:
37
75
 
38
76
  ```bash
39
- python3 {CM_WORKFLOW_ROOT}/scripts/cm-task-gate.py hash-implementation \
77
+ node {CM_WORKFLOW_ROOT}/scripts/cm-task-gate.mjs hash-implementation \
40
78
  --project-root {CODE_PROJECT} \
41
79
  --file path/one --file path/two
42
80
  ```
@@ -48,9 +86,23 @@ symlinks and directories are rejected. Historical unbound handoffs require the
48
86
  explicit recovery flag `--allow-legacy-unbound` and return `content_bound: false`;
49
87
  new work must not use that flag.
50
88
 
51
- The gate validates declaration consistency; it does not reconstruct a task diff
52
- from an already-dirty or multi-repository working tree. N3 remains responsible
53
- for comparing `changed_files` with the task-scoped diff before writing handoff.
89
+ With a baseline, CLI `check-n4` and `check-n5` reconstruct the actual added, modified
90
+ (including executable-bit changes) and deleted paths from the starting inventory
91
+ and current tree. `changed_files` must equal that set. Mismatch lists “改了但没列”
92
+ and “列了但没改”, each capped at 20 paths with `+N more`. Success returns
93
+ `inventory: "verified"` and `inventory_counts: {added, modified, deleted}`.
94
+ Content binding remains mandatory and independent of inventory verification.
95
+ Preexisting dirty content is part of the baseline; concurrent unrelated edits are
96
+ still task-period changes and must be reconciled before review.
97
+
98
+ A missing baseline blocks these CLI entries. Only explicit `--allow-legacy-unbound`
99
+ recovery returns `inventory: "unverified"` and the fixed `inventory_note`:
100
+ “未捕获编辑前基线,不保证清单完整,只保证已列文件的内容绑定”。
101
+ If the legacy handoff also lacks its content digest, `content_bound` remains false;
102
+ the note does not create a missing content binding. The flag cannot bypass a corrupt,
103
+ wrong-task or wrong-root baseline. The unchanged handoff schema carries no baseline
104
+ fields. Before writing the handoff, reconcile the complete file list; after writing,
105
+ run N4 and keep its digest and inventory result for independent review.
54
106
 
55
107
  Validate the evidence before N4:
56
108
 
@@ -82,14 +134,58 @@ handoff_sha256: <lowercase SHA-256 returned by check-n4>
82
134
  entry and the body must contain findings or an explicit zero-findings result.
83
135
  `changes_requested` returns to N3 and produces the next attempt. N4 never edits
84
136
  implementation files. Round 2 cannot create attempt 3: another blocking result
85
- becomes `blocked` and requires human resolution under `runtime/review.md`.
137
+ becomes `blocked`. Safety/data-correctness disputes still require a real human
138
+ decision under `runtime/review.md`; the separately bounded continuation protocols
139
+ below do not create ordinary attempt 3 or erase blocking findings.
86
140
 
87
- For an explicitly human-authorized correction after round-two blocked, see
141
+ For a correction with confirmed scope after round-two blocked, see
88
142
  `docs/human-correction.md`: `prepare-human-correction` and
89
143
  `publish-human-correction-review` keep the original four records and bind a separate
90
- one-shot correction. N4/N5 and locked completion accept its fixed `--correction`
144
+ one-shot correction with its reason and bound decision-source declaration. These
145
+ records do not create approval. N4/N5 and locked completion accept its fixed `--correction`
91
146
  record; legacy-unbound flags do not weaken correction checks.
92
147
 
148
+ A separate version-two compatibility taskgate entrance provides one-shot
149
+ `cm-controlled-correction` evidence
150
+ (`version:2`, `continuation:1`), prepared by `prepare-controlled-correction` and
151
+ sealed by `publish-controlled-correction-review`; see `docs/cm-control-policy-v2.md`.
152
+ It supports only tasks without JS ownership. Retained JS journal/run/unknown
153
+ evidence blocks the compatibility writer and must reject preparation first;
154
+ prepared/published correction evidence cannot bypass that ownership gate.
155
+ `--decision-source operator|model` is provenance only, not authentication or human
156
+ approval. Neither entrance accepts `--human-authorized`; the legacy human protocol
157
+ binds only its reason and source declaration. The two continuations are mutually exclusive.
158
+ Both prepare commands hold the shared `{feature}-{task}-correction-prepare.lock`
159
+ through preparation, with PID/time ownership and fail-fast contention. A peer's
160
+ orphan handoff alone is preserved for bounded preparation recovery; any peer
161
+ record/review/receipt prevents another continuation. Interrupted locks are not
162
+ automatically removed: verify the owner has exited, inspect preparation/sealed
163
+ evidence and coordinate explicitly. An active or unknown owner never authorizes
164
+ lock deletion, retry or automatic crash recovery.
165
+ The gate pins the original r1/r2 handoff/review history, keeps blocked r2 and P2
166
+ findings, and binds the corrected implementation plus finalized Learning/handoff.
167
+ A fresh independent review must cover the complete correction scope, bind
168
+ `correction_sha256` and `handoff_sha256`, and report approved with zero blocking
169
+ findings. The v2 review's strict raw JSON body has exactly `conclusion`, `findings`
170
+ and `resolved_findings`; item keys are exactly `id`, `priority` (P0-P3), and
171
+ `evidence`, with ids unique across both arrays. Active findings count must equal
172
+ `blocking_findings`; approved requires `"Zero findings."` with no active finding,
173
+ while non-approved requires `"Blocking findings."`. Repaired historical P2 is
174
+ recorded only in resolved findings. A zero-findings phrase does not suppress an
175
+ active P2 or extra text; the old human body contract stays unchanged.
176
+ N4/N5 and locked completion consume that sealed evidence through the
177
+ existing fixed `--correction` selector. Drift, missing Learning, duplicate
178
+ continuation or a new blocking finding refuses completion; no manual checkbox,
179
+ third ordinary round, journal reset or extra completion path is introduced.
180
+ This correction slice changes only owner-free compatibility taskgate evidence
181
+ and the exact task checkbox. cm-ai v2 single-task and batch r2 remains formally
182
+ blocked, with no runner-owned correction completion entrance. Compatibility
183
+ `mark-done` cannot finish that JS-owned run, restore its batch, advance N6/N7/N8
184
+ or publish `run_done`. Never delete ownership evidence or hand-edit journal/batch
185
+ state to imply completion.
186
+ The source declaration cannot widen real dialogue authorization or external
187
+ push, publication, deployment and financial permissions.
188
+
93
189
  N5 must let the JavaScript gate validate and update the exact task checkbox while
94
190
  the compatibility entry holds the existing platform ownership lock:
95
191
 
@@ -180,8 +276,10 @@ completion. Missing independent capacity leaves work pending; do not add a skip
180
276
  flag or treat diagnostic approval as independent. Existing completed tasks are
181
277
  not automatically reopened or assigned fabricated review evidence.
182
278
 
183
- This is a declaration gate, not proof of reviewer execution, an immutable code
184
- snapshot, or full crash-recoverable completion. Any post-review change to reviewed code,
279
+ `reviewer`, `independent` and any `decision_source` are source declarations.
280
+ This gate checks their format and binding to the task, materials and execution
281
+ records; it does not authenticate the reviewer or the reported interaction. It
282
+ also does not provide an immutable code snapshot or full crash-recoverable completion. Any post-review change to reviewed code,
185
283
  tests, or instructions needs fresh evidence under `runtime/review.md`, including
186
284
  changes suggested during N5 lesson recording.
187
285
 
@@ -41,14 +41,7 @@ function execution(f,verdict='blocked'){
41
41
  requestedModel:'fixture',worker:async()=>{fs.writeFileSync(path.join(f.codeProject,'a.mjs'),'written\n');
42
42
  return {status:'succeeded',value:{outcome:'implemented',application:{status:'no_relevant_lesson',note:null},
43
43
  retrospective:{status:'no_new_lesson',candidates:[],reason:null}}};}})},
44
- reviewers:[reviewer],reviewInvocation:{developerThreadId:'author-thread',excludedThreadIds:['control'],
45
- authorize:(value,{authorizationAt})=>{const body={version:1,kind:'cm-review-dispatch-grant',
46
- grantId:'grant',adapterId:'codex-review-adapter',invocationId:value.invocationId,
47
- requestDigest:value.requestDigest,identity:value.identity,reviewerId:'reviewer',
48
- logicalContextId:value.contextId,packageDigest:value.payload.reviewPackage.packageDigest,
49
- hostContextId:'control',decisionId:'approved',decision:'approved',issuedAt:authorizationAt,
50
- expiresAt:authorizationAt+60000};return {...body,grantDigest:digest(body)};}},
51
- hostDecision:{status:'approved'},check:createHostCheck({cwd:f.codeProject,
44
+ reviewers:[reviewer],reviewInvocation:{developerThreadId:'author-thread',excludedThreadIds:['control']},check:createHostCheck({cwd:f.codeProject,
52
45
  commands:[{id:'syntax',command:[process.execPath,'--check','a.mjs']}]})};
53
46
  }
54
47
  async function start(f,runId,verdict='blocked',options={}){
@@ -20,20 +20,20 @@ test('drivers prepare the redo answer for a timed-out develop (develop_call_time
20
20
  assert.deepEqual(projectDevelopAttempts(history.state,'advance',[]).attempts,[]);
21
21
  const projected=projectedRunnerStatus(history,config);
22
22
  assert.deepEqual([projected.state,projected.code],['blocked','develop_call_timeout']);
23
- assert.deepEqual(projectDevelopAttempts(projected,'advance',[]).attempts,[1]);
24
- assert.deepEqual(batchDevelopAttempts(projected,'1.work/T-002',[]),[1]);
23
+ assert.deepEqual(projectDevelopAttempts(projected,'advance',[]).attempts,[1,2]);
24
+ assert.deepEqual(batchDevelopAttempts(projected,'1.work/T-002',[]),[1,2]);
25
25
  });
26
26
  test('drivers prepare no developer answer for a re-check (check_answer_missing)',async t=>{
27
27
  const f=gapFixture(t,'driver-recheck');
28
28
  await gapSession(f,'create',gapExecution(f,{developer:['round-1\n'],checks:['hang']}),[['advance',1]]);
29
29
  const {history,config}=replay(f),projected=projectedRunnerStatus(history,config);
30
30
  assert.deepEqual([projected.state,projected.code],['blocked','check_answer_missing']);
31
- assert.deepEqual(projectDevelopAttempts(projected,'advance',[]).attempts,[]);
32
- assert.deepEqual(batchDevelopAttempts(projected,'1.work/T-002',[]),[]);
33
- // Codex round 1: with the round-1 review authorized, the same advance can reach round 2.
34
- const reach=projectDevelopAttempts(projected,'advance',['--allow-review-attempt','1']);
31
+ assert.deepEqual(projectDevelopAttempts(projected,'advance',[]).attempts,[2]);
32
+ assert.deepEqual(batchDevelopAttempts(projected,'1.work/T-002',[]),[2]);
33
+ // Codex round 1: with direct round-1 review, the same advance can reach round 2.
34
+ const reach=projectDevelopAttempts(projected,'advance',[]);
35
35
  assert.deepEqual([reach.attempts,reach.reviewAfterDevelop,reach.holdable],[[2],true,true]);
36
- assert.deepEqual(batchDevelopAttempts(projected,'1.work/T-002',['--allow-review','1.work/T-002:1']),[2]);
36
+ assert.deepEqual(batchDevelopAttempts(projected,'1.work/T-002',[]),[2]);
37
37
  // Without a round-2 answer the driver launches with --hold-revision: the re-check and
38
38
  // its review run, then the task stops at changes_requested; no develop is asked.
39
39
  const before=f.calls.developer;
@@ -41,11 +41,11 @@ test('drivers prepare no developer answer for a re-check (check_answer_missing)'
41
41
  assert.deepEqual([held.state,held.code,held.identity.attempt],['changes_requested','revision_answer_required',2],JSON.stringify(held));
42
42
  assert.equal(f.calls.developer,before);
43
43
  });
44
- test('drivers preflight both rounds for a retryable round-1 block when the round-1 review is authorized',()=>{
44
+ test('drivers preflight both rounds for a retryable round-1 block before direct round-1 review',()=>{
45
45
  const status={state:'blocked',code:'develop_call_timeout',attempt:1};
46
- const reach=projectDevelopAttempts(status,'advance',['--allow-review-attempt','1']);
46
+ const reach=projectDevelopAttempts(status,'advance',[]);
47
47
  assert.deepEqual([reach.attempts,reach.reviewAfterDevelop],[[1,2],true]);
48
- assert.deepEqual(projectDevelopAttempts(status,'advance',[]).attempts,[1]);
49
- assert.deepEqual(batchDevelopAttempts(status,'1.work/T-002',['--allow-review','1.work/T-002:1']),[1,2]);
50
- assert.deepEqual(batchDevelopAttempts({...status,attempt:2},'1.work/T-002',['--allow-review','1.work/T-002:1']),[2]);
48
+ assert.deepEqual(projectDevelopAttempts(status,'advance',[]).attempts,[1,2]);
49
+ assert.deepEqual(batchDevelopAttempts(status,'1.work/T-002',[]),[1,2]);
50
+ assert.deepEqual(batchDevelopAttempts({...status,attempt:2},'1.work/T-002',[]),[2]);
51
51
  });
@@ -67,14 +67,7 @@ export function gapExecution(f,{developer=[],checks=[],verdicts=[]}={}){
67
67
  throw Object.assign(new Error(beforeDispatch),{code:beforeDispatch});}
68
68
  return developerRun(request,control);
69
69
  }},
70
- reviewers:[reviewer],reviewInvocation:{developerThreadId:'author-thread',excludedThreadIds:['control'],
71
- authorize:(value,{authorizationAt})=>{const body={version:1,kind:'cm-review-dispatch-grant',
72
- grantId:'grant',adapterId:'codex-review-adapter',invocationId:value.invocationId,
73
- requestDigest:value.requestDigest,identity:value.identity,reviewerId:'reviewer',
74
- logicalContextId:value.contextId,packageDigest:value.payload.reviewPackage.packageDigest,
75
- hostContextId:'control',decisionId:'approved',decision:'approved',issuedAt:authorizationAt,
76
- expiresAt:authorizationAt+60000};return {...body,grantDigest:digest(body)};}},
77
- hostDecision:{status:'approved'},check:(request,control)=>{
70
+ reviewers:[reviewer],reviewInvocation:{developerThreadId:'author-thread',excludedThreadIds:['control']},check:(request,control)=>{
78
71
  f.calls.check++;
79
72
  const item=checkQueue.shift();
80
73
  if(item==='hang')return new Promise(()=>{});
@@ -22,14 +22,15 @@ import fs from 'node:fs';
22
22
  import path from 'node:path';
23
23
  import {fileURLToPath} from 'node:url';
24
24
  import {createHostCheck,reportHostCheckProgress} from '../runtime/js/cm-ai/host-check.mjs';
25
- import {decideHostQaPolicy} from '../runtime/js/cm-ai/host-qa-policy.mjs';
25
+ import {readQaAssessment} from '../runtime/js/cm-ai/host-qa-policy.mjs';
26
26
  import {validateHostWorkflowConfiguration} from '../runtime/js/cm-ai/host-workflow-capabilities.mjs';
27
27
  import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
28
28
  import {validateRunDefinition} from './cm-ai-run.mjs';
29
29
  import {createCmAiBatch} from './cm-ai-batch-run.mjs';
30
30
  import {readConversationReviewConfiguration,readConversationProtection} from './cm-ai-host.mjs';
31
31
  import {validateCmAiAnswer,developFilename,preflightDevelopDeliveries,baselineScope,inputLimitFrom,
32
- applyDevelopEdits,protectedDevelopEdits,developPreview,plannedCheckResults,journalRestBytes} from './cm-ai-drive.mjs';
32
+ applyDevelopEdits,protectedDevelopEdits,developPreview,plannedCheckResults,journalRestBytes,
33
+ readDriverControl,controlDevelopAttempts} from './cm-ai-drive.mjs';
33
34
  import {readExecutionSnapshot} from '../runtime/js/cm-ai/execution-snapshot.mjs';
34
35
  import {readRunnerHistory,projectedRunnerStatus,RECHECK_CODES,DOCUMENTATION_SYNC_CODES} from '../runtime/js/cm-ai/durable-runner-state.mjs';
35
36
  import {developmentRetryable} from '../runtime/js/cm-ai/cm-ai-conversation-entry.mjs';
@@ -45,7 +46,7 @@ const KINDS={develop:'develop.json',qa_assess:'qa-assess.json',
45
46
  const MEMBER_ACTION_FLAGS={develop_redo:'--allow-develop-redo',abandon_effect:'--allow-abandon-effect',
46
47
  abandon_review:'--allow-abandon-review',bootstrap_review_recover:'--allow-bootstrap-review-recovery'};
47
48
  const PAIRS=new Set(['--external-models-config','--runtime','--review-config','--browser-qa','--protected-conversation-config',
48
- '--protected-config','--allow-provider-development','--allow-review','--input-limit','--qa-environment-failure',...Object.values(MEMBER_ACTION_FLAGS)]);
49
+ '--protected-config','--allow-provider-development','--input-limit','--qa-environment-failure',...Object.values(MEMBER_ACTION_FLAGS)]);
49
50
  const FLAGS=new Set(['--execution-optimizations','--external-models','--allow-qa','--rerun-unknown-qa','--rerun-blocked-qa','--verification-precheck',
50
51
  '--allow-bootstrap-write']);
51
52
  const isObject=x=>x!==null&&typeof x==='object'&&!Array.isArray(x);
@@ -60,23 +61,21 @@ export function batchMemberActionPlanError(operation,plan,permissions,keys){
60
61
  if(!permissions.some((name,index)=>name===flag&&permissions[index+1]===plan.taskKey))return `${operation} 需要 permissions 中的 ${flag} ${plan.taskKey}`;
61
62
  return null;
62
63
  }
63
- export function batchDevelopAttempts(state,key,permissions){
64
- // The round-1 review this launch authorizes may lead into round 2 within the
64
+ export function batchDevelopAttempts(state,key,permissions,controlPolicy=null){
65
+ if(controlPolicy)return controlPolicy.development==='provider'?[]:controlDevelopAttempts(state,'advance').attempts;
66
+ // The configured round-1 review may lead into round 2 within the
65
67
  // same advance (Codex round 1 on Q28): list it too; a missing a2 answer then
66
68
  // holds the task after that review (revision_answer_required) instead of
67
69
  // sending an unanswerable develop request.
68
- const reviewNext=state.attempt===1&&permissions.some((flag,index)=>flag==='--allow-review'&&permissions[index+1]===`${key}:1`);
70
+ const reviewNext=state.attempt===1;
69
71
  // A re-check (check_answer_*) re-runs only the checks: no developer answer for this round.
70
72
  if(state.state==='blocked'&&RECHECK_CODES.includes(state.code))return reviewNext?[2]:[];
71
73
  // Q16/Q17: a documentation-only redo reuses the journaled developer answer.
72
74
  if(state.state==='blocked'&&DOCUMENTATION_SYNC_CODES.includes(state.code))return reviewNext?[2]:[];
73
75
  if(developmentRetryable(state))return reviewNext?[1,2]:[state.attempt];
74
- if(state.state==='ready'&&state.attempt===1&&permissions.some((flag,index)=>
75
- flag==='--allow-review'&&permissions[index+1]===`${key}:1`))return [1,2];
76
+ if(state.state==='ready'&&state.attempt===1)return [1,2];
76
77
  if(['ready','changes_requested'].includes(state.state))return [state.attempt];
77
- if(['awaiting_review','pending_review'].includes(state.state)&&state.attempt<2
78
- &&permissions.some((flag,index)=>flag==='--allow-review'
79
- &&permissions[index+1]===`${key}:${state.attempt}`))return [state.attempt+1];
78
+ if(['awaiting_review','pending_review'].includes(state.state)&&state.attempt<2)return [state.attempt+1];
80
79
  return [];
81
80
  }
82
81
  function actualCwd(bundle,key,generation=1){
@@ -105,16 +104,21 @@ function checkCommandShape(commands,key,plan,executionPolicy){
105
104
  }
106
105
  function preflight(){
107
106
  if(process.argv.length===3&&['--help','-h'].includes(process.argv[2])){
107
+ process.stdout.write('新版 PLAN.controlConfig 为相对 PLAN 的 v2 控制配置路径;permissions 禁止所有 --allow-*,批次 qaFix 只能为 disabled。普通 advance 自动独立审查;缺少 develop-a2.json 时保持 revision_answer_required。显式成员恢复需要 resume、taskKey 与此前 status 返回的 PLAN.expectedControl,驾驶员不会读取新目标覆盖它。\n');
108
108
  process.stdout.write('用法: cm-ai-batch-drive.mjs --plan PLAN.json <operation>\n'
109
109
  +'operation: advance, status, cancel, reconcile_review(taskKey、invocationId), develop_redo / abandon_effect / abandon_review / bootstrap_review_recover(resume、PLAN.taskKey、单行 PLAN.reason,permissions 带对应 --allow-… 任务)。PLAN: config, mode, hostContext, permissions, answers, checks, checkTimeoutMs。\n'
110
110
  +'checks 每项为 {id,command,timeoutMs?};超时为 1..3600000 整数,默认 900000 ms(15 分钟)。\n'
111
111
  +'develop.json.edits 与单任务驾驶员相同:内容文件、{file,mode}、{mode}、{delete:true};启动前同样拒绝超限、空交付与受保护模式下的非 UTF-8 内容(尚未开跑的后续任务不看代码树,只做答案本身就能判定的检查:单文件 1 MiB、答案写入的 scope 文件合计 2 MiB,等等;运行存档单条记录上限要看该任务开跑时的代码树,驾驶员事先算不出,超限交付写入后由宿主拦下,停在可重试的 blocked/develop_package_too_large)。\n'
112
- +'带 --allow-review 任务:1 但还没有 develop-a2.json 时照常启动:审查若要求修改,该任务停在 changes_requested(revision_answer_required),读 .reviews/<feature>-<task>-r1.md 的 findings 写好 develop-a2.json 后再 advance。\n');
112
+ +'按已有配置自动审查,还没有 develop-a2.json 时照常启动:审查若要求修改,该任务停在 changes_requested(revision_answer_required),读 .reviews/<feature>-<task>-r1.md 的 findings 写好 develop-a2.json 后再 advance。\n');
113
113
  process.exit(0);
114
114
  }
115
115
  const loaded=loadPlanFile({name:'cm-ai-batch-drive.mjs',known:new Set(['advance','status','cancel','reconcile_review',...Object.keys(MEMBER_ACTION_FLAGS)])});
116
116
  const {plan,base,operation}=loaded;
117
117
  requireFields(plan,['config','mode','hostContext','permissions']);
118
+ let control;
119
+ try{control=readDriverControl(plan,base,operation,operation==='reconcile_review'||Object.hasOwn(MEMBER_ACTION_FLAGS,operation));}
120
+ catch(error){stop(2,error.message);}
121
+ if(control&&control.policy.qaFix!=='disabled')stop(2,'invalid_arguments: batch qaFix 必须为 disabled');
118
122
  try{planCheckTimeout(plan);}catch(error){stop(2,error.message);}
119
123
  if(!['create','resume'].includes(plan.mode))stop(2,'mode 只能是 create 或 resume');
120
124
  if(!nonempty(plan.hostContext))stop(2,'hostContext 必须是当前真实会话 ID');
@@ -186,7 +190,11 @@ function preflight(){
186
190
  let externalModels;
187
191
  try{externalModels=readBatchExternalModels({batch,started:hasStore,enabled:permissions.includes('--external-models'),inputFile:argumentValue('--external-models-config'),providers:[routes.coderRuntime,routes.reviewerRuntime].filter(Boolean)});}catch(error){stop(2,error.code??'external_model_configuration_invalid');}
188
192
  if(operation==='reconcile_review'&&(plan.mode!=='resume'||!keys.includes(plan.taskKey)||!nonempty(plan.invocationId)))stop(2,'reconcile_review requires resume, taskKey and original invocationId');
189
- const memberError=batchMemberActionPlanError(operation,plan,permissions,keys);if(memberError)stop(2,memberError);
193
+ if(control&&Object.hasOwn(MEMBER_ACTION_FLAGS,operation)){
194
+ if(!keys.includes(plan.taskKey)||!nonempty(plan.reason)||Buffer.byteLength(plan.reason,'utf8')>500||/[\r\n\0]/.test(plan.reason))
195
+ stop(2,`${operation} 需要本批次 taskKey、expectedControl 与单行 reason(最多 500 UTF-8 字节)`);
196
+ }
197
+ const memberError=control?null:batchMemberActionPlanError(operation,plan,permissions,keys);if(memberError)stop(2,memberError);
190
198
  for(let i=0;i<permissions.length;i++)if(PAIRS.has(permissions[i])){
191
199
  const name=permissions[i],value=permissions[++i];
192
200
  if(['--review-config','--protected-conversation-config','--protected-config'].includes(name)){
@@ -206,7 +214,7 @@ function preflight(){
206
214
  permissions[i]=file;
207
215
  }else if(Object.values(MEMBER_ACTION_FLAGS).includes(name)){
208
216
  if(!keys.includes(value))stop(2,`${name} 需要本批次的 FEATURE/TASK: ${value}`);
209
- }else if(['--allow-review','--allow-provider-development'].includes(name)){
217
+ }else if(name==='--allow-provider-development'){
210
218
  const cut=value.lastIndexOf(':');
211
219
  if(!keys.includes(value.slice(0,cut))||!['1','2'].includes(value.slice(cut+1)))
212
220
  stop(2,`${name} 任务授权无效: ${value}`);
@@ -217,14 +225,12 @@ function preflight(){
217
225
  stop(2,'--runtime 只能是 codex 或 claude');
218
226
  if(permissions.includes('--browser-qa')&&!['available','unavailable'].includes(argument('--browser-qa')))
219
227
  stop(2,'--browser-qa 只能是 available 或 unavailable');
220
- if(permissions.includes('--allow-review')&&!permissions.includes('--review-config'))
221
- stop(2,'--allow-review 需要 --review-config');
222
228
  if(permissions.includes('--allow-provider-development')&&!permissions.includes('--protected-config'))
223
229
  stop(2,'--allow-provider-development 需要 --protected-config');
224
- if(Object.values(bundle.workflows).some(workflow=>workflow?.qa)&&!permissions.includes('--allow-qa'))
230
+ if(!control&&Object.values(bundle.workflows).some(workflow=>workflow?.qa)&&!permissions.includes('--allow-qa'))
225
231
  stop(2,'有 QA 工作流时缺少 --allow-qa');
226
232
  const protectedMode=permissions.includes('--protected-config')||permissions.includes('--protected-conversation-config');
227
- const providerAll=permissions.includes('--protected-config')&&keys.every(key=>
233
+ const providerAll=control?control.policy.development==='provider':permissions.includes('--protected-config')&&keys.every(key=>
228
234
  permissions.includes(`${key}:1`)&&permissions[permissions.indexOf(`${key}:1`)-1]==='--allow-provider-development');
229
235
  let live;
230
236
  try{live=driverLiveEvidence(plan,{base,protectedRoots:[batch.codeProject,batch.specsDir,path.resolve(batch.codeProject,'..','.cm-worktrees'),...(batch.codeProjects??[])],
@@ -246,11 +252,13 @@ function preflight(){
246
252
  kinds.push('check');
247
253
  if(workflow?.documentationPaths?.length)kinds.push('documentation_sync');
248
254
  }
249
- if(workflow?.qa){
255
+ if(workflow&&(control||workflow.qa)){
250
256
  // A rescheduled second generation runs serially and asks qa_assess like a serial task.
251
257
  if(!batch.parallel?.some(group=>group.includes(key))||rescheduled.has(key))kinds.push('qa_assess');
252
- const cases=readJson(path.join(batch.specsDir,task.feature,'test-cases.json'),'test-cases');
253
- for(const kind of ['logic','browser'])if(cases?.cases?.some(item=>item.kind===kind))kinds.push(`qa_${kind}`);
258
+ if(workflow.qa&&(!control||control.policy.qa==='run')){
259
+ const cases=readJson(path.join(batch.specsDir,task.feature,'test-cases.json'),'test-cases');
260
+ for(const kind of ['logic','browser'])if(cases?.cases?.some(item=>item.kind===kind))kinds.push(`qa_${kind}`);
261
+ }
254
262
  }
255
263
  if(workflow)kinds.push('documentation_inspect');
256
264
  const evidence=kinds.filter(kind=>['qa_logic','qa_browser'].includes(kind)&&!live.has(kind));
@@ -271,23 +279,23 @@ function preflight(){
271
279
  const snapshot=readExecutionSnapshot({specsRoot:batch.specsDir,identity:{repositoryId:batch.repositoryId,runId:existing[0]}});
272
280
  const history=readRunnerHistory(snapshot.records,snapshot.records[0].payload.config,3);
273
281
  // Q28: decide from what the host will show (projected answer-gap blocks), not the raw replay state.
274
- attempts=batchDevelopAttempts(projectedRunnerStatus(history,snapshot.records[0].payload.config),key,permissions);current=history.state.attempt;
282
+ attempts=batchDevelopAttempts(projectedRunnerStatus(history,snapshot.records[0].payload.config),key,permissions,control?.policy??null);current=history.state.attempt;
275
283
  journal={baseline:snapshot.records[0].payload.baseline,generation:existing[1].generation,
276
284
  frame:journalRestBytes(snapshot.records)};
277
285
  }catch(error){stop(2,`任务 ${key} 无法只读检查恢复存档: ${error.code??error.message}`);}
278
286
  }
279
287
  // A task with no run yet (a new batch, or a later task on resume) starts at
280
- // attempt 1; a first-round review grant can then reach attempt 2 as well.
281
- if(journal===null&&permissions.some((flag,index)=>flag==='--allow-review'&&permissions[index+1]===`${key}:1`))attempts=[1,2];
288
+ // attempt 1; the configured first-round review can reach attempt 2 as well.
289
+ if(journal===null)attempts=[1,2];
282
290
  const deliveries=[],definition=definitions.get(key);
283
291
  for(const attempt of attempts){
284
292
  const file=path.join(taskRoot??'',developFilename(taskRoot??'',attempt));
285
293
  if(!taskRoot||!fs.existsSync(file)){
286
- // A later attempt is only reached if the review this launch authorizes asks
294
+ // A later attempt is only reached if the configured review asks
287
295
  // for changes. Without its answer the task stops right after that review.
288
296
  if(attempt>current){
289
297
  holds.push(key);
290
- stderr(`任务 ${key} 没有 ${path.basename(file)}:本次授权的审查若要求修改,任务会停在 changes_requested(revision_answer_required),不会发起第 ${attempt} 轮开发;读取 .reviews/${task.feature.replace(/^\d+\./,'')}-${task.taskId}-r${attempt-1}.md 的 findings,写 ${file} 后再 advance`);
298
+ stderr(`任务 ${key} 没有 ${path.basename(file)}:本次审查若要求修改,任务会停在 changes_requested(revision_answer_required),不会发起第 ${attempt} 轮开发;读取 .reviews/${task.feature.replace(/^\d+\./,'')}-${task.taskId}-r${attempt-1}.md 的 findings,写 ${file} 后再 advance`);
291
299
  continue;
292
300
  }
293
301
  stop(2,attempt===1?`任务 ${key} 会反问 develop,但答案文件不存在: ${file}`
@@ -322,7 +330,7 @@ function preflight(){
322
330
  if(answers[key].documentation_sync)for(const target of Object.keys(answers[key].documentation_sync.edits))
323
331
  if(!workflow.documentationPaths.includes(target))stop(2,`任务 ${key} documentation-sync.json.edits 越过文档 scope: ${target}`);
324
332
  }
325
- return {...loaded,executionPolicy,bundle,definitions,runs,config,permissions,answers,developAnswers,answerRoot:root,holds,live};
333
+ return {...loaded,control,executionPolicy,bundle,definitions,runs,config,permissions,answers,developAnswers,answerRoot:root,holds,live};
326
334
  }
327
335
 
328
336
  let loaded;
@@ -382,16 +390,27 @@ async function answerFor(row,answers,paths,control){
382
390
  contextDigest:row.payload.contextDigest,
383
391
  at:value.at??new Date().toISOString().replace(/\.\d{3}Z$/,'Z')};
384
392
  if(row.kind==='qa_assess'){
385
- decideHostQaPolicy({assessment:value,pending:1,mergeEligible:false,unassessedTasks:1});return value;
393
+ readQaAssessment(value);return value;
386
394
  }
387
395
  return null;
388
396
  }
397
+ export function buildCmAiBatchDriveHostArgs(plan,permissions,config,controlConfig=null,holds=[]){
398
+ return ['serve','--config',config,...(Object.hasOwn(plan,'controlConfig')?['--mode',plan.mode]:[]),
399
+ '--host-context',plan.hostContext,
400
+ ...(Object.hasOwn(plan,'controlConfig')?['--control-config',controlConfig??plan.controlConfig]:['--allow-development']),
401
+ ...permissions,...holds.flatMap(key=>['--hold-revision',key])];
402
+ }
403
+ export function buildCmAiBatchDriveRequest(operation,plan){
404
+ const recovery=operation==='reconcile_review'||Object.hasOwn(MEMBER_ACTION_FLAGS,operation);
405
+ return {...(Object.hasOwn(plan,'controlConfig')?{version:2,...(recovery?{expectedControl:plan.expectedControl}:{})}:{}),
406
+ ...(operation==='reconcile_review'?{taskKey:plan.taskKey,invocationId:plan.invocationId}
407
+ :Object.hasOwn(MEMBER_ACTION_FLAGS,operation)?{taskKey:plan.taskKey,reason:plan.reason}:{})};
408
+ }
389
409
  function main(){
390
410
  loaded=preflight();
391
411
  const {plan,operation,bundle,config,permissions}=loaded;
392
- driveHost({host:HOST,args:['serve','--config',config,'--host-context',plan.hostContext,
393
- '--allow-development',...permissions,...loaded.holds.flatMap(key=>['--hold-revision',key])],cwd:bundle.batch.codeProject,operation,request:operation==='reconcile_review'?{taskKey:plan.taskKey,invocationId:plan.invocationId}
394
- :Object.hasOwn(MEMBER_ACTION_FLAGS,operation)?{taskKey:plan.taskKey,reason:plan.reason}:{},
412
+ driveHost({host:HOST,args:buildCmAiBatchDriveHostArgs(plan,permissions,config,loaded.control?.file,loaded.holds),
413
+ cwd:bundle.batch.codeProject,operation,request:buildCmAiBatchDriveRequest(operation,plan),
395
414
  answers:loaded.answers,answerFor});
396
415
  }
397
416
  if(process.argv[1]&&fs.realpathSync(process.argv[1])===fileURLToPath(import.meta.url))main();