deepmodebot 0.0.0-stage → 0.9.1

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 (313) hide show
  1. package/.claude-plugin/marketplace.json +26 -0
  2. package/.omp-plugin/marketplace.json +26 -0
  3. package/LICENSE +24 -0
  4. package/README.md +377 -2
  5. package/bin/deepmodebot.mjs +247 -0
  6. package/lib/autoupdate.mjs +47 -0
  7. package/lib/clients.mjs +139 -0
  8. package/lib/run.mjs +32 -0
  9. package/lib/state.mjs +52 -0
  10. package/lib/tree.mjs +48 -0
  11. package/lib/version.mjs +26 -0
  12. package/package.json +44 -4
  13. package/plugins/deepmodebot/.antigravity-plugin/plugin.json +35 -0
  14. package/plugins/deepmodebot/.antigravity-plugin/skills/deep/SKILL.md +13 -0
  15. package/plugins/deepmodebot/.antigravity-plugin/skills/land-pr/SKILL.md +23 -0
  16. package/plugins/deepmodebot/.antigravity-plugin/skills/pr-thread/SKILL.md +17 -0
  17. package/plugins/deepmodebot/.antigravity-plugin/skills/review-pr/SKILL.md +16 -0
  18. package/plugins/deepmodebot/.antigravity-plugin/skills/tournament/SKILL.md +14 -0
  19. package/plugins/deepmodebot/.claude-plugin/plugin.json +27 -0
  20. package/plugins/deepmodebot/agents/reviewer/agent.md +33 -0
  21. package/plugins/deepmodebot/agents/scout/agent.md +34 -0
  22. package/plugins/deepmodebot/agents/security-reviewer/agent.md +30 -0
  23. package/plugins/deepmodebot/assets/logo.svg +8 -0
  24. package/plugins/deepmodebot/commands/contribute.md +8 -0
  25. package/plugins/deepmodebot/commands/deep.md +11 -0
  26. package/plugins/deepmodebot/commands/land-pr.md +12 -0
  27. package/plugins/deepmodebot/commands/pr-thread.md +14 -0
  28. package/plugins/deepmodebot/commands/project-brief.md +8 -0
  29. package/plugins/deepmodebot/commands/review-pr.md +10 -0
  30. package/plugins/deepmodebot/commands/tournament.md +12 -0
  31. package/plugins/deepmodebot/hooks/hooks.json +26 -0
  32. package/plugins/deepmodebot/hooks.json +24 -0
  33. package/plugins/deepmodebot/mcp_config.json +11 -0
  34. package/plugins/deepmodebot/scripts/antigravity-guard.mjs +413 -0
  35. package/plugins/deepmodebot/scripts/omp-mcp-server.mjs +1091 -0
  36. package/plugins/deepmodebot/skills/agent-harnesses/SKILL.md +57 -0
  37. package/plugins/deepmodebot/skills/agent-harnesses/assets/sdks/bun.lock +391 -0
  38. package/plugins/deepmodebot/skills/agent-harnesses/assets/sdks/check.ts +53 -0
  39. package/plugins/deepmodebot/skills/agent-harnesses/assets/sdks/check_antigravity.py +38 -0
  40. package/plugins/deepmodebot/skills/agent-harnesses/assets/sdks/check_claude.mjs +11 -0
  41. package/plugins/deepmodebot/skills/agent-harnesses/assets/sdks/package.json +11 -0
  42. package/plugins/deepmodebot/skills/agent-harnesses/assets/sdks/requirements.txt +1 -0
  43. package/plugins/deepmodebot/skills/agent-harnesses/references/ai-native-tooling.md +190 -0
  44. package/plugins/deepmodebot/skills/agent-harnesses/references/ai-sdk-selection.md +50 -0
  45. package/plugins/deepmodebot/skills/agent-harnesses/references/antigravity.md +108 -0
  46. package/plugins/deepmodebot/skills/agent-harnesses/references/claude-code.md +166 -0
  47. package/plugins/deepmodebot/skills/agent-harnesses/references/codex.md +151 -0
  48. package/plugins/deepmodebot/skills/agent-harnesses/references/delegation-efficiency.md +230 -0
  49. package/plugins/deepmodebot/skills/agent-harnesses/references/langchain-ecosystem.md +124 -0
  50. package/plugins/deepmodebot/skills/agent-harnesses/references/omp.md +183 -0
  51. package/plugins/deepmodebot/skills/agent-harnesses/references/protocols.md +172 -0
  52. package/plugins/deepmodebot/skills/agent-harnesses/references/sdks.md +228 -0
  53. package/plugins/deepmodebot/skills/agent-harnesses/references/self-authoring.md +171 -0
  54. package/plugins/deepmodebot/skills/cloud-devsecops/SKILL.md +24 -0
  55. package/plugins/deepmodebot/skills/cloud-devsecops/references/aws.md +264 -0
  56. package/plugins/deepmodebot/skills/cloud-devsecops/references/azure.md +261 -0
  57. package/plugins/deepmodebot/skills/cloud-devsecops/references/containers.md +96 -0
  58. package/plugins/deepmodebot/skills/cloud-devsecops/references/devops-tools.md +297 -0
  59. package/plugins/deepmodebot/skills/cloud-devsecops/references/devsecops-pipeline.md +258 -0
  60. package/plugins/deepmodebot/skills/cloud-devsecops/references/gcp.md +258 -0
  61. package/plugins/deepmodebot/skills/cloud-devsecops/references/kubernetes.md +74 -0
  62. package/plugins/deepmodebot/skills/cloud-devsecops/references/local-emulators.md +265 -0
  63. package/plugins/deepmodebot/skills/contribute/SKILL.md +134 -0
  64. package/plugins/deepmodebot/skills/create-verification-skill/LICENSE +21 -0
  65. package/plugins/deepmodebot/skills/create-verification-skill/SKILL.md +101 -0
  66. package/plugins/deepmodebot/skills/create-verification-skill/references/feature-map-example/README.md +47 -0
  67. package/plugins/deepmodebot/skills/create-verification-skill/references/feature-map-example/create-note.md +39 -0
  68. package/plugins/deepmodebot/skills/create-verification-skill/references/feature-map-example/search.md +45 -0
  69. package/plugins/deepmodebot/skills/deep-stack/SKILL.md +53 -0
  70. package/plugins/deepmodebot/skills/deep-stack/references/AGENTS.template.md +52 -0
  71. package/plugins/deepmodebot/skills/deep-stack/references/agentic-workflow.md +114 -0
  72. package/plugins/deepmodebot/skills/deep-stack/references/any-app-stack.md +51 -0
  73. package/plugins/deepmodebot/skills/deep-stack/references/design-workflow.md +101 -0
  74. package/plugins/deepmodebot/skills/deep-stack/references/isolate.md +23 -0
  75. package/plugins/deepmodebot/skills/deep-stack/references/philosophy.md +306 -0
  76. package/plugins/deepmodebot/skills/deep-stack/references/prove.md +31 -0
  77. package/plugins/deepmodebot/skills/deep-stack/references/stack.md +119 -0
  78. package/plugins/deepmodebot/skills/deep-stack/references/structure.md +22 -0
  79. package/plugins/deepmodebot/skills/deep-stack/references/unslop/LICENSE +21 -0
  80. package/plugins/deepmodebot/skills/deep-stack/references/unslop/unslop.md +80 -0
  81. package/plugins/deepmodebot/skills/deepmodebot/LICENSE +23 -0
  82. package/plugins/deepmodebot/skills/deepmodebot/SKILL.md +198 -0
  83. package/plugins/deepmodebot/skills/deepmodebot/assets/agents-md/agents_md.py +207 -0
  84. package/plugins/deepmodebot/skills/deepmodebot/assets/agents-md/test_agents_md.py +146 -0
  85. package/plugins/deepmodebot/skills/deepmodebot/assets/architecture-review/report-template.html +92 -0
  86. package/plugins/deepmodebot/skills/deepmodebot/assets/contain/claude-guard.sh +42 -0
  87. package/plugins/deepmodebot/skills/deepmodebot/assets/contain/claude_guard.py +135 -0
  88. package/plugins/deepmodebot/skills/deepmodebot/assets/contain/omp-contain-link.ts +12 -0
  89. package/plugins/deepmodebot/skills/deepmodebot/assets/contain/omp-contain.ts +115 -0
  90. package/plugins/deepmodebot/skills/deepmodebot/assets/contain/test_antigravity_guard.py +483 -0
  91. package/plugins/deepmodebot/skills/deepmodebot/assets/contain/test_audit_regressions.py +139 -0
  92. package/plugins/deepmodebot/skills/deepmodebot/assets/contain/test_contain.py +301 -0
  93. package/plugins/deepmodebot/skills/deepmodebot/assets/contain/test_omp_mcp.py +602 -0
  94. package/plugins/deepmodebot/skills/deepmodebot/assets/e2e/design.py +242 -0
  95. package/plugins/deepmodebot/skills/deepmodebot/assets/e2e/evidence.py +293 -0
  96. package/plugins/deepmodebot/skills/deepmodebot/assets/e2e/record.py +387 -0
  97. package/plugins/deepmodebot/skills/deepmodebot/assets/e2e/review.py +339 -0
  98. package/plugins/deepmodebot/skills/deepmodebot/assets/e2e/test_design.py +69 -0
  99. package/plugins/deepmodebot/skills/deepmodebot/assets/e2e/test_evidence.py +160 -0
  100. package/plugins/deepmodebot/skills/deepmodebot/assets/e2e/test_record.py +180 -0
  101. package/plugins/deepmodebot/skills/deepmodebot/assets/e2e/test_review.py +265 -0
  102. package/plugins/deepmodebot/skills/deepmodebot/assets/git-guardrails/git-guard-patterns.txt +44 -0
  103. package/plugins/deepmodebot/skills/deepmodebot/assets/git-guardrails/git-guard.sh +132 -0
  104. package/plugins/deepmodebot/skills/deepmodebot/assets/git-guardrails/git-guard.ts +122 -0
  105. package/plugins/deepmodebot/skills/deepmodebot/assets/git-guardrails/test_git_guard.py +192 -0
  106. package/plugins/deepmodebot/skills/deepmodebot/assets/github-app/bot.py +3037 -0
  107. package/plugins/deepmodebot/skills/deepmodebot/assets/github-app/brand.json +11 -0
  108. package/plugins/deepmodebot/skills/deepmodebot/assets/github-app/brand.py +51 -0
  109. package/plugins/deepmodebot/skills/deepmodebot/assets/github-app/ghapp.py +361 -0
  110. package/plugins/deepmodebot/skills/deepmodebot/assets/github-app/install.py +274 -0
  111. package/plugins/deepmodebot/skills/deepmodebot/assets/github-app/local_updates.py +576 -0
  112. package/plugins/deepmodebot/skills/deepmodebot/assets/github-app/review_context.py +204 -0
  113. package/plugins/deepmodebot/skills/deepmodebot/assets/github-app/test_bot.py +2182 -0
  114. package/plugins/deepmodebot/skills/deepmodebot/assets/github-app/test_brand.py +19 -0
  115. package/plugins/deepmodebot/skills/deepmodebot/assets/github-app/test_local_updates.py +691 -0
  116. package/plugins/deepmodebot/skills/deepmodebot/assets/github-app/test_review_context.py +127 -0
  117. package/plugins/deepmodebot/skills/deepmodebot/assets/github-app/test_workspace_cleanup.py +496 -0
  118. package/plugins/deepmodebot/skills/deepmodebot/assets/github-app/workspace_cleanup.py +351 -0
  119. package/plugins/deepmodebot/skills/deepmodebot/assets/loop/loop.py +2394 -0
  120. package/plugins/deepmodebot/skills/deepmodebot/assets/loop/plan.py +583 -0
  121. package/plugins/deepmodebot/skills/deepmodebot/assets/loop/test_loop.py +1426 -0
  122. package/plugins/deepmodebot/skills/deepmodebot/assets/loop/test_plan.py +320 -0
  123. package/plugins/deepmodebot/skills/deepmodebot/assets/loop/test_windows_job.py +326 -0
  124. package/plugins/deepmodebot/skills/deepmodebot/assets/loop/windows_job.py +244 -0
  125. package/plugins/deepmodebot/skills/deepmodebot/assets/perf-audit/bench_harness.py +165 -0
  126. package/plugins/deepmodebot/skills/deepmodebot/assets/perf-audit/perf_audit.py +240 -0
  127. package/plugins/deepmodebot/skills/deepmodebot/assets/perf-audit/test_bench_harness.py +55 -0
  128. package/plugins/deepmodebot/skills/deepmodebot/assets/perf-audit/test_perf_audit.py +53 -0
  129. package/plugins/deepmodebot/skills/deepmodebot/assets/pr-agent/diff_coverage.py +350 -0
  130. package/plugins/deepmodebot/skills/deepmodebot/assets/pr-agent/pr_agent_local.py +370 -0
  131. package/plugins/deepmodebot/skills/deepmodebot/assets/pr-agent/test_diff_coverage.py +94 -0
  132. package/plugins/deepmodebot/skills/deepmodebot/assets/pr-conversation/arena.html +425 -0
  133. package/plugins/deepmodebot/skills/deepmodebot/assets/pr-conversation/arena.py +579 -0
  134. package/plugins/deepmodebot/skills/deepmodebot/assets/pr-conversation/arena_tui.py +839 -0
  135. package/plugins/deepmodebot/skills/deepmodebot/assets/pr-conversation/font8x8_basic.hex +1 -0
  136. package/plugins/deepmodebot/skills/deepmodebot/assets/pr-conversation/show_thread.py +329 -0
  137. package/plugins/deepmodebot/skills/deepmodebot/assets/pr-conversation/test_arena.py +610 -0
  138. package/plugins/deepmodebot/skills/deepmodebot/assets/repo-references.json +637 -0
  139. package/plugins/deepmodebot/skills/deepmodebot/assets/scrape/test_yt_enrich.py +250 -0
  140. package/plugins/deepmodebot/skills/deepmodebot/assets/scrape/yt_enrich.py +1820 -0
  141. package/plugins/deepmodebot/skills/deepmodebot/assets/scrape/yt_meta.py +156 -0
  142. package/plugins/deepmodebot/skills/deepmodebot/assets/scrape/yt_transcript_relay.js +54 -0
  143. package/plugins/deepmodebot/skills/deepmodebot/assets/security-audit/audit-pr.sh +122 -0
  144. package/plugins/deepmodebot/skills/deepmodebot/assets/security-audit/gate.cjs +155 -0
  145. package/plugins/deepmodebot/skills/deepmodebot/assets/security-audit/prompt.md +13 -0
  146. package/plugins/deepmodebot/skills/deepmodebot/assets/tournament/test_tournament.py +654 -0
  147. package/plugins/deepmodebot/skills/deepmodebot/assets/tournament/tournament.py +1285 -0
  148. package/plugins/deepmodebot/skills/deepmodebot/assets/wizard/wizard.sh +234 -0
  149. package/plugins/deepmodebot/skills/deepmodebot/assets/workspace-map/test_workspace_map.py +879 -0
  150. package/plugins/deepmodebot/skills/deepmodebot/assets/workspace-map/workspace_map.py +2436 -0
  151. package/plugins/deepmodebot/skills/deepmodebot/references/README.md +61 -0
  152. package/plugins/deepmodebot/skills/deepmodebot/references/catalog.md +105 -0
  153. package/plugins/deepmodebot/skills/deepmodebot/references/contain.md +39 -0
  154. package/plugins/deepmodebot/skills/deepmodebot/references/factory-landscape.md +147 -0
  155. package/plugins/deepmodebot/skills/deepmodebot/references/flows.md +50 -0
  156. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/authoring-a-skill.md +37 -0
  157. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/babysit.md +77 -0
  158. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/bug-fix.md +34 -0
  159. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/end-to-end.md +50 -0
  160. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/eval.md +39 -0
  161. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/feature.md +60 -0
  162. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/handoff.md +52 -0
  163. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/hillclimb.md +46 -0
  164. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/investigation.md +20 -0
  165. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/opening-a-pr.md +97 -0
  166. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/pause-safely.md +30 -0
  167. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/perf-issue.md +31 -0
  168. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/phased-build.md +146 -0
  169. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/prototype.md +31 -0
  170. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/refactoring.md +60 -0
  171. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/reference-rebuild.md +45 -0
  172. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/run-a-goal.md +143 -0
  173. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/runtime-forensics.md +22 -0
  174. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/self-authoring.md +130 -0
  175. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/session-pickup.md +33 -0
  176. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/setup.md +105 -0
  177. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/shipping.md +52 -0
  178. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/spec.md +67 -0
  179. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/tickets.md +56 -0
  180. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/trace-forensics.md +24 -0
  181. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/triage.md +102 -0
  182. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/visual-parity.md +19 -0
  183. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/wayfinder.md +44 -0
  184. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/work-a-queue.md +189 -0
  185. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/worktree-cleanup.md +35 -0
  186. package/plugins/deepmodebot/skills/deepmodebot/references/principles/attack-the-premise.md +7 -0
  187. package/plugins/deepmodebot/skills/deepmodebot/references/principles/boundary-discipline.md +8 -0
  188. package/plugins/deepmodebot/skills/deepmodebot/references/principles/build-the-lever.md +8 -0
  189. package/plugins/deepmodebot/skills/deepmodebot/references/principles/encode-lessons-in-structure.md +6 -0
  190. package/plugins/deepmodebot/skills/deepmodebot/references/principles/exhaust-the-design-space.md +4 -0
  191. package/plugins/deepmodebot/skills/deepmodebot/references/principles/experience-first.md +7 -0
  192. package/plugins/deepmodebot/skills/deepmodebot/references/principles/explain-the-number.md +9 -0
  193. package/plugins/deepmodebot/skills/deepmodebot/references/principles/fix-root-causes.md +6 -0
  194. package/plugins/deepmodebot/skills/deepmodebot/references/principles/foundational-thinking.md +9 -0
  195. package/plugins/deepmodebot/skills/deepmodebot/references/principles/guard-the-context-window.md +7 -0
  196. package/plugins/deepmodebot/skills/deepmodebot/references/principles/laziness-protocol.md +6 -0
  197. package/plugins/deepmodebot/skills/deepmodebot/references/principles/make-operations-idempotent.md +7 -0
  198. package/plugins/deepmodebot/skills/deepmodebot/references/principles/migrate-callers-then-delete-legacy-apis.md +5 -0
  199. package/plugins/deepmodebot/skills/deepmodebot/references/principles/minimize-reader-load.md +7 -0
  200. package/plugins/deepmodebot/skills/deepmodebot/references/principles/model-the-domain.md +7 -0
  201. package/plugins/deepmodebot/skills/deepmodebot/references/principles/never-block-on-the-human.md +7 -0
  202. package/plugins/deepmodebot/skills/deepmodebot/references/principles/outcome-oriented-execution.md +6 -0
  203. package/plugins/deepmodebot/skills/deepmodebot/references/principles/prove-it-works.md +8 -0
  204. package/plugins/deepmodebot/skills/deepmodebot/references/principles/redesign-from-first-principles.md +7 -0
  205. package/plugins/deepmodebot/skills/deepmodebot/references/principles/separate-before-serializing-shared-state.md +6 -0
  206. package/plugins/deepmodebot/skills/deepmodebot/references/principles/sequence-verifiable-units.md +7 -0
  207. package/plugins/deepmodebot/skills/deepmodebot/references/principles/subtract-before-you-add.md +6 -0
  208. package/plugins/deepmodebot/skills/deepmodebot/references/principles/test-behavior-not-implementation.md +7 -0
  209. package/plugins/deepmodebot/skills/deepmodebot/references/principles/type-system-discipline.md +6 -0
  210. package/plugins/deepmodebot/skills/deepmodebot/references/rust-migration-case-studies.md +26 -0
  211. package/plugins/deepmodebot/skills/deepmodebot/references/startup-ideas.md +21 -0
  212. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/agent-collaboration.md +82 -0
  213. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/architect.md +32 -0
  214. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/architecture-review.md +43 -0
  215. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/arena.md +20 -0
  216. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/benchmark-checklist.md +31 -0
  217. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/blast-radius.md +19 -0
  218. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/correct.md +20 -0
  219. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/course.md +47 -0
  220. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/coworkers.md +70 -0
  221. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/domain-model.md +69 -0
  222. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/figure-it-out.md +25 -0
  223. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/git-guardrails.md +44 -0
  224. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/github-app.md +160 -0
  225. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/goal-review.md +156 -0
  226. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/grill.md +27 -0
  227. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/how.md +23 -0
  228. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/in-your-own-words.md +12 -0
  229. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/inner-loop.md +39 -0
  230. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/interrogate.md +16 -0
  231. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/issue-conversation.md +52 -0
  232. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/no-comments.md +29 -0
  233. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/open-design-evidence.md +65 -0
  234. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/panel.md +34 -0
  235. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/pr-agent.md +39 -0
  236. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/pr-conversation.md +135 -0
  237. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/pr-review.md +138 -0
  238. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/pre-commit.md +31 -0
  239. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/prior-art.md +44 -0
  240. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/questionnaire.md +46 -0
  241. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/re-explain.md +23 -0
  242. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/recall.md +19 -0
  243. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/reflect.md +20 -0
  244. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/research.md +99 -0
  245. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/retro.md +30 -0
  246. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/scrape.md +32 -0
  247. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/security-audit.md +40 -0
  248. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/sharpen.md +15 -0
  249. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/show-me-your-work.md +19 -0
  250. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/sme-review.md +49 -0
  251. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/swarm.md +14 -0
  252. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/tdd.md +55 -0
  253. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/teach.md +20 -0
  254. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/technical-writing.md +22 -0
  255. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/tool-routing.md +85 -0
  256. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/tournament.md +44 -0
  257. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/tracker.md +78 -0
  258. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/unslop.md +15 -0
  259. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/visual-e2e.md +78 -0
  260. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/why.md +31 -0
  261. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/wizard.md +25 -0
  262. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/workspace-map.md +35 -0
  263. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/writing-for-agents.md +66 -0
  264. package/plugins/deepmodebot/skills/deepmodebot/scripts/check_skill.py +93 -0
  265. package/plugins/deepmodebot/skills/deepmodebot/scripts/trending.py +598 -0
  266. package/plugins/deepmodebot/skills/domain-rules/SKILL.md +131 -0
  267. package/plugins/deepmodebot/skills/domain-rules/references/agent-engineering.md +105 -0
  268. package/plugins/deepmodebot/skills/domain-rules/references/ai-concepts.md +103 -0
  269. package/plugins/deepmodebot/skills/domain-rules/references/aws-networking.md +121 -0
  270. package/plugins/deepmodebot/skills/domain-rules/references/backend-system-design.md +162 -0
  271. package/plugins/deepmodebot/skills/domain-rules/references/data-structures-and-cache-optimization.md +48 -0
  272. package/plugins/deepmodebot/skills/domain-rules/references/devops-and-fundamentals.md +137 -0
  273. package/plugins/deepmodebot/skills/domain-rules/references/engineering-practice.md +100 -0
  274. package/plugins/deepmodebot/skills/domain-rules/references/high-scale-server-optimization.md +181 -0
  275. package/plugins/deepmodebot/skills/domain-rules/references/language-ecosystems.md +56 -0
  276. package/plugins/deepmodebot/skills/frontend-ui/SKILL.md +146 -0
  277. package/plugins/deepmodebot/skills/frontend-ui/references/patterns/live-demos.md +38 -0
  278. package/plugins/deepmodebot/skills/frontend-ui/references/patterns/mobbin-shipped-apps.md +28 -0
  279. package/plugins/deepmodebot/skills/frontend-ui/references/patterns/motion-clips.md +269 -0
  280. package/plugins/deepmodebot/skills/frontend-ui/references/patterns/motion-graphics.md +62 -0
  281. package/plugins/deepmodebot/skills/frontend-ui/references/patterns/pinterest-animations.md +217 -0
  282. package/plugins/deepmodebot/skills/frontend-ui/references/patterns/pinterest-patterns.md +101 -0
  283. package/plugins/deepmodebot/skills/frontend-ui/references/playbook/01-workflow.md +25 -0
  284. package/plugins/deepmodebot/skills/frontend-ui/references/playbook/02-review-rubric.md +21 -0
  285. package/plugins/deepmodebot/skills/frontend-ui/references/playbook/03-ai-tells.md +46 -0
  286. package/plugins/deepmodebot/skills/frontend-ui/references/playbook/04-components.md +21 -0
  287. package/plugins/deepmodebot/skills/frontend-ui/references/playbook/04a-agent-ui.md +153 -0
  288. package/plugins/deepmodebot/skills/frontend-ui/references/playbook/05-motion.md +106 -0
  289. package/plugins/deepmodebot/skills/frontend-ui/references/playbook/05a-motion-graphics.md +121 -0
  290. package/plugins/deepmodebot/skills/frontend-ui/references/playbook/06-typography-layout.md +48 -0
  291. package/plugins/deepmodebot/skills/frontend-ui/references/playbook/06a-color.md +26 -0
  292. package/plugins/deepmodebot/skills/frontend-ui/references/playbook/07-copy.md +11 -0
  293. package/plugins/deepmodebot/skills/frontend-ui/references/playbook/08-quality-floor.md +63 -0
  294. package/plugins/deepmodebot/skills/frontend-ui/references/playbook/09-steering-agents.md +13 -0
  295. package/plugins/deepmodebot/skills/maintain-verification-skill/LICENSE +21 -0
  296. package/plugins/deepmodebot/skills/maintain-verification-skill/SKILL.md +47 -0
  297. package/plugins/deepmodebot/skills/project-brief/SKILL.md +100 -0
  298. package/plugins/deepmodebot/skills/project-brief/assets/CONTRIBUTING.template.md +124 -0
  299. package/plugins/deepmodebot/skills/project-brief/assets/ISSUE_TEMPLATE/task.yml +61 -0
  300. package/plugins/deepmodebot/skills/project-brief/assets/PROJECT_BRIEF.template.md +98 -0
  301. package/plugins/deepmodebot/skills/project-brief/assets/PULL_REQUEST_TEMPLATE.md +35 -0
  302. package/plugins/deepmodebot/skills/project-brief/assets/pr-overlap.py +643 -0
  303. package/plugins/deepmodebot/skills/project-brief/assets/sync-roadmap.py +314 -0
  304. package/plugins/deepmodebot/skills/secrets-and-auth/SKILL.md +60 -0
  305. package/plugins/deepmodebot/skills/secrets-and-auth/references/agent-authentication.md +198 -0
  306. package/plugins/deepmodebot/skills/secrets-and-auth/references/leak-prevention.md +206 -0
  307. package/plugins/deepmodebot/skills/secrets-and-auth/references/logins-and-passwords.md +165 -0
  308. package/plugins/deepmodebot/skills/secrets-and-auth/references/secrets-and-env.md +182 -0
  309. package/plugins/deepmodebot/skills/software-architecture/SKILL.md +47 -0
  310. package/plugins/deepmodebot/skills/software-architecture/references/backend-infrastructure.md +273 -0
  311. package/plugins/deepmodebot/skills/software-architecture/references/databases.md +277 -0
  312. package/plugins/deepmodebot/skills/software-architecture/references/monorepos.md +210 -0
  313. package/plugins/deepmodebot/skills/software-architecture/references/ontology.md +287 -0
@@ -0,0 +1,1285 @@
1
+ #!/usr/bin/env python3
2
+ """Intent and vagueness auto-router plus 12-agent tournament bracket engine for deepmodebot.
3
+
4
+ python tournament.py route --stdin [--root <repo>] [--has-factory] [--empty-dir] [--json] <<'EOF'
5
+ python tournament.py init --root <repo> --slug <slug> --prompt-stdin [--entrants 12|8|4] [--force] [--json] <<'EOF'
6
+ python tournament.py pitch --dir <dir> --entrant <id> --title <t> --thesis <t> --gap-kind <kind> --receipt <r>
7
+ python tournament.py rebut --dir <dir> --entrant <id> --match <id> --target <id> --attack <t> --receipt <r>
8
+ python tournament.py dropout --dir <dir> --entrant <id> --reason <why>
9
+ python tournament.py judge --dir <dir> --match <id> --winner <id> --judge-model <m> --verified-receipt <r> --rationale <w>
10
+ python tournament.py status --dir <dir> [--json]
11
+ python tournament.py render --dir <dir> [--out <path>]
12
+
13
+ Pitches may be revised only before the entrant's first judged match.
14
+ Tournament routes preserve build intent; explicit choice or no-code constraints keep the checkpoint.
15
+ """
16
+ import argparse
17
+ import contextlib
18
+ import ipaddress
19
+ import json
20
+ import os
21
+ import re
22
+ import sys
23
+ import tempfile
24
+ import time
25
+ import urllib.parse
26
+ from pathlib import Path
27
+
28
+ LENSES = (
29
+ ("seam-archaeologist", "pod-a", "architecture",
30
+ "Audit module depth, coupling seams, and git churn hotspots for structural blind spots."),
31
+ ("data-state-architect", "pod-a", "architecture",
32
+ "Audit domain types, state ownership, invariants, consistency, and schema gaps."),
33
+ ("contract-boundary-auditor", "pod-a", "architecture",
34
+ "Audit API, CLI, protocol, and trust boundaries, idempotency, and error contracts."),
35
+ ("sota-paper-researcher", "pod-b", "research",
36
+ "Search primary papers, specs, and algorithmic advances that leapfrog incremental fixes."),
37
+ ("oss-prior-art-hunter", "pod-b", "research",
38
+ "Search newest open-source repos, libraries, and shipped systems to adopt or adapt."),
39
+ ("eval-oracle-scientist", "pod-b", "research",
40
+ "Design falsifiable benchmarks, ground-truth oracles, and failure metrics missing today."),
41
+ ("premise-attacker", "pod-c", "hybrid",
42
+ "Challenge XY framing in the prompt and identify changes that remove the problem class."),
43
+ ("adjacent-capability-scout", "pod-c", "hybrid",
44
+ "Identify missing capabilities one step upstream or downstream that unlock the real goal."),
45
+ ("workflow-ux-strategist", "pod-c", "hybrid",
46
+ "Audit end-to-end human and agent workflow friction, feedback latency, and approval gates."),
47
+ ("radical-simplifier", "pod-d", "architecture",
48
+ "Apply the deletion test to collapse layers, wrappers, and state instead of adding glue."),
49
+ ("scale-cost-analyst", "pod-d", "hybrid",
50
+ "Stress-test throughput, tail latency, token or compute cost, caching, and IO bottlenecks."),
51
+ ("failure-security-redteam", "pod-d", "architecture",
52
+ "Probe adversarial inputs, race conditions, partial failures, credentials, and blast radius."),
53
+ )
54
+
55
+ EIGHT_IDS = (
56
+ "seam-archaeologist", "data-state-architect",
57
+ "sota-paper-researcher", "oss-prior-art-hunter",
58
+ "premise-attacker", "adjacent-capability-scout",
59
+ "radical-simplifier", "failure-security-redteam",
60
+ )
61
+
62
+ FOUR_IDS = (
63
+ "seam-archaeologist", "sota-paper-researcher",
64
+ "premise-attacker", "radical-simplifier",
65
+ )
66
+
67
+ SLUG_RE = re.compile(r"[a-z0-9]+(?:-[a-z0-9]+)*")
68
+ BRAND_SLUG = "deepmodebot"
69
+ BRAND_DISPLAY = "Deepmodebot"
70
+ BRAND_TRIGGER = "@deepmodebot"
71
+
72
+ CONCRETE_ANCHOR_RE = re.compile(
73
+ r"(`[^`]+`"
74
+ r"|#\d+\b"
75
+ r"|\bPR\s*#?\d+\b"
76
+ r"|\bspec\s*#?\d+\b"
77
+ r"|[A-Za-z0-9_./\\-]+\.(?:py|ts|tsx|js|jsx|mjs|cjs|rs|go|java|cs|rb|php|md|json|ya?ml|toml|sql|sh|html|css)\b"
78
+ r"|\b(?:src|lib|app|packages|plugins|scripts|docs|tests|evals)/[A-Za-z0-9_./-]+"
79
+ r"|/[A-Za-z0-9_-]+/[A-Za-z0-9_/-]+"
80
+ r"|\bp9[059]\b|\b\d+\s*(?:ms|s|mb|gb|x)\b)",
81
+ re.I,
82
+ )
83
+ ENV_ANCHOR_RE = re.compile(r"\b[A-Z][A-Z0-9]*_[A-Z0-9_]+\b")
84
+
85
+ TOURNAMENT_EXPLICIT_RE = re.compile(
86
+ r"(^\s*tournament\b"
87
+ r"|\b(?:run|start|use|hold|do|launch)\s+(?:a\s+|the\s+)?(?:agent\s+|idea\s+|design\s+|architecture\s+|research\s+)?tournament\b"
88
+ r"|\btournament\s+(?:mode|bracket|debate|of\s+ideas|to\s+decide|on\s+(?:our|this|the)|and\s+(?:build|implement|let|wait|create|deliver|only))\b"
89
+ r"|\barena\s+debate\b"
90
+ r"|\bdebate\s+(?:research|architecture|design|system|ideas|the\s+best)\b"
91
+ r"|\b(?:architecture|architectural|research)\s+(?:gaps?|blind\s*spots?)\b"
92
+ r"|\bblind\s*spots?\b"
93
+ r"|\bwhat\s+(?:are\s+we|is\s+this\s+repo)\s+missing\b"
94
+ r"|\bpropose\s+the\s+best\s+(?:system|architecture|research|design|approach)\b"
95
+ r"|\bbest\s+(?:sota\s+)?research\s+ideas?\b"
96
+ r"|\bcompete\b.*\b(?:ideas?|agents?|proposals?|designs?)\b"
97
+ r"|\bsota\s+(?:approach|architecture|methods?|ideas?|research)\b)",
98
+ re.I,
99
+ )
100
+
101
+ OPEN_AMBITION_RE = re.compile(
102
+ r"(\brethink\b"
103
+ r"|\bre-?architect\b"
104
+ r"|\bfrom\s+first\s+principles\b"
105
+ r"|\bnext[- ]gen(?:eration)?\b"
106
+ r"|\b10x\b"
107
+ r"|\bmake\s+(?:it|this|our\s+[\w\s-]+?)\s+(?:way\s+|much\s+)?(?:better|smarter|stronger|faster|modern)\b"
108
+ r"|\bupgrade\s+(?:our|the)\s+(?:architecture|system|agent|ai|stack|pipeline)\b"
109
+ r"|\bfix\s+(?:our|the)\s+(?:whole\s+)?(?:architecture|system|design)\b"
110
+ r"|\bhow\s+should\s+we\s+(?:evolve|redesign|rethink|architect)\b"
111
+ r"|\bwhat\s+should\s+we\s+build\s+next\b"
112
+ r"|\bfigure\s+out\s+the\s+best\s+(?:way|system|architecture|direction)\b"
113
+ r"|\bexplore\s+(?:research|architectural|design)\s+(?:directions|ideas|options)\b)",
114
+ re.I,
115
+ )
116
+
117
+ CONCRETE_ACTION_VERB_RE = re.compile(
118
+ r"\b(add|create|implement|wire|store|expose|render|show|support|track|remember|allow|parse|validate|export"
119
+ r"|send|delete|remove|update|change|sort|filter|replace|move|configure|set\s+up|enable|disable|hide|limit|block|log"
120
+ r"|notify|sync|import|download|upload|convert|converts|compute|enforce)\b",
121
+ re.I,
122
+ )
123
+
124
+ CONCRETE_SURFACE_RE = re.compile(
125
+ r"\b(page|endpoint|button|toggle|table|cli|flag|modal|form|route|webhook|webhooks|test|tests|file|column|header|footer"
126
+ r"|sidebar|menu|dialog|banner|card|list|row|field|input|dropdown|tab|api|command|hook|job|queue|email|emails"
127
+ r"|invoice|invoices|order|orders|cart|session|login|checkout|billing|settings|profile|user|users|token|cache"
128
+ r"|report|reports|rule|rules|siem|subscription|subscriptions)\b",
129
+ re.I,
130
+ )
131
+
132
+ GREENFIELD_LEAD_RE = re.compile(
133
+ r"^\s*(?:please\s+)?(?:start|build|create|make)\s+(?:me\s+)?(?:a|an)\s+(?:[\w-]+\s+){0,3}?(?:app|tool|cli|service|site)\b",
134
+ re.I,
135
+ )
136
+
137
+ TOURNAMENT_BUILD_RE = re.compile(
138
+ r"(?:^|[,;.!?]\s*|\b(?:and|then)\s+)"
139
+ r"(?:(?:please|also)\s+)*"
140
+ r"(?:(?:i\s+(?:want|need)\s+you\s+to|you\s+should)\s+)?"
141
+ r"(?:build|implement|code)\b",
142
+ re.I,
143
+ )
144
+
145
+ TOURNAMENT_CHECKPOINT_RE = re.compile(
146
+ r"(\b(?:let|allow)\s+me\s+(?:choose|pick|select|approve)\b"
147
+ r"|\b(?:ask|consult)\s+me\s+(?:first|before)\b"
148
+ r"|\b(?:wait|pause|stop)\s+(?:for|until|at|before)\b"
149
+ r"|\b(?:approval|permission|consent|sign[- ]?off)\s+"
150
+ r"(?:first|before\s+(?:you\s+)?(?:code|coding|implementation|implementing|building|editing))\b"
151
+ r"|\b(?:do\s+not|don't|don’t|never)\s+(?:\w+\s+){0,2}(?:build|code|implement|modify|edit)\b"
152
+ r"|\b(?:no|without)\s+(?:code|coding|implementation|production\s+(?:edits|changes))\b"
153
+ r"|\b(?:choose|pick|select|approve)\s+(?:first|before\s+(?:coding|implementation|building))\b"
154
+ r"|\bonly\s+(?:propose|research|plan|discuss)\b)",
155
+ re.I,
156
+ )
157
+
158
+ GRILL_RE = re.compile(
159
+ r"(\bgrill\s+(?:me|this|my|our|with\s+docs)\b"
160
+ r"|\brecord\s+the\s+decisions\b"
161
+ r"|\bstress[- ]test\s+(?:this|my|our|the)\s+(?:plan|idea|design|spec|approach)\b"
162
+ r"|\bpoke\s+holes\s+in\b"
163
+ r"|^\s*(?:here(?:'s|\s+is)\s+(?:my|our|a)\s+)?draft\s+(?:plan|design|spec)\b"
164
+ r"|\b(?:review|check|critique)\s+(?:my|our|this)\s+draft\s+(?:plan|design|spec)\b)",
165
+ re.I,
166
+ )
167
+
168
+
169
+ def count_concrete_anchors(prompt: str) -> int:
170
+ hits = {m.group(0).lower() for m in CONCRETE_ANCHOR_RE.finditer(prompt)}
171
+ hits.update(m.group(0) for m in ENV_ANCHOR_RE.finditer(prompt))
172
+ clause_markers = len(
173
+ re.findall(r"(?::\s+\w|,\s+(?:handle|store|show|create|add|mark|and\s+\w+\s+the)\b)", prompt, re.I)
174
+ )
175
+ return len(hits) + (1 if clause_markers >= 2 else 0)
176
+
177
+
178
+ def classify_prompt(prompt: str, has_factory: bool = False, empty_dir: bool = False) -> dict:
179
+ text = " ".join(prompt.strip().split())
180
+ lower = text.lower()
181
+ anchors = count_concrete_anchors(text)
182
+ brand_names = "|".join(
183
+ sorted({re.escape(BRAND_SLUG.lower()), re.escape(BRAND_DISPLAY.lower())}, key=len, reverse=True)
184
+ )
185
+ brand_triggers = "|".join(
186
+ sorted({re.escape(BRAND_TRIGGER.lower()), re.escape("@" + BRAND_SLUG.lower())}, key=len, reverse=True)
187
+ )
188
+
189
+ def out(mode: str, intent: str, vagueness: str, reason: str, checkpoint: bool = False) -> dict:
190
+ if mode == "tournament":
191
+ build_requested = bool(GREENFIELD_LEAD_RE.search(text) or TOURNAMENT_BUILD_RE.search(text))
192
+ intent = "execute" if build_requested else "discover"
193
+ checkpoint = not build_requested or bool(TOURNAMENT_CHECKPOINT_RE.search(text))
194
+ return {
195
+ "mode": mode,
196
+ "intent": intent,
197
+ "vagueness": vagueness,
198
+ "checkpoint_before_code": checkpoint,
199
+ "anchors": anchors,
200
+ "reason": reason,
201
+ }
202
+
203
+ if (
204
+ re.search(r"^\s*review\s+(?:pr\s*#?\d+|#\d+|https?://\S+/pull/\d+)\b", lower)
205
+ or re.search(r"^\s*(?:pr\s*#?\d+|https?://\S+/pull/\d+)\s*$", lower)
206
+ or re.search(r"\breview\s+since\s+\S+|\breview\s+my\s+branch\b", lower)
207
+ ):
208
+ return out("pr-review", "audit", "low", "Explicit PR or branch review request.")
209
+
210
+ if (
211
+ re.search(r"\b(?:land|merge|finish)\b.*\b(?:on\s+your\s+own|no\s+human|bots\s+talk\s+it\s+out)\b", lower)
212
+ or re.search(r"^\s*(?:land|merge|finish)\s+pr\s*#?\d+\b", lower)
213
+ or (re.search(r"\bpr\s*#?\d+\b", lower) and re.search(r"\bland\s+it\b", lower))
214
+ ):
215
+ return out("pr-conversation", "execute", "low", "Autonomous PR landing request.")
216
+
217
+ if re.search(
218
+ r"\b(?:babysit|check\s+on)\s+pr\b|\bget\s+pr\s*#?\d+\s+green\b|\bpr\s*#?\d+\b.*\b(?:until\s+it'?s\s+green|when\s+it'?s\s+green)\b",
219
+ lower,
220
+ ):
221
+ return out("babysit", "execute", "low", "PR babysitting and check resolution request.")
222
+
223
+ if re.search(rf"(?<![\w.~/-])(?:{brand_triggers})\s+implement\b|\bbots\s+(?:plan|discuss|implement)\s+this\s+issue\b", lower):
224
+ return out("issue-conversation", "execute", "low", "Bot issue conversation request.")
225
+
226
+ if re.search(
227
+ rf"\binstall\s+(?:{brand_names})\s+on\s+my\s+repos\b|\brun\s+the\s+bots\s+on\s+their\s+own\b"
228
+ rf"|\bauto[- ]update\s+(?:local\s+)?(?:{brand_names})\s+copies\b"
229
+ r"|\bai\s+review\s+on\s+my\s+own\s+subscription\b|\b(?:start|stop|opt\b.*\bout\s+of)\s+the\s+bots\b",
230
+ lower,
231
+ ):
232
+ return out("github-app", "execute", "low", "GitHub App bot setup or control request.")
233
+
234
+ if re.search(
235
+ r"\b(?:set\b.*\bup|publish\b.*)\s+for\s+contributors\b|\bmake\s+(?:some\s+)?issues\s+(?:people|helpers)\s+can\s+pick\s+up\b",
236
+ lower,
237
+ ):
238
+ return out("project-brief", "execute", "low", "Maintainer contributor-onboarding request.")
239
+
240
+ if re.search(
241
+ r"\bwhat\s+can\s+i\s+work\s+on\b"
242
+ r"|\b(?:how\s+(?:can|do)\s+i\s+|want\s+to\s+|i'?d\s+like\s+to\s+|looking\s+to\s+)?contribute\s+to\s+(?:this|the)\s+(?:repo|project|codebase|open[- ]source)\b"
243
+ r"|\bhelp\s+(?:out\s+)?on\s+(?:this|the)\s+(?:repo|project)\b",
244
+ lower,
245
+ ):
246
+ return out("contribute", "execute", "low", "Contributor task-picking request.")
247
+
248
+ if (
249
+ re.search(
250
+ r"\brun\s+the\s+factory\b|\bwork\s+the\s+issue\s+queue\b|\bturn\s+issues\s+into\s+prs\b|\bset\s+up\s+a\s+software\s+factory\b",
251
+ lower,
252
+ )
253
+ or (
254
+ has_factory
255
+ and re.search(
256
+ r"\b(?:run|start|work|drive|check|status\s+of)\s+(?:the\s+)?factory\b"
257
+ r"|\bfactory\s+(?:queue|board|backlog|run|loop|workers?)\b",
258
+ lower,
259
+ )
260
+ )
261
+ or re.search(
262
+ r"\b(?:drive|work)\s+the\s+(?:board|backlog)\b|\brun\s+this\s+project\s+autonomously\b"
263
+ r"|\bkeep\s+going\s+on\s+the\s+roadmap\b|\bautopilot\b|\bstack\s+them,\s+don'?t\s+ship\b|\bbuild\s+the\s+stack,\s+i'?ll\s+land\s+it\b",
264
+ lower,
265
+ )
266
+ ):
267
+ return out("work-a-queue", "execute", "low", "Queue, factory, or backlog execution request.")
268
+
269
+ if re.search(rf"\bset\s+up\s+(?:{brand_names})\b|\bconfigure\s+the\s+(?:tracker|labels)\b|\badd\s+a\s+glossary\s+and\s+adrs\b", lower):
270
+ return out("setup", "execute", "low", "Repository tracker and conventions setup request.")
271
+
272
+ if re.search(
273
+ r"^\s*triage\b|\btriage\s+(?:the\s+|our\s+|open\s+|new\s+|incoming\s+)?(?:issues?|prs?|pull\s+requests?|bugs?|backlog|queue|inbox|tickets?)\b"
274
+ r"|\bwhat\s+needs\s+my\s+attention\b|\bis\s+#\d+\s+ready\s+for\s+an\s+agent\b|\bmove\s+#\d+\s+to\s+agent-ready\b",
275
+ lower,
276
+ ):
277
+ return out("triage", "execute", "low", "Issue or PR triage request.")
278
+
279
+ if re.search(
280
+ r"\bsme[- ]review\b|\bsme\s+in\s+the\s+loop\b|\bsubject\s+matter\s+expert\s+review\b"
281
+ r"|\bsme[-_ ]?gate\b|\bcomplex[- ]domain\s+(?:customer\s+)?spec\s+(?:sanity\s+check|review)\b",
282
+ lower,
283
+ ):
284
+ return out("sme-review", "audit", "low", "Complex-domain SME review or gate check.")
285
+
286
+ if re.search(
287
+ r"\bgoal[- ]review\b|\breview\s+(?:my|our|this)\s+goal\s+with\s+(?:three|3)\s+(?:agents|reviewers)\b"
288
+ r"|\bvague\s+goal\s+into\s+measurable\s+milestones\b",
289
+ lower,
290
+ ):
291
+ return out("goal-review", "audit", "medium", "Goal milestone drafting and three-reviewer goal review.")
292
+
293
+ if GRILL_RE.search(text):
294
+ return out("grill", "stress-test", "medium", "Plan or design stress-test request.")
295
+
296
+ if re.search(r"\b(?:write|draft)\s+(?:the|a)\s+spec\b|\bturn\s+this\s+into\s+a\s+spec\b|\bspec\s+it\s+up\b", lower):
297
+ return out("spec", "execute", "low", "Specification authoring request.")
298
+
299
+ if re.search(r"\bbreak\s+this\s+into\s+tickets\b|\bsplit\s+the\s+spec\s+into\s+issues\b|\bmake\s+tickets\s+for\s+this\b", lower):
300
+ return out("tickets", "execute", "low", "Ticket breakdown request.")
301
+
302
+ if re.search(
303
+ r"\b(?:implement|build|ship)\s+(?:the\s+)?spec(?:\s*#?\d+)?(?:\s+in\s+(?:incremental\s+)?sprints)?\b"
304
+ r"|\bbuild\s+all\s+the\s+tickets\s+on\s+one\s+branch\b|\bship\s+(?:this|it)\s+in\s+(?:incremental\s+)?sprints\b",
305
+ lower,
306
+ ):
307
+ return out("phased-build", "execute", "low", "Spec implementation across tickets or incremental sprints.")
308
+
309
+ if re.search(r"\b(?:write|author|create|edit)\s+(?:me\s+)?a\s+skill\b|\bedit\s+skill\.md\b", lower):
310
+ return out("authoring-a-skill", "execute", "low", "Skill authoring request.")
311
+
312
+ if re.search(
313
+ r"\b(?:write|edit|update|generate|regenerate|build|create|overwrite|refresh)\s+(?:an?\s+|the\s+|our\s+)?"
314
+ r"(?:agents\.md|claude\.md|a\s+rule\s+file|a?\s*subagent\s+brief)\b",
315
+ lower,
316
+ ):
317
+ return out("writing-for-agents", "execute", "low", "Agent instruction or brief authoring request.")
318
+
319
+ if re.search(r"\b(?:write|improve)\s+your\s+own\s+(?:prompt|skill|goal|loop)\b|\bmake\s+yourself\s+able\s+to\b", lower):
320
+ return out("self-authoring", "execute", "low", "Self-authoring workflow request.")
321
+
322
+ if re.search(r"\bwhat\s+do\s+we\s+call\s+this\b|\badd\b.*\bto\s+the\s+glossary\b|\bwrite\s+an\s+adr\b", lower):
323
+ return out("domain-model", "execute", "low", "Glossary or ADR domain-modeling request.")
324
+
325
+ if re.search(r"\bresearch\b.*\bwrite\s+it\s+up\b|\bgather\s+the\s+docs\s+on\b", lower):
326
+ return out("research", "question", "low", "Cited repository research note request.")
327
+
328
+ if re.search(rf"\bwhich\s+flow\s+fits\b|\bwhat'?s\s+the\s+process\s+for\b|\bexplain\s+the\s+(?:{brand_names})\s+workflow\b", lower):
329
+ return out("flows", "question", "low", "Workflow explanation request.")
330
+
331
+ if re.search(r"\btdd\b|\btest-first\b|\bred-green-refactor\b|\bwrite\s+integration\s+tests\b", lower):
332
+ return out("tdd", "execute", "low", "Test-first build or integration test request.")
333
+
334
+ if re.search(
335
+ r"\breview\s+the\s+architecture\b|\bwhere\s+should\s+we\s+refactor\b"
336
+ r"|\bfind\s+deepening\s+opportunities\b|\bshallow\s+modules?\b|\bmake\s+the\s+codebase\s+easier\s+for\s+agents\b",
337
+ lower,
338
+ ):
339
+ return out("architecture-review", "audit", "low", "Codebase structural refactoring scan.")
340
+
341
+ if re.search(
342
+ r"^\s*retro(?:spective)?\b|\bretrospective\b"
343
+ r"|\b(?:run|do|write|hold|start)\s+(?:a\s+|the\s+|our\s+)?retro\b"
344
+ r"|\b(?:session|sprint|post[- ]merge|project)\s+retro\b"
345
+ r"|\bwhat\s+should\s+we\s+change\s+after\s+this\s+session\b",
346
+ lower,
347
+ ):
348
+ return out("retro", "audit", "low", "Session retrospective request.")
349
+
350
+ if re.search(r"\bmake\s+me\s+a\s+setup\s+script\b|\bwalk\s+me\s+through\s+setting\s+up\b|\bsteps\s+only\s+a\s+human\s+can\s+do\b", lower):
351
+ return out("wizard", "execute", "low", "Guided human-step wizard request.")
352
+
353
+ if re.search(r"\bteach\s+me\b.*\bover\s+the\s+next\b|\bmake\s+me\s+a\s+course\b|\bcontinue\s+my\s+course\b", lower):
354
+ return out("course", "question", "low", "Multi-session learning course request.")
355
+
356
+ if re.search(r"\bwrite\s+questions\s+for\s+the\s+client\b|\bmake\s+a\s+questionnaire\b", lower):
357
+ return out("questionnaire", "question", "low", "Stakeholder questionnaire request.")
358
+
359
+ if re.search(r"\bwait,\s+what\??|\bi'?m\s+lost\b|\bsay\s+that\s+again\s+simply\b|\btoo\s+dense\b", lower):
360
+ return out("re-explain", "question", "low", "Plain-language re-explanation request.")
361
+
362
+ if re.search(
363
+ r"\bhand\s+this\s+off\b|\bwrite\s+a\s+handoff\b|\bcontinue\s+in\s+a\s+new\s+session\b|\bstart\s+a\s+background\s+agent\s+on\s+the\s+rest\b",
364
+ lower,
365
+ ):
366
+ return out("handoff", "execute", "low", "Session handoff document request.")
367
+
368
+ if re.search(r"\bblock\s+dangerous\s+git\b|\b(?:add|set\s+up)\s+git\s+safety\s+hooks\b|\bstop\s+the\s+agent\s+from\s+force-pushing\b", lower):
369
+ return out("git-guardrails", "execute", "low", "Git safety hook setup request.")
370
+
371
+ if re.search(
372
+ r"\b(?:add|set\s+up)\s+pre-commit\s+hooks\b|\bset\s+up\s+(?:husky|lint-staged|lefthook|pre-commit)\b|\bformat\s+and\s+typecheck\s+on\s+commit\b",
373
+ lower,
374
+ ):
375
+ return out("pre-commit", "execute", "low", "Pre-commit hook setup request.")
376
+
377
+ if re.search(
378
+ r"\bbe\s+my\s+chief\s+of\s+staff\b|\bgoing\s+to\s+bed\b|\bkeep\s+going\s+until\b"
379
+ r"|(?:^|[.;,]\s*)loop\s+until\b|\b(?:run|iterate|work|keep\s+running)\s+in\s+a\s+loop\s+until\b"
380
+ r"|\bloop\s+until\s+(?:it'?s?\s+|all\s+)?(?:green|done|passing|passes|clean|tests?\s+pass)\b"
381
+ r"|\bkeep\s+pushing\s+(?:it|this\s+goal)\s+forward\s+across\s+sessions\b|\bown\s+this\s+(?:goal|migration)\b",
382
+ lower,
383
+ ):
384
+ return out("run-a-goal", "execute", "low", "Sustained autonomous goal execution request.")
385
+
386
+ if re.search(r"\b(?:scrape|pull|archive)\b.*\b(?:page|video|channel|playlist)\b|\bget\s+his\s+diagram\b", lower):
387
+ return out("scrape", "execute", "low", "Media or page archive request.")
388
+
389
+ if re.search(r"\bwayfinder\b|\bchart\s+the\s+way\b|\bplan\s+this\s+migration\s+before\s+anyone\s+builds\b", lower):
390
+ return out("wayfinder", "chart", "high", "Multi-session foggy route mapping request.")
391
+
392
+ if re.search(
393
+ r"\b(?:rename|extract|dedupe)\b"
394
+ r"|^\s*inline\b|\binline\s+(?:the|this|that|these|those|helper|function|method|variable|const|class|module)\b"
395
+ r"|\b(?:port|rewrite|migrate)\b.*\bto\s+another\s+language\b|\b(?:port|rewrite)\b.*\bpreserving\s+behavior\b",
396
+ lower,
397
+ ):
398
+ return out("refactoring", "execute", "low", "Behavior-preserving structural change.")
399
+
400
+ if re.search(r"\bsecurity-audit\b|\baudit\s+every\s+pr\b|\badd\s+a\s+security\s+gate\b|\bsecurity\s+audit\s+of\b", lower):
401
+ return out("security-audit", "audit", "low", "Security audit request.")
402
+
403
+ if re.search(r"\brun\s+pr-agent\b|\bwith\s+pr-agent\b", lower):
404
+ return out("pr-agent", "audit", "low", "PR-Agent review pass request.")
405
+
406
+ if re.search(r"\bis\s+there\s+a\s+(?:library|project|example)\s+for\b|\bfind\s+something\s+we\s+can\s+(?:fork|copy)\b", lower):
407
+ return out("prior-art", "question", "low", "Prior-art search request.")
408
+
409
+ if re.search(r"\binner[- ]loop\b|\b(?:ai\s+)?code\s+slop\b|\bblock\s+agent\s+slop\b", lower):
410
+ return out("inner-loop", "audit" if re.search(r"\baudit\b", lower) else "execute", "low",
411
+ "Inner-loop gate hardening or audit request.")
412
+
413
+ if re.search(
414
+ r"\brun\s+(?:an?\s+|the\s+)?(?:skill|prompt|workflow|routing)\s+eval(?:s|uation)?\b"
415
+ r"|\beval\s+(?:playbook|suite)\b|\bcompare\s+(?:this|the)\s+(?:skill|prompt)\s+against\s+(?:baseline|the\s+version\s+without)\b",
416
+ lower,
417
+ ):
418
+ return out("eval", "audit", "low", "Skill or workflow evaluation request.")
419
+
420
+ if re.search(
421
+ r"\bhillclimb\b|\bautoresearch\b|\boptimize\s+(?:this|the)\s+(?:metric|score|pass\s+rate|throughput|latency)\s+(?:in\s+a\s+loop|iteratively|until)\b",
422
+ lower,
423
+ ):
424
+ return out("hillclimb", "execute", "low", "Iterative metric-improvement loop request.")
425
+
426
+ if re.search(
427
+ r"\bvisual[- ]e2e\b|\be2e\s+video\b|\brecord\s+(?:a\s+|an\s+)?(?:visual\s+)?e2e\s+(?:video|recording|walkthrough)\b"
428
+ r"|\bvisual\s+e2e\s+(?:recording|review)\b",
429
+ lower,
430
+ ):
431
+ return out("visual-e2e", "execute", "low", "Visual E2E recording and image-review request.")
432
+
433
+ if re.search(r"\bopen[- ]design[- ]evidence\b|\bpenpot\b|\beditable\s+design\s+evidence\b", lower):
434
+ return out("open-design-evidence", "execute", "low", "Editable design evidence or Penpot workflow request.")
435
+
436
+ if re.search(
437
+ r"\bagent[- ]collaboration\b|\bacp\s+session\s+identity\b|\bnative\s+sibling\s+messaging\b|\bmulti[- ]agent\s+handoff\s+mechanics\b",
438
+ lower,
439
+ ):
440
+ return out("agent-collaboration", "question", "low", "Native agent collaboration and ACP handoff mechanics.")
441
+
442
+ if re.search(r"\btool[- ]routing\b|\btool\s+router\b|\bwhich\s+(?:tool|capability|mcp)\s+should\s+(?:we|i)\s+use\b", lower):
443
+ return out("tool-routing", "question", "low", "Tool and capability routing request.")
444
+
445
+ if re.search(
446
+ r"\bprototype\s+(?:this|it|both|the\s+two|to\s+settle)\b|\bbuild\s+a\s+(?:quick|throwaway|empirical)\s+prototype\b"
447
+ r"|\bsettle\s+(?:this|the)\s+fork\s+by\s+(?:running|prototyping)\b",
448
+ lower,
449
+ ):
450
+ return out("prototype", "execute", "low", "Empirical prototype to settle a technical fork.")
451
+
452
+ if re.search(r"\bopen(?:ing)?\s+(?:a|the)\s+pr\b|\bcut\s+a\s+pr\s+for\s+(?:this|my)\s+branch\b|\bprepare\s+(?:this|my)\s+branch\s+for\s+a\s+pr\b", lower):
453
+ return out("opening-a-pr", "execute", "low", "PR preparation and opening workflow.")
454
+
455
+ if re.search(r"\bship\s+(?:this|the)\s+(?:pr|branch|change|release)\b|\bshipping\s+playbook\b|\bverify\s+trunk\s+after\s+merge\b", lower):
456
+ return out("shipping", "execute", "low", "PR shipping and post-merge verification workflow.")
457
+
458
+ if re.search(r"\bpause[- ]safely\b|\bpause\s+(?:this|work|for\s+now)\s+safely\b|\bstop\s+for\s+now\s+and\s+(?:save|leave)\s+a\s+resume\s+note\b", lower):
459
+ return out("pause-safely", "execute", "low", "Safe pause and resume-note capture.")
460
+
461
+ if re.search(r"\bsession[- ]pickup\b|\bpick\s+up\s+(?:this|the|a)\s+(?:handoff|paused\s+session)\b|\bresume\s+from\s+(?:this|the)\s+(?:handoff|resume\s+note)\b", lower):
462
+ return out("session-pickup", "execute", "low", "Resuming work from a handoff or paused session.")
463
+
464
+ if re.search(r"\bworktree[- ]cleanup\b|\bclean\s*up\s+(?:(?:old|stale|merged|my|the)\s+)*(?:git\s+)?worktrees?\b|\bprune\s+(?:stale\s+)?(?:git\s+)?worktrees?\b", lower):
465
+ return out("worktree-cleanup", "execute", "low", "Git worktree and branch cleanup.")
466
+
467
+ if re.search(
468
+ r"\bworkspace[- ]map\b"
469
+ r"|\b(?:index|map|reindex|sync)\s+(?:(?:this|the|my|our)\s+)?(?:workspace|repo\s+symbols?|codebase\s+symbols?)\b"
470
+ r"|\b(?:list|show|map|inspect)\s+(?:(?:my|our|all|active|open|current)\s+)*(?:(?:orca|git)\s+)?worktrees?\b"
471
+ r"|\b(?:list|show)\s+(?:(?:my|our|all)\s+)?open\s+prs?\b"
472
+ r"|\b(?:find|search|locate|query|lookup|look\s+up)\s+(?:a\s+|the\s+|this\s+)?symbols?\b",
473
+ lower,
474
+ ):
475
+ return out("workspace-map", "question", "low", "Workspace, worktree, PR, or FTS5 symbol index lookup.")
476
+
477
+ if re.search(r"\bvisual[- ]parity\b|\bpixel[- ]exact\s+(?:ui|match|parity)\b|\bpixel[- ]diff\s+zero\b|\bmatch\s+(?:this|the)\s+(?:figma|mockup|screenshot)\s+pixel\b", lower):
478
+ return out("visual-parity", "execute", "low", "Pixel-exact UI visual parity work.")
479
+
480
+ if re.search(r"\breference[- ]rebuild\b|\brebuild\s+(?:this|our|the)\s+ui\s+(?:to\s+match|like)\b|\bclone\s+the\s+ui\s+of\b", lower):
481
+ return out("reference-rebuild", "execute", "low", "UI rebuild against a named reference app.")
482
+
483
+ if re.search(r"\bruntime[- ]forensics\b|\bdebug\s+(?:a|this)\s+live\s+(?:symptom|process|hanging\s+service)\b|\bdiagnose\s+(?:why|this)\s+live\s+(?:server|process|worker)\b", lower):
484
+ return out("runtime-forensics", "audit", "low", "Live runtime symptom forensics.")
485
+
486
+ if re.search(r"\btrace[- ]forensics\b|\b(?:cpu\s+profile|flame\s*graph|heap\s+dump|heap\s+snapshot|memory\s+leak\s+trace|perf\s+trace)\b", lower):
487
+ return out("trace-forensics", "audit", "low", "Profile, trace, or heap-dump forensics.")
488
+
489
+ if re.search(r"\bwhat\s+stack\b|\bpick\s+(?:a|the)\s+stack\b", lower) and not GREENFIELD_LEAD_RE.search(text):
490
+ return out("deep-stack", "question", "low", "Stack choice only, no build requested.")
491
+
492
+ if re.search(
493
+ r"\bend[- ]to[- ]end\b.*\b(?:product|project|app)\b|\b(?:product|project|app)\b.*\bend[- ]to[- ]end\b"
494
+ r"|\bdon'?t\s+stop\s+at\s+(?:a|the)\s+(?:first\s+)?(?:slice|mvp)\b|\bidea\s+into\s+a\s+complete\b",
495
+ lower,
496
+ ):
497
+ return out("end-to-end", "execute", "low", "Full-scope product delivery across every slice.")
498
+
499
+ if TOURNAMENT_EXPLICIT_RE.search(text):
500
+ vagueness = "high" if anchors == 0 else "medium"
501
+ return out(
502
+ "tournament",
503
+ "discover",
504
+ vagueness,
505
+ "Prompt asks for tournament competition or architecture and research gap discovery.",
506
+ checkpoint=True,
507
+ )
508
+
509
+ if OPEN_AMBITION_RE.search(text) and anchors <= 1:
510
+ return out(
511
+ "tournament",
512
+ "discover",
513
+ "high",
514
+ "High-level open architectural or research ambition without concrete implementation anchors.",
515
+ checkpoint=True,
516
+ )
517
+
518
+ if re.search(r"^(?:how|where|why|what|are\s+we\s+sure|explain\s+(?:how|why|the))\b", lower) and not re.search(
519
+ r"\b(?:fix|build|implement|add|change|rethink|propose|make|create|remove|delete|update)\b", lower
520
+ ):
521
+ return out("investigation", "question", "low", "Read-only codebase question.")
522
+
523
+ if re.search(
524
+ r"\b(?:\d+(?:\.\d+)?x\s+slower|got\s+slower|slowness|p9[59]\s+went\s+from|p9[59]\s+(?:tail\s+)?latency|tail\s+latency|latency\s+regression|cache\s+misses|memory\s+layout|hits\s+oom|optimize\s+(?:the\s+)?(?:server|db\s+pooling|memory\s+layout|throughput|latency))\b",
525
+ lower,
526
+ ):
527
+ return out("perf-issue", "execute", "low", "Measured performance regression.")
528
+
529
+ gf_match = GREENFIELD_LEAD_RE.search(text)
530
+ if gf_match and (empty_dir or re.search(r"\bnew\s+(?:app|tool|cli|service|site)\b", lower)):
531
+ remainder = text[gf_match.end():].strip(" .,:;-")
532
+ has_behavior = bool(
533
+ remainder
534
+ and (
535
+ count_concrete_anchors(remainder) >= 1
536
+ or CONCRETE_ACTION_VERB_RE.search(remainder)
537
+ or re.search(r"\bthat\s+\w+|\bfor\s+\w+ing\b", remainder, re.I)
538
+ )
539
+ )
540
+ if has_behavior:
541
+ return out("prior-art", "execute", "low", "Greenfield app with concrete behaviors starts at prior-art.")
542
+ return out(
543
+ "tournament",
544
+ "execute",
545
+ "high",
546
+ "Greenfield request has no concrete behaviors yet, so explore competing system shapes first.",
547
+ checkpoint=False,
548
+ )
549
+
550
+ if re.search(
551
+ r"\b(?:find\s+out\s+why\s+and\s+fix|wrong\s+total|is\s+wrong|typo|bug|crash(?:es|ed|ing)?|fail(?:s|ed|ing)"
552
+ r"|throws?\b|broken|regression|error\b|500\b|redirect\s+loop|deadlock|race\s+condition|should\s+be)\b",
553
+ lower,
554
+ ) or (re.search(r"\bfix\b", lower) and not re.search(r"\bfix\s+(?:everything|it\s+all)\b", lower)):
555
+ return out("bug-fix", "execute", "low", "Concrete defect reproduction and fix.")
556
+
557
+ if anchors >= 1 or (CONCRETE_ACTION_VERB_RE.search(text) and CONCRETE_SURFACE_RE.search(text)):
558
+ return out("feature", "execute", "low", "Concrete feature request with identifiable target behavior.")
559
+
560
+ if CONCRETE_ACTION_VERB_RE.search(text):
561
+ return out(
562
+ "grill",
563
+ "stress-test",
564
+ "medium",
565
+ "Goal names an action without concrete UI or API details, so resolve decisions before coding.",
566
+ checkpoint=False,
567
+ )
568
+
569
+ return out(
570
+ "tournament",
571
+ "discover",
572
+ "high",
573
+ "Underspecified goal with no concrete file, symbol, or behavioral anchor.",
574
+ checkpoint=True,
575
+ )
576
+
577
+
578
+ def reject_unsafe_root(root_arg: Path) -> Path:
579
+ if root_arg.is_symlink():
580
+ raise SystemExit(f"project root cannot be a symlink: {root_arg}")
581
+ resolved = root_arg.resolve()
582
+ if not resolved.is_dir():
583
+ raise SystemExit(f"project root does not exist: {resolved}")
584
+ if resolved.parent == resolved:
585
+ raise SystemExit(f"refusing filesystem root as project root: {resolved}")
586
+ forbidden = {Path.home().resolve(), Path(tempfile.gettempdir()).resolve()}
587
+ for extra in ("/tmp", "/var/tmp", "/private/tmp"):
588
+ p = Path(extra)
589
+ if p.exists():
590
+ forbidden.add(p.resolve())
591
+ if resolved in forbidden:
592
+ raise SystemExit(f"refusing home or system temp directory as project root: {resolved}")
593
+ return resolved
594
+
595
+
596
+ def ensure_contained(target: Path, root: Path) -> Path:
597
+ resolved_root = reject_unsafe_root(root)
598
+ if target.is_symlink():
599
+ raise SystemExit(f"refusing symlink path: {target}")
600
+ resolved_target = target.resolve()
601
+ try:
602
+ rel_parts = resolved_target.relative_to(resolved_root).parts
603
+ except ValueError as err:
604
+ raise SystemExit(f"path {resolved_target} escapes project root {resolved_root}") from err
605
+ probe = resolved_root
606
+ for part in rel_parts:
607
+ probe = probe / part
608
+ if probe.is_symlink():
609
+ raise SystemExit(f"refusing symlink component inside root: {probe}")
610
+ return resolved_target
611
+
612
+
613
+ def atomic_write_text(target: Path, content: str, root: Path) -> None:
614
+ safe_target = ensure_contained(target, root)
615
+ safe_parent = ensure_contained(safe_target.parent, root)
616
+ safe_parent.mkdir(parents=True, exist_ok=True)
617
+ fd, tmp_name = tempfile.mkstemp(prefix=f".{safe_target.name}.", suffix=".tmp", dir=str(safe_parent))
618
+ tmp_path = Path(tmp_name)
619
+ try:
620
+ with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as handle:
621
+ handle.write(content)
622
+ if safe_target.is_symlink():
623
+ raise SystemExit(f"refusing symlink target: {safe_target}")
624
+ deadline = time.monotonic() + 2.0
625
+ while True:
626
+ try:
627
+ os.replace(tmp_path, safe_target)
628
+ break
629
+ except PermissionError:
630
+ if os.name != "nt" or time.monotonic() >= deadline:
631
+ raise
632
+ time.sleep(0.02)
633
+ except BaseException:
634
+ with contextlib.suppress(OSError):
635
+ tmp_path.unlink()
636
+ raise
637
+
638
+
639
+ def ensure_scratch_gitignore(root: Path) -> Path:
640
+ scratch = ensure_contained(root / ".scratch", root)
641
+ scratch.mkdir(parents=True, exist_ok=True)
642
+ gitignore = ensure_contained(scratch / ".gitignore", root)
643
+ if not gitignore.exists():
644
+ atomic_write_text(gitignore, "*\n", root)
645
+ return scratch
646
+
647
+
648
+ class BracketLock:
649
+ def __init__(self, lock_path: Path, wait_seconds: float = 10.0) -> None:
650
+ self.lock_path = lock_path
651
+ self.wait_seconds = wait_seconds
652
+ self.fh = None
653
+
654
+ def __enter__(self):
655
+ if self.lock_path.is_symlink():
656
+ raise SystemExit(f"refusing symlink lockfile: {self.lock_path}")
657
+ self.fh = open(self.lock_path, "a+", encoding="utf-8")
658
+ deadline = time.monotonic() + self.wait_seconds
659
+ while True:
660
+ try:
661
+ if os.name == "nt":
662
+ import msvcrt
663
+
664
+ self.fh.seek(0)
665
+ msvcrt.locking(self.fh.fileno(), msvcrt.LK_NBLCK, 1)
666
+ else:
667
+ import fcntl
668
+
669
+ fcntl.flock(self.fh.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
670
+ return self
671
+ except OSError:
672
+ if time.monotonic() >= deadline:
673
+ self._close()
674
+ raise SystemExit(f"timed out waiting for tournament lock: {self.lock_path}") from None
675
+ time.sleep(0.02)
676
+
677
+ def _close(self) -> None:
678
+ if self.fh is not None:
679
+ with contextlib.suppress(OSError):
680
+ if os.name == "nt":
681
+ import msvcrt
682
+
683
+ self.fh.seek(0)
684
+ msvcrt.locking(self.fh.fileno(), msvcrt.LK_UNLCK, 1)
685
+ self.fh.close()
686
+ self.fh = None
687
+
688
+ def __exit__(self, *exc) -> None:
689
+ self._close()
690
+
691
+
692
+ def select_lenses(count: int) -> list[dict]:
693
+ if count == 12:
694
+ chosen = list(LENSES)
695
+ elif count == 8:
696
+ chosen = [row for row in LENSES if row[0] in EIGHT_IDS]
697
+ elif count == 4:
698
+ chosen = [row for row in LENSES if row[0] in FOUR_IDS]
699
+ else:
700
+ raise SystemExit("--entrants must be 12, 8, or 4")
701
+ return [
702
+ {"id": eid, "pod": pod, "default_gap_kind": kind, "mandate": mandate, "status": "active", "pitch": None, "grafts": []}
703
+ for eid, pod, kind, mandate in chosen
704
+ ]
705
+
706
+
707
+ def build_matches(entrants: list[dict]) -> list[dict]:
708
+ n = len(entrants)
709
+ ids = [e["id"] for e in entrants]
710
+ if n == 12:
711
+ return [
712
+ {"id": "pod-a", "round": 1, "label": "Pod A (Architecture and boundaries)", "entrants": ids[0:3], "next_match": "sf-1", "rebuttals": [], "result": None},
713
+ {"id": "pod-b", "round": 1, "label": "Pod B (SOTA research and prior art)", "entrants": ids[3:6], "next_match": "sf-1", "rebuttals": [], "result": None},
714
+ {"id": "pod-c", "round": 1, "label": "Pod C (Premise and product strategy)", "entrants": ids[6:9], "next_match": "sf-2", "rebuttals": [], "result": None},
715
+ {"id": "pod-d", "round": 1, "label": "Pod D (Subtraction, scale, and red-team)", "entrants": ids[9:12], "next_match": "sf-2", "rebuttals": [], "result": None},
716
+ {"id": "sf-1", "round": 2, "label": "Semifinal 1 (Architecture vs research)", "entrants": [], "next_match": "final", "rebuttals": [], "result": None},
717
+ {"id": "sf-2", "round": 2, "label": "Semifinal 2 (Premise vs resilience)", "entrants": [], "next_match": "final", "rebuttals": [], "result": None},
718
+ {"id": "final", "round": 3, "label": "Championship final", "entrants": [], "next_match": None, "rebuttals": [], "result": None},
719
+ ]
720
+ if n == 8:
721
+ return [
722
+ {"id": "qf-1", "round": 1, "label": "Quarterfinal 1", "entrants": ids[0:2], "next_match": "sf-1", "rebuttals": [], "result": None},
723
+ {"id": "qf-2", "round": 1, "label": "Quarterfinal 2", "entrants": ids[2:4], "next_match": "sf-1", "rebuttals": [], "result": None},
724
+ {"id": "qf-3", "round": 1, "label": "Quarterfinal 3", "entrants": ids[4:6], "next_match": "sf-2", "rebuttals": [], "result": None},
725
+ {"id": "qf-4", "round": 1, "label": "Quarterfinal 4", "entrants": ids[6:8], "next_match": "sf-2", "rebuttals": [], "result": None},
726
+ {"id": "sf-1", "round": 2, "label": "Semifinal 1", "entrants": [], "next_match": "final", "rebuttals": [], "result": None},
727
+ {"id": "sf-2", "round": 2, "label": "Semifinal 2", "entrants": [], "next_match": "final", "rebuttals": [], "result": None},
728
+ {"id": "final", "round": 3, "label": "Championship final", "entrants": [], "next_match": None, "rebuttals": [], "result": None},
729
+ ]
730
+ return [
731
+ {"id": "sf-1", "round": 1, "label": "Semifinal 1", "entrants": ids[0:2], "next_match": "final", "rebuttals": [], "result": None},
732
+ {"id": "sf-2", "round": 1, "label": "Semifinal 2", "entrants": ids[2:4], "next_match": "final", "rebuttals": [], "result": None},
733
+ {"id": "final", "round": 2, "label": "Championship final", "entrants": [], "next_match": None, "rebuttals": [], "result": None},
734
+ ]
735
+
736
+
737
+ def validate_https_url(text: str) -> dict:
738
+ parsed = urllib.parse.urlsplit(text)
739
+ if parsed.scheme != "https" or not parsed.hostname or re.search(r"\s", text):
740
+ raise SystemExit(f"URL receipt must be an https:// URL with a public host: {text!r}")
741
+ host = parsed.hostname.lower().rstrip(".")
742
+ if host == "localhost" or host.endswith((".localhost", ".local", ".internal")):
743
+ raise SystemExit(f"URL receipt cannot target local or internal host: {host}")
744
+ try:
745
+ ip = ipaddress.ip_address(host)
746
+ except ValueError:
747
+ ip = None
748
+ if ip is not None and not ip.is_global:
749
+ raise SystemExit(f"URL receipt cannot target non-public IP address: {host}")
750
+ return {"kind": "url", "raw": text}
751
+
752
+
753
+ def validate_receipt(raw: str, root: Path) -> dict:
754
+ text = raw.strip()
755
+ if not text:
756
+ raise SystemExit("receipt cannot be empty")
757
+ if text.startswith("http://"):
758
+ raise SystemExit("URL receipt must use https://, not http://")
759
+ if text.startswith("https://"):
760
+ return validate_https_url(text)
761
+ if text.startswith("cmd:"):
762
+ body = text[4:].strip()
763
+ if "->" not in body:
764
+ raise SystemExit("probe receipt must use 'cmd:<command> -> <observed output>'")
765
+ cmd_part, out_part = [p.strip() for p in body.split("->", 1)]
766
+ if not cmd_part or not out_part:
767
+ raise SystemExit("probe receipt needs both command and observed output")
768
+ return {"kind": "probe", "raw": text}
769
+ match = re.match(r"^(.+?):(\d+)(?:-(\d+))?$", text)
770
+ if not match:
771
+ raise SystemExit(
772
+ f"invalid receipt {text!r}: expected '<repo-rel-path>:<line>', 'https://...', or 'cmd:<cmd> -> <out>'"
773
+ )
774
+ rel_path, start_s, end_s = match.group(1), match.group(2), match.group(3)
775
+ rel_obj = Path(rel_path)
776
+ if rel_path.startswith(("/", "\\")) or rel_obj.is_absolute() or rel_obj.drive or ".." in rel_obj.parts:
777
+ raise SystemExit(f"repo receipt must be a relative path inside root without '..': {rel_path}")
778
+ candidate = ensure_contained(root / rel_obj, root)
779
+ if not candidate.is_file():
780
+ raise SystemExit(f"receipt file does not exist inside root: {rel_path}")
781
+ line_count = max(1, len(candidate.read_bytes().splitlines()))
782
+ start = int(start_s)
783
+ end = int(end_s) if end_s else start
784
+ if start < 1 or end < start or end > line_count:
785
+ raise SystemExit(f"receipt line {start}-{end} out of range for {rel_path} ({line_count} lines)")
786
+ return {"kind": "repo", "raw": text}
787
+
788
+
789
+ def load_state(tdir: Path) -> tuple[Path, Path, dict]:
790
+ if tdir.is_symlink():
791
+ raise SystemExit(f"refusing symlink tournament directory: {tdir}")
792
+ resolved_dir = tdir.resolve()
793
+ raw_state_path = resolved_dir / "bracket.json"
794
+ if raw_state_path.is_symlink() or not raw_state_path.is_file():
795
+ raise SystemExit(f"missing or unsafe tournament state: {raw_state_path}")
796
+ state = json.loads(raw_state_path.read_text(encoding="utf-8"))
797
+ slug = str(state.get("slug", ""))
798
+ if not SLUG_RE.fullmatch(slug):
799
+ raise SystemExit(f"invalid slug in tournament state: {slug!r}")
800
+ root = reject_unsafe_root(Path(str(state.get("root", ""))))
801
+ expected = ensure_contained(root / ".scratch" / "tournaments" / slug / "bracket.json", root)
802
+ if raw_state_path != expected:
803
+ raise SystemExit(f"tournament state {raw_state_path} does not match contained path {expected}")
804
+ return expected, root, state
805
+
806
+
807
+ def save_state(state_path: Path, root: Path, state: dict) -> None:
808
+ atomic_write_text(state_path, json.dumps(state, indent=2) + "\n", root)
809
+
810
+
811
+ @contextlib.contextmanager
812
+ def state_transaction(tdir_arg: str):
813
+ tdir = Path(tdir_arg)
814
+ if tdir.is_symlink():
815
+ raise SystemExit(f"refusing symlink tournament directory: {tdir}")
816
+ resolved_dir = tdir.resolve()
817
+ if (
818
+ not SLUG_RE.fullmatch(resolved_dir.name)
819
+ or resolved_dir.parent.name != "tournaments"
820
+ or resolved_dir.parent.parent.name != ".scratch"
821
+ ):
822
+ raise SystemExit(f"tournament directory must be <root>/.scratch/tournaments/<slug>: {resolved_dir}")
823
+ inferred_root = reject_unsafe_root(resolved_dir.parent.parent.parent)
824
+ lock_path = ensure_contained(resolved_dir / "bracket.lock", inferred_root)
825
+ with BracketLock(lock_path):
826
+ locked_path, locked_root, locked_state = load_state(tdir)
827
+ yield locked_path, locked_root, locked_state
828
+ save_state(locked_path, locked_root, locked_state)
829
+
830
+
831
+ def require_nonempty(value: str, flag: str) -> str:
832
+ cleaned = (value or "").lstrip("\ufeff").strip()
833
+ if not cleaned:
834
+ raise SystemExit(f"{flag} must be non-empty")
835
+ return cleaned
836
+
837
+
838
+ def read_prompt_arg(inline_value: str, use_stdin: bool, flag: str) -> str:
839
+ raw = sys.stdin.read() if (use_stdin or inline_value == "-") else inline_value
840
+ return require_nonempty(raw, flag)
841
+
842
+
843
+ def find_entrant(state: dict, entrant_id: str) -> dict:
844
+ for entrant in state["entrants"]:
845
+ if entrant["id"] == entrant_id:
846
+ return entrant
847
+ raise SystemExit(f"unknown entrant: {entrant_id}")
848
+
849
+
850
+ def find_match(state: dict, match_id: str) -> dict:
851
+ for match in state["matches"]:
852
+ if match["id"] == match_id:
853
+ return match
854
+ raise SystemExit(f"unknown match: {match_id}")
855
+
856
+
857
+ def unfinished_feeders(state: dict, match_id: str) -> list[str]:
858
+ return [m["id"] for m in state["matches"] if m["next_match"] == match_id and m["result"] is None]
859
+
860
+
861
+ def propagate_forfeits(state: dict) -> None:
862
+ changed = True
863
+ while changed:
864
+ changed = False
865
+ for match in state["matches"]:
866
+ if match["result"] is not None or unfinished_feeders(state, match["id"]):
867
+ continue
868
+ active = [eid for eid in match["entrants"] if find_entrant(state, eid)["status"] == "active"]
869
+ if active:
870
+ continue
871
+ has_feeders = any(m["next_match"] == match["id"] for m in state["matches"])
872
+ if (match["entrants"] or has_feeders) and all(
873
+ find_entrant(state, eid)["status"] == "dropout" for eid in match["entrants"]
874
+ ):
875
+ match["result"] = {
876
+ "winner": None,
877
+ "losers": [],
878
+ "forfeit": True,
879
+ "judge_model": "forfeit",
880
+ "verified_receipt": None,
881
+ "rationale": "All entrants in match dropped out.",
882
+ "graft": None,
883
+ }
884
+ changed = True
885
+
886
+
887
+ def match_is_ready(state: dict, match: dict) -> bool:
888
+ if match["result"] is not None or unfinished_feeders(state, match["id"]):
889
+ return False
890
+ active = [eid for eid in match["entrants"] if find_entrant(state, eid)["status"] == "active"]
891
+ return len(active) >= 1 and all(find_entrant(state, eid)["pitch"] is not None for eid in active)
892
+
893
+
894
+ def fallback_runner_up(state: dict, champion_id: str) -> str | None:
895
+ for match in reversed(state["matches"]):
896
+ res = match["result"]
897
+ if not res or res.get("forfeit"):
898
+ continue
899
+ for lid in res["losers"]:
900
+ if lid != champion_id and find_entrant(state, lid)["pitch"] is not None:
901
+ return lid
902
+ return None
903
+
904
+
905
+ def detect_repo_signals(root_arg: str) -> tuple[bool, bool]:
906
+ if not root_arg:
907
+ return False, False
908
+ rpath = Path(root_arg).resolve()
909
+ if not rpath.is_dir():
910
+ return False, False
911
+ has_factory = (rpath / "factory.json").is_file()
912
+ entries = [p.name for p in rpath.iterdir() if p.name not in {".scratch", ".DS_Store"}]
913
+ empty_dir = len(entries) == 0
914
+ return has_factory, empty_dir
915
+
916
+
917
+ def cmd_route(args: argparse.Namespace) -> int:
918
+ prompt = read_prompt_arg(args.prompt, args.stdin, "prompt")
919
+ auto_factory, auto_empty = detect_repo_signals(args.root)
920
+ verdict = classify_prompt(
921
+ prompt,
922
+ has_factory=args.has_factory or auto_factory,
923
+ empty_dir=args.empty_dir or auto_empty,
924
+ )
925
+ if args.json:
926
+ print(json.dumps(verdict, indent=2))
927
+ else:
928
+ gate = "checkpoint" if verdict["checkpoint_before_code"] else "direct"
929
+ print(f"mode={verdict['mode']} intent={verdict['intent']} vagueness={verdict['vagueness']} gate={gate}")
930
+ print(f"reason: {verdict['reason']}")
931
+ return 0
932
+
933
+
934
+ def cmd_init(args: argparse.Namespace) -> int:
935
+ root = reject_unsafe_root(Path(args.root))
936
+ if not SLUG_RE.fullmatch(args.slug):
937
+ raise SystemExit("--slug must be kebab-case (a-z0-9 and '-')")
938
+ prompt = read_prompt_arg(args.prompt, args.prompt_stdin, "--prompt")
939
+ scratch = ensure_scratch_gitignore(root)
940
+ tdir = ensure_contained(scratch / "tournaments" / args.slug, root)
941
+ state_path = ensure_contained(tdir / "bracket.json", root)
942
+ tdir.mkdir(parents=True, exist_ok=True)
943
+ lock_path = ensure_contained(tdir / "bracket.lock", root)
944
+ with BracketLock(lock_path):
945
+ if state_path.exists() and not args.force:
946
+ raise SystemExit(f"tournament already exists at {state_path} (pass --force to overwrite)")
947
+ entrants = select_lenses(args.entrants)
948
+ state = {
949
+ "slug": args.slug,
950
+ "root": str(root),
951
+ "prompt": prompt,
952
+ "entrant_count": len(entrants),
953
+ "entrants": entrants,
954
+ "matches": build_matches(entrants),
955
+ "champion": None,
956
+ "runner_up": None,
957
+ }
958
+ save_state(state_path, root, state)
959
+ payload = {"dir": str(tdir), "entrant_count": len(entrants), "entrants": entrants, "matches": state["matches"]}
960
+ if args.json:
961
+ print(json.dumps(payload, indent=2))
962
+ else:
963
+ print(f"initialized {len(entrants)}-entrant tournament at {tdir}")
964
+ return 0
965
+
966
+
967
+ def cmd_pitch(args: argparse.Namespace) -> int:
968
+ title = require_nonempty(args.title, "--title")
969
+ thesis = require_nonempty(args.thesis, "--thesis")
970
+ with state_transaction(args.dir) as (_, root, state):
971
+ entrant = find_entrant(state, args.entrant)
972
+ if entrant["status"] != "active":
973
+ raise SystemExit(f"entrant {args.entrant} is {entrant['status']}")
974
+ if any(match["result"] is not None and args.entrant in match["entrants"] for match in state["matches"]):
975
+ raise SystemExit(f"entrant {args.entrant} has an already judged match; its pitch is frozen")
976
+ receipts = [validate_receipt(r, root) for r in args.receipt]
977
+ entrant["pitch"] = {
978
+ "title": title,
979
+ "thesis": thesis,
980
+ "gap_kind": args.gap_kind,
981
+ "receipts": receipts,
982
+ "counter_risk": (args.counter_risk or "").strip(),
983
+ }
984
+ noun = "receipt" if len(receipts) == 1 else "receipts"
985
+ print(f"recorded pitch for {args.entrant} ({len(receipts)} submitted {noun})")
986
+ return 0
987
+
988
+
989
+ def cmd_rebut(args: argparse.Namespace) -> int:
990
+ attack = require_nonempty(args.attack, "--attack")
991
+ with state_transaction(args.dir) as (_, root, state):
992
+ match = find_match(state, args.match)
993
+ if match["result"] is not None:
994
+ raise SystemExit(f"match {args.match} is already judged")
995
+ pending = unfinished_feeders(state, args.match)
996
+ if pending:
997
+ raise SystemExit(f"match {args.match} waits on feeder matches: {', '.join(pending)}")
998
+ for eid in (args.entrant, args.target):
999
+ if eid not in match["entrants"]:
1000
+ raise SystemExit(f"{eid} is not in match {args.match}")
1001
+ ent = find_entrant(state, eid)
1002
+ if ent["status"] != "active":
1003
+ raise SystemExit(f"entrant {eid} is {ent['status']} and cannot participate in rebuttals")
1004
+ if ent["pitch"] is None:
1005
+ raise SystemExit(f"entrant {eid} has not submitted a pitch yet")
1006
+ if args.entrant == args.target:
1007
+ raise SystemExit("--entrant and --target must differ")
1008
+ receipt = validate_receipt(args.receipt, root)
1009
+ match["rebuttals"].append({
1010
+ "entrant": args.entrant,
1011
+ "target": args.target,
1012
+ "attack": attack,
1013
+ "receipt": receipt,
1014
+ })
1015
+ print(f"recorded rebuttal in {args.match}: {args.entrant} against {args.target}")
1016
+ return 0
1017
+
1018
+
1019
+ def cmd_dropout(args: argparse.Namespace) -> int:
1020
+ reason = require_nonempty(args.reason, "--reason")
1021
+ with state_transaction(args.dir) as (_, _, state):
1022
+ if state["champion"] == args.entrant:
1023
+ raise SystemExit(f"cannot mark crowned champion {args.entrant} as dropout")
1024
+ entrant = find_entrant(state, args.entrant)
1025
+ if entrant["status"] != "active":
1026
+ raise SystemExit(f"entrant {args.entrant} is already {entrant['status']}")
1027
+ entrant["status"] = "dropout"
1028
+ entrant["dropout_reason"] = reason
1029
+ propagate_forfeits(state)
1030
+ print(f"marked {args.entrant} as dropout")
1031
+ return 0
1032
+
1033
+
1034
+ def cmd_judge(args: argparse.Namespace) -> int:
1035
+ judge_model = require_nonempty(args.judge_model, "--judge-model")
1036
+ rationale = require_nonempty(args.rationale, "--rationale")
1037
+ with state_transaction(args.dir) as (_, root, state):
1038
+ match = find_match(state, args.match)
1039
+ if match["result"] is not None:
1040
+ raise SystemExit(f"match {args.match} is already judged")
1041
+ pending = unfinished_feeders(state, args.match)
1042
+ if pending:
1043
+ raise SystemExit(f"match {args.match} waits on feeder matches: {', '.join(pending)}")
1044
+ active = [eid for eid in match["entrants"] if find_entrant(state, eid)["status"] == "active"]
1045
+ if len(active) < 1:
1046
+ raise SystemExit(f"match {args.match} has no active entrants")
1047
+ unpitched = [eid for eid in active if find_entrant(state, eid)["pitch"] is None]
1048
+ if unpitched:
1049
+ raise SystemExit(f"match {args.match} has entrants without pitches: {', '.join(unpitched)}")
1050
+ if args.winner not in active:
1051
+ raise SystemExit(f"winner {args.winner} is not an active entrant in {args.match}")
1052
+ verified = validate_receipt(args.verified_receipt, root)
1053
+ losers = [eid for eid in active if eid != args.winner]
1054
+ graft_record = None
1055
+ if args.graft or args.graft_from:
1056
+ if not (args.graft and args.graft_from):
1057
+ raise SystemExit("--graft and --graft-from must be provided together")
1058
+ graft_text = require_nonempty(args.graft, "--graft")
1059
+ if args.graft_from not in losers:
1060
+ raise SystemExit(f"--graft-from {args.graft_from} is not an eliminated opponent in {args.match}")
1061
+ graft_record = {"from": args.graft_from, "match": args.match, "insight": graft_text}
1062
+ find_entrant(state, args.winner)["grafts"].append(graft_record)
1063
+
1064
+ for lid in losers:
1065
+ find_entrant(state, lid)["status"] = "eliminated"
1066
+
1067
+ match["result"] = {
1068
+ "winner": args.winner,
1069
+ "losers": losers,
1070
+ "judge_model": judge_model,
1071
+ "verified_receipt": verified,
1072
+ "rationale": rationale,
1073
+ "graft": graft_record,
1074
+ }
1075
+ if match["next_match"]:
1076
+ nxt = find_match(state, match["next_match"])
1077
+ if args.winner not in nxt["entrants"]:
1078
+ nxt["entrants"].append(args.winner)
1079
+ else:
1080
+ state["champion"] = args.winner
1081
+ state["runner_up"] = losers[0] if losers else fallback_runner_up(state, args.winner)
1082
+
1083
+ print(f"match {args.match}: winner={args.winner} (advanced to {match['next_match'] or 'champion'})")
1084
+ return 0
1085
+
1086
+
1087
+ def cmd_status(args: argparse.Namespace) -> int:
1088
+ _, _, state = load_state(Path(args.dir))
1089
+ pending_pitches = [e["id"] for e in state["entrants"] if e["status"] == "active" and e["pitch"] is None]
1090
+ ready_matches = [m["id"] for m in state["matches"] if match_is_ready(state, m)]
1091
+ summary = {
1092
+ "slug": state["slug"],
1093
+ "entrant_count": state["entrant_count"],
1094
+ "pending_pitches": pending_pitches,
1095
+ "ready_matches": ready_matches,
1096
+ "champion": state["champion"],
1097
+ "runner_up": state["runner_up"],
1098
+ }
1099
+ if args.json:
1100
+ print(json.dumps(summary, indent=2))
1101
+ else:
1102
+ print(
1103
+ f"slug={summary['slug']} champion={summary['champion']} "
1104
+ f"pending_pitches={len(pending_pitches)} ready_matches={ready_matches}"
1105
+ )
1106
+ return 0
1107
+
1108
+
1109
+ def render_markdown(state: dict) -> str:
1110
+ if not state["champion"]:
1111
+ raise SystemExit("cannot render proposal before Championship final is judged")
1112
+ champ = find_entrant(state, state["champion"])
1113
+ cp = champ["pitch"]
1114
+ lines = [
1115
+ f"# Tournament proposal: {cp['title']}",
1116
+ "",
1117
+ f"**Prompt:** {state['prompt']}",
1118
+ f"**Champion lens:** `{champ['id']}` ({cp['gap_kind']} gap)",
1119
+ "",
1120
+ "## Champion thesis",
1121
+ "",
1122
+ cp["thesis"],
1123
+ "",
1124
+ "### Submitted receipts (not independently verified)",
1125
+ ]
1126
+ for r in cp["receipts"]:
1127
+ lines.append(f"- [{r['kind']}] `{r['raw']}`")
1128
+ lines.extend(["", "### Judge-verified receipts"])
1129
+ for match in state["matches"]:
1130
+ result = match["result"]
1131
+ if result and result["winner"] == champ["id"] and result["verified_receipt"]:
1132
+ lines.append(f"- `{match['id']}` (judge `{result['judge_model']}`): `{result['verified_receipt']['raw']}`")
1133
+ if champ["grafts"]:
1134
+ lines.extend(["", "### Grafted insights from eliminated contenders"])
1135
+ for g in champ["grafts"]:
1136
+ lines.append(f"- From `{g['from']}` ({g['match']}): {g['insight']}")
1137
+ if cp.get("counter_risk"):
1138
+ lines.extend(["", f"**Primary risk to watch:** {cp['counter_risk']}"])
1139
+
1140
+ final_res = find_match(state, "final")["result"]
1141
+ if state["runner_up"]:
1142
+ ru = find_entrant(state, state["runner_up"])
1143
+ rp = ru["pitch"]
1144
+ lines.extend([
1145
+ "",
1146
+ f"## Runner-up counter-thesis: {rp['title']} (`{ru['id']}`)",
1147
+ "",
1148
+ rp["thesis"],
1149
+ "",
1150
+ f"**Why Champion won the final:** {final_res['rationale']} "
1151
+ f"(judge `{final_res['judge_model']}`, checked `{final_res['verified_receipt']['raw']}`).",
1152
+ ])
1153
+ else:
1154
+ lines.extend([
1155
+ "",
1156
+ "## Runner-up counter-thesis",
1157
+ "",
1158
+ "No opposing finalist survived upstream dropouts.",
1159
+ ])
1160
+
1161
+ lines.extend(["", "## Bracket ledger", ""])
1162
+ for m in state["matches"]:
1163
+ res = m["result"]
1164
+ if not res:
1165
+ continue
1166
+ if res.get("forfeit") or res["winner"] is None:
1167
+ lines.append(f"- **{m['label']} (`{m['id']}`)**: forfeited (all entrants dropped out).")
1168
+ continue
1169
+ graft_note = f", grafted from `{res['graft']['from']}`" if res["graft"] else ""
1170
+ outcome = (
1171
+ f"beat {', '.join(f'`{x}`' for x in res['losers'])}"
1172
+ if res["losers"]
1173
+ else "advanced unopposed"
1174
+ )
1175
+ lines.append(
1176
+ f"- **{m['label']} (`{m['id']}`)**: `{res['winner']}` {outcome} "
1177
+ f"(judge `{res['judge_model']}`, verified `{res['verified_receipt']['raw']}`{graft_note}). {res['rationale']}"
1178
+ )
1179
+
1180
+ gate_prompt = (
1181
+ "Discovery-only requests: reply with **Champion**, **Runner-Up**, or a constraint adjustment before implementation."
1182
+ if state["runner_up"]
1183
+ else "Discovery-only requests: reply with **Champion** or a constraint adjustment before implementation."
1184
+ )
1185
+ gate_prompt += (
1186
+ " For an original build request, continue with Champion within the existing delivery scope"
1187
+ " unless the user asked to choose first."
1188
+ )
1189
+ lines.extend(["", "## Decision gate", "", gate_prompt])
1190
+ return "\n".join(lines) + "\n"
1191
+
1192
+
1193
+ def cmd_render(args: argparse.Namespace) -> int:
1194
+ state_path, root, state = load_state(Path(args.dir))
1195
+ md = render_markdown(state)
1196
+ if args.out:
1197
+ raw_out = Path(args.out)
1198
+ candidate = raw_out if raw_out.is_absolute() else (root / raw_out)
1199
+ else:
1200
+ candidate = state_path.parent / "proposal.md"
1201
+ out_path = ensure_contained(candidate, root)
1202
+ atomic_write_text(out_path, md, root)
1203
+ print(md, end="")
1204
+ return 0
1205
+
1206
+
1207
+ def build_parser() -> argparse.ArgumentParser:
1208
+ parser = argparse.ArgumentParser(description="deepmodebot auto-router and tournament bracket engine")
1209
+ sub = parser.add_subparsers(dest="subcommand", required=True)
1210
+
1211
+ p_route = sub.add_parser("route", help="classify user prompt intent and vagueness")
1212
+ p_route.add_argument("prompt", nargs="?", default="")
1213
+ p_route.add_argument("--stdin", action="store_true")
1214
+ p_route.add_argument("--root", default="")
1215
+ p_route.add_argument("--has-factory", action="store_true")
1216
+ p_route.add_argument("--empty-dir", action="store_true")
1217
+ p_route.add_argument("--json", action="store_true")
1218
+ p_route.set_defaults(func=cmd_route)
1219
+
1220
+ p_init = sub.add_parser("init", help="initialize a contained tournament bracket")
1221
+ p_init.add_argument("--root", required=True)
1222
+ p_init.add_argument("--slug", required=True)
1223
+ p_init.add_argument("--prompt", default="")
1224
+ p_init.add_argument("--prompt-stdin", action="store_true")
1225
+ p_init.add_argument("--entrants", type=int, default=12, choices=(4, 8, 12))
1226
+ p_init.add_argument("--force", action="store_true")
1227
+ p_init.add_argument("--json", action="store_true")
1228
+ p_init.set_defaults(func=cmd_init)
1229
+
1230
+ p_pitch = sub.add_parser("pitch", help="record a receipt-backed entrant proposal")
1231
+ p_pitch.add_argument("--dir", required=True)
1232
+ p_pitch.add_argument("--entrant", required=True)
1233
+ p_pitch.add_argument("--title", required=True)
1234
+ p_pitch.add_argument("--thesis", required=True)
1235
+ p_pitch.add_argument("--gap-kind", required=True, choices=("architecture", "research", "hybrid"))
1236
+ p_pitch.add_argument("--receipt", action="append", required=True)
1237
+ p_pitch.add_argument("--counter-risk", default="")
1238
+ p_pitch.set_defaults(func=cmd_pitch)
1239
+
1240
+ p_rebut = sub.add_parser("rebut", help="record an evidence-backed rebuttal inside a match")
1241
+ p_rebut.add_argument("--dir", required=True)
1242
+ p_rebut.add_argument("--match", required=True)
1243
+ p_rebut.add_argument("--entrant", required=True)
1244
+ p_rebut.add_argument("--target", required=True)
1245
+ p_rebut.add_argument("--attack", required=True)
1246
+ p_rebut.add_argument("--receipt", required=True)
1247
+ p_rebut.set_defaults(func=cmd_rebut)
1248
+
1249
+ p_drop = sub.add_parser("dropout", help="mark an entrant as dropped out")
1250
+ p_drop.add_argument("--dir", required=True)
1251
+ p_drop.add_argument("--entrant", required=True)
1252
+ p_drop.add_argument("--reason", required=True)
1253
+ p_drop.set_defaults(func=cmd_dropout)
1254
+
1255
+ p_judge = sub.add_parser("judge", help="record an independent judge verdict and advance winner")
1256
+ p_judge.add_argument("--dir", required=True)
1257
+ p_judge.add_argument("--match", required=True)
1258
+ p_judge.add_argument("--winner", required=True)
1259
+ p_judge.add_argument("--judge-model", required=True)
1260
+ p_judge.add_argument("--verified-receipt", required=True)
1261
+ p_judge.add_argument("--rationale", required=True)
1262
+ p_judge.add_argument("--graft-from", default="")
1263
+ p_judge.add_argument("--graft", default="")
1264
+ p_judge.set_defaults(func=cmd_judge)
1265
+
1266
+ p_status = sub.add_parser("status", help="inspect bracket progress")
1267
+ p_status.add_argument("--dir", required=True)
1268
+ p_status.add_argument("--json", action="store_true")
1269
+ p_status.set_defaults(func=cmd_status)
1270
+
1271
+ p_render = sub.add_parser("render", help="render final Champion and Runner-Up proposal")
1272
+ p_render.add_argument("--dir", required=True)
1273
+ p_render.add_argument("--out", default="")
1274
+ p_render.set_defaults(func=cmd_render)
1275
+ return parser
1276
+
1277
+
1278
+ def main(argv: list[str] | None = None) -> int:
1279
+ parser = build_parser()
1280
+ args = parser.parse_args(argv)
1281
+ return args.func(args)
1282
+
1283
+
1284
+ if __name__ == "__main__":
1285
+ sys.exit(main())