@aibyzero/cm-workflow 0.20.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 (72) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +30 -0
  3. package/README.md +8 -1
  4. package/VERSION +1 -1
  5. package/docs/installation.md +1 -1
  6. package/docs/js-workflow-control.md +1 -1
  7. package/docs/proposals/spec-amendment-tiers.md +100 -0
  8. package/package.json +1 -1
  9. package/runtime/js/acceptance-language.mjs +32 -0
  10. package/runtime/js/autonomy.mjs +15 -6
  11. package/runtime/js/cm-ai/acceptance-contract.mjs +8 -3
  12. package/runtime/js/cm-ai/checkpoint-package-material.mjs +13 -3
  13. package/runtime/js/cm-ai/cm-ai-admission.mjs +35 -2
  14. package/runtime/js/cm-ai/codex-review-adapter.mjs +19 -3
  15. package/runtime/js/cm-ai/drive-core.mjs +9 -2
  16. package/runtime/js/cm-ai/durable-runner-state.mjs +8 -4
  17. package/runtime/js/cm-ai/effect-contract.mjs +8 -1
  18. package/runtime/js/cm-ai/execution-snapshot.mjs +4 -3
  19. package/runtime/js/cm-ai/execution-store-limits.mjs +3 -3
  20. package/runtime/js/cm-ai/execution-store.mjs +7 -4
  21. package/runtime/js/cm-ai/fix-code-association.mjs +27 -6
  22. package/runtime/js/cm-ai/review-package.mjs +20 -6
  23. package/runtime/js/cm-ai/review-presentation.mjs +12 -5
  24. package/runtime/js/cm-ai/reviewed-deliveries.mjs +10 -7
  25. package/runtime/js/cm-ai/reviewed-integration.mjs +1 -1
  26. package/runtime/js/cm-ai/spec-amendment.mjs +535 -0
  27. package/runtime/js/cm-ai/task-commit.mjs +4 -2
  28. package/runtime/js/cm-ai/task-runner.mjs +26 -9
  29. package/runtime/js/cm-ai/user-maintained-paths.mjs +68 -0
  30. package/runtime/js/cm-prd/change.mjs +35 -4
  31. package/runtime/js/cm-prd/self-check.mjs +36 -6
  32. package/runtime/js/cm-prd/session.mjs +8 -3
  33. package/runtime/js/cm-prd/task-scope-record.mjs +13 -7
  34. package/runtime/js/task-scope.mjs +4 -1
  35. package/runtime/test-contract.md +1 -0
  36. package/scripts/cm-ai-acceptance-contract.test.mjs +10 -0
  37. package/scripts/cm-ai-admission.mjs +8 -2
  38. package/scripts/cm-ai-admission.test.mjs +15 -2
  39. package/scripts/cm-ai-checkpoint-package-material.test.mjs +60 -6
  40. package/scripts/cm-ai-checkpoint-package-owner.test.mjs +1 -0
  41. package/scripts/cm-ai-develop-driver-gaps.test.mjs +1 -0
  42. package/scripts/cm-ai-drive.mjs +18 -11
  43. package/scripts/cm-ai-fix-later-delivery.test.mjs +2 -2
  44. package/scripts/cm-ai-later-delivery-feature.test.mjs +102 -0
  45. package/scripts/cm-ai-review-input-limit.test.mjs +91 -0
  46. package/scripts/cm-ai-user-maintained-paths.test.mjs +183 -0
  47. package/scripts/cm-autonomy-review-r1.test.mjs +49 -0
  48. package/scripts/cm-check-runtime.sh +4 -1
  49. package/scripts/cm-drive-liveness.test.mjs +8 -0
  50. package/scripts/cm-fix-observation-task-id.test.mjs +49 -0
  51. package/scripts/cm-fix-review-storage.test.mjs +14 -4
  52. package/scripts/cm-journal-limit.test.mjs +69 -0
  53. package/scripts/cm-prd-completion.test.mjs +37 -0
  54. package/scripts/cm-prd-drive.mjs +1 -1
  55. package/scripts/cm-prd-host.test.mjs +1 -1
  56. package/scripts/cm-prd-self-check-rules.test.mjs +23 -11
  57. package/scripts/cm-prd-self-check.test.mjs +24 -1
  58. package/scripts/cm-prd-summary.test.mjs +6 -0
  59. package/scripts/cm-review-inventory.test.mjs +5 -1
  60. package/scripts/cm-spec-amend.mjs +68 -0
  61. package/scripts/cm-spec-amend.test.mjs +510 -0
  62. package/scripts/cm-specs-status.test.mjs +6 -0
  63. package/scripts/cm-start-check.mjs +82 -2
  64. package/scripts/cm-start-check.test.mjs +64 -1
  65. package/scripts/cm-task-scope.test.mjs +3 -2
  66. package/scripts/test-journal-limit-1mib.mjs +4 -0
  67. package/scripts/validate-public-repo.py +4 -0
  68. package/skills/cm-ai/references/N1-init.md +23 -1
  69. package/skills/cm-ai/references/js-host-qa-recovery.md +3 -2
  70. package/skills/cm-ai/references/js-host-recovery.md +2 -1
  71. package/skills/cm-ai/references/js-host.md +2 -1
  72. package/skills/cm-prd/references/js-change-recovery.md +1 -0
@@ -0,0 +1,68 @@
1
+ // A code project may declare files its user maintains by hand, outside any task
2
+ // (AI潮: Baseline/glass-verdicts.json, edited only by the user). Only the plain
3
+ // completed-run delivery chain tolerates their differences, like the root CM
4
+ // config; QA-fix chains and integration acceptance stay strict. Exact relative
5
+ // files only, under the review inventory's own path contract: no directories,
6
+ // globs, agent instructions, CM config or this declaration itself, compared
7
+ // case-insensitively. A malformed declaration tolerates nothing and fails closed.
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
10
+ import {createHash} from 'node:crypto';
11
+ import {parseModelJson} from './model-configuration-file.mjs';
12
+ import {CONFIG_FILENAMES} from '../../../scripts/cm-workflow-config.mjs';
13
+
14
+ export const USER_MAINTAINED_FILE='.cm-user-maintained.json';
15
+ const MAX_BYTES=16*1024,MAX_PATHS=64,MAX_PATH=512;
16
+ const INSTRUCTIONS=new Set(['agents.md','claude.md']);
17
+ const RESERVED=new Set([...CONFIG_FILENAMES,USER_MAINTAINED_FILE].map(name=>name.toLowerCase()));
18
+ const SECRET_SEGMENTS=new Set(['.git','.ssh','.aws','.gnupg']);
19
+
20
+ export function userMaintainedInvalid(detail){
21
+ return Object.assign(new Error(`user_maintained_invalid: ${detail}`),{code:'user_maintained_invalid',detail});
22
+ }
23
+ // review-package.mjs filePath, plus the declaration's own refusals.
24
+ function readPath(root,value){
25
+ if(typeof value!=='string'||value.length===0||value.length>MAX_PATH||/[\\:*?[\]{}\x00-\x1f\x7f-\x9f]/.test(value)
26
+ ||value.startsWith('/')||value.normalize('NFC')!==value)
27
+ throw userMaintainedInvalid('路径必须是代码根下的相对文件路径(NFC,无控制字符、反斜杠、冒号或通配符)');
28
+ const parts=value.split('/');
29
+ if(parts.some(part=>part===''||part==='.'||part==='..'))throw userMaintainedInvalid(`路径不规范:${value}`);
30
+ if(parts.some(part=>SECRET_SEGMENTS.has(part.toLowerCase())||/^\.env(?:\.|$)/i.test(part))
31
+ ||INSTRUCTIONS.has(parts.at(-1).toLowerCase())||RESERVED.has(value.toLowerCase()))
32
+ throw userMaintainedInvalid(`不能声明:${value}`);
33
+ let stat=null;
34
+ try{stat=fs.lstatSync(path.join(root,value));}catch(error){if(error.code!=='ENOENT')throw userMaintainedInvalid(`无法检查:${value}`);}
35
+ if(stat&&!stat.isFile())throw userMaintainedInvalid(`只能声明普通文件:${value}`);
36
+ return value;
37
+ }
38
+
39
+ // {paths, sha256}: the declared paths and the exact declaration bytes' digest
40
+ // (null when the code root has no declaration). The caller binds sha256 to the
41
+ // inventory it compares, so a declaration replaced mid-check is refused.
42
+ export function readUserMaintainedPaths(root){
43
+ const file=path.join(root,USER_MAINTAINED_FILE);
44
+ let before;
45
+ try{before=fs.lstatSync(file);}
46
+ catch(error){if(error.code==='ENOENT')return {paths:[],sha256:null};throw userMaintainedInvalid('无法读取');}
47
+ if(!before.isFile()||before.nlink!==1||before.size>MAX_BYTES)throw userMaintainedInvalid('必须是普通单链接文件且不超过 16 KiB');
48
+ let bytes;
49
+ try{
50
+ const descriptor=fs.openSync(file,fs.constants.O_RDONLY|fs.constants.O_NOFOLLOW);
51
+ try{
52
+ bytes=fs.readFileSync(descriptor);const after=fs.fstatSync(descriptor);
53
+ if(!['dev','ino','size','mtimeMs','ctimeMs'].every(key=>after[key]===before[key])||bytes.length!==before.size)
54
+ throw userMaintainedInvalid('读取期间被修改');
55
+ }finally{fs.closeSync(descriptor);}
56
+ }catch(error){throw error.code==='user_maintained_invalid'?error:userMaintainedInvalid('无法读取');}
57
+ let value;
58
+ try{value=parseModelJson(new TextDecoder('utf-8',{fatal:true}).decode(bytes));}
59
+ catch{throw userMaintainedInvalid('不是严格的 UTF-8 JSON(含重复键)');}
60
+ if(value===null||typeof value!=='object'||Array.isArray(value)
61
+ ||Object.keys(value).sort().join(',')!=='paths,version'||value.version!==1)
62
+ throw userMaintainedInvalid('格式必须是 {"version":1,"paths":[...]}');
63
+ if(!Array.isArray(value.paths)||value.paths.length===0||value.paths.length>MAX_PATHS)
64
+ throw userMaintainedInvalid(`paths 必须有 1 到 ${MAX_PATHS} 项`);
65
+ const paths=value.paths.map(item=>readPath(root,item));
66
+ if(new Set(paths.map(item=>item.toLowerCase())).size!==paths.length)throw userMaintainedInvalid('paths 有重复项(不区分大小写)');
67
+ return {paths,sha256:createHash('sha256').update(bytes).digest('hex')};
68
+ }
@@ -15,6 +15,7 @@ import {prdTreeFileDigest} from './tree-digest.mjs';
15
15
  import {writeImmutableWorkflowFile} from '../cm-ai/review-evidence-file.mjs';
16
16
  import {need,json,shape,digest} from '../cm-ai/effect-contract.mjs';
17
17
  import {inspectPrdDraft} from './draft.mjs';
18
+ import {prdDraftJson,PRD_DRAFT_LIMIT} from './validation-reason.mjs';
18
19
  import {checkPrdDraftMechanics,inspectPrdContextCheck,PRD_SELF_CHECK_RULES} from './self-check.mjs';
19
20
  import {recordPrdTaskScopes,approvedScopeExemptions,prdTaskScopeRecords} from './task-scope-record.mjs';
20
21
  import {replaceSessionFile} from './session.mjs';
@@ -88,7 +89,37 @@ function approvedGrammar(before){
88
89
  function sourceLines(source){return specLines(source).map(line=>line.body);}
89
90
  function userCases(files){return Object.entries(files).filter(([file])=>file.endsWith('/test-cases.json'))
90
91
  .flatMap(([file,content])=>JSON.parse(content).cases.filter(c=>c.origin==='user').map(c=>({feature:file.split('/')[0],value:c})));}
91
- export function inspectPrdChangeProposal(before,raw,selected,config,{rules=PRD_SELF_CHECK_RULES}={}){
92
+ // change_tasks 回包可以省略未改动的文档:已有 feature 省略的 requirements.md/design.md 等于需求、设计阶段已接受的原字节,
93
+ // 省略的 tasks.md 等于原稿,testCasesReason 为 null 时省略的 test-cases.json 也等于原稿;这里按原稿顺序补回,
94
+ // 64 KiB 上限只算实际回的文档(同 draft.mjs 的 withAcceptedPrdDocuments)。否则四件套超过 64 KiB 的 feature
95
+ // 连只改用例格式的变更都提交不进来(wue 8.todo-inbox 约 94 KB,2026-11-14)。省略过去本就是无效回包
96
+ // (prd_draft_triad_missing / prd_draft_cases_reason_missing),所以这层含义不改变任何原本合法的回包;
97
+ // 要删除用例合同仍须写非 null 的 testCasesReason,不会被补回。新 feature 不补,照旧要求完整。
98
+ export function withUnchangedPrdChangeDocuments(raw,before,parts=null){
99
+ if(raw?.status!=='draft'||!Array.isArray(raw.features))return {reply:raw,limit:PRD_DRAFT_LIMIT};
100
+ let restored=0;
101
+ const features=raw.features.map(feature=>{
102
+ if(!feature||typeof feature!=='object'||!before.directories.includes(feature.directory)||!Array.isArray(feature.documents)
103
+ ||new Set(feature.documents.map(doc=>doc?.path)).size!==feature.documents.length)return feature;
104
+ const accepted=parts?.features?.find(item=>item.directory===feature.directory)?.documents??[];
105
+ const original=file=>accepted.find(doc=>doc.path===file)?.content??before.files[`${feature.directory}/${file}`];
106
+ const documents=[];
107
+ for(const file of ['requirements.md','design.md','tasks.md','test-cases.json']){
108
+ const given=feature.documents.find(doc=>doc?.path===file);
109
+ if(given){documents.push(given);continue;}
110
+ if(file==='test-cases.json'&&feature.testCasesReason!==null)continue;
111
+ const content=original(file);
112
+ if(typeof content!=='string')continue;
113
+ documents.push({path:file,content});restored+=Buffer.byteLength(JSON.stringify({path:file,content}));
114
+ }
115
+ documents.push(...feature.documents.filter(doc=>!documents.includes(doc)));
116
+ return {...feature,documents};
117
+ });
118
+ return {reply:{...raw,features},limit:PRD_DRAFT_LIMIT+restored};
119
+ }
120
+ export function inspectPrdChangeProposal(before,sent,selected,config,{rules=PRD_SELF_CHECK_RULES,parts=null}={}){
121
+ prdDraftJson(sent);
122
+ const {reply:raw,limit}=withUnchangedPrdChangeDocuments(sent,before,parts);
92
123
  const grammar=approvedGrammar(before);
93
124
  shape(raw,['status','summary','features','removed']);need(raw.status==='draft'&&text(raw.summary)&&Array.isArray(raw.features)
94
125
  &&Array.isArray(raw.removed)&&new Set(raw.removed).size===raw.removed.length,'prd_change_proposal_invalid');
@@ -102,7 +133,7 @@ export function inspectPrdChangeProposal(before,raw,selected,config,{rules=PRD_S
102
133
  const inspected=inspectPrdDraft({status:'draft',summary:raw.summary,features:[{name:feature.directory.replace(/^\d+\./,''),
103
134
  documents:feature.documents,testCasesReason:feature.testCasesReason}]},
104
135
  {nextIndex:Number(feature.directory.split('.')[0]),generateCases:feature.documents.some(doc=>doc.path==='test-cases.json')||config.policies.generate_cases,
105
- userCasesProvided:false}).features[0];
136
+ userCasesProvided:false,limit}).features[0];
106
137
  if(!config.policies.generate_cases){
107
138
  const contract=inspected.documents.find(doc=>doc.path==='test-cases.json');
108
139
  const prior=JSON.parse(before.files[`${feature.directory}/test-cases.json`]??'{"cases":[]}').cases;
@@ -210,13 +241,13 @@ export function createPrdChange({admission,runtime,call,restored=null,selected=[
210
241
  messages:state.messages,parts:state.parts,previousProposal:state.proposal,contextCheck:state.contextCheck,text:answer,
211
242
  generateCases:config.policies.generate_cases,userCases:state.userCases,
212
243
  instructions:phase==='change_tasks'?
213
- 'C7/C7.5: return {status:draft,summary,features:[{directory,documents:[{path,content}],testCasesReason}],removed:[directory]}. Include complete triads/optional test contracts for the exact selected plus explicitly proposed new features. Preserve previous requirements/design bytes and inventory from parts. Retain completed task lines EXACTLY; preserve task IDs, mark changed pending CHANGED, obsolete DROPPED, added NEW. Append version rows to changed documents. Preserve unaffected/user cases; changes to user cases require separate explicit human consent. No writes, review/provider calls or approval.':
244
+ 'C7/C7.5: return {status:draft,summary,features:[{directory,documents:[{path,content}],testCasesReason}],removed:[directory]}. Include complete triads/optional test contracts for the exact selected plus explicitly proposed new features; for an existing feature you may omit any document left byte-identical (requirements/design as accepted in parts, tasks.md and, with testCasesReason null, test-cases.json as before) and it is restored, so the 64 KiB limit counts only documents you send. Preserve previous requirements/design bytes and inventory from parts. Retain completed task lines EXACTLY; preserve task IDs, mark changed pending CHANGED, obsolete DROPPED, added NEW. Append version rows to changed documents. Preserve unaffected/user cases; changes to user cases require separate explicit human consent. No writes, review/provider calls or approval.':
214
245
  `Apply ${phase==='change_requirements'?'C5 requirements changes':'C6 design changes'}. Return {status:documents,summary,features:[{directory,documents:[{path,content}]}],removed:[directory]}, or question/blocked. ${phase==='change_requirements'?'Only requirements.md; include retained selected features and proposed additions/removals.':'Keep exact requirements and feature/removal inventory from parts, add design.md; preserve unaffected modules.'} Preserve version rows and append new version for changed documents. Do not change completed history, call reviewers/providers, write files or infer consent.`},signal,'planner');
215
246
  current();
216
247
  if(response.status==='question'){need(text(response.question),'prd_change_reply_invalid');state.messages.push({role:'user',text:answer},{role:'assistant',result:response});state.question=response.question;return this.status();}
217
248
  if(response.status==='blocked'){state.stage='blocked';state.analysis=response;return this.status();}
218
249
  if(phase==='change_tasks'){
219
- const proposal=inspectPrdChangeProposal(state.before,response,state.selected,config,{rules:selfCheckRules()});
250
+ const proposal=inspectPrdChangeProposal(state.before,response,state.selected,config,{rules:selfCheckRules(),parts:state.parts});
220
251
  need(state.userCases===null||userCases(proposal.files).length>0,'prd_user_cases_missing');
221
252
  this.checkParts(proposal.features,proposal.removed,state.parts,true);
222
253
  state.proposal=proposal;state.round++;state.stage='change_check';
@@ -1,5 +1,5 @@
1
1
  // Mechanical subset of the existing Step 10.5 checklist. No semantic approval.
2
- import {parseFeatureTaskText,validDependencies,declaredAcceptanceIds,DEPENDENCY} from '../cm-ai/cm-ai-admission.mjs';
2
+ import {parseFeatureTaskText,validDependencies,declaredAcceptanceIds,acceptanceDeclarations,DEPENDENCY} from '../cm-ai/cm-ai-admission.mjs';
3
3
  import {specLines,taskLines,TASK_GRAMMAR} from '../spec-task-line.mjs';
4
4
  import {parseTaskScopes,BOOTSTRAP_FEATURE,sessionTaskProblem,sessionTaskReason} from '../task-scope.mjs';
5
5
  import {validateTestCases} from '../../../scripts/validate-test-cases.mjs';
@@ -41,6 +41,24 @@ function outsideFences(source){
41
41
  return fence===null?line:'';
42
42
  }).join('\n');
43
43
  }
44
+ // Fences for the rule-5 exemption follow CommonMark strictly: a closing fence is the same
45
+ // character, at least as long, with nothing but spaces after it. The looser outsideFences
46
+ // above would end a fence at "```not-a-closing-fence" and expose an example marker.
47
+ function strictOutsideFences(source){
48
+ let fence=null;return source.split(/\r?\n/).map(line=>{
49
+ if(fence===null){const open=line.match(/^ {0,3}(`{3,}|~{3,})/);if(open){fence=open[1];return '';}return line;}
50
+ // Only spaces and tabs may follow a closing fence; \s would also accept U+00A0 and other Unicode spaces.
51
+ const close=line.match(/^ {0,3}(`{3,}|~{3,})[ \t]*$/);
52
+ if(close&&close[1][0]===fence[0]&&close[1].length>=fence.length)fence=null;
53
+ return '';
54
+ }).join('\n');
55
+ }
56
+ // Rule 5: ids whose only declarations say NOT_APPLICABLE. A marker counts only outside strict
57
+ // fences, and any plain declaration of the same id anywhere (fenced or not) keeps it required.
58
+ function inapplicableAcceptanceIds(source){
59
+ const plain=new Set(acceptanceDeclarations(source).filter(item=>!item.inapplicable).map(item=>item.id));
60
+ return new Set(acceptanceDeclarations(strictOutsideFences(source)).filter(item=>item.inapplicable&&!plain.has(item.id)).map(item=>item.id));
61
+ }
44
62
  // Rule 2 adds checks the parser alone cannot make; rule 1 is the original subset.
45
63
  // Only a fresh draft round and a change proposal opt into rule 2. Every re-check
46
64
  // of material that may predate it (corrections, dispositions, summary) stays on
@@ -51,10 +69,18 @@ function outsideFences(source){
51
69
  // instead of a session's guess. Tasks an approved tasks.md already had may stay
52
70
  // without scope (they simply run serially).
53
71
  // Rule 4 reads tasks.md as task grammar 3 (`开发: 会话`) and adds the session-task checks.
54
- export const PRD_SELF_CHECK_RULES=4;
72
+ // Rule 5 = rule 4 plus the NOT_APPLICABLE coverage exemption (inapplicableAcceptanceIds below).
73
+ // Rule 6 = rule 3 plus that exemption, for sessions on specs still published under task grammar 2:
74
+ // they cannot take rule 4's grammar-3 reading, yet need the exemption too (Wue specs8, 2026-11-14).
75
+ // Rules are therefore feature sets, not a ladder: test them with the predicates below.
76
+ // Reports recorded under rules 1–4 recompute exactly as before.
77
+ export const PRD_SELF_CHECK_RULES=5;
78
+ export const PRD_SELF_CHECK_LEGACY_GRAMMAR_RULES=6;
79
+ export const ruleReadsGrammar3=rules=>rules===4||rules===5;
80
+ export const ruleExemptsInapplicable=rules=>rules===5||rules===6;
55
81
  // Every rule a session, an operation or a recorded report may carry. Earlier rules
56
82
  // stay listed explicitly so raising the current one never drops them.
57
- export const PRD_SELF_CHECK_RULE_VERSIONS=Object.freeze([...new Set([PRD_SELF_CHECK_RULES,3,2,1])]);
83
+ export const PRD_SELF_CHECK_RULE_VERSIONS=Object.freeze([...new Set([PRD_SELF_CHECK_RULES,PRD_SELF_CHECK_LEGACY_GRAMMAR_RULES,4,3,2,1])]);
58
84
  // Task- or dependency-looking lines the parser skips: a task written this way
59
85
  // would silently drop out of execution.
60
86
  const TASK_LIKE=/^\s*-\s*\[[^\]]*\]\s+(?:~~)?T-/,DEPENDENCY_LIKE=/^\s*-\s*T-\S*\s+依赖(?:\s|$)/;
@@ -110,10 +136,12 @@ export function matchesPrdDraftMechanics(draft,recorded,options={}){
110
136
  // `sessionTasks` ([directory...]) likewise applies only what rule 4 adds (tasks.md
111
137
  // read as grammar 3, with the session-task checks) to the features whose save
112
138
  // recorded rule 4, so a correction cannot move or add a `开发: 会话` mark unnoticed.
113
- export function checkPrdDraftMechanics(draft,{change=false,previous=null,rules=1,scopes=null,sessionTasks=null}={}){
139
+ export function checkPrdDraftMechanics(draft,{change=false,previous=null,rules=1,scopes=null,sessionTasks=null,inapplicableAcceptance=null}={}){
114
140
  need(PRD_SELF_CHECK_RULE_VERSIONS.includes(rules),'prd_self_check_rules_invalid');
115
141
  need(sessionTasks===null||Array.isArray(sessionTasks)&&sessionTasks.every(item=>typeof item==='string'),
116
142
  'prd_self_check_rules_invalid');
143
+ need(inapplicableAcceptance===null||Array.isArray(inapplicableAcceptance)&&inapplicableAcceptance.every(item=>typeof item==='string'),
144
+ 'prd_self_check_rules_invalid');
117
145
  const findings=[],features=[];
118
146
  for(const feature of draft.features){
119
147
  const files=new Map(feature.documents.map(document=>[document.path,document.content]));
@@ -139,7 +167,7 @@ export function checkPrdDraftMechanics(draft,{change=false,previous=null,rules=1
139
167
  if(!reported.has(code))add(code);
140
168
  }
141
169
  const scope=scopes!==null&&Object.hasOwn(scopes,feature.directory)?scopes[feature.directory]:null;
142
- const grammar3=rules>=4||sessionTasks?.includes(feature.directory)===true;
170
+ const grammar3=ruleReadsGrammar3(rules)||sessionTasks?.includes(feature.directory)===true;
143
171
  if((rules>=3||scope!==null)&&!parsed.error){
144
172
  // Rules 1-3 predate grammar 3: a `开发:` line there stays prose, as it was then.
145
173
  const scopes=parseTaskScopes(files.get('tasks.md'),{grammar:grammar3?TASK_GRAMMAR:2});
@@ -171,7 +199,9 @@ export function checkPrdDraftMechanics(draft,{change=false,previous=null,rules=1
171
199
  if(cases.cases.some(item=>item.taskIds.length===0||item.taskIds.some(id=>!taskIds.has(id))
172
200
  ||item.acIds.some(id=>!acIds.has(id))))add('test_reference_invalid');
173
201
  const covered=new Set(cases.cases.flatMap(item=>item.acIds));
174
- if([...acIds].some(id=>!covered.has(id)))add('acceptance_test_coverage_missing');
202
+ const inapplicable=ruleExemptsInapplicable(rules)||inapplicableAcceptance?.includes(feature.directory)===true
203
+ ?inapplicableAcceptanceIds(files.get('requirements.md')):new Set();
204
+ if([...acIds].some(id=>!covered.has(id)&&!inapplicable.has(id)))add('acceptance_test_coverage_missing');
175
205
  }
176
206
  }
177
207
  }
@@ -8,7 +8,7 @@ import {recoverPrdResponse,readPrdRepairBinding} from './response-recovery.mjs';
8
8
  import {readCmInitSource} from '../cm-init/draft-inspection.mjs';
9
9
  import {TASK_GRAMMAR} from '../spec-task-line.mjs';
10
10
  import {readSpecsStatus} from '../specs-status.mjs';
11
- import {PRD_SELF_CHECK_RULES,PRD_SELF_CHECK_RULE_VERSIONS} from './self-check.mjs';
11
+ import {PRD_SELF_CHECK_RULES,PRD_SELF_CHECK_RULE_VERSIONS,PRD_SELF_CHECK_LEGACY_GRAMMAR_RULES,ruleReadsGrammar3} from './self-check.mjs';
12
12
 
13
13
  export function readPrdSessionFile(root,relative){
14
14
  if(!['state.json','inputs-replaced.json'].includes(relative))return readCmInitSource(root,relative)?.toString('utf8')??null;
@@ -44,7 +44,9 @@ export function prdSessionVersions(state,specs=null){
44
44
  if(state==null){
45
45
  const status=specs===null?{kind:'missing'}:readSpecsStatus(specs);
46
46
  return status.kind==='missing'||status.kind==='valid'&&status.value.taskGrammar===TASK_GRAMMAR
47
- ?{taskGrammar:TASK_GRAMMAR,selfCheckRules:PRD_SELF_CHECK_RULES}:{...PRD_SESSION_LEGACY_VERSIONS};
47
+ ?{taskGrammar:TASK_GRAMMAR,selfCheckRules:PRD_SELF_CHECK_RULES}
48
+ // Same grammar as before; rule 6 adds only the NOT_APPLICABLE exemption to rule 3, never grammar 3.
49
+ :{...PRD_SESSION_LEGACY_VERSIONS,selfCheckRules:PRD_SELF_CHECK_LEGACY_GRAMMAR_RULES};
48
50
  }
49
51
  return Object.hasOwn(state,'selfCheckRules')?{taskGrammar:state.taskGrammar,selfCheckRules:state.selfCheckRules}:{...PRD_SESSION_LEGACY_VERSIONS};
50
52
  }
@@ -70,7 +72,10 @@ export function openPrdSession({specs,sessionId,identity,executionPolicy=null}){
70
72
  try{need([1,2].includes(state.version)&&digest(state.identity)===digest(identity),'prd_session_identity_changed');
71
73
  need(Object.hasOwn(state,'taskGrammar')===Object.hasOwn(state,'selfCheckRules')&&(!Object.hasOwn(state,'taskGrammar')
72
74
  ||Number.isSafeInteger(state.taskGrammar)&&state.taskGrammar>=2&&state.taskGrammar<=TASK_GRAMMAR
73
- &&PRD_SELF_CHECK_RULE_VERSIONS.includes(state.selfCheckRules)),'prd_session_versions_invalid');
75
+ &&PRD_SELF_CHECK_RULE_VERSIONS.includes(state.selfCheckRules)
76
+ // A grammar-3 rule only with grammar 3, and rule 6 (grammar-2 exemption) only with grammar 2.
77
+ &&(!ruleReadsGrammar3(state.selfCheckRules)||state.taskGrammar===TASK_GRAMMAR)
78
+ &&(state.selfCheckRules!==PRD_SELF_CHECK_LEGACY_GRAMMAR_RULES||state.taskGrammar===2)),'prd_session_versions_invalid');
74
79
  if(state.version===2){readExecutionPolicy(state.executionPolicy);need(Array.isArray(state.responseRepairs),'prd_recovery_binding');}
75
80
  else need(executionPolicy===null,'execution_policy_legacy_run');}
76
81
  catch(e){fs.unlinkSync(lock);throw e;}
@@ -17,7 +17,7 @@ import path from 'node:path';
17
17
  import {createHash} from 'node:crypto';
18
18
  import {need} from '../cm-ai/effect-contract.mjs';
19
19
  import {parseFeatureTaskText} from '../cm-ai/cm-ai-admission.mjs';
20
- import {checkPrdDraftMechanics,PRD_SELF_CHECK_RULE_VERSIONS} from './self-check.mjs';
20
+ import {checkPrdDraftMechanics,PRD_SELF_CHECK_RULE_VERSIONS,ruleReadsGrammar3,ruleExemptsInapplicable} from './self-check.mjs';
21
21
  import {readPrdSessionFile,replaceSessionFile} from './session.mjs';
22
22
  import {normalizeRuntimeMarkBytes} from '../../../scripts/cm-spec-manifest.mjs';
23
23
 
@@ -29,11 +29,13 @@ function taskIds(text,grammar){
29
29
  const parsed=parseFeatureTaskText(text,{grammar});
30
30
  return parsed.error?[]:parsed.tasks.map(task=>task.id).sort();
31
31
  }
32
+ // Only rules that add something to re-checks are written: grammar-3 session tasks (4, 5) or the exemption (5, 6).
33
+ const recordedRule=rules=>ruleReadsGrammar3(rules)||ruleExemptsInapplicable(rules);
32
34
  function parseRecord(raw){
33
35
  let value;try{value=JSON.parse(raw);}catch{value=null;}
34
36
  need(value!==null&&typeof value==='object'&&value.version===1&&typeof value.enforced==='boolean'
35
37
  &&Array.isArray(value.exempt)&&value.exempt.every(id=>typeof id==='string')
36
- &&(!Object.hasOwn(value,'selfCheckRules')||PRD_SELF_CHECK_RULE_VERSIONS.includes(value.selfCheckRules)&&value.selfCheckRules>=4)
38
+ &&(!Object.hasOwn(value,'selfCheckRules')||PRD_SELF_CHECK_RULE_VERSIONS.includes(value.selfCheckRules)&&recordedRule(value.selfCheckRules))
37
39
  &&Object.keys(value).length===(Object.hasOwn(value,'selfCheckRules')?4:3),'prd_task_scope_record_invalid');
38
40
  return value;
39
41
  }
@@ -64,7 +66,8 @@ export function approvedScopeExemptions(before,directories,grammar){
64
66
 
65
67
  // `exemptions` maps a directory to {exempt} (a change) or is empty (a new draft).
66
68
  // `selfCheckRules` is the rule of the saving operation (session.mjs); only rule 4
67
- // and later are written, since earlier rules add nothing beyond the scope record.
69
+ // and later are written, since earlier rules add nothing beyond the scope record
70
+ // (4: session tasks; 5: also the NOT_APPLICABLE coverage exemption; 6: the exemption only).
68
71
  export function recordPrdTaskScopes(specs,features,exemptions={},{selfCheckRules=1}={}){
69
72
  need(PRD_SELF_CHECK_RULE_VERSIONS.includes(selfCheckRules),'prd_self_check_rules_invalid');
70
73
  const reviews=path.join(specs,'.reviews');
@@ -77,7 +80,7 @@ export function recordPrdTaskScopes(specs,features,exemptions={},{selfCheckRules
77
80
  {scopes:{[feature.directory]:{exempt}}});
78
81
  const enforced=!report.findings.some(item=>SCOPE_CODES.has(item.code));
79
82
  const relative=recordPath(feature.directory),bytes=JSON.stringify({version:1,enforced,exempt,
80
- ...(selfCheckRules>=4?{selfCheckRules}:{})})+'\n';
83
+ ...(recordedRule(selfCheckRules)?{selfCheckRules}:{})})+'\n';
81
84
  const prior=readPrdSessionFile(specs,relative);
82
85
  if(prior!==bytes)replaceSessionFile(specs,relative,prior,bytes);
83
86
  }
@@ -85,13 +88,16 @@ export function recordPrdTaskScopes(specs,features,exemptions={},{selfCheckRules
85
88
 
86
89
  // The checkPrdDraftMechanics options a re-check of saved features must use.
87
90
  export function prdTaskScopeOptions(specs,directories){
88
- const scopes={},sessionTasks=[];
91
+ const scopes={},sessionTasks=[],inapplicableAcceptance=[];
89
92
  for(const directory of typeof directories==='string'?[directories]:directories){
90
93
  const raw=readPrdSessionFile(specs,recordPath(directory));
91
94
  if(raw===null)continue;
92
95
  const value=parseRecord(raw);
93
96
  if(value.enforced)scopes[directory]={exempt:value.exempt};
94
- if(Object.hasOwn(value,'selfCheckRules'))sessionTasks.push(directory);
97
+ if(ruleReadsGrammar3(value.selfCheckRules))sessionTasks.push(directory);
98
+ // Saved under rule 5 or 6: re-checks keep the NOT_APPLICABLE coverage exemption, as rule 4 keeps session tasks.
99
+ if(ruleExemptsInapplicable(value.selfCheckRules))inapplicableAcceptance.push(directory);
95
100
  }
96
- return {...(Object.keys(scopes).length?{scopes}:{}),...(sessionTasks.length?{sessionTasks}:{})};
101
+ return {...(Object.keys(scopes).length?{scopes}:{}),...(sessionTasks.length?{sessionTasks}:{}),
102
+ ...(inapplicableAcceptance.length?{inapplicableAcceptance}:{})};
97
103
  }
@@ -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 全部符合结构合同。
@@ -183,3 +183,13 @@ test('legacy frozen material keeps verifying without retroactive contract or inv
183
183
  const old=captureSpecificationMaterial({...selection,acceptance:false});assert.equal(Object.hasOwn(old,'acceptanceContract'),false);
184
184
  assert.deepEqual(verifySpecificationMaterial({specification:old,specificationRoot:f.specsDir,identity}),old);
185
185
  });
186
+ // A linked NOT_APPLICABLE item stays declared, but its reason ("真机…") is not an execution duty (Wue specs8).
187
+ test('a NOT_APPLICABLE acceptance block infers no execution obligation from its reason',()=>{
188
+ const c=buildAcceptanceContract({taskId:'T-001',taskText:'- [ ] T-001: implement AC-001, AC-002',
189
+ requirementsText:'- [ ] [AC-001] complete\n- [ ] [AC-002] NOT_APPLICABLE:本期不做真机验收(依据)\n - 必须在真机完成保存回读'});
190
+ assert.ok(!c.unresolved.some(item=>item.includes('AC-002')));
191
+ assert.ok(!c.obligations.some(item=>item.id.startsWith('AC-002')||item.environment==='device'));
192
+ const plain=buildAcceptanceContract({taskId:'T-001',taskText:'- [ ] T-001: implement AC-001, AC-002',
193
+ requirementsText:'- [ ] [AC-001] complete\n- [ ] [AC-002] 必须在真机完成保存回读'});
194
+ assert.ok(plain.obligations.some(item=>item.environment==='device'));
195
+ });
@@ -7,7 +7,7 @@ import {fileURLToPath} from 'node:url';
7
7
  import {inspectCmAiAdmission,approveCmAiSpecs,matchesCmAiTaskSelection,explainCmAiTaskSelection} from '../runtime/js/cm-ai/cm-ai-admission.mjs';
8
8
  import {validateRunDefinition} from './cm-ai-run.mjs';
9
9
 
10
- const usage='usage: cm-ai-admission.mjs --specs-dir PATH --code-project PATH [--code-project PATH ...] [--approval-response TEXT | --yes] [--approve (--approval-response TEXT | --standing-authorization) (no --yes) [--expect-revision-digest HEX]] [--feature N.slug] [--print-run-definition --scope a,b [--task T-xxx] [--requirements c,d] [--run-id X] [--repository-id Y]]';
10
+ const usage='usage: cm-ai-admission.mjs --specs-dir PATH --code-project PATH [--code-project PATH ...] [--approval-response TEXT | --yes] [--approve (--approval-response TEXT | --standing-authorization) (no --yes) [--expect-revision-digest HEX] [--no-spec-amend]] [--feature N.slug] [--print-run-definition --scope a,b [--task T-xxx] [--requirements c,d] [--run-id X] [--repository-id Y]]';
11
11
 
12
12
  function parse(argv){
13
13
  const result={codeProjects:[]};
@@ -22,6 +22,10 @@ function parse(argv){
22
22
  if(result.standingAuthorization)throw new Error('invalid arguments');
23
23
  result.standingAuthorization=true;continue;
24
24
  }
25
+ if(flag==='--no-spec-amend'){
26
+ if(Object.hasOwn(result,'specAmend'))throw new Error('invalid arguments');
27
+ result.specAmend=false;continue;
28
+ }
25
29
  if(flag==='--print-run-definition'){
26
30
  if(result.printRunDefinition)throw new Error('invalid arguments');
27
31
  result.printRunDefinition=true;continue;
@@ -42,6 +46,7 @@ function parse(argv){
42
46
  throw new Error('--expect-revision-digest requires --approve and a 64-character lowercase hex digest');
43
47
  if(result.standingAuthorization&&(!result.approve||!Object.hasOwn(result,'expectRevisionDigest')||result.assumeYes||Object.hasOwn(result,'approvalResponse')))
44
48
  throw new Error('--standing-authorization requires --approve and --expect-revision-digest, without --approval-response or --yes');
49
+ if(Object.hasOwn(result,'specAmend')&&!result.approve)throw new Error('--no-spec-amend requires --approve');
45
50
  if(!result.printRunDefinition&&['scope','task','requirements','runId','repositoryId'].some(key=>Object.hasOwn(result,key)))
46
51
  throw new Error('run definition options require --print-run-definition');
47
52
  return result;
@@ -96,7 +101,8 @@ export function main(argv=process.argv.slice(2)){
96
101
  const mismatch=!firstBlocked&&projectResults.some(item=>JSON.stringify({state:item.state,reason:item.reason,features:item.features,nextTask:item.nextTask})!==decision);
97
102
  const selected=mismatch?{...reference,state:'blocked',reason:'project_admission_mismatch',nextTask:null}:reference;
98
103
  const result={...selected,...(approval?.approveRefused?{approveRefused:approval.approveRefused}:{}),
99
- ...(approval?.approveReason?{approveReason:approval.approveReason}:{}),codeProject:input.codeProjects.length===1?selected.codeProject:null,
104
+ ...(approval?.approveReason?{approveReason:approval.approveReason}:{}),
105
+ ...(approval?.specAmend?{specAmend:approval.specAmend}:{}),codeProject:input.codeProjects.length===1?selected.codeProject:null,
100
106
  codeProjects:projectResults.map(item=>item.codeProject),
101
107
  projectAdmissions:projectResults.map(item=>({codeProject:item.codeProject,state:item.state,reason:item.reason}))};
102
108
  if(result.state==='awaiting_spec_approval'&&(result.approvalIntent!=='explicit'||input.assumeYes))
@@ -8,6 +8,12 @@ import {fileURLToPath} from 'node:url';
8
8
  import {parseFeatureTaskText,validDependencies,identifyApprovedBootstrapFeature,approveCmAiSpecs} from '../runtime/js/cm-ai/cm-ai-admission.mjs';
9
9
  import {validateRunDefinition} from './cm-ai-run.mjs';
10
10
  import {buildManifest} from './cm-spec-manifest.mjs';
11
+ // Spec approvals write a round ledger under CM_WORKFLOW_HOME; keep it off the real home.
12
+ if(!process.env.CM_WORKFLOW_HOME){
13
+ const isolatedHome=fs.mkdtempSync(path.join(os.tmpdir(),'cm-approval-home-'));
14
+ process.env.CM_WORKFLOW_HOME=isolatedHome;
15
+ process.on('exit',()=>fs.rmSync(isolatedHome,{recursive:true,force:true}));
16
+ }
11
17
 
12
18
  const entry=fileURLToPath(new URL('./cm-ai-admission.mjs',import.meta.url));
13
19
  function fixture(run){
@@ -117,8 +123,15 @@ test('bound approve refuses changes made after its first check, before the appro
117
123
  const requirements=path.join(specs,'1.login','requirements.md'),original=fs.readFileSync(requirements);
118
124
  const interleavings={
119
125
  'spec edited':()=>fs.appendFileSync(requirements,'unreviewed\n'),
120
- 'another proposal saved':()=>fs.writeFileSync(status,saved('b'.repeat(64))),
121
- 'duplicate approval landed':()=>assert.equal(approve().approveRefused,undefined)};
126
+ 'another proposal saved':()=>fs.writeFileSync(status,saved('b'.repeat(64)))};
127
+ // A second approval cannot land here at all: the approval lock refuses it, and the first proceeds.
128
+ {
129
+ fs.writeFileSync(requirements,original);fs.writeFileSync(status,saved());
130
+ let nested;
131
+ assert.equal(approve(()=>{nested=approve();}).approveRefused,undefined);
132
+ assert.equal(nested.approveRefused,'spec_approval_busy');
133
+ assert.equal(JSON.parse(fs.readFileSync(status,'utf8')).status,'approved');
134
+ }
122
135
  for(const [name,interleave] of Object.entries(interleavings)){
123
136
  fs.writeFileSync(requirements,original);fs.writeFileSync(status,saved());
124
137
  let after;
@@ -6,7 +6,10 @@ import {packageMaterialEligible,packageMaterialReference,resolveCheckpointPackag
6
6
  const identity={repositoryId:'capacity',runId:'capacity-fixture',taskId:'T-001',attempt:1};
7
7
  const invalid={code:'checkpoint_package_material_invalid'};
8
8
  const size=value=>Buffer.byteLength(JSON.stringify(value));
9
- const pkg=(bytes=789000,who=identity)=>{const body={version:1,kind:'cm-review-package',identity:who,material:'x'.repeat(bytes)};
9
+ // 这些夹具原按 1 MiB 记录上限写死字节数;D 把它们平移到当前上限,各测试的相对含义不变
10
+ const D=JOURNAL_PAYLOAD_LIMIT-1024*1024;
11
+ // 默认包刚好越过「记录上限 − 预留」、又装得进一条记录:按上限换算(1 MiB 时即原来的 789000),上限调整后含义不变
12
+ const pkg=(bytes=JOURNAL_PAYLOAD_LIMIT-259576,who=identity)=>{const body={version:1,kind:'cm-review-package',identity:who,material:'x'.repeat(bytes)};
10
13
  return {...body,packageDigest:digest(body)};};
11
14
  function append(records,payload,kind='result'){
12
15
  const body={version:1,seq:records.length+1,id:`runner.${String(records.length+1).padStart(6,'0')}`,kind,payload,
@@ -67,7 +70,7 @@ test('inline develop followed by a failed review crossing the future reserve sta
67
70
  observation:{events:[{event:'process_closed',exit_code:1,timed_out:false}]},
68
71
  inspection:{kind:'cm-provider-review-failure',category:'provider',failure:'reviewer_exited'}}};
69
72
  }
70
- checkpoint.padding='';checkpoint.padding='r'.repeat(764046-size(payload(effectId,checkpoint)));
73
+ checkpoint.padding='';checkpoint.padding='r'.repeat(764046+D-size(payload(effectId,checkpoint)));
71
74
  assert(size(payload(effectId,checkpoint))>JOURNAL_PAYLOAD_LIMIT-reserve);
72
75
  assert(size(payload(effectId,checkpoint))<JOURNAL_PAYLOAD_LIMIT);
73
76
  const before=JSON.stringify(checkpoint);
@@ -136,7 +139,7 @@ test('a reference cannot replace the current package, erase other frame fields o
136
139
  const restored=resolveCheckpointPackage(p,records,identity);
137
140
  assert.deepEqual({...restored,reviewPackage:null},p.checkpoint);
138
141
  assert.equal(packageMaterialReference(f.archived,pkg(32),identity),null);
139
- const secondIdentity={...identity,attempt:2},secondPackage=pkg(789000,secondIdentity);
142
+ const secondIdentity={...identity,attempt:2},secondPackage=pkg(789000+D,secondIdentity);
140
143
  assert.equal(packageMaterialReference(f.archived,secondPackage,secondIdentity),null,'old r1 material must not replace r2');
141
144
  const secondRecords=intent(f.archived,'develop-2','develop',secondIdentity),secondCheckpoint=frame(secondPackage,'develop-2','develop','awaiting_review',secondIdentity);
142
145
  const second=checkpointStoragePlan({records:secondRecords,effectId:'develop-2',checkpoint:secondCheckpoint,identity:secondIdentity,enabled:true,reserve:272125});
@@ -175,16 +178,45 @@ test('r2 failed develop may retain the r1 package and exact r1 archive without s
175
178
  test('a package above the original record limit cannot be admitted by material storage and no reserve is changed',()=>{
176
179
  const f=fixture(),oversize=frame(pkg(JOURNAL_PAYLOAD_LIMIT));
177
180
  const measured={inlineBytes:815380,packageBytes:789175,reserve:272125};
181
+ // Without an archive the package keeps the original 1 MiB inline budget (whole-state capacity).
178
182
  assert.deepEqual(checkpointPackageBudget({...measured,enabled:false}),{fits:false,material:false,bytes:815380,budget:776451});
179
- assert.deepEqual(checkpointPackageBudget({...measured,enabled:true}),{fits:true,material:true,bytes:26717,budget:776451});
180
- assert.deepEqual(checkpointPackageBudget({...measured,enabled:true,referenced:true}),{fits:true,material:false,bytes:26717,budget:776451});
183
+ assert.deepEqual(checkpointPackageBudget({...measured,enabled:true}),{fits:true,material:true,bytes:26717,budget:776451+D});
184
+ assert.deepEqual(checkpointPackageBudget({...measured,enabled:true,referenced:true}),{fits:true,material:false,bytes:26717,budget:776451+D});
181
185
  assert.equal(checkpointPackageBudget({...measured,inlineBytes:JOURNAL_PAYLOAD_LIMIT-1023,enabled:true}).fits,false);
182
- assert.equal(checkpointPackageBudget({...measured,packageBytes:16,enabled:true}).fits,false,'future compact frame must leave original reserve');
186
+ assert.equal(checkpointPackageBudget({...measured,inlineBytes:JOURNAL_PAYLOAD_LIMIT-272125+1000,packageBytes:16,enabled:true}).fits,false,'future compact frame must leave original reserve');
183
187
  assert.throws(()=>checkpointStoragePlan({records:f.records,effectId:'develop-1',checkpoint:oversize,identity,enabled:true,reserve:272125}),invalid);
184
188
  for(const reserve of [-1,JOURNAL_PAYLOAD_LIMIT,1.5])assert.throws(()=>checkpointStoragePlan({records:f.records,effectId:'develop-1',checkpoint:f.checkpoint,identity,enabled:true,reserve}),invalid);
185
189
  });
186
190
 
187
191
 
192
+ // Codex review (journal limit 4 MiB): a package between the original 1 MiB budget and
193
+ // the raised record limit must be archived once, or two review rounds and completion
194
+ // repeat it past the 16 MiB whole state after the task commit.
195
+ test('a 3.6 MB package archives once and two review rounds plus completion stay within the whole state',()=>{
196
+ const STATE=16*1024*1024,reserve=272125;
197
+ const material1=pkg(3600000);
198
+ assert.equal(checkpointPackageBudget({inlineBytes:size(payload('develop-1',frame(material1))),packageBytes:size(material1),reserve,enabled:false}).fits,false,
199
+ 'without an archive the package is refused before develop is accepted');
200
+ let records=append([],{version:3,protocol:'cm-task-runner',type:'init',config:{identity}});
201
+ const step=(effectId,kind,state,material,who)=>{
202
+ records=intent(records,effectId,kind,who);
203
+ const checkpoint=frame(material,effectId,kind,state,who);
204
+ const plan=checkpointStoragePlan({records,effectId,checkpoint,identity:who,enabled:true,reserve});
205
+ const stored=payload(effectId,plan.checkpoint,plan.payloadFields);
206
+ assert(size(stored)<=JOURNAL_PAYLOAD_LIMIT);
207
+ records=append(records,stored);
208
+ assert(size(records)<STATE,`${effectId}: whole state ${size(records)} bytes`);
209
+ return plan.payloadFields;
210
+ };
211
+ const second={...identity,attempt:2},material2=pkg(3600001,second);
212
+ assert.deepEqual(step('develop-1','develop','awaiting_review',material1,identity),{packageMaterial:true});
213
+ assert(Object.hasOwn(step('review-1','review','changes_requested',material1,identity),'packageRef'));
214
+ assert.deepEqual(step('develop-2','develop','awaiting_review',material2,second),{packageMaterial:true});
215
+ assert(Object.hasOwn(step('review-2','review','approved',material2,second),'packageRef'));
216
+ assert(Object.hasOwn(step('complete-2','complete','fixture_completed',material2,second),'packageRef'));
217
+ assert(size(records)<2*size(material1)+1024*1024,'each package is stored once');
218
+ });
219
+
188
220
  test('eligibility is limited to durable v3 single-project conversation v2 without bootstrap or parallel/batch metadata',()=>{
189
221
  const config={root:'/fixture',identity,controlPolicy:{version:2,development:'conversation',bootstrap:'disabled',qa:'disabled',qaFix:'disabled'}};
190
222
  assert.equal(packageMaterialEligible(config,3),true);
@@ -210,6 +242,28 @@ test('reconciled review uses the same backward package reference and validates i
210
242
  }
211
243
  });
212
244
 
245
+ // Codex review r2: a run that stored a large package inline before the fixed archive
246
+ // threshold keeps working: a reconciled review and the completion stay inline instead
247
+ // of being asked for a first archive they may not create.
248
+ test('an old inline large package survives a reconciled review and completion without a first archive',()=>{
249
+ const material=pkg(3600000),binding={invocationId:'review-invocation',registeredDigest:digest('registered'),
250
+ startedDigest:digest('started'),resultDigest:digest('result'),receiptDigest:digest('receipt')};
251
+ let records=append([],{version:3,protocol:'cm-task-runner',type:'init',config:{identity}});
252
+ records=intent(records,'develop-1');
253
+ records=append(records,payload('develop-1',frame(material)));
254
+ records=intent(records,'review-1','review');
255
+ const review=frame(material,'review-1','review','approved');
256
+ const reconciled=checkpointStoragePlan({records,effectId:'review-1',checkpoint:review,identity,enabled:true,reserve:272125,
257
+ type:'review-invocation-reconciled',binding});
258
+ assert.deepEqual(reconciled.payloadFields,{});assert.deepEqual(reconciled.checkpoint,review);
259
+ const stored={...payload('review-1',reconciled.checkpoint),type:'review-invocation-reconciled',...binding};
260
+ assert.deepEqual(resolveCheckpointPackage(stored,records,identity),review);
261
+ records=append(records,stored);records=intent(records,'complete-1','complete');
262
+ const done=checkpointStoragePlan({records,effectId:'complete-1',checkpoint:frame(material,'complete-1','complete','fixture_completed'),
263
+ identity,enabled:true,reserve:272125});
264
+ assert.deepEqual(done.payloadFields,{});
265
+ });
266
+
213
267
  test('only marked develop checkpoints can source references and the dedicated failure code survives normalization',()=>{
214
268
  const f=fixture();
215
269
  const unmarked=append(f.records,payload('develop-1',f.checkpoint));
@@ -1,5 +1,6 @@
1
1
  // Real owner/driver and local checks; reviewer output is synthetic protocol
2
2
  // evidence, never independent review of this implementation. No Codex sandbox.
3
+ import './test-journal-limit-1mib.mjs'; // 第一条 import:这些边界场景按 1 MiB 记录上限构造
3
4
  import test from 'node:test';
4
5
  import assert from 'node:assert/strict';
5
6
  import fs from 'node:fs';
@@ -1,6 +1,7 @@
1
1
  // Develop answers and driver gaps found in the pre-release audit. Every test here
2
2
  // drives the real driver/host processes; none needs the Codex sandbox, so CI runs them.
3
3
  // Protected-mode flows that do reach the sandbox live in cm-ai-host.test.mjs.
4
+ import './test-journal-limit-1mib.mjs'; // 第一条 import:这些边界场景按 1 MiB 记录上限构造
4
5
  import test,{after} from 'node:test';
5
6
  import assert from 'node:assert/strict';
6
7
  import fs from 'node:fs';