deepmodebot 0.0.0-stage → 0.9.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 (312) 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 +229 -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/package.json +44 -4
  12. package/plugins/deepmodebot/.antigravity-plugin/plugin.json +35 -0
  13. package/plugins/deepmodebot/.antigravity-plugin/skills/deep/SKILL.md +13 -0
  14. package/plugins/deepmodebot/.antigravity-plugin/skills/land-pr/SKILL.md +23 -0
  15. package/plugins/deepmodebot/.antigravity-plugin/skills/pr-thread/SKILL.md +17 -0
  16. package/plugins/deepmodebot/.antigravity-plugin/skills/review-pr/SKILL.md +16 -0
  17. package/plugins/deepmodebot/.antigravity-plugin/skills/tournament/SKILL.md +14 -0
  18. package/plugins/deepmodebot/.claude-plugin/plugin.json +27 -0
  19. package/plugins/deepmodebot/agents/reviewer/agent.md +33 -0
  20. package/plugins/deepmodebot/agents/scout/agent.md +34 -0
  21. package/plugins/deepmodebot/agents/security-reviewer/agent.md +30 -0
  22. package/plugins/deepmodebot/assets/logo.svg +8 -0
  23. package/plugins/deepmodebot/commands/contribute.md +8 -0
  24. package/plugins/deepmodebot/commands/deep.md +11 -0
  25. package/plugins/deepmodebot/commands/land-pr.md +12 -0
  26. package/plugins/deepmodebot/commands/pr-thread.md +14 -0
  27. package/plugins/deepmodebot/commands/project-brief.md +8 -0
  28. package/plugins/deepmodebot/commands/review-pr.md +10 -0
  29. package/plugins/deepmodebot/commands/tournament.md +12 -0
  30. package/plugins/deepmodebot/hooks/hooks.json +26 -0
  31. package/plugins/deepmodebot/hooks.json +24 -0
  32. package/plugins/deepmodebot/mcp_config.json +11 -0
  33. package/plugins/deepmodebot/scripts/antigravity-guard.mjs +413 -0
  34. package/plugins/deepmodebot/scripts/omp-mcp-server.mjs +1091 -0
  35. package/plugins/deepmodebot/skills/agent-harnesses/SKILL.md +57 -0
  36. package/plugins/deepmodebot/skills/agent-harnesses/assets/sdks/bun.lock +391 -0
  37. package/plugins/deepmodebot/skills/agent-harnesses/assets/sdks/check.ts +53 -0
  38. package/plugins/deepmodebot/skills/agent-harnesses/assets/sdks/check_antigravity.py +38 -0
  39. package/plugins/deepmodebot/skills/agent-harnesses/assets/sdks/check_claude.mjs +11 -0
  40. package/plugins/deepmodebot/skills/agent-harnesses/assets/sdks/package.json +11 -0
  41. package/plugins/deepmodebot/skills/agent-harnesses/assets/sdks/requirements.txt +1 -0
  42. package/plugins/deepmodebot/skills/agent-harnesses/references/ai-native-tooling.md +190 -0
  43. package/plugins/deepmodebot/skills/agent-harnesses/references/ai-sdk-selection.md +50 -0
  44. package/plugins/deepmodebot/skills/agent-harnesses/references/antigravity.md +108 -0
  45. package/plugins/deepmodebot/skills/agent-harnesses/references/claude-code.md +166 -0
  46. package/plugins/deepmodebot/skills/agent-harnesses/references/codex.md +151 -0
  47. package/plugins/deepmodebot/skills/agent-harnesses/references/delegation-efficiency.md +230 -0
  48. package/plugins/deepmodebot/skills/agent-harnesses/references/langchain-ecosystem.md +124 -0
  49. package/plugins/deepmodebot/skills/agent-harnesses/references/omp.md +183 -0
  50. package/plugins/deepmodebot/skills/agent-harnesses/references/protocols.md +172 -0
  51. package/plugins/deepmodebot/skills/agent-harnesses/references/sdks.md +228 -0
  52. package/plugins/deepmodebot/skills/agent-harnesses/references/self-authoring.md +171 -0
  53. package/plugins/deepmodebot/skills/cloud-devsecops/SKILL.md +24 -0
  54. package/plugins/deepmodebot/skills/cloud-devsecops/references/aws.md +264 -0
  55. package/plugins/deepmodebot/skills/cloud-devsecops/references/azure.md +261 -0
  56. package/plugins/deepmodebot/skills/cloud-devsecops/references/containers.md +96 -0
  57. package/plugins/deepmodebot/skills/cloud-devsecops/references/devops-tools.md +297 -0
  58. package/plugins/deepmodebot/skills/cloud-devsecops/references/devsecops-pipeline.md +258 -0
  59. package/plugins/deepmodebot/skills/cloud-devsecops/references/gcp.md +258 -0
  60. package/plugins/deepmodebot/skills/cloud-devsecops/references/kubernetes.md +74 -0
  61. package/plugins/deepmodebot/skills/cloud-devsecops/references/local-emulators.md +265 -0
  62. package/plugins/deepmodebot/skills/contribute/SKILL.md +134 -0
  63. package/plugins/deepmodebot/skills/create-verification-skill/LICENSE +21 -0
  64. package/plugins/deepmodebot/skills/create-verification-skill/SKILL.md +101 -0
  65. package/plugins/deepmodebot/skills/create-verification-skill/references/feature-map-example/README.md +47 -0
  66. package/plugins/deepmodebot/skills/create-verification-skill/references/feature-map-example/create-note.md +39 -0
  67. package/plugins/deepmodebot/skills/create-verification-skill/references/feature-map-example/search.md +45 -0
  68. package/plugins/deepmodebot/skills/deep-stack/SKILL.md +53 -0
  69. package/plugins/deepmodebot/skills/deep-stack/references/AGENTS.template.md +52 -0
  70. package/plugins/deepmodebot/skills/deep-stack/references/agentic-workflow.md +114 -0
  71. package/plugins/deepmodebot/skills/deep-stack/references/any-app-stack.md +51 -0
  72. package/plugins/deepmodebot/skills/deep-stack/references/design-workflow.md +101 -0
  73. package/plugins/deepmodebot/skills/deep-stack/references/isolate.md +23 -0
  74. package/plugins/deepmodebot/skills/deep-stack/references/philosophy.md +306 -0
  75. package/plugins/deepmodebot/skills/deep-stack/references/prove.md +31 -0
  76. package/plugins/deepmodebot/skills/deep-stack/references/stack.md +119 -0
  77. package/plugins/deepmodebot/skills/deep-stack/references/structure.md +22 -0
  78. package/plugins/deepmodebot/skills/deep-stack/references/unslop/LICENSE +21 -0
  79. package/plugins/deepmodebot/skills/deep-stack/references/unslop/unslop.md +80 -0
  80. package/plugins/deepmodebot/skills/deepmodebot/LICENSE +23 -0
  81. package/plugins/deepmodebot/skills/deepmodebot/SKILL.md +198 -0
  82. package/plugins/deepmodebot/skills/deepmodebot/assets/agents-md/agents_md.py +207 -0
  83. package/plugins/deepmodebot/skills/deepmodebot/assets/agents-md/test_agents_md.py +146 -0
  84. package/plugins/deepmodebot/skills/deepmodebot/assets/architecture-review/report-template.html +92 -0
  85. package/plugins/deepmodebot/skills/deepmodebot/assets/contain/claude-guard.sh +42 -0
  86. package/plugins/deepmodebot/skills/deepmodebot/assets/contain/claude_guard.py +135 -0
  87. package/plugins/deepmodebot/skills/deepmodebot/assets/contain/omp-contain-link.ts +12 -0
  88. package/plugins/deepmodebot/skills/deepmodebot/assets/contain/omp-contain.ts +115 -0
  89. package/plugins/deepmodebot/skills/deepmodebot/assets/contain/test_antigravity_guard.py +483 -0
  90. package/plugins/deepmodebot/skills/deepmodebot/assets/contain/test_audit_regressions.py +139 -0
  91. package/plugins/deepmodebot/skills/deepmodebot/assets/contain/test_contain.py +301 -0
  92. package/plugins/deepmodebot/skills/deepmodebot/assets/contain/test_omp_mcp.py +602 -0
  93. package/plugins/deepmodebot/skills/deepmodebot/assets/e2e/design.py +242 -0
  94. package/plugins/deepmodebot/skills/deepmodebot/assets/e2e/evidence.py +293 -0
  95. package/plugins/deepmodebot/skills/deepmodebot/assets/e2e/record.py +387 -0
  96. package/plugins/deepmodebot/skills/deepmodebot/assets/e2e/review.py +339 -0
  97. package/plugins/deepmodebot/skills/deepmodebot/assets/e2e/test_design.py +69 -0
  98. package/plugins/deepmodebot/skills/deepmodebot/assets/e2e/test_evidence.py +160 -0
  99. package/plugins/deepmodebot/skills/deepmodebot/assets/e2e/test_record.py +180 -0
  100. package/plugins/deepmodebot/skills/deepmodebot/assets/e2e/test_review.py +265 -0
  101. package/plugins/deepmodebot/skills/deepmodebot/assets/git-guardrails/git-guard-patterns.txt +44 -0
  102. package/plugins/deepmodebot/skills/deepmodebot/assets/git-guardrails/git-guard.sh +132 -0
  103. package/plugins/deepmodebot/skills/deepmodebot/assets/git-guardrails/git-guard.ts +122 -0
  104. package/plugins/deepmodebot/skills/deepmodebot/assets/git-guardrails/test_git_guard.py +192 -0
  105. package/plugins/deepmodebot/skills/deepmodebot/assets/github-app/bot.py +3037 -0
  106. package/plugins/deepmodebot/skills/deepmodebot/assets/github-app/brand.json +11 -0
  107. package/plugins/deepmodebot/skills/deepmodebot/assets/github-app/brand.py +51 -0
  108. package/plugins/deepmodebot/skills/deepmodebot/assets/github-app/ghapp.py +361 -0
  109. package/plugins/deepmodebot/skills/deepmodebot/assets/github-app/install.py +274 -0
  110. package/plugins/deepmodebot/skills/deepmodebot/assets/github-app/local_updates.py +576 -0
  111. package/plugins/deepmodebot/skills/deepmodebot/assets/github-app/review_context.py +204 -0
  112. package/plugins/deepmodebot/skills/deepmodebot/assets/github-app/test_bot.py +2182 -0
  113. package/plugins/deepmodebot/skills/deepmodebot/assets/github-app/test_brand.py +19 -0
  114. package/plugins/deepmodebot/skills/deepmodebot/assets/github-app/test_local_updates.py +691 -0
  115. package/plugins/deepmodebot/skills/deepmodebot/assets/github-app/test_review_context.py +127 -0
  116. package/plugins/deepmodebot/skills/deepmodebot/assets/github-app/test_workspace_cleanup.py +496 -0
  117. package/plugins/deepmodebot/skills/deepmodebot/assets/github-app/workspace_cleanup.py +351 -0
  118. package/plugins/deepmodebot/skills/deepmodebot/assets/loop/loop.py +2394 -0
  119. package/plugins/deepmodebot/skills/deepmodebot/assets/loop/plan.py +583 -0
  120. package/plugins/deepmodebot/skills/deepmodebot/assets/loop/test_loop.py +1426 -0
  121. package/plugins/deepmodebot/skills/deepmodebot/assets/loop/test_plan.py +320 -0
  122. package/plugins/deepmodebot/skills/deepmodebot/assets/loop/test_windows_job.py +326 -0
  123. package/plugins/deepmodebot/skills/deepmodebot/assets/loop/windows_job.py +244 -0
  124. package/plugins/deepmodebot/skills/deepmodebot/assets/perf-audit/bench_harness.py +165 -0
  125. package/plugins/deepmodebot/skills/deepmodebot/assets/perf-audit/perf_audit.py +240 -0
  126. package/plugins/deepmodebot/skills/deepmodebot/assets/perf-audit/test_bench_harness.py +55 -0
  127. package/plugins/deepmodebot/skills/deepmodebot/assets/perf-audit/test_perf_audit.py +53 -0
  128. package/plugins/deepmodebot/skills/deepmodebot/assets/pr-agent/diff_coverage.py +350 -0
  129. package/plugins/deepmodebot/skills/deepmodebot/assets/pr-agent/pr_agent_local.py +370 -0
  130. package/plugins/deepmodebot/skills/deepmodebot/assets/pr-agent/test_diff_coverage.py +94 -0
  131. package/plugins/deepmodebot/skills/deepmodebot/assets/pr-conversation/arena.html +425 -0
  132. package/plugins/deepmodebot/skills/deepmodebot/assets/pr-conversation/arena.py +579 -0
  133. package/plugins/deepmodebot/skills/deepmodebot/assets/pr-conversation/arena_tui.py +839 -0
  134. package/plugins/deepmodebot/skills/deepmodebot/assets/pr-conversation/font8x8_basic.hex +1 -0
  135. package/plugins/deepmodebot/skills/deepmodebot/assets/pr-conversation/show_thread.py +329 -0
  136. package/plugins/deepmodebot/skills/deepmodebot/assets/pr-conversation/test_arena.py +610 -0
  137. package/plugins/deepmodebot/skills/deepmodebot/assets/repo-references.json +637 -0
  138. package/plugins/deepmodebot/skills/deepmodebot/assets/scrape/test_yt_enrich.py +250 -0
  139. package/plugins/deepmodebot/skills/deepmodebot/assets/scrape/yt_enrich.py +1820 -0
  140. package/plugins/deepmodebot/skills/deepmodebot/assets/scrape/yt_meta.py +156 -0
  141. package/plugins/deepmodebot/skills/deepmodebot/assets/scrape/yt_transcript_relay.js +54 -0
  142. package/plugins/deepmodebot/skills/deepmodebot/assets/security-audit/audit-pr.sh +122 -0
  143. package/plugins/deepmodebot/skills/deepmodebot/assets/security-audit/gate.cjs +155 -0
  144. package/plugins/deepmodebot/skills/deepmodebot/assets/security-audit/prompt.md +13 -0
  145. package/plugins/deepmodebot/skills/deepmodebot/assets/tournament/test_tournament.py +654 -0
  146. package/plugins/deepmodebot/skills/deepmodebot/assets/tournament/tournament.py +1285 -0
  147. package/plugins/deepmodebot/skills/deepmodebot/assets/wizard/wizard.sh +234 -0
  148. package/plugins/deepmodebot/skills/deepmodebot/assets/workspace-map/test_workspace_map.py +879 -0
  149. package/plugins/deepmodebot/skills/deepmodebot/assets/workspace-map/workspace_map.py +2436 -0
  150. package/plugins/deepmodebot/skills/deepmodebot/references/README.md +61 -0
  151. package/plugins/deepmodebot/skills/deepmodebot/references/catalog.md +105 -0
  152. package/plugins/deepmodebot/skills/deepmodebot/references/contain.md +39 -0
  153. package/plugins/deepmodebot/skills/deepmodebot/references/factory-landscape.md +147 -0
  154. package/plugins/deepmodebot/skills/deepmodebot/references/flows.md +50 -0
  155. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/authoring-a-skill.md +37 -0
  156. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/babysit.md +77 -0
  157. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/bug-fix.md +34 -0
  158. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/end-to-end.md +50 -0
  159. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/eval.md +39 -0
  160. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/feature.md +60 -0
  161. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/handoff.md +52 -0
  162. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/hillclimb.md +46 -0
  163. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/investigation.md +20 -0
  164. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/opening-a-pr.md +97 -0
  165. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/pause-safely.md +30 -0
  166. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/perf-issue.md +31 -0
  167. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/phased-build.md +146 -0
  168. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/prototype.md +31 -0
  169. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/refactoring.md +60 -0
  170. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/reference-rebuild.md +45 -0
  171. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/run-a-goal.md +143 -0
  172. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/runtime-forensics.md +22 -0
  173. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/self-authoring.md +130 -0
  174. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/session-pickup.md +33 -0
  175. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/setup.md +105 -0
  176. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/shipping.md +52 -0
  177. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/spec.md +67 -0
  178. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/tickets.md +56 -0
  179. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/trace-forensics.md +24 -0
  180. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/triage.md +102 -0
  181. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/visual-parity.md +19 -0
  182. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/wayfinder.md +44 -0
  183. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/work-a-queue.md +189 -0
  184. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/worktree-cleanup.md +35 -0
  185. package/plugins/deepmodebot/skills/deepmodebot/references/principles/attack-the-premise.md +7 -0
  186. package/plugins/deepmodebot/skills/deepmodebot/references/principles/boundary-discipline.md +8 -0
  187. package/plugins/deepmodebot/skills/deepmodebot/references/principles/build-the-lever.md +8 -0
  188. package/plugins/deepmodebot/skills/deepmodebot/references/principles/encode-lessons-in-structure.md +6 -0
  189. package/plugins/deepmodebot/skills/deepmodebot/references/principles/exhaust-the-design-space.md +4 -0
  190. package/plugins/deepmodebot/skills/deepmodebot/references/principles/experience-first.md +7 -0
  191. package/plugins/deepmodebot/skills/deepmodebot/references/principles/explain-the-number.md +9 -0
  192. package/plugins/deepmodebot/skills/deepmodebot/references/principles/fix-root-causes.md +6 -0
  193. package/plugins/deepmodebot/skills/deepmodebot/references/principles/foundational-thinking.md +9 -0
  194. package/plugins/deepmodebot/skills/deepmodebot/references/principles/guard-the-context-window.md +7 -0
  195. package/plugins/deepmodebot/skills/deepmodebot/references/principles/laziness-protocol.md +6 -0
  196. package/plugins/deepmodebot/skills/deepmodebot/references/principles/make-operations-idempotent.md +7 -0
  197. package/plugins/deepmodebot/skills/deepmodebot/references/principles/migrate-callers-then-delete-legacy-apis.md +5 -0
  198. package/plugins/deepmodebot/skills/deepmodebot/references/principles/minimize-reader-load.md +7 -0
  199. package/plugins/deepmodebot/skills/deepmodebot/references/principles/model-the-domain.md +7 -0
  200. package/plugins/deepmodebot/skills/deepmodebot/references/principles/never-block-on-the-human.md +7 -0
  201. package/plugins/deepmodebot/skills/deepmodebot/references/principles/outcome-oriented-execution.md +6 -0
  202. package/plugins/deepmodebot/skills/deepmodebot/references/principles/prove-it-works.md +8 -0
  203. package/plugins/deepmodebot/skills/deepmodebot/references/principles/redesign-from-first-principles.md +7 -0
  204. package/plugins/deepmodebot/skills/deepmodebot/references/principles/separate-before-serializing-shared-state.md +6 -0
  205. package/plugins/deepmodebot/skills/deepmodebot/references/principles/sequence-verifiable-units.md +7 -0
  206. package/plugins/deepmodebot/skills/deepmodebot/references/principles/subtract-before-you-add.md +6 -0
  207. package/plugins/deepmodebot/skills/deepmodebot/references/principles/test-behavior-not-implementation.md +7 -0
  208. package/plugins/deepmodebot/skills/deepmodebot/references/principles/type-system-discipline.md +6 -0
  209. package/plugins/deepmodebot/skills/deepmodebot/references/rust-migration-case-studies.md +26 -0
  210. package/plugins/deepmodebot/skills/deepmodebot/references/startup-ideas.md +21 -0
  211. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/agent-collaboration.md +82 -0
  212. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/architect.md +32 -0
  213. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/architecture-review.md +43 -0
  214. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/arena.md +20 -0
  215. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/benchmark-checklist.md +31 -0
  216. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/blast-radius.md +19 -0
  217. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/correct.md +20 -0
  218. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/course.md +47 -0
  219. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/coworkers.md +70 -0
  220. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/domain-model.md +69 -0
  221. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/figure-it-out.md +25 -0
  222. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/git-guardrails.md +44 -0
  223. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/github-app.md +160 -0
  224. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/goal-review.md +156 -0
  225. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/grill.md +27 -0
  226. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/how.md +23 -0
  227. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/in-your-own-words.md +12 -0
  228. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/inner-loop.md +39 -0
  229. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/interrogate.md +16 -0
  230. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/issue-conversation.md +52 -0
  231. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/no-comments.md +29 -0
  232. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/open-design-evidence.md +65 -0
  233. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/panel.md +34 -0
  234. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/pr-agent.md +39 -0
  235. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/pr-conversation.md +135 -0
  236. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/pr-review.md +138 -0
  237. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/pre-commit.md +31 -0
  238. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/prior-art.md +44 -0
  239. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/questionnaire.md +46 -0
  240. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/re-explain.md +23 -0
  241. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/recall.md +19 -0
  242. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/reflect.md +20 -0
  243. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/research.md +99 -0
  244. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/retro.md +30 -0
  245. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/scrape.md +32 -0
  246. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/security-audit.md +40 -0
  247. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/sharpen.md +15 -0
  248. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/show-me-your-work.md +19 -0
  249. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/sme-review.md +49 -0
  250. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/swarm.md +14 -0
  251. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/tdd.md +55 -0
  252. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/teach.md +20 -0
  253. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/technical-writing.md +22 -0
  254. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/tool-routing.md +85 -0
  255. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/tournament.md +44 -0
  256. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/tracker.md +78 -0
  257. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/unslop.md +15 -0
  258. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/visual-e2e.md +78 -0
  259. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/why.md +31 -0
  260. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/wizard.md +25 -0
  261. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/workspace-map.md +35 -0
  262. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/writing-for-agents.md +66 -0
  263. package/plugins/deepmodebot/skills/deepmodebot/scripts/check_skill.py +93 -0
  264. package/plugins/deepmodebot/skills/deepmodebot/scripts/trending.py +598 -0
  265. package/plugins/deepmodebot/skills/domain-rules/SKILL.md +131 -0
  266. package/plugins/deepmodebot/skills/domain-rules/references/agent-engineering.md +105 -0
  267. package/plugins/deepmodebot/skills/domain-rules/references/ai-concepts.md +103 -0
  268. package/plugins/deepmodebot/skills/domain-rules/references/aws-networking.md +121 -0
  269. package/plugins/deepmodebot/skills/domain-rules/references/backend-system-design.md +162 -0
  270. package/plugins/deepmodebot/skills/domain-rules/references/data-structures-and-cache-optimization.md +48 -0
  271. package/plugins/deepmodebot/skills/domain-rules/references/devops-and-fundamentals.md +137 -0
  272. package/plugins/deepmodebot/skills/domain-rules/references/engineering-practice.md +100 -0
  273. package/plugins/deepmodebot/skills/domain-rules/references/high-scale-server-optimization.md +181 -0
  274. package/plugins/deepmodebot/skills/domain-rules/references/language-ecosystems.md +56 -0
  275. package/plugins/deepmodebot/skills/frontend-ui/SKILL.md +146 -0
  276. package/plugins/deepmodebot/skills/frontend-ui/references/patterns/live-demos.md +38 -0
  277. package/plugins/deepmodebot/skills/frontend-ui/references/patterns/mobbin-shipped-apps.md +28 -0
  278. package/plugins/deepmodebot/skills/frontend-ui/references/patterns/motion-clips.md +269 -0
  279. package/plugins/deepmodebot/skills/frontend-ui/references/patterns/motion-graphics.md +62 -0
  280. package/plugins/deepmodebot/skills/frontend-ui/references/patterns/pinterest-animations.md +217 -0
  281. package/plugins/deepmodebot/skills/frontend-ui/references/patterns/pinterest-patterns.md +101 -0
  282. package/plugins/deepmodebot/skills/frontend-ui/references/playbook/01-workflow.md +25 -0
  283. package/plugins/deepmodebot/skills/frontend-ui/references/playbook/02-review-rubric.md +21 -0
  284. package/plugins/deepmodebot/skills/frontend-ui/references/playbook/03-ai-tells.md +46 -0
  285. package/plugins/deepmodebot/skills/frontend-ui/references/playbook/04-components.md +21 -0
  286. package/plugins/deepmodebot/skills/frontend-ui/references/playbook/04a-agent-ui.md +153 -0
  287. package/plugins/deepmodebot/skills/frontend-ui/references/playbook/05-motion.md +106 -0
  288. package/plugins/deepmodebot/skills/frontend-ui/references/playbook/05a-motion-graphics.md +121 -0
  289. package/plugins/deepmodebot/skills/frontend-ui/references/playbook/06-typography-layout.md +48 -0
  290. package/plugins/deepmodebot/skills/frontend-ui/references/playbook/06a-color.md +26 -0
  291. package/plugins/deepmodebot/skills/frontend-ui/references/playbook/07-copy.md +11 -0
  292. package/plugins/deepmodebot/skills/frontend-ui/references/playbook/08-quality-floor.md +63 -0
  293. package/plugins/deepmodebot/skills/frontend-ui/references/playbook/09-steering-agents.md +13 -0
  294. package/plugins/deepmodebot/skills/maintain-verification-skill/LICENSE +21 -0
  295. package/plugins/deepmodebot/skills/maintain-verification-skill/SKILL.md +47 -0
  296. package/plugins/deepmodebot/skills/project-brief/SKILL.md +100 -0
  297. package/plugins/deepmodebot/skills/project-brief/assets/CONTRIBUTING.template.md +124 -0
  298. package/plugins/deepmodebot/skills/project-brief/assets/ISSUE_TEMPLATE/task.yml +61 -0
  299. package/plugins/deepmodebot/skills/project-brief/assets/PROJECT_BRIEF.template.md +98 -0
  300. package/plugins/deepmodebot/skills/project-brief/assets/PULL_REQUEST_TEMPLATE.md +35 -0
  301. package/plugins/deepmodebot/skills/project-brief/assets/pr-overlap.py +643 -0
  302. package/plugins/deepmodebot/skills/project-brief/assets/sync-roadmap.py +314 -0
  303. package/plugins/deepmodebot/skills/secrets-and-auth/SKILL.md +60 -0
  304. package/plugins/deepmodebot/skills/secrets-and-auth/references/agent-authentication.md +198 -0
  305. package/plugins/deepmodebot/skills/secrets-and-auth/references/leak-prevention.md +206 -0
  306. package/plugins/deepmodebot/skills/secrets-and-auth/references/logins-and-passwords.md +165 -0
  307. package/plugins/deepmodebot/skills/secrets-and-auth/references/secrets-and-env.md +182 -0
  308. package/plugins/deepmodebot/skills/software-architecture/SKILL.md +47 -0
  309. package/plugins/deepmodebot/skills/software-architecture/references/backend-infrastructure.md +273 -0
  310. package/plugins/deepmodebot/skills/software-architecture/references/databases.md +277 -0
  311. package/plugins/deepmodebot/skills/software-architecture/references/monorepos.md +210 -0
  312. package/plugins/deepmodebot/skills/software-architecture/references/ontology.md +287 -0
@@ -0,0 +1,2436 @@
1
+ #!/usr/bin/env python3
2
+ """Zero-bloat memory-mapped workspace, repo, Orca, PR, and project-state index.
3
+
4
+ python workspace_map.py sync [path] [--offline] [--no-orca] [--force-prs] [--fast]
5
+ python workspace_map.py overview [path] [--max-bytes 1400] [--offline] [--no-orca] [--fast]
6
+ python workspace_map.py query <term> [path] [--limit 15] [--all-repos] [--no-sync]
7
+ python workspace_map.py workspaces [path] [--all-repos] [--no-orca] [--fast]
8
+ python workspace_map.py prs [path] [--all-repos] [--offline] [--force-prs]
9
+ python workspace_map.py prune [--days 30]
10
+
11
+ All subcommands accept `--json`, `--db <path>`, and `--global`.
12
+ One shared SQLite DB per repo lives at `<main-checkout>/.scratch/workspace-map.db`
13
+ so linked git/Orca worktrees share the same symbol index without duplication.
14
+ No file bodies, no embeddings, no background daemon, 100% Python 3 stdlib.
15
+ """
16
+ import argparse
17
+ import ast
18
+ import concurrent.futures
19
+ import glob
20
+ import json
21
+ import os
22
+ import re
23
+ import shutil
24
+ import sqlite3
25
+ import subprocess
26
+ import sys
27
+ import time
28
+ from pathlib import Path
29
+
30
+ SCHEMA_VERSION = 2
31
+ MAX_FILE_BYTES = 256 * 1024
32
+ MAX_SIGNATURE_CHARS = 120
33
+ PR_TTL_SECONDS = 180.0
34
+ DEFAULT_OVERVIEW_BYTES = 1400
35
+ DEFAULT_PRUNE_DAYS = 30
36
+ MMAP_SIZE_BYTES = 67_108_864
37
+ MAX_DIRTY_CHECK_WORKTREES = 16
38
+ CREATE_NO_WINDOW = getattr(subprocess, "CREATE_NO_WINDOW", 0)
39
+
40
+ PR_JSON_FIELDS = (
41
+ "number,title,headRefName,baseRefName,state,isDraft,"
42
+ "mergeStateStatus,reviewDecision,url,updatedAt,statusCheckRollup"
43
+ )
44
+
45
+ SKIP_DIR_PARTS = {
46
+ ".git", ".scratch", ".worktrees", "node_modules", "__pycache__",
47
+ ".venv", "venv", ".tox", ".mypy_cache", ".pytest_cache", ".ruff_cache",
48
+ }
49
+
50
+ LOCKFILE_NAMES = {
51
+ "package-lock.json", "yarn.lock", "pnpm-lock.yaml", "cargo.lock",
52
+ "poetry.lock", "uv.lock", "composer.lock", "gemfile.lock",
53
+ "bun.lock", "bun.lockb", "flake.lock", "pipfile.lock", "podfile.lock",
54
+ "go.sum", "shrinkwrap.yaml", "npm-shrinkwrap.json",
55
+ }
56
+
57
+ SKIP_SUFFIXES = (
58
+ ".min.js", ".min.css", ".min.mjs", ".min.cjs", ".bundle.js", ".js.map", ".css.map",
59
+ )
60
+
61
+ BINARY_MEDIA_EXTS = {
62
+ # Images
63
+ ".png", ".jpg", ".jpeg", ".gif", ".webp", ".ico", ".bmp", ".tif", ".tiff",
64
+ ".psd", ".avif", ".heic", ".tga", ".exr", ".hdr", ".icns", ".svg",
65
+ # Audio / Video
66
+ ".mp3", ".wav", ".ogg", ".flac", ".m4a", ".aac", ".mp4", ".mov", ".avi",
67
+ ".mkv", ".webm",
68
+ # 3D / Game assets
69
+ ".blend", ".blend1", ".fbx", ".glb", ".gltf", ".obj", ".stl", ".dae",
70
+ ".usdz", ".usd", ".usda", ".usdc", ".abc", ".ply", ".3ds", ".uasset",
71
+ ".umap", ".pak", ".unitypackage", ".dds", ".ktx", ".ktx2",
72
+ # Archives / Binaries / Fonts / Databases
73
+ ".zip", ".tar", ".gz", ".bz2", ".xz", ".7z", ".rar", ".exe", ".dll",
74
+ ".so", ".dylib", ".pdb", ".lib", ".a", ".o", ".pyc", ".pyo", ".class",
75
+ ".jar", ".war", ".wasm", ".pdf", ".woff", ".woff2", ".ttf", ".otf", ".eot",
76
+ ".sqlite", ".sqlite3", ".db", ".bin", ".dat", ".hex", ".dmg", ".iso",
77
+ }
78
+
79
+ LANG_BY_EXT = {
80
+ ".py": "python", ".pyi": "python",
81
+ ".ts": "typescript", ".tsx": "typescript", ".mts": "typescript", ".cts": "typescript",
82
+ ".js": "javascript", ".jsx": "javascript", ".mjs": "javascript", ".cjs": "javascript",
83
+ ".rs": "rust",
84
+ ".go": "go",
85
+ ".cs": "csharp",
86
+ ".java": "java",
87
+ ".cpp": "cpp", ".cc": "cpp", ".cxx": "cpp", ".hpp": "cpp", ".hh": "cpp",
88
+ ".c": "c", ".h": "c",
89
+ ".md": "markdown", ".mdx": "markdown",
90
+ ".json": "json", ".toml": "toml", ".yaml": "yaml", ".yml": "yaml",
91
+ ".sh": "shell", ".bash": "shell", ".ps1": "powershell",
92
+ ".html": "html", ".css": "css", ".sql": "sql",
93
+ }
94
+
95
+ ENTRYPOINT_NAMES = {
96
+ "main.py", "app.py", "cli.py", "server.py", "manage.py", "run.py", "__main__.py",
97
+ "index.ts", "index.tsx", "index.js", "index.mjs", "main.ts", "main.js", "server.ts", "server.js",
98
+ "main.rs", "lib.rs", "main.go", "program.cs", "makefile", "justfile",
99
+ "package.json", "pyproject.toml", "cargo.toml", "go.mod",
100
+ }
101
+
102
+ TOP_DOC_NAMES = {"readme.md", "agents.md", "claude.md", "contributing.md", "project_brief.md"}
103
+
104
+ # Lightweight regex extractors (line-oriented to avoid catastrophic backtracking).
105
+ JS_FUNC_RE = re.compile(
106
+ r"^\s*(?:export\s+(?:default\s+)?)?(?:async\s+)?function\s*\*?\s+([A-Za-z_$][\w$]*)\s*(?:<[^>{]*>)?\s*\([^)]*\)"
107
+ )
108
+ JS_CLASS_RE = re.compile(
109
+ r"^\s*(?:export\s+(?:default\s+)?)?(?:abstract\s+)?class\s+([A-Za-z_$][\w$]*)"
110
+ )
111
+ JS_IFACE_RE = re.compile(r"^\s*(?:export\s+)?interface\s+([A-Za-z_$][\w$]*)")
112
+ JS_TYPE_RE = re.compile(r"^\s*(?:export\s+)?type\s+([A-Za-z_$][\w$]*)\s*(?:<[^>]*>)?\s*=")
113
+ JS_ENUM_RE = re.compile(r"^\s*(?:export\s+)?(?:const\s+)?enum\s+([A-Za-z_$][\w$]*)")
114
+ JS_ARROW_RE = re.compile(
115
+ r"^\s*(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=]{1,60})?=\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)\s*=>"
116
+ )
117
+
118
+ RS_FN_RE = re.compile(
119
+ r"^\s*(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?(?:unsafe\s+)?(?:const\s+)?(?:extern\s+\"[^\"]*\"\s+)?fn\s+([A-Za-z_]\w*)"
120
+ )
121
+ RS_STRUCT_RE = re.compile(r"^\s*(?:pub(?:\([^)]*\))?\s+)?struct\s+([A-Za-z_]\w*)")
122
+ RS_ENUM_RE = re.compile(r"^\s*(?:pub(?:\([^)]*\))?\s+)?enum\s+([A-Za-z_]\w*)")
123
+ RS_TRAIT_RE = re.compile(r"^\s*(?:pub(?:\([^)]*\))?\s+)?(?:unsafe\s+)?trait\s+([A-Za-z_]\w*)")
124
+ RS_IMPL_RE = re.compile(r"^\s*(?:unsafe\s+)?impl(?:<[^>]*>)?\s+([A-Za-z_][\w:<>,\s]*?)(?:\s+where\b|\s*\{|$)")
125
+ RS_TYPE_RE = re.compile(r"^\s*(?:pub(?:\([^)]*\))?\s+)?type\s+([A-Za-z_]\w*)\b")
126
+
127
+ GO_FUNC_RE = re.compile(r"^func\s+(?:\(([^)]*)\)\s+)?([A-Za-z_]\w*)\s*\(")
128
+ GO_TYPE_RE = re.compile(r"^type\s+([A-Za-z_]\w*)\s+(struct|interface|\S+)")
129
+
130
+ CLAN_TYPE_RE = re.compile(
131
+ r"^\s*(?:(?:public|private|protected|internal|static|final|abstract|sealed|partial|readonly|export)\s+)*"
132
+ r"(class|struct|interface|enum|record)\s+([A-Za-z_]\w*)"
133
+ )
134
+ CLAN_FUNC_RE = re.compile(
135
+ r"^\s*(?:(?:public|private|protected|internal|static|virtual|override|async|inline|extern|"
136
+ r"constexpr|const|final|synchronized|abstract|native|unsafe)\s+)*"
137
+ r"(?:[\w:<>\[\],*&~]+\s+)+([A-Za-z_~]\w*)\s*\([^;{}]*\)\s*"
138
+ r"(?:const\s*)?(?:noexcept\s*)?(?:override\s*)?(?:throws\s+[\w.,\s]+)?(?:\{|=>|$)"
139
+ )
140
+ CLAN_CONTROL_KW = {
141
+ "if", "for", "while", "switch", "catch", "return", "else", "sizeof",
142
+ "typeof", "delete", "new", "throw", "case", "do", "using", "lock", "fixed",
143
+ }
144
+
145
+ MD_FENCE_RE = re.compile(r"^\s*(`{3,}|~{3,})")
146
+ MD_HEADING_RE = re.compile(r"^(#{1,2})\s+(.+?)\s*#*\s*$")
147
+
148
+ REMOTE_SLUG_RE = re.compile(r"(?:github\.com[:/]|[:/])([A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+?)(?:\.git)?/?$", re.I)
149
+
150
+ SCHEMA_SQL = """
151
+ CREATE TABLE IF NOT EXISTS meta (
152
+ key TEXT PRIMARY KEY,
153
+ value TEXT NOT NULL
154
+ );
155
+
156
+ CREATE TABLE IF NOT EXISTS repos (
157
+ repo_key TEXT PRIMARY KEY,
158
+ name TEXT NOT NULL,
159
+ main_checkout TEXT NOT NULL,
160
+ common_dir TEXT NOT NULL,
161
+ remote_url TEXT NOT NULL DEFAULT '',
162
+ remote_slug TEXT NOT NULL DEFAULT '',
163
+ default_branch TEXT NOT NULL DEFAULT '',
164
+ last_sync_ts REAL NOT NULL DEFAULT 0,
165
+ last_pr_sync_ts REAL NOT NULL DEFAULT 0,
166
+ file_count INTEGER NOT NULL DEFAULT 0,
167
+ symbol_count INTEGER NOT NULL DEFAULT 0
168
+ );
169
+
170
+ CREATE TABLE IF NOT EXISTS files (
171
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
172
+ repo_key TEXT NOT NULL REFERENCES repos(repo_key) ON DELETE CASCADE,
173
+ worktree_key TEXT NOT NULL DEFAULT '',
174
+ rel_path TEXT NOT NULL,
175
+ mtime_ns INTEGER NOT NULL,
176
+ size INTEGER NOT NULL,
177
+ lang TEXT NOT NULL,
178
+ role TEXT NOT NULL,
179
+ blob_sha TEXT NOT NULL DEFAULT '',
180
+ UNIQUE(repo_key, worktree_key, rel_path)
181
+ );
182
+ CREATE INDEX IF NOT EXISTS idx_files_repo_role ON files(repo_key, worktree_key, role);
183
+
184
+ CREATE TABLE IF NOT EXISTS worktree_deleted (
185
+ repo_key TEXT NOT NULL REFERENCES repos(repo_key) ON DELETE CASCADE,
186
+ worktree_key TEXT NOT NULL,
187
+ rel_path TEXT NOT NULL,
188
+ PRIMARY KEY (repo_key, worktree_key, rel_path)
189
+ );
190
+
191
+ CREATE TABLE IF NOT EXISTS symbols (
192
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
193
+ file_id INTEGER NOT NULL REFERENCES files(id) ON DELETE CASCADE,
194
+ repo_key TEXT NOT NULL REFERENCES repos(repo_key) ON DELETE CASCADE,
195
+ worktree_key TEXT NOT NULL DEFAULT '',
196
+ rel_path TEXT NOT NULL,
197
+ name TEXT NOT NULL,
198
+ kind TEXT NOT NULL,
199
+ line INTEGER NOT NULL,
200
+ signature TEXT NOT NULL
201
+ );
202
+ CREATE INDEX IF NOT EXISTS idx_symbols_file ON symbols(file_id);
203
+ CREATE INDEX IF NOT EXISTS idx_symbols_repo_wt ON symbols(repo_key, worktree_key);
204
+
205
+ CREATE VIRTUAL TABLE IF NOT EXISTS symbols_fts USING fts5(
206
+ name,
207
+ signature,
208
+ rel_path,
209
+ content='symbols',
210
+ content_rowid='id'
211
+ );
212
+
213
+ CREATE TRIGGER IF NOT EXISTS symbols_ai AFTER INSERT ON symbols BEGIN
214
+ INSERT INTO symbols_fts(rowid, name, signature, rel_path)
215
+ VALUES (new.id, new.name, new.signature, new.rel_path);
216
+ END;
217
+
218
+ CREATE TRIGGER IF NOT EXISTS symbols_ad AFTER DELETE ON symbols BEGIN
219
+ INSERT INTO symbols_fts(symbols_fts, rowid, name, signature, rel_path)
220
+ VALUES ('delete', old.id, old.name, old.signature, old.rel_path);
221
+ END;
222
+
223
+ CREATE TRIGGER IF NOT EXISTS symbols_au AFTER UPDATE ON symbols BEGIN
224
+ INSERT INTO symbols_fts(symbols_fts, rowid, name, signature, rel_path)
225
+ VALUES ('delete', old.id, old.name, old.signature, old.rel_path);
226
+ INSERT INTO symbols_fts(rowid, name, signature, rel_path)
227
+ VALUES (new.id, new.name, new.signature, new.rel_path);
228
+ END;
229
+
230
+ CREATE TABLE IF NOT EXISTS workspaces (
231
+ worktree_key TEXT PRIMARY KEY,
232
+ repo_key TEXT NOT NULL REFERENCES repos(repo_key) ON DELETE CASCADE,
233
+ path TEXT NOT NULL,
234
+ branch TEXT NOT NULL DEFAULT '',
235
+ head_sha TEXT NOT NULL DEFAULT '',
236
+ is_main INTEGER NOT NULL DEFAULT 0,
237
+ is_detached INTEGER NOT NULL DEFAULT 0,
238
+ is_dirty INTEGER NOT NULL DEFAULT 0,
239
+ dirty_count INTEGER NOT NULL DEFAULT 0,
240
+ source TEXT NOT NULL DEFAULT 'git',
241
+ orca_id TEXT NOT NULL DEFAULT '',
242
+ orca_name TEXT NOT NULL DEFAULT '',
243
+ orca_host TEXT NOT NULL DEFAULT '',
244
+ orca_status TEXT NOT NULL DEFAULT '',
245
+ updated_at REAL NOT NULL DEFAULT 0
246
+ );
247
+ CREATE INDEX IF NOT EXISTS idx_workspaces_repo ON workspaces(repo_key);
248
+ CREATE INDEX IF NOT EXISTS idx_workspaces_branch ON workspaces(repo_key, branch);
249
+
250
+ CREATE TABLE IF NOT EXISTS prs (
251
+ repo_key TEXT NOT NULL REFERENCES repos(repo_key) ON DELETE CASCADE,
252
+ number INTEGER NOT NULL,
253
+ title TEXT NOT NULL,
254
+ head_branch TEXT NOT NULL DEFAULT '',
255
+ base_branch TEXT NOT NULL DEFAULT '',
256
+ state TEXT NOT NULL DEFAULT 'OPEN',
257
+ is_draft INTEGER NOT NULL DEFAULT 0,
258
+ merge_state TEXT NOT NULL DEFAULT '',
259
+ review_decision TEXT NOT NULL DEFAULT '',
260
+ checks_summary TEXT NOT NULL DEFAULT '',
261
+ url TEXT NOT NULL DEFAULT '',
262
+ updated_at TEXT NOT NULL DEFAULT '',
263
+ synced_at REAL NOT NULL DEFAULT 0,
264
+ PRIMARY KEY (repo_key, number)
265
+ );
266
+ CREATE INDEX IF NOT EXISTS idx_prs_branch ON prs(repo_key, head_branch);
267
+
268
+ CREATE TABLE IF NOT EXISTS project_state (
269
+ repo_key TEXT NOT NULL REFERENCES repos(repo_key) ON DELETE CASCADE,
270
+ worktree_key TEXT NOT NULL DEFAULT '',
271
+ state_key TEXT NOT NULL,
272
+ source_kind TEXT NOT NULL,
273
+ source_path TEXT NOT NULL,
274
+ product TEXT NOT NULL DEFAULT '',
275
+ active_sprint INTEGER,
276
+ passed_slices INTEGER NOT NULL DEFAULT 0,
277
+ active_slices INTEGER NOT NULL DEFAULT 0,
278
+ total_slices INTEGER NOT NULL DEFAULT 0,
279
+ deferred_count INTEGER NOT NULL DEFAULT 0,
280
+ pending_inventory INTEGER NOT NULL DEFAULT 0,
281
+ sme_gate_blocked INTEGER NOT NULL DEFAULT 0,
282
+ last_exit_code INTEGER,
283
+ last_exit_reason TEXT NOT NULL DEFAULT '',
284
+ updated_at REAL NOT NULL DEFAULT 0,
285
+ PRIMARY KEY (repo_key, worktree_key, state_key)
286
+ );
287
+ CREATE INDEX IF NOT EXISTS idx_project_state_repo ON project_state(repo_key);
288
+ """
289
+
290
+
291
+ def run_cmd(args, cwd=None, timeout=15):
292
+ """Run an external command safely on Windows and POSIX without console popups."""
293
+ try:
294
+ return subprocess.run(
295
+ args,
296
+ cwd=cwd,
297
+ stdin=subprocess.DEVNULL,
298
+ capture_output=True,
299
+ text=True,
300
+ encoding="utf-8",
301
+ errors="replace",
302
+ timeout=timeout,
303
+ creationflags=CREATE_NO_WINDOW,
304
+ )
305
+ except (OSError, subprocess.TimeoutExpired) as err:
306
+ return subprocess.CompletedProcess(args, 127, "", str(err))
307
+
308
+
309
+ def run_cmd_bytes(args, cwd=None, timeout=15):
310
+ """Run an external command returning raw bytes (e.g. git ls-files -z)."""
311
+ try:
312
+ return subprocess.run(
313
+ args,
314
+ cwd=cwd,
315
+ stdin=subprocess.DEVNULL,
316
+ capture_output=True,
317
+ timeout=timeout,
318
+ creationflags=CREATE_NO_WINDOW,
319
+ )
320
+ except (OSError, subprocess.TimeoutExpired) as err:
321
+ return subprocess.CompletedProcess(args, 127, b"", str(err).encode("utf-8", errors="replace"))
322
+
323
+
324
+ def normalize_path_key(path):
325
+ """Canonical lowercase POSIX key so Windows/POSIX paths match identically across tools."""
326
+ resolved = os.path.realpath(os.path.abspath(path))
327
+ return os.path.normcase(resolved).replace("\\", "/").rstrip("/") or "/"
328
+
329
+
330
+ def display_path(path):
331
+ """Clean normalized path with forward slashes for concise cross-platform output."""
332
+ return os.path.realpath(os.path.abspath(path)).replace("\\", "/")
333
+
334
+
335
+ def cap_sig(text, limit=MAX_SIGNATURE_CHARS):
336
+ clean = re.sub(r"\s+", " ", text).strip()
337
+ if len(clean) <= limit:
338
+ return clean
339
+ return clean[: limit - 3].rstrip() + "..."
340
+
341
+
342
+ def truncate_utf8(text, max_bytes):
343
+ """Truncate text so its UTF-8 encoding fits strictly within max_bytes."""
344
+ raw = text.encode("utf-8")
345
+ if len(raw) <= max_bytes:
346
+ return text
347
+ if max_bytes <= 0:
348
+ return ""
349
+ suffix = b"\n..." if max_bytes >= 8 else b"..."
350
+ if max_bytes <= len(suffix):
351
+ return raw[:max_bytes].decode("utf-8", errors="ignore")
352
+ cut = raw[: max_bytes - len(suffix)]
353
+ decoded = cut.decode("utf-8", errors="ignore").rstrip()
354
+ result = decoded + suffix.decode("ascii")
355
+ while len(result.encode("utf-8")) > max_bytes and decoded:
356
+ decoded = decoded[:-1]
357
+ result = decoded + suffix.decode("ascii")
358
+ return result
359
+
360
+
361
+ def db_disk_bytes(db_path):
362
+ total = 0
363
+ for suffix in ("", "-wal", "-shm"):
364
+ candidate = db_path + suffix
365
+ if os.path.exists(candidate):
366
+ try:
367
+ total += os.path.getsize(candidate)
368
+ except OSError:
369
+ pass
370
+ return total
371
+
372
+
373
+ def global_db_path():
374
+ return os.path.join(os.path.expanduser("~"), ".cache", "deepmodebot", "workspace-map.db")
375
+
376
+
377
+ def ensure_scratch_gitignore(main_checkout):
378
+ scratch_dir = os.path.join(main_checkout, ".scratch")
379
+ os.makedirs(scratch_dir, exist_ok=True)
380
+ ignore_path = os.path.join(scratch_dir, ".gitignore")
381
+ if not os.path.exists(ignore_path):
382
+ with open(ignore_path, "w", encoding="utf-8", newline="\n") as handle:
383
+ handle.write("*\n")
384
+
385
+
386
+ def parse_remote_slug(remote_url):
387
+ if not remote_url:
388
+ return ""
389
+ match = REMOTE_SLUG_RE.search(remote_url.strip())
390
+ return match.group(1) if match else ""
391
+
392
+
393
+ def _read_git_head_branch(git_dir):
394
+ try:
395
+ with open(os.path.join(git_dir, "HEAD"), encoding="utf-8", errors="replace") as handle:
396
+ line = handle.readline().strip()
397
+ except OSError:
398
+ return None
399
+ if line.startswith("ref: refs/heads/"):
400
+ return line[len("ref: refs/heads/"):].strip()
401
+ return ""
402
+
403
+
404
+ def _read_origin_remote_url(common_dir):
405
+ config_path = os.path.join(common_dir, "config")
406
+ try:
407
+ with open(config_path, encoding="utf-8", errors="replace") as handle:
408
+ lines = handle.readlines()
409
+ except OSError:
410
+ return None
411
+ in_origin = False
412
+ has_include = False
413
+ for raw in lines:
414
+ line = raw.strip()
415
+ if not line or line.startswith(("#", ";")):
416
+ continue
417
+ if line.startswith("[") and line.endswith("]"):
418
+ header = line[1:-1].strip()
419
+ in_origin = header.lower() == 'remote "origin"'
420
+ if header.lower().startswith("include"):
421
+ has_include = True
422
+ continue
423
+ if in_origin and "=" in line:
424
+ key, val = line.split("=", 1)
425
+ if key.strip().lower() == "url":
426
+ return val.strip()
427
+ return None if has_include else ""
428
+
429
+
430
+ def _read_origin_default_branch(common_dir):
431
+ ref_path = os.path.join(common_dir, "refs", "remotes", "origin", "HEAD")
432
+ try:
433
+ with open(ref_path, encoding="utf-8", errors="replace") as handle:
434
+ line = handle.readline().strip()
435
+ except OSError:
436
+ return ""
437
+ prefix = "ref: refs/remotes/origin/"
438
+ if line.startswith(prefix):
439
+ return line[len(prefix):].strip()
440
+ return ""
441
+
442
+
443
+ def resolve_repo(path="."):
444
+ """Resolve git checkout + common dir so linked worktrees share one repo_key and DB."""
445
+ abs_path = os.path.abspath(path or ".")
446
+ probe = abs_path if os.path.isdir(abs_path) else os.path.dirname(abs_path)
447
+ while probe and not os.path.exists(probe):
448
+ parent = os.path.dirname(probe)
449
+ if parent == probe:
450
+ break
451
+ probe = parent
452
+ if not os.path.isdir(probe):
453
+ return None
454
+
455
+ rev = run_cmd([
456
+ "git", "-C", probe, "rev-parse", "--path-format=absolute",
457
+ "--show-toplevel", "--git-common-dir", "--git-dir",
458
+ ])
459
+ lines = [ln.strip() for ln in rev.stdout.splitlines() if ln.strip()]
460
+ if rev.returncode == 0 and len(lines) >= 3:
461
+ checkout_root = os.path.realpath(lines[0])
462
+ common_dir = os.path.realpath(lines[1])
463
+ git_dir = os.path.realpath(lines[2])
464
+ else:
465
+ top = run_cmd(["git", "-C", probe, "rev-parse", "--show-toplevel"])
466
+ if top.returncode != 0 or not top.stdout.strip():
467
+ return None
468
+ checkout_root = os.path.realpath(top.stdout.strip())
469
+ common = run_cmd(["git", "-C", checkout_root, "rev-parse", "--git-common-dir"])
470
+ if common.returncode != 0 or not common.stdout.strip():
471
+ return None
472
+ raw_common = common.stdout.strip()
473
+ common_dir = os.path.realpath(
474
+ raw_common if os.path.isabs(raw_common) else os.path.join(checkout_root, raw_common)
475
+ )
476
+ gdir = run_cmd(["git", "-C", checkout_root, "rev-parse", "--git-dir"])
477
+ raw_gdir = gdir.stdout.strip() if gdir.returncode == 0 and gdir.stdout.strip() else ".git"
478
+ git_dir = os.path.realpath(
479
+ raw_gdir if os.path.isabs(raw_gdir) else os.path.join(checkout_root, raw_gdir)
480
+ )
481
+
482
+ if os.path.basename(common_dir).lower() == ".git":
483
+ main_checkout = os.path.realpath(os.path.dirname(common_dir))
484
+ else:
485
+ main_checkout = common_dir
486
+
487
+ repo_key = normalize_path_key(main_checkout)
488
+ remote_url = _read_origin_remote_url(common_dir)
489
+ if remote_url is None:
490
+ remote = run_cmd(["git", "-C", checkout_root, "config", "--get", "remote.origin.url"])
491
+ remote_url = remote.stdout.strip() if remote.returncode == 0 else ""
492
+ remote_slug = parse_remote_slug(remote_url)
493
+
494
+ current_branch = _read_git_head_branch(git_dir)
495
+ if current_branch is None:
496
+ branch_res = run_cmd(["git", "-C", checkout_root, "symbolic-ref", "--short", "HEAD"])
497
+ current_branch = branch_res.stdout.strip() if branch_res.returncode == 0 else ""
498
+
499
+ def_branch = _read_origin_default_branch(common_dir) or current_branch
500
+
501
+ name = remote_slug or os.path.basename(main_checkout) or "repo"
502
+ return {
503
+ "repo_key": repo_key,
504
+ "name": name,
505
+ "checkout_root": checkout_root,
506
+ "worktree_key": normalize_path_key(checkout_root),
507
+ "main_checkout": main_checkout,
508
+ "common_dir": common_dir,
509
+ "remote_url": remote_url,
510
+ "remote_slug": remote_slug,
511
+ "current_branch": current_branch,
512
+ "default_branch": def_branch,
513
+ }
514
+
515
+
516
+ def resolve_db_path(opts, repo_info=None):
517
+ explicit_db = getattr(opts, "db", None)
518
+ use_global = getattr(opts, "use_global", False)
519
+ if explicit_db:
520
+ return os.path.abspath(explicit_db)
521
+ if use_global:
522
+ return global_db_path()
523
+ env_db = os.environ.get("DEEPMODEBOT_MAP_DB", "").strip()
524
+ if env_db:
525
+ return os.path.abspath(env_db)
526
+ if repo_info is not None:
527
+ ensure_scratch_gitignore(repo_info["main_checkout"])
528
+ return os.path.join(repo_info["main_checkout"], ".scratch", "workspace-map.db")
529
+ return global_db_path()
530
+
531
+
532
+ def connect_db(db_path, readonly=False):
533
+ if readonly:
534
+ uri = f"file:{Path(os.path.abspath(db_path)).as_posix()}?mode=ro"
535
+ conn = sqlite3.connect(uri, uri=True, timeout=10.0)
536
+ conn.row_factory = sqlite3.Row
537
+ try:
538
+ conn.execute("PRAGMA query_only=ON")
539
+ conn.execute(f"PRAGMA mmap_size={MMAP_SIZE_BYTES}")
540
+ conn.execute("PRAGMA busy_timeout=5000")
541
+ except Exception:
542
+ conn.close()
543
+ raise
544
+ return conn
545
+ parent = os.path.dirname(os.path.abspath(db_path))
546
+ if parent:
547
+ os.makedirs(parent, exist_ok=True)
548
+ conn = sqlite3.connect(db_path, timeout=10.0)
549
+ conn.row_factory = sqlite3.Row
550
+ try:
551
+ conn.execute("PRAGMA auto_vacuum=INCREMENTAL")
552
+ conn.execute("PRAGMA journal_mode=WAL")
553
+ conn.execute("PRAGMA synchronous=NORMAL")
554
+ conn.execute(f"PRAGMA mmap_size={MMAP_SIZE_BYTES}")
555
+ conn.execute("PRAGMA foreign_keys=ON")
556
+ conn.execute("PRAGMA busy_timeout=5000")
557
+ cols = {row[1] for row in conn.execute("PRAGMA table_info(files)").fetchall()}
558
+ if cols and "worktree_key" not in cols:
559
+ conn.executescript(
560
+ "DROP TRIGGER IF EXISTS symbols_ai;"
561
+ "DROP TRIGGER IF EXISTS symbols_ad;"
562
+ "DROP TRIGGER IF EXISTS symbols_au;"
563
+ "DROP TABLE IF EXISTS symbols_fts;"
564
+ "DROP TABLE IF EXISTS symbols;"
565
+ "DROP TABLE IF EXISTS files;"
566
+ )
567
+ conn.executescript(SCHEMA_SQL)
568
+ conn.execute(
569
+ "INSERT OR REPLACE INTO meta(key, value) VALUES('schema_version', ?)",
570
+ (str(SCHEMA_VERSION),),
571
+ )
572
+ conn.commit()
573
+ except Exception:
574
+ conn.close()
575
+ raise
576
+ return conn
577
+
578
+
579
+ def should_skip_relpath(rel_path):
580
+ norm = rel_path.replace("\\", "/")
581
+ while norm.startswith("./"):
582
+ norm = norm[2:]
583
+ norm = norm.lstrip("/")
584
+ if not norm:
585
+ return True
586
+ parts = [p.lower() for p in norm.split("/")]
587
+ if any(part in SKIP_DIR_PARTS for part in parts[:-1]):
588
+ return True
589
+ base = parts[-1]
590
+ if base in LOCKFILE_NAMES:
591
+ return True
592
+ if any(base.endswith(suf) for suf in SKIP_SUFFIXES):
593
+ return True
594
+ _, ext = os.path.splitext(base)
595
+ if ext in BINARY_MEDIA_EXTS:
596
+ return True
597
+ return False
598
+
599
+
600
+ def detect_lang(rel_path):
601
+ base = os.path.basename(rel_path).lower()
602
+ if base in ("makefile", "justfile", "dockerfile"):
603
+ return base
604
+ _, ext = os.path.splitext(base)
605
+ return LANG_BY_EXT.get(ext, "text")
606
+
607
+
608
+ def classify_role(rel_path):
609
+ norm = rel_path.replace("\\", "/").lower()
610
+ parts = norm.split("/")
611
+ base = parts[-1]
612
+ if base == "skill.md":
613
+ if len(parts) >= 2 and parts[-2].startswith("verify-"):
614
+ return "verify-skill"
615
+ return "skill"
616
+ if base.endswith("-manifest.json") and (norm.startswith("docs/specs/") or norm.startswith(".scratch/goals/")):
617
+ return "manifest"
618
+ if (
619
+ any(p in ("tests", "test", "__tests__") for p in parts[:-1])
620
+ or base.startswith("test_")
621
+ or base.endswith(("_test.py", "_test.go", "_test.rs", ".test.ts", ".test.js", ".test.tsx", ".spec.ts", ".spec.js"))
622
+ ):
623
+ return "test"
624
+ if base in TOP_DOC_NAMES or (len(parts) == 1 and base.endswith(".md")) or (parts[0] == "docs" and base.endswith(".md")):
625
+ return "doc"
626
+ if base in ENTRYPOINT_NAMES or (parts[0] in ("bin", "cmd", "scripts") and not base.endswith(".md")):
627
+ return "entrypoint"
628
+ if base.endswith((".json", ".toml", ".yaml", ".yml", ".ini", ".cfg")) or norm.startswith(".github/workflows/"):
629
+ return "config"
630
+ return "source"
631
+
632
+
633
+ def _py_format_args(args_node):
634
+ if hasattr(ast, "unparse"):
635
+ try:
636
+ return ast.unparse(args_node)
637
+ except Exception:
638
+ pass
639
+ names = [a.arg for a in args_node.posonlyargs + args_node.args]
640
+ if args_node.vararg:
641
+ names.append("*" + args_node.vararg.arg)
642
+ names.extend(a.arg for a in args_node.kwonlyargs)
643
+ if args_node.kwarg:
644
+ names.append("**" + args_node.kwarg.arg)
645
+ return ", ".join(names)
646
+
647
+
648
+ def _extract_python_symbols(text):
649
+ try:
650
+ tree = ast.parse(text)
651
+ except (SyntaxError, ValueError):
652
+ return []
653
+ out = []
654
+
655
+ def visit_body(body, class_prefix=""):
656
+ for node in body:
657
+ if isinstance(node, ast.ClassDef):
658
+ bases = []
659
+ if hasattr(ast, "unparse"):
660
+ for base in node.bases:
661
+ try:
662
+ bases.append(ast.unparse(base))
663
+ except Exception:
664
+ pass
665
+ base_str = f"({', '.join(bases)})" if bases else ""
666
+ full_name = f"{class_prefix}.{node.name}" if class_prefix else node.name
667
+ out.append((full_name, "class", node.lineno, cap_sig(f"class {full_name}{base_str}")))
668
+ visit_body(node.body, full_name)
669
+ elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
670
+ prefix = "async def" if isinstance(node, ast.AsyncFunctionDef) else "def"
671
+ arg_str = _py_format_args(node.args)
672
+ ret = ""
673
+ if node.returns is not None and hasattr(ast, "unparse"):
674
+ try:
675
+ ret = f" -> {ast.unparse(node.returns)}"
676
+ except Exception:
677
+ ret = ""
678
+ kind = "method" if class_prefix else "function"
679
+ full_name = f"{class_prefix}.{node.name}" if class_prefix else node.name
680
+ sig = cap_sig(f"{prefix} {full_name}({arg_str}){ret}")
681
+ out.append((full_name, kind, node.lineno, sig))
682
+
683
+ visit_body(tree.body)
684
+ return out
685
+
686
+
687
+ def _extract_js_ts_symbols(text):
688
+ out = []
689
+ for lineno, line in enumerate(text.splitlines(), 1):
690
+ stripped = line.lstrip()
691
+ if not stripped or stripped.startswith(("//", "/*", "*")):
692
+ continue
693
+ for regex, kind in (
694
+ (JS_FUNC_RE, "function"),
695
+ (JS_CLASS_RE, "class"),
696
+ (JS_IFACE_RE, "interface"),
697
+ (JS_TYPE_RE, "type"),
698
+ (JS_ENUM_RE, "enum"),
699
+ (JS_ARROW_RE, "function"),
700
+ ):
701
+ match = regex.match(line)
702
+ if match:
703
+ name = match.group(1)
704
+ sig = cap_sig(stripped.split("{", 1)[0].rstrip())
705
+ out.append((name, kind, lineno, sig))
706
+ break
707
+ return out
708
+
709
+
710
+ def _extract_rust_symbols(text):
711
+ out = []
712
+ for lineno, line in enumerate(text.splitlines(), 1):
713
+ stripped = line.lstrip()
714
+ if not stripped or stripped.startswith(("//", "/*", "*", "#[")):
715
+ continue
716
+ for regex, kind in (
717
+ (RS_FN_RE, "function"),
718
+ (RS_STRUCT_RE, "struct"),
719
+ (RS_ENUM_RE, "enum"),
720
+ (RS_TRAIT_RE, "trait"),
721
+ (RS_IMPL_RE, "impl"),
722
+ (RS_TYPE_RE, "type"),
723
+ ):
724
+ match = regex.match(line)
725
+ if match:
726
+ name = re.sub(r"\s+", " ", match.group(1)).strip()
727
+ sig = cap_sig(stripped.split("{", 1)[0].rstrip("; "))
728
+ out.append((name, kind, lineno, sig))
729
+ break
730
+ return out
731
+
732
+
733
+ def _extract_go_symbols(text):
734
+ out = []
735
+ for lineno, line in enumerate(text.splitlines(), 1):
736
+ stripped = line.lstrip()
737
+ if not stripped or stripped.startswith(("//", "/*", "*")):
738
+ continue
739
+ match = GO_FUNC_RE.match(line)
740
+ if match:
741
+ recv, name = match.group(1), match.group(2)
742
+ kind = "method" if recv else "function"
743
+ sig = cap_sig(stripped.split("{", 1)[0].rstrip())
744
+ out.append((name, kind, lineno, sig))
745
+ continue
746
+ match = GO_TYPE_RE.match(line)
747
+ if match:
748
+ name, target = match.group(1), match.group(2)
749
+ kind = target if target in ("struct", "interface") else "type"
750
+ sig = cap_sig(stripped.split("{", 1)[0].rstrip())
751
+ out.append((name, kind, lineno, sig))
752
+ return out
753
+
754
+
755
+ def _extract_clan_symbols(text):
756
+ out = []
757
+ for lineno, line in enumerate(text.splitlines(), 1):
758
+ stripped = line.lstrip()
759
+ if not stripped or stripped.startswith(("//", "/*", "*", "#")):
760
+ continue
761
+ match = CLAN_TYPE_RE.match(line)
762
+ if match:
763
+ kind, name = match.group(1), match.group(2)
764
+ sig = cap_sig(stripped.split("{", 1)[0].rstrip())
765
+ out.append((name, kind, lineno, sig))
766
+ continue
767
+ match = CLAN_FUNC_RE.match(line)
768
+ if match:
769
+ name = match.group(1)
770
+ if name.lower() in CLAN_CONTROL_KW:
771
+ continue
772
+ sig = cap_sig(stripped.split("{", 1)[0].split("=>", 1)[0].rstrip())
773
+ out.append((name, "function", lineno, sig))
774
+ return out
775
+
776
+
777
+ def _extract_markdown_symbols(text):
778
+ out = []
779
+ fence_char = ""
780
+ fence_len = 0
781
+ for lineno, line in enumerate(text.splitlines(), 1):
782
+ fmatch = MD_FENCE_RE.match(line)
783
+ if fmatch:
784
+ marker = fmatch.group(1)
785
+ if not fence_char:
786
+ fence_char, fence_len = marker[0], len(marker)
787
+ elif marker[0] == fence_char and len(marker) >= fence_len:
788
+ fence_char, fence_len = "", 0
789
+ continue
790
+ if fence_char:
791
+ continue
792
+ hmatch = MD_HEADING_RE.match(line)
793
+ if hmatch:
794
+ hashes, title = hmatch.group(1), hmatch.group(2).strip()
795
+ out.append((cap_sig(title, 80), "heading", lineno, cap_sig(f"{hashes} {title}")))
796
+ return out
797
+
798
+
799
+ def extract_symbols(rel_path, lang, text):
800
+ if lang == "python":
801
+ return _extract_python_symbols(text)
802
+ if lang in ("typescript", "javascript"):
803
+ return _extract_js_ts_symbols(text)
804
+ if lang == "rust":
805
+ return _extract_rust_symbols(text)
806
+ if lang == "go":
807
+ return _extract_go_symbols(text)
808
+ if lang in ("csharp", "java", "cpp", "c"):
809
+ return _extract_clan_symbols(text)
810
+ if lang == "markdown":
811
+ return _extract_markdown_symbols(text)
812
+ return []
813
+
814
+
815
+ def list_tracked_files(checkout_root):
816
+ res = run_cmd_bytes(["git", "-C", checkout_root, "ls-files", "-z"])
817
+ if res.returncode != 0:
818
+ return []
819
+ raw_items = res.stdout.split(b"\x00")
820
+ return [item.decode("utf-8", errors="replace") for item in raw_items if item]
821
+
822
+
823
+ def list_tracked_blobs(checkout_root):
824
+ """Return ordered list of (rel_path, clean_blob_sha) for tracked files; dirty files get '' as blob_sha."""
825
+ res = run_cmd_bytes(["git", "-C", checkout_root, "ls-files", "-s", "-z"])
826
+ if res.returncode != 0:
827
+ return [(p.replace("\\", "/"), "") for p in list_tracked_files(checkout_root)]
828
+ dirty_res = run_cmd_bytes(["git", "-C", checkout_root, "diff", "--name-only", "-z"])
829
+ dirty = set()
830
+ if dirty_res.returncode == 0:
831
+ for item in dirty_res.stdout.split(b"\x00"):
832
+ if item:
833
+ dirty.add(item.decode("utf-8", errors="replace").replace("\\", "/"))
834
+ by_path = {}
835
+ for entry in res.stdout.split(b"\x00"):
836
+ if not entry or b"\t" not in entry:
837
+ continue
838
+ meta, raw_path = entry.split(b"\t", 1)
839
+ parts = meta.decode("ascii", errors="replace").split()
840
+ blob_sha = parts[1] if len(parts) >= 2 else ""
841
+ rel_path = raw_path.decode("utf-8", errors="replace").replace("\\", "/")
842
+ by_path[rel_path] = "" if rel_path in dirty else blob_sha
843
+ return list(by_path.items())
844
+
845
+
846
+ def _active_view_counts(conn, repo_key, wt_key):
847
+ """Count files and symbols visible from `wt_key` (baseline '' plus per-worktree overlay minus tombstones)."""
848
+ is_main = not wt_key or wt_key == repo_key
849
+ if is_main:
850
+ total_files = conn.execute(
851
+ "SELECT COUNT(*) FROM files WHERE repo_key = ? AND worktree_key = ''",
852
+ (repo_key,),
853
+ ).fetchone()[0]
854
+ total_symbols = conn.execute(
855
+ "SELECT COUNT(*) FROM symbols WHERE repo_key = ? AND worktree_key = ''",
856
+ (repo_key,),
857
+ ).fetchone()[0]
858
+ return total_files, total_symbols
859
+ total_files = conn.execute(
860
+ """SELECT COUNT(*) FROM files f
861
+ WHERE f.repo_key = ?
862
+ AND (f.worktree_key = ? OR (
863
+ f.worktree_key = ''
864
+ AND NOT EXISTS (
865
+ SELECT 1 FROM files ov
866
+ WHERE ov.repo_key = f.repo_key AND ov.worktree_key = ? AND ov.rel_path = f.rel_path
867
+ )
868
+ AND NOT EXISTS (
869
+ SELECT 1 FROM worktree_deleted wd
870
+ WHERE wd.repo_key = f.repo_key AND wd.worktree_key = ? AND wd.rel_path = f.rel_path
871
+ )
872
+ ))""",
873
+ (repo_key, wt_key, wt_key, wt_key),
874
+ ).fetchone()[0]
875
+ total_symbols = conn.execute(
876
+ """SELECT COUNT(*) FROM symbols s
877
+ WHERE s.repo_key = ?
878
+ AND (s.worktree_key = ? OR (
879
+ s.worktree_key = ''
880
+ AND NOT EXISTS (
881
+ SELECT 1 FROM files ov
882
+ WHERE ov.repo_key = s.repo_key AND ov.worktree_key = ? AND ov.rel_path = s.rel_path
883
+ )
884
+ AND NOT EXISTS (
885
+ SELECT 1 FROM worktree_deleted wd
886
+ WHERE wd.repo_key = s.repo_key AND wd.worktree_key = ? AND wd.rel_path = s.rel_path
887
+ )
888
+ ))""",
889
+ (repo_key, wt_key, wt_key, wt_key),
890
+ ).fetchone()[0]
891
+ return total_files, total_symbols
892
+
893
+
894
+ def sync_files_and_symbols(conn, repo_info):
895
+ """Sync tracked files and symbols for a checkout.
896
+
897
+ Main checkout owns the shared baseline (`worktree_key = ''`). Linked worktrees inherit unchanged baseline
898
+ files (same clean git blob SHA) with zero duplication and store only added/modified files in their own
899
+ `worktree_key` overlay plus tombstones in `worktree_deleted`, so branches never clobber each other.
900
+ """
901
+ repo_key = repo_info["repo_key"]
902
+ wt_key = repo_info["worktree_key"]
903
+ checkout_root = repo_info["checkout_root"]
904
+ is_main = wt_key == repo_key
905
+ target_wt = "" if is_main else wt_key
906
+ tracked = list_tracked_blobs(checkout_root)
907
+
908
+ baseline = {
909
+ row["rel_path"]: (row["id"], row["mtime_ns"], row["size"], row["blob_sha"])
910
+ for row in conn.execute(
911
+ "SELECT id, rel_path, mtime_ns, size, blob_sha FROM files WHERE repo_key = ? AND worktree_key = ''",
912
+ (repo_key,),
913
+ )
914
+ }
915
+ existing = (
916
+ baseline
917
+ if is_main
918
+ else {
919
+ row["rel_path"]: (row["id"], row["mtime_ns"], row["size"], row["blob_sha"])
920
+ for row in conn.execute(
921
+ "SELECT id, rel_path, mtime_ns, size, blob_sha FROM files WHERE repo_key = ? AND worktree_key = ?",
922
+ (repo_key, target_wt),
923
+ )
924
+ }
925
+ )
926
+
927
+ seen_target = set()
928
+ seen_all_tracked = set()
929
+ files_indexed = 0
930
+ files_skipped = 0
931
+ files_filtered = 0
932
+
933
+ for rel_path, blob_sha in tracked:
934
+ if should_skip_relpath(rel_path):
935
+ files_filtered += 1
936
+ continue
937
+ abs_path = os.path.join(checkout_root, rel_path)
938
+ try:
939
+ st = os.stat(abs_path)
940
+ except OSError:
941
+ continue
942
+ if not os.path.isfile(abs_path):
943
+ continue
944
+ if st.st_size > MAX_FILE_BYTES:
945
+ files_filtered += 1
946
+ continue
947
+
948
+ seen_all_tracked.add(rel_path)
949
+
950
+ if not is_main:
951
+ base_row = baseline.get(rel_path)
952
+ if base_row is not None and blob_sha and base_row[3] and base_row[3] == blob_sha:
953
+ # Identical clean file in shared baseline: inherit without duplicating rows.
954
+ files_skipped += 1
955
+ continue
956
+
957
+ prev = existing.get(rel_path)
958
+ if prev is not None and prev[1] == st.st_mtime_ns and prev[2] == st.st_size and prev[3] == blob_sha:
959
+ seen_target.add(rel_path)
960
+ files_skipped += 1
961
+ continue
962
+
963
+ try:
964
+ with open(abs_path, "rb") as handle:
965
+ raw = handle.read(MAX_FILE_BYTES + 1)
966
+ except OSError:
967
+ continue
968
+ if len(raw) > MAX_FILE_BYTES or b"\x00" in raw[:8192]:
969
+ files_filtered += 1
970
+ continue
971
+
972
+ text = raw.decode("utf-8", errors="replace")
973
+ lang = detect_lang(rel_path)
974
+ role = classify_role(rel_path)
975
+ symbols = extract_symbols(rel_path, lang, text)
976
+
977
+ if prev is not None:
978
+ file_id = prev[0]
979
+ conn.execute(
980
+ "UPDATE files SET mtime_ns = ?, size = ?, lang = ?, role = ?, blob_sha = ? WHERE id = ?",
981
+ (st.st_mtime_ns, st.st_size, lang, role, blob_sha, file_id),
982
+ )
983
+ conn.execute("DELETE FROM symbols WHERE file_id = ?", (file_id,))
984
+ else:
985
+ cur = conn.execute(
986
+ "INSERT INTO files(repo_key, worktree_key, rel_path, mtime_ns, size, lang, role, blob_sha) "
987
+ "VALUES(?, ?, ?, ?, ?, ?, ?, ?)",
988
+ (repo_key, target_wt, rel_path, st.st_mtime_ns, st.st_size, lang, role, blob_sha),
989
+ )
990
+ file_id = cur.lastrowid
991
+
992
+ if symbols:
993
+ conn.executemany(
994
+ "INSERT INTO symbols(file_id, repo_key, worktree_key, rel_path, name, kind, line, signature) "
995
+ "VALUES(?, ?, ?, ?, ?, ?, ?, ?)",
996
+ [(file_id, repo_key, target_wt, rel_path, name, kind, line, sig) for name, kind, line, sig in symbols],
997
+ )
998
+ seen_target.add(rel_path)
999
+ files_indexed += 1
1000
+
1001
+ removed_ids = [file_id for rel_path, (file_id, _, _, _) in existing.items() if rel_path not in seen_target]
1002
+ if removed_ids:
1003
+ conn.executemany("DELETE FROM files WHERE id = ?", [(fid,) for fid in removed_ids])
1004
+
1005
+ if is_main:
1006
+ # Prune redundant linked-worktree overlay rows that now match the clean main baseline.
1007
+ conn.execute(
1008
+ """DELETE FROM files
1009
+ WHERE repo_key = ? AND worktree_key != '' AND blob_sha != ''
1010
+ AND EXISTS (
1011
+ SELECT 1 FROM files b
1012
+ WHERE b.repo_key = files.repo_key AND b.worktree_key = ''
1013
+ AND b.rel_path = files.rel_path AND b.blob_sha = files.blob_sha
1014
+ )""",
1015
+ (repo_key,),
1016
+ )
1017
+ else:
1018
+ conn.execute(
1019
+ "DELETE FROM worktree_deleted WHERE repo_key = ? AND worktree_key = ?",
1020
+ (repo_key, target_wt),
1021
+ )
1022
+ deleted_from_base = [rp for rp in baseline if rp not in seen_all_tracked]
1023
+ if deleted_from_base:
1024
+ conn.executemany(
1025
+ "INSERT OR IGNORE INTO worktree_deleted(repo_key, worktree_key, rel_path) VALUES(?, ?, ?)",
1026
+ [(repo_key, target_wt, rp) for rp in deleted_from_base],
1027
+ )
1028
+
1029
+ total_files, total_symbols = _active_view_counts(conn, repo_key, wt_key)
1030
+ return {
1031
+ "files_indexed": files_indexed,
1032
+ "files_skipped": files_skipped,
1033
+ "files_filtered": files_filtered,
1034
+ "files_removed": len(removed_ids),
1035
+ "total_files": total_files,
1036
+ "total_symbols": total_symbols,
1037
+ }
1038
+
1039
+
1040
+ def parse_git_worktrees(checkout_root, main_checkout):
1041
+ res = run_cmd(["git", "-C", checkout_root, "worktree", "list", "--porcelain"])
1042
+ if res.returncode != 0:
1043
+ return []
1044
+ main_key = normalize_path_key(main_checkout)
1045
+ items = []
1046
+ cur = {}
1047
+
1048
+ def flush():
1049
+ if not cur.get("path"):
1050
+ return
1051
+ if cur.get("prunable") or not os.path.isdir(cur["path"]):
1052
+ return
1053
+ wkey = normalize_path_key(cur["path"])
1054
+ items.append({
1055
+ "worktree_key": wkey,
1056
+ "path": display_path(cur["path"]),
1057
+ "raw_path": cur["path"],
1058
+ "branch": cur.get("branch", ""),
1059
+ "head_sha": cur.get("head", "")[:12],
1060
+ "is_main": 1 if wkey == main_key else 0,
1061
+ "is_detached": 1 if cur.get("detached") else 0,
1062
+ "is_dirty": 0,
1063
+ "dirty_count": 0,
1064
+ "source": "git",
1065
+ "orca_id": "",
1066
+ "orca_name": "",
1067
+ "orca_host": "",
1068
+ "orca_status": "",
1069
+ })
1070
+
1071
+ for line in res.stdout.splitlines():
1072
+ if not line.strip():
1073
+ flush()
1074
+ cur = {}
1075
+ continue
1076
+ if line.startswith("worktree "):
1077
+ cur["path"] = line[9:].strip()
1078
+ elif line.startswith("HEAD "):
1079
+ cur["head"] = line[5:].strip()
1080
+ elif line.startswith("branch "):
1081
+ ref = line[7:].strip()
1082
+ cur["branch"] = ref[11:] if ref.startswith("refs/heads/") else ref
1083
+ elif line == "detached":
1084
+ cur["detached"] = True
1085
+ elif line.startswith("prunable"):
1086
+ cur["prunable"] = True
1087
+ flush()
1088
+ return items
1089
+
1090
+
1091
+ def _check_dirty(raw_path):
1092
+ res = run_cmd(["git", "-C", raw_path, "status", "--porcelain"], timeout=4)
1093
+ if res.returncode != 0:
1094
+ return 0, 0
1095
+ lines = [ln for ln in res.stdout.splitlines() if ln.strip()]
1096
+ return (1 if lines else 0), len(lines)
1097
+
1098
+
1099
+ def populate_dirty_status(worktrees, current_wkey, fast=False):
1100
+ """Check dirty status in parallel for current, main, and (unless fast) branch-attached worktrees."""
1101
+ prioritized = []
1102
+ seen = set()
1103
+ if fast:
1104
+ predicates = (
1105
+ lambda w: w["worktree_key"] == current_wkey,
1106
+ lambda w: w["is_main"] == 1,
1107
+ )
1108
+ max_checks = 2
1109
+ else:
1110
+ predicates = (
1111
+ lambda w: w["worktree_key"] == current_wkey,
1112
+ lambda w: w["is_main"] == 1,
1113
+ lambda w: not w["is_detached"],
1114
+ )
1115
+ max_checks = MAX_DIRTY_CHECK_WORKTREES
1116
+ for predicate in predicates:
1117
+ for wt in worktrees:
1118
+ if wt["worktree_key"] not in seen and predicate(wt):
1119
+ prioritized.append(wt)
1120
+ seen.add(wt["worktree_key"])
1121
+ if len(prioritized) >= max_checks:
1122
+ break
1123
+ if len(prioritized) >= max_checks:
1124
+ break
1125
+ if not prioritized:
1126
+ return
1127
+ workers = min(6, len(prioritized))
1128
+ with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool:
1129
+ future_map = {pool.submit(_check_dirty, wt["raw_path"]): wt for wt in prioritized}
1130
+ for future, wt in future_map.items():
1131
+ try:
1132
+ is_dirty, dirty_count = future.result()
1133
+ wt["is_dirty"] = is_dirty
1134
+ wt["dirty_count"] = dirty_count
1135
+ except Exception:
1136
+ pass
1137
+
1138
+
1139
+ def fetch_orca_worktrees():
1140
+ """Query `orca worktree list --json` when Orca CLI is available; skip gracefully otherwise."""
1141
+ if not shutil.which("orca"):
1142
+ return None
1143
+ res = run_cmd(["orca", "worktree", "list", "--json"], timeout=4)
1144
+ if res.returncode != 0 or not res.stdout.strip():
1145
+ return None
1146
+ try:
1147
+ payload = json.loads(res.stdout)
1148
+ except ValueError:
1149
+ return None
1150
+ if isinstance(payload, list):
1151
+ rows = payload
1152
+ elif isinstance(payload, dict):
1153
+ rows = (
1154
+ payload.get("worktrees")
1155
+ or payload.get("items")
1156
+ or payload.get("data")
1157
+ or payload.get("rows")
1158
+ or []
1159
+ )
1160
+ else:
1161
+ return None
1162
+ if not isinstance(rows, list):
1163
+ return None
1164
+ parsed = []
1165
+ for item in rows:
1166
+ if not isinstance(item, dict):
1167
+ continue
1168
+ raw_path = (
1169
+ item.get("path")
1170
+ or item.get("worktreePath")
1171
+ or item.get("worktree_path")
1172
+ or item.get("directory")
1173
+ or item.get("dir")
1174
+ or ""
1175
+ )
1176
+ if not isinstance(raw_path, str) or not raw_path.strip():
1177
+ continue
1178
+ branch = str(item.get("branch") or item.get("headRef") or item.get("gitBranch") or "")
1179
+ if branch.startswith("refs/heads/"):
1180
+ branch = branch[11:]
1181
+ repo_path = str(item.get("repoPath") or item.get("repo_path") or item.get("repoRoot") or "")
1182
+ parsed.append({
1183
+ "raw_path": raw_path,
1184
+ "worktree_key": normalize_path_key(raw_path),
1185
+ "path": display_path(raw_path),
1186
+ "branch": branch,
1187
+ "repo_path": repo_path,
1188
+ "orca_id": str(item.get("id") or ""),
1189
+ "orca_name": str(item.get("name") or item.get("displayName") or ""),
1190
+ "orca_host": str(item.get("host") or item.get("environment") or ""),
1191
+ "orca_status": str(item.get("status") or item.get("state") or ""),
1192
+ "is_dirty": 1 if item.get("dirty") or item.get("isDirty") else 0,
1193
+ })
1194
+ return parsed
1195
+
1196
+
1197
+ def sync_workspaces(conn, repo_info, no_orca=False, include_foreign_orca=False, fast=False):
1198
+ repo_key = repo_info["repo_key"]
1199
+ now = time.time()
1200
+ if fast:
1201
+ dirty_targets = [repo_info["checkout_root"]]
1202
+ if normalize_path_key(repo_info["main_checkout"]) != repo_info["worktree_key"]:
1203
+ dirty_targets.append(repo_info["main_checkout"])
1204
+ with concurrent.futures.ThreadPoolExecutor(max_workers=len(dirty_targets) + 1) as pool:
1205
+ wt_future = pool.submit(parse_git_worktrees, repo_info["checkout_root"], repo_info["main_checkout"])
1206
+ dirty_futures = {normalize_path_key(p): pool.submit(_check_dirty, p) for p in dirty_targets}
1207
+ git_wts = wt_future.result()
1208
+ dirty_results = {}
1209
+ for wkey, fut in dirty_futures.items():
1210
+ try:
1211
+ dirty_results[wkey] = fut.result()
1212
+ except Exception:
1213
+ dirty_results[wkey] = (0, 0)
1214
+ for wt in git_wts:
1215
+ if wt["worktree_key"] in dirty_results:
1216
+ wt["is_dirty"], wt["dirty_count"] = dirty_results[wt["worktree_key"]]
1217
+ else:
1218
+ git_wts = parse_git_worktrees(repo_info["checkout_root"], repo_info["main_checkout"])
1219
+ populate_dirty_status(git_wts, repo_info["worktree_key"], fast=False)
1220
+ by_key = {wt["worktree_key"]: wt for wt in git_wts}
1221
+
1222
+ orca_used = False
1223
+ if not no_orca:
1224
+ orca_rows = fetch_orca_worktrees()
1225
+ if orca_rows is not None:
1226
+ orca_used = True
1227
+ main_prefix = repo_key + "/"
1228
+ for row in orca_rows:
1229
+ wkey = row["worktree_key"]
1230
+ if wkey in by_key:
1231
+ target = by_key[wkey]
1232
+ target["source"] = "git+orca"
1233
+ target["orca_id"] = row["orca_id"]
1234
+ target["orca_name"] = row["orca_name"]
1235
+ target["orca_host"] = row["orca_host"]
1236
+ target["orca_status"] = row["orca_status"]
1237
+ if not target["branch"] and row["branch"]:
1238
+ target["branch"] = row["branch"]
1239
+ continue
1240
+ same_repo = (
1241
+ (row["repo_path"] and normalize_path_key(row["repo_path"]) == repo_key)
1242
+ or wkey == repo_key
1243
+ or wkey.startswith(main_prefix)
1244
+ )
1245
+ if same_repo and os.path.isdir(row["raw_path"]):
1246
+ by_key[wkey] = {
1247
+ "worktree_key": wkey,
1248
+ "path": row["path"],
1249
+ "raw_path": row["raw_path"],
1250
+ "branch": row["branch"],
1251
+ "head_sha": "",
1252
+ "is_main": 1 if wkey == repo_key else 0,
1253
+ "is_detached": 0 if row["branch"] else 1,
1254
+ "is_dirty": row["is_dirty"],
1255
+ "dirty_count": 1 if row["is_dirty"] else 0,
1256
+ "source": "orca",
1257
+ "orca_id": row["orca_id"],
1258
+ "orca_name": row["orca_name"],
1259
+ "orca_host": row["orca_host"],
1260
+ "orca_status": row["orca_status"],
1261
+ }
1262
+ elif include_foreign_orca and os.path.isdir(row["raw_path"]):
1263
+ foreign = resolve_repo(row["raw_path"])
1264
+ if foreign and foreign["repo_key"] != repo_key:
1265
+ upsert_repo_row(conn, foreign, touch_sync=False)
1266
+ conn.execute(
1267
+ """INSERT INTO workspaces(
1268
+ worktree_key, repo_key, path, branch, head_sha, is_main, is_detached,
1269
+ is_dirty, dirty_count, source, orca_id, orca_name, orca_host, orca_status, updated_at
1270
+ ) VALUES(?, ?, ?, ?, '', ?, ?, ?, ?, 'orca', ?, ?, ?, ?, ?)
1271
+ ON CONFLICT(worktree_key) DO UPDATE SET
1272
+ repo_key=excluded.repo_key, path=excluded.path, branch=excluded.branch,
1273
+ source=CASE WHEN workspaces.source='git' THEN 'git+orca' ELSE excluded.source END,
1274
+ orca_id=excluded.orca_id, orca_name=excluded.orca_name,
1275
+ orca_host=excluded.orca_host, orca_status=excluded.orca_status,
1276
+ updated_at=excluded.updated_at""",
1277
+ (
1278
+ wkey, foreign["repo_key"], row["path"], row["branch"],
1279
+ 1 if wkey == foreign["repo_key"] else 0,
1280
+ 0 if row["branch"] else 1,
1281
+ row["is_dirty"], 1 if row["is_dirty"] else 0,
1282
+ row["orca_id"], row["orca_name"], row["orca_host"], row["orca_status"], now,
1283
+ ),
1284
+ )
1285
+
1286
+ existing_keys = {
1287
+ r["worktree_key"]
1288
+ for r in conn.execute("SELECT worktree_key FROM workspaces WHERE repo_key = ?", (repo_key,))
1289
+ }
1290
+ stale_keys = existing_keys - set(by_key.keys())
1291
+ if stale_keys:
1292
+ conn.executemany("DELETE FROM workspaces WHERE worktree_key = ?", [(k,) for k in stale_keys])
1293
+ conn.executemany("DELETE FROM files WHERE repo_key = ? AND worktree_key = ?", [(repo_key, k) for k in stale_keys])
1294
+ conn.executemany(
1295
+ "DELETE FROM worktree_deleted WHERE repo_key = ? AND worktree_key = ?",
1296
+ [(repo_key, k) for k in stale_keys],
1297
+ )
1298
+
1299
+ for wt in by_key.values():
1300
+ conn.execute(
1301
+ """INSERT INTO workspaces(
1302
+ worktree_key, repo_key, path, branch, head_sha, is_main, is_detached,
1303
+ is_dirty, dirty_count, source, orca_id, orca_name, orca_host, orca_status, updated_at
1304
+ ) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1305
+ ON CONFLICT(worktree_key) DO UPDATE SET
1306
+ repo_key=excluded.repo_key, path=excluded.path, branch=excluded.branch,
1307
+ head_sha=excluded.head_sha, is_main=excluded.is_main, is_detached=excluded.is_detached,
1308
+ is_dirty=excluded.is_dirty, dirty_count=excluded.dirty_count, source=excluded.source,
1309
+ orca_id=excluded.orca_id, orca_name=excluded.orca_name, orca_host=excluded.orca_host,
1310
+ orca_status=excluded.orca_status, updated_at=excluded.updated_at""",
1311
+ (
1312
+ wt["worktree_key"], repo_key, wt["path"], wt["branch"], wt["head_sha"],
1313
+ wt["is_main"], wt["is_detached"], wt["is_dirty"], wt["dirty_count"],
1314
+ wt["source"], wt["orca_id"], wt["orca_name"], wt["orca_host"], wt["orca_status"], now,
1315
+ ),
1316
+ )
1317
+ return len(by_key), orca_used
1318
+
1319
+
1320
+ def summarize_checks(rollup):
1321
+ if not isinstance(rollup, list) or not rollup:
1322
+ return ""
1323
+ passed = failed = pending = 0
1324
+ for item in rollup:
1325
+ if not isinstance(item, dict):
1326
+ continue
1327
+ conclusion = str(item.get("conclusion") or item.get("state") or "").upper()
1328
+ status = str(item.get("status") or "").upper()
1329
+ if conclusion in ("SUCCESS", "NEUTRAL", "SKIPPED"):
1330
+ passed += 1
1331
+ elif conclusion in ("FAILURE", "ERROR", "TIMED_OUT", "CANCELLED", "ACTION_REQUIRED", "STARTUP_FAILURE"):
1332
+ failed += 1
1333
+ elif status in ("IN_PROGRESS", "QUEUED", "PENDING", "WAITING", "REQUESTED") or conclusion in ("PENDING", "EXPECTED", ""):
1334
+ pending += 1
1335
+ else:
1336
+ pending += 1
1337
+ parts = []
1338
+ if failed:
1339
+ parts.append(f"fail:{failed}")
1340
+ if pending:
1341
+ parts.append(f"pending:{pending}")
1342
+ if passed:
1343
+ parts.append(f"pass:{passed}")
1344
+ return ",".join(parts)
1345
+
1346
+
1347
+ def sync_prs(conn, repo_info, offline=False, force_prs=False):
1348
+ repo_key = repo_info["repo_key"]
1349
+ if offline or not repo_info["remote_url"] or not shutil.which("gh"):
1350
+ count = conn.execute("SELECT COUNT(*) FROM prs WHERE repo_key = ?", (repo_key,)).fetchone()[0]
1351
+ return count, True
1352
+
1353
+ row = conn.execute("SELECT last_pr_sync_ts FROM repos WHERE repo_key = ?", (repo_key,)).fetchone()
1354
+ last_pr_ts = float(row["last_pr_sync_ts"]) if row and row["last_pr_sync_ts"] else 0.0
1355
+ now = time.time()
1356
+ if not force_prs and last_pr_ts > 0 and (now - last_pr_ts) < PR_TTL_SECONDS:
1357
+ count = conn.execute("SELECT COUNT(*) FROM prs WHERE repo_key = ?", (repo_key,)).fetchone()[0]
1358
+ return count, True
1359
+
1360
+ res = run_cmd(
1361
+ [
1362
+ "gh", "pr", "list", "--author", "@me", "--state", "open",
1363
+ "--limit", "50", "--json", PR_JSON_FIELDS,
1364
+ ],
1365
+ cwd=repo_info["checkout_root"],
1366
+ timeout=10,
1367
+ )
1368
+ if res.returncode != 0 or not res.stdout.strip():
1369
+ count = conn.execute("SELECT COUNT(*) FROM prs WHERE repo_key = ?", (repo_key,)).fetchone()[0]
1370
+ return count, True
1371
+
1372
+ try:
1373
+ items = json.loads(res.stdout)
1374
+ except ValueError:
1375
+ count = conn.execute("SELECT COUNT(*) FROM prs WHERE repo_key = ?", (repo_key,)).fetchone()[0]
1376
+ return count, True
1377
+
1378
+ if not isinstance(items, list):
1379
+ count = conn.execute("SELECT COUNT(*) FROM prs WHERE repo_key = ?", (repo_key,)).fetchone()[0]
1380
+ return count, True
1381
+
1382
+ seen_nums = set()
1383
+ for pr in items:
1384
+ if not isinstance(pr, dict) or not isinstance(pr.get("number"), int):
1385
+ continue
1386
+ num = pr["number"]
1387
+ seen_nums.add(num)
1388
+ conn.execute(
1389
+ """INSERT INTO prs(
1390
+ repo_key, number, title, head_branch, base_branch, state, is_draft,
1391
+ merge_state, review_decision, checks_summary, url, updated_at, synced_at
1392
+ ) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1393
+ ON CONFLICT(repo_key, number) DO UPDATE SET
1394
+ title=excluded.title, head_branch=excluded.head_branch, base_branch=excluded.base_branch,
1395
+ state=excluded.state, is_draft=excluded.is_draft, merge_state=excluded.merge_state,
1396
+ review_decision=excluded.review_decision, checks_summary=excluded.checks_summary,
1397
+ url=excluded.url, updated_at=excluded.updated_at, synced_at=excluded.synced_at""",
1398
+ (
1399
+ repo_key,
1400
+ num,
1401
+ cap_sig(str(pr.get("title") or ""), 120),
1402
+ str(pr.get("headRefName") or ""),
1403
+ str(pr.get("baseRefName") or ""),
1404
+ str(pr.get("state") or "OPEN"),
1405
+ 1 if pr.get("isDraft") else 0,
1406
+ str(pr.get("mergeStateStatus") or ""),
1407
+ str(pr.get("reviewDecision") or ""),
1408
+ summarize_checks(pr.get("statusCheckRollup")),
1409
+ str(pr.get("url") or ""),
1410
+ str(pr.get("updatedAt") or ""),
1411
+ now,
1412
+ ),
1413
+ )
1414
+
1415
+ existing_nums = {
1416
+ r["number"] for r in conn.execute("SELECT number FROM prs WHERE repo_key = ?", (repo_key,))
1417
+ }
1418
+ closed_nums = existing_nums - seen_nums
1419
+ if closed_nums:
1420
+ conn.executemany(
1421
+ "DELETE FROM prs WHERE repo_key = ? AND number = ?",
1422
+ [(repo_key, n) for n in closed_nums],
1423
+ )
1424
+ conn.execute("UPDATE repos SET last_pr_sync_ts = ? WHERE repo_key = ?", (now, repo_key))
1425
+ return len(seen_nums), False
1426
+
1427
+
1428
+ def _parse_goal_frontmatter(goal_path):
1429
+ """Extract lightweight YAML frontmatter key/value pairs from a goal markdown file."""
1430
+ try:
1431
+ with open(goal_path, encoding="utf-8", errors="replace") as handle:
1432
+ text = handle.read(32768)
1433
+ except OSError:
1434
+ return {}
1435
+ match = re.match(r"^---\r?\n(.*?)\r?\n---(?:\r?\n|$)", text, re.S)
1436
+ if not match:
1437
+ return {}
1438
+ fields = {}
1439
+ for line in match.group(1).splitlines():
1440
+ if ":" not in line or line.startswith((" ", "\t")):
1441
+ continue
1442
+ key, value = line.split(":", 1)
1443
+ value = value.strip()
1444
+ if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'":
1445
+ value = value[1:-1]
1446
+ fields[key.strip()] = value
1447
+ return fields
1448
+
1449
+
1450
+ def _normalize_rel_manifest(raw_rel):
1451
+ rel = str(raw_rel or "").strip().replace("\\", "/")
1452
+ while rel.startswith("./"):
1453
+ rel = rel[2:]
1454
+ return rel
1455
+
1456
+
1457
+ def _safe_int(value, default=0):
1458
+ if value is None or isinstance(value, bool):
1459
+ return default
1460
+ try:
1461
+ return int(value)
1462
+ except (TypeError, ValueError):
1463
+ return default
1464
+
1465
+
1466
+ def _safe_relpath(target, root):
1467
+ try:
1468
+ return os.path.relpath(target, root)
1469
+ except ValueError:
1470
+ return None
1471
+
1472
+
1473
+ def _scan_project_state_for_checkout(checkout_root):
1474
+ """Scan goal frontmatter, scope manifests, and goal latest-summary.json files inside a checkout."""
1475
+ records = {}
1476
+ root_key = normalize_path_key(checkout_root)
1477
+
1478
+ # Read active_sprint and manifest links from .scratch/goals/*.md frontmatter (newest wins per manifest).
1479
+ goal_by_manifest = {}
1480
+ linked_manifest_paths = set()
1481
+ goal_files = glob.glob(os.path.join(checkout_root, ".scratch", "goals", "*.md"))
1482
+ goal_files.sort(key=lambda p: (os.path.getmtime(p) if os.path.exists(p) else 0.0, p))
1483
+ for gpath in goal_files:
1484
+ fields = _parse_goal_frontmatter(gpath)
1485
+ manifest_rel = _normalize_rel_manifest(fields.get("manifest"))
1486
+ if not manifest_rel:
1487
+ continue
1488
+ raw_sprint = str(fields.get("active_sprint") or "").strip()
1489
+ active_sprint = int(raw_sprint) if raw_sprint.isdigit() and int(raw_sprint) >= 1 else None
1490
+ goal_by_manifest[manifest_rel] = {
1491
+ "goal": str(fields.get("goal") or "").strip(),
1492
+ "active_sprint": active_sprint,
1493
+ }
1494
+ candidate = os.path.join(checkout_root, manifest_rel)
1495
+ if os.path.isfile(candidate):
1496
+ cand_key = normalize_path_key(candidate)
1497
+ if cand_key == root_key or cand_key.startswith(root_key + "/"):
1498
+ linked_manifest_paths.add(os.path.realpath(candidate))
1499
+
1500
+ manifest_paths = sorted({
1501
+ *(os.path.realpath(p) for p in glob.glob(os.path.join(checkout_root, "docs", "specs", "*-manifest.json"))),
1502
+ *(os.path.realpath(p) for p in glob.glob(os.path.join(checkout_root, ".scratch", "goals", "*-manifest.json"))),
1503
+ *linked_manifest_paths,
1504
+ })
1505
+ for mpath in manifest_paths:
1506
+ try:
1507
+ with open(mpath, encoding="utf-8") as handle:
1508
+ data = json.load(handle)
1509
+ except (OSError, ValueError):
1510
+ continue
1511
+ if not isinstance(data, dict) or not isinstance(data.get("slices"), list):
1512
+ continue
1513
+ raw_rel = _safe_relpath(mpath, checkout_root)
1514
+ if raw_rel is None:
1515
+ continue
1516
+ rel = _normalize_rel_manifest(raw_rel)
1517
+ slices = [s for s in data["slices"] if isinstance(s, dict)]
1518
+ goal_meta = goal_by_manifest.get(rel) or {}
1519
+ active_sprint = goal_meta.get("active_sprint")
1520
+ if active_sprint is not None:
1521
+ active_slices = [s for s in slices if _safe_int(s.get("sprint"), 1) <= active_sprint]
1522
+ deferred_count = len(slices) - len(active_slices)
1523
+ else:
1524
+ active_slices = slices
1525
+ deferred_count = 0
1526
+ pending_inv = sum(
1527
+ 1 for item in data.get("inventory", ())
1528
+ if isinstance(item, dict) and str(item.get("status") or "").lower() == "pending"
1529
+ )
1530
+ sme_blocked = (
1531
+ str(data.get("sme_gate") or "none").lower() == "required"
1532
+ or any(str(s.get("sme_gate") or "none").lower() == "required" for s in active_slices)
1533
+ )
1534
+ records[rel] = {
1535
+ "state_key": rel,
1536
+ "source_kind": "manifest",
1537
+ "source_path": rel,
1538
+ "product": cap_sig(str(data.get("product") or goal_meta.get("goal") or Path(mpath).stem), 80),
1539
+ "active_sprint": active_sprint,
1540
+ "passed_slices": 0,
1541
+ "active_slices": len(active_slices),
1542
+ "total_slices": len(slices),
1543
+ "deferred_count": deferred_count,
1544
+ "pending_inventory": pending_inv,
1545
+ "sme_gate_blocked": 1 if sme_blocked else 0,
1546
+ "last_exit_code": None,
1547
+ "last_exit_reason": "",
1548
+ }
1549
+
1550
+ summary_paths = glob.glob(os.path.join(checkout_root, ".scratch", "goals", "*", "latest-summary.json"))
1551
+ summary_paths.sort(key=lambda p: (os.path.getmtime(p) if os.path.exists(p) else 0.0, p))
1552
+ for spath in summary_paths:
1553
+ try:
1554
+ with open(spath, encoding="utf-8") as handle:
1555
+ data = json.load(handle)
1556
+ except (OSError, ValueError):
1557
+ continue
1558
+ if not isinstance(data, dict):
1559
+ continue
1560
+ raw_rel = _safe_relpath(spath, checkout_root)
1561
+ if raw_rel is None:
1562
+ continue
1563
+ rel = _normalize_rel_manifest(raw_rel)
1564
+ exit_code = data.get("exit_code")
1565
+ if isinstance(exit_code, bool) or not isinstance(exit_code, int):
1566
+ exit_code = None
1567
+ exit_reason = str(data.get("exit_reason") or "")
1568
+ scope = data.get("scope") if isinstance(data.get("scope"), dict) else None
1569
+
1570
+ if scope:
1571
+ manifest_rel = _normalize_rel_manifest(scope.get("manifest"))
1572
+ s_sprint = scope.get("active_sprint")
1573
+ if isinstance(s_sprint, bool) or not isinstance(s_sprint, int):
1574
+ s_sprint = None
1575
+ deferred_val = scope.get("deferred_slices", 0)
1576
+ deferred_count = len(deferred_val) if isinstance(deferred_val, list) else _safe_int(deferred_val, 0)
1577
+ pending_val = scope.get("pending_inventory", 0)
1578
+ pending_count = len(pending_val) if isinstance(pending_val, list) else _safe_int(pending_val, 0)
1579
+ passed = _safe_int(scope.get("passed_slices"), 0)
1580
+ active_cnt = _safe_int(scope.get("active_slices"), 0)
1581
+ total_cnt = _safe_int(scope.get("total_slices"), 0)
1582
+ sme_blocked = 1 if scope.get("sme_gate_blocked") else 0
1583
+
1584
+ if manifest_rel and manifest_rel in records:
1585
+ rec = records[manifest_rel]
1586
+ if s_sprint is not None:
1587
+ rec["active_sprint"] = s_sprint
1588
+ rec["passed_slices"] = passed
1589
+ if active_cnt:
1590
+ rec["active_slices"] = active_cnt
1591
+ if total_cnt:
1592
+ rec["total_slices"] = total_cnt
1593
+ rec["deferred_count"] = deferred_count
1594
+ rec["pending_inventory"] = pending_count
1595
+ rec["sme_gate_blocked"] = 1 if (rec["sme_gate_blocked"] or sme_blocked) else 0
1596
+ rec["last_exit_code"] = exit_code
1597
+ rec["last_exit_reason"] = exit_reason
1598
+ else:
1599
+ records[rel] = {
1600
+ "state_key": rel,
1601
+ "source_kind": "goal_summary",
1602
+ "source_path": rel,
1603
+ "product": cap_sig(str(data.get("goal") or Path(spath).parent.name), 80),
1604
+ "active_sprint": s_sprint,
1605
+ "passed_slices": passed,
1606
+ "active_slices": active_cnt,
1607
+ "total_slices": total_cnt,
1608
+ "deferred_count": deferred_count,
1609
+ "pending_inventory": pending_count,
1610
+ "sme_gate_blocked": sme_blocked,
1611
+ "last_exit_code": exit_code,
1612
+ "last_exit_reason": exit_reason,
1613
+ }
1614
+ else:
1615
+ records[rel] = {
1616
+ "state_key": rel,
1617
+ "source_kind": "goal_summary",
1618
+ "source_path": rel,
1619
+ "product": cap_sig(str(data.get("goal") or Path(spath).parent.name), 80),
1620
+ "active_sprint": None,
1621
+ "passed_slices": 0,
1622
+ "active_slices": 0,
1623
+ "total_slices": 0,
1624
+ "deferred_count": 0,
1625
+ "pending_inventory": 0,
1626
+ "sme_gate_blocked": 0,
1627
+ "last_exit_code": exit_code,
1628
+ "last_exit_reason": exit_reason,
1629
+ }
1630
+ return records
1631
+
1632
+
1633
+ def sync_project_state(conn, repo_info):
1634
+ repo_key = repo_info["repo_key"]
1635
+ wkey = repo_info["worktree_key"]
1636
+ now = time.time()
1637
+ records = _scan_project_state_for_checkout(repo_info["checkout_root"])
1638
+
1639
+ existing_keys = {
1640
+ r["state_key"]
1641
+ for r in conn.execute(
1642
+ "SELECT state_key FROM project_state WHERE repo_key = ? AND worktree_key = ?",
1643
+ (repo_key, wkey),
1644
+ )
1645
+ }
1646
+ stale = existing_keys - set(records.keys())
1647
+ if stale:
1648
+ conn.executemany(
1649
+ "DELETE FROM project_state WHERE repo_key = ? AND worktree_key = ? AND state_key = ?",
1650
+ [(repo_key, wkey, sk) for sk in stale],
1651
+ )
1652
+
1653
+ for rec in records.values():
1654
+ conn.execute(
1655
+ """INSERT INTO project_state(
1656
+ repo_key, worktree_key, state_key, source_kind, source_path, product,
1657
+ active_sprint, passed_slices, active_slices, total_slices, deferred_count,
1658
+ pending_inventory, sme_gate_blocked, last_exit_code, last_exit_reason, updated_at
1659
+ ) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1660
+ ON CONFLICT(repo_key, worktree_key, state_key) DO UPDATE SET
1661
+ source_kind=excluded.source_kind, source_path=excluded.source_path, product=excluded.product,
1662
+ active_sprint=excluded.active_sprint, passed_slices=excluded.passed_slices,
1663
+ active_slices=excluded.active_slices, total_slices=excluded.total_slices,
1664
+ deferred_count=excluded.deferred_count, pending_inventory=excluded.pending_inventory,
1665
+ sme_gate_blocked=excluded.sme_gate_blocked, last_exit_code=excluded.last_exit_code,
1666
+ last_exit_reason=excluded.last_exit_reason, updated_at=excluded.updated_at""",
1667
+ (
1668
+ repo_key, wkey, rec["state_key"], rec["source_kind"], rec["source_path"], rec["product"],
1669
+ rec["active_sprint"], rec["passed_slices"], rec["active_slices"], rec["total_slices"],
1670
+ rec["deferred_count"], rec["pending_inventory"], rec["sme_gate_blocked"],
1671
+ rec["last_exit_code"], rec["last_exit_reason"], now,
1672
+ ),
1673
+ )
1674
+ return len(records)
1675
+
1676
+
1677
+ def upsert_repo_row(conn, repo_info, touch_sync=True):
1678
+ now = time.time() if touch_sync else 0.0
1679
+ conn.execute(
1680
+ """INSERT INTO repos(
1681
+ repo_key, name, main_checkout, common_dir, remote_url, remote_slug, default_branch, last_sync_ts
1682
+ ) VALUES(?, ?, ?, ?, ?, ?, ?, ?)
1683
+ ON CONFLICT(repo_key) DO UPDATE SET
1684
+ name=excluded.name, main_checkout=excluded.main_checkout, common_dir=excluded.common_dir,
1685
+ remote_url=excluded.remote_url, remote_slug=excluded.remote_slug,
1686
+ default_branch=excluded.default_branch,
1687
+ last_sync_ts=CASE WHEN excluded.last_sync_ts > 0 THEN excluded.last_sync_ts ELSE repos.last_sync_ts END""",
1688
+ (
1689
+ repo_info["repo_key"],
1690
+ repo_info["name"],
1691
+ display_path(repo_info["main_checkout"]),
1692
+ display_path(repo_info["common_dir"]),
1693
+ repo_info["remote_url"],
1694
+ repo_info["remote_slug"],
1695
+ repo_info["default_branch"],
1696
+ now,
1697
+ ),
1698
+ )
1699
+
1700
+
1701
+ def perform_sync(
1702
+ conn,
1703
+ repo_info,
1704
+ offline=False,
1705
+ no_orca=False,
1706
+ force_prs=False,
1707
+ include_foreign_orca=False,
1708
+ fast=False,
1709
+ ):
1710
+ started = time.perf_counter()
1711
+ upsert_repo_row(conn, repo_info, touch_sync=True)
1712
+ file_stats = sync_files_and_symbols(conn, repo_info)
1713
+ wt_count, orca_used = sync_workspaces(
1714
+ conn, repo_info, no_orca=no_orca, include_foreign_orca=include_foreign_orca, fast=fast
1715
+ )
1716
+ pr_count, prs_cached = sync_prs(conn, repo_info, offline=offline, force_prs=force_prs)
1717
+ ps_count = sync_project_state(conn, repo_info)
1718
+ conn.execute(
1719
+ "UPDATE repos SET file_count = ?, symbol_count = ?, last_sync_ts = ? WHERE repo_key = ?",
1720
+ (file_stats["total_files"], file_stats["total_symbols"], time.time(), repo_info["repo_key"]),
1721
+ )
1722
+ conn.commit()
1723
+ conn.execute("PRAGMA incremental_vacuum")
1724
+ elapsed_ms = round((time.perf_counter() - started) * 1000.0, 1)
1725
+ return {
1726
+ "repo": repo_info["name"],
1727
+ "repo_key": repo_info["repo_key"],
1728
+ "checkout": display_path(repo_info["checkout_root"]),
1729
+ "main_checkout": display_path(repo_info["main_checkout"]),
1730
+ "branch": repo_info["current_branch"] or "detached",
1731
+ **file_stats,
1732
+ "workspaces_count": wt_count,
1733
+ "orca_used": orca_used,
1734
+ "prs_count": pr_count,
1735
+ "prs_cached": prs_cached,
1736
+ "project_states": ps_count,
1737
+ "elapsed_ms": elapsed_ms,
1738
+ }
1739
+
1740
+
1741
+ def build_fts_query(raw_term):
1742
+ tokens = [tok for tok in raw_term.strip().split() if tok]
1743
+ if not tokens:
1744
+ return ""
1745
+ parts = []
1746
+ for tok in tokens:
1747
+ prefix = tok.endswith("*") and len(tok) > 1
1748
+ core = tok[:-1] if prefix else tok
1749
+ core = core.strip('"')
1750
+ if not core:
1751
+ continue
1752
+ escaped = core.replace('"', '""')
1753
+ parts.append(f'"{escaped}"*' if prefix else f'"{escaped}"')
1754
+ return " ".join(parts)
1755
+
1756
+
1757
+ def format_project_state_compact(ps):
1758
+ parts = [ps["product"] or ps["source_path"]]
1759
+ if ps["active_sprint"] is not None:
1760
+ parts.append(f"S{ps['active_sprint']}")
1761
+ if ps["total_slices"]:
1762
+ parts.append(f"{ps['passed_slices']}/{ps['total_slices']}")
1763
+ if ps["deferred_count"]:
1764
+ parts.append(f"def={ps['deferred_count']}")
1765
+ if ps["pending_inventory"]:
1766
+ parts.append(f"pend_inv={ps['pending_inventory']}")
1767
+ if ps["sme_gate_blocked"]:
1768
+ parts.append("SME_BLOCKED")
1769
+ if ps["last_exit_code"] is not None:
1770
+ reason = f"({ps['last_exit_reason']})" if ps["last_exit_reason"] else ""
1771
+ parts.append(f"exit={ps['last_exit_code']}{reason}")
1772
+ return " ".join(parts)
1773
+
1774
+
1775
+ def collect_workspaces(conn, repo_key=None):
1776
+ where = "WHERE w.repo_key = ?" if repo_key else ""
1777
+ params = (repo_key,) if repo_key else ()
1778
+ rows = conn.execute(
1779
+ f"""SELECT w.*, r.name AS repo_name
1780
+ FROM workspaces w
1781
+ JOIN repos r ON r.repo_key = w.repo_key
1782
+ {where}
1783
+ ORDER BY r.name, w.is_main DESC, w.is_detached ASC, w.path ASC""",
1784
+ params,
1785
+ ).fetchall()
1786
+
1787
+ prs_by_key = {}
1788
+ pr_rows = conn.execute(
1789
+ f"SELECT * FROM prs {'WHERE repo_key = ?' if repo_key else ''} ORDER BY number DESC",
1790
+ params,
1791
+ ).fetchall()
1792
+ for pr in pr_rows:
1793
+ if pr["head_branch"]:
1794
+ prs_by_key.setdefault((pr["repo_key"], pr["head_branch"]), dict(pr))
1795
+
1796
+ ps_by_wt = {}
1797
+ ps_rows = conn.execute(
1798
+ f"SELECT * FROM project_state {'WHERE repo_key = ?' if repo_key else ''} ORDER BY source_path",
1799
+ params,
1800
+ ).fetchall()
1801
+ for ps in ps_rows:
1802
+ ps_by_wt.setdefault((ps["repo_key"], ps["worktree_key"]), []).append(dict(ps))
1803
+
1804
+ out = []
1805
+ for row in rows:
1806
+ item = dict(row)
1807
+ matched_pr = prs_by_key.get((item["repo_key"], item["branch"])) if item["branch"] else None
1808
+ item["pr"] = (
1809
+ {
1810
+ "number": matched_pr["number"],
1811
+ "title": matched_pr["title"],
1812
+ "merge_state": matched_pr["merge_state"],
1813
+ "checks_summary": matched_pr["checks_summary"],
1814
+ "is_draft": bool(matched_pr["is_draft"]),
1815
+ "url": matched_pr["url"],
1816
+ }
1817
+ if matched_pr else None
1818
+ )
1819
+ item["project_state"] = ps_by_wt.get((item["repo_key"], item["worktree_key"]), [])
1820
+ out.append(item)
1821
+ return out
1822
+
1823
+
1824
+ def collect_prs(conn, repo_key=None):
1825
+ where = "WHERE p.repo_key = ?" if repo_key else ""
1826
+ params = (repo_key,) if repo_key else ()
1827
+ rows = conn.execute(
1828
+ f"""SELECT p.*, r.name AS repo_name
1829
+ FROM prs p
1830
+ JOIN repos r ON r.repo_key = p.repo_key
1831
+ {where}
1832
+ ORDER BY r.name, p.number DESC""",
1833
+ params,
1834
+ ).fetchall()
1835
+
1836
+ wt_by_branch = {}
1837
+ wt_rows = conn.execute(
1838
+ f"SELECT * FROM workspaces {'WHERE repo_key = ?' if repo_key else ''} ORDER BY is_main DESC, path ASC",
1839
+ params,
1840
+ ).fetchall()
1841
+ for wt in wt_rows:
1842
+ if wt["branch"]:
1843
+ wt_by_branch.setdefault((wt["repo_key"], wt["branch"]), dict(wt))
1844
+
1845
+ out = []
1846
+ for row in rows:
1847
+ item = dict(row)
1848
+ wt = wt_by_branch.get((item["repo_key"], item["head_branch"])) if item["head_branch"] else None
1849
+ item["worktree_path"] = wt["path"] if wt else None
1850
+ item["worktree_dirty"] = bool(wt["is_dirty"]) if wt else None
1851
+ out.append(item)
1852
+ return out
1853
+
1854
+
1855
+ def render_overview_text(repo_info, sync_stats, db_size_kb, key_files, workspaces, prs, states, max_bytes):
1856
+ lines = []
1857
+ branch = repo_info["current_branch"] or "detached"
1858
+ cur_wkey = repo_info["worktree_key"]
1859
+ lines.append(
1860
+ f"repo: {repo_info['name']} [{branch}] | "
1861
+ f"files:{sync_stats['total_files']} syms:{sync_stats['total_symbols']} | db:{db_size_kb:.1f}KB"
1862
+ )
1863
+ if normalize_path_key(repo_info["checkout_root"]) != repo_info["repo_key"]:
1864
+ lines.append(f"cwd: {display_path(repo_info['checkout_root'])} (main: {display_path(repo_info['main_checkout'])})")
1865
+ else:
1866
+ lines.append(f"root: {display_path(repo_info['main_checkout'])}")
1867
+
1868
+ key_bits = []
1869
+ if key_files["docs"]:
1870
+ key_bits.append("docs: " + ", ".join(key_files["docs"][:5]))
1871
+ if key_files["entrypoints"]:
1872
+ key_bits.append("entry: " + ", ".join(key_files["entrypoints"][:5]))
1873
+ if key_files["verify_skills"]:
1874
+ key_bits.append("verify: " + ", ".join(key_files["verify_skills"][:4]))
1875
+ if key_bits:
1876
+ lines.append(" | ".join(key_bits))
1877
+
1878
+ if states:
1879
+ state_bits = [format_project_state_compact(s) for s in states[:3]]
1880
+ extra_s = f" (+{len(states) - 3})" if len(states) > 3 else ""
1881
+ lines.append("state: " + "; ".join(state_bits) + extra_s)
1882
+
1883
+ if prs:
1884
+ pr_bits = []
1885
+ for pr in prs[:4]:
1886
+ meta = []
1887
+ if pr["is_draft"]:
1888
+ meta.append("draft")
1889
+ if pr["merge_state"]:
1890
+ meta.append(pr["merge_state"])
1891
+ if pr["checks_summary"]:
1892
+ meta.append(pr["checks_summary"])
1893
+ mstr = f" ({', '.join(meta)})" if meta else ""
1894
+ pr_bits.append(f"#{pr['number']}[{pr['head_branch']}] {cap_sig(pr['title'], 42)}{mstr}")
1895
+ extra_p = f" (+{len(prs) - 4})" if len(prs) > 4 else ""
1896
+ lines.append("prs: " + "; ".join(pr_bits) + extra_p)
1897
+
1898
+ if workspaces:
1899
+ interesting = []
1900
+ detached_extra = 0
1901
+ for wt in workspaces:
1902
+ is_cur = wt["worktree_key"] == cur_wkey
1903
+ if is_cur or wt["is_main"] or not wt["is_detached"] or wt["source"] != "git" or wt["pr"]:
1904
+ interesting.append(wt)
1905
+ else:
1906
+ detached_extra += 1
1907
+ interesting.sort(
1908
+ key=lambda w: (
1909
+ 0 if w["worktree_key"] == cur_wkey else 1,
1910
+ 0 if w["pr"] else 1,
1911
+ 0 if w["source"] != "git" else 1,
1912
+ 0 if w["is_main"] else 1,
1913
+ w["branch"] or w["path"],
1914
+ )
1915
+ )
1916
+ wt_lines = []
1917
+ shown = 0
1918
+ for wt in interesting[:6]:
1919
+ shown += 1
1920
+ tag = "*" if wt["worktree_key"] == cur_wkey else " "
1921
+ dirty = f" dirty({wt['dirty_count']})" if wt["is_dirty"] else ""
1922
+ label = wt["branch"] or f"detached@{wt['head_sha']}"
1923
+ src = f" [{wt['source']}]" if wt["source"] != "git" else ""
1924
+ pr_tag = f" PR#{wt['pr']['number']}" if wt["pr"] else ""
1925
+ short_p = os.path.basename(wt["path"].rstrip("/")) or wt["path"]
1926
+ wt_lines.append(f" {tag} {short_p} ({label}){dirty}{src}{pr_tag}")
1927
+ omitted = (len(interesting) - shown) + detached_extra
1928
+ header = f"worktrees ({len(workspaces)}):"
1929
+ if omitted:
1930
+ header += f" (+{omitted} more)"
1931
+ lines.append(header)
1932
+ lines.extend(wt_lines)
1933
+
1934
+ text = "\n".join(lines)
1935
+ return truncate_utf8(text, max_bytes)
1936
+
1937
+
1938
+ def cmd_sync(opts):
1939
+ repo_info = resolve_repo(opts.path)
1940
+ if repo_info is None:
1941
+ raise SystemExit(f"not inside a git repository: {os.path.abspath(opts.path)}")
1942
+ db_path = resolve_db_path(opts, repo_info)
1943
+ conn = connect_db(db_path)
1944
+ try:
1945
+ stats = perform_sync(
1946
+ conn,
1947
+ repo_info,
1948
+ offline=opts.offline,
1949
+ no_orca=opts.no_orca,
1950
+ force_prs=opts.force_prs,
1951
+ include_foreign_orca=getattr(opts, "use_global", False),
1952
+ fast=opts.fast,
1953
+ )
1954
+ finally:
1955
+ conn.close()
1956
+ db_kb = round(db_disk_bytes(db_path) / 1024.0, 2)
1957
+ stats["db_path"] = display_path(db_path)
1958
+ stats["db_size_kb"] = db_kb
1959
+ if opts.json:
1960
+ print(json.dumps(stats, indent=2))
1961
+ else:
1962
+ print(
1963
+ f"synced {stats['repo']} [{stats['branch']}]: "
1964
+ f"{stats['files_indexed']} indexed, {stats['files_skipped']} skipped, {stats['files_removed']} removed "
1965
+ f"({stats['total_files']} files, {stats['total_symbols']} symbols, {stats['workspaces_count']} worktrees, "
1966
+ f"{stats['prs_count']} prs, {stats['project_states']} states) | db {db_kb:.1f} KB in {stats['elapsed_ms']}ms"
1967
+ )
1968
+ return 0
1969
+
1970
+
1971
+ def cmd_overview(opts):
1972
+ repo_info = resolve_repo(opts.path)
1973
+ if repo_info is None:
1974
+ raise SystemExit(f"not inside a git repository: {os.path.abspath(opts.path)}")
1975
+ db_path = resolve_db_path(opts, repo_info)
1976
+ conn = connect_db(db_path)
1977
+ try:
1978
+ stats = perform_sync(
1979
+ conn,
1980
+ repo_info,
1981
+ offline=opts.offline,
1982
+ no_orca=opts.no_orca,
1983
+ force_prs=False,
1984
+ include_foreign_orca=getattr(opts, "use_global", False),
1985
+ fast=opts.fast,
1986
+ )
1987
+ rkey = repo_info["repo_key"]
1988
+ wkey = repo_info["worktree_key"]
1989
+ is_main = wkey == rkey
1990
+
1991
+ def role_files(role_name, order_by, limit=8):
1992
+ if is_main:
1993
+ sql = f"SELECT rel_path FROM files WHERE repo_key = ? AND worktree_key = '' AND role = ? ORDER BY {order_by} LIMIT ?"
1994
+ params = (rkey, role_name, limit)
1995
+ else:
1996
+ sql = (
1997
+ "SELECT rel_path FROM files f "
1998
+ "WHERE f.repo_key = ? AND f.role = ? "
1999
+ "AND (f.worktree_key = ? OR ("
2000
+ " f.worktree_key = '' "
2001
+ " AND NOT EXISTS (SELECT 1 FROM files ov WHERE ov.repo_key = f.repo_key AND ov.worktree_key = ? AND ov.rel_path = f.rel_path) "
2002
+ " AND NOT EXISTS (SELECT 1 FROM worktree_deleted wd WHERE wd.repo_key = f.repo_key AND wd.worktree_key = ? AND wd.rel_path = f.rel_path)"
2003
+ f")) ORDER BY {order_by} LIMIT ?"
2004
+ )
2005
+ params = (rkey, role_name, wkey, wkey, wkey, limit)
2006
+ return [r["rel_path"] for r in conn.execute(sql, params)]
2007
+
2008
+ docs = role_files("doc", "length(rel_path), rel_path")
2009
+ entrypoints = role_files("entrypoint", "length(rel_path), rel_path")
2010
+ verify_skills = role_files("verify-skill", "rel_path")
2011
+ workspaces = collect_workspaces(conn, rkey)
2012
+ prs = collect_prs(conn, rkey)
2013
+ states = [
2014
+ dict(r)
2015
+ for r in conn.execute(
2016
+ "SELECT * FROM project_state WHERE repo_key = ? ORDER BY updated_at DESC, source_path",
2017
+ (rkey,),
2018
+ )
2019
+ ]
2020
+ finally:
2021
+ conn.close()
2022
+
2023
+ db_kb = round(db_disk_bytes(db_path) / 1024.0, 2)
2024
+ key_files = {"docs": docs, "entrypoints": entrypoints, "verify_skills": verify_skills}
2025
+ overview_text = render_overview_text(
2026
+ repo_info, stats, db_kb, key_files, workspaces, prs, states, opts.max_bytes
2027
+ )
2028
+ if opts.json:
2029
+ payload = {
2030
+ "repo": repo_info["name"],
2031
+ "repo_key": repo_info["repo_key"],
2032
+ "branch": repo_info["current_branch"] or "detached",
2033
+ "checkout": display_path(repo_info["checkout_root"]),
2034
+ "main_checkout": display_path(repo_info["main_checkout"]),
2035
+ "db_path": display_path(db_path),
2036
+ "db_size_kb": db_kb,
2037
+ "sync": stats,
2038
+ **key_files,
2039
+ "workspaces": workspaces,
2040
+ "prs": prs,
2041
+ "project_state": states,
2042
+ "overview_text": overview_text,
2043
+ }
2044
+ print(json.dumps(payload, indent=2))
2045
+ else:
2046
+ print(overview_text)
2047
+ return 0
2048
+
2049
+
2050
+ def cmd_query(opts):
2051
+ repo_info = resolve_repo(opts.path)
2052
+ db_path = resolve_db_path(opts, repo_info)
2053
+ just_synced = False
2054
+ if not os.path.exists(db_path):
2055
+ if repo_info is None:
2056
+ raise SystemExit(f"index DB does not exist: {db_path}")
2057
+ conn = connect_db(db_path)
2058
+ try:
2059
+ perform_sync(conn, repo_info, offline=True, no_orca=True, fast=True)
2060
+ just_synced = True
2061
+ finally:
2062
+ conn.close()
2063
+
2064
+ fts_q = build_fts_query(opts.term)
2065
+ conn = connect_db(db_path, readonly=bool(opts.no_sync))
2066
+ try:
2067
+ repo_key = None if opts.all_repos else (repo_info["repo_key"] if repo_info else None)
2068
+ wt_key = repo_info["worktree_key"] if (repo_info and repo_key is not None) else None
2069
+ if repo_info is not None:
2070
+ exists = conn.execute("SELECT 1 FROM repos WHERE repo_key = ?", (repo_info["repo_key"],)).fetchone()
2071
+ if exists is None and getattr(opts, "db", None):
2072
+ if repo_key == repo_info["repo_key"]:
2073
+ repo_key = None
2074
+ wt_key = None
2075
+ elif exists is None and not opts.no_sync and not just_synced:
2076
+ perform_sync(conn, repo_info, offline=True, no_orca=True, fast=True)
2077
+ elif exists is not None and not opts.no_sync and not just_synced:
2078
+ file_stats = sync_files_and_symbols(conn, repo_info)
2079
+ conn.execute(
2080
+ "UPDATE repos SET file_count = ?, symbol_count = ?, last_sync_ts = ? WHERE repo_key = ?",
2081
+ (file_stats["total_files"], file_stats["total_symbols"], time.time(), repo_info["repo_key"]),
2082
+ )
2083
+ conn.commit()
2084
+
2085
+ results = []
2086
+ if fts_q:
2087
+ sql = (
2088
+ "SELECT s.rel_path, s.line, s.kind, s.name, s.signature, r.name AS repo_name "
2089
+ "FROM symbols_fts f "
2090
+ "JOIN symbols s ON s.id = f.rowid "
2091
+ "JOIN repos r ON r.repo_key = s.repo_key "
2092
+ "WHERE symbols_fts MATCH ?"
2093
+ )
2094
+ params = [fts_q]
2095
+ if repo_key is not None:
2096
+ sql += " AND s.repo_key = ?"
2097
+ params.append(repo_key)
2098
+ if wt_key and wt_key != repo_key:
2099
+ sql += (
2100
+ " AND (s.worktree_key = ? OR ("
2101
+ " s.worktree_key = '' "
2102
+ " AND NOT EXISTS (SELECT 1 FROM files ov WHERE ov.repo_key = s.repo_key AND ov.worktree_key = ? AND ov.rel_path = s.rel_path) "
2103
+ " AND NOT EXISTS (SELECT 1 FROM worktree_deleted wd WHERE wd.repo_key = s.repo_key AND wd.worktree_key = ? AND wd.rel_path = s.rel_path)"
2104
+ "))"
2105
+ )
2106
+ params.extend([wt_key, wt_key, wt_key])
2107
+ else:
2108
+ sql += " AND s.worktree_key = ''"
2109
+ else:
2110
+ sql += (
2111
+ " AND (s.worktree_key = '' OR NOT EXISTS ("
2112
+ " SELECT 1 FROM files fb WHERE fb.repo_key = s.repo_key AND fb.worktree_key = ''"
2113
+ "))"
2114
+ )
2115
+ sql += " ORDER BY bm25(symbols_fts, 10.0, 3.0, 1.0), s.rel_path, s.line LIMIT ?"
2116
+ params.append(max(1, opts.limit))
2117
+ try:
2118
+ rows = conn.execute(sql, params).fetchall()
2119
+ results = [dict(r) for r in rows]
2120
+ except sqlite3.OperationalError:
2121
+ results = []
2122
+ finally:
2123
+ conn.close()
2124
+
2125
+ if opts.json:
2126
+ print(json.dumps({"query": opts.term, "count": len(results), "results": results}, indent=2))
2127
+ else:
2128
+ multi_repo = opts.all_repos and len({r["repo_name"] for r in results}) > 1
2129
+ for r in results:
2130
+ prefix = f"[{r['repo_name']}] " if multi_repo else ""
2131
+ print(f"{prefix}{r['rel_path']}:{r['line']} {r['kind']} {r['signature']}")
2132
+ if not results:
2133
+ print(f"no matches for {opts.term!r}")
2134
+ return 0
2135
+
2136
+
2137
+ def cmd_workspaces(opts):
2138
+ repo_info = resolve_repo(opts.path)
2139
+ db_path = resolve_db_path(opts, repo_info)
2140
+ just_synced = False
2141
+ if not os.path.exists(db_path):
2142
+ if repo_info is None:
2143
+ raise SystemExit(f"index DB does not exist: {db_path}")
2144
+ conn = connect_db(db_path)
2145
+ try:
2146
+ perform_sync(
2147
+ conn,
2148
+ repo_info,
2149
+ offline=True,
2150
+ no_orca=opts.no_orca,
2151
+ include_foreign_orca=getattr(opts, "use_global", False),
2152
+ fast=opts.fast,
2153
+ )
2154
+ just_synced = True
2155
+ finally:
2156
+ conn.close()
2157
+
2158
+ conn = connect_db(db_path)
2159
+ try:
2160
+ repo_key = None if opts.all_repos else (repo_info["repo_key"] if repo_info else None)
2161
+ if repo_info is not None:
2162
+ exists = conn.execute("SELECT 1 FROM repos WHERE repo_key = ?", (repo_info["repo_key"],)).fetchone()
2163
+ if exists is None and getattr(opts, "db", None):
2164
+ if repo_key == repo_info["repo_key"]:
2165
+ repo_key = None
2166
+ elif exists is None and not just_synced:
2167
+ perform_sync(
2168
+ conn,
2169
+ repo_info,
2170
+ offline=True,
2171
+ no_orca=opts.no_orca,
2172
+ include_foreign_orca=getattr(opts, "use_global", False),
2173
+ fast=opts.fast,
2174
+ )
2175
+ elif exists is not None and not just_synced:
2176
+ sync_workspaces(
2177
+ conn,
2178
+ repo_info,
2179
+ no_orca=opts.no_orca,
2180
+ include_foreign_orca=getattr(opts, "use_global", False),
2181
+ fast=opts.fast,
2182
+ )
2183
+ sync_project_state(conn, repo_info)
2184
+ conn.commit()
2185
+ items = collect_workspaces(conn, repo_key)
2186
+ finally:
2187
+ conn.close()
2188
+
2189
+ if opts.json:
2190
+ print(json.dumps({"count": len(items), "workspaces": items}, indent=2))
2191
+ else:
2192
+ for wt in items:
2193
+ branch = wt["branch"] or f"detached@{wt['head_sha']}"
2194
+ dirty = f"dirty({wt['dirty_count']})" if wt["is_dirty"] else "clean"
2195
+ bits = [f"{wt['path']} [{branch}]", dirty, wt["source"]]
2196
+ if wt["orca_host"]:
2197
+ bits.append(f"host={wt['orca_host']}")
2198
+ if wt["pr"]:
2199
+ pr = wt["pr"]
2200
+ pr_meta = "/".join(x for x in (pr["merge_state"], pr["checks_summary"]) if x)
2201
+ bits.append(f"PR#{pr['number']}" + (f"({pr_meta})" if pr_meta else ""))
2202
+ if wt["project_state"]:
2203
+ bits.append("state:" + ";".join(format_project_state_compact(s) for s in wt["project_state"][:2]))
2204
+ print(" | ".join(bits))
2205
+ if not items:
2206
+ print("no workspaces indexed")
2207
+ return 0
2208
+
2209
+
2210
+ def cmd_prs(opts):
2211
+ repo_info = resolve_repo(opts.path)
2212
+ db_path = resolve_db_path(opts, repo_info)
2213
+ just_synced = False
2214
+ if not os.path.exists(db_path):
2215
+ if repo_info is None:
2216
+ raise SystemExit(f"index DB does not exist: {db_path}")
2217
+ conn = connect_db(db_path)
2218
+ try:
2219
+ perform_sync(
2220
+ conn,
2221
+ repo_info,
2222
+ offline=opts.offline,
2223
+ no_orca=True,
2224
+ force_prs=opts.force_prs,
2225
+ fast=True,
2226
+ )
2227
+ just_synced = True
2228
+ finally:
2229
+ conn.close()
2230
+
2231
+ conn = connect_db(db_path)
2232
+ try:
2233
+ repo_key = None if opts.all_repos else (repo_info["repo_key"] if repo_info else None)
2234
+ if repo_info is not None:
2235
+ exists = conn.execute("SELECT 1 FROM repos WHERE repo_key = ?", (repo_info["repo_key"],)).fetchone()
2236
+ if exists is None and getattr(opts, "db", None):
2237
+ if repo_key == repo_info["repo_key"]:
2238
+ repo_key = None
2239
+ elif exists is None and not just_synced:
2240
+ perform_sync(
2241
+ conn,
2242
+ repo_info,
2243
+ offline=opts.offline,
2244
+ no_orca=True,
2245
+ force_prs=opts.force_prs,
2246
+ fast=True,
2247
+ )
2248
+ elif exists is not None and not opts.offline and not just_synced:
2249
+ sync_prs(conn, repo_info, offline=False, force_prs=opts.force_prs)
2250
+ conn.commit()
2251
+ items = collect_prs(conn, repo_key)
2252
+ finally:
2253
+ conn.close()
2254
+
2255
+ if opts.json:
2256
+ print(json.dumps({"count": len(items), "prs": items}, indent=2))
2257
+ else:
2258
+ for pr in items:
2259
+ draft = "draft " if pr["is_draft"] else ""
2260
+ status_bits = [x for x in (pr["merge_state"], pr["review_decision"], pr["checks_summary"]) if x]
2261
+ status_str = ", ".join(status_bits) if status_bits else pr["state"]
2262
+ wt_str = pr["worktree_path"] or "none"
2263
+ print(
2264
+ f"#{pr['number']} [{draft}{pr['head_branch']}->{pr['base_branch']}] "
2265
+ f"{pr['title']} | {status_str} | wt={wt_str}"
2266
+ )
2267
+ if not items:
2268
+ print("no open PRs indexed")
2269
+ return 0
2270
+
2271
+
2272
+ def cmd_prune(opts):
2273
+ repo_info = resolve_repo(".")
2274
+ db_path = resolve_db_path(opts, repo_info)
2275
+ if not os.path.exists(db_path):
2276
+ payload = {
2277
+ "db_path": display_path(db_path),
2278
+ "dropped_repos": 0,
2279
+ "dropped_workspaces": 0,
2280
+ "dropped_prs": 0,
2281
+ "dropped_states": 0,
2282
+ "before_bytes": 0,
2283
+ "after_bytes": 0,
2284
+ "reclaimed_bytes": 0,
2285
+ }
2286
+ if opts.json:
2287
+ print(json.dumps(payload, indent=2))
2288
+ else:
2289
+ print(f"prune: nothing to prune ({db_path} does not exist)")
2290
+ return 0
2291
+
2292
+ before_bytes = db_disk_bytes(db_path)
2293
+ cutoff = time.time() - (max(0.0, float(opts.days)) * 86400.0)
2294
+ conn = connect_db(db_path)
2295
+ try:
2296
+ drop_repos = []
2297
+ for row in conn.execute("SELECT repo_key, main_checkout, last_sync_ts FROM repos").fetchall():
2298
+ last_ts = float(row["last_sync_ts"] or 0.0)
2299
+ if last_ts <= 0.0:
2300
+ wt_ts = conn.execute(
2301
+ "SELECT MAX(updated_at) FROM workspaces WHERE repo_key = ?",
2302
+ (row["repo_key"],),
2303
+ ).fetchone()[0]
2304
+ last_ts = float(wt_ts or 0.0)
2305
+ stale = (last_ts <= 0.0 and float(opts.days) >= 0.0) or (last_ts > 0.0 and last_ts < cutoff)
2306
+ if not os.path.isdir(row["main_checkout"]) or stale:
2307
+ drop_repos.append(row["repo_key"])
2308
+ if drop_repos:
2309
+ conn.executemany("DELETE FROM repos WHERE repo_key = ?", [(k,) for k in drop_repos])
2310
+
2311
+ drop_wts = []
2312
+ for row in conn.execute("SELECT repo_key, worktree_key, path, updated_at FROM workspaces").fetchall():
2313
+ stale = row["updated_at"] and row["updated_at"] < cutoff
2314
+ if not os.path.isdir(row["path"]) or stale:
2315
+ drop_wts.append((row["repo_key"], row["worktree_key"]))
2316
+ if drop_wts:
2317
+ conn.executemany("DELETE FROM workspaces WHERE worktree_key = ?", [(wk,) for _, wk in drop_wts])
2318
+ conn.executemany(
2319
+ "DELETE FROM files WHERE repo_key = ? AND worktree_key = ?",
2320
+ [(rk, wk) for rk, wk in drop_wts if wk != rk],
2321
+ )
2322
+ conn.executemany(
2323
+ "DELETE FROM worktree_deleted WHERE repo_key = ? AND worktree_key = ?",
2324
+ [(rk, wk) for rk, wk in drop_wts if wk != rk],
2325
+ )
2326
+
2327
+ pr_cur = conn.execute("DELETE FROM prs WHERE synced_at > 0 AND synced_at < ?", (cutoff,))
2328
+ dropped_prs = pr_cur.rowcount
2329
+
2330
+ ps_cur = conn.execute("DELETE FROM project_state WHERE updated_at > 0 AND updated_at < ?", (cutoff,))
2331
+ dropped_states = ps_cur.rowcount
2332
+
2333
+ conn.commit()
2334
+ conn.execute("INSERT INTO symbols_fts(symbols_fts) VALUES('optimize')")
2335
+ conn.commit()
2336
+ conn.execute("PRAGMA wal_checkpoint(TRUNCATE)")
2337
+ conn.execute("VACUUM")
2338
+ finally:
2339
+ conn.close()
2340
+
2341
+ after_bytes = db_disk_bytes(db_path)
2342
+ reclaimed = max(0, before_bytes - after_bytes)
2343
+ payload = {
2344
+ "db_path": display_path(db_path),
2345
+ "dropped_repos": len(drop_repos),
2346
+ "dropped_workspaces": len(drop_wts),
2347
+ "dropped_prs": dropped_prs,
2348
+ "dropped_states": dropped_states,
2349
+ "before_bytes": before_bytes,
2350
+ "after_bytes": after_bytes,
2351
+ "reclaimed_bytes": reclaimed,
2352
+ }
2353
+ if opts.json:
2354
+ print(json.dumps(payload, indent=2))
2355
+ else:
2356
+ print(
2357
+ f"pruned: repos={len(drop_repos)} workspaces={len(drop_wts)} prs={dropped_prs} "
2358
+ f"states={dropped_states} | reclaimed {reclaimed} bytes ({before_bytes} -> {after_bytes})"
2359
+ )
2360
+ return 0
2361
+
2362
+
2363
+ def build_parser():
2364
+ common = argparse.ArgumentParser(add_help=False)
2365
+ common.add_argument("--json", action="store_true", default=argparse.SUPPRESS, help="emit machine-readable JSON")
2366
+ common.add_argument("--db", default=argparse.SUPPRESS, help="explicit SQLite DB path")
2367
+ common.add_argument(
2368
+ "--global", dest="use_global", action="store_true", default=argparse.SUPPRESS,
2369
+ help="use cross-repo global index at ~/.cache/deepmodebot/workspace-map.db",
2370
+ )
2371
+
2372
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
2373
+ parser.add_argument("--json", action="store_true", default=False, help="emit machine-readable JSON")
2374
+ parser.add_argument("--db", default=None, help="explicit SQLite DB path")
2375
+ parser.add_argument(
2376
+ "--global", dest="use_global", action="store_true", default=False,
2377
+ help="use cross-repo global index at ~/.cache/deepmodebot/workspace-map.db",
2378
+ )
2379
+
2380
+ sub = parser.add_subparsers(dest="action", required=True)
2381
+
2382
+ p_sync = sub.add_parser("sync", parents=[common], help="incrementally index files, symbols, worktrees, PRs, state")
2383
+ p_sync.add_argument("path", nargs="?", default=".")
2384
+ p_sync.add_argument("--offline", action="store_true", help="skip gh PR lookup")
2385
+ p_sync.add_argument("--no-orca", action="store_true", help="skip orca worktree lookup")
2386
+ p_sync.add_argument("--force-prs", action="store_true", help="bypass 180s PR TTL cache")
2387
+ p_sync.add_argument("--fast", action="store_true", help="check dirty status on current and main worktrees only")
2388
+
2389
+ p_ov = sub.add_parser("overview", parents=[common], help="auto-sync and print a byte-capped turn-1 orientation")
2390
+ p_ov.add_argument("path", nargs="?", default=".")
2391
+ p_ov.add_argument("--max-bytes", type=int, default=DEFAULT_OVERVIEW_BYTES, help="hard UTF-8 byte cap")
2392
+ p_ov.add_argument("--offline", action="store_true", help="skip gh PR lookup")
2393
+ p_ov.add_argument("--no-orca", action="store_true", help="skip orca worktree lookup")
2394
+ p_ov.add_argument("--fast", action="store_true", help="check dirty status on current and main worktrees only")
2395
+
2396
+ p_q = sub.add_parser("query", parents=[common], help="FTS5 symbol lookup returning rel_path:line kind signature")
2397
+ p_q.add_argument("term", help="search term or prefix (e.g. evaluate_manifest or eval*)")
2398
+ p_q.add_argument("path", nargs="?", default=".")
2399
+ p_q.add_argument("--limit", type=int, default=15, help="max results")
2400
+ p_q.add_argument("--all-repos", action="store_true", help="search across every repo in the DB")
2401
+ p_q.add_argument("--no-sync", action="store_true", help="skip incremental file/symbol refresh before querying")
2402
+
2403
+ p_ws = sub.add_parser("workspaces", parents=[common], help="list worktrees joined with dirty state, PRs, and manifests")
2404
+ p_ws.add_argument("path", nargs="?", default=".")
2405
+ p_ws.add_argument("--all-repos", action="store_true", help="include all repos in the DB")
2406
+ p_ws.add_argument("--no-orca", action="store_true", help="skip orca worktree lookup")
2407
+ p_ws.add_argument("--fast", action="store_true", help="check dirty status on current and main worktrees only")
2408
+
2409
+ p_prs = sub.add_parser("prs", parents=[common], help="list own open PRs joined with local worktrees")
2410
+ p_prs.add_argument("path", nargs="?", default=".")
2411
+ p_prs.add_argument("--all-repos", action="store_true", help="include all repos in the DB")
2412
+ p_prs.add_argument("--offline", action="store_true", help="skip gh PR refresh and read cached rows only")
2413
+ p_prs.add_argument("--force-prs", action="store_true", help="bypass 180s PR TTL cache")
2414
+
2415
+ p_prune = sub.add_parser("prune", parents=[common], help="drop missing repos/worktrees and stale rows, then VACUUM")
2416
+ p_prune.add_argument("--days", type=float, default=DEFAULT_PRUNE_DAYS, help="drop rows older than N days")
2417
+
2418
+ return parser
2419
+
2420
+
2421
+ def main(argv=None):
2422
+ parser = build_parser()
2423
+ opts = parser.parse_args(argv)
2424
+ handlers = {
2425
+ "sync": cmd_sync,
2426
+ "overview": cmd_overview,
2427
+ "query": cmd_query,
2428
+ "workspaces": cmd_workspaces,
2429
+ "prs": cmd_prs,
2430
+ "prune": cmd_prune,
2431
+ }
2432
+ return handlers[opts.action](opts)
2433
+
2434
+
2435
+ if __name__ == "__main__":
2436
+ sys.exit(main())