@aibyzero/cm-workflow 0.20.0 → 0.21.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.codex-plugin/plugin.json +1 -1
- package/CHANGELOG.md +36 -0
- package/README.md +13 -1
- package/VERSION +1 -1
- package/docs/installation.md +1 -1
- package/docs/js-workflow-control.md +1 -1
- package/docs/proposals/spec-amendment-tiers.md +100 -0
- package/package.json +1 -1
- package/runtime/js/acceptance-language.mjs +32 -0
- package/runtime/js/autonomy.mjs +15 -6
- package/runtime/js/cm-ai/acceptance-contract.mjs +8 -3
- package/runtime/js/cm-ai/checkpoint-package-material.mjs +13 -3
- package/runtime/js/cm-ai/cm-ai-admission.mjs +35 -2
- package/runtime/js/cm-ai/codex-review-adapter.mjs +19 -3
- package/runtime/js/cm-ai/drive-core.mjs +9 -2
- package/runtime/js/cm-ai/durable-runner-state.mjs +12 -4
- package/runtime/js/cm-ai/effect-contract.mjs +8 -1
- package/runtime/js/cm-ai/execution-snapshot.mjs +4 -3
- package/runtime/js/cm-ai/execution-store-limits.mjs +3 -3
- package/runtime/js/cm-ai/execution-store.mjs +7 -4
- package/runtime/js/cm-ai/fix-code-association.mjs +27 -6
- package/runtime/js/cm-ai/review-package.mjs +20 -6
- package/runtime/js/cm-ai/review-presentation.mjs +12 -5
- package/runtime/js/cm-ai/reviewed-deliveries.mjs +10 -7
- package/runtime/js/cm-ai/reviewed-integration.mjs +1 -1
- package/runtime/js/cm-ai/spec-amendment.mjs +535 -0
- package/runtime/js/cm-ai/task-commit-codec.mjs +4 -2
- package/runtime/js/cm-ai/task-commit.mjs +4 -2
- package/runtime/js/cm-ai/task-runner.mjs +26 -9
- package/runtime/js/cm-ai/user-maintained-paths.mjs +68 -0
- package/runtime/js/cm-prd/change.mjs +35 -4
- package/runtime/js/cm-prd/self-check.mjs +36 -6
- package/runtime/js/cm-prd/session.mjs +8 -3
- package/runtime/js/cm-prd/task-scope-record.mjs +13 -7
- package/runtime/js/task-scope.mjs +4 -1
- package/runtime/test-contract.md +1 -0
- package/scripts/cm-ai-acceptance-contract.test.mjs +10 -0
- package/scripts/cm-ai-admission.mjs +8 -2
- package/scripts/cm-ai-admission.test.mjs +15 -2
- package/scripts/cm-ai-batch-run-fixture.mjs +5 -1
- package/scripts/cm-ai-checkpoint-package-material.test.mjs +60 -6
- package/scripts/cm-ai-checkpoint-package-owner.test.mjs +1 -0
- package/scripts/cm-ai-develop-driver-gaps.test.mjs +1 -0
- package/scripts/cm-ai-drive.mjs +18 -11
- package/scripts/cm-ai-fix-later-delivery.test.mjs +2 -2
- package/scripts/cm-ai-later-delivery-feature.test.mjs +102 -0
- package/scripts/cm-ai-review-input-limit.test.mjs +91 -0
- package/scripts/cm-ai-user-maintained-paths.test.mjs +183 -0
- package/scripts/cm-autonomy-review-r1.test.mjs +49 -0
- package/scripts/cm-check-runtime.sh +4 -1
- package/scripts/cm-drive-liveness.test.mjs +8 -0
- package/scripts/cm-fix-observation-task-id.test.mjs +49 -0
- package/scripts/cm-fix-review-storage.test.mjs +14 -4
- package/scripts/cm-journal-limit.test.mjs +69 -0
- package/scripts/cm-notify.test.mjs +6 -4
- package/scripts/cm-prd-completion.test.mjs +37 -0
- package/scripts/cm-prd-drive.mjs +1 -1
- package/scripts/cm-prd-host.test.mjs +1 -1
- package/scripts/cm-prd-self-check-rules.test.mjs +23 -11
- package/scripts/cm-prd-self-check.test.mjs +24 -1
- package/scripts/cm-prd-summary.test.mjs +6 -0
- package/scripts/cm-review-inventory.test.mjs +5 -1
- package/scripts/cm-skill-hints.json +1 -1
- package/scripts/cm-skill-hints.mjs +66 -3
- package/scripts/cm-skill-hints.test.mjs +96 -0
- package/scripts/cm-spec-amend.mjs +68 -0
- package/scripts/cm-spec-amend.test.mjs +510 -0
- package/scripts/cm-specs-status.test.mjs +6 -0
- package/scripts/cm-start-check.mjs +82 -2
- package/scripts/cm-start-check.test.mjs +64 -1
- package/scripts/cm-task-scope.test.mjs +3 -2
- package/scripts/test-journal-limit-1mib.mjs +4 -0
- package/scripts/validate-public-repo.py +4 -0
- package/skills/cm-ai/references/N1-init.md +23 -1
- package/skills/cm-ai/references/js-host-qa-recovery.md +3 -2
- package/skills/cm-ai/references/js-host-recovery.md +2 -1
- package/skills/cm-ai/references/js-host.md +2 -1
- package/skills/cm-prd/references/js-change-recovery.md +1 -0
|
@@ -8,7 +8,7 @@ import {readExecutionSnapshot} from '../runtime/js/cm-ai/execution-snapshot.mjs'
|
|
|
8
8
|
import {openFixExecution} from '../runtime/js/cm-fix/execution.mjs';
|
|
9
9
|
import {captureReviewBaseline,createReviewPackage,readReviewPackage} from '../runtime/js/cm-ai/review-package.mjs';
|
|
10
10
|
import * as presentation from '../runtime/js/cm-ai/review-presentation.mjs';
|
|
11
|
-
import {digest,requestFor} from '../runtime/js/cm-ai/effect-contract.mjs';
|
|
11
|
+
import {digest,requestFor,JOURNAL_PAYLOAD_LIMIT} from '../runtime/js/cm-ai/effect-contract.mjs';
|
|
12
12
|
|
|
13
13
|
const MiB=1024*1024,STATE_LIMIT=16*MiB,workflow='cm-fix-stages-v1';
|
|
14
14
|
const copy=value=>JSON.parse(JSON.stringify(value));
|
|
@@ -120,13 +120,23 @@ test('a real CM-fix journal stores a repeated canonical review larger than one M
|
|
|
120
120
|
assert.deepEqual(JSON.parse(fs.readFileSync(f.stateFile,'utf8')).records[prepared.seq-1],prepared);
|
|
121
121
|
});
|
|
122
122
|
|
|
123
|
-
test('
|
|
123
|
+
test('the fix workflow keeps its one MiB physical limit for data it cannot compress',t=>{
|
|
124
124
|
const f=fixture(t);rejectAppend(f,'large-ordinary',{ordinary:'x'.repeat(MiB)});
|
|
125
125
|
const {reviewPackage}=material(f,64);rejectAppend(f,'small-package-large-ordinary',{reviewPackage,ordinary:'x'.repeat(MiB)});
|
|
126
126
|
rejectAppend(f,'arbitrary-nested-review',{arbitrary:{reviewPackage:material(f).reviewPackage}});
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
// Ordinary runs store large records as they are, up to the journal record limit
|
|
130
|
+
// (Wue specs8 T-001: a 1.17 MB develop checkpoint). They are never compressed or
|
|
131
|
+
// marked, so the fix workflow's encoding rules above do not apply to them.
|
|
132
|
+
test('non-fix workflows and false workflow fingerprints store large records unencoded up to the journal limit',t=>{
|
|
127
133
|
for(const mode of ['cm-ai-stages-v1','cm-ai-batch-v1','wrong-fingerprint']){
|
|
128
|
-
const other=fixture(t,{mode}),large=material(other).reviewPackage;
|
|
129
|
-
|
|
134
|
+
const other=fixture(t,{mode}),large=material(other).reviewPackage,input=entry(other,'large-review',{reviewPackage:large});
|
|
135
|
+
assert.ok(Buffer.byteLength(JSON.stringify(input.payload))>MiB,mode);
|
|
136
|
+
assert.equal(appendFits(other.store().snapshot(),input),true,mode);
|
|
137
|
+
const saved=other.store().append(input);assert.deepEqual(saved.records.at(-1).payload,input.payload);
|
|
138
|
+
assert.equal(Object.hasOwn(JSON.parse(fs.readFileSync(other.stateFile,'utf8')),'storageEncoding'),false,mode);
|
|
139
|
+
rejectAppend(other,'over-journal-limit',{ordinary:'x'.repeat(JOURNAL_PAYLOAD_LIMIT)});
|
|
130
140
|
}
|
|
131
141
|
});
|
|
132
142
|
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
// 存档单条上限 4 MiB(Wue specs8 T-001 的审查包约 1.17 MB,1 MiB 时装不下):
|
|
2
|
+
// 默认值、只许调小的测试开关、普通运行的大记录写入与读回、cm-fix 压缩标记不误打。
|
|
3
|
+
import test,{after} from 'node:test';
|
|
4
|
+
import assert from 'node:assert/strict';
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import os from 'node:os';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import {spawnSync} from 'node:child_process';
|
|
9
|
+
import {fileURLToPath} from 'node:url';
|
|
10
|
+
import {JOURNAL_PAYLOAD_LIMIT} from '../runtime/js/cm-ai/effect-contract.mjs';
|
|
11
|
+
import {openExecutionStore} from '../runtime/js/cm-ai/execution-store.mjs';
|
|
12
|
+
import {appendFits} from '../runtime/js/cm-ai/execution-store-limits.mjs';
|
|
13
|
+
import {packFixJournalState} from '../runtime/js/cm-ai/review-presentation.mjs';
|
|
14
|
+
import {readExecutionSnapshot} from '../runtime/js/cm-ai/execution-snapshot.mjs';
|
|
15
|
+
|
|
16
|
+
const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');
|
|
17
|
+
const isolated=fs.mkdtempSync(path.join(os.tmpdir(),'cm-journal-limit-'));
|
|
18
|
+
after(()=>fs.rmSync(isolated,{recursive:true,force:true}));
|
|
19
|
+
const limitWith=value=>{
|
|
20
|
+
const env={...process.env};delete env.CM_JOURNAL_PAYLOAD_LIMIT_TEST;if(value!==undefined)env.CM_JOURNAL_PAYLOAD_LIMIT_TEST=value;
|
|
21
|
+
const run=spawnSync(process.execPath,['--input-type=module','-e',`import {JOURNAL_PAYLOAD_LIMIT} from ${JSON.stringify(path.join(root,'runtime/js/cm-ai/effect-contract.mjs'))};process.stdout.write(String(JOURNAL_PAYLOAD_LIMIT));`],{encoding:'utf8',env});
|
|
22
|
+
assert.equal(run.status,0,run.stderr);return Number(run.stdout);
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
test('默认 4 MiB;测试开关只许调小,调大与非法值忽略',()=>{
|
|
26
|
+
const MiB=1024*1024;
|
|
27
|
+
assert.equal(limitWith(undefined),4*MiB);
|
|
28
|
+
assert.equal(limitWith(String(MiB)),MiB);
|
|
29
|
+
for(const bad of [String(8*MiB),String(4*MiB),'abc','-1',String(1024),'1.5'])assert.equal(limitWith(bad),4*MiB,bad);
|
|
30
|
+
assert.equal(JOURNAL_PAYLOAD_LIMIT,4*MiB,'本测试进程没有设开关');
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
test('普通运行:1.2 MB 的记录写得进、读得回,不被打上 cm-fix 压缩标记',()=>{
|
|
34
|
+
const specsRoot=fs.realpathSync(fs.mkdtempSync(path.join(isolated,'store-')));
|
|
35
|
+
const options={specsRoot,identity:{repositoryId:'size',runId:'size-run'},fingerprints:{workflow:'a'.repeat(64),config:'b'.repeat(64),inputs:'c'.repeat(64)}};
|
|
36
|
+
let store=openExecutionStore({...options,create:true});
|
|
37
|
+
const payload={s:'x'.repeat(1200*1024)};
|
|
38
|
+
try{
|
|
39
|
+
const input={id:'big',kind:'result',payload,expectedRevision:store.snapshot().revision};
|
|
40
|
+
assert.equal(appendFits(store.snapshot(),input),true);
|
|
41
|
+
store.append(input);
|
|
42
|
+
}finally{store.close();}
|
|
43
|
+
store=openExecutionStore({...options,create:false});
|
|
44
|
+
try{assert.deepEqual(store.snapshot().records.at(-1).payload,payload);}finally{store.close();}
|
|
45
|
+
const file=fs.readdirSync(path.join(specsRoot,'.reviews','.execution','size-run')).find(name=>name==='state.json');
|
|
46
|
+
const physical=JSON.parse(fs.readFileSync(path.join(specsRoot,'.reviews','.execution','size-run',file),'utf8'));
|
|
47
|
+
assert.equal(Object.hasOwn(physical,'storageEncoding'),false);
|
|
48
|
+
// 只读发现路径(驾驶员 status/advance 先走它)按同一上限读回,不再写死 1 MiB(Wue specs8 T-001 第 2 轮 limit_exceeded)
|
|
49
|
+
assert.deepEqual(readExecutionSnapshot({specsRoot,identity:{repositoryId:'size',runId:'size-run'}}).records.at(-1).payload,payload);
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
test('整份状态打包:非 cm-fix 运行的大记录不打压缩标记',()=>{
|
|
53
|
+
const state={version:1,identity:{repositoryId:'r',runId:'r'},fingerprints:{workflow:'a'.repeat(64)},revision:'0'.repeat(64),
|
|
54
|
+
records:[{version:1,seq:1,id:'init',kind:'intent',payload:{s:'x'.repeat(1100*1024)},previousDigest:null,digest:'0'.repeat(64)}]};
|
|
55
|
+
assert.equal(Object.hasOwn(packFixJournalState(state),'storageEncoding'),false);
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
// Wue specs8 T-001: the store accepted a 1.2 MB develop checkpoint but the runner's
|
|
59
|
+
// own payload builder still used json()'s 1 MiB default, failed inside the store
|
|
60
|
+
// operation and poisoned the run as store_failure.
|
|
61
|
+
test('the runner builds and bounds a record between 1 MiB and the journal limit, and refuses one above it', async () => {
|
|
62
|
+
const {runnerPayload,runnerPayloadV3,boundRunnerRecord}=await import('../runtime/js/cm-ai/durable-runner-state.mjs');
|
|
63
|
+
const big={effectId:'develop-1',blob:'x'.repeat(1200*1024)};
|
|
64
|
+
for(const payload of [runnerPayloadV3('effect-checkpoint',big),runnerPayload('effect-checkpoint',big,2)]){
|
|
65
|
+
assert.ok(Buffer.byteLength(JSON.stringify(payload))>1024*1024);
|
|
66
|
+
assert.doesNotThrow(()=>boundRunnerRecord({id:'runner.000002',kind:'result',payload},2));
|
|
67
|
+
}
|
|
68
|
+
assert.throws(()=>runnerPayloadV3('effect-checkpoint',{blob:'x'.repeat(JOURNAL_PAYLOAD_LIMIT)}));
|
|
69
|
+
});
|
|
@@ -9,10 +9,12 @@ import {notify,notifyLater,cancelPendingNotice,clearAttention,sessionTitle,sched
|
|
|
9
9
|
|
|
10
10
|
// driveNotice and spawned drivers read the standing authorization from the default
|
|
11
11
|
// home: point it at an empty directory, never the tester's own ~/.cm-workflow.
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
12
|
+
// Always, not only when unset: a tester's exported CM_WORKFLOW_HOME may be their real
|
|
13
|
+
// home with autonomy.json on, which defers every stop and fails the 'now' expectations
|
|
14
|
+
// (dogfood 2026-11-17: four tests failed with a real home under standing authorization).
|
|
15
|
+
const DEFAULT_HOME=fs.mkdtempSync(path.join(os.tmpdir(),'cm-notify-default-home-'));
|
|
16
|
+
process.env.CM_WORKFLOW_HOME=DEFAULT_HOME;
|
|
17
|
+
process.on('exit',()=>fs.rmSync(DEFAULT_HOME,{recursive:true,force:true}));
|
|
16
18
|
const NOW=Date.parse('2026-10-08T08:00:00.000Z');
|
|
17
19
|
const DRIVE_CORE=new URL('../runtime/js/cm-ai/drive-core.mjs',import.meta.url).href;
|
|
18
20
|
const BRIDGE=new URL('../runtime/js/cm-ai/host-tool-bridge.mjs',import.meta.url).href;
|
|
@@ -352,3 +352,40 @@ for(const recoveryMode of ['process-loss','mode-mismatch','publication-conflict'
|
|
|
352
352
|
assert.ok(fs.readFileSync(path.join(dir,'.reviews/prd-new-guide-split-r1.md')).equals(evidence));
|
|
353
353
|
assert.equal(fs.existsSync(path.join(dir,'.reviews/prd-new-guide-split-r2.md')),false);assert.equal(calls,4);await c.close();
|
|
354
354
|
});
|
|
355
|
+
// A feature whose four documents exceed 64 KiB could not take even a format-only
|
|
356
|
+
// change: every change_tasks reply had to resend requirements/design (wue 8.todo-inbox, ~94 KB).
|
|
357
|
+
// Omitted documents of an existing feature mean byte-identical and are restored; the limit counts what is sent.
|
|
358
|
+
test('change_tasks may omit unchanged documents of an existing feature; the 64 KiB limit counts only sent ones',t=>{
|
|
359
|
+
const dir=fixture(t),config=loadConfig({projectRoot:dir}),pad='\n'+'x'.repeat(40*1024)+'\n';
|
|
360
|
+
const big=docs().map(doc=>doc.path==='tasks.md'?doc:{...doc,content:doc.content+pad});
|
|
361
|
+
for(const doc of big)fs.writeFileSync(path.join(dir,'1.guide',doc.path),doc.content,{mode:0o600});
|
|
362
|
+
const contract={schemaVersion:'1.0',feature:'guide',cases:[{id:'TC-001',origin:'generated',kind:'logic',blocking:true,
|
|
363
|
+
acIds:['AC-001'],taskIds:['T-002'],title:'Existing case',preconditions:[],steps:['Read guide'],expected:['Guide available'],cleanup:[]}]};
|
|
364
|
+
fs.writeFileSync(path.join(dir,'1.guide/test-cases.json'),JSON.stringify(contract),{mode:0o600});
|
|
365
|
+
const before=inspectPrdChangeSnapshot(dir);
|
|
366
|
+
const tasks=big[2].content.replace('| 2026-09-08 | v1 | original |','| 2026-09-08 | v1 | original |\n| 2026-09-08 | v2 | format |');
|
|
367
|
+
const full={status:'draft',summary:'Format',removed:[],features:[{directory:'1.guide',testCasesReason:null,
|
|
368
|
+
documents:[...big.slice(0,2),{path:'tasks.md',content:tasks},{path:'test-cases.json',content:JSON.stringify(contract)}]}]};
|
|
369
|
+
assert.throws(()=>inspectPrdChangeProposal(before,full,['1.guide'],config),/limit_exceeded/);
|
|
370
|
+
const sent={...full,features:[{...full.features[0],documents:[{path:'tasks.md',content:tasks}]}]};
|
|
371
|
+
const proposal=inspectPrdChangeProposal(before,sent,['1.guide'],config);
|
|
372
|
+
assert.equal(proposal.files['1.guide/requirements.md'],big[0].content);
|
|
373
|
+
assert.equal(proposal.files['1.guide/design.md'],big[1].content);
|
|
374
|
+
assert.equal(proposal.files['1.guide/tasks.md'],tasks);
|
|
375
|
+
assert.equal(proposal.files['1.guide/test-cases.json'],JSON.stringify(contract));
|
|
376
|
+
// Same proposal whichever unchanged documents the reply carried.
|
|
377
|
+
const partial={...full,features:[{...full.features[0],documents:[big[0],{path:'tasks.md',content:tasks}]}]};
|
|
378
|
+
assert.equal(inspectPrdChangeProposal(before,partial,['1.guide'],config).proposalDigest,proposal.proposalDigest);
|
|
379
|
+
// Requirements/design are restored from the accepted parts, not the disk original, when an earlier phase changed them.
|
|
380
|
+
const accepted={features:[{directory:'1.guide',documents:[{path:'requirements.md',content:big[0].content.replace('| 2026-09-08 | v1 | original |','| 2026-09-08 | v1 | original |\n| 2026-09-08 | v2 | format |')},big[1]]}],removed:[]};
|
|
381
|
+
assert.equal(inspectPrdChangeProposal(before,sent,['1.guide'],config,{parts:accepted}).files['1.guide/requirements.md'],accepted.features[0].documents[0].content);
|
|
382
|
+
// A non-null testCasesReason still removes the contract: omission never resurrects it.
|
|
383
|
+
const dropped={...full,features:[{directory:'1.guide',testCasesReason:'no_observable_behavior',documents:[{path:'tasks.md',content:tasks}]}]};
|
|
384
|
+
assert.equal(inspectPrdChangeProposal(before,dropped,['1.guide'],config).files['1.guide/test-cases.json'],undefined);
|
|
385
|
+
// The reply as sent is still bounded at 64 KiB, and a new feature is never filled in.
|
|
386
|
+
const oversent={...sent,features:[{...sent.features[0],documents:[{path:'tasks.md',content:tasks+'\n'+'y'.repeat(70*1024)}]}]};
|
|
387
|
+
assert.throws(()=>inspectPrdChangeProposal(before,oversent,['1.guide'],config),/limit_exceeded/);
|
|
388
|
+
const fresh={status:'draft',summary:'New',removed:[],features:[...sent.features,{directory:'2.extra',testCasesReason:'no_observable_behavior',
|
|
389
|
+
documents:[{path:'tasks.md',content:'## 任务版本'+'\n| 日期 | 版本 | 说明 |\n| --- | --- | --- |\n| 2026-09-08 | v1 | new |\n- [ ] T-001: [NEW] Extra\n'}]}]};
|
|
390
|
+
assert.throws(()=>inspectPrdChangeProposal(before,fresh,['1.guide'],config),/prd_draft_triad_missing|prd_change/);
|
|
391
|
+
});
|
package/scripts/cm-prd-drive.mjs
CHANGED
|
@@ -252,7 +252,7 @@ function validate(kind,value,ctx){
|
|
|
252
252
|
// Same rule the host applies: a resumed operation keeps the rule it began
|
|
253
253
|
// under (none recorded = rule 1); a new operation uses the one its session bound.
|
|
254
254
|
const rules=ctx.operation==='resume'?ctx.state.active?.selfCheckRules??1:prdSessionVersions(ctx.state,ctx.specs).selfCheckRules;
|
|
255
|
-
try{inspectPrdChangeProposal(inspectPrdChangeSnapshot(ctx.specs),value,ctx.state.checkpoint.change.selected,ctx.config,{rules});}
|
|
255
|
+
try{inspectPrdChangeProposal(inspectPrdChangeSnapshot(ctx.specs),value,ctx.state.checkpoint.change.selected,ctx.config,{rules,parts:ctx.state.checkpoint.change.parts??null});}
|
|
256
256
|
catch(e){fail('generate.json 不符合变更草稿或 scope',e.code??e.message);}
|
|
257
257
|
}else{
|
|
258
258
|
check(value.status==='documents'&&nonempty(value.summary)&&Array.isArray(value.features)&&Array.isArray(value.removed),'generate.json');
|
|
@@ -107,7 +107,7 @@ for(const mode of ['codex','claude','cancel','cases','materials','draft','self-c
|
|
|
107
107
|
}else if(message.requestId==='save'){
|
|
108
108
|
assert.equal(message.result.status,'draft_saved');assert.equal(message.result.artifacts.length,3);
|
|
109
109
|
// The save keeps its operation's rule, so later re-checks of these files use it.
|
|
110
|
-
assert.equal(JSON.parse(fs.readFileSync(path.join(dir,'.reviews/prd-guide-task-scope.json'),'utf8')).selfCheckRules,
|
|
110
|
+
assert.equal(JSON.parse(fs.readFileSync(path.join(dir,'.reviews/prd-guide-task-scope.json'),'utf8')).selfCheckRules,5);
|
|
111
111
|
assert.equal(fs.existsSync(path.join(dir,'.cm-specs-status')),false);
|
|
112
112
|
send({requestId:'package',operation:'final_review_package',stage:'split',feature:'1.guide'});
|
|
113
113
|
}else if(message.requestId==='package'){
|
|
@@ -67,7 +67,7 @@ test('the host binds both draft entries to the operation rule',()=>{
|
|
|
67
67
|
assert.match(drive,/ctx\.state\.active\?\.selfCheckRules\?\?1:prdSessionVersions\(ctx\.state,ctx\.specs\)\.selfCheckRules/);
|
|
68
68
|
assert.equal([...host.matchAll(/selfCheckRules:\(\)=>session\.selfCheckRules\(\)/g)].length,2);
|
|
69
69
|
const change=fs.readFileSync(path.join(root,'runtime/js/cm-prd/change.mjs'),'utf8');
|
|
70
|
-
assert.match(change,/inspectPrdChangeProposal\(state\.before,response,state\.selected,config,\{rules:selfCheckRules\(\)\}\)/);
|
|
70
|
+
assert.match(change,/inspectPrdChangeProposal\(state\.before,response,state\.selected,config,\{rules:selfCheckRules\(\),parts:state\.parts\}\)/);
|
|
71
71
|
});
|
|
72
72
|
|
|
73
73
|
// Design 3.7: a session binds the task grammar and self-check rule when it is created;
|
|
@@ -108,7 +108,7 @@ test('a session binding outside the known versions is refused',t=>{
|
|
|
108
108
|
const {dir,entry}=specs(t),sessionId='prd-invalid-fixture',open=()=>openPrdSession({specs:dir,sessionId,identity:{entry,runtime:'codex'}});
|
|
109
109
|
created(open);
|
|
110
110
|
for(const change of [state=>{delete state.taskGrammar;},state=>{state.taskGrammar=1;},state=>{state.taskGrammar=TASK_GRAMMAR+1;},
|
|
111
|
-
state=>{state.selfCheckRules=
|
|
111
|
+
state=>{state.selfCheckRules=7;},state=>{state.selfCheckRules='3';},state=>{state.selfCheckRules=6;}]){
|
|
112
112
|
const file=stateFile(dir,sessionId),bytes=fs.readFileSync(file);edit(file,change);
|
|
113
113
|
assert.throws(open,/prd_session_versions_invalid/);fs.writeFileSync(file,bytes,{mode:0o600});
|
|
114
114
|
}
|
|
@@ -118,25 +118,26 @@ test('the historical rule set lists rule 3 explicitly, so raising the current ru
|
|
|
118
118
|
for(const rules of [3,2,1,PRD_SELF_CHECK_RULES])assert.ok(PRD_SELF_CHECK_RULE_VERSIONS.includes(rules));
|
|
119
119
|
assert.equal(new Set(PRD_SELF_CHECK_RULE_VERSIONS).size,PRD_SELF_CHECK_RULE_VERSIONS.length);
|
|
120
120
|
const source=fs.readFileSync(path.join(root,'runtime/js/cm-prd/self-check.mjs'),'utf8');
|
|
121
|
-
assert.match(source,/new Set\(\[PRD_SELF_CHECK_RULES,3,2,1\]\)/);
|
|
121
|
+
assert.match(source,/new Set\(\[PRD_SELF_CHECK_RULES,PRD_SELF_CHECK_LEGACY_GRAMMAR_RULES,4,3,2,1\]\)/);
|
|
122
122
|
assert.doesNotMatch(source,/\[PRD_SELF_CHECK_RULES,2,1\]|\[1,2,PRD_SELF_CHECK_RULES\]/);
|
|
123
123
|
});
|
|
124
124
|
|
|
125
|
-
test('a new session binds grammar 3 only where the specs directory has none or grammar 3; earlier grammars keep 2
|
|
125
|
+
test('a new session binds grammar 3 only where the specs directory has none or grammar 3; earlier grammars keep 2 with rule 6',t=>{
|
|
126
126
|
const write=(dir,status)=>fs.writeFileSync(path.join(dir,'.cm-specs-status'),JSON.stringify({status:'approved',features:[],specFiles:[],approval:{response:'开始',at:'2026-10-27T00:00:00.000Z'},...status})+'\n');
|
|
127
127
|
const fresh=specs(t).dir;
|
|
128
128
|
assert.deepEqual(prdSessionVersions(null,fresh),{taskGrammar:TASK_GRAMMAR,selfCheckRules:PRD_SELF_CHECK_RULES});
|
|
129
129
|
const g3=specs(t).dir;write(g3,{taskGrammar:3});
|
|
130
130
|
assert.deepEqual(prdSessionVersions(null,g3),{taskGrammar:3,selfCheckRules:PRD_SELF_CHECK_RULES});
|
|
131
131
|
const g2=specs(t).dir;write(g2,{taskGrammar:2});
|
|
132
|
-
assert.deepEqual(prdSessionVersions(null,g2),{taskGrammar:2,selfCheckRules:
|
|
132
|
+
assert.deepEqual(prdSessionVersions(null,g2),{taskGrammar:2,selfCheckRules:6});
|
|
133
133
|
const g1=specs(t).dir;write(g1,{});
|
|
134
|
-
assert.deepEqual(prdSessionVersions(null,g1),{taskGrammar:2,selfCheckRules:
|
|
134
|
+
assert.deepEqual(prdSessionVersions(null,g1),{taskGrammar:2,selfCheckRules:6});
|
|
135
135
|
const {dir,entry}=specs(t);write(dir,{taskGrammar:2});
|
|
136
136
|
const session=openPrdSession({specs:dir,sessionId:'prd-g2-fixture',identity:{entry,runtime:'codex'}});
|
|
137
137
|
session.checkpoint(null);
|
|
138
138
|
const state=JSON.parse(fs.readFileSync(path.join(dir,'.reviews/prd-sessions/prd-g2-fixture/state.json'),'utf8'));
|
|
139
|
-
assert.deepEqual([state.taskGrammar,state.selfCheckRules],[2,
|
|
139
|
+
assert.deepEqual([state.taskGrammar,state.selfCheckRules],[2,6]);
|
|
140
|
+
// A state recorded before rule 6 keeps rule 3 (no exemption) and still opens.
|
|
140
141
|
});
|
|
141
142
|
test('rule 4 refuses a task that waits for the session task, directly or transitively',()=>{
|
|
142
143
|
const draft=deps=>({draftDigest:'d'.repeat(64),features:[{directory:'1.walk',name:'walk',documents:[
|
|
@@ -200,7 +201,7 @@ test('a sessionTasks-only re-check reports a bad, repeated or stray developer li
|
|
|
200
201
|
|
|
201
202
|
// R1-03: re-checks of saved files (correction, disposition, summary, driver) run
|
|
202
203
|
// outside the saving operation; the task-scope record carries a rule-4 save's rule.
|
|
203
|
-
test('a save records rule 4 for the re-checks; an earlier rule or an operation without a rule keeps the old record',t=>{
|
|
204
|
+
test('a save records the session rule (4 or later) for the re-checks; an earlier rule or an operation without a rule keeps the old record',t=>{
|
|
204
205
|
const {dir,entry}=specs(t),sessionId='prd-record-fixture',open=()=>openPrdSession({specs:dir,sessionId,identity:{entry,runtime:'codex'}});
|
|
205
206
|
const tasks=['- [ ] T-001: Build',' - 范围: `src/a.js`','- [ ] T-002: Walk',' - 范围: `docs/qa.md`',' - 开发: 会话',''].join('\n');
|
|
206
207
|
const feature=content=>({directory:'1.walk',name:'walk',documents:[
|
|
@@ -215,8 +216,8 @@ test('a save records rule 4 for the re-checks; an earlier rule or an operation w
|
|
|
215
216
|
let session=open();
|
|
216
217
|
try{session.begin({requestId:'r1',operation:'save_draft'},null,{selfCheckRules:session.versions().selfCheckRules});}finally{session.close();}
|
|
217
218
|
save();
|
|
218
|
-
assert.deepEqual(JSON.parse(fs.readFileSync(record,'utf8')),{version:1,enforced:true,exempt:[],selfCheckRules:
|
|
219
|
-
assert.deepEqual(prdTaskScopeOptions(dir,'1.walk'),{scopes:{'1.walk':{exempt:[]}},sessionTasks:['1.walk']});
|
|
219
|
+
assert.deepEqual(JSON.parse(fs.readFileSync(record,'utf8')),{version:1,enforced:true,exempt:[],selfCheckRules:PRD_SELF_CHECK_RULES});
|
|
220
|
+
assert.deepEqual(prdTaskScopeOptions(dir,'1.walk'),{scopes:{'1.walk':{exempt:[]}},sessionTasks:['1.walk'],inapplicableAcceptance:['1.walk']});
|
|
220
221
|
assert.deepEqual(recheck(tasks),[]);
|
|
221
222
|
assert.deepEqual(recheck(moved),['session_task_not_final']);
|
|
222
223
|
assert.deepEqual(recheck(second),['session_task_multiple']);
|
|
@@ -232,8 +233,19 @@ test('a save records rule 4 for the re-checks; an earlier rule or an operation w
|
|
|
232
233
|
// Rule 3 adds nothing beyond the scope record, so its save keeps the old bytes too.
|
|
233
234
|
recordPrdTaskScopes(dir,[feature(tasks)],{},{selfCheckRules:3});
|
|
234
235
|
assert.equal(fs.readFileSync(record,'utf8'),JSON.stringify({version:1,enforced:true,exempt:[]})+'\n');
|
|
235
|
-
for(const value of [3,
|
|
236
|
+
for(const value of [3,7,'4']){
|
|
236
237
|
fs.writeFileSync(record,JSON.stringify({version:1,enforced:true,exempt:[],selfCheckRules:value})+'\n',{mode:0o600});
|
|
237
238
|
assert.throws(()=>prdTaskScopeOptions(dir,'1.walk'),/prd_task_scope_record_invalid/);
|
|
238
239
|
}
|
|
239
240
|
});
|
|
241
|
+
// Rule 6 is rule 3 plus the NOT_APPLICABLE exemption only: a `开发:` line stays prose, exactly as under rule 3
|
|
242
|
+
// (Codex review a9babbb, minor: a rule-6 grammar-3 reading would otherwise pass every other test).
|
|
243
|
+
test('rule 6 keeps 开发 lines as prose and otherwise reports exactly what rule 3 reports',()=>{
|
|
244
|
+
const docs=tasks=>({draftDigest:'e'.repeat(64),features:[{directory:'1.walk',name:'walk',documents:[
|
|
245
|
+
{path:'requirements.md',content:'## 功能需求\n1. [F-001] Walk\n- [ ] [AC-001] Walk it.'},{path:'design.md',content:'## 方案摘要\nx'},{path:'tasks.md',content:tasks}]}]});
|
|
246
|
+
const misplaced=['- [ ] T-001: Build',' - 范围: `src/a.js`',' - 开发: 会话','- [ ] T-002: Walk',' - 范围: `docs/qa.md`',''].join('\n');
|
|
247
|
+
const codes=rules=>checkPrdDraftMechanics(docs(misplaced),{rules}).findings.map(item=>item.code).sort();
|
|
248
|
+
assert.deepEqual(codes(6),codes(3));
|
|
249
|
+
assert.ok(!codes(6).includes('session_task_not_final'));
|
|
250
|
+
assert.ok(codes(5).includes('session_task_not_final'));
|
|
251
|
+
});
|
|
@@ -75,7 +75,7 @@ test('an ordinary draft gets the same report under both rules; records match onl
|
|
|
75
75
|
assert.ok(matchesPrdDraftMechanics(odd,legacy));
|
|
76
76
|
assert.ok(matchesPrdDraftMechanics(odd,checkPrdDraftMechanics(odd,R2)));
|
|
77
77
|
assert.ok(!matchesPrdDraftMechanics(odd,{...legacy,status:'failed'}));
|
|
78
|
-
assert.throws(()=>checkPrdDraftMechanics(odd,{rules:
|
|
78
|
+
assert.throws(()=>checkPrdDraftMechanics(odd,{rules:7}),{code:'prd_self_check_rules_invalid'});
|
|
79
79
|
});
|
|
80
80
|
test('a self-check revision recorded under rule 1 still verifies after rule 2',()=>{
|
|
81
81
|
const sha=value=>createHash('sha256').update(value).digest('hex');
|
|
@@ -127,3 +127,26 @@ test('a rule-3 report recorded with the earlier missing-scope hint still matches
|
|
|
127
127
|
const forged={...current,findings:current.findings.map(item=>({...item,reason:{...item.reason,expected:'other'}}))};
|
|
128
128
|
assert.equal(matchesPrdDraftMechanics(missing,forged),false);
|
|
129
129
|
});
|
|
130
|
+
// An acceptance item marked NOT_APPLICABLE right after its id has no executable expectation, so from
|
|
131
|
+
// rule 5 it needs no case. Rules 1-4 keep their exact old reports; a passing mention, a marker inside a
|
|
132
|
+
// strict fence, or another plain declaration of the same id still requires coverage (Wue specs8 AC-012).
|
|
133
|
+
test('rule 5: an acceptance item marked NOT_APPLICABLE after its id needs no covering case',()=>{
|
|
134
|
+
const withRequirements=content=>{const value=draft();value.features[0].documents[0]={path:'requirements.md',content};return value;};
|
|
135
|
+
const codes=(content,options={rules:PRD_SELF_CHECK_RULES})=>checkPrdDraftMechanics(withRequirements(content),options).findings.map(x=>x.code);
|
|
136
|
+
const base='- [ ] [AC-001] Behavior works.\n';
|
|
137
|
+
for(const line of ['- [ ] [AC-002] NOT_APPLICABLE:本期不做(依据)','- [ ] [AC-002]: NOT_APPLICABLE','- AC-002 NOT_APPLICABLE'])
|
|
138
|
+
assert.ok(!codes(base+line).includes('acceptance_test_coverage_missing'),line);
|
|
139
|
+
for(const line of ['- [ ] [AC-002] Later work, not NOT_APPLICABLE','- [ ] [AC-002] NOT_APPLICABLEX','- [ ] [AC-002] Real behavior',
|
|
140
|
+
'- [ ] [AC-002] Real behavior\n- [ ] [AC-002] NOT_APPLICABLE:冲突声明',
|
|
141
|
+
'- [ ] [AC-002] Actual behavior must work.\n```md\n```not-a-closing-fence\n- [ ] [AC-002] NOT_APPLICABLE:仅为围栏中的示例\n```',
|
|
142
|
+
// Strict fences alone (no plain AC-002 to fall back on): a marker still inside a fence is no declaration.
|
|
143
|
+
'```md\n```not-a-closing-fence\n- [ ] [AC-002] NOT_APPLICABLE:仅为围栏中的示例\n```',
|
|
144
|
+
'```md\n```\u00a0\n- [ ] [AC-002] NOT_APPLICABLE:仅为围栏中的示例\n```'])
|
|
145
|
+
assert.ok(codes(base+line).includes('acceptance_test_coverage_missing'),line);
|
|
146
|
+
for(const rules of [1,2,3,4])assert.ok(codes(base+'- [ ] [AC-002] NOT_APPLICABLE:依据',{rules}).includes('acceptance_test_coverage_missing'),`rule ${rules}`);
|
|
147
|
+
// A saved rule-5 record carries the exemption into re-checks that pass no rule.
|
|
148
|
+
assert.ok(!codes(base+'- [ ] [AC-002] NOT_APPLICABLE:依据',{inapplicableAcceptance:['1.sample']}).includes('acceptance_test_coverage_missing'));
|
|
149
|
+
const referencing=structuredClone(contract);referencing.cases[0].acIds=['AC-001','AC-002'];
|
|
150
|
+
const value=draft(undefined,referencing);value.features[0].documents[0].content=base+'- [ ] [AC-002] NOT_APPLICABLE:依据';
|
|
151
|
+
assert.equal(checkPrdDraftMechanics(value,{rules:PRD_SELF_CHECK_RULES}).status,'mechanical_subset_passed');
|
|
152
|
+
});
|
|
@@ -15,6 +15,12 @@ import {approveCmAiSpecs} from '../runtime/js/cm-ai/cm-ai-admission.mjs';
|
|
|
15
15
|
import {loadConfig} from './cm-workflow-config.mjs';
|
|
16
16
|
import {TASK_GRAMMAR} from '../runtime/js/spec-task-line.mjs';
|
|
17
17
|
import {writeSpecsStatus} from '../runtime/js/specs-status.mjs';
|
|
18
|
+
// Spec approvals write a round ledger under CM_WORKFLOW_HOME; keep it off the real home.
|
|
19
|
+
if(!process.env.CM_WORKFLOW_HOME){
|
|
20
|
+
const isolatedHome=fs.mkdtempSync(path.join(os.tmpdir(),'cm-approval-home-'));
|
|
21
|
+
process.env.CM_WORKFLOW_HOME=isolatedHome;
|
|
22
|
+
process.on('exit',()=>fs.rmSync(isolatedHome,{recursive:true,force:true}));
|
|
23
|
+
}
|
|
18
24
|
const sha=content=>createHash('sha256').update(content).digest('hex');
|
|
19
25
|
function fixture(t,{pendingCorrection=false,mandatory=false}={}){
|
|
20
26
|
const specs=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-prd-summary-marks-')));
|
|
@@ -534,8 +534,12 @@ for(const size of [65536,65537,1024*1024+4])test(`design byte limit ${size} pres
|
|
|
534
534
|
|
|
535
535
|
test('new specification requires bound acceptance evidence while legacy receipt eligibility is retained',t=>{
|
|
536
536
|
const f=specificationFixture(t);
|
|
537
|
-
|
|
537
|
+
// Commands count only under an explicit declaration (acceptance-contract.mjs
|
|
538
|
+
// commandDeclaration); the shared fixture's bare verification line is prose.
|
|
539
|
+
f.writeSpec('tasks.md',fs.readFileSync(path.join(f.specsRoot,f.feature,'tasks.md'),'utf8').replace('T-001: implement','T-001: 必验: implement')
|
|
540
|
+
.replace('- T-001: node --test priority.test.mjs','- T-001: 运行:node --test priority.test.mjs'));f.approve();
|
|
538
541
|
const baseline=f.capture();
|
|
542
|
+
assert.deepEqual(baseline.specification.acceptanceContract.requiredCommands,[['node','--test','priority.test.mjs']]);
|
|
539
543
|
const legacyBaseline=captureReviewBaseline({root:f.code,identity,scope:['code.js'],requirements:['requirements.md']});
|
|
540
544
|
write(f.code,'code.js','after');
|
|
541
545
|
const contract=baseline.specification.acceptanceContract;
|
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
"invoke": {"mode": "direct", "when": "要结束或切换当前会话:请求写交接文档、交接摘要或接手说明,把当前进度和上下文留给新会话、新窗口或另一个 agent 接着做"},
|
|
27
27
|
"keywords": ["会话太长", "上下文太长", "上下文快满", "换个会话", "开个新会话", "新开一个会话", "context is getting long", "start a new session", "上下文不够了", "上下文要满了", "上下文快爆了", "上下文快用完", "下个会话接着做", "新会话接着做", "hand off to a new session", "running out of context", "context window is almost full", "continue in a new session"],
|
|
28
28
|
"reason": "先写交接摘要,再换新会话接着做",
|
|
29
|
-
"patterns": ["^(?=[\\s\\S]*(新会话|新的会话|下个会话|下一个会话|换(个|一个)?会话|开(个|一个)?新会话|(上下文|会话)((快|要)(满|爆|用完)|不够|满了|爆了|用完了|太长)))[\\s\\S]
|
|
29
|
+
"patterns": ["^(?=[\\s\\S]*(新会话|新的会话|下个会话|下一个会话|换(个|一个)?会话|开(个|一个)?新会话|(上下文|会话)((快|要)(满|爆|用完)|不够|满了|爆了|用完了|太长)|\\b(new|fresh|next|another) session|running out of context|context (window )?is (almost |getting )?(full|long)))[\\s\\S]*(交接|\\bhand-? ?off\\b)"]
|
|
30
30
|
},
|
|
31
31
|
{
|
|
32
32
|
"id": "multi-session-work",
|
|
@@ -156,6 +156,45 @@ export function loadRules({env=process.env,rulesFile=defaultRulesPath()}={}){
|
|
|
156
156
|
// Pasted logs and code are where stray keywords live, so fenced blocks never match.
|
|
157
157
|
export const stripCode=text=>text.replace(/```[\s\S]*?(?:```|$)/g,' ');
|
|
158
158
|
|
|
159
|
+
// Keyword-fallback guards for invoke rules only (方案-否定句 2026-11-16). Hints and the Jev
|
|
160
|
+
// path are untouched: changing what Jev is sent would void the recorded exam answers.
|
|
161
|
+
// Real misfire: "不要换个会话,继续当前任务" told the model to start handoff.
|
|
162
|
+
// Quoted or inline-code words are being talked about, not asked for. ASCII ' is left
|
|
163
|
+
// alone because English contractions use it.
|
|
164
|
+
const QUOTED=[/`[^`\n]*`/g,/“[^”]*”/g,/「[^」]*」/g,/『[^』]*』/g,/"[^"\n]*"/g];
|
|
165
|
+
export const stripQuoted=text=>QUOTED.reduce((out,re)=>out.replace(re,' '),text);
|
|
166
|
+
// A negation masks only the few characters (Chinese) or words (English) right after it,
|
|
167
|
+
// within its own clause: "不要继续当前任务,换个会话交接" still asks for a handoff.
|
|
168
|
+
// "别忘了/不要忘了/别忘记" mean "do", so a negation followed by 忘 is not one.
|
|
169
|
+
export const NEGATION_WINDOW={zh:4,en:3};
|
|
170
|
+
const CLAUSE_END=/[,,。.!!??;;::\n]/;
|
|
171
|
+
// A lone 别 inside a word (别人、特别、分别、区别、告别、别名…) is not a negation (review r1),
|
|
172
|
+
// nor are A-not-A questions (要不要、用不用、想不想) or "why not" (review r2).
|
|
173
|
+
const ZH_NEGATION=/(?:先别|(?<!(?<!只)要)不要|(?<!用)不用|(?<!想)不想|无需|不必|(?<![特分区识级类个告差辨鉴性派道送判甄离])别(?![人处的致墅名扭样具]))(?!忘)/g;
|
|
174
|
+
const EN_NEGATION=/\b(?:(?<!why\s+)don['’]?t|do not|no need to|(?<!why\s+)not)\b/g;
|
|
175
|
+
const EN_WORD=/^[ \t]+[^\s,,。.!!??;;::]+/;
|
|
176
|
+
export function maskNegated(text){
|
|
177
|
+
let out=text;
|
|
178
|
+
const blank=(from,to)=>{out=out.slice(0,from)+' '.repeat(to-from)+out.slice(to);};
|
|
179
|
+
for(const match of text.matchAll(ZH_NEGATION)){
|
|
180
|
+
const start=match.index+match[0].length;
|
|
181
|
+
let end=start;
|
|
182
|
+
while(end<text.length&&end-start<NEGATION_WINDOW.zh&&!CLAUSE_END.test(text[end]))end++;
|
|
183
|
+
blank(start,end);
|
|
184
|
+
}
|
|
185
|
+
for(const match of text.matchAll(EN_NEGATION)){
|
|
186
|
+
const start=match.index+match[0].length;
|
|
187
|
+
let end=start;
|
|
188
|
+
for(let words=0;words<NEGATION_WINDOW.en;words++){
|
|
189
|
+
const next=EN_WORD.exec(text.slice(end));
|
|
190
|
+
if(!next)break;
|
|
191
|
+
end+=next[0].length;
|
|
192
|
+
}
|
|
193
|
+
blank(start,end);
|
|
194
|
+
}
|
|
195
|
+
return out;
|
|
196
|
+
}
|
|
197
|
+
|
|
159
198
|
// A user regex can backtrack for minutes; it runs in a context with a hard time
|
|
160
199
|
// budget, and on timeout no pattern counts as matched (keywords still do).
|
|
161
200
|
export function patternMatches(rules,text,budget=PATTERN_BUDGET_MS){
|
|
@@ -269,8 +308,31 @@ export async function pickInvoke({prompt,rules,host,env,authorCheck,judgeModule,
|
|
|
269
308
|
choices:candidates.map(rule=>({skill:rule.skill,when:rule.invoke.when,near:rule.invoke.near}))});
|
|
270
309
|
}
|
|
271
310
|
if(!verdict.error)return {rule:candidates.find(rule=>rule.skill===verdict.skill)??null,via:'jev',candidates};
|
|
272
|
-
const
|
|
273
|
-
|
|
311
|
+
const fallback={via:'keyword',error:verdict.error,candidates};
|
|
312
|
+
const unquoted=stripQuoted(stripCode(prompt.toLowerCase()));
|
|
313
|
+
const guarded=splitHits(candidates,maskNegated(unquoted));
|
|
314
|
+
// Guards only take matches away: masking can also hide a pattern's exclusion words
|
|
315
|
+
// ("不要重构一下,架构太乱了"), so a guarded hit counts only where the plain text hit too.
|
|
316
|
+
const plain=splitHits(candidates,stripCode(prompt.toLowerCase()));
|
|
317
|
+
const raw=plain.map(hit=>hit.keyword||hit.pattern);
|
|
318
|
+
const index=guarded.findIndex((hit,at)=>raw[at]&&(hit.keyword||hit.pattern));
|
|
319
|
+
if(index>=0){
|
|
320
|
+
const rule=candidates[index];
|
|
321
|
+
// A rule with patterns keeps its mode only when a pattern matched both before and after
|
|
322
|
+
// the guards; its bare keywords ("换个会话" without "交接") make the model ask first.
|
|
323
|
+
const strong=guarded[index].pattern&&plain[index].pattern;
|
|
324
|
+
return {...fallback,rule,mode:rule.patterns.length&&!strong?'ask':rule.invoke.mode};
|
|
325
|
+
}
|
|
326
|
+
// What the guards held back, for the log (rule and reason only, never the text).
|
|
327
|
+
const first=raw.findIndex(Boolean);
|
|
328
|
+
if(first<0)return {...fallback,rule:null};
|
|
329
|
+
const unguarded=splitHits([candidates[first]],unquoted)[0];
|
|
330
|
+
return {...fallback,rule:null,suppressed:{rule:candidates[first].id,skill:candidates[first].skill,
|
|
331
|
+
reason:unguarded.keyword||unguarded.pattern?'negated':'quoted'}};
|
|
332
|
+
}
|
|
333
|
+
function splitHits(rules,text){
|
|
334
|
+
const byPattern=patternMatches(rules,text);
|
|
335
|
+
return rules.map((rule,index)=>({keyword:rule.keywords.some(word=>text.includes(word)),pattern:byPattern[index]}));
|
|
274
336
|
}
|
|
275
337
|
|
|
276
338
|
export const messageText=(hints,host)=>
|
|
@@ -304,13 +366,14 @@ export async function hook(input,{env=process.env,host='claude',rulesFile=defaul
|
|
|
304
366
|
// An installed invoke rule is handled above only; the rest hint as before.
|
|
305
367
|
const handled=new Set(invoked.candidates.map(rule=>rule.id));
|
|
306
368
|
const hints=short?pickHints({prompt,rules:loaded.rules.filter(rule=>!handled.has(rule.id)),host,env,hinted:state.hinted,authorCheck}):[];
|
|
307
|
-
const start=invoked.rule?{skill:invoked.rule.skill,mode:invoked.rule.invoke.mode,reason:invoked.rule.reason}:null;
|
|
369
|
+
const start=invoked.rule?{skill:invoked.rule.skill,mode:invoked.mode??invoked.rule.invoke.mode,reason:invoked.rule.reason}:null;
|
|
308
370
|
// Bookkeeping failures cost the statistics, never the hint itself.
|
|
309
371
|
try{
|
|
310
372
|
for(const item of adopted)appendLog(env,{t:time,event:'adopted',host,rule:item.rule,skill:item.skill});
|
|
311
373
|
// A missing key is the normal state for most users, not worth a line per message.
|
|
312
374
|
if(invoked.error&&!['no-key','off'].includes(invoked.error))appendLog(env,{t:time,event:'judge-error',host,error:invoked.error});
|
|
313
375
|
if(start)appendLog(env,{t:time,event:'invoke',host,rule:invoked.rule.id,skill:start.skill,mode:start.mode,via:invoked.via});
|
|
376
|
+
if(invoked.suppressed)appendLog(env,{t:time,event:'suppressed',host,...invoked.suppressed});
|
|
314
377
|
for(const hint of hints)appendLog(env,{t:time,event:'hint',host,rule:hint.rule,skill:hint.skill});
|
|
315
378
|
}catch{/* 统计丢一条 */}
|
|
316
379
|
// Session state is never removed (decided 2026-10-24): a session resumed months
|
|
@@ -829,3 +829,99 @@ test('the shipped table marks only handoff direct and the two heavy skills ask',
|
|
|
829
829
|
assert.deepEqual(Object.fromEntries(rules.filter(rule=>rule.invoke).map(rule=>[rule.skill,rule.invoke.mode])),
|
|
830
830
|
{handoff:'direct',wayfinder:'ask','improve-codebase-architecture':'ask'});
|
|
831
831
|
});
|
|
832
|
+
|
|
833
|
+
// ---- keyword-fallback guards (方案-否定句 2026-11-16) ----
|
|
834
|
+
// Real misfire: "不要换个会话,继续当前任务" told the model to start handoff (Jev off).
|
|
835
|
+
function guarded(t,rules=readJson(defaultRulesPath()).value){
|
|
836
|
+
const f=fixture(t,{rules,local:{judge:false},authorNames:['handoff','wayfinder','improve-codebase-architecture'],
|
|
837
|
+
authorSkills:[['.claude/skills','handoff'],['.claude/skills','wayfinder'],['.claude/skills','improve-codebase-architecture']]});
|
|
838
|
+
let session=0;
|
|
839
|
+
const run=async prompt=>{
|
|
840
|
+
const out=await hook({prompt,session_id:`g${session++}`},{env:f.env,host:'claude',rulesFile:f.rulesFile,now:NOW,
|
|
841
|
+
loadAuthor:async()=>({...(await loadAuthorCheck()),skills:f.authorOptions.skills,license:f.authorOptions.license})});
|
|
842
|
+
const parsed=out?JSON.parse(out):null;
|
|
843
|
+
if(!parsed?.hookSpecificOutput)return null;
|
|
844
|
+
const line=parsed.systemMessage.split('\n')[0];
|
|
845
|
+
const ask=/先问你要不要用 \/(\S+)$/.exec(line);
|
|
846
|
+
return ask?`ask:${ask[1]}`:`direct:${/已让模型用 \/(\S+)$/.exec(line)[1]}`;
|
|
847
|
+
};
|
|
848
|
+
return {...f,run};
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
test('guards: negation, quotes and bare keywords decide direct, ask or nothing for the shipped handoff rule',async t=>{
|
|
852
|
+
const f=guarded(t);
|
|
853
|
+
const cases=[
|
|
854
|
+
['不要换个会话,继续当前任务',null],
|
|
855
|
+
['不要继续当前任务,换个会话交接一下','direct:handoff'],
|
|
856
|
+
['上下文快满了,帮我写个交接','direct:handoff'],
|
|
857
|
+
['上下文快满了','ask:handoff'],
|
|
858
|
+
['不用交接,换个会话就行','ask:handoff'],
|
|
859
|
+
['我们讨论 “换个会话” 这个关键词',null],
|
|
860
|
+
['`换个会话` 是个关键词',null],
|
|
861
|
+
['别忘了换个会话前先交接','direct:handoff'],
|
|
862
|
+
['先别管测试,换个会话交接吧','direct:handoff'],
|
|
863
|
+
["don't start a new session, keep going",null],
|
|
864
|
+
['/handoff 下个会话接着做',null],
|
|
865
|
+
['帮我把这个大改造拆成多个会话','ask:wayfinder'],
|
|
866
|
+
// "handoff" counts as 交接, and English session phrases count as 会话 (user decision 2026-11-17).
|
|
867
|
+
['上下文快满了,写个 handoff 吧','direct:handoff'],
|
|
868
|
+
['context window is almost full, write a handoff doc for a fresh session','direct:handoff'],
|
|
869
|
+
['hand off to a new session','direct:handoff'],
|
|
870
|
+
["don't hand off, start a new session",'ask:handoff'],
|
|
871
|
+
['我们讨论 handoff 这个技能',null],
|
|
872
|
+
];
|
|
873
|
+
const got=[];
|
|
874
|
+
for(const [prompt] of cases)got.push([prompt,await f.run(prompt)]);
|
|
875
|
+
assert.deepEqual(got,cases);
|
|
876
|
+
});
|
|
877
|
+
|
|
878
|
+
test('guards: window edges, case, everyday words with 别, and guards never add a match (review r1)',async t=>{
|
|
879
|
+
const f=guarded(t);
|
|
880
|
+
const cases=[
|
|
881
|
+
['跟别人换个会话交接','direct:handoff'],
|
|
882
|
+
['特别是上下文快满了,帮我写交接','direct:handoff'],
|
|
883
|
+
['你别换个会话,继续',null],
|
|
884
|
+
// Chinese: a hit starting within 4 characters of the negation is masked, from the 5th it is not.
|
|
885
|
+
['不要啊啊啊上下文快满了',null],
|
|
886
|
+
['不要啊啊啊啊上下文快满了','ask:handoff'],
|
|
887
|
+
// English: up to 3 words after the negation.
|
|
888
|
+
["don't a b start a new session",null],
|
|
889
|
+
["don't a b c start a new session",'ask:handoff'],
|
|
890
|
+
['no need to start a new session',null],
|
|
891
|
+
['START A NEW SESSION','ask:handoff'],
|
|
892
|
+
// Masking a pattern's exclusion words must not create a new trigger.
|
|
893
|
+
// A-not-A questions and "why not" are not negations (review r2); plain "not"/"do not" are.
|
|
894
|
+
['要不要换个会话交接','direct:handoff'],
|
|
895
|
+
['用不用换个会话交接','direct:handoff'],
|
|
896
|
+
['想不想换个会话交接','direct:handoff'],
|
|
897
|
+
['why not start a new session','ask:handoff'],
|
|
898
|
+
["why don't we start a new session",'ask:handoff'],
|
|
899
|
+
['只要不要换个会话交接就行',null],
|
|
900
|
+
['i will not start a new session',null],
|
|
901
|
+
['do not start a new session',null],
|
|
902
|
+
['用别名换个会话交接','direct:handoff'],
|
|
903
|
+
['道别前换个会话交接','direct:handoff'],
|
|
904
|
+
['不要重构一下,架构太乱了',null],
|
|
905
|
+
['架构太乱了,我说的不是`重构一下`',null],
|
|
906
|
+
];
|
|
907
|
+
const got=[];
|
|
908
|
+
for(const [prompt] of cases)got.push([prompt,await f.run(prompt)]);
|
|
909
|
+
assert.deepEqual(got,cases);
|
|
910
|
+
});
|
|
911
|
+
|
|
912
|
+
test('guards: what they hold back is logged with rule and reason only, never the text',async t=>{
|
|
913
|
+
const f=guarded(t);
|
|
914
|
+
await f.run('不要换个会话,继续当前任务');
|
|
915
|
+
await f.run('我们讨论 “换个会话” 这个关键词');
|
|
916
|
+
assert.deepEqual(f.log().filter(entry=>entry.event==='suppressed').map(({rule,skill,reason})=>({rule,skill,reason})),[
|
|
917
|
+
{rule:'long-session',skill:'handoff',reason:'negated'},
|
|
918
|
+
{rule:'long-session',skill:'handoff',reason:'quoted'}]);
|
|
919
|
+
assert.doesNotMatch(fs.readFileSync(logFile(f.env),'utf8'),/换个会话|继续当前任务/);
|
|
920
|
+
});
|
|
921
|
+
|
|
922
|
+
test('guards: masking a pattern\'s exclusion words never upgrades ask to direct (review r2)',async t=>{
|
|
923
|
+
const f=guarded(t,{version:1,rules:[{id:'long-session',skill:'handoff',author:true,keywords:['换个会话'],
|
|
924
|
+
patterns:['^(?![\\s\\S]*只是问问)[\\s\\S]*会话'],reason:'写交接',invoke:{mode:'direct',when:'写交接'}}]});
|
|
925
|
+
assert.equal(await f.run('换个会话,不要只是问问'),'ask:handoff');
|
|
926
|
+
assert.equal(await f.run('换个会话吧'),'direct:handoff');
|
|
927
|
+
});
|