ctxora 6.2.2 → 6.3.0

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