@aibyzero/cm-workflow 0.19.0 → 0.21.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 (127) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +8 -0
  3. package/CHANGELOG.md +38 -0
  4. package/README.md +15 -1
  5. package/VERSION +1 -1
  6. package/docs/architecture.md +3 -0
  7. package/docs/cm-acceptance-completion.md +185 -0
  8. package/docs/installation.md +1 -1
  9. package/docs/js-workflow-control.md +1 -1
  10. package/docs/proposals/spec-amendment-tiers.md +100 -0
  11. package/package.json +1 -1
  12. package/runtime/js/acceptance-language.mjs +32 -0
  13. package/runtime/js/autonomy.mjs +168 -3
  14. package/runtime/js/check-coverage.mjs +130 -0
  15. package/runtime/js/cm-ai/acceptance-contract.mjs +257 -0
  16. package/runtime/js/cm-ai/checkpoint-package-material.mjs +13 -3
  17. package/runtime/js/cm-ai/claude-developer-proposal.schema.json +18 -0
  18. package/runtime/js/cm-ai/cm-ai-admission.mjs +49 -8
  19. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +10 -6
  20. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +8 -3
  21. package/runtime/js/cm-ai/codex-developer-basic-output.schema.json +1 -1
  22. package/runtime/js/cm-ai/codex-developer-output.schema.json +1 -1
  23. package/runtime/js/cm-ai/codex-review-adapter.mjs +19 -3
  24. package/runtime/js/cm-ai/completion-summary.mjs +187 -0
  25. package/runtime/js/cm-ai/control-policy.mjs +3 -1
  26. package/runtime/js/cm-ai/delivery-evidence.mjs +173 -0
  27. package/runtime/js/cm-ai/developer-adapter.mjs +4 -0
  28. package/runtime/js/cm-ai/drive-core.mjs +15 -4
  29. package/runtime/js/cm-ai/durable-runner-state.mjs +10 -6
  30. package/runtime/js/cm-ai/effect-contract.mjs +8 -1
  31. package/runtime/js/cm-ai/execution-snapshot.mjs +4 -3
  32. package/runtime/js/cm-ai/execution-store-limits.mjs +3 -3
  33. package/runtime/js/cm-ai/execution-store.mjs +7 -4
  34. package/runtime/js/cm-ai/fix-code-association.mjs +27 -6
  35. package/runtime/js/cm-ai/gate-bridge.mjs +13 -1
  36. package/runtime/js/cm-ai/host-conversation-execution.mjs +26 -14
  37. package/runtime/js/cm-ai/host-progress.mjs +2 -1
  38. package/runtime/js/cm-ai/log-rows.mjs +3 -2
  39. package/runtime/js/cm-ai/operator-guidance.mjs +110 -4
  40. package/runtime/js/cm-ai/requirement-evidence.mjs +4 -2
  41. package/runtime/js/cm-ai/review-package.mjs +22 -8
  42. package/runtime/js/cm-ai/review-presentation.mjs +12 -5
  43. package/runtime/js/cm-ai/reviewed-deliveries.mjs +10 -7
  44. package/runtime/js/cm-ai/reviewed-integration.mjs +1 -1
  45. package/runtime/js/cm-ai/spec-amendment.mjs +535 -0
  46. package/runtime/js/cm-ai/specification-material.mjs +57 -12
  47. package/runtime/js/cm-ai/task-commit.mjs +4 -2
  48. package/runtime/js/cm-ai/task-runner.mjs +64 -22
  49. package/runtime/js/cm-ai/user-maintained-paths.mjs +68 -0
  50. package/runtime/js/cm-ai/verification-auto.mjs +6 -4
  51. package/runtime/js/cm-prd/acceptance-preview.mjs +203 -0
  52. package/runtime/js/cm-prd/change.mjs +52 -5
  53. package/runtime/js/cm-prd/self-check.mjs +36 -6
  54. package/runtime/js/cm-prd/session.mjs +8 -3
  55. package/runtime/js/cm-prd/summary.mjs +5 -0
  56. package/runtime/js/cm-prd/task-scope-record.mjs +13 -7
  57. package/runtime/js/node-test-selection.mjs +38 -0
  58. package/runtime/js/run-analysis.mjs +153 -0
  59. package/runtime/js/session-boundary.mjs +17 -5
  60. package/runtime/js/session-handoff.mjs +5 -2
  61. package/runtime/js/task-scope.mjs +4 -1
  62. package/runtime/test-contract.md +1 -0
  63. package/scripts/cm-acceptance-preview.mjs +26 -0
  64. package/scripts/cm-acceptance-preview.test.mjs +156 -0
  65. package/scripts/cm-ai-acceptance-contract.test.mjs +195 -0
  66. package/scripts/cm-ai-admission.mjs +8 -2
  67. package/scripts/cm-ai-admission.test.mjs +20 -4
  68. package/scripts/cm-ai-blockage.test.mjs +120 -0
  69. package/scripts/cm-ai-checklist-coverage.test.mjs +5 -2
  70. package/scripts/cm-ai-checkpoint-package-material.test.mjs +60 -6
  71. package/scripts/cm-ai-checkpoint-package-owner.test.mjs +1 -0
  72. package/scripts/cm-ai-completion-summary.test.mjs +154 -0
  73. package/scripts/cm-ai-conversation-entry-ops.test.mjs +8 -2
  74. package/scripts/cm-ai-develop-driver-gaps.test.mjs +1 -0
  75. package/scripts/cm-ai-drive.mjs +18 -11
  76. package/scripts/cm-ai-fix-later-delivery.test.mjs +2 -2
  77. package/scripts/cm-ai-later-delivery-feature.test.mjs +102 -0
  78. package/scripts/cm-ai-progress.test.mjs +7 -0
  79. package/scripts/cm-ai-project-qa-gate.test.mjs +55 -4
  80. package/scripts/cm-ai-review-input-limit.test.mjs +91 -0
  81. package/scripts/cm-ai-run.test.mjs +23 -1
  82. package/scripts/cm-ai-spec-rebind.test.mjs +51 -15
  83. package/scripts/cm-ai-user-maintained-paths.test.mjs +183 -0
  84. package/scripts/cm-ai-verification-auto.test.mjs +33 -8
  85. package/scripts/cm-ai-verification-gate.test.mjs +1 -1
  86. package/scripts/cm-autonomy-acceptance.test.mjs +212 -0
  87. package/scripts/cm-autonomy-review-r1.test.mjs +142 -0
  88. package/scripts/cm-autonomy.mjs +3 -1
  89. package/scripts/cm-autonomy.test.mjs +10 -9
  90. package/scripts/cm-check-runtime.sh +5 -2
  91. package/scripts/cm-delivery-evidence.mjs +59 -0
  92. package/scripts/cm-delivery-evidence.test.mjs +177 -0
  93. package/scripts/cm-drive-liveness.test.mjs +14 -0
  94. package/scripts/cm-driver-light-import.test.mjs +32 -0
  95. package/scripts/cm-fix-observation-task-id.test.mjs +49 -0
  96. package/scripts/cm-fix-review-storage.test.mjs +14 -4
  97. package/scripts/cm-journal-limit.test.mjs +69 -0
  98. package/scripts/cm-mandatory-check-coverage.test.mjs +82 -0
  99. package/scripts/cm-node-test-selection.test.mjs +108 -0
  100. package/scripts/cm-notify-read-drift.test.mjs +6 -3
  101. package/scripts/cm-prd-completion.test.mjs +49 -0
  102. package/scripts/cm-prd-drive.mjs +1 -1
  103. package/scripts/cm-prd-host.mjs +3 -1
  104. package/scripts/cm-prd-host.test.mjs +19 -2
  105. package/scripts/cm-prd-self-check-rules.test.mjs +23 -11
  106. package/scripts/cm-prd-self-check.test.mjs +24 -1
  107. package/scripts/cm-prd-summary.test.mjs +25 -4
  108. package/scripts/cm-review-inventory.test.mjs +25 -6
  109. package/scripts/cm-run-analysis.mjs +21 -0
  110. package/scripts/cm-run-analysis.test.mjs +120 -0
  111. package/scripts/cm-spec-amend.mjs +68 -0
  112. package/scripts/cm-spec-amend.test.mjs +510 -0
  113. package/scripts/cm-specs-status.test.mjs +6 -0
  114. package/scripts/cm-start-check.mjs +140 -53
  115. package/scripts/cm-start-check.test.mjs +139 -1
  116. package/scripts/cm-task-scope.test.mjs +3 -2
  117. package/scripts/cm-usage-report.py +8 -3
  118. package/scripts/cm019-r1-contract.test.mjs +137 -0
  119. package/scripts/cm019-review-gates.test.mjs +97 -0
  120. package/scripts/test-journal-limit-1mib.mjs +4 -0
  121. package/scripts/validate-public-repo.py +4 -0
  122. package/skills/cm-ai/references/N1-init.md +23 -1
  123. package/skills/cm-ai/references/js-host-qa-recovery.md +3 -2
  124. package/skills/cm-ai/references/js-host-recovery.md +2 -1
  125. package/skills/cm-ai/references/js-host.md +7 -2
  126. package/skills/cm-prd/references/js-change-recovery.md +2 -1
  127. package/skills/cm-prd/references/js-host.md +1 -0
@@ -0,0 +1,153 @@
1
+ // Read-only analysis of one stable authoritative specs log; never execution authority.
2
+ import path from 'node:path';
3
+ import {spawnSync} from 'node:child_process';
4
+ import {fileURLToPath} from 'node:url';
5
+ import {readStableLogRows} from './cm-ai/log-rows.mjs';
6
+
7
+ const MAX_BYTES=32*1024*1024,MAX_ROWS=100000;
8
+ const label=value=>typeof value==='string'&&value.length>0&&value.length<=128
9
+ &&!/[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/u.test(value);
10
+ const key=parts=>JSON.stringify(parts);
11
+ const fail=()=>{throw Object.assign(new Error('run_analysis_log_invalid'),{code:'run_analysis_log_invalid'});};
12
+ const timestamp=value=>typeof value==='string'&&/T.*(?:Z|[+-]\d\d:\d\d)$/.test(value)&&Number.isFinite(Date.parse(value))?Date.parse(value):null;
13
+ const usageScript=fileURLToPath(new URL('../../scripts/cm-usage-report.py',import.meta.url));
14
+ const usageBridge=`import json,runpy,sys
15
+ from pathlib import Path
16
+ from datetime import datetime,timezone
17
+ m=runpy.run_path(sys.argv[1],run_name='cm_usage_report')
18
+ data=json.load(sys.stdin)
19
+ refs=[m['RunRef'](r,'unknown','unknown','unknown',datetime.now(timezone.utc),'','snapshot.jsonl') for r in data]
20
+ report=m['build_report'](Path('.').resolve(),refs,data)
21
+ report['source']='specs-local-stable-snapshot'
22
+ report['summary']['invalid_claims']=sum(1 for rows in data.values() for _,row in rows if row.get('event')=='model_call' and m['claim_row_error'](row) is not None)
23
+ print(json.dumps(report,separators=(',',':')))
24
+ `;
25
+ function usageReport(rows){
26
+ const grouped=Object.create(null);
27
+ const fields=['run_id','event_id','event','phase','call_id','workflow','runtime','stage','role','adapter','requested_model',
28
+ 'effective_model','source','purpose','outcome','usage_state','input_tokens','output_tokens','cache_read_tokens','cache_write_tokens','reasoning_tokens','duration_ms'];
29
+ rows.forEach((row,index)=>{
30
+ if(!grouped[row.run_id])grouped[row.run_id]=[];
31
+ if(!['model_call','model_usage'].includes(row.event))return;
32
+ const minimal={};
33
+ for(const field of fields)if(Object.hasOwn(row,field)){
34
+ const value=row[field];
35
+ // Invalid identities must remain invalid, rather than becoming a valid alias.
36
+ minimal[field]=typeof value==='string'&&!label(value)||typeof value==='number'&&!Number.isSafeInteger(value)?null:value;
37
+ }
38
+ grouped[row.run_id].push([index+1,minimal]);
39
+ });
40
+ const result=spawnSync('python3',['-I','-c',usageBridge,usageScript],{input:JSON.stringify(grouped),encoding:'utf8',
41
+ timeout:20000,maxBuffer:MAX_BYTES,windowsHide:true});
42
+ if(result.error||result.status!==0)return {status:'unavailable',reason:'usage_reader_unavailable'};
43
+ try{
44
+ const report=JSON.parse(result.stdout),summary=report.summary;
45
+ const complete=summary.observed_calls>0&&!summary.unavailable_calls&&!summary.unresolved_claims&&!summary.invalid_calls&&!summary.invalid_claims;
46
+ return {status:complete?'observed':summary.observed_calls?'partial':'unavailable',...report};
47
+ }catch{return {status:'unavailable',reason:'usage_reader_unavailable'};}
48
+ }
49
+ function unionDuration(intervals){
50
+ let total=0,end=null;
51
+ for(const [start,stop] of intervals.sort((a,b)=>a[0]-b[0])){
52
+ total+=Math.max(0,stop-Math.max(start,end??start));end=Math.max(end??stop,stop);
53
+ }
54
+ return total;
55
+ }
56
+ function timingReport(rows){
57
+ const groups=new Map();let unrecognized=0;
58
+ rows.forEach((row,index)=>{
59
+ if(row.event!=='progress'||!['start','complete'].includes(row.phase))return;
60
+ const prd=row.workflow==='cm-prd'&&Number.isSafeInteger(row.segment)&&row.segment>=1;
61
+ // AI host operations have unique ids and no segment; never infer PRD segment 1.
62
+ const ai=row.workflow==='cm-ai'&&!Object.hasOwn(row,'segment')
63
+ &&['developing','checking','verifying','review_starting','reviewing'].includes(row.phase_name)
64
+ &&label(row.feature)&&label(row.task)&&Number.isSafeInteger(row.attempt)&&row.attempt>=1;
65
+ if(!label(row.operation_id)||!label(row.phase_name)||!prd&&!ai){unrecognized++;return;}
66
+ const protocol=ai?'cm-ai-host-operation':'cm-prd-segment';
67
+ const id=key([row.run_id,row.workflow,row.operation_id,row.phase_name,protocol,
68
+ ...(ai?[row.feature,row.task,row.attempt]:[row.segment])]);
69
+ if(!groups.has(id))groups.set(id,{runId:row.run_id,workflow:row.workflow,stage:row.phase_name,protocol,start:[],complete:[]});
70
+ groups.get(id)[row.phase].push({row,index});
71
+ });
72
+ const stages=new Map(),intervalsByRun=new Map();let incomplete=0,pauses=0,paired=0,combined=0;
73
+ for(const group of groups.values()){
74
+ const {start,complete}=group;
75
+ if(start.length!==1||complete.length!==1){incomplete++;continue;}
76
+ const first=start[0],last=complete[0],a=timestamp(first.row.at),b=timestamp(last.row.at);
77
+ const allowed=group.protocol==='cm-ai-host-operation'?['returned','failed','aborted']:['completed','awaiting_input','blocked'];
78
+ if(a===null||b===null||b<a||first.index>=last.index||!allowed.includes(last.row.outcome)){
79
+ incomplete++;continue;
80
+ }
81
+ paired++;if(last.row.outcome==='awaiting_input')pauses++;
82
+ const isCombined=first.row.timing_scope==='combined_host_call'||last.row.timing_scope==='combined_host_call';
83
+ if(isCombined)combined++;
84
+ const id=key([group.runId,group.workflow,group.stage]);
85
+ if(!stages.has(id))stages.set(id,{runId:group.runId,workflow:group.workflow,stage:group.stage,durationMs:0,pairedSegments:0,combinedSegments:0,outcomes:{}});
86
+ const stage=stages.get(id);stage.durationMs+=b-a;stage.pairedSegments++;stage.combinedSegments+=Number(isCombined);
87
+ stage.outcomes[last.row.outcome]=(stage.outcomes[last.row.outcome]??0)+1;
88
+ if(!intervalsByRun.has(group.runId))intervalsByRun.set(group.runId,[]);
89
+ intervalsByRun.get(group.runId).push([a,b]);
90
+ }
91
+ return {status:paired?(incomplete||unrecognized?'partial':'observed'):'unavailable',
92
+ pairedSegments:paired,incompleteSegments:incomplete,unrecognizedEvents:unrecognized,closedForInput:pauses,combinedSegments:combined,
93
+ activeIntervalUnionMs:paired?[...intervalsByRun.values()].reduce((n,v)=>n+unionDuration(v),0):null,
94
+ waitingMs:null,waitingStatus:'unavailable',stages:[...stages.values()],
95
+ scope:'Only matched progress segments; overlapping stages are not additive; gaps and unpaired time are unknown.'};
96
+ }
97
+ function repetitionReport(rows){
98
+ const groups=new Map();let unrecognized=0;
99
+ for(const row of rows){
100
+ // These are recorded starts/claims, not proof that a command ran or that work was redundant.
101
+ let kind,identity,execution;
102
+ if(row.event==='model_call'&&row.phase==='claimed'){
103
+ kind='model_call_claim';identity=[row.workflow,row.stage,row.role,row.adapter,row.requested_model,row.source,row.purpose];execution=row.call_id;
104
+ }else if(row.event==='test_run'&&row.phase==='start'){
105
+ kind='qa_invocation_start';identity=[row.workflow,row.feature,row.task];execution=row.operation_id;
106
+ }else continue;
107
+ if(!identity.every(label)||!label(execution)){unrecognized++;continue;}
108
+ const id=key([row.run_id,kind,...identity]);
109
+ if(!groups.has(id))groups.set(id,{runId:row.run_id,kind,identity,executions:new Set()});
110
+ groups.get(id).executions.add(execution);
111
+ }
112
+ const repeated=[...groups.values()].filter(x=>x.executions.size>1).map(({executions,...group})=>({...group,count:executions.size,additionalOccurrences:executions.size-1}));
113
+ return {status:groups.size?'observed':'unavailable',groups:repeated,unrecognizedEvents:unrecognized,
114
+ commandReexecution:'unavailable',interpretation:'Repeated recorded starts/claims only; necessity, command equality and waste are not inferred.'};
115
+ }
116
+ export function analyzeRunRows(input,{runId=null}={}){
117
+ if(!Array.isArray(input)||input.length>MAX_ROWS||runId!==null&&!label(runId))fail();
118
+ const seen=new Map(),rows=[];let historicalRows=0,duplicates=0;
119
+ for(const row of input){
120
+ if(!row||typeof row!=='object'||Array.isArray(row))fail();
121
+ if(!label(row.run_id)){historicalRows++;continue;}
122
+ if(row.event_id!==undefined){
123
+ if(!label(row.event_id))fail();
124
+ const id=row.event_id,encoded=JSON.stringify(row);
125
+ if(seen.has(id)){if(seen.get(id)!==encoded)fail();if(runId===null||row.run_id===runId)duplicates++;continue;}seen.set(id,encoded);
126
+ }
127
+ if(runId===null||row.run_id===runId)rows.push(row);
128
+ }
129
+ if(runId!==null&&!rows.length)throw Object.assign(new Error('run_analysis_run_not_found'),{code:'run_analysis_run_not_found'});
130
+ const usage=usageReport(rows),timing=timingReport(rows),repetitions=repetitionReport(rows);
131
+ return {schemaVersion:1,source:'specs-local-log',readOnly:true,runs:[...new Set(rows.map(x=>x.run_id))],
132
+ rows:rows.length,ignoredHistoricalRows:historicalRows,deduplicatedEvents:duplicates,
133
+ usage,timing,repetitions,
134
+ authority:'Diagnostic observations only; no acceptance, completion, deployment or permission decision.'};
135
+ }
136
+ export function inspectRunAnalysis({specs,runId=null}){
137
+ let count=0;
138
+ const rows=readStableLogRows(path.join(specs,'运行日志.jsonl'),()=>{if(++count>MAX_ROWS)fail();return true;},'run_analysis_log_unavailable',{maxBytes:MAX_BYTES});
139
+ return analyzeRunRows(rows,{runId});
140
+ }
141
+ export function runAnalysisLines(report){
142
+ const lines=[`CM 运行分析:${report.runs.length} 个运行,${report.rows} 条记录(只读)`];
143
+ const u=report.usage,s=u.summary;
144
+ lines.push(`Token:${u.status}${s?`;已观测调用 ${s.observed_calls},缺失 ${s.unavailable_calls},未闭合 ${s.unresolved_claims},无效 ${s.invalid_calls+s.invalid_claims}`:''}`);
145
+ if(s?.observed_calls)lines.push(`已观测 Token 小计:input ${s.input_tokens},output ${s.output_tokens};不是缺失调用的估算。`);
146
+ const t=report.timing;
147
+ lines.push(`阶段耗时:${t.status};完整配对 ${t.pairedSegments},未配对/无效 ${t.incompleteSegments+t.unrecognizedEvents}`);
148
+ if(t.activeIntervalUnionMs!==null)lines.push(`已观测活动区间并集:${t.activeIntervalUnionMs} ms;等待时长未知,重叠阶段不相加。`);
149
+ for(const stage of t.stages)lines.push(`${stage.runId} / ${stage.stage}:${stage.durationMs} ms${stage.combinedSegments?'(含共享调用区间)':''};结束事件 ${Object.entries(stage.outcomes).map(([outcome,count])=>`${outcome}=${count}`).join(', ')}`);
150
+ lines.push(`重复启动/调用声明组:${report.repetitions.groups.length};未判断必要性,测试命令重复执行次数未知。`);
151
+ for(const group of report.repetitions.groups)lines.push(`${group.runId} / ${group.kind} / ${group.identity.join(' / ')}:${group.count} 次`);
152
+ lines.push('分析不改变验收、检查、重试或完成门禁。');return lines;
153
+ }
@@ -6,6 +6,7 @@ import path from 'node:path';
6
6
  import {approvedTaskGrammar} from './spec-task-line.mjs';
7
7
  import {parseFeatureTaskText} from './cm-ai/cm-ai-admission.mjs';
8
8
  import {writeHandoff} from './session-handoff.mjs';
9
+ import {completionLines} from './cm-ai/completion-summary.mjs';
9
10
 
10
11
  const HEADER='=== 会话边界(默认结论:把下面几行原样放在给用户回复的最后。例外:用户还要在本会话讨论本次结果时,第一行改为「会话边界:继续本会话。」;'
11
12
  +'用户拒绝换会话或宿主开不了新会话时,第一行改为「会话边界:留在本会话(原因)。」;这两种都删掉「新会话里运行」那一行,并按实际情况改写原因。'
@@ -35,15 +36,26 @@ export function openTasks(specsDir,feature){
35
36
 
36
37
  export function cmAiSessionBoundary(result,{specsDir,feature,identity,write=writeHandoff}={}){
37
38
  if(result?.workflow!=='cm-ai'||result?.state!=='run_done')return null;
38
- const open=openTasks(specsDir,feature);
39
+ const completion=result.completion;
40
+ // A structured host snapshot must stay one snapshot through the driver and
41
+ // handoff; do not reread tasks and splice a later task list into it.
42
+ const open=completion?completion.feature?.tasks?.open??null:openTasks(specsDir,feature);
39
43
  // 不指定「下一个可执行任务」:依赖与选择由准入决定,这里只如实列出未完成项。
40
44
  const next=open===null?'无法确定(任务清单读不到或无法解析),在新会话里运行 $cm-ai 由准入给出下一项'
41
45
  :open.length?`$cm-ai(${feature} 仍有未完成任务:${open.join('、')})`
42
- :`无,${feature} 的任务已全部完成`;
46
+ :completion?.project?.pendingTasks>0?`$cm-ai(其他已批准功能仍有 ${completion.project.pendingTasks} 个未完成任务)`
47
+ :completion&&completion.project?.status!=='completed'?'恢复原运行核对 QA/收尾;项目完成尚未证实'
48
+ :`无,${feature} 的任务已全部完成`;
49
+ const todo=completion?.project?.features?completion.project.features.flatMap(item=>[
50
+ ...item.tasks.open.map(id=>`${item.name} ${id}`),
51
+ ...(item.qa.status==='passed'?[]:[`${item.name} QA ${item.qa.status}:核对对应原运行证据`])]):
52
+ open===null?['无法确定:tasks.md 读不到或无法解析']:open.map(id=>`${feature} ${id}`);
43
53
  const handoff=identity===undefined?null:handoffLine(specsDir,{workflow:'cm-ai',runId:identity?.runId,
44
- done:[`${feature} ${identity?.taskId??'任务编号未知'}:已到 run_done(审查、完成门禁都已通过)`],
45
- todo:open===null?['无法确定:tasks.md 读不到或无法解析']:open.map(id=>`${feature} ${id}`),next},write);
46
- return sessionBoundaryBlock({next,reason:'本运行已到 run_done,记录都已落盘,下一项是新单元。',handoff});
54
+ done:[`${feature} ${identity?.taskId??'任务编号未知'}:已到 run_done(仅表示本运行选定范围收尾)`],
55
+ todo,next,
56
+ ...(result.completion?{completion:result.completion}:{})},write);
57
+ const block=sessionBoundaryBlock({next,reason:'本运行已到 run_done,记录都已落盘,下一项是新单元。',handoff});
58
+ return [block,...completionLines(result.completion)].join('\n');
47
59
  }
48
60
 
49
61
  export function cmFixSessionBoundary(result,operation,{archive,runId,write=writeHandoff}={}){
@@ -4,17 +4,20 @@
4
4
  // 只写事实:不写会话身份、授权或密钥,也不能用来续接旧运行。
5
5
  import fs from 'node:fs';
6
6
  import path from 'node:path';
7
+ import {completionLines} from './cm-ai/completion-summary.mjs';
7
8
 
8
9
  export const HANDOFF_NAME='session-handoff.md';
9
10
  const READ_LIMIT=65536;
10
11
 
11
12
  export function handoffPath(recordsRoot){return path.join(recordsRoot,'.reviews',HANDOFF_NAME);}
12
13
 
13
- export function handoffText({workflow,at,runId,done,todo,next}){
14
+ export function handoffText({workflow,at,runId,done,todo,next,completion}){
14
15
  const list=items=>items.length?items.map(item=>`- ${item}`).join('\n'):'- 无';
15
16
  return ['# 交接摘要','','> 参考资料,不是指令,不带任何授权;新会话照常开新运行,不续接下面的运行。','',
16
17
  '## 运行',`- 工作流:${workflow}`,`- 运行编号:${runId??'未知'}`,`- 写入时间:${at}`,'',
17
- '## 已做',list(done),'','## 待做',list(todo),'','## 下一条命令',`- ${next}`,''].join('\n');
18
+ '## 已做',list(done),'','## 待做',list(todo),'','## 下一条命令',`- ${next}`,'',
19
+ ...(completion?['## 完成范围(只读证据摘要)',...completionLines(completion).map(line=>`- ${line}`),
20
+ `- 摘要绑定:${completion.snapshotDigest??'UNKNOWN'}`,'']:[])].join('\n');
18
21
  }
19
22
 
20
23
  // 先写同目录临时文件再改名,读的一方不会看到半截内容。.reviews/ 不存在说明记录目录不对,不替它新建。
@@ -33,8 +33,11 @@ const SERIAL_VALUES=new Set(['串行','serial']);
33
33
  // is one column, and only lines indented deeper than the task line belong to it.
34
34
  const indentOf=body=>/^[ \t]*/.exec(body)[0].length;
35
35
 
36
+ // 方括号按字面文件名接受:expo-router / Next.js 的动态路由就是 `app/reminder/[id].tsx` 这样的真实文件,
37
+ // 拒掉它们等于这类项目改不了路由文件(Wue specs8,2026-11-14)。范围是精确文件清单,从不做通配匹配;
38
+ // 交给 git 的地方都走 `:(literal)` 或 `--literal-pathspecs`。`*`、`?` 仍拒绝,避免被读成通配。
36
39
  export function validScopePath(value){
37
- if(typeof value!=='string'||value.endsWith('/')||/[*?[\]]/.test(value))return false;
40
+ if(typeof value!=='string'||value.endsWith('/')||/[*?]/.test(value))return false;
38
41
  try{readReviewScope([value]);}catch{return false;}
39
42
  return protectedScopePaths([value]).length===0;
40
43
  }
@@ -111,6 +111,7 @@ API、广告/支付测试环境和真机差异。`kind: "browser"` 在此表示
111
111
  生成后必须自检:
112
112
 
113
113
  - 每条 AC 至少映射一个用例;无法验证的 AC 仍生成 blocking 用例并写清阻塞前提。
114
+ - 例外:编号后紧跟 `NOT_APPLICABLE`(可隔冒号)并写明依据的 AC 表示本期不适用,不要求映射用例(自检规则 5 起);用例仍可引用它,必验合同也不从其依据推断执行义务。它与「适用但暂时无法验证」不同:后者照旧生成 blocking 用例。同编号还有普通声明时不豁免,围栏内示例不算声明。
114
115
  - 每个 `taskIds`、`acIds` 都能在同 feature 三件套中找到。
115
116
  - `expected` 依赖二开防护网基线的用例(如「用例数不少于基线」),`taskIds` 含首个改代码任务,文字锚点写「首个改代码任务的宿主重放基线」,不再指向单列的基线任务(见 `skills/cm-prd/references/brownfield.md` B3)。
116
117
  - 根字段、case 必需字段、类型、枚举和唯一 ID 全部符合结构合同。
@@ -0,0 +1,26 @@
1
+ #!/usr/bin/env node
2
+ // Saved specification preview only: no approval, session creation or execution.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import {fileURLToPath} from 'node:url';
6
+ import {inspectAcceptancePreview,acceptancePreviewLines} from '../runtime/js/cm-prd/acceptance-preview.mjs';
7
+ const usage='用法: cm-acceptance-preview.mjs --specs DIR [--feature NAME [--task T-ID]] [--task-grammar 1|2|3] [--json]\n只读;0 要求映射可预览,1 需澄清,2 输入/读取失败。不是批准或测试通过。\n';
8
+ export function main(argv=process.argv.slice(2),{stdout=process.stdout,stderr=process.stderr}={}){
9
+ if(argv.length===1&&['--help','-h'].includes(argv[0])){stdout.write(usage);return 0;}
10
+ try{
11
+ const options={},allowed=new Set(['--specs','--feature','--task','--task-grammar','--json']);
12
+ for(let i=0;i<argv.length;i++){
13
+ const key=argv[i];if(!allowed.has(key)||Object.hasOwn(options,key))throw new Error('acceptance_preview_arguments_invalid');
14
+ if(key==='--json')options[key]=true;
15
+ else{const value=argv[++i];if(!value||value.startsWith('--'))throw new Error('acceptance_preview_arguments_invalid');options[key]=value;}
16
+ }
17
+ if(!options['--specs']||options['--task']&&!options['--feature'])throw new Error('acceptance_preview_arguments_invalid');
18
+ const preview=inspectAcceptancePreview({specs:fs.realpathSync(path.resolve(options['--specs'])),
19
+ feature:options['--feature']??null,taskId:options['--task']??null,
20
+ ...(options['--task-grammar']?{taskGrammar:Number(options['--task-grammar'])}:{})});
21
+ stdout.write(options['--json']?JSON.stringify(preview)+'\n':acceptancePreviewLines(preview).join('\n')+'\n');
22
+ return preview.status==='ready'?0:1;
23
+ }catch(error){const reason=error.code??error.message;
24
+ stderr.write(`验收预览不可用:${/^[a-zA-Z][a-zA-Z0-9_]{0,95}$/.test(reason)?reason:'acceptance_preview_read_failed'}\n`);return 2;}
25
+ }
26
+ if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url))process.exitCode=main();
@@ -0,0 +1,156 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import {spawnSync} from 'node:child_process';
7
+ import {fileURLToPath} from 'node:url';
8
+ import {inspectAcceptancePreview,buildAcceptancePreview,currentAcceptancePreview,summaryAcceptancePreview}
9
+ from '../runtime/js/cm-prd/acceptance-preview.mjs';
10
+ import {captureSpecificationMaterial} from '../runtime/js/cm-ai/specification-material.mjs';
11
+ import {approveCmAiSpecs} from '../runtime/js/cm-ai/cm-ai-admission.mjs';
12
+ import {buildManifest} from './cm-spec-manifest.mjs';
13
+ import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
14
+ const cli=fileURLToPath(new URL('./cm-acceptance-preview.mjs',import.meta.url));
15
+ function fixture(t){
16
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-acceptance-preview-')));
17
+ t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
18
+ const feature='1.work';fs.mkdirSync(path.join(root,feature));
19
+ const documents=[
20
+ {path:'requirements.md',content:'# Requirements\n- [ ] [AC-001] Read a\n - 必跑测试: `a.test.mjs`\n- [ ] [AC-002] Read b\n'},
21
+ {path:'design.md',content:'# Design\nRead values\n'},
22
+ {path:'tasks.md',content:'- [ ] T-001: Read a [AC-001]\n - 执行 `node --test a.test.mjs`\n- [ ] T-002: 必验: Read b [AC-002]\n'},
23
+ {path:'test-cases.json',content:JSON.stringify({cases:[{id:'TC-001',title:'Read a',kind:'logic',blocking:true,taskIds:['T-001'],
24
+ acIds:['AC-001'],steps:['Read a'],expected:['a is returned']}]})},
25
+ ];
26
+ for(const doc of documents)fs.writeFileSync(path.join(root,feature,doc.path),doc.content);
27
+ const approve=(grammar=3)=>fs.writeFileSync(path.join(root,'.cm-specs-status'),JSON.stringify({status:'approved',features:[feature],
28
+ specFiles:buildManifest(root),...(grammar===1?{}:{taskGrammar:grammar})}));
29
+ return {root,feature,documents,approve,file:name=>path.join(root,feature,name)};
30
+ }
31
+ function snapshot(root){
32
+ const files={};const walk=directory=>{for(const entry of fs.readdirSync(directory,{withFileTypes:true})){
33
+ const file=path.join(directory,entry.name),stat=fs.lstatSync(file);
34
+ if(entry.isDirectory())walk(file);else files[path.relative(root,file)]={bytes:fs.readFileSync(file).toString('base64'),mtime:stat.mtimeMs,mode:stat.mode};
35
+ }};walk(root);return files;
36
+ }
37
+ test('draft preview and approved capture freeze the same contracts and exact task selection',t=>{
38
+ const f=fixture(t),before=snapshot(f.root),preview=inspectAcceptancePreview({specs:f.root});
39
+ assert.equal(preview.status,'ready');assert.equal(preview.sourceStatus,'draft');
40
+ assert.deepEqual(snapshot(f.root),before);assert.equal(preview.approvalAuthorized,false);assert.equal(preview.executionAuthorized,false);
41
+ f.approve();
42
+ for(const task of preview.features[0].tasks){
43
+ const actual=captureSpecificationMaterial({specsRoot:f.root,feature:f.feature,taskId:task.taskId});
44
+ assert.deepEqual(task.contract,actual.acceptanceContract);assert.equal(task.contractDigest,digest(actual.acceptanceContract));
45
+ }
46
+ const [a,b]=preview.features[0].tasks;
47
+ assert.deepEqual(a.contract.requiredTests,['a.test.mjs']);assert.deepEqual(b.contract.requiredTests,[]);
48
+ assert.deepEqual(a.testCases,['TC-001']);assert.deepEqual(b.testCases,[]);
49
+ assert.deepEqual(a.acceptanceCriteria,['AC-001']);assert.deepEqual(b.acceptanceCriteria,['AC-002']);
50
+ assert(a.humanReviewIds.length>0);
51
+ assert(a.contract.obligations.some(item=>a.locations[item.id].some(at=>at.pointer==='/cases/0/expected/0')));
52
+ });
53
+ test('ambiguous requirements preserve raw source locations and do not rewrite approval or specs',t=>{
54
+ const f=fixture(t);fs.appendFileSync(f.file('tasks.md'),'\n - 真机先红后绿\n');
55
+ const before=snapshot(f.root),preview=inspectAcceptancePreview({specs:f.root});
56
+ assert.equal(preview.status,'needs_clarification');
57
+ const task=preview.features[0].tasks.find(task=>task.taskId==='T-002');
58
+ assert(task.issues.some(issue=>issue.message.includes('compound evidence')&&issue.locations.some(at=>at.path==='1.work/tasks.md'&&at.line===5)));
59
+ assert.deepEqual(snapshot(f.root),before);
60
+ });
61
+ test('real CLI is read-only, supports scoped JSON and returns separate ambiguity/input exits',t=>{
62
+ const f=fixture(t),before=snapshot(f.root);
63
+ const run=args=>spawnSync(process.execPath,[cli,'--specs',f.root,...args],{encoding:'utf8',timeout:10000});
64
+ const full=run([]);assert.equal(full.status,0,full.stderr);assert.match(full.stdout,/未执行测试/);assert.match(full.stdout,/requirements.md:3/);
65
+ const selected=run(['--feature',f.feature,'--task','T-001','--json']);assert.equal(selected.status,0,selected.stderr);
66
+ assert.deepEqual(JSON.parse(selected.stdout).scope,{features:[f.feature],taskId:'T-001'});
67
+ assert.equal(JSON.parse(selected.stdout).features[0].tasks.length,1);
68
+ assert.equal(run(['--task','T-001']).status,2);assert.equal(run(['--feature','../escape']).status,2);
69
+ assert.deepEqual(snapshot(f.root),before);
70
+ fs.appendFileSync(f.file('tasks.md'),'\n - 真机先红\n');assert.equal(run([]).status,1);
71
+ });
72
+ test('old recorded grammar is retained and future defaults cannot reinterpret its declarations',t=>{
73
+ const f=fixture(t);fs.appendFileSync(f.file('tasks.md'),'\n- [ ] T-003: legacy prose\n');f.approve(1);
74
+ const preview=inspectAcceptancePreview({specs:f.root});assert.equal(preview.taskGrammar,1);
75
+ assert.deepEqual(preview.features[0].tasks.map(task=>task.taskId),['T-001','T-002']);
76
+ for(const task of preview.features[0].tasks)assert.deepEqual(task.contract,
77
+ captureSpecificationMaterial({specsRoot:f.root,feature:f.feature,taskId:task.taskId}).acceptanceContract);
78
+ });
79
+ test('grammar 2, shared verification sections and task-bound cases match formal capture',t=>{
80
+ const f=fixture(t);
81
+ fs.appendFileSync(f.file('tasks.md'),'\n## 验证要求\nT-001 基线必须通过\nT-002 基线检查\n');
82
+ const cases=JSON.parse(fs.readFileSync(f.file('test-cases.json')));
83
+ cases.cases.push({...cases.cases[0],id:'TC-002',title:'Only b',taskIds:['T-002'],acIds:['AC-002']});
84
+ fs.writeFileSync(f.file('test-cases.json'),JSON.stringify(cases));f.approve(2);
85
+ const preview=inspectAcceptancePreview({specs:f.root});assert.equal(preview.taskGrammar,2);
86
+ for(const task of preview.features[0].tasks)assert.deepEqual(task.contract,
87
+ captureSpecificationMaterial({specsRoot:f.root,feature:f.feature,taskId:task.taskId}).acceptanceContract);
88
+ assert.deepEqual(preview.features[0].tasks[0].testCases,['TC-001']);
89
+ });
90
+ test('approval drift rejects CLI; saved preview becomes stale without changing historical evidence',t=>{
91
+ const f=fixture(t);f.approve();const preview=inspectAcceptancePreview({specs:f.root}),saved=JSON.stringify(preview);
92
+ assert.equal(currentAcceptancePreview({specs:f.root,preview}).status,'ready');
93
+ fs.appendFileSync(f.file('requirements.md'),'New requirement\n');
94
+ assert.equal(currentAcceptancePreview({specs:f.root,preview}).status,'stale');assert.equal(JSON.stringify(preview),saved);
95
+ const result=spawnSync(process.execPath,[cli,'--specs',f.root,'--json'],{encoding:'utf8',timeout:10000});
96
+ assert.equal(result.status,2);assert.match(result.stderr,/acceptance_preview_approved_sources_changed/);
97
+ });
98
+ test('whole feature inventory is bound separately from the displayed current feature scope',t=>{
99
+ const f=fixture(t),preview=inspectAcceptancePreview({specs:f.root});
100
+ fs.mkdirSync(path.join(f.root,'2.other'));
101
+ for(const doc of f.documents)fs.writeFileSync(path.join(f.root,'2.other',doc.path),doc.content);
102
+ assert.equal(currentAcceptancePreview({specs:f.root,preview}).status,'stale');
103
+ const next=inspectAcceptancePreview({specs:f.root,feature:f.feature});
104
+ assert.deepEqual(next.scope.features,['1.work']);assert.deepEqual(next.featureInventory,['1.work','2.other']);
105
+ assert.equal(currentAcceptancePreview({specs:f.root,preview:next}).status,'ready');
106
+ fs.renameSync(path.join(f.root,'2.other'),path.join(f.root,'old-other'));
107
+ assert.equal(currentAcceptancePreview({specs:f.root,preview:next}).status,'stale');
108
+ });
109
+ test('legacy awaiting-review migration conflict matches approval without changing its grammar or state',t=>{
110
+ const f=fixture(t);fs.appendFileSync(f.file('tasks.md'),'\n- [ ] T-003: new [NEW]\n');
111
+ const status={status:'awaiting_review',features:[f.feature],specFiles:buildManifest(f.root)};
112
+ fs.writeFileSync(path.join(f.root,'.cm-specs-status'),JSON.stringify(status));
113
+ const before=snapshot(f.root),preview=inspectAcceptancePreview({specs:f.root});
114
+ assert.equal(preview.taskGrammar,1);assert.equal(preview.status,'needs_clarification');
115
+ assert.deepEqual(preview.features[0].tasks.map(task=>task.taskId),['T-001','T-002']);
116
+ const issue=preview.features[0].issues.find(issue=>issue.message==='task_grammar_conflict');
117
+ assert.deepEqual(issue.locations,[{path:'1.work/tasks.md',line:5}]);
118
+ assert.deepEqual(snapshot(f.root),before);
119
+ const result=approveCmAiSpecs({specsDir:f.root,codeProjects:[f.root],approvalResponse:'开始'});
120
+ assert.equal(result.approveRefused,'task_grammar_conflict',JSON.stringify(result));assert.deepEqual(snapshot(f.root),before);
121
+ f.approve(1);const approved=inspectAcceptancePreview({specs:f.root});
122
+ assert.equal(approved.status,'ready','already approved legacy capture keeps its original grammar');
123
+ assert.equal(approved.approvalTransition,false);
124
+ });
125
+ test('source replacement during a preview read never returns a ready mixed snapshot',t=>{
126
+ const f=fixture(t),original=fs.readSync;let reads=0;
127
+ fs.readSync=function(...args){
128
+ const count=original.apply(this,args);
129
+ if(++reads===4)fs.appendFileSync(f.file('requirements.md'),'Changed during read\n');
130
+ return count;
131
+ };
132
+ try{assert.throws(()=>inspectAcceptancePreview({specs:f.root}),/acceptance_preview_sources_changed/);}
133
+ finally{fs.readSync=original;}
134
+ assert(reads>=4);
135
+ });
136
+ test('missing mappings and malformed task declarations are visible diagnostics',t=>{
137
+ const f=fixture(t);fs.writeFileSync(f.file('tasks.md'),'- [ ] T-003: 必验: Unmapped task\n');
138
+ let preview=inspectAcceptancePreview({specs:f.root});assert.equal(preview.status,'needs_clarification');
139
+ assert(preview.features[0].tasks[0].issues.some(issue=>issue.message.includes('no explicit task/case mapping')));
140
+ fs.appendFileSync(f.file('tasks.md'),'- [ ] T-003: Duplicate\n');preview=inspectAcceptancePreview({specs:f.root});
141
+ assert.equal(preview.status,'needs_clarification');assert.equal(preview.features[0].issues[0].locations[0].line,2);
142
+ });
143
+ test('linked source and invalid status refuse; preview never follows a source alias',t=>{
144
+ const f=fixture(t),outside=path.join(f.root,'outside');fs.writeFileSync(outside,'external');
145
+ fs.unlinkSync(f.file('design.md'));fs.symlinkSync(outside,f.file('design.md'));
146
+ assert.throws(()=>inspectAcceptancePreview({specs:f.root}));
147
+ fs.unlinkSync(f.file('design.md'));fs.writeFileSync(f.file('design.md'),'Design');
148
+ fs.writeFileSync(path.join(f.root,'.cm-specs-status'),'{}');assert.throws(()=>inspectAcceptancePreview({specs:f.root}),/acceptance_preview_status_invalid/);
149
+ });
150
+ test('summary previews are bounded and old summaries without a preview remain readable',t=>{
151
+ const f=fixture(t),features=[{directory:f.feature,documents:f.documents}];
152
+ assert.equal(buildAcceptancePreview({features}).status,'ready');
153
+ assert.equal(summaryAcceptancePreview({documents:features,statusBytes:null,taskGrammar:3}).status,'ready');
154
+ assert.equal(summaryAcceptancePreview({documents:features,statusBytes:Buffer.from('{}'),taskGrammar:3}).status,'unavailable');
155
+ assert.equal(currentAcceptancePreview({specs:f.root,preview:undefined}),null);
156
+ });