dsh-compound-engineering 0.0.0-stage → 0.1.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.
Files changed (461) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +160 -2
  3. package/README.zh.md +161 -0
  4. package/cordis.patch.yml +6 -0
  5. package/lib/frontmatter.js +167 -0
  6. package/lib/index.js +46 -0
  7. package/lib/provider.js +201 -0
  8. package/package.json +62 -4
  9. package/skills/CODING_STANDARDS.md +68 -0
  10. package/skills/ce-babysit-pr/SKILL.md +59 -0
  11. package/skills/ce-babysit-pr/references/branch-currency.md +22 -0
  12. package/skills/ce-babysit-pr/references/envelope.md +44 -0
  13. package/skills/ce-babysit-pr/references/pipeline.md +15 -0
  14. package/skills/ce-babysit-pr/references/report.md +20 -0
  15. package/skills/ce-babysit-pr/references/settle.md +37 -0
  16. package/skills/ce-babysit-pr/references/setup.md +33 -0
  17. package/skills/ce-babysit-pr/references/stack-commands.md +39 -0
  18. package/skills/ce-babysit-pr/references/stack.md +43 -0
  19. package/skills/ce-babysit-pr/references/tick.md +102 -0
  20. package/skills/ce-babysit-pr/references/watch-loop.md +222 -0
  21. package/skills/ce-babysit-pr/scripts/pr-snapshot +3656 -0
  22. package/skills/ce-bakeoff/SKILL.md +48 -0
  23. package/skills/ce-bakeoff/references/candidates.md +37 -0
  24. package/skills/ce-bakeoff/references/judging.md +19 -0
  25. package/skills/ce-bakeoff/references/output.md +11 -0
  26. package/skills/ce-bakeoff/references/verification.md +15 -0
  27. package/skills/ce-brainstorm/SKILL.md +69 -0
  28. package/skills/ce-brainstorm/references/agents/slack-researcher.md +127 -0
  29. package/skills/ce-brainstorm/references/approaches.md +57 -0
  30. package/skills/ce-brainstorm/references/bakeoff.md +9 -0
  31. package/skills/ce-brainstorm/references/blindspot-pass.md +70 -0
  32. package/skills/ce-brainstorm/references/brainstorm-sections.md +458 -0
  33. package/skills/ce-brainstorm/references/dialogue.md +89 -0
  34. package/skills/ce-brainstorm/references/handoff.md +187 -0
  35. package/skills/ce-brainstorm/references/html-rendering.md +638 -0
  36. package/skills/ce-brainstorm/references/interaction-rules.md +33 -0
  37. package/skills/ce-brainstorm/references/markdown-rendering.md +242 -0
  38. package/skills/ce-brainstorm/references/model-tiers.md +13 -0
  39. package/skills/ce-brainstorm/references/output-mode.md +26 -0
  40. package/skills/ce-brainstorm/references/phase-0.md +104 -0
  41. package/skills/ce-brainstorm/references/plan-write.md +32 -0
  42. package/skills/ce-brainstorm/references/product-pressure-test.md +42 -0
  43. package/skills/ce-brainstorm/references/reasoning-elevation.md +124 -0
  44. package/skills/ce-brainstorm/references/settled-decisions.md +45 -0
  45. package/skills/ce-brainstorm/references/synthesis-summary.md +149 -0
  46. package/skills/ce-brainstorm/references/universal-brainstorming.md +72 -0
  47. package/skills/ce-brainstorm/references/verdict-routing.md +26 -0
  48. package/skills/ce-brainstorm/references/visual-probes.md +164 -0
  49. package/skills/ce-brainstorm/scripts/elevation-dispatch.sh +288 -0
  50. package/skills/ce-brainstorm/scripts/light-webserver.js +1275 -0
  51. package/skills/ce-brainstorm/scripts/packs-resolve.py +737 -0
  52. package/skills/ce-brainstorm/scripts/peer-job-runner.py +2594 -0
  53. package/skills/ce-code-review/SKILL.md +40 -0
  54. package/skills/ce-code-review/references/action-class-rubric.md +67 -0
  55. package/skills/ce-code-review/references/cross-model-recovery.md +38 -0
  56. package/skills/ce-code-review/references/cross-model-review.md +191 -0
  57. package/skills/ce-code-review/references/depth-paths.md +32 -0
  58. package/skills/ce-code-review/references/diff-scope.md +59 -0
  59. package/skills/ce-code-review/references/dispatch-reviewers.md +135 -0
  60. package/skills/ce-code-review/references/findings-schema.json +125 -0
  61. package/skills/ce-code-review/references/finish-input.md +118 -0
  62. package/skills/ce-code-review/references/finish-review.md +202 -0
  63. package/skills/ce-code-review/references/intent-and-plan.md +73 -0
  64. package/skills/ce-code-review/references/modes-and-output.md +156 -0
  65. package/skills/ce-code-review/references/persona-catalog.md +66 -0
  66. package/skills/ce-code-review/references/personas/adversarial-reviewer.md +111 -0
  67. package/skills/ce-code-review/references/personas/agent-native-reviewer.md +173 -0
  68. package/skills/ce-code-review/references/personas/api-contract-reviewer.md +44 -0
  69. package/skills/ce-code-review/references/personas/correctness-reviewer.md +48 -0
  70. package/skills/ce-code-review/references/personas/data-migration-reviewer.md +111 -0
  71. package/skills/ce-code-review/references/personas/deployment-verification-agent.md +157 -0
  72. package/skills/ce-code-review/references/personas/julik-frontend-races-reviewer.md +45 -0
  73. package/skills/ce-code-review/references/personas/learnings-researcher.md +260 -0
  74. package/skills/ce-code-review/references/personas/maintainability-reviewer.md +85 -0
  75. package/skills/ce-code-review/references/personas/performance-reviewer.md +45 -0
  76. package/skills/ce-code-review/references/personas/previous-comments-reviewer.md +59 -0
  77. package/skills/ce-code-review/references/personas/project-standards-reviewer.md +77 -0
  78. package/skills/ce-code-review/references/personas/reliability-reviewer.md +49 -0
  79. package/skills/ce-code-review/references/personas/security-reviewer.md +50 -0
  80. package/skills/ce-code-review/references/personas/swift-ios-reviewer.md +99 -0
  81. package/skills/ce-code-review/references/personas/testing-reviewer.md +51 -0
  82. package/skills/ce-code-review/references/review-output-template.md +172 -0
  83. package/skills/ce-code-review/references/scope.md +176 -0
  84. package/skills/ce-code-review/references/select-and-route.md +93 -0
  85. package/skills/ce-code-review/references/subagent-template.md +206 -0
  86. package/skills/ce-code-review/references/validator-batch-template.md +67 -0
  87. package/skills/ce-code-review/scripts/cross-model-adversarial-review.sh +1275 -0
  88. package/skills/ce-code-review/scripts/findings-mechanics.py +274 -0
  89. package/skills/ce-code-review/scripts/packs-resolve.py +737 -0
  90. package/skills/ce-code-review/scripts/peer-job-runner.py +2594 -0
  91. package/skills/ce-code-review/scripts/review-scope.py +419 -0
  92. package/skills/ce-code-review/scripts/run-log.py +280 -0
  93. package/skills/ce-commit/SKILL.md +60 -0
  94. package/skills/ce-commit-push-pr/SKILL.md +69 -0
  95. package/skills/ce-commit-push-pr/references/apply-and-handoff.md +79 -0
  96. package/skills/ce-commit-push-pr/references/branch-creation.md +47 -0
  97. package/skills/ce-commit-push-pr/references/commit-and-push.md +26 -0
  98. package/skills/ce-commit-push-pr/references/compose.md +29 -0
  99. package/skills/ce-commit-push-pr/references/context.md +42 -0
  100. package/skills/ce-commit-push-pr/references/gh-stack-cli.md +83 -0
  101. package/skills/ce-commit-push-pr/references/pr-description-writing.md +208 -0
  102. package/skills/ce-commit-push-pr/references/stack-submit.md +81 -0
  103. package/skills/ce-compound/SKILL.md +79 -0
  104. package/skills/ce-compound/assets/resolution-template.md +96 -0
  105. package/skills/ce-compound/references/agents/best-practices-researcher.md +115 -0
  106. package/skills/ce-compound/references/agents/data-integrity-guardian.md +68 -0
  107. package/skills/ce-compound/references/agents/framework-docs-researcher.md +93 -0
  108. package/skills/ce-compound/references/agents/pattern-recognition-specialist.md +55 -0
  109. package/skills/ce-compound/references/agents/performance-oracle.md +108 -0
  110. package/skills/ce-compound/references/agents/security-sentinel.md +91 -0
  111. package/skills/ce-compound/references/agents/session-historian.md +82 -0
  112. package/skills/ce-compound/references/assembly.md +127 -0
  113. package/skills/ce-compound/references/concepts-vocabulary.md +98 -0
  114. package/skills/ce-compound/references/enhancement.md +42 -0
  115. package/skills/ce-compound/references/grounding-validation.md +89 -0
  116. package/skills/ce-compound/references/lightweight.md +56 -0
  117. package/skills/ce-compound/references/modes.md +13 -0
  118. package/skills/ce-compound/references/refresh-and-discoverability.md +96 -0
  119. package/skills/ce-compound/references/report.md +115 -0
  120. package/skills/ce-compound/references/research.md +144 -0
  121. package/skills/ce-compound/references/schema.yaml +236 -0
  122. package/skills/ce-compound/references/session-history.md +73 -0
  123. package/skills/ce-compound/references/yaml-schema.md +130 -0
  124. package/skills/ce-compound/scripts/packs-resolve.py +737 -0
  125. package/skills/ce-compound/scripts/session-history/__pycache__/dsh_session.cpython-314.pyc +0 -0
  126. package/skills/ce-compound/scripts/session-history/discover-sessions.sh +290 -0
  127. package/skills/ce-compound/scripts/session-history/discover_dsh.py +123 -0
  128. package/skills/ce-compound/scripts/session-history/dsh_session.py +225 -0
  129. package/skills/ce-compound/scripts/session-history/extract-errors.py +178 -0
  130. package/skills/ce-compound/scripts/session-history/extract-metadata.py +301 -0
  131. package/skills/ce-compound/scripts/session-history/extract-skeleton.py +346 -0
  132. package/skills/ce-compound/scripts/validate-doc-claims.py +497 -0
  133. package/skills/ce-compound/scripts/validate-frontmatter.py +137 -0
  134. package/skills/ce-compound-refresh/SKILL.md +88 -0
  135. package/skills/ce-compound-refresh/assets/resolution-template.md +96 -0
  136. package/skills/ce-compound-refresh/references/classify.md +42 -0
  137. package/skills/ce-compound-refresh/references/commit.md +7 -0
  138. package/skills/ce-compound-refresh/references/concepts-vocabulary.md +116 -0
  139. package/skills/ce-compound-refresh/references/discoverability.md +15 -0
  140. package/skills/ce-compound-refresh/references/investigate.md +23 -0
  141. package/skills/ce-compound-refresh/references/modes.md +27 -0
  142. package/skills/ce-compound-refresh/references/per-action-flows.md +142 -0
  143. package/skills/ce-compound-refresh/references/report.md +23 -0
  144. package/skills/ce-compound-refresh/references/schema.yaml +236 -0
  145. package/skills/ce-compound-refresh/references/scope.md +18 -0
  146. package/skills/ce-compound-refresh/references/worth-audit.md +35 -0
  147. package/skills/ce-compound-refresh/references/yaml-schema.md +130 -0
  148. package/skills/ce-compound-refresh/scripts/validate-doc-claims.py +497 -0
  149. package/skills/ce-compound-refresh/scripts/validate-frontmatter.py +137 -0
  150. package/skills/ce-debug/SKILL.md +122 -0
  151. package/skills/ce-debug/references/anti-patterns.md +91 -0
  152. package/skills/ce-debug/references/defense-in-depth.md +39 -0
  153. package/skills/ce-debug/references/fix.md +21 -0
  154. package/skills/ce-debug/references/investigate.md +114 -0
  155. package/skills/ce-debug/references/investigation-techniques.md +384 -0
  156. package/skills/ce-debug/references/pipeline-mode.md +78 -0
  157. package/skills/ce-debug/references/post-fix-handoff.md +60 -0
  158. package/skills/ce-debug/references/return-to-caller.md +57 -0
  159. package/skills/ce-doc-review/SKILL.md +75 -0
  160. package/skills/ce-doc-review/references/bulk-preview.md +146 -0
  161. package/skills/ce-doc-review/references/cross-model-review.md +207 -0
  162. package/skills/ce-doc-review/references/decision-primer.md +47 -0
  163. package/skills/ce-doc-review/references/dispatch.md +56 -0
  164. package/skills/ce-doc-review/references/document-intake.md +44 -0
  165. package/skills/ce-doc-review/references/findings-schema.json +85 -0
  166. package/skills/ce-doc-review/references/modes.md +20 -0
  167. package/skills/ce-doc-review/references/open-questions-defer.md +158 -0
  168. package/skills/ce-doc-review/references/persona-selection.md +41 -0
  169. package/skills/ce-doc-review/references/personas/adversarial-document-reviewer.md +109 -0
  170. package/skills/ce-doc-review/references/personas/coherence-reviewer.md +69 -0
  171. package/skills/ce-doc-review/references/personas/design-lens-reviewer.md +48 -0
  172. package/skills/ce-doc-review/references/personas/feasibility-reviewer.md +50 -0
  173. package/skills/ce-doc-review/references/personas/product-lens-reviewer.md +85 -0
  174. package/skills/ce-doc-review/references/personas/scope-guardian-reviewer.md +83 -0
  175. package/skills/ce-doc-review/references/personas/security-lens-reviewer.md +41 -0
  176. package/skills/ce-doc-review/references/personas/whole-doc-reviewer.md +25 -0
  177. package/skills/ce-doc-review/references/rendering-floor.md +175 -0
  178. package/skills/ce-doc-review/references/review-output-template.md +123 -0
  179. package/skills/ce-doc-review/references/subagent-template.md +188 -0
  180. package/skills/ce-doc-review/references/synthesis-and-presentation.md +350 -0
  181. package/skills/ce-doc-review/references/walkthrough.md +347 -0
  182. package/skills/ce-doc-review/scripts/cross-model-doc-review.sh +1270 -0
  183. package/skills/ce-doc-review/scripts/packs-resolve.py +737 -0
  184. package/skills/ce-doc-review/scripts/peer-job-runner.py +2594 -0
  185. package/skills/ce-dogfood/SKILL.md +66 -0
  186. package/skills/ce-dogfood/agents/openai.yaml +2 -0
  187. package/skills/ce-dogfood/references/dogfood-report-template.md +97 -0
  188. package/skills/ce-dogfood/references/phases.md +167 -0
  189. package/skills/ce-dogfood/references/test-matrix-taxonomy.md +62 -0
  190. package/skills/ce-dogfood/scripts/packs-resolve.py +737 -0
  191. package/skills/ce-explain/SKILL.md +81 -0
  192. package/skills/ce-explain/references/agents/behavior-trace-scout.md +19 -0
  193. package/skills/ce-explain/references/agents/work-recap-scout.md +23 -0
  194. package/skills/ce-explain/references/check-in.md +18 -0
  195. package/skills/ce-explain/references/destinations.md +35 -0
  196. package/skills/ce-explain/references/explainer-html.md +29 -0
  197. package/skills/ce-explain/references/explainer-markdown.md +24 -0
  198. package/skills/ce-explain/references/intake.md +50 -0
  199. package/skills/ce-explain/references/orchestration.md +46 -0
  200. package/skills/ce-handoff/SKILL.md +54 -0
  201. package/skills/ce-handoff/references/create.md +88 -0
  202. package/skills/ce-handoff/references/resume.md +46 -0
  203. package/skills/ce-ideate/SKILL.md +75 -0
  204. package/skills/ce-ideate/references/agents/issue-intelligence-analyst.md +166 -0
  205. package/skills/ce-ideate/references/agents/learnings-researcher.md +247 -0
  206. package/skills/ce-ideate/references/agents/slack-researcher.md +127 -0
  207. package/skills/ce-ideate/references/agents/web-researcher.md +121 -0
  208. package/skills/ce-ideate/references/decomposition.md +39 -0
  209. package/skills/ce-ideate/references/divergent-ideation.md +112 -0
  210. package/skills/ce-ideate/references/grounding.md +138 -0
  211. package/skills/ce-ideate/references/html-rendering.md +638 -0
  212. package/skills/ce-ideate/references/ideation-sections.md +191 -0
  213. package/skills/ce-ideate/references/issue-intelligence.md +44 -0
  214. package/skills/ce-ideate/references/markdown-rendering.md +242 -0
  215. package/skills/ce-ideate/references/output-mode.md +34 -0
  216. package/skills/ce-ideate/references/post-ideation-workflow.md +169 -0
  217. package/skills/ce-ideate/references/scope-gates.md +148 -0
  218. package/skills/ce-ideate/references/universal-ideation.md +119 -0
  219. package/skills/ce-ideate/references/user-research-artifacts.md +28 -0
  220. package/skills/ce-ideate/references/web-research-cache.md +56 -0
  221. package/skills/ce-noslop/SKILL.md +45 -0
  222. package/skills/ce-noslop/references/patterns.md +61 -0
  223. package/skills/ce-noslop/references/terminology.md +3 -0
  224. package/skills/ce-optimize/SKILL.md +64 -0
  225. package/skills/ce-optimize/references/agents/learnings-researcher.md +247 -0
  226. package/skills/ce-optimize/references/agents/repo-research-analyst.md +258 -0
  227. package/skills/ce-optimize/references/example-expensive-benchmark-spec.yaml +88 -0
  228. package/skills/ce-optimize/references/example-hard-spec.yaml +64 -0
  229. package/skills/ce-optimize/references/example-judge-spec.yaml +83 -0
  230. package/skills/ce-optimize/references/example-text-target-spec.yaml +80 -0
  231. package/skills/ce-optimize/references/experiment-log-schema.yaml +563 -0
  232. package/skills/ce-optimize/references/experiment-prompt-template.md +143 -0
  233. package/skills/ce-optimize/references/judge-prompt-template.md +117 -0
  234. package/skills/ce-optimize/references/loop.md +286 -0
  235. package/skills/ce-optimize/references/measurement.md +168 -0
  236. package/skills/ce-optimize/references/optimize-spec-schema.yaml +570 -0
  237. package/skills/ce-optimize/references/persistence.md +93 -0
  238. package/skills/ce-optimize/references/spec.md +107 -0
  239. package/skills/ce-optimize/references/text-targets.md +51 -0
  240. package/skills/ce-optimize/references/usage-guide.md +147 -0
  241. package/skills/ce-optimize/references/wrap-up.md +54 -0
  242. package/skills/ce-optimize/scripts/decide.mjs +676 -0
  243. package/skills/ce-optimize/scripts/experiment-worktree.sh +330 -0
  244. package/skills/ce-optimize/scripts/measure.sh +140 -0
  245. package/skills/ce-optimize/scripts/parallel-probe.sh +134 -0
  246. package/skills/ce-plan/SKILL.md +60 -0
  247. package/skills/ce-plan/references/agents/agent-native-planning-strategist.md +66 -0
  248. package/skills/ce-plan/references/agents/architecture-strategist.md +46 -0
  249. package/skills/ce-plan/references/agents/best-practices-researcher.md +118 -0
  250. package/skills/ce-plan/references/agents/data-integrity-guardian.md +68 -0
  251. package/skills/ce-plan/references/agents/framework-docs-researcher.md +97 -0
  252. package/skills/ce-plan/references/agents/git-history-analyzer.md +40 -0
  253. package/skills/ce-plan/references/agents/learnings-researcher.md +268 -0
  254. package/skills/ce-plan/references/agents/pattern-recognition-specialist.md +55 -0
  255. package/skills/ce-plan/references/agents/performance-oracle.md +108 -0
  256. package/skills/ce-plan/references/agents/repo-research-analyst.md +262 -0
  257. package/skills/ce-plan/references/agents/security-sentinel.md +91 -0
  258. package/skills/ce-plan/references/agents/slack-researcher.md +131 -0
  259. package/skills/ce-plan/references/agents/spec-flow-analyzer.md +84 -0
  260. package/skills/ce-plan/references/agents/web-researcher.md +125 -0
  261. package/skills/ce-plan/references/approach-altitude.md +55 -0
  262. package/skills/ce-plan/references/bakeoff.md +9 -0
  263. package/skills/ce-plan/references/deepening-workflow.md +263 -0
  264. package/skills/ce-plan/references/final-review.md +134 -0
  265. package/skills/ce-plan/references/html-rendering.md +638 -0
  266. package/skills/ce-plan/references/intake.md +158 -0
  267. package/skills/ce-plan/references/markdown-rendering.md +242 -0
  268. package/skills/ce-plan/references/output-contracts.md +29 -0
  269. package/skills/ce-plan/references/output-mode.md +45 -0
  270. package/skills/ce-plan/references/plan-handoff.md +116 -0
  271. package/skills/ce-plan/references/plan-sections.md +489 -0
  272. package/skills/ce-plan/references/reasoning-elevation.md +124 -0
  273. package/skills/ce-plan/references/research.md +211 -0
  274. package/skills/ce-plan/references/resume.md +61 -0
  275. package/skills/ce-plan/references/settled-decisions.md +45 -0
  276. package/skills/ce-plan/references/structure.md +207 -0
  277. package/skills/ce-plan/references/synthesis-summary.md +260 -0
  278. package/skills/ce-plan/references/universal-planning.md +170 -0
  279. package/skills/ce-plan/scripts/elevation-dispatch.sh +288 -0
  280. package/skills/ce-plan/scripts/packs-resolve.py +737 -0
  281. package/skills/ce-plan/scripts/peer-job-runner.py +2594 -0
  282. package/skills/ce-polish/SKILL.md +22 -0
  283. package/skills/ce-polish/agents/openai.yaml +2 -0
  284. package/skills/ce-polish/references/dev-server-astro.md +58 -0
  285. package/skills/ce-polish/references/dev-server-detection.md +40 -0
  286. package/skills/ce-polish/references/dev-server-next.md +61 -0
  287. package/skills/ce-polish/references/dev-server-nuxt.md +58 -0
  288. package/skills/ce-polish/references/dev-server-procfile.md +59 -0
  289. package/skills/ce-polish/references/dev-server-rails.md +50 -0
  290. package/skills/ce-polish/references/dev-server-remix.md +58 -0
  291. package/skills/ce-polish/references/dev-server-sveltekit.md +58 -0
  292. package/skills/ce-polish/references/dev-server-vite.md +48 -0
  293. package/skills/ce-polish/references/install-riffrec.md +35 -0
  294. package/skills/ce-polish/references/launch-json-schema.md +177 -0
  295. package/skills/ce-polish/references/live-loop.md +98 -0
  296. package/skills/ce-polish/references/live-remote.md +35 -0
  297. package/skills/ce-polish/references/live-start.md +93 -0
  298. package/skills/ce-polish/references/live-stream-contract.md +253 -0
  299. package/skills/ce-polish/references/run.md +67 -0
  300. package/skills/ce-polish/scripts/detect-project-type.sh +277 -0
  301. package/skills/ce-polish/scripts/detect-riffrec.sh +225 -0
  302. package/skills/ce-polish/scripts/live-endpoint.js +2841 -0
  303. package/skills/ce-polish/scripts/read-launch-json.sh +117 -0
  304. package/skills/ce-polish/scripts/resolve-package-manager.sh +95 -0
  305. package/skills/ce-polish/scripts/resolve-port.sh +307 -0
  306. package/skills/ce-pov/SKILL.md +64 -0
  307. package/skills/ce-pov/references/agents/external-evidence-researcher.md +26 -0
  308. package/skills/ce-pov/references/agents/pov-peer.md +43 -0
  309. package/skills/ce-pov/references/agents/precedent-activity-scout.md +21 -0
  310. package/skills/ce-pov/references/agents/project-grounding-scout.md +32 -0
  311. package/skills/ce-pov/references/boundaries.md +36 -0
  312. package/skills/ce-pov/references/cross-model-panel.md +596 -0
  313. package/skills/ce-pov/references/followup.md +9 -0
  314. package/skills/ce-pov/references/grounding.md +47 -0
  315. package/skills/ce-pov/references/intake.md +61 -0
  316. package/skills/ce-pov/references/invocation.md +47 -0
  317. package/skills/ce-pov/references/method.md +68 -0
  318. package/skills/ce-pov/references/pov-schema.json +56 -0
  319. package/skills/ce-pov/references/report.md +7 -0
  320. package/skills/ce-pov/scripts/cross-model-pov.sh +1110 -0
  321. package/skills/ce-pov/scripts/peer-job-runner.py +2594 -0
  322. package/skills/ce-product-pulse/SKILL.md +81 -0
  323. package/skills/ce-product-pulse/agents/openai.yaml +2 -0
  324. package/skills/ce-product-pulse/references/config.md +20 -0
  325. package/skills/ce-product-pulse/references/interview.md +260 -0
  326. package/skills/ce-product-pulse/references/report-template.md +89 -0
  327. package/skills/ce-product-pulse/references/run.md +46 -0
  328. package/skills/ce-product-pulse/references/setup.md +43 -0
  329. package/skills/ce-promote/SKILL.md +90 -0
  330. package/skills/ce-promote/agents/openai.yaml +2 -0
  331. package/skills/ce-promote/references/spiral-cli.md +149 -0
  332. package/skills/ce-proof/SKILL.md +65 -0
  333. package/skills/ce-proof/references/api.md +176 -0
  334. package/skills/ce-proof/references/workflows.md +124 -0
  335. package/skills/ce-prototype/SKILL.md +59 -0
  336. package/skills/ce-prototype/assets/annotate.css +206 -0
  337. package/skills/ce-prototype/assets/annotate.js +837 -0
  338. package/skills/ce-prototype/references/annotation-loop.md +32 -0
  339. package/skills/ce-prototype/references/build.md +39 -0
  340. package/skills/ce-prototype/references/craft-floor.md +43 -0
  341. package/skills/ce-prototype/references/preview.md +118 -0
  342. package/skills/ce-prototype/references/scoping.md +38 -0
  343. package/skills/ce-prototype/references/write-back.md +37 -0
  344. package/skills/ce-prototype/scripts/light-webserver.js +1275 -0
  345. package/skills/ce-resolve-pr-feedback/SKILL.md +60 -0
  346. package/skills/ce-resolve-pr-feedback/references/agents/pr-comment-resolver.md +59 -0
  347. package/skills/ce-resolve-pr-feedback/references/evaluation-rubric.md +141 -0
  348. package/skills/ce-resolve-pr-feedback/references/full-mode.md +336 -0
  349. package/skills/ce-resolve-pr-feedback/references/pipeline-mode.md +23 -0
  350. package/skills/ce-resolve-pr-feedback/references/resume.md +60 -0
  351. package/skills/ce-resolve-pr-feedback/references/return-to-caller.md +111 -0
  352. package/skills/ce-resolve-pr-feedback/references/targeted-mode.md +48 -0
  353. package/skills/ce-resolve-pr-feedback/scripts/get-pr-comments +176 -0
  354. package/skills/ce-resolve-pr-feedback/scripts/get-thread-for-comment +84 -0
  355. package/skills/ce-resolve-pr-feedback/scripts/pending-feedback.py +287 -0
  356. package/skills/ce-resolve-pr-feedback/scripts/reply-to-pr-thread +57 -0
  357. package/skills/ce-resolve-pr-feedback/scripts/resolve-pr-thread +23 -0
  358. package/skills/ce-retune/SKILL.md +42 -0
  359. package/skills/ce-retune/agents/openai.yaml +2 -0
  360. package/skills/ce-retune/references/baseline-mining.md +122 -0
  361. package/skills/ce-retune/references/corpus-audit.md +128 -0
  362. package/skills/ce-retune/references/cut-passes.md +129 -0
  363. package/skills/ce-retune/references/halt-taxonomy.md +123 -0
  364. package/skills/ce-retune/references/noise-floor.md +131 -0
  365. package/skills/ce-retune/references/workflow-shapes.md +73 -0
  366. package/skills/ce-riffrec-feedback-analysis/SKILL.md +33 -0
  367. package/skills/ce-riffrec-feedback-analysis/references/analyzer.md +18 -0
  368. package/skills/ce-riffrec-feedback-analysis/references/compound-engineering-feedback-format.md +116 -0
  369. package/skills/ce-riffrec-feedback-analysis/references/extensive-analysis.md +98 -0
  370. package/skills/ce-riffrec-feedback-analysis/references/install-riffrec.md +27 -0
  371. package/skills/ce-riffrec-feedback-analysis/references/quick-bug-report.md +38 -0
  372. package/skills/ce-riffrec-feedback-analysis/scripts/analyze_riffrec_zip.py +1306 -0
  373. package/skills/ce-setup/SKILL.md +103 -0
  374. package/skills/ce-setup/agents/openai.yaml +2 -0
  375. package/skills/ce-setup/assets/compounding-directive.md +11 -0
  376. package/skills/ce-setup/assets/noslop-directive.md +7 -0
  377. package/skills/ce-setup/assets/pack-rule-template.md +11 -0
  378. package/skills/ce-setup/references/acpx-cache-warm.md +14 -0
  379. package/skills/ce-setup/references/config-template.yaml +210 -0
  380. package/skills/ce-setup/references/legacy-codex-tool-map.md +15 -0
  381. package/skills/ce-setup/references/pack-scaffold.md +45 -0
  382. package/skills/ce-setup/references/repo-fixes.md +121 -0
  383. package/skills/ce-setup/scripts/check-health +929 -0
  384. package/skills/ce-setup/scripts/packs-resolve.py +737 -0
  385. package/skills/ce-simplify-code/SKILL.md +76 -0
  386. package/skills/ce-simplify-code/references/personas/code-quality-reviewer.md +17 -0
  387. package/skills/ce-simplify-code/references/personas/code-reuse-reviewer.md +7 -0
  388. package/skills/ce-simplify-code/references/personas/comment-reviewer.md +24 -0
  389. package/skills/ce-simplify-code/references/personas/efficiency-reviewer.md +11 -0
  390. package/skills/ce-simplify-code/references/personas/test-value-reviewer.md +23 -0
  391. package/skills/ce-simplify-code/references/reviewer-dispatch.md +11 -0
  392. package/skills/ce-simplify-code/references/standalone-report.md +25 -0
  393. package/skills/ce-strategy/SKILL.md +61 -0
  394. package/skills/ce-strategy/references/grounding.md +22 -0
  395. package/skills/ce-strategy/references/interview.md +179 -0
  396. package/skills/ce-strategy/references/strategy-template.md +94 -0
  397. package/skills/ce-strategy/references/update-run.md +33 -0
  398. package/skills/ce-sweep/SKILL.md +93 -0
  399. package/skills/ce-sweep/agents/openai.yaml +2 -0
  400. package/skills/ce-sweep/references/agents/media-analyzer.md +54 -0
  401. package/skills/ce-sweep/references/interview.md +208 -0
  402. package/skills/ce-sweep/references/model-tiers.md +13 -0
  403. package/skills/ce-sweep/references/plan-template.md +62 -0
  404. package/skills/ce-sweep/references/run.md +126 -0
  405. package/skills/ce-sweep/references/sources/email.md +57 -0
  406. package/skills/ce-sweep/references/sources/github-issues.md +59 -0
  407. package/skills/ce-sweep/references/sources/slack.md +61 -0
  408. package/skills/ce-sweep/references/state-schema.md +157 -0
  409. package/skills/ce-sweep/references/subagent-template.md +60 -0
  410. package/skills/ce-sweep/scripts/analyze_riffrec_zip.py +1306 -0
  411. package/skills/ce-sweep/scripts/sweep-state.py +793 -0
  412. package/skills/ce-test-browser/SKILL.md +50 -0
  413. package/skills/ce-test-browser/references/agent-browser-driver.md +47 -0
  414. package/skills/ce-test-browser/references/pipeline-orchestration.md +45 -0
  415. package/skills/ce-test-browser/references/route-and-report.md +129 -0
  416. package/skills/ce-test-browser/scripts/resolve-port.sh +41 -0
  417. package/skills/ce-test-xcode/SKILL.md +26 -0
  418. package/skills/ce-test-xcode/agents/openai.yaml +2 -0
  419. package/skills/ce-test-xcode/references/setup-and-build.md +32 -0
  420. package/skills/ce-test-xcode/references/test-and-report.md +64 -0
  421. package/skills/ce-work/SKILL.md +62 -0
  422. package/skills/ce-work/references/agents/figma-design-sync.md +27 -0
  423. package/skills/ce-work/references/agents/implementation-worker.md +17 -0
  424. package/skills/ce-work/references/cross-model-execution.md +191 -0
  425. package/skills/ce-work/references/execution-engines.md +64 -0
  426. package/skills/ce-work/references/execution-strategy.md +73 -0
  427. package/skills/ce-work/references/implementation-loop.md +107 -0
  428. package/skills/ce-work/references/implementation-result-schema.json +52 -0
  429. package/skills/ce-work/references/input-triage.md +50 -0
  430. package/skills/ce-work/references/non-code-execution.md +23 -0
  431. package/skills/ce-work/references/return-to-caller.md +33 -0
  432. package/skills/ce-work/references/review-findings-followup.md +82 -0
  433. package/skills/ce-work/references/shipping-workflow.md +89 -0
  434. package/skills/ce-work/references/tracker-defer.md +150 -0
  435. package/skills/ce-work/references/work-intake.md +51 -0
  436. package/skills/ce-work/references/workspace-setup.md +27 -0
  437. package/skills/ce-work/scripts/__pycache__/unit_workspace_jobs.cpython-314.pyc +0 -0
  438. package/skills/ce-work/scripts/__pycache__/unit_workspace_state.cpython-314.pyc +0 -0
  439. package/skills/ce-work/scripts/cross-model-work.sh +1385 -0
  440. package/skills/ce-work/scripts/peer-job-runner.py +2594 -0
  441. package/skills/ce-work/scripts/unit-workspace.py +215 -0
  442. package/skills/ce-work/scripts/unit_workspace_ignored.py +93 -0
  443. package/skills/ce-work/scripts/unit_workspace_integration.py +677 -0
  444. package/skills/ce-work/scripts/unit_workspace_jobs.py +1216 -0
  445. package/skills/ce-work/scripts/unit_workspace_lifecycle.py +981 -0
  446. package/skills/ce-work/scripts/unit_workspace_state.py +1379 -0
  447. package/skills/ce-work/scripts/unit_workspace_transaction.py +612 -0
  448. package/skills/ce-worktree/SKILL.md +54 -0
  449. package/skills/lfg/SKILL.md +59 -0
  450. package/skills/lfg/references/debug-return.md +25 -0
  451. package/skills/lfg/references/intake.md +30 -0
  452. package/skills/lfg/references/next-work-handoff.md +96 -0
  453. package/skills/lfg/references/plan-brief.md +36 -0
  454. package/skills/lfg/references/review-followup.md +78 -0
  455. package/skills/lfg/references/shipping.md +65 -0
  456. package/skills/lfg/references/stage-routing.md +49 -0
  457. package/skills/lfg/references/task-visibility.md +11 -0
  458. package/skills/lfg/references/tracker-defer.md +150 -0
  459. package/skills/lfg/references/work-return.md +27 -0
  460. package/skills/wtf/SKILL.md +33 -0
  461. package/skills/wtf/agents/openai.yaml +2 -0
@@ -0,0 +1,1216 @@
1
+ """Unit preparation, runner evidence, and complete-tree transport lifecycle."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import json
7
+ import os
8
+ import re
9
+ import stat
10
+
11
+ from unit_workspace_state import *
12
+
13
+
14
+ def _valid_retry_commit_id(value: object) -> bool:
15
+ return isinstance(value, str) and re.fullmatch(r"(?:[0-9a-f]{40}|[0-9a-f]{64})", value) is not None
16
+
17
+
18
+ def _validate_retry_base(doc: dict, unit: dict, requested_base: str) -> None:
19
+ wave = unit.get("wave", {})
20
+ original_base = wave.get("base")
21
+ allowed_heads = wave.get("allowed_heads", [])
22
+ if not _valid_retry_commit_id(original_base):
23
+ raise TrustFailure("recorded retry base is malformed")
24
+ if not isinstance(allowed_heads, list) or any(not _valid_retry_commit_id(head) for head in allowed_heads):
25
+ raise TrustFailure("recorded retry HEAD allowances are malformed")
26
+
27
+ accepted_heads = {
28
+ commit
29
+ for candidate in doc.get("units", {}).values()
30
+ if (commit := unit_accepted_commit(candidate)) is not None
31
+ }
32
+ latest_allowed = allowed_heads[-1] if allowed_heads else original_base
33
+ if requested_base != original_base and requested_base not in accepted_heads:
34
+ raise Operational(
35
+ "BLOCKED",
36
+ "retry base is not a controller-accepted canonical head",
37
+ {"requested_base": requested_base, "latest_allowed_head": latest_allowed},
38
+ )
39
+ repo = doc["repository"]["toplevel"]
40
+ required = accepted_heads | {original_base, *allowed_heads}
41
+ missing = sorted(
42
+ commit for commit in required
43
+ if git_text(repo, "merge-base", commit, requested_base, check=False) != commit
44
+ )
45
+ if missing:
46
+ raise Operational(
47
+ "BLOCKED",
48
+ "retry base omits controller-accepted canonical history",
49
+ {
50
+ "requested_base": requested_base,
51
+ "latest_allowed_head": latest_allowed,
52
+ "missing_ancestry": missing,
53
+ },
54
+ )
55
+
56
+
57
+ def _record_retry_base(doc: dict, unit: dict, requested_base: str) -> None:
58
+ wave = unit["wave"]
59
+ position = wave.get("position")
60
+ if not isinstance(position, int):
61
+ raise TrustFailure("recorded retry wave position is malformed")
62
+ targets = [unit]
63
+ if wave.get("id"):
64
+ for candidate in doc.get("units", {}).values():
65
+ candidate_wave = candidate.get("wave", {})
66
+ if candidate is unit or candidate_wave.get("id") != wave["id"]:
67
+ continue
68
+ candidate_position = candidate_wave.get("position")
69
+ if not isinstance(candidate_position, int):
70
+ raise TrustFailure("recorded wave position is malformed")
71
+ if candidate_position > position:
72
+ targets.append(candidate)
73
+ for candidate in targets:
74
+ candidate_wave = candidate.get("wave", {})
75
+ if candidate_wave.get("base") != wave.get("base"):
76
+ raise Operational("BLOCKED", "wave members do not share one recorded base")
77
+ allowed_heads = candidate_wave.setdefault("allowed_heads", [])
78
+ if not isinstance(allowed_heads, list) or any(not _valid_retry_commit_id(head) for head in allowed_heads):
79
+ raise TrustFailure("recorded retry HEAD allowances are malformed")
80
+ if requested_base not in allowed_heads:
81
+ allowed_heads.append(requested_base)
82
+
83
+
84
+ def cmd_prepare(args) -> tuple[str, dict]:
85
+ uid = safe_id(args.unit_id, "unit id")
86
+ attempt_id = safe_id(args.attempt_id, "attempt id")
87
+ packet_bytes = read_external_packet(args.packet)
88
+ packet_digest = digest_bytes(packet_bytes)
89
+ with locked_manifest(args.run_id) as doc:
90
+ info = validate_repo(doc)
91
+ repo = info["toplevel"]
92
+ base = git_text(repo, "rev-parse", f"{args.base}^{{commit}}")
93
+ if info["head"] != base:
94
+ raise Operational("BLOCKED", "canonical HEAD does not equal requested unit base")
95
+ if status_paths(repo):
96
+ raise Operational("BLOCKED", "canonical checkout is dirty; external workspace unavailable")
97
+ existing = doc["units"].get(uid)
98
+ unit_root = os.path.join(run_dir(args.run_id), "units", uid)
99
+ workspace = os.path.join(unit_root, "workspace")
100
+ packet_path = os.path.join(unit_root, "packet.md")
101
+ authorization_path = os.path.join(unit_root, "authorization.json")
102
+ authorization = attempt_authorization(doc, args.activity_posture, uid, attempt_id, packet_digest)
103
+ authorization_bytes = (json.dumps(authorization, sort_keys=True, separators=(",", ":")) + "\n").encode()
104
+ authorization_digest = digest_bytes(authorization_bytes)
105
+ contract_wave_base = existing.get("wave", {}).get("base") if existing else base
106
+ expected_contract = {
107
+ "dependencies": list(args.dependency),
108
+ "wave": {"id": args.wave_id, "base": contract_wave_base, "position": args.wave_position},
109
+ "packet_digest": packet_digest,
110
+ "attempt_id": attempt_id,
111
+ "authorization": authorization,
112
+ "authorization_path": authorization_path,
113
+ "authorization_digest": authorization_digest,
114
+ }
115
+ retrying = False
116
+ if existing:
117
+ matching_attempts = [attempt for attempt in existing.get("attempts", []) if attempt.get("attempt_id") == attempt_id]
118
+ if not matching_attempts:
119
+ cleanup = existing.get("cleanup")
120
+ if (
121
+ existing.get("state") != "cleaned"
122
+ or not isinstance(cleanup, dict)
123
+ or cleanup.get("abandoned") is not True
124
+ or cleanup.get("artifact_cleanup", {}).get("complete") is not True
125
+ ):
126
+ raise Operational("REFUSED", "a fresh attempt requires an exactly abandoned and fully cleaned prior attempt")
127
+ if doc.get("integration_lock"):
128
+ raise Operational("REFUSED", "release the prior integration lock before preparing a retry")
129
+ if existing.get("dependencies") != list(args.dependency):
130
+ raise Operational("BLOCKED", "retry dependencies differ from the recorded unit")
131
+ prior_wave = existing.get("wave", {})
132
+ if {
133
+ "id": prior_wave.get("id"),
134
+ "position": prior_wave.get("position"),
135
+ } != {"id": args.wave_id, "position": args.wave_position}:
136
+ raise Operational("BLOCKED", "retry wave identity/position differs from the recorded unit")
137
+ _validate_retry_base(doc, existing, base)
138
+ retrying = True
139
+ else:
140
+ attempt = find_attempt(existing, attempt_id)
141
+ if existing and not retrying and (
142
+ existing.get("workspace", {}).get("path") != workspace
143
+ or existing.get("workspace", {}).get("base") != base
144
+ ):
145
+ raise Operational("BLOCKED", "duplicate unit id has a different workspace contract")
146
+ if existing and not retrying:
147
+ if existing.get("state") == "cleaned" or existing.get("cleanup"):
148
+ raise Operational(
149
+ "REFUSED",
150
+ "cleaned unit cannot reuse a recorded attempt id; supply a fresh --attempt-id after exact abandonment cleanup and lock release",
151
+ )
152
+ observed_contract = {
153
+ "dependencies": existing.get("dependencies"),
154
+ "wave": {key: existing.get("wave", {}).get(key) for key in ("id", "base", "position")},
155
+ "packet_digest": existing.get("packet_digest"),
156
+ "attempt_id": attempt.get("attempt_id"),
157
+ "authorization": attempt.get("authorization"),
158
+ "authorization_path": attempt.get("authorization_path"),
159
+ "authorization_digest": attempt.get("authorization_digest"),
160
+ }
161
+ if observed_contract != expected_contract or existing.get("packet", {}).get("path") != packet_path:
162
+ raise Operational("BLOCKED", "resumed prepare contract differs from the recorded unit")
163
+ if read_private(packet_path, MAX_PACKET_BYTES) != packet_bytes:
164
+ raise Operational("BLOCKED", "controller-owned unit packet no longer matches supplied bytes")
165
+ if read_private(authorization_path, MAX_JSON_BYTES) != authorization_bytes:
166
+ raise Operational("BLOCKED", "controller-owned authorization no longer matches the recorded attempt")
167
+ result_fd, _ = open_recorded_result_dir(existing)
168
+ close_dir_handle(result_fd)
169
+ if existing and not retrying and existing["workspace"].get("registered"):
170
+ if existing.get("state") == "queued":
171
+ validate_pristine_unit_base(doc, existing)
172
+ else:
173
+ validate_workspace(doc, existing)
174
+ return "PREPARED", {
175
+ "unit_id": uid, "attempt_id": attempt_id,
176
+ "workspace": workspace, "result_dir": os.path.join(unit_root, "result"),
177
+ "packet_path": packet_path, "packet_digest": packet_digest,
178
+ "authorization_path": authorization_path, "authorization_digest": authorization_digest,
179
+ "adapter": attempt["adapter"],
180
+ "base": base, "resumed": True,
181
+ }
182
+ ensure_private_dir(unit_root)
183
+ result_dir = os.path.join(unit_root, "result")
184
+ ensure_private_dir(result_dir)
185
+ result_dir_identity = private_result_dir_identity(result_dir)
186
+ if os.path.lexists(packet_path):
187
+ if read_private(packet_path, MAX_PACKET_BYTES) != packet_bytes:
188
+ raise Operational("BLOCKED", "controller-owned packet path contains different bytes")
189
+ else:
190
+ create_private(packet_path, packet_bytes)
191
+ if os.path.lexists(authorization_path):
192
+ if read_private(authorization_path, MAX_JSON_BYTES) != authorization_bytes:
193
+ raise Operational("BLOCKED", "controller-owned authorization path contains different bytes")
194
+ else:
195
+ create_private(authorization_path, authorization_bytes)
196
+ attempt_record = {
197
+ "attempt_id": attempt_id,
198
+ "job_id": None,
199
+ "dispatch_authorization_receipt": None,
200
+ "process_state": "never-started",
201
+ "activity": {"posture": args.activity_posture, "latest_at": None},
202
+ "fallback": {"eligible": False, "reason": None, "claimed": None},
203
+ "authorization": authorization,
204
+ "authorization_path": authorization_path,
205
+ "authorization_digest": authorization_digest,
206
+ "authorization_retained": True,
207
+ "adapter": os.path.realpath(os.path.join(os.path.dirname(__file__), "cross-model-work.sh")),
208
+ "terminal_receipt": None,
209
+ }
210
+ if not existing:
211
+ unit = {
212
+ "unit_id": uid,
213
+ "state": "queued",
214
+ "dependencies": list(args.dependency),
215
+ "wave": {"id": args.wave_id, "base": base, "position": args.wave_position, "allowed_heads": [base]},
216
+ "packet_digest": packet_digest,
217
+ "packet": {"path": packet_path, "digest": packet_digest, "bytes": len(packet_bytes), "retained": True},
218
+ "workspace": {"path": workspace, "base": base, "registered": False},
219
+ "result_dir_identity": result_dir_identity,
220
+ "attempts": [attempt_record],
221
+ "transport": {"base": None, "tree": None, "commit": None, "ref": None, "digest": None, "changed_paths": []},
222
+ "integration": {"intent_revision": None, "pre_fold": None, "expected_apply": None, "applied": None, "verification": None, "canonical_commit": None, "restore": None},
223
+ "cleanup": None,
224
+ "recovery_path": unit_root,
225
+ }
226
+ with locked_manifest(args.run_id, write=True) as doc:
227
+ if uid in doc["units"]:
228
+ raise Operational("BLOCKED", "unit was concurrently claimed")
229
+ doc["units"][uid] = unit
230
+ event(doc, "worktree-add-intent", uid, {"path": workspace, "base": base})
231
+ elif retrying:
232
+ with locked_manifest(args.run_id, write=True) as doc:
233
+ unit = doc["units"].get(uid)
234
+ cleanup = unit.get("cleanup") if unit else None
235
+ if (
236
+ not unit
237
+ or unit.get("state") != "cleaned"
238
+ or not isinstance(cleanup, dict)
239
+ or cleanup.get("abandoned") is not True
240
+ or cleanup.get("artifact_cleanup", {}).get("complete") is not True
241
+ or doc.get("integration_lock")
242
+ ):
243
+ raise Operational("BLOCKED", "unit retry eligibility changed while it was being prepared")
244
+ if any(attempt.get("attempt_id") == attempt_id for attempt in unit.get("attempts", [])):
245
+ raise Operational("BLOCKED", "retry attempt id was concurrently claimed")
246
+ info = validate_repo(doc)
247
+ if info["head"] != base:
248
+ raise Operational("BLOCKED", "canonical HEAD changed while retry was being prepared")
249
+ if unit.get("dependencies") != list(args.dependency):
250
+ raise Operational("BLOCKED", "retry dependencies differ from the recorded unit")
251
+ prior_wave = unit.get("wave", {})
252
+ if {
253
+ "id": prior_wave.get("id"),
254
+ "position": prior_wave.get("position"),
255
+ } != {"id": args.wave_id, "position": args.wave_position}:
256
+ raise Operational("BLOCKED", "retry wave identity/position differs from the recorded unit")
257
+ _validate_retry_base(doc, unit, base)
258
+ previous = find_attempt(unit)
259
+ previous["cleanup_receipt"] = dict(cleanup)
260
+ restore = unit.get("integration", {}).get("restore")
261
+ if restore is not None:
262
+ previous["restore_receipt"] = json.loads(json.dumps(restore))
263
+ unit["state"] = "queued"
264
+ unit["packet_digest"] = packet_digest
265
+ unit["packet"] = {"path": packet_path, "digest": packet_digest, "bytes": len(packet_bytes), "retained": True}
266
+ unit["workspace"] = {"path": workspace, "base": base, "registered": False}
267
+ unit["result_dir_identity"] = result_dir_identity
268
+ _record_retry_base(doc, unit, base)
269
+ unit["attempts"].append(attempt_record)
270
+ unit["transport"] = {"base": None, "tree": None, "commit": None, "ref": None, "digest": None, "changed_paths": []}
271
+ unit["integration"] = {"intent_revision": None, "pre_fold": None, "expected_apply": None, "applied": None, "verification": None, "canonical_commit": None, "restore": None}
272
+ unit["cleanup"] = None
273
+ unit["recovery_path"] = unit_root
274
+ event(doc, "unit-retry-prepared", uid, {"attempt_id": attempt_id, "base": base})
275
+ event(doc, "worktree-add-intent", uid, {"path": workspace, "base": base})
276
+ with locked_manifest(args.run_id) as doc:
277
+ common = doc["repository"]["common_dir"]
278
+ repo = doc["repository"]["toplevel"]
279
+ with admin_lock(common):
280
+ if not os.path.exists(workspace):
281
+ git(repo, "worktree", "add", "--detach", workspace, base)
282
+ test_fault("after-worktree-add")
283
+ with locked_manifest(args.run_id) as doc:
284
+ unit = doc["units"][uid]
285
+ validate_pristine_unit_base(doc, unit)
286
+ with locked_manifest(args.run_id, write=True) as doc:
287
+ unit = doc["units"][uid]
288
+ unit["workspace"]["registered"] = True
289
+ event(doc, "worktree-prepared", uid, {"path": workspace, "base": base})
290
+ return "PREPARED", {
291
+ "unit_id": uid, "attempt_id": attempt_id,
292
+ "workspace": workspace, "result_dir": os.path.join(unit_root, "result"),
293
+ "packet_path": packet_path, "packet_digest": packet_digest,
294
+ "authorization_path": authorization_path, "authorization_digest": authorization_digest,
295
+ "adapter": attempt_record["adapter"],
296
+ "base": base, "resumed": False,
297
+ }
298
+
299
+
300
+ def runner_job_dir(run_id: str, job_id: str) -> str:
301
+ return os.path.join(run_dir(run_id), "jobs", safe_id(job_id, "job id"))
302
+
303
+
304
+ def process_evidence(job_dir: str) -> dict:
305
+ validate_private_dir(job_dir)
306
+ status_path = os.path.join(job_dir, "status")
307
+ if os.path.lexists(status_path):
308
+ word = read_private(status_path, 256).decode("ascii", "strict").strip()
309
+ if word not in TERMINAL_PROCESS:
310
+ raise TrustFailure("runner terminal state is invalid")
311
+ elif os.path.lexists(os.path.join(job_dir, "pid")):
312
+ read_private_json(os.path.join(job_dir, "pid"))
313
+ word = "running"
314
+ else:
315
+ word = "never-started"
316
+ failure_reason = None
317
+ reason_path = os.path.join(job_dir, "reason")
318
+ if word in TERMINAL_PROCESS and os.path.lexists(reason_path):
319
+ failure_reason = read_private(reason_path, 4096).decode("utf-8", "strict").strip() or None
320
+ activity = {"latest_at": None, "log_bytes": 0}
321
+ log = os.path.join(job_dir, "out.log")
322
+ if os.path.lexists(log):
323
+ st = stat_private_file(log)
324
+ activity = {"latest_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(st.st_mtime)), "log_bytes": st.st_size}
325
+ return {"process_state": word, "failure_reason": failure_reason, "activity": activity}
326
+
327
+
328
+ HOST_RECEIPT_FIELDS = (
329
+ "requested_route", "actual_route", "target", "harness", "intermediaries",
330
+ "model_requested", "model_actual", "model_receipt_status", "effort_requested", "activity_posture",
331
+ "restriction_posture", "failure_reason", "raw_log", "packet_digest",
332
+ )
333
+ MAX_RESULT_BYTES = 5 * 1024 * 1024
334
+ MAX_REPORTED_CHANGED_FILES = 1000
335
+
336
+
337
+ def _validate_private_dir_fd(fd: int, path: str) -> os.stat_result:
338
+ st = os.fstat(fd)
339
+ effective_uid = os.geteuid() if hasattr(os, "geteuid") else None
340
+ if not stat.S_ISDIR(st.st_mode):
341
+ raise TrustFailure(f"not a real directory: {path}")
342
+ if effective_uid is not None and st.st_uid != effective_uid:
343
+ raise TrustFailure(f"directory is not owned by current user: {path}")
344
+ mode = stat.S_IMODE(st.st_mode)
345
+ if mode != 0o700:
346
+ raise TrustFailure(f"directory mode is {mode:04o}, expected 0700: {path}")
347
+ return st
348
+
349
+
350
+ def _validate_private_dir_path(path: str) -> os.stat_result:
351
+ """Windows substitute for :func:`_validate_private_dir_fd`.
352
+
353
+ Windows cannot ``os.open()`` a directory, so there is no fd to ``fstat`` and
354
+ the POSIX mode bit is synthetic (a 0o700 mkdir always reports 0o777). The
355
+ privacy guarantee there comes from the hardened ACL, so ownership by the
356
+ current user SID is the check that actually carries weight.
357
+ """
358
+ try:
359
+ st = os.lstat(path)
360
+ except OSError as exc:
361
+ raise TrustFailure(f"cannot safely open result directory {path}: {exc}") from exc
362
+ if not stat.S_ISDIR(st.st_mode):
363
+ raise TrustFailure(f"not a real directory: {path}")
364
+ if not win_owns_path(path):
365
+ raise TrustFailure(f"directory is not owned by current user: {path}")
366
+ return st
367
+
368
+
369
+ def close_dir_handle(handle: "int | str") -> None:
370
+ """Release a directory handle from :func:`open_recorded_result_dir`.
371
+
372
+ POSIX hands back a real fd; Windows hands back the directory path because
373
+ directory descriptors do not exist there.
374
+ """
375
+ if isinstance(handle, int):
376
+ os.close(handle)
377
+
378
+
379
+ def private_result_dir_identity(path: str) -> dict:
380
+ if IS_WINDOWS:
381
+ st = _validate_private_dir_path(path)
382
+ return {"dev": st.st_dev, "ino": st.st_ino}
383
+ try:
384
+ fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY | O_NOFOLLOW)
385
+ except OSError as exc:
386
+ raise TrustFailure(f"cannot safely open result directory {path}: {exc}") from exc
387
+ try:
388
+ st = _validate_private_dir_fd(fd, path)
389
+ return {"dev": st.st_dev, "ino": st.st_ino}
390
+ finally:
391
+ os.close(fd)
392
+
393
+
394
+ def open_recorded_result_dir(unit: dict) -> tuple["int | str", str]:
395
+ result_dir = os.path.join(os.path.dirname(unit["workspace"]["path"]), "result")
396
+ identity = unit.get("result_dir_identity")
397
+ if (
398
+ not isinstance(identity, dict)
399
+ or set(identity) != {"dev", "ino"}
400
+ or any(not isinstance(identity.get(key), int) or isinstance(identity.get(key), bool) for key in ("dev", "ino"))
401
+ ):
402
+ raise TrustFailure("unit has no valid controller-recorded result directory identity")
403
+ if IS_WINDOWS:
404
+ st = _validate_private_dir_path(result_dir)
405
+ if (st.st_dev, st.st_ino) != (identity["dev"], identity["ino"]):
406
+ raise TrustFailure("controller result directory identity changed")
407
+ return result_dir, result_dir
408
+ try:
409
+ fd = os.open(result_dir, os.O_RDONLY | os.O_DIRECTORY | O_NOFOLLOW)
410
+ except OSError as exc:
411
+ raise TrustFailure(f"cannot safely open result directory {result_dir}: {exc}") from exc
412
+ try:
413
+ st = _validate_private_dir_fd(fd, result_dir)
414
+ if (st.st_dev, st.st_ino) != (identity["dev"], identity["ino"]):
415
+ raise TrustFailure("controller result directory identity changed")
416
+ return fd, result_dir
417
+ except Exception:
418
+ os.close(fd)
419
+ raise
420
+
421
+
422
+ def _open_in_dir(dir_handle: "int | str", name: str) -> int:
423
+ """Open ``name`` inside a directory handle, refusing symlink swaps.
424
+
425
+ POSIX uses ``dir_fd`` so the lookup cannot be redirected between the
426
+ directory check and the file open. Windows has no ``dir_fd``, so the path is
427
+ joined up front and ownership is re-verified on the resulting handle.
428
+ """
429
+ if IS_WINDOWS:
430
+ return os.open(os.path.join(dir_handle, name), os.O_RDONLY | O_NOFOLLOW | O_BINARY)
431
+ return os.open(name, os.O_RDONLY | O_NOFOLLOW, dir_fd=dir_handle)
432
+
433
+
434
+ def read_private_at(dir_handle: "int | str", name: str, cap: int, display_path: str) -> bytes:
435
+ if os.path.basename(name) != name or name in {"", ".", ".."}:
436
+ raise TrustFailure(f"unsafe state file name: {name!r}")
437
+ try:
438
+ fd = _open_in_dir(dir_handle, name)
439
+ except OSError as exc:
440
+ raise TrustFailure(f"cannot safely open state file {display_path}: {exc}") from exc
441
+ try:
442
+ st = os.fstat(fd)
443
+ effective_uid = os.geteuid() if hasattr(os, "geteuid") else None
444
+ if not stat.S_ISREG(st.st_mode):
445
+ raise TrustFailure(f"state is not a regular file: {display_path}")
446
+ if IS_WINDOWS:
447
+ if not win_owns_handle(msvcrt.get_osfhandle(fd)):
448
+ raise TrustFailure(f"state is not owned by current user: {display_path}")
449
+ elif effective_uid is not None and st.st_uid != effective_uid:
450
+ raise TrustFailure(f"state is not owned by current user: {display_path}")
451
+ mode = stat.S_IMODE(st.st_mode)
452
+ if not is_private(st, want_dir=False):
453
+ raise TrustFailure(f"state mode is {mode:04o}, expected 0600: {display_path}")
454
+ if st.st_size > cap:
455
+ raise TrustFailure(f"state exceeds {cap}-byte limit: {display_path}")
456
+ out = bytearray()
457
+ while len(out) <= cap:
458
+ part = os.read(fd, min(65536, cap + 1 - len(out)))
459
+ if not part:
460
+ break
461
+ out.extend(part)
462
+ if len(out) > cap:
463
+ raise TrustFailure(f"state grew beyond {cap}-byte limit: {display_path}")
464
+ return bytes(out)
465
+ finally:
466
+ os.close(fd)
467
+
468
+
469
+ def stat_private_at(
470
+ dir_handle: "int | str",
471
+ name: str,
472
+ display_path: str,
473
+ *,
474
+ missing_ok: bool = False,
475
+ ) -> os.stat_result | None:
476
+ if os.path.basename(name) != name or name in {"", ".", ".."}:
477
+ raise TrustFailure(f"unsafe state file name: {name!r}")
478
+ try:
479
+ fd = _open_in_dir(dir_handle, name)
480
+ except FileNotFoundError:
481
+ if missing_ok:
482
+ return None
483
+ raise TrustFailure(f"cannot safely open state file {display_path}: file is missing")
484
+ except OSError as exc:
485
+ raise TrustFailure(f"cannot safely open state file {display_path}: {exc}") from exc
486
+ try:
487
+ st = os.fstat(fd)
488
+ effective_uid = os.geteuid() if hasattr(os, "geteuid") else None
489
+ if not stat.S_ISREG(st.st_mode):
490
+ raise TrustFailure(f"state is not a regular file: {display_path}")
491
+ if IS_WINDOWS:
492
+ if not win_owns_handle(msvcrt.get_osfhandle(fd)):
493
+ raise TrustFailure(f"state is not owned by current user: {display_path}")
494
+ elif effective_uid is not None and st.st_uid != effective_uid:
495
+ raise TrustFailure(f"state is not owned by current user: {display_path}")
496
+ mode = stat.S_IMODE(st.st_mode)
497
+ if not is_private(st, want_dir=False):
498
+ raise TrustFailure(f"state mode is {mode:04o}, expected 0600: {display_path}")
499
+ return st
500
+ finally:
501
+ os.close(fd)
502
+
503
+
504
+ def read_recorded_result_file(unit: dict, name: str, cap: int) -> bytes:
505
+ result_fd, result_dir = open_recorded_result_dir(unit)
506
+ try:
507
+ return read_private_at(
508
+ result_fd,
509
+ name,
510
+ cap,
511
+ os.path.join(result_dir, name),
512
+ )
513
+ finally:
514
+ close_dir_handle(result_fd)
515
+
516
+
517
+ def read_recorded_result_json(unit: dict) -> tuple[dict, bytes]:
518
+ result_path = os.path.join(os.path.dirname(unit["workspace"]["path"]), "result", "implementation-result.json")
519
+ raw = read_recorded_result_file(unit, "implementation-result.json", MAX_RESULT_BYTES)
520
+ try:
521
+ value = json.loads(raw)
522
+ except (ValueError, UnicodeDecodeError) as exc:
523
+ raise TrustFailure(f"malformed JSON state: {result_path}") from exc
524
+ if not isinstance(value, dict):
525
+ raise TrustFailure(f"JSON state is not an object: {result_path}")
526
+ return value, raw
527
+
528
+
529
+ def terminal_receipt(
530
+ unit: dict,
531
+ attempt: dict,
532
+ *,
533
+ unavailable: bool = False,
534
+ launched_failure: bool = False,
535
+ ) -> dict:
536
+ result_dir = os.path.join(os.path.dirname(unit["workspace"]["path"]), "result")
537
+ receipt, result_bytes = read_recorded_result_json(unit)
538
+ authorization = attempt.get("authorization")
539
+ if not isinstance(authorization, dict):
540
+ raise Operational("BLOCKED", "attempt has no controller-issued route authorization")
541
+ expected = {
542
+ "requested_route": authorization["route"],
543
+ "actual_route": None if unavailable else authorization["route"],
544
+ "target": authorization["target"],
545
+ "harness": authorization["harness"],
546
+ "intermediaries": authorization["intermediaries"],
547
+ "model_requested": authorization["model_requested"],
548
+ "effort_requested": authorization.get("effort_requested"),
549
+ "restriction_posture": authorization["restriction_posture"],
550
+ "packet_digest": unit["packet_digest"],
551
+ }
552
+ if unavailable or launched_failure:
553
+ expected["activity_posture"] = authorization["activity_posture"]
554
+ mismatches = {key: {"expected": value, "actual": receipt.get(key)} for key, value in expected.items() if receipt.get(key) != value}
555
+ if mismatches:
556
+ raise Operational("BLOCKED", "adapter terminal receipt does not match controller authorization", {"mismatches": mismatches})
557
+ terminal_status = receipt.get("terminal_status")
558
+ if unavailable:
559
+ neutral = {
560
+ "schema_version": 1,
561
+ "terminal_status": "unavailable",
562
+ "summary": "External route unavailable",
563
+ "changed_files": [],
564
+ "evidence": [],
565
+ "scope_expansion": None,
566
+ "model_actual": "unverified",
567
+ "model_receipt_status": "unverified",
568
+ }
569
+ invalid = {key: {"expected": value, "actual": receipt.get(key)} for key, value in neutral.items() if receipt.get(key) != value}
570
+ failure_reason = receipt.get("failure_reason")
571
+ if invalid or not isinstance(failure_reason, str) or not failure_reason or len(failure_reason.encode()) > 4096:
572
+ raise Operational(
573
+ "BLOCKED",
574
+ "failed runner did not publish a bounded neutral unavailable receipt",
575
+ {"mismatches": invalid},
576
+ )
577
+ elif launched_failure:
578
+ neutral = {
579
+ "schema_version": 1,
580
+ "terminal_status": "failed",
581
+ "changed_files": [],
582
+ "evidence": [],
583
+ "scope_expansion": None,
584
+ }
585
+ invalid = {key: {"expected": value, "actual": receipt.get(key)} for key, value in neutral.items() if receipt.get(key) != value}
586
+ failure_reason = receipt.get("failure_reason")
587
+ summary = receipt.get("summary")
588
+ if (
589
+ invalid
590
+ or not isinstance(failure_reason, str)
591
+ or not failure_reason
592
+ or len(failure_reason.encode()) > 4096
593
+ or not isinstance(summary, str)
594
+ or not summary
595
+ or len(summary.encode()) > 4096
596
+ ):
597
+ raise Operational(
598
+ "BLOCKED",
599
+ "failed runner did not publish a bounded neutral launched-route receipt",
600
+ {"mismatches": invalid},
601
+ )
602
+ else:
603
+ if terminal_status not in {"completed", "blocked", "scope_expansion"}:
604
+ raise Operational("BLOCKED", "successful runner did not publish a host-resolvable adapter result")
605
+ if terminal_status == "scope_expansion" and not isinstance(receipt.get("scope_expansion"), dict):
606
+ raise Operational("BLOCKED", "scope-expansion adapter result has no expansion receipt")
607
+ changed_files = receipt.get("changed_files")
608
+ if (
609
+ not isinstance(changed_files, list)
610
+ or len(changed_files) > MAX_REPORTED_CHANGED_FILES
611
+ or any(not isinstance(path, str) or not path for path in changed_files)
612
+ ):
613
+ raise Operational("BLOCKED", "adapter terminal receipt has invalid changed-files evidence")
614
+ raw_log = receipt.get("raw_log")
615
+ expected_log = os.path.join(result_dir, "adapter.log")
616
+ if not isinstance(raw_log, str) or os.path.abspath(raw_log) != expected_log:
617
+ raise Operational("BLOCKED", "adapter raw-log receipt escaped the controller result directory")
618
+ log_bytes = read_recorded_result_file(unit, "adapter.log", 10 * 1024 * 1024)
619
+ return {key: receipt.get(key) for key in HOST_RECEIPT_FIELDS} | {
620
+ "terminal_status": receipt["terminal_status"],
621
+ "summary": str(receipt.get("summary", ""))[:4096],
622
+ "changed_files": changed_files,
623
+ "changed_file_count": len(changed_files),
624
+ "evidence_count": len(receipt.get("evidence", [])),
625
+ "scope_expansion_requested": receipt.get("scope_expansion") is not None,
626
+ "result_sha256": digest_bytes(result_bytes),
627
+ "raw_log_sha256": digest_bytes(log_bytes),
628
+ "raw_log_bytes": len(log_bytes),
629
+ }
630
+
631
+
632
+ def _validate_authorized_failed_job(
633
+ run_id: str,
634
+ unit: dict,
635
+ attempt: dict,
636
+ ) -> None:
637
+ job_id = attempt.get("job_id")
638
+ if not isinstance(job_id, str):
639
+ raise Operational("BLOCKED", "failed receipt has no bound runner job")
640
+ job_dir = runner_job_dir(run_id, job_id)
641
+ if process_evidence(job_dir)["process_state"] != "failed":
642
+ raise Operational("BLOCKED", "failed receipt requires authoritative failed runner evidence")
643
+ meta = read_private_json(os.path.join(job_dir, "meta.json"))
644
+ if meta.get("job_id") != job_id:
645
+ raise Operational("BLOCKED", "runner job metadata identity mismatch")
646
+ validate_runner_contract(run_id, unit, meta)
647
+ expected_result_dir = os.path.join(os.path.dirname(unit["workspace"]["path"]), "result")
648
+ expected_dispatch = {
649
+ "attempt_id": attempt.get("attempt_id"),
650
+ "job_id": job_id,
651
+ "authorization_path": attempt.get("authorization_path"),
652
+ "authorization_digest": attempt.get("authorization_digest"),
653
+ "workspace": unit["workspace"]["path"],
654
+ "packet_path": unit["packet"]["path"],
655
+ "packet_digest": unit["packet_digest"],
656
+ "result_dir": expected_result_dir,
657
+ "result_dir_identity": unit.get("result_dir_identity"),
658
+ }
659
+ if attempt.get("dispatch_authorization_receipt") != expected_dispatch:
660
+ raise Operational("BLOCKED", "failed receipt is not bound to the exact authorized dispatch")
661
+
662
+
663
+ def _authorized_failed_terminal_receipt(
664
+ run_id: str,
665
+ unit: dict,
666
+ attempt: dict,
667
+ *,
668
+ unavailable: bool,
669
+ ) -> dict:
670
+ _validate_authorized_failed_job(run_id, unit, attempt)
671
+ return terminal_receipt(
672
+ unit,
673
+ attempt,
674
+ unavailable=unavailable,
675
+ launched_failure=not unavailable,
676
+ )
677
+
678
+
679
+ def unavailable_terminal_receipt(run_id: str, unit: dict, attempt: dict) -> dict:
680
+ return _authorized_failed_terminal_receipt(run_id, unit, attempt, unavailable=True)
681
+
682
+
683
+ def launched_failure_terminal_receipt(run_id: str, unit: dict, attempt: dict) -> dict:
684
+ return _authorized_failed_terminal_receipt(run_id, unit, attempt, unavailable=False)
685
+
686
+
687
+ def record_terminal_validation_failure(run_id: str, unit_id: str, error: Operational) -> None:
688
+ if isinstance(error, TrustFailure):
689
+ raise error
690
+ with locked_manifest(run_id) as doc:
691
+ unit = doc["units"][unit_id]
692
+ result_digest = digest_bytes(read_recorded_result_file(unit, "implementation-result.json", MAX_RESULT_BYTES))
693
+ with locked_manifest(run_id, write=True) as doc:
694
+ attempt = find_attempt(doc["units"][unit_id])
695
+ failure = {
696
+ "at": now_iso(),
697
+ "word": error.word,
698
+ "reason": str(error),
699
+ "detail": error.detail,
700
+ "job_id": attempt.get("job_id"),
701
+ "result_sha256": result_digest,
702
+ }
703
+ attempt["terminal_validation_failure"] = failure
704
+ fallback = attempt.setdefault("fallback", {})
705
+ fallback.setdefault("claimed", None)
706
+ fallback["eligible"] = fallback.get("claimed") is None
707
+ fallback["reason"] = "terminal-validation-failure"
708
+ event(doc, "terminal-validation-failed", unit_id, failure)
709
+
710
+
711
+ def validate_terminal_validation_failure(run_id: str, unit: dict, attempt: dict) -> dict:
712
+ failure = attempt.get("terminal_validation_failure")
713
+ if not isinstance(failure, dict) or failure.get("job_id") != attempt.get("job_id"):
714
+ raise Operational("REFUSED", "attempt has no exact terminal-validation failure")
715
+ observed = process_evidence(runner_job_dir(run_id, attempt["job_id"]))["process_state"]
716
+ if observed != "done":
717
+ raise Operational("BLOCKED", "terminal-validation job evidence changed")
718
+ if digest_bytes(read_recorded_result_file(unit, "implementation-result.json", MAX_RESULT_BYTES)) != failure.get("result_sha256"):
719
+ raise Operational("BLOCKED", "terminal-validation result evidence changed")
720
+ return failure
721
+
722
+
723
+ def retire_terminal_validation_failure(unit: dict) -> None:
724
+ attempt = find_attempt(unit)
725
+ failure = attempt.get("terminal_validation_failure")
726
+ claimed = attempt.get("fallback", {}).get("claimed")
727
+ if failure is not None and not claimed:
728
+ attempt.pop("terminal_validation_failure")
729
+ attempt["fallback"] = {"eligible": False, "reason": None, "claimed": None}
730
+
731
+
732
+ def validate_runner_contract(run_id: str, unit: dict, meta: dict) -> None:
733
+ unit_id = unit["unit_id"]
734
+ expected_result_dir = os.path.join(run_dir(run_id), "units", unit_id, "result")
735
+ expected_result_file = os.path.join(expected_result_dir, "implementation-result.json")
736
+ if meta.get("skill") != "ce-work":
737
+ raise Operational("BLOCKED", "runner skill must be 'ce-work'")
738
+ if meta.get("run_id") != run_id:
739
+ raise Operational("BLOCKED", f"runner run id must equal the controller run id exactly: expected {run_id!r}")
740
+ if meta.get("label") != unit_id:
741
+ raise Operational(
742
+ "BLOCKED",
743
+ f"runner label must equal unit id exactly: expected {unit_id!r}, got {meta.get('label')!r}",
744
+ )
745
+ if meta.get("input_digest") != unit["packet_digest"]:
746
+ raise Operational("BLOCKED", "runner input digest must equal the controller packet digest")
747
+ if not isinstance(meta.get("result_path"), str) or os.path.abspath(meta["result_path"]) != expected_result_file:
748
+ raise Operational(
749
+ "BLOCKED",
750
+ f"runner result path must be the controller result file: {expected_result_file}",
751
+ )
752
+ attempt = find_attempt(unit)
753
+ authorization = attempt.get("authorization")
754
+ authorization_path = attempt.get("authorization_path")
755
+ authorization_digest = attempt.get("authorization_digest")
756
+ if not isinstance(authorization, dict) or not isinstance(authorization_path, str) or not isinstance(authorization_digest, str):
757
+ raise Operational("BLOCKED", "attempt has no controller-issued authorization artifact")
758
+ authorization_bytes = read_private(authorization_path, MAX_JSON_BYTES)
759
+ try:
760
+ observed_authorization = json.loads(authorization_bytes)
761
+ except (ValueError, UnicodeDecodeError) as exc:
762
+ raise TrustFailure("controller authorization artifact is malformed") from exc
763
+ if observed_authorization != authorization or digest_bytes(authorization_bytes) != authorization_digest:
764
+ raise Operational("BLOCKED", "controller authorization artifact no longer matches the recorded attempt")
765
+ expected_argv = [
766
+ attempt.get("adapter"), authorization_path, unit["workspace"]["path"],
767
+ unit["packet"]["path"], unit["packet_digest"], expected_result_dir,
768
+ ]
769
+ if meta.get("worker_argv") != expected_argv:
770
+ raise Operational(
771
+ "BLOCKED", "runner worker argv does not match the controller-issued fixed-route contract",
772
+ {"expected_argv": expected_argv, "actual_argv": meta.get("worker_argv")},
773
+ )
774
+
775
+
776
+ def cmd_authorize_dispatch(args) -> tuple[str, dict]:
777
+ run_id = safe_id(args.run_id, "run id")
778
+ unit_id = safe_id(args.unit_id, "unit id")
779
+ attempt_id = safe_id(args.attempt_id, "attempt id")
780
+ job_id = safe_id(args.job_id, "job id")
781
+ if not re.fullmatch(r"[0-9a-f]{64}", args.authorization_digest):
782
+ raise Operational("REFUSED", "observed authorization digest must be lowercase SHA-256")
783
+ if not re.fullmatch(r"[0-9a-f]{64}", args.packet_digest):
784
+ raise Operational("REFUSED", "observed packet digest must be lowercase SHA-256")
785
+ with locked_manifest(run_id, write=True) as doc:
786
+ validate_repo(doc)
787
+ unit = doc["units"].get(unit_id)
788
+ if not unit:
789
+ raise Operational("REFUSED", "unknown unit")
790
+ attempt = find_attempt(unit, attempt_id)
791
+ if unit.get("state") not in {"queued", "authoring"}:
792
+ raise Operational("REFUSED", "dispatch authorization is available only before worker completion")
793
+ bound_job = attempt.get("job_id")
794
+ if bound_job not in (None, job_id):
795
+ raise Operational("AMBIGUOUS", "attempt is already bound to another job")
796
+ job_dir = os.path.join(run_dir(run_id), "jobs", job_id)
797
+ validate_private_dir(job_dir)
798
+ meta = read_private_json(os.path.join(job_dir, "meta.json"))
799
+ if meta.get("job_id") != job_id:
800
+ raise Operational("BLOCKED", "runner job metadata identity mismatch")
801
+ validate_runner_contract(run_id, unit, meta)
802
+
803
+ expected_authorization_path = attempt.get("authorization_path")
804
+ expected_authorization_digest = attempt.get("authorization_digest")
805
+ if os.path.abspath(args.authorization) != expected_authorization_path:
806
+ raise Operational("BLOCKED", "authorization path does not match the recorded attempt")
807
+ if args.authorization_digest != expected_authorization_digest:
808
+ raise Operational("BLOCKED", "observed authorization digest does not match the recorded attempt")
809
+ authorization_bytes = read_private(expected_authorization_path, MAX_JSON_BYTES)
810
+ if digest_bytes(authorization_bytes) != expected_authorization_digest:
811
+ raise Operational("BLOCKED", "controller authorization bytes no longer match the recorded digest")
812
+ try:
813
+ authorization = json.loads(authorization_bytes)
814
+ except (ValueError, UnicodeDecodeError) as exc:
815
+ raise TrustFailure("controller authorization artifact is malformed") from exc
816
+ if authorization != attempt.get("authorization"):
817
+ raise Operational("BLOCKED", "controller authorization object no longer matches the recorded attempt")
818
+ if (
819
+ authorization.get("run_id") != run_id
820
+ or authorization.get("unit_id") != unit_id
821
+ or authorization.get("attempt_id") != attempt_id
822
+ ):
823
+ raise Operational("BLOCKED", "authorization run/unit/attempt identity mismatch")
824
+
825
+ expected_workspace = unit["workspace"]["path"]
826
+ if os.path.abspath(args.workspace) != expected_workspace:
827
+ raise Operational("BLOCKED", "workspace path does not match the recorded unit")
828
+ expected_dispatch_authorization_receipt = {
829
+ "attempt_id": attempt_id,
830
+ "job_id": job_id,
831
+ "authorization_path": expected_authorization_path,
832
+ "authorization_digest": expected_authorization_digest,
833
+ "workspace": expected_workspace,
834
+ "packet_path": unit["packet"]["path"],
835
+ "packet_digest": unit["packet_digest"],
836
+ "result_dir": os.path.join(os.path.dirname(expected_workspace), "result"),
837
+ "result_dir_identity": unit.get("result_dir_identity"),
838
+ }
839
+ recorded_dispatch_authorization_receipt = attempt.get("dispatch_authorization_receipt")
840
+ if recorded_dispatch_authorization_receipt is not None and (
841
+ bound_job != job_id
842
+ or recorded_dispatch_authorization_receipt != expected_dispatch_authorization_receipt
843
+ ):
844
+ raise Operational("BLOCKED", "recorded dispatch authorization does not match the exact request")
845
+ resumed = recorded_dispatch_authorization_receipt == expected_dispatch_authorization_receipt
846
+ if resumed:
847
+ validate_workspace(doc, unit)
848
+ else:
849
+ validate_pristine_unit_base(doc, unit)
850
+
851
+ expected_packet = unit["packet"]["path"]
852
+ if os.path.abspath(args.packet) != expected_packet:
853
+ raise Operational("BLOCKED", "packet path does not match the controller-owned unit packet")
854
+ if args.packet_digest != unit["packet_digest"] or authorization.get("packet_digest") != unit["packet_digest"]:
855
+ raise Operational("BLOCKED", "packet digest does not match the recorded authorization")
856
+ packet_bytes = read_private(expected_packet, MAX_PACKET_BYTES)
857
+ if digest_bytes(packet_bytes) != unit["packet_digest"]:
858
+ raise Operational("BLOCKED", "controller-owned packet bytes no longer match the recorded digest")
859
+
860
+ expected_result_dir = os.path.join(os.path.dirname(expected_workspace), "result")
861
+ if os.path.abspath(args.result_dir) != expected_result_dir:
862
+ raise Operational("BLOCKED", "result directory does not match the recorded unit")
863
+ result_fd, _ = open_recorded_result_dir(unit)
864
+ close_dir_handle(result_fd)
865
+ if not resumed:
866
+ attempt["job_id"] = job_id
867
+ attempt["dispatch_authorization_receipt"] = expected_dispatch_authorization_receipt
868
+ unit["state"] = "authoring"
869
+ event(doc, "job-bound", unit_id, {
870
+ "attempt_id": attempt_id,
871
+ "job_id": job_id,
872
+ "source": "authorize-dispatch",
873
+ })
874
+ return "AUTHORIZED", {
875
+ "run_id": run_id,
876
+ "unit_id": unit_id,
877
+ "attempt_id": attempt_id,
878
+ "job_id": job_id,
879
+ "resumed": resumed,
880
+ "authorization_digest": expected_authorization_digest,
881
+ "packet_digest": unit["packet_digest"],
882
+ }
883
+
884
+
885
+ def matching_runner_jobs(run_id: str, unit: dict) -> list[str]:
886
+ jobs = os.path.join(run_dir(run_id), "jobs")
887
+ validate_private_dir(jobs)
888
+ matches: list[str] = []
889
+ for entry in os.scandir(jobs):
890
+ if not entry.is_dir(follow_symlinks=False):
891
+ continue
892
+ safe_id(entry.name, "job id")
893
+ validate_private_dir(entry.path)
894
+ meta = read_private_json(os.path.join(entry.path, "meta.json"))
895
+ if (
896
+ meta.get("skill") == "ce-work"
897
+ and meta.get("run_id") == run_id
898
+ and meta.get("label") == unit["unit_id"]
899
+ and meta.get("input_digest") == unit["packet_digest"]
900
+ ):
901
+ validate_runner_contract(run_id, unit, meta)
902
+ matches.append(entry.name)
903
+ return sorted(matches)
904
+
905
+
906
+ def find_attempt(unit: dict, attempt_id: str | None = None) -> dict:
907
+ attempts = unit.get("attempts", [])
908
+ if attempt_id:
909
+ matches = [a for a in attempts if a.get("attempt_id") == attempt_id]
910
+ else:
911
+ matches = attempts[-1:]
912
+ if len(matches) != 1:
913
+ raise Operational("AMBIGUOUS", "attempt could not be identified exactly")
914
+ return matches[0]
915
+
916
+
917
+ def scope_expansion_pending(unit: dict) -> bool:
918
+ """Return whether the current authored result still requires host resolution."""
919
+ receipt = find_attempt(unit).get("terminal_receipt")
920
+ return isinstance(receipt, dict) and receipt.get("terminal_status") == "scope_expansion"
921
+
922
+
923
+ def cmd_record_job(args) -> tuple[str, dict]:
924
+ with locked_manifest(args.run_id) as doc:
925
+ unit = doc["units"].get(args.unit_id)
926
+ if not unit:
927
+ raise Operational("REFUSED", "unknown unit")
928
+ attempt = find_attempt(unit, args.attempt_id)
929
+ if attempt.get("job_id"):
930
+ if attempt["job_id"] != args.job_id:
931
+ raise Operational("AMBIGUOUS", "attempt is already bound to another job")
932
+ return "AUTHORING", {
933
+ "unit_id": args.unit_id,
934
+ "job_id": args.job_id,
935
+ "resumed": True,
936
+ "unit_state": unit["state"],
937
+ }
938
+ job_dir = runner_job_dir(args.run_id, args.job_id)
939
+ meta = read_private_json(os.path.join(job_dir, "meta.json"))
940
+ validate_runner_contract(args.run_id, unit, meta)
941
+ with locked_manifest(args.run_id, write=True) as doc:
942
+ unit = doc["units"][args.unit_id]
943
+ attempt = find_attempt(unit, args.attempt_id)
944
+ bound_job = attempt.get("job_id")
945
+ if bound_job == args.job_id:
946
+ return "AUTHORING", {
947
+ "unit_id": args.unit_id,
948
+ "job_id": args.job_id,
949
+ "resumed": True,
950
+ "unit_state": unit["state"],
951
+ }
952
+ if bound_job is not None:
953
+ raise Operational("AMBIGUOUS", "attempt was concurrently bound")
954
+ if unit.get("state") != "queued":
955
+ raise Operational("REFUSED", "an unbound job can be recorded only while the unit is queued")
956
+ attempt["job_id"] = args.job_id
957
+ unit["state"] = "authoring"
958
+ event(doc, "job-bound", args.unit_id, {"attempt_id": args.attempt_id, "job_id": args.job_id})
959
+ return "AUTHORING", {"unit_id": args.unit_id, "job_id": args.job_id, "resumed": False}
960
+
961
+
962
+ def sync_job(run_id: str, unit_id: str) -> dict:
963
+ with locked_manifest(run_id) as doc:
964
+ unit = doc["units"].get(unit_id)
965
+ if not unit:
966
+ raise Operational("REFUSED", "unknown unit")
967
+ attempt = find_attempt(unit)
968
+ if not attempt.get("job_id"):
969
+ return {"process_state": "never-started", "activity": attempt["activity"]}
970
+ evidence = process_evidence(runner_job_dir(run_id, attempt["job_id"]))
971
+ failure_receipt = None
972
+ oversized_result_failure = False
973
+ if evidence["process_state"] == "failed":
974
+ result_fd, result_dir = open_recorded_result_dir(unit)
975
+ try:
976
+ result_stat = stat_private_at(
977
+ result_fd,
978
+ "implementation-result.json",
979
+ os.path.join(result_dir, "implementation-result.json"),
980
+ missing_ok=True,
981
+ )
982
+ finally:
983
+ close_dir_handle(result_fd)
984
+ if result_stat is not None and result_stat.st_size > MAX_RESULT_BYTES:
985
+ _validate_authorized_failed_job(run_id, unit, attempt)
986
+ oversized_result_failure = True
987
+ else:
988
+ for reader in (unavailable_terminal_receipt, launched_failure_terminal_receipt):
989
+ try:
990
+ failure_receipt = reader(run_id, unit, attempt)
991
+ break
992
+ except TrustFailure:
993
+ raise
994
+ except Operational:
995
+ continue
996
+ with locked_manifest(run_id, write=True) as doc:
997
+ attempt = find_attempt(doc["units"][unit_id])
998
+ prior_state = attempt.get("process_state")
999
+ prior_activity = dict(attempt["activity"])
1000
+ prior_fallback = dict(attempt.get("fallback", {}))
1001
+ prior_receipt = attempt.get("terminal_receipt")
1002
+ attempt["process_state"] = evidence["process_state"]
1003
+ attempt["activity"].update(evidence["activity"])
1004
+ if failure_receipt is not None:
1005
+ attempt["terminal_receipt"] = failure_receipt
1006
+ authoritative_failure = evidence["process_state"] in TERMINAL_PROCESS - {"done"} or (
1007
+ evidence["process_state"] == "never-started" and bool(attempt.get("job_id"))
1008
+ )
1009
+ effective_failure_reason = None
1010
+ if authoritative_failure:
1011
+ effective_failure_reason = (
1012
+ failure_receipt["failure_reason"]
1013
+ if failure_receipt is not None
1014
+ else evidence["failure_reason"]
1015
+ if oversized_result_failure and evidence["failure_reason"]
1016
+ else evidence["process_state"]
1017
+ )
1018
+ fallback = attempt.setdefault("fallback", {})
1019
+ fallback.setdefault("claimed", None)
1020
+ fallback["eligible"] = fallback.get("claimed") is None
1021
+ fallback["reason"] = effective_failure_reason
1022
+ changed = (
1023
+ prior_state != evidence["process_state"]
1024
+ or prior_activity != attempt["activity"]
1025
+ or prior_fallback != attempt.get("fallback", {})
1026
+ or prior_receipt != attempt.get("terminal_receipt")
1027
+ )
1028
+ if changed:
1029
+ event(doc, "job-synced", unit_id, {"process_state": evidence["process_state"]})
1030
+ if prior_state != evidence["process_state"] and evidence["process_state"] in TERMINAL_PROCESS:
1031
+ event(doc, "job-terminal", unit_id, {"process_state": evidence["process_state"]})
1032
+ if failure_receipt is not None and prior_receipt != failure_receipt:
1033
+ receipt_event = "route-unavailable" if failure_receipt["terminal_status"] == "unavailable" else "route-failed"
1034
+ event(doc, receipt_event, unit_id, {"failure_reason": failure_receipt["failure_reason"]})
1035
+ activity = dict(attempt["activity"])
1036
+ return {
1037
+ "process_state": evidence["process_state"],
1038
+ "failure_reason": effective_failure_reason,
1039
+ "activity": activity,
1040
+ }
1041
+
1042
+
1043
+ def cmd_sync_job(args) -> tuple[str, dict]:
1044
+ evidence = sync_job(args.run_id, args.unit_id)
1045
+ return "SYNCED", {"unit_id": args.unit_id, **evidence}
1046
+
1047
+
1048
+ def transport_ref(run_id: str, unit_id: str) -> str:
1049
+ return f"refs/ce-work/{digest_bytes(run_id.encode())[:20]}/{digest_bytes(unit_id.encode())[:20]}"
1050
+
1051
+
1052
+ def no_sequencer(workspace: str) -> None:
1053
+ git_dir = git_text(workspace, "rev-parse", "--path-format=absolute", "--absolute-git-dir")
1054
+ for name in ("MERGE_HEAD", "CHERRY_PICK_HEAD", "REVERT_HEAD", "rebase-merge", "rebase-apply"):
1055
+ if os.path.exists(os.path.join(git_dir, name)):
1056
+ raise Operational("BLOCKED", f"worker workspace has unresolved Git operation: {name}")
1057
+
1058
+
1059
+ def parse_diff_paths(raw: bytes) -> list[str]:
1060
+ parts = raw.split(b"\0")
1061
+ paths: list[str] = []
1062
+ expect_paths = 0
1063
+ for part in parts:
1064
+ if not part:
1065
+ continue
1066
+ text = part.decode("utf-8", "surrogateescape")
1067
+ if expect_paths:
1068
+ paths.append(text)
1069
+ expect_paths -= 1
1070
+ else:
1071
+ expect_paths = 2 if text.startswith(("R", "C")) else 1
1072
+ if expect_paths:
1073
+ raise Operational("BLOCKED", "incomplete NUL-delimited transport inventory")
1074
+ return paths
1075
+
1076
+
1077
+ def diff_changes_gitlink(raw: bytes) -> bool:
1078
+ for record in raw.split(b"\0"):
1079
+ if not record.startswith(b":"):
1080
+ continue
1081
+ fields = record[1:].split(b" ", 4)
1082
+ if len(fields) >= 2 and b"160000" in fields[:2]:
1083
+ return True
1084
+ return False
1085
+
1086
+
1087
+ def terminalize(run_id: str, unit_id: str) -> dict:
1088
+ evidence = sync_job(run_id, unit_id)
1089
+ if evidence["process_state"] != "done":
1090
+ detail = {}
1091
+ if evidence["process_state"] == "failed":
1092
+ with locked_manifest(run_id) as doc:
1093
+ attempt = find_attempt(doc["units"][unit_id])
1094
+ receipt = attempt.get("terminal_receipt")
1095
+ if isinstance(receipt, dict) and receipt.get("terminal_status") == "unavailable":
1096
+ detail = {"terminal_receipt": receipt, "failure_reason": receipt["failure_reason"]}
1097
+ raise Operational(
1098
+ "BLOCKED",
1099
+ f"worker is not authoritatively done ({evidence['process_state']})",
1100
+ detail,
1101
+ )
1102
+ try:
1103
+ with locked_manifest(run_id) as doc:
1104
+ unit = doc["units"].get(unit_id)
1105
+ if not unit:
1106
+ raise Operational("REFUSED", "unknown unit")
1107
+ receipt = terminal_receipt(unit, find_attempt(unit))
1108
+ if receipt.get("model_receipt_status") == "mismatch":
1109
+ raise Operational("BLOCKED", "adapter reported a served-model mismatch")
1110
+ except Operational as exc:
1111
+ record_terminal_validation_failure(run_id, unit_id, exc)
1112
+ raise
1113
+ with locked_manifest(run_id, write=True) as doc:
1114
+ unit = doc["units"].get(unit_id)
1115
+ if unit and unit["state"] == "authoring":
1116
+ find_attempt(unit)["terminal_receipt"] = receipt
1117
+ unit["state"] = "authored"
1118
+ event(doc, "worker-output-authored", unit_id, {"route": receipt["actual_route"], "model": receipt["model_actual"]})
1119
+ if receipt["terminal_status"] == "blocked":
1120
+ raise Operational(
1121
+ "BLOCKED",
1122
+ "worker returned a host-resolvable blocker",
1123
+ {
1124
+ "unit_id": unit_id,
1125
+ "terminal_status": "blocked",
1126
+ "summary": receipt["summary"],
1127
+ "terminal_receipt": receipt,
1128
+ "recovery_path": os.path.join(run_dir(run_id), "units", unit_id),
1129
+ },
1130
+ )
1131
+ with locked_manifest(run_id, write=True) as doc:
1132
+ unit = doc["units"].get(unit_id)
1133
+ if not unit:
1134
+ raise Operational("REFUSED", "unknown unit")
1135
+ if unit["state"] == "integration-pending" and unit["transport"].get("commit"):
1136
+ retire_terminal_validation_failure(unit)
1137
+ return unit["transport"]
1138
+ if unit["state"] != "authored":
1139
+ raise Operational("BLOCKED", f"unit cannot terminalize from {unit['state']}")
1140
+ if find_attempt(unit).get("fallback", {}).get("claimed"):
1141
+ raise Operational(
1142
+ "REFUSED",
1143
+ "native fallback already owns implementation; worker output cannot be terminalized",
1144
+ )
1145
+ validate_workspace(doc, unit)
1146
+ workspace = unit["workspace"]["path"]
1147
+ base = unit["workspace"]["base"]
1148
+ repo = doc["repository"]["toplevel"]
1149
+ try:
1150
+ no_sequencer(workspace)
1151
+ ignored_raw = git(workspace, "ls-files", "--others", "--ignored", "--exclude-standard", "-z")
1152
+ ignored_paths = [
1153
+ part.decode("utf-8", "surrogateescape")
1154
+ for part in ignored_raw.split(b"\0")
1155
+ if part
1156
+ ]
1157
+ if ignored_paths:
1158
+ preview = json.dumps(ignored_paths[:20], ensure_ascii=True)
1159
+ suffix = f" and {len(ignored_paths) - 20} more" if len(ignored_paths) > 20 else ""
1160
+ raise Operational(
1161
+ "BLOCKED",
1162
+ f"worker workspace contains ignored untracked output that cannot enter the transport: {preview}{suffix}",
1163
+ {"ignored_paths": ignored_paths[:100], "ignored_path_count": len(ignored_paths)},
1164
+ )
1165
+ git(workspace, "add", "-A", "--", ".")
1166
+ tree = git_text(workspace, "write-tree")
1167
+ mode_diff = git(repo, "diff-tree", "-r", "--raw", "-z", "--no-renames", base, tree)
1168
+ if diff_changes_gitlink(mode_diff):
1169
+ raise Operational("BLOCKED", "submodule state cannot be transported implicitly")
1170
+ except Operational as exc:
1171
+ record_terminal_validation_failure(run_id, unit_id, exc)
1172
+ raise
1173
+ ref = transport_ref(run_id, unit_id)
1174
+ existing = git_text(repo, "rev-parse", "-q", "--verify", ref, check=False)
1175
+ if existing:
1176
+ parents = git_text(repo, "rev-list", "--parents", "-n", "1", existing).split()
1177
+ existing_tree = git_text(repo, "rev-parse", f"{existing}^{{tree}}")
1178
+ if parents != [existing, base] or existing_tree != tree:
1179
+ raise Operational("BLOCKED", "preexisting transport ref does not match final tree/base")
1180
+ commit = existing
1181
+ else:
1182
+ env = {
1183
+ "GIT_AUTHOR_NAME": "ce-work transport",
1184
+ "GIT_AUTHOR_EMAIL": "ce-work@localhost",
1185
+ "GIT_COMMITTER_NAME": "ce-work transport",
1186
+ "GIT_COMMITTER_EMAIL": "ce-work@localhost",
1187
+ }
1188
+ commit = git(repo, "commit-tree", tree, "-p", base, input_data=f"ce-work transport {run_id}/{unit_id}\n".encode(), env=env).decode().strip()
1189
+ zero = "0" * len(commit)
1190
+ git(repo, "update-ref", ref, commit, zero)
1191
+ test_fault("after-transport-ref")
1192
+ raw_diff = git(repo, "diff-tree", "-r", "-M", "--name-status", "-z", base, commit)
1193
+ paths = parse_diff_paths(raw_diff)
1194
+ tdigest = digest_bytes(base.encode() + b"\0" + tree.encode() + b"\0" + commit.encode() + b"\0" + raw_diff)
1195
+ transport = {
1196
+ "base": base, "tree": tree, "commit": commit, "ref": ref,
1197
+ "digest": tdigest, "changed_paths": paths,
1198
+ "inventory_b64": base64.b64encode(raw_diff).decode(),
1199
+ }
1200
+ # Make successful cleanup non-destructive: after F is pinned, normalize the
1201
+ # retained inspection worktree to the exact transported tree.
1202
+ git(workspace, "reset", "--hard", commit)
1203
+ with locked_manifest(run_id, write=True) as doc:
1204
+ unit = doc["units"][unit_id]
1205
+ if unit["state"] not in ("authored", "integration-pending"):
1206
+ raise Operational("BLOCKED", "unit state changed during terminalization")
1207
+ retire_terminal_validation_failure(unit)
1208
+ unit["state"] = "integration-pending"
1209
+ unit["transport"] = transport
1210
+ event(doc, "transport-pinned", unit_id, {"commit": commit, "ref": ref, "digest": tdigest})
1211
+ return transport
1212
+
1213
+
1214
+ def cmd_terminalize(args) -> tuple[str, dict]:
1215
+ transport = terminalize(args.run_id, args.unit_id)
1216
+ return "INTEGRATION_PENDING", {"unit_id": args.unit_id, "transport": transport}