@aibyzero/cm-workflow 0.17.0 → 0.17.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.
Files changed (52) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +4 -0
  3. package/CHANGELOG.md +6 -1
  4. package/CONTRIBUTING.md +47 -0
  5. package/README.md +8 -1
  6. package/VERSION +1 -1
  7. package/docs/architecture.md +29 -13
  8. package/docs/fixes/20261013-claude-preinit-ui-invalidate.md +48 -0
  9. package/docs/installation.md +1 -1
  10. package/docs/js-workflow-control.md +3 -1
  11. package/package.json +1 -1
  12. package/runtime/js/cm-ai/claude-review-stream.mjs +12 -8
  13. package/runtime/js/cm-ai/control-policy.mjs +3 -2
  14. package/runtime/js/cm-ai/drive-core.mjs +124 -25
  15. package/runtime/js/cm-ai/host-check.mjs +3 -1
  16. package/runtime/js/cm-ai/host-session.mjs +41 -8
  17. package/runtime/js/cm-ai/host-stage-observer.mjs +26 -0
  18. package/runtime/js/cm-ai/host-tool-bridge.mjs +22 -9
  19. package/runtime/js/cm-ai/operator-guidance.mjs +56 -30
  20. package/runtime/js/cm-ai/task-runner.mjs +5 -2
  21. package/runtime/js/cm-prd/summary.mjs +27 -12
  22. package/runtime/review.md +9 -0
  23. package/scripts/cm-ai-batch-host.test.mjs +21 -9
  24. package/scripts/cm-ai-batch-run.mjs +12 -6
  25. package/scripts/cm-ai-control-policy.test.mjs +68 -0
  26. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +3 -2
  27. package/scripts/cm-ai-drive.test.mjs +3 -3
  28. package/scripts/cm-ai-host-fixture.mjs +9 -6
  29. package/scripts/cm-ai-host-protected.test.mjs +1 -1
  30. package/scripts/cm-ai-host.test.mjs +15 -0
  31. package/scripts/cm-ai-operator-guidance.test.mjs +56 -0
  32. package/scripts/cm-ai-review-timeout.test.mjs +20 -0
  33. package/scripts/cm-check-drive-files.mjs +1 -1
  34. package/scripts/cm-check-host.test.mjs +1 -1
  35. package/scripts/cm-claude-probe.test.mjs +26 -0
  36. package/scripts/cm-claude-review-stream.test.mjs +36 -0
  37. package/scripts/cm-claude-worker.test.mjs +16 -0
  38. package/scripts/cm-drive-liveness.test.mjs +83 -0
  39. package/scripts/cm-external-batch-host.test.mjs +8 -6
  40. package/scripts/cm-host-diagnostic.test.mjs +33 -0
  41. package/scripts/cm-host-liveness.test.mjs +150 -0
  42. package/scripts/cm-host-stage-observer.test.mjs +41 -0
  43. package/scripts/cm-notify.test.mjs +50 -16
  44. package/scripts/cm-prd-drive.test.mjs +1 -1
  45. package/scripts/cm-prd-self-check-revision.test.mjs +15 -0
  46. package/scripts/cm-prd-session-recovery.test.mjs +5 -3
  47. package/scripts/cm-prd-summary.test.mjs +31 -0
  48. package/scripts/cm-release-smoke.sh +2 -14
  49. package/scripts/cm-test-suite.mjs +109 -0
  50. package/scripts/cm-test-suite.test.mjs +162 -0
  51. package/scripts/fixtures/host-diagnostic.mjs +33 -0
  52. package/skills/cm-ai/references/js-host.md +33 -1
@@ -0,0 +1,162 @@
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 {createHash} from 'node:crypto';
7
+ import {spawn, spawnSync} from 'node:child_process';
8
+ import {fileURLToPath} from 'node:url';
9
+ import {nativeTests, inventory, selectTests} from './cm-test-suite.mjs';
10
+ import {assignShards, readWeights} from './ci-test-shards.mjs';
11
+
12
+ const root = fileURLToPath(new URL('..', import.meta.url));
13
+ function cliEnv(env) {
14
+ const copy = {...env};
15
+ delete copy.NODE_TEST_CONTEXT; // The CLI starts an independent node --test invocation.
16
+ return copy;
17
+ }
18
+ const cli = (args, cwd = root, env = process.env) => spawnSync(process.execPath,
19
+ [path.join(cwd, 'scripts/cm-test-suite.mjs'), ...args], {cwd, env: cliEnv(env), encoding: 'utf8'});
20
+
21
+ function fixture(t, source = 'import test from "node:test"; test("fixture",()=>{});') {
22
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cm-test-suite-fixture-'));
23
+ t.after(() => fs.rmSync(dir, {recursive: true, force: true}));
24
+ fs.mkdirSync(path.join(dir, 'scripts'));
25
+ fs.mkdirSync(path.join(dir, 'experiments/js-orchestration'), {recursive: true});
26
+ for (const name of ['cm-test-suite.mjs', 'ci-test-shards.mjs', 'ci-test-weights.json'])
27
+ fs.copyFileSync(path.join(root, 'scripts', name), path.join(dir, 'scripts', name));
28
+ for (const file of nativeTests) fs.writeFileSync(path.join(dir, file), '');
29
+ fs.writeFileSync(path.join(dir, 'scripts/example.test.mjs'), source);
30
+ fs.writeFileSync(path.join(dir, 'experiments/js-orchestration/history.test.mjs'), source);
31
+ return dir;
32
+ }
33
+
34
+ test('approved native inventory is fixed, complete and disjoint from ordinary tests', () => {
35
+ assert.equal(nativeTests.length, 9);
36
+ // Approval fingerprint prevents additions, omissions and substitutions without a reviewed change.
37
+ assert.equal(createHash('sha256').update(nativeTests.join('\n')).digest('hex'), 'e036b229f15e0acca13f43c29a35a2cbc830b1dcdd812b1f379b46253f3eadce');
38
+ const groups = inventory(root);
39
+ const discovered = fs.readdirSync(path.join(root, 'scripts'))
40
+ .filter(name => name.endsWith('.test.mjs')).map(name => `scripts/${name}`).sort();
41
+ assert.deepEqual([...groups.ordinary, ...groups.native].sort(), discovered);
42
+ assert.equal(new Set([...groups.ordinary, ...groups.native]).size, discovered.length);
43
+ assert.deepEqual(groups.native, nativeTests);
44
+ });
45
+
46
+ test('listing every group is install-free and ordinary shards reuse the existing assignment', () => {
47
+ for (const group of ['ordinary', 'native', 'history']) {
48
+ const run = cli(['list', group]);
49
+ assert.equal(run.status, 0, run.stderr);
50
+ assert.deepEqual(run.stdout.trim().split('\n'), inventory(root)[group]);
51
+ }
52
+ const groups = inventory(root);
53
+ const shards = assignShards(groups.ordinary, 4, readWeights());
54
+ for (let index = 0; index < 4; index++)
55
+ assert.deepEqual(selectTests(groups, 'ordinary', {shards: 4, index}), shards[index].files);
56
+ assert.deepEqual(shards.flatMap(shard => shard.files).sort(), groups.ordinary);
57
+ });
58
+
59
+ test('new ordinary tests are included and missing native members stop the CLI', t => {
60
+ const dir = fixture(t);
61
+ fs.writeFileSync(path.join(dir, 'scripts/new.test.mjs'), '');
62
+ assert.match(cli(['list', 'ordinary'], dir).stdout, /scripts\/new.test.mjs/);
63
+ fs.unlinkSync(path.join(dir, nativeTests[0]));
64
+ const run = cli(['check'], dir);
65
+ assert.notEqual(run.status, 0);
66
+ assert.match(run.stderr, /missing native test/);
67
+ });
68
+
69
+ test('runner isolates both CM homes and cleans up after success', t => {
70
+ const dir = fixture(t, `import test from 'node:test'; import assert from 'node:assert/strict';
71
+ import fs from 'node:fs';
72
+ test('isolation',()=>{
73
+ assert.notEqual(process.env.CM_WORKFLOW_HOME, process.env.CALLER_HOME);
74
+ assert.notEqual(process.env.CM_WORKFLOW_LOG_HOME, process.env.CALLER_LOG_HOME);
75
+ assert(fs.statSync(process.env.CM_WORKFLOW_HOME).isDirectory());
76
+ assert(fs.statSync(process.env.CM_WORKFLOW_LOG_HOME).isDirectory());
77
+ fs.writeFileSync(process.env.CAPTURE, JSON.stringify([process.env.CM_WORKFLOW_HOME,process.env.CM_WORKFLOW_LOG_HOME]));
78
+ });`);
79
+ const capture = path.join(dir, 'capture.json');
80
+ const callerHome = path.join(dir, 'caller-home'), callerLogs = path.join(dir, 'caller-logs');
81
+ const run = cli(['run', 'ordinary', '--concurrency', '1'], dir,
82
+ {...process.env, CM_WORKFLOW_HOME: callerHome, CM_WORKFLOW_LOG_HOME: callerLogs,
83
+ CALLER_HOME: callerHome, CALLER_LOG_HOME: callerLogs, CAPTURE: capture});
84
+ assert.equal(run.status, 0, run.stderr + run.stdout);
85
+ for (const item of JSON.parse(fs.readFileSync(capture))) assert.equal(fs.existsSync(item), false);
86
+ assert.equal(fs.existsSync(callerHome), false);
87
+ assert.equal(fs.existsSync(callerLogs), false);
88
+ });
89
+
90
+ test('explicit concurrency reaches the Node runner', t => {
91
+ const source = `import test from 'node:test'; import fs from 'node:fs'; import assert from 'node:assert/strict';
92
+ test('overlap',async()=>{
93
+ fs.writeFileSync(process.env.CAPTURE+'/'+process.pid,'ready');
94
+ const deadline=Date.now()+5000;
95
+ while(fs.readdirSync(process.env.CAPTURE).length<2 && Date.now()<deadline)
96
+ await new Promise(resolve=>setTimeout(resolve,10));
97
+ assert.equal(fs.readdirSync(process.env.CAPTURE).length,2,'both test files must run concurrently');
98
+ });`;
99
+ const dir = fixture(t, source), capture = path.join(dir, 'parallel');
100
+ fs.mkdirSync(capture);
101
+ fs.writeFileSync(path.join(dir, 'scripts/second.test.mjs'), source);
102
+ const run = cli(['run', 'ordinary', '--concurrency', '2'], dir, {...process.env, CAPTURE: capture});
103
+ assert.equal(run.status, 0, run.stderr + run.stdout);
104
+ });
105
+
106
+ test('failed tests fail exactly once in ordinary and historical groups', t => {
107
+ const dir = fixture(t, `import test from 'node:test'; import fs from 'node:fs';
108
+ test('fail',()=>{fs.appendFileSync(process.env.CAPTURE,'attempt\\n');throw new Error('intentional fixture failure');});`);
109
+ for (const group of ['ordinary', 'history']) {
110
+ const capture = path.join(dir, `${group}.txt`);
111
+ const run = cli(['run', group], dir, {...process.env, CAPTURE: capture});
112
+ assert.equal(run.status, 1, run.stderr + run.stdout);
113
+ assert.equal(fs.readFileSync(capture, 'utf8'), 'attempt\n');
114
+ }
115
+ });
116
+
117
+ test('invalid arguments fail before running tests', t => {
118
+ const dir = fixture(t, 'throw new Error("must not execute");');
119
+ for (const args of [['run', 'unknown'], ['run', 'ordinary', '--concurrency', '0'],
120
+ ['run', 'ordinary', '--shards', '4'], ['list', 'ordinary', '--index', '0'],
121
+ ['run', 'ordinary', '--shards', '2', '--index', '2'], ['run', 'ordinary', '--retry']]) {
122
+ const run = cli(args, dir);
123
+ assert.notEqual(run.status, 0);
124
+ assert.doesNotMatch(run.stdout + run.stderr, /must not execute/);
125
+ }
126
+ });
127
+
128
+ test('parent signals reach tests, preserve failure and remove temporary homes', {skip: process.platform === 'win32'}, async t => {
129
+ const dir = fixture(t, `import fs from 'node:fs';
130
+ process.on('SIGTERM',()=>{fs.writeFileSync(process.env.SIGNAL_CAPTURE,'received'); process.exit(0);});
131
+ fs.writeFileSync(process.env.CAPTURE, process.env.CM_WORKFLOW_HOME);
132
+ setInterval(()=>{},1000);`);
133
+ const capture = path.join(dir, 'ready'), signalCapture = path.join(dir, 'signal');
134
+ const child = spawn(process.execPath, [path.join(dir, 'scripts/cm-test-suite.mjs'), 'run', 'ordinary'],
135
+ {cwd: dir, env: cliEnv({...process.env, CAPTURE: capture, SIGNAL_CAPTURE: signalCapture}), stdio: 'ignore'});
136
+ t.after(() => { if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL'); });
137
+ const closed = new Promise(resolve => child.on('close', (code, signal) => resolve({code, signal})));
138
+ const deadline = Date.now() + 10000;
139
+ while (!fs.existsSync(capture) && Date.now() < deadline) await new Promise(resolve => setTimeout(resolve, 20));
140
+ assert(fs.existsSync(capture), 'test child did not become ready');
141
+ child.kill('SIGTERM');
142
+ let timer;
143
+ const result = await Promise.race([closed, new Promise((_, reject) => {
144
+ timer = setTimeout(() => reject(new Error('signal not propagated')), 10000);
145
+ })]).finally(() => clearTimeout(timer));
146
+ assert.equal(result.signal, 'SIGTERM');
147
+ assert.equal(fs.readFileSync(signalCapture, 'utf8'), 'received');
148
+ assert.equal(fs.existsSync(fs.readFileSync(capture, 'utf8')), false);
149
+ });
150
+
151
+ test('CI and release smoke consume the same entrypoint without a second exclusion list', () => {
152
+ const ci = fs.readFileSync(path.join(root, '.github/workflows/ci.yml'), 'utf8');
153
+ const release = fs.readFileSync(path.join(root, 'scripts/cm-release-smoke.sh'), 'utf8');
154
+ assert.match(ci, /node scripts\/cm-test-suite\.mjs check/);
155
+ assert.match(ci, /node scripts\/cm-test-suite\.mjs run ordinary --shards 4 --index \$\{\{ matrix\.shard \}\}/);
156
+ assert.match(ci, /node scripts\/cm-test-suite\.mjs run history --concurrency 4/);
157
+ assert.match(release, /node "\$ROOT\/scripts\/cm-test-suite\.mjs" run native/);
158
+ for (const file of nativeTests) {
159
+ assert(!ci.includes(path.basename(file, '.test.mjs')), 'CI duplicated the native inventory');
160
+ assert(!release.includes(file), 'release duplicated the native inventory');
161
+ }
162
+ });
@@ -0,0 +1,33 @@
1
+ // Fixture-only metadata, following live-evidence-driver's bounded diagnostics.
2
+ // Never retain request IDs, paths, payloads, command lines or stderr contents.
3
+ const operations=new Set(['advance','start','status','fix_status','cancel','resume','host_close','host_result','eof']);
4
+ const kinds=new Set(['develop','check','review','complete','qa_assess','qa_browser','documentation_sync','documentation_inspect']);
5
+ const states=new Set(['idle','developing','pending_review','reviewing','fixture_completed','blocked','unknown','cancelled',
6
+ 'requirements_analysis','awaiting_user','status_only']);
7
+ const codes=new Set(['develop_answer_missing','host_busy','execution_error','host_launch_failed','invalid_arguments']);
8
+ const signals=new Set(['SIGTERM','SIGKILL','SIGINT','SIGABRT','SIGSEGV','SIGHUP','SIGPIPE']);
9
+ const allowed=(set,value)=>set.has(value)?value:value==null?null:'other';
10
+
11
+ export function hostDiagnostic(child,{timeoutMs=null,now=()=>performance.now()}={}){
12
+ const started=now(),events=[];
13
+ let stdoutBytes=0,stderrBytes=0,exitCode=null,signal=null,closed=false;
14
+ let lastOperation=null,lastKind=null,lastState=null,lastCode=null,eventCount=0;
15
+ const elapsed=()=>Math.max(0,Math.round(now()-started));
16
+ const mark=(direction,row={})=>{
17
+ const operation=allowed(operations,row.operation??row.type);
18
+ const kind=allowed(kinds,row.kind),state=allowed(states,row.result?.state??row.result?.stage);
19
+ const code=allowed(codes,row.result?.code??row.error?.code);
20
+ if(direction==='send'&&operation)lastOperation=operation;
21
+ if(kind)lastKind=kind;if(state)lastState=state;if(code)lastCode=code;
22
+ events.push({n:++eventCount,elapsedMs:elapsed(),direction,operation,kind,state,code});
23
+ if(events.length>32)events.shift();
24
+ };
25
+ child.stdout?.on('data',chunk=>{stdoutBytes+=Buffer.byteLength(chunk);});
26
+ child.stderr?.on('data',chunk=>{stderrBytes+=Buffer.byteLength(chunk);});
27
+ child.once('close',(code,value)=>{closed=true;exitCode=Number.isInteger(code)?code:null;signal=allowed(signals,value);});
28
+ const snapshot=()=>({pid:Number.isInteger(child.pid)?child.pid:null,timeoutMs,elapsedMs:elapsed(),
29
+ closed,exitCode,signal,stdoutBytes,stderrBytes,eventCount,lastOperation,lastKind,lastState,lastCode,
30
+ events:events.map(event=>({...event}))});
31
+ return {send:row=>mark('send',row),receive:row=>mark('receive',row),snapshot,
32
+ attach:error=>Object.assign(error,{diagnostic:snapshot()})};
33
+ }
@@ -84,6 +84,38 @@ node "{CM_WORKFLOW_ROOT}/scripts/cm-ai-drive.mjs" --plan "{PLAN.json}" advance
84
84
 
85
85
  先按下节准备计划及真实答案文件。计划中的 `checks` 须为实际可执行的命令;驱动不接受静态检查结果代替执行。
86
86
 
87
+ ## 探活、等待与关闭
88
+
89
+ 九个单步驾驶员共用 `drive-core`,自动启用 `CM_HOST_HEARTBEAT=1`。手动驱动可在启动宿主前设置同一环境变量;未启用时保留旧 JSONL 输出。心跳只存在于当前连接,不是新的存档文件,不写 journal、不改变运行配置指纹,也不调用 runner 的 `status`。
90
+
91
+ 支持探活的 `host_ready` 增加 `heartbeat:{intervalMs:5000,timeoutMs:30000}`。随后宿主立即发送、每 5 秒续发 `host_heartbeat`:
92
+
93
+ ```json
94
+ {"type":"host_heartbeat","sessionId":"当前连接","pid":12345,"at":"2026-10-12T00:00:05.000Z","lastProgressAt":"2026-10-12T00:00:00.000Z","inFlight":{"requestId":"adv-1","operation":"advance","startedAt":"2026-10-12T00:00:00.000Z","stage":"check","nativeStage":null,"call":{"callId":"本次反问","kind":"check","startedAt":"2026-10-12T00:00:00.000Z","deadlineMs":1791764100000}}}
95
+ ```
96
+
97
+ `inFlight:null` 表示传输层当前没有在途操作。`call:null` 表示没有等待会话回复的反问。`nativeStage` 为已接入的原生检查或 runner 开发/审查阶段,包含 `id`、`kind`、`startedAt`、`deadlineMs`;两者都为空时 `stage` 只表示 operation,不推断内部阶段或子进程状态。`deadlineMs` 是反问的绝对截止时间(Unix 毫秒);心跳不携带业务 payload、代码或密钥。`lastProgressAt` 只随实际操作或反问变化,收到新心跳不代表工作取得进展。心跳不能证明检查通过、子进程退出或任务完成。
98
+
99
+ 重复 `advance` 返回 `host_busy` 时,错误包含 `inFlight` 的原 requestId、operation、阶段和开始时间。含义是“上一步仍在执行,继续等它的结果”。驾驶员继续接收原请求结果;手动驱动也须按原 requestId 读取,不能据此关闭宿主或重派开发。
100
+
101
+ 空闲时仍可发送原 `{"type":"host_close","sessionId":"…"}`。操作或反问在途时默认返回 `host_close_busy`,保持连接和原请求。确认要中断后,才发送 `{"type":"host_close","sessionId":"…","force":true}`;响应会警告原运行可能进入 `unknown`。驾驶员无法应答或应答被拒收时,会明确打印 force 中断原因。声明心跳的新宿主须先确认关闭,再结束输入;未声明能力的旧宿主使用已提示的 force + EOF 兼容路径,以保留旧宿主最终拒答结果。强制关闭、EOF、进程死亡均不等于用户取消。强制关闭后先核对原 run、实际文件和相关进程,再沿原恢复入口操作,不手改 journal 或自动重派审查。
102
+
103
+ 驾驶员默认等待期限:启动 60 秒;已声明心跳的宿主连续 30 秒无心跳即失败;反问与已接入原生阶段取原截止时间的较早者,加 30 秒清理余量。嵌套检查结束后恢复外层原截止时间,同一阶段的重复心跳不能延长预算。未声明阶段期限的操作(包括旧宿主)使用 6 小时后备上限;这不是已接入检查/审查的默认预算。完成结果或关闭请求后最多再等 5 秒;故障清理先 SIGTERM,1 秒后向仍存在的自有进程组发送 SIGKILL;宿主先退出也不取消这次清理,以覆盖忽略 SIGTERM 的同组子进程。只作用于驾驶员自己创建的进程/进程组。
104
+
105
+ | 驾驶员退出码 | 含义及处理 |
106
+ | --- | --- |
107
+ | 0 | 收到正常结果;仍按结果内 state/code 判断业务是否完成 |
108
+ | 1 | 宿主业务错误、unknown/reconcile 或应答失败;核对打印的原运行结果 |
109
+ | 2 | 计划、答案预检或需人工回答的问题阻断;补齐输入再继续 |
110
+ | 70 | `host_start_timeout`:启动后未按时收到 host_ready |
111
+ | 71 | `host_start_failed`/`host_exited`:无法启动或结果前宿主退出 |
112
+ | 72 | `host_heartbeat_timeout`:已声明的心跳超时,宿主可能卡死 |
113
+ | 73 | `host_stage_timeout`:阶段截止或无阶段信息的后备期限已到 |
114
+ | 74 | `host_pipe_closed`:管道读端已关闭,无法继续写入 |
115
+ | 75 | `host_close_timeout`:结果或关闭后,宿主/继承管道未按时结束 |
116
+
117
+ 驾驶员看门狗的超时是连接故障,不能写成业务成功。它只处置自己启动的宿主并中止自己的应答;不能据此认定所有脱离宿主的后代进程都已退出。旧宿主未声明心跳时保留兼容等待,但仍有启动和操作截止。宿主不会因为单项任务 `fixture_completed` 自动关闭,后续 QA 与收尾继续使用原合同。
118
+
87
119
  ## 单步驾驶员
88
120
 
89
121
  仓库自带 `../../../scripts/cm-ai-drive.mjs`,按上例一次启动宿主、发送一个 operation、回答这一轮的反问并打印结果。
@@ -253,7 +285,7 @@ check 数组,也不是 QA/文档结果。只回报已实际执行的事实,
253
285
 
254
286
  JS 返回阻断、待授权、失败、取消、unknown 或补正要求时,报告原因并保留磁盘证据;
255
287
  不重试未知调用、换 runId 绕过历史、手工勾 tasks 或启动旧兼容流程。允许 status 查询;
256
- 只有用户明确取消才发送 cancel。结束用 host_close;断联不是用户取消。
288
+ 只有用户明确取消才发送 cancel。空闲结束用 host_close;在途关闭按上文“探活、等待与关闭”处理,断联不是用户取消。
257
289
 
258
290
  ## 汇报与能力边界
259
291