agim-cli 1.2.147 → 1.2.148

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