@aibyzero/cm-workflow 0.16.4 → 0.16.6

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 (283) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +22 -0
  3. package/CHANGELOG.md +57 -0
  4. package/README.md +22 -4
  5. package/THIRD_PARTY_NOTICES.md +9 -0
  6. package/VERSION +1 -1
  7. package/docs/architecture.md +43 -0
  8. package/docs/execution-optimizations.md +33 -0
  9. package/docs/external-models.md +114 -0
  10. package/docs/fixes/.reviews/20260929-bootstrap-unchanged-review-r1.md +7 -0
  11. package/docs/fixes/.reviews/20260930-develop-package-limit-recovery-r4.md +9 -0
  12. package/docs/fixes/20260929-bootstrap-rule-refresh-conflict.md +22 -0
  13. package/docs/fixes/20260929-bootstrap-unchanged-review.md +26 -0
  14. package/docs/fixes/20260930-develop-package-limit-recovery.md +65 -0
  15. package/docs/human-correction.md +31 -0
  16. package/docs/installation.md +48 -7
  17. package/docs/js-workflow-control.md +293 -33
  18. package/docs/live-evidence-drivers.md +62 -0
  19. package/docs/next-steps.md +15 -10
  20. package/docs/runtime-failover.md +1 -1
  21. package/docs/untested-branches.md +27 -4
  22. package/docs/user-guide.md +23 -8
  23. package/install-codex.sh +28 -11
  24. package/package.json +1 -1
  25. package/runtime/js/cm-ai/accepted-fix.mjs +23 -5
  26. package/runtime/js/cm-ai/bootstrap-feature.mjs +15 -0
  27. package/runtime/js/cm-ai/claude-review-adapter.mjs +7 -4
  28. package/runtime/js/cm-ai/claude-review-stream.mjs +12 -0
  29. package/runtime/js/cm-ai/claude-tool-preview.mjs +4 -4
  30. package/runtime/js/cm-ai/cm-ai-admission.mjs +115 -41
  31. package/runtime/js/cm-ai/cm-ai-context-refresh.mjs +3 -2
  32. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +208 -34
  33. package/runtime/js/cm-ai/cm-ai-learning-handoff-writer.mjs +11 -9
  34. package/runtime/js/cm-ai/cm-ai-learning-writer.mjs +22 -5
  35. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +181 -57
  36. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +15 -58
  37. package/runtime/js/cm-ai/codex-config.mjs +3 -2
  38. package/runtime/js/cm-ai/codex-review-adapter.mjs +56 -17
  39. package/runtime/js/cm-ai/committed-rule-basis.mjs +76 -0
  40. package/runtime/js/cm-ai/developer-adapter.mjs +6 -2
  41. package/runtime/js/cm-ai/diagnostic-reason.mjs +10 -0
  42. package/runtime/js/cm-ai/drive-bootstrap.mjs +315 -0
  43. package/runtime/js/cm-ai/drive-core.mjs +47 -9
  44. package/runtime/js/cm-ai/durable-runner-state.mjs +413 -56
  45. package/runtime/js/cm-ai/effect-abandon-log.mjs +19 -0
  46. package/runtime/js/cm-ai/effect-contract.mjs +44 -2
  47. package/runtime/js/cm-ai/execution-policy.mjs +58 -0
  48. package/runtime/js/cm-ai/execution-store-limits.mjs +18 -0
  49. package/runtime/js/cm-ai/execution-store.mjs +6 -4
  50. package/runtime/js/cm-ai/external-group-models.mjs +53 -0
  51. package/runtime/js/cm-ai/external-model-launch.mjs +23 -0
  52. package/runtime/js/cm-ai/external-models.mjs +52 -0
  53. package/runtime/js/cm-ai/external-run-guard.mjs +96 -0
  54. package/runtime/js/cm-ai/fix-code-association.mjs +171 -18
  55. package/runtime/js/cm-ai/host-bootstrap.mjs +126 -29
  56. package/runtime/js/cm-ai/host-check.mjs +30 -4
  57. package/runtime/js/cm-ai/host-conversation-execution.mjs +66 -20
  58. package/runtime/js/cm-ai/host-handoff.mjs +13 -6
  59. package/runtime/js/cm-ai/host-progress.mjs +80 -0
  60. package/runtime/js/cm-ai/host-project-execution.mjs +16 -11
  61. package/runtime/js/cm-ai/host-qa-executor.mjs +23 -9
  62. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +23 -6
  63. package/runtime/js/cm-ai/host-qa-policy.mjs +16 -7
  64. package/runtime/js/cm-ai/host-session.mjs +12 -4
  65. package/runtime/js/cm-ai/host-tool-bridge.mjs +1 -1
  66. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +16 -5
  67. package/runtime/js/cm-ai/host.mjs +1 -1
  68. package/runtime/js/cm-ai/knowledge-closeout.mjs +56 -0
  69. package/runtime/js/cm-ai/launch-mismatch.mjs +42 -0
  70. package/runtime/js/cm-ai/legacy-model-run-preview.mjs +24 -0
  71. package/runtime/js/cm-ai/legacy-model-settings.mjs +59 -0
  72. package/runtime/js/cm-ai/live-evidence.mjs +96 -0
  73. package/runtime/js/cm-ai/log-rows.mjs +21 -0
  74. package/runtime/js/cm-ai/model-configuration-file.mjs +63 -0
  75. package/runtime/js/cm-ai/model_configuration_write.py +214 -0
  76. package/runtime/js/cm-ai/native-usage-log.mjs +26 -0
  77. package/runtime/js/cm-ai/operator-guidance.mjs +86 -0
  78. package/runtime/js/cm-ai/owned-process-cleanup.mjs +22 -0
  79. package/runtime/js/cm-ai/project-qa-gate.mjs +84 -0
  80. package/runtime/js/cm-ai/provider-review-observation.mjs +68 -9
  81. package/runtime/js/cm-ai/provider-usage.mjs +39 -0
  82. package/runtime/js/cm-ai/qa-config-revision.mjs +44 -10
  83. package/runtime/js/cm-ai/review-abandon-log.mjs +21 -0
  84. package/runtime/js/cm-ai/review-package.mjs +438 -31
  85. package/runtime/js/cm-ai/review-presentation.mjs +45 -0
  86. package/runtime/js/cm-ai/review-reconciliation.mjs +20 -0
  87. package/runtime/js/cm-ai/review-runner.mjs +47 -1
  88. package/runtime/js/cm-ai/reviewed-deliveries.mjs +97 -0
  89. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +104 -10
  90. package/runtime/js/cm-ai/reviewed-evidence-supersession-record.mjs +42 -3
  91. package/runtime/js/cm-ai/specification-material.mjs +154 -12
  92. package/runtime/js/cm-ai/status-projection.mjs +93 -0
  93. package/runtime/js/cm-ai/task-commit.mjs +2 -2
  94. package/runtime/js/cm-ai/task-runner.mjs +658 -75
  95. package/runtime/js/cm-ai/tool-preview.mjs +8 -4
  96. package/runtime/js/cm-ai/worker-claude-developer.mjs +16 -7
  97. package/runtime/js/cm-ai/worker-claude.mjs +63 -19
  98. package/runtime/js/cm-ai/worker-codex-developer.mjs +15 -9
  99. package/runtime/js/cm-ai/worker-codex.mjs +45 -19
  100. package/runtime/js/cm-fix/cause-evidence.mjs +5 -3
  101. package/runtime/js/cm-fix/cause-invocation.mjs +6 -3
  102. package/runtime/js/cm-fix/cause-package.mjs +10 -1
  103. package/runtime/js/cm-fix/execution.mjs +279 -52
  104. package/runtime/js/cm-fix/final-review.mjs +18 -10
  105. package/runtime/js/cm-fix/host-review.mjs +32 -9
  106. package/runtime/js/cm-fix/host.mjs +6 -1
  107. package/runtime/js/cm-fix/layout.mjs +1 -1
  108. package/runtime/js/cm-fix/progress.mjs +5 -0
  109. package/runtime/js/cm-fix/protected-edits.mjs +15 -4
  110. package/runtime/js/cm-fix/qa-source.mjs +6 -4
  111. package/runtime/js/cm-fix/review-reconciliation.mjs +64 -0
  112. package/runtime/js/cm-prd/analysis.mjs +2 -1
  113. package/runtime/js/cm-prd/change.mjs +28 -10
  114. package/runtime/js/cm-prd/draft.mjs +5 -2
  115. package/runtime/js/cm-prd/response-recovery.mjs +23 -0
  116. package/runtime/js/cm-prd/review-preparation.mjs +10 -3
  117. package/runtime/js/cm-prd/review-publication.mjs +27 -15
  118. package/runtime/js/cm-prd/review-time.mjs +29 -0
  119. package/runtime/js/cm-prd/self-check.mjs +6 -3
  120. package/runtime/js/cm-prd/session.mjs +53 -6
  121. package/runtime/js/cm-prd/summary.mjs +3 -1
  122. package/runtime/js/cm-prd/validation-reason.mjs +20 -0
  123. package/runtime/js/cm-security/finalize.mjs +32 -0
  124. package/runtime/js/spec-task-line.mjs +117 -0
  125. package/runtime/js/specs-status.mjs +10 -3
  126. package/runtime/review.md +5 -0
  127. package/runtime/task-gates.md +6 -0
  128. package/runtime/workflow-config.md +10 -1
  129. package/scripts/cm-ai-abandon-effect-position.test.mjs +201 -0
  130. package/scripts/cm-ai-admission.mjs +18 -11
  131. package/scripts/cm-ai-admission.test.mjs +65 -1
  132. package/scripts/cm-ai-batch-drive.mjs +135 -34
  133. package/scripts/cm-ai-batch-drive.test.mjs +209 -3
  134. package/scripts/cm-ai-batch-host.mjs +63 -24
  135. package/scripts/cm-ai-batch-host.test.mjs +2 -1
  136. package/scripts/cm-ai-batch-run.mjs +101 -34
  137. package/scripts/cm-ai-batch-run.test.mjs +56 -5
  138. package/scripts/cm-ai-bootstrap-driver-preflight.test.mjs +45 -0
  139. package/scripts/cm-ai-bootstrap-flow.test.mjs +159 -0
  140. package/scripts/cm-ai-bootstrap-merge.test.mjs +162 -0
  141. package/scripts/cm-ai-bootstrap.test.mjs +174 -89
  142. package/scripts/cm-ai-conversation-entry-ops.test.mjs +97 -2
  143. package/scripts/cm-ai-develop-driver-gaps.test.mjs +924 -0
  144. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +468 -0
  145. package/scripts/cm-ai-drive-timeout.test.mjs +17 -0
  146. package/scripts/cm-ai-drive.mjs +526 -60
  147. package/scripts/cm-ai-drive.test.mjs +336 -10
  148. package/scripts/cm-ai-fix-later-delivery.test.mjs +383 -0
  149. package/scripts/cm-ai-host.mjs +142 -43
  150. package/scripts/cm-ai-host.test.mjs +232 -12
  151. package/scripts/cm-ai-launch-diagnostics.test.mjs +142 -0
  152. package/scripts/cm-ai-multi-root.test.mjs +9 -3
  153. package/scripts/cm-ai-operator-guidance.test.mjs +94 -0
  154. package/scripts/cm-ai-progress.test.mjs +521 -0
  155. package/scripts/cm-ai-project-qa-gate.test.mjs +308 -0
  156. package/scripts/cm-ai-qa-config-revision.test.mjs +187 -15
  157. package/scripts/cm-ai-qa-fingerprint-config.test.mjs +157 -0
  158. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +27 -2
  159. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +400 -0
  160. package/scripts/cm-ai-review-drift-precedence.test.mjs +90 -0
  161. package/scripts/cm-ai-review-failure.test.mjs +977 -0
  162. package/scripts/cm-ai-review-timeout-config.test.mjs +29 -7
  163. package/scripts/cm-ai-review-timeout.test.mjs +199 -4
  164. package/scripts/cm-ai-run.mjs +206 -62
  165. package/scripts/cm-ai-run.test.mjs +6 -4
  166. package/scripts/cm-ai-runner-error-code-regression.test.mjs +219 -0
  167. package/scripts/cm-ai-selection-guard.test.mjs +100 -0
  168. package/scripts/cm-ai-session-chain.test.mjs +7 -3
  169. package/scripts/cm-ai-spec-rebind.test.mjs +481 -0
  170. package/scripts/cm-ai-supersede.test.mjs +571 -17
  171. package/scripts/cm-ai-verification-gate.test.mjs +2 -1
  172. package/scripts/cm-bootstrap-review-recovery.test.mjs +70 -0
  173. package/scripts/cm-capability-gate.test.mjs +21 -2
  174. package/scripts/cm-check-drive.test.mjs +2 -1
  175. package/scripts/cm-check-host.test.mjs +1 -1
  176. package/scripts/cm-check-runtime.sh +12 -1
  177. package/scripts/cm-claude-developer-worker.test.mjs +3 -1
  178. package/scripts/cm-claude-install-layout.test.mjs +26 -0
  179. package/scripts/cm-claude-probe.test.mjs +10 -2
  180. package/scripts/cm-claude-review-stream.test.mjs +25 -0
  181. package/scripts/cm-claude-worker.test.mjs +11 -4
  182. package/scripts/cm-codex-developer-worker.test.mjs +4 -2
  183. package/scripts/cm-codex-plugin-metadata.py +83 -0
  184. package/scripts/cm-codex-plugin-metadata.test.mjs +55 -0
  185. package/scripts/cm-efficiency-checks.test.mjs +37 -0
  186. package/scripts/cm-efficiency-diagnostics.test.mjs +74 -0
  187. package/scripts/cm-efficiency-offline.mjs +35 -0
  188. package/scripts/cm-efficiency-policy.test.mjs +48 -0
  189. package/scripts/cm-efficiency-presentation.test.mjs +35 -0
  190. package/scripts/cm-efficiency-response.test.mjs +117 -0
  191. package/scripts/cm-efficiency-usage.test.mjs +148 -0
  192. package/scripts/cm-external-batch-host.test.mjs +157 -0
  193. package/scripts/cm-external-fix-host.test.mjs +281 -0
  194. package/scripts/cm-external-fix-reconciliation.test.mjs +105 -0
  195. package/scripts/cm-external-group-models.test.mjs +60 -0
  196. package/scripts/cm-external-model-host.test.mjs +180 -0
  197. package/scripts/cm-external-model-recovery.test.mjs +108 -0
  198. package/scripts/cm-external-models.test.mjs +89 -0
  199. package/scripts/cm-external-process-cleanup.test.mjs +71 -0
  200. package/scripts/cm-external-qa-fix.test.mjs +170 -0
  201. package/scripts/cm-external-review-reconciliation.test.mjs +314 -0
  202. package/scripts/cm-failover.mjs +8 -8
  203. package/scripts/cm-fix-abandon.test.mjs +123 -5
  204. package/scripts/cm-fix-cause-package.test.mjs +2 -0
  205. package/scripts/cm-fix-drive.mjs +70 -23
  206. package/scripts/cm-fix-drive.test.mjs +36 -1
  207. package/scripts/cm-fix-final-review.test.mjs +11 -6
  208. package/scripts/cm-fix-host.mjs +24 -14
  209. package/scripts/cm-fix-protected-edits.test.mjs +12 -0
  210. package/scripts/cm-fix-rediagnosis.test.mjs +168 -0
  211. package/scripts/cm-fix-review-budget.test.mjs +147 -0
  212. package/scripts/cm-fixture-process-cleanup.test.mjs +95 -0
  213. package/scripts/cm-host-check.test.mjs +6 -3
  214. package/scripts/cm-host-qa-executor.test.mjs +213 -17
  215. package/scripts/cm-host-session-diagnostic.test.mjs +10 -0
  216. package/scripts/cm-interactive-qa-diagnostic.test.mjs +53 -0
  217. package/scripts/cm-knowledge-closeout.test.mjs +160 -0
  218. package/scripts/cm-live-evidence.test.mjs +64 -0
  219. package/scripts/cm-log-event.mjs +25 -2
  220. package/scripts/cm-log-event.py +15 -0
  221. package/scripts/cm-log-event.test.mjs +31 -0
  222. package/scripts/cm-model-setup.mjs +79 -0
  223. package/scripts/cm-prd-completion.test.mjs +75 -0
  224. package/scripts/cm-prd-draft.test.mjs +14 -0
  225. package/scripts/cm-prd-drive.mjs +32 -11
  226. package/scripts/cm-prd-drive.test.mjs +15 -0
  227. package/scripts/cm-prd-gate-diagnostic.test.mjs +100 -0
  228. package/scripts/cm-prd-host.mjs +13 -4
  229. package/scripts/cm-prd-review-gate.mjs +126 -81
  230. package/scripts/cm-prd-review-gate.test.mjs +105 -1
  231. package/scripts/cm-prd-review-preparation.test.mjs +15 -0
  232. package/scripts/cm-prd-review-publication.test.mjs +6 -0
  233. package/scripts/cm-prd-self-check.test.mjs +6 -0
  234. package/scripts/cm-prd-summary.test.mjs +9 -0
  235. package/scripts/cm-release-smoke.sh +5 -1
  236. package/scripts/cm-review-dependency-snapshot.test.mjs +15 -0
  237. package/scripts/cm-review-inventory.test.mjs +253 -1
  238. package/scripts/cm-runtime-i18n.mjs +15 -4
  239. package/scripts/cm-runtime-install.mjs +8 -4
  240. package/scripts/cm-runtime.mjs +116 -23
  241. package/scripts/cm-runtime.test.mjs +121 -12
  242. package/scripts/cm-security.test.mjs +32 -0
  243. package/scripts/cm-spec-manifest.mjs +28 -10
  244. package/scripts/cm-spec-manifest.test.mjs +8 -4
  245. package/scripts/cm-spec-task-line.test.mjs +138 -0
  246. package/scripts/cm-specs-status.test.mjs +12 -1
  247. package/scripts/cm-task-gate-correction.test.mjs +117 -0
  248. package/scripts/cm-task-gate.mjs +164 -20
  249. package/scripts/cm-task-gate.py +2 -1
  250. package/scripts/cm-test-branch-impact.test.mjs +6 -3
  251. package/scripts/cm-test-drive.mjs +10 -4
  252. package/scripts/cm-test-drive.test.mjs +14 -1
  253. package/scripts/cm-tool-preview-context.test.mjs +12 -0
  254. package/scripts/cm-usage-report.py +22 -3
  255. package/scripts/cm-workflow-config.mjs +10 -1
  256. package/scripts/fixtures/bootstrap-review-runner.mjs +102 -0
  257. package/scripts/fixtures/claude-review-process.mjs +1 -0
  258. package/scripts/fixtures/live-evidence-driver.mjs +35 -0
  259. package/scripts/fixtures/process-cleanup.mjs +101 -0
  260. package/scripts/test-cm-log-event.py +2 -0
  261. package/scripts/test-cm-native-usage.py +62 -0
  262. package/scripts/test-cm-prd-review-gate.py +2 -1
  263. package/scripts/test-external-model-setup.py +91 -0
  264. package/scripts/test-model-configuration-write.py +201 -0
  265. package/scripts/test-npm-install.py +11 -2
  266. package/scripts/test-scan-public-safety.py +1 -1
  267. package/scripts/test-spec-manifest.py +16 -8
  268. package/scripts/test-task-gate.py +2 -2
  269. package/scripts/test-workflow-config.py +1 -0
  270. package/scripts/validate-public-repo.py +1 -0
  271. package/skills/cm-ai/SKILL.md +2 -2
  272. package/skills/cm-ai/references/N1-init.md +1 -1
  273. package/skills/cm-ai/references/N8-finish.md +5 -0
  274. package/skills/cm-ai/references/js-host.md +270 -43
  275. package/skills/cm-ai/references/knowledge-closeout.md +90 -0
  276. package/skills/cm-fix/SKILL.md +1 -1
  277. package/skills/cm-fix/references/js-host.md +52 -3
  278. package/skills/cm-prd/references/js-change-recovery.md +1 -1
  279. package/skills/cm-prd/references/js-host.md +6 -0
  280. package/skills/cm-runtime/SKILL.md +29 -6
  281. package/skills/cm-security/SKILL.md +4 -2
  282. package/skills/cm-security/references/scan-contract.md +1 -0
  283. package/templates/cm-workflow.yml +1 -1
@@ -0,0 +1,214 @@
1
+ #!/usr/bin/env python3
2
+ """POSIX publication only: pinned directories, cooperative lock, byte CAS.
3
+
4
+ The containing directory must be owned by the caller and not group/world writable.
5
+ This does not sandbox a same-UID actor that can move that directory or ignore locks.
6
+ """
7
+ import base64
8
+ import errno
9
+ import hashlib
10
+ import json
11
+ import os
12
+ import stat
13
+ import sys
14
+ import uuid
15
+
16
+ LIMIT = 64 * 1024
17
+ RUN_DIRECTORIES = {'.cm-external-models-v1', '.reviews', '.cm-model-runtime-v1', '.cm-model-reviews-v1',
18
+ '.cm-model-runtime-v2', '.cm-model-reviews-v2', '.cm-model-fix-runtime-v1'}
19
+ RUN_FILES = {'.cm-task-owner.json', '.cm-model-code-owner-v1.json',
20
+ '.cm-model-project-owner-v2.json', '.cm-model-snapshot-v1.json',
21
+ '.cm-model-fix-owner-v1.json'}
22
+ LOCK = '.cm-model-config.lock'
23
+ SECURE_PLATFORM = (os.name == 'posix' and hasattr(os, 'O_NOFOLLOW') and hasattr(os, 'O_DIRECTORY')
24
+ and all(function in os.supports_dir_fd for function in
25
+ (os.open, os.mkdir, os.stat, os.link, os.unlink, os.rename)))
26
+
27
+
28
+ class Refusal(Exception):
29
+ pass
30
+
31
+
32
+ def require(condition, code):
33
+ if not condition:
34
+ raise Refusal(code)
35
+
36
+
37
+ def validate_target(target):
38
+ require(isinstance(target, str) and os.path.isabs(target)
39
+ and os.path.normpath(target) == target, 'unsupported_model_path')
40
+ require(not any(part.lower() in RUN_DIRECTORIES for part in target.split(os.sep))
41
+ and os.path.basename(target).lower() not in RUN_FILES | {LOCK},
42
+ 'model_output_run_path_forbidden')
43
+
44
+
45
+ def open_parent(target, create):
46
+ """Never resolve an ancestor through a symlink, including during mkdir."""
47
+ flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
48
+ current = os.open(os.sep, flags)
49
+ try:
50
+ for part in os.path.dirname(target).split(os.sep)[1:]:
51
+ try:
52
+ child = os.open(part, flags, dir_fd=current)
53
+ except FileNotFoundError:
54
+ require(create, 'unsupported_model_path')
55
+ try:
56
+ os.mkdir(part, 0o700, dir_fd=current)
57
+ os.fsync(current)
58
+ except FileExistsError:
59
+ pass
60
+ child = os.open(part, flags, dir_fd=current)
61
+ os.close(current)
62
+ current = child
63
+ info = os.fstat(current)
64
+ require(info.st_uid == os.geteuid() and not info.st_mode & 0o022,
65
+ 'model_configuration_untrusted_directory')
66
+ return current
67
+ except BaseException:
68
+ os.close(current)
69
+ raise
70
+
71
+
72
+ def file_hash(parent, name):
73
+ try:
74
+ fd = os.open(name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=parent)
75
+ except FileNotFoundError:
76
+ return None
77
+ try:
78
+ before = os.fstat(fd)
79
+ require(stat.S_ISREG(before.st_mode) and before.st_nlink == 1
80
+ and before.st_size <= LIMIT, 'invalid_model_configuration_file')
81
+ with os.fdopen(os.dup(fd), 'rb') as stream:
82
+ content = stream.read(LIMIT + 1)
83
+ after = os.stat(name, dir_fd=parent, follow_symlinks=False)
84
+ identity = lambda info: (info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns,
85
+ info.st_ctime_ns, info.st_nlink)
86
+ require(len(content) <= LIMIT and identity(before) == identity(os.fstat(fd)) and identity(before) == identity(after),
87
+ 'model_configuration_changed')
88
+ return hashlib.sha256(content).hexdigest()
89
+ finally:
90
+ os.close(fd)
91
+
92
+
93
+ def publish(request):
94
+ require(SECURE_PLATFORM, 'model_secure_write_unavailable')
95
+ import fcntl
96
+ require(set(request) == {'target', 'bytes', 'expectedSha256', 'replace', 'createParents', 'sourceGuard'},
97
+ 'invalid_model_write_request')
98
+ target = request['target']
99
+ validate_target(target)
100
+ require(type(request['replace']) is bool and type(request['createParents']) is bool,
101
+ 'invalid_model_write_request')
102
+ content = base64.b64decode(request['bytes'], validate=True)
103
+ require(len(content) <= LIMIT, 'model_configuration_too_large')
104
+ expected = request['expectedSha256']
105
+ require(expected is None or isinstance(expected, str) and len(expected) == 64
106
+ and all(c in '0123456789abcdef' for c in expected), 'invalid_model_write_request')
107
+ guard = request['sourceGuard']
108
+ if guard is not None:
109
+ require(isinstance(guard, dict) and set(guard) == {'file', 'sha256'}
110
+ and isinstance(guard['file'], str)
111
+ and isinstance(guard['sha256'], str) and len(guard['sha256']) == 64
112
+ and all(c in '0123456789abcdef' for c in guard['sha256'])
113
+ and os.path.dirname(guard['file']) == os.path.dirname(target),
114
+ 'invalid_model_write_request')
115
+ validate_target(guard['file'])
116
+ parent = open_parent(target, request['createParents'])
117
+ lock = None
118
+ temporary = None
119
+ published = False
120
+ try:
121
+ try:
122
+ lock = os.open(LOCK, os.O_RDWR | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600, dir_fd=parent)
123
+ except FileExistsError:
124
+ try:
125
+ lock = os.open(LOCK, os.O_RDWR | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=parent)
126
+ except FileNotFoundError:
127
+ raise Refusal('model_configuration_busy')
128
+ info = os.fstat(lock)
129
+ require(stat.S_ISREG(info.st_mode) and info.st_nlink == 1 and info.st_uid == os.geteuid()
130
+ and not info.st_mode & 0o077, 'invalid_model_configuration_lock')
131
+ try:
132
+ fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
133
+ except BlockingIOError:
134
+ raise Refusal('model_configuration_busy')
135
+ # Persistent lock inode: never unlink it, including after crash or success.
136
+ require(os.stat(LOCK, dir_fd=parent, follow_symlinks=False).st_ino == info.st_ino,
137
+ 'invalid_model_configuration_lock')
138
+ name = os.path.basename(target)
139
+ actual = file_hash(parent, name)
140
+ require(request['replace'] or actual is None, 'model_configuration_exists')
141
+ require(actual == expected, 'model_configuration_changed')
142
+ if guard is not None:
143
+ require(file_hash(parent, os.path.basename(guard['file'])) == guard['sha256'],
144
+ 'model_configuration_changed')
145
+ temporary = '.cm-model-' + uuid.uuid4().hex + '.tmp'
146
+ fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600, dir_fd=parent)
147
+ with os.fdopen(fd, 'wb') as stream:
148
+ stream.write(content)
149
+ stream.flush()
150
+ os.fsync(stream.fileno())
151
+ require(file_hash(parent, name) == expected, 'model_configuration_changed')
152
+ if actual is None:
153
+ try:
154
+ os.link(temporary, name, src_dir_fd=parent, dst_dir_fd=parent, follow_symlinks=False)
155
+ except FileExistsError:
156
+ raise Refusal('model_configuration_changed')
157
+ published = True
158
+ os.unlink(temporary, dir_fd=parent)
159
+ else:
160
+ os.replace(temporary, name, src_dir_fd=parent, dst_dir_fd=parent)
161
+ published = True
162
+ temporary = None
163
+ os.fsync(parent)
164
+ # A renamed pinned directory cannot redirect the write, but the named
165
+ # configuration may no longer refer to it. Do not report success then.
166
+ named_parent = open_parent(target, False)
167
+ try:
168
+ pinned, named = os.fstat(parent), os.fstat(named_parent)
169
+ require((pinned.st_dev, pinned.st_ino) == (named.st_dev, named.st_ino),
170
+ 'model_configuration_write_unknown')
171
+ finally:
172
+ os.close(named_parent)
173
+ except BaseException:
174
+ if published:
175
+ raise Refusal('model_configuration_write_unknown')
176
+ raise
177
+ finally:
178
+ cleanup_error = None
179
+ if temporary is not None:
180
+ try:
181
+ os.unlink(temporary, dir_fd=parent)
182
+ except FileNotFoundError:
183
+ pass
184
+ except OSError as error:
185
+ cleanup_error = error
186
+ for descriptor in (lock, parent):
187
+ if descriptor is not None:
188
+ try:
189
+ os.close(descriptor)
190
+ except OSError as error:
191
+ cleanup_error = error
192
+ if cleanup_error is not None:
193
+ if published:
194
+ raise Refusal('model_configuration_write_unknown')
195
+ raise cleanup_error
196
+
197
+
198
+ def main():
199
+ try:
200
+ data = sys.stdin.buffer.read(192 * 1024 + 1)
201
+ require(len(data) <= 192 * 1024, 'model_configuration_too_large')
202
+ publish(json.loads(data))
203
+ print(json.dumps({'ok': True}))
204
+ except Exception as error:
205
+ code = str(error) if isinstance(error, Refusal) else (
206
+ 'unsupported_model_path' if isinstance(error, OSError) and error.errno in (errno.ELOOP, errno.ENOTDIR)
207
+ else 'model_configuration_write_failed')
208
+ print(json.dumps({'ok': False, 'code': code}))
209
+ return 1
210
+ return 0
211
+
212
+
213
+ if __name__ == '__main__':
214
+ sys.exit(main())
@@ -0,0 +1,26 @@
1
+ // Existing authoritative logger/lock adapter, no telemetry or execution authority.
2
+ import {spawnSync} from 'node:child_process';
3
+ import {fileURLToPath} from 'node:url';
4
+ const writer=fileURLToPath(new URL('../../../scripts/cm-log-event.py',import.meta.url));
5
+ export function createNativeUsageLog({definition,request,provider,role,workflow='cm-ai'}){
6
+ const identity={call_id:request.invocationId,stage:role==='developer'?'develop':'review',role,
7
+ adapter:provider+'-cli',requested_model:request.requestedModel,source:'native-cli-terminal',purpose:'workflow-execution'};
8
+ let claimed=false,completed=false;
9
+ const write=(event,phase,data)=>{
10
+ try{
11
+ const result=spawnSync('python3',[writer,'--workflow',workflow,'--event',event,'--phase',phase,
12
+ '--runtime',provider,'--project-root',definition.codeProject,...(definition.specsDir?['--specs-dir',definition.specsDir]:[]),
13
+ '--run-id',request.identity.runId,'--detail','Native CLI usage accounting','--data-json',JSON.stringify(data)],
14
+ {encoding:'utf8',timeout:10000,maxBuffer:1024*1024});
15
+ if(result.error||result.status!==0)throw Error('unavailable');return true;
16
+ }catch{try{process.stderr.write('[usage] usage_record_unavailable\n');}catch{}return false;}
17
+ };
18
+ return {
19
+ claimed(){if(claimed)return;claimed=true;write('model_call','claimed',identity);},
20
+ complete(usage,outcome){
21
+ if(completed||!claimed)return;completed=true;
22
+ write('model_usage','complete',{...identity,provider,...usage,outcome,
23
+ feature:definition.feature,task:request.identity.taskId,attempt:request.identity.attempt});
24
+ },
25
+ };
26
+ }
@@ -0,0 +1,86 @@
1
+ // Presentation only. Native pendingAction decides the available path; guidance
2
+ // never grants permission, changes retryability, or writes execution history.
3
+ const deliveryMessages={
4
+ develop_checks_not_passed:['开发检查未通过,尚未进入独立审查。','根据 reason 中的检查编号和证据修复代码或环境'],
5
+ develop_package_too_large:['审查材料或运行存档记录超过大小限制,交付暂时受阻。','缩小 reason 指出的文件或材料;若要改变任务范围,先走规格变更'],
6
+ developer_result_invalid:['开发答复不符合交付合同。','修正开发答复格式及 Learning 记录'],
7
+ verification_precheck_failed:['交付未满足任务的验证要求。','根据验证证据补齐交付'],
8
+ check_output_out_of_scope:['检查产生了任务范围外的改动。','核对并处理检查产物;保留用户改动,不擅自扩大范围'],
9
+ develop_empty_changes:['交付没有产生可审查的实际改动。','核对任务要求并提供实际修改'],
10
+ develop_unchanged_after_review:['交付没有处理上一轮审查要求。','处理原审查 findings 后提供本轮修改'],
11
+ develop_requirement_missing:['交付后缺少要求保留的文件。','恢复 reason 指出的必要文件'],
12
+ bootstrap_verification_failed:['项目规则验证未通过。','根据规则验证证据修正草稿或检查环境'],
13
+ };
14
+ const explain=(summary,nextStep,operation=null,prerequisites=[])=>Object.freeze({
15
+ summary,nextStep,recoveryOperation:operation,prerequisites:Object.freeze(prerequisites),authorizationGranted:false,
16
+ });
17
+ export function operatorGuidance(result,{executionActive=false}={}){
18
+ if(result?.workflow!=='cm-ai'||!result.state||!result.identity)return null;
19
+ const {state,code,pendingAction:action,outcome}=result;
20
+ if(outcome==='rejected'||outcome==='denied')return explain('本次操作被拒绝,运行状态没有因此获得新的执行权限。',
21
+ '先核对 code 与 reason,修正请求或取得所需授权;不要据此重复开发或审查。');
22
+ if(executionActive)return explain('原运行仍有操作在执行。','等待原操作结果;可读取状态,不重复派发。');
23
+ if(code==='spec_drift')return explain('已批准规格发生变化,后续执行被阻止。',
24
+ action==='spec_rebind'?'先核对重新批准的规格;符合原任务内容未变的条件时,在原运行显式换绑规格。'
25
+ :'先核对规格变更与原任务绑定;当前没有可直接继续的恢复动作。',null,['保留原运行身份与历史','不得绕过规格审批']);
26
+ if(action==='bootstrap_review_recover')return explain('项目规则交付已记录,但规则审查包尚未恢复。',
27
+ '核对当前规则文件、handoff 和原证据;恢复原运行后发送 bootstrap_review_recover。此路径不重新派发开发。',
28
+ 'bootstrap_review_recover',['使用原配置与 runId,以 --mode resume 启动','显式 --allow-bootstrap-review-recovery,并提供单行 reason','由原宿主重新核对恢复条件']);
29
+ if(state==='unknown'){
30
+ if(action==='abandon_effect'||action==='abandon_review'){
31
+ const review=action==='abandon_review';
32
+ return explain(review?'独立审查结果尚未确认。':'开发或完成操作的结果尚未确认。',
33
+ '先核对原操作与磁盘结果,确认旧宿主及相关子进程已退出;符合原宿主条件时,再审计放弃这次操作。放弃不代表成功。',
34
+ action,['保留原配置、runId 和失败历史,以 --mode resume 启动',
35
+ review?'显式 --allow-abandon-review,并提供单行 reason':'显式 --allow-abandon-effect,并提供单行 reason',
36
+ '由原宿主核对可放弃条件;不得直接重跑或改写完成记录']);
37
+ }
38
+ return explain('执行结果尚未确认,不能判断这一步成功或失败。',
39
+ '只读核对原运行记录、进程及实际文件;当前没有已确认的直接重试入口,不新建运行绕过历史。');
40
+ }
41
+ if(state==='blocked'&&action==='resume'&&Object.hasOwn(deliveryMessages,code)){
42
+ const [summary,repair]=deliveryMessages[code];
43
+ return explain(summary,`${repair};然后恢复原运行并发送 advance,重做本轮交付和检查。`,
44
+ 'advance',['保留原配置、runId 与历史,以 --mode resume 启动','确认原宿主已关闭,且本轮开发有原合同要求的授权','不会自动完成任务或消耗新的独立审查轮次']);
45
+ }
46
+ if(state==='pending_review'&&action==='resume')return explain('本轮独立审查未取得可接受的结论。',
47
+ '核对 code 与原审查证据;恢复原运行后,取得本轮绑定的独立审查授权,再发送 advance。',
48
+ 'advance',['原 run、配置和审查包绑定不变','原宿主仍须核对重派次数、进程和独立审查权限']);
49
+ if(state==='blocked'&&action==='complete')return explain('完成前复核受阻,已有审查结论不能直接当作任务完成。',
50
+ '核对 reason 中的检查或文件变化;满足原完成条件后,在原运行发送 complete,不重新开发。',
51
+ 'complete',['原 run 与已审交接、范围和包绑定不变','使用当前 packageDigest;由宿主重新核对完成条件']);
52
+ if(code==='bootstrap_instruction_conflict')return explain('已有项目规则与本次允许的写入基准冲突,规则生成被阻止。',
53
+ '核对前序规则任务、提交基准和当前文件;当前没有可直接重派的动作,不覆盖已有规则。');
54
+ if(code==='checks_not_passed')return explain('旧完成阶段的检查未通过,当前不是可重做开发的阻塞。',
55
+ '保留原检查与审查证据,核对原完成恢复合同;不要使用开发重试或新建运行绕过。');
56
+ if(state==='blocked'||code==='correction_review_required'||code==='review_package_changed')return explain('当前流程受阻,尚未确认可执行的恢复步骤。',
57
+ '核对 code、reason 和原运行证据;保留已有文件与历史,不把通用阻塞当作重试许可。');
58
+ return null;
59
+ }
60
+ // Only bounded static guidance is rendered, never raw provider output.
61
+ export function guidanceText(result){
62
+ if(result?.workflow!=='cm-ai')return null;
63
+ const guidance=result?.guidance;
64
+ const bounded=value=>typeof value==='string'&&Buffer.byteLength(value,'utf8')<=2000&&!/[\r\n\0]/.test(value);
65
+ if(!guidance||guidance.authorizationGranted!==false||!bounded(guidance.summary)||!bounded(guidance.nextStep)
66
+ ||!Array.isArray(guidance.prerequisites)||guidance.prerequisites.length>8||!guidance.prerequisites.every(bounded))return null;
67
+ return `${guidance.summary} ${guidance.nextStep} ${guidance.prerequisites.join(';')}`.trim();
68
+ }
69
+
70
+ // A member result is not a batch control surface. Keep unsupported single-run
71
+ // recovery operations out of batch instructions without changing pendingAction.
72
+ export function batchOperatorGuidance(result){
73
+ const g=result?.guidance;if(!g)return null;
74
+ if(result.code==='spec_drift')return explain(g.summary,
75
+ '批次成员不能换绑规格;先按 reason 核对原批次可用出口,不直接重派。');
76
+ if(g.recoveryOperation==='advance')return explain(g.summary,
77
+ g.nextStep.replace('然后恢复原运行并发送 advance,重做本轮交付和检查。','然后从原批次入口发送 advance,重做本轮交付和检查。')
78
+ .replace('恢复原运行后,取得本轮绑定的独立审查授权,再发送 advance。','沿原批次续接,取得本轮绑定的独立审查授权,再发送 advance。'),
79
+ 'advance',['保持原批次配置、身份和 PLAN;成员运行由批次宿主选择恢复','先确认原批次宿主已关闭;开发与审查仍需原合同授权']);
80
+ if(g.recoveryOperation==='complete')return explain(g.summary,
81
+ '核对 reason 中的检查或文件变化;满足原完成条件后,从原批次入口发送 advance,由成员宿主继续完成复核。',
82
+ 'advance',['保留原批次配置与已审证据;不重新开发','成员宿主重新核对完成条件']);
83
+ if(g.recoveryOperation)return explain(g.summary,
84
+ '批次入口不支持此成员恢复操作;先核对原成员运行与 reason,不通过 advance 重派或新建运行绕过。');
85
+ return g;
86
+ }
@@ -0,0 +1,22 @@
1
+ // POSIX children must be spawned detached. Own only that child's process group.
2
+ // A leader closing its pipes does not cancel escalation for its descendants.
3
+ export function ownedProcessCleanup(child,{graceMs=250,killWaitMs=750,killProcess=process.kill.bind(process)}={}) {
4
+ let cleanup;
5
+ const error=()=>Object.assign(new Error('process_cleanup_unknown'),{code:'process_cleanup_unknown'});
6
+ const signal=value=>{
7
+ try{killProcess(-child.pid,value);return true;}
8
+ catch(e){if(e.code==='ESRCH')return false;throw error();}
9
+ };
10
+ const pause=ms=>new Promise(resolve=>setTimeout(resolve,ms));
11
+ return ()=>cleanup??=(async()=>{
12
+ // Preserve the legacy Windows leader termination, without claiming tree cleanup.
13
+ if(process.platform==='win32'){child.kill('SIGTERM');throw error();}
14
+ // A failed spawn has no PID; in-memory test transports also have none.
15
+ if(!Number.isInteger(child.pid)||child.pid<=0){child.kill('SIGTERM');return;}
16
+ if(!signal('SIGTERM'))return;
17
+ await pause(graceMs);
18
+ if(!signal('SIGKILL'))return;
19
+ const until=Date.now()+killWaitMs;
20
+ while(signal(0)){if(Date.now()>=until)throw error();await pause(25);}
21
+ })();
22
+ }
@@ -0,0 +1,84 @@
1
+ // Project-level view of every approved feature's latest N6 QA, read from the
2
+ // authoritative specs log. Read-only: it names what has not passed; it never
3
+ // reruns, repairs, supersedes or reinterprets a QA result.
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import {scanRows} from './log-rows.mjs';
7
+
8
+ const LABELS={qa_failed:'最新一轮 FAIL',qa_blocked:'最新一轮 BLOCKED',qa_decision_blocked:'QA 决策阻塞',
9
+ qa_not_run:'已触发但未执行',qa_execution_unknown:'执行结果未知',qa_pending:'旧结果已作废,待下一轮',
10
+ qa_missing:'任务已全部完成,但没有 QA 记录',qa_skipped:'任务已全部完成,但最新 QA 决策为跳过'};
11
+ const cache=new Map();
12
+
13
+ // One pass: the latest decision per feature, and the test_run rows bound to it.
14
+ function readFeatureQa(specsDir){
15
+ const log=path.join(path.resolve(specsDir),'运行日志.jsonl');
16
+ let stat;
17
+ try{stat=fs.lstatSync(log);}catch(error){if(error.code==='ENOENT')return new Map();throw error;}
18
+ const key=[log,stat.dev,stat.ino,stat.size,stat.mtimeMs,stat.ctimeMs].join(':');
19
+ if(cache.has(key))return cache.get(key);
20
+ const decisions=new Map(),runs=[];
21
+ scanRows(log,row=>{
22
+ if(row?.schema_version!==1||row.workflow!=='cm-ai'||row.node!=='N6'||typeof row.feature!=='string')return;
23
+ if(row.event==='qa')decisions.set(row.feature,row);
24
+ else if(row.event==='test_run')runs.push(row);
25
+ });
26
+ const result=new Map([...decisions].map(([feature,decision])=>[feature,{decision,
27
+ runs:runs.filter(row=>row.feature===feature&&row.run_id===decision.run_id&&row.repository_id===decision.repository_id
28
+ &&row.task===decision.task&&row.package_digest===decision.package_digest&&row.qa_decision_id===decision.decision_id)}]));
29
+ cache.clear();cache.set(key,result);
30
+ return result;
31
+ }
32
+
33
+ // Row-level reading for warnings. The strict owner validator replaces it via
34
+ // `inspect` wherever a result gates run_done.
35
+ function latestRound(runs){
36
+ const start=runs.filter(row=>row.phase==='start').at(-1);
37
+ if(!start)return 'qa_not_run';
38
+ const rows=runs.filter(row=>row.operation_id===start.operation_id);
39
+ if(rows.some(row=>['superseded','abandoned'].includes(row.phase)))return 'qa_pending';
40
+ const complete=rows.find(row=>row.phase==='complete');
41
+ if(!complete)return 'qa_execution_unknown';
42
+ const result=String(complete.result).toUpperCase();
43
+ return ['PASS','PASSED'].includes(result)?null:['FAIL','FAILED'].includes(result)?'qa_failed':'qa_blocked';
44
+ }
45
+
46
+ // features: admission summaries {name,pending}. The latest QA decision of each
47
+ // feature (from any run but the caller's own) must not have failed. A skip is
48
+ // fine while tasks remain; a terminal feature (pending 0) must end in its
49
+ // feature-completion QA with a completed PASS. N6 cannot be switched off in the
50
+ // JS flow, so a terminal feature with no QA rows, or whose latest decision is a
51
+ // skip, was finished outside it and is reported rather than trusted.
52
+ export function outstandingFeatureQa({specsDir,features,currentRunId=null,inspect=null}){
53
+ const outstanding=[],qa=readFeatureQa(specsDir);
54
+ for(const {name:feature,pending} of features){
55
+ const terminal=pending===0,entry=qa.get(feature);
56
+ if(!entry){
57
+ if(terminal)outstanding.push({feature,runId:null,taskId:null,attempt:null,status:'qa_missing'});
58
+ continue;
59
+ }
60
+ const {decision,runs}=entry;
61
+ if(decision.run_id===currentRunId)continue;
62
+ let status;
63
+ if(decision.status==='skipped')status=terminal?'qa_skipped':null;
64
+ else if(decision.status!=='triggered')status='qa_decision_blocked';
65
+ else if(inspect===null)status=latestRound(runs);
66
+ else{
67
+ try{
68
+ const latest=inspect({specsDir,feature,packageDigest:decision.package_digest,identity:{repositoryId:decision.repository_id,
69
+ runId:decision.run_id,taskId:decision.task,attempt:decision.attempt}});
70
+ status=latest===null?'qa_not_run':latest.status==='passed'?null:latest.status==='failed'?'qa_failed':'qa_blocked';
71
+ }catch(error){
72
+ status=error?.code==='qa_result_incomplete'?'qa_execution_unknown':error?.code==='qa_result_superseded'?'qa_pending'
73
+ :typeof error?.code==='string'&&/^[a-z][a-z0-9_]{0,63}$/.test(error.code)?error.code:'qa_result_invalid';
74
+ }
75
+ }
76
+ if(status!==null)outstanding.push({feature,runId:decision.run_id,taskId:decision.task,attempt:decision.attempt,status});
77
+ }
78
+ return outstanding;
79
+ }
80
+
81
+ export function describeOutstandingQa(item){
82
+ const label=LABELS[item.status]??item.status;
83
+ return item.runId===null?`${item.feature}(${label})`:`${item.feature}(${item.taskId} / run ${item.runId}:${label})`;
84
+ }
@@ -18,9 +18,10 @@ function expectation(v,cause=false) {
18
18
  need(r.version===1&&r.role==='reviewer'&&['codex','claude'].includes(r.provider));
19
19
  id(r.invocationId);id(r.contextId);validIdentity(r.identity);text(r.requestedModel);hex(r.requestDigest);
20
20
  const {requestDigest,...body}=r;need(digest(body)===requestDigest,'observation_binding');
21
- shape(r.payload,['reviewPackage','priorReview']);
21
+ const carried=Object.hasOwn(r.payload,'supersededReview');
22
+ shape(r.payload,['reviewPackage','priorReview',...(carried?['supersededReview']:[])]);
22
23
  const pkg=(cause?readFixCausePackage:readReviewPackage)(r.payload.reviewPackage);
23
- if(cause)need(r.payload.priorReview===null,'observation_binding');
24
+ if(cause)need(r.payload.priorReview===null&&!carried,'observation_binding');
24
25
  need(digest(pkg.identity)===digest(r.identity),'observation_binding');
25
26
  return {request:r,pkg,excluded:new Set([v.developerThreadId,...v.excludedThreadIds])};
26
27
  }
@@ -60,15 +61,19 @@ export function inspectProviderCauseReview(observationText,expectationText){
60
61
  need(arguments.length===2);
61
62
  return inspect(observationText,expectationText,true);
62
63
  }
64
+ function readObservation(observationText,expectationText,cause) {
65
+ const observation=decode(observationText,1024*1024),expected=expectation(decode(expectationText,10*1024*1024),cause);
66
+ shape(observation,['version','kind','requestDigest','events','result']);
67
+ need(observation.version===1&&observation.kind==='cm-provider-review-observation');
68
+ hex(observation.requestDigest);need(observation.requestDigest===expected.request.requestDigest,'observation_binding');
69
+ const stream=eventStream(observation.events,expected.excluded),r=observation.result;
70
+ if(r?.status==='succeeded')shape(r,['status','value']);
71
+ else {shape(r,['status','code']);need(['failed','cancelled'].includes(r.status));text(r.code);need(r.code.length<=256);}
72
+ return {observation,expected,...stream,r};
73
+ }
63
74
  function inspect(observationText,expectationText,cause) {
64
75
  try {
65
- const observation=decode(observationText,1024*1024),expected=expectation(decode(expectationText,10*1024*1024),cause);
66
- shape(observation,['version','kind','requestDigest','events','result']);
67
- need(observation.version===1&&observation.kind==='cm-provider-review-observation');
68
- hex(observation.requestDigest);need(observation.requestDigest===expected.request.requestDigest,'observation_binding');
69
- const {thread,terminal,close}=eventStream(observation.events,expected.excluded),r=observation.result;
70
- if(r?.status==='succeeded')shape(r,['status','value']);
71
- else {shape(r,['status','code']);need(['failed','cancelled'].includes(r.status));text(r.code);need(r.code.length<=256);}
76
+ const {observation,expected,thread,terminal,close,r}=readObservation(observationText,expectationText,cause);
72
77
  let observationStatus='unknown',code='transport_incomplete',review=null;
73
78
  if(close?.timed_out===true||r.code==='timeout')code='transport_timeout';
74
79
  else if(r.status==='cancelled'||r.code==='cancelled'){observationStatus='cancelled';code='transport_cancelled';}
@@ -88,3 +93,57 @@ function inspect(observationText,expectationText,cause) {
88
93
  throw Object.assign(new Error(code),{code});
89
94
  }
90
95
  }
96
+
97
+ // A reviewer that ended without a usable verdict and broke no boundary may be
98
+ // dispatched once more; the class tells the user whether to log in or wait.
99
+ // Only these fixed worker codes qualify, and only with no final message and an
100
+ // observed process exit. Tool/context breaks, output limits, spawn or prompt
101
+ // failures and any other code stay unknown, as before.
102
+ export const REVIEWER_PROVIDER_FAILURES=Object.freeze({
103
+ reviewer_auth_failed:'reviewer_auth_failed',reviewer_billing_error:'reviewer_billing_error',
104
+ reviewer_rate_limited:'reviewer_rate_limited',reviewer_server_error:'reviewer_server_error',
105
+ reviewer_model_not_found:'reviewer_model_not_found',reviewer_api_error:'reviewer_api_error',
106
+ provider_failed:'reviewer_provider_failed',incomplete_result:'reviewer_exited',
107
+ missing_init:'reviewer_stream_unrecognized',unexpected_event:'reviewer_stream_unrecognized',
108
+ invalid_event:'reviewer_stream_unrecognized'});
109
+ // A complete answer that breaks the written verdict contract can never become a
110
+ // receipt. It is retried under the same budget and its exact code is kept.
111
+ export const REVIEWER_VERDICT_FAILURES=Object.freeze(['contradictory_verdict','invalid_finding_path',
112
+ 'invalid_finding_severity','invalid_finding_id','invalid_finding_shape','missing_material','review_package_mismatch']);
113
+ // Pure and deterministic: live classification and journal replay call it with
114
+ // the same bytes. Returns null for everything that is not such a failure.
115
+ export function inspectProviderReviewFailure(observationText,expectationText){
116
+ need(arguments.length===2);
117
+ let read;
118
+ try{read=readObservation(observationText,expectationText,false);}catch{return null;}
119
+ const {observation,expected,thread,terminal,close,hasResult,r}=read;
120
+ if(close===null||close.timed_out||r.status==='cancelled'||['timeout','cancelled'].includes(r.code))return null;
121
+ let category,failure;
122
+ if(!hasResult){
123
+ if(r.status!=='failed'||!Object.hasOwn(REVIEWER_PROVIDER_FAILURES,r.code))return null;
124
+ category='provider';failure=REVIEWER_PROVIDER_FAILURES[r.code];
125
+ }else{
126
+ if(!(close.exit_code===0&&close.signal===null&&terminal==='turn.completed'&&r.status==='succeeded'))return null;
127
+ try{reviewResult(r.value,expected.pkg);return null;}
128
+ catch(error){if(!REVIEWER_VERDICT_FAILURES.includes(error?.code))return null;category='verdict';failure=error.code;}
129
+ }
130
+ return json({version:1,kind:'cm-provider-review-failure',requestDigest:expected.request.requestDigest,
131
+ observationDigest:digest(observation),identity:expected.request.identity,logicalContextId:expected.request.contextId,
132
+ provider:expected.request.provider,requestedModel:expected.request.requestedModel,providerThreadId:thread,
133
+ category,failure,completionEligible:false});
134
+ }
135
+
136
+ export function inspectProviderReviewReconciliation(observationText,expectationText,cause=false){
137
+ const {observation,expected,thread,terminal,close,r}=readObservation(observationText,expectationText,cause);
138
+ need(thread!==null&&close!==null,'review_reconciliation_evidence_required');
139
+ if(terminal==='turn.completed'&&r.status==='succeeded'){
140
+ const review=cause?reviewResultForPaths(r.value,expected.pkg,causeReviewPaths(expected.pkg)):reviewResult(r.value,expected.pkg);
141
+ return json({...inspect(observationText,expectationText,cause),observationStatus:'completed',code:null,review});
142
+ }
143
+ need(['error','turn.failed'].includes(terminal)&&r.status==='failed'&&r.code==='provider_failed',
144
+ 'review_reconciliation_evidence_required');
145
+ return json({version:1,kind:'cm-provider-review-failure',requestDigest:expected.request.requestDigest,
146
+ observationDigest:digest(observation),identity:expected.request.identity,logicalContextId:expected.request.contextId,
147
+ provider:expected.request.provider,requestedModel:expected.request.requestedModel,providerThreadId:thread,
148
+ category:'provider',failure:'reviewer_provider_failed',completionEligible:false});
149
+ }
@@ -0,0 +1,39 @@
1
+ import {types} from 'node:util';
2
+ // Accept only actual CLI terminal usage, never answer text, estimates or heartbeats.
3
+ const record=value=>value!==null&&typeof value==='object'&&!Array.isArray(value);
4
+ const count=value=>Number.isSafeInteger(value)&&value>=0;
5
+ export function readProviderUsage(provider,raw){
6
+ if(!record(raw)||!count(raw.input_tokens)||!count(raw.output_tokens))return {usage_state:'unavailable'};
7
+ const result={usage_state:'observed',input_tokens:raw.input_tokens,output_tokens:raw.output_tokens};
8
+ const fields=provider==='codex'?{cached_input_tokens:'cache_read_tokens',cache_write_input_tokens:'cache_write_tokens',reasoning_output_tokens:'reasoning_tokens'}:
9
+ provider==='claude'?{cache_read_input_tokens:'cache_read_tokens',cache_creation_input_tokens:'cache_write_tokens'}:null;
10
+ if(fields===null)return {usage_state:'unavailable'};
11
+ for(const [source,target] of Object.entries(fields))if(Object.hasOwn(raw,source)){
12
+ if(!count(raw[source]))return {usage_state:'unavailable'};result[target]=raw[source];
13
+ }
14
+ if(record(raw.output_tokens_details)&&Object.hasOwn(raw.output_tokens_details,'reasoning_tokens')){
15
+ const reasoning=raw.output_tokens_details.reasoning_tokens;
16
+ if(!count(reasoning)||reasoning>raw.output_tokens)return {usage_state:'unavailable'};
17
+ if(Object.hasOwn(result,'reasoning_tokens')&&result.reasoning_tokens!==reasoning)return {usage_state:'unavailable'};
18
+ result.reasoning_tokens=reasoning; // A subset annotation: NEVER added to output_tokens.
19
+ }
20
+ if(provider==='codex'&&result.cache_read_tokens>result.input_tokens)return {usage_state:'unavailable'};
21
+ if(result.reasoning_tokens>result.output_tokens)return {usage_state:'unavailable'};
22
+ return result;
23
+ }
24
+ export function createProviderUsageCapture(provider,onUsage){
25
+ let value=null,conflict=false,completed=false;
26
+ return {
27
+ terminal(usage){
28
+ const next=readProviderUsage(provider,usage);
29
+ if(value!==null&&JSON.stringify(value)!==JSON.stringify(next))conflict=true;
30
+ value??=next;
31
+ },
32
+ complete(){
33
+ if(completed)return;completed=true;
34
+ try{const returned=onUsage?.(conflict?{usage_state:'unavailable'}:value??{usage_state:'unavailable'});
35
+ if(types.isPromise(returned))Promise.prototype.then.call(returned,()=>{},()=>{});
36
+ }catch{/* accounting cannot retry or decide execution */}
37
+ },
38
+ };
39
+ }