claude-code-pilot 2.0.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 (257) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +151 -0
  3. package/bin/install.js +431 -0
  4. package/docs/agent-guides/architecture.md +107 -0
  5. package/ecc/agents/architect.md +211 -0
  6. package/ecc/agents/code-reviewer.md +237 -0
  7. package/ecc/agents/doc-updater.md +107 -0
  8. package/ecc/agents/e2e-runner.md +107 -0
  9. package/ecc/agents/security-reviewer.md +108 -0
  10. package/ecc/agents/tdd-guide.md +91 -0
  11. package/ecc/commands/checkpoint.md +74 -0
  12. package/ecc/commands/evolve.md +178 -0
  13. package/ecc/commands/learn.md +70 -0
  14. package/ecc/commands/model-route.md +26 -0
  15. package/ecc/commands/quality-gate.md +29 -0
  16. package/ecc/commands/resume-session.md +155 -0
  17. package/ecc/commands/save-session.md +275 -0
  18. package/ecc/commands/sessions.md +305 -0
  19. package/ecc/commands/verify.md +59 -0
  20. package/ecc/contexts/dev.md +20 -0
  21. package/ecc/contexts/research.md +26 -0
  22. package/ecc/contexts/review.md +22 -0
  23. package/ecc/examples/CLAUDE.md +100 -0
  24. package/ecc/examples/django-api-CLAUDE.md +308 -0
  25. package/ecc/examples/go-microservice-CLAUDE.md +267 -0
  26. package/ecc/examples/rust-api-CLAUDE.md +285 -0
  27. package/ecc/examples/saas-nextjs-CLAUDE.md +166 -0
  28. package/ecc/examples/user-CLAUDE.md +109 -0
  29. package/ecc/rules/common/agents.md +49 -0
  30. package/ecc/rules/common/coding-style.md +48 -0
  31. package/ecc/rules/common/development-workflow.md +37 -0
  32. package/ecc/rules/common/git-workflow.md +24 -0
  33. package/ecc/rules/common/hooks.md +30 -0
  34. package/ecc/rules/common/patterns.md +31 -0
  35. package/ecc/rules/common/performance.md +55 -0
  36. package/ecc/rules/common/security.md +29 -0
  37. package/ecc/rules/common/testing.md +29 -0
  38. package/ecc/rules/golang/coding-style.md +32 -0
  39. package/ecc/rules/golang/hooks.md +17 -0
  40. package/ecc/rules/golang/patterns.md +45 -0
  41. package/ecc/rules/golang/security.md +34 -0
  42. package/ecc/rules/golang/testing.md +31 -0
  43. package/ecc/rules/kotlin/coding-style.md +86 -0
  44. package/ecc/rules/kotlin/patterns.md +146 -0
  45. package/ecc/rules/kotlin/security.md +82 -0
  46. package/ecc/rules/kotlin/testing.md +128 -0
  47. package/ecc/rules/perl/coding-style.md +46 -0
  48. package/ecc/rules/perl/hooks.md +22 -0
  49. package/ecc/rules/perl/patterns.md +76 -0
  50. package/ecc/rules/perl/security.md +69 -0
  51. package/ecc/rules/perl/testing.md +54 -0
  52. package/ecc/rules/php/coding-style.md +35 -0
  53. package/ecc/rules/php/hooks.md +24 -0
  54. package/ecc/rules/php/patterns.md +32 -0
  55. package/ecc/rules/php/security.md +33 -0
  56. package/ecc/rules/php/testing.md +34 -0
  57. package/ecc/rules/python/coding-style.md +42 -0
  58. package/ecc/rules/python/hooks.md +19 -0
  59. package/ecc/rules/python/patterns.md +39 -0
  60. package/ecc/rules/python/security.md +30 -0
  61. package/ecc/rules/python/testing.md +38 -0
  62. package/ecc/rules/swift/coding-style.md +47 -0
  63. package/ecc/rules/swift/hooks.md +20 -0
  64. package/ecc/rules/swift/patterns.md +66 -0
  65. package/ecc/rules/swift/security.md +33 -0
  66. package/ecc/rules/swift/testing.md +45 -0
  67. package/ecc/rules/typescript/coding-style.md +199 -0
  68. package/ecc/rules/typescript/hooks.md +22 -0
  69. package/ecc/rules/typescript/patterns.md +52 -0
  70. package/ecc/rules/typescript/security.md +28 -0
  71. package/ecc/rules/typescript/testing.md +18 -0
  72. package/ecc/scripts/hooks/check-hook-enabled.js +12 -0
  73. package/ecc/scripts/hooks/evaluate-session.js +100 -0
  74. package/ecc/scripts/hooks/pre-compact.js +48 -0
  75. package/ecc/scripts/hooks/run-with-flags-shell.sh +32 -0
  76. package/ecc/scripts/hooks/run-with-flags.js +120 -0
  77. package/ecc/scripts/hooks/session-end-marker.js +15 -0
  78. package/ecc/scripts/hooks/session-end.js +258 -0
  79. package/ecc/scripts/hooks/session-start.js +97 -0
  80. package/ecc/scripts/hooks/suggest-compact.js +80 -0
  81. package/ecc/scripts/lib/hook-flags.js +74 -0
  82. package/ecc/scripts/lib/package-manager.d.ts +119 -0
  83. package/ecc/scripts/lib/package-manager.js +431 -0
  84. package/ecc/scripts/lib/project-detect.js +428 -0
  85. package/ecc/scripts/lib/resolve-formatter.js +185 -0
  86. package/ecc/scripts/lib/session-aliases.d.ts +136 -0
  87. package/ecc/scripts/lib/session-aliases.js +481 -0
  88. package/ecc/scripts/lib/session-manager.d.ts +131 -0
  89. package/ecc/scripts/lib/session-manager.js +444 -0
  90. package/ecc/scripts/lib/shell-split.js +86 -0
  91. package/ecc/scripts/lib/utils.d.ts +183 -0
  92. package/ecc/scripts/lib/utils.js +543 -0
  93. package/ecc/skills/continuous-learning-v2/SKILL.md +365 -0
  94. package/ecc/skills/continuous-learning-v2/agents/observer-loop.sh +144 -0
  95. package/ecc/skills/continuous-learning-v2/agents/observer.md +198 -0
  96. package/ecc/skills/continuous-learning-v2/agents/start-observer.sh +194 -0
  97. package/ecc/skills/continuous-learning-v2/config.json +8 -0
  98. package/ecc/skills/continuous-learning-v2/hooks/observe.sh +246 -0
  99. package/ecc/skills/continuous-learning-v2/scripts/detect-project.sh +218 -0
  100. package/ecc/skills/continuous-learning-v2/scripts/instinct-cli.py +1148 -0
  101. package/ecc/skills/continuous-learning-v2/scripts/test_parse_instinct.py +984 -0
  102. package/ecc/skills/strategic-compact/SKILL.md +103 -0
  103. package/ecc/skills/strategic-compact/suggest-compact.sh +54 -0
  104. package/ecc/skills/verification-loop-SKILL.md +126 -0
  105. package/gsd/LICENSE +21 -0
  106. package/gsd/agents/gsd-codebase-mapper.md +772 -0
  107. package/gsd/agents/gsd-debugger.md +1257 -0
  108. package/gsd/agents/gsd-executor.md +489 -0
  109. package/gsd/agents/gsd-integration-checker.md +445 -0
  110. package/gsd/agents/gsd-nyquist-auditor.md +178 -0
  111. package/gsd/agents/gsd-phase-researcher.md +555 -0
  112. package/gsd/agents/gsd-plan-checker.md +708 -0
  113. package/gsd/agents/gsd-planner.md +1309 -0
  114. package/gsd/agents/gsd-project-researcher.md +631 -0
  115. package/gsd/agents/gsd-research-synthesizer.md +249 -0
  116. package/gsd/agents/gsd-roadmapper.md +652 -0
  117. package/gsd/agents/gsd-verifier.md +581 -0
  118. package/gsd/commands-gsd/add-phase.md +43 -0
  119. package/gsd/commands-gsd/add-tests.md +41 -0
  120. package/gsd/commands-gsd/add-todo.md +47 -0
  121. package/gsd/commands-gsd/audit-milestone.md +36 -0
  122. package/gsd/commands-gsd/check-todos.md +45 -0
  123. package/gsd/commands-gsd/cleanup.md +18 -0
  124. package/gsd/commands-gsd/complete-milestone.md +136 -0
  125. package/gsd/commands-gsd/debug.md +168 -0
  126. package/gsd/commands-gsd/discuss-phase.md +90 -0
  127. package/gsd/commands-gsd/execute-phase.md +41 -0
  128. package/gsd/commands-gsd/health.md +22 -0
  129. package/gsd/commands-gsd/help.md +22 -0
  130. package/gsd/commands-gsd/insert-phase.md +32 -0
  131. package/gsd/commands-gsd/join-discord.md +18 -0
  132. package/gsd/commands-gsd/list-phase-assumptions.md +46 -0
  133. package/gsd/commands-gsd/map-codebase.md +71 -0
  134. package/gsd/commands-gsd/new-milestone.md +44 -0
  135. package/gsd/commands-gsd/new-project.md +42 -0
  136. package/gsd/commands-gsd/pause-work.md +38 -0
  137. package/gsd/commands-gsd/plan-milestone-gaps.md +34 -0
  138. package/gsd/commands-gsd/plan-phase.md +45 -0
  139. package/gsd/commands-gsd/progress.md +24 -0
  140. package/gsd/commands-gsd/quick.md +45 -0
  141. package/gsd/commands-gsd/reapply-patches.md +123 -0
  142. package/gsd/commands-gsd/remove-phase.md +31 -0
  143. package/gsd/commands-gsd/research-phase.md +190 -0
  144. package/gsd/commands-gsd/resume-work.md +40 -0
  145. package/gsd/commands-gsd/set-profile.md +34 -0
  146. package/gsd/commands-gsd/settings.md +36 -0
  147. package/gsd/commands-gsd/update.md +37 -0
  148. package/gsd/commands-gsd/validate-phase.md +35 -0
  149. package/gsd/commands-gsd/verify-work.md +38 -0
  150. package/gsd/get-shit-done/bin/gsd-tools.cjs +592 -0
  151. package/gsd/get-shit-done/bin/lib/commands.cjs +548 -0
  152. package/gsd/get-shit-done/bin/lib/config.cjs +169 -0
  153. package/gsd/get-shit-done/bin/lib/core.cjs +492 -0
  154. package/gsd/get-shit-done/bin/lib/frontmatter.cjs +299 -0
  155. package/gsd/get-shit-done/bin/lib/init.cjs +710 -0
  156. package/gsd/get-shit-done/bin/lib/milestone.cjs +241 -0
  157. package/gsd/get-shit-done/bin/lib/phase.cjs +901 -0
  158. package/gsd/get-shit-done/bin/lib/roadmap.cjs +298 -0
  159. package/gsd/get-shit-done/bin/lib/state.cjs +721 -0
  160. package/gsd/get-shit-done/bin/lib/template.cjs +222 -0
  161. package/gsd/get-shit-done/bin/lib/verify.cjs +820 -0
  162. package/gsd/get-shit-done/references/checkpoints.md +776 -0
  163. package/gsd/get-shit-done/references/continuation-format.md +249 -0
  164. package/gsd/get-shit-done/references/decimal-phase-calculation.md +65 -0
  165. package/gsd/get-shit-done/references/git-integration.md +248 -0
  166. package/gsd/get-shit-done/references/git-planning-commit.md +38 -0
  167. package/gsd/get-shit-done/references/model-profile-resolution.md +34 -0
  168. package/gsd/get-shit-done/references/model-profiles.md +93 -0
  169. package/gsd/get-shit-done/references/phase-argument-parsing.md +61 -0
  170. package/gsd/get-shit-done/references/planning-config.md +200 -0
  171. package/gsd/get-shit-done/references/questioning.md +162 -0
  172. package/gsd/get-shit-done/references/tdd.md +263 -0
  173. package/gsd/get-shit-done/references/ui-brand.md +160 -0
  174. package/gsd/get-shit-done/references/verification-patterns.md +612 -0
  175. package/gsd/get-shit-done/templates/DEBUG.md +164 -0
  176. package/gsd/get-shit-done/templates/UAT.md +247 -0
  177. package/gsd/get-shit-done/templates/VALIDATION.md +76 -0
  178. package/gsd/get-shit-done/templates/codebase/architecture.md +255 -0
  179. package/gsd/get-shit-done/templates/codebase/concerns.md +310 -0
  180. package/gsd/get-shit-done/templates/codebase/conventions.md +307 -0
  181. package/gsd/get-shit-done/templates/codebase/integrations.md +280 -0
  182. package/gsd/get-shit-done/templates/codebase/stack.md +186 -0
  183. package/gsd/get-shit-done/templates/codebase/structure.md +285 -0
  184. package/gsd/get-shit-done/templates/codebase/testing.md +480 -0
  185. package/gsd/get-shit-done/templates/config.json +37 -0
  186. package/gsd/get-shit-done/templates/context.md +297 -0
  187. package/gsd/get-shit-done/templates/continue-here.md +78 -0
  188. package/gsd/get-shit-done/templates/debug-subagent-prompt.md +91 -0
  189. package/gsd/get-shit-done/templates/discovery.md +146 -0
  190. package/gsd/get-shit-done/templates/milestone-archive.md +123 -0
  191. package/gsd/get-shit-done/templates/milestone.md +115 -0
  192. package/gsd/get-shit-done/templates/phase-prompt.md +569 -0
  193. package/gsd/get-shit-done/templates/planner-subagent-prompt.md +117 -0
  194. package/gsd/get-shit-done/templates/project.md +184 -0
  195. package/gsd/get-shit-done/templates/requirements.md +231 -0
  196. package/gsd/get-shit-done/templates/research-project/ARCHITECTURE.md +204 -0
  197. package/gsd/get-shit-done/templates/research-project/FEATURES.md +147 -0
  198. package/gsd/get-shit-done/templates/research-project/PITFALLS.md +200 -0
  199. package/gsd/get-shit-done/templates/research-project/STACK.md +120 -0
  200. package/gsd/get-shit-done/templates/research-project/SUMMARY.md +170 -0
  201. package/gsd/get-shit-done/templates/research.md +552 -0
  202. package/gsd/get-shit-done/templates/retrospective.md +54 -0
  203. package/gsd/get-shit-done/templates/roadmap.md +202 -0
  204. package/gsd/get-shit-done/templates/state.md +176 -0
  205. package/gsd/get-shit-done/templates/summary-complex.md +59 -0
  206. package/gsd/get-shit-done/templates/summary-minimal.md +41 -0
  207. package/gsd/get-shit-done/templates/summary-standard.md +48 -0
  208. package/gsd/get-shit-done/templates/summary.md +248 -0
  209. package/gsd/get-shit-done/templates/user-setup.md +311 -0
  210. package/gsd/get-shit-done/templates/verification-report.md +322 -0
  211. package/gsd/get-shit-done/workflows/add-phase.md +112 -0
  212. package/gsd/get-shit-done/workflows/add-tests.md +351 -0
  213. package/gsd/get-shit-done/workflows/add-todo.md +158 -0
  214. package/gsd/get-shit-done/workflows/audit-milestone.md +332 -0
  215. package/gsd/get-shit-done/workflows/check-todos.md +177 -0
  216. package/gsd/get-shit-done/workflows/cleanup.md +152 -0
  217. package/gsd/get-shit-done/workflows/complete-milestone.md +764 -0
  218. package/gsd/get-shit-done/workflows/diagnose-issues.md +219 -0
  219. package/gsd/get-shit-done/workflows/discovery-phase.md +289 -0
  220. package/gsd/get-shit-done/workflows/discuss-phase.md +676 -0
  221. package/gsd/get-shit-done/workflows/execute-phase.md +459 -0
  222. package/gsd/get-shit-done/workflows/execute-plan.md +449 -0
  223. package/gsd/get-shit-done/workflows/health.md +159 -0
  224. package/gsd/get-shit-done/workflows/help.md +489 -0
  225. package/gsd/get-shit-done/workflows/insert-phase.md +130 -0
  226. package/gsd/get-shit-done/workflows/list-phase-assumptions.md +178 -0
  227. package/gsd/get-shit-done/workflows/map-codebase.md +316 -0
  228. package/gsd/get-shit-done/workflows/new-milestone.md +384 -0
  229. package/gsd/get-shit-done/workflows/new-project.md +1111 -0
  230. package/gsd/get-shit-done/workflows/pause-work.md +122 -0
  231. package/gsd/get-shit-done/workflows/plan-milestone-gaps.md +274 -0
  232. package/gsd/get-shit-done/workflows/plan-phase.md +560 -0
  233. package/gsd/get-shit-done/workflows/progress.md +382 -0
  234. package/gsd/get-shit-done/workflows/quick.md +601 -0
  235. package/gsd/get-shit-done/workflows/remove-phase.md +155 -0
  236. package/gsd/get-shit-done/workflows/research-phase.md +74 -0
  237. package/gsd/get-shit-done/workflows/resume-project.md +307 -0
  238. package/gsd/get-shit-done/workflows/set-profile.md +81 -0
  239. package/gsd/get-shit-done/workflows/settings.md +214 -0
  240. package/gsd/get-shit-done/workflows/transition.md +544 -0
  241. package/gsd/get-shit-done/workflows/update.md +240 -0
  242. package/gsd/get-shit-done/workflows/validate-phase.md +167 -0
  243. package/gsd/get-shit-done/workflows/verify-phase.md +243 -0
  244. package/gsd/get-shit-done/workflows/verify-work.md +583 -0
  245. package/gsd/hooks/gsd-check-update.js +81 -0
  246. package/gsd/hooks/gsd-context-monitor.js +141 -0
  247. package/gsd/hooks/gsd-statusline.js +115 -0
  248. package/kit/CLAUDE.md +43 -0
  249. package/kit/commands/kit/update.md +46 -0
  250. package/kit/commands/setup-refresh.md +50 -0
  251. package/kit/commands/setup.md +579 -0
  252. package/kit/commands/tool-guide.md +44 -0
  253. package/kit/hooks/kit-check-update.js +54 -0
  254. package/kit/mcp.json +10 -0
  255. package/kit/rules/code-style.md +24 -0
  256. package/manifest.json +30 -0
  257. package/package.json +36 -0
@@ -0,0 +1,1148 @@
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
+ """
16
+
17
+ import argparse
18
+ import json
19
+ import hashlib
20
+ import os
21
+ import subprocess
22
+ import sys
23
+ import re
24
+ import urllib.request
25
+ from pathlib import Path
26
+ from datetime import datetime, timezone
27
+ from collections import defaultdict
28
+ from typing import Optional
29
+
30
+ # ─────────────────────────────────────────────
31
+ # Configuration
32
+ # ─────────────────────────────────────────────
33
+
34
+ HOMUNCULUS_DIR = Path.home() / ".claude" / "homunculus"
35
+ PROJECTS_DIR = HOMUNCULUS_DIR / "projects"
36
+ REGISTRY_FILE = HOMUNCULUS_DIR / "projects.json"
37
+
38
+ # Global (non-project-scoped) paths
39
+ GLOBAL_INSTINCTS_DIR = HOMUNCULUS_DIR / "instincts"
40
+ GLOBAL_PERSONAL_DIR = GLOBAL_INSTINCTS_DIR / "personal"
41
+ GLOBAL_INHERITED_DIR = GLOBAL_INSTINCTS_DIR / "inherited"
42
+ GLOBAL_EVOLVED_DIR = HOMUNCULUS_DIR / "evolved"
43
+ GLOBAL_OBSERVATIONS_FILE = HOMUNCULUS_DIR / "observations.jsonl"
44
+
45
+ # Thresholds for auto-promotion
46
+ PROMOTE_CONFIDENCE_THRESHOLD = 0.8
47
+ PROMOTE_MIN_PROJECTS = 2
48
+ ALLOWED_INSTINCT_EXTENSIONS = (".yaml", ".yml", ".md")
49
+
50
+ # Ensure global directories exist (deferred to avoid side effects at import time)
51
+ def _ensure_global_dirs():
52
+ for d in [GLOBAL_PERSONAL_DIR, GLOBAL_INHERITED_DIR,
53
+ GLOBAL_EVOLVED_DIR / "skills", GLOBAL_EVOLVED_DIR / "commands", GLOBAL_EVOLVED_DIR / "agents",
54
+ PROJECTS_DIR]:
55
+ d.mkdir(parents=True, exist_ok=True)
56
+
57
+
58
+ # ─────────────────────────────────────────────
59
+ # Path Validation
60
+ # ─────────────────────────────────────────────
61
+
62
+ def _validate_file_path(path_str: str, must_exist: bool = False) -> Path:
63
+ """Validate and resolve a file path, guarding against path traversal.
64
+
65
+ Raises ValueError if the path is invalid or suspicious.
66
+ """
67
+ path = Path(path_str).expanduser().resolve()
68
+
69
+ # Block paths that escape into system directories
70
+ # We block specific system paths but allow temp dirs (/var/folders on macOS)
71
+ blocked_prefixes = [
72
+ "/etc", "/usr", "/bin", "/sbin", "/proc", "/sys",
73
+ "/var/log", "/var/run", "/var/lib", "/var/spool",
74
+ # macOS resolves /etc → /private/etc
75
+ "/private/etc",
76
+ "/private/var/log", "/private/var/run", "/private/var/db",
77
+ ]
78
+ path_s = str(path)
79
+ for prefix in blocked_prefixes:
80
+ if path_s.startswith(prefix + "/") or path_s == prefix:
81
+ raise ValueError(f"Path '{path}' targets a system directory")
82
+
83
+ if must_exist and not path.exists():
84
+ raise ValueError(f"Path does not exist: {path}")
85
+
86
+ return path
87
+
88
+
89
+ def _validate_instinct_id(instinct_id: str) -> bool:
90
+ """Validate instinct IDs before using them in filenames."""
91
+ if not instinct_id or len(instinct_id) > 128:
92
+ return False
93
+ if "/" in instinct_id or "\\" in instinct_id:
94
+ return False
95
+ if ".." in instinct_id:
96
+ return False
97
+ if instinct_id.startswith("."):
98
+ return False
99
+ return bool(re.match(r"^[A-Za-z0-9][A-Za-z0-9._-]*$", instinct_id))
100
+
101
+
102
+ # ─────────────────────────────────────────────
103
+ # Project Detection (Python equivalent of detect-project.sh)
104
+ # ─────────────────────────────────────────────
105
+
106
+ def detect_project() -> dict:
107
+ """Detect current project context. Returns dict with id, name, root, project_dir."""
108
+ project_root = None
109
+
110
+ # 1. CLAUDE_PROJECT_DIR env var
111
+ env_dir = os.environ.get("CLAUDE_PROJECT_DIR")
112
+ if env_dir and os.path.isdir(env_dir):
113
+ project_root = env_dir
114
+
115
+ # 2. git repo root
116
+ if not project_root:
117
+ try:
118
+ result = subprocess.run(
119
+ ["git", "rev-parse", "--show-toplevel"],
120
+ capture_output=True, text=True, timeout=5
121
+ )
122
+ if result.returncode == 0:
123
+ project_root = result.stdout.strip()
124
+ except (subprocess.TimeoutExpired, FileNotFoundError):
125
+ pass
126
+
127
+ # 3. No project — global fallback
128
+ if not project_root:
129
+ return {
130
+ "id": "global",
131
+ "name": "global",
132
+ "root": "",
133
+ "project_dir": HOMUNCULUS_DIR,
134
+ "instincts_personal": GLOBAL_PERSONAL_DIR,
135
+ "instincts_inherited": GLOBAL_INHERITED_DIR,
136
+ "evolved_dir": GLOBAL_EVOLVED_DIR,
137
+ "observations_file": GLOBAL_OBSERVATIONS_FILE,
138
+ }
139
+
140
+ project_name = os.path.basename(project_root)
141
+
142
+ # Derive project ID from git remote URL or path
143
+ remote_url = ""
144
+ try:
145
+ result = subprocess.run(
146
+ ["git", "-C", project_root, "remote", "get-url", "origin"],
147
+ capture_output=True, text=True, timeout=5
148
+ )
149
+ if result.returncode == 0:
150
+ remote_url = result.stdout.strip()
151
+ except (subprocess.TimeoutExpired, FileNotFoundError):
152
+ pass
153
+
154
+ hash_source = remote_url if remote_url else project_root
155
+ project_id = hashlib.sha256(hash_source.encode()).hexdigest()[:12]
156
+
157
+ project_dir = PROJECTS_DIR / project_id
158
+
159
+ # Ensure project directory structure
160
+ for d in [
161
+ project_dir / "instincts" / "personal",
162
+ project_dir / "instincts" / "inherited",
163
+ project_dir / "observations.archive",
164
+ project_dir / "evolved" / "skills",
165
+ project_dir / "evolved" / "commands",
166
+ project_dir / "evolved" / "agents",
167
+ ]:
168
+ d.mkdir(parents=True, exist_ok=True)
169
+
170
+ # Update registry
171
+ _update_registry(project_id, project_name, project_root, remote_url)
172
+
173
+ return {
174
+ "id": project_id,
175
+ "name": project_name,
176
+ "root": project_root,
177
+ "remote": remote_url,
178
+ "project_dir": project_dir,
179
+ "instincts_personal": project_dir / "instincts" / "personal",
180
+ "instincts_inherited": project_dir / "instincts" / "inherited",
181
+ "evolved_dir": project_dir / "evolved",
182
+ "observations_file": project_dir / "observations.jsonl",
183
+ }
184
+
185
+
186
+ def _update_registry(pid: str, pname: str, proot: str, premote: str) -> None:
187
+ """Update the projects.json registry."""
188
+ try:
189
+ with open(REGISTRY_FILE, encoding="utf-8") as f:
190
+ registry = json.load(f)
191
+ except (FileNotFoundError, json.JSONDecodeError):
192
+ registry = {}
193
+
194
+ registry[pid] = {
195
+ "name": pname,
196
+ "root": proot,
197
+ "remote": premote,
198
+ "last_seen": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
199
+ }
200
+
201
+ REGISTRY_FILE.parent.mkdir(parents=True, exist_ok=True)
202
+ tmp_file = REGISTRY_FILE.parent / f".{REGISTRY_FILE.name}.tmp.{os.getpid()}"
203
+ with open(tmp_file, "w", encoding="utf-8") as f:
204
+ json.dump(registry, f, indent=2)
205
+ f.flush()
206
+ os.fsync(f.fileno())
207
+ os.replace(tmp_file, REGISTRY_FILE)
208
+
209
+
210
+ def load_registry() -> dict:
211
+ """Load the projects registry."""
212
+ try:
213
+ with open(REGISTRY_FILE, encoding="utf-8") as f:
214
+ return json.load(f)
215
+ except (FileNotFoundError, json.JSONDecodeError):
216
+ return {}
217
+
218
+
219
+ # ─────────────────────────────────────────────
220
+ # Instinct Parser
221
+ # ─────────────────────────────────────────────
222
+
223
+ def parse_instinct_file(content: str) -> list[dict]:
224
+ """Parse YAML-like instinct file format."""
225
+ instincts = []
226
+ current = {}
227
+ in_frontmatter = False
228
+ content_lines = []
229
+
230
+ for line in content.split('\n'):
231
+ if line.strip() == '---':
232
+ if in_frontmatter:
233
+ # End of frontmatter - content comes next, don't append yet
234
+ in_frontmatter = False
235
+ else:
236
+ # Start of frontmatter
237
+ in_frontmatter = True
238
+ if current:
239
+ current['content'] = '\n'.join(content_lines).strip()
240
+ instincts.append(current)
241
+ current = {}
242
+ content_lines = []
243
+ elif in_frontmatter:
244
+ # Parse YAML-like frontmatter
245
+ if ':' in line:
246
+ key, value = line.split(':', 1)
247
+ key = key.strip()
248
+ value = value.strip().strip('"').strip("'")
249
+ if key == 'confidence':
250
+ current[key] = float(value)
251
+ else:
252
+ current[key] = value
253
+ else:
254
+ content_lines.append(line)
255
+
256
+ # Don't forget the last instinct
257
+ if current:
258
+ current['content'] = '\n'.join(content_lines).strip()
259
+ instincts.append(current)
260
+
261
+ return [i for i in instincts if i.get('id')]
262
+
263
+
264
+ def _load_instincts_from_dir(directory: Path, source_type: str, scope_label: str) -> list[dict]:
265
+ """Load instincts from a single directory."""
266
+ instincts = []
267
+ if not directory.exists():
268
+ return instincts
269
+ files = [
270
+ file for file in sorted(directory.iterdir())
271
+ if file.is_file() and file.suffix.lower() in ALLOWED_INSTINCT_EXTENSIONS
272
+ ]
273
+ for file in files:
274
+ try:
275
+ content = file.read_text(encoding="utf-8")
276
+ parsed = parse_instinct_file(content)
277
+ for inst in parsed:
278
+ inst['_source_file'] = str(file)
279
+ inst['_source_type'] = source_type
280
+ inst['_scope_label'] = scope_label
281
+ # Default scope if not set in frontmatter
282
+ if 'scope' not in inst:
283
+ inst['scope'] = scope_label
284
+ instincts.extend(parsed)
285
+ except Exception as e:
286
+ print(f"Warning: Failed to parse {file}: {e}", file=sys.stderr)
287
+ return instincts
288
+
289
+
290
+ def load_all_instincts(project: dict, include_global: bool = True) -> list[dict]:
291
+ """Load all instincts: project-scoped + global.
292
+
293
+ Project-scoped instincts take precedence over global ones when IDs conflict.
294
+ """
295
+ instincts = []
296
+
297
+ # 1. Load project-scoped instincts (if not already global)
298
+ if project["id"] != "global":
299
+ instincts.extend(_load_instincts_from_dir(
300
+ project["instincts_personal"], "personal", "project"
301
+ ))
302
+ instincts.extend(_load_instincts_from_dir(
303
+ project["instincts_inherited"], "inherited", "project"
304
+ ))
305
+
306
+ # 2. Load global instincts
307
+ if include_global:
308
+ global_instincts = []
309
+ global_instincts.extend(_load_instincts_from_dir(
310
+ GLOBAL_PERSONAL_DIR, "personal", "global"
311
+ ))
312
+ global_instincts.extend(_load_instincts_from_dir(
313
+ GLOBAL_INHERITED_DIR, "inherited", "global"
314
+ ))
315
+
316
+ # Deduplicate: project-scoped wins over global when same ID
317
+ project_ids = {i.get('id') for i in instincts}
318
+ for gi in global_instincts:
319
+ if gi.get('id') not in project_ids:
320
+ instincts.append(gi)
321
+
322
+ return instincts
323
+
324
+
325
+ def load_project_only_instincts(project: dict) -> list[dict]:
326
+ """Load only project-scoped instincts (no global).
327
+
328
+ In global fallback mode (no git project), returns global instincts.
329
+ """
330
+ if project.get("id") == "global":
331
+ instincts = _load_instincts_from_dir(GLOBAL_PERSONAL_DIR, "personal", "global")
332
+ instincts += _load_instincts_from_dir(GLOBAL_INHERITED_DIR, "inherited", "global")
333
+ return instincts
334
+ return load_all_instincts(project, include_global=False)
335
+
336
+
337
+ # ─────────────────────────────────────────────
338
+ # Status Command
339
+ # ─────────────────────────────────────────────
340
+
341
+ def cmd_status(args) -> int:
342
+ """Show status of all instincts (project + global)."""
343
+ project = detect_project()
344
+ instincts = load_all_instincts(project)
345
+
346
+ if not instincts:
347
+ print("No instincts found.")
348
+ print(f"\nProject: {project['name']} ({project['id']})")
349
+ print(f" Project instincts: {project['instincts_personal']}")
350
+ print(f" Global instincts: {GLOBAL_PERSONAL_DIR}")
351
+ return 0
352
+
353
+ # Split by scope
354
+ project_instincts = [i for i in instincts if i.get('_scope_label') == 'project']
355
+ global_instincts = [i for i in instincts if i.get('_scope_label') == 'global']
356
+
357
+ # Print header
358
+ print(f"\n{'='*60}")
359
+ print(f" INSTINCT STATUS - {len(instincts)} total")
360
+ print(f"{'='*60}\n")
361
+
362
+ print(f" Project: {project['name']} ({project['id']})")
363
+ print(f" Project instincts: {len(project_instincts)}")
364
+ print(f" Global instincts: {len(global_instincts)}")
365
+ print()
366
+
367
+ # Print project-scoped instincts
368
+ if project_instincts:
369
+ print(f"## PROJECT-SCOPED ({project['name']})")
370
+ print()
371
+ _print_instincts_by_domain(project_instincts)
372
+
373
+ # Print global instincts
374
+ if global_instincts:
375
+ print(f"## GLOBAL (apply to all projects)")
376
+ print()
377
+ _print_instincts_by_domain(global_instincts)
378
+
379
+ # Observations stats
380
+ obs_file = project.get("observations_file")
381
+ if obs_file and Path(obs_file).exists():
382
+ with open(obs_file, encoding="utf-8") as f:
383
+ obs_count = sum(1 for _ in f)
384
+ print(f"-" * 60)
385
+ print(f" Observations: {obs_count} events logged")
386
+ print(f" File: {obs_file}")
387
+
388
+ print(f"\n{'='*60}\n")
389
+ return 0
390
+
391
+
392
+ def _print_instincts_by_domain(instincts: list[dict]) -> None:
393
+ """Helper to print instincts grouped by domain."""
394
+ by_domain = defaultdict(list)
395
+ for inst in instincts:
396
+ domain = inst.get('domain', 'general')
397
+ by_domain[domain].append(inst)
398
+
399
+ for domain in sorted(by_domain.keys()):
400
+ domain_instincts = by_domain[domain]
401
+ print(f" ### {domain.upper()} ({len(domain_instincts)})")
402
+ print()
403
+
404
+ for inst in sorted(domain_instincts, key=lambda x: -x.get('confidence', 0.5)):
405
+ conf = inst.get('confidence', 0.5)
406
+ conf_bar = '\u2588' * int(conf * 10) + '\u2591' * (10 - int(conf * 10))
407
+ trigger = inst.get('trigger', 'unknown trigger')
408
+ scope_tag = f"[{inst.get('scope', '?')}]"
409
+
410
+ print(f" {conf_bar} {int(conf*100):3d}% {inst.get('id', 'unnamed')} {scope_tag}")
411
+ print(f" trigger: {trigger}")
412
+
413
+ # Extract action from content
414
+ content = inst.get('content', '')
415
+ action_match = re.search(r'## Action\s*\n\s*(.+?)(?:\n\n|\n##|$)', content, re.DOTALL)
416
+ if action_match:
417
+ action = action_match.group(1).strip().split('\n')[0]
418
+ print(f" action: {action[:60]}{'...' if len(action) > 60 else ''}")
419
+
420
+ print()
421
+
422
+
423
+ # ─────────────────────────────────────────────
424
+ # Import Command
425
+ # ─────────────────────────────────────────────
426
+
427
+ def cmd_import(args) -> int:
428
+ """Import instincts from file or URL."""
429
+ project = detect_project()
430
+ source = args.source
431
+
432
+ # Determine target scope
433
+ target_scope = args.scope or "project"
434
+ if target_scope == "project" and project["id"] == "global":
435
+ print("No project detected. Importing as global scope.")
436
+ target_scope = "global"
437
+
438
+ # Fetch content
439
+ if source.startswith('http://') or source.startswith('https://'):
440
+ print(f"Fetching from URL: {source}")
441
+ try:
442
+ with urllib.request.urlopen(source) as response:
443
+ content = response.read().decode('utf-8')
444
+ except Exception as e:
445
+ print(f"Error fetching URL: {e}", file=sys.stderr)
446
+ return 1
447
+ else:
448
+ try:
449
+ path = _validate_file_path(source, must_exist=True)
450
+ except ValueError as e:
451
+ print(f"Invalid path: {e}", file=sys.stderr)
452
+ return 1
453
+ content = path.read_text(encoding="utf-8")
454
+
455
+ # Parse instincts
456
+ new_instincts = parse_instinct_file(content)
457
+ if not new_instincts:
458
+ print("No valid instincts found in source.")
459
+ return 1
460
+
461
+ print(f"\nFound {len(new_instincts)} instincts to import.")
462
+ print(f"Target scope: {target_scope}")
463
+ if target_scope == "project":
464
+ print(f"Target project: {project['name']} ({project['id']})")
465
+ print()
466
+
467
+ # Load existing instincts for dedup
468
+ existing = load_all_instincts(project)
469
+ existing_ids = {i.get('id') for i in existing}
470
+
471
+ # Categorize
472
+ to_add = []
473
+ duplicates = []
474
+ to_update = []
475
+
476
+ for inst in new_instincts:
477
+ inst_id = inst.get('id')
478
+ if inst_id in existing_ids:
479
+ existing_inst = next((e for e in existing if e.get('id') == inst_id), None)
480
+ if existing_inst:
481
+ if inst.get('confidence', 0) > existing_inst.get('confidence', 0):
482
+ to_update.append(inst)
483
+ else:
484
+ duplicates.append(inst)
485
+ else:
486
+ to_add.append(inst)
487
+
488
+ # Filter by minimum confidence
489
+ min_conf = args.min_confidence if args.min_confidence is not None else 0.0
490
+ to_add = [i for i in to_add if i.get('confidence', 0.5) >= min_conf]
491
+ to_update = [i for i in to_update if i.get('confidence', 0.5) >= min_conf]
492
+
493
+ # Display summary
494
+ if to_add:
495
+ print(f"NEW ({len(to_add)}):")
496
+ for inst in to_add:
497
+ print(f" + {inst.get('id')} (confidence: {inst.get('confidence', 0.5):.2f})")
498
+
499
+ if to_update:
500
+ print(f"\nUPDATE ({len(to_update)}):")
501
+ for inst in to_update:
502
+ print(f" ~ {inst.get('id')} (confidence: {inst.get('confidence', 0.5):.2f})")
503
+
504
+ if duplicates:
505
+ print(f"\nSKIP ({len(duplicates)} - already exists with equal/higher confidence):")
506
+ for inst in duplicates[:5]:
507
+ print(f" - {inst.get('id')}")
508
+ if len(duplicates) > 5:
509
+ print(f" ... and {len(duplicates) - 5} more")
510
+
511
+ if args.dry_run:
512
+ print("\n[DRY RUN] No changes made.")
513
+ return 0
514
+
515
+ if not to_add and not to_update:
516
+ print("\nNothing to import.")
517
+ return 0
518
+
519
+ # Confirm
520
+ if not args.force:
521
+ response = input(f"\nImport {len(to_add)} new, update {len(to_update)}? [y/N] ")
522
+ if response.lower() != 'y':
523
+ print("Cancelled.")
524
+ return 0
525
+
526
+ # Determine output directory based on scope
527
+ if target_scope == "global":
528
+ output_dir = GLOBAL_INHERITED_DIR
529
+ else:
530
+ output_dir = project["instincts_inherited"]
531
+
532
+ output_dir.mkdir(parents=True, exist_ok=True)
533
+
534
+ # Write
535
+ timestamp = datetime.now().strftime('%Y%m%d-%H%M%S')
536
+ source_name = Path(source).stem if not source.startswith('http') else 'web-import'
537
+ output_file = output_dir / f"{source_name}-{timestamp}.yaml"
538
+
539
+ all_to_write = to_add + to_update
540
+ output_content = f"# Imported from {source}\n# Date: {datetime.now().isoformat()}\n# Scope: {target_scope}\n"
541
+ if target_scope == "project":
542
+ output_content += f"# Project: {project['name']} ({project['id']})\n"
543
+ output_content += "\n"
544
+
545
+ for inst in all_to_write:
546
+ output_content += "---\n"
547
+ output_content += f"id: {inst.get('id')}\n"
548
+ output_content += f"trigger: \"{inst.get('trigger', 'unknown')}\"\n"
549
+ output_content += f"confidence: {inst.get('confidence', 0.5)}\n"
550
+ output_content += f"domain: {inst.get('domain', 'general')}\n"
551
+ output_content += f"source: inherited\n"
552
+ output_content += f"scope: {target_scope}\n"
553
+ output_content += f"imported_from: \"{source}\"\n"
554
+ if target_scope == "project":
555
+ output_content += f"project_id: {project['id']}\n"
556
+ output_content += f"project_name: {project['name']}\n"
557
+ if inst.get('source_repo'):
558
+ output_content += f"source_repo: {inst.get('source_repo')}\n"
559
+ output_content += "---\n\n"
560
+ output_content += inst.get('content', '') + "\n\n"
561
+
562
+ output_file.write_text(output_content)
563
+
564
+ print(f"\nImport complete!")
565
+ print(f" Scope: {target_scope}")
566
+ print(f" Added: {len(to_add)}")
567
+ print(f" Updated: {len(to_update)}")
568
+ print(f" Saved to: {output_file}")
569
+
570
+ return 0
571
+
572
+
573
+ # ─────────────────────────────────────────────
574
+ # Export Command
575
+ # ─────────────────────────────────────────────
576
+
577
+ def cmd_export(args) -> int:
578
+ """Export instincts to file."""
579
+ project = detect_project()
580
+
581
+ # Determine what to export based on scope filter
582
+ if args.scope == "project":
583
+ instincts = load_project_only_instincts(project)
584
+ elif args.scope == "global":
585
+ instincts = _load_instincts_from_dir(GLOBAL_PERSONAL_DIR, "personal", "global")
586
+ instincts += _load_instincts_from_dir(GLOBAL_INHERITED_DIR, "inherited", "global")
587
+ else:
588
+ instincts = load_all_instincts(project)
589
+
590
+ if not instincts:
591
+ print("No instincts to export.")
592
+ return 1
593
+
594
+ # Filter by domain if specified
595
+ if args.domain:
596
+ instincts = [i for i in instincts if i.get('domain') == args.domain]
597
+
598
+ # Filter by minimum confidence
599
+ if args.min_confidence:
600
+ instincts = [i for i in instincts if i.get('confidence', 0.5) >= args.min_confidence]
601
+
602
+ if not instincts:
603
+ print("No instincts match the criteria.")
604
+ return 1
605
+
606
+ # Generate output
607
+ output = f"# Instincts export\n# Date: {datetime.now().isoformat()}\n# Total: {len(instincts)}\n"
608
+ if args.scope:
609
+ output += f"# Scope: {args.scope}\n"
610
+ if project["id"] != "global":
611
+ output += f"# Project: {project['name']} ({project['id']})\n"
612
+ output += "\n"
613
+
614
+ for inst in instincts:
615
+ output += "---\n"
616
+ for key in ['id', 'trigger', 'confidence', 'domain', 'source', 'scope',
617
+ 'project_id', 'project_name', 'source_repo']:
618
+ if inst.get(key):
619
+ value = inst[key]
620
+ if key == 'trigger':
621
+ output += f'{key}: "{value}"\n'
622
+ else:
623
+ output += f"{key}: {value}\n"
624
+ output += "---\n\n"
625
+ output += inst.get('content', '') + "\n\n"
626
+
627
+ # Write to file or stdout
628
+ if args.output:
629
+ try:
630
+ out_path = _validate_file_path(args.output)
631
+ except ValueError as e:
632
+ print(f"Invalid output path: {e}", file=sys.stderr)
633
+ return 1
634
+ out_path.write_text(output)
635
+ print(f"Exported {len(instincts)} instincts to {out_path}")
636
+ else:
637
+ print(output)
638
+
639
+ return 0
640
+
641
+
642
+ # ─────────────────────────────────────────────
643
+ # Evolve Command
644
+ # ─────────────────────────────────────────────
645
+
646
+ def cmd_evolve(args) -> int:
647
+ """Analyze instincts and suggest evolutions to skills/commands/agents."""
648
+ project = detect_project()
649
+ instincts = load_all_instincts(project)
650
+
651
+ if len(instincts) < 3:
652
+ print("Need at least 3 instincts to analyze patterns.")
653
+ print(f"Currently have: {len(instincts)}")
654
+ return 1
655
+
656
+ project_instincts = [i for i in instincts if i.get('_scope_label') == 'project']
657
+ global_instincts = [i for i in instincts if i.get('_scope_label') == 'global']
658
+
659
+ print(f"\n{'='*60}")
660
+ print(f" EVOLVE ANALYSIS - {len(instincts)} instincts")
661
+ print(f" Project: {project['name']} ({project['id']})")
662
+ print(f" Project-scoped: {len(project_instincts)} | Global: {len(global_instincts)}")
663
+ print(f"{'='*60}\n")
664
+
665
+ # Group by domain
666
+ by_domain = defaultdict(list)
667
+ for inst in instincts:
668
+ domain = inst.get('domain', 'general')
669
+ by_domain[domain].append(inst)
670
+
671
+ # High-confidence instincts by domain (candidates for skills)
672
+ high_conf = [i for i in instincts if i.get('confidence', 0) >= 0.8]
673
+ print(f"High confidence instincts (>=80%): {len(high_conf)}")
674
+
675
+ # Find clusters (instincts with similar triggers)
676
+ trigger_clusters = defaultdict(list)
677
+ for inst in instincts:
678
+ trigger = inst.get('trigger', '')
679
+ # Normalize trigger
680
+ trigger_key = trigger.lower()
681
+ for keyword in ['when', 'creating', 'writing', 'adding', 'implementing', 'testing']:
682
+ trigger_key = trigger_key.replace(keyword, '').strip()
683
+ trigger_clusters[trigger_key].append(inst)
684
+
685
+ # Find clusters with 2+ instincts (good skill candidates)
686
+ skill_candidates = []
687
+ for trigger, cluster in trigger_clusters.items():
688
+ if len(cluster) >= 2:
689
+ avg_conf = sum(i.get('confidence', 0.5) for i in cluster) / len(cluster)
690
+ skill_candidates.append({
691
+ 'trigger': trigger,
692
+ 'instincts': cluster,
693
+ 'avg_confidence': avg_conf,
694
+ 'domains': list(set(i.get('domain', 'general') for i in cluster)),
695
+ 'scopes': list(set(i.get('scope', 'project') for i in cluster)),
696
+ })
697
+
698
+ # Sort by cluster size and confidence
699
+ skill_candidates.sort(key=lambda x: (-len(x['instincts']), -x['avg_confidence']))
700
+
701
+ print(f"\nPotential skill clusters found: {len(skill_candidates)}")
702
+
703
+ if skill_candidates:
704
+ print(f"\n## SKILL CANDIDATES\n")
705
+ for i, cand in enumerate(skill_candidates[:5], 1):
706
+ scope_info = ', '.join(cand['scopes'])
707
+ print(f"{i}. Cluster: \"{cand['trigger']}\"")
708
+ print(f" Instincts: {len(cand['instincts'])}")
709
+ print(f" Avg confidence: {cand['avg_confidence']:.0%}")
710
+ print(f" Domains: {', '.join(cand['domains'])}")
711
+ print(f" Scopes: {scope_info}")
712
+ print(f" Instincts:")
713
+ for inst in cand['instincts'][:3]:
714
+ print(f" - {inst.get('id')} [{inst.get('scope', '?')}]")
715
+ print()
716
+
717
+ # Command candidates (workflow instincts with high confidence)
718
+ workflow_instincts = [i for i in instincts if i.get('domain') == 'workflow' and i.get('confidence', 0) >= 0.7]
719
+ if workflow_instincts:
720
+ print(f"\n## COMMAND CANDIDATES ({len(workflow_instincts)})\n")
721
+ for inst in workflow_instincts[:5]:
722
+ trigger = inst.get('trigger', 'unknown')
723
+ cmd_name = trigger.replace('when ', '').replace('implementing ', '').replace('a ', '')
724
+ cmd_name = cmd_name.replace(' ', '-')[:20]
725
+ print(f" /{cmd_name}")
726
+ print(f" From: {inst.get('id')} [{inst.get('scope', '?')}]")
727
+ print(f" Confidence: {inst.get('confidence', 0.5):.0%}")
728
+ print()
729
+
730
+ # Agent candidates (complex multi-step patterns)
731
+ agent_candidates = [c for c in skill_candidates if len(c['instincts']) >= 3 and c['avg_confidence'] >= 0.75]
732
+ if agent_candidates:
733
+ print(f"\n## AGENT CANDIDATES ({len(agent_candidates)})\n")
734
+ for cand in agent_candidates[:3]:
735
+ agent_name = cand['trigger'].replace(' ', '-')[:20] + '-agent'
736
+ print(f" {agent_name}")
737
+ print(f" Covers {len(cand['instincts'])} instincts")
738
+ print(f" Avg confidence: {cand['avg_confidence']:.0%}")
739
+ print()
740
+
741
+ # Promotion candidates (project instincts that could be global)
742
+ _show_promotion_candidates(project)
743
+
744
+ if args.generate:
745
+ evolved_dir = project["evolved_dir"] if project["id"] != "global" else GLOBAL_EVOLVED_DIR
746
+ generated = _generate_evolved(skill_candidates, workflow_instincts, agent_candidates, evolved_dir)
747
+ if generated:
748
+ print(f"\nGenerated {len(generated)} evolved structures:")
749
+ for path in generated:
750
+ print(f" {path}")
751
+ else:
752
+ print("\nNo structures generated (need higher-confidence clusters).")
753
+
754
+ print(f"\n{'='*60}\n")
755
+ return 0
756
+
757
+
758
+ # ─────────────────────────────────────────────
759
+ # Promote Command
760
+ # ─────────────────────────────────────────────
761
+
762
+ def _find_cross_project_instincts() -> dict:
763
+ """Find instincts that appear in multiple projects (promotion candidates).
764
+
765
+ Returns dict mapping instinct ID → list of (project_id, instinct) tuples.
766
+ """
767
+ registry = load_registry()
768
+ cross_project = defaultdict(list)
769
+
770
+ for pid, pinfo in registry.items():
771
+ project_dir = PROJECTS_DIR / pid
772
+ personal_dir = project_dir / "instincts" / "personal"
773
+ inherited_dir = project_dir / "instincts" / "inherited"
774
+
775
+ for d, stype in [(personal_dir, "personal"), (inherited_dir, "inherited")]:
776
+ for inst in _load_instincts_from_dir(d, stype, "project"):
777
+ iid = inst.get('id')
778
+ if iid:
779
+ cross_project[iid].append((pid, pinfo.get('name', pid), inst))
780
+
781
+ # Filter to only those appearing in 2+ projects
782
+ return {iid: entries for iid, entries in cross_project.items() if len(entries) >= 2}
783
+
784
+
785
+ def _show_promotion_candidates(project: dict) -> None:
786
+ """Show instincts that could be promoted from project to global."""
787
+ cross = _find_cross_project_instincts()
788
+
789
+ if not cross:
790
+ return
791
+
792
+ # Filter to high-confidence ones not already global
793
+ global_instincts = _load_instincts_from_dir(GLOBAL_PERSONAL_DIR, "personal", "global")
794
+ global_instincts += _load_instincts_from_dir(GLOBAL_INHERITED_DIR, "inherited", "global")
795
+ global_ids = {i.get('id') for i in global_instincts}
796
+
797
+ candidates = []
798
+ for iid, entries in cross.items():
799
+ if iid in global_ids:
800
+ continue
801
+ avg_conf = sum(e[2].get('confidence', 0.5) for e in entries) / len(entries)
802
+ if avg_conf >= PROMOTE_CONFIDENCE_THRESHOLD:
803
+ candidates.append({
804
+ 'id': iid,
805
+ 'projects': [(pid, pname) for pid, pname, _ in entries],
806
+ 'avg_confidence': avg_conf,
807
+ 'sample': entries[0][2],
808
+ })
809
+
810
+ if candidates:
811
+ print(f"\n## PROMOTION CANDIDATES (project -> global)\n")
812
+ print(f" These instincts appear in {PROMOTE_MIN_PROJECTS}+ projects with high confidence:\n")
813
+ for cand in candidates[:10]:
814
+ proj_names = ', '.join(pname for _, pname in cand['projects'])
815
+ print(f" * {cand['id']} (avg: {cand['avg_confidence']:.0%})")
816
+ print(f" Found in: {proj_names}")
817
+ print()
818
+ print(f" Run `instinct-cli.py promote` to promote these to global scope.\n")
819
+
820
+
821
+ def cmd_promote(args) -> int:
822
+ """Promote project-scoped instincts to global scope."""
823
+ project = detect_project()
824
+
825
+ if args.instinct_id:
826
+ # Promote a specific instinct
827
+ return _promote_specific(project, args.instinct_id, args.force)
828
+ else:
829
+ # Auto-detect promotion candidates
830
+ return _promote_auto(project, args.force, args.dry_run)
831
+
832
+
833
+ def _promote_specific(project: dict, instinct_id: str, force: bool) -> int:
834
+ """Promote a specific instinct by ID from current project to global."""
835
+ if not _validate_instinct_id(instinct_id):
836
+ print(f"Invalid instinct ID: '{instinct_id}'.", file=sys.stderr)
837
+ return 1
838
+
839
+ project_instincts = load_project_only_instincts(project)
840
+ target = next((i for i in project_instincts if i.get('id') == instinct_id), None)
841
+
842
+ if not target:
843
+ print(f"Instinct '{instinct_id}' not found in project {project['name']}.")
844
+ return 1
845
+
846
+ # Check if already global
847
+ global_instincts = _load_instincts_from_dir(GLOBAL_PERSONAL_DIR, "personal", "global")
848
+ global_instincts += _load_instincts_from_dir(GLOBAL_INHERITED_DIR, "inherited", "global")
849
+ if any(i.get('id') == instinct_id for i in global_instincts):
850
+ print(f"Instinct '{instinct_id}' already exists in global scope.")
851
+ return 1
852
+
853
+ print(f"\nPromoting: {instinct_id}")
854
+ print(f" From: project '{project['name']}'")
855
+ print(f" Confidence: {target.get('confidence', 0.5):.0%}")
856
+ print(f" Domain: {target.get('domain', 'general')}")
857
+
858
+ if not force:
859
+ response = input(f"\nPromote to global? [y/N] ")
860
+ if response.lower() != 'y':
861
+ print("Cancelled.")
862
+ return 0
863
+
864
+ # Write to global personal directory
865
+ output_file = GLOBAL_PERSONAL_DIR / f"{instinct_id}.yaml"
866
+ output_content = "---\n"
867
+ output_content += f"id: {target.get('id')}\n"
868
+ output_content += f"trigger: \"{target.get('trigger', 'unknown')}\"\n"
869
+ output_content += f"confidence: {target.get('confidence', 0.5)}\n"
870
+ output_content += f"domain: {target.get('domain', 'general')}\n"
871
+ output_content += f"source: {target.get('source', 'promoted')}\n"
872
+ output_content += f"scope: global\n"
873
+ output_content += f"promoted_from: {project['id']}\n"
874
+ output_content += f"promoted_date: {datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z')}\n"
875
+ output_content += "---\n\n"
876
+ output_content += target.get('content', '') + "\n"
877
+
878
+ output_file.write_text(output_content)
879
+ print(f"\nPromoted '{instinct_id}' to global scope.")
880
+ print(f" Saved to: {output_file}")
881
+ return 0
882
+
883
+
884
+ def _promote_auto(project: dict, force: bool, dry_run: bool) -> int:
885
+ """Auto-promote instincts found in multiple projects."""
886
+ cross = _find_cross_project_instincts()
887
+
888
+ global_instincts = _load_instincts_from_dir(GLOBAL_PERSONAL_DIR, "personal", "global")
889
+ global_instincts += _load_instincts_from_dir(GLOBAL_INHERITED_DIR, "inherited", "global")
890
+ global_ids = {i.get('id') for i in global_instincts}
891
+
892
+ candidates = []
893
+ for iid, entries in cross.items():
894
+ if iid in global_ids:
895
+ continue
896
+ avg_conf = sum(e[2].get('confidence', 0.5) for e in entries) / len(entries)
897
+ if avg_conf >= PROMOTE_CONFIDENCE_THRESHOLD and len(entries) >= PROMOTE_MIN_PROJECTS:
898
+ candidates.append({
899
+ 'id': iid,
900
+ 'entries': entries,
901
+ 'avg_confidence': avg_conf,
902
+ })
903
+
904
+ if not candidates:
905
+ print("No instincts qualify for auto-promotion.")
906
+ print(f" Criteria: appears in {PROMOTE_MIN_PROJECTS}+ projects, avg confidence >= {PROMOTE_CONFIDENCE_THRESHOLD:.0%}")
907
+ return 0
908
+
909
+ print(f"\n{'='*60}")
910
+ print(f" AUTO-PROMOTION CANDIDATES - {len(candidates)} found")
911
+ print(f"{'='*60}\n")
912
+
913
+ for cand in candidates:
914
+ proj_names = ', '.join(pname for _, pname, _ in cand['entries'])
915
+ print(f" {cand['id']} (avg: {cand['avg_confidence']:.0%})")
916
+ print(f" Found in {len(cand['entries'])} projects: {proj_names}")
917
+
918
+ if dry_run:
919
+ print(f"\n[DRY RUN] No changes made.")
920
+ return 0
921
+
922
+ if not force:
923
+ response = input(f"\nPromote {len(candidates)} instincts to global? [y/N] ")
924
+ if response.lower() != 'y':
925
+ print("Cancelled.")
926
+ return 0
927
+
928
+ promoted = 0
929
+ for cand in candidates:
930
+ if not _validate_instinct_id(cand['id']):
931
+ print(f"Skipping invalid instinct ID during promotion: {cand['id']}", file=sys.stderr)
932
+ continue
933
+
934
+ # Use the highest-confidence version
935
+ best_entry = max(cand['entries'], key=lambda e: e[2].get('confidence', 0.5))
936
+ inst = best_entry[2]
937
+
938
+ output_file = GLOBAL_PERSONAL_DIR / f"{cand['id']}.yaml"
939
+ output_content = "---\n"
940
+ output_content += f"id: {inst.get('id')}\n"
941
+ output_content += f"trigger: \"{inst.get('trigger', 'unknown')}\"\n"
942
+ output_content += f"confidence: {cand['avg_confidence']}\n"
943
+ output_content += f"domain: {inst.get('domain', 'general')}\n"
944
+ output_content += f"source: auto-promoted\n"
945
+ output_content += f"scope: global\n"
946
+ output_content += f"promoted_date: {datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z')}\n"
947
+ output_content += f"seen_in_projects: {len(cand['entries'])}\n"
948
+ output_content += "---\n\n"
949
+ output_content += inst.get('content', '') + "\n"
950
+
951
+ output_file.write_text(output_content)
952
+ promoted += 1
953
+
954
+ print(f"\nPromoted {promoted} instincts to global scope.")
955
+ return 0
956
+
957
+
958
+ # ─────────────────────────────────────────────
959
+ # Projects Command
960
+ # ─────────────────────────────────────────────
961
+
962
+ def cmd_projects(args) -> int:
963
+ """List all known projects and their instinct counts."""
964
+ registry = load_registry()
965
+
966
+ if not registry:
967
+ print("No projects registered yet.")
968
+ print("Projects are auto-detected when you use Claude Code in a git repo.")
969
+ return 0
970
+
971
+ print(f"\n{'='*60}")
972
+ print(f" KNOWN PROJECTS - {len(registry)} total")
973
+ print(f"{'='*60}\n")
974
+
975
+ for pid, pinfo in sorted(registry.items(), key=lambda x: x[1].get('last_seen', ''), reverse=True):
976
+ project_dir = PROJECTS_DIR / pid
977
+ personal_dir = project_dir / "instincts" / "personal"
978
+ inherited_dir = project_dir / "instincts" / "inherited"
979
+
980
+ personal_count = len(_load_instincts_from_dir(personal_dir, "personal", "project"))
981
+ inherited_count = len(_load_instincts_from_dir(inherited_dir, "inherited", "project"))
982
+ obs_file = project_dir / "observations.jsonl"
983
+ if obs_file.exists():
984
+ with open(obs_file, encoding="utf-8") as f:
985
+ obs_count = sum(1 for _ in f)
986
+ else:
987
+ obs_count = 0
988
+
989
+ print(f" {pinfo.get('name', pid)} [{pid}]")
990
+ print(f" Root: {pinfo.get('root', 'unknown')}")
991
+ if pinfo.get('remote'):
992
+ print(f" Remote: {pinfo['remote']}")
993
+ print(f" Instincts: {personal_count} personal, {inherited_count} inherited")
994
+ print(f" Observations: {obs_count} events")
995
+ print(f" Last seen: {pinfo.get('last_seen', 'unknown')}")
996
+ print()
997
+
998
+ # Global stats
999
+ global_personal = len(_load_instincts_from_dir(GLOBAL_PERSONAL_DIR, "personal", "global"))
1000
+ global_inherited = len(_load_instincts_from_dir(GLOBAL_INHERITED_DIR, "inherited", "global"))
1001
+ print(f" GLOBAL")
1002
+ print(f" Instincts: {global_personal} personal, {global_inherited} inherited")
1003
+
1004
+ print(f"\n{'='*60}\n")
1005
+ return 0
1006
+
1007
+
1008
+ # ─────────────────────────────────────────────
1009
+ # Generate Evolved Structures
1010
+ # ─────────────────────────────────────────────
1011
+
1012
+ def _generate_evolved(skill_candidates: list, workflow_instincts: list, agent_candidates: list, evolved_dir: Path) -> list[str]:
1013
+ """Generate skill/command/agent files from analyzed instinct clusters."""
1014
+ generated = []
1015
+
1016
+ # Generate skills from top candidates
1017
+ for cand in skill_candidates[:5]:
1018
+ trigger = cand['trigger'].strip()
1019
+ if not trigger:
1020
+ continue
1021
+ name = re.sub(r'[^a-z0-9]+', '-', trigger.lower()).strip('-')[:30]
1022
+ if not name:
1023
+ continue
1024
+
1025
+ skill_dir = evolved_dir / "skills" / name
1026
+ skill_dir.mkdir(parents=True, exist_ok=True)
1027
+
1028
+ content = f"# {name}\n\n"
1029
+ content += f"Evolved from {len(cand['instincts'])} instincts "
1030
+ content += f"(avg confidence: {cand['avg_confidence']:.0%})\n\n"
1031
+ content += f"## When to Apply\n\n"
1032
+ content += f"Trigger: {trigger}\n\n"
1033
+ content += f"## Actions\n\n"
1034
+ for inst in cand['instincts']:
1035
+ inst_content = inst.get('content', '')
1036
+ action_match = re.search(r'## Action\s*\n\s*(.+?)(?:\n\n|\n##|$)', inst_content, re.DOTALL)
1037
+ action = action_match.group(1).strip() if action_match else inst.get('id', 'unnamed')
1038
+ content += f"- {action}\n"
1039
+
1040
+ (skill_dir / "SKILL.md").write_text(content)
1041
+ generated.append(str(skill_dir / "SKILL.md"))
1042
+
1043
+ # Generate commands from workflow instincts
1044
+ for inst in workflow_instincts[:5]:
1045
+ trigger = inst.get('trigger', 'unknown')
1046
+ cmd_name = re.sub(r'[^a-z0-9]+', '-', trigger.lower().replace('when ', '').replace('implementing ', ''))
1047
+ cmd_name = cmd_name.strip('-')[:20]
1048
+ if not cmd_name:
1049
+ continue
1050
+
1051
+ cmd_file = evolved_dir / "commands" / f"{cmd_name}.md"
1052
+ content = f"# {cmd_name}\n\n"
1053
+ content += f"Evolved from instinct: {inst.get('id', 'unnamed')}\n"
1054
+ content += f"Confidence: {inst.get('confidence', 0.5):.0%}\n\n"
1055
+ content += inst.get('content', '')
1056
+
1057
+ cmd_file.write_text(content)
1058
+ generated.append(str(cmd_file))
1059
+
1060
+ # Generate agents from complex clusters
1061
+ for cand in agent_candidates[:3]:
1062
+ trigger = cand['trigger'].strip()
1063
+ agent_name = re.sub(r'[^a-z0-9]+', '-', trigger.lower()).strip('-')[:20]
1064
+ if not agent_name:
1065
+ continue
1066
+
1067
+ agent_file = evolved_dir / "agents" / f"{agent_name}.md"
1068
+ domains = ', '.join(cand['domains'])
1069
+ instinct_ids = [i.get('id', 'unnamed') for i in cand['instincts']]
1070
+
1071
+ content = f"---\nmodel: sonnet\ntools: Read, Grep, Glob\n---\n"
1072
+ content += f"# {agent_name}\n\n"
1073
+ content += f"Evolved from {len(cand['instincts'])} instincts "
1074
+ content += f"(avg confidence: {cand['avg_confidence']:.0%})\n"
1075
+ content += f"Domains: {domains}\n\n"
1076
+ content += f"## Source Instincts\n\n"
1077
+ for iid in instinct_ids:
1078
+ content += f"- {iid}\n"
1079
+
1080
+ agent_file.write_text(content)
1081
+ generated.append(str(agent_file))
1082
+
1083
+ return generated
1084
+
1085
+
1086
+ # ─────────────────────────────────────────────
1087
+ # Main
1088
+ # ─────────────────────────────────────────────
1089
+
1090
+ def main() -> int:
1091
+ _ensure_global_dirs()
1092
+ parser = argparse.ArgumentParser(description='Instinct CLI for Continuous Learning v2.1 (Project-Scoped)')
1093
+ subparsers = parser.add_subparsers(dest='command', help='Available commands')
1094
+
1095
+ # Status
1096
+ status_parser = subparsers.add_parser('status', help='Show instinct status (project + global)')
1097
+
1098
+ # Import
1099
+ import_parser = subparsers.add_parser('import', help='Import instincts')
1100
+ import_parser.add_argument('source', help='File path or URL')
1101
+ import_parser.add_argument('--dry-run', action='store_true', help='Preview without importing')
1102
+ import_parser.add_argument('--force', action='store_true', help='Skip confirmation')
1103
+ import_parser.add_argument('--min-confidence', type=float, help='Minimum confidence threshold')
1104
+ import_parser.add_argument('--scope', choices=['project', 'global'], default='project',
1105
+ help='Import scope (default: project)')
1106
+
1107
+ # Export
1108
+ export_parser = subparsers.add_parser('export', help='Export instincts')
1109
+ export_parser.add_argument('--output', '-o', help='Output file')
1110
+ export_parser.add_argument('--domain', help='Filter by domain')
1111
+ export_parser.add_argument('--min-confidence', type=float, help='Minimum confidence')
1112
+ export_parser.add_argument('--scope', choices=['project', 'global', 'all'], default='all',
1113
+ help='Export scope (default: all)')
1114
+
1115
+ # Evolve
1116
+ evolve_parser = subparsers.add_parser('evolve', help='Analyze and evolve instincts')
1117
+ evolve_parser.add_argument('--generate', action='store_true', help='Generate evolved structures')
1118
+
1119
+ # Promote (new in v2.1)
1120
+ promote_parser = subparsers.add_parser('promote', help='Promote project instincts to global scope')
1121
+ promote_parser.add_argument('instinct_id', nargs='?', help='Specific instinct ID to promote')
1122
+ promote_parser.add_argument('--force', action='store_true', help='Skip confirmation')
1123
+ promote_parser.add_argument('--dry-run', action='store_true', help='Preview without promoting')
1124
+
1125
+ # Projects (new in v2.1)
1126
+ projects_parser = subparsers.add_parser('projects', help='List known projects and instinct counts')
1127
+
1128
+ args = parser.parse_args()
1129
+
1130
+ if args.command == 'status':
1131
+ return cmd_status(args)
1132
+ elif args.command == 'import':
1133
+ return cmd_import(args)
1134
+ elif args.command == 'export':
1135
+ return cmd_export(args)
1136
+ elif args.command == 'evolve':
1137
+ return cmd_evolve(args)
1138
+ elif args.command == 'promote':
1139
+ return cmd_promote(args)
1140
+ elif args.command == 'projects':
1141
+ return cmd_projects(args)
1142
+ else:
1143
+ parser.print_help()
1144
+ return 1
1145
+
1146
+
1147
+ if __name__ == '__main__':
1148
+ sys.exit(main())