squads-cli 0.1.2 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (223) hide show
  1. package/README.md +551 -177
  2. package/dist/auth-YW3UPFSB.js +23 -0
  3. package/dist/auth-YW3UPFSB.js.map +1 -0
  4. package/dist/autonomy-PSVZVX7A.js +105 -0
  5. package/dist/autonomy-PSVZVX7A.js.map +1 -0
  6. package/dist/chunk-67RO2HKR.js +174 -0
  7. package/dist/chunk-67RO2HKR.js.map +1 -0
  8. package/dist/chunk-7OCVIDC7.js +12 -0
  9. package/dist/chunk-7OCVIDC7.js.map +1 -0
  10. package/dist/chunk-BODLDQY7.js +452 -0
  11. package/dist/chunk-BODLDQY7.js.map +1 -0
  12. package/dist/chunk-EHQJHRIW.js +103 -0
  13. package/dist/chunk-EHQJHRIW.js.map +1 -0
  14. package/dist/chunk-FFFCFZ6A.js +121 -0
  15. package/dist/chunk-FFFCFZ6A.js.map +1 -0
  16. package/dist/chunk-FIWT2NMM.js +165 -0
  17. package/dist/chunk-FIWT2NMM.js.map +1 -0
  18. package/dist/chunk-HF4WR7RA.js +154 -0
  19. package/dist/chunk-HF4WR7RA.js.map +1 -0
  20. package/dist/chunk-J6QF4ZQX.js +230 -0
  21. package/dist/chunk-J6QF4ZQX.js.map +1 -0
  22. package/dist/chunk-LOA3KWYJ.js +294 -0
  23. package/dist/chunk-LOA3KWYJ.js.map +1 -0
  24. package/dist/chunk-M5FXNY6Y.js +384 -0
  25. package/dist/chunk-M5FXNY6Y.js.map +1 -0
  26. package/dist/chunk-QHNUMM4V.js +87 -0
  27. package/dist/chunk-QHNUMM4V.js.map +1 -0
  28. package/dist/chunk-QJ7C7CMB.js +223 -0
  29. package/dist/chunk-QJ7C7CMB.js.map +1 -0
  30. package/dist/chunk-RM6BWILN.js +74 -0
  31. package/dist/chunk-RM6BWILN.js.map +1 -0
  32. package/dist/chunk-TYFTF53O.js +613 -0
  33. package/dist/chunk-TYFTF53O.js.map +1 -0
  34. package/dist/chunk-TZXD6WFN.js +420 -0
  35. package/dist/chunk-TZXD6WFN.js.map +1 -0
  36. package/dist/chunk-WVOIY5GW.js +621 -0
  37. package/dist/chunk-WVOIY5GW.js.map +1 -0
  38. package/dist/chunk-Z2UKDBNL.js +162 -0
  39. package/dist/chunk-Z2UKDBNL.js.map +1 -0
  40. package/dist/chunk-ZTQ7ISUR.js +338 -0
  41. package/dist/chunk-ZTQ7ISUR.js.map +1 -0
  42. package/dist/cli.js +2506 -4475
  43. package/dist/cli.js.map +1 -1
  44. package/dist/context-GWPF4SEY.js +291 -0
  45. package/dist/context-GWPF4SEY.js.map +1 -0
  46. package/dist/context-feed-AJGVAR6H.js +394 -0
  47. package/dist/context-feed-AJGVAR6H.js.map +1 -0
  48. package/dist/cost-XBCDJ7XC.js +275 -0
  49. package/dist/cost-XBCDJ7XC.js.map +1 -0
  50. package/dist/create-BLFGG6PF.js +286 -0
  51. package/dist/create-BLFGG6PF.js.map +1 -0
  52. package/dist/dashboard-LGT2B2BL.js +951 -0
  53. package/dist/dashboard-LGT2B2BL.js.map +1 -0
  54. package/dist/dashboard-RMK2BOD2.js +794 -0
  55. package/dist/dashboard-RMK2BOD2.js.map +1 -0
  56. package/dist/doctor-XPUIIBHJ.js +374 -0
  57. package/dist/doctor-XPUIIBHJ.js.map +1 -0
  58. package/dist/env-config-SQEI3Y7Y.js +21 -0
  59. package/dist/env-config-SQEI3Y7Y.js.map +1 -0
  60. package/dist/exec-OUXM7JBF.js +223 -0
  61. package/dist/exec-OUXM7JBF.js.map +1 -0
  62. package/dist/feedback-KNAOG5QK.js +229 -0
  63. package/dist/feedback-KNAOG5QK.js.map +1 -0
  64. package/dist/github-UQTM5KMS.js +23 -0
  65. package/dist/github-UQTM5KMS.js.map +1 -0
  66. package/dist/goal-BVHV5573.js +168 -0
  67. package/dist/goal-BVHV5573.js.map +1 -0
  68. package/dist/health-4UXN44PF.js +218 -0
  69. package/dist/health-4UXN44PF.js.map +1 -0
  70. package/dist/history-ILH3SWHB.js +232 -0
  71. package/dist/history-ILH3SWHB.js.map +1 -0
  72. package/dist/index.d.ts +736 -8
  73. package/dist/index.js +1312 -6
  74. package/dist/index.js.map +1 -1
  75. package/dist/init-XQZ7BOGT.js +812 -0
  76. package/dist/init-XQZ7BOGT.js.map +1 -0
  77. package/dist/kpi-RQIU7WGK.js +413 -0
  78. package/dist/kpi-RQIU7WGK.js.map +1 -0
  79. package/dist/learn-OIFUVZAS.js +269 -0
  80. package/dist/learn-OIFUVZAS.js.map +1 -0
  81. package/dist/login-DXZANWZY.js +155 -0
  82. package/dist/login-DXZANWZY.js.map +1 -0
  83. package/dist/memory-T3ACCS7E.js +560 -0
  84. package/dist/memory-T3ACCS7E.js.map +1 -0
  85. package/dist/memory-VNF2VFRB.js +23 -0
  86. package/dist/memory-VNF2VFRB.js.map +1 -0
  87. package/dist/progress-DAUZMT3N.js +202 -0
  88. package/dist/progress-DAUZMT3N.js.map +1 -0
  89. package/dist/providers-3P5D2XL5.js +65 -0
  90. package/dist/providers-3P5D2XL5.js.map +1 -0
  91. package/dist/results-UECWGLTB.js +224 -0
  92. package/dist/results-UECWGLTB.js.map +1 -0
  93. package/dist/run-I6KAXU6U.js +4049 -0
  94. package/dist/run-I6KAXU6U.js.map +1 -0
  95. package/dist/session-HBU6KZOD.js +64 -0
  96. package/dist/session-HBU6KZOD.js.map +1 -0
  97. package/dist/sessions-CK25VGPL.js +333 -0
  98. package/dist/sessions-CK25VGPL.js.map +1 -0
  99. package/dist/squad-parser-DCG65BJS.js +35 -0
  100. package/dist/squad-parser-DCG65BJS.js.map +1 -0
  101. package/dist/stats-G6NAU5BD.js +334 -0
  102. package/dist/stats-G6NAU5BD.js.map +1 -0
  103. package/dist/status-AQNLDZVN.js +352 -0
  104. package/dist/status-AQNLDZVN.js.map +1 -0
  105. package/dist/sync-ZI3MHA4G.js +836 -0
  106. package/dist/sync-ZI3MHA4G.js.map +1 -0
  107. package/dist/templates/core/AGENTS.md.template +51 -0
  108. package/dist/templates/core/BUSINESS_BRIEF.md.template +29 -0
  109. package/dist/templates/core/CLAUDE.md.template +48 -0
  110. package/dist/templates/core/provider.yaml.template +5 -0
  111. package/dist/templates/first-squad/SQUAD.md.template +23 -0
  112. package/dist/templates/first-squad/lead.md.template +44 -0
  113. package/dist/templates/memory/getting-started/state.md.template +19 -0
  114. package/dist/templates/seed/BUSINESS_BRIEF.md.template +27 -0
  115. package/dist/templates/seed/CLAUDE.md.template +119 -0
  116. package/dist/templates/seed/README.md.template +42 -0
  117. package/dist/templates/seed/config/SYSTEM.md +52 -0
  118. package/dist/templates/seed/config/provider.yaml +4 -0
  119. package/dist/templates/seed/hooks/settings.json.template +31 -0
  120. package/dist/templates/seed/memory/company/directives.md +37 -0
  121. package/dist/templates/seed/memory/company/manager/state.md +16 -0
  122. package/dist/templates/seed/memory/engineering/issue-solver/state.md +12 -0
  123. package/dist/templates/seed/memory/intelligence/intel-lead/state.md +9 -0
  124. package/dist/templates/seed/memory/marketing/content-drafter/state.md +12 -0
  125. package/dist/templates/seed/memory/operations/ops-lead/state.md +12 -0
  126. package/dist/templates/seed/memory/product/lead/state.md +14 -0
  127. package/dist/templates/seed/memory/research/lead/state.md +14 -0
  128. package/dist/templates/seed/skills/gh/SKILL.md +57 -0
  129. package/dist/templates/seed/skills/squads-cli/SKILL.md +84 -0
  130. package/dist/templates/seed/squads/company/SQUAD.md +51 -0
  131. package/dist/templates/seed/squads/company/company-critic.md +49 -0
  132. package/dist/templates/seed/squads/company/company-eval.md +49 -0
  133. package/dist/templates/seed/squads/company/event-dispatcher.md +43 -0
  134. package/dist/templates/seed/squads/company/goal-tracker.md +43 -0
  135. package/dist/templates/seed/squads/company/manager.md +54 -0
  136. package/dist/templates/seed/squads/engineering/SQUAD.md +48 -0
  137. package/dist/templates/seed/squads/engineering/code-reviewer.md +57 -0
  138. package/dist/templates/seed/squads/engineering/issue-solver.md +58 -0
  139. package/dist/templates/seed/squads/engineering/test-writer.md +50 -0
  140. package/dist/templates/seed/squads/intelligence/SQUAD.md +38 -0
  141. package/dist/templates/seed/squads/intelligence/intel-critic.md +36 -0
  142. package/dist/templates/seed/squads/intelligence/intel-eval.md +31 -0
  143. package/dist/templates/seed/squads/intelligence/intel-lead.md +71 -0
  144. package/dist/templates/seed/squads/marketing/SQUAD.md +47 -0
  145. package/dist/templates/seed/squads/marketing/content-drafter.md +71 -0
  146. package/dist/templates/seed/squads/marketing/growth-analyst.md +49 -0
  147. package/dist/templates/seed/squads/marketing/social-poster.md +44 -0
  148. package/dist/templates/seed/squads/operations/SQUAD.md +45 -0
  149. package/dist/templates/seed/squads/operations/finance-tracker.md +47 -0
  150. package/dist/templates/seed/squads/operations/goal-tracker.md +48 -0
  151. package/dist/templates/seed/squads/operations/ops-lead.md +58 -0
  152. package/dist/templates/seed/squads/product/SQUAD.md +41 -0
  153. package/dist/templates/seed/squads/product/lead.md +56 -0
  154. package/dist/templates/seed/squads/product/scanner.md +50 -0
  155. package/dist/templates/seed/squads/product/worker.md +55 -0
  156. package/dist/templates/seed/squads/research/SQUAD.md +38 -0
  157. package/dist/templates/seed/squads/research/analyst.md +50 -0
  158. package/dist/templates/seed/squads/research/lead.md +52 -0
  159. package/dist/templates/seed/squads/research/synthesizer.md +59 -0
  160. package/dist/templates/skills/squads-learn/SKILL.md +86 -0
  161. package/dist/templates/skills/squads-workflow/instruction.md +70 -0
  162. package/dist/terminal-FBQFQTKZ.js +55 -0
  163. package/dist/terminal-FBQFQTKZ.js.map +1 -0
  164. package/dist/update-D7CGIZ3M.js +18 -0
  165. package/dist/update-D7CGIZ3M.js.map +1 -0
  166. package/dist/update-STU276HR.js +83 -0
  167. package/dist/update-STU276HR.js.map +1 -0
  168. package/package.json +31 -13
  169. package/templates/core/AGENTS.md.template +51 -0
  170. package/templates/core/BUSINESS_BRIEF.md.template +29 -0
  171. package/templates/core/CLAUDE.md.template +48 -0
  172. package/templates/core/provider.yaml.template +5 -0
  173. package/templates/first-squad/SQUAD.md.template +23 -0
  174. package/templates/first-squad/lead.md.template +44 -0
  175. package/templates/memory/getting-started/state.md.template +19 -0
  176. package/templates/seed/BUSINESS_BRIEF.md.template +27 -0
  177. package/templates/seed/CLAUDE.md.template +119 -0
  178. package/templates/seed/README.md.template +42 -0
  179. package/templates/seed/config/SYSTEM.md +52 -0
  180. package/templates/seed/config/provider.yaml +4 -0
  181. package/templates/seed/hooks/settings.json.template +31 -0
  182. package/templates/seed/memory/company/directives.md +37 -0
  183. package/templates/seed/memory/company/manager/state.md +16 -0
  184. package/templates/seed/memory/engineering/issue-solver/state.md +12 -0
  185. package/templates/seed/memory/intelligence/intel-lead/state.md +9 -0
  186. package/templates/seed/memory/marketing/content-drafter/state.md +12 -0
  187. package/templates/seed/memory/operations/ops-lead/state.md +12 -0
  188. package/templates/seed/memory/product/lead/state.md +14 -0
  189. package/templates/seed/memory/research/lead/state.md +14 -0
  190. package/templates/seed/skills/gh/SKILL.md +57 -0
  191. package/templates/seed/skills/squads-cli/SKILL.md +84 -0
  192. package/templates/seed/squads/company/SQUAD.md +51 -0
  193. package/templates/seed/squads/company/company-critic.md +49 -0
  194. package/templates/seed/squads/company/company-eval.md +49 -0
  195. package/templates/seed/squads/company/event-dispatcher.md +43 -0
  196. package/templates/seed/squads/company/goal-tracker.md +43 -0
  197. package/templates/seed/squads/company/manager.md +54 -0
  198. package/templates/seed/squads/engineering/SQUAD.md +48 -0
  199. package/templates/seed/squads/engineering/code-reviewer.md +57 -0
  200. package/templates/seed/squads/engineering/issue-solver.md +58 -0
  201. package/templates/seed/squads/engineering/test-writer.md +50 -0
  202. package/templates/seed/squads/intelligence/SQUAD.md +38 -0
  203. package/templates/seed/squads/intelligence/intel-critic.md +36 -0
  204. package/templates/seed/squads/intelligence/intel-eval.md +31 -0
  205. package/templates/seed/squads/intelligence/intel-lead.md +71 -0
  206. package/templates/seed/squads/marketing/SQUAD.md +47 -0
  207. package/templates/seed/squads/marketing/content-drafter.md +71 -0
  208. package/templates/seed/squads/marketing/growth-analyst.md +49 -0
  209. package/templates/seed/squads/marketing/social-poster.md +44 -0
  210. package/templates/seed/squads/operations/SQUAD.md +45 -0
  211. package/templates/seed/squads/operations/finance-tracker.md +47 -0
  212. package/templates/seed/squads/operations/goal-tracker.md +48 -0
  213. package/templates/seed/squads/operations/ops-lead.md +58 -0
  214. package/templates/seed/squads/product/SQUAD.md +41 -0
  215. package/templates/seed/squads/product/lead.md +56 -0
  216. package/templates/seed/squads/product/scanner.md +50 -0
  217. package/templates/seed/squads/product/worker.md +55 -0
  218. package/templates/seed/squads/research/SQUAD.md +38 -0
  219. package/templates/seed/squads/research/analyst.md +50 -0
  220. package/templates/seed/squads/research/lead.md +52 -0
  221. package/templates/seed/squads/research/synthesizer.md +59 -0
  222. package/templates/skills/squads-learn/SKILL.md +86 -0
  223. package/templates/skills/squads-workflow/instruction.md +70 -0
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/cli.ts","../src/version.ts","../src/commands/init.ts","../src/lib/git.ts","../src/lib/telemetry.ts","../src/commands/run.ts","../src/lib/squad-parser.ts","../src/lib/memory.ts","../src/lib/terminal.ts","../src/commands/list.ts","../src/commands/status.ts","../src/commands/memory.ts","../src/commands/sync.ts","../src/commands/goal.ts","../src/commands/feedback.ts","../src/commands/dashboard.ts","../src/lib/costs.ts","../src/lib/db.ts","../src/commands/issues.ts","../src/commands/solve-issues.ts","../src/commands/open-issues.ts","../src/commands/login.ts","../src/lib/auth.ts","../src/commands/progress.ts","../src/commands/results.ts","../src/commands/workers.ts"],"sourcesContent":["import { config } from 'dotenv';\nimport { existsSync } from 'fs';\nimport { join } from 'path';\nimport { homedir } from 'os';\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport { version } from './version.js';\n\n// Load .env from multiple locations (first found wins)\nconst envPaths = [\n join(process.cwd(), '.env'),\n join(process.cwd(), '..', 'hq', '.env'),\n join(homedir(), 'agents-squads', 'hq', '.env'),\n];\n\nfor (const envPath of envPaths) {\n if (existsSync(envPath)) {\n config({ path: envPath, quiet: true });\n break;\n }\n}\nimport { initCommand } from './commands/init.js';\nimport { runCommand } from './commands/run.js';\nimport { listCommand } from './commands/list.js';\nimport { statusCommand } from './commands/status.js';\nimport {\n memoryQueryCommand,\n memoryShowCommand,\n memoryUpdateCommand,\n memoryListCommand,\n memorySearchCommand\n} from './commands/memory.js';\nimport { syncCommand } from './commands/sync.js';\nimport {\n goalSetCommand,\n goalListCommand,\n goalCompleteCommand,\n goalProgressCommand\n} from './commands/goal.js';\nimport {\n feedbackAddCommand,\n feedbackShowCommand,\n feedbackStatsCommand\n} from './commands/feedback.js';\nimport { dashboardCommand } from './commands/dashboard.js';\nimport { issuesCommand } from './commands/issues.js';\nimport { solveIssuesCommand } from './commands/solve-issues.js';\nimport { openIssuesCommand } from './commands/open-issues.js';\nimport { loginCommand, logoutCommand, whoamiCommand } from './commands/login.js';\nimport { progressCommand, progressStartCommand, progressCompleteCommand } from './commands/progress.js';\nimport { resultsCommand } from './commands/results.js';\nimport { workersCommand } from './commands/workers.js';\nimport { registerExitHandler } from './lib/telemetry.js';\n\n// Register telemetry exit handler early\nregisterExitHandler();\n\nconst program = new Command();\n\nprogram\n .name('squads')\n .description('A CLI for humans and agents')\n .version(version);\n\n// Init command\nprogram\n .command('init')\n .description('Initialize a new squad project')\n .option('-t, --template <template>', 'Project template', 'default')\n .action(initCommand);\n\n// Run command - runs squads or individual agents\nprogram\n .command('run <target>')\n .description('Run a squad or agent')\n .option('-v, --verbose', 'Verbose output')\n .option('-d, --dry-run', 'Show what would be run without executing')\n .option('-e, --execute', 'Execute agent via Claude CLI (requires claude installed)')\n .option('-a, --agent <agent>', 'Run specific agent within squad')\n .action(runCommand);\n\n// List command\nprogram\n .command('list')\n .description('List agents and squads')\n .option('-s, --squads', 'List squads only')\n .option('-a, --agents', 'List agents only')\n .action(listCommand);\n\n// Status command\nprogram\n .command('status [squad]')\n .description('Show squad status and state')\n .option('-v, --verbose', 'Show detailed status')\n .action(statusCommand);\n\n// Dashboard command\nprogram\n .command('dashboard')\n .alias('dash')\n .description('Show comprehensive goals and metrics dashboard')\n .option('-v, --verbose', 'Show additional details')\n .option('-c, --ceo', 'Executive summary with priorities and blockers')\n .action(dashboardCommand);\n\n// Issues command\nprogram\n .command('issues')\n .description('Show GitHub issues across repos')\n .option('-o, --org <org>', 'GitHub organization', 'agents-squads')\n .option('-r, --repos <repos>', 'Comma-separated repo names')\n .action(issuesCommand);\n\n// Solve issues command - close issues by creating PRs\nprogram\n .command('solve-issues')\n .description('Solve ready-to-fix issues by creating PRs')\n .option('-r, --repo <repo>', 'Target repo (hq, agents-squads-web)')\n .option('-i, --issue <number>', 'Specific issue number', parseInt)\n .option('-d, --dry-run', 'Show what would be solved')\n .option('-e, --execute', 'Execute with Claude CLI')\n .action(solveIssuesCommand);\n\n// Open issues command - run evaluators to find new issues\nprogram\n .command('open-issues')\n .description('Run evaluators/critics to find and create issues')\n .option('-s, --squad <squad>', 'Target squad (website, engineering, etc.)')\n .option('-a, --agent <agent>', 'Specific evaluator agent')\n .option('-d, --dry-run', 'Show what would run')\n .option('-e, --execute', 'Execute with Claude CLI')\n .action(openIssuesCommand);\n\n// Progress command - track agent task progress\nconst progress = program\n .command('progress')\n .description('Track active and completed agent tasks')\n .option('-v, --verbose', 'Show more activity')\n .action(progressCommand);\n\nprogress\n .command('start <squad> <description>')\n .description('Register a new active task')\n .action(progressStartCommand);\n\nprogress\n .command('complete <taskId>')\n .description('Mark a task as completed')\n .option('-f, --failed', 'Mark as failed instead')\n .action(progressCompleteCommand);\n\n// Results command - KPI goals vs actuals\nprogram\n .command('results [squad]')\n .description('Show squad results: git activity + KPI goals vs actuals')\n .option('-d, --days <days>', 'Days to look back', '7')\n .option('-v, --verbose', 'Show detailed KPIs per goal')\n .action((squad, options) => resultsCommand({ ...options, squad }));\n\n// Workers command - show running processes and tasks\nprogram\n .command('workers')\n .description('Show active workers: Claude sessions, tasks, dev servers')\n .option('-v, --verbose', 'Show more details')\n .option('-k, --kill <pid>', 'Kill a process by PID')\n .action(workersCommand);\n\n// Memory command group\nconst memory = program\n .command('memory')\n .description('Query and manage squad memory');\n\nmemory\n .command('query <query>')\n .description('Search across all squad memory')\n .option('-s, --squad <squad>', 'Limit search to specific squad')\n .option('-a, --agent <agent>', 'Limit search to specific agent')\n .action(memoryQueryCommand);\n\nmemory\n .command('show <squad>')\n .description('Show memory for a squad')\n .action(memoryShowCommand);\n\nmemory\n .command('update <squad> <content>')\n .description('Add to squad memory')\n .option('-a, --agent <agent>', 'Specific agent (default: squad-lead)')\n .option('-t, --type <type>', 'Memory type: state, learnings, feedback', 'learnings')\n .action(memoryUpdateCommand);\n\nmemory\n .command('list')\n .description('List all memory entries')\n .action(memoryListCommand);\n\nmemory\n .command('sync')\n .description('Sync memory from recent git commits (auto-update)')\n .option('-v, --verbose', 'Show detailed commit info')\n .action(syncCommand);\n\nmemory\n .command('search <query>')\n .description('Search conversations stored in postgres (via squads-bridge)')\n .option('-l, --limit <limit>', 'Number of results', '10')\n .option('-r, --role <role>', 'Filter by role: user, assistant, thinking')\n .option('-i, --importance <importance>', 'Filter by importance: low, normal, high')\n .action((query, opts) => memorySearchCommand(query, {\n limit: parseInt(opts.limit, 10),\n role: opts.role,\n importance: opts.importance\n }));\n\n// Goal command group\nconst goal = program\n .command('goal')\n .description('Manage squad goals');\n\ngoal\n .command('set <squad> <description>')\n .description('Set a goal for a squad')\n .option('-m, --metric <metrics...>', 'Metrics to track')\n .action(goalSetCommand);\n\ngoal\n .command('list [squad]')\n .description('List goals for squad(s)')\n .option('-a, --all', 'Show completed goals too')\n .action(goalListCommand);\n\ngoal\n .command('complete <squad> <index>')\n .description('Mark a goal as completed')\n .action(goalCompleteCommand);\n\ngoal\n .command('progress <squad> <index> <progress>')\n .description('Update goal progress')\n .action(goalProgressCommand);\n\n// Feedback command group\nconst feedback = program\n .command('feedback')\n .description('Record and view execution feedback');\n\nfeedback\n .command('add <squad> <rating> <feedback>')\n .description('Add feedback for last execution (rating 1-5)')\n .option('-l, --learning <learnings...>', 'Learnings to extract')\n .action(feedbackAddCommand);\n\nfeedback\n .command('show <squad>')\n .description('Show feedback history')\n .option('-n, --limit <n>', 'Number of entries to show', '5')\n .action(feedbackShowCommand);\n\nfeedback\n .command('stats')\n .description('Show feedback summary across all squads')\n .action(feedbackStatsCommand);\n\n// Auth commands\nprogram\n .command('login')\n .description('Log in to Squads (Pro & Enterprise)')\n .action(loginCommand);\n\nprogram\n .command('logout')\n .description('Log out from Squads')\n .action(logoutCommand);\n\nprogram\n .command('whoami')\n .description('Show current logged in user')\n .action(whoamiCommand);\n\n// Parse arguments (use parseAsync to properly await async actions)\nawait program.parseAsync();\n\n// Show help if no command provided\nif (!process.argv.slice(2).length) {\n console.log(`\n${chalk.bold.magenta('squads')} - AI agent squad management\n\n${chalk.dim('Quick start:')}\n ${chalk.cyan('squads status')} View all squads status\n ${chalk.cyan('squads run <squad>')} Run a squad\n ${chalk.cyan('squads memory query \"<term>\"')} Search squad memory\n\n${chalk.dim('Goals & Feedback:')}\n ${chalk.cyan('squads goal set <squad> \"<goal>\"')} Set a goal\n ${chalk.cyan('squads goal list')} View active goals\n ${chalk.cyan('squads feedback add <squad> 4 \"msg\"')} Rate last execution\n\n${chalk.dim('Examples:')}\n ${chalk.cyan('squads run website')} Run website squad\n ${chalk.cyan('squads goal set finance \"Track costs\"')} Set finance goal\n ${chalk.cyan('squads feedback stats')} View feedback summary\n\n${chalk.dim('Run')} ${chalk.cyan('squads --help')} ${chalk.dim('for all commands.')}\n`);\n}\n","export const version = '0.1.0';\n","import chalk from 'chalk';\nimport ora from 'ora';\nimport fs from 'fs/promises';\nimport path from 'path';\nimport { checkGitStatus, initGitRepo, getRepoName } from '../lib/git.js';\nimport { track, Events } from '../lib/telemetry.js';\n\ninterface InitOptions {\n template: string;\n}\n\nexport async function initCommand(options: InitOptions): Promise<void> {\n const cwd = process.cwd();\n\n // Check Git status first\n console.log(chalk.dim('Checking project setup...\\n'));\n\n const gitStatus = checkGitStatus(cwd);\n\n if (!gitStatus.isGitRepo) {\n console.log(chalk.yellow('⚠ No git repository found.'));\n console.log(chalk.dim(' Squads work best with git for version control and GitHub integration.'));\n console.log(chalk.dim(' Run: git init && git remote add origin <your-repo-url>\\n'));\n } else {\n console.log(chalk.green('✓ Git repository detected'));\n\n if (gitStatus.hasRemote) {\n const repoName = getRepoName(gitStatus.remoteUrl);\n console.log(chalk.green(`✓ Remote: ${chalk.cyan(repoName || gitStatus.remoteUrl)}`));\n } else {\n console.log(chalk.yellow('⚠ No remote configured.'));\n console.log(chalk.dim(' Add a remote: git remote add origin <your-repo-url>\\n'));\n }\n\n if (gitStatus.isDirty) {\n console.log(chalk.yellow(`⚠ ${gitStatus.uncommittedCount} uncommitted changes`));\n }\n }\n\n console.log();\n\n const spinner = ora('Initializing squad project...').start();\n\n try {\n // Create directory structure\n const dirs = [\n '.agents/squads',\n '.agents/memory',\n '.agents/outputs',\n '.claude',\n ];\n\n for (const dir of dirs) {\n await fs.mkdir(path.join(cwd, dir), { recursive: true });\n }\n\n // Create git commit template\n const commitTemplate = `\n\n# ────────────────────────────────────────────────────────────\n# Commit message format (delete this comment block):\n#\n# <type>(<scope>): <subject>\n#\n# <body>\n#\n# 🤖 Generated with [Agents Squads](https://agents-squads.com)\n#\n# Co-Authored-By: <model> <email>\n# ────────────────────────────────────────────────────────────\n# AI Models (add those that contributed to this commit):\n#\n# Model | Email | API Key\n# --------------------|----------------------------|------------------\n# Claude Opus 4.5 | <noreply@anthropic.com> | ANTHROPIC_API_KEY\n# Claude Sonnet 4 | <noreply@anthropic.com> | ANTHROPIC_API_KEY\n# Claude Haiku 3.5 | <noreply@anthropic.com> | ANTHROPIC_API_KEY\n# GPT-4o | <noreply@openai.com> | OPENAI_API_KEY\n# GPT-o1 | <noreply@openai.com> | OPENAI_API_KEY\n# Gemini 2.0 Flash | <noreply@google.com> | GEMINI_API_KEY\n# Grok 3 | <noreply@x.ai> | XAI_API_KEY\n# Perplexity | <noreply@perplexity.ai> | PERPLEXITY_API_KEY\n# Manus AI | <noreply@manus.im> | MANUS_API_KEY\n#\n# Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>\n# Co-Authored-By: Claude Sonnet 4 <noreply@anthropic.com>\n# Co-Authored-By: Claude Haiku 3.5 <noreply@anthropic.com>\n# Co-Authored-By: GPT-4o <noreply@openai.com>\n# Co-Authored-By: GPT-o1 <noreply@openai.com>\n# Co-Authored-By: Gemini 2.0 Flash <noreply@google.com>\n# Co-Authored-By: Grok 3 <noreply@x.ai>\n# Co-Authored-By: Perplexity <noreply@perplexity.ai>\n# Co-Authored-By: Manus AI <noreply@manus.im>\n# ────────────────────────────────────────────────────────────\n`;\n\n await fs.writeFile(\n path.join(cwd, '.agents/commit-template.txt'),\n commitTemplate\n );\n\n // Create .mailmap for author consolidation\n const mailmap = `# Git author name consolidation\n# Format: Proper Name <proper@email> Commit Name <commit@email>\n# Add entries to consolidate multiple git identities\n\n# AI Contributors\nAgents Squads <agents@agents-squads.com> Agents Squads <agents@agents-squads.com>\n`;\n\n await fs.writeFile(path.join(cwd, '.mailmap'), mailmap);\n\n // Create Claude Code settings with hooks\n const claudeSettings = {\n hooks: {\n SessionStart: [\n {\n hooks: [\n {\n type: 'command',\n command: 'squads status',\n timeout: 10,\n },\n ],\n },\n ],\n Stop: [\n {\n hooks: [\n {\n type: 'command',\n command: 'squads memory sync',\n timeout: 15,\n },\n ],\n },\n ],\n },\n };\n\n await fs.writeFile(\n path.join(cwd, '.claude/settings.json'),\n JSON.stringify(claudeSettings, null, 2)\n );\n\n // Create example agent\n const exampleAgent = `# Example Agent\n\n## Purpose\nDemonstrate basic agent structure.\n\n## Model\nclaude-sonnet-4\n\n## Tools\n- Read\n- Write\n- WebSearch\n\n## Instructions\n1. Greet the user\n2. Ask how you can help\n3. Execute the task\n\n## Output\nMarkdown summary of actions taken.\n`;\n\n await fs.writeFile(\n path.join(cwd, '.agents/squads/example-agent.md'),\n exampleAgent\n );\n\n // Create CLAUDE.md if it doesn't exist\n const claudeMdPath = path.join(cwd, 'CLAUDE.md');\n try {\n await fs.access(claudeMdPath);\n } catch {\n await fs.writeFile(\n claudeMdPath,\n `# Project Instructions\n\n## Squads CLI\n\nThis project uses AI agent squads. The \\`squads\\` CLI provides persistent memory across sessions.\n\n### Key Commands\n\n| Command | Purpose |\n|---------|---------|\n| \\`squads status\\` | Overview of all squads (runs on session start) |\n| \\`squads dash\\` | Full operational dashboard |\n| \\`squads dash --ceo\\` | Executive summary with P0/P1 priorities |\n| \\`squads goal list\\` | View all active goals |\n| \\`squads memory query \"<topic>\"\\` | Search squad memory before researching |\n| \\`squads run <squad>\\` | Execute a squad |\n\n### Workflow\n\n1. **Session Start**: \\`squads status\\` runs automatically via hook\n2. **Before Research**: Query memory to avoid re-doing work\n3. **Session End**: Memory syncs automatically from git commits\n\n### Git Commit Format\n\nAll commits should use the Agents Squads format:\n\n\\`\\`\\`\n<type>(<scope>): <subject>\n\n<body>\n\n🤖 Generated with [Agents Squads](https://agents-squads.com)\n\nCo-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>\n\\`\\`\\`\n\n**AI Models** (include those that contributed):\n\n| Model | Co-Author Email | API Key Required |\n|-------|-----------------|------------------|\n| Claude Opus 4.5 | \\`<noreply@anthropic.com>\\` | \\`ANTHROPIC_API_KEY\\` |\n| Claude Sonnet 4 | \\`<noreply@anthropic.com>\\` | \\`ANTHROPIC_API_KEY\\` |\n| Claude Haiku 3.5 | \\`<noreply@anthropic.com>\\` | \\`ANTHROPIC_API_KEY\\` |\n| GPT-4o | \\`<noreply@openai.com>\\` | \\`OPENAI_API_KEY\\` |\n| GPT-o1 | \\`<noreply@openai.com>\\` | \\`OPENAI_API_KEY\\` |\n| Gemini 2.0 Flash | \\`<noreply@google.com>\\` | \\`GEMINI_API_KEY\\` |\n| Grok 3 | \\`<noreply@x.ai>\\` | \\`XAI_API_KEY\\` |\n| Perplexity | \\`<noreply@perplexity.ai>\\` | \\`PERPLEXITY_API_KEY\\` |\n| Manus AI | \\`<noreply@manus.im>\\` | \\`MANUS_API_KEY\\` |\n\n### For Reports\n\nAlways use CLI commands for status reports:\n- Executive summary: \\`squads dash --ceo\\`\n- Operational view: \\`squads dash\\`\n- Goals: \\`squads goal list\\`\n`\n );\n }\n\n spinner.succeed('Squad project initialized!');\n\n // Track initialization\n await track(Events.CLI_INIT, {\n hasGit: gitStatus.isGitRepo,\n hasRemote: gitStatus.hasRemote,\n template: options.template,\n });\n\n console.log(`\n${chalk.green('Success!')} Created squad project structure:\n\n ${chalk.cyan('.agents/')}\n ${chalk.dim('├──')} ${chalk.cyan('squads/')} Squad & agent definitions\n ${chalk.dim('├──')} ${chalk.cyan('memory/')} Persistent squad memory\n ${chalk.dim('├──')} ${chalk.cyan('outputs/')} Squad outputs\n ${chalk.dim('└──')} ${chalk.cyan('commit-template.txt')} Git commit format\n\n ${chalk.cyan('.mailmap')} Author name consolidation\n\n${chalk.dim('Commit format:')}\n 🤖 Generated with [Agents Squads](https://agents-squads.com)\n Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>\n\n${chalk.dim('Next steps:')}\n ${chalk.cyan('1.')} Create a squad: ${chalk.yellow('mkdir .agents/squads/my-squad && touch .agents/squads/my-squad/SQUAD.md')}\n ${chalk.cyan('2.')} Set a goal: ${chalk.yellow('squads goal set my-squad \"Solve a problem\"')}\n ${chalk.cyan('3.')} Run it: ${chalk.yellow('squads run my-squad')}\n\n${chalk.dim('Put your first squad to work solving a problem in minutes.')}\n`);\n\n } catch (error) {\n spinner.fail('Failed to initialize project');\n console.error(chalk.red(error));\n process.exit(1);\n }\n}\n","import { execSync } from 'child_process';\nimport { existsSync } from 'fs';\nimport { join } from 'path';\n\nexport interface GitStatus {\n isGitRepo: boolean;\n hasRemote: boolean;\n remoteName?: string;\n remoteUrl?: string;\n branch?: string;\n isDirty: boolean;\n uncommittedCount: number;\n}\n\nexport function checkGitStatus(cwd: string = process.cwd()): GitStatus {\n const status: GitStatus = {\n isGitRepo: false,\n hasRemote: false,\n isDirty: false,\n uncommittedCount: 0,\n };\n\n // Check if .git directory exists\n if (!existsSync(join(cwd, '.git'))) {\n return status;\n }\n\n status.isGitRepo = true;\n\n try {\n // Get current branch\n const branch = execSync('git rev-parse --abbrev-ref HEAD', {\n cwd,\n encoding: 'utf-8',\n stdio: ['pipe', 'pipe', 'pipe']\n }).trim();\n status.branch = branch;\n\n // Check for remote\n const remotes = execSync('git remote -v', {\n cwd,\n encoding: 'utf-8',\n stdio: ['pipe', 'pipe', 'pipe']\n }).trim();\n\n if (remotes) {\n status.hasRemote = true;\n const lines = remotes.split('\\n');\n if (lines.length > 0) {\n const parts = lines[0].split(/\\s+/);\n status.remoteName = parts[0];\n status.remoteUrl = parts[1];\n }\n }\n\n // Check for uncommitted changes\n const statusOutput = execSync('git status --porcelain', {\n cwd,\n encoding: 'utf-8',\n stdio: ['pipe', 'pipe', 'pipe']\n }).trim();\n\n if (statusOutput) {\n status.isDirty = true;\n status.uncommittedCount = statusOutput.split('\\n').filter(l => l.trim()).length;\n }\n\n } catch {\n // Git commands failed, but we know it's a git repo\n }\n\n return status;\n}\n\nexport function initGitRepo(cwd: string = process.cwd()): boolean {\n try {\n execSync('git init', { cwd, stdio: 'pipe' });\n return true;\n } catch {\n return false;\n }\n}\n\nexport function getRepoName(remoteUrl?: string): string | null {\n if (!remoteUrl) return null;\n\n // Handle various remote URL formats\n // git@github.com:user/repo.git\n // https://github.com/user/repo.git\n const match = remoteUrl.match(/[:/]([^/]+\\/[^/]+?)(?:\\.git)?$/);\n return match ? match[1] : null;\n}\n\n// Multi-repo git performance stats\nexport interface GitPerformanceStats {\n totalCommits: number;\n commitsByDay: Map<string, number>; // date string -> count\n commitsByAuthor: Map<string, number>;\n commitsByRepo: Map<string, number>;\n activeDays: number;\n avgCommitsPerDay: number;\n peakDay: { date: string; count: number } | null;\n repos: RepoStats[];\n}\n\nexport interface RepoStats {\n name: string;\n path: string;\n commits: number;\n lastCommit: string;\n authors: string[];\n}\n\nexport interface CommitInfo {\n hash: string;\n author: string;\n date: string;\n message: string;\n repo: string;\n}\n\nconst SQUAD_REPOS = ['hq', 'agents-squads-web', 'squads-cli', 'company', 'product', 'engineering', 'research', 'intelligence', 'customer', 'finance', 'marketing'];\n\n// Squad to repo mapping for GitHub stats\nconst SQUAD_REPO_MAP: Record<string, string[]> = {\n website: ['agents-squads-web'],\n product: ['squads-cli'],\n engineering: ['hq', 'squads-cli'],\n research: ['research'],\n intelligence: ['intelligence'],\n customer: ['customer'],\n finance: ['finance'],\n company: ['company', 'hq'],\n marketing: ['marketing', 'agents-squads-web'],\n};\n\n// Label patterns that map to squads\nconst SQUAD_LABELS: Record<string, string[]> = {\n website: ['website', 'web', 'frontend', 'ui'],\n product: ['product', 'cli', 'feature'],\n engineering: ['engineering', 'infra', 'backend', 'bug'],\n research: ['research', 'analysis'],\n intelligence: ['intel', 'monitoring'],\n customer: ['customer', 'sales', 'lead'],\n finance: ['finance', 'cost', 'billing'],\n company: ['company', 'strategy'],\n marketing: ['marketing', 'content', 'seo'],\n};\n\nexport interface GitHubStats {\n prsOpened: number;\n prsMerged: number;\n issuesClosed: number;\n issuesOpen: number;\n bySquad: Map<string, SquadGitHubStats>;\n}\n\nexport interface SquadGitHubStats {\n prsOpened: number;\n prsMerged: number;\n issuesClosed: number;\n issuesOpen: number;\n commits: number;\n recentIssues: { title: string; number: number; state: string }[];\n recentPRs: { title: string; number: number; merged: boolean }[];\n}\n\nexport function getGitHubStats(basePath: string, days: number = 30): GitHubStats {\n const stats: GitHubStats = {\n prsOpened: 0,\n prsMerged: 0,\n issuesClosed: 0,\n issuesOpen: 0,\n bySquad: new Map(),\n };\n\n // Initialize squad stats\n for (const squad of Object.keys(SQUAD_REPO_MAP)) {\n stats.bySquad.set(squad, {\n prsOpened: 0,\n prsMerged: 0,\n issuesClosed: 0,\n issuesOpen: 0,\n commits: 0,\n recentIssues: [],\n recentPRs: [],\n });\n }\n\n const repos = ['hq', 'agents-squads-web'];\n const since = new Date(Date.now() - days * 24 * 60 * 60 * 1000).toISOString();\n\n for (const repo of repos) {\n const repoPath = join(basePath, repo);\n if (!existsSync(repoPath)) continue;\n\n try {\n // Get PRs\n const prsOutput = execSync(\n `gh pr list --state all --json number,title,createdAt,mergedAt,labels --limit 100 2>/dev/null`,\n { cwd: repoPath, encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] }\n );\n const prs = JSON.parse(prsOutput || '[]');\n\n for (const pr of prs) {\n const created = new Date(pr.createdAt);\n if (created < new Date(since)) continue;\n\n stats.prsOpened++;\n if (pr.mergedAt) stats.prsMerged++;\n\n // Detect squad from labels or title\n const squad = detectSquadFromPR(pr, repo);\n const squadStats = stats.bySquad.get(squad);\n if (squadStats) {\n squadStats.prsOpened++;\n if (pr.mergedAt) squadStats.prsMerged++;\n if (squadStats.recentPRs.length < 3) {\n squadStats.recentPRs.push({\n title: pr.title,\n number: pr.number,\n merged: !!pr.mergedAt,\n });\n }\n }\n }\n\n // Get Issues\n const issuesOutput = execSync(\n `gh issue list --state all --json number,title,state,closedAt,labels --limit 100 2>/dev/null`,\n { cwd: repoPath, encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] }\n );\n const issues = JSON.parse(issuesOutput || '[]');\n\n for (const issue of issues) {\n const squad = detectSquadFromIssue(issue, repo);\n const squadStats = stats.bySquad.get(squad);\n\n if (issue.state === 'CLOSED') {\n const closed = new Date(issue.closedAt);\n if (closed >= new Date(since)) {\n stats.issuesClosed++;\n if (squadStats) {\n squadStats.issuesClosed++;\n }\n }\n } else {\n stats.issuesOpen++;\n if (squadStats) {\n squadStats.issuesOpen++;\n if (squadStats.recentIssues.length < 3) {\n squadStats.recentIssues.push({\n title: issue.title,\n number: issue.number,\n state: issue.state,\n });\n }\n }\n }\n }\n } catch {\n // gh not available or not in repo\n }\n }\n\n // Add commit counts per squad\n const gitStats = getMultiRepoGitStats(basePath, days);\n for (const [repo, commits] of gitStats.commitsByRepo) {\n // Map repo to squad\n for (const [squad, repos] of Object.entries(SQUAD_REPO_MAP)) {\n if (repos.includes(repo)) {\n const squadStats = stats.bySquad.get(squad);\n if (squadStats) {\n squadStats.commits += commits;\n }\n }\n }\n }\n\n return stats;\n}\n\nfunction detectSquadFromPR(pr: { title: string; labels: { name: string }[] }, repo: string): string {\n // Check labels first\n for (const label of pr.labels || []) {\n const labelLower = label.name.toLowerCase();\n for (const [squad, patterns] of Object.entries(SQUAD_LABELS)) {\n if (patterns.some(p => labelLower.includes(p))) {\n return squad;\n }\n }\n }\n\n // Check title\n const titleLower = pr.title.toLowerCase();\n for (const [squad, patterns] of Object.entries(SQUAD_LABELS)) {\n if (patterns.some(p => titleLower.includes(p))) {\n return squad;\n }\n }\n\n // Default based on repo\n if (repo === 'agents-squads-web') return 'website';\n if (repo === 'squads-cli') return 'product';\n return 'engineering';\n}\n\nfunction detectSquadFromIssue(issue: { title: string; labels: { name: string }[] }, repo: string): string {\n // Check labels first\n for (const label of issue.labels || []) {\n const labelLower = label.name.toLowerCase();\n\n // Direct squad label match\n if (labelLower.startsWith('squad:')) {\n return labelLower.replace('squad:', '');\n }\n\n for (const [squad, patterns] of Object.entries(SQUAD_LABELS)) {\n if (patterns.some(p => labelLower.includes(p))) {\n return squad;\n }\n }\n }\n\n // Check title\n const titleLower = issue.title.toLowerCase();\n for (const [squad, patterns] of Object.entries(SQUAD_LABELS)) {\n if (patterns.some(p => titleLower.includes(p))) {\n return squad;\n }\n }\n\n // Default based on repo\n if (repo === 'agents-squads-web') return 'website';\n if (repo === 'squads-cli') return 'product';\n return 'engineering';\n}\n\nexport function getMultiRepoGitStats(basePath: string, days: number = 30): GitPerformanceStats {\n const stats: GitPerformanceStats = {\n totalCommits: 0,\n commitsByDay: new Map(),\n commitsByAuthor: new Map(),\n commitsByRepo: new Map(),\n activeDays: 0,\n avgCommitsPerDay: 0,\n peakDay: null,\n repos: [],\n };\n\n for (const repo of SQUAD_REPOS) {\n const repoPath = join(basePath, repo);\n if (!existsSync(repoPath) || !existsSync(join(repoPath, '.git'))) {\n continue;\n }\n\n try {\n // Get commits from this repo (use %aN to respect .mailmap)\n const logOutput = execSync(\n `git log --since=\"${days} days ago\" --format=\"%H|%aN|%ad|%s\" --date=short 2>/dev/null`,\n { cwd: repoPath, encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] }\n ).trim();\n\n if (!logOutput) continue;\n\n const commits = logOutput.split('\\n').filter(l => l.trim());\n const authors = new Set<string>();\n let lastCommit = '';\n\n for (const line of commits) {\n const [hash, author, date, message] = line.split('|');\n if (!hash) continue;\n\n stats.totalCommits++;\n authors.add(author);\n if (!lastCommit) lastCommit = date;\n\n // By day\n const dayCount = stats.commitsByDay.get(date) || 0;\n stats.commitsByDay.set(date, dayCount + 1);\n\n // By author\n const authorCount = stats.commitsByAuthor.get(author) || 0;\n stats.commitsByAuthor.set(author, authorCount + 1);\n\n // By repo\n const repoCount = stats.commitsByRepo.get(repo) || 0;\n stats.commitsByRepo.set(repo, repoCount + 1);\n }\n\n stats.repos.push({\n name: repo,\n path: repoPath,\n commits: commits.length,\n lastCommit,\n authors: Array.from(authors),\n });\n\n } catch {\n // Skip repos that fail\n }\n }\n\n // Calculate derived stats\n stats.activeDays = stats.commitsByDay.size;\n stats.avgCommitsPerDay = stats.activeDays > 0\n ? Math.round((stats.totalCommits / days) * 10) / 10\n : 0;\n\n // Find peak day\n let peakCount = 0;\n let peakDate = '';\n for (const [date, count] of stats.commitsByDay) {\n if (count > peakCount) {\n peakCount = count;\n peakDate = date;\n }\n }\n if (peakDate) {\n stats.peakDay = { date: peakDate, count: peakCount };\n }\n\n return stats;\n}\n\n// Get recent activity sparkline data (last 7 days)\nexport function getActivitySparkline(basePath: string, days: number = 7): number[] {\n const activity: number[] = [];\n const now = new Date();\n\n for (let i = days - 1; i >= 0; i--) {\n const date = new Date(now);\n date.setDate(date.getDate() - i);\n const dateStr = date.toISOString().split('T')[0];\n activity.push(0);\n }\n\n for (const repo of SQUAD_REPOS) {\n const repoPath = join(basePath, repo);\n if (!existsSync(repoPath) || !existsSync(join(repoPath, '.git'))) {\n continue;\n }\n\n try {\n const logOutput = execSync(\n `git log --since=\"${days} days ago\" --format=\"%ad\" --date=short 2>/dev/null`,\n { cwd: repoPath, encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] }\n ).trim();\n\n if (!logOutput) continue;\n\n for (const dateStr of logOutput.split('\\n')) {\n const commitDate = new Date(dateStr);\n const daysAgo = Math.floor((now.getTime() - commitDate.getTime()) / (1000 * 60 * 60 * 24));\n const index = days - 1 - daysAgo;\n if (index >= 0 && index < days) {\n activity[index]++;\n }\n }\n } catch {\n // Skip\n }\n }\n\n return activity;\n}\n","import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'fs';\nimport { join } from 'path';\nimport { homedir } from 'os';\nimport { randomUUID } from 'crypto';\n\ninterface TelemetryEvent {\n event: string;\n timestamp: string;\n properties?: Record<string, string | number | boolean | undefined>;\n}\n\ninterface TelemetryConfig {\n enabled: boolean;\n anonymousId: string;\n firstRun: string;\n}\n\nconst TELEMETRY_DIR = join(homedir(), '.squads-cli');\nconst CONFIG_PATH = join(TELEMETRY_DIR, 'telemetry.json');\nconst EVENTS_PATH = join(TELEMETRY_DIR, 'events.json');\n\n// Telemetry endpoint - bridge or cloud\nconst TELEMETRY_ENDPOINT = process.env.SQUADS_TELEMETRY_URL ||\n (process.env.SQUADS_BRIDGE_URL ? `${process.env.SQUADS_BRIDGE_URL}/api/telemetry` : null);\n\n// Event queue for batch flushing\nlet eventQueue: TelemetryEvent[] = [];\nlet flushScheduled = false;\n\nfunction ensureDir(): void {\n if (!existsSync(TELEMETRY_DIR)) {\n mkdirSync(TELEMETRY_DIR, { recursive: true });\n }\n}\n\nfunction getConfig(): TelemetryConfig {\n ensureDir();\n\n if (!existsSync(CONFIG_PATH)) {\n const config: TelemetryConfig = {\n enabled: true, // Opt-out by default (common for CLIs)\n anonymousId: randomUUID(),\n firstRun: new Date().toISOString(),\n };\n writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2));\n return config;\n }\n\n try {\n return JSON.parse(readFileSync(CONFIG_PATH, 'utf-8'));\n } catch {\n return { enabled: false, anonymousId: '', firstRun: '' };\n }\n}\n\nfunction saveConfig(config: TelemetryConfig): void {\n ensureDir();\n writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2));\n}\n\nexport function isEnabled(): boolean {\n // Check environment variable first (allows CI/testing override)\n if (process.env.SQUADS_TELEMETRY_DISABLED === '1') {\n return false;\n }\n if (process.env.DO_NOT_TRACK === '1') {\n return false;\n }\n\n return getConfig().enabled;\n}\n\nexport function enable(): void {\n const config = getConfig();\n config.enabled = true;\n saveConfig(config);\n}\n\nexport function disable(): void {\n const config = getConfig();\n config.enabled = false;\n saveConfig(config);\n}\n\nexport function getAnonymousId(): string {\n return getConfig().anonymousId;\n}\n\nexport async function track(event: string, properties?: Record<string, string | number | boolean | undefined>): Promise<void> {\n if (!isEnabled()) return;\n\n const config = getConfig();\n\n const telemetryEvent: TelemetryEvent = {\n event,\n timestamp: new Date().toISOString(),\n properties: {\n ...properties,\n anonymousId: config.anonymousId,\n cliVersion: process.env.npm_package_version || 'unknown',\n },\n };\n\n // Store locally (for debugging/review)\n storeEventLocally(telemetryEvent);\n\n // Queue for batch sending\n eventQueue.push(telemetryEvent);\n\n // Schedule flush if not already scheduled\n if (TELEMETRY_ENDPOINT && !flushScheduled) {\n flushScheduled = true;\n // Flush on next tick to batch events from same command\n setImmediate(() => {\n flushEvents().catch(() => {});\n });\n }\n}\n\n/**\n * Flush queued events to the telemetry endpoint\n */\nexport async function flushEvents(): Promise<void> {\n if (!TELEMETRY_ENDPOINT || eventQueue.length === 0) {\n flushScheduled = false;\n return;\n }\n\n const batch = [...eventQueue];\n eventQueue = [];\n flushScheduled = false;\n\n try {\n await fetch(TELEMETRY_ENDPOINT, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ events: batch }),\n });\n } catch {\n // Restore events on failure (will retry on next track)\n eventQueue = [...batch, ...eventQueue].slice(-100); // Keep max 100\n }\n}\n\n/**\n * Track an error event\n */\nexport async function trackError(\n command: string,\n error: Error,\n context?: Record<string, string | number | boolean>\n): Promise<void> {\n await track(Events.CLI_ERROR, {\n command,\n errorType: error.constructor.name,\n errorMessage: error.message.slice(0, 100), // Truncate for privacy\n ...context,\n });\n}\n\n/**\n * Wrap an async command function with telemetry\n */\nexport function instrumentCommand<T>(\n name: string,\n fn: () => Promise<T>\n): () => Promise<T> {\n return async () => {\n const start = Date.now();\n try {\n const result = await fn();\n await track(`cli.${name}`, {\n durationMs: Date.now() - start,\n success: true,\n });\n return result;\n } catch (error) {\n await trackError(name, error as Error, {\n durationMs: Date.now() - start,\n });\n throw error;\n }\n };\n}\n\nfunction storeEventLocally(event: TelemetryEvent): void {\n ensureDir();\n\n let events: TelemetryEvent[] = [];\n\n if (existsSync(EVENTS_PATH)) {\n try {\n events = JSON.parse(readFileSync(EVENTS_PATH, 'utf-8'));\n } catch {\n events = [];\n }\n }\n\n // Keep last 1000 events\n events.push(event);\n if (events.length > 1000) {\n events = events.slice(-1000);\n }\n\n writeFileSync(EVENTS_PATH, JSON.stringify(events, null, 2));\n}\n\n// Pre-defined events for consistency\nexport const Events = {\n // Lifecycle\n CLI_INIT: 'cli.init',\n CLI_ERROR: 'cli.error',\n\n // Commands\n CLI_RUN: 'cli.run',\n CLI_STATUS: 'cli.status',\n CLI_DASHBOARD: 'cli.dashboard',\n CLI_WORKERS: 'cli.workers',\n\n // Goals\n CLI_GOAL_SET: 'cli.goal.set',\n CLI_GOAL_LIST: 'cli.goal.list',\n CLI_GOAL_COMPLETE: 'cli.goal.complete',\n CLI_GOAL_PROGRESS: 'cli.goal.progress',\n\n // Memory\n CLI_MEMORY_QUERY: 'cli.memory.query',\n CLI_MEMORY_SHOW: 'cli.memory.show',\n CLI_MEMORY_UPDATE: 'cli.memory.update',\n CLI_MEMORY_LIST: 'cli.memory.list',\n CLI_MEMORY_SYNC: 'cli.memory.sync',\n\n // Feedback\n CLI_FEEDBACK_ADD: 'cli.feedback.add',\n CLI_FEEDBACK_SHOW: 'cli.feedback.show',\n CLI_FEEDBACK_STATS: 'cli.feedback.stats',\n\n // Auth\n CLI_LOGIN: 'cli.login',\n CLI_LOGOUT: 'cli.logout',\n} as const;\n\n// Track command execution time (legacy helper)\nexport function trackCommand(command: string): () => void {\n const start = Date.now();\n\n return () => {\n const duration = Date.now() - start;\n track(`cli.${command}`, { durationMs: duration });\n };\n}\n\n// Register exit handler to flush remaining events\nlet exitHandlerRegistered = false;\n\nexport function registerExitHandler(): void {\n if (exitHandlerRegistered) return;\n exitHandlerRegistered = true;\n\n const cleanup = () => {\n // Synchronous flush attempt on exit\n if (eventQueue.length > 0 && TELEMETRY_ENDPOINT) {\n // Can't do async on exit, so just log\n storeEventLocally({\n event: 'cli.exit',\n timestamp: new Date().toISOString(),\n properties: { pendingEvents: eventQueue.length },\n });\n }\n };\n\n process.on('exit', cleanup);\n process.on('SIGINT', () => {\n cleanup();\n process.exit(0);\n });\n process.on('SIGTERM', () => {\n cleanup();\n process.exit(0);\n });\n}\n","import ora from 'ora';\nimport { spawn } from 'child_process';\nimport { join, dirname } from 'path';\nimport { existsSync, readFileSync, writeFileSync, mkdirSync } from 'fs';\nimport {\n findSquadsDir,\n loadSquad,\n listAgents,\n loadAgentDefinition\n} from '../lib/squad-parser.js';\nimport { findMemoryDir } from '../lib/memory.js';\nimport { track, Events } from '../lib/telemetry.js';\nimport {\n colors,\n bold,\n RESET,\n gradient,\n box,\n icons,\n writeLine,\n} from '../lib/terminal.js';\n\ninterface RunOptions {\n verbose?: boolean;\n dryRun?: boolean;\n agent?: string;\n}\n\ninterface ExecutionRecord {\n squadName: string;\n agentName: string;\n startTime: string;\n endTime?: string;\n status: 'running' | 'completed' | 'failed';\n outcome?: string;\n}\n\nfunction getExecutionLogPath(squadName: string, agentName: string): string | null {\n const memoryDir = findMemoryDir();\n if (!memoryDir) return null;\n return join(memoryDir, squadName, agentName, 'executions.md');\n}\n\nfunction logExecution(record: ExecutionRecord): void {\n const logPath = getExecutionLogPath(record.squadName, record.agentName);\n if (!logPath) return;\n\n const dir = dirname(logPath);\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n }\n\n let content = '';\n if (existsSync(logPath)) {\n content = readFileSync(logPath, 'utf-8');\n } else {\n content = `# ${record.squadName}/${record.agentName} - Execution Log\\n\\n`;\n }\n\n const entry = `\n---\n**${record.startTime}** | Status: ${record.status}\n${record.endTime ? `Completed: ${record.endTime}` : ''}\n${record.outcome ? `Outcome: ${record.outcome}` : ''}\n`;\n\n writeFileSync(logPath, content + entry);\n}\n\nfunction updateExecutionStatus(\n squadName: string,\n agentName: string,\n status: 'completed' | 'failed',\n outcome?: string\n): void {\n const logPath = getExecutionLogPath(squadName, agentName);\n if (!logPath || !existsSync(logPath)) return;\n\n let content = readFileSync(logPath, 'utf-8');\n const endTime = new Date().toISOString();\n\n // Update the last \"running\" entry\n content = content.replace(\n /Status: running\\n$/,\n `Status: ${status}\\nCompleted: ${endTime}\\n${outcome ? `Outcome: ${outcome}\\n` : ''}`\n );\n\n writeFileSync(logPath, content);\n}\n\nexport async function runCommand(\n target: string,\n options: RunOptions\n): Promise<void> {\n const squadsDir = findSquadsDir();\n\n if (!squadsDir) {\n writeLine(` ${colors.red}No .agents/squads directory found${RESET}`);\n writeLine(` ${colors.dim}Run \\`squads init\\` to create one.${RESET}`);\n process.exit(1);\n }\n\n // Check if target is a squad or an agent\n const squad = loadSquad(target);\n\n if (squad) {\n await track(Events.CLI_RUN, { type: 'squad', target: squad.name });\n await runSquad(squad, squadsDir, options);\n } else {\n // Try to find as an agent\n const agents = listAgents(squadsDir);\n const agent = agents.find(a => a.name === target);\n\n if (agent && agent.filePath) {\n // Extract squad name from path\n const pathParts = agent.filePath.split('/');\n const squadIdx = pathParts.indexOf('squads');\n const squadName = squadIdx >= 0 ? pathParts[squadIdx + 1] : 'unknown';\n await runAgent(agent.name, agent.filePath, squadName, options);\n } else {\n writeLine(` ${colors.red}Squad or agent \"${target}\" not found${RESET}`);\n writeLine(` ${colors.dim}Run \\`squads list\\` to see available squads and agents.${RESET}`);\n process.exit(1);\n }\n }\n}\n\nasync function runSquad(\n squad: ReturnType<typeof loadSquad>,\n squadsDir: string,\n options: RunOptions\n): Promise<void> {\n if (!squad) return;\n\n const startTime = new Date().toISOString();\n\n writeLine();\n writeLine(` ${gradient('squads')} ${colors.dim}run${RESET} ${colors.cyan}${squad.name}${RESET}`);\n writeLine();\n if (squad.mission) {\n writeLine(` ${colors.dim}${squad.mission}${RESET}`);\n writeLine();\n }\n writeLine(` ${colors.dim}Started: ${startTime}${RESET}`);\n writeLine();\n\n // If there's a pipeline, run agents in order\n if (squad.pipelines.length > 0) {\n const pipeline = squad.pipelines[0];\n writeLine(` ${bold}Pipeline${RESET} ${colors.dim}${pipeline.agents.join(' → ')}${RESET}`);\n writeLine();\n\n for (let i = 0; i < pipeline.agents.length; i++) {\n const agentName = pipeline.agents[i];\n const agentPath = join(squadsDir, squad.name, `${agentName}.md`);\n\n if (existsSync(agentPath)) {\n writeLine(` ${colors.dim}[${i + 1}/${pipeline.agents.length}]${RESET}`);\n await runAgent(agentName, agentPath, squad.name, options);\n writeLine();\n } else {\n writeLine(` ${icons.warning} ${colors.yellow}Agent ${agentName} not found, skipping${RESET}`);\n }\n }\n } else {\n // Run orchestrator if exists, otherwise list agents\n const orchestrator = squad.agents.find(a =>\n a.name.includes('lead') || a.trigger === 'Manual'\n );\n\n if (orchestrator) {\n const agentPath = join(squadsDir, squad.name, `${orchestrator.name}.md`);\n if (existsSync(agentPath)) {\n await runAgent(orchestrator.name, agentPath, squad.name, options);\n }\n } else {\n writeLine(` ${colors.dim}No pipeline defined. Available agents:${RESET}`);\n for (const agent of squad.agents) {\n writeLine(` ${icons.empty} ${colors.cyan}${agent.name}${RESET} ${colors.dim}${agent.role}${RESET}`);\n }\n writeLine();\n writeLine(` ${colors.dim}Run a specific agent:${RESET}`);\n writeLine(` ${colors.dim}$${RESET} squads run ${colors.cyan}${squad.name}${RESET} --agent ${colors.cyan}<name>${RESET}`);\n }\n }\n\n writeLine();\n writeLine(` ${colors.dim}After execution, record outcome:${RESET}`);\n writeLine(` ${colors.dim}$${RESET} squads feedback add ${colors.cyan}${squad.name}${RESET} ${colors.cyan}<1-5>${RESET} ${colors.cyan}\"<feedback>\"${RESET}`);\n writeLine();\n}\n\nasync function runAgent(\n agentName: string,\n agentPath: string,\n squadName: string,\n options: RunOptions & { execute?: boolean }\n): Promise<void> {\n const spinner = ora(`Running agent: ${agentName}`).start();\n const startTime = new Date().toISOString();\n\n const definition = loadAgentDefinition(agentPath);\n\n if (options.dryRun) {\n spinner.info(`[DRY RUN] Would run ${agentName}`);\n if (options.verbose) {\n writeLine(` ${colors.dim}Agent definition:${RESET}`);\n writeLine(` ${colors.dim}${definition.slice(0, 500)}...${RESET}`);\n }\n return;\n }\n\n // Log execution start\n logExecution({\n squadName,\n agentName,\n startTime,\n status: 'running',\n });\n\n // Generate the Claude Code prompt\n const prompt = `Execute the ${agentName} agent from squad ${squadName}.\n\nRead the agent definition at ${agentPath} and follow its instructions exactly.\n\nThe agent definition contains:\n- Purpose/role\n- Tools it can use (MCP servers, skills)\n- Step-by-step instructions\n- Expected output format\n\nAfter completion:\n1. Update the agent's memory in .agents/memory/${squadName}/${agentName}/state.md\n2. Log any learnings to learnings.md\n3. Report what was accomplished`;\n\n // Check if Claude CLI is available\n const claudeAvailable = await checkClaudeCliAvailable();\n\n if (options.execute && claudeAvailable) {\n spinner.text = `Executing ${agentName} with Claude Code...`;\n\n try {\n const result = await executeWithClaude(prompt, options.verbose);\n spinner.succeed(`Agent ${agentName} completed`);\n updateExecutionStatus(squadName, agentName, 'completed', 'Executed via Claude CLI');\n\n if (result) {\n writeLine(` ${colors.dim}Output:${RESET}`);\n writeLine(` ${result.slice(0, 500)}`);\n if (result.length > 500) writeLine(` ${colors.dim}... (truncated)${RESET}`);\n }\n } catch (error) {\n spinner.fail(`Agent ${agentName} failed`);\n updateExecutionStatus(squadName, agentName, 'failed', String(error));\n writeLine(` ${colors.red}${String(error)}${RESET}`);\n }\n } else {\n // Show instructions for manual execution\n spinner.succeed(`Agent ${agentName} ready`);\n writeLine(` ${colors.dim}Execution logged: ${startTime}${RESET}`);\n\n if (!claudeAvailable) {\n writeLine();\n writeLine(` ${colors.yellow}Claude CLI not found${RESET}`);\n writeLine(` ${colors.dim}Install: npm install -g @anthropic-ai/claude-code${RESET}`);\n }\n\n writeLine();\n writeLine(` ${colors.dim}To execute with Claude Code:${RESET}`);\n writeLine(` ${colors.dim}$${RESET} claude --print \"${prompt.replace(/\"/g, '\\\\\"').replace(/\\n/g, ' ').slice(0, 80)}...\"`);\n writeLine();\n writeLine(` ${colors.dim}Or run with --execute flag:${RESET}`);\n writeLine(` ${colors.dim}$${RESET} squads run ${colors.cyan}${squadName}${RESET} --execute`);\n writeLine();\n writeLine(` ${colors.dim}Or in Claude Code session:${RESET}`);\n writeLine(` ${colors.dim}$${RESET} Run the ${colors.cyan}${agentName}${RESET} agent from ${agentPath}`);\n }\n}\n\nasync function checkClaudeCliAvailable(): Promise<boolean> {\n return new Promise((resolve) => {\n const check = spawn('which', ['claude'], { stdio: 'pipe' });\n check.on('close', (code) => resolve(code === 0));\n check.on('error', () => resolve(false));\n });\n}\n\nasync function executeWithClaude(prompt: string, verbose?: boolean): Promise<string> {\n return new Promise((resolve, reject) => {\n const args = ['--print', prompt];\n if (verbose) {\n writeLine(` ${colors.dim}Spawning: claude ${args.slice(0, 1).join(' ')} ...${RESET}`);\n }\n\n // Extract squad/agent from prompt for telemetry tagging\n const squadMatch = prompt.match(/squad (\\w+)/);\n const agentMatch = prompt.match(/(\\w+) agent/);\n\n const claude = spawn('claude', args, {\n stdio: ['pipe', 'pipe', 'pipe'],\n env: {\n ...process.env,\n SQUADS_SQUAD: squadMatch?.[1] || 'unknown',\n SQUADS_AGENT: agentMatch?.[1] || 'unknown',\n },\n });\n\n let output = '';\n let error = '';\n\n claude.stdout?.on('data', (data) => {\n output += data.toString();\n if (verbose) {\n process.stdout.write(data.toString());\n }\n });\n\n claude.stderr?.on('data', (data) => {\n error += data.toString();\n });\n\n claude.on('close', (code) => {\n if (code === 0) {\n resolve(output);\n } else {\n reject(new Error(error || `Claude exited with code ${code}`));\n }\n });\n\n claude.on('error', (err) => {\n reject(err);\n });\n\n // Timeout after 5 minutes\n setTimeout(() => {\n claude.kill();\n reject(new Error('Execution timed out after 5 minutes'));\n }, 5 * 60 * 1000);\n });\n}\n\nexport async function runSquadCommand(\n squadName: string,\n options: RunOptions\n): Promise<void> {\n return runCommand(squadName, options);\n}\n","import { readFileSync, existsSync, readdirSync, writeFileSync } from 'fs';\nimport { join, basename } from 'path';\n\nexport interface Agent {\n name: string;\n role: string;\n trigger: string;\n status?: string;\n filePath?: string;\n squad?: string;\n}\n\nexport interface Pipeline {\n name: string;\n agents: string[];\n}\n\nexport interface Goal {\n description: string;\n completed: boolean;\n progress?: string;\n metrics?: string[];\n}\n\nexport interface Squad {\n name: string;\n mission: string;\n agents: Agent[];\n pipelines: Pipeline[];\n triggers: {\n scheduled: string[];\n event: string[];\n manual: string[];\n };\n dependencies: string[];\n outputPath: string;\n goals: Goal[];\n}\n\nexport function findSquadsDir(): string | null {\n // Look for .agents/squads in current directory or parent directories\n let dir = process.cwd();\n\n for (let i = 0; i < 5; i++) {\n const squadsPath = join(dir, '.agents', 'squads');\n if (existsSync(squadsPath)) {\n return squadsPath;\n }\n const parent = join(dir, '..');\n if (parent === dir) break;\n dir = parent;\n }\n\n return null;\n}\n\nexport function listSquads(squadsDir: string): string[] {\n const squads: string[] = [];\n\n const entries = readdirSync(squadsDir, { withFileTypes: true });\n for (const entry of entries) {\n if (entry.isDirectory() && !entry.name.startsWith('_')) {\n const squadFile = join(squadsDir, entry.name, 'SQUAD.md');\n if (existsSync(squadFile)) {\n squads.push(entry.name);\n }\n }\n }\n\n return squads;\n}\n\nexport function listAgents(squadsDir: string, squadName?: string): Agent[] {\n const agents: Agent[] = [];\n\n const dirs = squadName\n ? [squadName]\n : readdirSync(squadsDir, { withFileTypes: true })\n .filter(e => e.isDirectory() && !e.name.startsWith('_'))\n .map(e => e.name);\n\n for (const dir of dirs) {\n const squadPath = join(squadsDir, dir);\n if (!existsSync(squadPath)) continue;\n\n const files = readdirSync(squadPath);\n for (const file of files) {\n if (file.endsWith('.md') && file !== 'SQUAD.md') {\n const agentName = file.replace('.md', '');\n agents.push({\n name: agentName,\n role: `Agent in ${dir}`,\n trigger: 'manual',\n filePath: join(squadPath, file)\n });\n }\n }\n }\n\n return agents;\n}\n\nexport function parseSquadFile(filePath: string): Squad {\n const content = readFileSync(filePath, 'utf-8');\n const lines = content.split('\\n');\n\n const squad: Squad = {\n name: basename(filePath).replace('.md', ''),\n mission: '',\n agents: [],\n pipelines: [],\n triggers: { scheduled: [], event: [], manual: [] },\n dependencies: [],\n outputPath: '',\n goals: []\n };\n\n let currentSection = '';\n let inTable = false;\n let tableHeaders: string[] = [];\n\n for (const line of lines) {\n // Extract squad name from title\n if (line.startsWith('# Squad:')) {\n squad.name = line.replace('# Squad:', '').trim().toLowerCase();\n continue;\n }\n\n // Track sections\n if (line.startsWith('## ')) {\n currentSection = line.replace('## ', '').trim().toLowerCase();\n inTable = false;\n continue;\n }\n\n // Extract mission\n if (currentSection === 'mission' && line.trim() && !line.startsWith('#')) {\n if (!squad.mission) {\n squad.mission = line.trim();\n }\n }\n\n // Parse agent tables\n if (currentSection.includes('agent') || currentSection.includes('orchestrator') ||\n currentSection.includes('evaluator') || currentSection.includes('builder') ||\n currentSection.includes('priority')) {\n\n if (line.includes('|') && line.includes('Agent')) {\n inTable = true;\n tableHeaders = line.split('|').map(h => h.trim().toLowerCase());\n continue;\n }\n\n if (inTable && line.includes('|') && !line.includes('---')) {\n const cells = line.split('|').map(c => c.trim().replace(/`/g, ''));\n const agentIdx = tableHeaders.findIndex(h => h === 'agent');\n const roleIdx = tableHeaders.findIndex(h => h === 'role');\n const triggerIdx = tableHeaders.findIndex(h => h === 'trigger');\n const statusIdx = tableHeaders.findIndex(h => h === 'status');\n\n if (agentIdx >= 0 && cells[agentIdx]) {\n squad.agents.push({\n name: cells[agentIdx],\n role: roleIdx >= 0 ? cells[roleIdx] : '',\n trigger: triggerIdx >= 0 ? cells[triggerIdx] : 'manual',\n status: statusIdx >= 0 ? cells[statusIdx] : 'active'\n });\n }\n }\n }\n\n // Parse pipelines (looking for patterns like: agent1 → agent2 → agent3)\n if (line.includes('→') && line.includes('`')) {\n const pipelineMatch = line.match(/`([^`]+)`\\s*→\\s*`([^`]+)`/g);\n if (pipelineMatch) {\n const agentNames = line.match(/`([^`]+)`/g)?.map(m => m.replace(/`/g, '')) || [];\n if (agentNames.length >= 2) {\n squad.pipelines.push({\n name: 'default',\n agents: agentNames\n });\n }\n }\n }\n\n // Also look for Pipeline: format\n if (line.toLowerCase().includes('pipeline:')) {\n const pipelineContent = line.split(':')[1];\n if (pipelineContent && pipelineContent.includes('→')) {\n const agentNames = pipelineContent.match(/`([^`]+)`/g)?.map(m => m.replace(/`/g, '')) || [];\n if (agentNames.length >= 2) {\n squad.pipelines.push({\n name: 'default',\n agents: agentNames\n });\n }\n }\n }\n\n // Extract output path\n if (line.toLowerCase().includes('primary') && line.includes('`')) {\n const match = line.match(/`([^`]+)`/);\n if (match) {\n squad.outputPath = match[1].replace(/\\/$/, '');\n }\n }\n\n // Parse goals (checkbox format: - [ ] or - [x])\n if (currentSection === 'goals') {\n const goalMatch = line.match(/^-\\s*\\[([ x])\\]\\s*(.+)$/);\n if (goalMatch) {\n const completed = goalMatch[1] === 'x';\n let description = goalMatch[2].trim();\n let progress: string | undefined;\n\n // Check for progress annotation\n const progressMatch = description.match(/\\(progress:\\s*([^)]+)\\)/i);\n if (progressMatch) {\n progress = progressMatch[1];\n description = description.replace(progressMatch[0], '').trim();\n }\n\n squad.goals.push({\n description,\n completed,\n progress\n });\n }\n }\n }\n\n return squad;\n}\n\nexport function loadSquad(squadName: string): Squad | null {\n const squadsDir = findSquadsDir();\n if (!squadsDir) return null;\n\n const squadFile = join(squadsDir, squadName, 'SQUAD.md');\n if (!existsSync(squadFile)) return null;\n\n return parseSquadFile(squadFile);\n}\n\nexport function loadAgentDefinition(agentPath: string): string {\n if (!existsSync(agentPath)) return '';\n return readFileSync(agentPath, 'utf-8');\n}\n\nexport function addGoalToSquad(squadName: string, goal: string): boolean {\n const squadsDir = findSquadsDir();\n if (!squadsDir) return false;\n\n const squadFile = join(squadsDir, squadName, 'SQUAD.md');\n if (!existsSync(squadFile)) return false;\n\n let content = readFileSync(squadFile, 'utf-8');\n\n // Check if Goals section exists\n if (!content.includes('## Goals')) {\n // Add Goals section before Dependencies or at end\n const insertPoint = content.indexOf('## Dependencies');\n if (insertPoint > 0) {\n content = content.slice(0, insertPoint) + `## Goals\\n\\n- [ ] ${goal}\\n\\n` + content.slice(insertPoint);\n } else {\n content += `\\n## Goals\\n\\n- [ ] ${goal}\\n`;\n }\n } else {\n // Add to existing Goals section\n const goalsIdx = content.indexOf('## Goals');\n const nextSectionIdx = content.indexOf('\\n## ', goalsIdx + 1);\n const endIdx = nextSectionIdx > 0 ? nextSectionIdx : content.length;\n\n // Find last goal line or section header\n const goalsSection = content.slice(goalsIdx, endIdx);\n const lastGoalMatch = goalsSection.match(/^-\\s*\\[[ x]\\].+$/gm);\n\n if (lastGoalMatch) {\n // Add after last goal\n const lastGoal = lastGoalMatch[lastGoalMatch.length - 1];\n const lastGoalIdx = content.lastIndexOf(lastGoal, endIdx);\n const insertPos = lastGoalIdx + lastGoal.length;\n content = content.slice(0, insertPos) + `\\n- [ ] ${goal}` + content.slice(insertPos);\n } else {\n // No goals yet, add after section header\n const headerEnd = goalsIdx + '## Goals'.length;\n content = content.slice(0, headerEnd) + `\\n\\n- [ ] ${goal}` + content.slice(headerEnd);\n }\n }\n\n writeFileSync(squadFile, content);\n return true;\n}\n\nexport function updateGoalInSquad(\n squadName: string,\n goalIndex: number,\n updates: { completed?: boolean; progress?: string }\n): boolean {\n const squadsDir = findSquadsDir();\n if (!squadsDir) return false;\n\n const squadFile = join(squadsDir, squadName, 'SQUAD.md');\n if (!existsSync(squadFile)) return false;\n\n const content = readFileSync(squadFile, 'utf-8');\n const lines = content.split('\\n');\n\n let currentSection = '';\n let goalCount = 0;\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n\n if (line.startsWith('## ')) {\n currentSection = line.replace('## ', '').trim().toLowerCase();\n continue;\n }\n\n if (currentSection === 'goals') {\n const goalMatch = line.match(/^-\\s*\\[([ x])\\]\\s*(.+)$/);\n if (goalMatch) {\n if (goalCount === goalIndex) {\n let newLine = '- [' + (updates.completed ? 'x' : ' ') + '] ' + goalMatch[2];\n\n // Handle progress update\n if (updates.progress !== undefined) {\n // Remove existing progress annotation\n newLine = newLine.replace(/\\s*\\(progress:\\s*[^)]+\\)/i, '');\n if (updates.progress) {\n newLine += ` (progress: ${updates.progress})`;\n }\n }\n\n lines[i] = newLine;\n writeFileSync(squadFile, lines.join('\\n'));\n return true;\n }\n goalCount++;\n }\n }\n }\n\n return false;\n}\n","import { readFileSync, writeFileSync, existsSync, readdirSync, mkdirSync } from 'fs';\nimport { join, dirname } from 'path';\n\nexport interface MemoryEntry {\n squad: string;\n agent: string;\n type: 'state' | 'output' | 'learnings' | 'feedback';\n content: string;\n path: string;\n lastUpdated?: string;\n}\n\nexport interface SearchResult {\n entry: MemoryEntry;\n matches: string[];\n score: number;\n}\n\nexport function findMemoryDir(): string | null {\n let dir = process.cwd();\n\n for (let i = 0; i < 5; i++) {\n const memoryPath = join(dir, '.agents', 'memory');\n if (existsSync(memoryPath)) {\n return memoryPath;\n }\n const parent = join(dir, '..');\n if (parent === dir) break;\n dir = parent;\n }\n\n return null;\n}\n\nexport function listMemoryEntries(memoryDir: string): MemoryEntry[] {\n const entries: MemoryEntry[] = [];\n\n const squads = readdirSync(memoryDir, { withFileTypes: true })\n .filter(e => e.isDirectory())\n .map(e => e.name);\n\n for (const squad of squads) {\n const squadPath = join(memoryDir, squad);\n const agents = readdirSync(squadPath, { withFileTypes: true })\n .filter(e => e.isDirectory())\n .map(e => e.name);\n\n for (const agent of agents) {\n const agentPath = join(squadPath, agent);\n const files = readdirSync(agentPath).filter(f => f.endsWith('.md'));\n\n for (const file of files) {\n const filePath = join(agentPath, file);\n const type = file.replace('.md', '') as MemoryEntry['type'];\n\n entries.push({\n squad,\n agent,\n type,\n content: readFileSync(filePath, 'utf-8'),\n path: filePath\n });\n }\n }\n }\n\n return entries;\n}\n\n// Semantic expansions for common business terms\nconst SEMANTIC_EXPANSIONS: Record<string, string[]> = {\n 'pricing': ['price', 'cost', '$', 'revenue', 'fee', 'rate'],\n 'price': ['pricing', 'cost', '$', 'fee'],\n 'revenue': ['income', 'sales', 'mrr', 'arr', '$'],\n 'cost': ['expense', 'spend', 'budget', '$', 'price'],\n 'customer': ['client', 'lead', 'prospect', 'user'],\n 'client': ['customer', 'lead', 'prospect'],\n 'lead': ['prospect', 'customer', 'client', 'pipeline'],\n 'agent': ['squad', 'bot', 'ai'],\n 'squad': ['team', 'agent', 'group'],\n 'status': ['state', 'progress', 'health'],\n 'bug': ['issue', 'error', 'problem', 'fix'],\n 'feature': ['capability', 'function', 'ability'],\n};\n\nfunction expandQuery(query: string): string[] {\n const words = query.toLowerCase().split(/\\s+/);\n const expanded = new Set(words);\n\n for (const word of words) {\n if (SEMANTIC_EXPANSIONS[word]) {\n SEMANTIC_EXPANSIONS[word].forEach(syn => expanded.add(syn));\n }\n }\n\n return Array.from(expanded);\n}\n\nfunction getFileAge(filePath: string): number {\n try {\n const { statSync } = require('fs');\n const stats = statSync(filePath);\n const ageMs = Date.now() - stats.mtimeMs;\n const ageDays = ageMs / (1000 * 60 * 60 * 24);\n return ageDays;\n } catch {\n return 999;\n }\n}\n\nexport function searchMemory(query: string, memoryDir?: string): SearchResult[] {\n const dir = memoryDir || findMemoryDir();\n if (!dir) return [];\n\n const entries = listMemoryEntries(dir);\n const results: SearchResult[] = [];\n const queryLower = query.toLowerCase();\n const expandedTerms = expandQuery(queryLower);\n\n for (const entry of entries) {\n const contentLower = entry.content.toLowerCase();\n const lines = entry.content.split('\\n');\n const matches: string[] = [];\n let score = 0;\n let directHits = 0;\n let expandedHits = 0;\n\n // Check direct query words first\n const directWords = queryLower.split(/\\s+/);\n for (const word of directWords) {\n if (contentLower.includes(word)) {\n directHits += 1;\n score += 2; // Direct matches worth more\n }\n }\n\n // Check expanded terms\n for (const term of expandedTerms) {\n if (contentLower.includes(term)) {\n expandedHits += 1;\n score += 0.5; // Expanded matches worth less but still count\n\n // Find matching lines with context\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n if (line.toLowerCase().includes(term) && line.trim() && !matches.includes(line.trim())) {\n matches.push(line.trim());\n }\n }\n }\n }\n\n // Boost score for exact phrase match\n if (contentLower.includes(queryLower)) {\n score += 5;\n }\n\n // Recency boost - files updated recently are more relevant\n const ageDays = getFileAge(entry.path);\n if (ageDays < 1) {\n score *= 1.5; // Updated today\n } else if (ageDays < 7) {\n score *= 1.2; // Updated this week\n } else if (ageDays > 30) {\n score *= 0.8; // Stale data penalty\n }\n\n // Type weighting - balanced across types\n const typeWeights: Record<string, number> = {\n 'state': 1.2, // Current state slightly preferred\n 'learnings': 1.1, // Learnings are valuable\n 'output': 1.0, // Recent outputs\n 'feedback': 0.9, // Feedback less commonly needed\n };\n score *= typeWeights[entry.type] || 1.0;\n\n if (score > 0 && (directHits > 0 || expandedHits > 1)) {\n results.push({ entry, matches: matches.slice(0, 7), score });\n }\n }\n\n // Sort by score descending\n return results.sort((a, b) => b.score - a.score);\n}\n\nexport function getSquadState(squadName: string): MemoryEntry[] {\n const memoryDir = findMemoryDir();\n if (!memoryDir) return [];\n\n const squadPath = join(memoryDir, squadName);\n if (!existsSync(squadPath)) return [];\n\n const entries: MemoryEntry[] = [];\n const agents = readdirSync(squadPath, { withFileTypes: true })\n .filter(e => e.isDirectory())\n .map(e => e.name);\n\n for (const agent of agents) {\n const statePath = join(squadPath, agent, 'state.md');\n if (existsSync(statePath)) {\n entries.push({\n squad: squadName,\n agent,\n type: 'state',\n content: readFileSync(statePath, 'utf-8'),\n path: statePath\n });\n }\n }\n\n return entries;\n}\n\nexport function updateMemory(\n squadName: string,\n agentName: string,\n type: MemoryEntry['type'],\n content: string\n): void {\n const memoryDir = findMemoryDir();\n if (!memoryDir) {\n throw new Error('No .agents/memory directory found');\n }\n\n const filePath = join(memoryDir, squadName, agentName, `${type}.md`);\n const dir = dirname(filePath);\n\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n }\n\n writeFileSync(filePath, content);\n}\n\nexport function appendToMemory(\n squadName: string,\n agentName: string,\n type: MemoryEntry['type'],\n addition: string\n): void {\n const memoryDir = findMemoryDir();\n if (!memoryDir) {\n throw new Error('No .agents/memory directory found');\n }\n\n const filePath = join(memoryDir, squadName, agentName, `${type}.md`);\n\n let existing = '';\n if (existsSync(filePath)) {\n existing = readFileSync(filePath, 'utf-8');\n }\n\n const timestamp = new Date().toISOString().split('T')[0];\n const newContent = existing + `\\n\\n---\\n_Added: ${timestamp}_\\n\\n${addition}`;\n\n updateMemory(squadName, agentName, type, newContent.trim());\n}\n","// Terminal utilities - Bun-style approach\n// Raw ANSI for performance, no heavy deps\n\n// ANSI escape codes\nexport const ESC = '\\x1b[';\nexport const RESET = `${ESC}0m`;\n\n// Colors (256-color mode for gradients)\nexport const rgb = (r: number, g: number, b: number) => `${ESC}38;2;${r};${g};${b}m`;\nexport const bgRgb = (r: number, g: number, b: number) => `${ESC}48;2;${r};${g};${b}m`;\n\n// Named colors (our brand palette)\nexport const colors = {\n purple: rgb(168, 85, 247), // #a855f7\n pink: rgb(236, 72, 153), // #ec4899\n cyan: rgb(6, 182, 212), // #06b6d4\n green: rgb(16, 185, 129), // #10b981\n yellow: rgb(234, 179, 8), // #eab308\n red: rgb(239, 68, 68), // #ef4444\n gray: rgb(107, 114, 128), // #6b7280\n dim: rgb(75, 85, 99), // #4b5563\n white: rgb(255, 255, 255),\n};\n\n// Styles\nexport const bold = `${ESC}1m`;\nexport const dim = `${ESC}2m`;\n\n// Cursor control\nexport const cursor = {\n hide: `${ESC}?25l`,\n show: `${ESC}?25h`,\n up: (n = 1) => `${ESC}${n}A`,\n down: (n = 1) => `${ESC}${n}B`,\n left: (n = 1) => `${ESC}${n}D`,\n right: (n = 1) => `${ESC}${n}C`,\n to: (x: number, y: number) => `${ESC}${y};${x}H`,\n save: `${ESC}s`,\n restore: `${ESC}u`,\n};\n\n// Clear\nexport const clear = {\n line: `${ESC}2K`,\n toEnd: `${ESC}0K`,\n screen: `${ESC}2J${ESC}0;0H`,\n};\n\n// Gradient text (purple → pink → cyan)\nexport function gradient(text: string): string {\n const stops = [\n [168, 85, 247], // purple\n [192, 132, 252], // purple-light\n [232, 121, 249], // pink\n [244, 114, 182], // pink-light\n [251, 113, 133], // rose\n ];\n\n let result = '';\n for (let i = 0; i < text.length; i++) {\n const t = i / Math.max(text.length - 1, 1);\n const stopIndex = t * (stops.length - 1);\n const lower = Math.floor(stopIndex);\n const upper = Math.min(lower + 1, stops.length - 1);\n const blend = stopIndex - lower;\n\n const r = Math.round(stops[lower][0] + (stops[upper][0] - stops[lower][0]) * blend);\n const g = Math.round(stops[lower][1] + (stops[upper][1] - stops[lower][1]) * blend);\n const b = Math.round(stops[lower][2] + (stops[upper][2] - stops[lower][2]) * blend);\n\n result += rgb(r, g, b) + text[i];\n }\n return result + RESET;\n}\n\n// Progress bar with gradient fill\nexport function progressBar(percent: number, width = 20): string {\n const filled = Math.round((percent / 100) * width);\n const empty = width - filled;\n\n let bar = '';\n for (let i = 0; i < filled; i++) {\n const t = i / Math.max(filled - 1, 1);\n const r = Math.round(16 + (168 - 16) * t);\n const g = Math.round(185 + (85 - 185) * t);\n const b = Math.round(129 + (247 - 129) * t);\n bar += rgb(r, g, b) + '━';\n }\n\n bar += colors.dim + '━'.repeat(empty) + RESET;\n return bar;\n}\n\n// Box drawing\nexport const box = {\n topLeft: '┌',\n topRight: '┐',\n bottomLeft: '└',\n bottomRight: '┘',\n horizontal: '─',\n vertical: '│',\n teeRight: '├',\n teeLeft: '┤',\n};\n\n// Format helpers\nexport function padEnd(str: string, len: number): string {\n // Strip ANSI codes for length calculation\n const visible = str.replace(/\\x1b\\[[0-9;]*m/g, '');\n const pad = Math.max(0, len - visible.length);\n return str + ' '.repeat(pad);\n}\n\nexport function truncate(str: string, len: number): string {\n const visible = str.replace(/\\x1b\\[[0-9;]*m/g, '');\n if (visible.length <= len) return str;\n\n // Simple truncation (won't handle mid-ANSI truncation perfectly)\n let result = '';\n let count = 0;\n let i = 0;\n\n while (i < str.length && count < len - 1) {\n if (str[i] === '\\x1b') {\n const end = str.indexOf('m', i);\n if (end !== -1) {\n result += str.slice(i, end + 1);\n i = end + 1;\n continue;\n }\n }\n result += str[i];\n count++;\n i++;\n }\n\n return result + colors.dim + '…' + RESET;\n}\n\n// Spinner frames\nexport const spinnerFrames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];\n\n// Status icons\nexport const icons = {\n success: `${colors.green}●${RESET}`,\n warning: `${colors.yellow}○${RESET}`,\n error: `${colors.red}●${RESET}`,\n pending: `${colors.dim}○${RESET}`,\n active: `${colors.green}●${RESET}`,\n progress: `${colors.cyan}◆${RESET}`,\n empty: `${colors.dim}◇${RESET}`,\n};\n\n// Write without newline\nexport function write(str: string): void {\n process.stdout.write(str);\n}\n\n// Write line\nexport function writeLine(str = ''): void {\n process.stdout.write(str + '\\n');\n}\n\n// Sparkline chart using block characters\nexport function sparkline(values: number[], width?: number): string {\n if (values.length === 0) return '';\n\n const blocks = ['▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'];\n const max = Math.max(...values, 1);\n\n let result = '';\n for (const val of values) {\n const normalized = val / max;\n const blockIndex = Math.min(Math.floor(normalized * blocks.length), blocks.length - 1);\n const intensity = normalized;\n\n // Color gradient from dim to cyan to green based on value\n if (normalized === 0) {\n result += colors.dim + blocks[0];\n } else if (normalized < 0.5) {\n result += colors.cyan + blocks[blockIndex];\n } else {\n result += colors.green + blocks[blockIndex];\n }\n }\n\n return result + RESET;\n}\n\n// Bar chart (horizontal)\nexport function barChart(value: number, max: number, width: number = 20, label?: string): string {\n const filled = Math.round((value / max) * width);\n const empty = width - filled;\n\n let bar = '';\n for (let i = 0; i < filled; i++) {\n const t = i / Math.max(filled - 1, 1);\n // Green to cyan gradient\n const r = Math.round(16 + (6 - 16) * t);\n const g = Math.round(185 + (182 - 185) * t);\n const b = Math.round(129 + (212 - 129) * t);\n bar += rgb(r, g, b) + '━';\n }\n\n bar += colors.dim + '━'.repeat(empty) + RESET;\n\n if (label) {\n return `${bar} ${label}`;\n }\n return bar;\n}\n","import {\n findSquadsDir,\n listSquads,\n listAgents\n} from '../lib/squad-parser.js';\nimport {\n colors,\n bold,\n RESET,\n gradient,\n box,\n padEnd,\n icons,\n writeLine,\n} from '../lib/terminal.js';\n\ninterface ListOptions {\n squads?: boolean;\n agents?: boolean;\n}\n\nexport async function listCommand(options: ListOptions): Promise<void> {\n const squadsDir = findSquadsDir();\n\n if (!squadsDir) {\n writeLine(` ${colors.red}No .agents/squads directory found${RESET}`);\n writeLine(` ${colors.dim}Run \\`squads init\\` to create one.${RESET}`);\n process.exit(1);\n }\n\n const squads = listSquads(squadsDir);\n const allAgents = listAgents(squadsDir);\n\n writeLine();\n writeLine(` ${gradient('squads')} ${colors.dim}list${RESET}`);\n writeLine();\n\n // Stats\n writeLine(` ${colors.cyan}${squads.length}${RESET} squads ${colors.dim}│${RESET} ${colors.cyan}${allAgents.length}${RESET} agents`);\n writeLine();\n\n if (!options.agents) {\n // Show squads table\n const w = { name: 16, agents: 8, lead: 24 };\n const tableWidth = w.name + w.agents + w.lead + 4;\n\n writeLine(` ${colors.purple}${box.topLeft}${colors.dim}${box.horizontal.repeat(tableWidth)}${colors.purple}${box.topRight}${RESET}`);\n\n const header = ` ${colors.purple}${box.vertical}${RESET} ` +\n `${bold}${padEnd('SQUAD', w.name)}${RESET}` +\n `${bold}${padEnd('AGENTS', w.agents)}${RESET}` +\n `${bold}LEAD${RESET}` +\n ` ${colors.purple}${box.vertical}${RESET}`;\n writeLine(header);\n\n writeLine(` ${colors.purple}${box.teeRight}${colors.dim}${box.horizontal.repeat(tableWidth)}${colors.purple}${box.teeLeft}${RESET}`);\n\n for (const squadName of squads) {\n const agents = listAgents(squadsDir, squadName);\n const lead = agents.find(a => a.name.includes('lead'))?.name || agents[0]?.name || '-';\n\n const row = ` ${colors.purple}${box.vertical}${RESET} ` +\n `${colors.cyan}${padEnd(squadName, w.name)}${RESET}` +\n `${padEnd(String(agents.length), w.agents)}` +\n `${colors.dim}${padEnd(lead, w.lead)}${RESET}` +\n `${colors.purple}${box.vertical}${RESET}`;\n\n writeLine(row);\n }\n\n writeLine(` ${colors.purple}${box.bottomLeft}${colors.dim}${box.horizontal.repeat(tableWidth)}${colors.purple}${box.bottomRight}${RESET}`);\n writeLine();\n }\n\n if (!options.squads && options.agents) {\n // Show agents list\n writeLine(` ${bold}Agents${RESET}`);\n writeLine();\n\n for (const agent of allAgents) {\n const squadPart = agent.squad ? `${colors.dim}${agent.squad}/${RESET}` : '';\n const statusIcon = agent.status?.toLowerCase() === 'active' ? icons.active : icons.pending;\n\n writeLine(` ${statusIcon} ${squadPart}${colors.white}${agent.name}${RESET}`);\n if (agent.role) {\n writeLine(` ${colors.dim}└ ${agent.role}${RESET}`);\n }\n }\n writeLine();\n }\n\n // Commands\n writeLine(` ${colors.dim}$${RESET} squads status ${colors.cyan}<squad>${RESET} ${colors.dim}Squad details${RESET}`);\n writeLine(` ${colors.dim}$${RESET} squads run ${colors.cyan}<squad>${RESET} ${colors.dim}Execute a squad${RESET}`);\n writeLine();\n}\n","import { existsSync, statSync } from 'fs';\nimport { join } from 'path';\nimport {\n findSquadsDir,\n loadSquad,\n listSquads,\n listAgents\n} from '../lib/squad-parser.js';\nimport { findMemoryDir, getSquadState } from '../lib/memory.js';\nimport {\n colors,\n bold,\n RESET,\n gradient,\n box,\n padEnd,\n icons,\n writeLine,\n} from '../lib/terminal.js';\n\ninterface StatusOptions {\n verbose?: boolean;\n}\n\nexport async function statusCommand(\n squadName?: string,\n options: StatusOptions = {}\n): Promise<void> {\n const squadsDir = findSquadsDir();\n\n if (!squadsDir) {\n writeLine(`${colors.red}No .agents/squads directory found${RESET}`);\n writeLine(`${colors.dim}Run \\`squads init\\` to create one.${RESET}`);\n process.exit(1);\n }\n\n if (squadName) {\n await showSquadStatus(squadName, squadsDir, options);\n } else {\n await showOverallStatus(squadsDir, options);\n }\n}\n\nasync function showOverallStatus(\n squadsDir: string,\n _options: StatusOptions\n): Promise<void> {\n const squads = listSquads(squadsDir);\n const memoryDir = findMemoryDir();\n\n writeLine();\n writeLine(` ${gradient('squads')} ${colors.dim}status${RESET}`);\n writeLine();\n\n // Stats row\n const totalSquads = squads.length;\n const activeCount = squads.length; // All loaded squads are \"active\"\n writeLine(` ${colors.cyan}${activeCount}${RESET}/${totalSquads} squads ${colors.dim}│${RESET} ${colors.dim}memory: ${memoryDir ? 'enabled' : 'none'}${RESET}`);\n writeLine();\n\n // Table\n const w = { name: 16, agents: 8, memory: 14, activity: 12 };\n const tableWidth = w.name + w.agents + w.memory + w.activity + 6;\n\n writeLine(` ${colors.purple}${box.topLeft}${colors.dim}${box.horizontal.repeat(tableWidth)}${colors.purple}${box.topRight}${RESET}`);\n\n const header = ` ${colors.purple}${box.vertical}${RESET} ` +\n `${bold}${padEnd('SQUAD', w.name)}${RESET}` +\n `${bold}${padEnd('AGENTS', w.agents)}${RESET}` +\n `${bold}${padEnd('MEMORY', w.memory)}${RESET}` +\n `${bold}ACTIVITY${RESET}` +\n ` ${colors.purple}${box.vertical}${RESET}`;\n writeLine(header);\n\n writeLine(` ${colors.purple}${box.teeRight}${colors.dim}${box.horizontal.repeat(tableWidth)}${colors.purple}${box.teeLeft}${RESET}`);\n\n for (const squadName of squads) {\n const agents = listAgents(squadsDir, squadName);\n\n // Check memory\n let memoryStatus = `${colors.dim}none${RESET}`;\n let lastActivity = `${colors.dim}—${RESET}`;\n let activityColor = colors.dim;\n\n if (memoryDir) {\n const squadMemoryPath = join(memoryDir, squadName);\n if (existsSync(squadMemoryPath)) {\n const states = getSquadState(squadName);\n memoryStatus = `${colors.green}${states.length} entries${RESET}`;\n\n // Find most recent file\n let mostRecent = 0;\n for (const state of states) {\n const stat = statSync(state.path);\n if (stat.mtimeMs > mostRecent) {\n mostRecent = stat.mtimeMs;\n }\n }\n\n if (mostRecent > 0) {\n const daysAgo = Math.floor((Date.now() - mostRecent) / (1000 * 60 * 60 * 24));\n if (daysAgo === 0) {\n lastActivity = 'today';\n activityColor = colors.green;\n } else if (daysAgo === 1) {\n lastActivity = 'yesterday';\n activityColor = colors.green;\n } else if (daysAgo < 7) {\n lastActivity = `${daysAgo}d ago`;\n activityColor = colors.yellow;\n } else {\n lastActivity = `${daysAgo}d ago`;\n activityColor = colors.dim;\n }\n }\n }\n }\n\n const row = ` ${colors.purple}${box.vertical}${RESET} ` +\n `${colors.cyan}${padEnd(squadName, w.name)}${RESET}` +\n `${padEnd(String(agents.length), w.agents)}` +\n `${padEnd(memoryStatus, w.memory)}` +\n `${padEnd(`${activityColor}${lastActivity}${RESET}`, w.activity)}` +\n `${colors.purple}${box.vertical}${RESET}`;\n\n writeLine(row);\n }\n\n writeLine(` ${colors.purple}${box.bottomLeft}${colors.dim}${box.horizontal.repeat(tableWidth)}${colors.purple}${box.bottomRight}${RESET}`);\n writeLine();\n\n // Commands\n writeLine(` ${colors.dim}$${RESET} squads status ${colors.cyan}<squad>${RESET} ${colors.dim}Squad details${RESET}`);\n writeLine(` ${colors.dim}$${RESET} squads dash ${colors.dim}Full dashboard${RESET}`);\n writeLine(` ${colors.dim}$${RESET} squads run ${colors.cyan}<squad>${RESET} ${colors.dim}Execute a squad${RESET}`);\n writeLine();\n}\n\nasync function showSquadStatus(\n squadName: string,\n squadsDir: string,\n options: StatusOptions\n): Promise<void> {\n const squad = loadSquad(squadName);\n\n if (!squad) {\n writeLine(`${colors.red}Squad \"${squadName}\" not found.${RESET}`);\n process.exit(1);\n }\n\n writeLine();\n writeLine(` ${gradient('squads')} ${colors.dim}status${RESET} ${colors.cyan}${squad.name}${RESET}`);\n writeLine();\n\n // Mission\n if (squad.mission) {\n writeLine(` ${colors.dim}${squad.mission}${RESET}`);\n writeLine();\n }\n\n // Agents table\n const agents = listAgents(squadsDir, squadName);\n const w = { name: 24, role: 36 };\n const tableWidth = w.name + w.role + 4;\n\n writeLine(` ${bold}Agents${RESET} ${colors.dim}(${agents.length})${RESET}`);\n writeLine();\n\n writeLine(` ${colors.purple}${box.topLeft}${colors.dim}${box.horizontal.repeat(tableWidth)}${colors.purple}${box.topRight}${RESET}`);\n\n for (const agent of agents) {\n const status = agent.status?.toLowerCase() === 'active'\n ? icons.active\n : icons.pending;\n\n const role = options.verbose && agent.role\n ? `${colors.dim}${agent.role.substring(0, w.role - 2)}${RESET}`\n : '';\n\n const row = ` ${colors.purple}${box.vertical}${RESET} ` +\n `${status} ${padEnd(agent.name, w.name - 2)}` +\n `${padEnd(role, w.role)}` +\n `${colors.purple}${box.vertical}${RESET}`;\n\n writeLine(row);\n }\n\n writeLine(` ${colors.purple}${box.bottomLeft}${colors.dim}${box.horizontal.repeat(tableWidth)}${colors.purple}${box.bottomRight}${RESET}`);\n\n // Pipelines\n if (squad.pipelines.length > 0) {\n writeLine();\n writeLine(` ${bold}Pipelines${RESET}`);\n for (const pipeline of squad.pipelines) {\n writeLine(` ${colors.dim}${pipeline.agents.join(' → ')}${RESET}`);\n }\n }\n\n // Memory state\n const memoryDir = findMemoryDir();\n if (memoryDir) {\n const states = getSquadState(squadName);\n\n if (states.length > 0) {\n writeLine();\n writeLine(` ${bold}Memory${RESET} ${colors.dim}(${states.length} entries)${RESET}`);\n writeLine();\n\n for (const state of states) {\n const updated = state.content.match(/Updated:\\s*(\\S+)/)?.[1] || 'unknown';\n writeLine(` ${icons.progress} ${colors.white}${state.agent}${RESET}`);\n writeLine(` ${colors.dim}└ updated: ${updated}${RESET}`);\n\n if (options.verbose) {\n const signalsMatch = state.content.match(/## Active Signals([\\s\\S]*?)(?=##|$)/);\n if (signalsMatch) {\n const signalLines = signalsMatch[1]\n .split('\\n')\n .filter(l => l.match(/^\\d+\\./))\n .slice(0, 3);\n\n for (const sig of signalLines) {\n writeLine(` ${colors.dim} ${sig.trim()}${RESET}`);\n }\n }\n }\n }\n }\n }\n\n writeLine();\n writeLine(` ${colors.dim}$${RESET} squads run ${colors.cyan}${squadName}${RESET} ${colors.dim}Run the squad${RESET}`);\n writeLine(` ${colors.dim}$${RESET} squads memory show ${colors.cyan}${squadName}${RESET} ${colors.dim}View full memory${RESET}`);\n writeLine(` ${colors.dim}$${RESET} squads status ${colors.cyan}${squadName}${RESET} -v ${colors.dim}Verbose status${RESET}`);\n writeLine();\n}\n","import {\n findMemoryDir,\n searchMemory,\n getSquadState,\n appendToMemory,\n listMemoryEntries\n} from '../lib/memory.js';\nimport {\n colors,\n bold,\n RESET,\n gradient,\n box,\n padEnd,\n truncate,\n icons,\n writeLine,\n} from '../lib/terminal.js';\n\nconst SQUADS_BRIDGE_URL = process.env.SQUADS_BRIDGE_URL || 'http://localhost:8088';\n\ninterface MemoryOptions {\n squad?: string;\n agent?: string;\n type?: string;\n}\n\nexport async function memoryQueryCommand(\n query: string,\n options: MemoryOptions\n): Promise<void> {\n const memoryDir = findMemoryDir();\n\n if (!memoryDir) {\n writeLine(` ${colors.red}No .agents/memory directory found${RESET}`);\n writeLine(` ${colors.dim}Run \\`squads init\\` to create one.${RESET}`);\n process.exit(1);\n }\n\n writeLine();\n writeLine(` ${gradient('squads')} ${colors.dim}memory query${RESET} \"${colors.cyan}${query}${RESET}\"`);\n writeLine();\n\n const results = searchMemory(query, memoryDir);\n\n if (results.length === 0) {\n writeLine(` ${colors.yellow}No results found.${RESET}`);\n writeLine();\n return;\n }\n\n // Filter by squad/agent if specified\n let filtered = results;\n if (options.squad) {\n filtered = filtered.filter(r => r.entry.squad === options.squad);\n }\n if (options.agent) {\n filtered = filtered.filter(r => r.entry.agent === options.agent);\n }\n\n writeLine(` ${colors.green}${filtered.length}${RESET} results found`);\n writeLine();\n\n // Table\n const w = { location: 28, type: 10, score: 8 };\n const tableWidth = w.location + w.type + w.score + 4;\n\n writeLine(` ${colors.purple}${box.topLeft}${colors.dim}${box.horizontal.repeat(tableWidth)}${colors.purple}${box.topRight}${RESET}`);\n\n const header = ` ${colors.purple}${box.vertical}${RESET} ` +\n `${bold}${padEnd('LOCATION', w.location)}${RESET}` +\n `${bold}${padEnd('TYPE', w.type)}${RESET}` +\n `${bold}SCORE${RESET}` +\n ` ${colors.purple}${box.vertical}${RESET}`;\n writeLine(header);\n\n writeLine(` ${colors.purple}${box.teeRight}${colors.dim}${box.horizontal.repeat(tableWidth)}${colors.purple}${box.teeLeft}${RESET}`);\n\n for (const result of filtered.slice(0, 8)) {\n const { entry, score } = result;\n const location = `${entry.squad}/${entry.agent}`;\n const scoreColor = score > 5 ? colors.green : score > 2 ? colors.yellow : colors.dim;\n\n const row = ` ${colors.purple}${box.vertical}${RESET} ` +\n `${colors.cyan}${padEnd(location, w.location)}${RESET}` +\n `${colors.dim}${padEnd(entry.type, w.type)}${RESET}` +\n `${scoreColor}${padEnd(score.toFixed(1), w.score)}${RESET}` +\n `${colors.purple}${box.vertical}${RESET}`;\n\n writeLine(row);\n }\n\n writeLine(` ${colors.purple}${box.bottomLeft}${colors.dim}${box.horizontal.repeat(tableWidth)}${colors.purple}${box.bottomRight}${RESET}`);\n writeLine();\n\n // Show matches\n writeLine(` ${bold}Matches${RESET}`);\n writeLine();\n\n for (const result of filtered.slice(0, 5)) {\n const { entry, matches } = result;\n\n for (const match of matches.slice(0, 2)) {\n const highlighted = match.replace(\n new RegExp(query, 'gi'),\n (m) => `${colors.yellow}${m}${RESET}`\n );\n writeLine(` ${icons.empty} ${truncate(highlighted, 60)}`);\n writeLine(` ${colors.dim}└ ${entry.squad}/${entry.agent}${RESET}`);\n }\n }\n\n if (filtered.length > 5) {\n writeLine(` ${colors.dim} +${filtered.length - 5} more results${RESET}`);\n }\n writeLine();\n\n // Commands\n writeLine(` ${colors.dim}$${RESET} squads memory show ${colors.cyan}<squad>${RESET} ${colors.dim}View full memory${RESET}`);\n writeLine();\n}\n\nexport async function memoryShowCommand(\n squadName: string,\n _options: MemoryOptions\n): Promise<void> {\n const memoryDir = findMemoryDir();\n\n if (!memoryDir) {\n writeLine(` ${colors.red}No .agents/memory directory found${RESET}`);\n process.exit(1);\n }\n\n const states = getSquadState(squadName);\n\n if (states.length === 0) {\n writeLine(` ${colors.yellow}No memory found for squad: ${squadName}${RESET}`);\n return;\n }\n\n writeLine();\n writeLine(` ${gradient('squads')} ${colors.dim}memory${RESET} ${colors.cyan}${squadName}${RESET}`);\n writeLine();\n\n writeLine(` ${colors.dim}${states.length} entries${RESET}`);\n writeLine();\n\n for (const state of states) {\n writeLine(` ${icons.progress} ${colors.white}${state.agent}${RESET} ${colors.dim}(${state.type || 'state'})${RESET}`);\n writeLine(` ${colors.dim}${box.horizontal.repeat(40)}${RESET}`);\n\n // Show preview\n const lines = state.content.split('\\n').slice(0, 12);\n for (const line of lines) {\n writeLine(` ${colors.dim}${truncate(line, 70)}${RESET}`);\n }\n\n if (state.content.split('\\n').length > 12) {\n writeLine(` ${colors.dim}... (more content)${RESET}`);\n }\n writeLine();\n }\n\n // Commands\n writeLine(` ${colors.dim}$${RESET} squads memory query ${colors.cyan}\"<term>\"${RESET} ${colors.dim}Search memory${RESET}`);\n writeLine();\n}\n\nexport async function memoryUpdateCommand(\n squadName: string,\n content: string,\n options: MemoryOptions\n): Promise<void> {\n const agentName = options.agent || `${squadName}-lead`;\n const type = (options.type || 'learnings') as 'state' | 'output' | 'learnings' | 'feedback';\n\n writeLine();\n\n try {\n appendToMemory(squadName, agentName, type, content);\n writeLine(` ${icons.success} Updated ${colors.cyan}${type}${RESET} for ${colors.white}${squadName}/${agentName}${RESET}`);\n } catch (error) {\n writeLine(` ${icons.error} ${colors.red}Failed to update memory: ${error}${RESET}`);\n process.exit(1);\n }\n\n writeLine();\n}\n\nexport async function memoryListCommand(): Promise<void> {\n const memoryDir = findMemoryDir();\n\n if (!memoryDir) {\n writeLine(` ${colors.red}No .agents/memory directory found${RESET}`);\n process.exit(1);\n }\n\n const entries = listMemoryEntries(memoryDir);\n\n // Group by squad\n const bySquad: Record<string, typeof entries> = {};\n for (const entry of entries) {\n if (!bySquad[entry.squad]) {\n bySquad[entry.squad] = [];\n }\n bySquad[entry.squad].push(entry);\n }\n\n writeLine();\n writeLine(` ${gradient('squads')} ${colors.dim}memory list${RESET}`);\n writeLine();\n\n const squadNames = Object.keys(bySquad);\n writeLine(` ${colors.cyan}${entries.length}${RESET} entries across ${squadNames.length} squads`);\n writeLine();\n\n // Table\n const w = { squad: 16, agents: 8, types: 28 };\n const tableWidth = w.squad + w.agents + w.types + 4;\n\n writeLine(` ${colors.purple}${box.topLeft}${colors.dim}${box.horizontal.repeat(tableWidth)}${colors.purple}${box.topRight}${RESET}`);\n\n const header = ` ${colors.purple}${box.vertical}${RESET} ` +\n `${bold}${padEnd('SQUAD', w.squad)}${RESET}` +\n `${bold}${padEnd('AGENTS', w.agents)}${RESET}` +\n `${bold}TYPES${RESET}` +\n ` ${colors.purple}${box.vertical}${RESET}`;\n writeLine(header);\n\n writeLine(` ${colors.purple}${box.teeRight}${colors.dim}${box.horizontal.repeat(tableWidth)}${colors.purple}${box.teeLeft}${RESET}`);\n\n for (const [squad, squadEntries] of Object.entries(bySquad)) {\n const agents = new Set(squadEntries.map(e => e.agent));\n const types = [...new Set(squadEntries.map(e => e.type))].join(', ');\n const typesDisplay = truncate(types, w.types - 2);\n\n const row = ` ${colors.purple}${box.vertical}${RESET} ` +\n `${colors.cyan}${padEnd(squad, w.squad)}${RESET}` +\n `${padEnd(String(agents.size), w.agents)}` +\n `${colors.dim}${padEnd(typesDisplay, w.types)}${RESET}` +\n `${colors.purple}${box.vertical}${RESET}`;\n\n writeLine(row);\n }\n\n writeLine(` ${colors.purple}${box.bottomLeft}${colors.dim}${box.horizontal.repeat(tableWidth)}${colors.purple}${box.bottomRight}${RESET}`);\n writeLine();\n\n // Commands\n writeLine(` ${colors.dim}$${RESET} squads memory show ${colors.cyan}<squad>${RESET} ${colors.dim}View squad memory${RESET}`);\n writeLine(` ${colors.dim}$${RESET} squads memory query ${colors.cyan}\"<term>\"${RESET} ${colors.dim}Search all memory${RESET}`);\n writeLine();\n}\n\ninterface ConversationResult {\n id: number;\n session_id: string;\n role: string;\n content: string;\n type: string; // message_type in the API response\n importance: string;\n created_at: string;\n rank: number;\n}\n\nexport async function memorySearchCommand(\n query: string,\n options: { limit?: number; role?: string; importance?: string } = {}\n): Promise<void> {\n writeLine();\n writeLine(` ${gradient('squads')} ${colors.dim}memory search${RESET} \"${colors.cyan}${query}${RESET}\"`);\n writeLine();\n\n const limit = options.limit || 10;\n const params = new URLSearchParams({ q: query, limit: String(limit) });\n\n if (options.role) {\n params.append('role', options.role);\n }\n if (options.importance) {\n params.append('importance', options.importance);\n }\n\n try {\n const response = await fetch(`${SQUADS_BRIDGE_URL}/api/conversations/search?${params}`);\n\n if (!response.ok) {\n if (response.status === 503) {\n writeLine(` ${colors.yellow}Database not available${RESET}`);\n writeLine(` ${colors.dim}Run: docker compose up -d${RESET}`);\n writeLine();\n return;\n }\n throw new Error(`HTTP ${response.status}`);\n }\n\n const data = await response.json() as { results: ConversationResult[]; count: number };\n const conversations = data.results;\n const total = data.count;\n\n if (conversations.length === 0) {\n writeLine(` ${colors.yellow}No conversations found for \"${query}\"${RESET}`);\n writeLine();\n writeLine(` ${colors.dim}Conversations are captured via hooks. Make sure:${RESET}`);\n writeLine(` ${colors.dim} 1. squads-bridge is running (docker compose up)${RESET}`);\n writeLine(` ${colors.dim} 2. engram hook is configured in Claude settings${RESET}`);\n writeLine();\n return;\n }\n\n writeLine(` ${colors.green}${conversations.length}${RESET} of ${total} results`);\n writeLine();\n\n // Table\n const w = { time: 12, role: 10, type: 10, content: 50 };\n const tableWidth = w.time + w.role + w.type + w.content + 6;\n\n writeLine(` ${colors.purple}${box.topLeft}${colors.dim}${box.horizontal.repeat(tableWidth)}${colors.purple}${box.topRight}${RESET}`);\n\n const header = ` ${colors.purple}${box.vertical}${RESET} ` +\n `${bold}${padEnd('TIME', w.time)}${RESET}` +\n `${bold}${padEnd('ROLE', w.role)}${RESET}` +\n `${bold}${padEnd('TYPE', w.type)}${RESET}` +\n `${bold}${padEnd('CONTENT', w.content)}${RESET}` +\n ` ${colors.purple}${box.vertical}${RESET}`;\n writeLine(header);\n\n writeLine(` ${colors.purple}${box.teeRight}${colors.dim}${box.horizontal.repeat(tableWidth)}${colors.purple}${box.teeLeft}${RESET}`);\n\n for (const conv of conversations) {\n const time = new Date(conv.created_at).toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });\n const roleColor = conv.role === 'user' ? colors.cyan : conv.role === 'thinking' ? colors.yellow : colors.green;\n const importanceIcon = conv.importance === 'high' ? icons.success : '';\n\n // Highlight search term in content\n const contentPreview = truncate((conv.content || '').replace(/\\n/g, ' '), w.content - 2);\n const highlighted = contentPreview.replace(\n new RegExp(query, 'gi'),\n (m) => `${colors.yellow}${m}${RESET}${colors.dim}`\n );\n\n const row = ` ${colors.purple}${box.vertical}${RESET} ` +\n `${colors.dim}${padEnd(time, w.time)}${RESET}` +\n `${roleColor}${padEnd(conv.role || '', w.role)}${RESET}` +\n `${colors.dim}${padEnd(conv.type || 'message', w.type)}${RESET}` +\n `${colors.dim}${padEnd(highlighted + importanceIcon, w.content)}${RESET}` +\n ` ${colors.purple}${box.vertical}${RESET}`;\n\n writeLine(row);\n }\n\n writeLine(` ${colors.purple}${box.bottomLeft}${colors.dim}${box.horizontal.repeat(tableWidth)}${colors.purple}${box.bottomRight}${RESET}`);\n writeLine();\n\n // Expanded view of top results\n writeLine(` ${bold}Top Matches${RESET}`);\n writeLine();\n\n for (const conv of conversations.slice(0, 3)) {\n const time = new Date(conv.created_at).toLocaleString('en-US', {\n month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit'\n });\n const roleIcon = conv.role === 'user' ? '👤' : conv.role === 'thinking' ? '💭' : '🤖';\n\n writeLine(` ${roleIcon} ${colors.dim}${time}${RESET} ${conv.importance === 'high' ? colors.yellow + '[high]' + RESET : ''}`);\n\n // Show first 200 chars with highlighted search term\n const content = conv.content || '';\n const preview = content.substring(0, 200).replace(/\\n/g, ' ');\n const highlighted = preview.replace(\n new RegExp(query, 'gi'),\n (m) => `${colors.yellow}${m}${RESET}`\n );\n writeLine(` ${highlighted}${content.length > 200 ? '...' : ''}`);\n writeLine();\n }\n\n // Commands\n writeLine(` ${colors.dim}$${RESET} squads memory search ${colors.cyan}\"<term>\"${RESET} --role user ${colors.dim}Filter by role${RESET}`);\n writeLine(` ${colors.dim}$${RESET} squads memory search ${colors.cyan}\"<term>\"${RESET} --importance high ${colors.dim}Filter by importance${RESET}`);\n writeLine();\n\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n if (errorMessage.includes('ECONNREFUSED')) {\n writeLine(` ${colors.yellow}Cannot connect to squads-bridge${RESET}`);\n writeLine(` ${colors.dim}Run: docker compose up -d${RESET}`);\n } else {\n writeLine(` ${colors.red}Error searching conversations: ${errorMessage}${RESET}`);\n }\n writeLine();\n }\n}\n","import { execSync } from 'child_process';\nimport { existsSync, readFileSync, writeFileSync, mkdirSync, readdirSync } from 'fs';\nimport { join, dirname } from 'path';\nimport { findMemoryDir } from '../lib/memory.js';\nimport { findSquadsDir, listSquads } from '../lib/squad-parser.js';\nimport {\n colors,\n bold,\n RESET,\n gradient,\n icons,\n writeLine,\n} from '../lib/terminal.js';\n\ninterface CommitInfo {\n hash: string;\n date: string;\n message: string;\n files: string[];\n}\n\ninterface SquadUpdate {\n squad: string;\n commits: CommitInfo[];\n summary: string;\n}\n\n// Map file paths to squads\nconst PATH_TO_SQUAD: Record<string, string> = {\n 'squads-cli': 'product',\n 'agents-squads-web': 'website',\n 'research': 'research',\n 'intelligence': 'intelligence',\n 'customer': 'customer',\n 'finance': 'finance',\n 'engineering': 'engineering',\n 'product': 'product',\n 'company': 'company',\n '.agents/squads': 'engineering',\n '.agents/memory': 'engineering',\n};\n\n// Keywords in commit messages that map to squads\nconst MESSAGE_TO_SQUAD: Record<string, string> = {\n 'cli': 'product',\n 'website': 'website',\n 'web': 'website',\n 'homepage': 'website',\n 'research': 'research',\n 'intel': 'intelligence',\n 'lead': 'customer',\n 'finance': 'finance',\n 'cost': 'finance',\n 'engineering': 'engineering',\n 'infra': 'engineering',\n};\n\nfunction getLastSyncTime(memoryDir: string): string | null {\n const syncFile = join(memoryDir, '.last-sync');\n if (existsSync(syncFile)) {\n return readFileSync(syncFile, 'utf-8').trim();\n }\n return null;\n}\n\nfunction updateLastSyncTime(memoryDir: string): void {\n const syncFile = join(memoryDir, '.last-sync');\n writeFileSync(syncFile, new Date().toISOString());\n}\n\nfunction getRecentCommits(since?: string): CommitInfo[] {\n const commits: CommitInfo[] = [];\n\n try {\n // Get commits with files changed\n const sinceArg = since ? `--since=\"${since}\"` : '-n 20';\n const logOutput = execSync(\n `git log ${sinceArg} --format=\"%H|%aI|%s\" --name-only`,\n { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] }\n ).trim();\n\n if (!logOutput) return commits;\n\n // Parse git log output\n const entries = logOutput.split('\\n\\n');\n for (const entry of entries) {\n const lines = entry.split('\\n').filter(l => l.trim());\n if (lines.length === 0) continue;\n\n const [header, ...fileLines] = lines;\n const [hash, date, ...messageParts] = header.split('|');\n const message = messageParts.join('|');\n\n if (hash && date && message) {\n commits.push({\n hash: hash.substring(0, 7),\n date: date.split('T')[0],\n message,\n files: fileLines.filter(f => f && !f.includes('|')),\n });\n }\n }\n } catch (error) {\n // Not in a git repo or other error\n }\n\n return commits;\n}\n\nfunction detectSquadsFromCommit(commit: CommitInfo): string[] {\n const squads = new Set<string>();\n\n // Check file paths\n for (const file of commit.files) {\n for (const [pathPattern, squad] of Object.entries(PATH_TO_SQUAD)) {\n if (file.includes(pathPattern)) {\n squads.add(squad);\n }\n }\n }\n\n // Check commit message\n const msgLower = commit.message.toLowerCase();\n for (const [keyword, squad] of Object.entries(MESSAGE_TO_SQUAD)) {\n if (msgLower.includes(keyword)) {\n squads.add(squad);\n }\n }\n\n return Array.from(squads);\n}\n\nfunction groupCommitsBySquad(commits: CommitInfo[]): Map<string, CommitInfo[]> {\n const grouped = new Map<string, CommitInfo[]>();\n\n for (const commit of commits) {\n const squads = detectSquadsFromCommit(commit);\n\n for (const squad of squads) {\n if (!grouped.has(squad)) {\n grouped.set(squad, []);\n }\n grouped.get(squad)!.push(commit);\n }\n }\n\n return grouped;\n}\n\nfunction generateSummary(commits: CommitInfo[]): string {\n if (commits.length === 0) return '';\n\n const messages = commits.map(c => `- ${c.message}`).join('\\n');\n const date = new Date().toISOString().split('T')[0];\n\n return `\n## Session Update (${date})\n\n${messages}\n`;\n}\n\nfunction appendToSquadMemory(\n memoryDir: string,\n squad: string,\n summary: string\n): boolean {\n // Find the lead agent for this squad\n const squadMemoryDir = join(memoryDir, squad);\n\n if (!existsSync(squadMemoryDir)) {\n mkdirSync(squadMemoryDir, { recursive: true });\n }\n\n // Look for existing agent directories or create default\n let agentDir: string;\n const existingDirs = existsSync(squadMemoryDir)\n ? readdirSync(squadMemoryDir, { withFileTypes: true })\n .filter((d) => d.isDirectory())\n .map((d) => d.name)\n : [];\n\n if (existingDirs.length > 0) {\n // Use first existing agent (usually the lead)\n agentDir = join(squadMemoryDir, existingDirs[0]);\n } else {\n // Create default agent directory\n agentDir = join(squadMemoryDir, `${squad}-lead`);\n mkdirSync(agentDir, { recursive: true });\n }\n\n const statePath = join(agentDir, 'state.md');\n\n let content = '';\n if (existsSync(statePath)) {\n content = readFileSync(statePath, 'utf-8');\n } else {\n content = `# ${squad} Squad - State\\n\\nUpdated: ${new Date().toISOString().split('T')[0]}\\n`;\n }\n\n // Update the \"Updated\" line\n content = content.replace(\n /Updated:\\s*\\d{4}-\\d{2}-\\d{2}/,\n `Updated: ${new Date().toISOString().split('T')[0]}`\n );\n\n // Append the summary\n content += summary;\n\n writeFileSync(statePath, content);\n return true;\n}\n\nexport async function syncCommand(options: { verbose?: boolean } = {}): Promise<void> {\n const memoryDir = findMemoryDir();\n const squadsDir = findSquadsDir();\n\n if (!memoryDir) {\n writeLine(` ${colors.yellow}No .agents/memory directory found${RESET}`);\n writeLine(` ${colors.dim}Run \\`squads init\\` to create one.${RESET}`);\n return; // Graceful exit - don't fail hooks\n }\n\n writeLine();\n writeLine(` ${gradient('squads')} ${colors.dim}memory sync${RESET}`);\n writeLine();\n\n // Get last sync time\n const lastSync = getLastSyncTime(memoryDir);\n if (lastSync) {\n writeLine(` ${colors.dim}Last sync: ${lastSync.split('T')[0]}${RESET}`);\n } else {\n writeLine(` ${colors.dim}First sync${RESET}`);\n }\n writeLine();\n\n // Get recent commits\n const commits = getRecentCommits(lastSync || undefined);\n\n if (commits.length === 0) {\n writeLine(` ${colors.yellow}No new commits since last sync${RESET}`);\n writeLine();\n return;\n }\n\n writeLine(` ${colors.cyan}${commits.length}${RESET} commits to process`);\n writeLine();\n\n // Group by squad\n const bySquad = groupCommitsBySquad(commits);\n\n if (bySquad.size === 0) {\n writeLine(` ${colors.yellow}No squad-related commits found${RESET}`);\n writeLine();\n updateLastSyncTime(memoryDir);\n return;\n }\n\n // Update each squad's memory\n let updated = 0;\n for (const [squad, squadCommits] of bySquad) {\n const summary = generateSummary(squadCommits);\n\n if (options.verbose) {\n writeLine(` ${icons.progress} ${colors.cyan}${squad}${RESET}`);\n for (const commit of squadCommits) {\n writeLine(` ${colors.dim}${commit.hash} ${commit.message}${RESET}`);\n }\n }\n\n const success = appendToSquadMemory(memoryDir, squad, summary);\n if (success) {\n writeLine(` ${icons.success} ${colors.cyan}${squad}${RESET} ${colors.dim}(${squadCommits.length} commits)${RESET}`);\n updated++;\n }\n }\n\n writeLine();\n writeLine(` ${colors.green}${updated}${RESET} squad memories updated`);\n writeLine();\n\n // Update last sync time\n updateLastSyncTime(memoryDir);\n\n // Show helpful commands\n writeLine(` ${colors.dim}$${RESET} squads memory show ${colors.cyan}<squad>${RESET} ${colors.dim}View updated memory${RESET}`);\n writeLine(` ${colors.dim}$${RESET} squads status ${colors.dim}See all squads${RESET}`);\n writeLine();\n}\n","import {\n loadSquad,\n findSquadsDir,\n listSquads,\n addGoalToSquad,\n updateGoalInSquad,\n Goal\n} from '../lib/squad-parser.js';\nimport {\n colors,\n bold,\n RESET,\n gradient,\n box,\n padEnd,\n truncate,\n icons,\n writeLine,\n} from '../lib/terminal.js';\n\nexport async function goalSetCommand(\n squadName: string,\n description: string,\n options: { metric?: string[] }\n): Promise<void> {\n const squad = loadSquad(squadName);\n if (!squad) {\n writeLine(` ${colors.red}Squad \"${squadName}\" not found${RESET}`);\n return;\n }\n\n // Add metric annotations if provided\n let goalText = description;\n if (options.metric && options.metric.length > 0) {\n goalText += ` [metrics: ${options.metric.join(', ')}]`;\n }\n\n const success = addGoalToSquad(squadName, goalText);\n\n writeLine();\n if (success) {\n writeLine(` ${icons.success} Goal added to ${colors.cyan}${squadName}${RESET}`);\n writeLine(` ${bold}${description}${RESET}`);\n if (options.metric && options.metric.length > 0) {\n writeLine(` ${colors.dim}Metrics: ${options.metric.join(', ')}${RESET}`);\n }\n } else {\n writeLine(` ${colors.red}Failed to add goal${RESET}`);\n }\n writeLine();\n}\n\nexport async function goalListCommand(\n squadName?: string,\n options: { all?: boolean } = {}\n): Promise<void> {\n const squadsDir = findSquadsDir();\n if (!squadsDir) {\n writeLine(` ${colors.red}No .agents/squads directory found${RESET}`);\n return;\n }\n\n const squadsToCheck = squadName ? [squadName] : listSquads(squadsDir);\n\n let totalActive = 0;\n let totalCompleted = 0;\n let hasGoals = false;\n\n writeLine();\n writeLine(` ${gradient('squads')} ${colors.dim}goal list${RESET}`);\n writeLine();\n\n for (const name of squadsToCheck) {\n const squad = loadSquad(name);\n if (!squad || squad.goals.length === 0) {\n if (squadName) {\n writeLine(` ${colors.yellow}No goals set for ${name}${RESET}`);\n }\n continue;\n }\n\n hasGoals = true;\n const activeGoals = squad.goals.filter(g => !g.completed);\n const completedGoals = squad.goals.filter(g => g.completed);\n\n totalActive += activeGoals.length;\n totalCompleted += completedGoals.length;\n\n if (activeGoals.length === 0 && !options.all) continue;\n\n writeLine(` ${colors.cyan}${name}${RESET}`);\n if (squad.mission) {\n writeLine(` ${colors.dim}${truncate(squad.mission, 60)}${RESET}`);\n }\n writeLine();\n\n for (const goal of activeGoals) {\n const globalIdx = squad.goals.indexOf(goal) + 1;\n writeLine(` ${icons.active} ${colors.dim}[${globalIdx}]${RESET} ${goal.description}`);\n if (goal.progress) {\n writeLine(` ${colors.dim}└ ${goal.progress}${RESET}`);\n }\n }\n\n if (options.all && completedGoals.length > 0) {\n for (const goal of completedGoals) {\n const globalIdx = squad.goals.indexOf(goal) + 1;\n writeLine(` ${icons.success} ${colors.dim}[${globalIdx}] ${goal.description}${RESET}`);\n }\n }\n writeLine();\n }\n\n if (hasGoals) {\n writeLine(` ${colors.green}${totalActive}${RESET} active ${colors.dim}│${RESET} ${colors.dim}${totalCompleted} completed${RESET}`);\n } else if (!squadName) {\n writeLine(` ${colors.yellow}No goals defined yet${RESET}`);\n writeLine();\n writeLine(` ${colors.dim}$${RESET} squads goal set ${colors.cyan}<squad>${RESET} ${colors.cyan}\"<goal>\"${RESET}`);\n }\n writeLine();\n}\n\nexport async function goalCompleteCommand(\n squadName: string,\n goalIndex: string\n): Promise<void> {\n const squad = loadSquad(squadName);\n if (!squad) {\n writeLine(` ${colors.red}Squad \"${squadName}\" not found${RESET}`);\n return;\n }\n\n const idx = parseInt(goalIndex) - 1;\n if (idx < 0 || idx >= squad.goals.length) {\n writeLine(` ${colors.red}Invalid goal index: ${goalIndex}${RESET}`);\n writeLine(` ${colors.dim}Squad has ${squad.goals.length} goal(s)${RESET}`);\n return;\n }\n\n const success = updateGoalInSquad(squadName, idx, { completed: true });\n\n writeLine();\n if (success) {\n writeLine(` ${icons.success} Goal completed: ${colors.cyan}${squad.goals[idx].description}${RESET}`);\n } else {\n writeLine(` ${colors.red}Failed to update goal${RESET}`);\n }\n writeLine();\n}\n\nexport async function goalProgressCommand(\n squadName: string,\n goalIndex: string,\n progress: string\n): Promise<void> {\n const squad = loadSquad(squadName);\n if (!squad) {\n writeLine(` ${colors.red}Squad \"${squadName}\" not found${RESET}`);\n return;\n }\n\n const idx = parseInt(goalIndex) - 1;\n if (idx < 0 || idx >= squad.goals.length) {\n writeLine(` ${colors.red}Invalid goal index: ${goalIndex}${RESET}`);\n return;\n }\n\n const success = updateGoalInSquad(squadName, idx, { progress });\n\n writeLine();\n if (success) {\n writeLine(` ${icons.success} Progress updated: ${colors.cyan}${squad.goals[idx].description}${RESET}`);\n writeLine(` ${colors.dim}${progress}${RESET}`);\n } else {\n writeLine(` ${colors.red}Failed to update progress${RESET}`);\n }\n writeLine();\n}\n","import { readFileSync, writeFileSync, existsSync, mkdirSync, readdirSync } from 'fs';\nimport { join, dirname } from 'path';\nimport { findMemoryDir, appendToMemory } from '../lib/memory.js';\nimport { loadSquad } from '../lib/squad-parser.js';\nimport {\n colors,\n bold,\n RESET,\n gradient,\n box,\n padEnd,\n icons,\n writeLine,\n} from '../lib/terminal.js';\n\nexport interface FeedbackEntry {\n date: string;\n execution: string;\n rating: number; // 1-5\n feedback: string;\n learnings?: string[];\n}\n\nfunction getFeedbackPath(squadName: string): string | null {\n const memoryDir = findMemoryDir();\n if (!memoryDir) return null;\n\n // Find the lead agent for this squad\n const squad = loadSquad(squadName);\n const agentName = squad?.agents[0]?.name || `${squadName}-lead`;\n\n return join(memoryDir, squadName, agentName, 'feedback.md');\n}\n\nfunction getOutputPath(squadName: string): string | null {\n const memoryDir = findMemoryDir();\n if (!memoryDir) return null;\n\n const squad = loadSquad(squadName);\n const agentName = squad?.agents[0]?.name || `${squadName}-lead`;\n\n return join(memoryDir, squadName, agentName, 'output.md');\n}\n\nfunction getLastExecution(squadName: string): { date: string; summary: string } | null {\n const outputPath = getOutputPath(squadName);\n if (!outputPath || !existsSync(outputPath)) {\n return null;\n }\n\n const content = readFileSync(outputPath, 'utf-8');\n const lines = content.split('\\n');\n\n // Try to extract date from content\n let date = 'unknown';\n let summary = lines.slice(0, 5).join('\\n');\n\n // Look for date patterns\n const dateMatch = content.match(/(\\d{4}-\\d{2}-\\d{2})/);\n if (dateMatch) {\n date = dateMatch[1];\n }\n\n // Look for title\n const titleMatch = content.match(/^#\\s+(.+)$/m);\n if (titleMatch) {\n summary = titleMatch[1];\n }\n\n return { date, summary };\n}\n\nfunction parseFeedbackHistory(content: string): FeedbackEntry[] {\n const entries: FeedbackEntry[] = [];\n const sections = content.split(/---\\n/).filter(s => s.trim());\n\n for (const section of sections) {\n const dateMatch = section.match(/_Date:\\s*(.+)_/);\n const ratingMatch = section.match(/\\*\\*Rating\\*\\*:\\s*(\\d)\\/5/);\n const feedbackMatch = section.match(/\\*\\*Feedback\\*\\*:\\s*(.+)/);\n const executionMatch = section.match(/\\*\\*Execution\\*\\*:\\s*(.+)/);\n\n if (dateMatch && ratingMatch) {\n const entry: FeedbackEntry = {\n date: dateMatch[1],\n execution: executionMatch?.[1] || 'unknown',\n rating: parseInt(ratingMatch[1]),\n feedback: feedbackMatch?.[1] || '',\n learnings: [],\n };\n\n // Extract learnings\n const learningsMatch = section.match(/\\*\\*Learnings\\*\\*:\\n((?:- .+\\n?)+)/);\n if (learningsMatch) {\n entry.learnings = learningsMatch[1]\n .split('\\n')\n .filter(l => l.startsWith('- '))\n .map(l => l.replace(/^- /, ''));\n }\n\n entries.push(entry);\n }\n }\n\n return entries;\n}\n\nexport async function feedbackAddCommand(\n squadName: string,\n rating: string,\n feedback: string,\n options: { learning?: string[] }\n): Promise<void> {\n const feedbackPath = getFeedbackPath(squadName);\n if (!feedbackPath) {\n writeLine(` ${colors.red}Could not find memory directory${RESET}`);\n return;\n }\n\n const ratingNum = parseInt(rating);\n if (isNaN(ratingNum) || ratingNum < 1 || ratingNum > 5) {\n writeLine(` ${colors.red}Rating must be 1-5${RESET}`);\n return;\n }\n\n // Get last execution for context\n const lastExec = getLastExecution(squadName);\n\n // Ensure directory exists\n const dir = dirname(feedbackPath);\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n }\n\n // Build feedback entry\n const date = new Date().toISOString().split('T')[0];\n let entry = `\\n---\\n_Date: ${date}_\\n\\n`;\n entry += `**Execution**: ${lastExec?.summary || 'Manual feedback'}\\n`;\n entry += `**Rating**: ${ratingNum}/5 ${'★'.repeat(ratingNum)}${'☆'.repeat(5 - ratingNum)}\\n`;\n entry += `**Feedback**: ${feedback}\\n`;\n\n if (options.learning && options.learning.length > 0) {\n entry += `**Learnings**:\\n`;\n for (const learning of options.learning) {\n entry += `- ${learning}\\n`;\n }\n\n // Also add learnings to the learnings file\n const squad = loadSquad(squadName);\n const agentName = squad?.agents[0]?.name || `${squadName}-lead`;\n\n for (const learning of options.learning) {\n appendToMemory(squadName, agentName, 'learnings', `From feedback (${date}): ${learning}`);\n }\n }\n\n // Append to feedback file\n let existing = '';\n if (existsSync(feedbackPath)) {\n existing = readFileSync(feedbackPath, 'utf-8');\n } else {\n existing = `# ${squadName} - Feedback Log\\n\\n> Execution feedback and learnings\\n`;\n }\n\n writeFileSync(feedbackPath, existing + entry);\n\n // Display\n const stars = `${colors.yellow}${'★'.repeat(ratingNum)}${'☆'.repeat(5 - ratingNum)}${RESET}`;\n\n writeLine();\n writeLine(` ${icons.success} Feedback recorded for ${colors.cyan}${squadName}${RESET}`);\n writeLine(` Rating: ${stars}`);\n writeLine(` ${feedback}`);\n if (options.learning && options.learning.length > 0) {\n writeLine(` ${colors.dim}+ ${options.learning.length} learning(s) added${RESET}`);\n }\n writeLine();\n}\n\nexport async function feedbackShowCommand(\n squadName: string,\n options: { limit?: string }\n): Promise<void> {\n const feedbackPath = getFeedbackPath(squadName);\n if (!feedbackPath || !existsSync(feedbackPath)) {\n writeLine(` ${colors.yellow}No feedback recorded for ${squadName}${RESET}`);\n return;\n }\n\n const content = readFileSync(feedbackPath, 'utf-8');\n const entries = parseFeedbackHistory(content);\n\n const limit = options.limit ? parseInt(options.limit) : 5;\n const recent = entries.slice(-limit).reverse();\n\n writeLine();\n writeLine(` ${gradient('squads')} ${colors.dim}feedback${RESET} ${colors.cyan}${squadName}${RESET}`);\n writeLine();\n\n if (recent.length === 0) {\n writeLine(` ${colors.dim}No feedback entries yet${RESET}`);\n return;\n }\n\n // Calculate average rating\n const avgRating = entries.reduce((sum, e) => sum + e.rating, 0) / entries.length;\n\n writeLine(` ${colors.dim}Average: ${avgRating.toFixed(1)}/5 (${entries.length} entries)${RESET}`);\n writeLine();\n\n for (const entry of recent) {\n const stars = `${colors.yellow}${'★'.repeat(entry.rating)}${'☆'.repeat(5 - entry.rating)}${RESET}`;\n writeLine(` ${colors.dim}${entry.date}${RESET} ${stars}`);\n writeLine(` ${entry.feedback}`);\n if (entry.learnings && entry.learnings.length > 0) {\n for (const learning of entry.learnings) {\n writeLine(` ${colors.green}→ ${learning}${RESET}`);\n }\n }\n writeLine();\n }\n}\n\nexport async function feedbackStatsCommand(): Promise<void> {\n const memoryDir = findMemoryDir();\n if (!memoryDir) {\n writeLine(` ${colors.red}Could not find memory directory${RESET}`);\n return;\n }\n\n writeLine();\n writeLine(` ${gradient('squads')} ${colors.dim}feedback stats${RESET}`);\n writeLine();\n\n const squads = readdirSync(memoryDir, { withFileTypes: true })\n .filter(e => e.isDirectory())\n .map(e => e.name);\n\n // Table\n const w = { squad: 18, avg: 12, count: 8, trend: 6 };\n const tableWidth = w.squad + w.avg + w.count + w.trend + 4;\n\n writeLine(` ${colors.purple}${box.topLeft}${colors.dim}${box.horizontal.repeat(tableWidth)}${colors.purple}${box.topRight}${RESET}`);\n\n const header = ` ${colors.purple}${box.vertical}${RESET} ` +\n `${bold}${padEnd('SQUAD', w.squad)}${RESET}` +\n `${bold}${padEnd('AVG', w.avg)}${RESET}` +\n `${bold}${padEnd('COUNT', w.count)}${RESET}` +\n `${bold}TREND${RESET}` +\n ` ${colors.purple}${box.vertical}${RESET}`;\n writeLine(header);\n\n writeLine(` ${colors.purple}${box.teeRight}${colors.dim}${box.horizontal.repeat(tableWidth)}${colors.purple}${box.teeLeft}${RESET}`);\n\n for (const squad of squads) {\n const feedbackPath = getFeedbackPath(squad);\n if (!feedbackPath || !existsSync(feedbackPath)) {\n continue;\n }\n\n const content = readFileSync(feedbackPath, 'utf-8');\n const entries = parseFeedbackHistory(content);\n\n if (entries.length === 0) continue;\n\n const avgRating = entries.reduce((sum, e) => sum + e.rating, 0) / entries.length;\n\n // Calculate trend (last 3 vs previous)\n let trend = `${colors.dim}→${RESET}`;\n if (entries.length >= 4) {\n const recent = entries.slice(-3).reduce((s, e) => s + e.rating, 0) / 3;\n const older = entries.slice(-6, -3).reduce((s, e) => s + e.rating, 0) / Math.min(3, entries.slice(-6, -3).length);\n if (recent > older + 0.3) trend = `${colors.green}↑${RESET}`;\n else if (recent < older - 0.3) trend = `${colors.red}↓${RESET}`;\n }\n\n const stars = `${colors.yellow}${'★'.repeat(Math.round(avgRating))}${'☆'.repeat(5 - Math.round(avgRating))}${RESET}`;\n\n const row = ` ${colors.purple}${box.vertical}${RESET} ` +\n `${colors.cyan}${padEnd(squad, w.squad)}${RESET}` +\n `${padEnd(stars, w.avg + 20)}` + // extra for color codes\n `${padEnd(String(entries.length), w.count)}` +\n `${trend}` +\n ` ${colors.purple}${box.vertical}${RESET}`;\n\n writeLine(row);\n }\n\n writeLine(` ${colors.purple}${box.bottomLeft}${colors.dim}${box.horizontal.repeat(tableWidth)}${colors.purple}${box.bottomRight}${RESET}`);\n writeLine();\n\n // Commands\n writeLine(` ${colors.dim}$${RESET} squads feedback show ${colors.cyan}<squad>${RESET} ${colors.dim}View squad feedback${RESET}`);\n writeLine(` ${colors.dim}$${RESET} squads feedback add ${colors.cyan}<squad>${RESET} ${colors.dim}Add new feedback${RESET}`);\n writeLine();\n}\n","import { readdirSync, readFileSync, existsSync, statSync } from 'fs';\nimport { join } from 'path';\nimport { homedir } from 'os';\nimport { findSquadsDir, listSquads, loadSquad, Goal } from '../lib/squad-parser.js';\nimport { findMemoryDir } from '../lib/memory.js';\nimport { fetchCostSummary, formatCostBar, CostSummary, fetchRateLimits, RateLimits, fetchInsights, Insights } from '../lib/costs.js';\nimport { getMultiRepoGitStats, getActivitySparkline, getGitHubStats, SquadGitHubStats, GitPerformanceStats, GitHubStats } from '../lib/git.js';\nimport { saveDashboardSnapshot, isDatabaseAvailable, getDashboardHistory, DashboardSnapshot, SquadSnapshotData } from '../lib/db.js';\nimport {\n colors,\n bold,\n RESET,\n gradient,\n progressBar,\n box,\n padEnd,\n truncate,\n icons,\n writeLine,\n sparkline,\n barChart,\n} from '../lib/terminal.js';\n\ninterface SquadMetrics {\n name: string;\n mission: string;\n goals: Goal[];\n lastActivity: string;\n status: 'active' | 'stale' | 'needs-goal';\n github: SquadGitHubStats | null;\n goalProgress: number; // 0-100\n}\n\nfunction getLastActivityDate(squadName: string): string {\n const memoryDir = findMemoryDir();\n if (!memoryDir) return 'unknown';\n\n const squadMemory = join(memoryDir, squadName);\n if (!existsSync(squadMemory)) return '—';\n\n let latestTime = 0;\n\n try {\n const agents = readdirSync(squadMemory, { withFileTypes: true })\n .filter(e => e.isDirectory());\n\n for (const agent of agents) {\n const agentPath = join(squadMemory, agent.name);\n const files = readdirSync(agentPath).filter(f => f.endsWith('.md'));\n\n for (const file of files) {\n const filePath = join(agentPath, file);\n const stats = statSync(filePath);\n if (stats.mtimeMs > latestTime) {\n latestTime = stats.mtimeMs;\n }\n }\n }\n } catch {\n return '—';\n }\n\n if (latestTime === 0) return '—';\n\n const ageMs = Date.now() - latestTime;\n const ageDays = Math.floor(ageMs / (1000 * 60 * 60 * 24));\n\n if (ageDays === 0) return 'today';\n if (ageDays === 1) return '1d';\n if (ageDays < 7) return `${ageDays}d`;\n return `${Math.floor(ageDays / 7)}w`;\n}\n\nexport async function dashboardCommand(options: { verbose?: boolean; ceo?: boolean } = {}): Promise<void> {\n const squadsDir = findSquadsDir();\n if (!squadsDir) {\n writeLine(`${colors.red}No .agents/squads directory found${RESET}`);\n return;\n }\n\n // CEO mode: executive summary\n if (options.ceo) {\n await renderCeoReport(squadsDir);\n return;\n }\n\n const squadNames = listSquads(squadsDir);\n const squadData: SquadMetrics[] = [];\n\n // Fetch GitHub stats\n const baseDir = findAgentsSquadsDir();\n const ghStats = baseDir ? getGitHubStats(baseDir, 30) : null;\n\n for (const name of squadNames) {\n const squad = loadSquad(name);\n if (!squad) continue;\n\n const lastActivity = getLastActivityDate(name);\n const github = ghStats?.bySquad.get(name) || null;\n\n let status: SquadMetrics['status'] = 'active';\n const activeGoals = squad.goals.filter(g => !g.completed);\n if (activeGoals.length === 0) {\n status = 'needs-goal';\n } else if (lastActivity.includes('w') || lastActivity === '—') {\n status = 'stale';\n }\n\n // Calculate goal progress based on work done\n const totalGoals = squad.goals.length;\n const completedGoals = squad.goals.filter(g => g.completed).length;\n const hasProgress = squad.goals.filter(g => g.progress).length;\n // Progress = completed + half credit for in-progress\n const goalProgress = totalGoals > 0\n ? Math.round(((completedGoals + hasProgress * 0.3) / totalGoals) * 100)\n : 0;\n\n squadData.push({\n name,\n mission: squad.mission,\n goals: squad.goals,\n lastActivity,\n status,\n github,\n goalProgress,\n });\n }\n\n // Stats\n const totalGoals = squadData.reduce((sum, s) => sum + s.goals.length, 0);\n const activeGoals = squadData.reduce((sum, s) => sum + s.goals.filter(g => !g.completed).length, 0);\n const completedGoals = totalGoals - activeGoals;\n const completionRate = totalGoals > 0 ? Math.round((completedGoals / totalGoals) * 100) : 0;\n const activeSquads = squadData.filter(s => s.status === 'active').length;\n\n // GitHub totals\n const totalPRs = ghStats ? ghStats.prsMerged : 0;\n const totalIssuesClosed = ghStats ? ghStats.issuesClosed : 0;\n const totalIssuesOpen = ghStats ? ghStats.issuesOpen : 0;\n\n // Render\n writeLine();\n\n // Header\n writeLine(` ${gradient('squads')} ${colors.dim}dashboard${RESET}`);\n writeLine();\n\n // Stats row\n const stats = [\n `${colors.cyan}${activeSquads}${RESET}/${squadData.length} squads`,\n `${colors.green}${totalPRs}${RESET} PRs merged`,\n `${colors.purple}${totalIssuesClosed}${RESET} closed`,\n `${colors.yellow}${totalIssuesOpen}${RESET} open`,\n ].join(` ${colors.dim}│${RESET} `);\n writeLine(` ${stats}`);\n writeLine();\n\n // Overall progress\n const overallProgress = squadData.length > 0\n ? Math.round(squadData.reduce((sum, s) => sum + s.goalProgress, 0) / squadData.length)\n : 0;\n writeLine(` ${progressBar(overallProgress, 32)} ${colors.dim}${overallProgress}% goal progress${RESET}`);\n writeLine();\n\n // Table header - enhanced with metrics\n const w = { name: 13, commits: 7, prs: 4, issues: 6, goals: 6, bar: 10 };\n const tableWidth = w.name + w.commits + w.prs + w.issues + w.goals + w.bar + 12;\n\n writeLine(` ${colors.purple}${box.topLeft}${colors.dim}${box.horizontal.repeat(tableWidth)}${colors.purple}${box.topRight}${RESET}`);\n\n const header = ` ${colors.purple}${box.vertical}${RESET} ` +\n `${bold}${padEnd('SQUAD', w.name)}${RESET}` +\n `${bold}${padEnd('COMMITS', w.commits)}${RESET}` +\n `${bold}${padEnd('PRs', w.prs)}${RESET}` +\n `${bold}${padEnd('ISSUES', w.issues)}${RESET}` +\n `${bold}${padEnd('GOALS', w.goals)}${RESET}` +\n `${bold}PROGRESS${RESET}` +\n ` ${colors.purple}${box.vertical}${RESET}`;\n writeLine(header);\n\n writeLine(` ${colors.purple}${box.teeRight}${colors.dim}${box.horizontal.repeat(tableWidth)}${colors.purple}${box.teeLeft}${RESET}`);\n\n // Table rows - sorted by activity\n const sortedSquads = [...squadData].sort((a, b) => {\n const aActivity = (a.github?.commits || 0) + (a.github?.prsMerged || 0) * 5;\n const bActivity = (b.github?.commits || 0) + (b.github?.prsMerged || 0) * 5;\n return bActivity - aActivity;\n });\n\n for (const squad of sortedSquads) {\n const gh = squad.github;\n const commits = gh?.commits || 0;\n const prs = gh?.prsMerged || 0;\n const issuesClosed = gh?.issuesClosed || 0;\n const issuesOpen = gh?.issuesOpen || 0;\n\n const activeCount = squad.goals.filter(g => !g.completed).length;\n const totalCount = squad.goals.length;\n\n // Color coding based on activity\n const commitColor = commits > 10 ? colors.green : commits > 0 ? colors.cyan : colors.dim;\n const prColor = prs > 0 ? colors.green : colors.dim;\n const issueColor = issuesClosed > 0 ? colors.green : colors.dim;\n\n // Issues display: closed/open\n const issuesDisplay = `${issuesClosed}/${issuesOpen}`;\n\n const row = ` ${colors.purple}${box.vertical}${RESET} ` +\n `${colors.cyan}${padEnd(squad.name, w.name)}${RESET}` +\n `${commitColor}${padEnd(String(commits), w.commits)}${RESET}` +\n `${prColor}${padEnd(String(prs), w.prs)}${RESET}` +\n `${issueColor}${padEnd(issuesDisplay, w.issues)}${RESET}` +\n `${padEnd(`${activeCount}/${totalCount}`, w.goals)}` +\n `${progressBar(squad.goalProgress, 8)}` +\n ` ${colors.purple}${box.vertical}${RESET}`;\n\n writeLine(row);\n }\n\n writeLine(` ${colors.purple}${box.bottomLeft}${colors.dim}${box.horizontal.repeat(tableWidth)}${colors.purple}${box.bottomRight}${RESET}`);\n writeLine();\n\n // Git Performance\n await renderGitPerformance();\n\n // Token Economics\n await renderTokenEconomics(squadData.map(s => s.name));\n\n // Historical Trends (if database available)\n await renderHistoricalTrends();\n\n // Agent Insights (task completion, quality, tools)\n await renderInsights();\n\n // Active goals (compact)\n const allActiveGoals = squadData.flatMap(s =>\n s.goals.filter(g => !g.completed).map(g => ({ squad: s.name, goal: g }))\n );\n\n if (allActiveGoals.length > 0) {\n writeLine(` ${bold}Goals${RESET}`);\n writeLine();\n\n const maxGoals = 6;\n for (const { squad, goal } of allActiveGoals.slice(0, maxGoals)) {\n const hasProgress = goal.progress && goal.progress.length > 0;\n const icon = hasProgress ? icons.progress : icons.empty;\n const squadLabel = `${colors.dim}${squad}${RESET}`;\n const goalText = truncate(goal.description, 48);\n\n writeLine(` ${icon} ${squadLabel} ${goalText}`);\n\n if (hasProgress) {\n const progressText = truncate(goal.progress!, 52);\n writeLine(` ${colors.dim}└${RESET} ${colors.green}${progressText}${RESET}`);\n }\n }\n\n if (allActiveGoals.length > maxGoals) {\n writeLine(` ${colors.dim} +${allActiveGoals.length - maxGoals} more${RESET}`);\n }\n writeLine();\n }\n\n // Quick actions\n writeLine(` ${colors.dim}$${RESET} squads run ${colors.cyan}<squad>${RESET} ${colors.dim}Execute a squad${RESET}`);\n writeLine(` ${colors.dim}$${RESET} squads goal set ${colors.dim}Add a goal${RESET}`);\n writeLine();\n\n // Save snapshot to local postgres (silent on failure)\n await saveSnapshot(squadData, ghStats, baseDir);\n}\n\n/**\n * Save dashboard snapshot to local PostgreSQL for historical tracking\n */\nasync function saveSnapshot(\n squadData: SquadMetrics[],\n ghStats: GitHubStats | null,\n baseDir: string | null\n): Promise<void> {\n // Check if database is available\n const dbAvailable = await isDatabaseAvailable();\n if (!dbAvailable) return;\n\n // Fetch additional data for snapshot\n const gitStats = baseDir ? getMultiRepoGitStats(baseDir, 30) : null;\n const costs = await fetchCostSummary(100);\n\n // Build squad snapshot data\n const squadsData: SquadSnapshotData[] = squadData.map(s => ({\n name: s.name,\n commits: s.github?.commits || 0,\n prsOpened: s.github?.prsOpened || 0,\n prsMerged: s.github?.prsMerged || 0,\n issuesClosed: s.github?.issuesClosed || 0,\n issuesOpen: s.github?.issuesOpen || 0,\n goalsActive: s.goals.filter(g => !g.completed).length,\n goalsTotal: s.goals.length,\n progress: s.goalProgress,\n }));\n\n // Build authors data\n const authorsData = gitStats\n ? Array.from(gitStats.commitsByAuthor.entries())\n .sort((a, b) => b[1] - a[1])\n .slice(0, 10)\n .map(([name, commits]) => ({ name, commits }))\n : [];\n\n // Build repos data\n const reposData = gitStats\n ? Array.from(gitStats.commitsByRepo.entries())\n .sort((a, b) => b[1] - a[1])\n .map(([name, commits]) => ({ name, commits }))\n : [];\n\n // Calculate totals\n const totalInputTokens = costs?.bySquad.reduce((sum, s) => sum + s.inputTokens, 0) || 0;\n const totalOutputTokens = costs?.bySquad.reduce((sum, s) => sum + s.outputTokens, 0) || 0;\n const overallProgress = squadData.length > 0\n ? Math.round(squadData.reduce((sum, s) => sum + s.goalProgress, 0) / squadData.length)\n : 0;\n\n const snapshot: DashboardSnapshot = {\n totalSquads: squadData.length,\n totalCommits: gitStats?.totalCommits || 0,\n totalPrsMerged: ghStats?.prsMerged || 0,\n totalIssuesClosed: ghStats?.issuesClosed || 0,\n totalIssuesOpen: ghStats?.issuesOpen || 0,\n goalProgressPct: overallProgress,\n costUsd: costs?.totalCost || 0,\n dailyBudgetUsd: costs?.dailyBudget || 50,\n inputTokens: totalInputTokens,\n outputTokens: totalOutputTokens,\n commits30d: gitStats?.totalCommits || 0,\n avgCommitsPerDay: gitStats?.avgCommitsPerDay || 0,\n activeDays: gitStats?.activeDays || 0,\n peakCommits: gitStats?.peakDay?.count || 0,\n peakDate: gitStats?.peakDay?.date || null,\n squadsData,\n authorsData,\n reposData,\n };\n\n await saveDashboardSnapshot(snapshot);\n}\n\n// Find agents-squads base directory\nfunction findAgentsSquadsDir(): string | null {\n const candidates = [\n join(process.cwd(), '..'),\n join(homedir(), 'agents-squads'),\n ];\n\n for (const dir of candidates) {\n if (existsSync(join(dir, 'hq'))) {\n return dir;\n }\n }\n return null;\n}\n\nasync function renderGitPerformance(): Promise<void> {\n const baseDir = findAgentsSquadsDir();\n\n if (!baseDir) {\n writeLine(` ${bold}Git Activity${RESET} ${colors.dim}(no repos found)${RESET}`);\n writeLine();\n return;\n }\n\n const stats = getMultiRepoGitStats(baseDir, 30);\n const activity = getActivitySparkline(baseDir, 14);\n\n if (stats.totalCommits === 0) {\n writeLine(` ${bold}Git Activity${RESET} ${colors.dim}(no commits in 30d)${RESET}`);\n writeLine();\n return;\n }\n\n writeLine(` ${bold}Git Activity${RESET} ${colors.dim}(30d)${RESET}`);\n writeLine();\n\n // Sparkline for last 14 days\n const spark = sparkline(activity);\n writeLine(` ${colors.dim}Last 14d:${RESET} ${spark}`);\n writeLine();\n\n // Key metrics row\n const metrics = [\n `${colors.cyan}${stats.totalCommits}${RESET} commits`,\n `${colors.green}${stats.avgCommitsPerDay}${RESET}/day`,\n `${colors.purple}${stats.activeDays}${RESET} active days`,\n ];\n if (stats.peakDay) {\n metrics.push(`${colors.yellow}${stats.peakDay.count}${RESET} peak ${colors.dim}(${stats.peakDay.date})${RESET}`);\n }\n writeLine(` ${metrics.join(` ${colors.dim}│${RESET} `)}`);\n writeLine();\n\n // Repos by commits (top 5)\n const sortedRepos = Array.from(stats.commitsByRepo.entries())\n .sort((a, b) => b[1] - a[1])\n .slice(0, 5);\n\n if (sortedRepos.length > 0) {\n const maxRepoCommits = sortedRepos[0][1];\n\n for (const [repo, commits] of sortedRepos) {\n const bar = barChart(commits, maxRepoCommits, 12);\n writeLine(` ${colors.cyan}${padEnd(repo, 20)}${RESET}${bar} ${colors.dim}${commits}${RESET}`);\n }\n writeLine();\n }\n\n // Authors (top 3)\n const sortedAuthors = Array.from(stats.commitsByAuthor.entries())\n .sort((a, b) => b[1] - a[1])\n .slice(0, 3);\n\n if (sortedAuthors.length > 0) {\n const authorLine = sortedAuthors\n .map(([author, count]) => `${colors.dim}${truncate(author, 15)}${RESET} ${colors.cyan}${count}${RESET}`)\n .join(` ${colors.dim}│${RESET} `);\n writeLine(` ${colors.dim}By author:${RESET} ${authorLine}`);\n writeLine();\n }\n}\n\nasync function renderTokenEconomics(squadNames: string[]): Promise<void> {\n const costs = await fetchCostSummary(100);\n\n if (!costs) {\n // No Langfuse config or API error - show hint\n writeLine(` ${bold}Token Economics${RESET} ${colors.dim}(no data)${RESET}`);\n writeLine(` ${colors.dim}Set LANGFUSE_PUBLIC_KEY & LANGFUSE_SECRET_KEY for cost tracking${RESET}`);\n writeLine();\n return;\n }\n\n writeLine(` ${bold}Token Economics${RESET} ${colors.dim}(last 100 calls)${RESET}`);\n writeLine();\n\n // Budget bar\n const barWidth = 32;\n const costBar = formatCostBar(costs.usedPercent, barWidth);\n writeLine(` ${colors.dim}Budget $${costs.dailyBudget}${RESET} [${costBar}] ${costs.usedPercent.toFixed(1)}%`);\n writeLine(` ${colors.green}$${costs.totalCost.toFixed(2)}${RESET} used ${colors.dim}│${RESET} ${colors.cyan}$${costs.idleBudget.toFixed(2)}${RESET} idle`);\n writeLine();\n\n // Anthropic tier and limits\n const tier = parseInt(process.env.ANTHROPIC_TIER || '4', 10);\n\n // RPM limits by tier (same for all models)\n const rpmByTier: Record<number, number> = { 1: 50, 2: 1000, 3: 2000, 4: 4000 };\n const rpmLimit = rpmByTier[tier] || 4000;\n\n // Token limits by tier and model family (ITPM/OTPM per minute)\n const tokenLimits: Record<number, Record<string, { itpm: number; otpm: number }>> = {\n 1: { opus: { itpm: 30000, otpm: 8000 }, sonnet: { itpm: 30000, otpm: 8000 }, haiku: { itpm: 50000, otpm: 10000 } },\n 2: { opus: { itpm: 450000, otpm: 90000 }, sonnet: { itpm: 450000, otpm: 90000 }, haiku: { itpm: 450000, otpm: 90000 } },\n 3: { opus: { itpm: 800000, otpm: 160000 }, sonnet: { itpm: 800000, otpm: 160000 }, haiku: { itpm: 1000000, otpm: 200000 } },\n 4: { opus: { itpm: 2000000, otpm: 400000 }, sonnet: { itpm: 2000000, otpm: 400000 }, haiku: { itpm: 4000000, otpm: 800000 } },\n };\n\n const modelShortNames: Record<string, string> = {\n 'claude-opus-4-5-20251101': 'opus-4.5',\n 'claude-sonnet-4-20250514': 'sonnet-4',\n 'claude-haiku-4-5-20251001': 'haiku-4.5',\n 'claude-3-5-sonnet-20241022': 'sonnet-3.5',\n 'claude-3-5-haiku-20241022': 'haiku-3.5',\n };\n\n const modelToFamily: Record<string, string> = {\n 'claude-opus-4-5-20251101': 'opus',\n 'claude-sonnet-4-20250514': 'sonnet',\n 'claude-haiku-4-5-20251001': 'haiku',\n 'claude-3-5-sonnet-20241022': 'sonnet',\n 'claude-3-5-haiku-20241022': 'haiku',\n };\n\n // Aggregate stats by model\n const modelStats: Record<string, { calls: number; input: number; output: number; cached: number }> = {};\n for (const squad of costs.bySquad) {\n for (const [model, count] of Object.entries(squad.models)) {\n if (!modelStats[model]) {\n modelStats[model] = { calls: 0, input: 0, output: 0, cached: 0 };\n }\n modelStats[model].calls += count;\n }\n // Distribute tokens proportionally (approximation since we don't have per-model token breakdown)\n const totalCalls = Object.values(squad.models).reduce((a, b) => a + b, 0);\n for (const [model, count] of Object.entries(squad.models)) {\n const ratio = totalCalls > 0 ? count / totalCalls : 0;\n modelStats[model].input += Math.round(squad.inputTokens * ratio);\n modelStats[model].output += Math.round(squad.outputTokens * ratio);\n }\n }\n\n // Total tokens for all models\n const totalInput = costs.bySquad.reduce((sum, s) => sum + s.inputTokens, 0);\n const totalOutput = costs.bySquad.reduce((sum, s) => sum + s.outputTokens, 0);\n const totalCalls = costs.bySquad.reduce((sum, s) => sum + s.calls, 0);\n\n // Cost projections\n const hourlyRate = costs.totalCost; // Based on last 100 calls, rough proxy\n const dailyProjection = hourlyRate * 24;\n const monthlyProjection = dailyProjection * 30;\n\n // Fetch real rate limits from proxy (if available)\n const rateLimits = await fetchRateLimits();\n const hasRealLimits = rateLimits.source === 'proxy' && Object.keys(rateLimits.limits).length > 0;\n\n // Display rate limits section\n if (hasRealLimits) {\n writeLine(` ${colors.dim}Rate Limits${RESET} ${colors.green}(live)${RESET}`);\n\n for (const [family, limits] of Object.entries(rateLimits.limits)) {\n const name = family === 'opus' ? 'opus' : family === 'sonnet' ? 'sonnet' : family === 'haiku' ? 'haiku' : family;\n\n // Request rate usage\n const reqUsed = limits.requestsLimit - limits.requestsRemaining;\n const reqPct = limits.requestsLimit > 0 ? (reqUsed / limits.requestsLimit) * 100 : 0;\n const reqColor = reqPct > 80 ? colors.red : reqPct > 50 ? colors.yellow : colors.green;\n\n // Token rate usage\n const tokUsed = limits.tokensLimit - limits.tokensRemaining;\n const tokPct = limits.tokensLimit > 0 ? (tokUsed / limits.tokensLimit) * 100 : 0;\n const tokColor = tokPct > 80 ? colors.red : tokPct > 50 ? colors.yellow : colors.green;\n\n writeLine(` ${colors.cyan}${padEnd(name, 8)}${RESET} ${reqColor}${String(reqUsed).padStart(4)}${RESET}${colors.dim}/${limits.requestsLimit}req${RESET} ${tokColor}${formatK(tokUsed)}${RESET}${colors.dim}/${formatK(limits.tokensLimit)}tok${RESET}`);\n }\n } else {\n writeLine(` ${colors.dim}Rate Limits (Tier ${tier})${RESET}`);\n\n const sortedModels = Object.entries(modelStats).sort((a, b) => b[1].calls - a[1].calls);\n for (const [model, stats] of sortedModels.slice(0, 3)) {\n const name = modelShortNames[model] || model.split('-').slice(1, 3).join('-');\n const family = modelToFamily[model] || 'sonnet';\n const limits = tokenLimits[tier]?.[family] || { itpm: 1000000, otpm: 200000 };\n\n // RPM\n const rpmPct = (stats.calls / rpmLimit) * 100;\n const rpmColor = rpmPct > 80 ? colors.red : rpmPct > 50 ? colors.yellow : colors.green;\n\n // Format: model [RPM bar] calls [ITPM] input [OTPM] output\n writeLine(` ${colors.cyan}${padEnd(name, 11)}${RESET} ${rpmColor}${String(stats.calls).padStart(4)}${RESET}${colors.dim}rpm${RESET} ${colors.dim}${formatK(stats.input)}${RESET}${colors.dim}/${formatK(limits.itpm)}i${RESET} ${colors.dim}${formatK(stats.output)}${RESET}${colors.dim}/${formatK(limits.otpm)}o${RESET}`);\n }\n }\n writeLine();\n\n // Cache efficiency\n if (costs.totalCachedTokens > 0 || costs.cacheHitRate > 0) {\n const cacheColor = costs.cacheHitRate > 50 ? colors.green : costs.cacheHitRate > 20 ? colors.yellow : colors.red;\n writeLine(` ${colors.dim}Cache:${RESET} ${cacheColor}${costs.cacheHitRate.toFixed(1)}%${RESET} hit rate ${colors.dim}(${formatK(costs.totalCachedTokens)} cached / ${formatK(costs.totalInputTokens + costs.totalCachedTokens)} total)${RESET}`);\n writeLine();\n }\n\n // Cost projections\n writeLine(` ${colors.dim}Projections${RESET}`);\n const projColor = dailyProjection > costs.dailyBudget ? colors.red : colors.green;\n writeLine(` ${colors.dim}Daily:${RESET} ${projColor}~$${dailyProjection.toFixed(2)}${RESET}${colors.dim}/${costs.dailyBudget}${RESET} ${colors.dim}Monthly:${RESET} ${colors.cyan}~$${monthlyProjection.toFixed(0)}${RESET}`);\n\n // Alerts\n if (dailyProjection > costs.dailyBudget * 0.8) {\n writeLine(` ${colors.yellow}⚠${RESET} ${colors.yellow}Projected to exceed daily budget${RESET}`);\n }\n if (costs.usedPercent > 80) {\n writeLine(` ${colors.red}⚠${RESET} ${colors.red}${costs.usedPercent.toFixed(0)}% of daily budget used${RESET}`);\n }\n writeLine();\n}\n\n// Format number as K/M\nfunction formatK(n: number): string {\n if (n >= 1000000) return (n / 1000000).toFixed(1) + 'M';\n if (n >= 1000) return (n / 1000).toFixed(0) + 'k';\n return String(n);\n}\n\nasync function renderHistoricalTrends(): Promise<void> {\n // Check if database is available\n const dbAvailable = await isDatabaseAvailable();\n if (!dbAvailable) return;\n\n const history = await getDashboardHistory(14);\n if (history.length < 2) return; // Need at least 2 data points\n\n writeLine(` ${bold}Usage Trends${RESET} ${colors.dim}(${history.length}d history)${RESET}`);\n writeLine();\n\n // Daily cost sparkline (most recent first, so reverse for left-to-right)\n const dailyCosts = history.map(h => h.costUsd).reverse();\n const costSparkStr = sparkline(dailyCosts);\n const totalSpend = dailyCosts.reduce((sum, c) => sum + c, 0);\n const avgDaily = totalSpend / dailyCosts.length;\n\n writeLine(` ${colors.dim}Cost:${RESET} ${costSparkStr} ${colors.green}$${totalSpend.toFixed(2)}${RESET} total ${colors.dim}($${avgDaily.toFixed(2)}/day avg)${RESET}`);\n\n // Token usage trend\n const inputTokens = history.map(h => h.inputTokens).reverse();\n const totalInput = inputTokens.reduce((sum, t) => sum + t, 0);\n const tokenSparkStr = sparkline(inputTokens);\n\n writeLine(` ${colors.dim}Tokens:${RESET} ${tokenSparkStr} ${colors.cyan}${formatK(totalInput)}${RESET} input ${colors.dim}(${formatK(Math.round(totalInput / inputTokens.length))}/day)${RESET}`);\n\n // Goal progress trend\n const goalProgress = history.map(h => h.goalProgressPct).reverse();\n const latestProgress = goalProgress[goalProgress.length - 1] || 0;\n const earliestProgress = goalProgress[0] || 0;\n const progressDelta = latestProgress - earliestProgress;\n const progressColor = progressDelta > 0 ? colors.green : progressDelta < 0 ? colors.red : colors.dim;\n const progressSign = progressDelta > 0 ? '+' : '';\n\n writeLine(` ${colors.dim}Goals:${RESET} ${sparkline(goalProgress)} ${colors.purple}${latestProgress}%${RESET} ${progressColor}${progressSign}${progressDelta.toFixed(0)}%${RESET}${colors.dim} vs start${RESET}`);\n writeLine();\n}\n\nasync function renderInsights(): Promise<void> {\n const insights = await fetchInsights('week');\n\n if (insights.source === 'none' || insights.taskMetrics.length === 0) {\n // No insights data available - skip section entirely\n return;\n }\n\n writeLine(` ${bold}Agent Insights${RESET} ${colors.dim}(${insights.days}d)${RESET}`);\n writeLine();\n\n // Task completion metrics (aggregated)\n const totals = insights.taskMetrics.reduce(\n (acc, t) => ({\n tasks: acc.tasks + t.tasksTotal,\n completed: acc.completed + t.tasksCompleted,\n failed: acc.failed + t.tasksFailed,\n retries: acc.retries + t.totalRetries,\n withRetries: acc.withRetries + t.tasksWithRetries,\n }),\n { tasks: 0, completed: 0, failed: 0, retries: 0, withRetries: 0 }\n );\n\n if (totals.tasks > 0) {\n const successRate = totals.tasks > 0 ? ((totals.completed / totals.tasks) * 100).toFixed(0) : '0';\n const successColor = parseInt(successRate) >= 80 ? colors.green : parseInt(successRate) >= 60 ? colors.yellow : colors.red;\n\n // Task completion row\n writeLine(` ${colors.dim}Tasks:${RESET} ${colors.green}${totals.completed}${RESET}${colors.dim}/${totals.tasks} completed${RESET} ${successColor}${successRate}%${RESET}${colors.dim} success${RESET} ${colors.red}${totals.failed}${RESET}${colors.dim} failed${RESET}`);\n\n // Retry metrics\n if (totals.retries > 0) {\n const retryRate = totals.tasks > 0 ? ((totals.withRetries / totals.tasks) * 100).toFixed(0) : '0';\n const retryColor = parseInt(retryRate) > 30 ? colors.red : parseInt(retryRate) > 15 ? colors.yellow : colors.green;\n writeLine(` ${colors.dim}Retries:${RESET} ${retryColor}${totals.retries}${RESET}${colors.dim} total${RESET} ${retryColor}${retryRate}%${RESET}${colors.dim} of tasks needed retry${RESET}`);\n }\n }\n\n // Quality metrics (if feedback exists)\n const qualityTotals = insights.qualityMetrics.reduce(\n (acc, q) => ({\n feedback: acc.feedback + q.feedbackCount,\n qualitySum: acc.qualitySum + (q.avgQuality * q.feedbackCount),\n helpfulSum: acc.helpfulSum + (q.helpfulPct * q.feedbackCount / 100),\n fixSum: acc.fixSum + (q.fixRequiredPct * q.feedbackCount / 100),\n }),\n { feedback: 0, qualitySum: 0, helpfulSum: 0, fixSum: 0 }\n );\n\n if (qualityTotals.feedback > 0) {\n const avgQuality = qualityTotals.qualitySum / qualityTotals.feedback;\n const helpfulPct = (qualityTotals.helpfulSum / qualityTotals.feedback) * 100;\n const fixPct = (qualityTotals.fixSum / qualityTotals.feedback) * 100;\n\n const qualityColor = avgQuality >= 4 ? colors.green : avgQuality >= 3 ? colors.yellow : colors.red;\n const stars = '★'.repeat(Math.round(avgQuality)) + '☆'.repeat(5 - Math.round(avgQuality));\n\n writeLine(` ${colors.dim}Quality:${RESET} ${qualityColor}${stars}${RESET} ${colors.dim}(${avgQuality.toFixed(1)}/5)${RESET} ${colors.green}${helpfulPct.toFixed(0)}%${RESET}${colors.dim} helpful${RESET} ${fixPct > 20 ? colors.red : colors.dim}${fixPct.toFixed(0)}% needed fixes${RESET}`);\n }\n\n // Context window utilization\n const contextMetrics = insights.taskMetrics.filter(t => t.avgContextPct > 0);\n if (contextMetrics.length > 0) {\n const avgContext = contextMetrics.reduce((sum, t) => sum + t.avgContextPct, 0) / contextMetrics.length;\n const maxContext = Math.max(...contextMetrics.map(t => t.maxContextTokens));\n\n // Context utilization colors: green < 40%, yellow 40-70%, red > 70%\n const contextColor = avgContext < 40 ? colors.green : avgContext < 70 ? colors.yellow : colors.red;\n const contextStatus = avgContext < 40 ? 'lean' : avgContext < 70 ? 'moderate' : 'heavy';\n\n writeLine(` ${colors.dim}Context:${RESET} ${contextColor}${avgContext.toFixed(0)}%${RESET}${colors.dim} avg utilization (${contextStatus})${RESET} ${colors.dim}peak ${formatK(maxContext)} tokens${RESET}`);\n }\n\n writeLine();\n\n // Top tools (compact)\n if (insights.topTools.length > 0) {\n const toolLine = insights.topTools.slice(0, 5).map(t => {\n const successColor = t.successRate >= 95 ? colors.green : t.successRate >= 80 ? colors.yellow : colors.red;\n return `${colors.dim}${t.toolName.replace('mcp__', '').slice(0, 12)}${RESET} ${successColor}${t.successRate.toFixed(0)}%${RESET}`;\n }).join(' ');\n\n writeLine(` ${colors.dim}Tools:${RESET} ${toolLine}`);\n\n // Tool failure alert\n if (insights.toolFailureRate > 5) {\n writeLine(` ${colors.yellow}⚠${RESET} ${colors.yellow}${insights.toolFailureRate.toFixed(1)}% tool failure rate${RESET}`);\n }\n writeLine();\n }\n}\n\n// Priority keywords that indicate high priority goals\nconst P0_KEYWORDS = ['revenue', 'first', 'launch', 'publish', 'ship', 'critical', 'urgent'];\nconst P1_KEYWORDS = ['track', 'establish', 'identify', 'define', 'fix'];\n\nfunction inferPriority(goal: string): 'P0' | 'P1' | 'P2' {\n const lower = goal.toLowerCase();\n if (P0_KEYWORDS.some(k => lower.includes(k))) return 'P0';\n if (P1_KEYWORDS.some(k => lower.includes(k))) return 'P1';\n return 'P2';\n}\n\nasync function renderCeoReport(squadsDir: string): Promise<void> {\n const squadNames = listSquads(squadsDir);\n const allGoals: { squad: string; goal: Goal; priority: 'P0' | 'P1' | 'P2' }[] = [];\n const blockers: string[] = [];\n let activeSquads = 0;\n let staleSquads = 0;\n\n for (const name of squadNames) {\n const squad = loadSquad(name);\n if (!squad) continue;\n\n const lastActivity = getLastActivityDate(name);\n const activeGoals = squad.goals.filter(g => !g.completed);\n\n // Check for blockers\n if (activeGoals.length === 0) {\n blockers.push(`${name}: No active goals`);\n } else if (lastActivity.includes('w') || lastActivity === '—') {\n blockers.push(`${name}: Stale (${lastActivity})`);\n staleSquads++;\n } else {\n activeSquads++;\n }\n\n // Collect goals with inferred priority\n for (const goal of activeGoals) {\n allGoals.push({\n squad: name,\n goal,\n priority: inferPriority(goal.description),\n });\n }\n }\n\n // Sort by priority\n allGoals.sort((a, b) => {\n const order = { P0: 0, P1: 1, P2: 2 };\n return order[a.priority] - order[b.priority];\n });\n\n const p0Goals = allGoals.filter(g => g.priority === 'P0');\n const p1Goals = allGoals.filter(g => g.priority === 'P1');\n\n // Render\n writeLine();\n writeLine(` ${gradient('squads')} ${colors.dim}CEO Report${RESET}`);\n writeLine(` ${colors.dim}${new Date().toISOString().split('T')[0]}${RESET}`);\n writeLine();\n\n // Key metrics\n const w = { label: 20, value: 12 };\n const tableWidth = w.label + w.value + 4;\n\n writeLine(` ${colors.purple}${box.topLeft}${colors.dim}${box.horizontal.repeat(tableWidth)}${colors.purple}${box.topRight}${RESET}`);\n writeLine(` ${colors.purple}${box.vertical}${RESET} ${bold}${padEnd('METRIC', w.label)}${RESET}${bold}VALUE${RESET} ${colors.purple}${box.vertical}${RESET}`);\n writeLine(` ${colors.purple}${box.teeRight}${colors.dim}${box.horizontal.repeat(tableWidth)}${colors.purple}${box.teeLeft}${RESET}`);\n\n writeLine(` ${colors.purple}${box.vertical}${RESET} ${padEnd('Active Squads', w.label)}${colors.green}${padEnd(`${activeSquads}/${squadNames.length}`, w.value)}${RESET}${colors.purple}${box.vertical}${RESET}`);\n writeLine(` ${colors.purple}${box.vertical}${RESET} ${padEnd('P0 Goals', w.label)}${colors.red}${padEnd(String(p0Goals.length), w.value)}${RESET}${colors.purple}${box.vertical}${RESET}`);\n writeLine(` ${colors.purple}${box.vertical}${RESET} ${padEnd('P1 Goals', w.label)}${colors.yellow}${padEnd(String(p1Goals.length), w.value)}${RESET}${colors.purple}${box.vertical}${RESET}`);\n writeLine(` ${colors.purple}${box.vertical}${RESET} ${padEnd('Blockers', w.label)}${blockers.length > 0 ? colors.red : colors.green}${padEnd(String(blockers.length), w.value)}${RESET}${colors.purple}${box.vertical}${RESET}`);\n\n // Token Economics (add to metrics table)\n const costs = await fetchCostSummary(100);\n if (costs) {\n const spendStr = `$${costs.totalCost.toFixed(2)} / $${costs.dailyBudget}`;\n writeLine(` ${colors.purple}${box.vertical}${RESET} ${padEnd('Daily Spend', w.label)}${colors.green}${padEnd(spendStr, w.value)}${RESET}${colors.purple}${box.vertical}${RESET}`);\n }\n\n writeLine(` ${colors.purple}${box.bottomLeft}${colors.dim}${box.horizontal.repeat(tableWidth)}${colors.purple}${box.bottomRight}${RESET}`);\n writeLine();\n\n // Top Priorities (P0)\n if (p0Goals.length > 0) {\n writeLine(` ${bold}${colors.red}P0${RESET} ${bold}Priorities${RESET} ${colors.dim}(revenue/launch critical)${RESET}`);\n writeLine();\n for (const { squad, goal } of p0Goals.slice(0, 5)) {\n writeLine(` ${icons.error} ${colors.cyan}${squad}${RESET} ${goal.description}`);\n if (goal.progress) {\n writeLine(` ${colors.dim}└ ${goal.progress}${RESET}`);\n }\n }\n writeLine();\n }\n\n // P1 Goals\n if (p1Goals.length > 0) {\n writeLine(` ${bold}${colors.yellow}P1${RESET} ${bold}Important${RESET} ${colors.dim}(tracking/foundations)${RESET}`);\n writeLine();\n for (const { squad, goal } of p1Goals.slice(0, 3)) {\n writeLine(` ${icons.warning} ${colors.cyan}${squad}${RESET} ${truncate(goal.description, 50)}`);\n }\n if (p1Goals.length > 3) {\n writeLine(` ${colors.dim} +${p1Goals.length - 3} more${RESET}`);\n }\n writeLine();\n }\n\n // Blockers\n if (blockers.length > 0) {\n writeLine(` ${bold}Blockers${RESET}`);\n writeLine();\n for (const blocker of blockers.slice(0, 3)) {\n writeLine(` ${icons.error} ${colors.red}${blocker}${RESET}`);\n }\n writeLine();\n }\n\n // Next Steps\n writeLine(` ${bold}Next Steps${RESET}`);\n writeLine();\n if (p0Goals.length > 0) {\n writeLine(` ${icons.active} Focus on P0: ${colors.cyan}${p0Goals[0].squad}${RESET} - ${truncate(p0Goals[0].goal.description, 40)}`);\n }\n if (blockers.length > 0) {\n writeLine(` ${icons.warning} Unblock: ${colors.yellow}${blockers[0]}${RESET}`);\n }\n if (staleSquads > 0) {\n writeLine(` ${icons.progress} Revive ${staleSquads} stale squad(s)`);\n }\n writeLine();\n\n // Commands\n writeLine(` ${colors.dim}$${RESET} squads dash ${colors.dim}Full operational view${RESET}`);\n writeLine(` ${colors.dim}$${RESET} squads goal list ${colors.dim}All active goals${RESET}`);\n writeLine();\n}\n","/**\n * Cost tracking via Squads Bridge (postgres) or Langfuse\n * Primary: Squads Bridge API → PostgreSQL\n * Fallback: Langfuse API (if bridge unavailable)\n */\n\ninterface SquadCosts {\n squad: string;\n calls: number;\n inputTokens: number;\n outputTokens: number;\n cachedTokens: number;\n cost: number;\n models: Record<string, number>;\n}\n\nexport interface CostSummary {\n totalCost: number;\n dailyBudget: number;\n usedPercent: number;\n idleBudget: number;\n totalCalls: number;\n dailyCallLimit: number;\n callsPercent: number;\n totalCachedTokens: number;\n totalInputTokens: number;\n cacheHitRate: number;\n bySquad: SquadCosts[];\n source: 'postgres' | 'langfuse' | 'none';\n}\n\n// Model pricing (per 1M tokens)\nconst MODEL_PRICING: Record<string, { input: number; output: number }> = {\n 'claude-opus-4-5-20251101': { input: 15.0, output: 75.0 },\n 'claude-sonnet-4-20250514': { input: 3.0, output: 15.0 },\n 'claude-haiku-4-5-20251001': { input: 0.80, output: 4.0 },\n 'claude-3-5-sonnet-20241022': { input: 3.0, output: 15.0 },\n 'claude-3-5-haiku-20241022': { input: 0.80, output: 4.0 },\n default: { input: 3.0, output: 15.0 },\n};\n\nconst DEFAULT_DAILY_BUDGET = 50.0;\nconst DEFAULT_DAILY_CALL_LIMIT = 1000; // Default API call limit per day\nconst BRIDGE_URL = process.env.SQUADS_BRIDGE_URL || 'http://localhost:8088';\n\nfunction calcCost(model: string, inputTokens: number, outputTokens: number): number {\n const pricing = MODEL_PRICING[model] || MODEL_PRICING.default;\n return (inputTokens / 1_000_000) * pricing.input + (outputTokens / 1_000_000) * pricing.output;\n}\n\n/**\n * Fetch cost summary from Squads Bridge (postgres)\n */\nasync function fetchFromBridge(period: 'day' | 'week' | 'month' = 'day'): Promise<CostSummary | null> {\n try {\n const response = await fetch(`${BRIDGE_URL}/api/cost/summary?period=${period}`, {\n headers: { 'Content-Type': 'application/json' },\n });\n\n if (!response.ok) {\n return null;\n }\n\n const data = await response.json() as { totals?: { cost_usd?: number }; by_squad?: Record<string, unknown>[] };\n const dailyBudget = parseFloat(process.env.SQUADS_DAILY_BUDGET || '') || DEFAULT_DAILY_BUDGET;\n const totalCost = data.totals?.cost_usd || 0;\n\n const bySquad: SquadCosts[] = (data.by_squad || []).map((s: Record<string, unknown>) => ({\n squad: s.squad as string,\n calls: (s.generations as number) || 0,\n inputTokens: (s.input_tokens as number) || 0,\n outputTokens: (s.output_tokens as number) || 0,\n cachedTokens: (s.cached_tokens as number) || 0,\n cost: (s.cost_usd as number) || 0,\n models: {},\n }));\n\n const totalCalls = bySquad.reduce((sum, s) => sum + s.calls, 0);\n const dailyCallLimit = parseFloat(process.env.SQUADS_DAILY_CALL_LIMIT || '') || DEFAULT_DAILY_CALL_LIMIT;\n const totalCachedTokens = bySquad.reduce((sum, s) => sum + s.cachedTokens, 0);\n const totalInputTokens = bySquad.reduce((sum, s) => sum + s.inputTokens, 0);\n const totalAllInput = totalInputTokens + totalCachedTokens;\n const cacheHitRate = totalAllInput > 0 ? (totalCachedTokens / totalAllInput) * 100 : 0;\n\n return {\n totalCost,\n dailyBudget,\n usedPercent: (totalCost / dailyBudget) * 100,\n idleBudget: dailyBudget - totalCost,\n totalCalls,\n dailyCallLimit,\n callsPercent: (totalCalls / dailyCallLimit) * 100,\n totalCachedTokens,\n totalInputTokens,\n cacheHitRate,\n bySquad,\n source: 'postgres',\n };\n } catch {\n return null;\n }\n}\n\n/**\n * Fetch cost summary from Langfuse API (fallback)\n */\nasync function fetchFromLangfuse(limit = 100): Promise<CostSummary | null> {\n const publicKey = process.env.LANGFUSE_PUBLIC_KEY;\n const secretKey = process.env.LANGFUSE_SECRET_KEY;\n const host = process.env.LANGFUSE_HOST || process.env.LANGFUSE_BASE_URL || 'https://us.cloud.langfuse.com';\n\n if (!publicKey || !secretKey) {\n return null;\n }\n\n try {\n const auth = Buffer.from(`${publicKey}:${secretKey}`).toString('base64');\n const url = `${host}/api/public/observations?limit=${limit}`;\n\n const response = await fetch(url, {\n headers: {\n Authorization: `Basic ${auth}`,\n 'Content-Type': 'application/json',\n },\n });\n\n if (!response.ok) {\n return null;\n }\n\n interface LangfuseObs {\n type?: string;\n model?: string;\n metadata?: { squad?: string };\n usage?: { input?: number; output?: number };\n }\n const data = await response.json() as { data?: LangfuseObs[] };\n const observations = data.data || [];\n\n // Group by squad\n const bySquad: Record<string, SquadCosts> = {};\n\n for (const obs of observations) {\n if (obs.type !== 'GENERATION') continue;\n\n const metadata = obs.metadata || {};\n const squad = metadata.squad || 'unknown';\n const model = obs.model || 'unknown';\n const usage = obs.usage || {};\n\n const inputTokens = usage.input || 0;\n const outputTokens = usage.output || 0;\n const cost = calcCost(model, inputTokens, outputTokens);\n\n if (!bySquad[squad]) {\n bySquad[squad] = {\n squad,\n calls: 0,\n inputTokens: 0,\n outputTokens: 0,\n cachedTokens: 0,\n cost: 0,\n models: {},\n };\n }\n\n bySquad[squad].calls += 1;\n bySquad[squad].inputTokens += inputTokens;\n bySquad[squad].outputTokens += outputTokens;\n bySquad[squad].cost += cost;\n bySquad[squad].models[model] = (bySquad[squad].models[model] || 0) + 1;\n }\n\n const squadList = Object.values(bySquad).sort((a, b) => b.cost - a.cost);\n const totalCost = squadList.reduce((sum, s) => sum + s.cost, 0);\n const dailyBudget = parseFloat(process.env.SQUADS_DAILY_BUDGET || '') || DEFAULT_DAILY_BUDGET;\n\n const totalCalls = squadList.reduce((sum, s) => sum + s.calls, 0);\n const dailyCallLimit = parseFloat(process.env.SQUADS_DAILY_CALL_LIMIT || '') || DEFAULT_DAILY_CALL_LIMIT;\n const totalCachedTokens = squadList.reduce((sum, s) => sum + s.cachedTokens, 0);\n const totalInputTokens = squadList.reduce((sum, s) => sum + s.inputTokens, 0);\n const totalAllInput = totalInputTokens + totalCachedTokens;\n const cacheHitRate = totalAllInput > 0 ? (totalCachedTokens / totalAllInput) * 100 : 0;\n\n return {\n totalCost,\n dailyBudget,\n usedPercent: (totalCost / dailyBudget) * 100,\n idleBudget: dailyBudget - totalCost,\n totalCalls,\n dailyCallLimit,\n callsPercent: (totalCalls / dailyCallLimit) * 100,\n totalCachedTokens,\n totalInputTokens,\n cacheHitRate,\n bySquad: squadList,\n source: 'langfuse',\n };\n } catch {\n return null;\n }\n}\n\n/**\n * Fetch cost summary - tries postgres first, falls back to Langfuse\n */\nexport async function fetchCostSummary(\n limit = 100,\n period: 'day' | 'week' | 'month' = 'day'\n): Promise<CostSummary | null> {\n // Try postgres (via bridge) first\n const bridgeResult = await fetchFromBridge(period);\n if (bridgeResult) {\n return bridgeResult;\n }\n\n // Fall back to Langfuse\n const langfuseResult = await fetchFromLangfuse(limit);\n if (langfuseResult) {\n return langfuseResult;\n }\n\n // No data source available\n const defaultBudget = parseFloat(process.env.SQUADS_DAILY_BUDGET || '') || DEFAULT_DAILY_BUDGET;\n return {\n totalCost: 0,\n dailyBudget: defaultBudget,\n usedPercent: 0,\n idleBudget: defaultBudget,\n totalCalls: 0,\n dailyCallLimit: DEFAULT_DAILY_CALL_LIMIT,\n callsPercent: 0,\n totalCachedTokens: 0,\n totalInputTokens: 0,\n cacheHitRate: 0,\n bySquad: [],\n source: 'none',\n };\n}\n\nexport function formatCostBar(usedPercent: number, width = 20): string {\n const filled = Math.min(Math.round((usedPercent / 100) * width), width);\n const empty = width - filled;\n return '█'.repeat(filled) + '░'.repeat(empty);\n}\n\n/**\n * Rate limit data from Anthropic API headers\n */\nexport interface RateLimitInfo {\n model: string;\n requestsLimit: number;\n requestsRemaining: number;\n requestsReset?: string;\n tokensLimit: number;\n tokensRemaining: number;\n tokensReset?: string;\n inputTokensLimit?: number;\n inputTokensRemaining?: number;\n outputTokensLimit?: number;\n outputTokensRemaining?: number;\n capturedAt: string;\n}\n\nexport interface RateLimits {\n limits: Record<string, RateLimitInfo>;\n source: 'proxy' | 'none';\n}\n\n/**\n * Fetch real rate limits from the Anthropic proxy (via bridge)\n */\nexport async function fetchRateLimits(): Promise<RateLimits> {\n try {\n const response = await fetch(`${BRIDGE_URL}/api/rate-limits`, {\n headers: { 'Content-Type': 'application/json' },\n });\n\n if (!response.ok) {\n return { limits: {}, source: 'none' };\n }\n\n interface RateLimitResponse {\n rate_limits?: Record<string, {\n model?: string;\n requests_limit?: number;\n requests_remaining?: number;\n requests_reset?: string;\n tokens_limit?: number;\n tokens_remaining?: number;\n tokens_reset?: string;\n input_tokens_limit?: number;\n input_tokens_remaining?: number;\n output_tokens_limit?: number;\n output_tokens_remaining?: number;\n captured_at?: string;\n }>;\n }\n\n const data = await response.json() as RateLimitResponse;\n const rateLimits = data.rate_limits || {};\n\n const limits: Record<string, RateLimitInfo> = {};\n for (const [key, value] of Object.entries(rateLimits)) {\n limits[key] = {\n model: value.model || key,\n requestsLimit: value.requests_limit || 0,\n requestsRemaining: value.requests_remaining || 0,\n requestsReset: value.requests_reset,\n tokensLimit: value.tokens_limit || 0,\n tokensRemaining: value.tokens_remaining || 0,\n tokensReset: value.tokens_reset,\n inputTokensLimit: value.input_tokens_limit,\n inputTokensRemaining: value.input_tokens_remaining,\n outputTokensLimit: value.output_tokens_limit,\n outputTokensRemaining: value.output_tokens_remaining,\n capturedAt: value.captured_at || new Date().toISOString(),\n };\n }\n\n return { limits, source: 'proxy' };\n } catch {\n return { limits: {}, source: 'none' };\n }\n}\n\n/**\n * Task and quality insights\n */\nexport interface TaskMetrics {\n squad: string;\n tasksTotal: number;\n tasksCompleted: number;\n tasksFailed: number;\n successRate: number;\n totalRetries: number;\n tasksWithRetries: number;\n avgRetries: number;\n avgDurationMs: number;\n avgTokens: number;\n avgCost: number;\n avgContextPct: number;\n maxContextTokens: number;\n}\n\nexport interface ToolMetrics {\n toolName: string;\n usageCount: number;\n successRate: number;\n avgDurationMs: number;\n}\n\nexport interface QualityMetrics {\n squad: string;\n feedbackCount: number;\n avgQuality: number;\n helpfulPct: number;\n fixRequiredPct: number;\n}\n\nexport interface Insights {\n period: string;\n days: number;\n taskMetrics: TaskMetrics[];\n qualityMetrics: QualityMetrics[];\n topTools: ToolMetrics[];\n toolFailureRate: number;\n source: 'bridge' | 'none';\n}\n\n/**\n * Fetch insights from the bridge\n */\nexport async function fetchInsights(period: 'day' | 'week' | 'month' = 'week'): Promise<Insights> {\n try {\n const response = await fetch(`${BRIDGE_URL}/api/insights?period=${period}`, {\n headers: { 'Content-Type': 'application/json' },\n });\n\n if (!response.ok) {\n return {\n period,\n days: period === 'day' ? 1 : period === 'week' ? 7 : 30,\n taskMetrics: [],\n qualityMetrics: [],\n topTools: [],\n toolFailureRate: 0,\n source: 'none',\n };\n }\n\n interface InsightsResponse {\n period: string;\n days: number;\n task_metrics?: Array<{\n squad: string;\n tasks_total: number;\n tasks_completed: number;\n tasks_failed: number;\n success_rate: number;\n total_retries: number;\n tasks_with_retries: number;\n avg_retries: number;\n avg_duration_ms: number;\n avg_tokens: number;\n avg_cost: number;\n avg_context_pct: number;\n max_context_tokens: number;\n }>;\n quality_metrics?: Array<{\n squad: string;\n feedback_count: number;\n avg_quality: number;\n helpful_pct: number;\n fix_required_pct: number;\n }>;\n top_tools?: Array<{\n tool_name: string;\n usage_count: number;\n success_rate: number;\n avg_duration_ms: number;\n }>;\n tool_failure_rate?: number;\n }\n\n const data = await response.json() as InsightsResponse;\n\n return {\n period: data.period || period,\n days: data.days || 7,\n taskMetrics: (data.task_metrics || []).map(t => ({\n squad: t.squad,\n tasksTotal: t.tasks_total || 0,\n tasksCompleted: t.tasks_completed || 0,\n tasksFailed: t.tasks_failed || 0,\n successRate: t.success_rate || 0,\n totalRetries: t.total_retries || 0,\n tasksWithRetries: t.tasks_with_retries || 0,\n avgRetries: t.avg_retries || 0,\n avgDurationMs: t.avg_duration_ms || 0,\n avgTokens: t.avg_tokens || 0,\n avgCost: t.avg_cost || 0,\n avgContextPct: t.avg_context_pct || 0,\n maxContextTokens: t.max_context_tokens || 0,\n })),\n qualityMetrics: (data.quality_metrics || []).map(q => ({\n squad: q.squad,\n feedbackCount: q.feedback_count || 0,\n avgQuality: q.avg_quality || 0,\n helpfulPct: q.helpful_pct || 0,\n fixRequiredPct: q.fix_required_pct || 0,\n })),\n topTools: (data.top_tools || []).map(t => ({\n toolName: t.tool_name,\n usageCount: t.usage_count || 0,\n successRate: t.success_rate || 0,\n avgDurationMs: t.avg_duration_ms || 0,\n })),\n toolFailureRate: data.tool_failure_rate || 0,\n source: 'bridge',\n };\n } catch {\n return {\n period,\n days: period === 'day' ? 1 : period === 'week' ? 7 : 30,\n taskMetrics: [],\n qualityMetrics: [],\n topTools: [],\n toolFailureRate: 0,\n source: 'none',\n };\n }\n}\n","/**\n * Database utilities for local PostgreSQL persistence\n * Connects to the squads schema for storing metrics and snapshots\n */\n\nimport { createRequire } from 'module';\nconst require = createRequire(import.meta.url);\nconst pg = require('pg');\nconst { Pool } = pg;\n\n// Connection config from environment or defaults\nconst DATABASE_URL = process.env.SQUADS_DATABASE_URL ||\n 'postgresql://squads:squads_local_dev@localhost:5433/squads';\n\nlet pool: InstanceType<typeof Pool> | null = null;\n\n/**\n * Get or create the connection pool\n */\nfunction getPool(): InstanceType<typeof Pool> {\n if (!pool) {\n pool = new Pool({\n connectionString: DATABASE_URL,\n max: 5,\n idleTimeoutMillis: 30000,\n connectionTimeoutMillis: 5000,\n });\n\n // Handle pool errors\n pool.on('error', (err: Error) => {\n console.error('Unexpected database pool error:', err);\n });\n }\n return pool;\n}\n\n/**\n * Check if database is available\n */\nexport async function isDatabaseAvailable(): Promise<boolean> {\n try {\n const pool = getPool();\n const client = await pool.connect();\n await client.query('SELECT 1');\n client.release();\n return true;\n } catch (err) {\n if (process.env.DEBUG) {\n console.error('DB availability check failed:', err);\n }\n return false;\n }\n}\n\n/**\n * Dashboard snapshot data structure\n */\nexport interface DashboardSnapshot {\n // Top-level metrics\n totalSquads: number;\n totalCommits: number;\n totalPrsMerged: number;\n totalIssuesClosed: number;\n totalIssuesOpen: number;\n goalProgressPct: number;\n\n // Cost metrics\n costUsd: number;\n dailyBudgetUsd: number;\n inputTokens: number;\n outputTokens: number;\n\n // Git activity\n commits30d: number;\n avgCommitsPerDay: number;\n activeDays: number;\n peakCommits: number;\n peakDate: string | null;\n\n // Detailed breakdowns (stored as JSONB)\n squadsData: SquadSnapshotData[];\n authorsData: { name: string; commits: number }[];\n reposData: { name: string; commits: number }[];\n}\n\nexport interface SquadSnapshotData {\n name: string;\n commits: number;\n prsOpened: number;\n prsMerged: number;\n issuesClosed: number;\n issuesOpen: number;\n goalsActive: number;\n goalsTotal: number;\n progress: number;\n}\n\n/**\n * Save a dashboard snapshot to the database\n */\nexport async function saveDashboardSnapshot(snapshot: DashboardSnapshot): Promise<number | null> {\n try {\n const pool = getPool();\n const client = await pool.connect();\n\n const result = await client.query(`\n INSERT INTO squads.dashboard_snapshots (\n total_squads, total_commits, total_prs_merged, total_issues_closed, total_issues_open,\n goal_progress_pct, cost_usd, daily_budget_usd, input_tokens, output_tokens,\n commits_30d, avg_commits_per_day, active_days, peak_commits, peak_date,\n squads_data, authors_data, repos_data\n ) VALUES (\n $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18\n ) RETURNING id\n `, [\n snapshot.totalSquads,\n snapshot.totalCommits,\n snapshot.totalPrsMerged,\n snapshot.totalIssuesClosed,\n snapshot.totalIssuesOpen,\n snapshot.goalProgressPct,\n snapshot.costUsd,\n snapshot.dailyBudgetUsd,\n snapshot.inputTokens,\n snapshot.outputTokens,\n snapshot.commits30d,\n snapshot.avgCommitsPerDay,\n snapshot.activeDays,\n snapshot.peakCommits,\n snapshot.peakDate,\n JSON.stringify(snapshot.squadsData),\n JSON.stringify(snapshot.authorsData),\n JSON.stringify(snapshot.reposData),\n ]);\n\n client.release();\n return result.rows[0]?.id ?? null;\n } catch (err) {\n // Log error for debugging, but don't crash\n if (process.env.DEBUG) {\n console.error('DB save error:', err);\n }\n return null;\n }\n}\n\n/**\n * Get recent dashboard snapshots for trend analysis\n */\nexport async function getDashboardHistory(limit: number = 30): Promise<DashboardSnapshot[]> {\n try {\n const client = await getPool().connect();\n\n const result = await client.query(`\n SELECT\n total_squads, total_commits, total_prs_merged, total_issues_closed, total_issues_open,\n goal_progress_pct, cost_usd, daily_budget_usd, input_tokens, output_tokens,\n commits_30d, avg_commits_per_day, active_days, peak_commits, peak_date,\n squads_data, authors_data, repos_data, captured_at\n FROM squads.dashboard_snapshots\n ORDER BY captured_at DESC\n LIMIT $1\n `, [limit]);\n\n client.release();\n\n return result.rows.map((row: Record<string, unknown>) => ({\n totalSquads: row.total_squads,\n totalCommits: row.total_commits,\n totalPrsMerged: row.total_prs_merged,\n totalIssuesClosed: row.total_issues_closed,\n totalIssuesOpen: row.total_issues_open,\n goalProgressPct: row.goal_progress_pct,\n costUsd: parseFloat(String(row.cost_usd)),\n dailyBudgetUsd: parseFloat(String(row.daily_budget_usd)),\n inputTokens: row.input_tokens,\n outputTokens: row.output_tokens,\n commits30d: row.commits_30d,\n avgCommitsPerDay: parseFloat(String(row.avg_commits_per_day)),\n activeDays: row.active_days,\n peakCommits: row.peak_commits,\n peakDate: row.peak_date,\n squadsData: row.squads_data || [],\n authorsData: row.authors_data || [],\n reposData: row.repos_data || [],\n }));\n } catch {\n return [];\n }\n}\n\n/**\n * Close the database connection pool\n */\nexport async function closeDatabase(): Promise<void> {\n if (pool) {\n await pool.end();\n pool = null;\n }\n}\n","import { execSync } from 'child_process';\nimport {\n colors,\n bold,\n RESET,\n gradient,\n box,\n padEnd,\n truncate,\n icons,\n writeLine,\n} from '../lib/terminal.js';\n\ninterface Issue {\n number: number;\n title: string;\n state: string;\n labels: string[];\n createdAt: string;\n}\n\ninterface RepoIssues {\n repo: string;\n issues: Issue[];\n error?: string;\n}\n\ninterface IssuesOptions {\n org?: string;\n repos?: string;\n}\n\nconst DEFAULT_ORG = 'agents-squads';\nconst DEFAULT_REPOS = ['hq', 'agents-squads-web', 'squads-cli'];\n\nexport async function issuesCommand(options: IssuesOptions = {}): Promise<void> {\n const org = options.org || DEFAULT_ORG;\n const repos = options.repos ? options.repos.split(',') : DEFAULT_REPOS;\n\n writeLine();\n writeLine(` ${gradient('squads')} ${colors.dim}issues${RESET}`);\n writeLine();\n\n // Check if gh is available\n try {\n execSync('gh --version', { stdio: 'pipe' });\n } catch {\n writeLine(` ${colors.red}GitHub CLI (gh) not found${RESET}`);\n writeLine(` ${colors.dim}Install: brew install gh${RESET}`);\n writeLine();\n return;\n }\n\n // Fetch issues for each repo\n const repoData: RepoIssues[] = [];\n let totalOpen = 0;\n\n for (const repo of repos) {\n try {\n const result = execSync(\n `gh issue list -R ${org}/${repo} --state open --json number,title,state,labels,createdAt --limit 50`,\n { stdio: 'pipe', encoding: 'utf-8' }\n );\n const issues: Issue[] = JSON.parse(result);\n repoData.push({ repo, issues });\n totalOpen += issues.length;\n } catch (e: any) {\n repoData.push({ repo, issues: [], error: 'not found or no access' });\n }\n }\n\n // Stats row\n const reposWithIssues = repoData.filter(r => r.issues.length > 0).length;\n writeLine(` ${colors.cyan}${totalOpen}${RESET} open issues ${colors.dim}│${RESET} ${reposWithIssues}/${repos.length} repos`);\n writeLine();\n\n // Table\n const w = { repo: 20, open: 6, latest: 40 };\n const tableWidth = w.repo + w.open + w.latest + 4;\n\n writeLine(` ${colors.purple}${box.topLeft}${colors.dim}${box.horizontal.repeat(tableWidth)}${colors.purple}${box.topRight}${RESET}`);\n\n const header = ` ${colors.purple}${box.vertical}${RESET} ` +\n `${bold}${padEnd('REPO', w.repo)}${RESET}` +\n `${bold}${padEnd('OPEN', w.open)}${RESET}` +\n `${bold}LATEST${RESET}` +\n ` ${colors.purple}${box.vertical}${RESET}`;\n writeLine(header);\n\n writeLine(` ${colors.purple}${box.teeRight}${colors.dim}${box.horizontal.repeat(tableWidth)}${colors.purple}${box.teeLeft}${RESET}`);\n\n for (const { repo, issues, error } of repoData) {\n const count = issues.length;\n const countColor = count > 5 ? colors.red : count > 0 ? colors.yellow : colors.green;\n\n let latest = `${colors.dim}—${RESET}`;\n if (error) {\n latest = `${colors.dim}${error}${RESET}`;\n } else if (issues.length > 0) {\n latest = truncate(issues[0].title, w.latest - 2);\n }\n\n const row = ` ${colors.purple}${box.vertical}${RESET} ` +\n `${colors.cyan}${padEnd(repo, w.repo)}${RESET}` +\n `${countColor}${padEnd(String(count), w.open)}${RESET}` +\n `${padEnd(latest, w.latest + 10)}` + // extra for color codes\n `${colors.purple}${box.vertical}${RESET}`;\n\n writeLine(row);\n }\n\n writeLine(` ${colors.purple}${box.bottomLeft}${colors.dim}${box.horizontal.repeat(tableWidth)}${colors.purple}${box.bottomRight}${RESET}`);\n writeLine();\n\n // Show recent issues\n const allIssues = repoData\n .flatMap(r => r.issues.map(i => ({ ...i, repo: r.repo })))\n .sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())\n .slice(0, 6);\n\n if (allIssues.length > 0) {\n writeLine(` ${bold}Recent${RESET}`);\n writeLine();\n\n for (const issue of allIssues) {\n const labelStr = issue.labels.length > 0\n ? `${colors.dim}[${issue.labels.map((l: any) => l.name || l).join(', ')}]${RESET}`\n : '';\n\n writeLine(` ${icons.empty} ${colors.dim}#${issue.number}${RESET} ${truncate(issue.title, 50)} ${labelStr}`);\n writeLine(` ${colors.dim}└ ${issue.repo}${RESET}`);\n }\n writeLine();\n }\n\n // Commands\n writeLine(` ${colors.dim}$${RESET} gh issue list -R ${colors.cyan}${org}/<repo>${RESET} ${colors.dim}View repo issues${RESET}`);\n writeLine(` ${colors.dim}$${RESET} gh issue create -R ${colors.cyan}${org}/<repo>${RESET} ${colors.dim}Create issue${RESET}`);\n writeLine();\n}\n","import { execSync, spawn } from 'child_process';\nimport ora from 'ora';\nimport {\n colors,\n bold,\n RESET,\n gradient,\n box,\n padEnd,\n truncate,\n icons,\n writeLine,\n} from '../lib/terminal.js';\n\ninterface Issue {\n number: number;\n title: string;\n labels: Array<{ name: string }>;\n body?: string;\n}\n\ninterface SolveOptions {\n repo?: string;\n issue?: number;\n dryRun?: boolean;\n execute?: boolean;\n}\n\nconst DEFAULT_ORG = 'agents-squads';\nconst DEFAULT_REPOS = ['hq', 'agents-squads-web', 'squads-cli', 'agents-squads'];\n\nexport async function solveIssuesCommand(options: SolveOptions = {}): Promise<void> {\n const repos = options.repo ? [options.repo] : DEFAULT_REPOS;\n\n writeLine();\n writeLine(` ${gradient('squads')} ${colors.dim}solve-issues${RESET}`);\n writeLine();\n\n // Check if gh is available\n try {\n execSync('gh --version', { stdio: 'pipe' });\n } catch {\n writeLine(` ${colors.red}GitHub CLI (gh) not found${RESET}`);\n writeLine(` ${colors.dim}Install: brew install gh${RESET}`);\n return;\n }\n\n // Collect issues to solve\n const issuesToSolve: Array<Issue & { repo: string }> = [];\n\n if (options.issue) {\n // Specific issue\n const repo = options.repo || 'hq';\n try {\n const result = execSync(\n `gh issue view ${options.issue} -R ${DEFAULT_ORG}/${repo} --json number,title,labels,body`,\n { stdio: 'pipe', encoding: 'utf-8' }\n );\n const issue = JSON.parse(result);\n issuesToSolve.push({ ...issue, repo });\n } catch {\n writeLine(` ${colors.red}Issue #${options.issue} not found in ${repo}${RESET}`);\n return;\n }\n } else {\n // All ready-to-fix issues\n for (const repo of repos) {\n try {\n const result = execSync(\n `gh issue list -R ${DEFAULT_ORG}/${repo} --label \"ready-to-fix\" --state open --json number,title,labels --limit 20`,\n { stdio: 'pipe', encoding: 'utf-8' }\n );\n const issues: Issue[] = JSON.parse(result);\n for (const issue of issues) {\n issuesToSolve.push({ ...issue, repo });\n }\n } catch {\n // Repo might not exist or no access\n }\n }\n }\n\n if (issuesToSolve.length === 0) {\n writeLine(` ${colors.yellow}No issues with 'ready-to-fix' label found${RESET}`);\n writeLine();\n writeLine(` ${colors.dim}Label an issue to make it solvable:${RESET}`);\n writeLine(` ${colors.dim}$${RESET} gh issue edit ${colors.cyan}<number>${RESET} -R ${colors.cyan}${DEFAULT_ORG}/<repo>${RESET} --add-label ready-to-fix`);\n writeLine();\n return;\n }\n\n // Show issues to solve\n writeLine(` ${colors.cyan}${issuesToSolve.length}${RESET} issue${issuesToSolve.length > 1 ? 's' : ''} to solve`);\n writeLine();\n\n for (const issue of issuesToSolve) {\n const labels = issue.labels.map(l => l.name).join(', ');\n writeLine(` ${icons.empty} ${colors.dim}#${issue.number}${RESET} ${truncate(issue.title, 50)}`);\n writeLine(` ${colors.dim}└ ${issue.repo} [${labels}]${RESET}`);\n }\n writeLine();\n\n if (options.dryRun) {\n writeLine(` ${colors.yellow}[DRY RUN] Would solve ${issuesToSolve.length} issues${RESET}`);\n return;\n }\n\n // Solve issues\n if (options.execute) {\n await solveWithClaude(issuesToSolve);\n } else {\n showSolveInstructions(issuesToSolve);\n }\n}\n\nfunction showSolveInstructions(issues: Array<Issue & { repo: string }>): void {\n writeLine(` ${bold}To solve these issues:${RESET}`);\n writeLine();\n writeLine(` ${colors.dim}Option 1: In Claude Code session${RESET}`);\n writeLine(` ${colors.dim}$${RESET} /solve-issue ${colors.cyan}${issues[0].repo}${RESET}`);\n writeLine();\n writeLine(` ${colors.dim}Option 2: Execute with Claude CLI${RESET}`);\n writeLine(` ${colors.dim}$${RESET} squads solve-issues --execute`);\n writeLine();\n writeLine(` ${colors.dim}Option 3: Solve specific issue${RESET}`);\n writeLine(` ${colors.dim}$${RESET} squads solve-issues --repo ${colors.cyan}${issues[0].repo}${RESET} --issue ${colors.cyan}${issues[0].number}${RESET} --execute`);\n writeLine();\n}\n\nasync function solveWithClaude(issues: Array<Issue & { repo: string }>): Promise<void> {\n const spinner = ora('Starting issue solver...').start();\n\n // Check if claude is available\n try {\n execSync('which claude', { stdio: 'pipe' });\n } catch {\n spinner.fail('Claude CLI not found');\n writeLine(` ${colors.dim}Install: npm install -g @anthropic-ai/claude-code${RESET}`);\n return;\n }\n\n for (const issue of issues) {\n spinner.text = `Solving #${issue.number}: ${truncate(issue.title, 40)}`;\n\n const prompt = buildSolvePrompt(issue);\n\n try {\n const result = await executeClaudePrompt(prompt);\n spinner.succeed(`Solved #${issue.number}`);\n\n // Extract PR URL if present\n const prMatch = result.match(/https:\\/\\/github\\.com\\/[^\\s]+\\/pull\\/\\d+/);\n if (prMatch) {\n writeLine(` ${colors.green}PR: ${prMatch[0]}${RESET}`);\n }\n } catch (error) {\n spinner.fail(`Failed #${issue.number}: ${error}`);\n }\n }\n\n writeLine();\n writeLine(` ${colors.dim}View results:${RESET}`);\n writeLine(` ${colors.dim}$${RESET} gh pr list -R ${colors.cyan}${DEFAULT_ORG}/<repo>${RESET}`);\n writeLine();\n}\n\nfunction buildSolvePrompt(issue: Issue & { repo: string }): string {\n return `Solve GitHub issue #${issue.number} in ${DEFAULT_ORG}/${issue.repo}.\n\nIssue: ${issue.title}\n\n## CRITICAL: Work Decisively (No Verification Loops!)\n\nRead each file ONCE, edit ONCE, commit IMMEDIATELY.\nVerify with git diff, NOT by re-reading files.\nIf reading the same file twice, STOP and move forward.\n\n## Instructions\n\n1. Read the issue: gh issue view ${issue.number} --repo ${DEFAULT_ORG}/${issue.repo}\n\n2. Set up worktree:\n git fetch origin main\n git worktree add ../.worktrees/issue-${issue.number} -b solve/issue-${issue.number} origin/main\n cd ../.worktrees/issue-${issue.number}\n\n3. Find and fix the problem (minimal changes)\n\n4. Commit: git add -A && git commit -m \"fix: ...\"\n\n5. Push and create PR:\n git push -u origin solve/issue-${issue.number}\n gh pr create --title \"fix: ...\" --body \"Fixes #${issue.number}\" --repo ${DEFAULT_ORG}/${issue.repo}\n\n6. Clean up: git worktree remove ../.worktrees/issue-${issue.number} --force\n\nReturn the PR URL when done.`;\n}\n\nfunction executeClaudePrompt(prompt: string): Promise<string> {\n return new Promise((resolve, reject) => {\n const claude = spawn('claude', ['--print', prompt], {\n stdio: ['pipe', 'pipe', 'pipe'],\n });\n\n let output = '';\n let error = '';\n\n claude.stdout?.on('data', (data) => {\n output += data.toString();\n });\n\n claude.stderr?.on('data', (data) => {\n error += data.toString();\n });\n\n claude.on('close', (code) => {\n if (code === 0) {\n resolve(output);\n } else {\n reject(new Error(error || `Exited with code ${code}`));\n }\n });\n\n claude.on('error', reject);\n\n // 10 minute timeout\n setTimeout(() => {\n claude.kill();\n reject(new Error('Timeout after 10 minutes'));\n }, 10 * 60 * 1000);\n });\n}\n","import { execSync, spawn } from 'child_process';\nimport { existsSync, readdirSync } from 'fs';\nimport { join } from 'path';\nimport ora from 'ora';\nimport {\n colors,\n bold,\n RESET,\n gradient,\n truncate,\n icons,\n writeLine,\n} from '../lib/terminal.js';\nimport { findSquadsDir } from '../lib/squad-parser.js';\n\ninterface OpenOptions {\n squad?: string;\n agent?: string;\n dryRun?: boolean;\n execute?: boolean;\n}\n\ninterface EvalAgent {\n name: string;\n squad: string;\n path: string;\n}\n\n// Agents that find issues (evaluators, critics, auditors)\nconst ISSUE_FINDER_PATTERNS = [\n '*-eval.md',\n '*-critic.md',\n '*-auditor.md',\n 'site-tester.md',\n];\n\nexport async function openIssuesCommand(options: OpenOptions = {}): Promise<void> {\n writeLine();\n writeLine(` ${gradient('squads')} ${colors.dim}open-issues${RESET}`);\n writeLine();\n\n const squadsDir = findSquadsDir();\n if (!squadsDir) {\n writeLine(` ${colors.red}No .agents/squads directory found${RESET}`);\n return;\n }\n\n // Find evaluator/critic agents\n const evalAgents = findEvalAgents(squadsDir, options.squad);\n\n if (evalAgents.length === 0) {\n writeLine(` ${colors.yellow}No evaluator agents found${RESET}`);\n writeLine(` ${colors.dim}Evaluators match: *-eval.md, *-critic.md, *-auditor.md${RESET}`);\n return;\n }\n\n // Filter by specific agent if requested\n const agents = options.agent\n ? evalAgents.filter(a => a.name === options.agent || a.name === `${options.agent}.md`)\n : evalAgents;\n\n if (agents.length === 0) {\n writeLine(` ${colors.red}Agent '${options.agent}' not found${RESET}`);\n writeLine(` ${colors.dim}Available: ${evalAgents.map(a => a.name).join(', ')}${RESET}`);\n return;\n }\n\n // Group by squad\n const bySquad = agents.reduce((acc, agent) => {\n if (!acc[agent.squad]) acc[agent.squad] = [];\n acc[agent.squad].push(agent);\n return acc;\n }, {} as Record<string, EvalAgent[]>);\n\n writeLine(` ${colors.cyan}${agents.length}${RESET} evaluator${agents.length > 1 ? 's' : ''} ready`);\n writeLine();\n\n for (const [squad, squadAgents] of Object.entries(bySquad)) {\n writeLine(` ${bold}${squad}${RESET}`);\n for (const agent of squadAgents) {\n writeLine(` ${icons.empty} ${colors.cyan}${agent.name.replace('.md', '')}${RESET}`);\n }\n }\n writeLine();\n\n if (options.dryRun) {\n writeLine(` ${colors.yellow}[DRY RUN] Would run ${agents.length} evaluators${RESET}`);\n return;\n }\n\n if (options.execute) {\n await runEvaluators(agents);\n } else {\n showRunInstructions(agents);\n }\n}\n\nfunction findEvalAgents(squadsDir: string, filterSquad?: string): EvalAgent[] {\n const agents: EvalAgent[] = [];\n const squads = readdirSync(squadsDir, { withFileTypes: true })\n .filter(d => d.isDirectory())\n .filter(d => !filterSquad || d.name === filterSquad)\n .map(d => d.name);\n\n for (const squad of squads) {\n const squadPath = join(squadsDir, squad);\n const files = readdirSync(squadPath).filter(f => f.endsWith('.md'));\n\n for (const file of files) {\n // Check if matches evaluator patterns\n const isEval = ISSUE_FINDER_PATTERNS.some(pattern => {\n const regex = new RegExp('^' + pattern.replace('*', '.*') + '$');\n return regex.test(file);\n });\n\n if (isEval) {\n agents.push({\n name: file,\n squad,\n path: join(squadPath, file),\n });\n }\n }\n }\n\n return agents;\n}\n\nfunction showRunInstructions(agents: EvalAgent[]): void {\n writeLine(` ${bold}To run evaluators:${RESET}`);\n writeLine();\n writeLine(` ${colors.dim}Option 1: In Claude Code session${RESET}`);\n writeLine(` ${colors.dim}$${RESET} /website-eval`);\n writeLine();\n writeLine(` ${colors.dim}Option 2: Execute with Claude CLI${RESET}`);\n writeLine(` ${colors.dim}$${RESET} squads open-issues --execute`);\n writeLine();\n writeLine(` ${colors.dim}Option 3: Run specific evaluator${RESET}`);\n writeLine(` ${colors.dim}$${RESET} squads open-issues --squad ${colors.cyan}${agents[0].squad}${RESET} --agent ${colors.cyan}${agents[0].name.replace('.md', '')}${RESET} --execute`);\n writeLine();\n writeLine(` ${colors.dim}Option 4: Via squads run${RESET}`);\n writeLine(` ${colors.dim}$${RESET} squads run ${colors.cyan}${agents[0].squad}/${agents[0].name.replace('.md', '')}${RESET} --execute`);\n writeLine();\n}\n\nasync function runEvaluators(agents: EvalAgent[]): Promise<void> {\n const spinner = ora('Starting evaluators...').start();\n\n // Check if claude is available\n try {\n execSync('which claude', { stdio: 'pipe' });\n } catch {\n spinner.fail('Claude CLI not found');\n writeLine(` ${colors.dim}Install: npm install -g @anthropic-ai/claude-code${RESET}`);\n return;\n }\n\n let issuesCreated = 0;\n\n for (const agent of agents) {\n spinner.text = `Running ${agent.squad}/${agent.name.replace('.md', '')}...`;\n\n const prompt = buildEvalPrompt(agent);\n\n try {\n const result = await executeClaudePrompt(prompt);\n spinner.succeed(`${agent.name.replace('.md', '')}`);\n\n // Count issues created\n const issueMatches = result.match(/Created issue #\\d+/g) || [];\n issuesCreated += issueMatches.length;\n\n if (issueMatches.length > 0) {\n writeLine(` ${colors.green}Created ${issueMatches.length} issue(s)${RESET}`);\n } else {\n writeLine(` ${colors.dim}No issues found${RESET}`);\n }\n } catch (error) {\n spinner.fail(`${agent.name.replace('.md', '')}: ${error}`);\n }\n }\n\n writeLine();\n writeLine(` ${bold}Summary${RESET}`);\n writeLine(` ${colors.cyan}${issuesCreated}${RESET} new issues created`);\n writeLine();\n writeLine(` ${colors.dim}View issues:${RESET}`);\n writeLine(` ${colors.dim}$${RESET} squads issues`);\n writeLine();\n writeLine(` ${colors.dim}Solve them:${RESET}`);\n writeLine(` ${colors.dim}$${RESET} squads solve-issues`);\n writeLine();\n}\n\nfunction buildEvalPrompt(agent: EvalAgent): string {\n return `Execute the ${agent.name.replace('.md', '')} evaluator from squad ${agent.squad}.\n\nRead the agent definition at ${agent.path} and follow its instructions exactly.\n\n## CRITICAL: Work Decisively\n\n- Evaluate the target (website, code, etc.)\n- For each finding, create a GitHub issue\n- Use: gh issue create --repo agents-squads/{repo} --title \"...\" --body \"...\" --label \"type:...,priority:P1/P2/P3,squad:${agent.squad}\"\n- Report how many issues were created\n\nDo NOT get stuck re-reading files. Evaluate, report findings, create issues, done.`;\n}\n\nfunction executeClaudePrompt(prompt: string): Promise<string> {\n return new Promise((resolve, reject) => {\n const claude = spawn('claude', ['--print', prompt], {\n stdio: ['pipe', 'pipe', 'pipe'],\n });\n\n let output = '';\n let error = '';\n\n claude.stdout?.on('data', (data) => {\n output += data.toString();\n });\n\n claude.stderr?.on('data', (data) => {\n error += data.toString();\n });\n\n claude.on('close', (code) => {\n if (code === 0) {\n resolve(output);\n } else {\n reject(new Error(error || `Exited with code ${code}`));\n }\n });\n\n claude.on('error', reject);\n\n // 5 minute timeout per evaluator\n setTimeout(() => {\n claude.kill();\n reject(new Error('Timeout after 5 minutes'));\n }, 5 * 60 * 1000);\n });\n}\n","import chalk from 'chalk';\nimport ora from 'ora';\nimport open from 'open';\nimport {\n isPersonalEmail,\n getEmailDomain,\n saveSession,\n loadSession,\n clearSession,\n startAuthCallbackServer,\n AuthSession\n} from '../lib/auth.js';\nimport { track } from '../lib/telemetry.js';\n\nconst AUTH_URL = process.env.SQUADS_AUTH_URL || 'https://app.agents-squads.com/auth';\nconst CALLBACK_PORT = 54321;\n\nexport async function loginCommand(): Promise<void> {\n const existingSession = loadSession();\n\n if (existingSession && existingSession.status === 'active') {\n console.log(chalk.green(`✓ Already logged in as ${existingSession.email}`));\n console.log(chalk.dim(` Domain: ${existingSession.domain}`));\n console.log(chalk.dim(` Run 'squads logout' to sign out.`));\n return;\n }\n\n console.log(`\n${chalk.bold.magenta('Squads CLI Login')}\n${chalk.dim('─'.repeat(40))}\n\nOpening browser to authenticate...\n`);\n\n const spinner = ora('Waiting for authentication...').start();\n\n try {\n // Start local callback server\n const callbackPromise = startAuthCallbackServer(CALLBACK_PORT);\n\n // Open browser to auth page\n const authUrl = `${AUTH_URL}?callback=http://localhost:${CALLBACK_PORT}/callback`;\n await open(authUrl);\n\n // Wait for callback\n const { email, token } = await callbackPromise;\n\n // Check if personal email\n if (isPersonalEmail(email)) {\n spinner.fail('Personal emails not supported');\n console.log(`\n${chalk.yellow('⚠ Squads CLI is for Pro & Enterprise teams only.')}\n\nPersonal email domains (Gmail, Yahoo, etc.) are not supported.\n\n${chalk.dim('Want to stay updated?')}\n → Get our free research report: ${chalk.cyan('https://agents-squads.com/research')}\n → Follow us: ${chalk.cyan('https://x.com/agents_squads')}\n`);\n\n await track('cli.login.personal_email', { domain: getEmailDomain(email) });\n return;\n }\n\n // Save session\n const session: AuthSession = {\n email,\n domain: getEmailDomain(email),\n status: 'pending', // Will be 'active' after sales contact\n createdAt: new Date().toISOString(),\n accessToken: token,\n };\n\n saveSession(session);\n spinner.succeed(`Logged in as ${chalk.cyan(email)}`);\n\n await track('cli.login.success', { domain: session.domain });\n\n console.log(`\n${chalk.green('✓ Thanks for signing up!')}\n\n${chalk.bold('What happens next:')}\n 1. Our team will reach out within 24 hours\n 2. We'll discuss your AI agent needs\n 3. You'll get access to Pro features\n\n${chalk.dim('In the meantime:')}\n → Explore squads: ${chalk.cyan('squads status')}\n → Set goals: ${chalk.cyan('squads goal set <squad> \"<goal>\"')}\n → Read our research: ${chalk.cyan('https://agents-squads.com/research')}\n\n${chalk.dim('Questions? Email us at')} ${chalk.cyan('hello@agents-squads.com')}\n`);\n\n } catch (error) {\n spinner.fail('Login failed');\n console.error(chalk.red(error instanceof Error ? error.message : 'Unknown error'));\n }\n}\n\nexport async function logoutCommand(): Promise<void> {\n const session = loadSession();\n\n if (!session) {\n console.log(chalk.yellow('Not logged in.'));\n return;\n }\n\n clearSession();\n console.log(chalk.green(`✓ Logged out from ${session.email}`));\n await track('cli.logout');\n}\n\nexport async function whoamiCommand(): Promise<void> {\n const session = loadSession();\n\n if (!session) {\n console.log(chalk.yellow('Not logged in.'));\n console.log(chalk.dim('Run: squads login'));\n return;\n }\n\n console.log(`\n${chalk.bold('Current Session')}\n${chalk.dim('─'.repeat(30))}\nEmail: ${chalk.cyan(session.email)}\nDomain: ${session.domain}\nStatus: ${session.status === 'active' ? chalk.green('Active') : chalk.yellow('Pending')}\nSince: ${new Date(session.createdAt).toLocaleDateString()}\n`);\n}\n","import { createClient } from '@supabase/supabase-js';\nimport { existsSync, readFileSync, writeFileSync, mkdirSync } from 'fs';\nimport { join } from 'path';\nimport { homedir } from 'os';\nimport open from 'open';\nimport http from 'http';\n\n// Personal email domains to reject\nconst PERSONAL_DOMAINS = [\n 'gmail.com', 'googlemail.com',\n 'yahoo.com', 'yahoo.co.uk', 'yahoo.fr',\n 'hotmail.com', 'outlook.com', 'live.com', 'msn.com',\n 'icloud.com', 'me.com', 'mac.com',\n 'aol.com',\n 'protonmail.com', 'proton.me',\n 'zoho.com',\n 'mail.com',\n 'yandex.com', 'yandex.ru',\n 'gmx.com', 'gmx.de',\n 'fastmail.com',\n 'tutanota.com',\n 'hey.com',\n];\n\nconst AUTH_DIR = join(homedir(), '.squads-cli');\nconst AUTH_PATH = join(AUTH_DIR, 'auth.json');\n\nexport interface AuthSession {\n email: string;\n domain: string;\n status: 'pending' | 'contacted' | 'active';\n createdAt: string;\n accessToken?: string;\n}\n\nexport function isPersonalEmail(email: string): boolean {\n const domain = email.split('@')[1]?.toLowerCase();\n return PERSONAL_DOMAINS.includes(domain);\n}\n\nexport function getEmailDomain(email: string): string {\n return email.split('@')[1]?.toLowerCase() || '';\n}\n\nexport function saveSession(session: AuthSession): void {\n if (!existsSync(AUTH_DIR)) {\n mkdirSync(AUTH_DIR, { recursive: true });\n }\n writeFileSync(AUTH_PATH, JSON.stringify(session, null, 2));\n}\n\nexport function loadSession(): AuthSession | null {\n if (!existsSync(AUTH_PATH)) return null;\n try {\n return JSON.parse(readFileSync(AUTH_PATH, 'utf-8'));\n } catch {\n return null;\n }\n}\n\nexport function clearSession(): void {\n if (existsSync(AUTH_PATH)) {\n writeFileSync(AUTH_PATH, '');\n }\n}\n\nexport function isLoggedIn(): boolean {\n const session = loadSession();\n return session !== null && session.status === 'active';\n}\n\n// Create Supabase client (for edge function use)\nexport function createSupabaseClient(url: string, anonKey: string) {\n return createClient(url, anonKey);\n}\n\n// Local callback server for OAuth flow\nexport function startAuthCallbackServer(port: number = 54321): Promise<{ email: string; token: string }> {\n return new Promise((resolve, reject) => {\n const server = http.createServer((req, res) => {\n const url = new URL(req.url || '', `http://localhost:${port}`);\n\n if (url.pathname === '/callback') {\n const email = url.searchParams.get('email');\n const token = url.searchParams.get('token');\n const error = url.searchParams.get('error');\n\n if (error) {\n res.writeHead(200, { 'Content-Type': 'text/html' });\n res.end(`\n <html>\n <body style=\"font-family: system-ui; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0;\">\n <div style=\"text-align: center;\">\n <h1 style=\"color: #ef4444;\">❌ ${error}</h1>\n <p>You can close this window.</p>\n </div>\n </body>\n </html>\n `);\n server.close();\n reject(new Error(error));\n return;\n }\n\n if (email && token) {\n res.writeHead(200, { 'Content-Type': 'text/html' });\n res.end(`\n <html>\n <body style=\"font-family: system-ui; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0;\">\n <div style=\"text-align: center;\">\n <h1 style=\"color: #10b981;\">✓ Logged in!</h1>\n <p>Welcome, ${email}</p>\n <p style=\"color: #6b7280;\">You can close this window and return to your terminal.</p>\n </div>\n </body>\n </html>\n `);\n server.close();\n resolve({ email, token });\n } else {\n res.writeHead(400, { 'Content-Type': 'text/plain' });\n res.end('Missing email or token');\n }\n } else {\n res.writeHead(404);\n res.end();\n }\n });\n\n server.listen(port, () => {\n // Server started\n });\n\n // Timeout after 5 minutes\n setTimeout(() => {\n server.close();\n reject(new Error('Login timed out'));\n }, 5 * 60 * 1000);\n });\n}\n","import { execSync } from 'child_process';\nimport { existsSync, readFileSync, writeFileSync, mkdirSync } from 'fs';\nimport { join } from 'path';\nimport { findSquadsDir, listSquads, loadSquad } from '../lib/squad-parser.js';\nimport { findMemoryDir } from '../lib/memory.js';\nimport {\n colors,\n bold,\n RESET,\n gradient,\n box,\n padEnd,\n truncate,\n icons,\n writeLine,\n} from '../lib/terminal.js';\n\ninterface TaskEntry {\n id: string;\n squad: string;\n description: string;\n status: 'active' | 'completed' | 'failed';\n startedAt: string;\n completedAt?: string;\n commits?: string[];\n}\n\ninterface TasksFile {\n tasks: TaskEntry[];\n lastUpdated: string;\n}\n\nfunction getTasksFilePath(): string {\n const memoryDir = findMemoryDir();\n if (!memoryDir) {\n const cwd = process.cwd();\n const agentsDir = join(cwd, '.agents');\n if (!existsSync(agentsDir)) {\n mkdirSync(agentsDir, { recursive: true });\n }\n return join(agentsDir, 'tasks.json');\n }\n return join(memoryDir, '..', 'tasks.json');\n}\n\nfunction loadTasks(): TasksFile {\n const tasksPath = getTasksFilePath();\n if (existsSync(tasksPath)) {\n try {\n return JSON.parse(readFileSync(tasksPath, 'utf-8'));\n } catch {\n return { tasks: [], lastUpdated: new Date().toISOString() };\n }\n }\n return { tasks: [], lastUpdated: new Date().toISOString() };\n}\n\nfunction saveTasks(data: TasksFile): void {\n const tasksPath = getTasksFilePath();\n data.lastUpdated = new Date().toISOString();\n writeFileSync(tasksPath, JSON.stringify(data, null, 2));\n}\n\n// Get recent commits to infer activity\nfunction getRecentActivity(): { squad: string; message: string; hash: string; date: string }[] {\n const activity: { squad: string; message: string; hash: string; date: string }[] = [];\n\n const squadKeywords: Record<string, string[]> = {\n website: ['website', 'web', 'homepage', 'astro', 'page'],\n product: ['cli', 'squads-cli', 'command'],\n research: ['research', 'report', 'analysis'],\n engineering: ['infra', 'engineering', 'build'],\n intelligence: ['intel', 'monitor', 'competitor'],\n customer: ['lead', 'customer', 'outreach'],\n finance: ['cost', 'finance', 'budget'],\n company: ['company', 'strategy', 'mission'],\n marketing: ['marketing', 'content', 'social'],\n };\n\n try {\n const logOutput = execSync(\n 'git log --since=\"24 hours ago\" --format=\"%h|%aI|%s\" 2>/dev/null',\n { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] }\n ).trim();\n\n if (!logOutput) return activity;\n\n for (const line of logOutput.split('\\n')) {\n const [hash, date, ...msgParts] = line.split('|');\n const message = msgParts.join('|');\n if (!hash || !message) continue;\n\n // Detect squad from commit message\n const msgLower = message.toLowerCase();\n let detectedSquad = 'unknown';\n\n for (const [squad, keywords] of Object.entries(squadKeywords)) {\n if (keywords.some(k => msgLower.includes(k))) {\n detectedSquad = squad;\n break;\n }\n }\n\n activity.push({\n squad: detectedSquad,\n message,\n hash,\n date: date.split('T')[0],\n });\n }\n } catch {\n // Not in git repo\n }\n\n return activity;\n}\n\nexport async function progressCommand(options: { verbose?: boolean } = {}): Promise<void> {\n writeLine();\n writeLine(` ${gradient('squads')} ${colors.dim}progress${RESET}`);\n writeLine();\n\n const tasksData = loadTasks();\n const recentActivity = getRecentActivity();\n\n // Active tasks\n const activeTasks = tasksData.tasks.filter(t => t.status === 'active');\n const completedToday = tasksData.tasks.filter(t =>\n t.status === 'completed' &&\n t.completedAt?.startsWith(new Date().toISOString().split('T')[0])\n );\n\n // Stats row\n const stats = [\n `${colors.cyan}${activeTasks.length}${RESET} active`,\n `${colors.green}${completedToday.length}${RESET} done today`,\n `${colors.purple}${recentActivity.length}${RESET} commits (24h)`,\n ].join(` ${colors.dim}│${RESET} `);\n writeLine(` ${stats}`);\n writeLine();\n\n // Active tasks section\n if (activeTasks.length > 0) {\n writeLine(` ${bold}Active Tasks${RESET}`);\n writeLine();\n\n for (const task of activeTasks) {\n const elapsed = getElapsedTime(task.startedAt);\n writeLine(` ${icons.progress} ${colors.cyan}${task.squad}${RESET} ${truncate(task.description, 45)}`);\n writeLine(` ${colors.dim}started ${elapsed} ago${RESET}`);\n }\n writeLine();\n } else {\n writeLine(` ${colors.dim}No active tasks${RESET}`);\n writeLine();\n }\n\n // Recent activity from git\n if (recentActivity.length > 0) {\n writeLine(` ${bold}Recent Activity${RESET} ${colors.dim}(last 24h)${RESET}`);\n writeLine();\n\n const w = { squad: 12, message: 50 };\n const tableWidth = w.squad + w.message + 4;\n\n writeLine(` ${colors.purple}${box.topLeft}${colors.dim}${box.horizontal.repeat(tableWidth)}${colors.purple}${box.topRight}${RESET}`);\n writeLine(` ${colors.purple}${box.vertical}${RESET} ${bold}${padEnd('SQUAD', w.squad)}${RESET}${bold}COMMIT${RESET}${' '.repeat(w.message - 6)} ${colors.purple}${box.vertical}${RESET}`);\n writeLine(` ${colors.purple}${box.teeRight}${colors.dim}${box.horizontal.repeat(tableWidth)}${colors.purple}${box.teeLeft}${RESET}`);\n\n const maxRows = options.verbose ? 15 : 8;\n for (const act of recentActivity.slice(0, maxRows)) {\n const squadColor = act.squad === 'unknown' ? colors.dim : colors.cyan;\n const row = ` ${colors.purple}${box.vertical}${RESET} ` +\n `${squadColor}${padEnd(act.squad, w.squad)}${RESET}` +\n `${truncate(act.message, w.message - 2)}` +\n ` ${colors.purple}${box.vertical}${RESET}`;\n writeLine(row);\n }\n\n writeLine(` ${colors.purple}${box.bottomLeft}${colors.dim}${box.horizontal.repeat(tableWidth)}${colors.purple}${box.bottomRight}${RESET}`);\n\n if (recentActivity.length > maxRows) {\n writeLine(` ${colors.dim}+${recentActivity.length - maxRows} more commits${RESET}`);\n }\n writeLine();\n }\n\n // Completed today\n if (completedToday.length > 0) {\n writeLine(` ${bold}Completed Today${RESET}`);\n writeLine();\n for (const task of completedToday.slice(0, 5)) {\n writeLine(` ${icons.success} ${colors.cyan}${task.squad}${RESET} ${truncate(task.description, 50)}`);\n }\n if (completedToday.length > 5) {\n writeLine(` ${colors.dim}+${completedToday.length - 5} more${RESET}`);\n }\n writeLine();\n }\n\n // Commands\n writeLine(` ${colors.dim}$${RESET} squads results ${colors.dim}KPI goals vs actuals${RESET}`);\n writeLine(` ${colors.dim}$${RESET} squads dash ${colors.dim}Full dashboard${RESET}`);\n writeLine();\n}\n\n// Register a new task (called by agents)\nexport async function progressStartCommand(\n squad: string,\n description: string\n): Promise<void> {\n const tasksData = loadTasks();\n const id = Math.random().toString(36).substring(2, 9);\n\n tasksData.tasks.push({\n id,\n squad,\n description,\n status: 'active',\n startedAt: new Date().toISOString(),\n });\n\n saveTasks(tasksData);\n writeLine(` ${icons.active} Task ${colors.cyan}${id}${RESET} started for ${colors.purple}${squad}${RESET}`);\n}\n\n// Complete a task\nexport async function progressCompleteCommand(\n taskId: string,\n options: { failed?: boolean } = {}\n): Promise<void> {\n const tasksData = loadTasks();\n const task = tasksData.tasks.find(t => t.id === taskId);\n\n if (!task) {\n writeLine(` ${icons.error} Task ${colors.red}${taskId}${RESET} not found`);\n return;\n }\n\n task.status = options.failed ? 'failed' : 'completed';\n task.completedAt = new Date().toISOString();\n\n saveTasks(tasksData);\n\n const icon = options.failed ? icons.error : icons.success;\n const status = options.failed ? 'failed' : 'completed';\n writeLine(` ${icon} Task ${colors.cyan}${taskId}${RESET} ${status}`);\n}\n\nfunction getElapsedTime(startTime: string): string {\n const start = new Date(startTime).getTime();\n const now = Date.now();\n const diffMs = now - start;\n\n const minutes = Math.floor(diffMs / 60000);\n const hours = Math.floor(minutes / 60);\n const days = Math.floor(hours / 24);\n\n if (days > 0) return `${days}d`;\n if (hours > 0) return `${hours}h`;\n if (minutes > 0) return `${minutes}m`;\n return '<1m';\n}\n","import { execSync } from 'child_process';\nimport { existsSync, readFileSync } from 'fs';\nimport { join } from 'path';\nimport { findSquadsDir, listSquads, loadSquad, Goal } from '../lib/squad-parser.js';\nimport {\n colors,\n bold,\n RESET,\n gradient,\n box,\n padEnd,\n truncate,\n icons,\n writeLine,\n progressBar,\n} from '../lib/terminal.js';\n\ninterface SquadResults {\n name: string;\n commits: number;\n prsOpened: number;\n prsMerged: number;\n issuesClosed: number;\n goals: GoalWithMetrics[];\n}\n\ninterface GoalWithMetrics {\n description: string;\n metrics: string[];\n progress?: string;\n completed: boolean;\n actual?: Record<string, number | string>;\n}\n\n// Get git stats for the past week per squad\nfunction getGitStats(days: number = 7): Map<string, { commits: number; files: string[] }> {\n const stats = new Map<string, { commits: number; files: string[] }>();\n\n const squadKeywords: Record<string, string[]> = {\n website: ['agents-squads-web', 'website', 'homepage'],\n product: ['squads-cli', 'cli'],\n research: ['research'],\n engineering: ['engineering', '.agents'],\n intelligence: ['intelligence'],\n customer: ['customer'],\n finance: ['finance'],\n company: ['company'],\n marketing: ['marketing'],\n };\n\n try {\n const logOutput = execSync(\n `git log --since=\"${days} days ago\" --format=\"%s\" --name-only 2>/dev/null`,\n { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] }\n ).trim();\n\n if (!logOutput) return stats;\n\n const entries = logOutput.split('\\n\\n');\n for (const entry of entries) {\n const lines = entry.split('\\n').filter(l => l.trim());\n if (lines.length === 0) continue;\n\n const message = lines[0];\n const files = lines.slice(1);\n const msgLower = message.toLowerCase();\n\n // Detect squad\n let detectedSquad = 'other';\n for (const [squad, keywords] of Object.entries(squadKeywords)) {\n const inMessage = keywords.some(k => msgLower.includes(k));\n const inFiles = files.some(f =>\n keywords.some(k => f.toLowerCase().includes(k))\n );\n if (inMessage || inFiles) {\n detectedSquad = squad;\n break;\n }\n }\n\n if (!stats.has(detectedSquad)) {\n stats.set(detectedSquad, { commits: 0, files: [] });\n }\n const squadStats = stats.get(detectedSquad)!;\n squadStats.commits++;\n squadStats.files.push(...files);\n }\n } catch {\n // Not in git repo\n }\n\n return stats;\n}\n\n// Get GitHub stats via gh CLI\nfunction getGitHubStats(days: number = 7): {\n prsOpened: Map<string, number>;\n prsMerged: Map<string, number>;\n issuesClosed: Map<string, number>;\n} {\n const prsOpened = new Map<string, number>();\n const prsMerged = new Map<string, number>();\n const issuesClosed = new Map<string, number>();\n\n try {\n // Get PRs opened\n const prsOutput = execSync(\n `gh pr list --state all --json title,createdAt,mergedAt --limit 50 2>/dev/null`,\n { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] }\n );\n const prs = JSON.parse(prsOutput || '[]');\n const since = new Date(Date.now() - days * 24 * 60 * 60 * 1000);\n\n for (const pr of prs) {\n const created = new Date(pr.createdAt);\n if (created < since) continue;\n\n const squad = detectSquadFromTitle(pr.title);\n prsOpened.set(squad, (prsOpened.get(squad) || 0) + 1);\n\n if (pr.mergedAt) {\n prsMerged.set(squad, (prsMerged.get(squad) || 0) + 1);\n }\n }\n\n // Get issues closed\n const issuesOutput = execSync(\n `gh issue list --state closed --json title,closedAt --limit 50 2>/dev/null`,\n { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] }\n );\n const issues = JSON.parse(issuesOutput || '[]');\n\n for (const issue of issues) {\n const closed = new Date(issue.closedAt);\n if (closed < since) continue;\n\n const squad = detectSquadFromTitle(issue.title);\n issuesClosed.set(squad, (issuesClosed.get(squad) || 0) + 1);\n }\n } catch {\n // gh not available or not in repo\n }\n\n return { prsOpened, prsMerged, issuesClosed };\n}\n\nfunction detectSquadFromTitle(title: string): string {\n const lower = title.toLowerCase();\n const mapping: Record<string, string[]> = {\n website: ['website', 'web', 'homepage', 'page'],\n product: ['cli', 'squads', 'command'],\n research: ['research', 'report'],\n engineering: ['infra', 'build', 'ci'],\n intelligence: ['intel', 'monitor'],\n customer: ['lead', 'customer'],\n finance: ['cost', 'finance'],\n marketing: ['marketing', 'content'],\n };\n\n for (const [squad, keywords] of Object.entries(mapping)) {\n if (keywords.some(k => lower.includes(k))) {\n return squad;\n }\n }\n return 'other';\n}\n\n// Parse metrics from goal description\nfunction parseMetrics(goal: Goal): string[] {\n const metrics: string[] = [];\n\n // Check for explicit metrics in goal\n if (goal.metrics && goal.metrics.length > 0) {\n return goal.metrics;\n }\n\n // Infer from description\n const desc = goal.description.toLowerCase();\n\n if (desc.includes('revenue')) metrics.push('revenue_usd');\n if (desc.includes('lead')) metrics.push('leads_count');\n if (desc.includes('traffic') || desc.includes('visit')) metrics.push('page_views');\n if (desc.includes('signup') || desc.includes('email')) metrics.push('signups');\n if (desc.includes('cost')) metrics.push('cost_usd');\n if (desc.includes('publish') || desc.includes('launch')) metrics.push('shipped');\n if (desc.includes('demo')) metrics.push('demos_booked');\n\n return metrics.length > 0 ? metrics : ['progress'];\n}\n\nexport async function resultsCommand(options: {\n squad?: string;\n days?: string;\n verbose?: boolean;\n} = {}): Promise<void> {\n const squadsDir = findSquadsDir();\n if (!squadsDir) {\n writeLine(`${colors.red}No .agents/squads directory found${RESET}`);\n return;\n }\n\n const days = parseInt(options.days || '7', 10);\n\n writeLine();\n writeLine(` ${gradient('squads')} ${colors.dim}results${RESET} ${colors.dim}(${days}d)${RESET}`);\n writeLine();\n\n const squadNames = options.squad ? [options.squad] : listSquads(squadsDir);\n const gitStats = getGitStats(days);\n const ghStats = getGitHubStats(days);\n\n const results: SquadResults[] = [];\n\n for (const name of squadNames) {\n const squad = loadSquad(name);\n if (!squad) continue;\n\n const git = gitStats.get(name) || { commits: 0, files: [] };\n const activeGoals = squad.goals.filter(g => !g.completed);\n\n results.push({\n name,\n commits: git.commits,\n prsOpened: ghStats.prsOpened.get(name) || 0,\n prsMerged: ghStats.prsMerged.get(name) || 0,\n issuesClosed: ghStats.issuesClosed.get(name) || 0,\n goals: activeGoals.map(g => ({\n description: g.description,\n metrics: parseMetrics(g),\n progress: g.progress,\n completed: g.completed,\n })),\n });\n }\n\n // Summary stats\n const totalCommits = results.reduce((sum, r) => sum + r.commits, 0);\n const totalPRs = results.reduce((sum, r) => sum + r.prsMerged, 0);\n const totalGoals = results.reduce((sum, r) => sum + r.goals.length, 0);\n\n const stats = [\n `${colors.cyan}${totalCommits}${RESET} commits`,\n `${colors.green}${totalPRs}${RESET} PRs merged`,\n `${colors.purple}${totalGoals}${RESET} active goals`,\n ].join(` ${colors.dim}│${RESET} `);\n writeLine(` ${stats}`);\n writeLine();\n\n // Results table\n const w = { squad: 14, commits: 8, prs: 6, goals: 5, kpi: 20 };\n const tableWidth = w.squad + w.commits + w.prs + w.goals + w.kpi + 8;\n\n writeLine(` ${colors.purple}${box.topLeft}${colors.dim}${box.horizontal.repeat(tableWidth)}${colors.purple}${box.topRight}${RESET}`);\n writeLine(` ${colors.purple}${box.vertical}${RESET} ` +\n `${bold}${padEnd('SQUAD', w.squad)}${RESET}` +\n `${bold}${padEnd('COMMITS', w.commits)}${RESET}` +\n `${bold}${padEnd('PRs', w.prs)}${RESET}` +\n `${bold}${padEnd('GOALS', w.goals)}${RESET}` +\n `${bold}KEY METRIC${RESET}` +\n ` ${colors.purple}${box.vertical}${RESET}`);\n writeLine(` ${colors.purple}${box.teeRight}${colors.dim}${box.horizontal.repeat(tableWidth)}${colors.purple}${box.teeLeft}${RESET}`);\n\n for (const result of results) {\n const keyMetric = result.goals.length > 0\n ? result.goals[0].metrics[0] || '—'\n : '—';\n\n const commitColor = result.commits > 0 ? colors.green : colors.dim;\n const prColor = result.prsMerged > 0 ? colors.green : colors.dim;\n\n const row = ` ${colors.purple}${box.vertical}${RESET} ` +\n `${colors.cyan}${padEnd(result.name, w.squad)}${RESET}` +\n `${commitColor}${padEnd(String(result.commits), w.commits)}${RESET}` +\n `${prColor}${padEnd(String(result.prsMerged), w.prs)}${RESET}` +\n `${padEnd(String(result.goals.length), w.goals)}` +\n `${colors.dim}${truncate(keyMetric, w.kpi)}${RESET}` +\n ` ${colors.purple}${box.vertical}${RESET}`;\n writeLine(row);\n }\n\n writeLine(` ${colors.purple}${box.bottomLeft}${colors.dim}${box.horizontal.repeat(tableWidth)}${colors.purple}${box.bottomRight}${RESET}`);\n writeLine();\n\n // Goal details with KPIs\n if (options.verbose || options.squad) {\n writeLine(` ${bold}Goals & KPIs${RESET}`);\n writeLine();\n\n for (const result of results) {\n if (result.goals.length === 0) continue;\n\n writeLine(` ${colors.cyan}${result.name}${RESET}`);\n\n for (const goal of result.goals) {\n const statusIcon = goal.progress ? icons.progress : icons.empty;\n writeLine(` ${statusIcon} ${truncate(goal.description, 55)}`);\n\n // Show metrics\n if (goal.metrics.length > 0) {\n const metricsStr = goal.metrics.map(m => `${colors.purple}${m}${RESET}`).join(', ');\n writeLine(` ${colors.dim}metrics:${RESET} ${metricsStr}`);\n }\n\n // Show progress if any\n if (goal.progress) {\n writeLine(` ${colors.dim}progress:${RESET} ${colors.green}${goal.progress}${RESET}`);\n }\n }\n writeLine();\n }\n }\n\n // Help\n writeLine(` ${colors.dim}$${RESET} squads results ${colors.cyan}<squad>${RESET} -v ${colors.dim}Detailed squad KPIs${RESET}`);\n writeLine(` ${colors.dim}$${RESET} squads goal progress ${colors.dim}Update goal progress${RESET}`);\n writeLine();\n}\n","import { execSync } from 'child_process';\nimport { existsSync, readFileSync } from 'fs';\nimport { join } from 'path';\nimport { findMemoryDir } from '../lib/memory.js';\nimport {\n colors,\n bold,\n RESET,\n gradient,\n box,\n padEnd,\n truncate,\n icons,\n writeLine,\n} from '../lib/terminal.js';\n\ninterface TaskEntry {\n id: string;\n squad: string;\n description: string;\n status: 'active' | 'completed' | 'failed';\n startedAt: string;\n}\n\ninterface ProcessInfo {\n pid: string;\n cpu: string;\n mem: string;\n time: string;\n command: string;\n type: 'claude' | 'agent' | 'hook' | 'dev-server';\n}\n\nfunction getTasksFilePath(): string | null {\n const memoryDir = findMemoryDir();\n if (!memoryDir) return null;\n return join(memoryDir, '..', 'tasks.json');\n}\n\nfunction loadActiveTasks(): TaskEntry[] {\n const tasksPath = getTasksFilePath();\n if (!tasksPath || !existsSync(tasksPath)) return [];\n\n try {\n const data = JSON.parse(readFileSync(tasksPath, 'utf-8'));\n return data.tasks?.filter((t: TaskEntry) => t.status === 'active') || [];\n } catch {\n return [];\n }\n}\n\nfunction getRunningProcesses(): ProcessInfo[] {\n const processes: ProcessInfo[] = [];\n\n try {\n // Get Claude and related processes\n const psOutput = execSync(\n 'ps aux | grep -E \"claude|squads|astro|node.*agent\" | grep -v grep',\n { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] }\n ).trim();\n\n if (!psOutput) return processes;\n\n for (const line of psOutput.split('\\n')) {\n const parts = line.trim().split(/\\s+/);\n if (parts.length < 11) continue;\n\n const pid = parts[1];\n const cpu = parts[2];\n const mem = parts[3];\n const time = parts[9];\n const command = parts.slice(10).join(' ');\n\n // Categorize the process\n let type: ProcessInfo['type'] = 'agent';\n if (command.includes('claude')) type = 'claude';\n else if (command.includes('squads')) type = 'hook';\n else if (command.includes('astro')) type = 'dev-server';\n\n // Skip very short-lived processes\n if (command.includes('grep')) continue;\n\n processes.push({ pid, cpu, mem, time, command, type });\n }\n } catch {\n // No matching processes\n }\n\n return processes;\n}\n\nfunction categorizeProcesses(processes: ProcessInfo[]): {\n claude: ProcessInfo[];\n hooks: ProcessInfo[];\n devServers: ProcessInfo[];\n agents: ProcessInfo[];\n} {\n return {\n claude: processes.filter(p => p.type === 'claude'),\n hooks: processes.filter(p => p.type === 'hook'),\n devServers: processes.filter(p => p.type === 'dev-server'),\n agents: processes.filter(p => p.type === 'agent'),\n };\n}\n\nfunction formatCommand(cmd: string, maxLen = 45): string {\n // Extract meaningful part of command\n if (cmd.includes('claude')) {\n return truncate('claude (session)', maxLen);\n }\n if (cmd.includes('astro dev')) {\n return truncate('astro dev server', maxLen);\n }\n if (cmd.includes('squads')) {\n const match = cmd.match(/squads\\s+(\\S+)/);\n return truncate(`squads ${match?.[1] || 'command'}`, maxLen);\n }\n return truncate(cmd, maxLen);\n}\n\nexport async function workersCommand(options: { verbose?: boolean; kill?: string } = {}): Promise<void> {\n writeLine();\n writeLine(` ${gradient('squads')} ${colors.dim}workers${RESET}`);\n writeLine();\n\n // Kill a process if requested\n if (options.kill) {\n try {\n execSync(`kill ${options.kill}`, { stdio: 'pipe' });\n writeLine(` ${icons.success} Killed process ${colors.cyan}${options.kill}${RESET}`);\n writeLine();\n return;\n } catch {\n writeLine(` ${icons.error} Failed to kill process ${colors.red}${options.kill}${RESET}`);\n writeLine();\n return;\n }\n }\n\n const activeTasks = loadActiveTasks();\n const processes = getRunningProcesses();\n const categorized = categorizeProcesses(processes);\n\n // Summary stats\n const stats = [\n `${colors.cyan}${categorized.claude.length}${RESET} claude`,\n `${colors.green}${activeTasks.length}${RESET} tasks`,\n `${colors.purple}${categorized.devServers.length}${RESET} dev servers`,\n ].join(` ${colors.dim}│${RESET} `);\n writeLine(` ${stats}`);\n writeLine();\n\n // Claude sessions\n if (categorized.claude.length > 0) {\n writeLine(` ${bold}Claude Sessions${RESET} ${colors.dim}(terminal tabs)${RESET}`);\n writeLine();\n\n const w = { pid: 8, cpu: 6, mem: 6, time: 8, cmd: 30 };\n const tableWidth = w.pid + w.cpu + w.mem + w.time + w.cmd + 8;\n\n writeLine(` ${colors.purple}${box.topLeft}${colors.dim}${box.horizontal.repeat(tableWidth)}${colors.purple}${box.topRight}${RESET}`);\n writeLine(` ${colors.purple}${box.vertical}${RESET} ${bold}${padEnd('PID', w.pid)}${padEnd('CPU%', w.cpu)}${padEnd('MEM%', w.mem)}${padEnd('TIME', w.time)}${padEnd('STATUS', w.cmd)}${RESET} ${colors.purple}${box.vertical}${RESET}`);\n writeLine(` ${colors.purple}${box.teeRight}${colors.dim}${box.horizontal.repeat(tableWidth)}${colors.purple}${box.teeLeft}${RESET}`);\n\n for (const proc of categorized.claude) {\n const cpuColor = parseFloat(proc.cpu) > 50 ? colors.yellow : colors.dim;\n const status = parseFloat(proc.cpu) > 10 ? `${icons.active} active` : `${icons.pending} idle`;\n\n const row = ` ${colors.purple}${box.vertical}${RESET} ` +\n `${colors.cyan}${padEnd(proc.pid, w.pid)}${RESET}` +\n `${cpuColor}${padEnd(proc.cpu, w.cpu)}${RESET}` +\n `${colors.dim}${padEnd(proc.mem, w.mem)}${RESET}` +\n `${colors.dim}${padEnd(proc.time, w.time)}${RESET}` +\n `${padEnd(status, w.cmd)}` +\n ` ${colors.purple}${box.vertical}${RESET}`;\n writeLine(row);\n }\n\n writeLine(` ${colors.purple}${box.bottomLeft}${colors.dim}${box.horizontal.repeat(tableWidth)}${colors.purple}${box.bottomRight}${RESET}`);\n writeLine();\n }\n\n // Active tasks (registered via squads progress start)\n if (activeTasks.length > 0) {\n writeLine(` ${bold}Registered Tasks${RESET} ${colors.dim}(squads progress)${RESET}`);\n writeLine();\n\n for (const task of activeTasks) {\n const elapsed = getElapsedTime(task.startedAt);\n writeLine(` ${icons.progress} ${colors.cyan}${task.squad}${RESET} ${truncate(task.description, 40)}`);\n writeLine(` ${colors.dim}id: ${task.id} · started ${elapsed} ago${RESET}`);\n }\n writeLine();\n }\n\n // Dev servers\n if (categorized.devServers.length > 0) {\n writeLine(` ${bold}Dev Servers${RESET}`);\n writeLine();\n\n for (const proc of categorized.devServers) {\n const name = formatCommand(proc.command);\n writeLine(` ${icons.active} ${colors.green}${name}${RESET} ${colors.dim}(pid: ${proc.pid})${RESET}`);\n }\n writeLine();\n }\n\n // Hooks/squads processes\n if (categorized.hooks.length > 0) {\n writeLine(` ${bold}Hook Processes${RESET}`);\n writeLine();\n\n for (const proc of categorized.hooks) {\n const name = formatCommand(proc.command);\n writeLine(` ${icons.pending} ${colors.yellow}${name}${RESET} ${colors.dim}(pid: ${proc.pid})${RESET}`);\n }\n writeLine();\n }\n\n // No workers message\n if (categorized.claude.length === 0 && activeTasks.length === 0) {\n writeLine(` ${colors.dim}No active workers${RESET}`);\n writeLine();\n }\n\n // Commands\n writeLine(` ${colors.dim}$${RESET} squads workers --kill <pid> ${colors.dim}Kill a process${RESET}`);\n writeLine(` ${colors.dim}$${RESET} squads progress ${colors.dim}Task history${RESET}`);\n writeLine();\n}\n\nfunction getElapsedTime(startTime: string): string {\n const start = new Date(startTime).getTime();\n const now = Date.now();\n const diffMs = now - start;\n\n const minutes = Math.floor(diffMs / 60000);\n const hours = Math.floor(minutes / 60);\n const days = Math.floor(hours / 24);\n\n if (days > 0) return `${days}d`;\n if (hours > 0) return `${hours}h`;\n if (minutes > 0) return `${minutes}m`;\n return '<1m';\n}\n"],"mappings":";;;;;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kB;AAE5B,SACG,QAAQ,cAAc,EACtB,YAAY,uBAAuB,EACnC,OAAO,mBAAmB,6BAA6B,GAAG,EAC1D,OAAO,mBAAmB;AAE7B,SACG,QAAQ,OAAO,EACf,YAAY,yCAAyC,EACrD,OAAO,oBAAoB;AAG9B,QACG,QAAQ,OAAO,EACf,YAAY,qCAAqC,EACjD,OAAO,YAAY;AAEtB,QACG,QAAQ,QAAQ,EAChB,YAAY,qBAAqB,EACjC,OAAO,aAAa;AAEvB,QACG,QAAQ,QAAQ,EAChB,YAAY,6BAA6B,EACzC,OAAO,aAAa;AAGvB,MAAM,QAAQ,WAAW;AAGzB,IAAI,CAAC,QAAQ,KAAK,MAAM,CAAC,EAAE,QAAQ;AACjC,UAAQ,IAAI;AAAA,EACZC,OAAM,KAAK,QAAQ,QAAQ,CAAC;AAAA;AAAA,EAE5BA,OAAM,IAAI,cAAc,CAAC;AAAA,IACvBA,OAAM,KAAK,eAAe,CAAC;AAAA,IAC3BA,OAAM,KAAK,oBAAoB,CAAC;AAAA,IAChCA,OAAM,KAAK,8BAA8B,CAAC;AAAA;AAAA,EAE5CA,OAAM,IAAI,mBAAmB,CAAC;AAAA,IAC5BA,OAAM,KAAK,kCAAkC,CAAC;AAAA,IAC9CA,OAAM,KAAK,kBAAkB,CAAC;AAAA,IAC9BA,OAAM,KAAK,qCAAqC,CAAC;AAAA;AAAA,EAEnDA,OAAM,IAAI,WAAW,CAAC;AAAA,IACpBA,OAAM,KAAK,oBAAoB,CAAC;AAAA,IAChCA,OAAM,KAAK,uCAAuC,CAAC;AAAA,IACnDA,OAAM,KAAK,uBAAuB,CAAC;AAAA;AAAA,EAErCA,OAAM,IAAI,KAAK,CAAC,IAAIA,OAAM,KAAK,eAAe,CAAC,IAAIA,OAAM,IAAI,mBAAmB,CAAC;AAAA,CAClF;AACD;","names":["existsSync","join","homedir","chalk","repos","existsSync","join","config","config","existsSync","ora","join","dirname","existsSync","readFileSync","writeFileSync","mkdirSync","readFileSync","existsSync","writeFileSync","join","progress","goal","readFileSync","writeFileSync","existsSync","readdirSync","mkdirSync","join","statSync","join","dirname","existsSync","mkdirSync","readFileSync","writeFileSync","ora","existsSync","join","join","existsSync","execSync","existsSync","readFileSync","writeFileSync","mkdirSync","readdirSync","join","join","existsSync","readFileSync","writeFileSync","execSync","mkdirSync","readdirSync","goal","progress","readFileSync","writeFileSync","existsSync","mkdirSync","readdirSync","join","dirname","join","existsSync","readFileSync","feedback","dirname","mkdirSync","writeFileSync","readdirSync","readdirSync","existsSync","statSync","join","homedir","require","pool","join","existsSync","readdirSync","statSync","activeGoals","totalGoals","completedGoals","goal","homedir","totalCalls","execSync","execSync","execSync","spawn","ora","DEFAULT_ORG","DEFAULT_REPOS","execSync","ora","spawn","execSync","spawn","readdirSync","join","ora","readdirSync","join","ora","execSync","executeClaudePrompt","spawn","chalk","ora","existsSync","readFileSync","writeFileSync","mkdirSync","join","homedir","chalk","ora","execSync","existsSync","readFileSync","writeFileSync","mkdirSync","join","join","existsSync","mkdirSync","readFileSync","writeFileSync","execSync","execSync","execSync","getGitHubStats","goal","execSync","existsSync","readFileSync","join","getTasksFilePath","join","existsSync","readFileSync","execSync","getElapsedTime","join","homedir","existsSync","chalk"]}
1
+ {"version":3,"sources":["../src/cli.ts","../src/lib/stack-config.ts","../src/commands/orchestrate.ts","../src/lib/orchestration/lead-orchestrator.ts","../src/commands/trigger.ts","../src/commands/autonomous.ts","../src/commands/approval.ts","../src/commands/deploy.ts","../src/commands/eval.ts","../src/commands/cognition.ts"],"sourcesContent":["import { config } from 'dotenv';\nimport { existsSync } from 'fs';\nimport { join } from 'path';\nimport { homedir } from 'os';\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport { version } from './version.js';\nimport { colors as termColors, RESET as termReset, bold as termBold, writeLine } from './lib/terminal.js';\n\n// Disable colors when output is piped (not a TTY)\n// This ensures piped output is clean for parsing\nif (!process.stdout.isTTY) {\n chalk.level = 0;\n}\n\n// Handle EPIPE gracefully when output is piped through head/tail/grep\n// These commands close the pipe early, which is normal Unix behavior\nprocess.stdout.on('error', (err: NodeJS.ErrnoException) => {\n if (err.code === 'EPIPE') {\n process.exit(0);\n }\n throw err;\n});\n\nprocess.stderr.on('error', (err: NodeJS.ErrnoException) => {\n if (err.code === 'EPIPE') {\n process.exit(0);\n }\n throw err;\n});\n\n// Load .env from multiple locations (first found wins)\nconst envPaths = [\n join(process.cwd(), '.env'),\n join(process.cwd(), '..', 'hq', '.env'),\n join(homedir(), 'agents-squads', 'hq', '.env'),\n];\n\nfor (const envPath of envPaths) {\n if (existsSync(envPath)) {\n config({ path: envPath, quiet: true });\n break;\n }\n}\n\n// Type-only import (erased at compile time, zero runtime cost)\nimport type { SessionSummaryData } from './commands/sessions.js';\n\n// Setup imports (must run on every invocation)\nimport { registerExitHandler } from './lib/telemetry.js';\nimport { applyStackConfig } from './lib/stack-config.js';\n\n// Register-pattern commands (must define subcommand structure before parseAsync)\nimport { registerOrchestrateCommand } from './commands/orchestrate.js';\nimport { registerTriggerCommand } from './commands/trigger.js';\nimport { registerAutonomousCommand } from './commands/autonomous.js';\nimport { registerApprovalCommand } from './commands/approval.js';\nimport { registerDeployCommand } from './commands/deploy.js';\nimport { registerEvalCommand } from './commands/eval.js';\nimport { registerCognitionCommand } from './commands/cognition.js';\n\n// All other command handlers are lazy-loaded via dynamic import() inside\n// action handlers. Only the invoked command's dependencies are loaded,\n// avoiding heavy transitive deps (pg, supabase, inquirer, ora) on every\n// invocation. Saves ~300ms+ on cold start. See: #24\n\n// Load stack config from ~/.squadsrc (if exists)\napplyStackConfig();\n\n// Seamless auto-update on startup (like Gemini CLI)\n// Runs in background, shows message on success\n// Set SQUADS_NO_AUTO_UPDATE=1 to disable\n// Skip for --help and --version to keep those instant\nconst isHelpOrVersion = process.argv.includes('--help') || process.argv.includes('-h') || process.argv.includes('--version') || process.argv.includes('-V');\nif (!isHelpOrVersion) {\n const { autoUpdateOnStartup } = await import('./lib/update.js');\n await autoUpdateOnStartup();\n}\n\n// Register telemetry exit handler early\nregisterExitHandler();\n\n// Helper: show removed command message\nfunction removedCommand(name: string, alternative: string): () => void {\n return () => {\n console.error(chalk.red(`\\n Command \"${name}\" has been removed.`));\n console.error(chalk.dim(` ${alternative}\\n`));\n process.exit(1);\n };\n}\n\n// ─── Friendly error messages for missing arguments (#317) ─────────────────────\n// Maps command paths to user-friendly hints when required arguments are missing.\n// Each entry: { message: plain-language explanation, example: usage example }\nconst friendlyArgErrors: Record<string, { message: string; example: string }> = {\n 'add': {\n message: 'Specify a name for the new squad.',\n example: 'squads add marketing # add with interactive prompts\\n squads add marketing -d \"Drive growth\" -y # non-interactive',\n },\n 'run': {\n message: 'Specify which squad or agent to run.',\n example: 'squads run engineering # run the whole squad\\n squads run engineering/code-review # run a specific agent',\n },\n 'orchestrate': {\n message: 'Specify which squad to orchestrate.',\n example: 'squads orchestrate intelligence',\n },\n 'eval': {\n message: 'Specify which squad or agent to evaluate.',\n example: 'squads eval company # evaluate all agents in squad\\n squads eval company/coo # evaluate a specific agent',\n },\n 'budget': {\n message: 'Specify which squad to check budget for.',\n example: 'squads budget engineering',\n },\n 'goal set': {\n message: 'Provide the squad name and a goal description.',\n example: 'squads goal set marketing \"Increase blog traffic by 20%\"',\n },\n 'goal complete': {\n message: 'Provide the squad name and the goal index to mark complete.',\n example: 'squads goal complete marketing 1',\n },\n 'goal progress': {\n message: 'Provide the squad, goal index, and progress update.',\n example: 'squads goal progress marketing 1 \"50% — halfway through campaign\"',\n },\n};\n\n/**\n * Detect which command the user invoked from process.argv.\n * Returns the command path (e.g. \"goal set\" or \"run\").\n */\nfunction detectCommandFromArgs(): string | null {\n // argv: [node, script, ...commands/options]\n const args = process.argv.slice(2).filter(a => !a.startsWith('-'));\n if (args.length === 0) return null;\n // Try two-word command first (e.g. \"goal set\"), then single word\n if (args.length >= 2) {\n const twoWord = `${args[0]} ${args[1]}`;\n if (friendlyArgErrors[twoWord]) return twoWord;\n }\n return args[0] || null;\n}\n\n/**\n * Handle Commander.js outputError: intercept \"missing required argument\"\n * errors and show friendly, colorized messages instead of raw format.\n */\nfunction handleOutputError(str: string, write: (s: string) => void): void {\n const missingArgMatch = str.match(/^error: missing required argument '(.+)'/);\n if (missingArgMatch) {\n const argName = missingArgMatch[1];\n const command = detectCommandFromArgs();\n const hint = command ? friendlyArgErrors[command] : null;\n\n // Friendly error header\n process.stderr.write(`\\n ${termColors.red}Missing argument: ${termReset}${termBold}${argName}${termReset}\\n`);\n\n if (hint) {\n process.stderr.write(` ${hint.message}\\n\\n`);\n process.stderr.write(` ${termColors.dim}Usage:${termReset}\\n`);\n for (const line of hint.example.split('\\n')) {\n process.stderr.write(` ${termColors.cyan}$${termReset} ${line.trim()}\\n`);\n }\n } else {\n process.stderr.write(` Run the command with ${termColors.cyan}--help${termReset} for usage information.\\n`);\n }\n\n process.stderr.write('\\n');\n return;\n }\n\n // For all other errors (unknown option, etc.), pass through\n write(str);\n}\n\nconst program = new Command();\n\nprogram\n .name('squads')\n .description('Your AI workforce — business operating system for AI managers')\n .version(version)\n // Enable typo suggestions (Commander.js built-in feature)\n .showSuggestionAfterError(true)\n // Configure help to exit with code 0 (Unix convention)\n .configureOutput({\n outputError: handleOutputError,\n })\n .exitOverride((err) => {\n // Exit code 0 for help display (Unix convention)\n if (err.code === 'commander.helpDisplayed' || err.code === 'commander.version') {\n process.exit(0);\n }\n // For other commander errors, use the default exit code\n if (err.exitCode !== undefined) {\n process.exit(err.exitCode);\n }\n throw err;\n })\n // Default action when no command provided - show status dashboard\n .action(async () => {\n // If args were provided but didn't match any command, they're unknown\n if (program.args.length > 0) {\n const unknown = program.args[0];\n process.stderr.write(`\\n Unknown command: \"${unknown}\"\\n\\n`);\n process.stderr.write(` Run \\`squads --help\\` to see available commands.\\n\\n`);\n process.exit(1);\n }\n\n const { gradient, colors, RESET } = await import('./lib/terminal.js');\n const { checkForUpdate } = await import('./lib/update.js');\n\n writeLine();\n writeLine(` ${gradient('squads')} ${colors.dim}v${version}${RESET}`);\n writeLine();\n\n // Check for updates\n const updateInfo = checkForUpdate();\n if (updateInfo.updateAvailable) {\n writeLine(` ${colors.cyan}⬆${RESET} Update available: ${colors.dim}${updateInfo.currentVersion}${RESET} → ${colors.green}${updateInfo.latestVersion}${RESET}`);\n writeLine(` ${colors.dim}Run \\`squads update\\` to install${RESET}`);\n writeLine();\n }\n\n // Run status command to show all squads (includes quick commands)\n const { statusCommand } = await import('./commands/status.js');\n await statusCommand(undefined, {});\n });\n\n// ─── Execute (daily operations) ──────────────────────────────────────────────\n\n// Init command - plant the seed (manager agent + CLI skill + starter squads)\nprogram\n .command('init')\n .description('Plant the seed: create manager agent, CLI skill, and starter squads')\n .option('-p, --provider <provider>', 'LLM provider (claude, gemini, openai, ollama, none)')\n .option('--pack <packs...>', 'Additional squad packs to install (engineering, marketing, operations, all)')\n .option('--skip-infra', 'Skip infrastructure setup prompt')\n .option('--force', 'Skip requirement checks (for CI/testing)')\n .option('-y, --yes', 'Accept all defaults (non-interactive mode)')\n .option('-q, --quick', 'Quick init - create files only, skip interactive prompts')\n .action(async (options) => {\n const { initCommand } = await import('./commands/init.js');\n return initCommand(options);\n });\n\n// Add command - add a new squad to your workforce\nprogram\n .command('add <name>')\n .description('Add a new squad with directory structure and starter files')\n .option('-d, --description <text>', 'Squad mission (one sentence)')\n .option('-g, --goal <text>', 'First goal for the squad')\n .option('-m, --model <model>', 'Default model (default: sonnet)')\n .option('-f, --force', 'Overwrite existing squad')\n .option('-y, --yes', 'Accept all defaults (non-interactive)')\n .option('-r, --repo', 'Create a GitHub repository for the squad')\n .option('-o, --org <org>', 'GitHub organization for --repo (default: detected from git remote)')\n .addHelpText('after', `\nExamples:\n $ squads add marketing Add with interactive prompts\n $ squads add marketing -d \"Drive growth\" -y Add non-interactively\n $ squads add marketing --force Overwrite existing squad\n $ squads add marketing --repo Add with GitHub repo\n $ squads add marketing --repo --org myorg Add with GitHub repo in specific org\n`)\n .action(async (name, options) => {\n const { createCommand } = await import('./commands/create.js');\n return createCommand(name, options);\n });\n\n// Hidden alias: create → add (backward compat)\nprogram.command('create <name>', { hidden: true }).description('[renamed]').action(removedCommand('create', 'Renamed to: squads add <name>'));\n\n// Run command - execute squads or individual agents\nprogram\n .command('run [target]')\n .description('Run a squad, agent, or autopilot (no target = autopilot mode)')\n .option('-v, --verbose', 'Verbose output')\n .option('-d, --dry-run', 'Show what would be run without executing')\n .option('-a, --agent <agent>', 'Run specific agent within squad')\n .option('-t, --timeout <minutes>', 'Execution timeout in minutes (default: 30)', '30')\n .option('-p, --parallel', 'Run all agents in parallel (N tmux sessions)')\n .option('-l, --lead', 'Lead mode: single orchestrator using Task tool for parallelization')\n .option('-b, --background', 'Run agent in background (detached process)')\n .option('-w, --watch', 'Run in background but tail the log for visibility')\n .option('--use-api', 'Use API credits instead of subscription')\n .option('--effort <level>', 'Effort level: high, medium, low (default: from SQUAD.md or high)')\n .option('--skills <skills...>', 'Skills to load (skill IDs or local paths)')\n .option('--provider <provider>', 'LLM provider: anthropic, google, openai, mistral, xai, aider, ollama')\n .option('--model <model>', 'Model to use (e.g., opus, sonnet, haiku, gemini-2.5-flash, gpt-4o)')\n .option('--trigger <type>', 'Trigger source: manual, scheduled, event, smart (default: manual)')\n .option('--cloud', 'Dispatch execution to cloud worker via API (requires squads login)')\n .option('--task <directive>', 'Founder directive for conversation mode (replaces lead briefing)')\n .option('--max-turns <n>', 'Max conversation turns (default: 20)', '20')\n .option('--cost-ceiling <usd>', 'Cost ceiling in USD (default: 25)', '25')\n .option('--no-verify', 'Skip post-execution verification (Ralph loop)')\n .option('--execute', 'Explicitly execute agents (default for run <target>)')\n .option('-j, --json', 'Output as JSON')\n .option('-i, --interval <minutes>', 'Autopilot: minutes between cycles', '30')\n .option('--max-parallel <count>', 'Autopilot: max parallel squad loops', '2')\n .option('--budget <usd>', 'Autopilot: daily budget cap ($)', '0')\n .option('--once', 'Autopilot: run one cycle then exit')\n .option('--phased', 'Autopilot: use dependency-based phase ordering (from SQUAD.md depends_on)')\n .option('--no-eval', 'Skip post-run COO evaluation')\n .addHelpText('after', `\nExamples:\n $ squads run engineering Run squad conversation (lead → scan → work → review)\n $ squads run engineering --task \"fix CI\" Conversation with founder directive\n $ squads run engineering/code-review Run specific agent (slash notation)\n $ squads run engineering -a code-review Same as above (flag notation)\n $ squads run engineering --dry-run Preview what would run\n $ squads run engineering --parallel Run all agents in parallel (tmux)\n $ squads run engineering --lead Single orchestrator with Task tool\n $ squads run engineering -b Run in background (detached)\n $ squads run engineering -w Run in background but tail logs\n $ squads run research --provider=google Use Gemini CLI instead of Claude\n $ squads run engineering/issue-solver --cloud Dispatch to cloud worker\n $ squads run Autopilot mode (watch → decide → dispatch → learn)\n $ squads run --once --dry-run Preview one autopilot cycle\n $ squads run -i 15 --budget 50 Autopilot: 15min cycles, $50/day cap\n`)\n .action(async (target, options) => {\n const { runCommand } = await import('./commands/run.js');\n return runCommand(target || null, { ...options, timeout: parseInt(options.timeout, 10) });\n });\n\n// List command (removed — use status instead)\nprogram.command('list', { hidden: true }).description('[removed]').action(removedCommand('list', 'Use: squads status'));\n\n// Orchestrate command - lead-coordinated squad execution\nregisterOrchestrateCommand(program);\n\n// Env command - squad execution environment (MCP, skills, budget, model)\nconst env = program\n .command('env')\n .description('View squad execution environment (MCP, skills, model, budget)')\n .action(() => { env.outputHelp(); });\n\nenv\n .command('show <squad>')\n .description('Show execution environment for a squad')\n .option('--json', 'Output as JSON')\n .action(async (squad, options) => {\n const { contextShowCommand } = await import('./commands/context.js');\n return contextShowCommand(squad, options);\n });\n\nenv\n .command('prompt <squad>')\n .description('Output ready-to-use prompt for Claude Code execution')\n .option('-a, --agent <agent>', 'Agent to execute (required)')\n .option('--json', 'Output as JSON')\n .action(async (squad, options) => {\n const { contextPromptCommand } = await import('./commands/context.js');\n return contextPromptCommand(squad, options);\n });\n\n// Exec command group - execution history introspection\nconst exec = program\n .command('exec')\n .description('View execution history and statistics');\n\nexec\n .command('list')\n .description('List recent executions')\n .option('-s, --squad <squad>', 'Filter by squad')\n .option('-a, --agent <agent>', 'Filter by agent')\n .option('--status <status>', 'Filter by status (running, completed, failed)')\n .option('-n, --limit <n>', 'Number of executions to show', '20')\n .option('--json', 'Output as JSON')\n .action(async (options) => {\n const { execListCommand } = await import('./commands/exec.js');\n return execListCommand({ ...options, limit: parseInt(options.limit, 10) });\n });\n\nexec\n .command('show <id>')\n .description('Show execution details')\n .option('--json', 'Output as JSON')\n .action(async (id, options) => {\n const { execShowCommand } = await import('./commands/exec.js');\n return execShowCommand(id, options);\n });\n\nexec\n .command('stats')\n .description('Show execution statistics')\n .option('-s, --squad <squad>', 'Filter by squad')\n .option('--json', 'Output as JSON')\n .action(async (options) => {\n const { execStatsCommand } = await import('./commands/exec.js');\n return execStatsCommand(options);\n });\n\n// Default action: show list\nexec.action(async (options) => {\n const { execListCommand } = await import('./commands/exec.js');\n return execListCommand(options);\n});\n\n// ─── Understand (situational awareness) ──────────────────────────────────────\n\n// Dashboard command\nprogram\n .command('dashboard [name]')\n .alias('dash')\n .description('Show dashboards. Use \"squads dash\" for overview, \"squads dash <name>\" for specific dashboard, \"squads dash --list\" to see all.')\n .option('-v, --verbose', 'Show additional details')\n .option('-c, --ceo', 'Executive summary with priorities and blockers')\n .option('-f, --full', 'Include GitHub PR/issue stats (slower, ~30s)')\n .option('-l, --list', 'List available declarative dashboards')\n .option('--view <view>', 'Render specific view from dashboard')\n .option('-j, --json', 'Output as JSON')\n .action(async (name, options) => {\n const { renderDashboard, showAvailableDashboards, findDashboard } = await import('./lib/dashboard/index.js');\n\n // List available dashboards\n if (options.list) {\n showAvailableDashboards();\n return;\n }\n\n // If a name is provided, try declarative dashboard first\n if (name) {\n const def = findDashboard(name);\n if (def) {\n const views = options.view ? [options.view] : undefined;\n await renderDashboard(name, { verbose: options.verbose, views });\n return;\n }\n // Fall through to default dashboard with a warning\n writeLine(` Dashboard \"${name}\" not found. Showing default dashboard.\\n`);\n }\n\n // Default: show the comprehensive dashboard\n const { dashboardCommand } = await import('./commands/dashboard.js');\n dashboardCommand({ ...options, fast: !options.full });\n });\n\n// Status command\nprogram\n .command('status [squad]')\n .description('Show squad status and state')\n .option('-v, --verbose', 'Show detailed status')\n .option('-j, --json', 'Output as JSON')\n .action(async (squad, options) => {\n const { statusCommand } = await import('./commands/status.js');\n return statusCommand(squad, options);\n });\n\n// Context command - business context for alignment\nprogram\n .command('context')\n .alias('feed')\n .description('Get business context for alignment: goals, memory, costs, activity')\n .option('-s, --squad <squad>', 'Focus on specific squad')\n .option('-t, --topic <topic>', 'Search memory for relevant context')\n .option('-a, --agent', 'Output JSON for agent consumption')\n .option('-j, --json', 'Output as JSON (alias for --agent)')\n .option('-v, --verbose', 'Show additional details')\n .action(async (options) => {\n const { contextFeedCommand } = await import('./commands/context-feed.js');\n return contextFeedCommand(options);\n });\n\n// Cost command - cost introspection for self-improvement\nprogram\n .command('cost')\n .description('Show cost summary (today, week, by squad)')\n .option('-s, --squad <squad>', 'Filter to specific squad')\n .option('--json', 'Output as JSON')\n .action(async (options) => {\n const { costCommand } = await import('./commands/cost.js');\n return costCommand(options);\n });\n\n// Budget check command - pre-flight budget validation\nprogram\n .command('budget')\n .description('Check budget status for a squad')\n .argument('<squad>', 'Squad to check')\n .option('--json', 'Output as JSON')\n .action(async (squad, options) => {\n const { budgetCheckCommand } = await import('./commands/cost.js');\n return budgetCheckCommand(squad, options);\n });\n\n// Health command - quick infrastructure check\nprogram\n .command('health')\n .description('Quick health check for all infrastructure services')\n .option('-v, --verbose', 'Show optional services')\n .action(async (options) => {\n const { healthCommand } = await import('./commands/health.js');\n return healthCommand(options);\n });\n\n// Doctor command - check local environment readiness\nprogram\n .command('doctor')\n .description('Check local tools, auth, and project readiness')\n .option('-v, --verbose', 'Show install hints and optional tools')\n .action(async (options) => {\n const { doctorCommand } = await import('./commands/doctor.js');\n return doctorCommand(options);\n });\n\n// History command - show recent agent executions\nprogram\n .command('history')\n .description('Show recent agent execution history')\n .option('-d, --days <days>', 'Days to look back', '7')\n .option('-s, --squad <squad>', 'Filter by squad')\n .option('-v, --verbose', 'Show cost and token details')\n .option('-j, --json', 'Output as JSON')\n .action(async (options) => {\n const { historyCommand } = await import('./commands/history.js');\n return historyCommand(options);\n });\n\n// Results command - KPI goals vs actuals\nprogram\n .command('results [squad]')\n .description('Show squad results: git activity + KPI goals vs actuals')\n .option('-d, --days <days>', 'Days to look back', '7')\n .option('-v, --verbose', 'Show detailed KPIs per goal')\n .action(async (squad, options) => {\n const { resultsCommand } = await import('./commands/results.js');\n return resultsCommand({ ...options, squad });\n });\n\n// ─── Track (objectives + metrics) ────────────────────────────────────────────\n\n// Goal command group\nconst goal = program\n .command('goal')\n .description('Manage squad goals')\n .action(() => {\n goal.outputHelp();\n });\n\ngoal\n .command('set <squad> <description>')\n .description('Set a goal for a squad')\n .option('-m, --metric <metrics...>', 'Metrics to track')\n .action(async (squad, description, options) => {\n const { goalSetCommand } = await import('./commands/goal.js');\n return goalSetCommand(squad, description, options);\n });\n\ngoal\n .command('list [squad]')\n .description('List goals for squad(s)')\n .option('-a, --all', 'Show completed goals too')\n .option('-j, --json', 'Output as JSON')\n .action(async (squad, options) => {\n const { goalListCommand } = await import('./commands/goal.js');\n return goalListCommand(squad, options);\n });\n\ngoal\n .command('complete <squad> <index>')\n .description('Mark a goal as completed')\n .action(async (squad, index) => {\n const { goalCompleteCommand } = await import('./commands/goal.js');\n return goalCompleteCommand(squad, index);\n });\n\ngoal\n .command('progress <squad> <index> <progress>')\n .description('Update goal progress')\n .action(async (squad, index, progress) => {\n const { goalProgressCommand } = await import('./commands/goal.js');\n return goalProgressCommand(squad, index, progress);\n });\n\n// KPI command group - track squad metrics\nconst kpi = program\n .command('kpi')\n .description('Track and analyze squad KPIs (defined in SQUAD.md frontmatter)')\n .addHelpText('after', `\nExamples:\n $ squads kpi list List all defined KPIs\n $ squads kpi show engineering Show KPI status for a squad\n $ squads kpi record engineering leads_generated 15\n $ squads kpi trend engineering leads_generated\n $ squads kpi insights Show insights across all squads\n`)\n .action(() => { kpi.outputHelp(); });\n\nkpi\n .command('list')\n .description('List all KPIs across squads')\n .option('-j, --json', 'Output as JSON')\n .action(async (options) => {\n const { kpiListCommand } = await import('./commands/kpi.js');\n return kpiListCommand(options);\n });\n\nkpi\n .command('show <squad>')\n .description('Show KPI status for a squad')\n .option('-j, --json', 'Output as JSON')\n .action(async (squad, options) => {\n const { kpiShowCommand } = await import('./commands/kpi.js');\n return kpiShowCommand(squad, options);\n });\n\nkpi\n .command('record <squad> <kpi> <value>')\n .description('Record a KPI value')\n .option('-n, --note <note>', 'Add a note to the record')\n .option('-j, --json', 'Output as JSON')\n .action(async (squad, kpi, value, options) => {\n const { kpiRecordCommand } = await import('./commands/kpi.js');\n return kpiRecordCommand(squad, kpi, value, options);\n });\n\nkpi\n .command('trend <squad> <kpi>')\n .description('Show KPI trend over time')\n .option('-p, --periods <n>', 'Number of periods to show', '7')\n .option('-j, --json', 'Output as JSON')\n .action(async (squad, kpi, options) => {\n const { kpiTrendCommand } = await import('./commands/kpi.js');\n return kpiTrendCommand(squad, kpi, options);\n });\n\nkpi\n .command('insights [squad]')\n .description('Generate insights from KPI data')\n .option('-j, --json', 'Output as JSON')\n .action(async (squad, options) => {\n const { kpiInsightsCommand } = await import('./commands/kpi.js');\n return kpiInsightsCommand(squad, options);\n });\n\n// Progress command - track agent task progress\nconst progress = program\n .command('progress')\n .description('Track active and completed agent tasks')\n .option('-v, --verbose', 'Show more activity')\n .action(async (options) => {\n const { progressCommand } = await import('./commands/progress.js');\n return progressCommand(options);\n });\n\nprogress\n .command('start <squad> <description>')\n .description('Register a new active task')\n .action(async (squad, description) => {\n const { progressStartCommand } = await import('./commands/progress.js');\n return progressStartCommand(squad, description);\n });\n\nprogress\n .command('complete <taskId>')\n .description('Mark a task as completed')\n .option('-f, --failed', 'Mark as failed instead')\n .action(async (taskId, options) => {\n const { progressCompleteCommand } = await import('./commands/progress.js');\n return progressCompleteCommand(taskId, options);\n });\n\n// Feedback command group\nconst feedback = program\n .command('feedback')\n .description('Record and view execution feedback')\n .action(() => { feedback.outputHelp(); });\n\nfeedback\n .command('add <squad> <rating> <feedback>')\n .description('Add feedback for last execution (rating 1-5)')\n .option('-l, --learning <learnings...>', 'Learnings to extract')\n .action(async (squad, rating, feedbackText, options) => {\n const { feedbackAddCommand } = await import('./commands/feedback.js');\n return feedbackAddCommand(squad, rating, feedbackText, options);\n });\n\nfeedback\n .command('show <squad>')\n .description('Show feedback history')\n .option('-n, --limit <n>', 'Number of entries to show', '5')\n .action(async (squad, options) => {\n const { feedbackShowCommand } = await import('./commands/feedback.js');\n return feedbackShowCommand(squad, options);\n });\n\nfeedback\n .command('stats')\n .description('Show feedback summary across all squads')\n .action(async () => {\n const { feedbackStatsCommand } = await import('./commands/feedback.js');\n return feedbackStatsCommand();\n });\n\n// Autonomy command - show autonomous operation readiness\nprogram\n .command('autonomy')\n .description('Show autonomy score and confidence metrics')\n .option('-s, --squad <squad>', 'Filter by squad')\n .option('-p, --period <period>', 'Time period: today, week, month', 'today')\n .option('-j, --json', 'Output as JSON')\n .action(async (options) => {\n const { autonomyCommand } = await import('./commands/autonomy.js');\n return autonomyCommand({ squad: options.squad, period: options.period, json: options.json });\n });\n\n// Autopilot — deprecated, now \"squads run\" (no arguments)\nprogram\n .command('autopilot')\n .alias('daemon')\n .description('[deprecated] Use \"squads run\" instead — autopilot mode when no target given')\n .option('-i, --interval <minutes>', 'Minutes between cycles', '30')\n .option('-p, --parallel <count>', 'Max parallel agent runs', '2')\n .option('-b, --budget <dollars>', 'Max daily spend in dollars (0 = unlimited/subscription)', '0')\n .option('--once', 'Run one cycle and exit')\n .option('--dry-run', 'Show what would run without dispatching')\n .option('-v, --verbose', 'Show detailed scoring')\n .action(async (options) => {\n const colors = termColors;\n writeLine(` ${colors.yellow}Note: \"squads autopilot\" is now \"squads run\" (no arguments)${termReset}`);\n const { runCommand } = await import('./commands/run.js');\n return runCommand(null, { interval: parseInt(options.interval || '30', 10), ...options });\n });\n\n// Stats command - agent outcome scorecards\nprogram\n .command('stats [squad]')\n .description('Show agent outcome scorecards: merge rate, waste, cost per outcome')\n .option('-p, --period <period>', 'Time period: 7d or 30d', '7d')\n .option('-j, --json', 'Output as JSON')\n .action(async (squad, options) => {\n const { statsCommand } = await import('./commands/stats.js');\n return statsCommand({ squad, period: options.period, json: options.json });\n });\n\n// ─── Learn (memory + knowledge) ─────────────────────────────────────────────\n\n// Memory command group\nconst memory = program\n .command('memory')\n .description('Query and manage squad memory')\n .addHelpText('after', `\nExamples:\n $ squads memory read engineering View engineering squad's memory\n $ squads memory write research \"Found: MCP adoption at 15%\"\n $ squads memory search \"pricing\" Search all memory\n $ squads memory list List all memory entries\n $ squads memory sync --push Sync and push to git\n`)\n .action(() => {\n memory.outputHelp();\n });\n\nmemory\n .command('query <query>')\n .description('Search across all squad memory')\n .option('-s, --squad <squad>', 'Limit search to specific squad')\n .option('-a, --agent <agent>', 'Limit search to specific agent')\n .action(async (query, options) => {\n const { memoryQueryCommand } = await import('./commands/memory.js');\n return memoryQueryCommand(query, options);\n });\n\n// read (new name) + show (alias)\nmemory\n .command('read <squad>')\n .alias('show')\n .description('Show memory for a squad')\n .action(async (squad, options) => {\n const { memoryShowCommand } = await import('./commands/memory.js');\n return memoryShowCommand(squad, options);\n });\n\n// write (new name) + update (alias)\nmemory\n .command('write <squad> <content>')\n .alias('update')\n .description('Add to squad memory')\n .option('-a, --agent <agent>', 'Specific agent (default: squad-lead)')\n .option('-t, --type <type>', 'Memory type: state, learnings, feedback', 'learnings')\n .action(async (squad, content, options) => {\n const { memoryUpdateCommand } = await import('./commands/memory.js');\n return memoryUpdateCommand(squad, content, options);\n });\n\nmemory\n .command('list')\n .description('List all memory entries')\n .action(async () => {\n const { memoryListCommand } = await import('./commands/memory.js');\n return memoryListCommand();\n });\n\nmemory\n .command('sync')\n .description('Sync memory from git: pull remote changes, process commits, optionally push to Postgres')\n .option('-v, --verbose', 'Show detailed commit info')\n .option('-p, --push', 'Push local memory changes to remote after sync')\n .option('--no-pull', 'Skip pulling from remote')\n .option('--postgres', 'Sync cycle data (goals, feedback, KPIs, learnings) to Postgres')\n .option('--dimensions', 'Sync squad/agent definitions to Postgres dim tables')\n .option('--learnings', 'Sync learnings.md files to Postgres')\n .option('--auto-learn', 'Auto-generate learnings from session commits')\n .action(async (options) => {\n const { syncCommand } = await import('./commands/sync.js');\n return syncCommand({ verbose: options.verbose, push: options.push, pull: options.pull, postgres: options.postgres, dimensions: options.dimensions, learnings: options.learnings, autoLearn: options.autoLearn });\n });\n\n// search (new name) — also keep old 'search' subcommand\nmemory\n .command('search <query>')\n .description('Search stored conversations (requires authentication: squads login)')\n .option('-l, --limit <limit>', 'Number of results', '10')\n .option('-r, --role <role>', 'Filter by role: user, assistant, thinking')\n .option('-i, --importance <importance>', 'Filter by importance: low, normal, high')\n .action(async (query, opts) => {\n const { memorySearchCommand } = await import('./commands/memory.js');\n return memorySearchCommand(query, {\n limit: parseInt(opts.limit, 10),\n role: opts.role,\n importance: opts.importance\n });\n });\n\nmemory\n .command('extract')\n .description('Extract memories from recent conversations into Engram')\n .option('-s, --session <session>', 'Extract specific session only')\n .option('-h, --hours <hours>', 'Look back period in hours', '24')\n .option('-d, --dry-run', 'Preview without sending to Engram')\n .action(async (opts) => {\n const { memoryExtractCommand } = await import('./commands/memory.js');\n return memoryExtractCommand({\n session: opts.session,\n hours: parseInt(opts.hours, 10),\n dryRun: opts.dryRun\n });\n });\n\n// Learn command - capture learnings for autonomous improvement\nprogram\n .command('learn <insight>')\n .description('Capture a learning for future sessions')\n .option('-s, --squad <squad>', 'Squad to associate learning with')\n .option('-c, --category <category>', 'Category: success, failure, pattern, tip')\n .option('-t, --tags <tags>', 'Comma-separated tags')\n .option('--context <context>', 'Additional context')\n .action(async (insight, options) => {\n const { learnCommand } = await import('./commands/learn.js');\n return learnCommand(insight, options);\n });\n\nconst learn = program\n .command('learnings')\n .description('View and search learnings');\n\nlearn\n .command('show <squad>')\n .description('Show learnings for a squad')\n .option('-n, --limit <n>', 'Number to show', '10')\n .option('-c, --category <category>', 'Filter by category')\n .option('--tag <tag>', 'Filter by tag')\n .action(async (squad, options) => {\n const { learnShowCommand } = await import('./commands/learn.js');\n return learnShowCommand(squad, options);\n });\n\nlearn\n .command('search <query>')\n .description('Search learnings across all squads')\n .option('-n, --limit <n>', 'Max results', '10')\n .action(async (query, options) => {\n const { learnSearchCommand } = await import('./commands/learn.js');\n return learnSearchCommand(query, options);\n });\n\n// Sync command (also available as `memory sync`)\nprogram\n .command('sync')\n .description('Git memory synchronization (Postgres sync optional)')\n .option('-v, --verbose', 'Show detailed commit info')\n .option('-p, --push', 'Push local memory changes to remote after sync')\n .option('--no-pull', 'Skip pulling from remote')\n .option('--postgres', 'Sync cycle data to Postgres')\n .action(async (options) => {\n const { syncCommand } = await import('./commands/sync.js');\n return syncCommand({ verbose: options.verbose, push: options.push, pull: options.pull, postgres: options.postgres });\n });\n\n// ─── Schedule (automation) ───────────────────────────────────────────────────\n\n// Trigger command group - smart value-driven triggers\nregisterTriggerCommand(program);\n\n// Approval command group - human-in-the-loop for agents\nregisterApprovalCommand(program);\n\n// Autonomous command group - scheduled routines\nregisterAutonomousCommand(program);\n\n// ─── System ──────────────────────────────────────────────────────────────────\n\n// Sessions command group - list active sessions and history\nconst sessions = program\n .command('sessions')\n .description('Show active Claude Code sessions across squads')\n .option('-v, --verbose', 'Show session details')\n .option('-j, --json', 'Output as JSON')\n .action(async (options) => {\n const { sessionsCommand } = await import('./commands/sessions.js');\n return sessionsCommand(options);\n });\n\nsessions\n .command('history')\n .description('Show session history and statistics')\n .option('-d, --days <days>', 'Days of history to show', '7')\n .option('-s, --squad <squad>', 'Filter by squad')\n .option('-j, --json', 'Output as JSON')\n .action(async (options) => {\n const { sessionsHistoryCommand } = await import('./commands/sessions.js');\n return sessionsHistoryCommand({\n days: parseInt(options.days, 10),\n squad: options.squad,\n json: options.json,\n });\n });\n\nsessions\n .command('summary')\n .description('Show pretty session summary (auto-detects current session or pass JSON)')\n .option('-d, --data <json>', 'JSON data for summary (overrides auto-detection)')\n .option('-f, --file <path>', 'Path to JSON file with summary data')\n .option('-j, --json', 'Output as JSON instead of pretty format')\n .action(async (options) => {\n const { buildCurrentSessionSummary, sessionsSummaryCommand } = await import('./commands/sessions.js');\n let data: SessionSummaryData;\n\n if (options.file) {\n // Read from file\n const { readFileSync } = await import('fs');\n data = JSON.parse(readFileSync(options.file, 'utf-8'));\n } else if (options.data) {\n // Parse from --data argument\n data = JSON.parse(options.data);\n } else if (!process.stdin.isTTY) {\n // Read from stdin only if piped\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(chunk);\n }\n const input = Buffer.concat(chunks).toString('utf-8').trim();\n if (input) {\n data = JSON.parse(input);\n } else {\n data = await buildCurrentSessionSummary();\n }\n } else {\n // Auto-detect current session\n data = await buildCurrentSessionSummary();\n }\n\n await sessionsSummaryCommand(data, { json: options.json });\n });\n\n// Session command group - lifecycle management\nconst session = program\n .command('session')\n .description('Manage current session lifecycle')\n .action(() => { session.outputHelp(); });\n\nsession\n .command('start')\n .description('Register a new session')\n .option('-s, --squad <squad>', 'Override squad detection')\n .option('-q, --quiet', 'Suppress output')\n .action(async (options) => {\n const { sessionStartCommand } = await import('./commands/session.js');\n return sessionStartCommand({ squad: options.squad, quiet: options.quiet });\n });\n\nsession\n .command('stop')\n .description('End current session')\n .option('-q, --quiet', 'Suppress output')\n .action(async (options) => {\n const { sessionStopCommand } = await import('./commands/session.js');\n return sessionStopCommand({ quiet: options.quiet });\n });\n\nsession\n .command('heartbeat')\n .description('Update session heartbeat')\n .option('-q, --quiet', 'Suppress output')\n .action(async (options) => {\n const { sessionHeartbeatCommand } = await import('./commands/session.js');\n return sessionHeartbeatCommand({ quiet: options.quiet });\n });\n\n// Detect squad command - useful for hooks\nprogram\n .command('detect-squad')\n .description('Detect current squad based on cwd (for use in hooks)')\n .action(async () => {\n const { detectSquadCommand } = await import('./commands/session.js');\n return detectSquadCommand();\n });\n\n// Auth commands\nprogram\n .command('login')\n .description('Log in to Squads (Pro & Enterprise)')\n .action(async () => {\n const { loginCommand } = await import('./commands/login.js');\n return loginCommand();\n });\n\nprogram\n .command('logout')\n .description('Log out from Squads')\n .action(async () => {\n const { logoutCommand } = await import('./commands/login.js');\n return logoutCommand();\n });\n\nprogram\n .command('whoami')\n .description('Show current logged in user')\n .action(async () => {\n const { whoamiCommand } = await import('./commands/login.js');\n return whoamiCommand();\n });\n\n// Eval command - agent readiness scoring\nregisterEvalCommand(program);\n\n// Deploy command group - push agents to platform\nregisterDeployCommand(program);\n\n// Cognition command group - business cognition engine\nregisterCognitionCommand(program);\n\n// Providers command - show LLM CLI availability for multi-LLM support\nprogram\n .command('providers')\n .description('Show available LLM CLI providers (claude, gemini, codex, etc.)')\n .option('-j, --json', 'Output as JSON')\n .action(async (options) => {\n const { providersCommand } = await import('./commands/providers.js');\n return providersCommand(options);\n });\n\n// Update command\nprogram\n .command('update')\n .description('Check for and install updates')\n .option('-y, --yes', 'Auto-confirm update without prompting')\n .option('-c, --check', 'Check for updates without installing')\n .action(async (options) => {\n const { updateCommand } = await import('./commands/update.js');\n return updateCommand(options);\n });\n\n// Version command (following npm/docker pattern)\nprogram\n .command('version')\n .description('Show version information')\n .action(() => {\n writeLine(`squads-cli ${version}`);\n });\n\n// ─── Removed commands (hidden from --help, show helpful message if invoked) ──\n\nprogram.command('stack', { hidden: true }).description('[removed]').action(removedCommand('stack', 'Infrastructure is managed via the cloud. Use: squads login'));\nprogram.command('cron', { hidden: true }).description('[removed]').action(removedCommand('cron', 'Use platform scheduler: squads trigger list'));\nprogram.command('tonight', { hidden: true }).description('[removed]').action(removedCommand('tonight', 'Use platform scheduler for overnight runs: squads autonomous start'));\nprogram.command('live', { hidden: true }).description('[removed]').action(removedCommand('live', 'Use: squads dash'));\nprogram.command('top', { hidden: true }).description('[removed]').action(removedCommand('top', 'Use: squads sessions'));\nprogram.command('watch', { hidden: true }).description('[removed]').action(removedCommand('watch', 'Use: watch -n 2 squads status'));\nprogram.command('setup', { hidden: true }).description('[removed]').action(removedCommand('setup', 'Use: squads init'));\nprogram.command('slack', { hidden: true }).description('[removed]').action(removedCommand('slack', 'Slack integration runs as a service, not a CLI command'));\nprogram.command('skill', { hidden: true }).description('[removed]').action(removedCommand('skill', 'Skills are defined in agent .md files. See: .agents/skills/'));\nprogram.command('baseline', { hidden: true }).description('[removed]').action(removedCommand('baseline', 'Use: squads dash --ceo'));\nprogram.command('permissions', { hidden: true }).description('[removed]').action(removedCommand('permissions', 'Permissions are defined in SQUAD.md approvals config'));\nprogram.command('issues', { hidden: true }).description('[removed]').action(removedCommand('issues', 'Use: gh issue list'));\nprogram.command('solve-issues', { hidden: true }).description('[removed]').action(removedCommand('solve-issues', 'Issue solving is agent behavior. Use: squads run engineering/issues-solver'));\nprogram.command('open-issues', { hidden: true }).description('[removed]').action(removedCommand('open-issues', 'Evaluators are agents. Use: squads run <squad>/<evaluator>'));\nprogram.command('workers', { hidden: true }).description('[removed]').action(removedCommand('workers', 'Use: squads sessions'));\n\n// ─── Error handling ──────────────────────────────────────────────────────────\n\n// Global error handler for uncaught exceptions\n// Provides helpful recovery steps instead of raw stack traces (#31)\nfunction handleError(error: unknown): void {\n const err = error instanceof Error ? error : new Error(String(error));\n\n // Check for common error types and provide helpful messages\n if (err.message.includes('ECONNREFUSED') || err.message.includes('fetch failed')) {\n console.error(chalk.red('\\nConnection error:'), err.message);\n console.error(chalk.dim('\\nCore commands (init, run, status, eval) work without cloud services.'));\n console.error(chalk.dim('If you need scheduling or telemetry:'));\n console.error(chalk.dim(' 1. Authenticate: squads login'));\n console.error(chalk.dim(' 2. Check services: squads health'));\n console.error(chalk.dim(' 3. Check your network connection'));\n } else if (err.message.includes('ENOENT')) {\n console.error(chalk.red('\\nFile not found:'), err.message);\n console.error(chalk.dim('\\nPossible fixes:'));\n console.error(chalk.dim(' 1. Make sure you are in the correct directory'));\n console.error(chalk.dim(' 2. Initialize the project: squads init'));\n } else if (err.message.includes('permission denied') || err.message.includes('EACCES')) {\n console.error(chalk.red('\\nPermission denied:'), err.message);\n console.error(chalk.dim('\\nPossible fixes:'));\n console.error(chalk.dim(' 1. Check file permissions'));\n console.error(chalk.dim(' 2. Avoid running with sudo if not needed'));\n } else if (err.message.includes('rate limit') || err.message.includes('429')) {\n console.error(chalk.red('\\nRate limit exceeded'));\n console.error(chalk.dim('\\nPossible fixes:'));\n console.error(chalk.dim(' 1. Wait a few minutes and try again'));\n console.error(chalk.dim(' 2. Check your API usage: squads dash'));\n } else {\n // Generic error with stack trace only in verbose mode\n console.error(chalk.red('\\nError:'), err.message);\n if (process.env.DEBUG || process.env.VERBOSE) {\n console.error(chalk.dim('\\nStack trace:'));\n console.error(chalk.dim(err.stack));\n } else {\n console.error(chalk.dim('\\nRun with DEBUG=1 for more details'));\n }\n }\n\n console.error(chalk.dim('\\nIf this persists, please report at:'));\n console.error(chalk.cyan(' https://github.com/agents-squads/squads-cli/issues\\n'));\n\n process.exit(1);\n}\n\n// Register global error handlers\nprocess.on('uncaughtException', handleError);\nprocess.on('unhandledRejection', handleError);\n\n// Parse arguments (use parseAsync to properly await async actions)\ntry {\n await program.parseAsync();\n} catch (error) {\n handleError(error);\n}\n","/**\n * Stack configuration loading from ~/.squadsrc\n * Extracted from stack.ts for use at CLI startup\n */\n\nimport { existsSync, readFileSync } from 'fs';\nimport { join } from 'path';\nimport { homedir } from 'os';\n\ninterface StackConfig {\n SQUADS_DATABASE_URL?: string;\n SQUADS_BRIDGE_URL: string;\n LANGFUSE_HOST: string;\n LANGFUSE_PUBLIC_KEY: string;\n LANGFUSE_SECRET_KEY: string;\n REDIS_URL?: string;\n}\n\nconst DEFAULT_CONFIG: StackConfig = {\n SQUADS_BRIDGE_URL: '',\n LANGFUSE_HOST: '',\n LANGFUSE_PUBLIC_KEY: '',\n LANGFUSE_SECRET_KEY: '',\n};\n\nconst CONFIG_PATH = join(homedir(), '.squadsrc');\n\n/**\n * Load stack configuration from ~/.squadsrc\n */\nexport function loadStackConfig(): Partial<StackConfig> | null {\n if (!existsSync(CONFIG_PATH)) {\n return null;\n }\n\n try {\n const content = readFileSync(CONFIG_PATH, 'utf-8');\n const config: Partial<StackConfig> = {};\n\n for (const line of content.split('\\n')) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith('#')) continue;\n\n const match = trimmed.match(/^export\\s+(\\w+)=[\"']?([^\"'\\n]*)[\"']?$/);\n if (match) {\n const [, key, value] = match;\n if (key in DEFAULT_CONFIG) {\n (config as Record<string, string>)[key] = value;\n }\n }\n }\n\n return config;\n } catch {\n return null;\n }\n}\n\n/**\n * Apply stack config to current process environment\n */\nexport function applyStackConfig(): void {\n const config = loadStackConfig();\n if (!config) return;\n\n for (const [key, value] of Object.entries(config)) {\n if (value && !process.env[key]) {\n process.env[key] = value;\n }\n }\n}\n","/**\n * squads orchestrate <squad> - Run squad with lead orchestration\n *\n * Starts the squad lead as a persistent session that:\n * - Spawns worker agents\n * - Reviews their outputs\n * - Coordinates multi-agent work\n *\n * Usage:\n * squads orchestrate intelligence\n * squads orchestrate cli --foreground\n */\n\nimport { Command } from 'commander';\nimport { spawn } from 'child_process';\nimport { existsSync, readFileSync, readdirSync } from 'fs';\nimport { join } from 'path';\nimport {\n initEventsDir,\n buildLeadPrompt,\n watchForEvents,\n} from '../lib/orchestration/lead-orchestrator.js';\nimport { resolveMcpConfigPath } from '../lib/mcp-config.js';\nimport { findSquadsDir, loadSquad } from '../lib/squad-parser.js';\nimport { findMemoryDir } from '../lib/memory.js';\nimport {\n colors as termColors,\n RESET,\n writeLine,\n} from '../lib/terminal.js';\n\n// Local alias to match existing usage (color names + reset)\nconst colors = {\n cyan: termColors.cyan,\n green: termColors.green,\n yellow: termColors.yellow,\n red: termColors.red,\n dim: termColors.dim,\n reset: RESET,\n};\n\n/**\n * Gather context for the lead agent (similar to run.ts gatherSquadContext)\n */\nfunction gatherLeadContext(squadName: string, leadAgent: string): string {\n const squadsDir = findSquadsDir();\n if (!squadsDir) return '';\n\n const memoryDir = findMemoryDir();\n const sections: string[] = [];\n\n // 1. SQUAD.md - full content for lead (they need everything)\n const squadFile = join(squadsDir, squadName, 'SQUAD.md');\n if (existsSync(squadFile)) {\n try {\n const squadContent = readFileSync(squadFile, 'utf-8');\n // Extract key sections\n const missionMatch = squadContent.match(/## Mission[\\s\\S]*?(?=\\n## |$)/i);\n const goalsMatch = squadContent.match(/## (?:Goals|Objectives)[\\s\\S]*?(?=\\n## |$)/i);\n\n let context = '';\n if (missionMatch) context += missionMatch[0] + '\\n';\n if (goalsMatch) context += goalsMatch[0] + '\\n';\n\n if (context) {\n sections.push(`## Squad Mission & Goals\\n${context.trim()}`);\n }\n } catch {\n // Ignore\n }\n }\n\n // 2. Lead's previous state\n if (memoryDir) {\n const stateFile = join(memoryDir, squadName, leadAgent, 'state.md');\n if (existsSync(stateFile)) {\n try {\n const stateContent = readFileSync(stateFile, 'utf-8');\n if (stateContent.trim()) {\n sections.push(`## Your Previous State\\n${stateContent.trim()}`);\n }\n } catch {\n // Ignore\n }\n }\n }\n\n if (sections.length === 0) return '';\n\n return `\\n# EXISTING CONTEXT\\nBuild on this - do NOT start from scratch:\\n\\n${sections.join('\\n\\n')}\\n`;\n}\n\ninterface OrchestrateOptions {\n foreground?: boolean;\n verbose?: boolean;\n timeout?: number;\n}\n\n/**\n * Find the lead agent for a squad\n */\nfunction findLeadAgent(squadDir: string): string | null {\n const files = readdirSync(squadDir).filter(f => f.endsWith('.md') && !f.startsWith('_'));\n\n // Look for *-lead.md or squad-lead.md\n const leadFile = files.find(f =>\n f.endsWith('-lead.md') ||\n f === 'lead.md' ||\n f.includes('lead')\n );\n\n return leadFile ? leadFile.replace('.md', '') : null;\n}\n\n/**\n * Get all non-lead agents in a squad\n */\nfunction getWorkerAgents(squadDir: string, leadAgent: string): string[] {\n const files = readdirSync(squadDir).filter(f =>\n f.endsWith('.md') &&\n !f.startsWith('_') &&\n !f.startsWith('README') &&\n f !== `${leadAgent}.md`\n );\n\n return files.map(f => f.replace('.md', ''));\n}\n\n/**\n * Main orchestrate command\n */\nasync function orchestrateSquad(\n squadName: string,\n options: OrchestrateOptions\n): Promise<void> {\n const projectRoot = process.cwd();\n const squadsDir = join(projectRoot, '.agents', 'squads');\n const squadDir = join(squadsDir, squadName);\n\n // Validate squad exists\n if (!existsSync(squadDir)) {\n writeLine(`${colors.red}Squad not found: ${squadName}${colors.reset}`);\n writeLine(`${colors.dim}Available: ${readdirSync(squadsDir).filter(f => !f.startsWith('_')).join(', ')}${colors.reset}`);\n process.exit(1);\n }\n\n // Find lead agent\n const leadAgent = findLeadAgent(squadDir);\n if (!leadAgent) {\n writeLine(`${colors.red}No lead agent found in squad ${squadName}${colors.reset}`);\n writeLine(`${colors.dim}Expected: *-lead.md or lead.md${colors.reset}`);\n process.exit(1);\n }\n\n // Get worker agents\n const workers = getWorkerAgents(squadDir, leadAgent);\n\n writeLine(`${colors.cyan}Orchestrating squad: ${squadName}${colors.reset}`);\n writeLine(` ${colors.green}Lead:${colors.reset} ${leadAgent}`);\n writeLine(` ${colors.green}Workers:${colors.reset} ${workers.length} agents`);\n if (options.verbose) {\n workers.forEach(w => writeLine(` - ${w}`));\n }\n\n // Initialize events directory\n const eventsDir = initEventsDir(projectRoot);\n writeLine(` ${colors.dim}Events: ${eventsDir}${colors.reset}`);\n\n // Get MCP config for the squad\n const squad = loadSquad(squadName);\n const mcpServers = squad?.context?.mcp || [];\n const mcpConfigPath = mcpServers.length > 0\n ? resolveMcpConfigPath(squadName, mcpServers)\n : join(process.env.HOME || '', '.claude.json');\n\n // Gather context for the lead\n const leadContext = gatherLeadContext(squadName, leadAgent);\n if (options.verbose && leadContext) {\n writeLine(` ${colors.dim}Context: ~${Math.ceil(leadContext.length / 4)} tokens${colors.reset}`);\n }\n\n // Build lead prompt with context\n const basePrompt = buildLeadPrompt({\n squad: squadName,\n lead: leadAgent,\n projectRoot,\n agents: workers,\n });\n\n // Inject context and add instructions\n const leadPrompt = `${basePrompt}\n${leadContext}\nTOOL PREFERENCE: Always prefer CLI tools over MCP servers:\n- Use \\`squads run\\` to spawn workers (not MCP)\n- Use \\`gh\\` for GitHub operations\n- Use \\`git\\` for version control\n- Only use MCP when CLI cannot do it\n\nIMPORTANT: When updating state.md, use ISO timestamps (e.g., 2026-01-23T02:45:00Z) not just dates.\nThis allows tracking multiple executions per day.`;\n\n // Session name\n const sessionName = `squads-lead-${squadName}-${Date.now()}`;\n\n if (options.foreground) {\n // Run lead in foreground (interactive)\n writeLine(`\\n${colors.cyan}Starting lead in foreground...${colors.reset}`);\n writeLine(`${colors.dim}Press Ctrl+C to stop${colors.reset}\\n`);\n\n const { CLAUDECODE: _cc, ...cleanOrcEnv } = process.env;\n const claude = spawn('claude', [\n '--permission-mode', 'bypassPermissions',\n '--mcp-config', mcpConfigPath,\n '--', leadPrompt,\n ], {\n stdio: 'inherit',\n env: {\n ...cleanOrcEnv,\n SQUADS_SQUAD: squadName,\n SQUADS_AGENT: leadAgent,\n SQUADS_ROLE: 'lead',\n SQUADS_EVENTS_DIR: eventsDir,\n },\n });\n\n claude.on('exit', (code) => {\n writeLine(`\\n${colors.cyan}Lead session ended (exit code: ${code})${colors.reset}`);\n });\n } else {\n // Run lead in tmux (background)\n const escapedPrompt = leadPrompt.replace(/'/g, \"'\\\\''\");\n\n const claudeCmd = `cd '${projectRoot}' && unset CLAUDECODE && claude --print --permission-mode bypassPermissions --mcp-config '${mcpConfigPath}' -- '${escapedPrompt}'; tmux kill-session -t ${sessionName} 2>/dev/null`;\n\n const tmux = spawn('tmux', [\n 'new-session',\n '-d',\n '-s', sessionName,\n '-x', '200',\n '-y', '50',\n '/bin/sh', '-c', claudeCmd,\n ], {\n stdio: 'ignore',\n detached: true,\n env: {\n ...process.env,\n SQUADS_SQUAD: squadName,\n SQUADS_AGENT: leadAgent,\n SQUADS_ROLE: 'lead',\n SQUADS_EVENTS_DIR: eventsDir,\n },\n });\n\n tmux.unref();\n\n writeLine(`\\n${colors.green}Lead started in background${colors.reset}`);\n writeLine(` ${colors.dim}Session: ${sessionName}${colors.reset}`);\n writeLine(` ${colors.dim}Attach: tmux attach -t ${sessionName}${colors.reset}`);\n\n // Watch for events if verbose\n if (options.verbose) {\n writeLine(`\\n${colors.cyan}Watching for worker events...${colors.reset}`);\n writeLine(`${colors.dim}Press Ctrl+C to stop watching (lead continues)${colors.reset}\\n`);\n\n const stopWatching = watchForEvents(eventsDir, (event) => {\n const icon = event.type === 'completed' ? '✓' : '✗';\n const color = event.type === 'completed' ? colors.green : colors.red;\n writeLine(`${color}${icon} ${event.agent}${colors.reset} ${colors.dim}(${event.type})${colors.reset}`);\n });\n\n process.on('SIGINT', () => {\n stopWatching();\n writeLine(`\\n${colors.dim}Stopped watching. Lead continues in tmux.${colors.reset}`);\n process.exit(0);\n });\n\n // Keep process alive\n await new Promise(() => {});\n }\n }\n}\n\n/**\n * Register the orchestrate command\n */\nexport function registerOrchestrateCommand(program: Command): void {\n program\n .command('orchestrate <squad>')\n .description('Run squad with lead agent orchestration')\n .option('-f, --foreground', 'Run lead in foreground (interactive)')\n .option('-v, --verbose', 'Show detailed output and watch events')\n .option('-t, --timeout <minutes>', 'Maximum runtime in minutes', '60')\n .action(async (squad: string, options: OrchestrateOptions) => {\n await orchestrateSquad(squad, options);\n });\n}\n\nexport default registerOrchestrateCommand;\n","/**\n * Lead Orchestrator - Persistent squad lead that coordinates workers\n *\n * Pattern:\n * 1. Lead agent runs as persistent session\n * 2. Lead spawns worker agents for specific tasks\n * 3. Workers complete and signal via events\n * 4. Lead reviews outputs and decides next steps\n */\n\nimport { existsSync, mkdirSync, writeFileSync, readFileSync, readdirSync, unlinkSync, watch } from 'fs';\nimport { join } from 'path';\n\nexport interface WorkerEvent {\n type: 'started' | 'completed' | 'failed' | 'output';\n squad: string;\n agent: string;\n executionId: string;\n timestamp: string;\n exitCode?: number;\n outputPath?: string;\n summary?: string;\n error?: string;\n}\n\nexport interface OrchestratorConfig {\n projectRoot: string;\n squad: string;\n lead: string;\n eventsDir: string;\n onWorkerComplete?: (event: WorkerEvent) => void;\n}\n\n/**\n * Events directory structure:\n * .agents/events/\n * pending/ - New events waiting for lead to process\n * processed/ - Events that lead has reviewed\n */\nexport function initEventsDir(projectRoot: string): string {\n const eventsDir = join(projectRoot, '.agents', 'events');\n const pendingDir = join(eventsDir, 'pending');\n const processedDir = join(eventsDir, 'processed');\n\n [eventsDir, pendingDir, processedDir].forEach(dir => {\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n }\n });\n\n return eventsDir;\n}\n\n/**\n * Worker signals completion by writing event file\n */\nexport function signalWorkerComplete(config: {\n eventsDir: string;\n squad: string;\n agent: string;\n executionId: string;\n exitCode: number;\n outputPath?: string;\n summary?: string;\n}): void {\n const event: WorkerEvent = {\n type: config.exitCode === 0 ? 'completed' : 'failed',\n squad: config.squad,\n agent: config.agent,\n executionId: config.executionId,\n timestamp: new Date().toISOString(),\n exitCode: config.exitCode,\n outputPath: config.outputPath,\n summary: config.summary,\n };\n\n const filename = `${config.executionId}-${config.agent}.json`;\n const filepath = join(config.eventsDir, 'pending', filename);\n writeFileSync(filepath, JSON.stringify(event, null, 2));\n}\n\n/**\n * Read pending events for lead to review\n */\nexport function getPendingEvents(eventsDir: string): WorkerEvent[] {\n const pendingDir = join(eventsDir, 'pending');\n if (!existsSync(pendingDir)) return [];\n\n const files = readdirSync(pendingDir).filter(f => f.endsWith('.json'));\n return files.map(f => {\n const content = readFileSync(join(pendingDir, f), 'utf-8');\n return JSON.parse(content) as WorkerEvent;\n });\n}\n\n/**\n * Mark event as processed (move to processed dir)\n */\nexport function markEventProcessed(eventsDir: string, event: WorkerEvent): void {\n const filename = `${event.executionId}-${event.agent}.json`;\n const pendingPath = join(eventsDir, 'pending', filename);\n const processedPath = join(eventsDir, 'processed', filename);\n\n if (existsSync(pendingPath)) {\n const content = readFileSync(pendingPath, 'utf-8');\n writeFileSync(processedPath, content);\n unlinkSync(pendingPath);\n }\n}\n\n/**\n * Generate shell command for worker that signals completion\n */\nexport function buildWorkerCommand(config: {\n projectRoot: string;\n squad: string;\n agent: string;\n executionId: string;\n prompt: string;\n mcpConfigPath: string;\n sessionName: string;\n}): string {\n const eventsDir = join(config.projectRoot, '.agents', 'events');\n const escapedPrompt = config.prompt.replace(/'/g, \"'\\\\''\");\n\n // Worker command that:\n // 1. Runs claude with acceptEdits (pre-configured permissions)\n // 2. Captures exit code\n // 3. Signals completion via event file\n // 4. Kills tmux session\n return `\ncd '${config.projectRoot}' && \\\\\nunset CLAUDECODE && claude --print --permission-mode acceptEdits --mcp-config '${config.mcpConfigPath}' -- '${escapedPrompt}'; \\\\\nEXIT_CODE=$?; \\\\\necho '{\"type\":\"'$([ $EXIT_CODE -eq 0 ] && echo completed || echo failed)'\",\"squad\":\"${config.squad}\",\"agent\":\"${config.agent}\",\"executionId\":\"${config.executionId}\",\"timestamp\":\"'$(date -u +%Y-%m-%dT%H:%M:%SZ)'\",\"exitCode\":'$EXIT_CODE'}' > '${eventsDir}/pending/${config.executionId}-${config.agent}.json'; \\\\\ntmux kill-session -t ${config.sessionName} 2>/dev/null\n`.trim().replace(/\\n/g, ' ');\n}\n\n/**\n * Build the lead agent prompt that includes orchestration capabilities\n */\nexport function buildLeadPrompt(config: {\n squad: string;\n lead: string;\n projectRoot: string;\n agents: string[];\n}): string {\n // Keep prompt short - Claude will read detailed instructions from files\n return `You are ${config.lead}, orchestrating the ${config.squad} squad.\n\nRead .agents/squads/${config.squad}/SQUAD.md for goals.\nRead .agents/squads/${config.squad}/${config.lead}.md for your instructions.\n\nWorkers: ${config.agents.slice(0, 5).join(', ')}${config.agents.length > 5 ? ` (+${config.agents.length - 5} more)` : ''}\n\nTo spawn workers: squads run ${config.squad}/<agent> --execute --background\nCheck events: ls .agents/events/pending/\nReview output: cat .agents/memory/${config.squad}/<agent>/state.md\n\nWhen done: git add .agents/ && git commit -m \"feat(${config.squad}): orchestration complete\" && git push && /exit`.trim();\n}\n\n/**\n * Watch for worker completion events (for real-time notification)\n */\nexport function watchForEvents(\n eventsDir: string,\n callback: (event: WorkerEvent) => void\n): () => void {\n const pendingDir = join(eventsDir, 'pending');\n\n const watcher = watch(pendingDir, (eventType, filename) => {\n if (eventType === 'rename' && filename?.endsWith('.json')) {\n const filepath = join(pendingDir, filename);\n if (existsSync(filepath)) {\n try {\n const content = readFileSync(filepath, 'utf-8');\n const event = JSON.parse(content) as WorkerEvent;\n callback(event);\n } catch {\n // Ignore parse errors\n }\n }\n }\n });\n\n // Return cleanup function\n return () => watcher.close();\n}\n","/**\n * squads trigger - Manage smart triggers\n *\n * Commands:\n * squads trigger list [squad] List triggers\n * squads trigger sync Sync SQUAD.md triggers to scheduler\n * squads trigger fire <name> Manually fire a trigger\n * squads trigger enable <name> Enable a trigger\n * squads trigger disable <name> Disable a trigger\n * squads trigger status Show scheduler status\n */\n\nimport { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport { writeLine } from \"../lib/terminal.js\";\nimport { getApiUrl } from \"../lib/env-config.js\";\n\nconst API_URL = getApiUrl();\n\ninterface Trigger {\n id: string;\n name: string;\n squad: string;\n agent: string | null;\n enabled: boolean;\n priority: number;\n cooldown: string;\n last_fired: string | null;\n fire_count: number;\n}\n\ninterface SchedulerStats {\n triggers: {\n total: number;\n enabled: number;\n fired_24h: number;\n };\n executions_24h: {\n total_24h: number;\n completed: number;\n failed: number;\n running: number;\n queued: number;\n };\n}\n\nasync function fetchScheduler<T>(\n path: string,\n options?: RequestInit\n): Promise<T> {\n const res = await fetch(`${API_URL}${path}`, {\n ...options,\n headers: {\n \"Content-Type\": \"application/json\",\n ...options?.headers,\n },\n });\n\n if (!res.ok) {\n const error = await res.text();\n throw new Error(`Scheduler error: ${res.status} ${error}`);\n }\n\n return res.json() as T;\n}\n\nasync function listTriggers(squad?: string): Promise<void> {\n let triggers: Trigger[];\n\n try {\n const params = squad ? `?squad=${squad}` : \"\";\n triggers = await fetchScheduler<Trigger[]>(`/triggers${params}`);\n } catch (error: unknown) {\n // Check for connection refused (scheduler offline)\n const isConnectionError = error instanceof Error &&\n (error.cause?.toString().includes('ECONNREFUSED') ||\n error.message.includes('fetch failed'));\n\n if (isConnectionError) {\n console.error(chalk.red(\"\\n Scheduler not running\\n\"));\n writeLine(chalk.gray(\" The trigger system requires the local stack to be running.\\n\"));\n writeLine(` ${chalk.cyan(\"$ squads stack start\")} Start the local stack`);\n writeLine(` ${chalk.cyan(\"$ squads stack status\")} Check stack status\\n`);\n return;\n }\n\n // Re-throw unexpected errors\n throw error;\n }\n\n if (triggers.length === 0) {\n writeLine(chalk.gray(\"No triggers found\"));\n return;\n }\n\n writeLine(chalk.bold(\"\\nSmart Triggers\\n\"));\n\n const grouped = triggers.reduce(\n (acc, t) => {\n (acc[t.squad] = acc[t.squad] || []).push(t);\n return acc;\n },\n {} as Record<string, Trigger[]>\n );\n\n for (const [squadName, squadTriggers] of Object.entries(grouped)) {\n writeLine(chalk.cyan(` ${squadName}`));\n\n for (const t of squadTriggers) {\n const status = t.enabled ? chalk.green(\"●\") : chalk.gray(\"○\");\n const agent = t.agent ? `/${t.agent}` : \"\";\n const fires = t.fire_count > 0 ? chalk.gray(` (${t.fire_count}x)`) : \"\";\n\n writeLine(\n ` ${status} ${t.name}${chalk.gray(agent)} P${t.priority}${fires}`\n );\n }\n writeLine();\n }\n}\n\nasync function syncTriggers(): Promise<void> {\n writeLine(chalk.gray(\"Syncing triggers from SQUAD.md files...\\n\"));\n\n try {\n const result = await fetchScheduler<{ synced: number; triggers: string[]; errors: Array<{ name: string; error: string }> }>(\n \"/triggers/sync\",\n { method: \"POST\" }\n );\n\n if (result.errors && result.errors.length > 0) {\n writeLine(chalk.yellow(`Synced with ${result.errors.length} error(s):`));\n for (const err of result.errors) {\n writeLine(chalk.red(` - ${err.name}: ${err.error}`));\n }\n }\n\n writeLine(chalk.green(`Synced ${result.synced} trigger(s)`));\n if (result.triggers && result.triggers.length > 0) {\n for (const name of result.triggers) {\n writeLine(chalk.gray(` - ${name}`));\n }\n }\n } catch (error: unknown) {\n const isConnectionError = error instanceof Error &&\n (error.cause?.toString().includes('ECONNREFUSED') ||\n error.message.includes('fetch failed'));\n\n if (isConnectionError) {\n console.error(chalk.red(\"\\n API not running\\n\"));\n writeLine(chalk.gray(\" The sync command requires the API to be running.\\n\"));\n writeLine(` ${chalk.cyan(\"$ squads stack start\")} Start the local stack`);\n writeLine(` ${chalk.cyan(\"$ squads health\")} Check service status\\n`);\n return;\n }\n\n const message = error instanceof Error ? error.message : String(error);\n console.error(chalk.red(\"Sync failed:\"), message);\n }\n}\n\nasync function fireTrigger(name: string): Promise<void> {\n // Find trigger by name\n const triggers = await fetchScheduler<Trigger[]>(`/triggers`);\n const trigger = triggers.find((t) => t.name === name);\n\n if (!trigger) {\n console.error(chalk.red(`Trigger '${name}' not found`));\n return;\n }\n\n writeLine(\n chalk.gray(`Firing ${trigger.squad}/${trigger.agent || \"*\"}...`)\n );\n\n interface Execution {\n id: string;\n status: string;\n }\n\n const execution = await fetchScheduler<Execution>(\n `/triggers/${trigger.id}/fire`,\n { method: \"POST\" }\n );\n\n writeLine(chalk.green(`✓ Queued execution ${execution.id.slice(0, 8)}`));\n}\n\nasync function toggleTrigger(name: string, enable: boolean): Promise<void> {\n const triggers = await fetchScheduler<Trigger[]>(`/triggers`);\n const trigger = triggers.find((t) => t.name === name);\n\n if (!trigger) {\n console.error(chalk.red(`Trigger '${name}' not found`));\n return;\n }\n\n await fetchScheduler(`/triggers/${trigger.id}`, {\n method: \"PATCH\",\n body: JSON.stringify({ enabled: enable }),\n });\n\n const status = enable ? chalk.green(\"enabled\") : chalk.gray(\"disabled\");\n writeLine(`${trigger.name} ${status}`);\n}\n\nasync function showStatus(): Promise<void> {\n try {\n const stats = await fetchScheduler<SchedulerStats>(\"/stats\");\n\n writeLine(chalk.bold(\"\\nScheduler Status\\n\"));\n\n writeLine(chalk.cyan(\" Triggers\"));\n writeLine(` Total: ${stats.triggers.total}`);\n writeLine(` Enabled: ${chalk.green(stats.triggers.enabled)}`);\n writeLine(` Fired 24h: ${stats.triggers.fired_24h}`);\n\n writeLine(chalk.cyan(\"\\n Executions (24h)\"));\n writeLine(` Completed: ${chalk.green(stats.executions_24h.completed)}`);\n writeLine(` Failed: ${chalk.red(stats.executions_24h.failed)}`);\n writeLine(` Running: ${chalk.yellow(stats.executions_24h.running)}`);\n writeLine(` Queued: ${stats.executions_24h.queued}`);\n writeLine();\n } catch {\n console.error(chalk.red(\"Scheduler not running or unreachable\"));\n writeLine(chalk.gray(` Expected at: ${API_URL}`));\n }\n}\n\nexport function registerTriggerCommand(program: Command): void {\n const trigger = program\n .command(\"trigger\")\n .description(\"Manage smart triggers\")\n .action(() => { trigger.outputHelp(); });\n\n trigger\n .command(\"list [squad]\")\n .description(\"List triggers\")\n .action(async (squad?: string) => {\n await listTriggers(squad);\n });\n\n trigger\n .command(\"sync\")\n .description(\"Sync SQUAD.md triggers to scheduler\")\n .action(async () => {\n await syncTriggers();\n });\n\n trigger\n .command(\"fire <name>\")\n .description(\"Manually fire a trigger\")\n .action(async (name: string) => {\n await fireTrigger(name);\n });\n\n trigger\n .command(\"enable <name>\")\n .description(\"Enable a trigger\")\n .action(async (name: string) => {\n await toggleTrigger(name, true);\n });\n\n trigger\n .command(\"disable <name>\")\n .description(\"Disable a trigger\")\n .action(async (name: string) => {\n await toggleTrigger(name, false);\n });\n\n trigger\n .command(\"status\")\n .description(\"Show scheduler status\")\n .action(async () => {\n await showStatus();\n });\n}\n","/**\n * squads autonomous - Local scheduling daemon for autonomous agent execution\n *\n * Commands:\n * squads autonomous start Start the daemon (detached background process)\n * squads autonomous stop Stop the daemon\n * squads autonomous status Show daemon status, running agents, next runs\n *\n * The daemon reads SQUAD.md routines, evaluates cron schedules, and spawns\n * agents via `squads run --background`. No database. No Redis. Just a process.\n *\n * Architecture: Layer 2 in docs/ARCHITECTURE.md\n */\n\nimport { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport { writeLine } from \"../lib/terminal.js\";\nimport {\n existsSync,\n readFileSync,\n writeFileSync,\n unlinkSync,\n readdirSync,\n mkdirSync,\n appendFileSync,\n openSync,\n} from \"fs\";\nimport { join } from \"path\";\nimport { homedir } from \"os\";\nimport { spawn, execSync } from \"child_process\";\nimport { findSquadsDir, listSquads, Routine } from \"../lib/squad-parser.js\";\nimport {\n cronMatches,\n getNextCronRun,\n parseCooldown,\n} from \"../lib/cron.js\";\n\n// Daemon state directory — persistent across runs\nconst DAEMON_DIR = join(homedir(), \".squads\");\nconst PID_FILE = join(DAEMON_DIR, \"autonomous.pid\");\nconst DAEMON_LOG = join(DAEMON_DIR, \"autonomous.log\");\nconst PAUSE_FILE = join(DAEMON_DIR, \"autonomous.paused\");\nconst COOLDOWN_FILE = join(DAEMON_DIR, \"autonomous.cooldowns.json\");\n\n// Configuration from env vars (all optional)\nconst MAX_CONCURRENT = parseInt(process.env.SQUADS_MAX_CONCURRENT || \"5\");\nconst AGENT_TIMEOUT_MIN = parseInt(process.env.SQUADS_AGENT_TIMEOUT || \"30\");\nconst EVAL_INTERVAL_SEC = parseInt(process.env.SQUADS_EVAL_INTERVAL || \"60\");\n\ninterface RoutineWithSquad extends Routine {\n squad: string;\n}\n\n// =============================================================================\n// Cron Evaluator - now imported from lib/cron.ts\n// =============================================================================\n// Functions: cronMatches, getNextCronRun, parseCooldown are now in lib/cron.ts\n\n// =============================================================================\n// Routine Collection (from SQUAD.md files)\n// =============================================================================\n\n/**\n * Parse routines from SQUAD.md YAML blocks\n */\nfunction parseRoutinesFromFile(filePath: string): Routine[] {\n if (!existsSync(filePath)) return [];\n\n const content = readFileSync(filePath, \"utf-8\");\n const routines: Routine[] = [];\n\n const routinesMatch = content.match(\n /##+ \\w*\\s*Routines[\\s\\S]*?```yaml\\s*\\n([\\s\\S]*?)```/i\n );\n if (!routinesMatch) return [];\n\n let yamlContent = routinesMatch[1];\n yamlContent = yamlContent.replace(/^\\s*routines:\\s*\\n?/, \"\");\n yamlContent = \"\\n\" + yamlContent.trim();\n\n const routineBlocks = yamlContent.split(/\\n\\s*- name:\\s*/);\n\n for (const block of routineBlocks) {\n if (!block.trim()) continue;\n\n const lines = block.split(\"\\n\");\n const name = lines[0].trim();\n if (!name) continue;\n\n const scheduleMatch = block.match(/schedule:\\s*[\"']?([^\"'\\n#]+)/);\n const agentsMatch = block.match(/agents:\\s*\\[(.*?)\\]/);\n const modelMatch = block.match(/model:\\s*(\\w+)/);\n const enabledMatch = block.match(/enabled:\\s*(true|false)/);\n const priorityMatch = block.match(/priority:\\s*(\\d+)/);\n const cooldownMatch = block.match(\n /cooldown:\\s*[\"']?([^\"'\\n]+)[\"']?/\n );\n\n if (scheduleMatch && agentsMatch) {\n const agents = agentsMatch[1]\n .split(\",\")\n .map((a) => a.trim().replace(/[\"']/g, \"\"))\n .filter(Boolean);\n\n routines.push({\n name,\n schedule: scheduleMatch[1].trim().replace(/[\"']/g, \"\"),\n agents,\n model: modelMatch\n ? (modelMatch[1] as \"opus\" | \"sonnet\" | \"haiku\")\n : undefined,\n enabled: enabledMatch ? enabledMatch[1] === \"true\" : true,\n priority: priorityMatch ? parseInt(priorityMatch[1]) : undefined,\n cooldown: cooldownMatch ? cooldownMatch[1].trim() : undefined,\n });\n }\n }\n\n return routines;\n}\n\nfunction collectRoutines(): RoutineWithSquad[] {\n const squadsDir = findSquadsDir();\n if (!squadsDir) return [];\n\n const routines: RoutineWithSquad[] = [];\n const squadNames = listSquads(squadsDir);\n\n for (const name of squadNames) {\n const squadFile = join(squadsDir, name, \"SQUAD.md\");\n const squadRoutines = parseRoutinesFromFile(squadFile);\n\n for (const routine of squadRoutines) {\n routines.push({ ...routine, squad: name });\n }\n }\n\n return routines;\n}\n\n// =============================================================================\n// PID File Management\n// =============================================================================\n\n/**\n * Find the .agents/logs directory (relative to project root)\n */\nfunction getLogsDir(): string | null {\n const squadsDir = findSquadsDir();\n if (!squadsDir) return null;\n // squadsDir is .agents/squads, logs are at .agents/logs\n return join(squadsDir, \"..\", \"logs\");\n}\n\n/**\n * Count currently running agents by checking PID files\n */\nfunction getRunningAgents(): {\n squad: string;\n agent: string;\n pid: number;\n startedAt: number;\n logFile: string;\n}[] {\n const logsDir = getLogsDir();\n if (!logsDir || !existsSync(logsDir)) return [];\n\n const running: {\n squad: string;\n agent: string;\n pid: number;\n startedAt: number;\n logFile: string;\n }[] = [];\n\n let squadDirs: string[];\n try {\n squadDirs = readdirSync(logsDir);\n } catch {\n return [];\n }\n\n for (const squadDir of squadDirs) {\n const squadPath = join(logsDir, squadDir);\n let files: string[];\n try {\n files = readdirSync(squadPath);\n } catch {\n continue;\n }\n\n for (const file of files) {\n if (!file.endsWith(\".pid\")) continue;\n\n const pidPath = join(squadPath, file);\n try {\n const pid = parseInt(readFileSync(pidPath, \"utf-8\").trim());\n if (isNaN(pid)) continue;\n\n // Check if process is alive\n try {\n process.kill(pid, 0);\n } catch {\n // Process dead — clean up orphan PID file\n try {\n unlinkSync(pidPath);\n } catch {\n /* ignore */\n }\n continue;\n }\n\n // Extract agent name and timestamp from filename: agent-timestamp.pid\n const match = file.match(/^(.+)-(\\d+)\\.pid$/);\n if (!match) continue;\n\n const agentName = match[1];\n const timestamp = parseInt(match[2]);\n\n running.push({\n squad: squadDir,\n agent: agentName,\n pid,\n startedAt: timestamp,\n logFile: pidPath.replace(\".pid\", \".log\"),\n });\n } catch {\n continue;\n }\n }\n }\n\n return running;\n}\n\n/**\n * Kill an agent by PID and clean up its PID file\n */\nfunction killAgent(pid: number, pidFile: string, signal: NodeJS.Signals = \"SIGTERM\"): boolean {\n try {\n process.kill(pid, signal);\n // Give it a moment, then check if it's dead\n if (signal === \"SIGTERM\") {\n setTimeout(() => {\n try {\n process.kill(pid, 0); // Still alive?\n process.kill(pid, \"SIGKILL\"); // Force kill\n } catch {\n /* already dead */\n }\n }, 5000);\n }\n try {\n unlinkSync(pidFile);\n } catch {\n /* ignore */\n }\n return true;\n } catch {\n return false;\n }\n}\n\n// =============================================================================\n// Cooldown Parsing - now imported from lib/cron.ts\n// =============================================================================\n// Function: parseCooldown is now in lib/cron.ts\n\n// =============================================================================\n// Daemon Core\n// =============================================================================\n\n/**\n * Log a message to the daemon log file with timestamp\n */\nfunction daemonLog(msg: string): void {\n const ts = new Date().toISOString();\n const line = `[${ts}] ${msg}\\n`;\n try {\n appendFileSync(DAEMON_LOG, line);\n } catch {\n // Can't log — ignore\n }\n}\n\n// =============================================================================\n// Pause / Resume — quota awareness\n// =============================================================================\n\n/**\n * Check if the daemon is paused (e.g., quota exhausted).\n * The daemon stays running but stops spawning new agents.\n */\nfunction isPaused(): { paused: boolean; reason?: string; since?: string } {\n if (!existsSync(PAUSE_FILE)) return { paused: false };\n try {\n const data = JSON.parse(readFileSync(PAUSE_FILE, \"utf-8\"));\n return { paused: true, reason: data.reason, since: data.since };\n } catch {\n return { paused: true, reason: \"unknown\" };\n }\n}\n\n/**\n * Pause the daemon. It stays running but won't spawn new agents.\n * Use for quota limits, maintenance, or manual override.\n */\nfunction pauseDaemon(reason: string): void {\n if (!existsSync(DAEMON_DIR)) {\n mkdirSync(DAEMON_DIR, { recursive: true });\n }\n writeFileSync(PAUSE_FILE, JSON.stringify({\n reason,\n since: new Date().toISOString(),\n }));\n daemonLog(`PAUSED: ${reason}`);\n}\n\n/**\n * Resume the daemon after a pause.\n */\nfunction resumeDaemon(): void {\n try {\n unlinkSync(PAUSE_FILE);\n } catch {\n /* not paused */\n }\n daemonLog(\"RESUMED\");\n}\n\n// =============================================================================\n// Persistent Cooldown State — survives daemon restarts\n// =============================================================================\n\nfunction loadCooldowns(): Map<string, number> {\n const map = new Map<string, number>();\n if (!existsSync(COOLDOWN_FILE)) return map;\n try {\n const data = JSON.parse(readFileSync(COOLDOWN_FILE, \"utf-8\"));\n for (const [key, ts] of Object.entries(data)) {\n if (typeof ts === \"number\") map.set(key, ts);\n }\n } catch {\n /* corrupt file — start fresh */\n }\n return map;\n}\n\nfunction saveCooldowns(map: Map<string, number>): void {\n try {\n const obj: Record<string, number> = {};\n for (const [key, ts] of map) {\n obj[key] = ts;\n }\n writeFileSync(COOLDOWN_FILE, JSON.stringify(obj));\n } catch {\n /* best effort */\n }\n}\n\n/**\n * The main daemon loop. Runs as a long-lived process.\n * This is the COO's operating system — always on, managing the workforce.\n */\nasync function daemonLoop(): Promise<void> {\n daemonLog(\"Daemon started\");\n\n // Load persistent cooldown state (survives restarts)\n const lastSpawned = loadCooldowns();\n\n // Track consecutive spawn failures for auto-pause (quota detection)\n let consecutiveFailures = 0;\n const AUTO_PAUSE_THRESHOLD = 5;\n\n const tick = async () => {\n try {\n // Check if paused (quota, maintenance, manual)\n const pauseStatus = isPaused();\n if (pauseStatus.paused) {\n // Still enforce timeouts on running agents even when paused\n const running = getRunningAgents();\n for (const agent of running) {\n const runtimeMin = (Date.now() - agent.startedAt) / 60000;\n if (runtimeMin > AGENT_TIMEOUT_MIN) {\n daemonLog(\n `TIMEOUT: ${agent.squad}/${agent.agent} (PID ${agent.pid}, ${Math.round(runtimeMin)}min)`\n );\n const pidFile = agent.logFile.replace(\".log\", \".pid\");\n killAgent(agent.pid, pidFile);\n }\n }\n return; // Don't spawn new agents while paused\n }\n\n const now = new Date();\n now.setSeconds(0, 0); // Round to minute\n\n // 1. Collect enabled routines\n const routines = collectRoutines().filter((r) => r.enabled !== false);\n\n // 2. Check running agents\n const running = getRunningAgents();\n\n // 3. Timeout enforcement\n for (const agent of running) {\n const runtimeMin = (Date.now() - agent.startedAt) / 60000;\n if (runtimeMin > AGENT_TIMEOUT_MIN) {\n daemonLog(\n `TIMEOUT: ${agent.squad}/${agent.agent} (PID ${agent.pid}, ${Math.round(runtimeMin)}min)`\n );\n const pidFile = agent.logFile.replace(\".log\", \".pid\");\n killAgent(agent.pid, pidFile);\n }\n }\n\n // 4. Evaluate cron schedules\n for (const routine of routines) {\n if (!cronMatches(routine.schedule, now)) continue;\n\n for (const agentName of routine.agents) {\n const key = `${routine.squad}/${agentName}`;\n\n // Cooldown check (persistent across restarts)\n if (routine.cooldown) {\n const last = lastSpawned.get(key);\n const cooldownMs = parseCooldown(routine.cooldown);\n if (last && Date.now() - last < cooldownMs) {\n continue;\n }\n }\n\n // Already running check\n const alreadyRunning = running.some(\n (r) => r.squad === routine.squad && r.agent === agentName\n );\n if (alreadyRunning) continue;\n\n // Concurrency check\n const currentRunning = getRunningAgents().length;\n if (currentRunning >= MAX_CONCURRENT) {\n daemonLog(\n `SKIP: ${key} — concurrency limit (${currentRunning}/${MAX_CONCURRENT})`\n );\n continue;\n }\n\n // Spawn the agent\n daemonLog(`SPAWN: ${key} (routine: ${routine.name})`);\n try {\n const modelFlag = routine.model ? `--model ${routine.model}` : \"\";\n execSync(\n `squads run ${routine.squad}/${agentName} --background ${modelFlag} --trigger scheduled`,\n {\n cwd: process.cwd(),\n stdio: \"ignore\",\n timeout: 10000, // 10s to spawn\n env: {\n ...process.env,\n CLAUDECODE: \"\", // Allow nested claude sessions\n },\n }\n );\n lastSpawned.set(key, Date.now());\n saveCooldowns(lastSpawned); // Persist to disk\n consecutiveFailures = 0; // Reset failure counter\n daemonLog(`SPAWNED: ${key}`);\n } catch (err) {\n consecutiveFailures++;\n daemonLog(`ERROR: Failed to spawn ${key} (${consecutiveFailures}/${AUTO_PAUSE_THRESHOLD}): ${err}`);\n\n // Auto-pause after repeated failures (likely quota exhausted)\n if (consecutiveFailures >= AUTO_PAUSE_THRESHOLD) {\n pauseDaemon(`Auto-paused: ${consecutiveFailures} consecutive spawn failures (likely quota exhausted)`);\n daemonLog(`AUTO-PAUSED: ${consecutiveFailures} consecutive failures. Run 'squads autonomous resume' when quota resets.`);\n }\n }\n }\n }\n } catch (err) {\n daemonLog(`TICK ERROR: ${err}`);\n }\n };\n\n // Run immediately, then on interval\n await tick();\n setInterval(tick, EVAL_INTERVAL_SEC * 1000);\n\n // Clean shutdown\n const cleanup = (signal: string) => {\n daemonLog(`Received ${signal}, shutting down`);\n saveCooldowns(lastSpawned); // Persist cooldowns before exit\n try {\n unlinkSync(PID_FILE);\n } catch {\n /* ignore */\n }\n process.exit(0);\n };\n\n process.on(\"SIGTERM\", () => cleanup(\"SIGTERM\"));\n process.on(\"SIGINT\", () => cleanup(\"SIGINT\"));\n}\n\n// =============================================================================\n// Daemon Lifecycle (check/start/stop)\n// =============================================================================\n\nfunction isRunning(): { running: boolean; pid?: number } {\n if (!existsSync(PID_FILE)) return { running: false };\n\n const pid = parseInt(readFileSync(PID_FILE, \"utf-8\").trim());\n if (isNaN(pid)) return { running: false };\n\n try {\n process.kill(pid, 0);\n return { running: true, pid };\n } catch {\n // Stale PID file\n try {\n unlinkSync(PID_FILE);\n } catch {\n /* ignore */\n }\n return { running: false };\n }\n}\n\nasync function startScheduler(): Promise<void> {\n const status = isRunning();\n if (status.running) {\n writeLine(\n chalk.yellow(`Daemon already running (PID ${status.pid})`)\n );\n writeLine(chalk.gray(` Log: ${DAEMON_LOG}`));\n return;\n }\n\n // Ensure daemon directory exists\n if (!existsSync(DAEMON_DIR)) {\n mkdirSync(DAEMON_DIR, { recursive: true });\n }\n\n const routines = collectRoutines().filter((r) => r.enabled !== false);\n if (routines.length === 0) {\n writeLine(chalk.yellow(\"No enabled routines found.\"));\n writeLine(\n chalk.gray(\"Add routines to SQUAD.md files under ### Routines section.\")\n );\n return;\n }\n\n // Check if we're being invoked as the daemon itself (via env var)\n if (process.env.SQUADS_DAEMON === \"1\") {\n // We ARE the daemon — run the loop\n writeFileSync(PID_FILE, process.pid.toString());\n await daemonLoop();\n // daemonLoop never returns (infinite setInterval)\n // Keep the event loop alive\n await new Promise(() => {});\n return;\n }\n\n // Spawn a detached daemon process\n // Use SQUADS_DAEMON env var instead of --daemon CLI flag to avoid\n // Commander.js rejecting the unknown option and silently exiting\n\n // Redirect child stdout/stderr to daemon log for diagnosability\n if (!existsSync(DAEMON_LOG)) {\n writeFileSync(DAEMON_LOG, \"\");\n }\n const logFd = openSync(DAEMON_LOG, \"a\");\n\n const child = spawn(\n process.execPath, // node\n [process.argv[1], \"autonomous\", \"start\"],\n {\n cwd: process.cwd(),\n detached: true,\n stdio: [\"ignore\", logFd, logFd],\n env: { ...process.env, SQUADS_DAEMON: \"1\" },\n }\n );\n child.unref();\n\n // Wait for PID file to appear (2s for slower systems)\n await new Promise((resolve) => setTimeout(resolve, 2000));\n\n const check = isRunning();\n if (check.running) {\n writeLine(chalk.green(`\\n Daemon started (PID ${check.pid})`));\n } else {\n writeLine(chalk.red(\"\\n Daemon failed to start. Check log:\"));\n writeLine(chalk.gray(` $ tail -20 ${DAEMON_LOG}`));\n }\n\n writeLine(chalk.gray(` Log: ${DAEMON_LOG}`));\n writeLine(chalk.gray(` Config: SQUAD.md routines\\n`));\n\n // Show what's scheduled\n writeLine(chalk.cyan(\" Routines\"));\n const bySquad = new Map<string, RoutineWithSquad[]>();\n for (const r of routines) {\n if (!bySquad.has(r.squad)) bySquad.set(r.squad, []);\n bySquad.get(r.squad)!.push(r);\n }\n\n for (const [squad, squadRoutines] of bySquad) {\n for (const r of squadRoutines) {\n const next = getNextCronRun(r.schedule);\n const timeStr = next.toLocaleTimeString([], {\n hour: \"2-digit\",\n minute: \"2-digit\",\n });\n writeLine(\n ` ${chalk.green(\"●\")} ${chalk.cyan(squad)}/${r.name} ${chalk.gray(r.schedule)} ${chalk.gray(`→ ${timeStr}`)}`\n );\n }\n }\n\n writeLine(\n chalk.gray(`\\n ${routines.length} routines, max ${MAX_CONCURRENT} concurrent`)\n );\n writeLine(chalk.gray(\" Stop: squads autonomous stop\"));\n writeLine(chalk.gray(` Monitor: tail -f ${DAEMON_LOG}\\n`));\n}\n\nfunction stopScheduler(): void {\n const status = isRunning();\n\n if (!status.running) {\n writeLine(chalk.gray(\"Daemon not running\"));\n return;\n }\n\n try {\n process.kill(status.pid!, \"SIGTERM\");\n try {\n unlinkSync(PID_FILE);\n } catch {\n /* ignore */\n }\n writeLine(chalk.green(`Daemon stopped (PID ${status.pid})`));\n } catch (error) {\n console.error(chalk.red(`Failed to stop daemon: ${error}`));\n }\n}\n\nasync function showStatus(): Promise<void> {\n const daemon = isRunning();\n const routines = collectRoutines();\n const enabled = routines.filter((r) => r.enabled !== false);\n const running = getRunningAgents();\n\n writeLine(chalk.bold(\"\\n Autonomous Scheduler\\n\"));\n\n // Daemon status\n const pauseStatus = isPaused();\n if (daemon.running) {\n if (pauseStatus.paused) {\n writeLine(\n ` ${chalk.yellow(\"●\")} Daemon paused ${chalk.gray(`(PID ${daemon.pid})`)}`\n );\n writeLine(` ${chalk.yellow(pauseStatus.reason || \"No reason given\")} ${chalk.gray(`since ${pauseStatus.since || \"unknown\"}`)}`);\n } else {\n writeLine(\n ` ${chalk.green(\"●\")} Daemon running ${chalk.gray(`(PID ${daemon.pid})`)}`\n );\n }\n } else {\n writeLine(` ${chalk.red(\"●\")} Daemon not running`);\n }\n writeLine();\n\n // Running agents\n if (running.length > 0) {\n writeLine(chalk.cyan(\" Running Agents\"));\n for (const agent of running) {\n const runtimeMin = Math.round((Date.now() - agent.startedAt) / 60000);\n const timeoutWarning =\n runtimeMin > AGENT_TIMEOUT_MIN * 0.8 ? chalk.yellow(\" ⚠\") : \"\";\n writeLine(\n ` ${chalk.green(\"●\")} ${chalk.cyan(agent.squad)}/${agent.agent} ${chalk.gray(`${runtimeMin}min`)}${timeoutWarning} ${chalk.gray(`PID ${agent.pid}`)}`\n );\n }\n writeLine();\n }\n\n // Routine summary\n writeLine(chalk.cyan(\" Routines\"));\n writeLine(\n ` ${enabled.length} enabled / ${routines.length} total, ${running.length}/${MAX_CONCURRENT} running`\n );\n writeLine();\n\n // Next 10 upcoming runs\n if (enabled.length > 0) {\n writeLine(chalk.cyan(\" Next Runs\"));\n\n const now = new Date();\n const nextRuns: {\n squad: string;\n routine: string;\n agent: string;\n nextRun: Date;\n }[] = [];\n\n for (const r of enabled) {\n const next = getNextCronRun(r.schedule, now);\n for (const agent of r.agents) {\n nextRuns.push({\n squad: r.squad,\n routine: r.name,\n agent,\n nextRun: next,\n });\n }\n }\n\n nextRuns\n .sort((a, b) => a.nextRun.getTime() - b.nextRun.getTime())\n .slice(0, 10)\n .forEach((run) => {\n const timeStr = run.nextRun.toLocaleTimeString([], {\n hour: \"2-digit\",\n minute: \"2-digit\",\n });\n const dateStr =\n run.nextRun.toDateString() === now.toDateString()\n ? \"today\"\n : run.nextRun.toLocaleDateString([], {\n month: \"short\",\n day: \"numeric\",\n });\n writeLine(\n ` ${chalk.gray(timeStr)} ${chalk.gray(dateStr)} ${chalk.cyan(run.squad)}/${run.agent}`\n );\n });\n }\n\n writeLine();\n writeLine(chalk.gray(\" Commands:\"));\n writeLine(chalk.gray(\" $ squads autonomous start Start daemon\"));\n writeLine(chalk.gray(\" $ squads autonomous stop Stop daemon\"));\n writeLine(chalk.gray(\" $ squads autonomous pause Pause (quota/manual)\"));\n writeLine(chalk.gray(\" $ squads autonomous resume Resume after pause\"));\n writeLine(chalk.gray(` $ tail -f ${DAEMON_LOG}`));\n writeLine();\n}\n\n// =============================================================================\n// Command Registration\n// =============================================================================\n\nexport function registerAutonomousCommand(program: Command): void {\n const autonomous = program\n .command(\"autonomous\")\n .alias(\"auto\")\n .description(\"Local scheduling daemon for autonomous agent execution\")\n .action(() => { autonomous.outputHelp(); });\n\n autonomous\n .command(\"start\")\n .description(\"Start the scheduling daemon\")\n .action(async () => {\n await startScheduler();\n });\n\n autonomous\n .command(\"stop\")\n .description(\"Stop the scheduling daemon\")\n .action(() => {\n stopScheduler();\n });\n\n autonomous\n .command(\"status\")\n .description(\"Show daemon status, running agents, and next runs\")\n .action(async () => {\n await showStatus();\n });\n\n autonomous\n .command(\"pause\")\n .description(\"Pause the daemon (e.g. quota exhausted)\")\n .argument(\"[reason]\", \"Reason for pausing\", \"Manual pause\")\n .action((reason: string) => {\n pauseDaemon(reason);\n });\n\n autonomous\n .command(\"resume\")\n .description(\"Resume a paused daemon\")\n .action(() => {\n resumeDaemon();\n });\n}\n","/**\n * squads approval - Manage approval requests for agent actions\n *\n * Commands:\n * squads approval send <type> Send approval request to Slack\n * squads approval list List pending approvals\n * squads approval check <id> Check approval status\n * squads approval cancel <id> Cancel pending approval\n */\n\nimport { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport { writeLine } from \"../lib/terminal.js\";\nimport { getApiUrl } from \"../lib/env-config.js\";\n\nconst API_URL = getApiUrl();\n\ntype ApprovalType = \"issue\" | \"pr\" | \"content\" | \"run\" | \"brief\";\n\ninterface Approval {\n approval_id: string;\n type: ApprovalType;\n squad: string;\n agent?: string;\n title: string;\n description?: string;\n payload: Record<string, unknown>;\n status: \"pending\" | \"approved\" | \"rejected\" | \"expired\" | \"cancelled\";\n decided_by?: string;\n decided_at?: string;\n created_at: string;\n expires_at: string;\n}\n\nfunction generateApprovalId(): string {\n const timestamp = Date.now().toString(36);\n const random = Math.random().toString(36).substring(2, 8);\n return `appr_${timestamp}_${random}`;\n}\n\nfunction parseExpiresIn(expiresIn: string): Date {\n const expiresAt = new Date();\n const match = expiresIn.match(/(\\d+)(h|m|d)/);\n if (match) {\n const [, num, unit] = match;\n const hours =\n unit === \"d\"\n ? parseInt(num) * 24\n : unit === \"h\"\n ? parseInt(num)\n : parseInt(num) / 60;\n expiresAt.setHours(expiresAt.getHours() + hours);\n } else {\n // Default to 24 hours\n expiresAt.setHours(expiresAt.getHours() + 24);\n }\n return expiresAt;\n}\n\nasync function sendApproval(\n type: string,\n options: {\n title?: string;\n description?: string;\n squad?: string;\n agent?: string;\n priority?: string;\n expiresIn?: string;\n json?: string;\n }\n): Promise<void> {\n const approvalId = generateApprovalId();\n\n let payload: Record<string, unknown> = {};\n\n // Parse JSON payload if provided\n if (options.json) {\n try {\n if (options.json === \"-\") {\n // Read from stdin\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(chunk);\n }\n payload = JSON.parse(Buffer.concat(chunks).toString());\n } else {\n payload = JSON.parse(options.json);\n }\n } catch {\n console.error(chalk.red(\"Invalid JSON payload\"));\n process.exit(1);\n }\n }\n\n const expiresAt = parseExpiresIn(options.expiresIn || \"24h\");\n\n const approval = {\n approval_id: approvalId,\n type,\n title: options.title || payload.title || `Approval needed: ${type}`,\n description: options.description || (payload.description as string),\n squad: options.squad || process.env.SQUADS_SQUAD || \"unknown\",\n agent: options.agent || process.env.SQUADS_AGENT,\n priority: parseInt(options.priority || \"5\"),\n expires_at: expiresAt.toISOString(),\n payload,\n };\n\n try {\n const response = await fetch(`${API_URL}/approvals`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(approval),\n });\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(error);\n }\n\n const result = (await response.json()) as {\n success: boolean;\n approval_id: string;\n };\n\n writeLine(chalk.green(`\\nApproval sent: ${result.approval_id}`));\n writeLine(chalk.dim(` Expires: ${expiresAt.toISOString()}`));\n writeLine();\n\n // Output for agent consumption\n if (process.env.SQUADS_AGENT) {\n writeLine(`APPROVAL_ID=${approvalId}`);\n }\n } catch (error) {\n console.error(chalk.red(`Failed to send approval: ${error}`));\n process.exit(1);\n }\n}\n\nasync function listApprovals(options: {\n pending?: boolean;\n squad?: string;\n json?: boolean;\n}): Promise<void> {\n const status = options.pending ? \"pending\" : \"\";\n const params = new URLSearchParams();\n if (status) params.set(\"status\", status);\n if (options.squad) params.set(\"squad\", options.squad);\n\n try {\n const response = await fetch(\n `${API_URL}/approvals?${params.toString()}`\n );\n if (!response.ok) throw new Error(await response.text());\n\n const approvals = (await response.json()) as Approval[];\n\n if (options.json) {\n console.log(JSON.stringify(approvals, null, 2));\n return;\n }\n\n if (approvals.length === 0) {\n writeLine(chalk.gray(\"\\nNo pending approvals\\n\"));\n return;\n }\n\n writeLine(chalk.bold(\"\\nPending Approvals\\n\"));\n\n for (const a of approvals) {\n const typeColors: Record<ApprovalType, typeof chalk.green> = {\n issue: chalk.green,\n pr: chalk.magenta,\n content: chalk.blue,\n run: chalk.yellow,\n brief: chalk.cyan,\n };\n const color = typeColors[a.type] || chalk.white;\n\n writeLine(\n ` ${color(`[${a.type}]`)} ${chalk.bold(a.title)} ${chalk.dim(`(${a.approval_id})`)}`\n );\n writeLine(\n chalk.dim(\n ` Squad: ${a.squad}${a.agent ? \"/\" + a.agent : \"\"} | Created: ${new Date(a.created_at).toLocaleString()}`\n )\n );\n writeLine();\n }\n } catch (error) {\n console.error(chalk.red(`Failed to list approvals: ${error}`));\n process.exit(1);\n }\n}\n\nasync function checkApproval(\n approvalId: string,\n options: { wait?: boolean; timeout?: string }\n): Promise<void> {\n const timeoutMs = parseInt(options.timeout || \"60\") * 60 * 1000;\n const startTime = Date.now();\n\n async function check(): Promise<Approval | null> {\n try {\n const response = await fetch(\n `${API_URL}/approvals/${approvalId}`\n );\n if (response.status === 404) return null;\n if (!response.ok) throw new Error(await response.text());\n return (await response.json()) as Approval;\n } catch (error) {\n console.error(chalk.red(`Failed to check approval: ${error}`));\n return null;\n }\n }\n\n const approval = await check();\n\n if (!approval) {\n console.error(chalk.red(`Approval not found: ${approvalId}`));\n process.exit(1);\n }\n\n if (approval.status !== \"pending\" || !options.wait) {\n // Output current status\n const statusColors: Record<string, typeof chalk.green> = {\n pending: chalk.yellow,\n approved: chalk.green,\n rejected: chalk.red,\n expired: chalk.gray,\n cancelled: chalk.gray,\n };\n const color = statusColors[approval.status] || chalk.white;\n\n writeLine(`\\nApproval: ${approvalId}`);\n writeLine(` Status: ${color(approval.status)}`);\n if (approval.decided_by) {\n writeLine(` Decided by: ${approval.decided_by}`);\n writeLine(` Decided at: ${approval.decided_at}`);\n }\n writeLine();\n\n // Exit with appropriate code\n if (approval.status === \"approved\") {\n process.exit(0);\n } else if (approval.status === \"rejected\") {\n process.exit(1);\n } else if (approval.status === \"pending\") {\n process.exit(2);\n } else {\n process.exit(3);\n }\n }\n\n // Wait mode\n writeLine(chalk.dim(`Waiting for decision on ${approvalId}...`));\n\n while (Date.now() - startTime < timeoutMs) {\n await new Promise((resolve) => setTimeout(resolve, 5000)); // Poll every 5s\n\n const updated = await check();\n if (!updated) {\n console.error(chalk.red(\"Approval disappeared\"));\n process.exit(1);\n }\n\n if (updated.status !== \"pending\") {\n const color =\n updated.status === \"approved\" ? chalk.green : chalk.red;\n writeLine(color(`\\nDecision: ${updated.status}`));\n if (updated.decided_by) {\n writeLine(chalk.dim(` By: ${updated.decided_by}`));\n }\n process.exit(updated.status === \"approved\" ? 0 : 1);\n }\n }\n\n console.error(chalk.red(\"Timeout waiting for approval\"));\n process.exit(2);\n}\n\nasync function cancelApproval(approvalId: string): Promise<void> {\n writeLine(chalk.yellow(`Cancel not yet implemented for: ${approvalId}`));\n // TODO: Implement cancel endpoint\n}\n\nexport function registerApprovalCommand(program: Command): void {\n const approval = program\n .command(\"approval\")\n .description(\"Manage approval requests for agent actions\")\n .action(() => { approval.outputHelp(); });\n\n approval\n .command(\"send <type>\")\n .description(\"Send approval request to Slack\")\n .option(\"-t, --title <title>\", \"Approval title\")\n .option(\"-d, --description <desc>\", \"Detailed description\")\n .option(\"-s, --squad <squad>\", \"Squad name\")\n .option(\"-a, --agent <agent>\", \"Agent name\")\n .option(\"-p, --priority <n>\", \"Priority 1-10 (1=urgent)\", \"5\")\n .option(\"-e, --expires-in <time>\", \"Expiration time (24h, 1h, 30m)\", \"24h\")\n .option(\"-j, --json <json>\", \"Full payload as JSON (use - for stdin)\")\n .addHelpText(\n \"after\",\n `\nTypes: issue, pr, content, run, brief\n\nExamples:\n $ squads approval send pr --title \"Merge feature X\" --json '{\"repo\":\"agents-squads/hq\",\"number\":123}'\n $ squads approval send content -t \"LinkedIn post\" -d \"New blog announcement\"\n $ echo '{\"title\":\"Run overnight\"}' | squads approval send run --json -\n`\n )\n .action(sendApproval);\n\n approval\n .command(\"list\")\n .description(\"List approvals\")\n .option(\"--pending\", \"Only show pending approvals\", true)\n .option(\"-s, --squad <squad>\", \"Filter by squad\")\n .option(\"-j, --json\", \"Output as JSON\")\n .action(listApprovals);\n\n approval\n .command(\"check <id>\")\n .description(\"Check approval status\")\n .option(\"-w, --wait\", \"Wait for decision (polls every 5s)\")\n .option(\"-t, --timeout <minutes>\", \"Wait timeout in minutes\", \"60\")\n .action(checkApproval);\n\n approval\n .command(\"cancel <id>\")\n .description(\"Cancel pending approval\")\n .action(cancelApproval);\n}\n","/**\n * squads deploy — Push agent definitions to the Squads platform.\n *\n * Reads .agents/ directory (squads, agents, routines, memory),\n * packages the deployment manifest, and syncs it to the platform API.\n *\n * This is the upgrade path from Layer 2 (local autonomous) to Layer 3 (platform).\n */\n\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { existsSync, readFileSync } from 'fs';\nimport { execSync } from 'child_process';\nimport {\n findSquadsDir,\n listSquads,\n loadSquad,\n listAgents,\n} from '../lib/squad-parser.js';\nimport { writeLine } from '../lib/terminal.js';\nimport matter from 'gray-matter';\nimport { loadSession } from '../lib/auth.js';\nimport { track } from '../lib/telemetry.js';\n\n// Platform API URL\nconst PLATFORM_API_URL = process.env.SQUADS_PLATFORM_URL || process.env.SQUADS_API_URL || process.env.SQUADS_SCHEDULER_URL || '';\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\ninterface DeployManifest {\n /** Squads with their agents and routines */\n squads: SquadManifest[];\n /** Triggers to sync (from routines) */\n triggers: TriggerSync[];\n /** Timestamp of deployment */\n deployedAt: string;\n /** Git SHA if available */\n gitSha?: string;\n}\n\ninterface SquadManifest {\n name: string;\n agentCount: number;\n agents: AgentManifest[];\n routineCount: number;\n}\n\ninterface AgentManifest {\n name: string;\n squad: string;\n role: string;\n model: string;\n schedule?: string;\n status: string;\n}\n\ninterface TriggerSync {\n name: string;\n squad: string;\n agent: string | null;\n condition: string;\n cooldown: string;\n priority: number;\n context: Record<string, unknown>;\n}\n\ninterface DeployResult {\n triggersCreated: number;\n triggersSynced: string[];\n errors: Array<{ name: string; error: string }>;\n}\n\n// ─── Commands ────────────────────────────────────────────────────────────────\n\nexport async function deployCommand(options: {\n dryRun?: boolean;\n squad?: string;\n verbose?: boolean;\n}): Promise<void> {\n const session = loadSession();\n\n if (!session || session.status !== 'active') {\n writeLine(`\n${chalk.yellow('Not logged in or account not active.')}\n\n${chalk.bold('To deploy agents to the platform:')}\n 1. ${chalk.cyan('squads login')} — Authenticate with your team account\n 2. ${chalk.cyan('squads deploy')} — Push agents to the platform\n\n${chalk.dim('Status:')} ${session ? `${session.email} (${session.status})` : 'Not logged in'}\n${chalk.dim('Need access?')} ${chalk.cyan('hello@agents-squads.com')}\n`);\n await track('cli.deploy.not_authenticated');\n return;\n }\n\n // Find .agents/ directory\n const squadsDir = findSquadsDir();\n if (!squadsDir) {\n console.error(chalk.red('No .agents/squads/ directory found.'));\n writeLine(chalk.dim('Run: squads init'));\n return;\n }\n\n const spinner = ora('Building deployment manifest...').start();\n\n try {\n // Build manifest\n const manifest = buildManifest(squadsDir, options.squad);\n\n if (manifest.squads.length === 0) {\n spinner.warn('No squads found to deploy.');\n return;\n }\n\n spinner.succeed(`Found ${manifest.squads.length} squad(s), ${manifest.triggers.length} trigger(s)`);\n\n // Show what will be deployed\n writeLine('');\n writeLine(chalk.bold('Deployment Manifest'));\n writeLine(chalk.dim('─'.repeat(50)));\n\n for (const squad of manifest.squads) {\n writeLine(` ${chalk.cyan(squad.name)} — ${squad.agentCount} agent(s), ${squad.routineCount} routine(s)`);\n if (options.verbose) {\n for (const agent of squad.agents) {\n const status = agent.status === 'active' ? chalk.green('active') : chalk.yellow(agent.status);\n writeLine(` ${chalk.dim('→')} ${agent.name} (${agent.model}) [${status}]`);\n if (agent.schedule) {\n writeLine(` ${chalk.dim('schedule:')} ${agent.schedule}`);\n }\n }\n }\n }\n\n if (manifest.triggers.length > 0) {\n writeLine('');\n writeLine(chalk.bold('Triggers to sync'));\n writeLine(chalk.dim('─'.repeat(50)));\n for (const trigger of manifest.triggers) {\n writeLine(` ${chalk.magenta(trigger.name)} — ${trigger.squad}${trigger.agent ? '/' + trigger.agent : ''}`);\n if (options.verbose) {\n writeLine(` ${chalk.dim('schedule:')} ${trigger.condition}`);\n writeLine(` ${chalk.dim('cooldown:')} ${trigger.cooldown}`);\n }\n }\n }\n\n if (manifest.gitSha) {\n writeLine('');\n writeLine(chalk.dim(`Git SHA: ${manifest.gitSha}`));\n }\n\n // Dry run stops here\n if (options.dryRun) {\n writeLine('');\n writeLine(chalk.yellow('Dry run — no changes pushed to platform.'));\n writeLine(chalk.dim('Remove --dry-run to deploy.'));\n await track('cli.deploy.dry_run', {\n squads: manifest.squads.length,\n triggers: manifest.triggers.length,\n });\n return;\n }\n\n // Push to platform\n writeLine('');\n const pushSpinner = ora('Pushing to platform...').start();\n\n const result = await pushToplatform(manifest, session.accessToken || '');\n\n if (result.errors.length > 0) {\n pushSpinner.warn(`Deployed with ${result.errors.length} error(s)`);\n for (const err of result.errors) {\n writeLine(` ${chalk.red('✗')} ${err.name}: ${err.error}`);\n }\n } else {\n pushSpinner.succeed(`Deployed ${result.triggersCreated} trigger(s) to platform`);\n }\n\n if (result.triggersSynced.length > 0 && options.verbose) {\n writeLine('');\n writeLine(chalk.dim('Synced triggers:'));\n for (const name of result.triggersSynced) {\n writeLine(` ${chalk.green('✓')} ${name}`);\n }\n }\n\n writeLine(`\n${chalk.green('✓ Deployment complete.')}\n\n${chalk.bold('Next steps:')}\n ${chalk.dim('→')} View in dashboard: ${chalk.cyan(process.env.SQUADS_CONSOLE_URL || 'squads deploy status')}\n ${chalk.dim('→')} Check status: ${chalk.cyan('squads deploy status')}\n ${chalk.dim('→')} Pull cloud state: ${chalk.cyan('squads deploy pull')}\n`);\n\n await track('cli.deploy.success', {\n squads: manifest.squads.length,\n triggers: manifest.triggers.length,\n errors: result.errors.length,\n });\n\n } catch (error) {\n spinner.fail('Deployment failed');\n const message = error instanceof Error ? error.message : String(error);\n console.error(chalk.red(message));\n\n if (message.includes('fetch failed') || message.includes('ECONNREFUSED')) {\n writeLine(chalk.dim('\\nPlatform may be unreachable. Check your connection.'));\n }\n\n await track('cli.deploy.error', { error: message });\n }\n}\n\nexport async function deployStatusCommand(): Promise<void> {\n const session = loadSession();\n if (!session?.accessToken) {\n writeLine(chalk.yellow('Not logged in. Run: squads login'));\n return;\n }\n\n const spinner = ora('Fetching deployment status...').start();\n\n try {\n const response = await fetch(`${PLATFORM_API_URL}/triggers`, {\n headers: {\n 'Authorization': `Bearer ${session.accessToken}`,\n },\n signal: AbortSignal.timeout(5000),\n });\n\n if (!response.ok) {\n spinner.fail(`Failed to fetch triggers: ${response.status}`);\n return;\n }\n\n const data = await response.json() as Array<{\n name: string;\n squad: string;\n agent: string | null;\n enabled: boolean;\n last_fired_at: string | null;\n trigger_type: string;\n }>;\n\n spinner.succeed(`${data.length} trigger(s) on platform`);\n\n if (data.length === 0) {\n writeLine(chalk.dim('\\nNo triggers deployed. Run: squads deploy'));\n return;\n }\n\n writeLine('');\n writeLine(chalk.bold('Platform Triggers'));\n writeLine(chalk.dim('─'.repeat(60)));\n\n for (const trigger of data) {\n const status = trigger.enabled ? chalk.green('enabled') : chalk.red('disabled');\n const lastFired = trigger.last_fired_at\n ? chalk.dim(new Date(trigger.last_fired_at).toLocaleString())\n : chalk.dim('never');\n\n writeLine(` ${status} ${chalk.cyan(trigger.name)} — ${trigger.squad}${trigger.agent ? '/' + trigger.agent : ''}`);\n writeLine(` ${chalk.dim('type:')} ${trigger.trigger_type} ${chalk.dim('last fired:')} ${lastFired}`);\n }\n\n // Show execution stats\n const execResponse = await fetch(`${PLATFORM_API_URL}/stats`, {\n headers: {\n 'Authorization': `Bearer ${session.accessToken}`,\n },\n signal: AbortSignal.timeout(5000),\n });\n\n if (execResponse.ok) {\n const stats = await execResponse.json() as Record<string, unknown>;\n writeLine('');\n writeLine(chalk.bold('Platform Stats'));\n writeLine(chalk.dim('─'.repeat(60)));\n if (stats.running_agents !== undefined) {\n writeLine(` Running agents: ${chalk.cyan(String(stats.running_agents))}`);\n }\n if (stats.executions_today !== undefined) {\n writeLine(` Executions today: ${chalk.cyan(String(stats.executions_today))}`);\n }\n if (stats.total_cost_today !== undefined) {\n writeLine(` Cost today: ${chalk.cyan('$' + String(stats.total_cost_today))}`);\n }\n }\n\n } catch (error) {\n spinner.fail('Failed to fetch status');\n const msg = error instanceof Error ? error.message : String(error);\n if (msg.includes('fetch failed') || msg.includes('ECONNREFUSED') || msg.includes('abort')) {\n writeLine(chalk.yellow('\\nAPI unavailable. Check connection or run `squads login`.'));\n } else {\n console.error(chalk.red(msg));\n }\n }\n}\n\nexport async function deployPullCommand(options: { verbose?: boolean }): Promise<void> {\n const session = loadSession();\n if (!session?.accessToken) {\n writeLine(chalk.yellow('Not logged in. Run: squads login'));\n return;\n }\n\n const spinner = ora('Pulling execution data from platform...').start();\n\n try {\n // Pull recent executions\n const response = await fetch(`${PLATFORM_API_URL}/executions?limit=20`, {\n headers: {\n 'Authorization': `Bearer ${session.accessToken}`,\n },\n signal: AbortSignal.timeout(5000),\n });\n\n if (!response.ok) {\n spinner.fail(`Failed to pull executions: ${response.status}`);\n return;\n }\n\n const executions = await response.json() as Array<{\n id: string;\n trigger_name: string;\n squad: string;\n agent: string | null;\n status: string;\n started_at: string;\n completed_at: string | null;\n cost_usd: number | null;\n }>;\n\n spinner.succeed(`Pulled ${executions.length} recent execution(s)`);\n\n if (executions.length === 0) {\n writeLine(chalk.dim('\\nNo executions found on platform.'));\n return;\n }\n\n writeLine('');\n writeLine(chalk.bold('Recent Platform Executions'));\n writeLine(chalk.dim('─'.repeat(70)));\n\n for (const exec of executions) {\n const statusColor = exec.status === 'completed' ? chalk.green\n : exec.status === 'failed' ? chalk.red\n : exec.status === 'running' ? chalk.yellow\n : chalk.dim;\n\n const cost = exec.cost_usd !== null ? chalk.dim(`$${exec.cost_usd.toFixed(2)}`) : '';\n const time = new Date(exec.started_at).toLocaleString();\n\n writeLine(` ${statusColor(exec.status.padEnd(10))} ${chalk.cyan(exec.trigger_name)} ${chalk.dim(time)} ${cost}`);\n\n if (options.verbose && exec.completed_at) {\n const duration = (new Date(exec.completed_at).getTime() - new Date(exec.started_at).getTime()) / 1000;\n writeLine(` ${chalk.dim(`duration: ${duration.toFixed(0)}s`)}`);\n }\n }\n\n // Pull learnings (collective memory from cloud runs)\n const learningsResponse = await fetch(`${PLATFORM_API_URL}/learnings/relevant?limit=5`, {\n headers: {\n 'Authorization': `Bearer ${session.accessToken}`,\n },\n signal: AbortSignal.timeout(5000),\n });\n\n if (learningsResponse.ok) {\n const learnings = await learningsResponse.json() as Array<{\n squad: string;\n agent: string;\n insight: string;\n created_at: string;\n }>;\n\n if (learnings.length > 0) {\n writeLine('');\n writeLine(chalk.bold('Recent Learnings'));\n writeLine(chalk.dim('─'.repeat(70)));\n for (const l of learnings) {\n writeLine(` ${chalk.cyan(l.squad)}/${l.agent}: ${l.insight.substring(0, 80)}${l.insight.length > 80 ? '...' : ''}`);\n }\n }\n }\n\n } catch (error) {\n spinner.fail('Failed to pull data');\n const msg = error instanceof Error ? error.message : String(error);\n if (msg.includes('fetch failed') || msg.includes('ECONNREFUSED') || msg.includes('abort')) {\n writeLine(chalk.yellow('\\nAPI unavailable. Check connection or run `squads login`.'));\n } else {\n console.error(chalk.red(msg));\n }\n }\n}\n\n// ─── Helpers ─────────────────────────────────────────────────────────────────\n\nfunction buildManifest(squadsDir: string, filterSquad?: string): DeployManifest {\n const squadNames = filterSquad ? [filterSquad] : listSquads(squadsDir);\n const squads: SquadManifest[] = [];\n const triggers: TriggerSync[] = [];\n\n // Try to get git SHA\n let gitSha: string | undefined;\n try {\n gitSha = execSync('git rev-parse --short HEAD', { encoding: 'utf-8' }).trim();\n } catch {\n // Not in a git repo\n }\n\n for (const squadName of squadNames) {\n const squad = loadSquad(squadName);\n if (!squad) continue;\n\n const agents: AgentManifest[] = [];\n const agentList = listAgents(squadsDir, squadName);\n\n for (const agent of agentList) {\n // Parse agent frontmatter for model, schedule, status\n let role = '';\n let model = 'sonnet';\n let schedule: string | undefined;\n let status = 'active';\n\n if (agent.filePath && existsSync(agent.filePath)) {\n const raw = readFileSync(agent.filePath, 'utf-8');\n const { data: fm } = matter(raw);\n role = (fm.role as string) || '';\n model = (fm.model as string) || 'sonnet';\n schedule = fm.schedule as string | undefined;\n status = (fm.status as string) || 'active';\n }\n\n agents.push({\n name: agent.name,\n squad: squadName,\n role,\n model,\n schedule,\n status,\n });\n }\n\n // Extract triggers from routines\n for (const routine of squad.routines) {\n if (routine.enabled === false) continue;\n\n for (const agent of routine.agents) {\n triggers.push({\n name: `${squadName}-${routine.name}-${agent}`,\n squad: squadName,\n agent,\n condition: routine.schedule, // cron expression\n cooldown: routine.cooldown || '1 hour',\n priority: routine.priority || 50,\n context: {\n routine: routine.name,\n model: routine.model || squad.effort || 'sonnet',\n },\n });\n }\n }\n\n squads.push({\n name: squadName,\n agentCount: agents.length,\n agents,\n routineCount: squad.routines.length,\n });\n }\n\n return {\n squads,\n triggers,\n deployedAt: new Date().toISOString(),\n gitSha,\n };\n}\n\nasync function pushToplatform(manifest: DeployManifest, token: string): Promise<DeployResult> {\n if (manifest.triggers.length === 0) {\n return { triggersCreated: 0, triggersSynced: [], errors: [] };\n }\n\n const response = await fetch(`${PLATFORM_API_URL}/triggers/sync`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${token}`,\n },\n body: JSON.stringify(manifest.triggers),\n signal: AbortSignal.timeout(10000),\n });\n\n if (!response.ok) {\n const text = await response.text();\n throw new Error(`Platform sync failed (${response.status}): ${text}`);\n }\n\n const result = await response.json() as {\n synced: number;\n triggers: string[];\n errors: Array<{ name: string; error: string }>;\n };\n\n return {\n triggersCreated: result.synced,\n triggersSynced: result.triggers,\n errors: result.errors,\n };\n}\n\n// ─── Command Registration ────────────────────────────────────────────────────\n\nexport function registerDeployCommand(program: Command): void {\n const deploy = program\n .command('deploy')\n .description('Deploy agents to the Squads platform')\n .option('-n, --dry-run', 'Show what would be deployed without pushing')\n .option('-s, --squad <squad>', 'Deploy only a specific squad')\n .option('-v, --verbose', 'Show detailed agent and trigger info')\n .action((options) => deployCommand({\n dryRun: options.dryRun,\n squad: options.squad,\n verbose: options.verbose,\n }));\n\n deploy\n .command('status')\n .description('Show current platform deployment status')\n .action(() => deployStatusCommand());\n\n deploy\n .command('pull')\n .description('Pull execution data and learnings from platform')\n .option('-v, --verbose', 'Show detailed execution info')\n .action((options) => deployPullCommand({ verbose: options.verbose }));\n}\n","/**\n * squads eval — Agent readiness scorer.\n *\n * Evaluates an agent's readiness for autonomous or platform deployment\n * by checking definition quality, execution history, memory usage,\n * output consistency, and resource safety.\n *\n * Readiness levels:\n * - Untested: No local runs → cannot deploy\n * - Development: 1+ runs → local autonomous (L2) with supervision\n * - Staging: 5+ runs, >80% success → cloud with approval gates\n * - Production: 10+ runs, >95% success, memory working → cloud autonomous\n */\n\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport { writeLine } from '../lib/terminal.js';\nimport { existsSync, readFileSync, readdirSync, statSync } from 'fs';\nimport { join } from 'path';\nimport matter from 'gray-matter';\nimport {\n findSquadsDir,\n loadSquad,\n listAgents,\n} from '../lib/squad-parser.js';\nimport { findMemoryDir } from '../lib/memory.js';\nimport { track } from '../lib/telemetry.js';\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\ninterface EvalDimension {\n name: string;\n score: number; // 0-10\n maxScore: number;\n status: 'pass' | 'warn' | 'fail';\n details: string;\n}\n\ninterface EvalResult {\n agent: string;\n squad: string;\n overallScore: number; // 0-100\n readinessLevel: 'untested' | 'development' | 'staging' | 'production';\n dimensions: EvalDimension[];\n recommendations: string[];\n}\n\n// Required frontmatter fields for a well-defined agent\nconst REQUIRED_FIELDS = ['name', 'role', 'model'];\nconst RECOMMENDED_FIELDS = ['squad', 'trigger', 'schedule', 'status', 'timeout'];\n\n// Patterns that indicate destructive actions\nconst DESTRUCTIVE_PATTERNS = [\n /force.push/i,\n /--force/,\n /git\\s+reset\\s+--hard/i,\n /rm\\s+-rf/,\n /DROP\\s+TABLE/i,\n /DELETE\\s+FROM/i,\n /--dangerously/,\n];\n\n// ─── Scoring Functions ───────────────────────────────────────────────────────\n\nfunction scoreDefinitionQuality(agentPath: string): EvalDimension {\n const content = readFileSync(agentPath, 'utf-8');\n\n let score = 0;\n const maxScore = 10;\n const issues: string[] = [];\n\n // Parse frontmatter\n let frontmatter: Record<string, unknown> = {};\n try {\n const parsed = matter(content);\n frontmatter = parsed.data || {};\n } catch {\n return {\n name: 'Definition quality',\n score: 0,\n maxScore,\n status: 'fail',\n details: 'Failed to parse frontmatter',\n };\n }\n\n // Check required fields (3 points)\n let requiredPresent = 0;\n for (const field of REQUIRED_FIELDS) {\n if (frontmatter[field]) {\n requiredPresent++;\n } else {\n issues.push(`Missing required field: ${field}`);\n }\n }\n score += Math.round((requiredPresent / REQUIRED_FIELDS.length) * 3);\n\n // Check recommended fields (2 points)\n let recommendedPresent = 0;\n for (const field of RECOMMENDED_FIELDS) {\n if (frontmatter[field]) recommendedPresent++;\n }\n score += Math.round((recommendedPresent / RECOMMENDED_FIELDS.length) * 2);\n\n // Check instruction length (2 points)\n const bodyLength = content.split('---').slice(2).join('---').trim().length;\n if (bodyLength > 500) {\n score += 2;\n } else if (bodyLength > 200) {\n score += 1;\n issues.push('Instructions could be more detailed');\n } else {\n issues.push('Instructions are very short (<200 chars)');\n }\n\n // Check for role/mission description (1 point)\n if (content.match(/##\\s*(Role|Mission|Purpose|Responsibilities)/i)) {\n score += 1;\n } else {\n issues.push('No Role/Mission section found');\n }\n\n // Check for output format (1 point)\n if (content.match(/##\\s*(Output|Format|Report|Deliverable)/i)) {\n score += 1;\n } else {\n issues.push('No Output format section');\n }\n\n // Check for constraints/rules (1 point)\n if (content.match(/##\\s*(Constraints|Rules|Never|Always|Guidelines)/i)) {\n score += 1;\n }\n\n const status = score >= 8 ? 'pass' : score >= 5 ? 'warn' : 'fail';\n const details = issues.length > 0 ? issues.join('; ') : 'Well-defined agent';\n\n return { name: 'Definition quality', score, maxScore, status, details };\n}\n\nfunction scoreExecutionReliability(memoryDir: string, squad: string, agent: string): EvalDimension {\n const maxScore = 10;\n const agentMemoryDir = join(memoryDir, squad, agent);\n\n if (!existsSync(agentMemoryDir)) {\n return {\n name: 'Execution reliability',\n score: 0,\n maxScore,\n status: 'fail',\n details: 'No execution history found',\n };\n }\n\n // Check for state.md (indicates the agent has run and persisted state)\n const stateFile = join(agentMemoryDir, 'state.md');\n const outputFile = join(agentMemoryDir, 'output.md');\n\n let runsDetected = 0;\n let hasRecentActivity = false;\n\n // Count evidence of runs from state.md modifications\n if (existsSync(stateFile)) {\n const stat = statSync(stateFile);\n const fileContent = readFileSync(stateFile, 'utf-8');\n\n // Skip template state files that haven't been modified by an actual run\n const isTemplateState = fileContent.includes('awaiting first execution') || fileContent.includes('None yet.');\n if (!isTemplateState) {\n runsDetected += fileContent.length > 50 ? 1 : 0;\n\n // Check if modified in last 7 days\n const sevenDaysAgo = Date.now() - 7 * 24 * 60 * 60 * 1000;\n if (stat.mtimeMs > sevenDaysAgo) {\n hasRecentActivity = true;\n runsDetected += 2;\n }\n }\n }\n\n if (existsSync(outputFile)) {\n const stat = statSync(outputFile);\n const fileContent = readFileSync(outputFile, 'utf-8');\n runsDetected += fileContent.length > 100 ? 2 : 1;\n\n const sevenDaysAgo = Date.now() - 7 * 24 * 60 * 60 * 1000;\n if (stat.mtimeMs > sevenDaysAgo) {\n hasRecentActivity = true;\n }\n }\n\n // Check for execution log files\n const logDir = join(memoryDir, '..', 'logs', squad);\n if (existsSync(logDir)) {\n try {\n const logFiles = readdirSync(logDir).filter(f => f.startsWith(agent));\n runsDetected += logFiles.length;\n } catch { /* ignore */ }\n }\n\n // Score based on evidence\n let score = 0;\n if (runsDetected >= 10) score = 10;\n else if (runsDetected >= 5) score = 8;\n else if (runsDetected >= 3) score = 6;\n else if (runsDetected >= 1) score = 4;\n else score = 0;\n\n // Bonus for recent activity\n if (hasRecentActivity && score < 10) score = Math.min(score + 1, 10);\n\n const status = score >= 8 ? 'pass' : score >= 4 ? 'warn' : 'fail';\n const details = runsDetected === 0\n ? 'No runs detected'\n : `~${runsDetected} run(s) detected${hasRecentActivity ? ', active in last 7 days' : ''}`;\n\n return { name: 'Execution reliability', score, maxScore, status, details };\n}\n\nfunction scoreMemoryUtilization(memoryDir: string, squad: string, agent: string): EvalDimension {\n const maxScore = 10;\n const agentMemoryDir = join(memoryDir, squad, agent);\n\n if (!existsSync(agentMemoryDir)) {\n return {\n name: 'Memory utilization',\n score: 0,\n maxScore,\n status: 'fail',\n details: 'No memory directory',\n };\n }\n\n let score = 0;\n const issues: string[] = [];\n\n // Check state.md exists and has content (3 points)\n const stateFile = join(agentMemoryDir, 'state.md');\n if (existsSync(stateFile)) {\n const content = readFileSync(stateFile, 'utf-8').trim();\n if (content.length > 100) {\n score += 3;\n } else if (content.length > 0) {\n score += 1;\n issues.push('state.md exists but is sparse');\n } else {\n issues.push('state.md is empty');\n }\n } else {\n issues.push('No state.md — agent doesn\\'t persist state');\n }\n\n // Check learnings.md exists and has content (3 points)\n const learningsFile = join(agentMemoryDir, 'learnings.md');\n if (existsSync(learningsFile)) {\n const content = readFileSync(learningsFile, 'utf-8').trim();\n if (content.length > 100) {\n score += 3;\n } else if (content.length > 0) {\n score += 1;\n issues.push('learnings.md exists but is sparse');\n } else {\n issues.push('learnings.md is empty');\n }\n } else {\n issues.push('No learnings.md — agent doesn\\'t learn across runs');\n }\n\n // Check output.md exists and has content (2 points)\n const outputFile = join(agentMemoryDir, 'output.md');\n if (existsSync(outputFile)) {\n const content = readFileSync(outputFile, 'utf-8').trim();\n if (content.length > 50) {\n score += 2;\n } else {\n score += 1;\n issues.push('output.md is sparse');\n }\n } else {\n issues.push('No output.md');\n }\n\n // Check for briefs or additional memory files (2 points)\n try {\n const files = readdirSync(agentMemoryDir);\n const extraFiles = files.filter(f => !['state.md', 'output.md', 'learnings.md'].includes(f));\n if (extraFiles.length > 0) {\n score += 2;\n }\n } catch { /* ignore */ }\n\n const status = score >= 8 ? 'pass' : score >= 4 ? 'warn' : 'fail';\n const details = issues.length > 0 ? issues.join('; ') : 'Memory well-utilized';\n\n return { name: 'Memory utilization', score, maxScore, status, details };\n}\n\nfunction scoreOutputConsistency(memoryDir: string, squad: string, agent: string): EvalDimension {\n const maxScore = 10;\n const outputFile = join(memoryDir, squad, agent, 'output.md');\n\n if (!existsSync(outputFile)) {\n return {\n name: 'Output consistency',\n score: 0,\n maxScore,\n status: 'fail',\n details: 'No output.md found',\n };\n }\n\n const content = readFileSync(outputFile, 'utf-8').trim();\n let score = 0;\n\n // Check if output has structure (headers, lists, etc.)\n const hasHeaders = /^##?\\s/m.test(content);\n const hasLists = /^[-*]\\s/m.test(content);\n const hasStructuredSections = (content.match(/^##\\s/gm) || []).length >= 2;\n\n if (hasHeaders) score += 3;\n if (hasLists) score += 2;\n if (hasStructuredSections) score += 3;\n\n // Check reasonable output length\n if (content.length > 200) score += 2;\n else if (content.length > 50) score += 1;\n\n const status = score >= 8 ? 'pass' : score >= 4 ? 'warn' : 'fail';\n const details = score >= 8\n ? 'Well-structured output'\n : `Output structure: headers=${hasHeaders}, lists=${hasLists}, sections=${hasStructuredSections}`;\n\n return { name: 'Output consistency', score, maxScore, status, details };\n}\n\nfunction scoreResourceSafety(agentPath: string): EvalDimension {\n const maxScore = 10;\n const content = readFileSync(agentPath, 'utf-8');\n\n let score = 10;\n const issues: string[] = [];\n\n for (const pattern of DESTRUCTIVE_PATTERNS) {\n if (pattern.test(content)) {\n score -= 2;\n issues.push(`Mentions destructive pattern: ${pattern.source}`);\n }\n }\n\n // Check if agent has safety constraints\n if (content.match(/##\\s*(Constraints|Safety|Rules|Never)/i)) {\n score = Math.min(score + 1, 10);\n }\n\n score = Math.max(score, 0);\n const status = score >= 8 ? 'pass' : score >= 5 ? 'warn' : 'fail';\n const details = issues.length > 0 ? issues.join('; ') : 'No destructive patterns detected';\n\n return { name: 'Resource safety', score, maxScore, status, details };\n}\n\n// ─── Main Eval ───────────────────────────────────────────────────────────────\n\nfunction evaluateAgent(squad: string, agentName: string, agentPath: string): EvalResult {\n const memoryDir = findMemoryDir();\n const dimensions: EvalDimension[] = [];\n\n // 1. Definition quality\n dimensions.push(scoreDefinitionQuality(agentPath));\n\n // 2. Execution reliability\n if (memoryDir) {\n dimensions.push(scoreExecutionReliability(memoryDir, squad, agentName));\n } else {\n dimensions.push({\n name: 'Execution reliability',\n score: 0,\n maxScore: 10,\n status: 'fail',\n details: 'No memory directory found',\n });\n }\n\n // 3. Output consistency\n if (memoryDir) {\n dimensions.push(scoreOutputConsistency(memoryDir, squad, agentName));\n } else {\n dimensions.push({\n name: 'Output consistency',\n score: 0,\n maxScore: 10,\n status: 'fail',\n details: 'No memory directory found',\n });\n }\n\n // 4. Memory utilization\n if (memoryDir) {\n dimensions.push(scoreMemoryUtilization(memoryDir, squad, agentName));\n } else {\n dimensions.push({\n name: 'Memory utilization',\n score: 0,\n maxScore: 10,\n status: 'fail',\n details: 'No memory directory found',\n });\n }\n\n // 5. Resource safety\n dimensions.push(scoreResourceSafety(agentPath));\n\n // Calculate overall score\n const totalScore = dimensions.reduce((sum, d) => sum + d.score, 0);\n const totalMax = dimensions.reduce((sum, d) => sum + d.maxScore, 0);\n const overallScore = Math.round((totalScore / totalMax) * 100);\n\n // Determine readiness level\n let readinessLevel: EvalResult['readinessLevel'];\n const execDim = dimensions.find(d => d.name === 'Execution reliability');\n const execScore = execDim?.score || 0;\n\n if (execScore === 0) {\n readinessLevel = 'untested';\n } else if (overallScore >= 80 && execScore >= 8) {\n readinessLevel = 'production';\n } else if (overallScore >= 60 && execScore >= 6) {\n readinessLevel = 'staging';\n } else {\n readinessLevel = 'development';\n }\n\n // Generate recommendations\n const recommendations: string[] = [];\n for (const dim of dimensions) {\n if (dim.status === 'fail') {\n recommendations.push(`Fix: ${dim.name} — ${dim.details}`);\n } else if (dim.status === 'warn') {\n recommendations.push(`Improve: ${dim.name} — ${dim.details}`);\n }\n }\n\n return {\n agent: agentName,\n squad,\n overallScore,\n readinessLevel,\n dimensions,\n recommendations,\n };\n}\n\n// ─── Display ─────────────────────────────────────────────────────────────────\n\nfunction renderBar(score: number, max: number): string {\n const filled = Math.round((score / max) * 10);\n const empty = 10 - filled;\n const bar = chalk.green('█'.repeat(filled)) + chalk.dim('░'.repeat(empty));\n return `${bar} ${score}/${max}`;\n}\n\nfunction renderReadinessLevel(level: EvalResult['readinessLevel']): string {\n switch (level) {\n case 'untested': return chalk.red('UNTESTED');\n case 'development': return chalk.yellow('DEVELOPMENT');\n case 'staging': return chalk.blue('STAGING');\n case 'production': return chalk.green('PRODUCTION');\n }\n}\n\nfunction renderResult(result: EvalResult): void {\n writeLine(`\n${chalk.bold(`Agent Readiness: ${result.squad}/${result.agent}`)}\n${chalk.dim('━'.repeat(50))}\n`);\n\n for (const dim of result.dimensions) {\n const icon = dim.status === 'pass' ? chalk.green('✓')\n : dim.status === 'warn' ? chalk.yellow('⚠')\n : chalk.red('✗');\n writeLine(` ${icon} ${dim.name.padEnd(22)} ${renderBar(dim.score, dim.maxScore)}`);\n }\n\n writeLine(`\n Overall readiness: ${chalk.bold(String(result.overallScore) + '%')} — ${renderReadinessLevel(result.readinessLevel)}\n`);\n\n if (result.recommendations.length > 0) {\n writeLine(` ${chalk.bold('Recommendations:')}`);\n for (const rec of result.recommendations) {\n writeLine(` ${chalk.dim('→')} ${rec}`);\n }\n writeLine('');\n }\n}\n\n// ─── Commands ────────────────────────────────────────────────────────────────\n\nexport async function evalCommand(target: string, options: {\n json?: boolean;\n verbose?: boolean;\n}): Promise<void> {\n const squadsDir = findSquadsDir();\n if (!squadsDir) {\n console.error(chalk.red('No .agents/squads/ directory found.'));\n writeLine(chalk.dim('Run: squads init'));\n return;\n }\n\n // Parse target: squad/agent or squad\n const parts = target.split('/');\n const squadName = parts[0];\n const agentFilter = parts[1]; // optional\n\n // Validate squad exists\n const squad = loadSquad(squadName);\n if (!squad) {\n console.error(chalk.red(`Squad not found: ${squadName}`));\n return;\n }\n\n // Get agents to evaluate\n const allAgents = listAgents(squadsDir, squadName);\n const agents = agentFilter\n ? allAgents.filter(a => a.name === agentFilter)\n : allAgents;\n\n if (agents.length === 0) {\n console.error(chalk.red(`No agents found${agentFilter ? `: ${agentFilter}` : ''}`));\n return;\n }\n\n const results: EvalResult[] = [];\n\n for (const agent of agents) {\n if (!agent.filePath) continue;\n const result = evaluateAgent(squadName, agent.name, agent.filePath);\n results.push(result);\n }\n\n if (options.json) {\n writeLine(JSON.stringify(results, null, 2));\n return;\n }\n\n // Render results\n for (const result of results) {\n renderResult(result);\n }\n\n // Summary if evaluating multiple agents\n if (results.length > 1) {\n const avgScore = Math.round(results.reduce((sum, r) => sum + r.overallScore, 0) / results.length);\n const levels = results.reduce((acc, r) => {\n acc[r.readinessLevel] = (acc[r.readinessLevel] || 0) + 1;\n return acc;\n }, {} as Record<string, number>);\n\n writeLine(chalk.bold('Squad Summary'));\n writeLine(chalk.dim('━'.repeat(50)));\n writeLine(` Agents evaluated: ${results.length}`);\n writeLine(` Average score: ${avgScore}%`);\n for (const [level, count] of Object.entries(levels)) {\n writeLine(` ${renderReadinessLevel(level as EvalResult['readinessLevel'])}: ${count}`);\n }\n writeLine('');\n }\n\n await track('cli.eval', {\n squad: squadName,\n agents: results.length,\n avgScore: Math.round(results.reduce((sum, r) => sum + r.overallScore, 0) / results.length),\n });\n}\n\n// ─── Command Registration ────────────────────────────────────────────────────\n\nexport function registerEvalCommand(program: Command): void {\n program\n .command('eval <target>')\n .description('Evaluate agent readiness for deployment (e.g., squads eval company/coo)')\n .option('-j, --json', 'Output as JSON')\n .option('-v, --verbose', 'Show detailed scoring info')\n .action((target, options) => evalCommand(target, {\n json: options.json,\n verbose: options.verbose,\n }));\n}\n","/**\n * squads cognition — business cognition engine.\n *\n * Subcommands:\n * squads cognition brief — executive summary\n * squads cognition beliefs — world model\n * squads cognition decisions — decision log with scores\n * squads cognition reflect — trigger and display a reflection\n */\n\nimport { Command } from 'commander';\nimport {\n colors,\n bold,\n RESET,\n writeLine,\n} from '../lib/terminal.js';\n\ninterface Belief {\n belief_key: string;\n domain: string;\n statement: string;\n confidence: number;\n temperature: string;\n revision: number;\n}\n\ninterface CognitionSignal {\n source: string;\n}\n\ninterface CognitionDecision {\n id: number;\n title: string;\n}\n\ninterface CognitionReflectionSummary {\n created_at: string;\n assessment: string;\n}\n\ninterface CognitionBrief {\n generated_at: string;\n hot_beliefs?: Belief[];\n recent_signals?: CognitionSignal[];\n pending_decisions?: CognitionDecision[];\n latest_reflection?: CognitionReflectionSummary;\n}\n\ninterface Decision {\n id: number;\n title: string;\n reasoning: string;\n outcome_score: number | null;\n decided_at: string;\n decided_by: string;\n}\n\ninterface Insight {\n type: string;\n message: string;\n}\n\ninterface PriorityAdjustment {\n description?: string;\n}\n\ninterface Reflection {\n created_at: string;\n assessment: string;\n insights?: Insight[];\n priority_adjustments?: (string | PriorityAdjustment)[];\n}\n\nasync function apiFetch<T = unknown>(path: string, options?: RequestInit): Promise<T | null> {\n const { loadSession } = await import('../lib/auth.js');\n const { getApiUrl } = await import('../lib/env-config.js');\n const session = loadSession();\n if (!session?.accessToken || session.status !== 'active') {\n writeLine(` ${colors.red}Not logged in.${RESET} Run ${colors.cyan}squads login${RESET} first.`);\n return null;\n }\n const apiUrl = getApiUrl();\n try {\n const res = await fetch(`${apiUrl}${path}`, {\n ...options,\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${session.accessToken}`,\n ...(options?.headers || {}),\n },\n signal: AbortSignal.timeout(10000),\n });\n if (!res.ok) {\n writeLine(` ${colors.red}API error:${RESET} ${res.status} ${res.statusText}`);\n return null;\n }\n return (await res.json()) as T;\n } catch (error) {\n const msg = error instanceof Error && error.name === 'TimeoutError'\n ? 'Request timed out.'\n : 'API unavailable.';\n writeLine(` ${colors.yellow}${msg}${RESET}`);\n return null;\n }\n}\n\nasync function briefCommand(): Promise<void> {\n const data = await apiFetch<CognitionBrief>('/cognition/brief');\n if (!data) return;\n\n writeLine();\n writeLine(` ${bold}Executive Brief${RESET} ${colors.dim}${data.generated_at}${RESET}`);\n writeLine();\n\n // Hot beliefs\n if (data.hot_beliefs && data.hot_beliefs.length > 0) {\n writeLine(` ${colors.red}Hot Beliefs${RESET}`);\n for (const b of data.hot_beliefs) {\n const conf = Math.round(b.confidence * 100);\n const color = conf >= 70 ? colors.green : conf >= 40 ? colors.yellow : colors.red;\n writeLine(` ${color}${conf}%${RESET} ${bold}${b.belief_key}${RESET} ${b.statement}`);\n }\n writeLine();\n }\n\n // Recent signals\n if (data.recent_signals && data.recent_signals.length > 0) {\n writeLine(` ${colors.cyan}Signals (24h)${RESET} ${colors.dim}${data.recent_signals.length} total${RESET}`);\n const bySource: Record<string, number> = {};\n for (const s of data.recent_signals) {\n bySource[s.source] = (bySource[s.source] || 0) + 1;\n }\n for (const [source, count] of Object.entries(bySource)) {\n writeLine(` ${colors.dim}${source}:${RESET} ${count}`);\n }\n writeLine();\n }\n\n // Pending decisions\n if (data.pending_decisions && data.pending_decisions.length > 0) {\n writeLine(` ${colors.yellow}Pending Decisions${RESET}`);\n for (const d of data.pending_decisions) {\n writeLine(` ${colors.dim}#${d.id}${RESET} ${d.title}`);\n }\n writeLine();\n }\n\n // Latest reflection\n if (data.latest_reflection) {\n writeLine(` ${colors.purple}Latest Reflection${RESET} ${colors.dim}${data.latest_reflection.created_at}${RESET}`);\n writeLine(` ${data.latest_reflection.assessment}`);\n writeLine();\n }\n\n if (!data.hot_beliefs?.length && !data.recent_signals?.length && !data.pending_decisions?.length && !data.latest_reflection) {\n writeLine(` ${colors.dim}No cognition data yet. Seed beliefs with:${RESET}`);\n writeLine(` ${colors.cyan}$ squads cognition beliefs${RESET}`);\n writeLine();\n }\n}\n\nasync function beliefsCommand(options: { domain?: string; json?: boolean }): Promise<void> {\n const params = new URLSearchParams();\n if (options.domain) params.set('domain', options.domain);\n const path = `/cognition/beliefs${params.toString() ? '?' + params.toString() : ''}`;\n const data = await apiFetch<Belief[]>(path);\n if (!data) return;\n\n if (options.json) {\n writeLine(JSON.stringify(data, null, 2));\n return;\n }\n\n writeLine();\n writeLine(` ${bold}World Model${RESET} ${colors.dim}${data.length} beliefs${RESET}`);\n writeLine();\n\n // Group by domain\n const byDomain: Record<string, Belief[]> = {};\n for (const b of data) {\n const d = b.domain || 'other';\n if (!byDomain[d]) byDomain[d] = [];\n byDomain[d].push(b);\n }\n\n for (const [domain, beliefs] of Object.entries(byDomain)) {\n writeLine(` ${colors.cyan}${domain}${RESET}`);\n for (const b of beliefs) {\n const conf = Math.round(b.confidence * 100);\n const tempIcon = b.temperature === 'hot' ? `${colors.red}*${RESET}` : b.temperature === 'cold' ? `${colors.dim}~${RESET}` : ' ';\n const confColor = conf >= 70 ? colors.green : conf >= 40 ? colors.yellow : colors.red;\n writeLine(` ${tempIcon} ${confColor}${conf}%${RESET} ${bold}${b.belief_key}${RESET} ${colors.dim}r${b.revision}${RESET}`);\n writeLine(` ${b.statement}`);\n }\n writeLine();\n }\n}\n\nasync function decisionsCommand(options: { evaluated?: boolean; json?: boolean }): Promise<void> {\n const params = new URLSearchParams();\n if (options.evaluated !== undefined) params.set('evaluated', String(options.evaluated));\n const path = `/cognition/decisions${params.toString() ? '?' + params.toString() : ''}`;\n const data = await apiFetch<Decision[]>(path);\n if (!data) return;\n\n if (options.json) {\n writeLine(JSON.stringify(data, null, 2));\n return;\n }\n\n writeLine();\n writeLine(` ${bold}Decision Journal${RESET} ${colors.dim}${data.length} decisions${RESET}`);\n writeLine();\n\n for (const d of data) {\n const score = d.outcome_score !== null && d.outcome_score !== undefined\n ? `${d.outcome_score > 0 ? colors.green : d.outcome_score < 0 ? colors.red : colors.yellow}${d.outcome_score.toFixed(1)}${RESET}`\n : `${colors.dim}pending${RESET}`;\n writeLine(` ${colors.dim}#${d.id}${RESET} ${bold}${d.title}${RESET} score: ${score}`);\n writeLine(` ${colors.dim}${d.reasoning}${RESET}`);\n writeLine(` ${colors.dim}decided: ${d.decided_at} by ${d.decided_by}${RESET}`);\n writeLine();\n }\n}\n\nasync function reflectCommand(options: { scope?: string }): Promise<void> {\n const scope = options.scope || 'business';\n writeLine();\n writeLine(` ${colors.purple}Reflecting...${RESET} scope: ${scope}`);\n\n const data = await apiFetch<Reflection>('/cognition/reflect', {\n method: 'POST',\n body: JSON.stringify({ scope }),\n });\n if (!data) return;\n\n writeLine();\n writeLine(` ${bold}Reflection${RESET} ${colors.dim}${data.created_at}${RESET}`);\n writeLine();\n writeLine(` ${data.assessment}`);\n writeLine();\n\n if (data.insights && data.insights.length > 0) {\n writeLine(` ${colors.cyan}Insights${RESET}`);\n for (const i of data.insights) {\n const icon = i.type === 'warning' ? `${colors.yellow}!${RESET}` : `${colors.cyan}>${RESET}`;\n writeLine(` ${icon} ${i.message}`);\n }\n writeLine();\n }\n\n if (data.priority_adjustments && data.priority_adjustments.length > 0) {\n writeLine(` ${colors.yellow}Priority Adjustments${RESET}`);\n for (const a of data.priority_adjustments) {\n writeLine(` - ${typeof a === 'string' ? a : a.description || JSON.stringify(a)}`);\n }\n writeLine();\n }\n}\n\nexport function registerCognitionCommand(program: Command): void {\n const cmd = program\n .command('cognition')\n .description('Business cognition engine — beliefs, decisions, reflections')\n .addHelpText('after', `\nExamples:\n $ squads cognition brief Executive summary (hot beliefs + signals + decisions)\n $ squads cognition beliefs World model with confidence scores\n $ squads cognition decisions Decision journal with outcome scores\n $ squads cognition reflect Trigger meta-cognition analysis\n`)\n .action(() => {\n cmd.outputHelp();\n });\n\n cmd\n .command('brief')\n .description('Executive summary: hot beliefs + recent signals + pending decisions')\n .action(async () => briefCommand());\n\n cmd\n .command('beliefs')\n .description('Display world model beliefs')\n .option('-d, --domain <domain>', 'Filter by domain (revenue/product/operations/market/team)')\n .option('-j, --json', 'Output as JSON')\n .action(async (options) => beliefsCommand(options));\n\n cmd\n .command('decisions')\n .description('Decision journal with outcome scores')\n .option('-e, --evaluated', 'Only show evaluated decisions')\n .option('-j, --json', 'Output as JSON')\n .action(async (options) => decisionsCommand(options));\n\n cmd\n .command('reflect')\n .description('Trigger meta-cognition reflection')\n .option('-s, --scope <scope>', 'Reflection scope (business, squad:X, agent:X)', 'business')\n .action(async (options) => reflectCommand(options));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAA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AO;AACd,cAAY,KAAK;AACnB;","names":["existsSync","join","homedir","chalk","config","existsSync","readFileSync","readdirSync","join","existsSync","readFileSync","join","config","join","existsSync","readFileSync","colors","join","existsSync","readFileSync","readdirSync","program","program","chalk","existsSync","readFileSync","writeFileSync","unlinkSync","readdirSync","mkdirSync","join","homedir","spawn","join","homedir","existsSync","readFileSync","readdirSync","unlinkSync","mkdirSync","writeFileSync","running","chalk","spawn","showStatus","program","chalk","API_URL","chalk","program","chalk","existsSync","readFileSync","execSync","session","chalk","exec","execSync","existsSync","readFileSync","program","chalk","existsSync","readFileSync","readdirSync","join","matter","readFileSync","matter","join","existsSync","readdirSync","chalk","program","loadSession","getApiUrl","session","program","chalk","join","homedir","existsSync","colors","RESET","progress","kpi","readFileSync"]}