deepmodebot 0.9.0 → 0.10.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 (691) hide show
  1. package/.agents/plugins/marketplace.json +20 -0
  2. package/.claude-plugin/marketplace.json +2 -2
  3. package/.omp-plugin/marketplace.json +2 -2
  4. package/README.md +29 -5
  5. package/bin/deepmodebot.mjs +187 -10
  6. package/lib/clients.mjs +50 -3
  7. package/lib/tree.mjs +64 -10
  8. package/lib/version.mjs +26 -0
  9. package/native/dmb-gate/Cargo.toml +13 -0
  10. package/native/dmb-gate/src/agents.rs +77 -0
  11. package/native/dmb-gate/src/ci.rs +516 -0
  12. package/native/dmb-gate/src/cleanup.rs +198 -0
  13. package/native/dmb-gate/src/gap.rs +1376 -0
  14. package/native/dmb-gate/src/guard.rs +135 -0
  15. package/native/dmb-gate/src/main.rs +327 -0
  16. package/native/dmb-gate/src/map.rs +173 -0
  17. package/native/dmb-gate/src/perf.rs +347 -0
  18. package/native/dmb-gate/src/reward.rs +1214 -0
  19. package/native/dmb-gate/src/skill_check.rs +171 -0
  20. package/native/dmb-gate/src/slop.rs +1238 -0
  21. package/native/dmb-gate/src/ui.rs +842 -0
  22. package/native/dmb-gate/src/util.rs +260 -0
  23. package/native/dmb-net/go.mod +3 -0
  24. package/native/dmb-net/main.go +624 -0
  25. package/native/dmb-net/main_test.go +122 -0
  26. package/package.json +12 -2
  27. package/plugins/deepmodebot/.antigravity-plugin/plugin.json +1 -1
  28. package/plugins/deepmodebot/.antigravity-plugin/skills/deep/SKILL.md +5 -5
  29. package/plugins/deepmodebot/.antigravity-plugin/skills/pr-thread/SKILL.md +1 -1
  30. package/plugins/deepmodebot/.antigravity-plugin/skills/review-pr/SKILL.md +2 -2
  31. package/plugins/deepmodebot/.antigravity-plugin/skills/suggest/SKILL.md +13 -0
  32. package/plugins/deepmodebot/.antigravity-plugin/skills/tournament/SKILL.md +2 -2
  33. package/plugins/deepmodebot/.claude-plugin/plugin.json +1 -1
  34. package/plugins/deepmodebot/.codex-plugin/plugin.json +46 -0
  35. package/plugins/deepmodebot/agents/comment-sicko/agent.md +35 -0
  36. package/plugins/deepmodebot/agents/researcher/agent.md +33 -0
  37. package/plugins/deepmodebot/agents/reviewer/agent.md +4 -2
  38. package/plugins/deepmodebot/agents/scout/agent.md +11 -12
  39. package/plugins/deepmodebot/agents/security-reviewer/agent.md +2 -1
  40. package/plugins/deepmodebot/commands/deep.md +6 -6
  41. package/plugins/deepmodebot/commands/research.md +8 -0
  42. package/plugins/deepmodebot/commands/suggest.md +10 -0
  43. package/plugins/deepmodebot/commands/tournament.md +2 -2
  44. package/plugins/deepmodebot/hooks/hooks.json +2 -2
  45. package/plugins/deepmodebot/hooks.json +1 -1
  46. package/plugins/deepmodebot/scripts/antigravity-guard.mjs +140 -7
  47. package/plugins/deepmodebot/scripts/omp-mcp-server.mjs +179 -47
  48. package/plugins/deepmodebot/skills/agent-harnesses/SKILL.md +4 -6
  49. package/plugins/deepmodebot/skills/agent-harnesses/assets/sdks/check_antigravity.py +3 -0
  50. package/plugins/deepmodebot/skills/agent-harnesses/references/ai-native-tooling.md +4 -0
  51. package/plugins/deepmodebot/skills/agent-harnesses/references/ai-sdk-selection.md +3 -1
  52. package/plugins/deepmodebot/skills/agent-harnesses/references/antigravity.md +2 -2
  53. package/plugins/deepmodebot/skills/agent-harnesses/references/delegation-efficiency.md +12 -2
  54. package/plugins/deepmodebot/skills/agent-harnesses/references/protocols.md +11 -3
  55. package/plugins/deepmodebot/skills/app-automation-relay/SKILL.md +17 -0
  56. package/plugins/deepmodebot/skills/app-automation-relay/assets/relay_server.ts +364 -0
  57. package/plugins/deepmodebot/skills/app-automation-relay/references/adapter-cookbook.md +15 -0
  58. package/plugins/deepmodebot/skills/app-automation-relay/references/wire-protocol.md +23 -0
  59. package/plugins/deepmodebot/skills/cloud-devsecops/SKILL.md +4 -3
  60. package/plugins/deepmodebot/skills/cloud-devsecops/references/cloudflare-edge.md +43 -0
  61. package/plugins/deepmodebot/skills/cloud-devsecops/references/local-emulators.md +15 -2
  62. package/plugins/deepmodebot/skills/contribute/SKILL.md +3 -35
  63. package/plugins/deepmodebot/skills/create-formal-verification-skill/LICENSE +21 -0
  64. package/plugins/deepmodebot/skills/create-formal-verification-skill/NOTICE.md +16 -0
  65. package/plugins/deepmodebot/skills/create-formal-verification-skill/SKILL.md +71 -0
  66. package/plugins/deepmodebot/skills/create-verification-skill/SKILL.md +2 -2
  67. package/plugins/deepmodebot/skills/deep-learning/LICENSE +21 -0
  68. package/plugins/deepmodebot/skills/deep-learning/SKILL.md +33 -0
  69. package/plugins/deepmodebot/skills/deep-learning/references/neural-architectures.md +43 -0
  70. package/plugins/deepmodebot/skills/deep-learning/references/papers-and-repos.md +128 -0
  71. package/plugins/deepmodebot/skills/deep-learning/references/reinforcement-learning.md +57 -0
  72. package/plugins/deepmodebot/skills/deep-learning/references/training-optimization.md +40 -0
  73. package/plugins/deepmodebot/skills/deep-learning/references/weight-space-programming.md +76 -0
  74. package/plugins/deepmodebot/skills/deep-learning/scripts/hf_passes.py +166 -0
  75. package/plugins/deepmodebot/skills/deep-learning/scripts/wsp.py +493 -0
  76. package/plugins/deepmodebot/skills/deep-stack/SKILL.md +1 -1
  77. package/plugins/deepmodebot/skills/deep-stack/references/design-workflow.md +46 -92
  78. package/plugins/deepmodebot/skills/deep-stack/references/isolate.md +1 -0
  79. package/plugins/deepmodebot/skills/deep-stack/references/prove.md +6 -0
  80. package/plugins/deepmodebot/skills/deep-stack/references/stack.md +11 -1
  81. package/plugins/deepmodebot/skills/deepmodebot/SKILL.md +74 -145
  82. package/plugins/deepmodebot/skills/deepmodebot/assets/agents-md/agents_md.py +18 -6
  83. package/plugins/deepmodebot/skills/deepmodebot/assets/autoroute/autoroute.py +1021 -0
  84. package/plugins/deepmodebot/skills/deepmodebot/assets/cleanup/self_cleanup.py +305 -0
  85. package/plugins/deepmodebot/skills/deepmodebot/assets/contain/claude_guard.py +98 -5
  86. package/plugins/deepmodebot/skills/deepmodebot/assets/contain/omp-contain.ts +106 -5
  87. package/plugins/deepmodebot/skills/deepmodebot/assets/e2e/design.py +3 -0
  88. package/plugins/deepmodebot/skills/deepmodebot/assets/e2e/record.py +2 -0
  89. package/plugins/deepmodebot/skills/deepmodebot/assets/e2e/rehearsal_gate.py +536 -0
  90. package/plugins/deepmodebot/skills/deepmodebot/assets/e2e/review.py +2 -0
  91. package/plugins/deepmodebot/skills/deepmodebot/assets/formal-verification/verify_proof.py +638 -0
  92. package/plugins/deepmodebot/skills/deepmodebot/assets/gap-audit/gap_audit.py +1053 -0
  93. package/plugins/deepmodebot/skills/deepmodebot/assets/gen-ui/gen_ui.py +1782 -0
  94. package/plugins/deepmodebot/skills/deepmodebot/assets/git-guardrails/git-guard-patterns.txt +7 -0
  95. package/plugins/deepmodebot/skills/deepmodebot/assets/git-guardrails/git-guard.sh +3 -2
  96. package/plugins/deepmodebot/skills/deepmodebot/assets/git-guardrails/git-guard.ts +9 -5
  97. package/plugins/deepmodebot/skills/deepmodebot/assets/github-app/ghapp.py +2 -0
  98. package/plugins/deepmodebot/skills/deepmodebot/assets/github-app/install.py +2 -0
  99. package/plugins/deepmodebot/skills/deepmodebot/assets/local-ci/local_ci.py +540 -0
  100. package/plugins/deepmodebot/skills/deepmodebot/assets/local-ci/slop_gate.py +642 -0
  101. package/plugins/deepmodebot/skills/deepmodebot/assets/loop/loop.py +2 -1
  102. package/plugins/deepmodebot/skills/deepmodebot/assets/loop/plan.py +2 -1
  103. package/plugins/deepmodebot/skills/deepmodebot/assets/loop/windows_job.py +2 -0
  104. package/plugins/deepmodebot/skills/deepmodebot/assets/memory/project_memory.py +529 -0
  105. package/plugins/deepmodebot/skills/deepmodebot/assets/perf-audit/bench_harness.py +48 -21
  106. package/plugins/deepmodebot/skills/deepmodebot/assets/perf-audit/perf_audit.py +339 -5
  107. package/plugins/deepmodebot/skills/deepmodebot/assets/pr-agent/diff_coverage.py +96 -6
  108. package/plugins/deepmodebot/skills/deepmodebot/assets/pr-agent/pr_agent_local.py +2 -0
  109. package/plugins/deepmodebot/skills/deepmodebot/assets/pr-conversation/arena.py +2 -0
  110. package/plugins/deepmodebot/skills/deepmodebot/assets/pr-conversation/show_thread.py +2 -0
  111. package/plugins/deepmodebot/skills/deepmodebot/assets/prompt-tools/prompt_tools.py +1239 -0
  112. package/plugins/deepmodebot/skills/deepmodebot/assets/quota-guard/quota_guard.py +424 -0
  113. package/plugins/deepmodebot/skills/deepmodebot/assets/repo-references.json +477 -1
  114. package/plugins/deepmodebot/skills/deepmodebot/assets/reward-guard/reward_guard.py +1597 -0
  115. package/plugins/deepmodebot/skills/deepmodebot/assets/rules/rule-paths.json +57 -0
  116. package/plugins/deepmodebot/skills/deepmodebot/assets/rules/rule_ledger.py +1645 -0
  117. package/plugins/deepmodebot/skills/deepmodebot/assets/scrape/yt_enrich.py +2 -0
  118. package/plugins/deepmodebot/skills/deepmodebot/assets/scrape/yt_meta.py +2 -0
  119. package/plugins/deepmodebot/skills/deepmodebot/assets/scrape/yt_transcript_relay.js +13 -10
  120. package/plugins/deepmodebot/skills/deepmodebot/assets/security-audit/static_sec_audit.py +275 -0
  121. package/plugins/deepmodebot/skills/deepmodebot/assets/self-grill/self_grill.py +1473 -0
  122. package/plugins/deepmodebot/skills/deepmodebot/assets/setup/model_setup.py +329 -0
  123. package/plugins/deepmodebot/skills/deepmodebot/assets/setup/project_setup.py +312 -0
  124. package/plugins/deepmodebot/skills/deepmodebot/assets/tournament/tournament.py +304 -18
  125. package/plugins/deepmodebot/skills/deepmodebot/assets/workspace-map/workspace_map.py +121 -78
  126. package/plugins/deepmodebot/skills/deepmodebot/references/README.md +14 -0
  127. package/plugins/deepmodebot/skills/deepmodebot/references/catalog.md +16 -11
  128. package/plugins/deepmodebot/skills/deepmodebot/references/contain.md +2 -1
  129. package/plugins/deepmodebot/skills/deepmodebot/references/delegation.md +14 -0
  130. package/plugins/deepmodebot/skills/deepmodebot/references/flows.md +2 -0
  131. package/plugins/deepmodebot/skills/deepmodebot/references/full-scope.md +9 -0
  132. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/babysit.md +2 -0
  133. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/end-to-end.md +12 -9
  134. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/feature.md +7 -3
  135. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/hillclimb.md +2 -0
  136. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/investigation.md +4 -4
  137. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/opening-a-pr.md +1 -1
  138. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/perf-issue.md +13 -10
  139. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/refactoring.md +6 -6
  140. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/reference-rebuild.md +1 -0
  141. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/run-a-goal.md +3 -1
  142. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/setup.md +1 -2
  143. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/visual-parity.md +1 -0
  144. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/work-a-queue.md +4 -2
  145. package/plugins/deepmodebot/skills/deepmodebot/references/principles/hardcore-mode.md +7 -0
  146. package/plugins/deepmodebot/skills/deepmodebot/references/principles/no-reward-hacking.md +8 -0
  147. package/plugins/deepmodebot/skills/deepmodebot/references/principles/test-behavior-not-implementation.md +2 -1
  148. package/plugins/deepmodebot/skills/deepmodebot/references/principles/type-system-discipline.md +2 -2
  149. package/plugins/deepmodebot/skills/deepmodebot/references/rule-approval.md +51 -0
  150. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/architect.md +10 -24
  151. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/architecture-review.md +5 -4
  152. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/arena.md +3 -3
  153. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/autoroute.md +49 -0
  154. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/blast-radius.md +1 -1
  155. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/catchup-video.md +13 -0
  156. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/correct.md +8 -7
  157. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/course.md +2 -1
  158. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/devex-review.md +13 -0
  159. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/expand-contract.md +13 -0
  160. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/formal-verification.md +33 -0
  161. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/gen-ui.md +60 -0
  162. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/grill.md +2 -1
  163. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/how.md +7 -18
  164. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/inner-loop.md +7 -7
  165. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/model-setup.md +14 -0
  166. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/modernize-pr.md +15 -0
  167. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/mutation-testing.md +13 -0
  168. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/no-comments.md +5 -5
  169. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/panel.md +7 -3
  170. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/pr-conversation.md +1 -1
  171. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/pr-review.md +8 -5
  172. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/pre-commit.md +1 -2
  173. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/prior-art.md +33 -38
  174. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/product-lens.md +12 -0
  175. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/prompt-upgrade.md +30 -0
  176. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/recall.md +1 -1
  177. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/reframe.md +18 -0
  178. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/release-and-canary.md +10 -0
  179. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/research.md +62 -89
  180. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/security-audit.md +5 -1
  181. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/self-grill.md +54 -0
  182. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/sharpen.md +3 -3
  183. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/show-me-your-work.md +7 -0
  184. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/sme-review.md +3 -2
  185. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/suggest.md +24 -0
  186. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/swarm.md +7 -0
  187. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/teach.md +2 -2
  188. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/tournament.md +12 -11
  189. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/variant-analysis.md +11 -0
  190. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/video-forensics.md +46 -0
  191. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/visual-e2e.md +10 -1
  192. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/webhook-ui.md +11 -0
  193. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/writing-for-agents.md +6 -0
  194. package/plugins/deepmodebot/skills/deepmodebot/scripts/check_skill.py +7 -0
  195. package/plugins/deepmodebot/skills/deepmodebot/scripts/trending.py +141 -18
  196. package/plugins/deepmodebot/skills/deepmodebot/worker.md +16 -0
  197. package/plugins/deepmodebot/skills/domain-rules/SKILL.md +13 -119
  198. package/plugins/deepmodebot/skills/domain-rules/references/backend-system-design.md +19 -1
  199. package/plugins/deepmodebot/skills/domain-rules/references/engineering-practice.md +7 -0
  200. package/plugins/deepmodebot/skills/domain-rules/references/language-ecosystems.md +11 -0
  201. package/plugins/deepmodebot/skills/domain-rules/references/sources.md +108 -0
  202. package/plugins/deepmodebot/skills/frontend-ui/SKILL.md +30 -131
  203. package/plugins/deepmodebot/skills/frontend-ui/assets/themes/canvas.css +42 -0
  204. package/plugins/deepmodebot/skills/frontend-ui/assets/themes/editorial.css +39 -0
  205. package/plugins/deepmodebot/skills/frontend-ui/assets/themes/layouts.css +95 -0
  206. package/plugins/deepmodebot/skills/frontend-ui/assets/themes/swiss.css +40 -0
  207. package/plugins/deepmodebot/skills/frontend-ui/assets/themes/tactile.css +41 -0
  208. package/plugins/deepmodebot/skills/frontend-ui/assets/themes/workbench.css +50 -0
  209. package/plugins/deepmodebot/skills/frontend-ui/references/patterns/mobbin-animations.md +49 -0
  210. package/plugins/deepmodebot/skills/frontend-ui/references/patterns/mobbin-shipped-apps.md +46 -24
  211. package/plugins/deepmodebot/skills/frontend-ui/references/patterns/motion-clips.md +27 -258
  212. package/plugins/deepmodebot/skills/frontend-ui/references/patterns/motion-graphics.md +26 -51
  213. package/plugins/deepmodebot/skills/frontend-ui/references/patterns/pinterest-animations.md +22 -195
  214. package/plugins/deepmodebot/skills/frontend-ui/references/playbook/00-art-direction.md +39 -0
  215. package/plugins/deepmodebot/skills/frontend-ui/references/playbook/01-workflow.md +27 -24
  216. package/plugins/deepmodebot/skills/frontend-ui/references/playbook/02-review-rubric.md +23 -17
  217. package/plugins/deepmodebot/skills/frontend-ui/references/playbook/03-ai-tells.md +22 -45
  218. package/plugins/deepmodebot/skills/frontend-ui/references/playbook/04-components.md +11 -0
  219. package/plugins/deepmodebot/skills/frontend-ui/references/playbook/04a-agent-ui.md +32 -152
  220. package/plugins/deepmodebot/skills/frontend-ui/references/playbook/05-motion.md +36 -91
  221. package/plugins/deepmodebot/skills/frontend-ui/references/playbook/05a-motion-graphics.md +14 -120
  222. package/plugins/deepmodebot/skills/frontend-ui/references/playbook/06-typography-layout.md +11 -10
  223. package/plugins/deepmodebot/skills/frontend-ui/references/playbook/06a-color.md +9 -9
  224. package/plugins/deepmodebot/skills/frontend-ui/references/playbook/06b-media-icons-charts.md +19 -0
  225. package/plugins/deepmodebot/skills/frontend-ui/references/playbook/06c-product-shots-craft.md +42 -0
  226. package/plugins/deepmodebot/skills/frontend-ui/references/playbook/07-copy.md +5 -6
  227. package/plugins/deepmodebot/skills/frontend-ui/references/playbook/08-quality-floor.md +28 -56
  228. package/plugins/deepmodebot/skills/frontend-ui/references/playbook/09-steering-agents.md +9 -7
  229. package/plugins/deepmodebot/skills/frontend-ui/scripts/motion_diff.py +259 -0
  230. package/plugins/deepmodebot/skills/frontend-ui/scripts/ui_audit.py +496 -0
  231. package/plugins/deepmodebot/skills/maintain-formal-verification-skill/LICENSE +21 -0
  232. package/plugins/deepmodebot/skills/maintain-formal-verification-skill/NOTICE.md +16 -0
  233. package/plugins/deepmodebot/skills/maintain-formal-verification-skill/SKILL.md +68 -0
  234. package/plugins/deepmodebot/skills/maintain-verification-skill/SKILL.md +1 -1
  235. package/plugins/deepmodebot/skills/office-documents/SKILL.md +24 -0
  236. package/plugins/deepmodebot/skills/office-documents/references/documents-docx-pdf.md +15 -0
  237. package/plugins/deepmodebot/skills/office-documents/references/presentations-pptx.md +15 -0
  238. package/plugins/deepmodebot/skills/office-documents/references/spreadsheets-xlsx.md +15 -0
  239. package/plugins/deepmodebot/skills/office-documents/scripts/doc_audit.py +230 -0
  240. package/plugins/deepmodebot/skills/project-brief/SKILL.md +2 -19
  241. package/plugins/deepmodebot/skills/project-brief/assets/pr-overlap.py +4 -0
  242. package/plugins/deepmodebot/skills/project-brief/assets/sync-roadmap.py +4 -0
  243. package/plugins/deepmodebot/skills/project-brief/references/claim-contract.md +55 -0
  244. package/plugins/deepmodebot/skills/research/SKILL.md +18 -0
  245. package/plugins/deepmodebot/skills/secrets-and-auth/SKILL.md +1 -1
  246. package/plugins/deepmodebot/skills/seo-and-geo/SKILL.md +29 -0
  247. package/plugins/deepmodebot/skills/seo-and-geo/references/geo-and-agentic-web.md +30 -0
  248. package/plugins/deepmodebot/skills/seo-and-geo/references/technical-and-schema.md +25 -0
  249. package/plugins/deepmodebot/skills/seo-and-geo/scripts/seo_audit.py +282 -0
  250. package/plugins/deepmodebot/skills/software-architecture/SKILL.md +2 -2
  251. package/plugins/deepmodebot/skills/software-architecture/references/backend-infrastructure.md +5 -0
  252. package/plugins/deepmodebot/skills/software-architecture/references/monorepos.md +1 -0
  253. package/plugins/deepmodebot/skills/statechart/LICENSE +21 -0
  254. package/plugins/deepmodebot/skills/statechart/NOTICE.md +21 -0
  255. package/plugins/deepmodebot/skills/statechart/SKILL.md +106 -0
  256. package/plugins/deepmodebot/skills/statechart/references/render.md +93 -0
  257. package/plugins/deepmodebot/skills/statechart/references/tooling.md +78 -0
  258. package/plugins/deepmodebot/skills/statechart/scripts/backends/cfg.ts +33 -0
  259. package/plugins/deepmodebot/skills/statechart/scripts/backends/mermaid.ts +249 -0
  260. package/plugins/deepmodebot/skills/statechart/scripts/backends/plain-text.ts +72 -0
  261. package/plugins/deepmodebot/skills/statechart/scripts/backends/report.ts +177 -0
  262. package/plugins/deepmodebot/skills/statechart/scripts/frontends/config.ts +276 -0
  263. package/plugins/deepmodebot/skills/statechart/scripts/frontends/dot.ts +77 -0
  264. package/plugins/deepmodebot/skills/statechart/scripts/frontends/marks.ts +93 -0
  265. package/plugins/deepmodebot/skills/statechart/scripts/frontends/messages.ts +52 -0
  266. package/plugins/deepmodebot/skills/statechart/scripts/frontends/spec.ts +114 -0
  267. package/plugins/deepmodebot/skills/statechart/scripts/frontends/trace.ts +24 -0
  268. package/plugins/deepmodebot/skills/statechart/scripts/frontends/value.ts +166 -0
  269. package/plugins/deepmodebot/skills/statechart/scripts/frontends/verdict.ts +40 -0
  270. package/plugins/deepmodebot/skills/statechart/scripts/frontends/view.ts +119 -0
  271. package/plugins/deepmodebot/skills/statechart/scripts/ir.ts +547 -0
  272. package/plugins/deepmodebot/skills/statechart/scripts/janitor.ts +13 -0
  273. package/plugins/deepmodebot/skills/statechart/scripts/kill.ts +15 -0
  274. package/plugins/deepmodebot/skills/statechart/scripts/package.json +11 -0
  275. package/plugins/deepmodebot/skills/statechart/scripts/passes/annotate.ts +128 -0
  276. package/plugins/deepmodebot/skills/statechart/scripts/passes/label.ts +269 -0
  277. package/plugins/deepmodebot/skills/statechart/scripts/passes/lift.ts +85 -0
  278. package/plugins/deepmodebot/skills/statechart/scripts/passes/loop-check.ts +68 -0
  279. package/plugins/deepmodebot/skills/statechart/scripts/passes/paths.ts +60 -0
  280. package/plugins/deepmodebot/skills/statechart/scripts/passes/reach.ts +135 -0
  281. package/plugins/deepmodebot/skills/statechart/scripts/passes/region-check.ts +97 -0
  282. package/plugins/deepmodebot/skills/statechart/scripts/passes/regions.ts +295 -0
  283. package/plugins/deepmodebot/skills/statechart/scripts/pipeline.ts +76 -0
  284. package/plugins/deepmodebot/skills/statechart/scripts/run.ts +500 -0
  285. package/plugins/deepmodebot/skills/statechart/scripts/statechart +29 -0
  286. package/plugins/deepmodebot/skills/statechart/scripts/statechart.ts +165 -0
  287. package/plugins/deepmodebot/skills/statechart/scripts/test/ConfigOracle.java +63 -0
  288. package/plugins/deepmodebot/skills/statechart/scripts/test/chart.test.ts +1253 -0
  289. package/plugins/deepmodebot/skills/statechart/scripts/test/charts/Braces.mmd +7 -0
  290. package/plugins/deepmodebot/skills/statechart/scripts/test/charts/Escapes.mmd +11 -0
  291. package/plugins/deepmodebot/skills/statechart/scripts/test/charts/Phases.mmd +29 -0
  292. package/plugins/deepmodebot/skills/statechart/scripts/test/cli.test.ts +1344 -0
  293. package/plugins/deepmodebot/skills/statechart/scripts/test/config-fuzz.test.ts +263 -0
  294. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/Counter/ChartRun.out +57 -0
  295. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/Counter/Counter.cfg +3 -0
  296. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/Counter/Counter.tla +10 -0
  297. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/Counter/chart.mmd +9 -0
  298. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/Counter/graph.dot +16 -0
  299. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/Counter/report.md +7 -0
  300. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/Counter/sany.out +2 -0
  301. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/Counter/verdict-1.out +49 -0
  302. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterAction/ChartRun.out +60 -0
  303. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterAction/CounterAction.cfg +4 -0
  304. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterAction/CounterAction.tla +22 -0
  305. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterAction/chart.mmd +26 -0
  306. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterAction/graph.dot +19 -0
  307. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterAction/report.md +20 -0
  308. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterAction/sany.out +2 -0
  309. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterAction/verdict-1.exit +1 -0
  310. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterAction/verdict-1.out +56 -0
  311. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterAction/verdict-2.exit +1 -0
  312. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterAction/verdict-2.out +82 -0
  313. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterAction/verdict-3.out +57 -0
  314. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterDeadlock/ChartRun.out +59 -0
  315. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterDeadlock/CounterDeadlock.cfg +3 -0
  316. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterDeadlock/CounterDeadlock.tla +11 -0
  317. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterDeadlock/chart.mmd +22 -0
  318. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterDeadlock/graph.dot +16 -0
  319. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterDeadlock/report.md +17 -0
  320. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterDeadlock/sany.out +2 -0
  321. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterDeadlock/verdict-1.exit +1 -0
  322. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterDeadlock/verdict-1.out +56 -0
  323. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterDeadlock/verdict-2.exit +1 -0
  324. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterDeadlock/verdict-2.out +77 -0
  325. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterFan/ChartRun.out +69 -0
  326. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterFan/CounterFan.cfg +2 -0
  327. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterFan/CounterFan.tla +11 -0
  328. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterFan/chart.mmd +85 -0
  329. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterFan/graph.dot +70 -0
  330. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterFan/report.md +12 -0
  331. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterFan/sany.out +2 -0
  332. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterFan/verdict-1.exit +1 -0
  333. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterFan/verdict-1.out +67 -0
  334. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterFan/verdict-2.out +57 -0
  335. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterGuard/ChartRun.exit +1 -0
  336. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterGuard/ChartRun.out +85 -0
  337. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterGuard/CounterGuard.cfg +6 -0
  338. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterGuard/CounterGuard.tla +13 -0
  339. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterGuard/chart.mmd +5 -0
  340. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterGuard/graph.dot +10 -0
  341. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterGuard/report.md +31 -0
  342. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterGuard/sany.out +2 -0
  343. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterGuard/verdict-1.exit +1 -0
  344. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterGuard/verdict-1.out +64 -0
  345. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterGuard/verdict-2.exit +1 -0
  346. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterGuard/verdict-2.out +77 -0
  347. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterInitPast/ChartRun.out +55 -0
  348. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterInitPast/CounterInitPast.cfg +3 -0
  349. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterInitPast/CounterInitPast.tla +10 -0
  350. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterInitPast/chart.mmd +12 -0
  351. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterInitPast/graph.dot +6 -0
  352. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterInitPast/report.md +12 -0
  353. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterInitPast/sany.out +2 -0
  354. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterInitPast/verdict-1.exit +1 -0
  355. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterInitPast/verdict-1.out +33 -0
  356. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterInitPast/verdict-2.out +54 -0
  357. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterInitPastHolds/ChartRun.out +54 -0
  358. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterInitPastHolds/CounterInitPastHolds.cfg +3 -0
  359. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterInitPastHolds/CounterInitPastHolds.tla +10 -0
  360. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterInitPastHolds/chart.mmd +1 -0
  361. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterInitPastHolds/graph.dot +6 -0
  362. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterInitPastHolds/report.md +7 -0
  363. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterInitPastHolds/sany.out +2 -0
  364. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterInitPastHolds/verdict-1.out +46 -0
  365. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterInstance/ChartRun.out +59 -0
  366. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterInstance/CounterInstance.cfg +2 -0
  367. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterInstance/CounterInstance.tla +10 -0
  368. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterInstance/CounterSteps.tla +6 -0
  369. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterInstance/chart.mmd +17 -0
  370. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterInstance/graph.dot +15 -0
  371. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterInstance/report.md +14 -0
  372. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterInstance/sany.out +3 -0
  373. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterInstance/verdict-1.exit +1 -0
  374. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterInstance/verdict-1.out +78 -0
  375. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterJump/ChartRun.out +59 -0
  376. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterJump/CounterJump.cfg +3 -0
  377. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterJump/CounterJump.tla +19 -0
  378. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterJump/chart.mmd +26 -0
  379. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterJump/graph.dot +22 -0
  380. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterJump/report.md +12 -0
  381. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterJump/sany.out +2 -0
  382. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterJump/verdict-1.exit +1 -0
  383. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterJump/verdict-1.out +58 -0
  384. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterJump/verdict-2.out +57 -0
  385. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterLoop/ChartRun.out +57 -0
  386. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterLoop/CounterLoop.cfg +2 -0
  387. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterLoop/CounterLoop.tla +11 -0
  388. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterLoop/chart.mmd +17 -0
  389. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterLoop/graph.dot +15 -0
  390. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterLoop/report.md +14 -0
  391. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterLoop/sany.out +2 -0
  392. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterLoop/verdict-1.exit +1 -0
  393. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterLoop/verdict-1.out +76 -0
  394. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterOrder/ChartRun.out +59 -0
  395. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterOrder/CounterOrder.cfg +3 -0
  396. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterOrder/CounterOrder.tla +11 -0
  397. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterOrder/chart.mmd +19 -0
  398. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterOrder/graph.dot +10 -0
  399. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterOrder/report.md +15 -0
  400. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterOrder/sany.out +2 -0
  401. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterOrder/verdict-1.exit +1 -0
  402. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterOrder/verdict-1.out +56 -0
  403. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterOrder/verdict-2.exit +1 -0
  404. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterOrder/verdict-2.out +67 -0
  405. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterRules/ChartRun.out +62 -0
  406. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterRules/CounterRules.cfg +6 -0
  407. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterRules/CounterRules.tla +24 -0
  408. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterRules/Moves.tla +5 -0
  409. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterRules/chart.mmd +22 -0
  410. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterRules/graph.dot +10 -0
  411. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterRules/report.md +23 -0
  412. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterRules/sany.out +3 -0
  413. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterRules/verdict-1.exit +1 -0
  414. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterRules/verdict-1.out +58 -0
  415. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterRules/verdict-2.exit +1 -0
  416. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterRules/verdict-2.out +66 -0
  417. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterRules/verdict-3.exit +1 -0
  418. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterRules/verdict-3.out +74 -0
  419. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterRules/verdict-4.out +59 -0
  420. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterStart/ChartRun.out +58 -0
  421. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterStart/CounterStart.cfg +3 -0
  422. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterStart/CounterStart.tla +15 -0
  423. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterStart/chart.mmd +18 -0
  424. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterStart/graph.dot +13 -0
  425. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterStart/report.md +11 -0
  426. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterStart/sany.out +2 -0
  427. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterStart/verdict-1.exit +1 -0
  428. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterStart/verdict-1.out +33 -0
  429. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterStart/verdict-2.out +57 -0
  430. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterStop/ChartRun.out +57 -0
  431. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterStop/CounterStop.cfg +3 -0
  432. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterStop/CounterStop.tla +15 -0
  433. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterStop/chart.mmd +7 -0
  434. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterStop/graph.dot +13 -0
  435. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterStop/report.md +6 -0
  436. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterStop/sany.out +2 -0
  437. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterStop/verdict-1.out +49 -0
  438. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterTie/ChartRun.out +61 -0
  439. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterTie/CounterTie.cfg +4 -0
  440. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterTie/CounterTie.tla +14 -0
  441. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterTie/chart.mmd +30 -0
  442. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterTie/graph.dot +19 -0
  443. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterTie/report.md +27 -0
  444. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterTie/sany.out +2 -0
  445. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterTie/verdict-1.exit +1 -0
  446. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterTie/verdict-1.out +56 -0
  447. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterTie/verdict-2.exit +1 -0
  448. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterTie/verdict-2.out +64 -0
  449. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterTie/verdict-3.exit +1 -0
  450. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterTie/verdict-3.out +87 -0
  451. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterTie/verdict-4.out +57 -0
  452. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterTieInGraph/ChartRun.out +60 -0
  453. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterTieInGraph/CounterTieInGraph.cfg +3 -0
  454. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterTieInGraph/CounterTieInGraph.tla +12 -0
  455. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterTieInGraph/chart.mmd +23 -0
  456. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterTieInGraph/graph.dot +19 -0
  457. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterTieInGraph/report.md +11 -0
  458. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterTieInGraph/sany.out +2 -0
  459. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterTieInGraph/verdict-1.exit +1 -0
  460. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterTieInGraph/verdict-1.out +56 -0
  461. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterTieInGraph/verdict-2.out +57 -0
  462. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterView/ChartRun.out +61 -0
  463. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterView/CounterView.cfg +4 -0
  464. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterView/CounterView.tla +14 -0
  465. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterView/chart.mmd +23 -0
  466. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterView/graph.dot +19 -0
  467. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterView/report.md +27 -0
  468. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterView/sany.out +2 -0
  469. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterView/verdict-1.exit +1 -0
  470. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterView/verdict-1.out +56 -0
  471. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterView/verdict-2.exit +1 -0
  472. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterView/verdict-2.out +64 -0
  473. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterView/verdict-3.exit +1 -0
  474. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterView/verdict-3.out +87 -0
  475. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterView/verdict-4.out +57 -0
  476. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/CounterView/view.mjs +1 -0
  477. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/DieHard/ChartRun.out +59 -0
  478. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/DieHard/DieHard.cfg +4 -0
  479. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/DieHard/DieHard.tla +38 -0
  480. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/DieHard/chart.mmd +92 -0
  481. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/DieHard/graph.dot +126 -0
  482. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/DieHard/report.md +17 -0
  483. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/DieHard/sany.out +2 -0
  484. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/DieHard/verdict-1.exit +1 -0
  485. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/DieHard/verdict-1.out +91 -0
  486. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/DieHard/verdict-2.out +57 -0
  487. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/FirstRule/ChartRun.out +61 -0
  488. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/FirstRule/FirstRule.cfg +6 -0
  489. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/FirstRule/FirstRule.tla +11 -0
  490. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/FirstRule/chart.mmd +22 -0
  491. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/FirstRule/graph.dot +16 -0
  492. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/FirstRule/report.md +25 -0
  493. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/FirstRule/sany.out +2 -0
  494. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/FirstRule/verdict-1.exit +1 -0
  495. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/FirstRule/verdict-1.out +56 -0
  496. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/FirstRule/verdict-2.exit +1 -0
  497. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/FirstRule/verdict-2.out +64 -0
  498. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/FirstRule/verdict-3.exit +1 -0
  499. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/FirstRule/verdict-3.out +64 -0
  500. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/FirstRule/verdict-4.exit +1 -0
  501. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/FirstRule/verdict-4.out +77 -0
  502. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/HiddenClock/ChartRun.out +57 -0
  503. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/HiddenClock/HiddenClock.cfg +4 -0
  504. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/HiddenClock/HiddenClock.tla +11 -0
  505. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/HiddenClock/chart.mmd +13 -0
  506. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/HiddenClock/graph.dot +12 -0
  507. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/HiddenClock/report.md +11 -0
  508. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/HiddenClock/sany.out +2 -0
  509. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/HiddenClock/verdict-1.exit +1 -0
  510. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/HiddenClock/verdict-1.out +72 -0
  511. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/Login/ChartRun.out +57 -0
  512. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/Login/Login.cfg +3 -0
  513. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/Login/Login.tla +62 -0
  514. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/Login/chart.mmd +28 -0
  515. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/Login/graph.dot +40 -0
  516. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/Login/report.md +7 -0
  517. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/Login/sany.out +1 -0
  518. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/Login/verdict-1.out +47 -0
  519. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/Login/view.mjs +1 -0
  520. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/LoginGuarded/ChartRun.out +57 -0
  521. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/LoginGuarded/LoginGuarded.cfg +2 -0
  522. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/LoginGuarded/LoginGuarded.tla +64 -0
  523. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/LoginGuarded/chart.mmd +28 -0
  524. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/LoginGuarded/graph.dot +37 -0
  525. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/LoginGuarded/report.md +8 -0
  526. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/LoginGuarded/sany.out +1 -0
  527. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/LoginGuarded/verdict-1.out +47 -0
  528. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/LoginGuarded/view.mjs +1 -0
  529. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/LoginParallel/ChartRun.out +60 -0
  530. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/LoginParallel/LoginParallel.cfg +3 -0
  531. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/LoginParallel/LoginParallel.tla +64 -0
  532. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/LoginParallel/chart.mmd +44 -0
  533. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/LoginParallel/graph.dot +58 -0
  534. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/LoginParallel/report.md +17 -0
  535. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/LoginParallel/sany.out +1 -0
  536. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/LoginParallel/verdict-1.exit +1 -0
  537. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/LoginParallel/verdict-1.out +83 -0
  538. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/LoginParallel/verdict-2.out +57 -0
  539. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/LoginParallel/view.mjs +1 -0
  540. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/MediaPlayer/ChartRun.out +60 -0
  541. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/MediaPlayer/MediaPlayer.cfg +3 -0
  542. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/MediaPlayer/MediaPlayer.tla +103 -0
  543. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/MediaPlayer/chart.mmd +43 -0
  544. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/MediaPlayer/graph.dot +93 -0
  545. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/MediaPlayer/report.md +14 -0
  546. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/MediaPlayer/sany.out +1 -0
  547. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/MediaPlayer/verdict-1.exit +1 -0
  548. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/MediaPlayer/verdict-1.out +59 -0
  549. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/MediaPlayer/verdict-2.out +72 -0
  550. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/MediaPlayer/view.mjs +3 -0
  551. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/MediaPlayerFixed/ChartRun.out +57 -0
  552. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/MediaPlayerFixed/MediaPlayerFixed.cfg +2 -0
  553. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/MediaPlayerFixed/MediaPlayerFixed.tla +100 -0
  554. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/MediaPlayerFixed/chart.mmd +31 -0
  555. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/MediaPlayerFixed/graph.dot +85 -0
  556. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/MediaPlayerFixed/report.md +9 -0
  557. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/MediaPlayerFixed/sany.out +1 -0
  558. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/MediaPlayerFixed/verdict-1.out +47 -0
  559. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/MediaPlayerFixed/view.mjs +3 -0
  560. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/MediaPlayerProps/ChartRun.out +59 -0
  561. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/MediaPlayerProps/MediaPlayer.tla +103 -0
  562. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/MediaPlayerProps/MediaPlayerProps.cfg +3 -0
  563. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/MediaPlayerProps/MediaPlayerProps.tla +6 -0
  564. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/MediaPlayerProps/chart.mmd +42 -0
  565. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/MediaPlayerProps/graph.dot +93 -0
  566. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/MediaPlayerProps/report.md +19 -0
  567. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/MediaPlayerProps/sany.out +2 -0
  568. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/MediaPlayerProps/verdict-1.exit +1 -0
  569. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/MediaPlayerProps/verdict-1.out +61 -0
  570. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/MediaPlayerProps/verdict-2.out +59 -0
  571. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/MediaPlayerProps/verdict-3.out +61 -0
  572. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/MediaPlayerProps/verdict-4.exit +1 -0
  573. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/MediaPlayerProps/verdict-4.out +66 -0
  574. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/MediaPlayerProps/verdict-5.exit +1 -0
  575. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/MediaPlayerProps/verdict-5.out +58 -0
  576. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/MediaPlayerProps/verdict-6.out +49 -0
  577. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/MediaPlayerProps/view.mjs +3 -0
  578. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/PickWorker/ChartRun.out +57 -0
  579. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/PickWorker/PickWorker.cfg +6 -0
  580. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/PickWorker/PickWorker.tla +11 -0
  581. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/PickWorker/chart.mmd +5 -0
  582. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/PickWorker/graph.dot +11 -0
  583. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/PickWorker/report.md +7 -0
  584. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/PickWorker/sany.out +5 -0
  585. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/PickWorker/verdict-1.out +70 -0
  586. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/Shadow/ChartRun.out +61 -0
  587. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/Shadow/Shadow.cfg +4 -0
  588. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/Shadow/Shadow.tla +11 -0
  589. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/Shadow/ShadowLib.tla +6 -0
  590. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/Shadow/ShadowSub.tla +3 -0
  591. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/Shadow/chart.mmd +9 -0
  592. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/Shadow/graph.dot +16 -0
  593. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/Shadow/report.md +8 -0
  594. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/Shadow/sany.out +4 -0
  595. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/Shadow/verdict-1.out +65 -0
  596. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/SpacedNames/ChartRun.out +59 -0
  597. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/SpacedNames/SpacedNames.cfg +2 -0
  598. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/SpacedNames/SpacedNames.tla +9 -0
  599. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/SpacedNames/chart.mmd +23 -0
  600. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/SpacedNames/graph.dot +17 -0
  601. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/SpacedNames/report.md +15 -0
  602. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/SpacedNames/sany.out +1 -0
  603. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/SpacedNames/verdict-1.exit +1 -0
  604. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/SpacedNames/verdict-1.out +65 -0
  605. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/SpacedNames/verdict-2.exit +1 -0
  606. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/SpacedNames/verdict-2.out +75 -0
  607. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/TwoPhase/ChartRun.out +69 -0
  608. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/TwoPhase/TwoPhase.cfg +3 -0
  609. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/TwoPhase/TwoPhase.tla +75 -0
  610. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/TwoPhase/chart.mmd +60 -0
  611. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/TwoPhase/graph.dot +297 -0
  612. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/TwoPhase/report.md +20 -0
  613. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/TwoPhase/sany.out +1 -0
  614. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/TwoPhase/verdict-1.exit +1 -0
  615. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/TwoPhase/verdict-1.out +95 -0
  616. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/TwoPhase/verdict-2.out +57 -0
  617. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/TwoPhase/view.mjs +1 -0
  618. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/TwoPhaseFixed/ChartRun.out +57 -0
  619. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/TwoPhaseFixed/TwoPhaseFixed.cfg +3 -0
  620. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/TwoPhaseFixed/TwoPhaseFixed.tla +75 -0
  621. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/TwoPhaseFixed/chart.mmd +37 -0
  622. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/TwoPhaseFixed/graph.dot +223 -0
  623. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/TwoPhaseFixed/report.md +11 -0
  624. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/TwoPhaseFixed/sany.out +1 -0
  625. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/TwoPhaseFixed/verdict-1.out +47 -0
  626. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/TwoPhaseFixed/view.mjs +1 -0
  627. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/TypeGuard/ChartRun.exit +1 -0
  628. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/TypeGuard/ChartRun.out +75 -0
  629. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/TypeGuard/TypeGuard.cfg +5 -0
  630. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/TypeGuard/TypeGuard.tla +11 -0
  631. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/TypeGuard/chart.mmd +18 -0
  632. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/TypeGuard/graph.dot +14 -0
  633. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/TypeGuard/report.md +29 -0
  634. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/TypeGuard/sany.out +2 -0
  635. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/TypeGuard/verdict-1.exit +1 -0
  636. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/TypeGuard/verdict-1.out +64 -0
  637. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/TypeGuard/verdict-2.exit +1 -0
  638. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/TypeGuard/verdict-2.out +75 -0
  639. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/UserNoDeadlock/ChartRun.out +58 -0
  640. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/UserNoDeadlock/UserNoDeadlock.cfg +2 -0
  641. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/UserNoDeadlock/UserNoDeadlock.tla +8 -0
  642. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/UserNoDeadlock/chart.mmd +22 -0
  643. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/UserNoDeadlock/graph.dot +16 -0
  644. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/UserNoDeadlock/report.md +15 -0
  645. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/UserNoDeadlock/sany.out +2 -0
  646. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/UserNoDeadlock/verdict-1.exit +1 -0
  647. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/UserNoDeadlock/verdict-1.out +56 -0
  648. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/UserNoDeadlock/verdict-2.exit +1 -0
  649. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus/UserNoDeadlock/verdict-2.out +77 -0
  650. package/plugins/deepmodebot/skills/statechart/scripts/test/corpus.test.ts +441 -0
  651. package/plugins/deepmodebot/skills/statechart/scripts/test/differential.test.ts +565 -0
  652. package/plugins/deepmodebot/skills/statechart/scripts/test/drawn.ts +20 -0
  653. package/plugins/deepmodebot/skills/statechart/scripts/test/grid/Grid.cfg +2 -0
  654. package/plugins/deepmodebot/skills/statechart/scripts/test/grid/Grid.tla +9 -0
  655. package/plugins/deepmodebot/skills/statechart/scripts/test/grid/sany.out +2 -0
  656. package/plugins/deepmodebot/skills/statechart/scripts/test/java.ts +63 -0
  657. package/plugins/deepmodebot/skills/statechart/scripts/test/labels.ts +648 -0
  658. package/plugins/deepmodebot/skills/statechart/scripts/test/messages.test.ts +226 -0
  659. package/plugins/deepmodebot/skills/statechart/scripts/test/pipeline.test.ts +270 -0
  660. package/plugins/deepmodebot/skills/statechart/scripts/test/plain-tlc.test.ts +255 -0
  661. package/plugins/deepmodebot/skills/statechart/scripts/test/render.test.ts +145 -0
  662. package/plugins/deepmodebot/skills/statechart/scripts/test/tlc-out.test.ts +90 -0
  663. package/plugins/deepmodebot/skills/statechart/scripts/test/tlc.ts +158 -0
  664. package/plugins/deepmodebot/skills/statechart/scripts/tsconfig.json +11 -0
  665. package/plugins/deepmodebot/skills/statechart/scripts/worker.ts +35 -0
  666. package/plugins/deepmodebot/skills/agent-harnesses/assets/sdks/bun.lock +0 -391
  667. package/plugins/deepmodebot/skills/deepmodebot/assets/agents-md/test_agents_md.py +0 -146
  668. package/plugins/deepmodebot/skills/deepmodebot/assets/contain/test_antigravity_guard.py +0 -483
  669. package/plugins/deepmodebot/skills/deepmodebot/assets/contain/test_audit_regressions.py +0 -139
  670. package/plugins/deepmodebot/skills/deepmodebot/assets/contain/test_contain.py +0 -301
  671. package/plugins/deepmodebot/skills/deepmodebot/assets/contain/test_omp_mcp.py +0 -602
  672. package/plugins/deepmodebot/skills/deepmodebot/assets/e2e/test_design.py +0 -69
  673. package/plugins/deepmodebot/skills/deepmodebot/assets/e2e/test_evidence.py +0 -160
  674. package/plugins/deepmodebot/skills/deepmodebot/assets/e2e/test_record.py +0 -180
  675. package/plugins/deepmodebot/skills/deepmodebot/assets/e2e/test_review.py +0 -265
  676. package/plugins/deepmodebot/skills/deepmodebot/assets/git-guardrails/test_git_guard.py +0 -192
  677. package/plugins/deepmodebot/skills/deepmodebot/assets/github-app/test_bot.py +0 -2182
  678. package/plugins/deepmodebot/skills/deepmodebot/assets/github-app/test_brand.py +0 -19
  679. package/plugins/deepmodebot/skills/deepmodebot/assets/github-app/test_local_updates.py +0 -691
  680. package/plugins/deepmodebot/skills/deepmodebot/assets/github-app/test_review_context.py +0 -127
  681. package/plugins/deepmodebot/skills/deepmodebot/assets/github-app/test_workspace_cleanup.py +0 -496
  682. package/plugins/deepmodebot/skills/deepmodebot/assets/loop/test_loop.py +0 -1426
  683. package/plugins/deepmodebot/skills/deepmodebot/assets/loop/test_plan.py +0 -320
  684. package/plugins/deepmodebot/skills/deepmodebot/assets/loop/test_windows_job.py +0 -326
  685. package/plugins/deepmodebot/skills/deepmodebot/assets/perf-audit/test_bench_harness.py +0 -55
  686. package/plugins/deepmodebot/skills/deepmodebot/assets/perf-audit/test_perf_audit.py +0 -53
  687. package/plugins/deepmodebot/skills/deepmodebot/assets/pr-agent/test_diff_coverage.py +0 -94
  688. package/plugins/deepmodebot/skills/deepmodebot/assets/pr-conversation/test_arena.py +0 -610
  689. package/plugins/deepmodebot/skills/deepmodebot/assets/scrape/test_yt_enrich.py +0 -250
  690. package/plugins/deepmodebot/skills/deepmodebot/assets/tournament/test_tournament.py +0 -654
  691. package/plugins/deepmodebot/skills/deepmodebot/assets/workspace-map/test_workspace_map.py +0 -879
@@ -0,0 +1,1645 @@
1
+ #!/usr/bin/env python3
2
+ """Owner-approved agent rules: track every rule an AI agent loads and block the ones the owner never approved.
3
+
4
+ Rules are the instruction and permission files coding agents load (AGENTS.md, CLAUDE.md, .cursor/rules/, skills,
5
+ agent settings; the full list is rule-paths.json) plus `convention` records in the deepmodebot project memory.
6
+ .deepmodebot/rules/ledger.json pins the approved SHA-256 of each rule, .deepmodebot/rules/approved/<sha256> keeps the
7
+ approved bytes, and the history logs every decision. The ledger is signed with an Ed25519 key derived from a passphrase
8
+ only the owner knows: agents can read, review and propose, but approving, rejecting and re-keying need the passphrase.
9
+ Trust is anchored on the committed ledger at HEAD and at the merge-base with the remote default branch.
10
+
11
+ python -B rule_ledger.py status [--root R] [--json]
12
+ python -B rule_ledger.py review [--root R] [--json]
13
+ python -B rule_ledger.py log [--root R] [--json]
14
+ python -B rule_ledger.py propose --item AGENTS.md --file .scratch/AGENTS.draft.md --reason "why" [--by NAME] [--root R]
15
+ python -B rule_ledger.py check [--root R] [--staged] [--base REF] [--json]
16
+ python -B rule_ledger.py guard (hook helper: JSON {"cwd", "paths", "command"} on stdin, JSON verdict out)
17
+ Owner only; each asks for the owner passphrase on the terminal:
18
+ python -B rule_ledger.py init [--root R] [--yes] [--reset]
19
+ python -B rule_ledger.py approve (ID ... | --all) [--root R] [--yes]
20
+ python -B rule_ledger.py reject (ID ... | --all) [--root R] [--yes]
21
+ python -B rule_ledger.py rotate [--root R]
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import argparse
27
+ import datetime
28
+ import difflib
29
+ import fnmatch
30
+ import getpass
31
+ import glob
32
+ import hashlib
33
+ import importlib.util
34
+ import json
35
+ import os
36
+ import posixpath
37
+ import re
38
+ import secrets
39
+ import shlex
40
+ import sqlite3
41
+ import stat
42
+ import subprocess
43
+ import sys
44
+ import tempfile
45
+ import time
46
+ from pathlib import Path
47
+
48
+ sys.dont_write_bytecode = True
49
+
50
+ HERE = Path(__file__).resolve().parent
51
+ SCRIPT = HERE / "rule_ledger.py"
52
+ STORE_REL = ".deepmodebot/rules"
53
+ LEDGER_REL = STORE_REL + "/ledger.json"
54
+ APPROVED_REL = STORE_REL + "/approved"
55
+ PROPOSALS_REL = STORE_REL + "/proposals"
56
+ MEMORY_PREFIX = "memory:"
57
+ LEDGER_VERSION = 1
58
+ KDF_ITERATIONS = 600_000
59
+ MAX_KDF_ITERATIONS = 20_000_000
60
+ MIN_PASSPHRASE = 8
61
+ ROTATE_TAG = b"deepmodebot-rules-rotate:"
62
+ SUBCOMMANDS = frozenset({"status", "review", "log", "propose", "check", "guard", "init", "approve", "reject", "rotate"})
63
+ OWNER_COMMANDS = frozenset({"init", "approve", "reject", "rotate"})
64
+ SKIP_SEGMENTS = frozenset({".git", "node_modules", ".scratch", ".worktrees"})
65
+ NO_WINDOW = getattr(subprocess, "CREATE_NO_WINDOW", 0)
66
+ DIFF_LINES_SHOWN = 40
67
+ COPY_WALK_LIMIT = 2000
68
+
69
+ PUNCT = frozenset("();<>|&\n")
70
+ WRAPPERS = frozenset({"sudo", "doas", "env", "command", "builtin", "exec", "nohup", "time", "timeout", "nice", "ionice",
71
+ "stdbuf", "chronic"})
72
+ WRAPPER_ARG_OPTS = {
73
+ "sudo": frozenset({"-u", "-g", "-C", "-h", "-p", "-U", "-r", "-t", "-D", "-R"}),
74
+ "doas": frozenset({"-u", "-C"}),
75
+ "env": frozenset({"-u", "-C", "-S"}),
76
+ "timeout": frozenset({"-s", "-k", "--signal", "--kill-after"}),
77
+ "nice": frozenset({"-n"}),
78
+ "ionice": frozenset({"-c", "-n", "-p"}),
79
+ }
80
+ ENV_ASSIGN_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*=")
81
+ SHELLS = frozenset({"sh", "bash", "zsh", "dash", "ksh", "fish"})
82
+ SHELL_C_RE = re.compile(r"-[A-Za-z]*c[A-Za-z]*")
83
+ INTERPRETERS = frozenset({"python", "python3", "py", "node", "bun", "deno", "ruby", "perl", "php", "pwsh", "powershell"})
84
+ CODE_FLAGS = frozenset({"--eval", "--print", "-p", "-command", "-r"})
85
+ CODE_FLAG_RE = re.compile(r"-[A-Za-z]*[ce]")
86
+ DELETERS = frozenset({"rm", "unlink", "shred", "truncate", "rmdir", "del", "erase", "remove-item"})
87
+ MOVERS = frozenset({"mv", "move", "ren", "rename", "move-item"})
88
+ COPIERS = frozenset({"cp", "ln", "install", "rsync", "scp", "copy", "copy-item"})
89
+ IN_PLACE = frozenset({"sed", "perl", "ruby"})
90
+ IN_PLACE_FLAG_RE = re.compile(r"--in-place(?:=.*)?|-[A-Za-z]*i\S*")
91
+ FIND_ACTIONS = frozenset({"-exec", "-execdir", "-ok", "-okdir"})
92
+ HEREDOC_RE = re.compile(r"(?<!<)<<-?(?!<)\s*(['\"]?)([A-Za-z_][A-Za-z0-9_]*)\1")
93
+ WRITE_CODE_RE = re.compile(
94
+ r"(?<!stdout\.)(?<!stderr\.)\bwrite|append|unlink|remove|rename|os\.replace|rmtree|rmSync|rmdir|truncate|copy"
95
+ r"|cpSync|createWriteStream|symlink|\bmove\b|Set-Content|Out-File|Add-Content"
96
+ r"|open\s*\([^)]*,\s*['\"][rbt]*[wax+]|mode\s*=\s*['\"][rbt]*[wax+]|['\"]\s*\+?>{1,2}",
97
+ re.IGNORECASE,
98
+ )
99
+ CODE_WORD_RE = re.compile(r"[\w./\\~-]+")
100
+ FALLBACK_WORD_RE = re.compile(r"[^\s'\"`<>|;&()]+")
101
+ FALLBACK_WRITE_RE = re.compile(r">|\b(?:rm|mv|cp|tee|sed|perl|truncate|ln|install|rsync|dd|unlink|shred)\b")
102
+ CONTROL_RE = re.compile("[\x00-\x08\x0b-\x1f\x7f-\x9f\u200b-\u200f\u202a-\u202e\u2066-\u2069]")
103
+
104
+
105
+ class RuleError(Exception):
106
+ """A refused ledger action; the message is shown to the user as is."""
107
+
108
+
109
+ def _load_spec() -> tuple[frozenset, tuple, frozenset]:
110
+ data = json.loads((HERE / "rule-paths.json").read_text(encoding="utf-8"))
111
+ names = frozenset(n.lower() for n in data["names"])
112
+ dirs = tuple("/" + d.lower().strip("/") + "/" for d in data["dirs"])
113
+ files = frozenset(f.lower() for f in data["files"])
114
+ return names, dirs, files
115
+
116
+
117
+ RULE_NAMES, RULE_DIRS, RULE_FILES = _load_spec()
118
+
119
+
120
+ def norm_rel(raw: str) -> str:
121
+ s = str(raw).replace("\\", "/")
122
+ while s.startswith("./"):
123
+ s = s[2:]
124
+ return s.rstrip("/")
125
+
126
+
127
+ def is_store_path(rel: str) -> bool:
128
+ low = norm_rel(rel).lower()
129
+ return low == STORE_REL or low.startswith(STORE_REL + "/")
130
+
131
+
132
+ def is_rule_path(rel: str) -> bool:
133
+ low = norm_rel(rel).lower()
134
+ if not low or low.startswith("/") or is_store_path(low):
135
+ return False
136
+ parts = low.split("/")
137
+ if ".." in parts or any(p in SKIP_SEGMENTS for p in parts[:-1]):
138
+ return False
139
+ if parts[-1] in RULE_NAMES or low in RULE_FILES:
140
+ return True
141
+ padded = "/" + low
142
+ return any(d in padded for d in RULE_DIRS)
143
+
144
+
145
+ def _rule_ish(rel: str) -> bool:
146
+ """A rule path itself, or a folder that holds rule paths (a symlinked `.claude/skills`)."""
147
+ return is_rule_path(rel) or is_rule_path(norm_rel(rel) + "/x")
148
+
149
+
150
+ def _clean(text) -> str:
151
+ """Escape control and bidi characters so agent text cannot hide or rewrite lines on the owner's terminal."""
152
+ return CONTROL_RE.sub(lambda m: f"\\u{ord(m.group()):04x}", str(text))
153
+
154
+
155
+ def _git(root: Path, *args: str, input_bytes: bytes | None = None) -> subprocess.CompletedProcess | None:
156
+ try:
157
+ return subprocess.run(["git", "-C", str(root), *args], input=input_bytes, capture_output=True,
158
+ timeout=60, creationflags=NO_WINDOW, check=False)
159
+ except (OSError, subprocess.TimeoutExpired):
160
+ return None
161
+
162
+
163
+ def _git_text(root: Path, *args: str) -> str | None:
164
+ out = _git(root, *args)
165
+ if out is None or out.returncode != 0:
166
+ return None
167
+ return out.stdout.decode("utf-8", "replace").strip()
168
+
169
+
170
+ def project_root(start) -> Path:
171
+ start = Path(start).expanduser().resolve()
172
+ top = _git_text(start, "rev-parse", "--show-toplevel")
173
+ return Path(top).resolve() if top else start
174
+
175
+
176
+ def _now() -> str:
177
+ return datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
178
+
179
+
180
+ def _sha(data: bytes) -> str:
181
+ return hashlib.sha256(data).hexdigest()
182
+
183
+
184
+ def _eol(data: bytes | None) -> bytes | None:
185
+ """Text with CRLF line ends as LF, the way git stores it, so an autocrlf checkout hashes like the index."""
186
+ return data.replace(b"\r\n", b"\n") if data and b"\r\n" in data and b"\0" not in data else data
187
+
188
+
189
+ def _cat_blobs(root: Path, specs: list[str]) -> dict[str, bytes | None]:
190
+ specs = [s for s in specs if "\n" not in s]
191
+ res: dict[str, bytes | None] = {s: None for s in specs}
192
+ if not specs:
193
+ return res
194
+ proc = _git(root, "cat-file", "--batch", input_bytes="".join(s + "\n" for s in specs).encode("utf-8"))
195
+ if proc is None or proc.returncode != 0:
196
+ return res
197
+ out, pos = proc.stdout, 0
198
+ for spec in specs:
199
+ nl = out.find(b"\n", pos)
200
+ if nl < 0:
201
+ break
202
+ header = out[pos:nl].decode("utf-8", "replace").split()
203
+ pos = nl + 1
204
+ if len(header) != 3 or not header[2].isdigit():
205
+ continue
206
+ size = int(header[2])
207
+ if header[1] == "blob":
208
+ res[spec] = out[pos:pos + size]
209
+ pos += size + 1
210
+ return res
211
+
212
+
213
+ class Source:
214
+ """Rule bytes from the working tree ("work"), the git index ("index", pre-commit), or a commit ("ref").
215
+
216
+ Symlinks read as their link text in every mode, the way git stores them.
217
+ """
218
+
219
+ def __init__(self, root: Path, mode: str = "work", ref: str = ""):
220
+ self.root, self.mode, self.ref = Path(root), mode, ref
221
+
222
+ def read_many(self, rels: list[str]) -> dict[str, bytes | None]:
223
+ if self.mode != "work":
224
+ prefix = ":" if self.mode == "index" else self.ref + ":"
225
+ blobs = _cat_blobs(self.root, [prefix + r for r in rels])
226
+ return {r: _eol(blobs.get(prefix + r)) for r in rels}
227
+ out: dict[str, bytes | None] = {}
228
+ for rel in rels:
229
+ path = self.root / rel
230
+ try:
231
+ if path.is_symlink():
232
+ out[rel] = os.readlink(path).encode("utf-8", "surrogateescape")
233
+ else:
234
+ out[rel] = _eol(path.read_bytes()) if path.is_file() else None
235
+ except OSError:
236
+ out[rel] = None
237
+ return out
238
+
239
+ def read(self, rel: str) -> bytes | None:
240
+ return self.read_many([rel])[rel]
241
+
242
+ def paths(self) -> list[str]:
243
+ """Every file git tracks or would track; gitignored files are personal and stay out of the ledger."""
244
+ if self.mode == "index":
245
+ return self._git_list("ls-files", "-z", "--cached") or []
246
+ if self.mode == "ref":
247
+ return self._git_list("ls-tree", "-r", "-z", "--name-only", self.ref) or []
248
+ listed = self._git_list("ls-files", "-z", "--cached", "--others", "--exclude-standard")
249
+ if listed is None:
250
+ listed = []
251
+ for folder, dirnames, filenames in os.walk(self.root):
252
+ dirnames[:] = [d for d in dirnames if d not in SKIP_SEGMENTS]
253
+ base = Path(folder).relative_to(self.root)
254
+ listed += [(base / n).as_posix() for n in filenames]
255
+ return sorted({p for p in listed if os.path.lexists(self.root / p)})
256
+
257
+ def links(self) -> dict[str, str]:
258
+ """Symlinked rule paths and rule folders: {repo path: link target}."""
259
+ if self.mode == "work":
260
+ out = {}
261
+ for rel in self.paths():
262
+ path = self.root / rel
263
+ if _rule_ish(rel) and path.is_symlink():
264
+ out[rel] = os.readlink(path)
265
+ return out
266
+ args = ("ls-files", "-s", "-z") if self.mode == "index" else ("ls-tree", "-r", "-z", self.ref)
267
+ shas: dict[str, str] = {}
268
+ for entry in self._git_list(*args) or []:
269
+ meta, _, rel = entry.partition("\t")
270
+ parts = meta.split()
271
+ if len(parts) >= 3 and parts[0] == "120000" and _rule_ish(rel):
272
+ shas[rel] = parts[1] if self.mode == "index" else parts[2]
273
+ blobs = _cat_blobs(self.root, sorted(set(shas.values())))
274
+ return {rel: (blobs.get(sha) or b"").decode("utf-8", "surrogateescape") for rel, sha in shas.items()}
275
+
276
+ def _git_list(self, *args: str) -> list[str] | None:
277
+ out = _git(self.root, *args)
278
+ if out is None or out.returncode != 0:
279
+ return None
280
+ return [p for p in out.stdout.decode("utf-8", "surrogateescape").split("\0") if p]
281
+
282
+
283
+ def rule_files(src: Source) -> list[str]:
284
+ return sorted(p for p in src.paths() if is_rule_path(p))
285
+
286
+
287
+ def untracked_links(src: Source) -> list[tuple[str, str]]:
288
+ """Symlinked rules whose target is not itself a rule path: the target's content could change unseen."""
289
+ bad = []
290
+ for rel, target in sorted(src.links().items()):
291
+ t = target.replace("\\", "/")
292
+ resolved = posixpath.normpath(posixpath.join(posixpath.dirname(rel), t))
293
+ outside = posixpath.isabs(t) or re.match(r"^[A-Za-z]:", t) or resolved == ".." or resolved.startswith("../")
294
+ if outside or not _rule_ish(resolved):
295
+ bad.append((rel, target))
296
+ return bad
297
+
298
+
299
+ def memory_rules(root: Path) -> dict[str, bytes]:
300
+ """Unexpired `convention` records in the project memory, keyed `memory:<key>`."""
301
+ pm = _asset_module("dmb_project_memory", "memory/project_memory.py")
302
+ db = pm.resolve_main_root(Path(root)) / ".scratch" / "deepmode-memory.db"
303
+ if not db.is_file():
304
+ return {}
305
+ try:
306
+ conn = sqlite3.connect(f"file:{db}?mode=ro", uri=True, timeout=5.0)
307
+ try:
308
+ rows = conn.execute(
309
+ "SELECT key, content FROM memories WHERE kind = 'convention' AND (expires_at IS NULL OR expires_at > ?)",
310
+ (time.time(),),
311
+ ).fetchall()
312
+ finally:
313
+ conn.close()
314
+ except sqlite3.Error:
315
+ return {}
316
+ return {MEMORY_PREFIX + key: content.encode("utf-8") for key, content in rows}
317
+
318
+
319
+ _MODULES: dict[str, object] = {}
320
+
321
+
322
+ def _asset_module(name: str, rel: str):
323
+ if name not in _MODULES:
324
+ existing = sys.modules.get(name)
325
+ if existing is None:
326
+ spec = importlib.util.spec_from_file_location(name, HERE.parent / rel)
327
+ existing = importlib.util.module_from_spec(spec)
328
+ sys.modules[name] = existing
329
+ spec.loader.exec_module(existing)
330
+ _MODULES[name] = existing
331
+ return _MODULES[name]
332
+
333
+
334
+ def _ed():
335
+ return _asset_module("dmb_reward_guard", "reward-guard/reward_guard.py")
336
+
337
+
338
+ def _expand_seed(seed: bytes) -> tuple[int, bytes]:
339
+ h = hashlib.sha512(seed).digest()
340
+ scalar = int.from_bytes(h[:32], "little")
341
+ scalar &= (1 << 254) - 8
342
+ scalar |= 1 << 254
343
+ return scalar, h[32:]
344
+
345
+
346
+ def _encode_point(point) -> bytes:
347
+ p = _ed()._ED_P
348
+ x, y, z, _ = point
349
+ zi = pow(z, p - 2, p)
350
+ x, y = x * zi % p, y * zi % p
351
+ return (y | ((x & 1) << 255)).to_bytes(32, "little")
352
+
353
+
354
+ def public_key(seed: bytes) -> str:
355
+ ed = _ed()
356
+ scalar, _ = _expand_seed(seed)
357
+ return _encode_point(ed._ed_mul(ed._ED_B, scalar)).hex()
358
+
359
+
360
+ def sign(seed: bytes, msg: bytes) -> str:
361
+ """RFC 8032 Ed25519 signature over msg with the 32-byte private seed."""
362
+ ed = _ed()
363
+ scalar, prefix = _expand_seed(seed)
364
+ pub = _encode_point(ed._ed_mul(ed._ED_B, scalar))
365
+ r = int.from_bytes(hashlib.sha512(prefix + msg).digest(), "little") % ed._ED_L
366
+ big_r = _encode_point(ed._ed_mul(ed._ED_B, r))
367
+ k = int.from_bytes(hashlib.sha512(big_r + pub + msg).digest(), "little") % ed._ED_L
368
+ return (big_r + ((r + k * scalar) % ed._ED_L).to_bytes(32, "little")).hex()
369
+
370
+
371
+ def verify(pubkey_hex: str, msg: bytes, sig_hex: str) -> bool:
372
+ return bool(_ed().ed25519_verify(str(pubkey_hex), msg, str(sig_hex)))
373
+
374
+
375
+ def derive_seed(passphrase: str, owner: dict) -> bytes:
376
+ return hashlib.pbkdf2_hmac("sha256", passphrase.encode("utf-8"), bytes.fromhex(owner["salt"]),
377
+ int(owner["iterations"]), dklen=32)
378
+
379
+
380
+ def _new_owner(passphrase: str) -> tuple[dict, bytes]:
381
+ if len(passphrase) < MIN_PASSPHRASE:
382
+ raise RuleError(f"pick a passphrase of at least {MIN_PASSPHRASE} characters")
383
+ owner = {"kdf": "pbkdf2-sha256", "salt": secrets.token_hex(16), "iterations": KDF_ITERATIONS}
384
+ seed = derive_seed(passphrase, owner)
385
+ owner["pubkey"] = public_key(seed)
386
+ return owner, seed
387
+
388
+
389
+ def _owner_seed(ledger: dict, passphrase: str) -> bytes:
390
+ seed = derive_seed(passphrase, ledger["owner"])
391
+ if public_key(seed) != ledger["owner"]["pubkey"]:
392
+ raise RuleError("wrong passphrase: it does not match the owner key that signed this ledger")
393
+ return seed
394
+
395
+
396
+ def _canonical(ledger: dict) -> bytes:
397
+ body = {k: v for k, v in ledger.items() if k != "signature"}
398
+ return json.dumps(body, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
399
+
400
+
401
+ def parse_ledger(raw: bytes) -> dict:
402
+ try:
403
+ data = json.loads(raw.decode("utf-8"))
404
+ except (UnicodeDecodeError, ValueError) as exc:
405
+ raise RuleError(f"{LEDGER_REL} is not valid JSON: {exc}") from None
406
+ owner = data.get("owner") if isinstance(data, dict) else None
407
+ if (not isinstance(owner, dict) or not isinstance(data.get("approved"), dict)
408
+ or not isinstance(data.get("history"), list)
409
+ or not all(isinstance(owner.get(k), str) for k in ("pubkey", "salt"))
410
+ or not isinstance(owner.get("iterations"), int) or not 0 < owner["iterations"] <= MAX_KDF_ITERATIONS
411
+ or not isinstance(data.get("links", []), list)):
412
+ raise RuleError(f"{LEDGER_REL} is malformed")
413
+ return data
414
+
415
+
416
+ def signature_ok(ledger: dict) -> bool:
417
+ return verify(ledger["owner"]["pubkey"], _canonical(ledger), str(ledger.get("signature") or ""))
418
+
419
+
420
+ def _key_chain_ok(start: str, entries: list, final: str) -> bool:
421
+ key = start
422
+ for entry in entries:
423
+ if not isinstance(entry, dict) or entry.get("action") != "rotate" or entry.get("from") != key:
424
+ continue
425
+ nxt = str(entry.get("to") or "")
426
+ if verify(key, ROTATE_TAG + nxt.encode("utf-8"), str(entry.get("sig") or "")):
427
+ key = nxt
428
+ return key == final
429
+
430
+
431
+ def _resolves(root: Path, ref: str) -> bool:
432
+ return _git_text(root, "rev-parse", "--verify", "--quiet", ref + "^{commit}") is not None
433
+
434
+
435
+ def trust_bases(root: Path) -> list[str]:
436
+ """Commits whose ledger the working one must extend: HEAD and the merge-base with the remote default branch."""
437
+ bases = ["HEAD"] if _resolves(root, "HEAD") else []
438
+ head = _git_text(root, "rev-parse", "HEAD") if bases else None
439
+ default = _git_text(root, "symbolic-ref", "--quiet", "refs/remotes/origin/HEAD")
440
+ for ref in ([default] if default else []) + ["refs/remotes/origin/main", "refs/remotes/origin/master"]:
441
+ if head and _resolves(root, ref):
442
+ mb = _git_text(root, "merge-base", "HEAD", ref)
443
+ if mb and mb != head:
444
+ bases.append(mb)
445
+ break
446
+ return bases
447
+
448
+
449
+ def _trust_problem(ledger: dict, committed_raw: bytes | None, base: str) -> tuple[str, str] | None:
450
+ """(rule, message) when a validly signed ledger does not extend the committed one at `base`, else None."""
451
+ try:
452
+ committed = parse_ledger(committed_raw) if committed_raw is not None else None
453
+ except RuleError:
454
+ return None
455
+ if committed is None:
456
+ return None
457
+ n = len(committed["history"])
458
+ extends = ledger["history"][:n] == committed["history"]
459
+ if extends and _key_chain_ok(committed["owner"]["pubkey"], ledger["history"][n:], ledger["owner"]["pubkey"]):
460
+ return None
461
+ if ledger["owner"]["pubkey"] != committed["owner"]["pubkey"]:
462
+ return "rules-owner-key-changed", f"The owner key differs from {base} with no rotation signed by the old key."
463
+ return "rules-ledger-rollback", f"The rule ledger drops decisions recorded at {base} (an older ledger was restored)."
464
+
465
+
466
+ def _committed(root: Path, bases: list[str]) -> list[tuple[str, bytes | None]]:
467
+ return [(b, Source(root, "ref", b).read(LEDGER_REL)) for b in bases]
468
+
469
+
470
+ def _trust_warning(root: Path, ledger: dict) -> str:
471
+ for base, raw in _committed(root, trust_bases(root)):
472
+ problem = _trust_problem(ledger, raw, base[:12])
473
+ if problem:
474
+ return problem[1]
475
+ return ""
476
+
477
+
478
+ def trusted_approvals(root) -> dict | None:
479
+ """Approved item hashes from a signed ledger that extends the committed ones; None when approval is off.
480
+
481
+ A forged, rolled-back, re-keyed or deleted ledger yields {} so nothing it lists counts as approved.
482
+ """
483
+ root = project_root(root)
484
+ raw = Source(root).read(LEDGER_REL)
485
+ committed = _committed(root, trust_bases(root))
486
+ if raw is None:
487
+ return {} if any(c is not None for _, c in committed) else None
488
+ try:
489
+ ledger = parse_ledger(raw)
490
+ except RuleError:
491
+ return {}
492
+ if not signature_ok(ledger) or any(_trust_problem(ledger, c, b) for b, c in committed):
493
+ return {}
494
+ return dict(ledger["approved"])
495
+
496
+
497
+ def _require_ledger(root: Path) -> dict:
498
+ raw = Source(root).read(LEDGER_REL)
499
+ if raw is None:
500
+ raise RuleError("rule approval is off in this repo; the owner turns it on with `deepmodebot rules init`")
501
+ ledger = parse_ledger(raw)
502
+ if not signature_ok(ledger):
503
+ raise RuleError(f"{LEDGER_REL} does not carry a valid owner signature. "
504
+ f"Restore it from git (`git checkout HEAD -- {STORE_REL}`) before changing rules.")
505
+ return ledger
506
+
507
+
508
+ def _target(root: Path, rel: str, *, final_link_ok: bool = False) -> Path:
509
+ rel = norm_rel(rel)
510
+ parts = rel.split("/")
511
+ if not rel or rel.startswith("/") or ".." in parts or re.match(r"^[A-Za-z]:", rel):
512
+ raise RuleError(f"refusing path outside the repo: {rel!r}")
513
+ probe = root
514
+ for i, part in enumerate(parts):
515
+ probe = probe / part
516
+ if probe.is_symlink() and not (final_link_ok and i == len(parts) - 1):
517
+ raise RuleError(f"refusing to write through the symlink {probe}")
518
+ return probe
519
+
520
+
521
+ def _safe_write(root: Path, rel: str, data: bytes) -> None:
522
+ path = _target(root, rel)
523
+ path.parent.mkdir(parents=True, exist_ok=True)
524
+ fd, tmp = tempfile.mkstemp(dir=str(path.parent), prefix=f".{path.name}.")
525
+ try:
526
+ with os.fdopen(fd, "wb") as handle:
527
+ handle.write(data)
528
+ if path.is_file():
529
+ mode = stat.S_IMODE(path.stat().st_mode)
530
+ else:
531
+ umask = os.umask(0)
532
+ os.umask(umask)
533
+ mode = 0o666 & ~umask
534
+ os.chmod(tmp, mode)
535
+ os.replace(tmp, path)
536
+ except BaseException:
537
+ if os.path.lexists(tmp):
538
+ os.unlink(tmp)
539
+ raise
540
+
541
+
542
+ def _safe_unlink(root: Path, rel: str) -> None:
543
+ path = _target(root, rel, final_link_ok=True)
544
+ if os.path.lexists(path):
545
+ path.unlink()
546
+
547
+
548
+ def _memory_write(root: Path, item: str, data: bytes | None) -> None:
549
+ pm = _asset_module("dmb_project_memory", "memory/project_memory.py")
550
+ key = item[len(MEMORY_PREFIX):]
551
+ db = pm.db_path_for(Path(root))
552
+ with pm.connect_db(db) as conn:
553
+ if data is None:
554
+ conn.execute("DELETE FROM memories WHERE key = ? AND kind = 'convention'", (key,))
555
+ else:
556
+ text, now = data.decode("utf-8"), time.time()
557
+ digest = pm.content_digest("convention", text)
558
+ if conn.execute("SELECT 1 FROM memories WHERE key = ?", (key,)).fetchone():
559
+ conn.execute(
560
+ "UPDATE memories SET kind = 'convention', content = ?, content_hash = ?, updated_at = ?,"
561
+ " expires_at = NULL WHERE key = ?", (text, digest, now, key))
562
+ else:
563
+ conn.execute(
564
+ "INSERT INTO memories(key, kind, priority, content, tags, source, content_hash, tokens_est, hits,"
565
+ " created_at, updated_at, last_accessed, expires_at)"
566
+ " VALUES (?, 'convention', 0, ?, '', 'rule-ledger', ?, ?, 0, ?, ?, ?, NULL)",
567
+ (key, text, digest, pm.estimate_tokens(key, text), now, now, now))
568
+ conn.commit()
569
+
570
+
571
+ def _write_item(root: Path, item: str, data: bytes | None, *, link: bool = False) -> None:
572
+ if item.startswith(MEMORY_PREFIX):
573
+ _memory_write(root, item, data)
574
+ elif data is None:
575
+ _safe_unlink(root, item)
576
+ elif link:
577
+ path = _target(root, item, final_link_ok=True)
578
+ path.parent.mkdir(parents=True, exist_ok=True)
579
+ if os.path.lexists(path):
580
+ path.unlink()
581
+ os.symlink(data.decode("utf-8", "surrogateescape"), path)
582
+ else:
583
+ _safe_write(root, item, data)
584
+
585
+
586
+ def _state(root: Path, src: Source, approved: dict, *, memory: bool) -> tuple[dict, dict]:
587
+ """(current bytes per rule item, approved bytes per approved item); a tampered approved copy reads as None."""
588
+ approved = {i: s for i, s in approved.items() if memory or not i.startswith(MEMORY_PREFIX)}
589
+ files = set(rule_files(src)) | {i for i in approved if not i.startswith(MEMORY_PREFIX)}
590
+ current = src.read_many(sorted(files))
591
+ if memory:
592
+ mem = memory_rules(root)
593
+ current.update(mem)
594
+ current.update({i: None for i in approved if i.startswith(MEMORY_PREFIX) and i not in mem})
595
+ blobs = src.read_many(sorted({f"{APPROVED_REL}/{sha}" for sha in approved.values()}))
596
+ kept = {}
597
+ for item, sha in approved.items():
598
+ blob = blobs.get(f"{APPROVED_REL}/{sha}")
599
+ kept[item] = blob if blob is not None and _sha(blob) == sha else None
600
+ return current, kept
601
+
602
+
603
+ def _text(data: bytes | None) -> str | None:
604
+ if data is None:
605
+ return None
606
+ try:
607
+ return data.decode("utf-8")
608
+ except UnicodeDecodeError:
609
+ return None
610
+
611
+
612
+ def _seg(data: bytes | None) -> list[str]:
613
+ if data is None:
614
+ return []
615
+ text = _text(data)
616
+ return text.splitlines(keepends=True) if text is not None else [f"<binary, {len(data)} bytes, sha256 {_sha(data)[:12]}>\n"]
617
+
618
+
619
+ def _opcodes(old: str, new: str) -> tuple[list[str], list[str], list[tuple]]:
620
+ a, b = old.splitlines(keepends=True), new.splitlines(keepends=True)
621
+ return a, b, difflib.SequenceMatcher(None, a, b, autojunk=False).get_opcodes()
622
+
623
+
624
+ def _merge(a: list[str], b: list[str], ops: list[tuple], take_new: set[int]) -> bytes:
625
+ out: list[str] = []
626
+ for idx, (tag, i1, i2, j1, j2) in enumerate(ops):
627
+ out.extend(b[j1:j2] if tag != "equal" and idx in take_new else a[i1:i2])
628
+ return "".join(out).encode("utf-8")
629
+
630
+
631
+ def _change(item: str, kind: str, old: list[str], new: list[str], seen: dict, *, context: tuple = (), **extra) -> dict:
632
+ """One pending change. Its id hashes the change and its unchanged neighbours, so it survives other decisions."""
633
+ key = (item, "".join(old), "".join(new), *context)
634
+ nth = seen.get(key, 0)
635
+ seen[key] = nth + 1
636
+ cid = _sha("\0".join((*key, str(nth))).encode("utf-8", "surrogateescape"))[:8]
637
+ added = [_clean(line.rstrip("\r\n")) for line in new]
638
+ removed = [_clean(line.rstrip("\r\n")) for line in old]
639
+ summary = next((line.strip() for line in added if line.strip()), "")
640
+ if not summary:
641
+ summary = next(("removed: " + line.strip() for line in removed if line.strip()), "")
642
+ return {"id": cid, "item": item, "kind": kind, "added": len(new), "removed": len(old), "summary": summary[:120],
643
+ "diff": ["- " + line for line in removed] + ["+ " + line for line in added], **extra}
644
+
645
+
646
+ def _item_changes(item: str, new: bytes | None, approved: bool, old: bytes | None, seen: dict) -> list[dict]:
647
+ if not approved:
648
+ return [] if new is None else [_change(item, "new", [], _seg(new), seen)]
649
+ if new is None:
650
+ return [_change(item, "removed", _seg(old) or ["<approved copy missing>\n"], [], seen)]
651
+ old_text, new_text = _text(old), _text(new)
652
+ if old_text is None or new_text is None:
653
+ return [_change(item, "changed", _seg(old) or ["<approved copy missing>\n"], _seg(new), seen)]
654
+ a, b, ops = _opcodes(old_text, new_text)
655
+ return [_change(item, "changed", a[i1:i2], b[j1:j2], seen, block=idx,
656
+ context=(a[i1 - 1] if i1 else "", a[i2] if i2 < len(a) else ""))
657
+ for idx, (tag, i1, i2, j1, j2) in enumerate(ops) if tag != "equal"]
658
+
659
+
660
+ def load_proposals(root: Path) -> list[dict]:
661
+ folder = root / PROPOSALS_REL
662
+ out = []
663
+ for path in sorted(folder.glob("*.json")) if folder.is_dir() and not folder.is_symlink() else []:
664
+ try:
665
+ prop = json.loads(path.read_text(encoding="utf-8"))
666
+ except (OSError, ValueError):
667
+ continue
668
+ if isinstance(prop, dict) and isinstance(prop.get("content"), str) and is_rule_path(str(prop.get("item", ""))):
669
+ out.append({**prop, "file": f"{PROPOSALS_REL}/{path.name}"})
670
+ return out
671
+
672
+
673
+ def pending_changes(root: Path, src: Source, ledger: dict, *, memory: bool = True, proposals: bool = True) -> list[dict]:
674
+ """Every rule change the owner has not decided yet: drift blocks, new/removed rules, memory conventions, proposals."""
675
+ approved = ledger["approved"]
676
+ current, kept = _state(root, src, approved, memory=memory)
677
+ seen: dict = {}
678
+ out: list[dict] = []
679
+ for item in sorted(current):
680
+ new = current[item]
681
+ if item in approved and new is not None and _sha(new) == approved[item]:
682
+ continue
683
+ out += _item_changes(item, new, item in approved, kept.get(item), seen)
684
+ for prop in load_proposals(root) if proposals else []:
685
+ old = kept.get(prop["item"]) if prop["item"] in approved else b""
686
+ new = prop["content"].encode("utf-8")
687
+ old_text = _text(old)
688
+ if old_text is None:
689
+ removed, added = _seg(old) or ["<approved copy missing>\n"], _seg(new)
690
+ else:
691
+ a, b, ops = _opcodes(old_text, prop["content"])
692
+ removed = [line for tag, i1, i2, _, _ in ops if tag != "equal" for line in a[i1:i2]]
693
+ added = [line for tag, _, _, j1, j2 in ops if tag != "equal" for line in b[j1:j2]]
694
+ change = _change(prop["item"], "proposal", removed, added, seen,
695
+ reason=_clean(prop.get("reason") or ""), by=_clean(prop.get("by") or "agent"), file=prop["file"],
696
+ base_sha256=prop.get("base_sha256"), content=prop["content"])
697
+ change["id"] = _clean(prop.get("id") or change["id"])
698
+ change["summary"] = change["reason"][:120] or change["summary"]
699
+ out.append(change)
700
+ return out
701
+
702
+
703
+ def _select(changes: list[dict], ids: list[str], select_all: bool) -> list[dict]:
704
+ if select_all:
705
+ return list(changes)
706
+ chosen, missing = [], []
707
+ for raw in ids:
708
+ hits = [c for c in changes if c["id"] == raw] or [c for c in changes if len(raw) >= 4 and c["id"].startswith(raw)]
709
+ if len(hits) != 1:
710
+ missing.append(raw)
711
+ elif hits[0] not in chosen:
712
+ chosen.append(hits[0])
713
+ if missing:
714
+ raise RuleError(f"no single pending change matches {', '.join(missing)}; run `review` for the current ids")
715
+ if not chosen:
716
+ raise RuleError("name the change ids to decide, or pass --all")
717
+ return chosen
718
+
719
+
720
+ def _approve_bytes(root: Path, ledger: dict, item: str, data: bytes, *, link: bool = False) -> None:
721
+ sha = _sha(data)
722
+ blob = f"{APPROVED_REL}/{sha}"
723
+ existing = _target(root, blob)
724
+ if not (existing.is_file() and _sha(_eol(existing.read_bytes())) == sha):
725
+ _safe_write(root, blob, data)
726
+ ledger["approved"][item] = sha
727
+ links = set(ledger.get("links") or [])
728
+ if link:
729
+ links.add(item)
730
+ else:
731
+ links.discard(item)
732
+ if links:
733
+ ledger["links"] = sorted(links)
734
+ else:
735
+ ledger.pop("links", None)
736
+
737
+
738
+ def _forget(ledger: dict, item: str) -> None:
739
+ ledger["approved"].pop(item, None)
740
+ links = [i for i in ledger.get("links") or [] if i != item]
741
+ if links:
742
+ ledger["links"] = links
743
+ else:
744
+ ledger.pop("links", None)
745
+
746
+
747
+ def _save(root: Path, ledger: dict, seed: bytes) -> None:
748
+ folder = _target(root, APPROVED_REL)
749
+ ledger["version"] = LEDGER_VERSION
750
+ ledger["signature"] = sign(seed, _canonical(ledger))
751
+ _safe_write(root, LEDGER_REL, (json.dumps(ledger, indent=2, sort_keys=True, ensure_ascii=False) + "\n").encode("utf-8"))
752
+ keep = set(ledger["approved"].values())
753
+ for blob in folder.iterdir() if folder.is_dir() else []:
754
+ if blob.name not in keep and blob.is_file() and not blob.is_symlink():
755
+ blob.unlink()
756
+
757
+
758
+ def _history(at: str, action: str, change: dict) -> dict:
759
+ entry = {"at": at, "action": action, "item": change["item"], "change": change["id"], "kind": change["kind"],
760
+ "added": change["added"], "removed": change["removed"], "summary": change["summary"]}
761
+ if change["kind"] == "proposal":
762
+ entry.update(reason=change["reason"], by=change["by"])
763
+ return entry
764
+
765
+
766
+ def _is_link(root: Path, item: str) -> bool:
767
+ return not item.startswith(MEMORY_PREFIX) and (root / item).is_symlink()
768
+
769
+
770
+ def _decide_item(root: Path, ledger: dict, item: str, group: list[dict], current: dict, kept: dict, approve: bool) -> None:
771
+ drift = [c for c in group if c["kind"] != "proposal"]
772
+ if drift:
773
+ new, old = current.get(item), kept.get(item)
774
+ was_link = item in (ledger.get("links") or [])
775
+ blocks = set() if was_link or _is_link(root, item) else {c["block"] for c in drift if "block" in c}
776
+ if blocks:
777
+ a, b, ops = _opcodes(_text(old), _text(new))
778
+ changed = {i for i, op in enumerate(ops) if op[0] != "equal"}
779
+ if approve:
780
+ _approve_bytes(root, ledger, item, _merge(a, b, ops, blocks))
781
+ else:
782
+ _write_item(root, item, _merge(a, b, ops, changed - blocks))
783
+ elif approve:
784
+ if new is None:
785
+ _forget(ledger, item)
786
+ else:
787
+ _approve_bytes(root, ledger, item, new, link=_is_link(root, item))
788
+ else:
789
+ if item in ledger["approved"] and old is None:
790
+ raise RuleError(f"the approved copy of {item} is missing, so it cannot be restored")
791
+ _write_item(root, item, old, link=was_link)
792
+ for prop in (c for c in group if c["kind"] == "proposal"):
793
+ if approve:
794
+ content = prop["content"].encode("utf-8")
795
+ _write_item(root, item, content)
796
+ _approve_bytes(root, ledger, item, content)
797
+ _safe_unlink(root, prop["file"])
798
+
799
+
800
+ def decide(root: Path, ids: list[str], *, approve: bool, passphrase: str, select_all: bool = False) -> list[dict]:
801
+ """Owner approves (or rejects) pending changes; rejecting puts the approved text back."""
802
+ root = Path(root)
803
+ ledger = _require_ledger(root)
804
+ seed = _owner_seed(ledger, passphrase)
805
+ src = Source(root)
806
+ changes = pending_changes(root, src, ledger)
807
+ chosen = _select(changes, ids, select_all)
808
+ current, kept = _state(root, src, ledger["approved"], memory=True)
809
+ if approve:
810
+ for prop in (c for c in chosen if c["kind"] == "proposal"):
811
+ if any(c["item"] == prop["item"] and c["kind"] == "proposal" and c is not prop for c in chosen):
812
+ raise RuleError(f"approve one proposal for {prop['item']} at a time")
813
+ live = current.get(prop["item"])
814
+ if (_sha(live) if live is not None else None) != prop["base_sha256"]:
815
+ raise RuleError(f"{prop['item']} changed after proposal {prop['id']} was made; reject it and propose again")
816
+ by_item: dict[str, list[dict]] = {}
817
+ for change in chosen:
818
+ by_item.setdefault(change["item"], []).append(change)
819
+ at = _now()
820
+ for item, group in by_item.items():
821
+ _decide_item(root, ledger, item, group, current, kept, approve)
822
+ ledger["history"] += [_history(at, "approve" if approve else "reject", c) for c in group]
823
+ _save(root, ledger, seed)
824
+ return chosen
825
+
826
+
827
+ def init_ledger(root: Path, passphrase: str, *, reset: bool = False) -> dict:
828
+ """Owner turns rule approval on: every rule present now becomes the signed, approved baseline."""
829
+ root = Path(root)
830
+ src = Source(root)
831
+ raw = src.read(LEDGER_REL)
832
+ history: list = []
833
+ if raw is not None:
834
+ if not reset:
835
+ raise RuleError("rule approval is already on here; `rotate` changes the passphrase")
836
+ try:
837
+ history = list(parse_ledger(raw)["history"])
838
+ except RuleError:
839
+ history = []
840
+ links = untracked_links(src)
841
+ if links:
842
+ listed = ", ".join(f"{rel} -> {target}" for rel, target in links)
843
+ raise RuleError(f"these rule symlinks point at files that are not rule paths, so their content could change "
844
+ f"unseen: {listed}. Replace each link with the real file (or link it to a rule path), then run init again.")
845
+ owner, seed = _new_owner(passphrase)
846
+ ledger = {"version": LEDGER_VERSION, "owner": owner, "approved": {}, "history": history}
847
+ current, _ = _state(root, src, {}, memory=True)
848
+ for item, data in sorted(current.items()):
849
+ if data is not None:
850
+ _approve_bytes(root, ledger, item, data, link=_is_link(root, item))
851
+ ledger["history"].append({"at": _now(), "action": "reset" if raw is not None else "init",
852
+ "items": sorted(ledger["approved"])})
853
+ _save(root, ledger, seed)
854
+ return ledger
855
+
856
+
857
+ def rotate_key(root: Path, old_passphrase: str, new_passphrase: str) -> dict:
858
+ root = Path(root)
859
+ ledger = _require_ledger(root)
860
+ old_seed = _owner_seed(ledger, old_passphrase)
861
+ owner, seed = _new_owner(new_passphrase)
862
+ ledger["history"].append({"at": _now(), "action": "rotate", "from": ledger["owner"]["pubkey"], "to": owner["pubkey"],
863
+ "sig": sign(old_seed, ROTATE_TAG + owner["pubkey"].encode("utf-8"))})
864
+ ledger["owner"] = owner
865
+ _save(root, ledger, seed)
866
+ return ledger
867
+
868
+
869
+ def propose(root: Path, item: str, content: bytes, reason: str, by: str = "agent") -> dict:
870
+ """Agent-facing: park a full new version of a rule file for the owner to approve. The rule file is untouched."""
871
+ root = Path(root)
872
+ rel = norm_rel(item)
873
+ if not is_rule_path(rel):
874
+ raise RuleError(f"{rel} is not an agent rule file (see rule-paths.json), so it needs no approval")
875
+ if Source(root).read(LEDGER_REL) is None:
876
+ raise RuleError("rule approval is off in this repo, so there is nothing to propose to")
877
+ text = _text(content)
878
+ if text is None:
879
+ raise RuleError("a proposal must be UTF-8 text")
880
+ if not reason.strip():
881
+ raise RuleError("say why the rule is needed with --reason")
882
+ live = Source(root).read(rel)
883
+ pid = "p" + _sha(f"{rel}\0{text}".encode("utf-8", "surrogateescape"))[:7]
884
+ prop = {"id": pid, "item": rel, "base_sha256": _sha(live) if live is not None else None, "content": text,
885
+ "reason": _clean(reason.strip()), "by": _clean(by.strip() or "agent"), "proposed_at": _now()}
886
+ _safe_write(root, f"{PROPOSALS_REL}/{pid}.json", (json.dumps(prop, indent=2, ensure_ascii=False) + "\n").encode("utf-8"))
887
+ return prop
888
+
889
+
890
+ def _finding(severity: str, rule: str, file: str, message: str, fix: str) -> dict:
891
+ return {"severity": severity, "rule": rule, "file": _clean(file), "line": 1, "message": _clean(message), "fix": fix}
892
+
893
+
894
+ def check(root: Path, *, staged: bool = False, base: str | None = None) -> dict:
895
+ """Gate: fail on unapproved rules, a forged, rolled-back or deleted ledger, or a swapped owner key.
896
+
897
+ Without `base` the ledger must extend the committed ones at HEAD and at the merge-base with the remote default
898
+ branch; a CI run passes the protected branch it merges into.
899
+ """
900
+ root = project_root(root)
901
+ src = Source(root, "index" if staged else "work")
902
+ findings: list[dict] = []
903
+ if base and not _resolves(root, base):
904
+ findings.append(_finding("P0", "rules-base-missing", LEDGER_REL,
905
+ f"The base `{base}` does not resolve, so the ledger cannot be checked against it.",
906
+ "Fetch the base branch (`git fetch origin`) or pass a commit that exists."))
907
+ committed = _committed(root, [base] if base else trust_bases(root))
908
+ raw = src.read(LEDGER_REL)
909
+
910
+ def result(enabled: bool) -> dict:
911
+ blocking = [f for f in findings if f["severity"] in ("P0", "P1")]
912
+ return {"enabled": enabled, "ok": not blocking, "root": str(root), "findings": findings}
913
+
914
+ if raw is None:
915
+ for label, committed_raw in committed:
916
+ if committed_raw is not None:
917
+ findings.append(_finding("P0", "rules-ledger-removed", LEDGER_REL,
918
+ f"The owner-signed rule ledger exists at {label[:12]} but is gone now.",
919
+ f"Restore it: `git checkout {label} -- {STORE_REL}`."))
920
+ break
921
+ return result(bool(findings))
922
+ restore = f"Restore it: `git checkout HEAD -- {STORE_REL}`."
923
+ try:
924
+ _target(root, APPROVED_REL)
925
+ except RuleError as exc:
926
+ findings.append(_finding("P0", "rules-store-symlink", STORE_REL, str(exc), restore))
927
+ return result(True)
928
+ try:
929
+ ledger = parse_ledger(raw)
930
+ except RuleError as exc:
931
+ findings.append(_finding("P0", "rules-ledger-forged", LEDGER_REL, str(exc), restore))
932
+ return result(True)
933
+ if not signature_ok(ledger):
934
+ findings.append(_finding("P0", "rules-ledger-forged", LEDGER_REL,
935
+ "The rule ledger was edited without the owner's passphrase (bad signature).", restore))
936
+ return result(True)
937
+ for label, committed_raw in committed:
938
+ problem = _trust_problem(ledger, committed_raw, label[:12])
939
+ if problem:
940
+ findings.append(_finding("P0", problem[0], LEDGER_REL, problem[1],
941
+ f"{restore} Owners change the passphrase with `deepmodebot rules rotate`."))
942
+ break
943
+ approved = {i: s for i, s in ledger["approved"].items() if not (staged and i.startswith(MEMORY_PREFIX))}
944
+ _, kept = _state(root, src, approved, memory=False)
945
+ for item in sorted(i for i in approved if not i.startswith(MEMORY_PREFIX) and kept.get(i) is None):
946
+ findings.append(_finding("P0", "rules-snapshot-missing", f"{APPROVED_REL}/{approved[item]}",
947
+ f"The approved copy of `{item}` is missing or altered.", restore))
948
+ for rel, target in untracked_links(src):
949
+ findings.append(_finding("P1", "rules-symlink-untracked", rel,
950
+ f"`{rel}` links to `{target}`, which is not a rule path, so its content is never approved.",
951
+ "Replace the link with the real file, or link it to a rule path."))
952
+ review = "Owner: `deepmodebot rules review`, then `deepmodebot rules approve <id>` or `reject <id>`."
953
+ for change in pending_changes(root, src, ledger, memory=not staged, proposals=not staged):
954
+ label = f"[{change['id']}] ({change['kind']}, +{change['added']} -{change['removed']}) \"{change['summary']}\""
955
+ if change["kind"] == "proposal":
956
+ findings.append(_finding("P2", "rules-proposal-pending", change["item"],
957
+ f"Rule proposal {label} waits for the owner.", review))
958
+ elif change["item"].startswith(MEMORY_PREFIX):
959
+ findings.append(_finding("P2", "rules-memory-pending", change["item"],
960
+ f"Unapproved memory convention {label} is hidden from recall.", review))
961
+ else:
962
+ findings.append(_finding("P1", "rules-unapproved", change["item"], f"Unapproved rule change {label}",
963
+ review + " Agents never edit rule files; they run `rule_ledger.py propose`."))
964
+ return result(True)
965
+
966
+
967
+ def ledger_enabled(root: Path) -> bool:
968
+ root = Path(root)
969
+ if os.path.lexists(root / LEDGER_REL):
970
+ return True
971
+ return any(raw is not None for _, raw in _committed(root, trust_bases(root)))
972
+
973
+
974
+ def _owning_root(full: str) -> Path | None:
975
+ """The repo (or ledger-holding folder) a path belongs to: nearest ancestor with .git or a rule ledger."""
976
+ cur = full if os.path.isdir(full) else os.path.dirname(full)
977
+ while True:
978
+ if os.path.lexists(os.path.join(cur, ".git")) or os.path.lexists(os.path.join(cur, LEDGER_REL)):
979
+ return Path(cur)
980
+ parent = os.path.dirname(cur)
981
+ if parent == cur:
982
+ return None
983
+ cur = parent
984
+
985
+
986
+ def _locations(cwd: Path, raw: str, removes: bool) -> list[tuple[Path, str]]:
987
+ """(repo root, repo path) for a path as written, with its folders resolved, and (writes only) fully resolved."""
988
+ p = os.path.expanduser(str(raw).strip())
989
+ if not p:
990
+ return []
991
+ joined = (p if os.path.isabs(p) else os.path.join(str(cwd), p)).rstrip("/\\") or os.sep
992
+ variants = [os.path.normpath(joined),
993
+ os.path.join(os.path.realpath(os.path.dirname(joined)), os.path.basename(joined))]
994
+ if not removes:
995
+ variants.append(os.path.realpath(joined))
996
+ out = []
997
+ for full in dict.fromkeys(variants):
998
+ root = _owning_root(full)
999
+ if root is None:
1000
+ continue
1001
+ rel = os.path.relpath(full, str(root)).replace(os.sep, "/")
1002
+ if rel == "..":
1003
+ continue
1004
+ out.append((root, "" if rel == "." else rel))
1005
+ return out
1006
+
1007
+
1008
+ def _rule_reason(rel: str) -> str:
1009
+ return (f"deepmodebot rule approval: `{_clean(rel)}` is an agent rule file, and only the project owner approves rule "
1010
+ f"changes. Write your draft under .scratch/, run `\"{sys.executable or 'python3'}\" -B \"{SCRIPT}\" propose "
1011
+ f"--item {_clean(rel)} --file <draft> --reason \"<why>\"`, and tell the owner to review it with "
1012
+ "`deepmodebot rules review`.")
1013
+
1014
+
1015
+ STORE_REASON = (f"deepmodebot rule approval: {STORE_REL}/ holds the owner-signed rule ledger; agents may not write, "
1016
+ "move or delete anything in it.")
1017
+ HOOK_REASON = ("deepmodebot rule approval: skipping git hooks (`--no-verify`, `commit -n`, `core.hooksPath`) is blocked "
1018
+ "in a repo with owner rule approval, because those hooks run the rule gate.")
1019
+ UNSEEN_REASON = ("deepmodebot rule approval: this command changes files chosen by `xargs` or `$(...)`, so the guard "
1020
+ "cannot tell whether it rewrites agent rule files. Name the files explicitly.")
1021
+
1022
+
1023
+ def _owner_reason(sub: str) -> str:
1024
+ return (f"deepmodebot rule approval: `rules {sub}` is owner-only. Ask the owner to run `deepmodebot rules {sub}` in "
1025
+ "their own terminal. Never ask for, store or type the owner's passphrase.")
1026
+
1027
+
1028
+ def _path_reason(rel: str) -> str | None:
1029
+ if is_store_path(rel):
1030
+ return STORE_REASON
1031
+ return _rule_reason(rel) if is_rule_path(rel) else None
1032
+
1033
+
1034
+ def _dir_has_rules(root: Path, rel: str) -> bool:
1035
+ prefix = rel.lower().strip("/") + "/" if rel.strip("/") else ""
1036
+ if not prefix or (STORE_REL + "/").startswith(prefix):
1037
+ return True
1038
+ return any(p.lower().startswith(prefix) for p in rule_files(Source(root)))
1039
+
1040
+
1041
+ def _literal_reason(cwd: Path, raw: str, removes: bool) -> str | None:
1042
+ for root, rel in _locations(cwd, raw, removes):
1043
+ reason = _path_reason(rel) if rel else None
1044
+ if reason is None and removes and (root / rel).is_dir() and not (root / rel).is_symlink():
1045
+ if ledger_enabled(root) and _dir_has_rules(root, rel):
1046
+ return STORE_REASON if (STORE_REL + "/").startswith(rel.lower().strip("/") + "/") else _rule_reason(rel or ".")
1047
+ if reason and ledger_enabled(root):
1048
+ return reason
1049
+ return None
1050
+
1051
+
1052
+ def _token_reason(cwd: Path, token: str, *, removes: bool = False, expand: bool = True) -> str | None:
1053
+ """Deny reason when writing (or, with removes, deleting/moving) `token` would change a rule in a ledger repo."""
1054
+ reason = _literal_reason(cwd, token, removes)
1055
+ if reason or not expand or not any(ch in token for ch in "*?["):
1056
+ return reason
1057
+ for match in sorted(glob.glob(os.path.join(str(cwd), os.path.expanduser(token))))[:500]:
1058
+ reason = _literal_reason(cwd, match, removes)
1059
+ if reason:
1060
+ return reason
1061
+ return None
1062
+
1063
+
1064
+ def _first(cwd: Path, tokens, *, removes: bool = False) -> str | None:
1065
+ return next(filter(None, (_token_reason(cwd, t, removes=removes) for t in tokens)), None)
1066
+
1067
+
1068
+ def _code_reason(cwd: Path, code: str) -> str | None:
1069
+ if not WRITE_CODE_RE.search(code):
1070
+ return None
1071
+ for word in CODE_WORD_RE.findall(code):
1072
+ reason = _token_reason(cwd, word)
1073
+ if reason:
1074
+ return reason
1075
+ return None
1076
+
1077
+
1078
+ def _base(word: str) -> str:
1079
+ name = os.path.basename(word.replace("\\", "/")).lower()
1080
+ return name[:-4] if name.endswith(".exe") else name
1081
+
1082
+
1083
+ def _owner_command(words: list[str]) -> str | None:
1084
+ for i, word in enumerate(words):
1085
+ name = _base(word)
1086
+ if name in ("rule_ledger.py", "rule_ledger"):
1087
+ sub = next((w for w in words[i + 1:] if w in SUBCOMMANDS), "")
1088
+ return sub if sub in OWNER_COMMANDS else None
1089
+ if name in ("deepmodebot", "deepmodebot.mjs") or name.startswith("deepmodebot@"):
1090
+ rest = [w for w in words[i + 1:] if not w.startswith("-")]
1091
+ if "rules" in rest[:2]:
1092
+ j = rest.index("rules")
1093
+ if j + 1 < len(rest) and rest[j + 1] in OWNER_COMMANDS:
1094
+ return rest[j + 1]
1095
+ return None
1096
+
1097
+
1098
+ def _hook_skip(cwd: Path, words: list[str]) -> str | None:
1099
+ """HOOK_REASON for git commands that skip or reroute hooks in a ledger repo."""
1100
+ if not words or _base(words[0]) != "git":
1101
+ return None
1102
+ args, i, sub, hooks_path = words[1:], 0, "", False
1103
+ while i < len(args):
1104
+ arg = args[i]
1105
+ if arg == "-c" and i + 1 < len(args):
1106
+ hooks_path = hooks_path or args[i + 1].lower().startswith("core.hookspath")
1107
+ i += 2
1108
+ elif arg.startswith("-c") and "core.hookspath" in arg.lower():
1109
+ hooks_path, i = True, i + 1
1110
+ elif arg in ("-C", "--git-dir", "--work-tree", "--namespace") and i + 1 < len(args):
1111
+ i += 2
1112
+ elif arg.startswith("-"):
1113
+ i += 1
1114
+ else:
1115
+ sub = arg
1116
+ break
1117
+ rest = args[i + 1:]
1118
+ skips = hooks_path or "--no-verify" in rest
1119
+ skips = skips or (sub == "commit" and any(re.fullmatch(r"-[A-Za-z]*n[A-Za-z]*", r) for r in rest))
1120
+ reads = {"--get", "--get-all", "--get-regexp", "-l", "--list"} & set(rest)
1121
+ skips = skips or (sub == "config" and not reads and any(r.lower().startswith("core.hookspath") for r in rest))
1122
+ root = _owning_root(str(cwd))
1123
+ return HOOK_REASON if skips and root is not None and ledger_enabled(root) else None
1124
+
1125
+
1126
+ def _copy_targets(cmd: str, cwd: Path, args: list[str], plain: list[str]) -> list[str]:
1127
+ """Paths a cp/mv/ln/rsync-style command writes: the destination, or each source's copy inside it."""
1128
+ if "-t" in args[:-1]:
1129
+ dest = args[args.index("-t") + 1]
1130
+ sources = [a for a in plain if a != dest]
1131
+ elif plain:
1132
+ dest, sources = plain[-1], plain[:-1]
1133
+ else:
1134
+ return []
1135
+ into_dir = ("-t" in args or dest.endswith(("/", "\\")) or len(sources) > 1
1136
+ or os.path.isdir(os.path.join(str(cwd), os.path.expanduser(dest))))
1137
+ if not into_dir:
1138
+ return [dest]
1139
+ out = []
1140
+ for src in sources:
1141
+ src_path = os.path.join(str(cwd), os.path.expanduser(src))
1142
+ name = "" if cmd == "rsync" and src.endswith(("/", "\\")) else os.path.basename(src.rstrip("/\\"))
1143
+ top = os.path.join(dest, name) if name else dest
1144
+ if name:
1145
+ out.append(top)
1146
+ if os.path.isdir(src_path) and not os.path.islink(src_path):
1147
+ for folder, dirnames, filenames in os.walk(src_path):
1148
+ dirnames[:] = [d for d in dirnames if d not in SKIP_SEGMENTS]
1149
+ out += [os.path.join(top, os.path.relpath(os.path.join(folder, f), src_path)) for f in filenames]
1150
+ if len(out) > COPY_WALK_LIMIT:
1151
+ return out
1152
+ return out
1153
+
1154
+
1155
+ def _download_targets(cmd: str, args: list[str]) -> list[str]:
1156
+ short, long_opts = ("o", ("--output",)) if cmd == "curl" else ("O", ("--output-document",))
1157
+ out = []
1158
+ for i, arg in enumerate(args):
1159
+ if (arg in long_opts or re.fullmatch(rf"-[A-Za-z]*{short}", arg)) and i + 1 < len(args):
1160
+ out.append(args[i + 1])
1161
+ elif any(arg.startswith(opt + "=") for opt in long_opts):
1162
+ out.append(arg.split("=", 1)[1])
1163
+ return [t for t in out if t != "-"]
1164
+
1165
+
1166
+ def _find_reason(cwd: Path, args: list[str]) -> str | None:
1167
+ """find with -delete or a writing -exec: deny only when an existing rule file matches its tests."""
1168
+ writes = "-delete" in args
1169
+ for i, arg in enumerate(args[:-1]):
1170
+ if arg in FIND_ACTIONS:
1171
+ prog, rest = _base(args[i + 1]), args[i + 2:i + 8]
1172
+ writes = writes or prog in DELETERS | MOVERS | COPIERS | SHELLS or prog in ("tee", "sd")
1173
+ writes = writes or (prog in IN_PLACE and any(IN_PLACE_FLAG_RE.fullmatch(r) for r in rest))
1174
+ if not writes:
1175
+ return None
1176
+ starts = []
1177
+ for arg in args:
1178
+ if arg.startswith(("-", "(", "!", ")")):
1179
+ break
1180
+ starts.append(arg)
1181
+ names = [args[j + 1].lower() for j, a in enumerate(args[:-1]) if a in ("-name", "-iname")]
1182
+ paths = [args[j + 1].lower() for j, a in enumerate(args[:-1]) if a in ("-path", "-ipath", "-wholename", "-iwholename")]
1183
+ for start in starts or ["."]:
1184
+ for root, rel in _locations(cwd, start, True):
1185
+ if not ledger_enabled(root):
1186
+ continue
1187
+ prefix = rel.strip("/") + "/" if rel.strip("/") else ""
1188
+ for item in rule_files(Source(root)):
1189
+ if not item.lower().startswith(prefix.lower()):
1190
+ continue
1191
+ shown = os.path.join(start, item[len(prefix):]).replace(os.sep, "/").lower()
1192
+ if names and not any(fnmatch.fnmatchcase(item.rsplit("/", 1)[-1].lower(), n) for n in names):
1193
+ continue
1194
+ if paths and not any(fnmatch.fnmatchcase(shown, p) for p in paths):
1195
+ continue
1196
+ return _rule_reason(item)
1197
+ return None
1198
+
1199
+
1200
+ def _tokenize(text: str) -> list[str] | None:
1201
+ lex = shlex.shlex(text, posix=True, punctuation_chars="();<>|&\n")
1202
+ lex.whitespace = " \t\r"
1203
+ lex.whitespace_split = True
1204
+ lex.commenters = ""
1205
+ try:
1206
+ return list(lex)
1207
+ except ValueError:
1208
+ return None
1209
+
1210
+
1211
+ def _split_simple(tokens: list[str]) -> list[list[str]]:
1212
+ cmds, cur = [], []
1213
+ for tok in tokens:
1214
+ if tok and set(tok) <= PUNCT and ">" not in tok and "<" not in tok:
1215
+ cmds.append(cur)
1216
+ cur = []
1217
+ else:
1218
+ cur.append(tok)
1219
+ cmds.append(cur)
1220
+ return [c for c in cmds if c]
1221
+
1222
+
1223
+ def _simple_reason(cwd: Path, toks: list[str], depth: int) -> str | None:
1224
+ words: list[str] = []
1225
+ targets: list[str] = []
1226
+ i = 0
1227
+ while i < len(toks):
1228
+ tok = toks[i]
1229
+ nxt = toks[i + 1] if i + 1 < len(toks) else ""
1230
+ if tok and set(tok) <= PUNCT:
1231
+ if ">" in tok and not (tok.endswith("&") and re.fullmatch(r"\d+|-", nxt)):
1232
+ targets.append(nxt)
1233
+ if words and words[-1].isdigit():
1234
+ words.pop()
1235
+ i += 2
1236
+ continue
1237
+ words.append(tok)
1238
+ i += 1
1239
+ via_xargs = False
1240
+ while words:
1241
+ name = _base(words[0])
1242
+ if ENV_ASSIGN_RE.match(words[0]):
1243
+ words.pop(0)
1244
+ continue
1245
+ if name == "xargs":
1246
+ via_xargs = True
1247
+ elif name not in WRAPPERS:
1248
+ break
1249
+ words.pop(0)
1250
+ while words and words[0].startswith("-"):
1251
+ if words.pop(0) in WRAPPER_ARG_OPTS.get(name, ()) and words:
1252
+ words.pop(0)
1253
+ if name == "timeout" and words:
1254
+ words.pop(0)
1255
+ owner = _owner_command(words)
1256
+ if owner:
1257
+ return _owner_reason(owner)
1258
+ hook = _hook_skip(cwd, words)
1259
+ if hook:
1260
+ return hook
1261
+ reason = _first(cwd, targets)
1262
+ if reason or not words:
1263
+ return reason
1264
+ cmd, args = _base(words[0]), words[1:]
1265
+ plain = [a for a in args if not a.startswith("-")]
1266
+ in_place = (cmd in IN_PLACE and any(IN_PLACE_FLAG_RE.fullmatch(a) for a in args)) or (
1267
+ cmd in ("awk", "gawk") and "inplace" in args)
1268
+ writer = in_place or cmd in DELETERS | MOVERS | COPIERS or cmd in ("tee", "sd", "dd")
1269
+ unseen = via_xargs or any(a == "$" or "$(" in a or "`" in a for a in args)
1270
+ if writer and unseen:
1271
+ root = _owning_root(str(cwd))
1272
+ if root is not None and ledger_enabled(root):
1273
+ return UNSEEN_REASON
1274
+ if cmd == "git" and plain[:1] in (["rm"], ["mv"]):
1275
+ return _first(cwd, plain[1:], removes=True)
1276
+ if cmd in DELETERS:
1277
+ return _first(cwd, plain, removes=True)
1278
+ if cmd in MOVERS:
1279
+ sources = [a for a in plain if a != args[args.index("-t") + 1]] if "-t" in args[:-1] else plain[:-1]
1280
+ return _first(cwd, sources, removes=True) or _first(cwd, _copy_targets(cmd, cwd, args, plain))
1281
+ if cmd in ("tee", "sd") or in_place:
1282
+ return _first(cwd, plain)
1283
+ if cmd in COPIERS:
1284
+ return _first(cwd, _copy_targets(cmd, cwd, args, plain))
1285
+ if cmd == "dd":
1286
+ return _first(cwd, (a[3:] for a in args if a.startswith("of=")))
1287
+ if cmd in ("curl", "wget"):
1288
+ return _first(cwd, _download_targets(cmd, args))
1289
+ if cmd == "find":
1290
+ return _find_reason(cwd, args)
1291
+ if cmd in SHELLS:
1292
+ flag = next((j for j, a in enumerate(args[:-1]) if SHELL_C_RE.fullmatch(a)), None)
1293
+ return _shell_reason(cwd, args[flag + 1], depth + 1) if flag is not None else None
1294
+ if cmd == "eval":
1295
+ return _shell_reason(cwd, " ".join(args), depth + 1)
1296
+ if cmd in INTERPRETERS:
1297
+ flags = [j for j, a in enumerate(args[:-1]) if a.lower() in CODE_FLAGS or CODE_FLAG_RE.fullmatch(a)]
1298
+ return next(filter(None, (_code_reason(cwd, args[j + 1]) for j in flags)), None)
1299
+ return None
1300
+
1301
+
1302
+ def _chain_reason(cwd: Path, tokens: list[str], depth: int) -> str | None:
1303
+ cur = cwd
1304
+ for simple in _split_simple(tokens):
1305
+ if _base(simple[0]) in ("cd", "pushd") and len(simple) > 1 and simple[1] != "-":
1306
+ cur = Path(os.path.normpath(os.path.join(str(cur), os.path.expanduser(simple[1]))))
1307
+ continue
1308
+ reason = _simple_reason(cur, simple, depth)
1309
+ if reason:
1310
+ return reason
1311
+ return None
1312
+
1313
+
1314
+ def _split_heredocs(command: str) -> tuple[list[str], list[tuple[str, str]]]:
1315
+ lines = command.replace("\\\r\n", " ").replace("\\\n", " ").splitlines()
1316
+ kept: list[str] = []
1317
+ bodies: list[tuple[str, str]] = []
1318
+ i = 0
1319
+ while i < len(lines):
1320
+ line = lines[i]
1321
+ kept.append(line)
1322
+ i += 1
1323
+ for match in HEREDOC_RE.finditer(line):
1324
+ body = []
1325
+ while i < len(lines) and lines[i].strip() != match.group(2):
1326
+ body.append(lines[i])
1327
+ i += 1
1328
+ i += 1
1329
+ bodies.append((line, "\n".join(body)))
1330
+ return kept, bodies
1331
+
1332
+
1333
+ def _shell_reason(cwd: Path, command: str, depth: int = 0) -> str | None:
1334
+ if depth > 4:
1335
+ return None
1336
+ lines, bodies = _split_heredocs(command)
1337
+ tokens = _tokenize("\n".join(lines))
1338
+ if tokens is not None:
1339
+ reason = _chain_reason(cwd, tokens, depth)
1340
+ if reason:
1341
+ return reason
1342
+ else:
1343
+ for line in lines:
1344
+ line_tokens = _tokenize(line)
1345
+ if line_tokens is not None:
1346
+ reason = _chain_reason(cwd, line_tokens, depth)
1347
+ elif FALLBACK_WRITE_RE.search(line):
1348
+ reason = next(filter(None, (_token_reason(cwd, w) for w in FALLBACK_WORD_RE.findall(line))), None)
1349
+ else:
1350
+ reason = None
1351
+ if reason:
1352
+ return reason
1353
+ for owner_line, body in bodies:
1354
+ names = {_base(t) for t in _tokenize(owner_line) or []}
1355
+ if names & SHELLS:
1356
+ reason = _shell_reason(cwd, body, depth + 1)
1357
+ elif names & INTERPRETERS:
1358
+ reason = _code_reason(cwd, body)
1359
+ else:
1360
+ reason = None
1361
+ if reason:
1362
+ return reason
1363
+ return None
1364
+
1365
+
1366
+ def guard(cwd, *, paths=(), command: str = "") -> str | None:
1367
+ """Hook verdict: why to deny a tool call that writes a rule file or the ledger in a repo with rule approval on,
1368
+ skips its git hooks, or runs an owner-only rule command anywhere. None allows it."""
1369
+ cwd = Path(cwd).expanduser().resolve()
1370
+ for raw in paths:
1371
+ reason = _token_reason(cwd, raw, expand=False) if isinstance(raw, str) else None
1372
+ if reason:
1373
+ return reason
1374
+ return _shell_reason(cwd, command) if command else None
1375
+
1376
+
1377
+ def status(root: Path) -> dict:
1378
+ root = project_root(root)
1379
+ src = Source(root)
1380
+ raw = src.read(LEDGER_REL)
1381
+ committed = _committed(root, trust_bases(root))
1382
+ if raw is None:
1383
+ if all(c is None for _, c in committed):
1384
+ return {"enabled": False, "root": str(root), "rule_files": rule_files(src)}
1385
+ return {"enabled": True, "root": str(root), "problem": "the committed rule ledger was deleted from the working tree",
1386
+ "items": [], "pending": 0, "proposals": []}
1387
+ ledger = parse_ledger(raw)
1388
+ if not signature_ok(ledger):
1389
+ return {"enabled": True, "root": str(root), "items": [], "pending": 0, "proposals": [],
1390
+ "problem": "the ledger was edited without the owner passphrase (bad signature)"}
1391
+ problem = next((p[1] for p in (_trust_problem(ledger, c, b[:12]) for b, c in committed) if p), "")
1392
+ links = untracked_links(src)
1393
+ if links and not problem:
1394
+ problem = "rule symlinks point outside the rule paths: " + ", ".join(f"{r} -> {t}" for r, t in links)
1395
+ changes = pending_changes(root, src, ledger)
1396
+ last: dict[str, str] = {}
1397
+ for entry in ledger["history"]:
1398
+ if entry.get("action") == "approve":
1399
+ last[entry.get("item", "")] = entry.get("at", "")
1400
+ elif entry.get("action") in ("init", "reset"):
1401
+ last.update({i: entry.get("at", "") for i in entry.get("items", [])})
1402
+ drift = [c for c in changes if c["kind"] != "proposal"]
1403
+ rows = []
1404
+ for item in sorted(set(ledger["approved"]) | {c["item"] for c in drift}):
1405
+ mine = [c for c in drift if c["item"] == item]
1406
+ state = mine[0]["kind"] if mine and mine[0]["kind"] in ("new", "removed") else ("changed" if mine else "approved")
1407
+ rows.append({"item": item, "state": state, "pending": len(mine), "approved_at": last.get(item, "")})
1408
+ return {"enabled": True, "root": str(root), "problem": problem, "owner_key": ledger["owner"]["pubkey"],
1409
+ "items": rows, "pending": len(changes), "proposals": [c for c in changes if c["kind"] == "proposal"]}
1410
+
1411
+
1412
+ def _print_changes(changes: list[dict]) -> None:
1413
+ for c in changes:
1414
+ where = "memory convention " + c["item"][len(MEMORY_PREFIX):] if c["item"].startswith(MEMORY_PREFIX) else c["item"]
1415
+ extra = f" by {c['by']}: {c['reason']}" if c["kind"] == "proposal" else ""
1416
+ print(f"[{c['id']}] {_clean(where)} {c['kind']} +{c['added']} -{c['removed']}{extra}")
1417
+ for line in c["diff"][:DIFF_LINES_SHOWN]:
1418
+ print(" " + line)
1419
+ if len(c["diff"]) > DIFF_LINES_SHOWN:
1420
+ print(f" ... {len(c['diff']) - DIFF_LINES_SHOWN} more lines")
1421
+
1422
+
1423
+ def _confirm(question: str, yes: bool) -> bool:
1424
+ if yes:
1425
+ return True
1426
+ try:
1427
+ return input(f"{question} [y/N] ").strip().lower() in ("y", "yes")
1428
+ except EOFError:
1429
+ return False
1430
+
1431
+
1432
+ def _ask_new_passphrase() -> str:
1433
+ first = getpass.getpass("New owner passphrase (8+ characters; never give it to an AI agent): ")
1434
+ if getpass.getpass("Repeat the passphrase: ") != first:
1435
+ raise RuleError("the two passphrases differ")
1436
+ return first
1437
+
1438
+
1439
+ def _warn_untrusted(root: Path, ledger: dict) -> None:
1440
+ warning = _trust_warning(root, ledger)
1441
+ if warning:
1442
+ print(f"WARNING: {LEDGER_REL} cannot be trusted: {warning.rstrip('.')}. "
1443
+ f"Restore it with `git checkout HEAD -- {STORE_REL}`.")
1444
+
1445
+
1446
+ def _cmd_status(root: Path, as_json: bool) -> int:
1447
+ res = status(root)
1448
+ if as_json:
1449
+ print(json.dumps(res, indent=2))
1450
+ return 0
1451
+ if not res["enabled"]:
1452
+ print(f"Rule approval is off in {root}. Rule files agents load here ({len(res['rule_files'])}):")
1453
+ for item in res["rule_files"]:
1454
+ print(f" {_clean(item)}")
1455
+ print("The owner turns approval on with `deepmodebot rules init`.")
1456
+ return 0
1457
+ if res["problem"]:
1458
+ print(f"WARNING: {LEDGER_REL} cannot be trusted: {_clean(res['problem']).rstrip('.')}. "
1459
+ f"Restore it with `git checkout HEAD -- {STORE_REL}`.")
1460
+ if not res["items"]:
1461
+ return 1
1462
+ approved = sum(1 for r in res["items"] if r["state"] == "approved")
1463
+ print(f"Rule ledger for {root}: {approved} approved, {res['pending']} pending (owner key {res['owner_key'][:16]})")
1464
+ for row in res["items"]:
1465
+ note = f" {row['pending']} unapproved change(s)" if row["state"] == "changed" else ""
1466
+ when = f" approved {row['approved_at']}" if row["state"] == "approved" and row["approved_at"] else ""
1467
+ print(f" {row['state'].upper():9} {_clean(row['item'])}{note}{when}")
1468
+ for prop in res["proposals"]:
1469
+ print(f" PROPOSAL {_clean(prop['item'])} [{prop['id']}] by {prop['by']}: {prop['reason']}")
1470
+ if res["pending"]:
1471
+ print("Review with `deepmodebot rules review`; decide with `deepmodebot rules approve <id>` or `reject <id>`.")
1472
+ return 0
1473
+
1474
+
1475
+ def _cmd_review(root: Path, as_json: bool) -> int:
1476
+ ledger = _require_ledger(root)
1477
+ changes = pending_changes(root, Source(root), ledger)
1478
+ if as_json:
1479
+ print(json.dumps(changes, indent=2))
1480
+ return 0
1481
+ _warn_untrusted(root, ledger)
1482
+ if not changes:
1483
+ print("No pending rule changes.")
1484
+ else:
1485
+ _print_changes(changes)
1486
+ print(f"{len(changes)} pending. Owner: `deepmodebot rules approve <id> ...` or `deepmodebot rules reject <id> ...` "
1487
+ "(`--all` for everything).")
1488
+ return 0
1489
+
1490
+
1491
+ def _cmd_log(root: Path, as_json: bool) -> int:
1492
+ ledger = _require_ledger(root)
1493
+ history = ledger["history"]
1494
+ if as_json:
1495
+ print(json.dumps(history, indent=2))
1496
+ return 0
1497
+ _warn_untrusted(root, ledger)
1498
+ for e in history:
1499
+ if e.get("action") in ("init", "reset"):
1500
+ print(f"{e.get('at')} {e['action']:7} baseline of {len(e.get('items', []))} rule(s)")
1501
+ elif e.get("action") == "rotate":
1502
+ print(f"{e.get('at')} rotate owner key {str(e.get('from'))[:16]} -> {str(e.get('to'))[:16]}")
1503
+ else:
1504
+ by = f" (proposed by {e.get('by', 'agent')})" if e.get("kind") == "proposal" else ""
1505
+ print(_clean(f"{e.get('at')} {e.get('action', '?'):7} {e.get('item')} [{e.get('change')}] {e.get('kind')} "
1506
+ f"+{e.get('added')} -{e.get('removed')} {e.get('summary', '')}{by}"))
1507
+ return 0
1508
+
1509
+
1510
+ def _cmd_decide(root: Path, ids: list[str], select_all: bool, approve: bool, yes: bool) -> int:
1511
+ ledger = _require_ledger(root)
1512
+ changes = pending_changes(root, Source(root), ledger)
1513
+ if select_all and not changes:
1514
+ print("No pending rule changes.")
1515
+ return 0
1516
+ chosen = _select(changes, ids, select_all)
1517
+ _warn_untrusted(root, ledger)
1518
+ _print_changes(chosen)
1519
+ verb = "Approve" if approve else "Reject"
1520
+ if not _confirm(f"{verb} these {len(chosen)} change(s)?", yes):
1521
+ print("Nothing changed.")
1522
+ return 1
1523
+ done = decide(root, [c["id"] for c in chosen], approve=approve, passphrase=getpass.getpass("Owner passphrase: "))
1524
+ if approve:
1525
+ print(f"Approved {len(done)} change(s). Commit {STORE_REL}/ with the rule files to record it.")
1526
+ else:
1527
+ print(f"Rejected {len(done)} change(s); the rules are back to their approved text. Commit {STORE_REL}/ to record it.")
1528
+ return 0
1529
+
1530
+
1531
+ def _cmd_init(root: Path, yes: bool, reset: bool) -> int:
1532
+ src = Source(root)
1533
+ items = [i for i, d in _state(root, src, {}, memory=True)[0].items() if d is not None]
1534
+ print(f"Turning on rule approval in {root}. These {len(items)} rules become the approved baseline:")
1535
+ for item in sorted(items):
1536
+ print(f" {_clean(item)}")
1537
+ if not _confirm("Approve all of them exactly as they are now?", yes):
1538
+ print("Nothing changed. Fix or remove unwanted rules first, then run init again.")
1539
+ return 1
1540
+ init_ledger(root, _ask_new_passphrase(), reset=reset)
1541
+ print(f"Rule approval is on. Commit {STORE_REL}/ so every clone and CI run enforces it.")
1542
+ return 0
1543
+
1544
+
1545
+ def _cmd_rotate(root: Path) -> int:
1546
+ old = getpass.getpass("Current owner passphrase: ")
1547
+ _owner_seed(_require_ledger(root), old)
1548
+ rotate_key(root, old, _ask_new_passphrase())
1549
+ print(f"Owner key rotated. Commit {STORE_REL}/ to record it.")
1550
+ return 0
1551
+
1552
+
1553
+ def _cmd_check(root: Path, staged: bool, base: str | None, as_json: bool) -> int:
1554
+ res = check(root, staged=staged, base=base)
1555
+ if as_json:
1556
+ print(json.dumps(res, indent=2))
1557
+ elif res["enabled"]:
1558
+ print(f"rule-gate [{'OK' if res['ok'] else 'BLOCKED'}]: {len(res['findings'])} finding(s)")
1559
+ for f in res["findings"]:
1560
+ print(f" {f['file']} [{f['severity']}:{f['rule']}] {f['message']} -> {f['fix']}")
1561
+ else:
1562
+ print("rule-gate [OFF]: no owner rule ledger in this repo")
1563
+ return 0 if res["ok"] else 1
1564
+
1565
+
1566
+ def _cmd_guard() -> int:
1567
+ try:
1568
+ req = json.loads(sys.stdin.read() or "{}")
1569
+ except ValueError:
1570
+ req = {}
1571
+ req = req if isinstance(req, dict) else {}
1572
+ cwd = req.get("cwd") or os.getcwd()
1573
+ paths = [p for p in req.get("paths") or [] if isinstance(p, str)]
1574
+ reason = guard(cwd, paths=paths, command=str(req.get("command") or ""))
1575
+ print(json.dumps({"block": bool(reason), "reason": reason or ""}))
1576
+ return 0
1577
+
1578
+
1579
+ def build_parser() -> argparse.ArgumentParser:
1580
+ p = argparse.ArgumentParser(description="Owner-approved agent rules: track, review and sign off every rule AI agents load.")
1581
+ sub = p.add_subparsers(dest="cmd", required=True)
1582
+ for name, text in (("status", "List tracked rules and what waits for approval."),
1583
+ ("review", "Show every pending rule change with its id and diff."),
1584
+ ("log", "Show the signed decision history.")):
1585
+ sp = sub.add_parser(name, help=text)
1586
+ sp.add_argument("--root", default=".")
1587
+ sp.add_argument("--json", action="store_true")
1588
+ sp = sub.add_parser("propose", help="Agents: park a new version of a rule file for the owner.")
1589
+ sp.add_argument("--root", default=".")
1590
+ sp.add_argument("--item", required=True, help="Repo-relative rule file, e.g. AGENTS.md.")
1591
+ sp.add_argument("--file", required=True, help="Draft holding the full new file text.")
1592
+ sp.add_argument("--reason", required=True)
1593
+ sp.add_argument("--by", default="agent", help="Who proposes (harness or agent name).")
1594
+ sp = sub.add_parser("check", help="Gate: exit 1 on unapproved rules or a tampered ledger.")
1595
+ sp.add_argument("--root", default=".")
1596
+ sp.add_argument("--staged", action="store_true", help="Check the git index (pre-commit).")
1597
+ sp.add_argument("--base", default=None,
1598
+ help="Commit whose ledger this one must extend (default: HEAD and the merge-base with origin's default branch).")
1599
+ sp.add_argument("--json", action="store_true")
1600
+ sub.add_parser("guard", help="Hook helper: JSON request on stdin, JSON verdict on stdout.")
1601
+ sp = sub.add_parser("init", help="Owner: turn approval on; current rules become the signed baseline.")
1602
+ sp.add_argument("--root", default=".")
1603
+ sp.add_argument("--yes", action="store_true")
1604
+ sp.add_argument("--reset", action="store_true", help="Replace a ledger whose passphrase is lost (history kept).")
1605
+ for name in ("approve", "reject"):
1606
+ sp = sub.add_parser(name, help=f"Owner: {name} pending changes by id.")
1607
+ sp.add_argument("ids", nargs="*")
1608
+ sp.add_argument("--all", action="store_true")
1609
+ sp.add_argument("--root", default=".")
1610
+ sp.add_argument("--yes", action="store_true")
1611
+ sp = sub.add_parser("rotate", help="Owner: change the passphrase (signed by the old key).")
1612
+ sp.add_argument("--root", default=".")
1613
+ return p
1614
+
1615
+
1616
+ def main(argv: list[str] | None = None) -> int:
1617
+ args = build_parser().parse_args(argv)
1618
+ if args.cmd == "guard":
1619
+ return _cmd_guard()
1620
+ root = project_root(args.root)
1621
+ try:
1622
+ if args.cmd in ("status", "review", "log"):
1623
+ return {"status": _cmd_status, "review": _cmd_review, "log": _cmd_log}[args.cmd](root, args.json)
1624
+ if args.cmd == "propose":
1625
+ prop = propose(root, args.item, Path(args.file).read_bytes(), args.reason, args.by)
1626
+ print(f"Proposed [{prop['id']}] for {prop['item']}. The rule file is unchanged until the owner runs "
1627
+ f"`deepmodebot rules review` and `deepmodebot rules approve {prop['id']}`.")
1628
+ return 0
1629
+ if args.cmd == "check":
1630
+ return _cmd_check(root, args.staged, args.base, args.json)
1631
+ if args.cmd == "init":
1632
+ return _cmd_init(root, args.yes, args.reset)
1633
+ if args.cmd in ("approve", "reject"):
1634
+ return _cmd_decide(root, args.ids, args.all, args.cmd == "approve", args.yes)
1635
+ return _cmd_rotate(root)
1636
+ except (RuleError, OSError) as exc:
1637
+ print(f"rules: {exc}", file=sys.stderr)
1638
+ return 1
1639
+ except EOFError:
1640
+ print("rules: the owner passphrase must be typed on a terminal", file=sys.stderr)
1641
+ return 1
1642
+
1643
+
1644
+ if __name__ == "__main__":
1645
+ raise SystemExit(main())