@aibyzero/cm-workflow 0.21.7 → 0.25.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 (200) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +52 -0
  3. package/README.md +10 -1
  4. package/VERSION +1 -1
  5. package/docs/architecture.md +9 -0
  6. package/docs/cm-acceptance-completion.md +3 -1
  7. package/docs/cm-control-policy-v2.md +35 -3
  8. package/docs/execution-optimizations.md +1 -1
  9. package/docs/external-models.md +1 -0
  10. package/docs/human-correction.md +1 -1
  11. package/docs/installation.md +36 -10
  12. package/docs/js-workflow-control.md +65 -30
  13. package/docs/next-steps.md +10 -0
  14. package/docs/runtime-failover.md +2 -2
  15. package/docs/user-guide.md +1 -1
  16. package/package.json +1 -1
  17. package/runtime/js/cm-ai/batch-location.mjs +14 -0
  18. package/runtime/js/cm-ai/batch-plan.mjs +6 -2
  19. package/runtime/js/cm-ai/cm-ai-admission.mjs +9 -3
  20. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +51 -8
  21. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +30 -4
  22. package/runtime/js/cm-ai/codex-review-adapter.mjs +2 -4
  23. package/runtime/js/cm-ai/delivery-evidence.mjs +3 -1
  24. package/runtime/js/cm-ai/developer-adapter.mjs +15 -1
  25. package/runtime/js/cm-ai/drive-core.mjs +50 -6
  26. package/runtime/js/cm-ai/drive-next-step.mjs +61 -0
  27. package/runtime/js/cm-ai/durable-runner-state.mjs +85 -23
  28. package/runtime/js/cm-ai/execution-snapshot.mjs +5 -2
  29. package/runtime/js/cm-ai/execution-store.mjs +21 -3
  30. package/runtime/js/cm-ai/external-run-guard.mjs +9 -1
  31. package/runtime/js/cm-ai/host-check.mjs +4 -2
  32. package/runtime/js/cm-ai/host-conversation-execution.mjs +23 -2
  33. package/runtime/js/cm-ai/host-handoff.mjs +7 -0
  34. package/runtime/js/cm-ai/host-progress.mjs +18 -0
  35. package/runtime/js/cm-ai/host-qa-executor.mjs +47 -15
  36. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +11 -2
  37. package/runtime/js/cm-ai/host-qa-policy.mjs +24 -14
  38. package/runtime/js/cm-ai/host-session.mjs +1 -1
  39. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +1 -1
  40. package/runtime/js/cm-ai/host.mjs +1 -1
  41. package/runtime/js/cm-ai/operator-guidance.mjs +126 -2
  42. package/runtime/js/cm-ai/project-qa-gate.mjs +13 -2
  43. package/runtime/js/cm-ai/provider-review-observation.mjs +7 -3
  44. package/runtime/js/cm-ai/qa-plan-notes.mjs +106 -0
  45. package/runtime/js/cm-ai/review-continuation.mjs +102 -0
  46. package/runtime/js/cm-ai/review-evidence-file.mjs +11 -0
  47. package/runtime/js/cm-ai/review-package.mjs +25 -4
  48. package/runtime/js/cm-ai/review-presentation.mjs +31 -14
  49. package/runtime/js/cm-ai/review-runner.mjs +5 -4
  50. package/runtime/js/cm-ai/review-verdict-rules.mjs +7 -0
  51. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +30 -1
  52. package/runtime/js/cm-ai/task-commit-codec.mjs +11 -1
  53. package/runtime/js/cm-ai/task-commit.mjs +7 -4
  54. package/runtime/js/cm-ai/task-owner.mjs +5 -2
  55. package/runtime/js/cm-ai/task-runner.mjs +343 -52
  56. package/runtime/js/cm-fix/diagnosis.mjs +16 -3
  57. package/runtime/js/cm-fix/execution.mjs +47 -9
  58. package/runtime/js/cm-fix/finish.mjs +9 -1
  59. package/runtime/js/cm-fix/step-timing.mjs +222 -0
  60. package/runtime/js/cm-idea/session.mjs +22 -3
  61. package/runtime/js/cm-init/review-evidence.mjs +20 -7
  62. package/runtime/js/cm-prd/ai-draft.mjs +260 -0
  63. package/runtime/js/cm-prd/analysis.mjs +27 -9
  64. package/runtime/js/cm-prd/change.mjs +29 -8
  65. package/runtime/js/cm-prd/failed-correction.mjs +24 -4
  66. package/runtime/js/cm-prd/narrow-review.mjs +63 -3
  67. package/runtime/js/cm-prd/review-correction.mjs +65 -5
  68. package/runtime/js/cm-prd/review-disposition.mjs +10 -1
  69. package/runtime/js/cm-prd/self-check.mjs +121 -9
  70. package/runtime/js/cm-prd/session.mjs +55 -13
  71. package/runtime/js/cm-prd/summary.mjs +34 -6
  72. package/runtime/js/cm-prd/task-scope-record.mjs +40 -15
  73. package/runtime/js/cm-refactor/records.mjs +82 -11
  74. package/runtime/js/cm-refactor/workflow.mjs +3 -1
  75. package/runtime/js/executor-version.mjs +81 -0
  76. package/runtime/js/python-log-writer.mjs +15 -0
  77. package/runtime/js/run-analysis.mjs +136 -11
  78. package/runtime/logging.md +6 -0
  79. package/runtime/review.md +2 -1
  80. package/scripts/ci-test-weights.json +1 -0
  81. package/scripts/cm-ai-admission.mjs +27 -1
  82. package/scripts/cm-ai-admission.test.mjs +34 -2
  83. package/scripts/cm-ai-answer-gap-recheck.test.mjs +3 -2
  84. package/scripts/cm-ai-batch-drive.mjs +54 -17
  85. package/scripts/cm-ai-batch-drive.test.mjs +123 -6
  86. package/scripts/cm-ai-batch-host.mjs +55 -9
  87. package/scripts/cm-ai-batch-host.test.mjs +22 -3
  88. package/scripts/cm-ai-batch-location.test.mjs +22 -1
  89. package/scripts/cm-ai-batch-merge.mjs +102 -0
  90. package/scripts/cm-ai-batch-plan.mjs +55 -2
  91. package/scripts/cm-ai-batch-plan.test.mjs +228 -6
  92. package/scripts/cm-ai-batch-run-fixture.mjs +239 -15
  93. package/scripts/cm-ai-batch-run-parallel.test.mjs +23 -1
  94. package/scripts/cm-ai-batch-run.mjs +435 -33
  95. package/scripts/cm-ai-batch-session-member.test.mjs +85 -0
  96. package/scripts/cm-ai-check-recheck-cancellation.test.mjs +23 -2
  97. package/scripts/cm-ai-completion-summary.test.mjs +2 -1
  98. package/scripts/cm-ai-control-v2-drive.test.mjs +39 -9
  99. package/scripts/cm-ai-direct-review.test.mjs +1 -1
  100. package/scripts/cm-ai-disk-edits.test.mjs +229 -0
  101. package/scripts/cm-ai-drive-next-step.test.mjs +191 -0
  102. package/scripts/cm-ai-drive.mjs +66 -14
  103. package/scripts/cm-ai-drive.test.mjs +13 -3
  104. package/scripts/cm-ai-host-cli-workflow.test.mjs +4 -2
  105. package/scripts/cm-ai-host.mjs +16 -8
  106. package/scripts/cm-ai-host.test.mjs +12 -0
  107. package/scripts/cm-ai-operator-guidance.test.mjs +132 -1
  108. package/scripts/cm-ai-project-qa-gate.test.mjs +26 -0
  109. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +18 -0
  110. package/scripts/cm-ai-review-continuation.test.mjs +335 -0
  111. package/scripts/cm-ai-review-failure.test.mjs +13 -10
  112. package/scripts/cm-ai-review-timeout.test.mjs +1 -1
  113. package/scripts/cm-ai-run.mjs +42 -11
  114. package/scripts/cm-ai-run.test.mjs +26 -0
  115. package/scripts/cm-ai-supersede.test.mjs +10 -2
  116. package/scripts/cm-capability-gate.test.mjs +1 -1
  117. package/scripts/cm-check-runtime.sh +9 -0
  118. package/scripts/cm-codex-prompt-input.test.mjs +2 -1
  119. package/scripts/cm-developer-self-review.test.mjs +27 -0
  120. package/scripts/cm-efficiency-presentation-delta.test.mjs +4 -3
  121. package/scripts/cm-efficiency-response.test.mjs +2 -1
  122. package/scripts/cm-executor-version-draft.test.mjs +251 -0
  123. package/scripts/cm-executor-version-entries.test.mjs +93 -0
  124. package/scripts/cm-executor-version-prd.test.mjs +154 -0
  125. package/scripts/cm-executor-version-records.test.mjs +256 -0
  126. package/scripts/cm-executor-version.test.mjs +250 -0
  127. package/scripts/cm-external-model-host.test.mjs +6 -1
  128. package/scripts/cm-external-review-reconciliation.test.mjs +1 -1
  129. package/scripts/cm-fix-closeout-preflight.test.mjs +123 -0
  130. package/scripts/cm-fix-diagnosis-module-correction.test.mjs +5 -1
  131. package/scripts/cm-fix-drive.mjs +7 -2
  132. package/scripts/cm-fix-drive.test.mjs +45 -0
  133. package/scripts/cm-fix-entry.mjs +5 -2
  134. package/scripts/cm-fix-frozen-baseline.test.mjs +50 -0
  135. package/scripts/cm-fix-host.mjs +9 -2
  136. package/scripts/cm-fix-test-extension.test.mjs +30 -2
  137. package/scripts/cm-host-check.test.mjs +12 -0
  138. package/scripts/cm-host-qa-executor.test.mjs +172 -1
  139. package/scripts/cm-host-qa-policy.test.mjs +55 -1
  140. package/scripts/cm-idea-drive.mjs +5 -2
  141. package/scripts/cm-idea-entry.mjs +5 -2
  142. package/scripts/cm-idea-host.mjs +3 -1
  143. package/scripts/cm-init-drive.mjs +8 -5
  144. package/scripts/cm-init-entry.mjs +5 -2
  145. package/scripts/cm-init-host.mjs +6 -2
  146. package/scripts/cm-log-event.mjs +10 -2
  147. package/scripts/cm-log-event.test.mjs +29 -0
  148. package/scripts/cm-prd-ai-draft-fixture.mjs +18 -0
  149. package/scripts/cm-prd-ai-draft.test.mjs +505 -0
  150. package/scripts/cm-prd-answer-gaps.test.mjs +110 -5
  151. package/scripts/cm-prd-completion.test.mjs +67 -4
  152. package/scripts/cm-prd-design-phase.test.mjs +48 -13
  153. package/scripts/cm-prd-drive.mjs +89 -20
  154. package/scripts/cm-prd-drive.test.mjs +109 -4
  155. package/scripts/cm-prd-entry.mjs +5 -2
  156. package/scripts/cm-prd-host.mjs +89 -20
  157. package/scripts/cm-prd-host.test.mjs +17 -8
  158. package/scripts/cm-prd-narrow-review.test.mjs +49 -1
  159. package/scripts/cm-prd-review-disposition.test.mjs +94 -1
  160. package/scripts/cm-prd-review-gate.mjs +11 -4
  161. package/scripts/cm-prd-self-check-rules.test.mjs +175 -10
  162. package/scripts/cm-prd-self-check.test.mjs +1 -1
  163. package/scripts/cm-refactor-drive.mjs +10 -4
  164. package/scripts/cm-refactor-entry.mjs +5 -2
  165. package/scripts/cm-refactor-host.mjs +3 -1
  166. package/scripts/cm-run-analysis.test.mjs +373 -1
  167. package/scripts/cm-skill-hints-autowire.test.mjs +1 -1
  168. package/scripts/cm-skill-hints-exam.mjs +3 -1
  169. package/scripts/cm-skill-hints-install.test.mjs +1 -1
  170. package/scripts/cm-skill-hints.mjs +106 -10
  171. package/scripts/cm-skill-hints.test.mjs +162 -6
  172. package/scripts/cm-skill-judge.mjs +2 -1
  173. package/scripts/cm-task-gate.mjs +88 -18
  174. package/scripts/cm-task-scope.test.mjs +1 -1
  175. package/scripts/cm-test-drive.mjs +13 -8
  176. package/scripts/cm-test-entry.mjs +5 -2
  177. package/scripts/cm-test-host.mjs +3 -1
  178. package/scripts/cm-upgrade-compat-batch.test.mjs +62 -9
  179. package/scripts/fixtures/fresh-completion-checks.mjs +8 -0
  180. package/scripts/fixtures/prd-review-gate-python-oracle.py +9 -0
  181. package/scripts/policy-binding-compat.test.mjs +3 -2
  182. package/scripts/test-cm-prd-review-gate.py +25 -0
  183. package/skills/cm-ai/SKILL.md +1 -1
  184. package/skills/cm-ai/references/N1-init.md +1 -1
  185. package/skills/cm-ai/references/N4-review.md +2 -2
  186. package/skills/cm-ai/references/N6-qa-eval.md +3 -1
  187. package/skills/cm-ai/references/js-host-recovery.md +4 -1
  188. package/skills/cm-ai/references/js-host.md +17 -8
  189. package/skills/cm-fix/references/js-host.md +20 -0
  190. package/skills/cm-fix/references/test-extension.md +1 -1
  191. package/skills/cm-prd/SKILL.md +8 -6
  192. package/skills/cm-prd/references/ai-draft.md +81 -0
  193. package/skills/cm-prd/references/change-mode.md +2 -0
  194. package/skills/cm-prd/references/greenfield.md +2 -0
  195. package/skills/cm-prd/references/js-change-recovery.md +2 -2
  196. package/skills/cm-prd/references/js-host.md +9 -6
  197. package/skills/cm-prd/references/light-mode.md +19 -0
  198. package/skills/cm-prd/references/requirement-grilling.md +2 -0
  199. package/skills/cm-prd/references/spec-self-check.md +1 -0
  200. package/skills/cm-prd/references/summary-card.md +1 -0
@@ -22,7 +22,8 @@
22
22
  // start itself (`disable-model-invocation`) get a rule with `invoke`. When one fits, the
23
23
  // hook tells the model to read that skill's SKILL.md and follow it (mode "direct"), or to
24
24
  // ask the user first (mode "ask"), and shows the user one line saying so. Whether it fits
25
- // is judged by Jev when a TypeSafe key exists (cm-skill-judge.mjs: first 500 characters
25
+ // is judged by the rule's keywords; only when the local file says "judge": true (off by
26
+ // default since 2026-11-27) and a TypeSafe key exists does Jev judge (cm-skill-judge.mjs: first 500 characters
26
27
  // only, never a message that looks like it holds a secret, 3 seconds at most), else and
27
28
  // on any Jev failure by the rule's keywords. Only the pinned author version is started.
28
29
  import fs from 'node:fs';
@@ -149,7 +150,9 @@ export function loadRules({env=process.env,rulesFile=defaultRulesPath()}={}){
149
150
  const replaced=new Set(user.map(rule=>rule.id));
150
151
  const cm=(Array.isArray(defaults.value?.rules)?defaults.value.rules:[])
151
152
  .map(rule=>normalizeRule(rule,false)).filter(rule=>rule&&!disabled.has(rule.id)&&!replaced.has(rule.id));
152
- return {enabled:true,rules:[...user,...cm],judge:settings.judge!==false,localError:null,defaultsError:defaults.error??(defaults.missing?'missing':null),
153
+ // Jev is opt-in (2026-11-27, maintainer): message text leaves the machine only after the
154
+ // user writes "judge": true, not merely because a TypeSafe key happens to be set.
155
+ return {enabled:true,rules:[...user,...cm],judge:settings.judge===true,judgeSet:typeof settings.judge==='boolean',localError:null,defaultsError:defaults.error??(defaults.missing?'missing':null),
153
156
  userCount:user.length,disabledCount:disabled.size,cmCount:cm.length};
154
157
  }
155
158
 
@@ -428,7 +431,9 @@ function isOurs(hook,env,host){
428
431
  const tail=' '+managedTail(env,host);
429
432
  if(!hook.command.endsWith(tail))return false;
430
433
  const word=hook.command.slice(0,-tail.length);
431
- const interpreter=/^[^\s']+$/.test(word)?word:/^'[^']+'$/.test(word)?word.slice(1,-1):null;
434
+ // Exactly the forms shellWord writes: a plain word, or one '…' word. Anything sh would
435
+ // expand (`$(…)`, variables, globs) is not ours (review 2026-12-03).
436
+ const interpreter=/^[\w@%+=:,./-]+$/.test(word)?word:/^'[^']+'$/.test(word)?word.slice(1,-1):null;
432
437
  return Boolean(interpreter)&&/^node(?:\.exe)?$/i.test(path.basename(interpreter));
433
438
  }
434
439
  // A UserPromptSubmit that is not a list holds no hook of ours. A config of the wrong shape
@@ -442,6 +447,76 @@ export function shapeError(config){
442
447
  const list=promptHooks(config);
443
448
  return list!==undefined&&!Array.isArray(list)?'UserPromptSubmit 不是列表':null;
444
449
  }
450
+ // Split one plain command line into words the way sh would. Only literal characters,
451
+ // '…', "…" and backslash escapes (a backslash-newline is a continuation) are read;
452
+ // anything sh would expand, redirect or run as another command (variables, globs, ~,
453
+ // braces, ;, &, |, a bare line break …) returns null, and the caller reports the hook.
454
+ function shellWords(command){
455
+ const words=[];let word=null,i=0;
456
+ const add=char=>{word=(word??'')+char;};
457
+ while(i<command.length){
458
+ const char=command[i];
459
+ if(char===' '||char==='\t'){if(word!==null){words.push(word);word=null;}i++;continue;}
460
+ if(char==="'"){const end=command.indexOf("'",i+1);if(end<0)return null;add(command.slice(i+1,end));i=end+1;continue;}
461
+ if(char==='"'){
462
+ let j=i+1,text='';
463
+ for(;j<command.length&&command[j]!=='"';j++){
464
+ if(command[j]==='$'||command[j]==='`')return null;
465
+ if(command[j]==='\\'&&command[j+1]==='\n'){j++;continue;}
466
+ if(command[j]==='\\'&&/["\\$`]/.test(command[j+1]??'')){text+=command[++j];continue;}
467
+ text+=command[j];
468
+ }
469
+ if(j>=command.length)return null;
470
+ add(text);i=j+1;continue;
471
+ }
472
+ if(char==='\\'){if(i+1>=command.length)return null;if(command[i+1]!=='\n')add(command[i+1]);i+=2;continue;}
473
+ if(!/[\w@%+=:,./-]/.test(char))return null;
474
+ add(char);i++;
475
+ }
476
+ if(word!==null)words.push(word);
477
+ return words;
478
+ }
479
+ const NODE=/^node(?:\.exe)?$/i;
480
+ const PREFIX=/^(?:env|exec|command|nohup)(?:\.exe)?$/i;
481
+ // 'ours' | 'foreign' | 'unknown' | null (not a hint hook). Conservative on purpose
482
+ // (review rounds 2–7, 2026-12-02/03): a command that names the script is ours only as
483
+ // one plain line `[env|exec …] node <this copy, absolute> hook …`, and
484
+ // foreign only as the same line naming another absolute copy. Everything else that names
485
+ // the script (shells, wrappers, variables, globs, several commands, other subcommands)
486
+ // is reported as unknown: a false alarm is fine, a missed old sender is not. A command
487
+ // that builds the file name piece by piece is not recognised (documented gap).
488
+ function hintHookKind(command,env){
489
+ if(!command.includes(SCRIPT_NAME))return null;
490
+ const words=shellWords(command);
491
+ if(!words||command.split(SCRIPT_NAME).length!==2)return 'unknown';
492
+ const at=words.findIndex(word=>path.basename(word)===SCRIPT_NAME);
493
+ if(at<0||words[at+1]!=='hook')return 'unknown';
494
+ let first=0;
495
+ // A prefix is a bare command word; `NODE_OPTIONS=…/env` is an assignment, not `env`.
496
+ while(first<at&&!words[first].includes('=')&&PREFIX.test(path.basename(words[first])))first++;
497
+ // node must be followed directly by the script: a node option (--eval, --require,
498
+ // --import …) or a variable such as NODE_OPTIONS can run other code first.
499
+ if(first+1!==at||!NODE.test(path.basename(words[first])))return 'unknown';
500
+ const script=words[at];
501
+ if(!path.isAbsolute(script))return 'unknown';
502
+ return path.resolve(script)===path.join(installDir(env),SCRIPT_NAME)?'ours':'foreign';
503
+ }
504
+ // Hint hooks in a host config that run some other CM directory's copy (CM_WORKFLOW_HOME
505
+ // changed after wiring). Their copy may be a version that sends to Jev with just a key
506
+ // (review 2026-12-02), so status, refresh and install name them instead of staying quiet.
507
+ // Only the file and position are printed: a command can carry a key (`KEY=… node …`).
508
+ export function foreignHintHooks(env){
509
+ return HOSTS.flatMap(host=>{
510
+ let config;try{config=readJson(configFile(host,env)).value;}catch{return [];}
511
+ const list=promptHooks(config);
512
+ if(!Array.isArray(list))return [];
513
+ return list.flatMap((group,g)=>(Array.isArray(group?.hooks)?group.hooks:[]).map((hook,h)=>({hook,place:`UserPromptSubmit 第 ${g+1} 组第 ${h+1} 条`})))
514
+ .filter(({hook})=>hook?.type==='command'&&typeof hook.command==='string'&&!isOurs(hook,env,host))
515
+ .map(({hook,place})=>({host,file:configFile(host,env),place,kind:hintHookKind(hook.command,env)}))
516
+ .filter(item=>item.kind==='foreign'||item.kind==='unknown');
517
+ });
518
+ }
519
+ const FOREIGN_NOTE=found=>found.map(item=>`⚠ ${LABEL[item.host]} 的 ${item.file}(${item.place})${item.kind==='foreign'?'是另一个 CM 目录的技能提醒钩子':'像是技能提醒钩子,但 CM 读不准它跑的是哪份副本'}:它跑的副本可能是旧版本,有 TypeSafe 密钥就会把消息前 500 字发给 Jev;不需要就删掉这一条`).join('\n');
445
520
  export const hasHintHook=(config,env,host)=>{
446
521
  const list=promptHooks(config);
447
522
  return Array.isArray(list)&&list.some(group=>Array.isArray(group?.hooks)&&group.hooks.some(hook=>isOurs(hook,env,host)));
@@ -496,10 +571,12 @@ const refreshCommand=()=>`node ${shellWord(fileURLToPath(import.meta.url))} refr
496
571
  // copied files are replaced; host configs, Codex trust, session state and logs are not
497
572
  // touched, and a user who never enabled hints gets nothing. Failure is a warning.
498
573
  export function refresh({env=process.env,write=text=>process.stdout.write(text)}={}){
574
+ const foreign=foreignHintHooks(env);
575
+ if(foreign.length)write(FOREIGN_NOTE(foreign)+'\n');
499
576
  if(!hintsInstalled(env))return 0;
500
577
  if(runningFromCopy(env)){write(`⚠ 这是运行副本本身(${installDir(env)}),拿不到已装版本,未刷新;请运行已装 CM 里的 cm-skill-hints.mjs refresh\n`);return 1;}
501
578
  try{copyInstall(env);}
502
- catch(error){write(`⚠ 技能提醒运行副本未刷新(${installDir(env)}):${error.message};可稍后运行 ${refreshCommand()}\n`);return 1;}
579
+ catch(error){write(`⚠ 技能提醒运行副本未刷新(${installDir(env)}):${error.message};可稍后运行 ${refreshCommand()}。${OLD_COPY_NOTE(env)}\n`);return 1;}
503
580
  write(`技能提醒:运行副本已刷新(${installDir(env)})。\n`);
504
581
  return 0;
505
582
  }
@@ -519,8 +596,10 @@ export async function enable({env=process.env,hosts=HOSTS,node=process.execPath,
519
596
  write(noted.warning);
520
597
  if(requireRecord)return 1;
521
598
  }
599
+ // A copy already there (another host's) keeps running when this copy fails.
600
+ const hadCopy=fs.existsSync(path.join(installDir(env),SCRIPT_NAME));
522
601
  try{copyFiles(env);}
523
- catch(error){write(`✗ 复制提醒脚本到 ${installDir(env)} 失败:${error.message}\n`);return 1;}
602
+ catch(error){write(`✗ 复制提醒脚本到 ${installDir(env)} 失败:${error.message}${hadCopy?`。${OLD_COPY_NOTE(env)}`:''}\n`);return 1;}
524
603
  let failed=0;
525
604
  const done=[];
526
605
  for(const host of hosts){
@@ -617,7 +696,10 @@ async function noteRecord(env,add,{lockWaitMs,beforeReplace,lock}={}){
617
696
  }
618
697
 
619
698
  const OFF_NOTE=env=>`关掉提醒:在 ${localPath(env)} 写 {"enabled": false}`;
620
- const TYPESAFE_NOTE='有 TypeSafe 密钥时,handoff、wayfinder、improve-codebase-architecture 三个作者技能会把消息前 500 字发给 TypeSafe 判断。';
699
+ // Versions before 2026-11-27 send to Jev with just a key and no "judge" field; every
700
+ // version honours "judge": false, so that is the way to stop an old copy at once.
701
+ const OLD_COPY_NOTE=env=>`旧副本可能仍在运行:旧版本只要有 TypeSafe 密钥就会把消息前 500 字发给 Jev;想立刻停止外发,在 ${localPath(env)} 写 "judge": false`;
702
+ const TYPESAFE_NOTE='handoff、wayfinder、improve-codebase-architecture 三个作者技能默认只用本机关键词判断,不外发;在本地文件写 "judge": true 且有 TypeSafe 密钥时,才把消息前 500 字发给 TypeSafe 判断。';
621
703
 
622
704
  // Why an install must not add the hook now, or null. `optOut` is the user skipping this
623
705
  // run; `off` is "enabled": false; `pause` is a local file CM cannot use, so it does nothing.
@@ -672,6 +754,9 @@ export async function install({env=process.env,host,skip=false,node=process.exec
672
754
  +`(重装加 --no-skill-hints 只是不自动挂,不会摘掉已挂的钩子)。${TYPESAFE_NOTE}\n`);
673
755
  if(host==='codex')write(CODEX_TRUST);
674
756
  }
757
+ // Every other path above goes through refresh, which names these already.
758
+ const foreign=foreignHintHooks(env);
759
+ if(foreign.length)write(FOREIGN_NOTE(foreign)+'\n');
675
760
  return code;
676
761
  }catch(error){
677
762
  write(`⚠ 技能提醒钩子未处理:${error.message}\n`);
@@ -701,20 +786,31 @@ export function statusText({env=process.env,rulesFile=defaultRulesPath()}={}){
701
786
  :gate?.pause?` 安装时自动挂:暂停(${gate.pause})`
702
787
  :settled.state==='invalid'?` 安装时自动挂:暂停(${autoPath(env)} 异常:${settled.reason})`
703
788
  :` 安装时自动挂:开;已处理过:${settled.hosts.length?`${settled.hosts.map(host=>LABEL[host]).join('、')}(这些端不会再被自动挂上)`:'无'}`);
789
+ // Whether the copy the hook runs may be an older version than this one.
790
+ let unverified=false;
704
791
  if(!hintsInstalled(env))lines.push(' 运行副本:未建(还没开启)');
705
- else if(runningFromCopy(env))lines.push(' ⚠ 这是从运行副本本身查的,无法核验它与已装版本是否一致;请用已装 CM 里的 cm-skill-hints.mjs status');
706
- else{
792
+ else if(runningFromCopy(env)){
793
+ unverified=true;
794
+ lines.push(' ⚠ 这是从运行副本本身查的,无法核验它与已装版本是否一致;请用已装 CM 里的 cm-skill-hints.mjs status');
795
+ }else{
707
796
  const kind=copyDirKind(env);
708
797
  const stale=kind==='dir'?staleCopies(env):[];
798
+ // Only the hook script decides whether to send; a differing rules table alone does not.
799
+ // A missing script cannot run, so it sends nothing either.
800
+ unverified=kind==='other'||(stale.includes(SCRIPT_NAME)&&fs.existsSync(path.join(installDir(env),SCRIPT_NAME)));
709
801
  lines.push(kind==='missing'?` ⚠ 运行副本缺失(${installDir(env)}),钩子跑不起来;运行 ${refreshCommand()} 补上`
710
802
  :kind==='other'?` ⚠ 运行副本目录不是普通目录(${installDir(env)}),CM 不会写进去;请移走后运行 ${refreshCommand()}`
711
803
  :stale.length?` ⚠ 运行副本与已装版本不一致(${stale.join('、')});运行 ${refreshCommand()} 刷新`
712
804
  :' 运行副本:与已装版本一致');
713
805
  }
806
+ const foreign=foreignHintHooks(env);
807
+ if(foreign.length)lines.push(FOREIGN_NOTE(foreign).split('\n').map(line=>` ${line}`).join('\n'));
714
808
  if(loaded.enabled){
715
809
  lines.push(` 对照表:CM 自带 ${loaded.defaultsError?`读取失败(${loaded.defaultsError})`:`${loaded.cmCount} 条`};用户自加 ${loaded.userCount} 条;关掉自带 ${loaded.disabledCount} 条`);
716
- lines.push(loaded.judge?' 自动调用:有 TypeSafe 密钥(TYPESAFE_API_KEY 或钥匙串)时由 Jev 判断,否则用关键词'
717
- :` 自动调用:已关 Jev(${localPath(env)} 里 judge 为 false),只用关键词`);
810
+ // An unset judge means "off" only for this version; the old copy may still send.
811
+ lines.push(unverified&&!loaded.judgeSet?` 自动调用:运行副本未刷新,挂着的钩子可能按旧副本判断。${OLD_COPY_NOTE(env)}`
812
+ :loaded.judge?` 自动调用:已开 Jev(${localPath(env)} 里 judge 为 true),有 TypeSafe 密钥(TYPESAFE_API_KEY 或钥匙串)时由 Jev 判断,否则用关键词`
813
+ :` 自动调用:${foreign.length?'本目录的钩子':''}只用本机关键词(默认不开 Jev;要开在 ${localPath(env)} 写 "judge": true)${foreign.length?';上方 ⚠ 列出的钩子可能仍在外发':''}`);
718
814
  }
719
815
  return lines.join('\n')+'\n';
720
816
  }
@@ -6,7 +6,7 @@ import path from 'node:path';
6
6
  import crypto from 'node:crypto';
7
7
  import {execFileSync} from 'node:child_process';
8
8
  import {
9
- hook,main,enable,refresh,statusText,loadRules,stripCode,hookCommand,hasHintHook,
9
+ hook,main,enable,refresh,install,foreignHintHooks,statusText,loadRules,stripCode,hookCommand,hasHintHook,
10
10
  localPath,logFile,installDir,claudeSettingsPath,codexHooksPath,defaultRulesPath,
11
11
  MAX_PROMPT,ADOPT_WINDOW,LOG_LIMIT,SCRIPT_NAME,RULES_NAME,patternMatches,typed,readJson,loadAuthorCheck,
12
12
  } from './cm-skill-hints.mjs';
@@ -331,12 +331,166 @@ test('status reports wiring, switch and table counts',async t=>{
331
331
  let text=statusText({env:f.env,rulesFile:f.rulesFile});
332
332
  assert.match(text,/Claude 未挂,Codex 未挂;开关 开/);
333
333
  assert.match(text,/CM 自带 3 条;用户自加 1 条;关掉自带 1 条/);
334
- assert.match(text,/自动调用:有 TypeSafe 密钥/);
334
+ assert.match(text,/自动调用:只用本机关键词(默认不开 Jev/);
335
+ fs.writeFileSync(localPath(f.env),JSON.stringify({judge:true}));
336
+ assert.match(statusText({env:f.env,rulesFile:f.rulesFile}),/自动调用:已开 Jev.*有 TypeSafe 密钥/);
335
337
  fs.writeFileSync(localPath(f.env),JSON.stringify({enabled:false}));
336
338
  text=statusText({env:f.env,rulesFile:f.rulesFile});
337
339
  assert.match(text,/开关 关/);
338
340
  });
339
341
 
342
+ // Review 2026-11-27: a refresh that fails leaves the old copy running, and versions before
343
+ // Jev went opt-in send with just a key. Status and the warning must not claim keywords only.
344
+ test('a stale or unrefreshable copy is not reported as keywords only, and says how to stop sending',async t=>{
345
+ const f=fixture(t,{});
346
+ fs.mkdirSync(installDir(f.env),{recursive:true});
347
+ fs.writeFileSync(path.join(installDir(f.env),SCRIPT_NAME),'// old version\n');
348
+ const text=statusText({env:f.env,rulesFile:f.rulesFile});
349
+ assert.doesNotMatch(text,/只用本机关键词/);
350
+ assert.match(text,/自动调用:运行副本未刷新.*旧副本.*"judge": false/);
351
+ fs.mkdirSync(path.join(installDir(f.env),'cm-config-lock.mjs','blocker'),{recursive:true});
352
+ let out='';
353
+ assert.equal(refresh({env:f.env,write:text=>{out+=text;}}),1);
354
+ assert.match(out,/未刷新.*旧副本可能仍在运行.*"judge": false/);
355
+ });
356
+
357
+ // Review round 2: only the hook script decides whether to send, so a rules table that
358
+ // differs alone does not mean an old sender is running.
359
+ test('a copy that differs only in its rules table is not reported as an old sender',async t=>{
360
+ const f=fixture(t,{});
361
+ fs.mkdirSync(installDir(f.env),{recursive:true});
362
+ fs.copyFileSync(new URL(`./${SCRIPT_NAME}`,import.meta.url),path.join(installDir(f.env),SCRIPT_NAME));
363
+ fs.writeFileSync(path.join(installDir(f.env),RULES_NAME),'{}\n');
364
+ const text=statusText({env:f.env,rulesFile:f.rulesFile});
365
+ assert.match(text,/运行副本与已装版本不一致/);
366
+ assert.doesNotMatch(text,/旧副本可能仍在运行/);
367
+ assert.match(text,/自动调用:只用本机关键词/);
368
+ });
369
+
370
+ // Review round 2: a first enable for a second host that cannot copy leaves the first
371
+ // host's old copy running, so it warns like a failed refresh.
372
+ test('enable that cannot copy over an existing old copy says the old copy may still send',async t=>{
373
+ const f=fixture(t,{});
374
+ fs.mkdirSync(installDir(f.env),{recursive:true});
375
+ fs.writeFileSync(path.join(installDir(f.env),SCRIPT_NAME),'// old version\n');
376
+ let out='';
377
+ const code=await enable({env:f.env,hosts:['codex'],write:text=>{out+=text;},copyFiles:()=>{throw new Error('blocked');}});
378
+ assert.equal(code,1);
379
+ assert.match(out,/复制提醒脚本.*失败.*旧副本可能仍在运行.*"judge": false/);
380
+ });
381
+
382
+ // Review 2026-12-02: after CM_WORKFLOW_HOME changes, a hook still running the old
383
+ // directory's copy (which may send with just a key) must be named by status, refresh and
384
+ // a first install for the new directory, not reported as keywords only.
385
+ test('a hint hook that runs another CM directory\'s copy is named by status, refresh and install',async t=>{
386
+ const f=fixture(t,{});
387
+ const oldDir=path.join(f.env.HOME,'old-cm');
388
+ const oldCommand=`node ${path.join(oldDir,'skill-hints',SCRIPT_NAME)} hook --host claude`;
389
+ fs.mkdirSync(path.dirname(claudeSettingsPath(f.env)),{recursive:true});
390
+ fs.writeFileSync(claudeSettingsPath(f.env),JSON.stringify({hooks:{UserPromptSubmit:[{hooks:[{type:'command',command:oldCommand}]}]}}));
391
+ assert.deepEqual(foreignHintHooks(f.env).map(item=>[item.host,item.kind]),[['claude','foreign']]);
392
+ const text=statusText({env:f.env,rulesFile:f.rulesFile});
393
+ assert.match(text,/Claude 的 .*settings\.json(UserPromptSubmit 第 1 组第 1 条)是另一个 CM 目录的技能提醒钩子.*发给 Jev/);
394
+ assert.match(text,/自动调用:本目录的钩子只用本机关键词.*上方 ⚠ 列出的钩子可能仍在外发/);
395
+ let out='';
396
+ assert.equal(refresh({env:f.env,write:line=>{out+=line;}}),0);
397
+ assert.match(out,/第 1 组第 1 条)是另一个 CM 目录的技能提醒钩子/);
398
+ out='';
399
+ await install({env:f.env,host:'claude',write:line=>{out+=line;}});
400
+ assert.ok(hasHintHook(readJson(claudeSettingsPath(f.env)).value,f.env,'claude'),'the new directory is wired');
401
+ assert.match(out,/第 1 组第 1 条)是另一个 CM 目录的技能提醒钩子/);
402
+ assert.equal(foreignHintHooks(f.env).length,1,'only the old hook is foreign; the new one is ours');
403
+ });
404
+
405
+ test('a hook of this directory, or no hint hook at all, is never reported as foreign',async t=>{
406
+ const f=fixture(t,{});
407
+ fs.mkdirSync(path.dirname(claudeSettingsPath(f.env)),{recursive:true});
408
+ fs.writeFileSync(claudeSettingsPath(f.env),JSON.stringify({hooks:{UserPromptSubmit:[{hooks:[
409
+ {type:'command',command:hookCommand(f.env,'claude')},{type:'command',command:'echo other'}]}]}}));
410
+ assert.deepEqual(foreignHintHooks(f.env),[]);
411
+ assert.doesNotMatch(statusText({env:f.env,rulesFile:f.rulesFile}),/另一个 CM 目录/);
412
+ });
413
+
414
+ // Review round 2 (2026-12-02): the warning never prints the command (it can carry a
415
+ // key), quoting does not hide an old hook, and an echo or this directory's own copy run
416
+ // with node options is not called foreign.
417
+ test('foreign hint hooks: read like a shell, never echo the command, and report what CM cannot read',async t=>{
418
+ const f=fixture(t,{});
419
+ const own=path.join(installDir(f.env),SCRIPT_NAME);
420
+ const old=path.join(f.env.HOME,'old cm','skill-hints',SCRIPT_NAME);
421
+ const cases=[
422
+ [`TYPESAFE_API_KEY=sk-fake-123 node '${old}' hook --host claude`,'unknown'],
423
+ [`node '${old}' "hook" --host claude`,'foreign'],
424
+ [`env /usr/local/bin/node "${old}" hook --host claude`,'foreign'],
425
+ [`env A=1 /usr/local/bin/node --no-warnings "${old}" hook --host claude`,'unknown'],
426
+ [`exec node '${old}' hook --host claude`,'foreign'],
427
+ [`/usr/bin/env node '${old}' hook --host codex`,'foreign'],
428
+ // Review round 7: a node option or a variable (NODE_OPTIONS) can run other code first.
429
+ [`node --no-warnings ${own} hook --host claude`,'unknown'],
430
+ [`node --eval='require(1)' ${own} hook --host claude`,'unknown'],
431
+ [`NODE_OPTIONS=--require=/tmp/x.js node ${own} hook --host claude`,'unknown'],
432
+ [`NODE_OPTIONS=--require=/opt/legacy/env node ${own} hook --host claude`,'unknown'],
433
+ [`exec node ${own} hook --host claude`,null],
434
+ // Review round 3: an option with its own value, or a relative script path, is not
435
+ // read as plain, so it is reported rather than resolved against status's own cwd.
436
+ [`node --require node:path '${old}' hook --host claude`,'unknown'],
437
+ [`node --require node:path ${own} hook --host claude`,'unknown'],
438
+ [`node ./.cm-workflow/skill-hints/${SCRIPT_NAME} hook --host claude`,'unknown'],
439
+ // Printing text or another subcommand is not running the hook, but CM reports any
440
+ // command naming the script that is not one plain hook line (a false alarm is fine).
441
+ [`echo '${old}' hook --host claude`,'unknown'],
442
+ [`echo "Run node ${old} status"; true`,'unknown'],
443
+ [`node '${old}' status`,'unknown'],
444
+ [`bash -c 'node ${old} hook --host claude'`,'unknown'],
445
+ [`node $HOME/old/skill-hints/${SCRIPT_NAME} hook --host claude`,'unknown'],
446
+ // Review round 4: a variable or a line continuation can still become `hook`.
447
+ [`node "$HOME/old/skill-hints/${SCRIPT_NAME}" "$CM_HINT_ACTION" --host claude`,'unknown'],
448
+ [`node '${old}' \\\nhook --host claude`,'foreign'],
449
+ [`node "${old}" "\\\nhook" --host claude`,'foreign'],
450
+ [`node '${old}'`,'unknown'],
451
+ // Review round 5: a second command after a line break, or a second mention, is not
452
+ // hidden by a first command that runs this directory's copy.
453
+ [`node ${own} \\\n hook --host claude\nnode '${old}' hook --host claude`,'unknown'],
454
+ [`node ${own} hook --host claude && node '${old}' hook --host claude`,'unknown'],
455
+ [`node ${own} hook --host claude\nnode ${own} status`,'unknown'],
456
+ [`node ${own} hook --host claude ${old}`,'unknown'],
457
+ [`node ${own} hook --host claude\nnode --version`,'unknown'],
458
+ // Review round 6: wrappers that pass `hook` themselves, globs sh would expand, and a
459
+ // script name mentioned again elsewhere are all reported.
460
+ [`sh -c 'exec node "$1" hook --host claude' sh ${old} status`,'unknown'],
461
+ [`node ${path.dirname(path.dirname(own))}[1]/skill-hints/${SCRIPT_NAME} hook --host claude`,'unknown'],
462
+ [`node ~/old/skill-hints/${SCRIPT_NAME} hook --host claude`,'unknown'],
463
+ [`node ${own} hook --host "$(cat /tmp/host)"`,'unknown'],
464
+ [`node '${old}' hook --host claude '/a/${SCRIPT_NAME} status'`,'unknown'],
465
+ ];
466
+ fs.mkdirSync(path.dirname(claudeSettingsPath(f.env)),{recursive:true});
467
+ fs.writeFileSync(claudeSettingsPath(f.env),JSON.stringify({hooks:{UserPromptSubmit:cases.map(([command])=>({hooks:[{type:'command',command}]}))}}));
468
+ const found=foreignHintHooks(f.env);
469
+ const expected=cases.map(([,kind],i)=>kind&&[`UserPromptSubmit 第 ${i+1} 组第 1 条`,kind]).filter(Boolean);
470
+ assert.deepEqual(found.map(item=>[item.place,item.kind]),expected);
471
+ const text=statusText({env:f.env,rulesFile:f.rulesFile});
472
+ let out='';refresh({env:f.env,write:line=>{out+=line;}});
473
+ for(const shown of [text,out]){
474
+ assert.doesNotMatch(shown,/sk-fake-123/);
475
+ assert.doesNotMatch(shown,/old cm/);
476
+ assert.match(shown,/CM 读不准它跑的是哪份副本/);
477
+ }
478
+ });
479
+
480
+ // Review round 7: an interpreter word that sh would expand is not our hook, even when the
481
+ // rest of the command matches, so it is listed rather than skipped.
482
+ test('a hook whose interpreter word runs a command substitution is not ours and is listed',async t=>{
483
+ const f=fixture(t,{});
484
+ const sneaky=`$(node${'${IFS}'}/old/skill-hints/${SCRIPT_NAME}${'${IFS}'}hook)/usr/local/bin/node ${path.join(installDir(f.env),SCRIPT_NAME)} hook --host claude`;
485
+ const config={hooks:{UserPromptSubmit:[{hooks:[{type:'command',command:sneaky}]}]}};
486
+ assert.equal(hasHintHook(config,f.env,'claude'),false);
487
+ assert.equal(hasHintHook({hooks:{UserPromptSubmit:[{hooks:[{type:'command',command:hookCommand(f.env,'claude','/usr/local/bin/node')}]}]}},f.env,'claude'),true);
488
+ assert.equal(hasHintHook({hooks:{UserPromptSubmit:[{hooks:[{type:'command',command:hookCommand(f.env,'claude','/Applications/My Node/node')}]}]}},f.env,'claude'),true);
489
+ fs.mkdirSync(path.dirname(claudeSettingsPath(f.env)),{recursive:true});
490
+ fs.writeFileSync(claudeSettingsPath(f.env),JSON.stringify(config));
491
+ assert.deepEqual(foreignHintHooks(f.env).map(item=>item.kind),['unknown']);
492
+ });
493
+
340
494
  test('CM-launched Claude and Codex sessions carry the off switch',async()=>{
341
495
  const {claudeEnvironment}=await import('../runtime/js/cm-ai/worker-claude.mjs');
342
496
  const {cleanEnvironment}=await import('../runtime/js/cm-ai/codex-config.mjs');
@@ -699,8 +853,10 @@ const INVOKE_RULES={version:1,rules:[
699
853
  fallback:{skill:'cm-prd',reason:'拆规格'},invoke:{mode:'ask',when:'拆决策票',near:'排个计划'}},
700
854
  {id:'fix-bug',skill:'cm-fix',keywords:['修这个 bug'],reason:'先复现'},
701
855
  ]};
702
- function invoking(t,{installed=['handoff','wayfinder'],local,answer={none:1},key='fake-key'}={}){
703
- const f=fixture(t,{rules:INVOKE_RULES,local,authorNames:['handoff','wayfinder'],
856
+ // Jev is off unless the local file says "judge": true, so these fixtures turn it on;
857
+ // `jev:false` leaves the field out to check the default.
858
+ function invoking(t,{installed=['handoff','wayfinder'],local,jev=true,answer={none:1},key='fake-key'}={}){
859
+ const f=fixture(t,{rules:INVOKE_RULES,local:jev?{judge:true,...local}:local,authorNames:['handoff','wayfinder'],
704
860
  authorSkills:installed.flatMap(name=>[['.claude/skills',name],['.agents/skills',name]])});
705
861
  const calls=[];
706
862
  const fetchImpl=async(url,options)=>{
@@ -796,8 +952,8 @@ test('a skill that is not the installed author version is never judged or starte
796
952
  assert.equal(none.calls.length,0);
797
953
  });
798
954
 
799
- test('judge:false, no key or a missing judge module all fall back to keywords without a call',async t=>{
800
- for(const options of [{local:{judge:false}},{key:''}]){
955
+ test('Jev is off by default; judge:false, no key or a missing judge module also fall back to keywords without a call',async t=>{
956
+ for(const options of [{jev:false},{jev:false,local:{rules:[]}},{local:{judge:false}},{key:''}]){
801
957
  const f=invoking(t,{...options,answer:{handoff:1}});
802
958
  assert.equal(await f.run('今天先到这'),null);
803
959
  assert.match((await f.run('会话太长了',{session:'s2'})).systemMessage,/已让模型用 \/handoff/);
@@ -3,7 +3,8 @@
3
3
  // skill (`invoke` in cm-skill-hints.json); keywords stay the fallback.
4
4
  //
5
5
  // Decided 2026-10-25 (方案-技能自动调用): only with a TypeSafe key (env or the macOS
6
- // keychain); only the first SEND_CHARS characters leave the machine, and a message
6
+ // keychain), and since 2026-11-27 only when the hook's local file says "judge": true
7
+ // (checked by the hook, which does not call this module otherwise); only the first SEND_CHARS characters leave the machine, and a message
7
8
  // that looks like it holds a secret is never sent. At most BUDGET_MS in all and at most
8
9
  // two requests: the second goes out at once when the first fails, or alongside it when
9
10
  // the first has not answered within HEDGE_MS. Measured 2026-10-25 from fresh processes
@@ -11,8 +11,8 @@ import {inspectFixWalkthrough,readFixWalkthrough,fixWalkthroughBinding} from '..
11
11
  import {inspectFixRegressionFailure} from '../runtime/js/cm-fix/regression-evidence.mjs';
12
12
  import {taskDeclarations,approvedTaskGrammar,LEGACY_TASK_GRAMMAR} from '../runtime/js/spec-task-line.mjs';
13
13
  import {statesZeroBlockingFindings,ZERO_BLOCKING_PHRASES,REVIEWER_SOURCES} from '../runtime/js/review-findings.mjs';
14
- import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
15
14
  import {readExecutionSnapshot} from '../runtime/js/cm-ai/execution-snapshot.mjs';
15
+ import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
16
16
  import {readRunnerHistory} from '../runtime/js/cm-ai/durable-runner-state.mjs';
17
17
  import {resolveCheckpointPackage} from '../runtime/js/cm-ai/checkpoint-package-material.mjs';
18
18
  import {publishHostReview} from '../runtime/js/cm-ai/host-review-file.mjs';
@@ -718,10 +718,14 @@ function correctionHistory({reviewsDir,feature,task,projectRoot}){
718
718
  return {payload,revisions,history:revisions.map(item=>({file:path.basename(item.path),
719
719
  sha256:createHash('sha256').update(item.bytes).digest('hex')}))};
720
720
  }
721
- function boundCorrectionHandoff(handoff,task,projectRoot){
721
+ // A runner-owned correction handoff carries the runner's structured Learning,
722
+ // which the owning runner verifies itself before its native completion.
723
+ function boundCorrectionHandoff(handoff,task,projectRoot,{runnerOwned=false,allowSymlinks=false}={}){
722
724
  const payload=loadHandoff(handoff,{task,attempt:2});
723
725
  if(payload.status!=='ready_for_review')throw new GateError('human correction requires ready_for_review');
724
- verifyLearningRecord(payload,projectRoot);verifyImplementationBinding(payload,{projectRoot});
726
+ if(runnerOwned!==true)verifyLearningRecord(payload,projectRoot);
727
+ // Only a runner-owned correction inherits the run's symlink-capable baseline.
728
+ verifyImplementationBinding(payload,{projectRoot,allowSymlinks:runnerOwned===true&&allowSymlinks===true});
725
729
  return payload;
726
730
  }
727
731
  export function prepareHumanCorrection(selectors){
@@ -818,6 +822,35 @@ function checkHumanCorrection(selectors,stage){
818
822
 
819
823
  // Provenance is a declaration of who selected this bounded continuation. It is
820
824
  // neither authenticated identity nor authorization, and never a review verdict.
825
+ // Exclusive and all-or-nothing: bytes are written and synced to a private temp,
826
+ // then hard-linked into place, so a crash never leaves a partial evidence file.
827
+ function writeExclusiveAtomic(file,bytes){
828
+ const temp=path.join(path.dirname(file),`.cm-gate-${randomUUID()}`);
829
+ const fd=fs.openSync(temp,fs.constants.O_WRONLY|fs.constants.O_CREAT|fs.constants.O_EXCL,0o600);
830
+ try{fs.writeFileSync(fd,bytes);fs.fsyncSync(fd);}finally{fs.closeSync(fd);}
831
+ try{fs.linkSync(temp,file);}finally{fs.unlinkSync(temp);}
832
+ }
833
+ // A crash between the link and the temp unlink leaves the evidence with a second
834
+ // link. Only the caller's own fixed evidence files are healed, and only a temp
835
+ // named exactly like writeExclusiveAtomic's (random v4 UUID) sharing their inode.
836
+ const ATOMIC_TEMP=/^\.cm-gate-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
837
+ export function healAtomicTempLinks(dir,files){
838
+ // A listed temp may vanish before it is read (its own writer finished, or this
839
+ // loop removed it for an earlier file): that name is skipped, never fatal.
840
+ const temps=new Set(fs.readdirSync(dir).filter(name=>ATOMIC_TEMP.test(name)));
841
+ const gone=error=>{if(error.code!=='ENOENT')throw error;};
842
+ for(const file of files){
843
+ let target;try{target=fs.lstatSync(file);}catch(error){gone(error);continue;}
844
+ if(path.dirname(file)!==dir||!target.isFile()||target.nlink!==2)continue;
845
+ for(const name of [...temps]){
846
+ let temp;try{temp=fs.lstatSync(path.join(dir,name));}catch(error){gone(error);temps.delete(name);continue;}
847
+ if(temp.isFile()&&temp.dev===target.dev&&temp.ino===target.ino){
848
+ try{fs.unlinkSync(path.join(dir,name));}catch(error){gone(error);}
849
+ temps.delete(name);break;
850
+ }
851
+ }
852
+ }
853
+ }
821
854
  function controlledCorrectionPaths(reviewsDir,feature,task){
822
855
  const root=path.dirname(correctionPaths(reviewsDir,feature,task).record);
823
856
  const prefix=path.join(root,`${feature}-${task}-controlled-correction`);
@@ -852,8 +885,8 @@ function withCorrectionPreparation(selectors,action){
852
885
  }finally{fs.closeSync(descriptor);}
853
886
  }
854
887
  }
855
- function controlledCorrectionPayload(handoff,task,projectRoot,original){
856
- const payload=boundCorrectionHandoff(handoff,task,projectRoot);
888
+ function controlledCorrectionPayload(handoff,task,projectRoot,original,runnerOwned=false,allowSymlinks=false){
889
+ const payload=boundCorrectionHandoff(handoff,task,projectRoot,{runnerOwned,allowSymlinks});
857
890
  if(!sameSet(new Set(original.payload.changed_files),new Set(payload.changed_files)))
858
891
  throw new GateError('controlled correction must retain the full original reviewed file scope');
859
892
  if(payload.implementation_sha256===original.payload.implementation_sha256)
@@ -912,6 +945,41 @@ function assertCompatibilityCorrectionOwner(reviewsDir){
912
945
  }
913
946
  }
914
947
  }
948
+ // A cm-ai run that journaled its own third controlled review owns exactly this
949
+ // one correction (library callers only; the CLI cannot set runnerOwned). It must
950
+ // show the run's continuation marker instead of the compatibility writer.
951
+ export const REVIEW_CONTINUATION_MARKER_PROTOCOL='cm-ai-review-continuation';
952
+ export const reviewContinuationMarkerPath=(reviewsDir,feature,task)=>
953
+ path.join(path.dirname(correctionPaths(reviewsDir,feature,task).record),`${feature}-${task}-review-continuation.json`);
954
+ function assertCorrectionOwner(selectors){
955
+ if(selectors.runnerOwned!==true)return assertCompatibilityCorrectionOwner(selectors.reviewsDir);
956
+ let marker,markerBytes;
957
+ try{markerBytes=fileRevision(reviewContinuationMarkerPath(selectors.reviewsDir,selectors.feature,selectors.task),16384).bytes;
958
+ marker=parseJsonStrict(new TextDecoder('utf8',{fatal:true}).decode(markerBytes));}
959
+ catch{throw new GateError('runner-owned correction requires a valid run continuation marker');}
960
+ exactFields(marker,['version','protocol','feature','task','repositoryId','runId','fromDigest','at'],'run continuation marker');
961
+ const safeId=value=>typeof value==='string'&&/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(value)&&!value.includes('..');
962
+ if(marker.version!==1n||marker.protocol!==REVIEW_CONTINUATION_MARKER_PROTOCOL||marker.feature!==selectors.feature||marker.task!==selectors.task
963
+ ||!safeId(marker.runId)||!safeId(marker.repositoryId)||!/^[0-9a-f]{64}$/.test(marker.fromDigest??'')||typeof marker.at!=='string')
964
+ throw new GateError('runner-owned correction requires the run continuation marker for this task');
965
+ // The named run's own journal is the authority: it must be this task's v2 run
966
+ // and hold the authorization bound to these exact marker bytes.
967
+ const reviews=fs.realpathSync(selectors.reviewsDir);
968
+ let snapshot;
969
+ try{snapshot=readExecutionSnapshot({specsRoot:path.dirname(reviews),identity:{repositoryId:marker.repositoryId,runId:marker.runId}});}
970
+ catch{throw new GateError('runner-owned correction requires the marker to name a retained JS run');}
971
+ const config=snapshot.records[0]?.payload?.config;
972
+ const markerSha=createHash('sha256').update(markerBytes).digest('hex');
973
+ // Replay the whole journal with the runner's own validator, so only an
974
+ // authorization that legally follows its recorded review_limit counts.
975
+ let history=null;
976
+ try{history=readRunnerHistory(snapshot.records,config,snapshot.records[0].payload.version);}catch{history=null;}
977
+ if(config?.controlPolicy?.version!==2||config.identity?.taskId!==selectors.task
978
+ ||config.completion?.owner?.feature!==selectors.feature||config.completion?.reviewsDir!==reviews
979
+ ||history?.reviewContinuation?.markerSha256!==markerSha||history.reviewContinuation.fromDigest!==marker.fromDigest
980
+ ||history.reviewContinuation.at!==marker.at)
981
+ throw new GateError('runner-owned correction requires the run journal to hold this continuation authorization');
982
+ }
915
983
  export function prepareControlledCorrection(selectors){
916
984
  const {reviewsDir,feature,task,handoff,projectRoot,decisionSource,reason}=selectors;
917
985
  if(!['operator','model'].includes(decisionSource))
@@ -919,15 +987,15 @@ export function prepareControlledCorrection(selectors){
919
987
  if(typeof reason!=='string'||!reason.trim()||reason.length>2000)
920
988
  throw new GateError('controlled correction requires a concrete bounded reason');
921
989
  return withCorrectionPreparation(selectors,()=>{
922
- assertCompatibilityCorrectionOwner(reviewsDir);
990
+ assertCorrectionOwner(selectors);
923
991
  const paths=controlledCorrectionPaths(reviewsDir,feature,task);
924
992
  noCorrectionEvidence(correctionPaths(reviewsDir,feature,task),{includeOrphan:false});
925
993
  absent(paths.record);absent(paths.review);absent(paths.receipt);
926
994
  const original=correctionHistory(selectors),draft=fileRevision(handoff,PREPARATION_FILE_LIMIT);
927
- controlledCorrectionPayload(handoff,task,projectRoot,original);
995
+ controlledCorrectionPayload(handoff,task,projectRoot,original,selectors.runnerOwned===true,selectors.allowSymlinks===true);
928
996
  requireRevisions([...original.revisions,draft]);
929
997
  // The only recoverable orphan is the exact handoff written before the record.
930
- try{absent(paths.handoff);fs.writeFileSync(paths.handoff,draft.bytes,{flag:'wx',mode:0o600});}
998
+ try{absent(paths.handoff);writeExclusiveAtomic(paths.handoff,draft.bytes);}
931
999
  catch(error){
932
1000
  if(error instanceof GateError&&!fs.existsSync(paths.record)&&fileRevision(paths.handoff,PREPARATION_FILE_LIMIT).bytes.equals(draft.bytes)){}
933
1001
  else throw error;
@@ -936,17 +1004,17 @@ export function prepareControlledCorrection(selectors){
936
1004
  decision_source:decisionSource,source_semantics:'provenance-only',at:new Date().toISOString(),reason:reason.trim(),
937
1005
  history:original.history,handoff_sha256:sha256(paths.handoff)};
938
1006
  requireRevisions(original.revisions);
939
- controlledCorrectionPayload(paths.handoff,task,projectRoot,original);
940
- assertCompatibilityCorrectionOwner(reviewsDir);
1007
+ controlledCorrectionPayload(paths.handoff,task,projectRoot,original,selectors.runnerOwned===true,selectors.allowSymlinks===true);
1008
+ assertCorrectionOwner(selectors);
941
1009
  noCorrectionEvidence(correctionPaths(reviewsDir,feature,task),{includeOrphan:false});
942
- fs.writeFileSync(paths.record,JSON.stringify(record,null,2)+'\n',{flag:'wx',mode:0o600});
1010
+ writeExclusiveAtomic(paths.record,Buffer.from(JSON.stringify(record,null,2)+'\n'));
943
1011
  return {outcome:'ready_for_correction_review',correction:paths.record,handoff:paths.handoff,
944
1012
  review:paths.review,correction_sha256:sha256(paths.record),attempt:2,continuation:1};
945
1013
  });
946
1014
  }
947
1015
  function inspectControlledCorrection(selectors){
948
1016
  const {reviewsDir,feature,task,correction,handoff,projectRoot}=selectors;
949
- assertCompatibilityCorrectionOwner(reviewsDir);
1017
+ assertCorrectionOwner(selectors);
950
1018
  const paths=controlledCorrectionPaths(reviewsDir,feature,task);
951
1019
  if(typeof correction!=='string'||typeof handoff!=='string'||path.resolve(correction)!==paths.record||path.resolve(handoff)!==paths.handoff)
952
1020
  throw new GateError('controlled correction must use its fixed evidence paths');
@@ -965,7 +1033,7 @@ function inspectControlledCorrection(selectors){
965
1033
  const original=correctionHistory(selectors);
966
1034
  if(canonical(record.history)!==canonical(original.history))throw new GateError('controlled correction history changed');
967
1035
  const handoffRevision=fileRevision(paths.handoff,PREPARATION_FILE_LIMIT);
968
- const payload=controlledCorrectionPayload(paths.handoff,task,projectRoot,original);
1036
+ const payload=controlledCorrectionPayload(paths.handoff,task,projectRoot,original,selectors.runnerOwned===true,selectors.allowSymlinks===true);
969
1037
  if(record.handoff_sha256!==createHash('sha256').update(handoffRevision.bytes).digest('hex'))
970
1038
  throw new GateError('controlled correction handoff changed');
971
1039
  requireRevisions([pinned,handoffRevision,...original.revisions]);
@@ -1010,7 +1078,7 @@ export function publishControlledCorrectionReview(selectors){
1010
1078
  inspectControlledCorrection(selectors);
1011
1079
  const receipt={version:2,protocol:'cm-controlled-correction-review',correction_sha256:correctionDigest,
1012
1080
  review_sha256:createHash('sha256').update(pinned.bytes).digest('hex'),verdict:header.verdict};
1013
- fs.writeFileSync(paths.receipt,JSON.stringify(receipt,null,2)+'\n',{flag:'wx',mode:0o600});
1081
+ writeExclusiveAtomic(paths.receipt,Buffer.from(JSON.stringify(receipt,null,2)+'\n'));
1014
1082
  return {outcome:header.verdict,receipt:paths.receipt};
1015
1083
  }
1016
1084
  function checkControlledCorrection(selectors,stage){
@@ -1048,8 +1116,9 @@ function checkCorrection(selectors,stage){
1048
1116
 
1049
1117
  // Only compatibility CLI entries opt into inventory validation. Library callers
1050
1118
  // retain the original content-binding contract and exact result shape.
1051
- export function checkN4({handoff,reviewsDir,feature,task,projectRoot=null,allowLegacyUnbound=false,requireLearning=false,correction=null,inventory=null,allowSymlinks=false}){
1052
- if(correction!==null)return checkCorrection({handoff,reviewsDir,feature,task,projectRoot,correction,allowLegacyUnbound,inventory},'n4');
1119
+ export function checkN4({handoff,reviewsDir,feature,task,projectRoot=null,allowLegacyUnbound=false,requireLearning=false,correction=null,inventory=null,allowSymlinks=false,runnerOwned=false}){
1120
+ if(correction!==null)return checkCorrection({handoff,reviewsDir,feature,task,projectRoot,correction,allowLegacyUnbound,inventory,
1121
+ ...(runnerOwned===true?{runnerOwned:true,allowSymlinks}:{})},'n4');
1053
1122
  requireTaskId(task,'task');
1054
1123
  const payload=loadHandoff(handoff,{task});
1055
1124
  if(payload.status!=='ready_for_review')throw new GateError('N4 requires a ready_for_review handoff');
@@ -1062,8 +1131,9 @@ export function checkN4({handoff,reviewsDir,feature,task,projectRoot=null,allowL
1062
1131
  return {gate:'n4',task,attempt,outcome:'ready_for_review',handoff_sha256:sha256(handoff),content_bound:contentBound,...inventoryResult};
1063
1132
  }
1064
1133
 
1065
- export function checkN5({handoff,reviewsDir,feature,task,projectRoot=null,allowLegacyUnbound=false,requireLearning=false,correction=null,inventory=null,allowSymlinks=false}){
1066
- if(correction!==null)return checkCorrection({handoff,reviewsDir,feature,task,projectRoot,correction,allowLegacyUnbound,inventory},'n5');
1134
+ export function checkN5({handoff,reviewsDir,feature,task,projectRoot=null,allowLegacyUnbound=false,requireLearning=false,correction=null,inventory=null,allowSymlinks=false,runnerOwned=false}){
1135
+ if(correction!==null)return checkCorrection({handoff,reviewsDir,feature,task,projectRoot,correction,allowLegacyUnbound,inventory,
1136
+ ...(runnerOwned===true?{runnerOwned:true,allowSymlinks}:{})},'n5');
1067
1137
  requireTaskId(task,'task');
1068
1138
  const payload=loadHandoff(handoff,{task});
1069
1139
  if(payload.status!=='ready_for_review')throw new GateError('N5 requires a ready_for_review handoff');
@@ -174,7 +174,7 @@ const draft=(tasks)=>({draftDigest:'d',features:[{directory:'1.sample',name:'sam
174
174
  const codes=report=>report.findings.map(item=>item.code);
175
175
 
176
176
  test('rule 3: every task of a new draft must declare its files; earlier rules do not ask',()=>{
177
- assert.equal(PRD_SELF_CHECK_RULES,5,'rules 4 and 5 keep the rule-3 scope check');
177
+ assert.equal(PRD_SELF_CHECK_RULES,8,'rules 4, 5, 7 and 8 keep the rule-3 scope check');
178
178
  const without=draft('- [ ] T-001: a\n- [ ] T-002: b\n - 范围: `b.js`\n');
179
179
  const report=checkPrdDraftMechanics(without,{rules:3});
180
180
  assert.deepEqual(codes(report),['task_scope_missing']);