@funnycode/myclaude 0.1.55 → 0.1.60

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