@aibyzero/cm-workflow 0.18.0 → 0.20.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.
- package/.codex-plugin/plugin.json +1 -1
- package/AGENTS.md +8 -0
- package/CHANGELOG.md +26 -0
- package/README.md +14 -1
- package/VERSION +1 -1
- package/docs/architecture.md +3 -0
- package/docs/cm-acceptance-completion.md +185 -0
- package/docs/installation.md +1 -1
- package/package.json +1 -1
- package/runtime/js/autonomy.mjs +308 -0
- package/runtime/js/check-coverage.mjs +130 -0
- package/runtime/js/cm-ai/acceptance-contract.mjs +252 -0
- package/runtime/js/cm-ai/claude-developer-proposal.schema.json +18 -0
- package/runtime/js/cm-ai/cm-ai-admission.mjs +53 -12
- package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +10 -6
- package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +8 -3
- package/runtime/js/cm-ai/codex-developer-basic-output.schema.json +1 -1
- package/runtime/js/cm-ai/codex-developer-output.schema.json +1 -1
- package/runtime/js/cm-ai/completion-summary.mjs +187 -0
- package/runtime/js/cm-ai/control-policy.mjs +3 -1
- package/runtime/js/cm-ai/delivery-evidence.mjs +173 -0
- package/runtime/js/cm-ai/developer-adapter.mjs +4 -0
- package/runtime/js/cm-ai/drive-core.mjs +8 -3
- package/runtime/js/cm-ai/durable-runner-state.mjs +2 -2
- package/runtime/js/cm-ai/gate-bridge.mjs +13 -1
- package/runtime/js/cm-ai/host-conversation-execution.mjs +26 -14
- package/runtime/js/cm-ai/host-progress.mjs +2 -1
- package/runtime/js/cm-ai/log-rows.mjs +3 -2
- package/runtime/js/cm-ai/operator-guidance.mjs +110 -4
- package/runtime/js/cm-ai/requirement-evidence.mjs +4 -2
- package/runtime/js/cm-ai/review-package.mjs +2 -2
- package/runtime/js/cm-ai/specification-material.mjs +57 -12
- package/runtime/js/cm-ai/task-runner.mjs +38 -13
- package/runtime/js/cm-ai/verification-auto.mjs +6 -4
- package/runtime/js/cm-prd/acceptance-preview.mjs +203 -0
- package/runtime/js/cm-prd/change.mjs +17 -1
- package/runtime/js/cm-prd/summary.mjs +5 -0
- package/runtime/js/node-test-selection.mjs +38 -0
- package/runtime/js/notify.mjs +17 -8
- package/runtime/js/run-analysis.mjs +153 -0
- package/runtime/js/session-boundary.mjs +17 -5
- package/runtime/js/session-handoff.mjs +5 -2
- package/runtime/js/specs-status.mjs +4 -3
- package/scripts/cm-acceptance-preview.mjs +26 -0
- package/scripts/cm-acceptance-preview.test.mjs +156 -0
- package/scripts/cm-ai-acceptance-contract.test.mjs +185 -0
- package/scripts/cm-ai-admission.mjs +10 -2
- package/scripts/cm-ai-admission.test.mjs +151 -1
- package/scripts/cm-ai-blockage.test.mjs +120 -0
- package/scripts/cm-ai-checklist-coverage.test.mjs +5 -2
- package/scripts/cm-ai-completion-summary.test.mjs +154 -0
- package/scripts/cm-ai-conversation-entry-ops.test.mjs +8 -2
- package/scripts/cm-ai-progress.test.mjs +7 -0
- package/scripts/cm-ai-project-qa-gate.test.mjs +55 -4
- package/scripts/cm-ai-run.test.mjs +23 -1
- package/scripts/cm-ai-spec-rebind.test.mjs +51 -15
- package/scripts/cm-ai-verification-auto.test.mjs +33 -8
- package/scripts/cm-ai-verification-gate.test.mjs +1 -1
- package/scripts/cm-autonomy-acceptance.test.mjs +212 -0
- package/scripts/cm-autonomy-review-r1.test.mjs +93 -0
- package/scripts/cm-autonomy.mjs +96 -0
- package/scripts/cm-autonomy.test.mjs +163 -0
- package/scripts/cm-check-runtime.sh +3 -1
- package/scripts/cm-delivery-evidence.mjs +59 -0
- package/scripts/cm-delivery-evidence.test.mjs +177 -0
- package/scripts/cm-drive-liveness.test.mjs +6 -0
- package/scripts/cm-driver-light-import.test.mjs +32 -0
- package/scripts/cm-mandatory-check-coverage.test.mjs +82 -0
- package/scripts/cm-node-test-selection.test.mjs +108 -0
- package/scripts/cm-notify-read-drift.test.mjs +6 -3
- package/scripts/cm-notify.test.mjs +6 -0
- package/scripts/cm-prd-completion.test.mjs +12 -0
- package/scripts/cm-prd-host.mjs +3 -1
- package/scripts/cm-prd-host.test.mjs +18 -1
- package/scripts/cm-prd-summary.test.mjs +19 -4
- package/scripts/cm-review-inventory.test.mjs +21 -6
- package/scripts/cm-run-analysis.mjs +21 -0
- package/scripts/cm-run-analysis.test.mjs +120 -0
- package/scripts/cm-start-check.mjs +128 -6
- package/scripts/cm-start-check.test.mjs +163 -3
- package/scripts/cm-usage-report.py +8 -3
- package/scripts/cm019-r1-contract.test.mjs +137 -0
- package/scripts/cm019-review-gates.test.mjs +97 -0
- package/scripts/validate-public-repo.py +3 -0
- package/skills/cm-ai/references/N3-execute-task.md +1 -1
- package/skills/cm-ai/references/js-host.md +31 -1
- package/skills/cm-prd/SKILL.md +3 -2
- package/skills/cm-prd/references/change-mode.md +3 -2
- package/skills/cm-prd/references/js-change-recovery.md +14 -0
- package/skills/cm-prd/references/js-host.md +1 -0
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import test from 'node:test';
|
|
3
|
+
import {mandatoryCheckCoverage} from '../runtime/js/check-coverage.mjs';
|
|
4
|
+
|
|
5
|
+
const xcode = (...selection) => ['/usr/bin/xcodebuild', 'test', '-scheme', 'App', ...selection];
|
|
6
|
+
const coverage = (requiredTests, ...commands) => mandatoryCheckCoverage({requiredTests, commands});
|
|
7
|
+
|
|
8
|
+
test('frozen Xcode test selection rejects omitted classes and skipped methods', () => {
|
|
9
|
+
const required = ['AppUITests/OldTests', 'AppUITests/NewTests'];
|
|
10
|
+
assert.deepEqual(coverage(required, xcode('-only-testing:AppUITests/NewTests')),
|
|
11
|
+
{satisfied: false, missing: required, unverifiable: ['AppUITests/NewTests']});
|
|
12
|
+
assert.deepEqual(coverage(required, xcode('-only-testing:AppUITests')),
|
|
13
|
+
{satisfied:false,missing:required,unverifiable:required});
|
|
14
|
+
assert.equal(coverage(['AppUITests/OldTests'], xcode('-only-testing:AppUITests', '-skip-testing:AppUITests/OldTests/testExisting')).satisfied, false);
|
|
15
|
+
assert.deepEqual(coverage(['AppUITests/OldTests'], ['/usr/bin/xcrun', 'xcodebuild', ...xcode('-only-testing:AppUITests/OldTests').slice(1)]),
|
|
16
|
+
{satisfied:false,missing:['AppUITests/OldTests'],unverifiable:['AppUITests/OldTests']});
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
test('build, enumeration and values named test are not execution selection', () => {
|
|
20
|
+
for (const command of [xcode('-enumerate-tests'), xcode('-showBuildSettings'),
|
|
21
|
+
['/usr/bin/xcodebuild', '-resultBundlePath', 'test', 'build-for-testing']])
|
|
22
|
+
assert.equal(coverage(['AppUITests/OldTests'], command).satisfied, false, JSON.stringify(command));
|
|
23
|
+
assert.deepEqual(coverage(['AppUITests/OldTests'], xcode('-only-testing', 'AppUITests/OldTests')).unverifiable,
|
|
24
|
+
['AppUITests/OldTests']);
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
test('a wrapper mentioning a test or xcodebuild cannot prove mandatory coverage', () => {
|
|
28
|
+
for (const command of [['bash', 'checks.sh', 'AppUITests/OldTests'],
|
|
29
|
+
['echo', 'xcodebuild', 'test'], [process.execPath, 'wrapper.js', 'AppUITests/OldTests']]) {
|
|
30
|
+
const result = coverage(['AppUITests/OldTests'], command);
|
|
31
|
+
assert.deepEqual(result, {satisfied: false, missing: ['AppUITests/OldTests'], unverifiable: ['AppUITests/OldTests']});
|
|
32
|
+
}
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
test('direct Node test files and explicit node --test files are supported without substring matches', () => {
|
|
36
|
+
assert.equal(coverage(['test/a.test.js'], [process.execPath, 'test/a.test.js']).satisfied, true);
|
|
37
|
+
assert.equal(coverage(['test/a.test.js', 'test/b.test.js'], [process.execPath, '--test', './test/a.test.js', 'test/b.test.js']).satisfied, true);
|
|
38
|
+
assert.deepEqual(coverage(['test/a.test.js', 'test/b.test.js'], [process.execPath, '--test', 'test/a.test.js']),
|
|
39
|
+
{satisfied: false, missing: ['test/b.test.js'], unverifiable: []});
|
|
40
|
+
assert.equal(coverage(['test/a.test.js'], [process.execPath, '--test', 'test/a.test.js.bak']).satisfied, false);
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
test('Node filters, discovery, globs and unmodeled options remain unverifiable', () => {
|
|
44
|
+
for (const args of [['--test'], ['--test', 'test/*.test.js'], ['--test', '--test-name-pattern=easy', 'test/a.test.js'],
|
|
45
|
+
['--test', '--test-shard=1/2', 'test/a.test.js'], ['--test', '--test-only', 'test/a.test.js'],
|
|
46
|
+
['--eval', "require('./test/a.test.js')"]])
|
|
47
|
+
assert.deepEqual(coverage(['test/a.test.js'], [process.execPath, ...args]),
|
|
48
|
+
{satisfied: false, missing: ['test/a.test.js'], unverifiable: ['test/a.test.js']}, JSON.stringify(args));
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
test('commands from another test family cannot satisfy a frozen test identifier', () => {
|
|
52
|
+
assert.deepEqual(coverage(['test/a.test.js'], xcode()).unverifiable, ['test/a.test.js']);
|
|
53
|
+
assert.deepEqual(coverage(['AppUITests/OldTests.swift'], xcode()).unverifiable, ['AppUITests/OldTests.swift']);
|
|
54
|
+
assert.deepEqual(coverage(['AppUITests/OldTests'], [process.execPath, 'AppUITests/OldTests']).unverifiable, ['AppUITests/OldTests']);
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
test('approved subsets are respected; no contract obligations does not expand the gate', () => {
|
|
58
|
+
assert.deepEqual(coverage(['AppUITests/NewTests'], xcode('-only-testing:AppUITests/NewTests')),
|
|
59
|
+
{satisfied:false,missing:['AppUITests/NewTests'],unverifiable:['AppUITests/NewTests']});
|
|
60
|
+
assert.deepEqual(coverage([], ['bash', 'unknown.sh']), {satisfied: true, missing: [], unverifiable: []});
|
|
61
|
+
assert.deepEqual(coverage(['test/a.js']), {satisfied: false, missing: ['test/a.js'], unverifiable: []});
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
test('invalid frozen test identities are rejected and input is never mutated', () => {
|
|
65
|
+
for (const requiredTests of [null, [''], ['a', 'a'], ['../a'], ['/a'], ['a\0b']])
|
|
66
|
+
assert.throws(() => mandatoryCheckCoverage({requiredTests, commands: []}), {code: 'mandatory_check_contract_invalid'});
|
|
67
|
+
const requiredTests = Object.freeze(['test/a.test.js']);
|
|
68
|
+
const commands = Object.freeze([Object.freeze([process.execPath, '--test', 'test/a.test.js'])]);
|
|
69
|
+
assert.equal(mandatoryCheckCoverage({requiredTests, commands}).satisfied, true);
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
test('a program basename or PATH lookup is not a trusted test engine identity', () => {
|
|
73
|
+
for (const binary of ['node', './node', '/project/node'])
|
|
74
|
+
assert.deepEqual(coverage(['test/a.test.js'], [binary, '--test', 'test/a.test.js']).unverifiable, ['test/a.test.js']);
|
|
75
|
+
for (const binary of ['xcodebuild', '/project/xcodebuild'])
|
|
76
|
+
assert.deepEqual(coverage(['AppUITests/OldTests'], [binary, 'test']).unverifiable, ['AppUITests/OldTests']);
|
|
77
|
+
});
|
|
78
|
+
test('unmodeled Xcode configuration selectors and future flags remain unverifiable',()=>{
|
|
79
|
+
for(const args of [['-only-test-configuration','SmokeOnly'],['-skip-test-configuration','FullTests'],
|
|
80
|
+
['-testPlan','Subset'],['-future-filter','Easy'],['SWIFT_ACTIVE_COMPILATION_CONDITIONS=OMIT_TESTS']])
|
|
81
|
+
assert.deepEqual(coverage(['AppTests/ImportantTests'],xcode(...args)).unverifiable,['AppTests/ImportantTests']);
|
|
82
|
+
});
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import {spawnSync} from 'node:child_process';
|
|
6
|
+
import test from 'node:test';
|
|
7
|
+
import {selectedNodeTestFiles} from '../runtime/js/node-test-selection.mjs';
|
|
8
|
+
import {mandatoryCheckCoverage} from '../runtime/js/check-coverage.mjs';
|
|
9
|
+
import {createHostCheck} from '../runtime/js/cm-ai/host-check.mjs';
|
|
10
|
+
import {acceptanceCoverage} from '../runtime/js/cm-ai/acceptance-contract.mjs';
|
|
11
|
+
|
|
12
|
+
const files=['a.test.mjs','b.test.mjs'];
|
|
13
|
+
const argv=(...options)=>[process.execPath,'--test',...options,...files];
|
|
14
|
+
const coverage=command=>mandatoryCheckCoverage({requiredTests:files,commands:[command]});
|
|
15
|
+
const identity={repositoryId:'node-selection',runId:'native-fixture',taskId:'T-001',attempt:1};
|
|
16
|
+
const supported=spawnSync(process.execPath,['--help'],{encoding:'utf8'}).stdout;
|
|
17
|
+
|
|
18
|
+
test('native non-filtering options select exact explicit files without changing argv',()=>{
|
|
19
|
+
for(const options of [
|
|
20
|
+
['--test-concurrency=2'],['--test-concurrency','2'],
|
|
21
|
+
['--test-timeout=1000'],['--test-timeout','1000'],
|
|
22
|
+
...['tap','spec','dot'].flatMap(value=>[['--test-reporter',value],[`--test-reporter=${value}`]]),
|
|
23
|
+
['--test-reporter=tap','--test-reporter-destination=stdout'],
|
|
24
|
+
['--test-reporter','spec','--test-reporter-destination','stderr'],
|
|
25
|
+
['--test-concurrency=2','--test-timeout=1000','--test-reporter=dot','--'],
|
|
26
|
+
]){
|
|
27
|
+
const command=Object.freeze(argv(...options));
|
|
28
|
+
assert.deepEqual(selectedNodeTestFiles(command),files,JSON.stringify(options));
|
|
29
|
+
assert.deepEqual(coverage(command),{satisfied:true,missing:[],unverifiable:[]});
|
|
30
|
+
}
|
|
31
|
+
assert.deepEqual(selectedNodeTestFiles([process.execPath,'--test-reporter=tap','--test','./a.test.mjs']),['a.test.mjs']);
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
test('every supported option rejects absent, invalid or duplicate values',()=>{
|
|
35
|
+
const cases=[
|
|
36
|
+
['--test-concurrency'],['--test-timeout'],['--test-reporter'],['--test-reporter-destination'],
|
|
37
|
+
...['0','-1','1.5','Infinity','2147483648','01',''].flatMap(value=>[
|
|
38
|
+
[`--test-concurrency=${value}`],[`--test-timeout=${value}`]]),
|
|
39
|
+
['--test-reporter=./custom.mjs'],['--test-reporter=node:custom'],['--test-reporter='],
|
|
40
|
+
['--test-reporter-destination=stdout'],
|
|
41
|
+
['--test-reporter=tap','--test-reporter-destination=a.test.mjs'],
|
|
42
|
+
['--test-reporter=tap','--test-reporter-destination='],
|
|
43
|
+
['--test','--test'],
|
|
44
|
+
...[['--test-concurrency=1'],['--test-timeout=1000'],['--test-reporter=tap'],
|
|
45
|
+
['--test-reporter=tap','--test-reporter-destination=stdout']].map(options=>[...options,...options]),
|
|
46
|
+
];
|
|
47
|
+
for(const options of cases)assert.deepEqual(coverage(argv(...options)),
|
|
48
|
+
{satisfied:false,missing:files,unverifiable:files},JSON.stringify(options));
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
test('filters, npm wrappers, custom execution hooks and unknown options stay unverifiable',()=>{
|
|
52
|
+
for(const options of [
|
|
53
|
+
['--test-name-pattern=small'],['--test-skip-pattern=important'],['--test-shard=1/2'],['--test-only'],
|
|
54
|
+
['--test-rerun-failures=prior.json'],['--test-global-setup=setup.mjs'],['--test-isolation=none'],
|
|
55
|
+
['--import=preload.mjs'],['--require=preload.cjs'],['--experimental-config-file=config.json'],
|
|
56
|
+
['--test-update-snapshots'],['--future-filter=small'],['--test-reporter=tap','--test-only'],
|
|
57
|
+
])assert.deepEqual(coverage(argv(...options)).unverifiable,files,JSON.stringify(options));
|
|
58
|
+
for(const command of [['npm','test','--',...files],['npm','run','test','--',...files],
|
|
59
|
+
['node','--test',...files],['/project/node','--test',...files]])
|
|
60
|
+
assert.deepEqual(coverage(command).unverifiable,files);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
test('options stop at the first file and missing files remain missing',()=>{
|
|
64
|
+
for(const command of [[process.execPath,'--test','a.test.mjs','--test-concurrency=1','b.test.mjs'],
|
|
65
|
+
[process.execPath,'--test','*.test.mjs'],[process.execPath,'--test'],
|
|
66
|
+
[process.execPath,'--test-reporter=tap',...files],
|
|
67
|
+
[process.execPath,'--test','--','--test-only',...files]])
|
|
68
|
+
assert.deepEqual(coverage(command).unverifiable,files);
|
|
69
|
+
assert.deepEqual(coverage([process.execPath,'--test','--test-reporter=tap','./a.test.mjs']),
|
|
70
|
+
{satisfied:false,missing:['b.test.mjs'],unverifiable:[]});
|
|
71
|
+
assert.deepEqual(coverage([process.execPath,'--test','--test-reporter=tap','a.test.mjs.bak']),
|
|
72
|
+
{satisfied:false,missing:files,unverifiable:[]});
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
// Real native subprocesses, isolated temporary files, no npm or external access.
|
|
76
|
+
// Options unavailable in an older supported Node are not injected into user
|
|
77
|
+
// commands; here those specific executions are explicitly skipped.
|
|
78
|
+
for(const [name,options] of [
|
|
79
|
+
['concurrency',['--test-concurrency','1']],
|
|
80
|
+
['timeout',['--test-timeout=1000']],
|
|
81
|
+
['tap',['--test-reporter=tap']],['spec',['--test-reporter','spec']],['dot',['--test-reporter=dot']],
|
|
82
|
+
['destination',['--test-reporter=tap','--test-reporter-destination','stderr']],
|
|
83
|
+
['separator',['--test-reporter=tap','--',]],
|
|
84
|
+
])test(`actual host Node execution with ${name} preserves both selected files`,
|
|
85
|
+
{skip:!supported.includes(options[0].split('=')[0])},async()=>{
|
|
86
|
+
const cwd=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-node-selection-')));
|
|
87
|
+
try{
|
|
88
|
+
for(const [index,file] of files.entries())fs.writeFileSync(path.join(cwd,file),
|
|
89
|
+
`import test from 'node:test';import fs from 'node:fs';test('selected ${index}',()=>fs.writeFileSync('ran-${index}','yes'));\n`);
|
|
90
|
+
const command=argv(...options),check=createHostCheck({cwd,commands:[{id:'node-tests',command}],timeoutMs:10000});
|
|
91
|
+
const observed=await check({identity},{signal:new AbortController().signal});
|
|
92
|
+
assert.equal(observed[0].outcome,'passed');assert.deepEqual(observed[0].command,command);
|
|
93
|
+
for(let index=0;index<files.length;index++)assert.equal(fs.readFileSync(path.join(cwd,`ran-${index}`),'utf8'),'yes');
|
|
94
|
+
assert.equal(acceptanceCoverage({requiredTests:files,requiredCommands:[['node',...command.slice(1)]]},observed).satisfied,true);
|
|
95
|
+
}finally{fs.rmSync(cwd,{recursive:true,force:true});}
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
test('native command failure remains failure even when its file selection is modeled',async()=>{
|
|
99
|
+
const cwd=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-node-selection-fail-')));
|
|
100
|
+
try{
|
|
101
|
+
fs.writeFileSync(path.join(cwd,files[0]),"import test from 'node:test';test('failure',()=>{throw Error('fixture');});\n");
|
|
102
|
+
const command=[process.execPath,'--test','--test-reporter=tap',files[0]],
|
|
103
|
+
check=createHostCheck({cwd,commands:[{id:'node-tests',command}],timeoutMs:10000});
|
|
104
|
+
const observed=await check({identity},{signal:new AbortController().signal});
|
|
105
|
+
assert.equal(observed[0].outcome,'failed');
|
|
106
|
+
assert.equal(acceptanceCoverage({requiredTests:[files[0]],requiredCommands:[['node',...command.slice(1)]]},observed).satisfied,false);
|
|
107
|
+
}finally{fs.rmSync(cwd,{recursive:true,force:true});}
|
|
108
|
+
});
|
|
@@ -256,10 +256,13 @@ test('importing runtime/js/notify.mjs has no process-exit side effect, also when
|
|
|
256
256
|
assert.equal(plain.status,0,plain.stderr);assert.match(plain.stdout,/imported/);
|
|
257
257
|
// Simulated Node without import.meta.main: copy the whole import graph with
|
|
258
258
|
// every `import.meta.main` replaced by `undefined`, import that copy.
|
|
259
|
-
const copy=(files,dir)=>{for(const file of files){
|
|
260
|
-
const target=path.
|
|
259
|
+
const copy=(files,dir,root=dir)=>{for(const file of files){
|
|
260
|
+
const target=path.resolve(dir,file);
|
|
261
|
+
assert(target.startsWith(path.resolve(root)+path.sep),`copied module must stay inside the fixture: ${file}`);
|
|
262
|
+
fs.mkdirSync(path.dirname(target),{recursive:true});
|
|
261
263
|
fs.writeFileSync(target,fs.readFileSync(new URL(file,RUNTIME),'utf8').replaceAll('import.meta.main','undefined'));}};
|
|
262
|
-
const
|
|
264
|
+
const repositoryCopy=sandbox(t),runtimeCopy=path.join(repositoryCopy,'runtime/js');
|
|
265
|
+
copy(graph.concat(['notify-run.mjs']),runtimeCopy,repositoryCopy);
|
|
263
266
|
const simulated=importChild(path.join(runtimeCopy,'notify.mjs'));
|
|
264
267
|
assert.equal(simulated.status,0,simulated.stderr);assert.match(simulated.stdout,/imported/);
|
|
265
268
|
// Negative control: the same simulation does kill an import of the sender,
|
|
@@ -7,6 +7,12 @@ import path from 'node:path';
|
|
|
7
7
|
import {spawn,spawnSync} from 'node:child_process';
|
|
8
8
|
import {notify,notifyLater,cancelPendingNotice,clearAttention,sessionTitle,scheduleWaitNotice,driveProgressKey,readNotifyConfig,writeHostRegistry,scheduleIdleNotice,parseNotifyConfig,buildNotifyMessage,normalizeNotifyText,driveNotice,NOTIFY_LIMITS,NOTIFY_WORKFLOWS,DEFAULT_NOTIFY_TEXT} from '../runtime/js/notify.mjs';
|
|
9
9
|
|
|
10
|
+
// driveNotice and spawned drivers read the standing authorization from the default
|
|
11
|
+
// home: point it at an empty directory, never the tester's own ~/.cm-workflow.
|
|
12
|
+
if(!process.env.CM_WORKFLOW_HOME){
|
|
13
|
+
process.env.CM_WORKFLOW_HOME=fs.mkdtempSync(path.join(os.tmpdir(),'cm-notify-default-home-'));
|
|
14
|
+
process.on('exit',()=>fs.rmSync(process.env.CM_WORKFLOW_HOME,{recursive:true,force:true}));
|
|
15
|
+
}
|
|
10
16
|
const NOW=Date.parse('2026-10-08T08:00:00.000Z');
|
|
11
17
|
const DRIVE_CORE=new URL('../runtime/js/cm-ai/drive-core.mjs',import.meta.url).href;
|
|
12
18
|
const BRIDGE=new URL('../runtime/js/cm-ai/host-tool-bridge.mjs',import.meta.url).href;
|
|
@@ -73,6 +73,18 @@ test('actual change CLI resumes unsaved phase across processes and stops at huma
|
|
|
73
73
|
c=await client(t,dir,respond,{session:runId});assert.equal((await c.request('status')).result.stage,'change_design');
|
|
74
74
|
for(const text of ['Design','Tasks','Check']){result=await c.request('advance',{text});assert.ok(result.result,JSON.stringify(result));}
|
|
75
75
|
assert.equal(result.result.stage,'change_confirmation');const proposalDigest=result.result.proposal.proposalDigest;
|
|
76
|
+
assert.equal(result.result.acceptancePreview.proposalDigest,proposalDigest);
|
|
77
|
+
assert.equal(result.result.acceptancePreview.sourceKind,'proposed_documents');
|
|
78
|
+
assert.equal(result.result.acceptancePreview.taskGrammar,1,'unpublished existing change retains legacy grammar');
|
|
79
|
+
assert.equal(result.result.acceptancePreview.approvalAuthorized,false);
|
|
80
|
+
assert.equal(result.result.acceptancePreview.executionAuthorized,false);
|
|
81
|
+
const checkpointPath=path.join(dir,'.reviews/prd-sessions',runId,'state.json'),checkpoint=fs.readFileSync(checkpointPath);
|
|
82
|
+
const sourcePath=path.join(dir,'1.guide/requirements.md'),originalSource=fs.readFileSync(sourcePath);
|
|
83
|
+
fs.appendFileSync(sourcePath,'\nExternal edit\n');
|
|
84
|
+
const stale=await c.request('status');assert.equal(stale.result.acceptancePreview.status,'stale');
|
|
85
|
+
assert.equal(stale.result.acceptancePreview.proposalDigest,proposalDigest);
|
|
86
|
+
assert.deepEqual(fs.readFileSync(checkpointPath),checkpoint,'preview status does not rewrite the session');
|
|
87
|
+
fs.writeFileSync(sourcePath,originalSource);
|
|
76
88
|
assert.equal((await c.request('save_draft')).error.code,'host_request_failed');
|
|
77
89
|
assert.ok((await c.request('decision',{proposalDigest,approved:true,allowUserCaseChanges:false})).result);
|
|
78
90
|
result=await c.request('save_draft');assert.equal(result.result.status,'awaiting_review');assert.equal(result.result.counts.preservedCompletedTasks,1);
|
package/scripts/cm-prd-host.mjs
CHANGED
|
@@ -16,6 +16,7 @@ import {createPrdDispositionOwner} from '../runtime/js/cm-prd/review-disposition
|
|
|
16
16
|
import {savePrdDraft,savePrdDesign,savePrdPromotedDraft} from '../runtime/js/cm-prd/draft-save.mjs';
|
|
17
17
|
import {createPrdCorrectionOwner,inspectPrdCorrectionRecovery,resumePrdCorrection} from '../runtime/js/cm-prd/review-correction.mjs';
|
|
18
18
|
import {createPrdSummaryOwner,publishPrdAwaitingReview} from '../runtime/js/cm-prd/summary.mjs';
|
|
19
|
+
import {currentAcceptancePreview} from '../runtime/js/cm-prd/acceptance-preview.mjs';
|
|
19
20
|
import {createHostToolBridge} from '../runtime/js/cm-ai/host-tool-bridge.mjs';
|
|
20
21
|
import {serveCmAiHost} from '../runtime/js/cm-ai/host-session.mjs';
|
|
21
22
|
import {need,shape,json,id,digest} from '../runtime/js/cm-ai/effect-contract.mjs';
|
|
@@ -138,6 +139,7 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
|
|
|
138
139
|
// Repair older cancelled checkpoints without replaying their retained call.
|
|
139
140
|
if(cancelled&&!ended){reviewController.abort();session.commit(checkpoint());}
|
|
140
141
|
const status=()=>ended?{stage:'inputs_replaced',runId,replacement:ended,completionAuthorized:false}:({...change?.status()??analysis.status(),...(predecessor?{predecessor}:{}),runId,logWriteEnabled:true,reviewState,summaryState,publishedSummary,
|
|
142
|
+
...(summaryState?.acceptancePreview?{acceptancePreview:currentAcceptancePreview({specs:admission.specs,preview:summaryState.acceptancePreview})}:{}),
|
|
141
143
|
recovery:session.state.active?{request:session.state.active.request,calls:session.state.active.calls.map(({callId,requestDigest,kind,result})=>
|
|
142
144
|
({callId,requestDigest,kind,status:result===undefined?'unknown':'recorded'}))}:null});
|
|
143
145
|
const handle=async raw=>{
|
|
@@ -185,7 +187,7 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
|
|
|
185
187
|
summaryState=null;
|
|
186
188
|
try{
|
|
187
189
|
need(Array.isArray(currentFeatures)&¤tFeatures.length>0,'prd_summary_scope_unknown');
|
|
188
|
-
summaryState=await summarize(admission.specs,{currentFeatures},reviewController.signal);return summaryState;
|
|
190
|
+
summaryState=await summarize(admission.specs,{currentFeatures,taskGrammar:session.versions().taskGrammar},reviewController.signal);return summaryState;
|
|
189
191
|
}catch(cause){
|
|
190
192
|
// The shared transport redacts thrown errors. Keep this recoverable
|
|
191
193
|
// scope failure visible without changing that transport contract.
|
|
@@ -7,6 +7,7 @@ import {spawn} from 'node:child_process';
|
|
|
7
7
|
import {once} from 'node:events';
|
|
8
8
|
import {createInterface} from 'node:readline';
|
|
9
9
|
import {fileURLToPath} from 'node:url';
|
|
10
|
+
import {analyzeRunRows} from '../runtime/js/run-analysis.mjs';
|
|
10
11
|
import {createCmPrdAnalysis} from '../runtime/js/cm-prd/analysis.mjs';
|
|
11
12
|
import {openPrdSession} from '../runtime/js/cm-prd/session.mjs';
|
|
12
13
|
const FIXTURE_TIMEOUT_MS=Number(process.env.CM_TEST_FIXTURE_TIMEOUT_MS??60000);
|
|
@@ -148,6 +149,10 @@ for(const mode of ['codex','claude','cancel','cases','materials','draft','self-c
|
|
|
148
149
|
send({requestId:'summary',operation:'prepare_summary'});
|
|
149
150
|
}else if(message.requestId==='summary'){
|
|
150
151
|
assert.equal(message.result.status,'human_summary_prepared');assert.equal(message.result.readyForAwaitingReview,true);
|
|
152
|
+
assert.equal(message.result.acceptancePreview.taskGrammar,3);
|
|
153
|
+
assert.deepEqual(message.result.acceptancePreview.scope.features,['1.guide']);
|
|
154
|
+
assert.equal(message.result.acceptancePreview.approvalAuthorized,false);
|
|
155
|
+
assert.equal(message.result.acceptancePreview.executionAuthorized,false);
|
|
151
156
|
assert.deepEqual(message.result.currentFeatures,['1.guide']);
|
|
152
157
|
assert.match(message.result.notes.join('\n'),/历史 feature 2.history.*旧版归档/);
|
|
153
158
|
assert.equal(message.result.totals.tasks,1);assert.equal(message.result.checklist.every(item=>!item.checked),true);
|
|
@@ -166,7 +171,14 @@ for(const mode of ['codex','claude','cancel','cases','materials','draft','self-c
|
|
|
166
171
|
assert.equal(JSON.parse(fs.readFileSync(path.join(dir,'.cm-specs-status'))).status,'awaiting_review');
|
|
167
172
|
assert.deepEqual(JSON.parse(fs.readFileSync(path.join(dir,'.cm-specs-status'))).features,['1.guide','2.history']);
|
|
168
173
|
send({requestId:'status',operation:'status'});
|
|
169
|
-
}else if(message.requestId==='status'){
|
|
174
|
+
}else if(message.requestId==='status'){
|
|
175
|
+
status=message.result;
|
|
176
|
+
if(mode==='self-check'){
|
|
177
|
+
assert.deepEqual(status.acceptancePreview,status.summaryState.acceptancePreview);
|
|
178
|
+
assert.equal(status.acceptancePreview.taskGrammar,3);
|
|
179
|
+
}
|
|
180
|
+
send({type:'host_close',sessionId});
|
|
181
|
+
}
|
|
170
182
|
}
|
|
171
183
|
assert.equal((await closed)[0],0,stderr);
|
|
172
184
|
assert.equal(status.stage,mode==='cancel'?'cancelled':mode==='draft'?'draft_ready':mode==='self-check'?'self_check_reported_passed':'analysis_ready');
|
|
@@ -175,6 +187,11 @@ for(const mode of ['codex','claude','cancel','cases','materials','draft','self-c
|
|
|
175
187
|
assert.equal(fs.existsSync(path.join(dir,'1.guide')),false);
|
|
176
188
|
}
|
|
177
189
|
const events=fs.readFileSync(path.join(dir,'运行日志.jsonl'),'utf8').trim().split('\n').map(JSON.parse);
|
|
190
|
+
const timing=analyzeRunRows(events).timing;
|
|
191
|
+
assert(timing.pairedSegments>0,'actual PRD producer timing must be recognized');
|
|
192
|
+
assert.equal(timing.unrecognizedEvents,0);assert.equal(timing.incompleteSegments,0);
|
|
193
|
+
if(mode==='draft'){assert(timing.combinedSegments>=3);assert(timing.stages.some(x=>x.stage==='design_generation'));}
|
|
194
|
+
if(mode==='codex'||mode==='claude')assert(timing.closedForInput>=1);
|
|
178
195
|
assert.equal(events.filter(event=>event.event==='run_start').length,1);
|
|
179
196
|
const done=events.filter(event=>event.event==='run_done');assert.equal(done.length,1);
|
|
180
197
|
assert.equal(done[0].outcome,mode==='cancel'?'cancelled':'incomplete');
|
|
@@ -10,13 +10,13 @@ import {preparePrdReview} from '../runtime/js/cm-prd/review-preparation.mjs';
|
|
|
10
10
|
import {publishPrdReview} from '../runtime/js/cm-prd/review-publication.mjs';
|
|
11
11
|
import {recordPrdHostDisposition,createPrdDispositionOwner} from '../runtime/js/cm-prd/review-disposition.mjs';
|
|
12
12
|
import {inspectPrdSummaryEvidence,createPrdSummaryOwner,publishPrdAwaitingReview} from '../runtime/js/cm-prd/summary.mjs';
|
|
13
|
-
import {inspectPrdChangeSnapshot,inspectPrdChangeProposal,applyPrdChange} from '../runtime/js/cm-prd/change.mjs';
|
|
13
|
+
import {inspectPrdChangeSnapshot,inspectPrdChangeProposal,applyPrdChange,createPrdChange} from '../runtime/js/cm-prd/change.mjs';
|
|
14
14
|
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
18
|
const sha=content=>createHash('sha256').update(content).digest('hex');
|
|
19
|
-
function fixture(t,{pendingCorrection=false}={}){
|
|
19
|
+
function fixture(t,{pendingCorrection=false,mandatory=false}={}){
|
|
20
20
|
const specs=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-prd-summary-marks-')));
|
|
21
21
|
t.after(()=>fs.rmSync(specs,{recursive:true,force:true}));fs.mkdirSync(path.join(specs,'.reviews'));
|
|
22
22
|
const inputs=[];
|
|
@@ -24,7 +24,7 @@ function fixture(t,{pendingCorrection=false}={}){
|
|
|
24
24
|
const findings=pendingCorrection&&feature==='1.guide'?[{id:'R1',severity:'P2',path:`${feature}/tasks.md`,
|
|
25
25
|
message:'Clarify task split',evidence:'Synthetic finding'}]:[];
|
|
26
26
|
const documents=[{path:'requirements.md',content:'## 功能需求\n1. [F-001] Guide\n- [ ] [AC-001] Read guide'},
|
|
27
|
-
{path:'design.md',content:'## 方案摘要\nDocumentation'}, {path:'tasks.md',content
|
|
27
|
+
{path:'design.md',content:'## 方案摘要\nDocumentation'}, {path:'tasks.md',content:`- [ ] T-001: ${mandatory?'必验: ':''}Guide\n - 范围: \`README.md\``}];
|
|
28
28
|
const prepared=preparePrdReview({specs,stage:'split',feature,draft:{draftDigest:'a'.repeat(64),features:[{name:feature.split('.')[1],directory:feature,documents}]}});
|
|
29
29
|
claimPrdReview({...prepared.paths,package_sha256:prepared.packageDigest});
|
|
30
30
|
publishPrdReview({specs,reviewPackage:prepared.reviewPackage,packageDigest:prepared.packageDigest,authorContextId:'author',
|
|
@@ -41,7 +41,7 @@ function fixture(t,{pendingCorrection=false}={}){
|
|
|
41
41
|
return {specs,mark,inputs};
|
|
42
42
|
}
|
|
43
43
|
test('summary includes completed historical feature and exact new feature with runtime metadata',async t=>{
|
|
44
|
-
const {specs,mark}=fixture(t),before=inspectPrdSummaryEvidence(specs);mark();
|
|
44
|
+
const {specs,mark}=fixture(t,{mandatory:true}),before=inspectPrdSummaryEvidence(specs);mark();
|
|
45
45
|
const evidence=inspectPrdSummaryEvidence(specs);
|
|
46
46
|
assert.equal(evidence.features.length,2);assert.deepEqual(evidence.specFiles,before.specFiles);
|
|
47
47
|
assert.equal(evidence.features[0].reviews.split.gate.runtimeMarksNormalized,true);
|
|
@@ -56,6 +56,10 @@ test('summary includes completed historical feature and exact new feature with r
|
|
|
56
56
|
evidence:['Synthetic documentation fixture']}))})});
|
|
57
57
|
const summary=await owner(specs,new AbortController().signal);
|
|
58
58
|
assert.equal(summary.status,'human_summary_prepared');
|
|
59
|
+
assert.equal(summary.acceptancePreview.status,'needs_clarification');
|
|
60
|
+
assert.equal(summary.acceptancePreview.approvalAuthorized,false);
|
|
61
|
+
assert.equal(summary.acceptancePreview.executionAuthorized,false);
|
|
62
|
+
assert(summary.acceptancePreview.features[0].tasks[0].issues.some(issue=>issue.message.includes('no explicit task/case mapping')));
|
|
59
63
|
assert.equal(summary.readyForAwaitingReview,false);
|
|
60
64
|
assert.deepEqual(summary.blockers,['mechanical_self_check_failed']);
|
|
61
65
|
assert.deepEqual(summary.mechanicalSelfCheck.findings,[{feature:'1.guide',code:'new_task_not_pending'}]);
|
|
@@ -281,3 +285,14 @@ test('historical gate failure still rejects publication when history changes aft
|
|
|
281
285
|
fs.appendFileSync(path.join(specs,'1.guide/requirements.md'),'\nAnother edit after preparation');
|
|
282
286
|
assert.throws(()=>publishPrdAwaitingReview({specs,summary,writeEnabled:true}),/prd_summary_inputs_changed/);
|
|
283
287
|
});
|
|
288
|
+
|
|
289
|
+
test('R1 G5 change preview inventory includes unchanged features outside proposal scope',t=>{
|
|
290
|
+
const {specs}=fixture(t),admission={specs,project:specs,feature:'1.guide',cases:null,skillDir:path.resolve('skills/cm-prd')};
|
|
291
|
+
const options={admission,runtime:'codex',call:()=>assert.fail('status is read-only')};
|
|
292
|
+
const original=createPrdChange(options),state=structuredClone(original.checkpoint());
|
|
293
|
+
state.stage='change_confirmation';state.proposal={proposalDigest:'a'.repeat(64),removed:[],features:[{directory:'1.guide',
|
|
294
|
+
documents:['requirements.md','design.md','tasks.md'].map(name=>({path:name,content:fs.readFileSync(path.join(specs,'1.guide',name),'utf8')}))}]};
|
|
295
|
+
const value=createPrdChange({...options,restored:state}).status();
|
|
296
|
+
assert.deepEqual(value.acceptancePreview.featureInventory,['1.guide','2.appendix']);
|
|
297
|
+
assert.deepEqual(value.acceptancePreview.scope.features,['1.guide']);
|
|
298
|
+
});
|
|
@@ -434,6 +434,8 @@ import {buildDeveloperPrompt,readDeveloperRequest} from '../runtime/js/cm-ai/dev
|
|
|
434
434
|
import {requestFor} from '../runtime/js/cm-ai/effect-contract.mjs';
|
|
435
435
|
import {reviewResult,reviewPaths,reviewReceipt} from '../runtime/js/cm-ai/review-runner.mjs';
|
|
436
436
|
import {checkCompletion} from '../runtime/js/cm-ai/gate-bridge.mjs';
|
|
437
|
+
import {encodeAcceptanceEvidence,acceptanceCoverage} from '../runtime/js/cm-ai/acceptance-contract.mjs';
|
|
438
|
+
import {createHostHandoff} from '../runtime/js/cm-ai/host-handoff.mjs';
|
|
437
439
|
|
|
438
440
|
function specificationFixture(t,{cases=true,design='export function normalizePriority(value): Priority;\n'}={}){
|
|
439
441
|
const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-specification-')));
|
|
@@ -530,22 +532,35 @@ for(const size of [65536,65537,1024*1024+4])test(`design byte limit ${size} pres
|
|
|
530
532
|
assert(design.startsWith(material.designExcerpt));
|
|
531
533
|
});
|
|
532
534
|
|
|
533
|
-
test('new specification
|
|
534
|
-
const f=specificationFixture(t)
|
|
535
|
+
test('new specification requires bound acceptance evidence while legacy receipt eligibility is retained',t=>{
|
|
536
|
+
const f=specificationFixture(t);
|
|
537
|
+
f.writeSpec('tasks.md',fs.readFileSync(path.join(f.specsRoot,f.feature,'tasks.md'),'utf8').replace('T-001: implement','T-001: 必验: implement'));f.approve();
|
|
538
|
+
const baseline=f.capture();
|
|
535
539
|
const legacyBaseline=captureReviewBaseline({root:f.code,identity,scope:['code.js'],requirements:['requirements.md']});
|
|
536
540
|
write(f.code,'code.js','after');
|
|
537
|
-
const
|
|
541
|
+
const contract=baseline.specification.acceptanceContract;
|
|
542
|
+
const acceptedChecks=contract.requiredCommands.map((command,index)=>({...checks[0],id:`declared-${index}`,
|
|
543
|
+
command:command.map((token,at)=>at===0&&token==='node'?process.execPath:token)}));
|
|
544
|
+
const incomplete=createReviewPackage({root:f.code,baseline,checks:acceptedChecks});
|
|
545
|
+
const handoffPath=path.join(f.specsRoot,'.reviews','priority-T-001-a1-handoff.json');
|
|
546
|
+
fs.mkdirSync(path.dirname(handoffPath),{recursive:true});
|
|
547
|
+
const evidence=encodeAcceptanceEvidence({contract,identity,items:contract.obligations.map(item=>({...item,satisfied:true,
|
|
548
|
+
evidence:'Synthetic fixture approval input, not a product execution'})),facts:null,coverage:acceptanceCoverage(contract,acceptedChecks)});
|
|
549
|
+
createHostHandoff({root:f.code,baseline,checks:acceptedChecks,handoffPath,evidence:[evidence]});
|
|
550
|
+
const current=createReviewPackage({root:f.code,baseline,checks:acceptedChecks,handoffPath});
|
|
538
551
|
const old=createReviewPackage({root:f.code,baseline:legacyBaseline,checks});
|
|
539
552
|
const {unchangedScope,packageDigest,...oldBody}=old,legacy={...oldBody,packageDigest:digest(oldBody)};
|
|
540
|
-
for(const pkg of [current,legacy]){
|
|
553
|
+
for(const pkg of [incomplete,current,legacy]){
|
|
541
554
|
assert.deepEqual(readReviewPackage(pkg),pkg);
|
|
542
555
|
const result=reviewResult({verdict:'approved',packageDigest:pkg.packageDigest,examinedPaths:reviewPaths(pkg),findings:[],summary:'Synthetic review'},pkg);
|
|
543
556
|
const request=requestFor({invocationId:'receipt',identity,role:'reviewer',provider:'claude',requestedModel:'fixture',contextId:'reviewer',payload:{reviewPackage:pkg,priorReview:null}});
|
|
544
557
|
const call={invocationId:request.invocationId,started:true,terminal:'succeeded',requestDigest:request.requestDigest,resultDigest:digest(result),
|
|
545
558
|
provider:'claude',contextId:'reviewer',requestedModel:'fixture',effectiveModel:'fixture',channel:'fixture'};
|
|
546
559
|
const receipt=reviewReceipt({request,call,result,reviewPackage:pkg,developerProvider:'codex',fallbackReasons:[]});
|
|
547
|
-
assert.
|
|
548
|
-
assert.equal(
|
|
560
|
+
if(pkg===incomplete)assert.throws(()=>checkCompletion({receipt,registered:receipt,execution:call,reviewPackage:pkg,identity}),{code:'verification_precheck_failed'});
|
|
561
|
+
else assert.equal(checkCompletion({receipt,registered:receipt,execution:call,reviewPackage:pkg,identity}).outcome,'eligible');
|
|
562
|
+
assert.equal(verifyReviewPackage({root:f.code,baseline:pkg===legacy?legacyBaseline:baseline,checks:pkg===legacy?checks:acceptedChecks,
|
|
563
|
+
...(pkg===current?{handoffPath}:{}),reviewPackage:pkg,expectedDigest:pkg.packageDigest}).outcome,'matched');
|
|
549
564
|
}
|
|
550
565
|
});
|
|
551
566
|
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import {fileURLToPath} from 'node:url';
|
|
4
|
+
import {inspectRunAnalysis,runAnalysisLines} from '../runtime/js/run-analysis.mjs';
|
|
5
|
+
const usage='用法: cm-run-analysis.mjs --specs DIR [--run-id ID] [--json]\n读取规格目录的运行日志;不执行工作流或修改状态。\n';
|
|
6
|
+
export function main(argv=process.argv.slice(2),{stdout=process.stdout,stderr=process.stderr}={}){
|
|
7
|
+
if(argv.length===1&&['--help','-h'].includes(argv[0])){stdout.write(usage);return 0;}
|
|
8
|
+
try{
|
|
9
|
+
const options={};
|
|
10
|
+
for(let i=0;i<argv.length;i++){
|
|
11
|
+
const name=argv[i];if(!['--specs','--run-id','--json'].includes(name)||Object.hasOwn(options,name))throw Error('run_analysis_arguments_invalid');
|
|
12
|
+
if(name==='--json')options[name]=true;
|
|
13
|
+
else{const value=argv[++i];if(!value||value.startsWith('--'))throw Error('run_analysis_arguments_invalid');options[name]=value;}
|
|
14
|
+
}
|
|
15
|
+
if(!options['--specs'])throw Error('run_analysis_arguments_invalid');
|
|
16
|
+
const report=inspectRunAnalysis({specs:path.resolve(options['--specs']),runId:options['--run-id']??null});
|
|
17
|
+
stdout.write(options['--json']?JSON.stringify(report)+'\n':runAnalysisLines(report).join('\n')+'\n');return 0;
|
|
18
|
+
}catch(error){const reason=error.code??error.message;
|
|
19
|
+
stderr.write(`运行分析不可用:${/^run_analysis_[a-z_]+$/.test(reason)?reason:'run_analysis_read_failed'}\n`);return 2;}
|
|
20
|
+
}
|
|
21
|
+
if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url))process.exitCode=main();
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import {spawnSync} from 'node:child_process';
|
|
7
|
+
import {fileURLToPath} from 'node:url';
|
|
8
|
+
import {withHostProgress,startHostProgress} from '../runtime/js/cm-ai/host-progress.mjs';
|
|
9
|
+
import {recordCmAiQaDecision,recordCmAiQaRun} from '../runtime/js/cm-ai/cm-ai-qa-log.mjs';
|
|
10
|
+
import {analyzeRunRows,inspectRunAnalysis,runAnalysisLines} from '../runtime/js/run-analysis.mjs';
|
|
11
|
+
const cli=fileURLToPath(new URL('./cm-run-analysis.mjs',import.meta.url));
|
|
12
|
+
const base={run_id:'run-1',workflow:'cm-ai',runtime:'codex',stage:'develop',role:'developer',adapter:'codex-cli',requested_model:'configured',source:'native-cli-terminal',purpose:'workflow-execution'};
|
|
13
|
+
const claim=(id,extra={})=>({...base,event:'model_call',phase:'claimed',call_id:id,...extra});
|
|
14
|
+
const usage=(id,extra={})=>({...base,event:'model_usage',phase:'complete',call_id:id,usage_state:'observed',outcome:'success',input_tokens:10,output_tokens:5,...extra});
|
|
15
|
+
const progress=(phase,time,extra={})=>({run_id:'run-1',workflow:'cm-prd',event:'progress',phase,operation_id:'prd-design',phase_name:'design_generation',segment:1,at:`2026-01-01T00:${time}Z`,...(phase==='complete'?{outcome:'completed'}:{}),...extra});
|
|
16
|
+
function fixture(t,rows){const dir=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-analysis-')));t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));fs.writeFileSync(path.join(dir,'运行日志.jsonl'),rows.map(x=>JSON.stringify(x)).join('\n')+'\n');return dir;}
|
|
17
|
+
|
|
18
|
+
test('reuses native usage identity, reasoning subset and unavailable semantics',()=>{
|
|
19
|
+
const report=analyzeRunRows([claim('a'),usage('a',{outcome:'error',cache_write_tokens:3,reasoning_tokens:4}),claim('b'),usage('b',{usage_state:'unavailable',input_tokens:undefined,output_tokens:undefined}),claim('c')]);
|
|
20
|
+
assert.equal(report.usage.status,'partial');assert.equal(report.usage.summary.observed_calls,1);
|
|
21
|
+
assert.equal(report.usage.summary.outcomes.error,1);assert.equal(report.usage.summary.unavailable_calls,1);
|
|
22
|
+
assert.equal(report.usage.summary.unresolved_claims,1);assert.equal(report.usage.summary.output_tokens,5);
|
|
23
|
+
assert.equal(report.usage.native_components.fields.reasoning_tokens.tokens,4);
|
|
24
|
+
assert.equal(report.usage.native_components.fields.cache_read_tokens.tokens,null);
|
|
25
|
+
assert.equal(report.repetitions.groups[0].count,3);
|
|
26
|
+
});
|
|
27
|
+
test('claim mismatch, missing prior claim, duplicate call and invalid reasoning are never counted',()=>{
|
|
28
|
+
const report=analyzeRunRows([usage('missing'),claim('a'),usage('a',{stage:'review'}),claim('b'),usage('b',{reasoning_tokens:6}),claim('c'),usage('c'),usage('c')]);
|
|
29
|
+
assert.equal(report.usage.summary.observed_calls,1);assert.equal(report.usage.summary.invalid_calls,4);
|
|
30
|
+
assert.equal(report.usage.summary.unresolved_claims,2);assert.equal(report.usage.status,'partial');
|
|
31
|
+
});
|
|
32
|
+
test('paired phase segments exclude waiting gaps and union combined call overlaps',()=>{
|
|
33
|
+
const rows=[progress('start','00:00'),progress('complete','00:10',{outcome:'awaiting_input'}),
|
|
34
|
+
progress('start','05:00',{segment:2,timing_scope:'combined_host_call'}),
|
|
35
|
+
progress('start','05:00',{operation_id:'prd-task',phase_name:'task_split',timing_scope:'combined_host_call'}),
|
|
36
|
+
progress('complete','05:20',{segment:2,timing_scope:'combined_host_call'}),
|
|
37
|
+
progress('complete','05:20',{operation_id:'prd-task',phase_name:'task_split',timing_scope:'combined_host_call'})];
|
|
38
|
+
const r=analyzeRunRows(rows).timing;assert.equal(r.activeIntervalUnionMs,30000);assert.equal(r.closedForInput,1);
|
|
39
|
+
assert.equal(r.combinedSegments,2);assert.equal(r.waitingMs,null);assert.equal(r.stages[0].durationMs,30000);
|
|
40
|
+
});
|
|
41
|
+
test('timing never pairs across run, workflow, operation, duplicate or inverted order',()=>{
|
|
42
|
+
const r=analyzeRunRows([progress('start','00:00'),progress('complete','00:10',{run_id:'run-2'}),
|
|
43
|
+
progress('complete','00:10',{workflow:'cm-ai'}),progress('start','00:00',{operation_id:'duplicate'}),progress('start','00:00',{operation_id:'duplicate'}),progress('complete','00:10',{operation_id:'duplicate'}),
|
|
44
|
+
progress('complete','00:10',{operation_id:'inverted'}),progress('start','00:00',{operation_id:'inverted'})]).timing;
|
|
45
|
+
assert.equal(r.pairedSegments,0);assert.equal(r.activeIntervalUnionMs,null);assert.equal(r.incompleteSegments,4);assert.equal(r.unrecognizedEvents,1);
|
|
46
|
+
});
|
|
47
|
+
test('selects original run, deduplicates exact events, rejects conflicting identity and preserves legacy unknown',()=>{
|
|
48
|
+
const a=claim('a',{event_id:'event-1'});const r=analyzeRunRows([a,a,usage('a'),claim('other',{run_id:'run-2'}),{event:'legacy'}],{runId:'run-1'});
|
|
49
|
+
assert.deepEqual(r.runs,['run-1']);assert.equal(r.deduplicatedEvents,1);assert.equal(r.ignoredHistoricalRows,1);
|
|
50
|
+
assert.equal(r.usage.summary.observed_calls,1);
|
|
51
|
+
assert.throws(()=>analyzeRunRows([a,{...a,stage:'review'}]),/log_invalid/);
|
|
52
|
+
assert.throws(()=>analyzeRunRows([a],{runId:'absent'}),/run_not_found/);
|
|
53
|
+
});
|
|
54
|
+
test('QA repetitions are unique operation starts, command execution remains unknown',()=>{
|
|
55
|
+
const start={run_id:'run-1',workflow:'cm-ai',event:'test_run',phase:'start',feature:'1.login',task:'T-001',operation_id:'qa-1'};
|
|
56
|
+
const r=analyzeRunRows([start,start,{...start,operation_id:'qa-2'}]).repetitions;
|
|
57
|
+
assert.equal(r.groups[0].count,2);assert.equal(r.commandReexecution,'unavailable');
|
|
58
|
+
});
|
|
59
|
+
test('actual CLI reads one stable log and does not modify logs or state',t=>{
|
|
60
|
+
const dir=fixture(t,[claim('a'),usage('a'),progress('start','00:00'),progress('complete','00:10')]);
|
|
61
|
+
const state=path.join(dir,'.cm-run.json');fs.writeFileSync(state,'{"run_id":"do-not-use-pointer"}');
|
|
62
|
+
const before=fs.readdirSync(dir).map(name=>[name,fs.readFileSync(path.join(dir,name)),fs.statSync(path.join(dir,name)).mtimeMs]);
|
|
63
|
+
const result=spawnSync(process.execPath,[cli,'--specs',dir,'--run-id','run-1','--json'],{encoding:'utf8'});
|
|
64
|
+
assert.equal(result.status,0,result.stderr);assert.equal(JSON.parse(result.stdout).usage.summary.observed_calls,1);
|
|
65
|
+
for(const [name,bytes,mtime] of before){assert.deepEqual(fs.readFileSync(path.join(dir,name)),bytes);assert.equal(fs.statSync(path.join(dir,name)).mtimeMs,mtime);}
|
|
66
|
+
assert.equal(fs.readdirSync(dir).length,before.length);
|
|
67
|
+
});
|
|
68
|
+
test('malformed, symlink and oversized authoritative logs fail closed without raw input',t=>{
|
|
69
|
+
const dir=fixture(t,[]),file=path.join(dir,'运行日志.jsonl');fs.writeFileSync(file,'SECRET-BAD-JSON');
|
|
70
|
+
let r=spawnSync(process.execPath,[cli,'--specs',dir,'--json'],{encoding:'utf8'});assert.equal(r.status,2);assert.doesNotMatch(r.stderr,/SECRET/);
|
|
71
|
+
fs.unlinkSync(file);fs.writeFileSync(path.join(dir,'other'),'{}');fs.symlinkSync('other',file);assert.throws(()=>inspectRunAnalysis({specs:dir}),/unavailable/);
|
|
72
|
+
fs.unlinkSync(file);fs.writeFileSync(file,'');fs.truncateSync(file,32*1024*1024+1);assert.throws(()=>inspectRunAnalysis({specs:dir}),/unavailable/);
|
|
73
|
+
});
|
|
74
|
+
test('missing Python is explicit unavailable and malicious labels never reach human output',()=>{
|
|
75
|
+
const old=process.env.PATH;try{process.env.PATH='';const r=analyzeRunRows([claim('a'),usage('a')]);assert.equal(r.usage.status,'unavailable');assert.equal(r.usage.reason,'usage_reader_unavailable');}finally{process.env.PATH=old;}
|
|
76
|
+
const r=analyzeRunRows([claim('a',{stage:'\u001b[31mSECRET'}),usage('a',{stage:'\u001b[31mSECRET'})]);
|
|
77
|
+
assert.equal(r.usage.summary.observed_calls,0);assert.equal(r.usage.summary.invalid_claims,1);
|
|
78
|
+
assert.doesNotMatch(runAnalysisLines(r).join('\n'),/SECRET|\u001b/);
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
test('actual AI progress producer: returned, failed, aborted and unfinished operations remain distinct',async t=>{
|
|
83
|
+
const dir=fixture(t,[]),specsDir=dir,codeProject=path.join(dir,'code');fs.mkdirSync(codeProject);
|
|
84
|
+
const definition={specsDir,codeProject,feature:'1.example'},identity={repositoryId:'analysis-fixture',runId:'run-ai-native',taskId:'T-001',attempt:1};
|
|
85
|
+
const options={definition,identity,stage:'checking'};
|
|
86
|
+
await withHostProgress({...options,signal:new AbortController().signal},async()=>({outcome:'failed'}));
|
|
87
|
+
await assert.rejects(withHostProgress({...options,signal:new AbortController().signal},async()=>{throw Error('fixture failure');}),/fixture failure/);
|
|
88
|
+
const controller=new AbortController(),p=startHostProgress({...options,signal:controller.signal});controller.abort();p.complete('returned');
|
|
89
|
+
startHostProgress({...options,signal:new AbortController().signal});
|
|
90
|
+
const rows=fs.readFileSync(path.join(dir,'运行日志.jsonl'),'utf8').trim().split('\n').map(JSON.parse);
|
|
91
|
+
assert(rows.filter(x=>x.event==='progress').every(x=>!Object.hasOwn(x,'segment')));
|
|
92
|
+
const report=inspectRunAnalysis({specs:dir}),timing=report.timing;
|
|
93
|
+
assert.equal(timing.pairedSegments,3);assert.equal(timing.incompleteSegments,1);assert.equal(timing.unrecognizedEvents,0);
|
|
94
|
+
assert.equal(timing.status,'partial');assert.deepEqual(timing.stages[0].outcomes,{returned:1,failed:1,aborted:1});
|
|
95
|
+
assert.equal(timing.waitingMs,null);assert.equal(timing.closedForInput,0);
|
|
96
|
+
assert.match(runAnalysisLines(report).join('\n'),/returned=1, failed=1, aborted=1/);
|
|
97
|
+
const start=rows.find(x=>x.phase==='start');
|
|
98
|
+
const wrong={...rows.find(x=>x.phase==='complete'),event_id:'wrong-task',task:'T-002'};
|
|
99
|
+
assert.equal(analyzeRunRows([start,wrong]).timing.pairedSegments,0);
|
|
100
|
+
assert.equal(analyzeRunRows([{...start,workflow:'cm-prd'}]).timing.unrecognizedEvents,1);
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
test('actual QA writer provides identity and operation fields consumed by repetition analysis',t=>{
|
|
104
|
+
const dir=fixture(t,[]),codeProject=path.join(dir,'code');fs.mkdirSync(codeProject);
|
|
105
|
+
const identity={repositoryId:'analysis-fixture',runId:'run-qa-native',taskId:'T-001',attempt:1},packageDigest='a'.repeat(64);
|
|
106
|
+
const binding={specsDir:dir,codeProject,feature:'1.example',identity,packageDigest,logHome:path.join(dir,'mirror')};
|
|
107
|
+
recordCmAiQaDecision({...binding,decision:{decisionId:'qa-decision',identity,packageDigest,status:'triggered',score:null,reason:'api',at:'2026-01-01T00:00:00Z'}});
|
|
108
|
+
recordCmAiQaRun({...binding,testRunId:'qa-operation-native',mode:'commands',caseCount:1,phase:'start'});
|
|
109
|
+
const row=fs.readFileSync(path.join(dir,'运行日志.jsonl'),'utf8').trim().split('\n').map(JSON.parse).find(x=>x.event==='test_run');
|
|
110
|
+
assert.equal(row.operation_id,'qa-operation-native');assert.equal(row.feature,'1.example');assert.equal(row.task,'T-001');
|
|
111
|
+
// A second distinct start follows the exact producer shape; does not simulate a QA verdict or retry authorization.
|
|
112
|
+
const report=analyzeRunRows([row,{...row,event_id:'second-observed-start',operation_id:'qa-operation-2'}]);
|
|
113
|
+
assert.equal(report.repetitions.groups[0].count,2);assert.equal(report.repetitions.groups[0].kind,'qa_invocation_start');
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
test('global event identity collisions across runs are rejected before usage deduplication',()=>{
|
|
117
|
+
const a=usage('a',{event_id:'same-event'}),b=usage('b',{run_id:'run-2',event_id:'same-event'});
|
|
118
|
+
assert.throws(()=>analyzeRunRows([a,b]),/log_invalid/);
|
|
119
|
+
assert.throws(()=>analyzeRunRows([a,b],{runId:'run-1'}),/log_invalid/);
|
|
120
|
+
});
|