squads-cli 0.2.1 → 0.2.2

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 (129) hide show
  1. package/dist/{autonomy-PSVZVX7A.js → autonomy-GARI6J2J.js} +4 -4
  2. package/dist/chunk-NP5BDPE6.js +240 -0
  3. package/dist/chunk-NP5BDPE6.js.map +1 -0
  4. package/dist/chunk-O632SBON.js +62 -0
  5. package/dist/chunk-O632SBON.js.map +1 -0
  6. package/dist/{chunk-QHNUMM4V.js → chunk-QRNR4GIT.js} +3 -2
  7. package/dist/chunk-QRNR4GIT.js.map +1 -0
  8. package/dist/chunk-XTHZT53Y.js +364 -0
  9. package/dist/chunk-XTHZT53Y.js.map +1 -0
  10. package/dist/cli.js +1026 -88
  11. package/dist/cli.js.map +1 -1
  12. package/dist/{context-GWPF4SEY.js → context-PYTO2UQG.js} +7 -7
  13. package/dist/{context-feed-AJGVAR6H.js → context-feed-TLVZZ24S.js} +15 -15
  14. package/dist/{cost-XBCDJ7XC.js → cost-OALPURUQ.js} +7 -7
  15. package/dist/{dashboard-LGT2B2BL.js → dashboard-HQIEHTZC.js} +14 -14
  16. package/dist/{doctor-XPUIIBHJ.js → doctor-TWHMR23W.js} +4 -4
  17. package/dist/{exec-OUXM7JBF.js → exec-DYLI4TXY.js} +2 -2
  18. package/dist/{feedback-KNAOG5QK.js → feedback-5AEACUX6.js} +8 -8
  19. package/dist/{goal-BVHV5573.js → goal-XUNV3CKV.js} +8 -8
  20. package/dist/{health-4UXN44PF.js → health-ZF3HSA4W.js} +4 -4
  21. package/dist/{history-ILH3SWHB.js → history-WP6R5BNG.js} +5 -5
  22. package/dist/history-WP6R5BNG.js.map +1 -0
  23. package/dist/{init-XQZ7BOGT.js → init-BQSCG57S.js} +115 -6
  24. package/dist/init-BQSCG57S.js.map +1 -0
  25. package/dist/{kpi-RQIU7WGK.js → kpi-VBGDO4GI.js} +6 -6
  26. package/dist/{learn-OIFUVZAS.js → learn-C4B2PQ5J.js} +8 -8
  27. package/dist/{login-DXZANWZY.js → login-F6ITE7PR.js} +7 -7
  28. package/dist/{memory-T3ACCS7E.js → memory-33HYD6AN.js} +11 -11
  29. package/dist/observability-CL23L7LD.js +20 -0
  30. package/dist/observability-CL23L7LD.js.map +1 -0
  31. package/dist/org-cycle-Q74OT4I4.js +130 -0
  32. package/dist/org-cycle-Q74OT4I4.js.map +1 -0
  33. package/dist/{progress-DAUZMT3N.js → progress-P2EIZBKP.js} +5 -5
  34. package/dist/{providers-3P5D2XL5.js → providers-LE744DM6.js} +2 -2
  35. package/dist/repo-enforcement-JJQMKDAU.js +75 -0
  36. package/dist/repo-enforcement-JJQMKDAU.js.map +1 -0
  37. package/dist/{results-UECWGLTB.js → results-6TH33HPN.js} +6 -6
  38. package/dist/{run-I6KAXU6U.js → run-DOY5SGF3.js} +3713 -3688
  39. package/dist/run-DOY5SGF3.js.map +1 -0
  40. package/dist/run-context-GB6GUCKZ.js +26 -0
  41. package/dist/run-context-GB6GUCKZ.js.map +1 -0
  42. package/dist/{status-AQNLDZVN.js → status-PFFB2NV6.js} +16 -16
  43. package/dist/{sync-ZI3MHA4G.js → sync-FR6LQJ4C.js} +12 -12
  44. package/dist/templates/seed/config/SYSTEM.md +6 -0
  45. package/dist/templates/seed/idp/catalog/service.yaml.template +25 -0
  46. package/dist/templates/seed/memory/_squad/goals.md +23 -0
  47. package/dist/templates/seed/memory/_squad/priorities.md +25 -0
  48. package/dist/templates/seed/memory/company/company.md +31 -0
  49. package/dist/templates/seed/skills/squads-cli/SKILL.md +302 -57
  50. package/dist/templates/seed/skills/squads-cli/references/commands.md +181 -0
  51. package/dist/templates/seed/squads/company/company-critic.md +12 -4
  52. package/dist/templates/seed/squads/company/company-eval.md +12 -4
  53. package/dist/templates/seed/squads/company/event-dispatcher.md +14 -4
  54. package/dist/templates/seed/squads/company/goal-tracker.md +12 -4
  55. package/dist/templates/seed/squads/company/manager.md +17 -11
  56. package/dist/templates/seed/squads/engineering/code-reviewer.md +14 -2
  57. package/dist/templates/seed/squads/engineering/issue-solver.md +10 -2
  58. package/dist/templates/seed/squads/engineering/test-writer.md +15 -5
  59. package/dist/templates/seed/squads/intelligence/intel-critic.md +19 -2
  60. package/dist/templates/seed/squads/intelligence/intel-eval.md +18 -1
  61. package/dist/templates/seed/squads/intelligence/intel-lead.md +12 -4
  62. package/dist/templates/seed/squads/marketing/content-drafter.md +14 -4
  63. package/dist/templates/seed/squads/marketing/growth-analyst.md +14 -2
  64. package/dist/templates/seed/squads/marketing/social-poster.md +15 -3
  65. package/dist/templates/seed/squads/operations/finance-tracker.md +11 -3
  66. package/dist/templates/seed/squads/operations/goal-tracker.md +14 -2
  67. package/dist/templates/seed/squads/operations/ops-lead.md +14 -4
  68. package/dist/templates/seed/squads/product/lead.md +11 -3
  69. package/dist/templates/seed/squads/product/scanner.md +12 -4
  70. package/dist/templates/seed/squads/product/worker.md +12 -4
  71. package/dist/templates/seed/squads/research/analyst.md +12 -4
  72. package/dist/templates/seed/squads/research/lead.md +11 -5
  73. package/dist/templates/seed/squads/research/synthesizer.md +12 -4
  74. package/dist/tier-detect-YX2HPNNR.js +15 -0
  75. package/dist/tier-detect-YX2HPNNR.js.map +1 -0
  76. package/package.json +1 -1
  77. package/templates/seed/config/SYSTEM.md +6 -0
  78. package/templates/seed/idp/catalog/service.yaml.template +25 -0
  79. package/templates/seed/memory/_squad/goals.md +23 -0
  80. package/templates/seed/memory/_squad/priorities.md +25 -0
  81. package/templates/seed/memory/company/company.md +31 -0
  82. package/templates/seed/skills/squads-cli/SKILL.md +302 -57
  83. package/templates/seed/skills/squads-cli/references/commands.md +181 -0
  84. package/templates/seed/squads/company/company-critic.md +12 -4
  85. package/templates/seed/squads/company/company-eval.md +12 -4
  86. package/templates/seed/squads/company/event-dispatcher.md +14 -4
  87. package/templates/seed/squads/company/goal-tracker.md +12 -4
  88. package/templates/seed/squads/company/manager.md +17 -11
  89. package/templates/seed/squads/engineering/code-reviewer.md +14 -2
  90. package/templates/seed/squads/engineering/issue-solver.md +10 -2
  91. package/templates/seed/squads/engineering/test-writer.md +15 -5
  92. package/templates/seed/squads/intelligence/intel-critic.md +19 -2
  93. package/templates/seed/squads/intelligence/intel-eval.md +18 -1
  94. package/templates/seed/squads/intelligence/intel-lead.md +12 -4
  95. package/templates/seed/squads/marketing/content-drafter.md +14 -4
  96. package/templates/seed/squads/marketing/growth-analyst.md +14 -2
  97. package/templates/seed/squads/marketing/social-poster.md +15 -3
  98. package/templates/seed/squads/operations/finance-tracker.md +11 -3
  99. package/templates/seed/squads/operations/goal-tracker.md +14 -2
  100. package/templates/seed/squads/operations/ops-lead.md +14 -4
  101. package/templates/seed/squads/product/lead.md +11 -3
  102. package/templates/seed/squads/product/scanner.md +12 -4
  103. package/templates/seed/squads/product/worker.md +12 -4
  104. package/templates/seed/squads/research/analyst.md +12 -4
  105. package/templates/seed/squads/research/lead.md +11 -5
  106. package/templates/seed/squads/research/synthesizer.md +12 -4
  107. package/dist/chunk-QHNUMM4V.js.map +0 -1
  108. package/dist/history-ILH3SWHB.js.map +0 -1
  109. package/dist/init-XQZ7BOGT.js.map +0 -1
  110. package/dist/run-I6KAXU6U.js.map +0 -1
  111. /package/dist/{autonomy-PSVZVX7A.js.map → autonomy-GARI6J2J.js.map} +0 -0
  112. /package/dist/{context-GWPF4SEY.js.map → context-PYTO2UQG.js.map} +0 -0
  113. /package/dist/{context-feed-AJGVAR6H.js.map → context-feed-TLVZZ24S.js.map} +0 -0
  114. /package/dist/{cost-XBCDJ7XC.js.map → cost-OALPURUQ.js.map} +0 -0
  115. /package/dist/{dashboard-LGT2B2BL.js.map → dashboard-HQIEHTZC.js.map} +0 -0
  116. /package/dist/{doctor-XPUIIBHJ.js.map → doctor-TWHMR23W.js.map} +0 -0
  117. /package/dist/{exec-OUXM7JBF.js.map → exec-DYLI4TXY.js.map} +0 -0
  118. /package/dist/{feedback-KNAOG5QK.js.map → feedback-5AEACUX6.js.map} +0 -0
  119. /package/dist/{goal-BVHV5573.js.map → goal-XUNV3CKV.js.map} +0 -0
  120. /package/dist/{health-4UXN44PF.js.map → health-ZF3HSA4W.js.map} +0 -0
  121. /package/dist/{kpi-RQIU7WGK.js.map → kpi-VBGDO4GI.js.map} +0 -0
  122. /package/dist/{learn-OIFUVZAS.js.map → learn-C4B2PQ5J.js.map} +0 -0
  123. /package/dist/{login-DXZANWZY.js.map → login-F6ITE7PR.js.map} +0 -0
  124. /package/dist/{memory-T3ACCS7E.js.map → memory-33HYD6AN.js.map} +0 -0
  125. /package/dist/{progress-DAUZMT3N.js.map → progress-P2EIZBKP.js.map} +0 -0
  126. /package/dist/{providers-3P5D2XL5.js.map → providers-LE744DM6.js.map} +0 -0
  127. /package/dist/{results-UECWGLTB.js.map → results-6TH33HPN.js.map} +0 -0
  128. /package/dist/{status-AQNLDZVN.js.map → status-PFFB2NV6.js.map} +0 -0
  129. /package/dist/{sync-ZI3MHA4G.js.map → sync-FR6LQJ4C.js.map} +0 -0
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
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,SAAS,cAAc;AACvB,SAAS,cAAAA,mBAAkB;AAC3B,SAAS,QAAAC,aAAY;AACrB,SAAS,WAAAC,gBAAe;AACxB,SAAS,eAAe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AA0C,CAAC;AAAA,EACrE,WAAW,IAAI,QAAQ,SAAS,mBAAmB,KAAK,IAAI,QAAQ,SAAS,QAAQ,GAAG;AACtF,YAAQ,MAAMA,OAAM,IAAI,sBAAsB,GAAG,IAAI,OAAO;AAC5D,YAAQ,MAAMA,OAAM,IAAI,mBAAmB,CAAC;AAC5C,YAAQ,MAAMA,OAAM,IAAI,6BAA6B,CAAC;AACtD,YAAQ,MAAMA,OAAM,IAAI,4CAA4C,CAAC;AAAA,EACvE,WAAW,IAAI,QAAQ,SAAS,YAAY,KAAK,IAAI,QAAQ,SAAS,KAAK,GAAG;AAC5E,YAAQ,MAAMA,OAAM,IAAI,uBAAuB,CAAC;AAChD,YAAQ,MAAMA,OAAM,IAAI,mBAAmB,CAAC;AAC5C,YAAQ,MAAMA,OAAM,IAAI,uCAAuC,CAAC;AAChE,YAAQ,MAAMA,OAAM,IAAI,wCAAwC,CAAC;AAAA,EACnE,OAAO;AAEL,YAAQ,MAAMA,OAAM,IAAI,UAAU,GAAG,IAAI,OAAO;AAChD,QAAI,QAAQ,IAAI,SAAS,QAAQ,IAAI,SAAS;AAC5C,cAAQ,MAAMA,OAAM,IAAI,gBAAgB,CAAC;AACzC,cAAQ,MAAMA,OAAM,IAAI,IAAI,KAAK,CAAC;AAAA,IACpC,OAAO;AACL,cAAQ,MAAMA,OAAM,IAAI,qCAAqC,CAAC;AAAA,IAChE;AAAA,EACF;AAEA,UAAQ,MAAMA,OAAM,IAAI,uCAAuC,CAAC;AAChE,UAAQ,MAAMA,OAAM,KAAK,wDAAwD,CAAC;AAElF,UAAQ,KAAK,CAAC;AAChB;AAGA,QAAQ,GAAG,qBAAqB,WAAW;AAC3C,QAAQ,GAAG,sBAAsB,WAAW;AAG5C,IAAI;AACF,QAAM,QAAQ,WAAW;AAC3B,SAAS,OAAO;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"]}
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","../src/lib/idp/catalog-loader.ts","../src/lib/idp/resolver.ts","../src/lib/idp/scorecard-engine.ts","../src/commands/catalog.ts","../src/commands/release-check.ts","../src/commands/observability.ts","../src/commands/tier.ts","../src/commands/services.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';\nimport { registerCatalogCommands } from './commands/catalog.js';\nimport { registerReleaseCommands } from './commands/release-check.js';\nimport { registerObservabilityCommands } from './commands/observability.js';\nimport { registerTierCommand } from './commands/tier.js';\nimport { registerServicesCommands } from './commands/services.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 .option('--org', 'Run all squads as a coordinated org cycle (scan → plan → execute → report)')\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 — alias for status\nprogram.command('list').description('List squads (alias for: squads status)').action(async () => {\n const { statusCommand } = await import('./commands/status.js');\n return statusCommand();\n});\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// IDP — service catalog, scorecards, release checks\nregisterCatalogCommands(program);\nregisterReleaseCommands(program);\nregisterObservabilityCommands(program);\nregisterTierCommand(program);\nregisterServicesCommands(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\":\"my-org/my-repo\",\"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","/**\n * Catalog loader — reads and parses YAML catalog entries from the IDP repo.\n */\n\nimport { readdirSync, readFileSync, existsSync } from 'fs';\nimport { join } from 'path';\nimport matter from 'gray-matter';\nimport { findIdpDir } from './resolver.js';\nimport type { CatalogEntry, ScorecardDefinition, DependencyGraph } from './types.js';\n\n/** Parse a YAML file using gray-matter's YAML engine */\nfunction loadYaml<T>(filePath: string): T | null {\n if (!existsSync(filePath)) return null;\n try {\n const raw = readFileSync(filePath, 'utf-8');\n // gray-matter parses YAML frontmatter — wrap raw YAML so it treats entire file as frontmatter\n const { data } = matter(`---\\n${raw}\\n---`);\n return data as T;\n } catch {\n return null;\n }\n}\n\n/** Load all catalog entries from the IDP catalog/ directory */\nexport function loadCatalog(): CatalogEntry[] {\n const idpDir = findIdpDir();\n if (!idpDir) return [];\n\n const catalogDir = join(idpDir, 'catalog');\n if (!existsSync(catalogDir)) return [];\n\n const entries: CatalogEntry[] = [];\n for (const file of readdirSync(catalogDir).filter(f => f.endsWith('.yaml')).sort()) {\n const entry = loadYaml<CatalogEntry>(join(catalogDir, file));\n if (entry?.metadata?.name) {\n entries.push(entry);\n }\n }\n return entries;\n}\n\n/** Load a single catalog entry by service name */\nexport function loadService(name: string): CatalogEntry | null {\n const idpDir = findIdpDir();\n if (!idpDir) return null;\n\n const filePath = join(idpDir, 'catalog', `${name}.yaml`);\n return loadYaml<CatalogEntry>(filePath);\n}\n\n/** Load a scorecard definition by name */\nexport function loadScorecard(name: string): ScorecardDefinition | null {\n const idpDir = findIdpDir();\n if (!idpDir) return null;\n\n const filePath = join(idpDir, 'scorecards', `${name}.yaml`);\n return loadYaml<ScorecardDefinition>(filePath);\n}\n\n/** Load the dependency graph */\nexport function loadDependencyGraph(): DependencyGraph | null {\n const idpDir = findIdpDir();\n if (!idpDir) return null;\n\n return loadYaml<DependencyGraph>(join(idpDir, 'dependencies', 'graph.yaml'));\n}\n","/**\n * IDP directory resolver — finds the IDP repo/directory.\n *\n * Resolution order:\n * 1. SQUADS_IDP_PATH env var (explicit override)\n * 2. .agents/idp/ in project root (co-located)\n * 3. ../idp/ sibling repo (our setup)\n * 4. ~/agents-squads/idp/ (absolute fallback)\n */\n\nimport { existsSync } from 'fs';\nimport { join, resolve } from 'path';\nimport { findProjectRoot } from '../squad-parser.js';\n\nexport function findIdpDir(): string | null {\n // 1. Explicit env var\n const envPath = process.env.SQUADS_IDP_PATH;\n if (envPath && existsSync(envPath)) {\n return resolve(envPath);\n }\n\n // 2. Co-located in project\n const projectRoot = findProjectRoot();\n if (projectRoot) {\n const colocated = join(projectRoot, '.agents', 'idp');\n if (existsSync(join(colocated, 'catalog'))) {\n return colocated;\n }\n\n // 3. Sibling repo\n const sibling = join(projectRoot, '..', 'idp');\n if (existsSync(join(sibling, 'catalog'))) {\n return resolve(sibling);\n }\n }\n\n // 4. Absolute fallback\n const home = process.env.HOME || process.env.USERPROFILE || '';\n const absolute = join(home, 'agents-squads', 'idp');\n if (existsSync(join(absolute, 'catalog'))) {\n return absolute;\n }\n\n return null;\n}\n","/**\n * Scorecard engine — evaluates services against quality checks.\n *\n * Sources data from:\n * - Local filesystem (README exists, build works)\n * - gh CLI (CI status, PRs, security alerts) — graceful if missing\n * - Git log (deploy frequency, recent activity)\n */\n\nimport { existsSync, readFileSync, statSync } from 'fs';\nimport { join } from 'path';\nimport { execSync } from 'child_process';\nimport type { CatalogEntry, ScorecardDefinition, ScorecardResult } from './types.js';\n\nfunction exec(cmd: string, cwd?: string): string | null {\n try {\n return execSync(cmd, { encoding: 'utf-8', timeout: 15000, cwd, stdio: ['pipe', 'pipe', 'pipe'] }).trim();\n } catch {\n return null;\n }\n}\n\nfunction ghAvailable(): boolean {\n return exec('gh --version') !== null;\n}\n\ninterface CheckResult {\n name: string;\n passed: boolean;\n weight: number;\n detail: string;\n}\n\nfunction runCheck(\n check: ScorecardDefinition['checks'][0],\n service: CatalogEntry,\n repoPath: string | null\n): CheckResult {\n const result: CheckResult = { name: check.name, passed: false, weight: check.weight, detail: 'unknown' };\n const repo = service.metadata.repo;\n\n switch (check.name) {\n case 'ci-passing': {\n if (!ghAvailable()) { result.detail = 'gh CLI not available'; break; }\n const out = exec(`gh api repos/${repo}/actions/runs?per_page=1&status=completed --jq '.[0].conclusion // empty'`);\n // GitHub API returns runs array directly\n const out2 = exec(`gh api repos/${repo}/actions/runs --jq '.workflow_runs[0].conclusion // empty'`);\n const conclusion = out || out2;\n if (conclusion === 'success') { result.passed = true; result.detail = 'latest run: success'; }\n else if (conclusion) { result.detail = `latest run: ${conclusion}`; }\n else { result.detail = 'no CI runs found'; }\n break;\n }\n\n case 'test-coverage': {\n // Would need CI output parsing — for v0.1, check if test command exists\n if (service.spec.ci.test_command && service.spec.ci.test_command !== 'null') {\n result.passed = true;\n result.detail = `test command defined: ${service.spec.ci.test_command}`;\n } else {\n result.detail = 'no test command configured';\n }\n break;\n }\n\n case 'build-succeeds': {\n if (repoPath && service.spec.ci.build_command) {\n const buildResult = exec(`cd \"${repoPath}\" && ${service.spec.ci.build_command} 2>&1`);\n if (buildResult !== null) { result.passed = true; result.detail = 'build passed'; }\n else { result.detail = 'build failed'; }\n } else {\n result.detail = repoPath ? 'no build command' : 'repo not found locally';\n }\n break;\n }\n\n case 'no-security-alerts': {\n if (!ghAvailable()) { result.detail = 'gh CLI not available'; break; }\n const alerts = exec(`gh api repos/${repo}/dependabot/alerts --jq '[.[] | select(.state==\"open\" and (.security_advisory.severity==\"high\" or .security_advisory.severity==\"critical\"))] | length'`);\n if (alerts === '0') { result.passed = true; result.detail = 'no high/critical alerts'; }\n else if (alerts) { result.detail = `${alerts} high/critical alerts`; }\n else { result.detail = 'could not check alerts'; }\n break;\n }\n\n case 'readme-exists': {\n if (repoPath) {\n const readmePath = join(repoPath, 'README.md');\n if (existsSync(readmePath)) {\n const size = statSync(readmePath).size;\n if (size > 100) { result.passed = true; result.detail = `README.md (${size} bytes)`; }\n else { result.detail = `README.md too short (${size} bytes)`; }\n } else {\n result.detail = 'README.md not found';\n }\n } else {\n result.detail = 'repo not found locally';\n }\n break;\n }\n\n case 'branch-protection': {\n if (!ghAvailable()) { result.detail = 'gh CLI not available'; break; }\n const protection = exec(`gh api repos/${repo}/branches/${service.spec.branches.default}/protection --jq '.required_status_checks.strict // false' 2>/dev/null`);\n if (protection && protection !== 'null') { result.passed = true; result.detail = 'branch protection enabled'; }\n else { result.detail = 'no branch protection'; }\n break;\n }\n\n case 'deploy-frequency': {\n if (!ghAvailable()) { result.detail = 'gh CLI not available'; break; }\n const runs = exec(`gh api repos/${repo}/actions/runs --jq '[.workflow_runs[] | select(.event==\"push\" and .head_branch==\"${service.spec.branches.default}\")] | length'`);\n const count = parseInt(runs || '0', 10);\n if (count > 0) { result.passed = true; result.detail = `${count} deploys recently`; }\n else { result.detail = 'no recent deploys'; }\n break;\n }\n\n case 'stale-prs': {\n if (!ghAvailable()) { result.detail = 'gh CLI not available'; break; }\n const stalePrs = exec(`gh pr list --repo ${repo} --state open --json updatedAt --jq '[.[] | select((now - (.updatedAt | fromdateiso8601)) > 1209600)] | length'`);\n const count = parseInt(stalePrs || '0', 10);\n if (count === 0) { result.passed = true; result.detail = 'no stale PRs'; }\n else { result.detail = `${count} PRs stale >14d`; }\n break;\n }\n\n case 'recent-activity': {\n if (repoPath) {\n const commits = exec(`git -C \"${repoPath}\" log --since=\"30 days ago\" --oneline 2>/dev/null | wc -l`);\n const count = parseInt(commits?.trim() || '0', 10);\n if (count > 0) { result.passed = true; result.detail = `${count} commits in last 30d`; }\n else { result.detail = 'no commits in 30 days'; }\n } else if (ghAvailable()) {\n const out = exec(`gh api repos/${repo}/commits?per_page=1 --jq '.[0].commit.committer.date // empty'`);\n if (out) { result.passed = true; result.detail = `last commit: ${out.slice(0, 10)}`; }\n else { result.detail = 'no recent commits'; }\n } else {\n result.detail = 'repo not found locally';\n }\n break;\n }\n\n case 'no-stale-prs': {\n if (!ghAvailable()) { result.detail = 'gh CLI not available'; break; }\n const stalePrs = exec(`gh pr list --repo ${repo} --state open --json updatedAt --jq '[.[] | select((now - (.updatedAt | fromdateiso8601)) > 604800)] | length'`);\n const count = parseInt(stalePrs || '0', 10);\n if (count === 0) { result.passed = true; result.detail = 'no stale PRs'; }\n else { result.detail = `${count} PRs stale >7d`; }\n break;\n }\n\n case 'clean-structure': {\n // For domain repos — check no binaries or misplaced files in root\n result.passed = true;\n result.detail = 'check not implemented (v0.2)';\n break;\n }\n\n default:\n result.detail = `unknown check: ${check.name}`;\n }\n\n return result;\n}\n\n/** Find the local path for a repo */\nfunction findRepoPath(repoFullName: string): string | null {\n const repoName = repoFullName.split('/')[1];\n if (!repoName) return null;\n\n const home = process.env.HOME || '';\n const candidates = [\n join(home, 'agents-squads', repoName),\n join(process.cwd(), '..', repoName),\n ];\n\n for (const candidate of candidates) {\n if (existsSync(candidate)) return candidate;\n }\n return null;\n}\n\n/** Run all scorecard checks for a service */\nexport function evaluateService(\n service: CatalogEntry,\n scorecard: ScorecardDefinition\n): ScorecardResult {\n const repoPath = findRepoPath(service.metadata.repo);\n const checks: CheckResult[] = [];\n\n for (const check of scorecard.checks) {\n checks.push(runCheck(check, service, repoPath));\n }\n\n const totalWeight = checks.reduce((sum, c) => sum + c.weight, 0);\n const earnedWeight = checks.filter(c => c.passed).reduce((sum, c) => sum + c.weight, 0);\n const score = totalWeight > 0 ? Math.round((earnedWeight / totalWeight) * 100) : 0;\n\n // Determine grade\n let grade = 'F';\n const sortedGrades = Object.entries(scorecard.grades).sort((a, b) => b[1].min - a[1].min);\n for (const [g, { min }] of sortedGrades) {\n if (score >= min) { grade = g; break; }\n }\n\n return {\n service: service.metadata.name,\n scorecard: scorecard.metadata.name,\n score,\n grade,\n checks,\n timestamp: new Date().toISOString(),\n };\n}\n","/**\n * squads catalog — service catalog commands.\n *\n * squads catalog list Show all services\n * squads catalog show <service> Service details\n * squads catalog check <service> Validate against scorecard\n */\n\nimport { Command } from 'commander';\nimport { loadCatalog, loadService, loadScorecard } from '../lib/idp/catalog-loader.js';\nimport { evaluateService } from '../lib/idp/scorecard-engine.js';\nimport { findIdpDir } from '../lib/idp/resolver.js';\nimport type { CatalogEntry } from '../lib/idp/types.js';\nimport { colors, bold, RESET, writeLine } from '../lib/terminal.js';\n\nfunction noIdp(): boolean {\n if (!findIdpDir()) {\n writeLine(` ${colors.red}IDP not found${RESET}`);\n writeLine(` ${colors.dim}Set SQUADS_IDP_PATH or clone the idp repo as a sibling directory.${RESET}`);\n return true;\n }\n return false;\n}\n\nexport function registerCatalogCommands(program: Command): void {\n const catalog = program\n .command('catalog')\n .description('Service catalog — browse, inspect, and validate services');\n\n // ── catalog list ──\n catalog\n .command('list')\n .description('List all services in the catalog')\n .option('--type <type>', 'Filter by type (product, domain)')\n .option('--json', 'Output as JSON')\n .action((opts) => {\n if (noIdp()) return;\n\n const entries = loadCatalog();\n if (entries.length === 0) {\n writeLine(' No catalog entries found.');\n return;\n }\n\n const filtered = opts.type\n ? entries.filter(e => e.spec.type === opts.type)\n : entries;\n\n if (opts.json) {\n console.log(JSON.stringify(filtered.map(e => ({\n name: e.metadata.name,\n type: e.spec.type,\n stack: e.spec.stack,\n owner: e.metadata.owner,\n repo: e.metadata.repo,\n })), null, 2));\n return;\n }\n\n writeLine();\n writeLine(` ${bold}Service Catalog${RESET} (${filtered.length} services)`);\n writeLine();\n\n // Group by type\n const products = filtered.filter(e => e.spec.type === 'product');\n const domains = filtered.filter(e => e.spec.type === 'domain');\n\n if (products.length > 0) {\n writeLine(` ${colors.cyan}Product Services${RESET}`);\n writeLine();\n for (const e of products) {\n const ci = e.spec.ci.template ? `ci:${e.spec.ci.template}` : 'no-ci';\n const deploy = e.spec.deploy?.target || 'manual';\n writeLine(` ${bold}${e.metadata.name}${RESET} ${colors.dim}${e.spec.stack} | ${ci} | deploy:${deploy} | owner:${e.metadata.owner}${RESET}`);\n writeLine(` ${colors.dim}${e.metadata.description}${RESET}`);\n }\n writeLine();\n }\n\n if (domains.length > 0) {\n writeLine(` ${colors.cyan}Domain Repos${RESET}`);\n writeLine();\n for (const e of domains) {\n writeLine(` ${e.metadata.name} ${colors.dim}owner:${e.metadata.owner} | ${e.metadata.repo}${RESET}`);\n }\n writeLine();\n }\n });\n\n // ── catalog show <service> ──\n catalog\n .command('show <service>')\n .description('Show detailed info for a service')\n .option('--json', 'Output as JSON')\n .action((serviceName: string, opts) => {\n if (noIdp()) return;\n\n const entry = loadService(serviceName);\n if (!entry) {\n writeLine(` ${colors.red}Service not found: ${serviceName}${RESET}`);\n writeLine(` ${colors.dim}Run 'squads catalog list' to see available services.${RESET}`);\n return;\n }\n\n if (opts.json) {\n console.log(JSON.stringify(entry, null, 2));\n return;\n }\n\n writeLine();\n writeLine(` ${bold}${entry.metadata.name}${RESET} ${colors.dim}${entry.spec.type}${RESET}`);\n writeLine(` ${entry.metadata.description}`);\n writeLine();\n\n writeLine(` ${colors.cyan}General${RESET}`);\n writeLine(` Owner: ${entry.metadata.owner}`);\n writeLine(` Repo: ${entry.metadata.repo}`);\n writeLine(` Stack: ${entry.spec.stack}${entry.spec.framework ? ` (${entry.spec.framework})` : ''}`);\n writeLine(` Scorecard: ${entry.spec.scorecard}`);\n writeLine(` Tags: ${entry.metadata.tags?.join(', ') || 'none'}`);\n writeLine();\n\n writeLine(` ${colors.cyan}Branches${RESET}`);\n writeLine(` Default: ${entry.spec.branches.default}`);\n writeLine(` Workflow: ${entry.spec.branches.workflow}`);\n if (entry.spec.branches.development) {\n writeLine(` Dev branch: ${entry.spec.branches.development}`);\n }\n writeLine();\n\n if (entry.spec.ci.template) {\n writeLine(` ${colors.cyan}CI/CD${RESET}`);\n writeLine(` Template: ${entry.spec.ci.template}`);\n writeLine(` Checks: ${entry.spec.ci.required_checks.join(', ') || 'none'}`);\n if (entry.spec.ci.build_command) writeLine(` Build: ${entry.spec.ci.build_command}`);\n if (entry.spec.ci.test_command) writeLine(` Test: ${entry.spec.ci.test_command}`);\n writeLine();\n }\n\n if (entry.spec.deploy) {\n writeLine(` ${colors.cyan}Deploy${RESET}`);\n writeLine(` Target: ${entry.spec.deploy.target}`);\n writeLine(` Trigger: ${entry.spec.deploy.trigger}`);\n if (entry.spec.deploy.environments) {\n for (const env of entry.spec.deploy.environments) {\n writeLine(` ${env.name}: ${env.url}`);\n }\n }\n writeLine();\n }\n\n if (entry.spec.dependencies.runtime.length > 0) {\n writeLine(` ${colors.cyan}Dependencies${RESET}`);\n for (const dep of entry.spec.dependencies.runtime) {\n const req = dep.required === false ? '(optional)' : '(required)';\n writeLine(` → ${dep.service} ${dep.version || ''} ${req}`);\n writeLine(` ${colors.dim}${dep.description}${RESET}`);\n }\n writeLine();\n }\n\n if (entry.spec.health.length > 0) {\n writeLine(` ${colors.cyan}Health Endpoints${RESET}`);\n for (const h of entry.spec.health) {\n writeLine(` ${h.name}: ${h.url}`);\n }\n writeLine();\n }\n });\n\n // ── catalog check <service> ──\n catalog\n .command('check [service]')\n .description('Run scorecard checks for a service (or all)')\n .option('--json', 'Output as JSON')\n .action((serviceName: string | undefined, opts) => {\n if (noIdp()) return;\n\n const entries = serviceName\n ? [loadService(serviceName)].filter(Boolean) as CatalogEntry[]\n : loadCatalog();\n\n if (entries.length === 0) {\n writeLine(` ${colors.red}No services found${RESET}`);\n return;\n }\n\n const results = [];\n\n for (const entry of entries) {\n const scorecard = loadScorecard(entry.spec.scorecard);\n if (!scorecard) {\n writeLine(` ${colors.dim}No scorecard '${entry.spec.scorecard}' for ${entry.metadata.name}${RESET}`);\n continue;\n }\n\n const result = evaluateService(entry, scorecard);\n results.push(result);\n\n if (!opts.json) {\n const gradeColor = result.grade === 'A' ? colors.green\n : result.grade === 'B' ? colors.cyan\n : result.grade === 'C' ? colors.yellow\n : colors.red;\n\n writeLine();\n writeLine(` ${bold}${result.service}${RESET} ${gradeColor}${result.grade}${RESET} (${result.score}/100)`);\n\n for (const check of result.checks) {\n const icon = check.passed ? `${colors.green}pass${RESET}` : `${colors.red}fail${RESET}`;\n writeLine(` ${icon} ${check.name} ${colors.dim}(${check.detail})${RESET}`);\n }\n }\n }\n\n if (opts.json) {\n console.log(JSON.stringify(results, null, 2));\n } else {\n writeLine();\n }\n });\n}\n","/**\n * squads release — release pre-check and status.\n *\n * squads release pre-check <service> Validate dependencies before deploy\n */\n\nimport { Command } from 'commander';\nimport { loadService, loadDependencyGraph } from '../lib/idp/catalog-loader.js';\nimport { findIdpDir } from '../lib/idp/resolver.js';\nimport { colors, bold, RESET, writeLine } from '../lib/terminal.js';\n\nasync function checkHealth(url: string, expect: number): Promise<{ ok: boolean; status: number | string }> {\n try {\n const response = await fetch(url, { signal: AbortSignal.timeout(10000) });\n return { ok: response.status === expect, status: response.status };\n } catch (e) {\n return { ok: false, status: e instanceof Error ? e.message : 'unreachable' };\n }\n}\n\nexport function registerReleaseCommands(program: Command): void {\n const release = program\n .command('release')\n .description('Release management — pre-deploy checks and status');\n\n release\n .command('pre-check <service>')\n .description('Validate dependencies and health before deploying a service')\n .option('--skip-health', 'Skip health endpoint checks')\n .action(async (serviceName: string, opts) => {\n const idpDir = findIdpDir();\n if (!idpDir) {\n writeLine(` ${colors.red}IDP not found${RESET}`);\n return;\n }\n\n const service = loadService(serviceName);\n if (!service) {\n writeLine(` ${colors.red}Service not found: ${serviceName}${RESET}`);\n return;\n }\n\n const graph = loadDependencyGraph();\n const deps = service.spec.dependencies.runtime;\n\n writeLine();\n writeLine(` ${bold}Release Pre-Check: ${serviceName}${RESET}`);\n writeLine();\n\n let allGreen = true;\n\n // Check dependencies\n if (deps.length === 0) {\n writeLine(` ${colors.green}pass${RESET} No runtime dependencies`);\n } else {\n writeLine(` ${colors.cyan}Dependencies${RESET}`);\n for (const dep of deps) {\n const depService = loadService(dep.service);\n const req = dep.required !== false;\n\n if (!depService) {\n if (dep.type === 'infrastructure') {\n writeLine(` ${colors.dim}skip${RESET} ${dep.service} (infrastructure — not in catalog)`);\n continue;\n }\n if (req) {\n writeLine(` ${colors.red}fail${RESET} ${dep.service} — not found in catalog`);\n allGreen = false;\n } else {\n writeLine(` ${colors.yellow}warn${RESET} ${dep.service} — not in catalog (optional)`);\n }\n continue;\n }\n\n // Check health of dependency\n if (!opts.skipHealth && depService.spec.health.length > 0) {\n for (const h of depService.spec.health) {\n const result = await checkHealth(h.url, h.expect);\n if (result.ok) {\n writeLine(` ${colors.green}pass${RESET} ${dep.service}/${h.name} — ${result.status}`);\n } else if (req) {\n writeLine(` ${colors.red}fail${RESET} ${dep.service}/${h.name} — ${result.status}`);\n allGreen = false;\n } else {\n writeLine(` ${colors.yellow}warn${RESET} ${dep.service}/${h.name} — ${result.status} (optional)`);\n }\n }\n } else {\n writeLine(` ${colors.dim}skip${RESET} ${dep.service} health check (${opts.skipHealth ? 'skipped' : 'no endpoints'})`);\n }\n }\n }\n\n writeLine();\n\n // Check deploy order from graph\n if (graph) {\n const order = graph.deploy_order;\n let servicePhase = -1;\n for (let i = 0; i < order.length; i++) {\n if (order[i].includes(serviceName)) {\n servicePhase = i;\n break;\n }\n }\n\n if (servicePhase >= 0) {\n writeLine(` ${colors.cyan}Deploy Order${RESET}`);\n for (let i = 0; i < order.length; i++) {\n const marker = i === servicePhase ? `${colors.green}→${RESET}` : ' ';\n const phase = order[i].join(', ');\n writeLine(` ${marker} Phase ${i + 1}: ${i === servicePhase ? bold : colors.dim}${phase}${RESET}`);\n }\n writeLine();\n }\n }\n\n // Self health check\n if (!opts.skipHealth && service.spec.health.length > 0) {\n writeLine(` ${colors.cyan}Self Health${RESET}`);\n for (const h of service.spec.health) {\n const result = await checkHealth(h.url, h.expect);\n if (result.ok) {\n writeLine(` ${colors.green}pass${RESET} ${h.name} — ${result.status}`);\n } else {\n writeLine(` ${colors.yellow}warn${RESET} ${h.name} — ${result.status}`);\n }\n }\n writeLine();\n }\n\n // Summary\n if (allGreen) {\n writeLine(` ${colors.green}All checks passed — safe to deploy ${serviceName}${RESET}`);\n } else {\n writeLine(` ${colors.red}Pre-check failed — fix issues before deploying ${serviceName}${RESET}`);\n }\n writeLine();\n });\n}\n","/**\n * squads obs — observability commands\n *\n * squads obs history Execution history with tokens/cost\n * squads obs cost Spend summary by squad and model\n */\n\nimport { Command } from 'commander';\nimport { queryExecutions, calculateCostSummary } from '../lib/observability.js';\nimport { colors, bold, RESET, writeLine } from '../lib/terminal.js';\n\nexport function registerObservabilityCommands(program: Command): void {\n const obs = program\n .command('obs')\n .description('Observability — execution history, token costs, and trends');\n\n obs\n .command('history')\n .description('Show execution history with tokens and cost')\n .option('-s, --squad <squad>', 'Filter by squad')\n .option('-a, --agent <agent>', 'Filter by agent')\n .option('-n, --limit <n>', 'Number of records', '20')\n .option('--since <date>', 'Since date (ISO or relative: 1d, 7d, 30d)')\n .option('--json', 'Output as JSON')\n .action((opts) => {\n let since = opts.since;\n if (since && /^\\d+d$/.test(since)) {\n const days = parseInt(since, 10);\n since = new Date(Date.now() - days * 24 * 60 * 60 * 1000).toISOString();\n }\n\n const records = queryExecutions({\n squad: opts.squad, agent: opts.agent, since, limit: parseInt(opts.limit, 10),\n });\n\n if (records.length === 0) {\n writeLine(`\\n ${colors.dim}No executions found. Run \\`squads run <squad>\\` to generate data.${RESET}\\n`);\n return;\n }\n\n if (opts.json) { console.log(JSON.stringify(records, null, 2)); return; }\n\n writeLine(`\\n ${bold}Execution History${RESET} (${records.length} records)\\n`);\n\n for (const r of records) {\n const icon = r.status === 'completed' ? `${colors.green}pass${RESET}`\n : r.status === 'failed' ? `${colors.red}fail${RESET}` : `${colors.yellow}timeout${RESET}`;\n const dur = r.duration_ms > 60000 ? `${Math.round(r.duration_ms / 60000)}m` : `${Math.round(r.duration_ms / 1000)}s`;\n const cost = r.cost_usd > 0 ? `$${r.cost_usd.toFixed(3)}` : '$—';\n const tok = (r.input_tokens + r.output_tokens) > 0 ? `${(r.input_tokens + r.output_tokens).toLocaleString()} tok` : '— tok';\n const date = r.ts.slice(0, 16).replace('T', ' ');\n\n const grade = r.grade ? ` ${r.grade}` : '';\n writeLine(` ${icon} ${bold}${r.squad}/${r.agent}${RESET} ${colors.dim}${date} ${dur} ${tok} ${cost} ${r.model}${grade}${RESET}`);\n if (r.error) writeLine(` ${colors.red}${r.error.slice(0, 80)}${RESET}`);\n if (r.goals_changed && r.goals_changed.length > 0) {\n for (const g of r.goals_changed) {\n writeLine(` ${colors.green}goal: ${g.name} ${g.before} → ${g.after}${RESET}`);\n }\n }\n }\n writeLine();\n });\n\n obs\n .command('cost')\n .description('Show token spend summary')\n .option('-p, --period <period>', 'Time period: today, 7d, 30d, all', '7d')\n .option('--json', 'Output as JSON')\n .action((opts) => {\n const summary = calculateCostSummary(opts.period);\n\n if (summary.total_runs === 0) {\n writeLine(`\\n ${colors.dim}No executions in the last ${opts.period}.${RESET}\\n`);\n return;\n }\n\n if (opts.json) { console.log(JSON.stringify(summary, null, 2)); return; }\n\n writeLine(`\\n ${bold}Cost Summary${RESET} (${summary.period})`);\n writeLine(`\\n Total: ${bold}$${summary.total_cost.toFixed(2)}${RESET} across ${summary.total_runs} runs`);\n writeLine(` Tokens: ${summary.total_input_tokens.toLocaleString()} in / ${summary.total_output_tokens.toLocaleString()} out\\n`);\n\n const squads = Object.entries(summary.by_squad).sort((a, b) => b[1].cost - a[1].cost);\n if (squads.length > 0) {\n writeLine(` ${colors.cyan}By Squad${RESET}`);\n for (const [name, data] of squads) {\n const bar = '█'.repeat(Math.max(1, Math.round(data.cost / (summary.total_cost || 1) * 20)));\n writeLine(` ${name.padEnd(20)} ${colors.dim}${bar}${RESET} $${data.cost.toFixed(2)} (${data.runs} runs, avg $${data.avg_cost.toFixed(3)})`);\n }\n writeLine();\n }\n\n const models = Object.entries(summary.by_model).sort((a, b) => b[1].cost - a[1].cost);\n if (models.length > 0) {\n writeLine(` ${colors.cyan}By Model${RESET}`);\n for (const [name, data] of models) {\n writeLine(` ${name.padEnd(30)} $${data.cost.toFixed(2)} (${data.runs} runs)`);\n }\n writeLine();\n }\n });\n\n // ── obs sync ──\n obs\n .command('sync')\n .description('Backfill JSONL execution data to Postgres (Tier 2)')\n .option('--dry-run', 'Show what would be synced without sending')\n .action(async (opts) => {\n const { detectTier } = await import('../lib/tier-detect.js');\n const { queryExecutions } = await import('../lib/observability.js');\n const info = await detectTier();\n\n if (info.tier < 2 || !info.urls.api) {\n writeLine(`\\n ${colors.dim}Tier 2 not available. Run 'squads services up' first.${RESET}\\n`);\n return;\n }\n\n const records = queryExecutions({ limit: 10000 });\n if (records.length === 0) {\n writeLine(`\\n ${colors.dim}No JSONL records to sync.${RESET}\\n`);\n return;\n }\n\n writeLine(`\\n ${bold}Syncing ${records.length} records to Postgres...${RESET}\\n`);\n\n let synced = 0;\n let skipped = 0;\n let errors = 0;\n\n for (const record of records) {\n if (opts.dryRun) {\n writeLine(` ${colors.dim}[dry-run] ${record.ts} ${record.squad}/${record.agent} $${record.cost_usd.toFixed(3)}${RESET}`);\n synced++;\n continue;\n }\n\n try {\n const res = await fetch(`${info.urls.api}/agent-executions`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n execution_id: record.id,\n squad: record.squad,\n agent: record.agent,\n model: record.model,\n status: record.status,\n input_tokens: record.input_tokens,\n output_tokens: record.output_tokens,\n cache_read_tokens: record.cache_read_tokens,\n cache_write_tokens: record.cache_write_tokens,\n cost_usd: record.cost_usd,\n duration_seconds: Math.round(record.duration_ms / 1000),\n error_message: record.error || null,\n metadata: { trigger: record.trigger, provider: record.provider },\n }),\n signal: AbortSignal.timeout(5000),\n });\n\n if (res.ok) {\n synced++;\n } else if (res.status === 409) {\n skipped++; // Already exists (dedup)\n } else {\n errors++;\n }\n } catch {\n errors++;\n }\n }\n\n writeLine(` ${colors.green}Synced: ${synced}${RESET} ${colors.dim}Skipped: ${skipped} Errors: ${errors}${RESET}\\n`);\n });\n}\n","/**\n * squads tier — show active infrastructure tier and available services.\n */\n\nimport { Command } from 'commander';\nimport { detectTier } from '../lib/tier-detect.js';\nimport { queryExecutions } from '../lib/observability.js';\nimport { loadCatalog } from '../lib/idp/catalog-loader.js';\nimport { findIdpDir } from '../lib/idp/resolver.js';\nimport { findMemoryDir } from '../lib/memory.js';\nimport { findSquadsDir } from '../lib/squad-parser.js';\nimport { colors, bold, RESET, writeLine } from '../lib/terminal.js';\nimport { existsSync, readdirSync } from 'fs';\n\nexport function registerTierCommand(program: Command): void {\n program\n .command('tier')\n .description('Show active infrastructure tier and available services')\n .option('--json', 'Output as JSON')\n .action(async (opts) => {\n const info = await detectTier();\n\n if (opts.json) {\n console.log(JSON.stringify(info, null, 2));\n return;\n }\n\n writeLine();\n if (info.tier === 1) {\n writeLine(` ${bold}Tier 1${RESET} ${colors.dim}(file-based)${RESET}`);\n } else {\n writeLine(` ${bold}Tier 2${RESET} ${colors.green}(local services)${RESET}`);\n }\n writeLine();\n\n // Data sources\n writeLine(` ${colors.cyan}Data${RESET}`);\n const executions = queryExecutions({ limit: 1000 });\n writeLine(` Observability: ${executions.length} executions logged`);\n\n const squadsDir = findSquadsDir();\n if (squadsDir) {\n const squads = readdirSync(squadsDir).filter(f => {\n try { return existsSync(`${squadsDir}/${f}/SQUAD.md`); } catch { return false; }\n });\n writeLine(` Squads: ${squads.length} defined`);\n }\n\n const memoryDir = findMemoryDir();\n if (memoryDir) {\n writeLine(` Memory: ${memoryDir}`);\n }\n\n const idpDir = findIdpDir();\n if (idpDir) {\n const catalog = loadCatalog();\n writeLine(` IDP: ${catalog.length} catalog entries`);\n } else {\n writeLine(` IDP: not configured`);\n }\n writeLine();\n\n // Services\n writeLine(` ${colors.cyan}Services${RESET}`);\n const svc = info.services;\n const icon = (ok: boolean) => ok ? `${colors.green}up${RESET}` : `${colors.dim}—${RESET}`;\n writeLine(` API: ${icon(svc.api)}${svc.api ? ` ${info.urls.api}` : ''}`);\n writeLine(` Bridge: ${icon(svc.bridge)}${svc.bridge ? ` ${info.urls.bridge}` : ''}`);\n writeLine(` Postgres: ${icon(svc.postgres)}`);\n writeLine(` Redis: ${icon(svc.redis)}`);\n writeLine();\n\n if (info.tier === 1) {\n writeLine(` ${colors.dim}Upgrade: run 'squads services up' for Tier 2${RESET}`);\n writeLine(` ${colors.dim}(smart triggers, Postgres, webhooks, budget enforcement)${RESET}`);\n } else {\n writeLine(` ${colors.dim}All local services healthy. Data syncs to Postgres.${RESET}`);\n }\n writeLine();\n });\n}\n","/**\n * squads services — manage Tier 2 local infrastructure.\n *\n * squads services up Start Docker services, switch to local config\n * squads services down Stop services, fall back to standalone\n * squads services status Show running containers and health\n */\n\nimport { Command } from 'commander';\nimport { execSync } from 'child_process';\nimport { existsSync } from 'fs';\nimport { join } from 'path';\nimport { detectTier } from '../lib/tier-detect.js';\nimport { colors, bold, RESET, writeLine } from '../lib/terminal.js';\n\nfunction exec(cmd: string, opts?: { cwd?: string }): string | null {\n try {\n return execSync(cmd, { encoding: 'utf-8', timeout: 30000, stdio: ['pipe', 'pipe', 'pipe'], ...opts }).trim();\n } catch {\n return null;\n }\n}\n\nfunction findComposeFile(): string | null {\n // Search for docker-compose in known locations\n const home = process.env.HOME || '';\n const candidates = [\n join(home, 'agents-squads', 'engineering', 'docker', 'docker-compose.yml'),\n join(home, 'agents-squads', 'engineering', 'docker', 'docker-compose.yaml'),\n join(process.cwd(), '..', 'engineering', 'docker', 'docker-compose.yml'),\n ];\n\n for (const candidate of candidates) {\n if (existsSync(candidate)) return candidate;\n }\n return null;\n}\n\nfunction dockerAvailable(): boolean {\n return exec('docker --version') !== null;\n}\n\nfunction dockerComposeAvailable(): boolean {\n return exec('docker compose version') !== null;\n}\n\nexport function registerServicesCommands(program: Command): void {\n const services = program\n .command('services')\n .description('Manage Tier 2 local services (Postgres, Redis, API, Bridge)');\n\n // ── services up ──\n services\n .command('up')\n .description('Start local services (Docker required)')\n .option('--webhooks', 'Also start ngrok tunnel for GitHub webhooks')\n .option('--telemetry', 'Also start OpenTelemetry collector')\n .action(async (opts) => {\n if (!dockerAvailable()) {\n writeLine(`\\n ${colors.red}Docker not found.${RESET}`);\n writeLine(` ${colors.dim}Install Docker Desktop: https://www.docker.com/products/docker-desktop${RESET}\\n`);\n return;\n }\n if (!dockerComposeAvailable()) {\n writeLine(`\\n ${colors.red}Docker Compose not found.${RESET}\\n`);\n return;\n }\n\n const composeFile = findComposeFile();\n if (!composeFile) {\n writeLine(`\\n ${colors.red}docker-compose.yml not found.${RESET}`);\n writeLine(` ${colors.dim}Expected at: ../engineering/docker/docker-compose.yml (sibling repo)${RESET}\\n`);\n return;\n }\n\n const composeDir = join(composeFile, '..');\n writeLine(`\\n ${bold}Starting Tier 2 services...${RESET}\\n`);\n\n // Build profile args\n let profileArgs = '';\n if (opts.webhooks) profileArgs += ' --profile webhooks';\n if (opts.telemetry) profileArgs += ' --profile telemetry';\n\n try {\n writeLine(` ${colors.dim}docker compose up -d${profileArgs}${RESET}`);\n execSync(`docker compose${profileArgs} up -d`, {\n cwd: composeDir,\n stdio: 'inherit',\n timeout: 120000,\n });\n\n writeLine();\n writeLine(` ${colors.green}Services started.${RESET} Waiting for health checks...`);\n\n // Wait for API to be healthy\n let healthy = false;\n for (let i = 0; i < 15; i++) {\n await new Promise(r => setTimeout(r, 2000));\n const info = await detectTier();\n if (info.services.api) {\n healthy = true;\n break;\n }\n }\n\n if (healthy) {\n writeLine(` ${colors.green}Tier 2 active.${RESET} All services healthy.\\n`);\n writeLine(` ${colors.dim}API: http://localhost:8090${RESET}`);\n writeLine(` ${colors.dim}Bridge: http://localhost:8088${RESET}`);\n writeLine(` ${colors.dim}Postgres: localhost:5432${RESET}`);\n writeLine(` ${colors.dim}Redis: localhost:6379${RESET}`);\n } else {\n writeLine(` ${colors.yellow}Services started but API not healthy yet. Run 'squads services status' to check.${RESET}`);\n }\n writeLine();\n } catch (e) {\n writeLine(`\\n ${colors.red}Failed to start services: ${e instanceof Error ? e.message : String(e)}${RESET}\\n`);\n }\n });\n\n // ── services down ──\n services\n .command('down')\n .description('Stop local services')\n .action(() => {\n const composeFile = findComposeFile();\n if (!composeFile) {\n writeLine(`\\n ${colors.dim}No docker-compose.yml found. Nothing to stop.${RESET}\\n`);\n return;\n }\n\n const composeDir = join(composeFile, '..');\n writeLine(`\\n ${bold}Stopping Tier 2 services...${RESET}\\n`);\n\n try {\n execSync('docker compose down', {\n cwd: composeDir,\n stdio: 'inherit',\n timeout: 60000,\n });\n writeLine(`\\n ${colors.dim}Services stopped. Falling back to Tier 1 (file-based).${RESET}\\n`);\n } catch (e) {\n writeLine(`\\n ${colors.red}Failed to stop services: ${e instanceof Error ? e.message : String(e)}${RESET}\\n`);\n }\n });\n\n // ── services status ──\n services\n .command('status')\n .description('Show running services and health')\n .action(async () => {\n const info = await detectTier();\n\n writeLine();\n writeLine(` ${bold}Services${RESET} (Tier ${info.tier})\\n`);\n\n const containers = exec('docker ps --filter name=squads --format \"{{.Names}}\\\\t{{.Status}}\\\\t{{.Ports}}\"');\n if (!containers) {\n writeLine(` ${colors.dim}No Docker containers running.${RESET}\\n`);\n return;\n }\n\n for (const line of containers.split('\\n').filter(Boolean)) {\n const [name, status, ports] = line.split('\\t');\n const healthy = status?.includes('healthy') || status?.includes('Up');\n const icon = healthy ? `${colors.green}up${RESET}` : `${colors.red}down${RESET}`;\n const portStr = ports ? ` ${colors.dim}${ports.split(',')[0]}${RESET}` : '';\n writeLine(` ${icon} ${bold}${name}${RESET}${portStr}`);\n }\n\n writeLine();\n\n // Show DB stats\n const jobCount = exec(\"docker exec squads-postgres psql -U squads -d squads -t -c 'SELECT count(*) FROM procrastinate_jobs;'\");\n const execCount = exec(\"docker exec squads-postgres psql -U squads -d squads -t -c 'SELECT count(*) FROM agent_executions;'\");\n\n if (jobCount || execCount) {\n writeLine(` ${colors.cyan}Database${RESET}`);\n if (jobCount) writeLine(` Procrastinate jobs: ${jobCount.trim()}`);\n if (execCount) writeLine(` Agent executions: ${execCount.trim()}`);\n writeLine();\n }\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,cAAc;AACvB,SAAS,cAAAA,oBAAkB;AAC3B,SAAS,QAAAC,cAAY;AACrB,SAAS,WAAAC,gBAAe;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,QAAQ,IAAI,SAAS;AAC5C,cAAQ,MAAMA,OAAM,IAAI,gBAAgB,CAAC;AACzC,cAAQ,MAAMA,OAAM,IAAI,IAAI,KAAK,CAAC;AAAA,IACpC,OAAO;AACL,cAAQ,MAAMA,OAAM,IAAI,qCAAqC,CAAC;AAAA,IAChE;AAAA,EACF;AAEA,UAAQ,MAAMA,OAAM,IAAI,uCAAuC,CAAC;AAChE,UAAQ,MAAMA,OAAM,KAAK,wDAAwD,CAAC;AAElF,UAAQ,KAAK,CAAC;AAChB;AAGA,QAAQ,GAAG,qBAAqB,WAAW;AAC3C,QAAQ,GAAG,sBAAsB,WAAW;AAG5C,IAAI;AACF,QAAM,QAAQ,WAAW;AAC3B,SAAS,OAAO;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","resolve","showStatus","program","chalk","API_URL","chalk","resolve","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","readdirSync","readFileSync","existsSync","join","matter","existsSync","join","existsSync","join","existsSync","readFileSync","matter","join","readdirSync","existsSync","statSync","join","execSync","program","env","program","program","detectTier","queryExecutions","existsSync","readdirSync","program","execSync","existsSync","join","exec","execSync","join","existsSync","program","chalk","join","homedir","existsSync","colors","RESET","exec","progress","kpi","readFileSync"]}