@aibyzero/cm-workflow 0.16.6 → 0.16.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +29 -0
  3. package/README.md +32 -1
  4. package/VERSION +1 -1
  5. package/assets/readme/workflow-recovery-detailed.png +0 -0
  6. package/assets/readme/workflow-stages-detailed.png +0 -0
  7. package/docs/installation.md +1 -1
  8. package/docs/js-workflow-control.md +84 -9
  9. package/docs/user-guide.md +104 -0
  10. package/package.json +1 -1
  11. package/runtime/js/cm-ai/cm-ai-admission.mjs +37 -11
  12. package/runtime/js/cm-ai/cm-ai-context-refresh.mjs +9 -5
  13. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +56 -17
  14. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +172 -33
  15. package/runtime/js/cm-ai/codex-review-adapter.mjs +2 -1
  16. package/runtime/js/cm-ai/developer-adapter.mjs +8 -5
  17. package/runtime/js/cm-ai/drive-bootstrap.mjs +2 -2
  18. package/runtime/js/cm-ai/drive-core.mjs +17 -4
  19. package/runtime/js/cm-ai/durable-runner-state.mjs +29 -0
  20. package/runtime/js/cm-ai/execution-store.mjs +4 -2
  21. package/runtime/js/cm-ai/host-conversation-execution.mjs +11 -3
  22. package/runtime/js/cm-ai/host-documentation.mjs +2 -2
  23. package/runtime/js/cm-ai/host-qa-executor.mjs +89 -19
  24. package/runtime/js/cm-ai/host-session.mjs +46 -6
  25. package/runtime/js/cm-ai/host-tool-bridge.mjs +15 -3
  26. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +4 -2
  27. package/runtime/js/cm-ai/log-rows.mjs +36 -0
  28. package/runtime/js/cm-ai/operator-guidance.mjs +3 -0
  29. package/runtime/js/cm-ai/reviewed-deliveries.mjs +29 -6
  30. package/runtime/js/cm-ai/task-runner.mjs +6 -1
  31. package/runtime/js/cm-fix/cause-package.mjs +37 -8
  32. package/runtime/js/cm-fix/diagnosis.mjs +43 -0
  33. package/runtime/js/cm-fix/execution.mjs +189 -148
  34. package/runtime/js/cm-fix/finish.mjs +2 -19
  35. package/runtime/js/cm-fix/investigation.mjs +25 -9
  36. package/runtime/js/cm-fix/log-events.mjs +29 -0
  37. package/runtime/js/cm-fix/metrics.mjs +3 -2
  38. package/runtime/js/cm-fix/progress.mjs +3 -1
  39. package/runtime/js/cm-prd/analysis.mjs +5 -2
  40. package/runtime/js/cm-prd/review-host.mjs +2 -1
  41. package/runtime/js/cm-test/recovery.mjs +4 -4
  42. package/runtime/js/notify-run.mjs +26 -0
  43. package/runtime/js/notify.mjs +388 -0
  44. package/runtime/model-efficiency.md +17 -0
  45. package/scripts/cm-ai-admission.mjs +14 -3
  46. package/scripts/cm-ai-batch-drive.mjs +2 -2
  47. package/scripts/cm-ai-batch-host.mjs +7 -2
  48. package/scripts/cm-ai-batch-run.mjs +11 -2
  49. package/scripts/cm-ai-batch-run.test.mjs +9 -1
  50. package/scripts/cm-ai-drive.mjs +18 -4
  51. package/scripts/cm-ai-drive.test.mjs +30 -0
  52. package/scripts/cm-ai-feature-selection.test.mjs +178 -0
  53. package/scripts/cm-ai-fix-run-delivery.test.mjs +138 -0
  54. package/scripts/cm-ai-host.mjs +20 -8
  55. package/scripts/cm-ai-host.test.mjs +88 -0
  56. package/scripts/cm-ai-project-qa-gate.test.mjs +71 -4
  57. package/scripts/cm-ai-protected-scope.test.mjs +194 -0
  58. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +77 -4
  59. package/scripts/cm-ai-run.mjs +36 -5
  60. package/scripts/cm-fix-abandon.test.mjs +89 -3
  61. package/scripts/cm-fix-cause-package.test.mjs +33 -0
  62. package/scripts/cm-fix-drive.mjs +9 -1
  63. package/scripts/cm-fix-host.mjs +1 -1
  64. package/scripts/cm-fix-large-log.test.mjs +113 -0
  65. package/scripts/cm-fix-rediagnosis.test.mjs +71 -4
  66. package/scripts/cm-host-qa-executor.test.mjs +429 -3
  67. package/scripts/cm-log-event.mjs +53 -6
  68. package/scripts/cm-notify.test.mjs +468 -0
  69. package/scripts/cm-patrol.mjs +83 -0
  70. package/scripts/cm-patrol.test.mjs +161 -0
  71. package/scripts/cm-prd-host.mjs +13 -2
  72. package/scripts/cm-prd-host.test.mjs +4 -0
  73. package/scripts/cm-prd-review-host.test.mjs +17 -0
  74. package/scripts/cm-prd-session-recovery.test.mjs +44 -2
  75. package/scripts/cm-prd-task-grouping.test.mjs +206 -0
  76. package/scripts/cm-review-scope-recovery.test.mjs +5 -3
  77. package/scripts/cm-test-branch-impact.test.mjs +11 -0
  78. package/scripts/cm-token-report.mjs +497 -0
  79. package/scripts/cm-token-report.test.mjs +346 -0
  80. package/skills/cm-ai/SKILL.md +7 -3
  81. package/skills/cm-ai/references/N1-init.md +1 -1
  82. package/skills/cm-ai/references/N6-qa-eval.md +2 -2
  83. package/skills/cm-ai/references/js-host-modes.md +90 -0
  84. package/skills/cm-ai/references/js-host-qa-recovery.md +110 -0
  85. package/skills/cm-ai/references/js-host-recovery.md +199 -0
  86. package/skills/cm-ai/references/js-host.md +69 -330
  87. package/skills/cm-fix/SKILL.md +2 -0
  88. package/skills/cm-fix/references/js-host.md +16 -9
  89. package/skills/cm-prd/SKILL.md +7 -4
  90. package/skills/cm-prd/references/spec-self-check.md +3 -1
@@ -0,0 +1,29 @@
1
+ // cm-fix's view of the run log: its own rows, in log order. The log only grows;
2
+ // reading it whole under the 1 MiB review-material limit made every fix run fail
3
+ // at completion once a project's 运行日志.jsonl passed 1 MiB (2026-10-07,
4
+ // api-native-reading-fix-story-return). Read it line by line, with the same file
5
+ // guarantees as before; callers still select their own run identity.
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+ import {readStableLogRows} from '../cm-ai/log-rows.mjs';
9
+ import {need} from '../cm-ai/effect-contract.mjs';
10
+
11
+ const fixRows=file=>readStableLogRows(file,row=>row!==null&&typeof row==='object'&&!Array.isArray(row)&&row.workflow==='cm-fix','fix_log_failed');
12
+ export function eventsAt(specsRoot,configuration={}){
13
+ need(path.isAbsolute(specsRoot)&&fs.realpathSync(specsRoot)===specsRoot,'unsupported_path');
14
+ if(configuration.archiveMode==='bare'){
15
+ const directory=path.join(specsRoot,'.reviews','host-log-mirror','runs');
16
+ if(!fs.existsSync(directory))return [];
17
+ need(fs.realpathSync(directory)===directory,'fix_log_failed');
18
+ const rows=[];
19
+ for(const month of fs.readdirSync(directory).sort()){
20
+ need(/^\d{4}-\d{2}$/.test(month)&&fs.realpathSync(path.join(directory,month))===path.join(directory,month),'fix_log_failed');
21
+ for(const file of fs.readdirSync(path.join(directory,month)).sort())
22
+ if(file.endsWith('.jsonl'))rows.push(...fixRows(path.join(directory,month,file)));
23
+ }
24
+ return rows;
25
+ }
26
+ const log=path.join(specsRoot,'运行日志.jsonl');
27
+ if(!fs.existsSync(log))return [];
28
+ return fixRows(log);
29
+ }
@@ -4,6 +4,7 @@ import fs from 'node:fs';
4
4
  import path from 'node:path';
5
5
  import {types} from 'node:util';
6
6
  import {readReviewSourceFiles} from '../cm-ai/review-package.mjs';
7
+ import {eventsAt} from './log-events.mjs';
7
8
  import {id,need,validIdentity} from '../cm-ai/effect-contract.mjs';
8
9
  import {METRICS_HEADER as header,METRICS_SEPARATOR as separator,hasMetricsHeader} from '../cm-ai/metrics-table.mjs';
9
10
  const cell=value=>String(value).replaceAll('|','|').replace(/[\r\n]+/g,' ');
@@ -43,8 +44,8 @@ export function appendFixMetrics({specsRoot,identity,dossierFile},{assertOwned})
43
44
  };
44
45
  owned();
45
46
  need(path.isAbsolute(specsRoot)&&fs.realpathSync(specsRoot)===specsRoot,'unsupported_path');
46
- const [log]=readReviewSourceFiles(specsRoot,['运行日志.jsonl']);
47
- const events=new TextDecoder('utf-8',{fatal:true}).decode(Buffer.from(log.contentBase64,'base64')).trim().split('\n').map(line=>JSON.parse(line));
47
+ // Streamed: the log may exceed the 1 MiB review-material limit (see log-events.mjs).
48
+ const events=eventsAt(specsRoot);
48
49
  const record=fixMetricsRow({events,identity,dossierFile});
49
50
  const [dossier]=readReviewSourceFiles(specsRoot,[`fixes/${dossierFile}`]);
50
51
  const completion=events.find(event=>event.event_id===record.completionEventId);
@@ -51,13 +51,15 @@ export function fixProgress(status,config={},authorization={}){
51
51
  }
52
52
  }
53
53
  const invocation=status.finalReviewInvocation;
54
+ if(stage==='unknown'&&status.pending==='rediagnosis')return {...result,current:'重新诊断已登记但还没有有效结论',blocker:'rediagnosis_answer_required',
55
+ nextAction:'原 run 再次使用 rediagnose(--allow-rediagnosis、reason)提交合法诊断答案;沿用已登记的这一次重新诊断,不另占次数,之后进入第二轮根因审查。',requiresUser:true};
54
56
  if(stage==='unknown'){
55
57
  const finalPending=!revision&&invocation&&(!review||review.observationStatus==='unknown');
56
58
  return {...result,current:finalPending?'独立审查结果未确认':'操作结果未确认',blocker:'result_unconfirmed',
57
59
  remaining:finalPending?['取得有效独立审查结果','保存审查证据','核对完成条件','审后回归',...(config.walkthrough?['走查']:[]),'完成收尾']:null,
58
60
  nextAction:finalPending&&invocation.providerThreadId
59
61
  ?'先确认原调用已停止;核对当前审查包并取得本次一次续审授权,再恢复原任务。'
60
- :status.reviewAbandonable?'审查没有结论:先确认原审查进程已停止,再用 abandon_review(--allow-abandon-review,原因审查与第二轮最终审查各一次)放弃这次调用,然后重新审查。'
62
+ :status.reviewAbandonable?'审查没有结论:先确认原审查进程已停止,再用 abandon_review(--allow-abandon-review,每轮原因审查与第二轮最终审查各一次)放弃这次调用,然后重新审查。'
61
63
  :'核对原操作与实际结果;不要重跑已完成步骤或推定成功。',requiresUser:true,
62
64
  ...(finalPending?{recovery:{invocationId:invocation.invocationId,packageDigest:invocation.packageDigest,
63
65
  completedRecoveryPreparations:status.finalReviewRecoveryCount??0,
@@ -16,6 +16,8 @@ import {inspectPrdDesignRiskSelection} from './design-risk.mjs';
16
16
  import {readCmInitSource} from '../cm-init/draft-inspection.mjs';
17
17
  import {prdDraftJson} from './validation-reason.mjs';
18
18
 
19
+ const initialTaskInstructions=' For FIRST task planning only: combine related low-risk work around one independently verifiable and reversible objective. Retain every AC, original user test, expected result and verification prerequisite; keep AC-to-test-to-task references complete. Same file/component alone is not evidence to combine. Keep high-risk work, unknown-risk work, explicit user requests for independent tasks and unrelated objectives separate; preserve legitimate contract-first tasks and real dependencies. Use requirement/design/context evidence, not keyword risk classification or another model call. No fixed merge ratio or task-count target. Do not repartition an existing draft, revision, restored task list, change or in-flight task. Scope expansion during development requires the existing explicit change and renewed approval. Keep configured developer/reviewer roles and each task independent N4 unchanged.';
20
+
19
21
  export function createCmPrdAnalysis({input,runtime,analyze,record,processMaterials,generate,checkContext,restored=null,allowInputDrift=false}){
20
22
  need(['codex','claude'].includes(runtime)&&typeof analyze==='function'&&typeof record==='function','prd_host_invalid');
21
23
  input=json(input);
@@ -192,11 +194,12 @@ export function createCmPrdAnalysis({input,runtime,analyze,record,processMateria
192
194
  revision:draft===null?null:{draft,contextCheck,round:selfCheckRound+1,
193
195
  instructions:'Correct findings only within these existing feature names/directories. Do not add, remove or rename features; retain user intent and tests. No review invocation. Two self-check rounds maximum.'},
194
196
  reference:path.join(admission.skillDir,'SKILL.md'),testContract:path.join(admission.workflowRoot,'runtime/test-contract.md'),
195
- instructions:canRevise?
197
+ instructions:(canRevise?
196
198
  'Correct the failed whole-draft self-check in the existing draft schema. Keep exactly the same ordered features and file inventory. Requirements/design changes require selfCheckRevisionReason. Return question or blocked if needed. No writes, review dispatch, invented approval or extra rounds.':acceptedDesign!==null?
197
199
  'Follow original cm-prd Step 10 and 10.4 on acceptedDesign. Return the existing draft schema with the exact same ordered features and exact requirements.md/design.md bytes supplied there; generate tasks.md and applicable test-cases.json only. Do not regenerate or revise accepted requirements/design, change scope or call a reviewer. Preserve original user cases and unresolved design findings for human review. Ask material questions with {status:question,question}; no invented user decisions. No writes, provider calls, installation, development or approval. Subsequent original self-check and split review remain required.':designOnly?
198
200
  'Follow cm-prd Steps 6-9 only, before original Step 9.5 design review. Read required references and actual relevant project context. Preserve user cases and requirements. No tasks or test-contract generation yet, even embedded in another document. Resolve material or human UI baseline decisions with {status:question,question}; never infer consent. Return {status:design,summary,features:[{name:kebab_slug,documents:[{path:requirements.md|design.md,content:string}]}]} with exactly both documents per feature, or {status:blocked,reason}. No writes, provider calls, browser launch, installation, review claims or development. These are unreviewed memory drafts, not authority to generate tasks.':
199
- 'Follow cm-prd Steps 6-10 for in-memory DRAFTS ONLY. Read required references and relevant project context. Resolve material questions and human UI baseline choices before design: return {status:question,question} and wait, never infer consent. No writes, provider calls, browser launch, installation, review claims or development. Return {status:draft,summary,features:[{name:kebab_slug,documents:[{path:requirements.md|design.md|tasks.md|test-cases.json,content:string}],testCasesReason:null|no_observable_behavior|generation_disabled}]} or {status:blocked,reason}. Each feature needs the triad. Apply functional task granularity <=15, AC/Task references, applicable test contract and original user-case intent; generateCases false forbids generated cases only. This draft is unreviewed; original conditional design review, split review, self-check and human approval remain pending.'},controller.signal),64*1024);
201
+ 'Follow cm-prd Steps 6-10 for in-memory DRAFTS ONLY. Read required references and relevant project context. Resolve material questions and human UI baseline choices before design: return {status:question,question} and wait, never infer consent. No writes, provider calls, browser launch, installation, review claims or development. Return {status:draft,summary,features:[{name:kebab_slug,documents:[{path:requirements.md|design.md|tasks.md|test-cases.json,content:string}],testCasesReason:null|no_observable_behavior|generation_disabled}]} or {status:blocked,reason}. Each feature needs the triad. Apply functional task granularity <=15, AC/Task references, applicable test contract and original user-case intent; generateCases false forbids generated cases only. This draft is unreviewed; original conditional design review, split review, self-check and human approval remain pending.')
202
+ +(draft===null&&!designOnly?initialTaskInstructions:'')},controller.signal),64*1024);
200
203
  need(!controller.signal.aborted,'cancelled');current();
201
204
  need(digest(inventory)===digest(prdFeatureInventory(admission.specs)),'prd_feature_inventory_changed');
202
205
  if(reply.status==='question'){
@@ -36,7 +36,8 @@ export async function runPrdHostReview({specs,prepared,authorContextId,writeEnab
36
36
  const paths=(pkg.stage==='design'?['requirements.md','design.md']:['requirements.md','design.md','tasks.md'])
37
37
  .map(file=>`${pkg.feature}/${file}`).sort();
38
38
  const response=json(await review({package:{...pkg,packageDigest:prepared.packageDigest},examinedPaths:paths,authorContextId,mode,
39
- instructions:'Use only the authorized current-host review channel. independent requires an actual fresh reviewer context, not the author. self-degraded uses the author and must explain unavailable independence. Verify context identity and forward the original result unchanged. No provider/CLI invocation, installation, external transmission, Git or project writes without separate authority. Return {reviewer,contextId,independent,at,result}, plus degradedReason only for self-degraded. Result follows verdict/packageDigest/examinedPaths/findings/summary. Do not retry or switch mode after this attempt; unavailable/interrupted remains unknown.'},signal),64*1024);
39
+ instructions:'Use only the authorized current-host review channel. independent requires an actual fresh reviewer context, not the author. self-degraded uses the author and must explain unavailable independence. Verify context identity and forward the original result unchanged. No provider/CLI invocation, installation, external transmission, Git or project writes without separate authority. Return {reviewer,contextId,independent,at,result}, plus degradedReason only for self-degraded. Result follows verdict/packageDigest/examinedPaths/findings/summary. Do not retry or switch mode after this attempt; unavailable/interrupted remains unknown.'
40
+ +(pkg.stage==='split'?' In this existing split attempt, assess submitted task boundaries: combined work must share one independently verifiable and reversible objective with every AC, original test and verification prerequisite retained. Check requirement/design/context evidence for high or unknown risk, explicit user independence and unrelated objectives; retain those boundaries and legitimate contract-first dependencies. Do not infer risk from keywords, add a classifier/review call, enforce a merge ratio or repartition already generated tasks for fewer reviews. Do not apply this new grouping guidance retroactively to older drafts, revisions, change plans or in-flight tasks. Report only existing requirement/design failures with concrete consequences; mechanical reference checks alone do not establish semantic risk or user intent. Configured roles and per-task N4 remain unchanged.':'')},signal),64*1024);
40
41
  need(!signal.aborted,'cancelled');current();
41
42
  validatePrdReviewMode(mode,response);
42
43
  const published=publishPrdReview({specs,reviewPackage:pkg,packageDigest:prepared.packageDigest,authorContextId,response});
@@ -4,6 +4,7 @@ import fs from 'node:fs';
4
4
  import path from 'node:path';
5
5
  import {inspectRunClosure} from '../../../scripts/cm-log-event.mjs';
6
6
  import {need,digest,json} from '../cm-ai/effect-contract.mjs';
7
+ import {readStableLogRows} from '../cm-ai/log-rows.mjs';
7
8
  import {inside,canonicalFuture,selectReportDirectory} from './source-snapshot.mjs';
8
9
 
9
10
  export function inspectCmTestRecovery(config,{runId,logFile}){
@@ -23,10 +24,9 @@ export function inspectCmTestRecovery(config,{runId,logFile}){
23
24
  const allowed=admission.specs?logFile===path.join(admission.specs,'运行日志.jsonl'):
24
25
  inside(path.join(logHome,'runs'),logFile)&&logFile.endsWith('.jsonl');
25
26
  need(allowed,'cm_test_log_path_invalid');
26
- const stat=fs.lstatSync(logFile);
27
- need(stat.isFile()&&!stat.isSymbolicLink()&&stat.nlink===1&&stat.size<=32*1024*1024,'cm_test_log_invalid');
28
- const lines=fs.readFileSync(logFile,'utf8').split('\n').filter(Boolean);
29
- const records=lines.map(line=>JSON.parse(line)).filter(event=>event.run_id===runId);
27
+ // Streamed with the same single-link/stable-file checks: a shared project log
28
+ // keeps growing, and only this run's rows matter here (no 32 MiB whole-file cap).
29
+ const records=readStableLogRows(logFile,event=>event?.run_id===runId,'cm_test_log_invalid');
30
30
  const starts=records.filter(event=>event.event==='run_start');
31
31
  need(starts.length===1&&starts[0].workflow==='cm-test'&&starts[0].project_path===admission.project,
32
32
  'cm_test_run_binding_invalid');
@@ -0,0 +1,26 @@
1
+ // Detached launcher for notify.mjs. Runs the user's notify command (no shell)
2
+ // with the message in CM_NOTIFY_TITLE/CM_NOTIFY_BODY and one JSON line on
3
+ // stdin, kills it after the timeout, and records only failures in notify.log.
4
+ // The workflow that started this process never waits for it.
5
+ import {spawn} from 'node:child_process';
6
+ import {appendNotifyLog} from './notify.mjs';
7
+
8
+ const [home,hash,event,workflow,timeoutRaw,separator,...command]=process.argv.slice(2);
9
+ const timeoutMs=Number(timeoutRaw);
10
+ let settled=false,timer=null;
11
+ const finish=reason=>{
12
+ if(settled)return;settled=true;clearTimeout(timer);
13
+ if(reason&&home)appendNotifyLog(home,Date.now(),{event,workflow,hash,result:`failed ${reason}`});
14
+ process.exit(0);
15
+ };
16
+ try{
17
+ if(separator!=='--'||command.length===0||!Number.isSafeInteger(timeoutMs)||timeoutMs<=0)finish('runner_arguments');
18
+ const payload=process.env.CM_NOTIFY_PAYLOAD??'{}';
19
+ const env={...process.env};delete env.CM_NOTIFY_PAYLOAD;
20
+ const child=spawn(command[0],command.slice(1),{stdio:['pipe','ignore','ignore'],shell:false,windowsHide:true,env});
21
+ timer=setTimeout(()=>{try{child.kill('SIGKILL');}catch{}finish('timeout');},timeoutMs);
22
+ child.on('error',error=>finish(`spawn_${String(error.code??'failed').toLowerCase()}`));
23
+ child.on('exit',(code,signal)=>finish(code===0?null:signal?`signal_${signal}`:`exit_${code}`));
24
+ child.stdin.on('error',()=>{});
25
+ child.stdin.end(payload+'\n');
26
+ }catch(error){finish(`spawn_${String(error?.code??'failed').toLowerCase()}`);}
@@ -0,0 +1,388 @@
1
+ // Optional "a person is needed" notices, shared by every workflow.
2
+ // Provider-neutral: hands one user-configured local command (no shell) a short
3
+ // message built only from structured fields. It never answers, continues or
4
+ // authorizes anything. Nothing here waits: the command runs under a detached,
5
+ // unref'd launcher (notify-run.mjs) that owns its own 15 s timeout, so a
6
+ // workflow's exit time, exit code, output and state never depend on it.
7
+ // Problems only append one line to notify.log.
8
+ import fs from 'node:fs';
9
+ import os from 'node:os';
10
+ import path from 'node:path';
11
+ import {spawn} from 'node:child_process';
12
+ import {fileURLToPath} from 'node:url';
13
+ import {createHash,randomUUID} from 'node:crypto';
14
+
15
+ export const NOTIFY_LIMITS=Object.freeze({sameKeyMs:6*3600*1000,perMinute:4,perDay:150,
16
+ commandTimeoutMs:15000,titleChars:60,bodyChars:500,defaultWaitMinutes:10,defaultCheckWaitMinutes:45,
17
+ defaultIdleMinutes:45});
18
+ const LOCK_STALE_MS=30000,LOG_LIMIT=256*1024;
19
+ const RUNNER=fileURLToPath(new URL('./notify-run.mjs',import.meta.url));
20
+
21
+ export function notifyHome(env=process.env){
22
+ return path.resolve(env.CM_WORKFLOW_HOME||path.join(os.homedir(),'.cm-workflow'));
23
+ }
24
+
25
+ // One line per problem; never the message, the command's output or any env.
26
+ export function appendNotifyLog(home,now,{event='-',workflow='-',hash='-',result}){
27
+ try{
28
+ const file=path.join(home,'notify.log');
29
+ try{if(fs.statSync(file).size>LOG_LIMIT)fs.renameSync(file,`${file}.1`);}catch{}
30
+ const word=(value,max)=>String(value??'-').replace(/[^A-Za-z0-9_.:-]+/g,'_').slice(0,max)||'-';
31
+ fs.appendFileSync(file,`${new Date(now).toISOString()} ${word(event,12)} ${word(workflow,24)} key=${word(hash,16)} ${String(result).replace(/[^A-Za-z0-9_ .:-]+/g,'_').slice(0,80)}\n`,{mode:0o600});
32
+ }catch{}
33
+ }
34
+
35
+ let warned=false;
36
+ const warn=(env,reason)=>{
37
+ if(warned)return;warned=true;
38
+ appendNotifyLog(notifyHome(env),Date.now(),{event:'config',result:`off invalid_config ${reason}`});
39
+ };
40
+
41
+ // null = feature off. Under `node --test` only an explicit CM_WORKFLOW_HOME
42
+ // enables it, so a test suite never reaches the user's real configuration.
43
+ // An invalid file is reported in notify.log only, never on workflow output.
44
+ export function readNotifyConfig(env=process.env){
45
+ if(env.NODE_TEST_CONTEXT&&!env.CM_WORKFLOW_HOME)return null;
46
+ const file=path.join(notifyHome(env),'notify.json');
47
+ let raw;
48
+ try{raw=fs.readFileSync(file,'utf8');}catch(error){if(error.code!=='ENOENT')warn(env,`unreadable_${error.code??'error'}`);return null;}
49
+ let value;
50
+ try{value=JSON.parse(raw);}catch{warn(env,'not_json');return null;}
51
+ if(!value||typeof value!=='object'||Array.isArray(value)||value.version!==1){warn(env,'version');return null;}
52
+ const {command}=value;
53
+ if(!Array.isArray(command)||command.length<1||command.length>32
54
+ ||!command.every(item=>typeof item==='string'&&item.length>0&&item.length<=4096&&!item.includes('\0'))){
55
+ warn(env,'command');return null;
56
+ }
57
+ if(!path.isAbsolute(command[0])){warn(env,'command_not_absolute');return null;}
58
+ const minutes=value.waitMinutes??NOTIFY_LIMITS.defaultWaitMinutes;
59
+ if(typeof minutes!=='number'||!Number.isFinite(minutes)||minutes<=0||minutes>1440){warn(env,'wait_minutes');return null;}
60
+ const checkMinutes=value.checkWaitMinutes??NOTIFY_LIMITS.defaultCheckWaitMinutes;
61
+ if(typeof checkMinutes!=='number'||!Number.isFinite(checkMinutes)||checkMinutes<=0||checkMinutes>1440){warn(env,'check_wait_minutes');return null;}
62
+ const idleMinutes=value.idleMinutes??NOTIFY_LIMITS.defaultIdleMinutes;
63
+ if(typeof idleMinutes!=='number'||!Number.isFinite(idleMinutes)||idleMinutes<=0||idleMinutes>1440){warn(env,'idle_minutes');return null;}
64
+ const ms=value=>Math.max(1,Math.round(value*60000));
65
+ return {command:[...command],waitMs:ms(minutes),checkWaitMs:ms(checkMinutes),idleMs:ms(idleMinutes)};
66
+ }
67
+
68
+ // Messages carry only these structured fields. Absolute paths (POSIX, drive
69
+ // letter, UNC; also when glued to CJK text) are redacted and control
70
+ // characters removed; every field and the whole message are bounded.
71
+ const cut=(text,max)=>{const chars=Array.from(text);return chars.length<=max?text:chars.slice(0,max-1).join('')+'…';};
72
+ function clean(value,max){
73
+ if(typeof value!=='string'&&!(typeof value==='number'&&Number.isFinite(value)))return '';
74
+ const text=String(value).replace(/[\u0000-\u001f\u007f-\u009f]+/g,' ')
75
+ .replace(/(?<![A-Za-z0-9_.~-])(?:~?\/|[A-Za-z]:[\\/]|\\\\)[^\s'"`,。;;、))]+/g,'<路径>')
76
+ .replace(/\s+/g,' ').trim();
77
+ return cut(text,max);
78
+ }
79
+ const projectName=value=>typeof value==='string'&&value?clean(path.basename(value),40):'';
80
+
81
+ export function buildNotifyMessage(fields,{now=Date.now()}={}){
82
+ const workflow=clean(fields.workflow,24)||'cm',project=projectName(fields.project);
83
+ const headline={done:'流程已结束',waiting:'等待会话应答',idle:'疑似空转',idle_waiting:'在等你',dead:'宿主已退出未收尾'}[fields.event]??'需要人处理';
84
+ const title=cut(`CM ${workflow} ${headline}${project?` · ${project}`:''}`,NOTIFY_LIMITS.titleChars);
85
+ const lines=[['项目',project],['流程',workflow],['运行',clean(fields.runId,64)],['任务',clean(fields.task,40)],
86
+ ['阶段',clean(fields.stage,48)],['原因',clean(fields.code,64)],['下一步',clean(fields.nextAction,200)]]
87
+ .filter(([,value])=>value).map(([label,value])=>`${label}:${value}`);
88
+ lines.push(`时间:${new Date(now).toISOString()}`);
89
+ if(fields.event!=='done')lines.push('CM 不会自动继续,请回到会话处理。');
90
+ return {title,body:cut(lines.join('\n'),NOTIFY_LIMITS.bodyChars)};
91
+ }
92
+
93
+ const keyHash=key=>createHash('sha256').update(key).digest('hex').slice(0,16);
94
+
95
+ // Cross-process lock without any waiting. The lock file is published complete
96
+ // (written to a temp file, then hard-linked into place, which fails if a lock
97
+ // exists). A busy lock skips the notice at once. A stale lock (owner gone or
98
+ // older than 30 s; the critical section takes milliseconds) is reclaimed only
99
+ // by renaming it to a unique name and confirming it is byte-identical to the
100
+ // stale lock that was judged; anything else is put back and the notice skipped.
101
+ function readLock(file){try{return fs.readFileSync(file,'utf8');}catch{return null;}}
102
+ function stale(raw){
103
+ let value;try{value=JSON.parse(raw);}catch{return false;}
104
+ if(!Number.isSafeInteger(value?.pid)||!Number.isFinite(value?.at))return false;
105
+ if(Date.now()-value.at>LOCK_STALE_MS)return true;
106
+ if(value.pid===process.pid)return false;
107
+ try{process.kill(value.pid,0);return false;}catch(error){return error.code==='ESRCH';}
108
+ }
109
+ function publishLock(file,body){
110
+ const temp=`${file}.${process.pid}.${randomUUID()}.tmp`;
111
+ try{fs.writeFileSync(temp,body,{mode:0o600});fs.linkSync(temp,file);return true;}
112
+ catch{return false;}
113
+ finally{try{fs.unlinkSync(temp);}catch{}}
114
+ }
115
+ function takeLock(file){
116
+ const token=randomUUID(),body=JSON.stringify({pid:process.pid,at:Date.now(),token});
117
+ if(publishLock(file,body))return body;
118
+ const seen=readLock(file);
119
+ if(seen===null||!stale(seen))return null;
120
+ const grave=`${file}.stale-${randomUUID()}`;
121
+ try{fs.renameSync(file,grave);}catch{return null;}
122
+ if(readLock(grave)!==seen){try{fs.linkSync(grave,file);}catch{}try{fs.unlinkSync(grave);}catch{}return null;}
123
+ try{fs.unlinkSync(grave);}catch{}
124
+ return publishLock(file,body)?body:null;
125
+ }
126
+ function releaseLock(file,body){if(readLock(file)===body){try{fs.unlinkSync(file);}catch{}}}
127
+
128
+ // Dedup and throttle across processes. Any lock or parse trouble skips the
129
+ // notice instead of waiting on it.
130
+ function reserve(home,hash,now){
131
+ const lockFile=path.join(home,'notify-state.lock'),stateFile=path.join(home,'notify-state.json');
132
+ const lock=takeLock(lockFile);if(lock===null)return 'state_busy';
133
+ try{
134
+ let state={version:1,keys:{},sends:[]};
135
+ try{state=JSON.parse(fs.readFileSync(stateFile,'utf8'));}
136
+ catch(error){if(error.code!=='ENOENT')return 'state_invalid';}
137
+ if(!state||state.version!==1||!state.keys||typeof state.keys!=='object'||Array.isArray(state.keys)
138
+ ||!Array.isArray(state.sends)||!state.sends.every(Number.isFinite)
139
+ ||!Object.values(state.keys).every(Number.isFinite))return 'state_invalid';
140
+ const keys=Object.fromEntries(Object.entries(state.keys).filter(([,at])=>now-at<NOTIFY_LIMITS.sameKeyMs&&at<=now));
141
+ const sends=state.sends.filter(at=>now-at<24*3600*1000&&at<=now);
142
+ if(Object.hasOwn(keys,hash))return 'duplicate';
143
+ if(sends.filter(at=>now-at<60000).length>=NOTIFY_LIMITS.perMinute)return 'rate_minute';
144
+ if(sends.length>=NOTIFY_LIMITS.perDay)return 'rate_day';
145
+ keys[hash]=now;sends.push(now);
146
+ const temp=`${stateFile}.${process.pid}.${randomUUID()}.tmp`;
147
+ try{fs.writeFileSync(temp,JSON.stringify({version:1,keys,sends}),{mode:0o600});fs.renameSync(temp,stateFile);}
148
+ catch{try{fs.unlinkSync(temp);}catch{}return 'state_write_failed';}
149
+ return 'ok';
150
+ }finally{releaseLock(lockFile,lock);}
151
+ }
152
+
153
+ // Never throws and never waits. Returns {sent, reason}; sent means the command
154
+ // was handed to the detached launcher, whose own failures go to notify.log.
155
+ export function notify(fields,{env=process.env,now=Date.now(),timeoutMs=NOTIFY_LIMITS.commandTimeoutMs}={}){
156
+ try{
157
+ const config=readNotifyConfig(env);if(!config)return {sent:false,reason:'off'};
158
+ if(typeof fields?.key!=='string'||!fields.key)return {sent:false,reason:'invalid_key'};
159
+ const home=notifyHome(env),hash=keyHash(fields.key),event=fields.event??'stuck',workflow=clean(fields.workflow,24)||'cm';
160
+ const reserved=reserve(home,hash,now);
161
+ if(reserved!=='ok'){
162
+ if(reserved!=='duplicate')appendNotifyLog(home,now,{event,workflow,hash,result:`skipped ${reserved}`});
163
+ return {sent:false,reason:reserved};
164
+ }
165
+ const message=buildNotifyMessage(fields,{now});
166
+ const payload={...message,event};
167
+ for(const name of ['project','workflow','runId','task','stage','code','nextAction']){
168
+ const value=name==='project'?projectName(fields.project):clean(fields[name],name==='nextAction'?200:64);
169
+ if(value)payload[name]=value;
170
+ }
171
+ const child=spawn(process.execPath,[RUNNER,home,hash,event,workflow,String(timeoutMs),'--',...config.command],
172
+ {detached:true,stdio:'ignore',windowsHide:true,
173
+ env:{...env,CM_NOTIFY_TITLE:message.title,CM_NOTIFY_BODY:message.body,CM_NOTIFY_PAYLOAD:JSON.stringify(payload)}});
174
+ child.on('error',()=>appendNotifyLog(home,Date.now(),{event,workflow,hash,result:'failed launcher'}));
175
+ child.unref();
176
+ return {sent:true,reason:'launched'};
177
+ }catch{return {sent:false,reason:'error'};}
178
+ }
179
+
180
+ // Host registry: one small private file per live host session under
181
+ // <home>/hosts, so the read-only patrol (scripts/cm-patrol.mjs) can tell a host
182
+ // that died from one that is merely idle. Written only when notices are
183
+ // configured, updated on events the host already has (start, each reply),
184
+ // removed at session end. Best-effort: never throws, never changes the host.
185
+ export const HOST_REGISTRY_MAX_AGE_MS=48*3600*1000;
186
+ const SESSION_KEY=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
187
+ export function hostRegistryDir(env=process.env){return path.join(notifyHome(env),'hosts');}
188
+ export function writeHostRegistry({sessionKey,workflow,project,startedAt,row=null,operation=null},{env=process.env,now=Date.now()}={}){
189
+ try{
190
+ if(!readNotifyConfig(env)||!SESSION_KEY.test(sessionKey))return false;
191
+ const dir=hostRegistryDir(env);fs.mkdirSync(dir,{recursive:true,mode:0o700});
192
+ const result=obj(row?.result);
193
+ const entry={version:1,pid:process.pid,sessionKey,workflow:clean(workflow,24)||'cm',
194
+ project:typeof project==='string'?project:'',startedAt:new Date(startedAt).toISOString(),at:new Date(now).toISOString(),
195
+ operation:clean(operation,32)||null,
196
+ runId:text(result.identity?.runId)??text(result.runId)??text(result.batchId)??null,
197
+ task:text(result.identity?.taskId)??text(result.taskId)??null,
198
+ stage:text(result.stage)??text(result.state)??text(result.status)??null};
199
+ const file=path.join(dir,`${sessionKey}.json`),temp=`${file}.${process.pid}.tmp`;
200
+ fs.writeFileSync(temp,JSON.stringify(entry),{mode:0o600});fs.renameSync(temp,file);return true;
201
+ }catch{return false;}
202
+ }
203
+ // Same test guard as readNotifyConfig: a test suite without an explicit
204
+ // CM_WORKFLOW_HOME never touches the user's real directory, not even to unlink.
205
+ export function removeHostRegistry(sessionKey,{env=process.env}={}){
206
+ if(env.NODE_TEST_CONTEXT&&!env.CM_WORKFLOW_HOME)return;
207
+ try{if(SESSION_KEY.test(sessionKey))fs.unlinkSync(path.join(hostRegistryDir(env),`${sessionKey}.json`));}catch{}
208
+ }
209
+
210
+ // Host side: one notice when a host_request has waited waitMinutes for the
211
+ // session's answer. The timer never keeps the process alive.
212
+ const CHECK_KINDS=new Set(['check','verification_precheck','init_verify']);
213
+ export function scheduleWaitNotice({kind,callId,workflow,project,env=process.env}){
214
+ try{
215
+ const config=readNotifyConfig(env);if(!config)return null;
216
+ // A check request is answered only after the session has run the project's
217
+ // check commands (xcodebuild, test suites), which normally take tens of
218
+ // minutes; waiting that long is not idleness, so it uses its own threshold.
219
+ const waitMs=CHECK_KINDS.has(kind)?config.checkWaitMs:config.waitMs;
220
+ const minutes=Math.max(1,Math.round(waitMs/60000));
221
+ const timer=setTimeout(()=>{notify({key:`wait|${workflow}|${callId}`,event:'waiting',workflow,project,stage:kind,
222
+ code:'waiting_session_answer',nextAction:`宿主已等待会话应答约 ${minutes} 分钟,请回到会话处理`},{env});},waitMs);
223
+ timer.unref?.();
224
+ return ()=>clearTimeout(timer);
225
+ }catch{return null;}
226
+ }
227
+
228
+ // Host side: one notice when an operation has replied, nothing is in flight
229
+ // and the session has not sent the next operation for idleMinutes (polls excluded). A last
230
+ // result that already waits on a person (or ended the run) says so instead of
231
+ // "idle". Built only from that result's structured fields; the timer never
232
+ // keeps the process alive.
233
+ export function scheduleIdleNotice({workflow,project,sessionKey,seq,row,since=Date.now(),env=process.env}){
234
+ try{
235
+ const config=readNotifyConfig(env);if(!config)return null;
236
+ // `since` is the last real reply: re-arming after a poll keeps that deadline.
237
+ const delay=Math.max(1,Math.min(config.idleMs,config.idleMs-(Date.now()-since)));
238
+ const minutes=Math.max(1,Math.round(config.idleMs/60000));
239
+ const kind=classifyDriveResult(workflow,row),result=obj(row?.result);
240
+ const runId=text(result.identity?.runId)??text(result.runId)??text(result.batchId);
241
+ const task=text(result.identity?.taskId)??text(result.taskId);
242
+ const stage=text(result.stage)??text(result.state)??text(result.status);
243
+ const nextAction=kind==='done'?`流程已结束,宿主仍开着约 ${minutes} 分钟没有下一步,请回到会话收尾或开始下一项`
244
+ :kind==='stuck'?`上一步停在需要你处理的状态,约 ${minutes} 分钟没有下一步,请回到会话处理`
245
+ :`上一步已结束约 ${minutes} 分钟,会话没有发下一步,请回到会话查看`;
246
+ const timer=setTimeout(()=>{notify({key:`idle|${workflow}|${sessionKey}|${seq}`,event:kind?'idle_waiting':'idle',
247
+ workflow,project,runId,task,stage,code:kind?'waiting_for_you':'no_next_step',nextAction},{env});},delay);
248
+ timer.unref?.();
249
+ return ()=>clearTimeout(timer);
250
+ }catch{return null;}
251
+ }
252
+
253
+ // Driver side: decide from the final host response (or the driver's own stop)
254
+ // whether a person is needed. Each workflow is classified by its own result
255
+ // contract (see the host named in each entry); normal progress returns null.
256
+ // 'stuck' = stopped until a person acts; 'done' = the run has ended.
257
+ const text=value=>typeof value==='string'&&value?value:null;
258
+ const obj=value=>value&&typeof value==='object'&&!Array.isArray(value)?value:{};
259
+ const STUCK_COMMON=new Set(['blocked','cancelled','failed','interrupted']);
260
+ const verdict=(value,{done,stuck})=>stuck.has(value)?'stuck':done.has(value)?'done':null;
261
+ // cm-fix owner projection (runtime/js/cm-fix/execution.mjs, progress.mjs): stages
262
+ // on the normal path continue; everything else falls through to "a person
263
+ // decides", exactly like fixProgress's requiresUser fallback.
264
+ const FIX_FLOW=new Set(['reproduce','diagnose','cause_review_required','test_author_required','red_test_required',
265
+ 'design_change_required','baseline_required','repair_required','regression_required','handoff_required',
266
+ 'learning_writeback_required','handoff_ready','final_review_required','final_review_evidence_required',
267
+ 'completion_gate_required','post_review_regression_required','closeout_required','escalation_required',
268
+ 'observation_resume_prepared','observation_diagnose_required','revision_prepared','revision_test_author_required',
269
+ 'revision_test_check_required']);
270
+ function classifyFix(r){
271
+ const stage=text(r.stage);if(!stage)return null;
272
+ if(stage==='completed')return 'done';
273
+ if(r.progress&&typeof r.progress==='object'){if(r.progress.finished===true)return 'done';if(r.progress.requiresUser===true)return 'stuck';}
274
+ // A refused review authorization keeps the stage (execution.mjs) but waits on a person.
275
+ if(text(r.reason)==='permission_denied')return 'stuck';
276
+ return FIX_FLOW.has(stage)||FIX_FLOW.has(stage.replace(/^revision_/,''))?null:'stuck';
277
+ }
278
+ // cm-ai conversation entry (runtime/js/cm-ai/cm-ai-conversation-entry.mjs, operator-guidance.mjs,
279
+ // task-runner.mjs) and the QA-fix owner (host-qa-fix-owner.mjs). The only run end is
280
+ // run_done; start_next_task hands over to the next task and is progress.
281
+ const AI_PROGRESS_CODES=new Set(['context_refreshed','context_complete','qa_skipped','qa_passed','documentation_synced',
282
+ 'documentation_sync_required','revision_answer_required']);
283
+ const AI_STUCK_STATES=new Set(['blocked','unknown','pending_review','cancelled','awaiting_spec_approval']);
284
+ const AI_STUCK_ACTIONS=new Set(['reconcile','abandon_effect','abandon_review','reconcile_review','bootstrap_review_recover',
285
+ 'review_evidence','spec_rebind','fix_authorization','fix_dispatch','qa_execution']);
286
+ const AI_STUCK_CODES=new Set(['decision_required','permission_denied','provider_development_authorization_required',
287
+ 'qa_decision_required','qa_mandatory_required','qa_triggered','qa_blocked','qa_failed','qa_result_blocked',
288
+ 'qa_execution_unknown','correction_review_required','project_qa_not_passed','documentation_sync_blocked',
289
+ 'handoff_exists','spec_drift','qa_fix_code_unmatched']);
290
+ function classifyAi(r){
291
+ const state=text(r.state),code=text(r.code),outcome=text(r.outcome);
292
+ if(state==='run_done'&&['run_done','run_done_degraded'].includes(code))return 'done';
293
+ if(code==='qa_fix_incomplete')return classifyFix({stage:r.fixStage});
294
+ if(['qa_fix_completed','qa_fix_active','qa_fix_owner_busy'].includes(code)||outcome==='abandoned')return null;
295
+ if(r.pendingAction==='start_next_task'||AI_PROGRESS_CODES.has(code))return null;
296
+ if(['rejected','denied','cancelled','blocked','awaiting'].includes(outcome)||AI_STUCK_STATES.has(state)
297
+ ||AI_STUCK_ACTIONS.has(r.pendingAction)||AI_STUCK_CODES.has(code))return 'stuck';
298
+ return null;
299
+ }
300
+ const CLASSIFY={
301
+ 'cm-ai':classifyAi,
302
+ // scripts/cm-ai-batch-run.mjs: member results pass through; batch-level stops
303
+ // carry outcome blocked/cancelled; the last member's run_done ends the batch.
304
+ 'cm-ai-batch':classifyAi,
305
+ 'cm-fix':classifyFix,
306
+ // runtime/js/cm-prd/analysis.mjs, change.mjs, summary.mjs, draft-save.mjs, review-*.mjs; scripts/cm-prd-host.mjs.
307
+ 'cm-prd'(r){
308
+ const stage=text(r.stage),status=text(r.status),review=obj(r.reviewState);
309
+ if(stage==='awaiting_review'||status==='awaiting_review')return 'done';
310
+ if(STUCK_COMMON.has(stage)||STUCK_COMMON.has(status))return 'stuck';
311
+ if(['awaiting_user','awaiting_planning_user','awaiting_design_user','self_check_needs_human','change_confirmation',
312
+ 'change_rejected','inputs_replaced'].includes(stage))return 'stuck';
313
+ if(stage==='change_check_failed'&&Number(r.round)>=2)return 'stuck';
314
+ if(/^change_(requirements|design|tasks|check)$/.test(stage??'')&&text(r.question))return 'stuck';
315
+ if(status&&(/_unknown$/.test(status)||['correction_recovery_required','disposition_details_need_verification'].includes(status)))return 'stuck';
316
+ if(status==='human_summary_prepared'&&r.readyForAwaitingReview===false)return 'stuck';
317
+ if(status==='review_findings_ready'&&r.verdict==='blocked')return 'stuck';
318
+ if(['review_unknown','review_cancelled'].includes(review.status)||review.verdict==='blocked'
319
+ ||obj(review.gate).outcome==='dispatch_unknown')return 'stuck';
320
+ if(Array.isArray(obj(r.recovery).calls)&&r.recovery.calls.some(call=>obj(call).status==='unknown'))return 'stuck';
321
+ return null;
322
+ },
323
+ // scripts/cm-idea-host.mjs.
324
+ 'cm-idea'(r){
325
+ const stage=text(r.stage),recovery=obj(r.recovery);
326
+ if(stage==='saved')return 'done';
327
+ if(recovery.writing===true||obj(recovery.call).status==='unknown')return 'stuck';
328
+ if(stage==='draft_ready')return r.confirmationRequired===true?null:'stuck';
329
+ return ['awaiting_user','save_unknown','save_blocked',...STUCK_COMMON].includes(stage)?'stuck':null;
330
+ },
331
+ // scripts/cm-init-host.mjs, runtime/js/cm-init/draft-generation.mjs (generation returns status, no stage).
332
+ 'cm-init'(r){
333
+ const stage=text(r.stage)??(r.status==='blocked'?'blocked':null),recovery=obj(r.recovery);
334
+ if(['rules_written','rules_present'].includes(stage))return 'done';
335
+ if(recovery.writing===true||obj(recovery.call).status==='unknown')return 'stuck';
336
+ return ['analysis_blocked','verification_blocked','confirmation_required','confirmation_rejected','review_changes_requested',
337
+ 'review_blocked','write_incomplete','write_unknown',...STUCK_COMMON].includes(stage)?'stuck':null;
338
+ },
339
+ // runtime/js/cm-refactor/workflow.mjs.
340
+ 'cm-refactor'(r){
341
+ const stage=text(r.stage);
342
+ if(['done','not_needed','rejected'].includes(stage))return 'done';
343
+ return ['awaiting_finish','rulebook_rejected','correction_required',...STUCK_COMMON].includes(stage)?'stuck':null;
344
+ },
345
+ // runtime/js/cm-test/host.mjs: verdict in result.overall when stage is reported.
346
+ 'cm-test'(r){
347
+ if(r.historical===true)return null;
348
+ const stage=text(r.stage);
349
+ if(stage==='reported')return verdict(r.overall,{stuck:new Set(['FAIL','BLOCKED','FINDING']),
350
+ done:new Set(['PASS','GENERATED','NO_CHANGES','ANALYZED','PARTIAL','REVIEWED','NO_FINDING'])})??'stuck';
351
+ return STUCK_COMMON.has(stage)?'stuck':null;
352
+ },
353
+ // runtime/js/cm-check/host.mjs: verdict nested in result.result.overall.
354
+ 'cm-check'(r){
355
+ const stage=text(r.stage);
356
+ if(stage==='reported')return verdict(obj(r.result).overall,{stuck:new Set(['FAILED','BLOCKED']),
357
+ done:new Set(['PASSED','MECHANICAL_ONLY'])})??'stuck';
358
+ return STUCK_COMMON.has(stage)?'stuck':null;
359
+ },
360
+ };
361
+ // Inspection operations never notify (per host help and driver READ_ONLY sets).
362
+ const READ_ONLY=new Set(['status','fix_status','cancel','qa_result','context_refresh','read_batch','inspect_correction',
363
+ 'final_review_package','review_findings','completion_evidence','cause_review_package']);
364
+ export const NOTIFY_WORKFLOWS=Object.freeze(Object.keys(CLASSIFY));
365
+ export function classifyDriveResult(workflow,row){
366
+ if(row?.error)return 'stuck';
367
+ const classify=CLASSIFY[workflow];
368
+ return classify?classify(obj(row?.result)):null;
369
+ }
370
+ export function driveNotice({host,cwd,args=[],operation,row=null,failure=null}){
371
+ if(READ_ONLY.has(operation))return null;
372
+ const workflow=path.basename(String(host??'')).replace(/-host\.mjs$/,'').replace(/\.mjs$/,'')||'cm';
373
+ const kind=failure?'stuck':classifyDriveResult(workflow,row);
374
+ if(!kind)return null;
375
+ const done=kind==='done',result=obj(row?.result),progress=obj(result.progress),nested=obj(result.result);
376
+ const code=text(failure)??text(row?.error?.code)??text(result.code)??text(result.reason)??text(result.blocker)
377
+ ??text(progress.blocker)??text(result.overall)??text(nested.overall)??text(result.state)??text(result.status)??text(result.stage)??null;
378
+ const runId=text(result.identity?.runId)??text(result.runId)??text(result.batchId);
379
+ const task=text(result.identity?.taskId)??text(result.taskId);
380
+ const attempt=Number.isSafeInteger(result.identity?.attempt)?result.identity.attempt:null;
381
+ const stage=text(result.stage)??text(result.state)??text(result.status)??operation??null;
382
+ const run=runId??`args:${keyHash(args.map(String).join('\0'))}`;
383
+ return {key:[workflow,run,task??'',attempt??'',stage??'',done?'done':code??''].join('|'),
384
+ event:kind,workflow,project:cwd?path.basename(path.resolve(cwd)):null,runId,task,stage,
385
+ code:done?(text(result.code)??text(result.overall)??text(nested.overall)??'done'):code,
386
+ // A finished unit is the natural point to start a fresh session (runtime/model-efficiency.md).
387
+ nextAction:done?'建议在新会话里开始下一个任务,减少重复读入的上下文':text(result.guidance?.nextStep)??text(progress.nextAction)??text(result.nextAction)};
388
+ }
@@ -33,6 +33,23 @@ shared contract, or review finding shows that the packet is insufficient.
33
33
  Record the reason and newly added scope; do not reread or resend unchanged full
34
34
  context. `cm-prd` additionally follows its progressive context-scope contract.
35
35
 
36
+ ## Session boundary
37
+
38
+ Conversation length can outweigh packet size. In one real project sample
39
+ (2026-09-27 to 10-09, 8,417 calls, measured with a local token report), a single
40
+ long session carried 89% of weighted usage: each call re-read about 480k tokens
41
+ of prior history while producing a few hundred output tokens. This is one
42
+ sample, not a general measurement; it motivates suggesting fresh sessions, not a
43
+ claim about every project.
44
+
45
+ Workflows therefore suggest, at the end of a unit of work (a single-task cm-ai
46
+ run at `run_done`, a cm-prd human-review stop, a cm-fix run), starting the next
47
+ unit in a fresh session, which becomes the next run's host context. Batches are
48
+ excluded: a batch hands over to its next task inside the same `advance` and
49
+ keeps its original host context; the suggestion comes only after the whole batch
50
+ ends. Mid-run handover uses the workflow's documented cross-session resume. Changing sessions never rewrites records, skips review, or resets
51
+ authorization.
52
+
36
53
  ## Stable prefix
37
54
 
38
55
  When an integration owns the prompt assembly, keep reusable instructions in