@aibyzero/cm-workflow 0.25.0 → 0.25.1

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 (46) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +12 -0
  3. package/README.md +6 -1
  4. package/VERSION +1 -1
  5. package/docs/installation.md +28 -10
  6. package/docs/js-workflow-control.md +2 -1
  7. package/package.json +1 -1
  8. package/runtime/js/cm-ai/claude-probe-diagnosis.mjs +21 -0
  9. package/runtime/js/cm-ai/claude-review-stream.mjs +20 -7
  10. package/runtime/js/cm-ai/claude-tool-preview.mjs +4 -2
  11. package/runtime/js/cm-ai/host-conversation-execution.mjs +7 -1
  12. package/runtime/js/cm-ai/worker-claude-developer.mjs +3 -1
  13. package/runtime/js/cm-ai/worker-claude.mjs +5 -1
  14. package/runtime/js/cm-check/host.mjs +13 -3
  15. package/runtime/js/cm-prd/review-channels.mjs +5 -0
  16. package/runtime/js/cm-prd/review-publication.mjs +2 -1
  17. package/scripts/cm-ai-batch-host.mjs +10 -3
  18. package/scripts/cm-ai-batch-host.test.mjs +1 -0
  19. package/scripts/cm-ai-batch-run.mjs +2 -1
  20. package/scripts/cm-ai-host.mjs +4 -1
  21. package/scripts/cm-check-host.test.mjs +54 -0
  22. package/scripts/cm-check-runtime.sh +18 -15
  23. package/scripts/cm-check-update.mjs +83 -8
  24. package/scripts/cm-check-update.test.mjs +114 -1
  25. package/scripts/cm-claude-developer-worker.test.mjs +29 -1
  26. package/scripts/cm-claude-managed-preflight.test.mjs +126 -0
  27. package/scripts/cm-claude-probe.test.mjs +5 -0
  28. package/scripts/cm-claude-review-stream.test.mjs +4 -1
  29. package/scripts/cm-claude-worker.test.mjs +29 -0
  30. package/scripts/cm-fix-review-preflight.mjs +2 -0
  31. package/scripts/cm-fix-review-verification-integration.test.mjs +19 -0
  32. package/scripts/cm-prd-drive.mjs +2 -1
  33. package/scripts/cm-prd-drive.test.mjs +17 -0
  34. package/scripts/cm-prd-review-gate.mjs +2 -1
  35. package/scripts/cm-prd-review-publication.test.mjs +34 -0
  36. package/scripts/cm-release-smoke.sh +3 -2
  37. package/scripts/cm-workflow-config.test.mjs +8 -3
  38. package/scripts/fixtures/prd-review-gate-python-oracle.py +1 -1
  39. package/scripts/scan-public-safety.py +1 -0
  40. package/scripts/shell-pipe-early-exit.test.mjs +96 -0
  41. package/scripts/test-cm-prd-review-gate.py +30 -0
  42. package/scripts/test-shell-compat.sh +7 -5
  43. package/skills/cm-ai/references/js-host-recovery.md +1 -0
  44. package/skills/cm-check/SKILL.md +3 -0
  45. package/skills/cm-fix/references/isolated-review.md +1 -1
  46. package/templates/auto-update/cm-update.sh +2 -2
@@ -3,6 +3,9 @@ set -euo pipefail
3
3
 
4
4
  ROOT="$(cd "$(dirname "$0")/.." && pwd)"
5
5
  FAILURES=0
6
+ # Substring test without a pipe or temp file: under pipefail, `printf | grep -q`
7
+ # can fail with SIGPIPE, and bash 3.2 here-strings need a writable temp dir.
8
+ contains() { case "$1" in *"$2"*) return 0 ;; esac; return 1; }
6
9
 
7
10
  fail() {
8
11
  echo "FAIL: $*" >&2
@@ -553,8 +556,8 @@ grep -q "never satisfies N4" "$ROOT/runtime/external-expert.md" ||
553
556
  fail "external-expert can be mistaken for independent review"
554
557
  grep -Fq "Version 1 external-expert evidence never satisfies" "$ROOT/runtime/review.md" ||
555
558
  fail "independent review contract does not exclude external-expert evidence"
556
- tr -d '\r' < "$ROOT/runtime/review.md" | tr '\n' ' ' |
557
- grep -Fq "A conversation that contributed to the plan, diagnosis, tests, or patch is an authoring channel" ||
559
+ review_flat="$(tr -d '\r' < "$ROOT/runtime/review.md" | tr '\n' ' ')" || review_flat=""
560
+ contains "$review_flat" "A conversation that contributed to the plan, diagnosis, tests, or patch is an authoring channel" ||
558
561
  fail "independent review contract does not preserve all external authoring categories"
559
562
  grep -Fq '{SPECS_DIR}/.external/' "$ROOT/runtime/external-expert.md" ||
560
563
  fail "external-expert has no isolated evidence location"
@@ -759,14 +762,14 @@ prd_spec_review_section=$(sed -n '/^### Step 10\.6:/,/^### Step 11:/p' \
759
762
  "$ROOT/skills/cm-prd/SKILL.md")
760
763
  [ "$(printf '%s' "$prd_design_review_section" | grep -Fc 'ROUND_LIMIT=1')" -eq 1 ] &&
761
764
  [ "$(printf '%s' "$prd_spec_review_section" | grep -Fc 'ROUND_LIMIT=1')" -eq 1 ] &&
762
- printf '%s' "$prd_design_review_section" | grep -Fq '后续 10.5 自检' &&
763
- printf '%s' "$prd_spec_review_section" | grep -Fq '重跑一次 10.5 自检' &&
764
- printf '%s' "$prd_design_review_section" | grep -Fq '禁止 review → 修正 → 再 review' &&
765
- printf '%s' "$prd_spec_review_section" | grep -Fq '禁止 review → 修正 → 再 review' &&
766
- printf '%s' "$prd_design_review_section" | grep -Fq '包括 `self-degraded`' &&
767
- printf '%s' "$prd_spec_review_section" | grep -Fq '包括 `self-degraded`' &&
768
- printf '%s' "$prd_design_review_section" | grep -Fq '不得生成 `design-r2.md`' &&
769
- printf '%s' "$prd_spec_review_section" | grep -Fq '不得生成 `split-r2.md`' &&
765
+ contains "$prd_design_review_section" '后续 10.5 自检' &&
766
+ contains "$prd_spec_review_section" '重跑一次 10.5 自检' &&
767
+ contains "$prd_design_review_section" '禁止 review → 修正 → 再 review' &&
768
+ contains "$prd_spec_review_section" '禁止 review → 修正 → 再 review' &&
769
+ contains "$prd_design_review_section" '包括 `self-degraded`' &&
770
+ contains "$prd_spec_review_section" '包括 `self-degraded`' &&
771
+ contains "$prd_design_review_section" '不得生成 `design-r2.md`' &&
772
+ contains "$prd_spec_review_section" '不得生成 `split-r2.md`' &&
770
773
  grep -Fq 'cm-prd Step 9.5/10.6 固定为一次审查调用' \
771
774
  "$ROOT/runtime/review.md" &&
772
775
  grep -Fq 'The rules in this section apply to N4 reviews of implemented task diffs.' \
@@ -774,10 +777,10 @@ prd_spec_review_section=$(sed -n '/^### Step 10\.6:/,/^### Step 11:/p' \
774
777
  grep -Fq 'Maximum two review rounds per task.' "$ROOT/runtime/review.md" &&
775
778
  grep -Fq 'reviewer/independent/at/scope' "$ROOT/runtime/review.md" ||
776
779
  fail "cm-prd pre-implementation reviews are not mechanically limited to one round"
777
- printf '%s' "$prd_design_review_section" | grep -Fq 'cm-prd-review-gate.py inspect --stage design' &&
778
- printf '%s' "$prd_spec_review_section" | grep -Fq 'cm-prd-review-gate.py inspect --stage split' &&
779
- printf '%s' "$prd_design_review_section" | grep -Fq 'resume_disposition' &&
780
- printf '%s' "$prd_spec_review_section" | grep -Fq 'resume_disposition' &&
780
+ contains "$prd_design_review_section" 'cm-prd-review-gate.py inspect --stage design' &&
781
+ contains "$prd_spec_review_section" 'cm-prd-review-gate.py inspect --stage split' &&
782
+ contains "$prd_design_review_section" 'resume_disposition' &&
783
+ contains "$prd_spec_review_section" 'resume_disposition' &&
781
784
  grep -Fq 'r1 内容哈希漂移' "$ROOT/runtime/review.md" ||
782
785
  fail "cm-prd single-round reviews have no crash-safe disposition recovery gate"
783
786
 
@@ -1058,7 +1061,7 @@ done
1058
1061
 
1059
1062
  while IFS= read -r skill; do
1060
1063
  dir="$(basename "$(dirname "$skill")")"
1061
- declared="$(sed -n 's/^name:[[:space:]]*//p' "$skill" | head -n 1 | tr -d '\r\"')"
1064
+ declared="$(sed -n 's/^name:[[:space:]]*//p' "$skill" | sed -n '1p' | tr -d '\r\"')"
1062
1065
  [ "$declared" = "$dir" ] || fail "skill name mismatch: ${skill#$ROOT/} declares '$declared'"
1063
1066
  done < <(find "$ROOT/skills" -mindepth 2 -maxdepth 2 -name SKILL.md -type f | sort)
1064
1067
 
@@ -5,9 +5,33 @@ import os from 'node:os';
5
5
  import path from 'node:path';
6
6
  import https from 'node:https';
7
7
  import {spawnSync} from 'node:child_process';
8
+ import {createHash} from 'node:crypto';
8
9
  import {fileURLToPath, pathToFileURL} from 'node:url';
9
10
 
10
11
  const PACKAGE = '@aibyzero/cm-workflow';
12
+ const MANIFESTS = {claude: 'cm-workflow/install-manifest.sha256', codex: '.cm-install-manifest.sha256'};
13
+ const DIGEST = /^[0-9a-f]{64}$/;
14
+ const FIND_EDITS = '. "$1" && cm_manifest_select_hasher || exit 4; ' +
15
+ 'cm_manifest_find_edits "$2" "$3" "$4/edits" "$4"; status=$?; [ "$status" -eq 0 ] && cat "$4/edits"; exit "$status"';
16
+
17
+ // Lists the locally edited CM files with the installer's own manifest helper, so an approval can be
18
+ // bound to exactly these files (2026-12 review: a global overwrite also took edits made after the
19
+ // user agreed, and let a malformed manifest through).
20
+ export function findLocalEdits({helper, target, manifest}, {run = spawnSync} = {}) {
21
+ const lexists = file => { try { fs.lstatSync(file); return true; } catch (error) { if (error.code === 'ENOENT') return false; throw error; } };
22
+ if (!lexists(manifest)) return {state: 'no-manifest', files: []};
23
+ const work = fs.mkdtempSync(path.join(os.tmpdir(), 'cm-check-edits-'));
24
+ try {
25
+ const found = run('/bin/bash', ['-c', FIND_EDITS, 'cm-find-edits', helper, target, manifest, work],
26
+ {encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 4 * 1024 * 1024});
27
+ if (found.error || found.signal) return {state: 'error', files: []};
28
+ if (found.status === 3) return {state: 'invalid', files: []};
29
+ if (found.status !== 0) return {state: 'error', files: []};
30
+ const files = found.stdout.split('\n').filter(Boolean);
31
+ return {state: files.length ? 'edits' : 'none', files};
32
+ } finally { fs.rmSync(work, {recursive: true, force: true}); }
33
+ }
34
+ export const editsDigest = files => createHash('sha256').update(files.join('\n')).digest('hex');
11
35
  const REGISTRY = 'https://registry.npmjs.org/';
12
36
  const stable = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?![\s\S])/;
13
37
  export function compareVersions(a, b) {
@@ -79,14 +103,17 @@ function ownedDirectory(dir, home, allowMissing = false) {
79
103
  }
80
104
  }
81
105
 
82
- export async function updateInstallation({skillDir, runtime}, {
83
- env = process.env, platform = process.platform, query = latestVersion, run = spawnSync,
106
+ export async function updateInstallation({skillDir, runtime, overwriteLocalEdits}, {
107
+ env = process.env, platform = process.platform, query = latestVersion, run = spawnSync, findEdits = findLocalEdits,
84
108
  } = {}) {
85
109
  let root, current, latest, lock, temporary;
86
- const result = (status, reason, workflowRoot = root, installed = current) =>
87
- ({status, reason, current, latest, installed, workflowRoot});
110
+ const result = (status, reason, workflowRoot = root, installed = current, extra = {}) =>
111
+ ({status, reason, current, latest, installed, workflowRoot, ...extra});
88
112
  try {
89
113
  if (!['codex', 'claude'].includes(runtime) || !path.isAbsolute(skillDir)) throw new Error('Invalid invocation');
114
+ if (overwriteLocalEdits !== undefined && (typeof overwriteLocalEdits !== 'string' || !DIGEST.test(overwriteLocalEdits))) {
115
+ throw new Error('--overwrite-local-edits needs the localEditsDigest from the blocked report');
116
+ }
90
117
  root = fs.realpathSync(path.resolve(skillDir, '../..'));
91
118
  if (fs.realpathSync(skillDir) !== path.join(root, 'skills/cm-check')) throw new Error('Invalid Skill root');
92
119
  regularFile(path.join(root, 'skills/cm-check/SKILL.md'));
@@ -171,7 +198,54 @@ export async function updateInstallation({skillDir, runtime}, {
171
198
  ownedDirectory(path.dirname(marketplaceFile), home, true);
172
199
  optionalRegularFile(marketplaceFile);
173
200
  }
174
- const installedResult = run('/bin/bash', [installer, '--yes'], {cwd: source, env: installEnv, stdio: ['ignore', 2, 2]});
201
+ // Discarding locally edited CM files is never the default. The caller passes the digest of the
202
+ // edit list it showed the user, and only after the user explicitly agreed to discard those files;
203
+ // the flag reaches the installer only while the current list still has exactly that digest.
204
+ const edits = () => {
205
+ try {
206
+ return findEdits({helper: path.join(source, 'scripts/cm-install-manifest.sh'), target,
207
+ manifest: path.join(target, MANIFESTS[runtime])});
208
+ } catch { return {state: 'error', files: []}; }
209
+ };
210
+ let overwrite = false;
211
+ if (overwriteLocalEdits !== undefined) {
212
+ const found = edits();
213
+ // Only the exact approved list may proceed. A missing manifest makes the installer skip its own
214
+ // edit check, so "no manifest" or "no edits" here also stops instead of installing (2026-12 review).
215
+ if (found.state !== 'edits') {
216
+ const why = {invalid: 'found an invalid install manifest', error: 'failed', 'no-manifest': 'found no install manifest', none: 'found no local edits any more'}[found.state];
217
+ // Without its manifest the installer cannot detect edits at all, so never point to a plain rerun.
218
+ const next = found.state === 'no-manifest'
219
+ ? 'Without the manifest the installer cannot detect local edits, so a plain update could overwrite them too: back up any CM files you changed (or restore the manifest) before updating again.'
220
+ : found.state === 'none' ? 'Rerun the update without that option.' : 'Fix the manifest or path problem first.';
221
+ return result('blocked', `Local-edit check ${why}; nothing was installed or discarded and --overwrite-local-edits was not passed to the installer. ${next} (docs/installation.md, "Local edits").`,
222
+ root, current, {localEditsState: found.state});
223
+ }
224
+ if (editsDigest(found.files) !== overwriteLocalEdits) {
225
+ return result('blocked', 'The locally edited CM files changed since the user agreed; nothing was installed or discarded. Show the user this new list and ask again before passing its localEditsDigest.',
226
+ root, current, {localEdits: found.files, localEditsDigest: editsDigest(found.files)});
227
+ }
228
+ overwrite = true;
229
+ }
230
+ const installerArgs = [installer, '--yes', ...(overwrite ? ['--overwrite-local-edits'] : [])];
231
+ const installedResult = run('/bin/bash', installerArgs, {cwd: source, env: installEnv, stdio: ['ignore', 2, 2]});
232
+ // Status 3 is the installer refusing to overwrite: local edits, an invalid manifest or a path
233
+ // that changed type. Name the way out instead of a bare failure (2026-12 user report).
234
+ if (!installedResult.error && !installedResult.signal && installedResult.status === 3) {
235
+ const rollback = 'If it had already written files it tried to roll them back; its output above reports whether that completed.';
236
+ if (overwrite) {
237
+ return result('blocked', `Installer stopped with status 3 even with --overwrite-local-edits: its output above names the cause (for example a path that changed type during the install). ${rollback} Fix that problem first (docs/installation.md, "Local edits").`,
238
+ root, current, {installerStatus: 3});
239
+ }
240
+ const found = edits();
241
+ const extra = {installerStatus: 3, localEditsState: found.state,
242
+ ...(found.state === 'edits' ? {localEdits: found.files, localEditsDigest: editsDigest(found.files)} : {})};
243
+ return result('blocked', `Installer stopped with status 3 (its output above names the cause: locally edited CM files, an invalid install manifest, or a path that changed type). ${rollback} First follow its output for any path problem or unfinished rollback. ` +
244
+ (found.state === 'edits'
245
+ ? 'If the cause is only the files in localEdits: save the edits you need; only after the user explicitly agrees to discard exactly these files, rerun this same update command with --overwrite-local-edits <localEditsDigest> appended.'
246
+ : 'No listed local edit can be discarded here; --overwrite-local-edits does not apply (docs/installation.md, "Local edits").'),
247
+ root, current, extra);
248
+ }
175
249
  if (installedResult.error || installedResult.signal || installedResult.status !== 0) {
176
250
  throw new Error('Installer failed; inspect installer output and its rollback result');
177
251
  }
@@ -191,12 +265,13 @@ export async function updateInstallation({skillDir, runtime}, {
191
265
  const ownFile = fileURLToPath(import.meta.url);
192
266
  if (process.argv[1] && pathToFileURL(fs.realpathSync(process.argv[1])).href === import.meta.url) {
193
267
  const args = process.argv.slice(2);
194
- if (args.length !== 4 || args[0] !== '--skill-dir' || args[2] !== '--runtime' ||
268
+ const overwriteLocalEdits = args.length === 6 && args[4] === '--overwrite-local-edits' ? args[5] : undefined;
269
+ if ((args.length !== 4 && overwriteLocalEdits === undefined) || args[0] !== '--skill-dir' || args[2] !== '--runtime' ||
195
270
  path.resolve(args[1], '../../scripts/cm-check-update.mjs') !== ownFile) {
196
- console.error('Usage: node cm-check-update.mjs --skill-dir ABS --runtime codex|claude (from that installation)');
271
+ console.error('Usage: node cm-check-update.mjs --skill-dir ABS --runtime codex|claude [--overwrite-local-edits DIGEST] (from that installation)');
197
272
  process.exitCode = 2;
198
273
  } else {
199
- const report = await updateInstallation({skillDir: args[1], runtime: args[3]});
274
+ const report = await updateInstallation({skillDir: args[1], runtime: args[3], overwriteLocalEdits});
200
275
  console.log(JSON.stringify(report));
201
276
  process.exitCode = report.status === 'blocked' ? 1 : 0;
202
277
  }
@@ -3,7 +3,10 @@ import assert from 'node:assert/strict';
3
3
  import fs from 'node:fs';
4
4
  import os from 'node:os';
5
5
  import path from 'node:path';
6
- import {compareVersions, updateInstallation} from './cm-check-update.mjs';
6
+ import {spawnSync} from 'node:child_process';
7
+ import {fileURLToPath} from 'node:url';
8
+ import {compareVersions, editsDigest, findLocalEdits, updateInstallation} from './cm-check-update.mjs';
9
+ import {createHash} from 'node:crypto';
7
10
 
8
11
  function fixture(t, runtime = 'codex') {
9
12
  const home = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'cm-update-test-')));
@@ -205,3 +208,113 @@ for (const mode of ['failure', 'false-success', 'download-failure', 'wrong-packa
205
208
  else assert.equal(fs.existsSync(`${f.root}.cm-check-update.lock`), false);
206
209
  });
207
210
  }
211
+
212
+ // 回归点:安装器以 3 停止(本机改动、清单无效或路径变化)时,原来只报通用失败,用户不知道出口(2026-12 用户反馈)。
213
+ // 默认仍不覆盖:只传 --yes,并列出本机改动及其摘要,用户明确同意后才带摘要重跑。
214
+ const editsStub = (...results) => { const calls = []; const fn = input => { calls.push(input); return results[Math.min(calls.length, results.length) - 1]; }; fn.calls = calls; return fn; };
215
+ const listed = {state: 'edits', files: ['skills/a/SKILL.md']};
216
+
217
+ for (const runtime of ['codex', 'claude']) test(`${runtime}: installer status 3 never overwrites by default and lists the edits to approve`, async t => {
218
+ const f = fixture(t, runtime);
219
+ f.installerStatus = 3; f.writeVersion = false; f.options.findEdits = editsStub(listed);
220
+ const report = await updateInstallation(f.input, f.options);
221
+ assert.equal(report.status, 'blocked');
222
+ assert.equal(report.installerStatus, 3);
223
+ assert.deepEqual(report.localEdits, listed.files);
224
+ assert.equal(report.localEditsDigest, editsDigest(listed.files));
225
+ assert.deepEqual(f.calls[1].args.slice(1), ['--yes']);
226
+ assert.equal(f.options.findEdits.calls.length, 1, 'the edit list is read only after the installer stopped');
227
+ assert.match(f.options.findEdits.calls[0].helper, /scripts\/cm-install-manifest\.sh$/);
228
+ assert.equal(f.options.findEdits.calls[0].manifest, path.join(f.root, runtime === 'codex' ? '.cm-install-manifest.sha256' : 'cm-workflow/install-manifest.sha256'));
229
+ assert.match(report.reason, /explicitly agrees to discard exactly these files/);
230
+ assert.match(report.reason, /--overwrite-local-edits <localEditsDigest>/);
231
+ assert.match(report.reason, /reports whether that completed/);
232
+ assert.doesNotMatch(report.reason, /without discarding/);
233
+ const g = fixture(t, runtime); g.installerStatus = 3; g.writeVersion = false; g.options.findEdits = editsStub({state: 'invalid', files: []});
234
+ const invalid = await updateInstallation(g.input, g.options);
235
+ assert.equal(invalid.localEditsDigest, undefined);
236
+ assert.match(invalid.reason, /does not apply/);
237
+ const h = fixture(t, runtime); h.installerStatus = 1; h.writeVersion = false;
238
+ const other = await updateInstallation(h.input, h.options);
239
+ assert.doesNotMatch(other.reason, /overwrite-local-edits/);
240
+ assert.equal(other.installerStatus, undefined);
241
+ });
242
+
243
+ // 回归点:同意必须绑定到用户看过的那份清单;期间多出的改动或损坏的清单都不能被一并覆盖(2026-12 审查)。
244
+ for (const runtime of ['codex', 'claude']) test(`${runtime}: an approved digest passes the flag only for the same edit list`, async t => {
245
+ const digest = editsDigest(listed.files);
246
+ const f = fixture(t, runtime); f.options.findEdits = editsStub(listed);
247
+ assert.equal((await updateInstallation({...f.input, overwriteLocalEdits: digest}, f.options)).status, 'updated');
248
+ assert.deepEqual(f.calls[1].args.slice(1), ['--yes', '--overwrite-local-edits']);
249
+
250
+ const grown = {state: 'edits', files: ['skills/a/SKILL.md', 'skills/b/SKILL.md']};
251
+ const g = fixture(t, runtime); g.options.findEdits = editsStub(grown);
252
+ const changed = await updateInstallation({...g.input, overwriteLocalEdits: digest}, g.options);
253
+ assert.equal(changed.status, 'blocked');
254
+ assert.equal(g.calls.length, 1, 'installer must not run when the list changed');
255
+ assert.deepEqual(changed.localEdits, grown.files);
256
+ assert.equal(changed.localEditsDigest, editsDigest(grown.files));
257
+
258
+ for (const state of ['invalid', 'error']) {
259
+ const h = fixture(t, runtime); h.options.findEdits = editsStub({state, files: []});
260
+ const refused = await updateInstallation({...h.input, overwriteLocalEdits: digest}, h.options);
261
+ assert.equal(refused.status, 'blocked'); assert.equal(refused.localEditsState, state);
262
+ assert.equal(h.calls.length, 1, `${state}: installer must not run`);
263
+ }
264
+ for (const state of ['none', 'no-manifest']) {
265
+ const h = fixture(t, runtime); h.options.findEdits = editsStub({state, files: []});
266
+ const refused = await updateInstallation({...h.input, overwriteLocalEdits: digest}, h.options);
267
+ assert.equal(refused.status, 'blocked'); assert.equal(refused.localEditsState, state);
268
+ assert.equal(h.calls.length, 1, `${state}: installer must not run without its own edit check`);
269
+ if (state === 'no-manifest') {
270
+ assert.match(refused.reason, /back up any CM files you changed/);
271
+ assert.doesNotMatch(refused.reason, /Rerun the update without/);
272
+ }
273
+ }
274
+ const thrown = fixture(t, runtime); thrown.installerStatus = 3; thrown.writeVersion = false;
275
+ thrown.options.findEdits = () => { throw new Error('mkdtemp failed'); };
276
+ const kept = await updateInstallation(thrown.input, thrown.options);
277
+ assert.equal(kept.installerStatus, 3); assert.equal(kept.localEditsState, 'error');
278
+
279
+ const stop = fixture(t, runtime); stop.installerStatus = 3; stop.writeVersion = false; stop.options.findEdits = editsStub(listed);
280
+ const stopped = await updateInstallation({...stop.input, overwriteLocalEdits: digest}, stop.options);
281
+ assert.equal(stopped.status, 'blocked'); assert.equal(stopped.installerStatus, 3);
282
+ assert.match(stopped.reason, /even with --overwrite-local-edits/);
283
+
284
+ for (const value of [true, 'yes', digest.toUpperCase(), digest.slice(1)]) {
285
+ const bad = fixture(t, runtime);
286
+ const report = await updateInstallation({...bad.input, overwriteLocalEdits: value}, bad.options);
287
+ assert.equal(report.status, 'blocked', String(value)); assert.equal(bad.calls.length, 0);
288
+ }
289
+ });
290
+
291
+ test('the edit list comes from the installer manifest helper', t => {
292
+ const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'cm-edits-test-')));
293
+ t.after(() => fs.rmSync(root, {recursive: true, force: true}));
294
+ const helper = fileURLToPath(new URL('./cm-install-manifest.sh', import.meta.url));
295
+ const manifest = path.join(root, 'manifest');
296
+ const files = {'a.md': 'a\n', 'dir/b.md': 'b\n'};
297
+ for (const [file, body] of Object.entries(files)) { fs.mkdirSync(path.dirname(path.join(root, file)), {recursive: true}); fs.writeFileSync(path.join(root, file), body); }
298
+ assert.deepEqual(findLocalEdits({helper, target: root, manifest}), {state: 'no-manifest', files: []});
299
+ const hash = body => createHash('sha256').update(body).digest('hex');
300
+ fs.writeFileSync(manifest, ['# cm-workflow install manifest v1', ...Object.entries(files).map(([f, b]) => `${hash(b)} ${f}`)].join('\n') + '\n');
301
+ assert.deepEqual(findLocalEdits({helper, target: root, manifest}), {state: 'none', files: []});
302
+ fs.writeFileSync(path.join(root, 'dir/b.md'), 'edited\n');
303
+ assert.deepEqual(findLocalEdits({helper, target: root, manifest}), {state: 'edits', files: ['dir/b.md']});
304
+ fs.writeFileSync(manifest, '# not a manifest\n');
305
+ assert.deepEqual(findLocalEdits({helper, target: root, manifest}), {state: 'invalid', files: []});
306
+ });
307
+
308
+ test('the CLI accepts only --overwrite-local-edits DIGEST as an optional tail and passes it on', () => {
309
+ const script = fileURLToPath(new URL('./cm-check-update.mjs', import.meta.url));
310
+ const skillDir = path.resolve(path.dirname(script), '../skills/cm-check');
311
+ const base = [script, '--skill-dir', skillDir, '--runtime', 'claude'];
312
+ for (const extra of [['--force'], ['--overwrite-local-edits'], ['--yes', 'x'], ['--overwrite-local-edits', 'a', 'b']]) {
313
+ const run = spawnSync(process.execPath, [...base, ...extra], {encoding: 'utf8'});
314
+ assert.equal(run.status, 2, extra.join(' '));
315
+ assert.match(run.stderr, /\[--overwrite-local-edits DIGEST\]/);
316
+ }
317
+ const passed = spawnSync(process.execPath, [...base, '--overwrite-local-edits', 'not-a-digest'], {encoding: 'utf8'});
318
+ assert.equal(passed.status, 1);
319
+ assert.match(JSON.parse(passed.stdout).reason, /needs the localEditsDigest/);
320
+ });
@@ -54,10 +54,25 @@ function fakeWorker(cwd,{value=proposal,mode='normal',timeoutMs=3000,noticeEvent
54
54
  const schema=JSON.parse(args[index+1]);assert.equal(Object.hasOwn(schema,'$schema'),false);assert.equal(Object.hasOwn(schema,'$id'),false);
55
55
  assert.deepEqual(schema.properties.status.enum,['succeeded','failed']);
56
56
  assert.equal(args[args.indexOf('--permission-mode')+1],'dontAsk');
57
- for(const key of ['NODE_OPTIONS','ANTHROPIC_BASE_URL','HTTP_PROXY','CLAUDE_CODE_USE_BEDROCK'])assert.equal(options.env[key],undefined);
57
+ for(const key of ['NODE_OPTIONS','HTTP_PROXY','HTTPS_PROXY','ANTHROPIC_AUTH_TOKEN','CLAUDE_CODE_USE_BEDROCK','CLAUDE_CODE_USE_VERTEX'])assert.equal(options.env[key],undefined);
58
+ // The gateway address alone is passed through (2026-12 maintainer decision).
59
+ assert.equal(options.env.ANTHROPIC_BASE_URL,process.env.ANTHROPIC_BASE_URL);
60
+ spawnedEnvs.push(options.env);
58
61
  return spawn(process.execPath,['-e',source],options);
59
62
  }});
60
63
  }
64
+ const spawnedEnvs=[];
65
+ // 回归点:开发进程曾不带 ANTHROPIC_BASE_URL(2026-12 用户反馈)。显式注入合成网关,CI 没设网关时也能拦住漏传。
66
+ test('developer process receives a synthetic gateway address and no other routing variables',async t=>{
67
+ const root=fixture(t),saved={...process.env};
68
+ try{
69
+ Object.assign(process.env,{ANTHROPIC_BASE_URL:'https://gateway.example.test',CLAUDE_CODE_USE_VERTEX:'1',HTTPS_PROXY:'http://proxy.example.test'});
70
+ spawnedEnvs.length=0;
71
+ await fakeWorker(root)({prompt:prompt()},{signal:new AbortController().signal});
72
+ assert.equal(spawnedEnvs.length,1);
73
+ assert.equal(spawnedEnvs[0].ANTHROPIC_BASE_URL,'https://gateway.example.test');
74
+ }finally{for(const key of Object.keys(process.env))if(!(key in saved))delete process.env[key];Object.assign(process.env,saved);}
75
+ });
61
76
  const rateLimit=(overrides={})=>({type:'rate_limit_event',session_id:'synthetic-claude-developer',
62
77
  rate_limit_info:{status:'allowed',rateLimitType:'five_hour',resetsAt:123,active:true,reason:null,
63
78
  nested:{raw:'private'},list:['private']},...overrides});
@@ -95,6 +110,19 @@ test('developer accepts ui_invalidate on either side of init with a sanitized no
95
110
  assert.deepEqual(await fakeWorker(root,{noticeAt:0,noticeEvents:[{...uiInvalidate,session_id:'other'}]})({prompt:prompt()},control),
96
111
  {status:'unknown',code:'session_mismatch'});
97
112
  });
113
+ // 回归点:托管 SessionStart 钩子的 hook_started/hook_response 曾在 init 前触发 missing_init、在 init 后触发 unexpected_event(2026-12 用户反馈)。
114
+ test('developer accepts managed hook notices on either side of init without forwarding hook output',async t=>{
115
+ const root=fixture(t),control={signal:new AbortController().signal};
116
+ const baseline=await fakeWorker(root)({prompt:prompt()},control);
117
+ const hooks=[{type:'system',subtype:'hook_started',session_id:'synthetic-claude-developer',output:'x'},
118
+ {type:'system',subtype:'hook_response',session_id:'synthetic-claude-developer',stdout:'private'}];
119
+ for(const noticeAt of [0,1,2]){
120
+ const notices=[],result=await fakeWorker(root,{noticeAt,noticeEvents:hooks,onNotice:n=>notices.push(n)})({prompt:prompt()},control);
121
+ assert.deepEqual(result,baseline);
122
+ assert.deepEqual(notices,[{kind:'claude_system_notice',subtype:'hook_started'},{kind:'claude_system_notice',subtype:'hook_response'}]);
123
+ }
124
+ assert.equal((await fakeWorker(root,{noticeAt:0,noticeEvents:Array.from({length:33},()=>hooks[0])})({prompt:prompt()},control)).code,'unexpected_event');
125
+ });
98
126
  test('developer dev_intent binds init session and shares a 32-notice budget',async t=>{
99
127
  const root=fixture(t),control={signal:new AbortController().signal};
100
128
  for(const [noticeEvents,noticeAt,code] of [
@@ -0,0 +1,126 @@
1
+ // External report 2026-12 item 6: a managed environment can pin the API endpoint, so the Claude CLI
2
+ // starts but no message request reaches the loopback probe. The preflight keeps blocking; these tests
3
+ // cover the explanation at every entry. Ordinary inventory (not the native Codex-sandbox set), so the
4
+ // darwin-only entry tests run in the macOS CI job; the unit tests run everywhere.
5
+ import test from 'node:test';
6
+ import assert from 'node:assert/strict';
7
+ import fs from 'node:fs';
8
+ import os from 'node:os';
9
+ import path from 'node:path';
10
+ import {spawn,spawnSync} from 'node:child_process';
11
+ import {fileURLToPath} from 'node:url';
12
+ import {claudeProbeDiagnosis} from '../runtime/js/cm-ai/claude-probe-diagnosis.mjs';
13
+ import {preflightMissingReason} from '../runtime/js/cm-ai/host-conversation-execution.mjs';
14
+ import {claudeReviewFingerprint} from '../runtime/js/cm-ai/worker-claude.mjs';
15
+ import {buildManifest} from './cm-spec-manifest.mjs';
16
+ import {cli,protectedResultFixture} from './cm-ai-host-fixture.mjs';
17
+
18
+ const unreached={provider:'claude',passed:false,cli_started:true,message_requests:0,local_requests:1,process_code:'incomplete_result',exit_code:3,request_checks:[{startup:true}]};
19
+ test('Claude probe diagnosis explains only a started CLI whose message request never arrived',()=>{
20
+ const reason=claudeProbeDiagnosis({preflight:unreached});
21
+ assert.match(reason,/Claude 命令行已启动,但工具预检没有收到用于核对工具的消息请求/);assert.match(reason,/ANTHROPIC_BASE_URL/);
22
+ assert.match(reason,/如果组织的托管设置/);assert.match(reason,/不提供跳过开关/);assert.match(reason,/改由 Codex 审查/);
23
+ assert.match(reason,/退出码 3/);assert.doesNotMatch(reason,/[\r\n\0]/);assert(Buffer.byteLength(reason,'utf8')<=1024);
24
+ const fix=claudeProbeDiagnosis({preflight:unreached},{flow:'fix'});
25
+ assert.match(fix,/只支持 Claude,不能改由 Codex/);assert.doesNotMatch(fix,/cm-runtime/);assert.match(fix,/同一代码根和同一份运行配置/);
26
+ for(const preflight of [{...unreached,passed:true},{...unreached,provider:undefined,cli_model:'x'},{...unreached,message_requests:1},
27
+ {...unreached,cli_started:false},{...unreached,cli_started:undefined},{...unreached,process_code:'spawn_failed'},
28
+ {...unreached,process_code:'reviewer_model_not_found'},{...unreached,request_checks:[{model_recognized:false}]},
29
+ {...unreached,request_checks:{}},{...unreached,request_checks:'x'},'x',null])
30
+ assert.equal(claudeProbeDiagnosis({preflight}),null,JSON.stringify(preflight));
31
+ assert.doesNotMatch(claudeProbeDiagnosis({preflight:{...unreached,exit_code:null}}),/退出码/);
32
+ });
33
+ test('tool_preflight_missing keeps its reason with odd receipts and appends the diagnosis only within the bound',()=>{
34
+ const missing=preflightMissingReason('claude',{preflight:unreached,model:'fixture'});
35
+ assert.match(missing,/review-config 里的预检没有通过/);assert.match(missing,/不提供跳过开关/);assert.doesNotMatch(missing,/[\r\n\0]/);
36
+ assert.doesNotMatch(preflightMissingReason('codex',{preflight:unreached,model:'fixture'}),/托管设置/);
37
+ for(const request_checks of [{},'x',null]){
38
+ const odd=preflightMissingReason('claude',{preflight:{...unreached,request_checks},model:'fixture'});
39
+ assert.match(odd,/review-config 里的预检没有通过/);assert.doesNotMatch(odd,/托管设置/);
40
+ }
41
+ // Review r2: the bound counts the joined text, separator included, at every model length near the edge.
42
+ const diagnosisBytes=Buffer.byteLength(claudeProbeDiagnosis({preflight:unreached}),'utf8');
43
+ for(let size=5800;size<=5900;size++){
44
+ const reason=preflightMissingReason('claude',{preflight:unreached,model:'m'.repeat(size)});
45
+ assert(Buffer.byteLength(reason,'utf8')<=7000,`model ${size}: ${Buffer.byteLength(reason,'utf8')} bytes`);
46
+ if(/托管设置/.test(reason))assert(Buffer.byteLength(reason,'utf8')>diagnosisBytes);
47
+ }
48
+ const long=preflightMissingReason('claude',{preflight:unreached,model:'m'.repeat(7500)});
49
+ assert.match(long,/review-config 里的预检没有通过/);assert.doesNotMatch(long,/托管设置/);assert(Buffer.byteLength(long,'utf8')<=8192);
50
+ });
51
+
52
+ // Fake CLIs for the entry tests: one starts (prints its init event) then exits without any request,
53
+ // as when an organisation-pinned endpoint is unreachable; one exits before starting.
54
+ const startedWithoutRequest=`#!${process.execPath}\nprocess.stdin.resume();process.stdin.on('end',()=>{console.log(JSON.stringify({type:'system',subtype:'init',session_id:'probe-managed'}));process.exit(3);});\n`;
55
+ const exitsBeforeStart=`#!${process.execPath}\nprocess.stdin.resume();process.stdin.on('end',()=>process.exit(3));\n`;
56
+ const darwinProbe={skip:process.platform!=='darwin'||!fs.existsSync('/usr/bin/sandbox-exec')};
57
+ for(const [label,source,explained] of [['a started CLI that never reaches the probe',startedWithoutRequest,true],['a CLI that exits before starting',exitsBeforeStart,false]])
58
+ test(`Claude preflight with ${label} exits 1${explained?' and explains it on stderr':' without the managed-endpoint explanation'}`,darwinProbe,()=>{
59
+ const f=protectedResultFixture();
60
+ try{
61
+ const bin=path.join(f.root,'probe-bin');fs.mkdirSync(bin);fs.writeFileSync(path.join(bin,'claude'),source,{mode:0o700});
62
+ const env={...f.env,PATH:bin+path.delimiter+(f.env?.PATH??process.env.PATH)};
63
+ const models=path.join(f.root,'external-models.json');
64
+ fs.writeFileSync(models,JSON.stringify({schemaVersion:1,providers:{claude:{model:'fixture'}}}),{mode:0o600});
65
+ for(const args of [['--review-model','fixture','--runtime','claude'],['--external-provider','claude','--external-models-config',models]]){
66
+ const preview=spawnSync(process.execPath,[cli,'preflight','--config',f.config,...args],{encoding:'utf8',env,timeout:30000});
67
+ assert.equal(preview.status,1,preview.stderr);
68
+ const receipt=JSON.parse(preview.stdout);assert.equal(receipt.preflight.passed,false);assert.equal(receipt.preflight.message_requests,0);
69
+ assert.equal(receipt.preflight.cli_started,explained);
70
+ if(explained){assert.match(preview.stderr,/工具预检没有收到用于核对工具的消息请求/,args[0]);assert.match(preview.stderr,/不提供跳过开关/);}
71
+ else assert.doesNotMatch(preview.stderr,/托管设置/,args[0]);
72
+ }
73
+ }finally{fs.rmSync(f.root,{recursive:true,force:true});}
74
+ });
75
+
76
+ // A parallel member's Claude loopback preflight that no message request reaches stops the batch with
77
+ // the reason and exits, not a bare code. The batch stops before any host request, so a minimal
78
+ // session (advance, read the reply, close) is enough.
79
+ test('parallel member Claude preflight that never reaches the probe stops with the managed-endpoint reason',darwinProbe,async()=>{
80
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-claude-managed-batch-')));
81
+ try{
82
+ const specsDir=path.join(root,'specs'),codeProject=path.join(root,'code'),bin=path.join(root,'bin'),feature='1.work';
83
+ fs.mkdirSync(path.join(specsDir,feature),{recursive:true});fs.mkdirSync(codeProject);fs.mkdirSync(bin);
84
+ for(const name of ['requirements.md','design.md'])fs.writeFileSync(path.join(specsDir,feature,name),'# Synthetic batch\n');
85
+ fs.writeFileSync(path.join(specsDir,feature,'tasks.md'),'- [ ] T-001: first\n - 范围: `task1.mjs`\n- [ ] T-002: second\n - 范围: `task2.mjs`\n- [ ] T-003: final\n - 范围: `task3.mjs`\n\n- T-003 依赖 T-001, T-002\n');
86
+ fs.writeFileSync(path.join(specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:[feature],specFiles:buildManifest(specsDir)}));
87
+ fs.writeFileSync(path.join(codeProject,'requirements.md'),'# Synthetic exports\n');
88
+ for(const args of [['init','-b','main'],['config','user.name','Fixture'],['config','user.email','fixture@example.invalid'],['add','-A'],['commit','-m','fixture baseline']]){
89
+ const result=spawnSync('git',['-C',codeProject,...args],{encoding:'utf8'});assert.equal(result.status,0,result.stderr);
90
+ }
91
+ const batch={version:1,repositoryId:'batch-host',batchId:'batch-managed-run',specsDir,codeProject,
92
+ tasks:[1,2,3].map(n=>({feature,taskId:`T-00${n}`,scope:[`task${n}.mjs`],requirements:['requirements.md']})),
93
+ parallel:[[`${feature}/T-001`,`${feature}/T-002`]]};
94
+ const workflow={documentationPaths:[],applicableAgentFiles:[],qa:{commands:[{id:'value',caseIds:[],command:[process.execPath,'-e','0']}],
95
+ environment:{kind:'web',carrier:'browser',target:'http://127.0.0.1',scope:'local'}}};
96
+ const config=path.join(root,'batch.json');
97
+ fs.writeFileSync(config,JSON.stringify({batch,workflows:Object.fromEntries(batch.tasks.map(task=>[`${feature}/${task.taskId}`,workflow]))}));
98
+ const review=path.join(root,'review.json');
99
+ fs.writeFileSync(review,JSON.stringify({model:'fixture',preflight:{passed:true,cli_model:'fixture',provider:'claude',prompt_transport:'stdin',
100
+ config_fingerprint:claudeReviewFingerprint({cwd:codeProject,model:'fixture'})}}));
101
+ fs.writeFileSync(path.join(bin,'claude'),startedWithoutRequest,{mode:0o700});
102
+ const env={...process.env,PATH:bin+path.delimiter+process.env.PATH};
103
+ const child=spawn(process.execPath,[fileURLToPath(new URL('./cm-ai-batch-host.mjs',import.meta.url)),'serve','--config',config,
104
+ '--host-context','current-batch-host','--allow-development','--review-config',review,'--allow-qa','--runtime','claude'],{env,stdio:['pipe','pipe','pipe']});
105
+ const result=await new Promise((resolve,reject)=>{
106
+ let buffer='',stderr='',sessionId,reply;const calls=[];
107
+ const timer=setTimeout(()=>{child.kill('SIGTERM');reject(Error(`batch host timeout: ${stderr}`));},60000);
108
+ const send=value=>child.stdin.write(JSON.stringify(value)+'\n');
109
+ child.stderr.on('data',part=>{stderr+=part;});child.once('error',reject);
110
+ child.stdout.on('data',part=>{
111
+ buffer+=part;let newline;
112
+ while((newline=buffer.indexOf('\n'))!==-1){
113
+ const line=buffer.slice(0,newline);buffer=buffer.slice(newline+1);if(!line)continue;
114
+ const row=JSON.parse(line);
115
+ if(row.type==='host_ready'){sessionId=row.sessionId;send({operation:'advance',requestId:'advance'});}
116
+ else if(row.type==='host_request'){calls.push(row.kind);send({type:'host_close',sessionId});}
117
+ else if(row.requestId==='advance'){reply=row.result??row;send({type:'host_close',sessionId});}
118
+ }
119
+ });
120
+ child.once('close',code=>{clearTimeout(timer);resolve({code,stderr,reply,calls});});
121
+ });
122
+ assert.deepEqual(result.calls,[],'review preflight must fail before any develop request');
123
+ assert.equal(result.reply?.code,'review_preflight_failed',JSON.stringify(result));
124
+ assert.match(result.reply.reason,/工具预检没有收到用于核对工具的消息请求/);assert.match(result.reply.reason,/不提供跳过开关/);
125
+ }finally{fs.rmSync(root,{recursive:true,force:true});}
126
+ });
@@ -11,6 +11,7 @@ import {buildManifest} from './cm-spec-manifest.mjs';
11
11
  import {ownerGuardSource} from './fixtures/process-cleanup.mjs';
12
12
  import {previewClaudeTools,claudeProbeSandbox,createClaudeModelMarkerDetector} from '../runtime/js/cm-ai/claude-tool-preview.mjs';
13
13
  import {previewPromptTransport,writePreviewPrompt} from '../runtime/js/cm-ai/tool-preview.mjs';
14
+ import {claudeProbeDiagnosis} from '../runtime/js/cm-ai/claude-probe-diagnosis.mjs';
14
15
 
15
16
  for(const sendMessage of [true,false])test(`UI invalidation before init ${sendMessage?'permits a validated POST':'cannot make startup-only preflight pass'}`,
16
17
  {skip:process.platform!=='darwin'},async()=>{
@@ -36,6 +37,10 @@ for(const sendMessage of [true,false])test(`UI invalidation before init ${sendMe
36
37
  assert.equal(preflight.stopped_by_probe,sendMessage);
37
38
  assert.equal(preflight.listener_closed,true);
38
39
  if(sendMessage)assert.equal(preflight.request_checks[1].synthetic_auth,true);
40
+ // External report 2026-12 item 6: a real failed receipt with no message request gets the managed-endpoint explanation.
41
+ const diagnosis=claudeProbeDiagnosis({preflight});
42
+ assert.equal(preflight.cli_started,true);
43
+ if(sendMessage)assert.equal(diagnosis,null);else assert.match(diagnosis,/没有收到用于核对工具的消息请求.*退出码 1/);
39
44
  });
40
45
 
41
46
  test('tool preview argument transport preserves a long Unicode argv prompt without stdin',()=>{
@@ -317,7 +317,10 @@ test('all system notices retain initialization, session, stage and terminal boun
317
317
  const [init,text,result]=transcript();
318
318
  for(const subtype of ['api_retry','hook_started','hook_response','commands_changed']){
319
319
  const notice=systemNotice(subtype);
320
- assert.throws(()=>decode([notice,init,text,result]),{code:'missing_init'});
320
+ // Managed SessionStart hooks report before init (2026-12 user report); other notices still need init first.
321
+ if(['hook_started','hook_response'].includes(subtype))assert.deepEqual(decode([notice,init,text,result]),decode([init,text,result]));
322
+ else assert.throws(()=>decode([notice,init,text,result]),{code:'missing_init'});
323
+ assert.throws(()=>decode([{...notice,session_id:'other'},init,text,result]),{code:subtype.startsWith('hook_')?'session_mismatch':'missing_init'});
321
324
  assert.throws(()=>decode([init,{...notice,session_id:'other'},text,result]),{code:'session_mismatch'});
322
325
  assert.throws(()=>decode([init,{...notice,session_id:''},text,result]),{code:'invalid_session'});
323
326
  assert.throws(()=>decode([init,notice,result]),{code:'unexpected_result'});
@@ -75,12 +75,41 @@ async function runMessages(wireMessages,onNotice){
75
75
  {signal:new AbortController().signal,onEvent:e=>events.push(e)});
76
76
  return {result,events};
77
77
  }
78
+ // 回归点:审查/开发进程曾不带 ANTHROPIC_BASE_URL,走网关的用户请求发错地方(2026-12 用户反馈,维护者批准只放开这一项)。
79
+ test('Claude workers pass the gateway address but no other routing or credential variables',async()=>{
80
+ const {claudeEnvironment}=await import('../runtime/js/cm-ai/worker-claude.mjs');
81
+ const saved={...process.env};
82
+ try{
83
+ Object.assign(process.env,{ANTHROPIC_BASE_URL:'https://gateway.example.test',ANTHROPIC_AUTH_TOKEN:'not-passed',
84
+ HTTPS_PROXY:'http://proxy.example.test',HTTP_PROXY:'http://proxy.example.test',NODE_OPTIONS:'--require x',CLAUDE_CODE_USE_BEDROCK:'1',CLAUDE_CODE_USE_VERTEX:'1'});
85
+ const env=claudeEnvironment();
86
+ assert.equal(env.ANTHROPIC_BASE_URL,'https://gateway.example.test');
87
+ for(const key of ['ANTHROPIC_AUTH_TOKEN','HTTPS_PROXY','HTTP_PROXY','NODE_OPTIONS','CLAUDE_CODE_USE_BEDROCK','CLAUDE_CODE_USE_VERTEX'])assert.equal(env[key],undefined,key);
88
+ delete process.env.ANTHROPIC_BASE_URL;
89
+ assert.equal(Object.hasOwn(claudeEnvironment(),'ANTHROPIC_BASE_URL'),false,'absent stays absent');
90
+ }finally{for(const key of Object.keys(process.env))if(!(key in saved))delete process.env[key];Object.assign(process.env,saved);}
91
+ });
78
92
  test('UI invalidation prefix does not stop the Claude reviewer before init',async()=>{
79
93
  const notices=[],notice={type:'system',subtype:'ui_invalidate',session_id:'fresh-review',payload:{text:'not forwarded'}};
80
94
  const actual=await runMessages([notice,...messages],n=>notices.push(n));
81
95
  assert.deepEqual(actual,await runMessages(messages));
82
96
  assert.deepEqual(notices,[{kind:'claude_system_notice',subtype:'ui_invalidate'}]);
83
97
  });
98
+ // 回归点:托管的 SessionStart 钩子在 init 前输出 hook_started/hook_response,审查曾一律 missing_init(2026-12 用户反馈)。
99
+ test('managed hook notices before init do not stop the reviewer and never forward hook output',async()=>{
100
+ const notices=[],hooks=[{type:'system',subtype:'hook_started',session_id:'fresh-review',hook_name:'SessionStart',output:'not forwarded'},
101
+ {type:'system',subtype:'hook_response',session_id:'fresh-review',stdout:'secret-ish',exit_code:0}];
102
+ const actual=await runMessages([...hooks,...messages],n=>notices.push(n));
103
+ assert.deepEqual(actual,await runMessages(messages));
104
+ // Same allowlisted summary as after init: hook name kept, hook output dropped.
105
+ assert.deepEqual(notices,[{kind:'claude_system_notice',subtype:'hook_started',hook_name:'SessionStart'},{kind:'claude_system_notice',subtype:'hook_response'}]);
106
+ for(const [wire,code] of [[hooks,'incomplete_result'],[[hooks[0],...messages.slice(1)],'missing_init'],
107
+ [Array.from({length:33},()=>hooks[0]),'unexpected_event']]){
108
+ const failed=await runMessages(wire);
109
+ assert.equal(failed.result.status,'failed');assert.equal(failed.result.code,code,JSON.stringify(failed.result));
110
+ assert(!failed.events.some(e=>e.event==='turn.completed'));
111
+ }
112
+ });
84
113
  test('UI invalidation without init or with a different session never produces review success',async()=>{
85
114
  const notice={type:'system',subtype:'ui_invalidate',session_id:'fresh-review'};
86
115
  for(const [wire,code] of [[[notice],'incomplete_result'],[[notice,{...messages[0],session_id:'other'}],'session_mismatch'],
@@ -3,6 +3,7 @@
3
3
  import fs from 'node:fs';
4
4
  import {fileURLToPath} from 'node:url';
5
5
  import {previewClaudeTools} from '../runtime/js/cm-ai/claude-tool-preview.mjs';
6
+ import {claudeProbeDiagnosis} from '../runtime/js/cm-ai/claude-probe-diagnosis.mjs';
6
7
  import {createReviewVerificationSession} from '../runtime/js/cm-fix/review-verification.mjs';
7
8
  import {readReviewVerification} from '../runtime/js/cm-fix/review-verification-contract.mjs';
8
9
  import {need} from '../runtime/js/cm-ai/effect-contract.mjs';
@@ -20,5 +21,6 @@ if(process.argv[1]&&fs.realpathSync(process.argv[1])===fileURLToPath(import.meta
20
21
  const run=JSON.parse(fs.readFileSync(a[1],'utf8'));
21
22
  const result=await previewFixReviewVerification({codeProject:run.reproduction.cwd,configuration:run.reviewVerification,model:a[3],...(a[5]?{effort:a[5]}:{})});
22
23
  process.stdout.write(JSON.stringify(result)+'\n');process.exitCode=result.preflight.passed?0:1;
24
+ const diagnosis=claudeProbeDiagnosis(result,{flow:'fix'});if(diagnosis)process.stderr.write(diagnosis+'\n');
23
25
  }catch(e){process.stderr.write(JSON.stringify({code:/^[a-z_]+$/.test(e.code??'')?e.code:'review_verification_preflight_failed'})+'\n');process.exitCode=1;}
24
26
  }