@aibyzero/cm-workflow 0.11.0 → 0.13.2

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 (130) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +3 -0
  3. package/CHANGELOG.md +64 -3
  4. package/README.md +45 -3
  5. package/VERSION +1 -1
  6. package/compat/claude-commands/cm-runtime.md +3 -0
  7. package/compat/claude-commands/cm-security.md +3 -0
  8. package/docs/architecture.md +22 -0
  9. package/docs/installation.md +56 -2
  10. package/docs/js-workflow-control.md +63 -6
  11. package/docs/runtime-failover.md +97 -0
  12. package/docs/user-guide.md +60 -3
  13. package/install-codex.sh +5 -0
  14. package/install.ps1 +10 -2
  15. package/install.sh +5 -0
  16. package/package.json +3 -1
  17. package/runtime/js/cm-ai/claude-developer-proposal.schema.json +151 -0
  18. package/runtime/js/cm-ai/claude-review-stream.mjs +69 -8
  19. package/runtime/js/cm-ai/claude-tool-preview.mjs +6 -4
  20. package/runtime/js/cm-ai/cm-ai-admission.mjs +38 -16
  21. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +44 -17
  22. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +105 -12
  23. package/runtime/js/cm-ai/codex-config.mjs +6 -0
  24. package/runtime/js/cm-ai/codex-review-adapter.mjs +6 -2
  25. package/runtime/js/cm-ai/developer-adapter.mjs +41 -16
  26. package/runtime/js/cm-ai/durable-runner-state.mjs +72 -15
  27. package/runtime/js/cm-ai/effect-contract.mjs +10 -1
  28. package/runtime/js/cm-ai/fix-code-association.mjs +4 -1
  29. package/runtime/js/cm-ai/host-conversation-execution.mjs +112 -27
  30. package/runtime/js/cm-ai/host-documentation.mjs +4 -2
  31. package/runtime/js/cm-ai/host-qa-executor.mjs +17 -4
  32. package/runtime/js/cm-ai/host-qa-policy.mjs +6 -3
  33. package/runtime/js/cm-ai/host-role-routing.mjs +9 -5
  34. package/runtime/js/cm-ai/host-tool-bridge.mjs +10 -7
  35. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +9 -4
  36. package/runtime/js/cm-ai/host.mjs +1 -1
  37. package/runtime/js/cm-ai/provider-review-observation.mjs +8 -4
  38. package/runtime/js/cm-ai/qa-attachment.mjs +30 -0
  39. package/runtime/js/cm-ai/review-package.mjs +76 -18
  40. package/runtime/js/cm-ai/review-runner.mjs +15 -3
  41. package/runtime/js/cm-ai/runtime-failover.mjs +75 -0
  42. package/runtime/js/cm-ai/specification-material.mjs +98 -0
  43. package/runtime/js/cm-ai/task-runner.mjs +57 -20
  44. package/runtime/js/cm-ai/worker-claude-developer.mjs +174 -0
  45. package/runtime/js/cm-ai/worker-claude.mjs +18 -5
  46. package/runtime/js/cm-ai/worker-codex-developer.mjs +15 -4
  47. package/runtime/js/cm-ai/worker-codex.mjs +8 -12
  48. package/runtime/js/cm-init/draft-generation.mjs +24 -4
  49. package/runtime/js/cm-init/draft-inspection.mjs +29 -1
  50. package/runtime/js/cm-prd/session.mjs +19 -2
  51. package/runtime/js/cm-prd/summary.mjs +46 -20
  52. package/runtime/js/cm-security/scan.mjs +263 -0
  53. package/runtime/js/cm-test/branch-impact.mjs +8 -2
  54. package/runtime/review.md +11 -1
  55. package/runtime/workflow-config.md +39 -2
  56. package/runtime/workflow-routing.md +6 -1
  57. package/scripts/cm-ai-admission.test.mjs +99 -0
  58. package/scripts/cm-ai-batch-host.test.mjs +4 -1
  59. package/scripts/cm-ai-batch-run.test.mjs +7 -1
  60. package/scripts/cm-ai-bootstrap.test.mjs +2 -1
  61. package/scripts/cm-ai-fix-integration.test.mjs +2 -1
  62. package/scripts/cm-ai-host.mjs +81 -12
  63. package/scripts/cm-ai-host.test.mjs +520 -5
  64. package/scripts/cm-ai-multi-root.test.mjs +9 -3
  65. package/scripts/cm-ai-nested-execution.test.mjs +11 -4
  66. package/scripts/cm-ai-review-timeout.test.mjs +226 -0
  67. package/scripts/cm-ai-run.mjs +40 -13
  68. package/scripts/cm-ai-run.test.mjs +45 -9
  69. package/scripts/cm-check-host.test.mjs +1 -1
  70. package/scripts/cm-check-runtime.sh +56 -1
  71. package/scripts/cm-check-update.mjs +200 -0
  72. package/scripts/cm-check-update.test.mjs +186 -0
  73. package/scripts/cm-claude-developer-worker.test.mjs +236 -0
  74. package/scripts/cm-claude-probe.test.mjs +64 -1
  75. package/scripts/cm-claude-review-stream.test.mjs +236 -1
  76. package/scripts/cm-claude-worker.test.mjs +110 -1
  77. package/scripts/cm-codex-developer-adapter.test.mjs +50 -2
  78. package/scripts/cm-codex-developer-worker.test.mjs +84 -1
  79. package/scripts/cm-codex-review-progress.test.mjs +34 -6
  80. package/scripts/cm-failover.mjs +288 -0
  81. package/scripts/cm-failover.test.mjs +184 -0
  82. package/scripts/cm-host-qa-executor.test.mjs +277 -0
  83. package/scripts/cm-host-tool-bridge.test.mjs +31 -0
  84. package/scripts/cm-init-draft-generation.test.mjs +62 -0
  85. package/scripts/cm-init-draft-inspection.test.mjs +76 -0
  86. package/scripts/cm-init-host.mjs +4 -4
  87. package/scripts/cm-init-host.test.mjs +12 -7
  88. package/scripts/cm-init-session.test.mjs +50 -0
  89. package/scripts/cm-log-event.mjs +34 -5
  90. package/scripts/cm-prd-completion.test.mjs +2 -2
  91. package/scripts/cm-prd-host.mjs +39 -3
  92. package/scripts/cm-prd-host.test.mjs +52 -0
  93. package/scripts/cm-prd-review-gate.mjs +11 -2
  94. package/scripts/cm-prd-review-gate.test.mjs +62 -0
  95. package/scripts/cm-prd-session-recovery.test.mjs +167 -0
  96. package/scripts/cm-prd-summary.test.mjs +147 -0
  97. package/scripts/cm-review-dependency-snapshot.test.mjs +10 -0
  98. package/scripts/cm-review-inventory.test.mjs +189 -0
  99. package/scripts/cm-review-schema.test.mjs +35 -1
  100. package/scripts/cm-review-scope-recovery.test.mjs +63 -0
  101. package/scripts/cm-runtime-edit.mjs +104 -0
  102. package/scripts/cm-runtime-failover.test.mjs +130 -0
  103. package/scripts/cm-runtime-install.mjs +42 -0
  104. package/scripts/cm-runtime.mjs +113 -0
  105. package/scripts/cm-runtime.test.mjs +117 -0
  106. package/scripts/cm-security.mjs +32 -0
  107. package/scripts/cm-security.test.mjs +203 -0
  108. package/scripts/cm-spec-manifest.mjs +24 -21
  109. package/scripts/cm-spec-manifest.test.mjs +19 -0
  110. package/scripts/cm-workflow-config.mjs +113 -5
  111. package/scripts/cm-workflow-config.test.mjs +124 -1
  112. package/scripts/fixtures/prd-review-gate-python-oracle.py +18 -2
  113. package/scripts/test-cm-prd-review-gate.py +30 -0
  114. package/scripts/test-shell-compat.sh +34 -0
  115. package/scripts/validate-public-repo.py +7 -1
  116. package/skills/cm-ai/references/N4-review.md +5 -4
  117. package/skills/cm-ai/references/js-host.md +36 -2
  118. package/skills/cm-check/SKILL.md +49 -8
  119. package/skills/cm-check/references/js-host.md +4 -1
  120. package/skills/cm-init/SKILL.md +4 -0
  121. package/skills/cm-init/references/js-host.md +2 -0
  122. package/skills/cm-init/references/runtime-declaration.md +26 -0
  123. package/skills/cm-prd/SKILL.md +3 -3
  124. package/skills/cm-prd/references/js-change-recovery.md +24 -3
  125. package/skills/cm-prd/references/summary-card.md +7 -0
  126. package/skills/cm-runtime/SKILL.md +32 -0
  127. package/skills/cm-security/SKILL.md +55 -0
  128. package/skills/cm-security/references/scan-contract.md +43 -0
  129. package/templates/auto-update/cm-update.sh +1 -1
  130. package/templates/cm-workflow.yml +16 -0
@@ -31,6 +31,12 @@
31
31
 
32
32
  安装后必须新开会话,再运行 `$cm-check`。如果检查通过,就不需要每次任务都重复执行它。
33
33
 
34
+ `cm-check` 默认先查 npm 稳定版,有新版就升级已管理的插件,再检查升级后的目录,
35
+ 不需要另加参数或再次确认。升级后其他 Skills 需新开会话加载。离线时继续本地检查,
36
+ 但会明确提示“无法确认最新版”。源码仓库、Pi/BYZ 等其他管理器安装保留原方式,
37
+ 自动升级当前支持 macOS Codex 个人本地市场和 macOS/Linux Claude。
38
+ 有其他 CM 任务在运行时先结束或暂停;临时只想检查,可说“cm-check,只检查,不升级”。
39
+
34
40
  `cm-ai` 的新任务默认使用 JS Workflow,无需额外指定执行方式。它要求 Node.js 24.14+;
35
41
  macOS 已有本地验证,Linux 尚缺目标环境验证,原生 Windows 尚不支持。
36
42
  已有运行按原执行方式续接,升级不自动迁移旧任务;新任务只有明确选择旧兼容流程才走兼容入口。
@@ -56,7 +62,8 @@ JS 缺少运行条件时会报告缺口,不会静默切回旧流程。默认
56
62
  | 已确认是缺陷 | `$cm-fix …` | **是** | 查看红灯测试、修复和回归结果 |
57
63
  | 只想改善代码结构 | `$cm-refactor …` | **是**,但不得改变行为 | 查看等价性验证和审查结果 |
58
64
  | 想讨论方案、研究问题或查论文 | `$external-expert …` | 否 | 查看外部原始回答、本地裁决与待验证项 |
59
- | 安装或入口不正常 | `$cm-check` | 否,只检查 | 按检查结果修复安装或配置 |
65
+ | 查看/切换单双 AI、谁写谁审 | `$cm-runtime` | 仅明确 set/unset 时写声明 | 查看来源与预设 |
66
+ | 安装或入口不正常 | `$cm-check` | 自动升级 CM 安装,不改业务代码 | 查看升级与自检结果 |
60
67
 
61
68
  ### 不想记命令,也可以直接描述目标
62
69
 
@@ -74,6 +81,7 @@ Codex 与 Claude Code 会先根据 Skill 的 `description` 判断入口。自然
74
81
  | `cm-test` | `$cm-test …` | “验证一下现有登录功能,再用浏览器走查” | 用户只说“好像有问题” → 先测试,不自动修 |
75
82
  | `cm-fix` | `$cm-fix …` | “这个 bug 已经能复现,请按失败报告修复” | 尚未复现 → `cm-test`;新增需求 → `cm-prd` |
76
83
  | `cm-refactor` | `$cm-refactor …` | “只整理这段代码结构,不改变行为” | 要改变功能或修 bug → 转交对应流程 |
84
+ | `cm-runtime` | `$cm-runtime show` | “两个工具都有,改为 Claude 写、Codex 审” | 不安装、不改当前 run |
77
85
  | `cm-check` | `$cm-check` | “检查一下 CM 是否安装正确,为什么没有命令” | 测试业务功能 → `cm-test` |
78
86
 
79
87
  ## 两个目录不要混淆
@@ -348,11 +356,12 @@ $cm-refactor ~/projects/my-app-specs ~/code/my-app 拆分过大的订单服务
348
356
 
349
357
  </details>
350
358
 
351
- ## 九个入口速查
359
+ ## 十个入口速查
352
360
 
353
361
  | 入口 | 主要输入 | 主要产出 | 关键边界 |
354
362
  | --- | --- | --- | --- |
355
- | `$cm-check` | 当前安装 | 机械与语义检查报告 | 只报告,不自动修复 |
363
+ | `$cm-runtime` | 预设与项目/用户范围 | 声明、来源与原子配置写入 | 不进入 N1–N8;仅影响新 run |
364
+ | `$cm-check` | 当前安装 | 版本更新 + 机械与语义检查报告 | 默认升级已管理插件,不自动修业务或配置 |
356
365
  | `$cm-idea` | 一句话点子 | 可交付 PRD | 不自动进入 `$cm-prd` |
357
366
  | `$cm-init` | 当前代码项目 | `AGENTS.md`、兼容规则、代码库上下文 | 不实现业务功能 |
358
367
  | `$cm-prd` | specs 的 `docs/` | requirements、design、tasks、可选测试合同 | 在人工审查处停止 |
@@ -531,3 +540,51 @@ $external-expert 你的问题
531
540
  - [安装指南](installation.md):Codex、Claude Code 与 Windows 安装细节。
532
541
  - [架构说明](architecture.md):状态真相、审查通道与测试合同。
533
542
  - [README](../README.md):项目定位、能力全景与维护入口。
543
+
544
+ ## 主动安全检查
545
+
546
+ ```text
547
+ $cm-security
548
+ $cm-security --all
549
+ $cm-security {项目路径} --semgrep-rules {外部本地规则文件} --osv-db {外部缓存目录}
550
+ ```
551
+
552
+ 默认检查当前分支相对主分支的差异及已跟踪未提交修改;`--all` 检查全部已跟踪文件。
553
+ 先读业务地图,再运行现有本地工具并复核鉴权、注入、文件/命令/网络边界。
554
+ 扫描不自动安装工具、下载规则/数据库、修改代码或发布;工具缺失会继续可做的复核,
555
+ 结果明确标记部分覆盖。未跟踪文件、受保护路径、Git 历史不在默认扫描范围。
556
+ 报告给出位置、业务影响、证据、修复建议与未检查项。工具结果不等于安全保证;
557
+ 需要修复时再明确交给 cm-fix。详细参数见 `skills/cm-security/references/scan-contract.md`。
558
+
559
+ ## 运行时默认与切换
560
+
561
+ 交互安装在核心成功后询问“只有 Codex / 只有 Claude / 两个都有”,两家都有再问谁写代码。
562
+ 结果保存为 `~/.cm-workflow/runtimes.yml`;已有文件显示当前值并默认保留。
563
+ `--yes` / `-Yes` 或非 TTY 跳过提问且不写文件。测试时可用 `CM_WORKFLOW_HOME` 覆盖目录。
564
+
565
+ 优先级:**项目 > 用户级默认 > 未声明**。项目没有 `runtimes.available` 才读取用户文件;
566
+ 显式项目角色字段覆盖用户预设的角色默认值,矛盾配置报字段路径并阻断。
567
+ `cm-init` 遇到用户默认直接继承、报告 `来源: 用户级默认`,两级都没有才询问。
568
+
569
+ | 预设 | 写代码 | 审代码 |
570
+ | --- | --- | --- |
571
+ | `codex-only` | Codex | Codex 的独立新上下文 |
572
+ | `claude-only` | Claude | Claude 的独立新上下文 |
573
+ | `codex-codes` | Codex | Claude |
574
+ | `claude-codes` | Claude | Codex |
575
+
576
+ ```text
577
+ $cm-runtime show
578
+ $cm-runtime set claude-codes --project /path/to/project
579
+ $cm-runtime set --user codex-codes
580
+ $cm-runtime unset --user
581
+ ```
582
+
583
+ Claude Code 用 `/cm-runtime`,macOS/Linux 兼容 `/cm:runtime`;终端入口为
584
+ `node <workflow-root>/scripts/cm-runtime.mjs`。`show` 显示 `runtimes_source: project|user|none`、
585
+ 有效预设(无法精确匹配时为 custom)、coder/reviewer adapter/source。CLI 缺失只 WARN,不代表配额检测。
586
+
587
+ `set` 只改声明和 coder/reviewer 的 adapter/source,保留模型、策略、注释、格式等其他原文;
588
+ 新配置从模板生成。`set --user` 改全局默认,`unset --user` 只删除用户默认,不清项目声明。
589
+ 这些操作不修改正在运行的 run;run 创建时已绑定配置。`set` 记录独立的 `decision/route` 日志,
590
+ 不借用业务 run 指针;若日志失败会明确提示“配置已写、日志失败”。`show` 不写日志。
package/install-codex.sh CHANGED
@@ -178,6 +178,11 @@ marketplace_name="$("$PYTHON_BIN" "$READ_MARKETPLACE" --marketplace-path "$MARKE
178
178
  codex plugin add "cm-workflow@$marketplace_name"
179
179
  INSTALL_COMPLETE=1
180
180
 
181
+ # User runtimes.yml: only after the verified core install, before updater prompts.
182
+ if [ "$ASSUME_YES" -ne 1 ] && [ -t 0 ] && [ -t 1 ]; then
183
+ node "$PLUGIN_DEST/scripts/cm-runtime-install.mjs"
184
+ fi
185
+
181
186
  echo
182
187
  echo "CM Workflow installed for Codex from: $PLUGIN_DEST"
183
188
  echo "User guide: $PLUGIN_DEST/docs/user-guide.md"
package/install.ps1 CHANGED
@@ -1,10 +1,12 @@
1
1
  param(
2
- [switch]$Force
2
+ [switch]$Force,
3
+ [switch]$Yes
3
4
  )
4
5
 
5
6
  # CM Workflow Claude Code compatibility installer for Windows.
6
- # Usage: powershell -ExecutionPolicy Bypass -File install.ps1 [-Force]
7
+ # Usage: powershell -ExecutionPolicy Bypass -File install.ps1 [-Force] [-Yes]
7
8
  $ErrorActionPreference = "Stop"
9
+ if ($Yes) { $Force = $true }
8
10
 
9
11
  $Src = $PSScriptRoot
10
12
  $Dest = if ($env:CLAUDE_HOME) { $env:CLAUDE_HOME } else { Join-Path $env:USERPROFILE ".claude" }
@@ -192,6 +194,12 @@ try {
192
194
  }
193
195
 
194
196
  if ($InstallComplete) {
197
+ # User runtimes.yml: same JS authority and atomic writer as Bash/Codex.
198
+ if (-not $Yes -and -not $Force -and -not [Console]::IsInputRedirected -and -not [Console]::IsOutputRedirected) {
199
+ & node (Join-Path $Dest "scripts/cm-runtime-install.mjs")
200
+ if ($LASTEXITCODE -ne 0) { throw "运行时声明未完成(核心安装已成功)" }
201
+ }
202
+
195
203
  Write-Host "`n完成(已安装版本: v$Version)。请在 Claude Code 中运行 /cm-check 校验。"
196
204
  Write-Host "使用手册: $(Join-Path $Dest 'cm-workflow\docs\user-guide.md')"
197
205
  Write-Host @"
package/install.sh CHANGED
@@ -232,6 +232,11 @@ done < "$STAGE/.cm-managed-files"
232
232
  "$DEST/scripts/cm-check-runtime.sh" --project "$SRC_DIR"
233
233
  INSTALL_COMPLETE=1
234
234
 
235
+ # User runtimes.yml: only after the verified core install, before updater prompts.
236
+ if [ "$ASSUME_YES" -ne 1 ] && [ -t 0 ] && [ -t 1 ]; then
237
+ node "$DEST/scripts/cm-runtime-install.mjs"
238
+ fi
239
+
235
240
  copy_file_atomic "$SRC_DIR/templates/auto-update/cm-update.sh" "$HOME/.cm-workflow/cm-update.sh" "~/.cm-workflow/cm-update.sh" ||
236
241
  echo "⚠ 可选更新器安装跳过: ~/.cm-workflow/cm-update.sh" >&2
237
242
  copy_file_atomic "$SRC_DIR/templates/auto-update/cm-announce.sh" "$HOME/.cm-workflow/cm-announce.sh" "~/.cm-workflow/cm-announce.sh" ||
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aibyzero/cm-workflow",
3
- "version": "0.11.0",
3
+ "version": "0.13.2",
4
4
  "description": "Spec-driven business development workflow for Pi, Codex, and Claude Code",
5
5
  "license": "MIT",
6
6
  "publishConfig": {
@@ -50,6 +50,8 @@
50
50
  "./skills/cm-init",
51
51
  "./skills/cm-prd",
52
52
  "./skills/cm-refactor",
53
+ "./skills/cm-runtime",
54
+ "./skills/cm-security",
53
55
  "./skills/cm-test"
54
56
  ],
55
57
  "prompts": [
@@ -0,0 +1,151 @@
1
+ {
2
+ "type": "object",
3
+ "additionalProperties": false,
4
+ "required": [
5
+ "status"
6
+ ],
7
+ "properties": {
8
+ "status": {
9
+ "type": "string",
10
+ "enum": [
11
+ "succeeded",
12
+ "failed"
13
+ ]
14
+ },
15
+ "code": {
16
+ "type": "string",
17
+ "minLength": 1
18
+ },
19
+ "value": {
20
+ "type": "object",
21
+ "additionalProperties": false,
22
+ "required": [
23
+ "outcome"
24
+ ],
25
+ "properties": {
26
+ "outcome": {
27
+ "type": "string",
28
+ "enum": [
29
+ "implemented",
30
+ "blocked"
31
+ ]
32
+ },
33
+ "application": {
34
+ "type": "object",
35
+ "additionalProperties": false,
36
+ "required": [
37
+ "status",
38
+ "note"
39
+ ],
40
+ "properties": {
41
+ "status": {
42
+ "type": "string",
43
+ "enum": [
44
+ "applied",
45
+ "no_relevant_lesson"
46
+ ]
47
+ },
48
+ "note": {
49
+ "type": [
50
+ "string",
51
+ "null"
52
+ ]
53
+ }
54
+ }
55
+ },
56
+ "retrospective": {
57
+ "type": "object",
58
+ "additionalProperties": false,
59
+ "required": [
60
+ "status",
61
+ "candidates",
62
+ "reason"
63
+ ],
64
+ "properties": {
65
+ "status": {
66
+ "type": "string",
67
+ "enum": [
68
+ "no_new_lesson",
69
+ "lesson_candidate",
70
+ "writeback_pending"
71
+ ]
72
+ },
73
+ "candidates": {
74
+ "type": "array",
75
+ "maxItems": 3,
76
+ "items": {
77
+ "type": "object",
78
+ "additionalProperties": false,
79
+ "required": [
80
+ "classification",
81
+ "trigger",
82
+ "action",
83
+ "evidence"
84
+ ],
85
+ "properties": {
86
+ "classification": {
87
+ "type": "string",
88
+ "enum": [
89
+ "structured",
90
+ "memory_only"
91
+ ]
92
+ },
93
+ "trigger": {
94
+ "type": "string"
95
+ },
96
+ "action": {
97
+ "type": "string"
98
+ },
99
+ "evidence": {
100
+ "type": "array",
101
+ "items": {
102
+ "type": "string"
103
+ }
104
+ }
105
+ }
106
+ }
107
+ },
108
+ "reason": {
109
+ "type": [
110
+ "string",
111
+ "null"
112
+ ]
113
+ }
114
+ }
115
+ }
116
+ }
117
+ },
118
+ "edits": {
119
+ "type": "array",
120
+ "maxItems": 64,
121
+ "items": {
122
+ "type": "object",
123
+ "additionalProperties": false,
124
+ "required": [
125
+ "path",
126
+ "beforeSha256",
127
+ "content"
128
+ ],
129
+ "properties": {
130
+ "path": {
131
+ "type": "string",
132
+ "minLength": 1
133
+ },
134
+ "beforeSha256": {
135
+ "type": [
136
+ "string",
137
+ "null"
138
+ ],
139
+ "pattern": "^[a-f0-9]{64}$"
140
+ },
141
+ "content": {
142
+ "type": [
143
+ "string",
144
+ "null"
145
+ ]
146
+ }
147
+ }
148
+ }
149
+ }
150
+ }
151
+ }
@@ -1,7 +1,18 @@
1
1
  // Conservative print/stream-json decoder. No dispatch, grant or completion authority.
2
2
  // Process ownership must append process_closed and reject unsuccessful exits.
3
- export function createClaudeReviewStream(onEvent) {
4
- let session = null, stage = 'init', value;
3
+ export function reportClaudeRateLimitNotice(raw, onNotice) {
4
+ if (typeof onNotice !== 'function') return;
5
+ const info = Object.fromEntries(Object.entries(
6
+ raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {},
7
+ ).filter(([, value]) => value === null || typeof value === 'string'
8
+ || typeof value === 'boolean' || (typeof value === 'number' && Number.isFinite(value))));
9
+ // Diagnostics must not change the provider result or leak nested provider payloads.
10
+ try { onNotice({kind:'rate_limit', info}); } catch {}
11
+ }
12
+
13
+ export function createClaudeReviewStream(onEvent, onNotice = null) {
14
+ let session = null, stage = 'init', value, noticeCount = 0, thinkingCount = 0, rejectedAttempts = 0;
15
+ const pendingTools = new Map(), toolIds = new Set();
5
16
  const reject = code => { stage = 'failed'; throw Object.assign(new Error(code), {code}); };
6
17
  return Object.freeze({
7
18
  accept(message) {
@@ -18,21 +29,71 @@ export function createClaudeReviewStream(onEvent) {
18
29
  onEvent({event:'turn.started', item_type:null});
19
30
  return;
20
31
  }
21
- if (message.type === 'assistant' && stage === 'assistant') {
32
+ if (message.type === 'rate_limit_event') {
33
+ if (noticeCount >= 32) reject('unexpected_event');
34
+ noticeCount++;
35
+ reportClaudeRateLimitNotice(message.rate_limit_info, onNotice);
36
+ return;
37
+ }
38
+ if (message.type === 'system') {
39
+ if (message.subtype === 'thinking_tokens') {
40
+ // Long reviews emit usage heartbeats; worker-claude also caps total output at 1 MB.
41
+ if (thinkingCount >= 4096) reject('unexpected_event');
42
+ thinkingCount++;
43
+ return;
44
+ }
45
+ if (!['api_retry','hook_started','hook_response','commands_changed'].includes(message.subtype)
46
+ || noticeCount >= 32) reject('unexpected_event');
47
+ noticeCount++;
48
+ // CLI notifications carry no verdict; never forward hook output or command bodies.
49
+ const notice = {kind:'claude_system_notice', subtype:message.subtype};
50
+ for (const key of ['attempt','max_retries','error_status']) {
51
+ if (typeof message[key] === 'number' && Number.isFinite(message[key])) notice[key] = message[key];
52
+ }
53
+ if (typeof message.hook_name === 'string') notice.hook_name = message.hook_name;
54
+ try { if (typeof onNotice === 'function') onNotice(notice); } catch {}
55
+ return;
56
+ }
57
+ if (message.type === 'assistant') {
22
58
  if (message.parent_tool_use_id !== null || message.error != null
23
59
  || message.message?.role !== 'assistant') reject('unexpected_assistant');
24
60
  const content = message.message.content;
25
- if (!Array.isArray(content) || content.length === 0
26
- || content.some(block => block?.type !== 'text' || typeof block.text !== 'string')) {
27
- reject('unexpected_tool_or_content');
61
+ if (!Array.isArray(content) || content.length === 0) reject('unexpected_tool_or_content');
62
+ let substantive = false;
63
+ for (const block of content) {
64
+ if (['thinking','redacted_thinking'].includes(block?.type)) continue;
65
+ substantive = true;
66
+ if (block?.type === 'text' && typeof block.text === 'string') continue;
67
+ if (block?.type !== 'tool_use' || typeof block.id !== 'string' || !block.id.trim()
68
+ || toolIds.has(block.id) || typeof block.name !== 'string' || !block.name.trim()) {
69
+ reject('unexpected_tool_or_content');
70
+ }
71
+ if (block.name !== 'StructuredOutput' && ++rejectedAttempts > 16) reject('unexpected_tool_or_content');
72
+ toolIds.add(block.id);
73
+ pendingTools.set(block.id, block.name);
28
74
  }
29
75
  // Result is authoritative for structured output; assistant prose is never a verdict.
30
- stage = 'result';
76
+ if (substantive) stage = 'result';
77
+ return;
78
+ }
79
+ if (message.type === 'user') {
80
+ const content = message.message?.content;
81
+ if (message.message?.role !== 'user' || !Array.isArray(content) || content.length === 0) {
82
+ reject('unexpected_tool_or_content');
83
+ }
84
+ for (const block of content) {
85
+ if (block?.type !== 'tool_result' || !pendingTools.has(block.tool_use_id)
86
+ || (pendingTools.get(block.tool_use_id) !== 'StructuredOutput' && block.is_error !== true)) {
87
+ reject('unexpected_tool_or_content');
88
+ }
89
+ pendingTools.delete(block.tool_use_id);
90
+ }
31
91
  return;
32
92
  }
33
93
  if (message.type === 'result') {
34
94
  if (message.subtype !== 'success' || message.is_error !== false) reject('provider_failed');
35
- if (stage !== 'result' || message.num_turns !== 1) reject('unexpected_result');
95
+ if (stage !== 'result' || pendingTools.size !== 0 || !Number.isInteger(message.num_turns)
96
+ || message.num_turns < 1 || message.num_turns > 20) reject('unexpected_result');
36
97
  if (message.structured_output !== undefined) value = message.structured_output;
37
98
  else {
38
99
  try { value = JSON.parse(message.result); } catch { reject('invalid_output_json'); }
@@ -62,7 +62,8 @@ export async function previewClaudeTools({cwd,model,cli='claude',spawnProcess=sp
62
62
  const checks={json:true,post:request.method==='POST',
63
63
  messages_endpoint:new URL(request.url,'http://127.0.0.1').pathname==='/v1/messages',
64
64
  model_matches:data.model===model,messages_array:Array.isArray(data.messages),
65
- tools_empty:Array.isArray(tools)&&tools.length===0,
65
+ tools_allowed:Array.isArray(tools)&&(tools.length===0
66
+ ||(tools.length===1&&tools[0]?.name==='StructuredOutput')),
66
67
  synthetic_auth:request.headers['x-api-key']==='cm-synthetic-local-probe'};
67
68
  safe={valid:Object.values(checks).every(Boolean),checks};
68
69
  }catch{}
@@ -70,7 +71,7 @@ export async function previewClaudeTools({cwd,model,cli='claude',spawnProcess=sp
70
71
  if(index<8)observations[index]=safe;
71
72
  response.writeHead(400,{'Content-Type':'application/json'});
72
73
  response.end(JSON.stringify({type:'error',error:{type:'invalid_request_error',message:'CM_LOCAL_PROBE_STOP'}}));
73
- // Inspection is finished; do not let CLI-internal repair/retry issue another model request.
74
+ // Stop after the first valid request; a CLI retry may already be in flight.
74
75
  if(safe.valid){stoppedByProbe=true;controller.abort();}
75
76
  });
76
77
  });
@@ -99,9 +100,10 @@ export async function previewClaudeTools({cwd,model,cli='claude',spawnProcess=sp
99
100
  }
100
101
  const messages=observations.filter(item=>item.startup!==true);
101
102
  return {model,disabledSkills:[],preflight:{provider:'claude',prompt_transport:'stdin',
102
- config_fingerprint:fingerprint,passed:messages.length===1&&messages[0].valid
103
+ config_fingerprint:fingerprint,passed:messages.length>=1&&messages.length<=2&&messages.every(message=>message.valid)
103
104
  &&stoppedByProbe&&result?.status==='cancelled'&&closeEvidence!==null&&!closeEvidence.timed_out,
104
- local_requests:observations.length,message_requests:messages.length,listener_closed:closed,isolation:'macos-loopback-sandbox',
105
+ local_requests:observations.length,message_requests:messages.length,message_requests_expected:'1-2',
106
+ listener_closed:closed,isolation:'macos-loopback-sandbox',
105
107
  process_code:result?.code??'unknown',stopped_by_probe:stoppedByProbe,exit_code:closeEvidence?.exit_code??null,
106
108
  request_checks:observations.map(item=>item.startup?{startup:true}:item.checks??{complete:false})}};
107
109
  }
@@ -4,6 +4,7 @@ import path from 'node:path';
4
4
  import { createHash } from 'node:crypto';
5
5
  import { spawnSync } from 'node:child_process';
6
6
  import { fileURLToPath } from 'node:url';
7
+ import {buildManifest,verifyManifest} from '../../../scripts/cm-spec-manifest.mjs';
7
8
 
8
9
  const TASK=/^\s*-\s*\[([ xX])\]\s+(?:~~)?(T-[A-Za-z0-9][A-Za-z0-9._-]*)(?=[:\s])[:\s]*(.*)$/;
9
10
  const DEPENDENCY=/^\s*-\s*(T-[A-Za-z0-9][A-Za-z0-9._-]*)\s+依赖\s+(.+)$/;
@@ -200,22 +201,27 @@ function validateTestCases(specsDir,status,names){
200
201
  }
201
202
 
202
203
  function readFeature(specsDir,name){
203
- return parseFeatureTaskText(fs.readFileSync(path.join(specsDir,name,'tasks.md'),'utf8'));
204
+ const parsed=parseFeatureTaskText(fs.readFileSync(path.join(specsDir,name,'tasks.md'),'utf8'),{allowDependencyPunctuation:true});
205
+ if(parsed.error)parsed.detail={feature:name,...parsed.detail};
206
+ return parsed;
204
207
  }
205
208
 
206
209
  export function declaredAcceptanceIds(source){
207
210
  return new Set(source.split(/\r?\n/).map(line=>line.match(ACCEPTANCE)).filter(Boolean).map(match=>match[1]||match[2]));
208
211
  }
209
212
 
210
- export function parseFeatureTaskText(source){
213
+ export function parseFeatureTaskText(source,{allowDependencyPunctuation=false}={}){
211
214
  const lines=source.split(/\r?\n/);
212
215
  const tasks=[];
213
216
  const taskIds=new Set();
214
217
  const dependencies=new Map();
215
- for(const line of lines){
218
+ const dependencyLocations=new Map();
219
+ const location=index=>({line:index+1,text:lines[index].slice(0,120)});
220
+ const invalid=(error,index)=>({error,detail:location(index)});
221
+ for(const [index,line] of lines.entries()){
216
222
  const task=line.match(TASK);
217
223
  if(task){
218
- if(taskIds.has(task[2]))return {error:'tasks_invalid'};
224
+ if(taskIds.has(task[2]))return invalid('tasks_invalid',index);
219
225
  taskIds.add(task[2]);
220
226
  const dropped=/\[DROPPED(?:\s[^\]]*)?\]/.test(task[3]);
221
227
  tasks.push({
@@ -228,30 +234,39 @@ export function parseFeatureTaskText(source){
228
234
  }
229
235
  const dependency=line.match(DEPENDENCY);
230
236
  if(dependency){
231
- if(dependencies.has(dependency[1]))return {error:'dependencies_invalid'};
232
- const required=dependency[2].split(/[,,]/).map(value=>value.trim()).filter(Boolean);
233
- if(!required.length||required.some(id=>!TASK_ID.test(id)))return {error:'dependencies_invalid'};
237
+ if(dependencies.has(dependency[1]))return invalid('dependencies_invalid',index);
238
+ // Only cm-ai admission opts in; cm-prd self-check retains strict parsing.
239
+ const required=dependency[2].split(/[,,]/).map(value=>value.trim()).filter(Boolean)
240
+ .map(value=>allowDependencyPunctuation?value.replace(/[。..;;、\s]+$/u,''):value);
241
+ if(!required.length||required.some(id=>!TASK_ID.test(id)))return invalid('dependencies_invalid',index);
234
242
  dependencies.set(dependency[1],required);
243
+ dependencyLocations.set(dependency[1],location(index));
235
244
  }
236
245
  }
237
- if(!tasks.length)return {error:'tasks_invalid'};
238
- return {tasks,dependencies};
246
+ if(!tasks.length)return invalid('tasks_invalid',Math.max(0,lines.findIndex(line=>line.trim())));
247
+ return {tasks,dependencies,dependencyLocations};
239
248
  }
240
249
 
241
250
  export function validDependencies(tasks,dependencies){
251
+ return invalidDependency(tasks,dependencies)===null;
252
+ }
253
+
254
+ function invalidDependency(tasks,dependencies){
242
255
  const ids=new Set(tasks.map(task=>task.id));
243
256
  for(const [taskId,required] of dependencies){
244
- if(!ids.has(taskId)||required.some(id=>id===taskId||!ids.has(id)))return false;
257
+ if(!ids.has(taskId)||required.some(id=>id===taskId||!ids.has(id)))return taskId;
245
258
  }
246
259
  const visiting=new Set(),visited=new Set();
260
+ let cycleTask=null;
247
261
  const visit=id=>{
248
- if(visiting.has(id))return false;
262
+ if(visiting.has(id)){cycleTask=id;return false;}
249
263
  if(visited.has(id))return true;
250
264
  visiting.add(id);
251
265
  for(const dependency of dependencies.get(id)||[])if(!visit(dependency))return false;
252
266
  visiting.delete(id);visited.add(id);return true;
253
267
  };
254
- return tasks.every(task=>visit(task.id));
268
+ tasks.every(task=>visit(task.id));
269
+ return cycleTask;
255
270
  }
256
271
 
257
272
  function validateBootstrap(codeProject,specsDir,names){
@@ -260,7 +275,7 @@ function validateBootstrap(codeProject,specsDir,names){
260
275
  if(empty&&!hasBootstrap)return 'bootstrap_required';
261
276
  if(!empty&&hasBootstrap){
262
277
  const parsed=readFeature(specsDir,'0.bootstrap');
263
- if(parsed.error)return parsed.error;
278
+ if(parsed.error)return null; // Let selection retain the parser's location and feature summaries.
264
279
  const bootstrapTask=parsed.tasks.find(task=>task.id==='T-001');
265
280
  if(bootstrapTask&&!bootstrapTask.completed&&!bootstrapTask.dropped)return 'bootstrap_conflict';
266
281
  }
@@ -295,8 +310,10 @@ function selectTask(specsDir,names){
295
310
  const evidenceNames=evidence.names;
296
311
  for(const name of names){
297
312
  const parsed=readFeature(specsDir,name);
298
- if(parsed.error)return {error:parsed.error,features,warnings};
299
- if(!validDependencies(parsed.tasks,parsed.dependencies))return {error:'dependencies_invalid',features,warnings};
313
+ if(parsed.error)return {error:parsed.error,detail:parsed.detail,features,warnings};
314
+ const invalidId=invalidDependency(parsed.tasks,parsed.dependencies);
315
+ if(invalidId!==null)return {error:'dependencies_invalid',
316
+ detail:{feature:name,...parsed.dependencyLocations.get(invalidId)},features,warnings};
300
317
  const byId=new Map(parsed.tasks.map(task=>[task.id,task]));
301
318
  const pending=parsed.tasks.filter(task=>!task.completed&&!task.dropped);
302
319
  const missing=missingReviewIds(name,parsed.tasks,evidenceNames);
@@ -340,6 +357,10 @@ function admissionFor(options,inProgressBootstrap=null){
340
357
  const featuresProblem=approvedFeaturesProblem(status.value,discovered.names);
341
358
  if(featuresProblem==='spec_features_changed')return result(base,'awaiting_spec_approval',featuresProblem);
342
359
  if(featuresProblem)return result(base,'blocked',featuresProblem);
360
+ if(Object.hasOwn(status.value,'specFiles')){
361
+ try{verifyManifest(buildManifest(specsDir),path.join(specsDir,'.cm-specs-status'));}
362
+ catch{return result(base,'blocked','spec_drift');}
363
+ }
343
364
  const testCasesProblem=validateTestCases(specsDir,status.value,discovered.names);
344
365
  if(testCasesProblem==='test_cases_changed')return result(base,'awaiting_spec_approval',testCasesProblem);
345
366
  if(testCasesProblem)return result(base,'blocked',testCasesProblem);
@@ -347,7 +368,8 @@ function admissionFor(options,inProgressBootstrap=null){
347
368
  if(bootstrapProblem&&!(bootstrapProblem==='bootstrap_conflict'&&inProgressBootstrap==='T-001'))
348
369
  return result(base,'blocked',bootstrapProblem);
349
370
  const selection=selectTask(specsDir,discovered.names);
350
- if(selection.error)return result(base,'blocked',selection.error,{features:selection.features,warnings:selection.warnings});
371
+ if(selection.error)return result(base,'blocked',selection.error,{features:selection.features,warnings:selection.warnings,
372
+ ...(selection.detail?{detail:selection.detail}:{})});
351
373
  if(!selection.nextTask)return result(base,'complete','all_tasks_terminal',{features:selection.features,warnings:selection.warnings});
352
374
  return result(base,'ready','task_selected',{features:selection.features,nextTask:selection.nextTask,warnings:selection.warnings});
353
375
  }