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