@aibyzero/cm-workflow 0.18.0 → 0.19.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/CHANGELOG.md +18 -0
- package/README.md +7 -1
- package/VERSION +1 -1
- package/docs/installation.md +1 -1
- package/package.json +1 -1
- package/runtime/js/autonomy.mjs +152 -0
- package/runtime/js/cm-ai/cm-ai-admission.mjs +39 -6
- package/runtime/js/cm-ai/drive-core.mjs +2 -1
- package/runtime/js/notify.mjs +17 -8
- package/runtime/js/specs-status.mjs +4 -3
- package/scripts/cm-ai-admission.mjs +10 -2
- package/scripts/cm-ai-admission.test.mjs +148 -1
- package/scripts/cm-autonomy.mjs +94 -0
- package/scripts/cm-autonomy.test.mjs +162 -0
- package/scripts/cm-check-runtime.sh +2 -0
- package/scripts/cm-notify.test.mjs +6 -0
- package/scripts/cm-start-check.mjs +119 -4
- package/scripts/cm-start-check.test.mjs +87 -2
- 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 +27 -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
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cm-workflow",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.19.0",
|
|
4
4
|
"description": "Spec-driven product development workflow for Codex: external research, PRD, implementation, read-only feature testing, review, QA, fixes, refactors, and documentation.",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "cm-workflow maintainers",
|
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,24 @@
|
|
|
5
5
|
|
|
6
6
|
## 未发布
|
|
7
7
|
|
|
8
|
+
## 0.19.0 — 2026-11-01
|
|
9
|
+
|
|
10
|
+
- **新增常设授权:一路执行到底,只在致命问题时停下并用手机提醒**(aihot 第二批实测:四个功能停下等人十几次):
|
|
11
|
+
- 用户明确要求后,用 `cm-autonomy.mjs on --response "<用户原话>"` 开启,`off` 关闭,`show` 查看;只认用户原话。
|
|
12
|
+
- 开启后任务、功能之间不再等「继续」;审查轮次或重试用完时查清根因后自动新建运行重做,每次先用 `cm-autonomy.mjs reopen` 领名额,同一任务最多自动重开 2 次;开发中途只改设计、任务或生成用例的规格变更先用 `cm-autonomy.mjs check-proposal` 预检,再用 `cm-ai-admission.mjs --approve --standing-authorization` 自行批准(核对归档与磁盘规格完全一致),改需求、增删功能或动用户用例的一律拒绝。
|
|
13
|
+
- 致命问题(改需求或用户用例、新截图要认作基准、同一任务自动重开 2 次仍失败、额度用完、要本人操作、安全或丢数据风险)先用 `cm-autonomy.mjs notify --kind fatal` 立即推送,再停下;全部完成时推送一条完成提醒。
|
|
14
|
+
- 开启期间驾驶员的停车提醒一律延后、会话接着推进就作废,单个运行完成不再推送;致命提醒不受限流,没发出时命令以 1 退出。延后提醒到点后不再被 10 分钟窗口限流吞掉(所有用户)。检查、审查和完成门禁一律不放宽。
|
|
15
|
+
|
|
16
|
+
- **开发中途改规格,只需确认一次**(aihot 第二批实测:任务范围外改一行修复,要连续确认三次——要不要走规格变更、确认提案、回「开始」):
|
|
17
|
+
- 开发中途要扩范围或补修复点时,不再先问要不要走规格变更,直接起草变更提案。提案卡只问一句:回「开始」即确认提案、保存规格并放行开发,卡上写明的后续动作(如开替代运行)一并放行。
|
|
18
|
+
- 审批绑定到这份提案:`cm-ai-admission.mjs --approve` 新增 `--expect-revision-digest`,只有规格状态仍是这份提案保存后的待审、且规格文件与保存时一致才写审批位,否则拒绝(`revision_digest_mismatch`/`revision_files_changed`);核对后到写入前规格被改、另一提案保存或重复审批先落盘,也拒绝(`revision_changed_during_approval`),不覆盖对方结果。
|
|
19
|
+
- 照旧分两步的情形:要删除或弱化用户用例、只回「确认提案」等非开始短语、或要求先人审规格。「开始」的认定短语不变。
|
|
20
|
+
|
|
21
|
+
- **每个任务的测试按风险分层,改了共用模块的任务开工前会被提醒补测**(aihot 第二批实测:单元测试约 45 秒,界面测试每个任务 20 多分钟,而 cm-ai 单次检查整步上限 30 分钟):
|
|
22
|
+
- `/cm:prd` 拆任务时,每个任务的验证要求分三层写:单元测试全跑;界面测试只跑本任务新写的和改动直接牵连的旧测试;功能最后的回归任务跑本功能受影响的全部界面测试,超过 30 分钟拆成几个回归任务分批跑。改了共用模块(如请求排队、滚动定位)的任务,牵连的旧界面测试必须当场跑,不能留到末尾。
|
|
23
|
+
- 「哪些文件牵连哪些旧界面测试」由项目自己记在代码根 `TESTING.md`(或 `docs/TESTING.md`)的「## 牵连测试」表里,每行 `| 改动路径(目录以 / 结尾) | 测试标识 |`。
|
|
24
|
+
- 开工体检 `cm-start-check.mjs` 读这张表:任务范围改到表里的路径、检查里却没跑对应测试时给 warn(`affected_tests_not_run`);没有这张表、检查又只跑了部分界面测试(`-only-testing`)时给 info,说明没能核对。超过 30 分钟的提醒也改为先建议按分层缩减。只是提醒,不拦创建;N4 审查、完成门禁和在途运行不变。
|
|
25
|
+
|
|
8
26
|
## 0.18.0 — 2026-10-30
|
|
9
27
|
|
|
10
28
|
- **修复:设计审完后,四个 feature 的任务交不上去**:`/cm:prd` 设计阶段之后生成任务时,回包以前必须把已审的需求和设计原样再带一遍,整包又不能超过 64 KB;已审文档一大(aihot 四个 feature 约 53 KB),任务和测试用例就放不下。现在这一步的回包可以只给 `tasks.md` 和适用的 `test-cases.json`,宿主和驾驶员预检按已接受设计的原字节补回需求和设计,64 KB 只算新回的文档。照旧带全文的回包仍要逐字一致;改写需求或设计、文档重复、feature 名或数量不符照旧拒绝。已经停在 `design_ready` 的会话直接 advance 即可,不用新建会话,审查轮次不变。
|
package/README.md
CHANGED
|
@@ -17,6 +17,12 @@
|
|
|
17
17
|
|
|
18
18
|
## 最近更新
|
|
19
19
|
|
|
20
|
+
**0.19.0**
|
|
21
|
+
|
|
22
|
+
- **每个任务的测试按风险分层**:`/cm:prd` 拆任务时单元测试全跑,界面测试只跑本任务新写的和直接牵连的旧测试,功能末尾再统一回归;改了共用模块却没跑牵连测试,开工体检会提醒(牵连关系记在项目 `TESTING.md` 的「牵连测试」表)。
|
|
23
|
+
- **开发中途改规格只确认一次**:提案卡只问一次「开始」,确认、保存、放行一步完成;审批绑定到你确认的那份提案。
|
|
24
|
+
- **常设授权:一路执行到底**:用 `cm-autonomy.mjs on` 按你的原话开启后,任务之间自动继续、审查没过自动修好重做(同一任务最多 2 次),只在改需求、额度用完等致命问题时停下并立即手机提醒。默认关闭。详见[更新日志](CHANGELOG.md)。
|
|
25
|
+
|
|
20
26
|
**0.18.0**
|
|
21
27
|
|
|
22
28
|
- **升级注意(开发方式)**:`/cm-ai` 新批次默认按 `tasks.md` 自动分组,符合条件的任务各自在 worktree 开发,独立任务可并行;功能末任务、要用设备的任务和部分 QA 场景仍在主目录串行。项目配置写 `parallel: {enabled: false}` 完全不建 worktree,写 `parallel: {worktree_all: false}` 恢复以前只让可并行任务进 worktree 的做法。升级前已开始的运行和批次按原配置恢复。
|
|
@@ -256,7 +262,7 @@ $cm-check
|
|
|
256
262
|
|
|
257
263
|
仓库直接分发 Skills 和脚本,无需在仓库根目录运行 `npm install` 或构建。完整安装行为、覆盖范围和卸载说明见[安装指南](docs/installation.md)。
|
|
258
264
|
|
|
259
|
-
需要固定版本时可使用 `npx @aibyzero/cm-workflow@0.
|
|
265
|
+
需要固定版本时可使用 `npx @aibyzero/cm-workflow@0.19.0 install`,请在 CM Workflow 源码仓库以外的目录执行,例如用户主目录。npm 安装入口复用原安装器,要求与覆盖范围见[安装指南](docs/installation.md#npm-installation-macos-codex)。
|
|
260
266
|
|
|
261
267
|
## 升级旧版本
|
|
262
268
|
|
package/VERSION
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
0.
|
|
1
|
+
0.19.0
|
package/docs/installation.md
CHANGED
|
@@ -76,7 +76,7 @@ Install or upgrade with the same command:
|
|
|
76
76
|
npx @aibyzero/cm-workflow@latest install
|
|
77
77
|
```
|
|
78
78
|
|
|
79
|
-
To pin a version, use `npx @aibyzero/cm-workflow@0.
|
|
79
|
+
To pin a version, use `npx @aibyzero/cm-workflow@0.19.0 install` from outside
|
|
80
80
|
the CM Workflow source checkout (for example, your home directory). Inside a
|
|
81
81
|
checkout with the same package name and version, npm can select the local
|
|
82
82
|
uninstalled package and report `cm-workflow: command not found`.
|
package/package.json
CHANGED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
// Standing "run to the end" authorization (scripts/cm-autonomy.mjs). Like
|
|
2
|
+
// --approval-response, the session relays the person's own words; the record
|
|
3
|
+
// changes three things: a driver stop waits waitMinutes instead of paging at once
|
|
4
|
+
// (the session usually carries on), cm-ai admission may approve a change proposal
|
|
5
|
+
// that leaves the requirement contract alone, and the session may reopen a task
|
|
6
|
+
// up to AUTO_REOPEN_LIMIT times. Fatal stops page at once (cm-autonomy.mjs notify).
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
import os from 'node:os';
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import {randomUUID,createHash} from 'node:crypto';
|
|
11
|
+
|
|
12
|
+
export const AUTONOMY_FILE='autonomy.json',AUTONOMY_OFF_FILE='autonomy.off.json',REOPEN_DIR='autonomy-reopens',AUTO_REOPEN_LIMIT=2;
|
|
13
|
+
// Same directory as notify.json (notify.mjs notifyHome); kept here so notify.mjs can import this module.
|
|
14
|
+
export const autonomyHome=(env=process.env)=>path.resolve(env.CM_WORKFLOW_HOME||path.join(os.homedir(),'.cm-workflow'));
|
|
15
|
+
const iso=value=>typeof value==='string'&&/^\d{4}-\d\d-\d\dT/.test(value)&&Number.isFinite(Date.parse(value));
|
|
16
|
+
const words=value=>typeof value==='string'&&value.trim()!==''&&Array.from(value).length<=500;
|
|
17
|
+
const record=value=>value!==null&&typeof value==='object'&&!Array.isArray(value);
|
|
18
|
+
|
|
19
|
+
function readJson(file){
|
|
20
|
+
try{if(!fs.lstatSync(file).isFile())return {invalid:true};return {value:JSON.parse(fs.readFileSync(file,'utf8'))};}
|
|
21
|
+
catch(error){return error.code==='ENOENT'?{missing:true}:{invalid:true};}
|
|
22
|
+
}
|
|
23
|
+
function writeJson(home,name,value){
|
|
24
|
+
fs.mkdirSync(home,{recursive:true,mode:0o700});
|
|
25
|
+
const target=path.join(home,name),temporary=path.join(home,`.${name}-${randomUUID()}`);
|
|
26
|
+
try{fs.writeFileSync(temporary,JSON.stringify(value,null,1)+'\n',{mode:0o600,flag:'wx'});fs.renameSync(temporary,target);}
|
|
27
|
+
finally{try{fs.unlinkSync(temporary);}catch(error){if(error.code!=='ENOENT')throw error;}}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// {on:true,value} only for a regular file the writer below would produce; anything else is off.
|
|
31
|
+
export function readAutonomy(env=process.env){
|
|
32
|
+
const read=readJson(path.join(autonomyHome(env),AUTONOMY_FILE));
|
|
33
|
+
if(read.missing)return {on:false,reason:'missing'};
|
|
34
|
+
const value=read.value;
|
|
35
|
+
if(read.invalid||!record(value)||Object.keys(value).sort().join()!=='at,mode,response,version'
|
|
36
|
+
||value.version!==1||value.mode!=='until_fatal'||!words(value.response)||!iso(value.at))return {on:false,reason:'invalid'};
|
|
37
|
+
return {on:true,value:{version:1,mode:'until_fatal',response:value.response,at:value.at}};
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function writeAutonomy(response,{env=process.env,now=Date.now()}={}){
|
|
41
|
+
if(!words(response))throw new Error('autonomy_response_invalid');
|
|
42
|
+
const value={version:1,mode:'until_fatal',response,at:new Date(now).toISOString()};
|
|
43
|
+
writeJson(autonomyHome(env),AUTONOMY_FILE,value);
|
|
44
|
+
return value;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// Turning it off keeps the record (renamed) so the last grant stays auditable.
|
|
48
|
+
export function clearAutonomy({env=process.env}={}){
|
|
49
|
+
const home=autonomyHome(env);
|
|
50
|
+
try{fs.renameSync(path.join(home,AUTONOMY_FILE),path.join(home,AUTONOMY_OFF_FILE));return true;}
|
|
51
|
+
catch(error){if(error.code==='ENOENT')return false;throw error;}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// Automatic reopens per task. Each reopen claims one numbered slot file with an
|
|
55
|
+
// exclusive create, which is atomic: concurrent takers (any project) can never
|
|
56
|
+
// claim the same slot, and there is no lock to reclaim. A slot left half-written
|
|
57
|
+
// by a crash still counts. {count} when a slot was claimed, {refused:true,count}
|
|
58
|
+
// when all AUTO_REOPEN_LIMIT are taken (a fatal stop).
|
|
59
|
+
const reopenKey=(project,task)=>`${path.resolve(project)}|${task}`;
|
|
60
|
+
const slotPrefix=key=>createHash('sha256').update(key).digest('hex').slice(0,32);
|
|
61
|
+
// Counted by slot file name, like takeReopen; a group whose files are all unreadable is still shown.
|
|
62
|
+
export function readReopens(env=process.env){
|
|
63
|
+
const dir=path.join(autonomyHome(env),REOPEN_DIR),groups={};
|
|
64
|
+
let names;try{names=fs.readdirSync(dir);}catch(error){if(error.code==='ENOENT')return {};throw error;}
|
|
65
|
+
for(const name of names){
|
|
66
|
+
const prefix=/^([0-9a-f]{32})-\d+$/.exec(name)?.[1];if(!prefix)continue;
|
|
67
|
+
let key=null;try{key=JSON.parse(fs.readFileSync(path.join(dir,name),'utf8')).key;}catch{}
|
|
68
|
+
const group=groups[prefix]??={key:null,count:0};group.count++;
|
|
69
|
+
if(typeof key==='string'&&slotPrefix(key)===prefix)group.key=key;
|
|
70
|
+
}
|
|
71
|
+
return Object.fromEntries(Object.entries(groups).map(([prefix,{key,count}])=>[key??`未识别|名额 ${prefix}`,count]));
|
|
72
|
+
}
|
|
73
|
+
export function takeReopen(project,task,{env=process.env,now=Date.now()}={}){
|
|
74
|
+
if(typeof task!=='string'||!/^\d+\.[^/\\\s]+\/T-\d+$/.test(task))throw new Error('autonomy_task_invalid');
|
|
75
|
+
const dir=path.join(autonomyHome(env),REOPEN_DIR),key=reopenKey(project,task);
|
|
76
|
+
// A count kept some other way is never taken as "none yet".
|
|
77
|
+
if(fs.existsSync(path.join(autonomyHome(env),'autonomy-reopens.json')))throw new Error('autonomy_reopens_legacy');
|
|
78
|
+
fs.mkdirSync(dir,{recursive:true,mode:0o700});
|
|
79
|
+
for(let slot=1;slot<=AUTO_REOPEN_LIMIT;slot++){
|
|
80
|
+
try{fs.writeFileSync(path.join(dir,`${slotPrefix(key)}-${slot}`),JSON.stringify({key,slot,at:new Date(now).toISOString()})+'\n',{flag:'wx',mode:0o600});}
|
|
81
|
+
catch(error){if(error.code==='EEXIST')continue;throw error;}
|
|
82
|
+
return {count:slot};
|
|
83
|
+
}
|
|
84
|
+
return {refused:true,count:AUTO_REOPEN_LIMIT};
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const DOCUMENTS=['requirements.md','design.md','tasks.md'],CHANGEABLE=new Set(['design.md','tasks.md','test-cases.json']);
|
|
88
|
+
const userCases=source=>{
|
|
89
|
+
if(source===undefined)return new Map();
|
|
90
|
+
const cases=JSON.parse(source)?.cases;
|
|
91
|
+
if(!Array.isArray(cases))throw new Error('cases');
|
|
92
|
+
return new Map(cases.filter(item=>item?.origin==='user').map(item=>[item.id,JSON.stringify(item)]));
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
// Whether a change proposal may be approved under the standing authorization,
|
|
96
|
+
// judged from the complete before/after contents: it may change design, tasks and
|
|
97
|
+
// generated cases of existing features, never a requirement, the feature list or a
|
|
98
|
+
// user case. Returns null when it may, else the reason in plain words.
|
|
99
|
+
export function standingProposalProblem(before,proposal){
|
|
100
|
+
if(!record(before)||!Array.isArray(before.directories)||!before.directories.every(dir=>typeof dir==='string')
|
|
101
|
+
||!record(before.files)||!Object.values(before.files).every(value=>typeof value==='string')
|
|
102
|
+
||!record(proposal)||!record(proposal.files)||!Object.keys(proposal.files).length
|
|
103
|
+
||!Object.values(proposal.files).every(value=>typeof value==='string')
|
|
104
|
+
||!Array.isArray(proposal.changedUserCases)||!Array.isArray(proposal.removed))return '提案内容不完整,无法判断';
|
|
105
|
+
if(proposal.changedUserCases.length)return '提案删除或减弱了用户用例';
|
|
106
|
+
if(proposal.removed.length)return '提案删除了功能';
|
|
107
|
+
const features=new Set(Object.keys(proposal.files).map(file=>file.split('/')[0]));
|
|
108
|
+
for(const feature of features){
|
|
109
|
+
if(!before.directories.includes(feature))return '提案新增了功能';
|
|
110
|
+
if(DOCUMENTS.some(name=>typeof proposal.files[`${feature}/${name}`]!=='string'))return '提案内容不完整,无法判断';
|
|
111
|
+
}
|
|
112
|
+
for(const [file,content] of Object.entries(proposal.files)){
|
|
113
|
+
const [feature,name,...rest]=file.split('/');
|
|
114
|
+
if(rest.length||!DOCUMENTS.includes(name)&&name!=='test-cases.json')return `提案改了规格以外的文件(${file})`;
|
|
115
|
+
if(content!==before.files[file]&&!CHANGEABLE.has(name))return '提案改了需求';
|
|
116
|
+
}
|
|
117
|
+
for(const feature of features){
|
|
118
|
+
const file=`${feature}/test-cases.json`;
|
|
119
|
+
let was,now;
|
|
120
|
+
// A test-cases.json the proposal leaves out is deleted on save: its user cases count as removed.
|
|
121
|
+
try{was=userCases(before.files[file]);now=userCases(proposal.files[file]);}
|
|
122
|
+
catch{return '提案的测试用例无法解析';}
|
|
123
|
+
for(const [id,item] of was)if(now.get(id)!==item)return '提案删除或减弱了用户用例';
|
|
124
|
+
}
|
|
125
|
+
return null;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// The saved archive (.reviews/prd-change-<digest>.json) must be this proposal and
|
|
129
|
+
// must be exactly what the specs now hold: features listed, proposal files written,
|
|
130
|
+
// every other feature untouched.
|
|
131
|
+
export function standingArchiveProblem(specsDir,archive,digest){
|
|
132
|
+
if(!record(archive)||archive.proposal?.proposalDigest!==digest)return '找不到这份提案的归档';
|
|
133
|
+
const problem=standingProposalProblem(archive.before,archive.proposal);
|
|
134
|
+
if(problem)return problem;
|
|
135
|
+
const {before,proposal}=archive;
|
|
136
|
+
const listed=fs.readdirSync(specsDir).filter(dir=>/^\d+\./.test(dir)).sort();
|
|
137
|
+
if(listed.join('\n')!==[...before.directories].sort().join('\n'))return '规格目录的功能与提案不一致';
|
|
138
|
+
// What the save leaves (cm-prd change.mjs applyPrdChange): the selected features hold
|
|
139
|
+
// exactly the proposal's files, every other feature its original ones. Compare the
|
|
140
|
+
// complete spec file set, so a file the archive does not list cannot stay on disk.
|
|
141
|
+
const selected=Array.isArray(archive.selected)?archive.selected:[...new Set(Object.keys(proposal.files).map(file=>file.split('/')[0]))];
|
|
142
|
+
const expected={...before.files};
|
|
143
|
+
for(const file of Object.keys(expected))if(selected.includes(file.split('/')[0]))delete expected[file];
|
|
144
|
+
Object.assign(expected,proposal.files);
|
|
145
|
+
const onDisk={};
|
|
146
|
+
for(const dir of listed)for(const name of [...DOCUMENTS,'test-cases.json']){
|
|
147
|
+
const file=`${dir}/${name}`;try{onDisk[file]=fs.readFileSync(path.join(specsDir,file),'utf8');}catch(error){if(error.code!=='ENOENT')return '规格文件与提案不一致';}
|
|
148
|
+
}
|
|
149
|
+
const files=Object.keys(expected).sort();
|
|
150
|
+
if(files.join('\n')!==Object.keys(onDisk).sort().join('\n')||files.some(file=>onDisk[file]!==expected[file]))return '规格文件与提案不一致';
|
|
151
|
+
return null;
|
|
152
|
+
}
|
|
@@ -5,6 +5,7 @@ import { createHash } from 'node:crypto';
|
|
|
5
5
|
import { spawnSync } from 'node:child_process';
|
|
6
6
|
import { fileURLToPath } from 'node:url';
|
|
7
7
|
import {readSpecsStatus,writeSpecsStatus} from '../specs-status.mjs';
|
|
8
|
+
import {readAutonomy,standingArchiveProblem} from '../autonomy.mjs';
|
|
8
9
|
import {identifyApprovedBootstrapFeature} from './bootstrap-feature.mjs';
|
|
9
10
|
import {buildManifest,verifyApprovedManifest} from '../../../scripts/cm-spec-manifest.mjs';
|
|
10
11
|
import {outstandingFeatureQa,describeOutstandingQa} from './project-qa-gate.mjs';
|
|
@@ -381,18 +382,49 @@ export function inspectCmAiAdmission(options){
|
|
|
381
382
|
// The CLI supplies every code project so no project can be skipped before writing.
|
|
382
383
|
export function approveCmAiSpecs(options){
|
|
383
384
|
const projects=options.codeProjects??[options.codeProject];
|
|
384
|
-
|
|
385
|
+
// The standing authorization (autonomy.mjs) stands in for the reply, and only for a bound change proposal.
|
|
386
|
+
const standing=options.standingAuthorization===true?readAutonomy(options.env):null;
|
|
387
|
+
const inspect=()=>projects.map(codeProject=>inspectCmAiAdmission({...options,...(standing?.on?{assumeYes:true}:{}),codeProject}));
|
|
385
388
|
const projectResults=inspect();
|
|
386
389
|
const refuse=(approveRefused,approveReason=null)=>({projectResults,approveRefused,...(approveReason?{approveReason}:{})});
|
|
387
390
|
if(options.assumeYes)return refuse('assume_yes_not_allowed');
|
|
388
|
-
if(
|
|
391
|
+
if(standing&&!standing.on)return refuse('standing_authorization_off');
|
|
392
|
+
if(standing&&(options.expectRevisionDigest===undefined||options.approvalResponse!==undefined))
|
|
393
|
+
return refuse('standing_authorization_not_applicable','常设授权只用于绑定提案摘要的规格变更,且不与用户原话同用');
|
|
394
|
+
const approvalResponse=standing?`常设授权(${standing.value.at}):${standing.value.response}`:options.approvalResponse;
|
|
395
|
+
if(typeof approvalResponse!=='string'||!approvalResponse.trim())
|
|
389
396
|
return refuse('approval_response_required');
|
|
390
397
|
const allowed=new Set(['approval_write_required','spec_features_changed','test_cases_changed']);
|
|
391
398
|
const rejected=projectResults.find(item=>item.state!=='awaiting_spec_approval'
|
|
392
399
|
||item.approvalIntent!=='explicit'||!allowed.has(item.reason));
|
|
393
400
|
if(rejected)return refuse(rejected.approvalIntent!=='explicit'?'explicit_approval_required':rejected.reason);
|
|
394
|
-
const specsDir=projectResults[0].specsDir,status=readSpecsStatus(specsDir);
|
|
401
|
+
const specsDir=projectResults[0].specsDir,status=readSpecsStatus(specsDir,{withBytes:true});
|
|
395
402
|
if(status.kind==='invalid')return refuse('spec_status_invalid');
|
|
403
|
+
// A change confirmed together with "开始" binds this approval to the saved proposal:
|
|
404
|
+
// any other status, or spec bytes that moved since the save, is not what the user saw.
|
|
405
|
+
// The write re-checks both just before its rename, so changes after this check are refused too.
|
|
406
|
+
let bound=null;
|
|
407
|
+
if(options.expectRevisionDigest!==undefined){
|
|
408
|
+
if(status.kind!=='valid'||status.value.status!=='awaiting_review'
|
|
409
|
+
||status.value.revisionDigest!==options.expectRevisionDigest)return refuse('revision_digest_mismatch');
|
|
410
|
+
const statusFile=path.join(specsDir,'.cm-specs-status'),saved=status.value.specFiles;
|
|
411
|
+
const unchanged=()=>{try{return Array.isArray(saved)&&JSON.stringify(saved)===JSON.stringify(buildManifest(specsDir));}catch{return false;}};
|
|
412
|
+
if(!unchanged())return refuse('revision_files_changed');
|
|
413
|
+
if(standing){
|
|
414
|
+
let archive=null;
|
|
415
|
+
try{const file=path.join(specsDir,'.reviews',`prd-change-${options.expectRevisionDigest}.json`);
|
|
416
|
+
if(path.dirname(fs.realpathSync(file))===fs.realpathSync(path.join(specsDir,'.reviews')))archive=JSON.parse(fs.readFileSync(file,'utf8'));}
|
|
417
|
+
catch{}
|
|
418
|
+
const problem=standingArchiveProblem(specsDir,archive,options.expectRevisionDigest);
|
|
419
|
+
if(problem)return refuse('standing_authorization_not_applicable',`${problem},要用户本人确认`);
|
|
420
|
+
}
|
|
421
|
+
// The baseline is the very bytes just validated, never a later re-read.
|
|
422
|
+
bound={statusBytes:status.bytes,saved,check(){
|
|
423
|
+
options.beforeApprovalWrite?.();
|
|
424
|
+
if(!fs.readFileSync(statusFile).equals(this.statusBytes)||!unchanged())
|
|
425
|
+
throw Object.assign(new Error('revision_changed_during_approval'),{code:'revision_changed_during_approval'});
|
|
426
|
+
}};
|
|
427
|
+
}
|
|
396
428
|
try{
|
|
397
429
|
const discovered=discoverFeatures(specsDir);
|
|
398
430
|
if(discovered.error)return refuse(discovered.error);
|
|
@@ -427,11 +459,12 @@ export function approveCmAiSpecs(options){
|
|
|
427
459
|
+differing.slice(0,5).map(item=>`第 ${item.line} 行 ${item.text}`).join(';')+`${differing.length>5?` 等 ${differing.length} 行`:''}`
|
|
428
460
|
+'。此前的批准不把这些行当任务(或反之);是示例就放进 ``` 围栏或删去,是任务就改用英文冒号「:」写法后再批准。');
|
|
429
461
|
}
|
|
430
|
-
const specFiles=buildManifest(specsDir),at=new Date().toISOString();
|
|
462
|
+
const specFiles=bound?bound.saved:buildManifest(specsDir),at=new Date().toISOString();
|
|
431
463
|
writeSpecsStatus(specsDir,{status:'approved',summaryDigest:status.value?.summaryDigest??null,at,
|
|
432
464
|
features:discovered.names,specFiles,testCases:specFiles.filter(item=>item.path.endsWith('/test-cases.json')),
|
|
433
|
-
approval:{response:
|
|
434
|
-
...(status.value&&Object.hasOwn(status.value,'revisionDigest')?{revisionDigest:status.value.revisionDigest}:{})}
|
|
465
|
+
approval:{response:approvalResponse,at},taskGrammar:grammar,
|
|
466
|
+
...(status.value&&Object.hasOwn(status.value,'revisionDigest')?{revisionDigest:status.value.revisionDigest}:{})},
|
|
467
|
+
bound?{beforeRename:()=>bound.check()}:{});
|
|
435
468
|
}catch(error){return refuse(error.code??error.message);}
|
|
436
469
|
return {projectResults:inspect()};
|
|
437
470
|
}
|
|
@@ -105,7 +105,8 @@ export function driveHost({host,args,cwd,operation,request={},answers,paths,answ
|
|
|
105
105
|
// the session moves on (notifyLater); a rate limit after this driver's own
|
|
106
106
|
// retries is sent at once and says how many were tried.
|
|
107
107
|
const sendNotice=(fields,mod)=>{
|
|
108
|
-
|
|
108
|
+
// Under the standing authorization the session retries on its own: the stop still waits.
|
|
109
|
+
if(!failureCode&&rateLimitedReview(finalRow)&&retriesDone>0)fields={...fields,rateLimitRetries:retriesDone,...(fields.autonomous?{}:{delivery:'now'})};
|
|
109
110
|
if(fields.delivery!=='later')return mod.notify(fields);
|
|
110
111
|
// An unsafe pending directory already produced its once-a-day fault notice
|
|
111
112
|
// and the stop is not sent; any other failure to schedule (state busy, write
|
package/runtime/js/notify.mjs
CHANGED
|
@@ -12,6 +12,7 @@ import {spawn} from 'node:child_process';
|
|
|
12
12
|
import {fileURLToPath} from 'node:url';
|
|
13
13
|
import {createHash,randomUUID} from 'node:crypto';
|
|
14
14
|
import {readRegularFileSync} from './notify-safe-read.mjs';
|
|
15
|
+
import {readAutonomy} from './autonomy.mjs';
|
|
15
16
|
|
|
16
17
|
export const NOTIFY_LIMITS=Object.freeze({sameKeyMs:6*3600*1000,perDay:150,
|
|
17
18
|
windowMs:10*60000,perWindow:3,followUpMs:2*3600*1000,attentionTtlMs:24*3600*1000,
|
|
@@ -563,7 +564,7 @@ function dropPending(home,hash,before){
|
|
|
563
564
|
if(pending?.missing||pending&&pending.at>before)return false;
|
|
564
565
|
return removePending(home,hash);
|
|
565
566
|
}
|
|
566
|
-
function reserve(home,{hash,attention=null,event,code=null,pendingToken},now,limits){
|
|
567
|
+
function reserve(home,{hash,attention=null,event,code=null,pendingToken,urgent=false},now,limits){
|
|
567
568
|
return withState(home,state=>{
|
|
568
569
|
// A deferred waiter fires only for its own still-pending stop; any other
|
|
569
570
|
// notice about the same session supersedes a pending one.
|
|
@@ -587,7 +588,10 @@ function reserve(home,{hash,attention=null,event,code=null,pendingToken},now,lim
|
|
|
587
588
|
else return {status:'duplicate'};
|
|
588
589
|
}
|
|
589
590
|
const persist=extra=>writeState(home,{version:2,keys,attention:records,sends,suppressed:state.suppressed,...extra});
|
|
590
|
-
|
|
591
|
+
// A fatal stop (urgent) is never rate limited. A deferred stop already waited and its
|
|
592
|
+
// pending record is gone, so neither limit may lose it for good: each one is a real
|
|
593
|
+
// stop the session did not move past within waitMinutes, which already bounds them.
|
|
594
|
+
if(!urgent&&pendingToken===undefined&&(sends.filter(at=>now-at<limits.windowMs).length>=limits.perWindow||sends.length>=NOTIFY_LIMITS.perDay)){
|
|
591
595
|
const status=sends.length>=NOTIFY_LIMITS.perDay?'rate_day':'rate_window';
|
|
592
596
|
return persist({suppressed:state.suppressed+1})?{status}:{status:'state_write_failed'};
|
|
593
597
|
}
|
|
@@ -696,7 +700,7 @@ export async function sendPendingNotice(fields,token,{env=process.env,attempts=2
|
|
|
696
700
|
const LEVEL_OF=Object.freeze({done:'passive',idle:'active'});
|
|
697
701
|
// Never throws and never waits. Returns {sent, reason}; sent means the command
|
|
698
702
|
// was handed to the detached launcher, whose own failures go to notify.log.
|
|
699
|
-
export function notify(fields,{env=process.env,now=Date.now(),timeoutMs=NOTIFY_LIMITS.commandTimeoutMs,pendingToken}={}){
|
|
703
|
+
export function notify(fields,{env=process.env,now=Date.now(),timeoutMs=NOTIFY_LIMITS.commandTimeoutMs,pendingToken,urgent=false}={}){
|
|
700
704
|
try{
|
|
701
705
|
const config=readNotifyConfig(env);if(!config)return {sent:false,reason:'off'};
|
|
702
706
|
if(typeof fields?.key!=='string'||!fields.key)return {sent:false,reason:'invalid_key'};
|
|
@@ -704,7 +708,7 @@ export function notify(fields,{env=process.env,now=Date.now(),timeoutMs=NOTIFY_L
|
|
|
704
708
|
const attention=typeof fields.attentionKey==='string'&&fields.attentionKey&&Object.hasOwn(ATTENTION_LEVEL,event)
|
|
705
709
|
?keyHash(fields.attentionKey):null;
|
|
706
710
|
if(pendingToken!==undefined&&attention===null)return {sent:false,reason:'cancelled'};
|
|
707
|
-
const reserved=reserve(home,{hash,attention,event,code:clean(fields.code,64)||null,pendingToken},now,config);
|
|
711
|
+
const reserved=reserve(home,{hash,attention,event,code:clean(fields.code,64)||null,pendingToken,urgent:urgent===true},now,config);
|
|
708
712
|
if(reserved.status!=='ok'){
|
|
709
713
|
if(!['duplicate','cancelled'].includes(reserved.status))appendNotifyLog(home,now,{event,workflow,hash,result:`skipped ${reserved.status}`});
|
|
710
714
|
return {sent:false,reason:reserved.status};
|
|
@@ -964,11 +968,15 @@ export function classifyDriveResult(workflow,row){
|
|
|
964
968
|
const kind=classifyRaw(workflow,row);
|
|
965
969
|
return kind==='ask'?'stuck':kind;
|
|
966
970
|
}
|
|
967
|
-
export function driveNotice({host,cwd,args=[],operation,row=null,failure=null}){
|
|
971
|
+
export function driveNotice({host,cwd,args=[],operation,row=null,failure=null,env=process.env}){
|
|
968
972
|
if(READ_ONLY.has(operation))return null;
|
|
973
|
+
// Under the standing authorization the session decides: a finished unit is not news,
|
|
974
|
+
// and any stop waits waitMinutes (dropped once the session moves on). Fatal stops
|
|
975
|
+
// page at once from the session itself (cm-autonomy.mjs notify).
|
|
976
|
+
const autonomous=readAutonomy(env).on;
|
|
969
977
|
const workflow=path.basename(String(host??'')).replace(/-host\.mjs$/,'').replace(/\.mjs$/,'')||'cm';
|
|
970
978
|
const raw=failure?'stuck':classifyRaw(workflow,row),kind=raw==='ask'?'stuck':raw,ask=raw==='ask';
|
|
971
|
-
if(!kind)return null;
|
|
979
|
+
if(!kind||autonomous&&kind==='done')return null;
|
|
972
980
|
const done=kind==='done',result=obj(row?.result),progress=obj(result.progress),nested=obj(result.result);
|
|
973
981
|
const code=text(failure)??text(row?.error?.code)??text(result.code)??text(result.reason)??text(result.blocker)
|
|
974
982
|
??text(progress.blocker)??text(result.overall)??text(nested.overall)??text(result.state)??text(result.status)??text(result.stage)??null;
|
|
@@ -981,7 +989,7 @@ export function driveNotice({host,cwd,args=[],operation,row=null,failure=null}){
|
|
|
981
989
|
const reviewFailure=typeof result.reviewFailure==='string'&&/^reviewer_[a-z_]{1,48}$/.test(result.reviewFailure)?result.reviewFailure:null;
|
|
982
990
|
const developFailure=typeof result.developFailure==='string'&&/^developer_[a-z_]{1,48}$/.test(result.developFailure)?result.developFailure:null;
|
|
983
991
|
const pendingAction=typeof result.pendingAction==='string'&&/^[a-z_]{1,32}$/.test(result.pendingAction)?result.pendingAction:null;
|
|
984
|
-
const delivery=done
|
|
992
|
+
const delivery=done||!autonomous&&immediateStop({codes:[failure,row?.error?.code,result.code,result.reason,result.blocker,progress.blocker],
|
|
985
993
|
state:text(result.state),pendingAction,ask})?'now':'later';
|
|
986
994
|
return {key:[workflow,run,task??'',attempt??'',stage??'',done?'done':code??''].join('|'),
|
|
987
995
|
...(done?{}:{attentionKey:attentionKeyFor({project,session,workflow,runId:run})}),
|
|
@@ -989,7 +997,8 @@ export function driveNotice({host,cwd,args=[],operation,row=null,failure=null}){
|
|
|
989
997
|
code:done?(text(result.code)??text(result.overall)??text(nested.overall)??'done'):code,
|
|
990
998
|
// A finished unit is the natural point to start a fresh session (runtime/model-efficiency.md).
|
|
991
999
|
nextAction:done?'会话边界:换新会话,下一项在新会话里运行':text(result.guidance?.nextStep)??text(progress.nextAction)??text(result.nextAction),
|
|
992
|
-
...(reviewFailure?{reviewFailure}:{}),...(developFailure?{developFailure}:{}),...(pendingAction&&!done?{pendingAction}:{}),...(ask?{ask:true}:{}),delivery
|
|
1000
|
+
...(reviewFailure?{reviewFailure}:{}),...(developFailure?{developFailure}:{}),...(pendingAction&&!done?{pendingAction}:{}),...(ask?{ask:true}:{}),delivery,
|
|
1001
|
+
...(autonomous?{autonomous:true}:{})};
|
|
993
1002
|
}
|
|
994
1003
|
|
|
995
1004
|
// The attention record a successful, non-read-only step clears (see clearAttention).
|
|
@@ -10,7 +10,8 @@ const revisionHex=value=>typeof value==='string'&&/^[a-f0-9]{64}$/.test(value);
|
|
|
10
10
|
const iso=value=>typeof value==='string'&&/^\d{4}-\d\d-\d\dT/.test(value)&&Number.isFinite(Date.parse(value));
|
|
11
11
|
const need=condition=>{if(!condition)throw new Error('spec_status_invalid');};
|
|
12
12
|
|
|
13
|
-
|
|
13
|
+
// withBytes also returns the exact bytes parsed, for callers that must later detect any replacement.
|
|
14
|
+
export function readSpecsStatus(specsDir,{withBytes=false}={}){
|
|
14
15
|
const target=path.join(specsDir,'.cm-specs-status');
|
|
15
16
|
try{
|
|
16
17
|
// lstat distinguishes a missing file from a dangling, invalid symlink.
|
|
@@ -19,14 +20,14 @@ export function readSpecsStatus(specsDir){
|
|
|
19
20
|
try{
|
|
20
21
|
const root=fs.realpathSync(specsDir),real=fs.realpathSync(target),relative=path.relative(root,real);
|
|
21
22
|
need(relative!==''&&relative!=='..'&&!relative.startsWith(`..${path.sep}`)&&!path.isAbsolute(relative));
|
|
22
|
-
const source=JSON.parse(
|
|
23
|
+
const bytes=fs.readFileSync(real),source=JSON.parse(bytes.toString('utf8'));
|
|
23
24
|
need(record(source)&&['approved','awaiting_review'].includes(source.status));
|
|
24
25
|
if(Object.hasOwn(source,'revisionDigest'))need(revisionHex(source.revisionDigest));
|
|
25
26
|
// Keep optional fields absent: admission distinguishes legacy omissions.
|
|
26
27
|
const value=Object.fromEntries(fields.filter(key=>Object.hasOwn(source,key)).map(key=>[key,source[key]]));
|
|
27
28
|
if(record(value.approval))value.approval=Object.fromEntries(['response','at']
|
|
28
29
|
.filter(key=>Object.hasOwn(value.approval,key)).map(key=>[key,value.approval[key]]));
|
|
29
|
-
return {kind:'valid',value};
|
|
30
|
+
return withBytes?{kind:'valid',value,bytes}:{kind:'valid',value};
|
|
30
31
|
}catch{return {kind:'invalid'};}
|
|
31
32
|
}
|
|
32
33
|
|
|
@@ -7,7 +7,7 @@ import {fileURLToPath} from 'node:url';
|
|
|
7
7
|
import {inspectCmAiAdmission,approveCmAiSpecs,matchesCmAiTaskSelection,explainCmAiTaskSelection} from '../runtime/js/cm-ai/cm-ai-admission.mjs';
|
|
8
8
|
import {validateRunDefinition} from './cm-ai-run.mjs';
|
|
9
9
|
|
|
10
|
-
const usage='usage: cm-ai-admission.mjs --specs-dir PATH --code-project PATH [--code-project PATH ...] [--approval-response TEXT | --yes] [--approve --approval-response TEXT (no --yes)] [--feature N.slug] [--print-run-definition --scope a,b [--task T-xxx] [--requirements c,d] [--run-id X] [--repository-id Y]]';
|
|
10
|
+
const usage='usage: cm-ai-admission.mjs --specs-dir PATH --code-project PATH [--code-project PATH ...] [--approval-response TEXT | --yes] [--approve (--approval-response TEXT | --standing-authorization) (no --yes) [--expect-revision-digest HEX]] [--feature N.slug] [--print-run-definition --scope a,b [--task T-xxx] [--requirements c,d] [--run-id X] [--repository-id Y]]';
|
|
11
11
|
|
|
12
12
|
function parse(argv){
|
|
13
13
|
const result={codeProjects:[]};
|
|
@@ -18,6 +18,10 @@ function parse(argv){
|
|
|
18
18
|
if(result.approve)throw new Error('invalid arguments');
|
|
19
19
|
result.approve=true;continue;
|
|
20
20
|
}
|
|
21
|
+
if(flag==='--standing-authorization'){
|
|
22
|
+
if(result.standingAuthorization)throw new Error('invalid arguments');
|
|
23
|
+
result.standingAuthorization=true;continue;
|
|
24
|
+
}
|
|
21
25
|
if(flag==='--print-run-definition'){
|
|
22
26
|
if(result.printRunDefinition)throw new Error('invalid arguments');
|
|
23
27
|
result.printRunDefinition=true;continue;
|
|
@@ -27,13 +31,17 @@ function parse(argv){
|
|
|
27
31
|
if(index+1>=argv.length||result.codeProjects.length>=16)throw new Error('invalid arguments');
|
|
28
32
|
result.codeProjects.push(argv[++index]);continue;
|
|
29
33
|
}
|
|
30
|
-
const key={'--specs-dir':'specsDir','--approval-response':'approvalResponse','--feature':'feature',
|
|
34
|
+
const key={'--specs-dir':'specsDir','--approval-response':'approvalResponse','--expect-revision-digest':'expectRevisionDigest','--feature':'feature',
|
|
31
35
|
'--scope':'scope','--task':'task','--requirements':'requirements','--run-id':'runId','--repository-id':'repositoryId'}[flag];
|
|
32
36
|
if(!key||index+1>=argv.length||Object.hasOwn(result,key))throw new Error('invalid arguments');
|
|
33
37
|
result[key]=argv[++index];
|
|
34
38
|
}
|
|
35
39
|
if(!result.specsDir||result.codeProjects.length===0)throw new Error('specs and code project paths are required');
|
|
36
40
|
if(result.assumeYes&&Object.hasOwn(result,'approvalResponse'))throw new Error('approval input is duplicated');
|
|
41
|
+
if(Object.hasOwn(result,'expectRevisionDigest')&&(!result.approve||!/^[0-9a-f]{64}$/.test(result.expectRevisionDigest)))
|
|
42
|
+
throw new Error('--expect-revision-digest requires --approve and a 64-character lowercase hex digest');
|
|
43
|
+
if(result.standingAuthorization&&(!result.approve||!Object.hasOwn(result,'expectRevisionDigest')||result.assumeYes||Object.hasOwn(result,'approvalResponse')))
|
|
44
|
+
throw new Error('--standing-authorization requires --approve and --expect-revision-digest, without --approval-response or --yes');
|
|
37
45
|
if(!result.printRunDefinition&&['scope','task','requirements','runId','repositoryId'].some(key=>Object.hasOwn(result,key)))
|
|
38
46
|
throw new Error('run definition options require --print-run-definition');
|
|
39
47
|
return result;
|