arboris-cli 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (451) hide show
  1. package/dist/cli.mjs +382 -0
  2. package/manifest.json +323 -0
  3. package/package.json +22 -10
  4. package/prisma/skills/accessibility/SKILL.md +147 -0
  5. package/prisma/skills/agent-architecture-audit/SKILL.md +257 -0
  6. package/prisma/skills/agent-eval/SKILL.md +146 -0
  7. package/prisma/skills/agent-harness-construction/SKILL.md +74 -0
  8. package/prisma/skills/agent-introspection-debugging/SKILL.md +154 -0
  9. package/prisma/skills/agent-payment-x402/SKILL.md +225 -0
  10. package/prisma/skills/agent-self-evaluation/SKILL.md +182 -0
  11. package/prisma/skills/agent-self-evaluation/examples/high-score-example.md +87 -0
  12. package/prisma/skills/agent-self-evaluation/examples/low-score-example.md +86 -0
  13. package/prisma/skills/agent-self-evaluation/references/evaluation-criteria.md +71 -0
  14. package/prisma/skills/agent-self-evaluation/references/hook-integration.md +64 -0
  15. package/prisma/skills/agent-self-evaluation/scripts/evaluate.py +408 -0
  16. package/prisma/skills/agent-self-evaluation/templates/evaluation-report.md +86 -0
  17. package/prisma/skills/agent-sort/SKILL.md +216 -0
  18. package/prisma/skills/agentic-engineering/SKILL.md +64 -0
  19. package/prisma/skills/agentic-os/SKILL.md +388 -0
  20. package/prisma/skills/ai-first-engineering/SKILL.md +52 -0
  21. package/prisma/skills/ai-regression-testing/SKILL.md +386 -0
  22. package/prisma/skills/android-clean-architecture/SKILL.md +340 -0
  23. package/prisma/skills/angular-developer/SKILL.md +155 -0
  24. package/prisma/skills/angular-developer/references/angular-animations.md +160 -0
  25. package/prisma/skills/angular-developer/references/angular-aria.md +410 -0
  26. package/prisma/skills/angular-developer/references/cli.md +86 -0
  27. package/prisma/skills/angular-developer/references/component-harnesses.md +59 -0
  28. package/prisma/skills/angular-developer/references/component-styling.md +91 -0
  29. package/prisma/skills/angular-developer/references/components.md +117 -0
  30. package/prisma/skills/angular-developer/references/creating-services.md +97 -0
  31. package/prisma/skills/angular-developer/references/data-resolvers.md +69 -0
  32. package/prisma/skills/angular-developer/references/define-routes.md +67 -0
  33. package/prisma/skills/angular-developer/references/defining-providers.md +72 -0
  34. package/prisma/skills/angular-developer/references/di-fundamentals.md +120 -0
  35. package/prisma/skills/angular-developer/references/e2e-testing.md +56 -0
  36. package/prisma/skills/angular-developer/references/effects.md +83 -0
  37. package/prisma/skills/angular-developer/references/hierarchical-injectors.md +43 -0
  38. package/prisma/skills/angular-developer/references/host-elements.md +80 -0
  39. package/prisma/skills/angular-developer/references/injection-context.md +63 -0
  40. package/prisma/skills/angular-developer/references/inputs.md +101 -0
  41. package/prisma/skills/angular-developer/references/linked-signal.md +59 -0
  42. package/prisma/skills/angular-developer/references/loading-strategies.md +61 -0
  43. package/prisma/skills/angular-developer/references/mcp.md +108 -0
  44. package/prisma/skills/angular-developer/references/navigate-to-routes.md +69 -0
  45. package/prisma/skills/angular-developer/references/outputs.md +86 -0
  46. package/prisma/skills/angular-developer/references/reactive-forms.md +122 -0
  47. package/prisma/skills/angular-developer/references/rendering-strategies.md +44 -0
  48. package/prisma/skills/angular-developer/references/resource.md +77 -0
  49. package/prisma/skills/angular-developer/references/route-animations.md +56 -0
  50. package/prisma/skills/angular-developer/references/route-guards.md +52 -0
  51. package/prisma/skills/angular-developer/references/router-lifecycle.md +45 -0
  52. package/prisma/skills/angular-developer/references/router-testing.md +87 -0
  53. package/prisma/skills/angular-developer/references/show-routes-with-outlets.md +68 -0
  54. package/prisma/skills/angular-developer/references/signal-forms.md +795 -0
  55. package/prisma/skills/angular-developer/references/signals-overview.md +94 -0
  56. package/prisma/skills/angular-developer/references/tailwind-css.md +69 -0
  57. package/prisma/skills/angular-developer/references/template-driven-forms.md +114 -0
  58. package/prisma/skills/angular-developer/references/testing-fundamentals.md +65 -0
  59. package/prisma/skills/api-connector-builder/SKILL.md +121 -0
  60. package/prisma/skills/api-design/SKILL.md +524 -0
  61. package/prisma/skills/architecture-decision-records/SKILL.md +180 -0
  62. package/prisma/skills/article-writing/SKILL.md +80 -0
  63. package/prisma/skills/automation-audit-ops/SKILL.md +143 -0
  64. package/prisma/skills/autonomous-agent-harness/SKILL.md +274 -0
  65. package/prisma/skills/autonomous-loops/SKILL.md +611 -0
  66. package/prisma/skills/backend-patterns/SKILL.md +562 -0
  67. package/prisma/skills/benchmark/SKILL.md +94 -0
  68. package/prisma/skills/benchmark-methodology/SKILL.md +190 -0
  69. package/prisma/skills/benchmark-optimization-loop/SKILL.md +70 -0
  70. package/prisma/skills/blender-motion-state-inspection/SKILL.md +165 -0
  71. package/prisma/skills/blueprint/SKILL.md +106 -0
  72. package/prisma/skills/brand-discovery/SKILL.md +145 -0
  73. package/prisma/skills/brand-discovery/references/10_purpose-why.md +40 -0
  74. package/prisma/skills/brand-discovery/references/20_positioning.md +44 -0
  75. package/prisma/skills/brand-discovery/references/30_audience-niche.md +52 -0
  76. package/prisma/skills/brand-discovery/references/40_personality-archetype.md +57 -0
  77. package/prisma/skills/brand-discovery/references/50_voice-tone.md +59 -0
  78. package/prisma/skills/brand-discovery/references/60_narrative-story.md +50 -0
  79. package/prisma/skills/brand-discovery/references/70_founder-tension.md +49 -0
  80. package/prisma/skills/brand-discovery/references/90_SYNTHESIS.md +133 -0
  81. package/prisma/skills/brand-voice/SKILL.md +98 -0
  82. package/prisma/skills/brand-voice/references/voice-profile-schema.md +55 -0
  83. package/prisma/skills/browser-qa/SKILL.md +105 -0
  84. package/prisma/skills/bun-runtime/SKILL.md +85 -0
  85. package/prisma/skills/canary-watch/SKILL.md +108 -0
  86. package/prisma/skills/carrier-relationship-management/SKILL.md +212 -0
  87. package/prisma/skills/cisco-ios-patterns/SKILL.md +164 -0
  88. package/prisma/skills/ck/SKILL.md +148 -0
  89. package/prisma/skills/ck/commands/forget.mjs +44 -0
  90. package/prisma/skills/ck/commands/info.mjs +24 -0
  91. package/prisma/skills/ck/commands/init.mjs +143 -0
  92. package/prisma/skills/ck/commands/list.mjs +40 -0
  93. package/prisma/skills/ck/commands/migrate.mjs +202 -0
  94. package/prisma/skills/ck/commands/resume.mjs +36 -0
  95. package/prisma/skills/ck/commands/save.mjs +210 -0
  96. package/prisma/skills/ck/commands/shared.mjs +387 -0
  97. package/prisma/skills/ck/hooks/session-start.mjs +224 -0
  98. package/prisma/skills/claude-devfleet/SKILL.md +112 -0
  99. package/prisma/skills/click-path-audit/SKILL.md +245 -0
  100. package/prisma/skills/clickhouse-io/SKILL.md +440 -0
  101. package/prisma/skills/code-tour/SKILL.md +254 -0
  102. package/prisma/skills/codebase-onboarding/SKILL.md +234 -0
  103. package/prisma/skills/codehealth-mcp/SKILL.md +167 -0
  104. package/prisma/skills/coding-standards/SKILL.md +551 -0
  105. package/prisma/skills/competitive-platform-analysis/SKILL.md +214 -0
  106. package/prisma/skills/competitive-report-structure/SKILL.md +162 -0
  107. package/prisma/skills/compose-multiplatform-patterns/SKILL.md +300 -0
  108. package/prisma/skills/config-gc/SKILL.md +120 -0
  109. package/prisma/skills/configure-ecc/SKILL.md +385 -0
  110. package/prisma/skills/connections-optimizer/SKILL.md +190 -0
  111. package/prisma/skills/content-engine/SKILL.md +132 -0
  112. package/prisma/skills/content-hash-cache-pattern/SKILL.md +162 -0
  113. package/prisma/skills/context-budget/SKILL.md +136 -0
  114. package/prisma/skills/continuous-agent-loop/SKILL.md +46 -0
  115. package/prisma/skills/continuous-learning/SKILL.md +132 -0
  116. package/prisma/skills/continuous-learning/config.json +18 -0
  117. package/prisma/skills/continuous-learning/evaluate-session.sh +69 -0
  118. package/prisma/skills/continuous-learning-v2/SKILL.md +361 -0
  119. package/prisma/skills/continuous-learning-v2/agents/observer-loop.sh +359 -0
  120. package/prisma/skills/continuous-learning-v2/agents/observer.md +189 -0
  121. package/prisma/skills/continuous-learning-v2/agents/session-guardian.sh +150 -0
  122. package/prisma/skills/continuous-learning-v2/agents/start-observer.sh +248 -0
  123. package/prisma/skills/continuous-learning-v2/config.json +8 -0
  124. package/prisma/skills/continuous-learning-v2/hooks/observe.sh +585 -0
  125. package/prisma/skills/continuous-learning-v2/scripts/detect-project.sh +322 -0
  126. package/prisma/skills/continuous-learning-v2/scripts/instinct-cli.py +1956 -0
  127. package/prisma/skills/continuous-learning-v2/scripts/lib/homunculus-dir.sh +31 -0
  128. package/prisma/skills/continuous-learning-v2/scripts/migrate-homunculus.sh +68 -0
  129. package/prisma/skills/continuous-learning-v2/scripts/test_parse_instinct.py +1421 -0
  130. package/prisma/skills/cost-aware-llm-pipeline/SKILL.md +184 -0
  131. package/prisma/skills/cost-tracking/SKILL.md +97 -0
  132. package/prisma/skills/council/SKILL.md +204 -0
  133. package/prisma/skills/cpp-coding-standards/SKILL.md +724 -0
  134. package/prisma/skills/cpp-testing/SKILL.md +325 -0
  135. package/prisma/skills/crosspost/SKILL.md +112 -0
  136. package/prisma/skills/csharp-testing/SKILL.md +322 -0
  137. package/prisma/skills/customer-billing-ops/SKILL.md +141 -0
  138. package/prisma/skills/customs-trade-compliance/SKILL.md +263 -0
  139. package/prisma/skills/dart-flutter-patterns/SKILL.md +564 -0
  140. package/prisma/skills/dashboard-builder/SKILL.md +109 -0
  141. package/prisma/skills/data-scraper-agent/SKILL.md +765 -0
  142. package/prisma/skills/data-throughput-accelerator/SKILL.md +73 -0
  143. package/prisma/skills/database-migrations/SKILL.md +430 -0
  144. package/prisma/skills/deep-research/SKILL.md +160 -0
  145. package/prisma/skills/defi-amm-security/SKILL.md +167 -0
  146. package/prisma/skills/delivery-gate/SKILL.md +126 -0
  147. package/prisma/skills/delivery-gate/hooks/quality-gate.py +220 -0
  148. package/prisma/skills/deployment-patterns/SKILL.md +428 -0
  149. package/prisma/skills/design-system/SKILL.md +83 -0
  150. package/prisma/skills/django-celery/SKILL.md +458 -0
  151. package/prisma/skills/django-patterns/SKILL.md +735 -0
  152. package/prisma/skills/django-security/SKILL.md +644 -0
  153. package/prisma/skills/django-tdd/SKILL.md +730 -0
  154. package/prisma/skills/django-verification/SKILL.md +470 -0
  155. package/prisma/skills/dmux-workflows/SKILL.md +192 -0
  156. package/prisma/skills/docker-patterns/SKILL.md +365 -0
  157. package/prisma/skills/documentation-lookup/SKILL.md +91 -0
  158. package/prisma/skills/dotnet-patterns/SKILL.md +322 -0
  159. package/prisma/skills/dynamic-workflow-mode/SKILL.md +124 -0
  160. package/prisma/skills/e2e-testing/SKILL.md +327 -0
  161. package/prisma/skills/ecc-guide/SKILL.md +190 -0
  162. package/prisma/skills/ecc-recipes/SKILL.md +149 -0
  163. package/prisma/skills/ecc-tools-cost-audit/SKILL.md +161 -0
  164. package/prisma/skills/email-ops/SKILL.md +122 -0
  165. package/prisma/skills/energy-procurement/SKILL.md +228 -0
  166. package/prisma/skills/enterprise-agent-ops/SKILL.md +51 -0
  167. package/prisma/skills/error-handling/SKILL.md +377 -0
  168. package/prisma/skills/eval-harness/SKILL.md +271 -0
  169. package/prisma/skills/evm-token-decimals/SKILL.md +131 -0
  170. package/prisma/skills/exa-search/SKILL.md +108 -0
  171. package/prisma/skills/fal-ai-media/SKILL.md +289 -0
  172. package/prisma/skills/fastapi-patterns/SKILL.md +514 -0
  173. package/prisma/skills/finance-billing-ops/SKILL.md +128 -0
  174. package/prisma/skills/flox-environments/SKILL.md +497 -0
  175. package/prisma/skills/flutter-dart-code-review/SKILL.md +436 -0
  176. package/prisma/skills/foundation-models-on-device/SKILL.md +243 -0
  177. package/prisma/skills/frontend-a11y/SKILL.md +446 -0
  178. package/prisma/skills/frontend-design-direction/SKILL.md +93 -0
  179. package/prisma/skills/frontend-patterns/SKILL.md +657 -0
  180. package/prisma/skills/frontend-slides/SKILL.md +185 -0
  181. package/prisma/skills/frontend-slides/STYLE_PRESETS.md +330 -0
  182. package/prisma/skills/frontend-slides/animation-patterns.md +122 -0
  183. package/prisma/skills/frontend-slides/html-template.md +419 -0
  184. package/prisma/skills/frontend-slides/scripts/export-pdf.sh +418 -0
  185. package/prisma/skills/frontend-slides/scripts/extract-pptx.py +96 -0
  186. package/prisma/skills/frontend-slides/viewport-base.css +153 -0
  187. package/prisma/skills/fsharp-testing/SKILL.md +281 -0
  188. package/prisma/skills/gan-style-harness/SKILL.md +279 -0
  189. package/prisma/skills/gateguard/SKILL.md +133 -0
  190. package/prisma/skills/generating-python-installer/SKILL.md +820 -0
  191. package/prisma/skills/git-workflow/SKILL.md +716 -0
  192. package/prisma/skills/github-ops/SKILL.md +145 -0
  193. package/prisma/skills/golang-patterns/SKILL.md +675 -0
  194. package/prisma/skills/golang-testing/SKILL.md +721 -0
  195. package/prisma/skills/google-workspace-ops/SKILL.md +96 -0
  196. package/prisma/skills/growth-log/SKILL.md +128 -0
  197. package/prisma/skills/healthcare-cdss-patterns/SKILL.md +246 -0
  198. package/prisma/skills/healthcare-emr-patterns/SKILL.md +160 -0
  199. package/prisma/skills/healthcare-eval-harness/SKILL.md +208 -0
  200. package/prisma/skills/healthcare-phi-compliance/SKILL.md +146 -0
  201. package/prisma/skills/hermes-imports/SKILL.md +89 -0
  202. package/prisma/skills/hexagonal-architecture/SKILL.md +277 -0
  203. package/prisma/skills/hipaa-compliance/SKILL.md +79 -0
  204. package/prisma/skills/homelab-network-readiness/SKILL.md +170 -0
  205. package/prisma/skills/homelab-network-setup/SKILL.md +130 -0
  206. package/prisma/skills/homelab-pihole-dns/SKILL.md +275 -0
  207. package/prisma/skills/homelab-vlan-segmentation/SKILL.md +312 -0
  208. package/prisma/skills/homelab-wireguard-vpn/SKILL.md +306 -0
  209. package/prisma/skills/hookify-rules/SKILL.md +128 -0
  210. package/prisma/skills/inherit-legacy-style/SKILL.md +157 -0
  211. package/prisma/skills/intent-driven-development/SKILL.md +360 -0
  212. package/prisma/skills/inventory-demand-planning/SKILL.md +247 -0
  213. package/prisma/skills/investor-materials/SKILL.md +97 -0
  214. package/prisma/skills/investor-outreach/SKILL.md +92 -0
  215. package/prisma/skills/ios-icon-gen/SKILL.md +158 -0
  216. package/prisma/skills/ios-icon-gen/scripts/generate_icons.swift +258 -0
  217. package/prisma/skills/ios-icon-gen/scripts/iconify_gen.sh +235 -0
  218. package/prisma/skills/iterative-retrieval/SKILL.md +212 -0
  219. package/prisma/skills/ito-basket-compare/SKILL.md +64 -0
  220. package/prisma/skills/ito-data-atlas-agent/SKILL.md +64 -0
  221. package/prisma/skills/ito-market-intelligence/SKILL.md +61 -0
  222. package/prisma/skills/ito-trade-planner/SKILL.md +68 -0
  223. package/prisma/skills/java-coding-standards/SKILL.md +384 -0
  224. package/prisma/skills/jira-integration/SKILL.md +303 -0
  225. package/prisma/skills/jpa-patterns/SKILL.md +152 -0
  226. package/prisma/skills/knowledge-ops/SKILL.md +155 -0
  227. package/prisma/skills/kotlin-coroutines-flows/SKILL.md +285 -0
  228. package/prisma/skills/kotlin-exposed-patterns/SKILL.md +720 -0
  229. package/prisma/skills/kotlin-ktor-patterns/SKILL.md +690 -0
  230. package/prisma/skills/kotlin-patterns/SKILL.md +712 -0
  231. package/prisma/skills/kotlin-testing/SKILL.md +825 -0
  232. package/prisma/skills/kubernetes-patterns/SKILL.md +756 -0
  233. package/prisma/skills/laravel-patterns/SKILL.md +416 -0
  234. package/prisma/skills/laravel-plugin-discovery/SKILL.md +230 -0
  235. package/prisma/skills/laravel-security/SKILL.md +948 -0
  236. package/prisma/skills/laravel-tdd/SKILL.md +675 -0
  237. package/prisma/skills/laravel-verification/SKILL.md +180 -0
  238. package/prisma/skills/latency-critical-systems/SKILL.md +74 -0
  239. package/prisma/skills/lead-intelligence/SKILL.md +322 -0
  240. package/prisma/skills/lead-intelligence/agents/enrichment-agent.md +85 -0
  241. package/prisma/skills/lead-intelligence/agents/mutual-mapper.md +75 -0
  242. package/prisma/skills/lead-intelligence/agents/outreach-drafter.md +98 -0
  243. package/prisma/skills/lead-intelligence/agents/signal-scorer.md +60 -0
  244. package/prisma/skills/liquid-glass-design/SKILL.md +279 -0
  245. package/prisma/skills/llm-trading-agent-security/SKILL.md +147 -0
  246. package/prisma/skills/logistics-exception-management/SKILL.md +222 -0
  247. package/prisma/skills/loop-design-check/SKILL.md +143 -0
  248. package/prisma/skills/mailtrap-email-integration/SKILL.md +77 -0
  249. package/prisma/skills/make-interfaces-feel-better/SKILL.md +152 -0
  250. package/prisma/skills/manim-video/SKILL.md +90 -0
  251. package/prisma/skills/manim-video/assets/network_graph_scene.py +52 -0
  252. package/prisma/skills/market-research/SKILL.md +76 -0
  253. package/prisma/skills/marketing-campaign/SKILL.md +114 -0
  254. package/prisma/skills/mcp-server-patterns/SKILL.md +70 -0
  255. package/prisma/skills/messages-ops/SKILL.md +105 -0
  256. package/prisma/skills/ml-adoption-playbook/SKILL.md +57 -0
  257. package/prisma/skills/mle-workflow/SKILL.md +347 -0
  258. package/prisma/skills/motion-advanced/SKILL.md +596 -0
  259. package/prisma/skills/motion-foundations/SKILL.md +299 -0
  260. package/prisma/skills/motion-patterns/SKILL.md +434 -0
  261. package/prisma/skills/motion-ui/SKILL.md +576 -0
  262. package/prisma/skills/mysql-patterns/SKILL.md +413 -0
  263. package/prisma/skills/nanoclaw-repl/SKILL.md +34 -0
  264. package/prisma/skills/nestjs-patterns/SKILL.md +231 -0
  265. package/prisma/skills/netmiko-ssh-automation/SKILL.md +174 -0
  266. package/prisma/skills/network-bgp-diagnostics/SKILL.md +168 -0
  267. package/prisma/skills/network-config-validation/SKILL.md +211 -0
  268. package/prisma/skills/network-interface-health/SKILL.md +153 -0
  269. package/prisma/skills/nextjs-turbopack/SKILL.md +58 -0
  270. package/prisma/skills/nodejs-keccak256/SKILL.md +103 -0
  271. package/prisma/skills/nutrient-document-processing/SKILL.md +168 -0
  272. package/prisma/skills/nuxt4-patterns/SKILL.md +101 -0
  273. package/prisma/skills/openclaw-persona-forge/SKILL.md +289 -0
  274. package/prisma/skills/openclaw-persona-forge/gacha.py +224 -0
  275. package/prisma/skills/openclaw-persona-forge/gacha.sh +5 -0
  276. package/prisma/skills/openclaw-persona-forge/references/avatar-style.md +124 -0
  277. package/prisma/skills/openclaw-persona-forge/references/boundary-rules.md +53 -0
  278. package/prisma/skills/openclaw-persona-forge/references/error-handling.md +53 -0
  279. package/prisma/skills/openclaw-persona-forge/references/identity-tension.md +48 -0
  280. package/prisma/skills/openclaw-persona-forge/references/naming-system.md +39 -0
  281. package/prisma/skills/openclaw-persona-forge/references/output-template.md +166 -0
  282. package/prisma/skills/opensource-pipeline/SKILL.md +256 -0
  283. package/prisma/skills/orch-add-feature/SKILL.md +45 -0
  284. package/prisma/skills/orch-build-mvp/SKILL.md +49 -0
  285. package/prisma/skills/orch-change-feature/SKILL.md +43 -0
  286. package/prisma/skills/orch-fix-defect/SKILL.md +43 -0
  287. package/prisma/skills/orch-pipeline/SKILL.md +121 -0
  288. package/prisma/skills/orch-refine-code/SKILL.md +44 -0
  289. package/prisma/skills/parallel-execution-optimizer/SKILL.md +73 -0
  290. package/prisma/skills/perl-patterns/SKILL.md +505 -0
  291. package/prisma/skills/perl-security/SKILL.md +504 -0
  292. package/prisma/skills/perl-testing/SKILL.md +476 -0
  293. package/prisma/skills/plan-orchestrate/SKILL.md +263 -0
  294. package/prisma/skills/plankton-code-quality/SKILL.md +237 -0
  295. package/prisma/skills/postgres-patterns/SKILL.md +148 -0
  296. package/prisma/skills/prediction-market-oracle-research/SKILL.md +64 -0
  297. package/prisma/skills/prediction-market-risk-review/SKILL.md +61 -0
  298. package/prisma/skills/prisma-patterns/SKILL.md +401 -0
  299. package/prisma/skills/product-capability/SKILL.md +142 -0
  300. package/prisma/skills/product-lens/SKILL.md +93 -0
  301. package/prisma/skills/production-audit/SKILL.md +207 -0
  302. package/prisma/skills/production-scheduling/SKILL.md +238 -0
  303. package/prisma/skills/project-flow-ops/SKILL.md +112 -0
  304. package/prisma/skills/prompt-optimizer/SKILL.md +398 -0
  305. package/prisma/skills/python-patterns/SKILL.md +751 -0
  306. package/prisma/skills/python-testing/SKILL.md +817 -0
  307. package/prisma/skills/pytorch-patterns/SKILL.md +397 -0
  308. package/prisma/skills/quality-nonconformance/SKILL.md +260 -0
  309. package/prisma/skills/quarkus-patterns/SKILL.md +723 -0
  310. package/prisma/skills/quarkus-security/SKILL.md +468 -0
  311. package/prisma/skills/quarkus-tdd/SKILL.md +812 -0
  312. package/prisma/skills/quarkus-verification/SKILL.md +480 -0
  313. package/prisma/skills/ralphinho-rfc-pipeline/SKILL.md +68 -0
  314. package/prisma/skills/react-native-patterns/SKILL.md +326 -0
  315. package/prisma/skills/react-patterns/SKILL.md +342 -0
  316. package/prisma/skills/react-performance/SKILL.md +575 -0
  317. package/prisma/skills/react-testing/SKILL.md +424 -0
  318. package/prisma/skills/recsys-pipeline-architect/SKILL.md +115 -0
  319. package/prisma/skills/recursive-decision-ledger/SKILL.md +80 -0
  320. package/prisma/skills/redis-patterns/SKILL.md +404 -0
  321. package/prisma/skills/regex-vs-llm-structured-text/SKILL.md +221 -0
  322. package/prisma/skills/remotion-video-creation/SKILL.md +43 -0
  323. package/prisma/skills/remotion-video-creation/rules/3d.md +86 -0
  324. package/prisma/skills/remotion-video-creation/rules/animations.md +29 -0
  325. package/prisma/skills/remotion-video-creation/rules/assets/charts-bar-chart.tsx +173 -0
  326. package/prisma/skills/remotion-video-creation/rules/assets/text-animations-typewriter.tsx +100 -0
  327. package/prisma/skills/remotion-video-creation/rules/assets/text-animations-word-highlight.tsx +108 -0
  328. package/prisma/skills/remotion-video-creation/rules/assets.md +78 -0
  329. package/prisma/skills/remotion-video-creation/rules/audio.md +172 -0
  330. package/prisma/skills/remotion-video-creation/rules/calculate-metadata.md +104 -0
  331. package/prisma/skills/remotion-video-creation/rules/can-decode.md +75 -0
  332. package/prisma/skills/remotion-video-creation/rules/charts.md +58 -0
  333. package/prisma/skills/remotion-video-creation/rules/compositions.md +146 -0
  334. package/prisma/skills/remotion-video-creation/rules/display-captions.md +126 -0
  335. package/prisma/skills/remotion-video-creation/rules/extract-frames.md +229 -0
  336. package/prisma/skills/remotion-video-creation/rules/fonts.md +152 -0
  337. package/prisma/skills/remotion-video-creation/rules/get-audio-duration.md +58 -0
  338. package/prisma/skills/remotion-video-creation/rules/get-video-dimensions.md +68 -0
  339. package/prisma/skills/remotion-video-creation/rules/get-video-duration.md +58 -0
  340. package/prisma/skills/remotion-video-creation/rules/gifs.md +138 -0
  341. package/prisma/skills/remotion-video-creation/rules/images.md +130 -0
  342. package/prisma/skills/remotion-video-creation/rules/import-srt-captions.md +67 -0
  343. package/prisma/skills/remotion-video-creation/rules/lottie.md +67 -0
  344. package/prisma/skills/remotion-video-creation/rules/measuring-dom-nodes.md +34 -0
  345. package/prisma/skills/remotion-video-creation/rules/measuring-text.md +143 -0
  346. package/prisma/skills/remotion-video-creation/rules/sequencing.md +106 -0
  347. package/prisma/skills/remotion-video-creation/rules/tailwind.md +11 -0
  348. package/prisma/skills/remotion-video-creation/rules/text-animations.md +20 -0
  349. package/prisma/skills/remotion-video-creation/rules/timing.md +179 -0
  350. package/prisma/skills/remotion-video-creation/rules/transcribe-captions.md +19 -0
  351. package/prisma/skills/remotion-video-creation/rules/transitions.md +122 -0
  352. package/prisma/skills/remotion-video-creation/rules/trimming.md +52 -0
  353. package/prisma/skills/remotion-video-creation/rules/videos.md +171 -0
  354. package/prisma/skills/repo-scan/SKILL.md +79 -0
  355. package/prisma/skills/research-ops/SKILL.md +113 -0
  356. package/prisma/skills/returns-reverse-logistics/SKILL.md +240 -0
  357. package/prisma/skills/rules-distill/SKILL.md +265 -0
  358. package/prisma/skills/rules-distill/scripts/scan-rules.sh +58 -0
  359. package/prisma/skills/rules-distill/scripts/scan-skills.sh +129 -0
  360. package/prisma/skills/rust-patterns/SKILL.md +500 -0
  361. package/prisma/skills/rust-testing/SKILL.md +501 -0
  362. package/prisma/skills/safety-guard/SKILL.md +76 -0
  363. package/prisma/skills/santa-method/SKILL.md +307 -0
  364. package/prisma/skills/scientific-db-pubmed-database/SKILL.md +176 -0
  365. package/prisma/skills/scientific-db-uspto-database/SKILL.md +178 -0
  366. package/prisma/skills/scientific-pkg-gget/SKILL.md +167 -0
  367. package/prisma/skills/scientific-thinking-literature-review/SKILL.md +193 -0
  368. package/prisma/skills/scientific-thinking-scholar-evaluation/SKILL.md +161 -0
  369. package/prisma/skills/search-first/SKILL.md +183 -0
  370. package/prisma/skills/security-bounty-hunter/SKILL.md +100 -0
  371. package/prisma/skills/security-review/SKILL.md +504 -0
  372. package/prisma/skills/security-review/cloud-infrastructure-security.md +361 -0
  373. package/prisma/skills/security-scan/SKILL.md +166 -0
  374. package/prisma/skills/seo/SKILL.md +155 -0
  375. package/prisma/skills/skill-comply/SKILL.md +59 -0
  376. package/prisma/skills/skill-comply/fixtures/compliant_trace.jsonl +5 -0
  377. package/prisma/skills/skill-comply/fixtures/noncompliant_trace.jsonl +3 -0
  378. package/prisma/skills/skill-comply/fixtures/tdd_spec.yaml +44 -0
  379. package/prisma/skills/skill-comply/prompts/classifier.md +24 -0
  380. package/prisma/skills/skill-comply/prompts/scenario_generator.md +62 -0
  381. package/prisma/skills/skill-comply/prompts/spec_generator.md +42 -0
  382. package/prisma/skills/skill-comply/pyproject.toml +15 -0
  383. package/prisma/skills/skill-comply/scripts/__init__.py +0 -0
  384. package/prisma/skills/skill-comply/scripts/classifier.py +85 -0
  385. package/prisma/skills/skill-comply/scripts/grader.py +124 -0
  386. package/prisma/skills/skill-comply/scripts/parser.py +107 -0
  387. package/prisma/skills/skill-comply/scripts/report.py +170 -0
  388. package/prisma/skills/skill-comply/scripts/run.py +127 -0
  389. package/prisma/skills/skill-comply/scripts/runner.py +194 -0
  390. package/prisma/skills/skill-comply/scripts/scenario_generator.py +70 -0
  391. package/prisma/skills/skill-comply/scripts/spec_generator.py +72 -0
  392. package/prisma/skills/skill-comply/scripts/utils.py +13 -0
  393. package/prisma/skills/skill-comply/tests/test_grader.py +197 -0
  394. package/prisma/skills/skill-comply/tests/test_parser.py +90 -0
  395. package/prisma/skills/skill-comply/tests/test_runner.py +172 -0
  396. package/prisma/skills/skill-scout/SKILL.md +141 -0
  397. package/prisma/skills/skill-stocktake/SKILL.md +195 -0
  398. package/prisma/skills/skill-stocktake/scripts/quick-diff.sh +87 -0
  399. package/prisma/skills/skill-stocktake/scripts/save-results.sh +56 -0
  400. package/prisma/skills/skill-stocktake/scripts/scan.sh +170 -0
  401. package/prisma/skills/social-graph-ranker/SKILL.md +155 -0
  402. package/prisma/skills/social-publisher/SKILL.md +130 -0
  403. package/prisma/skills/springboot-patterns/SKILL.md +315 -0
  404. package/prisma/skills/springboot-security/SKILL.md +273 -0
  405. package/prisma/skills/springboot-tdd/SKILL.md +159 -0
  406. package/prisma/skills/springboot-verification/SKILL.md +232 -0
  407. package/prisma/skills/strategic-compact/SKILL.md +136 -0
  408. package/prisma/skills/swift-actor-persistence/SKILL.md +144 -0
  409. package/prisma/skills/swift-concurrency-6-2/SKILL.md +216 -0
  410. package/prisma/skills/swift-protocol-di-testing/SKILL.md +191 -0
  411. package/prisma/skills/swiftui-patterns/SKILL.md +259 -0
  412. package/prisma/skills/taste/SKILL.md +264 -0
  413. package/prisma/skills/taste/references/genre-taxonomy.md +87 -0
  414. package/prisma/skills/tdd-workflow/SKILL.md +583 -0
  415. package/prisma/skills/team-agent-orchestration/SKILL.md +111 -0
  416. package/prisma/skills/team-builder/SKILL.md +169 -0
  417. package/prisma/skills/terminal-ops/SKILL.md +110 -0
  418. package/prisma/skills/tinystruct-patterns/SKILL.md +279 -0
  419. package/prisma/skills/tinystruct-patterns/references/architecture.md +90 -0
  420. package/prisma/skills/tinystruct-patterns/references/data-handling.md +60 -0
  421. package/prisma/skills/tinystruct-patterns/references/database.md +99 -0
  422. package/prisma/skills/tinystruct-patterns/references/routing.md +64 -0
  423. package/prisma/skills/tinystruct-patterns/references/system-usage.md +97 -0
  424. package/prisma/skills/tinystruct-patterns/references/testing.md +72 -0
  425. package/prisma/skills/token-budget-advisor/SKILL.md +134 -0
  426. package/prisma/skills/ui-demo/SKILL.md +466 -0
  427. package/prisma/skills/ui-to-vue/SKILL.md +135 -0
  428. package/prisma/skills/uncloud/SKILL.md +344 -0
  429. package/prisma/skills/unified-notifications-ops/SKILL.md +188 -0
  430. package/prisma/skills/verification-loop/SKILL.md +127 -0
  431. package/prisma/skills/video-editing/SKILL.md +311 -0
  432. package/prisma/skills/videodb/SKILL.md +375 -0
  433. package/prisma/skills/videodb/reference/api-reference.md +550 -0
  434. package/prisma/skills/videodb/reference/capture-reference.md +407 -0
  435. package/prisma/skills/videodb/reference/capture.md +101 -0
  436. package/prisma/skills/videodb/reference/editor.md +443 -0
  437. package/prisma/skills/videodb/reference/generative.md +331 -0
  438. package/prisma/skills/videodb/reference/rtstream-reference.md +564 -0
  439. package/prisma/skills/videodb/reference/rtstream.md +65 -0
  440. package/prisma/skills/videodb/reference/search.md +230 -0
  441. package/prisma/skills/videodb/reference/streaming.md +406 -0
  442. package/prisma/skills/videodb/reference/use-cases.md +118 -0
  443. package/prisma/skills/videodb/scripts/ws_listener.py +282 -0
  444. package/prisma/skills/visa-doc-translate/README.md +86 -0
  445. package/prisma/skills/visa-doc-translate/SKILL.md +117 -0
  446. package/prisma/skills/vite-patterns/SKILL.md +450 -0
  447. package/prisma/skills/vue-patterns/SKILL.md +471 -0
  448. package/prisma/skills/windows-desktop-e2e/SKILL.md +888 -0
  449. package/prisma/skills/workspace-surface-audit/SKILL.md +126 -0
  450. package/prisma/skills/x-api/SKILL.md +235 -0
  451. package/run.mjs +0 -10
@@ -0,0 +1,1956 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Instinct CLI - Manage instincts for Continuous Learning v2
4
+
5
+ v2.1: Project-scoped instincts — different projects get different instincts,
6
+ with global instincts applied universally.
7
+
8
+ Commands:
9
+ status - Show all instincts (project + global) and their status
10
+ import - Import instincts from file or URL
11
+ export - Export instincts to file
12
+ evolve - Cluster instincts into skills/commands/agents
13
+ promote - Promote project instincts to global scope
14
+ projects - List all known projects and their instinct counts
15
+ prune - Delete pending instincts older than 30 days (TTL)
16
+ """
17
+
18
+ import argparse
19
+ import json
20
+ import hashlib
21
+ import os
22
+ import subprocess
23
+ import sys
24
+ import re
25
+ import shutil
26
+ import ipaddress
27
+ import socket
28
+ import urllib.parse
29
+ import urllib.request
30
+ from contextlib import contextmanager
31
+ from pathlib import Path
32
+ from datetime import datetime, timedelta, timezone
33
+ from collections import defaultdict
34
+ from typing import Optional
35
+
36
+ if sys.platform == "win32":
37
+ try:
38
+ sys.stdout.reconfigure(encoding="utf-8")
39
+ sys.stderr.reconfigure(encoding="utf-8")
40
+ except Exception:
41
+ pass
42
+
43
+ try:
44
+ import fcntl
45
+ _HAS_FCNTL = True
46
+ except ImportError:
47
+ _HAS_FCNTL = False # Windows — skip file locking
48
+
49
+ # ─────────────────────────────────────────────
50
+ # Configuration
51
+ # ─────────────────────────────────────────────
52
+
53
+ def _resolve_homunculus_dir() -> Path:
54
+ override = os.environ.get("CLV2_HOMUNCULUS_DIR")
55
+ if override:
56
+ if Path(override).is_absolute():
57
+ return Path(override)
58
+ print(f"[ecc] CLV2_HOMUNCULUS_DIR={override!r} is not absolute; ignoring", file=sys.stderr)
59
+
60
+ xdg = os.environ.get("XDG_DATA_HOME")
61
+ if xdg:
62
+ if Path(xdg).is_absolute():
63
+ return Path(xdg) / "ecc-homunculus"
64
+ print(f"[ecc] XDG_DATA_HOME={xdg!r} is not absolute; ignoring", file=sys.stderr)
65
+
66
+ return Path.home() / ".local" / "share" / "ecc-homunculus"
67
+
68
+
69
+ def _strip_remote_credentials(remote_url: str) -> str:
70
+ return re.sub(r"://[^@]+@", "://", remote_url or "")
71
+
72
+
73
+ def _normalize_remote_url(remote_url: str) -> str:
74
+ if not remote_url:
75
+ return ""
76
+
77
+ is_network = (
78
+ not remote_url.startswith("file://")
79
+ and ("://" in remote_url or re.match(r"^[^@/:]+@[^:/]+:", remote_url) is not None)
80
+ )
81
+ normalized = _strip_remote_credentials(remote_url)
82
+ normalized = re.sub(r"^[A-Za-z][A-Za-z0-9+.-]*://", "", normalized)
83
+ normalized = re.sub(r"^[^@/:]+@([^:/]+):", r"\1/", normalized)
84
+ normalized = re.sub(r"\.git/?$", "", normalized)
85
+ normalized = re.sub(r"/+$", "", normalized)
86
+
87
+ return normalized.lower() if is_network else normalized
88
+
89
+
90
+ def _stream_can_encode(text: str, stream=None) -> bool:
91
+ stream = stream or sys.stdout
92
+ encoding = getattr(stream, "encoding", None) or sys.getdefaultencoding()
93
+ try:
94
+ text.encode(encoding)
95
+ except (LookupError, UnicodeEncodeError):
96
+ return False
97
+ return True
98
+
99
+
100
+ def _confidence_bar(confidence, stream=None) -> str:
101
+ try:
102
+ filled = int(float(confidence) * 10)
103
+ except (TypeError, ValueError):
104
+ filled = 5
105
+ filled = max(0, min(10, filled))
106
+
107
+ full, empty = ("\u2588", "\u2591") if _stream_can_encode("\u2588\u2591", stream) else ("#", ".")
108
+ return full * filled + empty * (10 - filled)
109
+
110
+
111
+ def _project_hash(value: str) -> str:
112
+ return hashlib.sha256(value.encode("utf-8")).hexdigest()[:12]
113
+
114
+
115
+ HOMUNCULUS_DIR = _resolve_homunculus_dir()
116
+ PROJECTS_DIR = HOMUNCULUS_DIR / "projects"
117
+ REGISTRY_FILE = HOMUNCULUS_DIR / "projects.json"
118
+
119
+ # Global (non-project-scoped) paths
120
+ GLOBAL_INSTINCTS_DIR = HOMUNCULUS_DIR / "instincts"
121
+ GLOBAL_PERSONAL_DIR = GLOBAL_INSTINCTS_DIR / "personal"
122
+ GLOBAL_INHERITED_DIR = GLOBAL_INSTINCTS_DIR / "inherited"
123
+ GLOBAL_EVOLVED_DIR = HOMUNCULUS_DIR / "evolved"
124
+ GLOBAL_OBSERVATIONS_FILE = HOMUNCULUS_DIR / "observations.jsonl"
125
+
126
+ # Thresholds for auto-promotion
127
+ PROMOTE_CONFIDENCE_THRESHOLD = 0.8
128
+ PROMOTE_MIN_PROJECTS = 2
129
+ ALLOWED_INSTINCT_EXTENSIONS = (".yaml", ".yml", ".md")
130
+
131
+ # Default TTL for pending instincts (days)
132
+ PENDING_TTL_DAYS = 30
133
+ # Warning threshold: show expiry warning when instinct expires within this many days
134
+ PENDING_EXPIRY_WARNING_DAYS = 7
135
+
136
+ # Ensure global directories exist (deferred to avoid side effects at import time)
137
+ def _ensure_global_dirs():
138
+ for d in [GLOBAL_PERSONAL_DIR, GLOBAL_INHERITED_DIR,
139
+ GLOBAL_EVOLVED_DIR / "skills", GLOBAL_EVOLVED_DIR / "commands", GLOBAL_EVOLVED_DIR / "agents",
140
+ PROJECTS_DIR]:
141
+ d.mkdir(parents=True, exist_ok=True)
142
+
143
+
144
+ # ─────────────────────────────────────────────
145
+ # Path Validation
146
+ # ─────────────────────────────────────────────
147
+
148
+ def _validate_file_path(path_str: str, must_exist: bool = False) -> Path:
149
+ """Validate and resolve a file path, guarding against path traversal.
150
+
151
+ Raises ValueError if the path is invalid or suspicious.
152
+ """
153
+ path = Path(path_str).expanduser().resolve()
154
+
155
+ # Block paths that escape into system directories
156
+ # We block specific system paths but allow temp dirs (/var/folders on macOS)
157
+ blocked_prefixes = [
158
+ "/etc", "/usr", "/bin", "/sbin", "/proc", "/sys",
159
+ "/var/log", "/var/run", "/var/lib", "/var/spool",
160
+ # macOS resolves /etc → /private/etc
161
+ "/private/etc",
162
+ "/private/var/log", "/private/var/run", "/private/var/db",
163
+ ]
164
+ path_s = str(path)
165
+ for prefix in blocked_prefixes:
166
+ if path_s.startswith(prefix + "/") or path_s == prefix:
167
+ raise ValueError(f"Path '{path}' targets a system directory")
168
+
169
+ if must_exist and not path.exists():
170
+ raise ValueError(f"Path does not exist: {path}")
171
+
172
+ return path
173
+
174
+
175
+ def _validate_instinct_id(instinct_id: str) -> bool:
176
+ """Validate instinct IDs before using them in filenames."""
177
+ if not instinct_id or len(instinct_id) > 128:
178
+ return False
179
+ if "/" in instinct_id or "\\" in instinct_id:
180
+ return False
181
+ if ".." in instinct_id:
182
+ return False
183
+ if instinct_id.startswith("."):
184
+ return False
185
+ return bool(re.match(r"^[A-Za-z0-9][A-Za-z0-9._-]*$", instinct_id))
186
+
187
+
188
+ def _validate_import_url(source: str) -> str:
189
+ """Validate remote instinct imports before opening a network connection."""
190
+ parsed = urllib.parse.urlparse(source)
191
+ if parsed.scheme != "https":
192
+ raise ValueError("remote instinct imports require https URLs")
193
+ if not parsed.hostname:
194
+ raise ValueError("remote import URL is missing a hostname")
195
+
196
+ try:
197
+ addr_infos = socket.getaddrinfo(parsed.hostname, parsed.port or 443, type=socket.SOCK_STREAM)
198
+ except socket.gaierror as exc:
199
+ raise ValueError(f"remote import host could not be resolved: {parsed.hostname}") from exc
200
+
201
+ for family, _, _, _, sockaddr in addr_infos:
202
+ host = sockaddr[0]
203
+ try:
204
+ ip = ipaddress.ip_address(host)
205
+ except ValueError:
206
+ continue
207
+ if (
208
+ ip.is_private
209
+ or ip.is_loopback
210
+ or ip.is_link_local
211
+ or ip.is_multicast
212
+ or ip.is_reserved
213
+ or ip.is_unspecified
214
+ ):
215
+ raise ValueError(f"remote import host resolves to a non-public address: {host}")
216
+
217
+ return urllib.parse.urlunparse(parsed)
218
+
219
+
220
+ def _fetch_import_url(source: str, *, max_bytes: int = 2 * 1024 * 1024) -> str:
221
+ """Fetch a validated remote instinct file with bounded size and timeout."""
222
+ url = _validate_import_url(source)
223
+ req = urllib.request.Request(url, headers={"User-Agent": "ECC-instinct-import/2"})
224
+ with urllib.request.urlopen(req, timeout=15) as response:
225
+ content_type = response.headers.get("Content-Type", "")
226
+ if content_type and not any(
227
+ allowed in content_type.lower()
228
+ for allowed in ("text/", "markdown", "yaml", "json", "octet-stream")
229
+ ):
230
+ raise ValueError(f"unsupported remote content type: {content_type}")
231
+ data = response.read(max_bytes + 1)
232
+ if len(data) > max_bytes:
233
+ raise ValueError(f"remote import exceeds {max_bytes} bytes")
234
+ return data.decode("utf-8")
235
+
236
+
237
+ def _yaml_quote(value: str) -> str:
238
+ """Quote a string for safe YAML frontmatter serialization.
239
+
240
+ Uses double quotes and escapes embedded double-quote characters to
241
+ prevent malformed YAML when the value contains quotes.
242
+ """
243
+ escaped = value.replace('\\', '\\\\').replace('"', '\\"')
244
+ return f'"{escaped}"'
245
+
246
+
247
+ # ─────────────────────────────────────────────
248
+ # Project Detection (Python equivalent of detect-project.sh)
249
+ # ─────────────────────────────────────────────
250
+
251
+ def _git_repo_root(cwd: Optional[str] = None) -> Optional[str]:
252
+ args = ["git"]
253
+ if cwd:
254
+ args.extend(["-C", cwd])
255
+ args.extend(["rev-parse", "--show-toplevel"])
256
+ try:
257
+ result = subprocess.run(args, capture_output=True, text=True, timeout=5)
258
+ if result.returncode == 0:
259
+ return result.stdout.strip()
260
+ except (subprocess.TimeoutExpired, FileNotFoundError):
261
+ pass
262
+ return None
263
+
264
+
265
+ def _main_worktree_root(project_root: str) -> str:
266
+ """Return the main worktree root when project_root is a linked worktree."""
267
+ try:
268
+ result = subprocess.run(
269
+ ["git", "-C", project_root, "worktree", "list", "--porcelain"],
270
+ capture_output=True, text=True, timeout=5
271
+ )
272
+ except (subprocess.TimeoutExpired, FileNotFoundError):
273
+ return project_root
274
+
275
+ if result.returncode != 0:
276
+ return project_root
277
+
278
+ for line in result.stdout.splitlines():
279
+ if line.startswith("worktree "):
280
+ main_root = line.split(" ", 1)[1].strip()
281
+ return main_root or project_root
282
+ return project_root
283
+
284
+
285
+ def detect_project() -> dict:
286
+ """Detect current project context. Returns dict with id, name, root, project_dir."""
287
+ project_root = None
288
+
289
+ if os.environ.get("CLV2_NO_PROJECT") == "1":
290
+ return {
291
+ "id": "global",
292
+ "name": "global",
293
+ "root": "",
294
+ "project_dir": HOMUNCULUS_DIR,
295
+ "instincts_personal": GLOBAL_PERSONAL_DIR,
296
+ "instincts_inherited": GLOBAL_INHERITED_DIR,
297
+ "evolved_dir": GLOBAL_EVOLVED_DIR,
298
+ "observations_file": GLOBAL_OBSERVATIONS_FILE,
299
+ }
300
+
301
+ # 1. CLAUDE_PROJECT_DIR env var
302
+ env_dir = os.environ.get("CLAUDE_PROJECT_DIR")
303
+ if env_dir and os.path.isdir(env_dir):
304
+ project_root = _git_repo_root(env_dir)
305
+
306
+ # 2. git repo root
307
+ if not project_root:
308
+ project_root = _git_repo_root()
309
+
310
+ # Normalize: strip trailing slashes to keep basename and hash stable
311
+ if project_root:
312
+ project_root = project_root.rstrip("/")
313
+
314
+ # 3. No project — global fallback
315
+ if not project_root:
316
+ return {
317
+ "id": "global",
318
+ "name": "global",
319
+ "root": "",
320
+ "project_dir": HOMUNCULUS_DIR,
321
+ "instincts_personal": GLOBAL_PERSONAL_DIR,
322
+ "instincts_inherited": GLOBAL_INHERITED_DIR,
323
+ "evolved_dir": GLOBAL_EVOLVED_DIR,
324
+ "observations_file": GLOBAL_OBSERVATIONS_FILE,
325
+ }
326
+
327
+ project_name = os.path.basename(project_root)
328
+
329
+ # Derive project ID from git remote URL or path
330
+ remote_url = ""
331
+ try:
332
+ result = subprocess.run(
333
+ ["git", "-C", project_root, "remote", "get-url", "origin"],
334
+ capture_output=True, text=True, timeout=5
335
+ )
336
+ if result.returncode == 0:
337
+ remote_url = result.stdout.strip()
338
+ except (subprocess.TimeoutExpired, FileNotFoundError):
339
+ pass
340
+
341
+ raw_remote_url = remote_url
342
+ if remote_url:
343
+ remote_url = _strip_remote_credentials(remote_url)
344
+
345
+ fallback_root = _main_worktree_root(project_root) if not remote_url else project_root
346
+ legacy_hash_source = remote_url if remote_url else project_root
347
+ normalized_remote = _normalize_remote_url(remote_url) if remote_url else ""
348
+ hash_source = normalized_remote if normalized_remote else (remote_url if remote_url else fallback_root)
349
+ project_id = _project_hash(hash_source)
350
+
351
+ project_dir = PROJECTS_DIR / project_id
352
+
353
+ if not project_dir.exists():
354
+ legacy_sources = []
355
+ if legacy_hash_source and legacy_hash_source != hash_source:
356
+ legacy_sources.append(legacy_hash_source)
357
+ if raw_remote_url and raw_remote_url not in {hash_source, legacy_hash_source}:
358
+ legacy_sources.append(raw_remote_url)
359
+
360
+ for legacy_source in legacy_sources:
361
+ legacy_id = _project_hash(legacy_source)
362
+ legacy_dir = PROJECTS_DIR / legacy_id
363
+ if legacy_id != project_id and legacy_dir.exists():
364
+ try:
365
+ legacy_dir.rename(project_dir)
366
+ except OSError:
367
+ project_id = legacy_id
368
+ project_dir = legacy_dir
369
+ break
370
+
371
+ # Ensure project directory structure
372
+ for d in [
373
+ project_dir / "instincts" / "personal",
374
+ project_dir / "instincts" / "inherited",
375
+ project_dir / "observations.archive",
376
+ project_dir / "evolved" / "skills",
377
+ project_dir / "evolved" / "commands",
378
+ project_dir / "evolved" / "agents",
379
+ ]:
380
+ d.mkdir(parents=True, exist_ok=True)
381
+
382
+ # Update registry
383
+ _update_registry(project_id, project_name, project_root, remote_url)
384
+
385
+ return {
386
+ "id": project_id,
387
+ "name": project_name,
388
+ "root": project_root,
389
+ "remote": remote_url,
390
+ "project_dir": project_dir,
391
+ "instincts_personal": project_dir / "instincts" / "personal",
392
+ "instincts_inherited": project_dir / "instincts" / "inherited",
393
+ "evolved_dir": project_dir / "evolved",
394
+ "observations_file": project_dir / "observations.jsonl",
395
+ }
396
+
397
+
398
+ @contextmanager
399
+ def _registry_lock():
400
+ """Serialize registry read-modify-write across concurrent sessions.
401
+
402
+ Acquires the same advisory lock for every registry writer (``_update_registry``
403
+ and ``_write_registry``) so ``projects delete/gc/merge`` cannot interleave with
404
+ a concurrent observe-time update and corrupt ``projects.json``. No-op on
405
+ platforms without ``fcntl`` (Windows).
406
+ """
407
+ REGISTRY_FILE.parent.mkdir(parents=True, exist_ok=True)
408
+ lock_path = REGISTRY_FILE.parent / f".{REGISTRY_FILE.name}.lock"
409
+ lock_fd = None
410
+ try:
411
+ if _HAS_FCNTL:
412
+ lock_fd = open(lock_path, "w")
413
+ fcntl.flock(lock_fd, fcntl.LOCK_EX)
414
+ yield
415
+ finally:
416
+ if lock_fd is not None:
417
+ fcntl.flock(lock_fd, fcntl.LOCK_UN)
418
+ lock_fd.close()
419
+
420
+
421
+ def _update_registry(pid: str, pname: str, proot: str, premote: str) -> None:
422
+ """Update the projects.json registry.
423
+
424
+ Uses file locking (where available) to prevent concurrent sessions from
425
+ overwriting each other's updates.
426
+ """
427
+ with _registry_lock():
428
+ try:
429
+ with open(REGISTRY_FILE, encoding="utf-8") as f:
430
+ registry = json.load(f)
431
+ except (FileNotFoundError, json.JSONDecodeError):
432
+ registry = {}
433
+ # A registry that is valid JSON but not a mapping (e.g. a list from a
434
+ # corrupt projects.json) must not crash the update before the per-entry
435
+ # guard below: fall back to an empty dict so the whole file is healed.
436
+ if not isinstance(registry, dict):
437
+ registry = {}
438
+
439
+ # Mirror the shell counterpart in detect-project.sh: the entry carries
440
+ # "id" and "created_at" alongside the other fields so a projects.json
441
+ # record has the same shape regardless of which path (Python CLI or
442
+ # shell hook) last wrote it. "created_at" is preserved from any
443
+ # existing entry; only "last_seen" advances on update.
444
+ now = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
445
+ existing = registry.get(pid, {})
446
+ # A malformed registry (e.g. a non-dict value for this id) must not
447
+ # crash the update: fall back to an empty dict so the corrupt entry is
448
+ # healed by the rewrite, matching the old unconditional-overwrite
449
+ # behavior.
450
+ if not isinstance(existing, dict):
451
+ existing = {}
452
+ registry[pid] = {
453
+ "id": pid,
454
+ "name": pname,
455
+ "root": proot,
456
+ "remote": premote,
457
+ "created_at": existing.get("created_at", now),
458
+ "last_seen": now,
459
+ }
460
+
461
+ tmp_file = REGISTRY_FILE.parent / f".{REGISTRY_FILE.name}.tmp.{os.getpid()}"
462
+ with open(tmp_file, "w", encoding="utf-8") as f:
463
+ json.dump(registry, f, indent=2)
464
+ f.flush()
465
+ os.fsync(f.fileno())
466
+ os.replace(tmp_file, REGISTRY_FILE)
467
+
468
+
469
+ def load_registry() -> dict:
470
+ """Load the projects registry."""
471
+ try:
472
+ with open(REGISTRY_FILE, encoding="utf-8") as f:
473
+ return json.load(f)
474
+ except (FileNotFoundError, json.JSONDecodeError):
475
+ return {}
476
+
477
+
478
+ def _write_registry(registry: dict) -> None:
479
+ """Write the project registry atomically.
480
+
481
+ Holds the same advisory lock as ``_update_registry`` so concurrent
482
+ ``projects delete/gc/merge`` and observe-time updates cannot corrupt the file.
483
+ """
484
+ with _registry_lock():
485
+ tmp_file = REGISTRY_FILE.parent / f".{REGISTRY_FILE.name}.tmp.{os.getpid()}"
486
+ with open(tmp_file, "w", encoding="utf-8") as f:
487
+ json.dump(registry, f, indent=2)
488
+ f.write("\n")
489
+ f.flush()
490
+ os.fsync(f.fileno())
491
+ os.replace(tmp_file, REGISTRY_FILE)
492
+
493
+
494
+ def _validate_project_id(project_id: str) -> bool:
495
+ if not project_id or len(project_id) > 128:
496
+ return False
497
+ if "/" in project_id or "\\" in project_id or ".." in project_id:
498
+ return False
499
+ return bool(re.match(r"^[A-Za-z0-9][A-Za-z0-9._-]*$", project_id))
500
+
501
+
502
+ # ─────────────────────────────────────────────
503
+ # Instinct Parser
504
+ # ─────────────────────────────────────────────
505
+
506
+ def parse_instinct_file(content: str) -> list[dict]:
507
+ """Parse YAML-like instinct file format.
508
+
509
+ Each instinct is delimited by a pair of ``---`` markers (YAML frontmatter).
510
+ Note: ``---`` is always treated as a frontmatter boundary; instinct body
511
+ content must use ``***`` or ``___`` for horizontal rules to avoid ambiguity.
512
+ """
513
+ instincts = []
514
+ current = {}
515
+ in_frontmatter = False
516
+ content_lines = []
517
+
518
+ for line in content.split('\n'):
519
+ if line.strip() == '---':
520
+ if in_frontmatter:
521
+ # End of frontmatter - content comes next
522
+ in_frontmatter = False
523
+ else:
524
+ # Start of new frontmatter block
525
+ in_frontmatter = True
526
+ if current:
527
+ current['content'] = '\n'.join(content_lines).strip()
528
+ instincts.append(current)
529
+ current = {}
530
+ content_lines = []
531
+ elif in_frontmatter:
532
+ # Parse YAML-like frontmatter
533
+ if ':' in line:
534
+ key, value = line.split(':', 1)
535
+ key = key.strip()
536
+ value = value.strip()
537
+ # Unescape quoted YAML strings
538
+ if value.startswith('"') and value.endswith('"'):
539
+ value = value[1:-1].replace('\\"', '"').replace('\\\\', '\\')
540
+ elif value.startswith("'") and value.endswith("'"):
541
+ value = value[1:-1].replace("''", "'")
542
+ if key == 'confidence':
543
+ try:
544
+ current[key] = float(value)
545
+ except ValueError:
546
+ current[key] = 0.5 # default on malformed confidence
547
+ else:
548
+ current[key] = value
549
+ else:
550
+ content_lines.append(line)
551
+
552
+ # Don't forget the last instinct
553
+ if current:
554
+ current['content'] = '\n'.join(content_lines).strip()
555
+ instincts.append(current)
556
+
557
+ return [i for i in instincts if i.get('id')]
558
+
559
+
560
+ def _load_instincts_from_dir(directory: Path, source_type: str, scope_label: str) -> list[dict]:
561
+ """Load instincts from a single directory."""
562
+ instincts = []
563
+ if not directory.exists():
564
+ return instincts
565
+ files = [
566
+ file for file in sorted(directory.iterdir())
567
+ if file.is_file() and file.suffix.lower() in ALLOWED_INSTINCT_EXTENSIONS
568
+ ]
569
+ for file in files:
570
+ try:
571
+ content = file.read_text(encoding="utf-8")
572
+ parsed = parse_instinct_file(content)
573
+ for inst in parsed:
574
+ inst['_source_file'] = str(file)
575
+ inst['_source_type'] = source_type
576
+ inst['_scope_label'] = scope_label
577
+ # Default scope if not set in frontmatter
578
+ if 'scope' not in inst:
579
+ inst['scope'] = scope_label
580
+ instincts.extend(parsed)
581
+ except Exception as e:
582
+ print(f"Warning: Failed to parse {file}: {e}", file=sys.stderr)
583
+ return instincts
584
+
585
+
586
+ def _project_counts(project_id: str) -> dict:
587
+ project_dir = PROJECTS_DIR / project_id
588
+ personal_dir = project_dir / "instincts" / "personal"
589
+ inherited_dir = project_dir / "instincts" / "inherited"
590
+ observations_file = project_dir / "observations.jsonl"
591
+
592
+ personal_count = len(_load_instincts_from_dir(personal_dir, "personal", "project"))
593
+ inherited_count = len(_load_instincts_from_dir(inherited_dir, "inherited", "project"))
594
+ observations_count = 0
595
+ if observations_file.exists():
596
+ try:
597
+ with open(observations_file, encoding="utf-8") as f:
598
+ observations_count = sum(1 for _ in f)
599
+ except OSError:
600
+ observations_count = 0
601
+
602
+ return {
603
+ "personal": personal_count,
604
+ "inherited": inherited_count,
605
+ "observations": observations_count,
606
+ "total": personal_count + inherited_count + observations_count,
607
+ }
608
+
609
+
610
+ def _remove_project_storage(project_id: str) -> None:
611
+ # Defense-in-depth: resolve and confirm the target is contained within
612
+ # PROJECTS_DIR before recursively deleting, even though callers validate the
613
+ # project id. A relaxed validator or a future caller must never be able to
614
+ # turn this into an arbitrary-directory delete.
615
+ projects_root = PROJECTS_DIR.resolve()
616
+ project_dir = (PROJECTS_DIR / project_id).resolve()
617
+ if project_dir == projects_root or projects_root not in project_dir.parents:
618
+ raise ValueError(f"refusing to remove {project_dir}: escapes {projects_root}")
619
+ if project_dir.exists():
620
+ shutil.rmtree(project_dir)
621
+
622
+
623
+ def _project_instinct_ids(project_dir: Path, source_type: str) -> set[str]:
624
+ instinct_dir = project_dir / "instincts" / source_type
625
+ return {
626
+ inst.get("id")
627
+ for inst in _load_instincts_from_dir(instinct_dir, source_type, "project")
628
+ if inst.get("id")
629
+ }
630
+
631
+
632
+ def _merge_instinct_dir(from_dir: Path, into_dir: Path, existing_ids: set[str]) -> tuple[int, int]:
633
+ moved = 0
634
+ skipped = 0
635
+ if not from_dir.exists():
636
+ return moved, skipped
637
+
638
+ into_dir.mkdir(parents=True, exist_ok=True)
639
+ for file_path in sorted(from_dir.iterdir()):
640
+ if not file_path.is_file() or file_path.suffix.lower() not in ALLOWED_INSTINCT_EXTENSIONS:
641
+ continue
642
+ try:
643
+ instincts = parse_instinct_file(file_path.read_text(encoding="utf-8"))
644
+ except (OSError, UnicodeDecodeError):
645
+ instincts = []
646
+ instinct_ids = [inst.get("id") for inst in instincts if inst.get("id")]
647
+ if any(instinct_id in existing_ids for instinct_id in instinct_ids):
648
+ skipped += 1
649
+ continue
650
+
651
+ target_path = into_dir / file_path.name
652
+ if target_path.exists():
653
+ target_path = into_dir / f"{file_path.stem}-{_project_hash(str(file_path))}{file_path.suffix}"
654
+ shutil.copy2(file_path, target_path)
655
+ existing_ids.update(instinct_ids)
656
+ moved += 1
657
+
658
+ return moved, skipped
659
+
660
+
661
+ def _append_observations(from_project_dir: Path, into_project_dir: Path) -> int:
662
+ from_file = from_project_dir / "observations.jsonl"
663
+ if not from_file.exists():
664
+ return 0
665
+
666
+ into_file = into_project_dir / "observations.jsonl"
667
+ into_file.parent.mkdir(parents=True, exist_ok=True)
668
+ try:
669
+ lines = from_file.read_text(encoding="utf-8").splitlines()
670
+ except (OSError, UnicodeDecodeError):
671
+ return 0
672
+
673
+ if not lines:
674
+ return 0
675
+
676
+ with open(into_file, "a", encoding="utf-8") as f:
677
+ for line in lines:
678
+ if line.strip():
679
+ f.write(line.rstrip("\n") + "\n")
680
+ return len([line for line in lines if line.strip()])
681
+
682
+
683
+ def load_all_instincts(project: dict, include_global: bool = True) -> list[dict]:
684
+ """Load all instincts: project-scoped + global.
685
+
686
+ Project-scoped instincts take precedence over global ones when IDs conflict.
687
+ """
688
+ instincts = []
689
+
690
+ # 1. Load project-scoped instincts (if not already global)
691
+ if project["id"] != "global":
692
+ instincts.extend(_load_instincts_from_dir(
693
+ project["instincts_personal"], "personal", "project"
694
+ ))
695
+ instincts.extend(_load_instincts_from_dir(
696
+ project["instincts_inherited"], "inherited", "project"
697
+ ))
698
+
699
+ # 2. Load global instincts
700
+ if include_global:
701
+ global_instincts = []
702
+ global_instincts.extend(_load_instincts_from_dir(
703
+ GLOBAL_PERSONAL_DIR, "personal", "global"
704
+ ))
705
+ global_instincts.extend(_load_instincts_from_dir(
706
+ GLOBAL_INHERITED_DIR, "inherited", "global"
707
+ ))
708
+
709
+ # Deduplicate: project-scoped wins over global when same ID
710
+ project_ids = {i.get('id') for i in instincts}
711
+ for gi in global_instincts:
712
+ if gi.get('id') not in project_ids:
713
+ instincts.append(gi)
714
+
715
+ return instincts
716
+
717
+
718
+ def load_project_only_instincts(project: dict) -> list[dict]:
719
+ """Load only project-scoped instincts (no global).
720
+
721
+ In global fallback mode (no git project), returns global instincts.
722
+ """
723
+ if project.get("id") == "global":
724
+ instincts = _load_instincts_from_dir(GLOBAL_PERSONAL_DIR, "personal", "global")
725
+ instincts += _load_instincts_from_dir(GLOBAL_INHERITED_DIR, "inherited", "global")
726
+ return instincts
727
+ return load_all_instincts(project, include_global=False)
728
+
729
+
730
+ # ─────────────────────────────────────────────
731
+ # Status Command
732
+ # ─────────────────────────────────────────────
733
+
734
+ def cmd_status(args) -> int:
735
+ """Show status of all instincts (project + global)."""
736
+ project = detect_project()
737
+ instincts = load_all_instincts(project)
738
+
739
+ if not instincts:
740
+ print("No instincts found.")
741
+ print(f"\nProject: {project['name']} ({project['id']})")
742
+ print(f" Project instincts: {project['instincts_personal']}")
743
+ print(f" Global instincts: {GLOBAL_PERSONAL_DIR}")
744
+ else:
745
+ # Split by scope
746
+ project_instincts = [i for i in instincts if i.get('_scope_label') == 'project']
747
+ global_instincts = [i for i in instincts if i.get('_scope_label') == 'global']
748
+
749
+ # Print header
750
+ print(f"\n{'='*60}")
751
+ print(f" INSTINCT STATUS - {len(instincts)} total")
752
+ print(f"{'='*60}\n")
753
+
754
+ print(f" Project: {project['name']} ({project['id']})")
755
+ print(f" Project instincts: {len(project_instincts)}")
756
+ print(f" Global instincts: {len(global_instincts)}")
757
+ print()
758
+
759
+ # Print project-scoped instincts
760
+ if project_instincts:
761
+ print(f"## PROJECT-SCOPED ({project['name']})")
762
+ print()
763
+ _print_instincts_by_domain(project_instincts)
764
+
765
+ # Print global instincts
766
+ if global_instincts:
767
+ print("## GLOBAL (apply to all projects)")
768
+ print()
769
+ _print_instincts_by_domain(global_instincts)
770
+
771
+ # Observations stats
772
+ obs_file = project.get("observations_file")
773
+ if obs_file and Path(obs_file).exists():
774
+ with open(obs_file, encoding="utf-8") as f:
775
+ obs_count = sum(1 for _ in f)
776
+ print(f"-" * 60)
777
+ print(f" Observations: {obs_count} events logged")
778
+ print(f" File: {obs_file}")
779
+
780
+ # Pending instinct stats
781
+ pending = _collect_pending_instincts()
782
+ if pending:
783
+ print(f"\n{'-'*60}")
784
+ print(f" Pending instincts: {len(pending)} awaiting review")
785
+
786
+ if len(pending) >= 5:
787
+ print(f"\n \u26a0 {len(pending)} pending instincts awaiting review."
788
+ f" Unreviewed instincts auto-delete after {PENDING_TTL_DAYS} days.")
789
+
790
+ # Show instincts expiring within PENDING_EXPIRY_WARNING_DAYS
791
+ expiry_threshold = PENDING_TTL_DAYS - PENDING_EXPIRY_WARNING_DAYS
792
+ expiring_soon = [p for p in pending
793
+ if p["age_days"] >= expiry_threshold and p["age_days"] < PENDING_TTL_DAYS]
794
+ if expiring_soon:
795
+ print(f"\n Expiring within {PENDING_EXPIRY_WARNING_DAYS} days:")
796
+ for item in expiring_soon:
797
+ days_left = max(0, PENDING_TTL_DAYS - item["age_days"])
798
+ print(f" - {item['name']} ({days_left}d remaining)")
799
+
800
+ # Legacy data warning
801
+ _warn_legacy_data()
802
+
803
+ print(f"\n{'='*60}\n")
804
+ return 0
805
+
806
+
807
+ def _warn_legacy_data() -> None:
808
+ """Warn if legacy ~/.claude/homunculus/ contains data while the active
809
+ path has moved to the XDG directory."""
810
+ legacy_dir = Path.home() / ".claude" / "homunculus"
811
+ if legacy_dir == HOMUNCULUS_DIR:
812
+ return # CLV2_HOMUNCULUS_DIR explicitly points at the legacy path
813
+ if not legacy_dir.is_dir():
814
+ return
815
+
816
+ # Count substantive files (skip empty dirs and the directory itself)
817
+ try:
818
+ legacy_files = [f for f in legacy_dir.rglob("*") if f.is_file()]
819
+ except (PermissionError, OSError):
820
+ print(f"\n Note: legacy directory exists but cannot be read: {legacy_dir}", file=sys.stderr)
821
+ return
822
+ if not legacy_files:
823
+ return
824
+
825
+ migrate_script = Path(__file__).resolve().parent / "migrate-homunculus.sh"
826
+
827
+ print(f"\n{'!'*60}")
828
+ print(" LEGACY DATA DETECTED")
829
+ print(f"{'!'*60}")
830
+ print(f" Found {len(legacy_files)} file(s) in legacy path:")
831
+ print(f" {legacy_dir}")
832
+ print(" Active data directory:")
833
+ print(f" {HOMUNCULUS_DIR}")
834
+ print()
835
+ print(" Run the migration script to move your data:")
836
+ print(f' bash "{migrate_script}"')
837
+ print(f" Or set CLV2_HOMUNCULUS_DIR={legacy_dir} to use the legacy path.")
838
+ print(f"{'!'*60}\n")
839
+
840
+
841
+ def _print_instincts_by_domain(instincts: list[dict]) -> None:
842
+ """Helper to print instincts grouped by domain."""
843
+ by_domain = defaultdict(list)
844
+ for inst in instincts:
845
+ domain = inst.get('domain', 'general')
846
+ by_domain[domain].append(inst)
847
+
848
+ for domain in sorted(by_domain.keys()):
849
+ domain_instincts = by_domain[domain]
850
+ print(f" ### {domain.upper()} ({len(domain_instincts)})")
851
+ print()
852
+
853
+ for inst in sorted(domain_instincts, key=lambda x: -x.get('confidence', 0.5)):
854
+ conf = inst.get('confidence', 0.5)
855
+ conf_bar = _confidence_bar(conf)
856
+ trigger = inst.get('trigger', 'unknown trigger')
857
+ scope_tag = f"[{inst.get('scope', '?')}]"
858
+
859
+ print(f" {conf_bar} {int(conf*100):3d}% {inst.get('id', 'unnamed')} {scope_tag}")
860
+ print(f" trigger: {trigger}")
861
+
862
+ # Extract action from content
863
+ content = inst.get('content', '')
864
+ action_match = re.search(r'## Action\s*\n\s*(.+?)(?:\n\n|\n##|$)', content, re.DOTALL)
865
+ if action_match:
866
+ action = action_match.group(1).strip().split('\n')[0]
867
+ print(f" action: {action[:60]}{'...' if len(action) > 60 else ''}")
868
+
869
+ print()
870
+
871
+
872
+ # ─────────────────────────────────────────────
873
+ # Import Command
874
+ # ─────────────────────────────────────────────
875
+
876
+ def cmd_import(args) -> int:
877
+ """Import instincts from file or URL."""
878
+ project = detect_project()
879
+ source = args.source
880
+
881
+ # Determine target scope
882
+ target_scope = args.scope or "project"
883
+ if target_scope == "project" and project["id"] == "global":
884
+ print("No project detected. Importing as global scope.")
885
+ target_scope = "global"
886
+
887
+ # Fetch content
888
+ if source.startswith('http://') or source.startswith('https://'):
889
+ print(f"Fetching from URL: {source}")
890
+ try:
891
+ content = _fetch_import_url(source)
892
+ except Exception as e:
893
+ print(f"Error fetching URL: {e}", file=sys.stderr)
894
+ return 1
895
+ else:
896
+ try:
897
+ path = _validate_file_path(source, must_exist=True)
898
+ except ValueError as e:
899
+ print(f"Invalid path: {e}", file=sys.stderr)
900
+ return 1
901
+ if not path.is_file():
902
+ print(f"Error: '{path}' is not a regular file.", file=sys.stderr)
903
+ return 1
904
+ content = path.read_text(encoding="utf-8")
905
+
906
+ # Parse instincts
907
+ new_instincts = parse_instinct_file(content)
908
+ if not new_instincts:
909
+ print("No valid instincts found in source.")
910
+ return 1
911
+
912
+ print(f"\nFound {len(new_instincts)} instincts to import.")
913
+ print(f"Target scope: {target_scope}")
914
+ if target_scope == "project":
915
+ print(f"Target project: {project['name']} ({project['id']})")
916
+ print()
917
+
918
+ # Load existing instincts for dedup, scoped to the target to avoid
919
+ # cross-scope shadowing (project instincts hiding global ones or vice versa)
920
+ if target_scope == "global":
921
+ existing = _load_instincts_from_dir(GLOBAL_PERSONAL_DIR, "personal", "global")
922
+ existing += _load_instincts_from_dir(GLOBAL_INHERITED_DIR, "inherited", "global")
923
+ else:
924
+ existing = load_project_only_instincts(project)
925
+ existing_ids = {i.get('id') for i in existing}
926
+
927
+ # Deduplicate within the import source: keep highest confidence per ID
928
+ best_by_id = {}
929
+ for inst in new_instincts:
930
+ inst_id = inst.get('id')
931
+ if inst_id not in best_by_id or inst.get('confidence', 0.5) > best_by_id[inst_id].get('confidence', 0.5):
932
+ best_by_id[inst_id] = inst
933
+ deduped_instincts = list(best_by_id.values())
934
+
935
+ # Categorize against existing instincts on disk
936
+ to_add = []
937
+ duplicates = []
938
+ to_update = []
939
+
940
+ for inst in deduped_instincts:
941
+ inst_id = inst.get('id')
942
+ if inst_id in existing_ids:
943
+ existing_inst = next((e for e in existing if e.get('id') == inst_id), None)
944
+ if existing_inst:
945
+ if inst.get('confidence', 0) > existing_inst.get('confidence', 0):
946
+ to_update.append(inst)
947
+ else:
948
+ duplicates.append(inst)
949
+ else:
950
+ to_add.append(inst)
951
+
952
+ # Filter by minimum confidence
953
+ min_conf = args.min_confidence if args.min_confidence is not None else 0.0
954
+ to_add = [i for i in to_add if i.get('confidence', 0.5) >= min_conf]
955
+ to_update = [i for i in to_update if i.get('confidence', 0.5) >= min_conf]
956
+
957
+ # Display summary
958
+ if to_add:
959
+ print(f"NEW ({len(to_add)}):")
960
+ for inst in to_add:
961
+ print(f" + {inst.get('id')} (confidence: {inst.get('confidence', 0.5):.2f})")
962
+
963
+ if to_update:
964
+ print(f"\nUPDATE ({len(to_update)}):")
965
+ for inst in to_update:
966
+ print(f" ~ {inst.get('id')} (confidence: {inst.get('confidence', 0.5):.2f})")
967
+
968
+ if duplicates:
969
+ print(f"\nSKIP ({len(duplicates)} - already exists with equal/higher confidence):")
970
+ for inst in duplicates[:5]:
971
+ print(f" - {inst.get('id')}")
972
+ if len(duplicates) > 5:
973
+ print(f" ... and {len(duplicates) - 5} more")
974
+
975
+ if args.dry_run:
976
+ print("\n[DRY RUN] No changes made.")
977
+ return 0
978
+
979
+ if not to_add and not to_update:
980
+ print("\nNothing to import.")
981
+ return 0
982
+
983
+ # Confirm
984
+ if not args.force:
985
+ response = input(f"\nImport {len(to_add)} new, update {len(to_update)}? [y/N] ")
986
+ if response.lower() != 'y':
987
+ print("Cancelled.")
988
+ return 0
989
+
990
+ # Determine output directory based on scope
991
+ if target_scope == "global":
992
+ output_dir = GLOBAL_INHERITED_DIR
993
+ else:
994
+ output_dir = project["instincts_inherited"]
995
+
996
+ output_dir.mkdir(parents=True, exist_ok=True)
997
+
998
+ # Collect stale files for instincts being updated (deleted after new file is written).
999
+ # Allow deletion from any subdirectory (personal/ or inherited/) within the
1000
+ # target scope to prevent the same ID existing in both places. Guard against
1001
+ # cross-scope deletion by restricting to the scope's instincts root.
1002
+ if target_scope == "global":
1003
+ scope_root = GLOBAL_INSTINCTS_DIR.resolve()
1004
+ else:
1005
+ scope_root = (project["project_dir"] / "instincts").resolve() if project["id"] != "global" else GLOBAL_INSTINCTS_DIR.resolve()
1006
+ stale_paths = []
1007
+ for inst in to_update:
1008
+ inst_id = inst.get('id')
1009
+ stale = next((e for e in existing if e.get('id') == inst_id), None)
1010
+ if stale and stale.get('_source_file'):
1011
+ stale_path = Path(stale['_source_file']).resolve()
1012
+ if stale_path.exists() and str(stale_path).startswith(str(scope_root) + os.sep):
1013
+ stale_paths.append(stale_path)
1014
+
1015
+ # Write new file first (safe: if this fails, stale files are preserved)
1016
+ timestamp = datetime.now().strftime('%Y%m%d-%H%M%S')
1017
+ source_name = Path(source).stem if not source.startswith('http') else 'web-import'
1018
+ output_file = output_dir / f"{source_name}-{timestamp}.yaml"
1019
+
1020
+ all_to_write = to_add + to_update
1021
+ output_content = f"# Imported from {source}\n# Date: {datetime.now().isoformat()}\n# Scope: {target_scope}\n"
1022
+ if target_scope == "project":
1023
+ output_content += f"# Project: {project['name']} ({project['id']})\n"
1024
+ output_content += "\n"
1025
+
1026
+ for inst in all_to_write:
1027
+ output_content += "---\n"
1028
+ output_content += f"id: {inst.get('id')}\n"
1029
+ output_content += f"trigger: {_yaml_quote(inst.get('trigger', 'unknown'))}\n"
1030
+ output_content += f"confidence: {inst.get('confidence', 0.5)}\n"
1031
+ output_content += f"domain: {inst.get('domain', 'general')}\n"
1032
+ output_content += "source: inherited\n"
1033
+ output_content += f"scope: {target_scope}\n"
1034
+ output_content += f"imported_from: {_yaml_quote(source)}\n"
1035
+ if target_scope == "project":
1036
+ output_content += f"project_id: {project['id']}\n"
1037
+ output_content += f"project_name: {project['name']}\n"
1038
+ if inst.get('source_repo'):
1039
+ output_content += f"source_repo: {inst.get('source_repo')}\n"
1040
+ output_content += "---\n\n"
1041
+ output_content += inst.get('content', '') + "\n\n"
1042
+
1043
+ output_file.write_text(output_content, encoding="utf-8")
1044
+
1045
+ # Remove stale files only after the new file has been written successfully
1046
+ for stale_path in stale_paths:
1047
+ try:
1048
+ stale_path.unlink()
1049
+ except OSError:
1050
+ pass # best-effort removal
1051
+
1052
+ print(f"\nImport complete!")
1053
+ print(f" Scope: {target_scope}")
1054
+ print(f" Added: {len(to_add)}")
1055
+ print(f" Updated: {len(to_update)}")
1056
+ print(f" Saved to: {output_file}")
1057
+
1058
+ return 0
1059
+
1060
+
1061
+ # ─────────────────────────────────────────────
1062
+ # Export Command
1063
+ # ─────────────────────────────────────────────
1064
+
1065
+ def cmd_export(args) -> int:
1066
+ """Export instincts to file."""
1067
+ project = detect_project()
1068
+
1069
+ # Determine what to export based on scope filter
1070
+ if args.scope == "project":
1071
+ instincts = load_project_only_instincts(project)
1072
+ elif args.scope == "global":
1073
+ instincts = _load_instincts_from_dir(GLOBAL_PERSONAL_DIR, "personal", "global")
1074
+ instincts += _load_instincts_from_dir(GLOBAL_INHERITED_DIR, "inherited", "global")
1075
+ else:
1076
+ instincts = load_all_instincts(project)
1077
+
1078
+ if not instincts:
1079
+ print("No instincts to export.")
1080
+ return 1
1081
+
1082
+ # Filter by domain if specified
1083
+ if args.domain:
1084
+ instincts = [i for i in instincts if i.get('domain') == args.domain]
1085
+
1086
+ # Filter by minimum confidence
1087
+ if args.min_confidence:
1088
+ instincts = [i for i in instincts if i.get('confidence', 0.5) >= args.min_confidence]
1089
+
1090
+ if not instincts:
1091
+ print("No instincts match the criteria.")
1092
+ return 1
1093
+
1094
+ # Generate output
1095
+ output = f"# Instincts export\n# Date: {datetime.now().isoformat()}\n# Total: {len(instincts)}\n"
1096
+ if args.scope:
1097
+ output += f"# Scope: {args.scope}\n"
1098
+ if project["id"] != "global":
1099
+ output += f"# Project: {project['name']} ({project['id']})\n"
1100
+ output += "\n"
1101
+
1102
+ for inst in instincts:
1103
+ output += "---\n"
1104
+ for key in ['id', 'trigger', 'confidence', 'domain', 'source', 'scope',
1105
+ 'project_id', 'project_name', 'source_repo']:
1106
+ if inst.get(key):
1107
+ value = inst[key]
1108
+ if key == 'trigger':
1109
+ output += f'{key}: {_yaml_quote(value)}\n'
1110
+ else:
1111
+ output += f"{key}: {value}\n"
1112
+ output += "---\n\n"
1113
+ output += inst.get('content', '') + "\n\n"
1114
+
1115
+ # Write to file or stdout
1116
+ if args.output:
1117
+ try:
1118
+ out_path = _validate_file_path(args.output)
1119
+ except ValueError as e:
1120
+ print(f"Invalid output path: {e}", file=sys.stderr)
1121
+ return 1
1122
+ if out_path.is_dir():
1123
+ print(f"Error: '{out_path}' is a directory, not a file.", file=sys.stderr)
1124
+ return 1
1125
+ out_path.parent.mkdir(parents=True, exist_ok=True)
1126
+ out_path.write_text(output, encoding="utf-8")
1127
+ print(f"Exported {len(instincts)} instincts to {out_path}")
1128
+ else:
1129
+ print(output)
1130
+
1131
+ return 0
1132
+
1133
+
1134
+ # ─────────────────────────────────────────────
1135
+ # Evolve Command
1136
+ # ─────────────────────────────────────────────
1137
+
1138
+ def cmd_evolve(args) -> int:
1139
+ """Analyze instincts and suggest evolutions to skills/commands/agents."""
1140
+ project = detect_project()
1141
+ instincts = load_all_instincts(project)
1142
+
1143
+ if len(instincts) < 3:
1144
+ print("Need at least 3 instincts to analyze patterns.")
1145
+ print(f"Currently have: {len(instincts)}")
1146
+ return 1
1147
+
1148
+ project_instincts = [i for i in instincts if i.get('_scope_label') == 'project']
1149
+ global_instincts = [i for i in instincts if i.get('_scope_label') == 'global']
1150
+
1151
+ print(f"\n{'='*60}")
1152
+ print(f" EVOLVE ANALYSIS - {len(instincts)} instincts")
1153
+ print(f" Project: {project['name']} ({project['id']})")
1154
+ print(f" Project-scoped: {len(project_instincts)} | Global: {len(global_instincts)}")
1155
+ print(f"{'='*60}\n")
1156
+
1157
+ # Group by domain
1158
+ by_domain = defaultdict(list)
1159
+ for inst in instincts:
1160
+ domain = inst.get('domain', 'general')
1161
+ by_domain[domain].append(inst)
1162
+
1163
+ # High-confidence instincts by domain (candidates for skills)
1164
+ high_conf = [i for i in instincts if i.get('confidence', 0) >= 0.8]
1165
+ print(f"High confidence instincts (>=80%): {len(high_conf)}")
1166
+
1167
+ # Find clusters (instincts with similar triggers)
1168
+ trigger_clusters = defaultdict(list)
1169
+ for inst in instincts:
1170
+ trigger = inst.get('trigger', '')
1171
+ # Normalize trigger
1172
+ trigger_key = trigger.lower()
1173
+ for keyword in ['when', 'creating', 'writing', 'adding', 'implementing', 'testing']:
1174
+ trigger_key = trigger_key.replace(keyword, '').strip()
1175
+ trigger_clusters[trigger_key].append(inst)
1176
+
1177
+ # Find clusters with 2+ instincts (good skill candidates)
1178
+ skill_candidates = []
1179
+ for trigger, cluster in trigger_clusters.items():
1180
+ if len(cluster) >= 2:
1181
+ avg_conf = sum(i.get('confidence', 0.5) for i in cluster) / len(cluster)
1182
+ skill_candidates.append({
1183
+ 'trigger': trigger,
1184
+ 'instincts': cluster,
1185
+ 'avg_confidence': avg_conf,
1186
+ 'domains': list(set(i.get('domain', 'general') for i in cluster)),
1187
+ 'scopes': list(set(i.get('scope', 'project') for i in cluster)),
1188
+ })
1189
+
1190
+ # Sort by cluster size and confidence
1191
+ skill_candidates.sort(key=lambda x: (-len(x['instincts']), -x['avg_confidence']))
1192
+
1193
+ print(f"\nPotential skill clusters found: {len(skill_candidates)}")
1194
+
1195
+ if skill_candidates:
1196
+ print(f"\n## SKILL CANDIDATES\n")
1197
+ for i, cand in enumerate(skill_candidates[:5], 1):
1198
+ scope_info = ', '.join(cand['scopes'])
1199
+ print(f"{i}. Cluster: \"{cand['trigger']}\"")
1200
+ print(f" Instincts: {len(cand['instincts'])}")
1201
+ print(f" Avg confidence: {cand['avg_confidence']:.0%}")
1202
+ print(f" Domains: {', '.join(cand['domains'])}")
1203
+ print(f" Scopes: {scope_info}")
1204
+ print(f" Instincts:")
1205
+ for inst in cand['instincts'][:3]:
1206
+ print(f" - {inst.get('id')} [{inst.get('scope', '?')}]")
1207
+ print()
1208
+
1209
+ # Command candidates (workflow instincts with high confidence)
1210
+ workflow_instincts = [i for i in instincts if i.get('domain') == 'workflow' and i.get('confidence', 0) >= 0.7]
1211
+ if workflow_instincts:
1212
+ print(f"\n## COMMAND CANDIDATES ({len(workflow_instincts)})\n")
1213
+ for inst in workflow_instincts[:5]:
1214
+ trigger = inst.get('trigger', 'unknown')
1215
+ cmd_name = trigger.replace('when ', '').replace('implementing ', '').replace('a ', '')
1216
+ cmd_name = cmd_name.replace(' ', '-')[:20]
1217
+ print(f" /{cmd_name}")
1218
+ print(f" From: {inst.get('id')} [{inst.get('scope', '?')}]")
1219
+ print(f" Confidence: {inst.get('confidence', 0.5):.0%}")
1220
+ print()
1221
+
1222
+ # Agent candidates (complex multi-step patterns)
1223
+ agent_candidates = [c for c in skill_candidates if len(c['instincts']) >= 3 and c['avg_confidence'] >= 0.75]
1224
+ if agent_candidates:
1225
+ print(f"\n## AGENT CANDIDATES ({len(agent_candidates)})\n")
1226
+ for cand in agent_candidates[:3]:
1227
+ agent_name = cand['trigger'].replace(' ', '-')[:20] + '-agent'
1228
+ print(f" {agent_name}")
1229
+ print(f" Covers {len(cand['instincts'])} instincts")
1230
+ print(f" Avg confidence: {cand['avg_confidence']:.0%}")
1231
+ print()
1232
+
1233
+ # Promotion candidates (project instincts that could be global)
1234
+ _show_promotion_candidates(project)
1235
+
1236
+ if args.generate:
1237
+ evolved_dir = project["evolved_dir"] if project["id"] != "global" else GLOBAL_EVOLVED_DIR
1238
+ generated = _generate_evolved(skill_candidates, workflow_instincts, agent_candidates, evolved_dir)
1239
+ if generated:
1240
+ print(f"\nGenerated {len(generated)} evolved structures:")
1241
+ for path in generated:
1242
+ print(f" {path}")
1243
+ else:
1244
+ print("\nNo structures generated (need higher-confidence clusters).")
1245
+
1246
+ print(f"\n{'='*60}\n")
1247
+ return 0
1248
+
1249
+
1250
+ # ─────────────────────────────────────────────
1251
+ # Promote Command
1252
+ # ─────────────────────────────────────────────
1253
+
1254
+ def _find_cross_project_instincts() -> dict:
1255
+ """Find instincts that appear in multiple projects (promotion candidates).
1256
+
1257
+ Returns dict mapping instinct ID → list of (project_id, instinct) tuples.
1258
+ """
1259
+ registry = load_registry()
1260
+ cross_project = defaultdict(list)
1261
+
1262
+ for pid, pinfo in registry.items():
1263
+ project_dir = PROJECTS_DIR / pid
1264
+ personal_dir = project_dir / "instincts" / "personal"
1265
+ inherited_dir = project_dir / "instincts" / "inherited"
1266
+
1267
+ # Track instinct IDs already seen for this project to avoid counting
1268
+ # the same instinct twice within one project (e.g. in both personal/ and inherited/)
1269
+ seen_in_project = set()
1270
+ for d, stype in [(personal_dir, "personal"), (inherited_dir, "inherited")]:
1271
+ for inst in _load_instincts_from_dir(d, stype, "project"):
1272
+ iid = inst.get('id')
1273
+ if iid and iid not in seen_in_project:
1274
+ seen_in_project.add(iid)
1275
+ cross_project[iid].append((pid, pinfo.get('name', pid), inst))
1276
+
1277
+ # Filter to only those appearing in 2+ unique projects
1278
+ return {iid: entries for iid, entries in cross_project.items() if len(entries) >= 2}
1279
+
1280
+
1281
+ def _show_promotion_candidates(project: dict) -> None:
1282
+ """Show instincts that could be promoted from project to global."""
1283
+ cross = _find_cross_project_instincts()
1284
+
1285
+ if not cross:
1286
+ return
1287
+
1288
+ # Filter to high-confidence ones not already global
1289
+ global_instincts = _load_instincts_from_dir(GLOBAL_PERSONAL_DIR, "personal", "global")
1290
+ global_instincts += _load_instincts_from_dir(GLOBAL_INHERITED_DIR, "inherited", "global")
1291
+ global_ids = {i.get('id') for i in global_instincts}
1292
+
1293
+ candidates = []
1294
+ for iid, entries in cross.items():
1295
+ if iid in global_ids:
1296
+ continue
1297
+ avg_conf = sum(e[2].get('confidence', 0.5) for e in entries) / len(entries)
1298
+ if avg_conf >= PROMOTE_CONFIDENCE_THRESHOLD:
1299
+ candidates.append({
1300
+ 'id': iid,
1301
+ 'projects': [(pid, pname) for pid, pname, _ in entries],
1302
+ 'avg_confidence': avg_conf,
1303
+ 'sample': entries[0][2],
1304
+ })
1305
+
1306
+ if candidates:
1307
+ print(f"\n## PROMOTION CANDIDATES (project -> global)\n")
1308
+ print(f" These instincts appear in {PROMOTE_MIN_PROJECTS}+ projects with high confidence:\n")
1309
+ for cand in candidates[:10]:
1310
+ proj_names = ', '.join(pname for _, pname in cand['projects'])
1311
+ print(f" * {cand['id']} (avg: {cand['avg_confidence']:.0%})")
1312
+ print(f" Found in: {proj_names}")
1313
+ print()
1314
+ print(f" Run `instinct-cli.py promote` to promote these to global scope.\n")
1315
+
1316
+
1317
+ def cmd_promote(args) -> int:
1318
+ """Promote project-scoped instincts to global scope."""
1319
+ project = detect_project()
1320
+
1321
+ if args.instinct_id:
1322
+ # Promote a specific instinct
1323
+ return _promote_specific(project, args.instinct_id, args.force, args.dry_run)
1324
+ else:
1325
+ # Auto-detect promotion candidates
1326
+ return _promote_auto(project, args.force, args.dry_run)
1327
+
1328
+
1329
+ def _promote_specific(project: dict, instinct_id: str, force: bool, dry_run: bool = False) -> int:
1330
+ """Promote a specific instinct by ID from current project to global."""
1331
+ if not _validate_instinct_id(instinct_id):
1332
+ print(f"Invalid instinct ID: '{instinct_id}'.", file=sys.stderr)
1333
+ return 1
1334
+
1335
+ project_instincts = load_project_only_instincts(project)
1336
+ target = next((i for i in project_instincts if i.get('id') == instinct_id), None)
1337
+
1338
+ if not target:
1339
+ print(f"Instinct '{instinct_id}' not found in project {project['name']}.")
1340
+ return 1
1341
+
1342
+ # Check if already global
1343
+ global_instincts = _load_instincts_from_dir(GLOBAL_PERSONAL_DIR, "personal", "global")
1344
+ global_instincts += _load_instincts_from_dir(GLOBAL_INHERITED_DIR, "inherited", "global")
1345
+ if any(i.get('id') == instinct_id for i in global_instincts):
1346
+ print(f"Instinct '{instinct_id}' already exists in global scope.")
1347
+ return 1
1348
+
1349
+ print(f"\nPromoting: {instinct_id}")
1350
+ print(f" From: project '{project['name']}'")
1351
+ print(f" Confidence: {target.get('confidence', 0.5):.0%}")
1352
+ print(f" Domain: {target.get('domain', 'general')}")
1353
+
1354
+ if dry_run:
1355
+ print("\n[DRY RUN] No changes made.")
1356
+ return 0
1357
+
1358
+ if not force:
1359
+ response = input(f"\nPromote to global? [y/N] ")
1360
+ if response.lower() != 'y':
1361
+ print("Cancelled.")
1362
+ return 0
1363
+
1364
+ # Write to global personal directory
1365
+ output_file = GLOBAL_PERSONAL_DIR / f"{instinct_id}.yaml"
1366
+ output_content = "---\n"
1367
+ output_content += f"id: {target.get('id')}\n"
1368
+ output_content += f"trigger: {_yaml_quote(target.get('trigger', 'unknown'))}\n"
1369
+ output_content += f"confidence: {target.get('confidence', 0.5)}\n"
1370
+ output_content += f"domain: {target.get('domain', 'general')}\n"
1371
+ output_content += f"source: {target.get('source', 'promoted')}\n"
1372
+ output_content += f"scope: global\n"
1373
+ output_content += f"promoted_from: {project['id']}\n"
1374
+ output_content += f"promoted_date: {datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z')}\n"
1375
+ output_content += "---\n\n"
1376
+ output_content += target.get('content', '') + "\n"
1377
+
1378
+ output_file.write_text(output_content, encoding="utf-8")
1379
+ print(f"\nPromoted '{instinct_id}' to global scope.")
1380
+ print(f" Saved to: {output_file}")
1381
+ return 0
1382
+
1383
+
1384
+ def _promote_auto(project: dict, force: bool, dry_run: bool) -> int:
1385
+ """Auto-promote instincts found in multiple projects."""
1386
+ cross = _find_cross_project_instincts()
1387
+
1388
+ global_instincts = _load_instincts_from_dir(GLOBAL_PERSONAL_DIR, "personal", "global")
1389
+ global_instincts += _load_instincts_from_dir(GLOBAL_INHERITED_DIR, "inherited", "global")
1390
+ global_ids = {i.get('id') for i in global_instincts}
1391
+
1392
+ candidates = []
1393
+ for iid, entries in cross.items():
1394
+ if iid in global_ids:
1395
+ continue
1396
+ avg_conf = sum(e[2].get('confidence', 0.5) for e in entries) / len(entries)
1397
+ if avg_conf >= PROMOTE_CONFIDENCE_THRESHOLD and len(entries) >= PROMOTE_MIN_PROJECTS:
1398
+ candidates.append({
1399
+ 'id': iid,
1400
+ 'entries': entries,
1401
+ 'avg_confidence': avg_conf,
1402
+ })
1403
+
1404
+ if not candidates:
1405
+ print("No instincts qualify for auto-promotion.")
1406
+ print(f" Criteria: appears in {PROMOTE_MIN_PROJECTS}+ projects, avg confidence >= {PROMOTE_CONFIDENCE_THRESHOLD:.0%}")
1407
+ return 0
1408
+
1409
+ print(f"\n{'='*60}")
1410
+ print(f" AUTO-PROMOTION CANDIDATES - {len(candidates)} found")
1411
+ print(f"{'='*60}\n")
1412
+
1413
+ for cand in candidates:
1414
+ proj_names = ', '.join(pname for _, pname, _ in cand['entries'])
1415
+ print(f" {cand['id']} (avg: {cand['avg_confidence']:.0%})")
1416
+ print(f" Found in {len(cand['entries'])} projects: {proj_names}")
1417
+
1418
+ if dry_run:
1419
+ print(f"\n[DRY RUN] No changes made.")
1420
+ return 0
1421
+
1422
+ if not force:
1423
+ response = input(f"\nPromote {len(candidates)} instincts to global? [y/N] ")
1424
+ if response.lower() != 'y':
1425
+ print("Cancelled.")
1426
+ return 0
1427
+
1428
+ promoted = 0
1429
+ for cand in candidates:
1430
+ if not _validate_instinct_id(cand['id']):
1431
+ print(f"Skipping invalid instinct ID during promotion: {cand['id']}", file=sys.stderr)
1432
+ continue
1433
+
1434
+ # Use the highest-confidence version
1435
+ best_entry = max(cand['entries'], key=lambda e: e[2].get('confidence', 0.5))
1436
+ inst = best_entry[2]
1437
+
1438
+ output_file = GLOBAL_PERSONAL_DIR / f"{cand['id']}.yaml"
1439
+ output_content = "---\n"
1440
+ output_content += f"id: {inst.get('id')}\n"
1441
+ output_content += f"trigger: {_yaml_quote(inst.get('trigger', 'unknown'))}\n"
1442
+ output_content += f"confidence: {cand['avg_confidence']}\n"
1443
+ output_content += f"domain: {inst.get('domain', 'general')}\n"
1444
+ output_content += f"source: auto-promoted\n"
1445
+ output_content += f"scope: global\n"
1446
+ output_content += f"promoted_date: {datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z')}\n"
1447
+ output_content += f"seen_in_projects: {len(cand['entries'])}\n"
1448
+ output_content += "---\n\n"
1449
+ output_content += inst.get('content', '') + "\n"
1450
+
1451
+ output_file.write_text(output_content, encoding="utf-8")
1452
+ promoted += 1
1453
+
1454
+ print(f"\nPromoted {promoted} instincts to global scope.")
1455
+ return 0
1456
+
1457
+
1458
+ # ─────────────────────────────────────────────
1459
+ # Projects Command
1460
+ # ─────────────────────────────────────────────
1461
+
1462
+ def cmd_projects(args) -> int:
1463
+ """List or maintain known projects and their instinct counts."""
1464
+ if getattr(args, "project_action", None) == "delete":
1465
+ return _cmd_projects_delete(args)
1466
+ if getattr(args, "project_action", None) == "merge":
1467
+ return _cmd_projects_merge(args)
1468
+ if getattr(args, "project_action", None) == "gc":
1469
+ return _cmd_projects_gc(args)
1470
+
1471
+ registry = load_registry()
1472
+
1473
+ if not registry:
1474
+ print("No projects registered yet.")
1475
+ print("Projects are auto-detected when you use Claude Code in a git repo.")
1476
+ return 0
1477
+
1478
+ print(f"\n{'='*60}")
1479
+ print(f" KNOWN PROJECTS - {len(registry)} total")
1480
+ print(f"{'='*60}\n")
1481
+
1482
+ for pid, pinfo in sorted(registry.items(), key=lambda x: x[1].get('last_seen', ''), reverse=True):
1483
+ project_dir = PROJECTS_DIR / pid
1484
+ personal_dir = project_dir / "instincts" / "personal"
1485
+ inherited_dir = project_dir / "instincts" / "inherited"
1486
+
1487
+ personal_count = len(_load_instincts_from_dir(personal_dir, "personal", "project"))
1488
+ inherited_count = len(_load_instincts_from_dir(inherited_dir, "inherited", "project"))
1489
+ obs_file = project_dir / "observations.jsonl"
1490
+ if obs_file.exists():
1491
+ with open(obs_file, encoding="utf-8") as f:
1492
+ obs_count = sum(1 for _ in f)
1493
+ else:
1494
+ obs_count = 0
1495
+
1496
+ print(f" {pinfo.get('name', pid)} [{pid}]")
1497
+ print(f" Root: {pinfo.get('root', 'unknown')}")
1498
+ if pinfo.get('remote'):
1499
+ print(f" Remote: {pinfo['remote']}")
1500
+ print(f" Instincts: {personal_count} personal, {inherited_count} inherited")
1501
+ print(f" Observations: {obs_count} events")
1502
+ print(f" Last seen: {pinfo.get('last_seen', 'unknown')}")
1503
+ print()
1504
+
1505
+ # Global stats
1506
+ global_personal = len(_load_instincts_from_dir(GLOBAL_PERSONAL_DIR, "personal", "global"))
1507
+ global_inherited = len(_load_instincts_from_dir(GLOBAL_INHERITED_DIR, "inherited", "global"))
1508
+ print(f" GLOBAL")
1509
+ print(f" Instincts: {global_personal} personal, {global_inherited} inherited")
1510
+
1511
+ print(f"\n{'='*60}\n")
1512
+ return 0
1513
+
1514
+
1515
+ def _cmd_projects_delete(args) -> int:
1516
+ registry = load_registry()
1517
+ project_id = args.project_id
1518
+
1519
+ if not _validate_project_id(project_id):
1520
+ print(f"Invalid project ID: {project_id}", file=sys.stderr)
1521
+ return 1
1522
+ if project_id not in registry and not (PROJECTS_DIR / project_id).exists():
1523
+ print(f"Project '{project_id}' not found.", file=sys.stderr)
1524
+ return 1
1525
+
1526
+ counts = _project_counts(project_id)
1527
+ print(f"Project: {project_id}")
1528
+ print(f" Instincts: {counts['personal']} personal, {counts['inherited']} inherited")
1529
+ print(f" Observations: {counts['observations']} events")
1530
+
1531
+ if args.dry_run:
1532
+ print(f"\n[DRY RUN] Would delete project '{project_id}' from registry and storage.")
1533
+ return 0
1534
+
1535
+ if not args.force:
1536
+ if counts["total"] > 0:
1537
+ print("\nWarning: this project has instincts or observations.")
1538
+ response = input(f"Delete project '{project_id}'? [y/N] ")
1539
+ if response.lower() != "y":
1540
+ print("Cancelled.")
1541
+ return 0
1542
+
1543
+ registry.pop(project_id, None)
1544
+ _write_registry(registry)
1545
+ _remove_project_storage(project_id)
1546
+ print(f"\nDeleted project '{project_id}'.")
1547
+ return 0
1548
+
1549
+
1550
+ def _cmd_projects_gc(args) -> int:
1551
+ registry = load_registry()
1552
+ candidates = [
1553
+ project_id
1554
+ for project_id in sorted(registry)
1555
+ if _validate_project_id(project_id) and _project_counts(project_id)["total"] == 0
1556
+ ]
1557
+
1558
+ if not candidates:
1559
+ print("No zero-value project entries found.")
1560
+ return 0
1561
+
1562
+ print(f"Zero-value project entries: {len(candidates)}")
1563
+ for project_id in candidates:
1564
+ pinfo = registry.get(project_id, {})
1565
+ print(f" - {pinfo.get('name', project_id)} [{project_id}]")
1566
+
1567
+ if args.dry_run:
1568
+ print(f"\n[DRY RUN] Would delete {len(candidates)} project entr{'y' if len(candidates) == 1 else 'ies'}.")
1569
+ return 0
1570
+
1571
+ if not args.force:
1572
+ response = input(f"\nDelete {len(candidates)} zero-value project entr{'y' if len(candidates) == 1 else 'ies'}? [y/N] ")
1573
+ if response.lower() != "y":
1574
+ print("Cancelled.")
1575
+ return 0
1576
+
1577
+ for project_id in candidates:
1578
+ registry.pop(project_id, None)
1579
+ _remove_project_storage(project_id)
1580
+ _write_registry(registry)
1581
+ print(f"\nDeleted {len(candidates)} zero-value project entr{'y' if len(candidates) == 1 else 'ies'}.")
1582
+ return 0
1583
+
1584
+
1585
+ def _cmd_projects_merge(args) -> int:
1586
+ from_id = args.from_id
1587
+ into_id = args.into_id
1588
+
1589
+ if not _validate_project_id(from_id) or not _validate_project_id(into_id):
1590
+ print("Invalid project ID.", file=sys.stderr)
1591
+ return 1
1592
+ if from_id == into_id:
1593
+ print("Cannot merge a project into itself.", file=sys.stderr)
1594
+ return 1
1595
+
1596
+ registry = load_registry()
1597
+ if from_id not in registry:
1598
+ print(f"Source project '{from_id}' not found.", file=sys.stderr)
1599
+ return 1
1600
+ if into_id not in registry:
1601
+ print(f"Destination project '{into_id}' not found.", file=sys.stderr)
1602
+ return 1
1603
+
1604
+ from_counts = _project_counts(from_id)
1605
+ into_counts = _project_counts(into_id)
1606
+ print(f"Merge: {from_id} -> {into_id}")
1607
+ print(f" Source: {from_counts['personal']} personal, {from_counts['inherited']} inherited, {from_counts['observations']} observations")
1608
+ print(f" Destination before merge: {into_counts['personal']} personal, {into_counts['inherited']} inherited, {into_counts['observations']} observations")
1609
+
1610
+ if args.dry_run:
1611
+ print("\n[DRY RUN] Would merge source project into destination and remove source.")
1612
+ return 0
1613
+
1614
+ if not args.force:
1615
+ response = input(f"\nMerge '{from_id}' into '{into_id}' and remove source? [y/N] ")
1616
+ if response.lower() != "y":
1617
+ print("Cancelled.")
1618
+ return 0
1619
+
1620
+ from_project_dir = PROJECTS_DIR / from_id
1621
+ into_project_dir = PROJECTS_DIR / into_id
1622
+ into_project_dir.mkdir(parents=True, exist_ok=True)
1623
+
1624
+ personal_existing = _project_instinct_ids(into_project_dir, "personal")
1625
+ inherited_existing = _project_instinct_ids(into_project_dir, "inherited")
1626
+ personal_moved, personal_skipped = _merge_instinct_dir(
1627
+ from_project_dir / "instincts" / "personal",
1628
+ into_project_dir / "instincts" / "personal",
1629
+ personal_existing,
1630
+ )
1631
+ inherited_moved, inherited_skipped = _merge_instinct_dir(
1632
+ from_project_dir / "instincts" / "inherited",
1633
+ into_project_dir / "instincts" / "inherited",
1634
+ inherited_existing,
1635
+ )
1636
+ observations_moved = _append_observations(from_project_dir, into_project_dir)
1637
+
1638
+ registry.pop(from_id, None)
1639
+ destination = registry.get(into_id, {})
1640
+ destination["last_seen"] = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
1641
+ registry[into_id] = destination
1642
+ _write_registry(registry)
1643
+ _remove_project_storage(from_id)
1644
+
1645
+ print("\nMerged project registry entry.")
1646
+ print(f" Moved instincts: {personal_moved + inherited_moved}")
1647
+ print(f" Skipped duplicate instincts: {personal_skipped + inherited_skipped}")
1648
+ print(f" Appended observations: {observations_moved}")
1649
+ return 0
1650
+
1651
+
1652
+ # ─────────────────────────────────────────────
1653
+ # Generate Evolved Structures
1654
+ # ─────────────────────────────────────────────
1655
+
1656
+ def _generate_evolved(skill_candidates: list, workflow_instincts: list, agent_candidates: list, evolved_dir: Path) -> list[str]:
1657
+ """Generate skill/command/agent files from analyzed instinct clusters."""
1658
+ generated = []
1659
+
1660
+ # Generate skills from top candidates
1661
+ for cand in skill_candidates[:5]:
1662
+ trigger = cand['trigger'].strip()
1663
+ if not trigger:
1664
+ continue
1665
+ name = re.sub(r'[^a-z0-9]+', '-', trigger.lower()).strip('-')[:30]
1666
+ if not name:
1667
+ continue
1668
+
1669
+ skill_dir = evolved_dir / "skills" / name
1670
+ skill_dir.mkdir(parents=True, exist_ok=True)
1671
+
1672
+ content = f"# {name}\n\n"
1673
+ content += f"Evolved from {len(cand['instincts'])} instincts "
1674
+ content += f"(avg confidence: {cand['avg_confidence']:.0%})\n\n"
1675
+ content += f"## When to Apply\n\n"
1676
+ content += f"Trigger: {trigger}\n\n"
1677
+ content += f"## Actions\n\n"
1678
+ for inst in cand['instincts']:
1679
+ inst_content = inst.get('content', '')
1680
+ action_match = re.search(r'## Action\s*\n\s*(.+?)(?:\n\n|\n##|$)', inst_content, re.DOTALL)
1681
+ action = action_match.group(1).strip() if action_match else inst.get('id', 'unnamed')
1682
+ content += f"- {action}\n"
1683
+
1684
+ (skill_dir / "SKILL.md").write_text(content, encoding="utf-8")
1685
+ generated.append(str(skill_dir / "SKILL.md"))
1686
+
1687
+ # Generate commands from workflow instincts
1688
+ for inst in workflow_instincts[:5]:
1689
+ trigger = inst.get('trigger', 'unknown')
1690
+ cmd_name = re.sub(r'[^a-z0-9]+', '-', trigger.lower().replace('when ', '').replace('implementing ', ''))
1691
+ cmd_name = cmd_name.strip('-')[:20]
1692
+ if not cmd_name:
1693
+ continue
1694
+
1695
+ cmd_file = evolved_dir / "commands" / f"{cmd_name}.md"
1696
+ content = f"# {cmd_name}\n\n"
1697
+ content += f"Evolved from instinct: {inst.get('id', 'unnamed')}\n"
1698
+ content += f"Confidence: {inst.get('confidence', 0.5):.0%}\n\n"
1699
+ content += inst.get('content', '')
1700
+
1701
+ cmd_file.write_text(content, encoding="utf-8")
1702
+ generated.append(str(cmd_file))
1703
+
1704
+ # Generate agents from complex clusters
1705
+ for cand in agent_candidates[:3]:
1706
+ trigger = cand['trigger'].strip()
1707
+ agent_name = re.sub(r'[^a-z0-9]+', '-', trigger.lower()).strip('-')[:20]
1708
+ if not agent_name:
1709
+ continue
1710
+
1711
+ agent_file = evolved_dir / "agents" / f"{agent_name}.md"
1712
+ domains = ', '.join(cand['domains'])
1713
+ instinct_ids = [i.get('id', 'unnamed') for i in cand['instincts']]
1714
+
1715
+ content = f"---\nmodel: sonnet\ntools: Read, Grep, Glob\n---\n"
1716
+ content += f"# {agent_name}\n\n"
1717
+ content += f"Evolved from {len(cand['instincts'])} instincts "
1718
+ content += f"(avg confidence: {cand['avg_confidence']:.0%})\n"
1719
+ content += f"Domains: {domains}\n\n"
1720
+ content += f"## Source Instincts\n\n"
1721
+ for iid in instinct_ids:
1722
+ content += f"- {iid}\n"
1723
+
1724
+ agent_file.write_text(content, encoding="utf-8")
1725
+ generated.append(str(agent_file))
1726
+
1727
+ return generated
1728
+
1729
+
1730
+ # ─────────────────────────────────────────────
1731
+ # Pending Instinct Helpers
1732
+ # ─────────────────────────────────────────────
1733
+
1734
+ def _collect_pending_dirs() -> list[Path]:
1735
+ """Return all pending instinct directories (global + per-project)."""
1736
+ dirs = []
1737
+ global_pending = GLOBAL_INSTINCTS_DIR / "pending"
1738
+ if global_pending.is_dir():
1739
+ dirs.append(global_pending)
1740
+ if PROJECTS_DIR.is_dir():
1741
+ for project_dir in sorted(PROJECTS_DIR.iterdir()):
1742
+ if project_dir.is_dir():
1743
+ pending = project_dir / "instincts" / "pending"
1744
+ if pending.is_dir():
1745
+ dirs.append(pending)
1746
+ return dirs
1747
+
1748
+
1749
+ def _parse_created_date(file_path: Path) -> Optional[datetime]:
1750
+ """Parse the 'created' date from YAML frontmatter of an instinct file.
1751
+
1752
+ Falls back to file mtime if no 'created' field is found.
1753
+ """
1754
+ try:
1755
+ content = file_path.read_text(encoding="utf-8")
1756
+ except (OSError, UnicodeDecodeError):
1757
+ return None
1758
+
1759
+ in_frontmatter = False
1760
+ for line in content.split('\n'):
1761
+ stripped = line.strip()
1762
+ if stripped == '---':
1763
+ if in_frontmatter:
1764
+ break # end of frontmatter without finding created
1765
+ in_frontmatter = True
1766
+ continue
1767
+ if in_frontmatter and ':' in line:
1768
+ key, value = line.split(':', 1)
1769
+ if key.strip() == 'created':
1770
+ date_str = value.strip().strip('"').strip("'")
1771
+ for fmt in (
1772
+ "%Y-%m-%dT%H:%M:%S%z",
1773
+ "%Y-%m-%dT%H:%M:%SZ",
1774
+ "%Y-%m-%dT%H:%M:%S",
1775
+ "%Y-%m-%d",
1776
+ ):
1777
+ try:
1778
+ dt = datetime.strptime(date_str, fmt)
1779
+ if dt.tzinfo is None:
1780
+ dt = dt.replace(tzinfo=timezone.utc)
1781
+ return dt
1782
+ except ValueError:
1783
+ continue
1784
+
1785
+ # Fallback: file modification time
1786
+ try:
1787
+ mtime = file_path.stat().st_mtime
1788
+ return datetime.fromtimestamp(mtime, tz=timezone.utc)
1789
+ except OSError:
1790
+ return None
1791
+
1792
+
1793
+ def _collect_pending_instincts() -> list[dict]:
1794
+ """Scan all pending directories and return info about each pending instinct.
1795
+
1796
+ Each dict contains: path, created, age_days, name, parent_dir.
1797
+ """
1798
+ now = datetime.now(timezone.utc)
1799
+ results = []
1800
+ for pending_dir in _collect_pending_dirs():
1801
+ files = [
1802
+ f for f in sorted(pending_dir.iterdir())
1803
+ if f.is_file() and f.suffix.lower() in ALLOWED_INSTINCT_EXTENSIONS
1804
+ ]
1805
+ for file_path in files:
1806
+ created = _parse_created_date(file_path)
1807
+ if created is None:
1808
+ print(f"Warning: could not parse age for pending instinct: {file_path.name}", file=sys.stderr)
1809
+ continue
1810
+ age = now - created
1811
+ results.append({
1812
+ "path": file_path,
1813
+ "created": created,
1814
+ "age_days": age.days,
1815
+ "name": file_path.stem,
1816
+ "parent_dir": str(pending_dir),
1817
+ })
1818
+ return results
1819
+
1820
+
1821
+ # ─────────────────────────────────────────────
1822
+ # Prune Command
1823
+ # ─────────────────────────────────────────────
1824
+
1825
+ def cmd_prune(args) -> int:
1826
+ """Delete pending instincts older than the TTL threshold."""
1827
+ max_age = args.max_age
1828
+ dry_run = args.dry_run
1829
+ quiet = args.quiet
1830
+
1831
+ pending = _collect_pending_instincts()
1832
+
1833
+ expired = [p for p in pending if p["age_days"] >= max_age]
1834
+ remaining = [p for p in pending if p["age_days"] < max_age]
1835
+
1836
+ if dry_run:
1837
+ if not quiet:
1838
+ if expired:
1839
+ print(f"\n[DRY RUN] Would prune {len(expired)} pending instinct(s) older than {max_age} days:\n")
1840
+ for item in expired:
1841
+ print(f" - {item['name']} (age: {item['age_days']}d) — {item['path']}")
1842
+ else:
1843
+ print(f"No pending instincts older than {max_age} days.")
1844
+ print(f"\nSummary: {len(expired)} would be pruned, {len(remaining)} remaining")
1845
+ return 0
1846
+
1847
+ pruned = 0
1848
+ pruned_items = []
1849
+ for item in expired:
1850
+ try:
1851
+ item["path"].unlink()
1852
+ pruned += 1
1853
+ pruned_items.append(item)
1854
+ except OSError as e:
1855
+ if not quiet:
1856
+ print(f"Warning: Failed to delete {item['path']}: {e}", file=sys.stderr)
1857
+
1858
+ if not quiet:
1859
+ if pruned > 0:
1860
+ print(f"\nPruned {pruned} pending instinct(s) older than {max_age} days.")
1861
+ for item in pruned_items:
1862
+ print(f" - {item['name']} (age: {item['age_days']}d)")
1863
+ else:
1864
+ print(f"No pending instincts older than {max_age} days.")
1865
+ failed = len(expired) - pruned
1866
+ remaining_total = len(remaining) + failed
1867
+ print(f"\nSummary: {pruned} pruned, {remaining_total} remaining")
1868
+
1869
+ return 0
1870
+
1871
+
1872
+ # ─────────────────────────────────────────────
1873
+ # Main
1874
+ # ─────────────────────────────────────────────
1875
+
1876
+ def main() -> int:
1877
+ _ensure_global_dirs()
1878
+ parser = argparse.ArgumentParser(description='Instinct CLI for Continuous Learning v2.1 (Project-Scoped)')
1879
+ subparsers = parser.add_subparsers(dest='command', help='Available commands')
1880
+
1881
+ # Status
1882
+ status_parser = subparsers.add_parser('status', help='Show instinct status (project + global)')
1883
+
1884
+ # Import
1885
+ import_parser = subparsers.add_parser('import', help='Import instincts')
1886
+ import_parser.add_argument('source', help='File path or URL')
1887
+ import_parser.add_argument('--dry-run', action='store_true', help='Preview without importing')
1888
+ import_parser.add_argument('--force', action='store_true', help='Skip confirmation')
1889
+ import_parser.add_argument('--min-confidence', type=float, help='Minimum confidence threshold')
1890
+ import_parser.add_argument('--scope', choices=['project', 'global'], default='project',
1891
+ help='Import scope (default: project)')
1892
+
1893
+ # Export
1894
+ export_parser = subparsers.add_parser('export', help='Export instincts')
1895
+ export_parser.add_argument('--output', '-o', help='Output file')
1896
+ export_parser.add_argument('--domain', help='Filter by domain')
1897
+ export_parser.add_argument('--min-confidence', type=float, help='Minimum confidence')
1898
+ export_parser.add_argument('--scope', choices=['project', 'global', 'all'], default='all',
1899
+ help='Export scope (default: all)')
1900
+
1901
+ # Evolve
1902
+ evolve_parser = subparsers.add_parser('evolve', help='Analyze and evolve instincts')
1903
+ evolve_parser.add_argument('--generate', action='store_true', help='Generate evolved structures')
1904
+
1905
+ # Promote (new in v2.1)
1906
+ promote_parser = subparsers.add_parser('promote', help='Promote project instincts to global scope')
1907
+ promote_parser.add_argument('instinct_id', nargs='?', help='Specific instinct ID to promote')
1908
+ promote_parser.add_argument('--force', action='store_true', help='Skip confirmation')
1909
+ promote_parser.add_argument('--dry-run', action='store_true', help='Preview without promoting')
1910
+
1911
+ # Projects (new in v2.1)
1912
+ projects_parser = subparsers.add_parser('projects', help='List known projects and instinct counts')
1913
+ projects_subparsers = projects_parser.add_subparsers(dest='project_action')
1914
+ projects_delete = projects_subparsers.add_parser('delete', help='Delete a project registry entry')
1915
+ projects_delete.add_argument('project_id', help='Project ID to delete')
1916
+ projects_delete.add_argument('--dry-run', action='store_true', help='Preview without deleting')
1917
+ projects_delete.add_argument('--force', action='store_true', help='Skip confirmation')
1918
+ projects_merge = projects_subparsers.add_parser('merge', help='Merge one project registry entry into another')
1919
+ projects_merge.add_argument('from_id', help='Source project ID')
1920
+ projects_merge.add_argument('into_id', help='Destination project ID')
1921
+ projects_merge.add_argument('--dry-run', action='store_true', help='Preview without merging')
1922
+ projects_merge.add_argument('--force', action='store_true', help='Skip confirmation')
1923
+ projects_gc = projects_subparsers.add_parser('gc', help='Delete zero-value project registry entries')
1924
+ projects_gc.add_argument('--dry-run', action='store_true', help='Preview without deleting')
1925
+ projects_gc.add_argument('--force', action='store_true', help='Skip confirmation')
1926
+
1927
+ # Prune (pending instinct TTL)
1928
+ prune_parser = subparsers.add_parser('prune', help='Delete pending instincts older than TTL')
1929
+ prune_parser.add_argument('--max-age', type=int, default=PENDING_TTL_DAYS,
1930
+ help=f'Max age in days before pruning (default: {PENDING_TTL_DAYS})')
1931
+ prune_parser.add_argument('--dry-run', action='store_true', help='Preview without deleting')
1932
+ prune_parser.add_argument('--quiet', action='store_true', help='Suppress output (for automated use)')
1933
+
1934
+ args = parser.parse_args()
1935
+
1936
+ if args.command == 'status':
1937
+ return cmd_status(args)
1938
+ elif args.command == 'import':
1939
+ return cmd_import(args)
1940
+ elif args.command == 'export':
1941
+ return cmd_export(args)
1942
+ elif args.command == 'evolve':
1943
+ return cmd_evolve(args)
1944
+ elif args.command == 'promote':
1945
+ return cmd_promote(args)
1946
+ elif args.command == 'projects':
1947
+ return cmd_projects(args)
1948
+ elif args.command == 'prune':
1949
+ return cmd_prune(args)
1950
+ else:
1951
+ parser.print_help()
1952
+ return 1
1953
+
1954
+
1955
+ if __name__ == '__main__':
1956
+ sys.exit(main())