@heytherevibin/skillforge 0.2.1

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