panopticon-cli 0.6.8 → 0.6.9
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.
- package/dist/{agents-D_2oRFVf.js → agents-BQOqo27C.js} +1 -1
- package/dist/{agents-CfFDs52G.js → agents-DezveQ1x.js} +4 -4
- package/dist/{agents-CfFDs52G.js.map → agents-DezveQ1x.js.map} +1 -1
- package/dist/cli/index.js +34 -34
- package/dist/{config-yaml-DGbLSMCa.js → config-yaml-BHD2Qdd8.js} +22 -1
- package/dist/config-yaml-BHD2Qdd8.js.map +1 -0
- package/dist/{config-yaml-Dqt4FWQH.js → config-yaml-IlSnFzJQ.js} +1 -1
- package/dist/dashboard/{agent-enrichment-DdO7ZqjI.js → agent-enrichment-BKZjVvlL.js} +3 -3
- package/dist/dashboard/{agent-enrichment-DdO7ZqjI.js.map → agent-enrichment-BKZjVvlL.js.map} +1 -1
- package/dist/dashboard/{agent-enrichment-dLeGE1fX.js → agent-enrichment-iY3_PylI.js} +1 -1
- package/dist/dashboard/{agents-DCpQQ_W5.js → agents-BQWA-Vps.js} +4 -4
- package/dist/dashboard/{agents-DCpQQ_W5.js.map → agents-BQWA-Vps.js.map} +1 -1
- package/dist/dashboard/{agents-Dgh2TjSp.js → agents-Dinc9j_8.js} +1 -1
- package/dist/dashboard/{config-yaml-DkresmrS.js → config-yaml-CNNnB4Mu.js} +1 -1
- package/dist/dashboard/{config-yaml-DSfYpzN6.js → config-yaml-DUu0JI25.js} +22 -1
- package/dist/dashboard/{config-yaml-DSfYpzN6.js.map → config-yaml-DUu0JI25.js.map} +1 -1
- package/dist/dashboard/{factory-C8nhLGHB.js → factory-CBY0WWeE.js} +2 -2
- package/dist/dashboard/{factory-C8nhLGHB.js.map → factory-CBY0WWeE.js.map} +1 -1
- package/dist/dashboard/{inspect-agent-7eour7EA.js → inspect-agent-KKOeNR7E.js} +3 -3
- package/dist/dashboard/{inspect-agent-7eour7EA.js.map → inspect-agent-KKOeNR7E.js.map} +1 -1
- package/dist/dashboard/{issue-service-singleton-Wv4xBm3y.js → issue-service-singleton-BCZ62hLj.js} +3 -3
- package/dist/dashboard/{issue-service-singleton-Wv4xBm3y.js.map → issue-service-singleton-BCZ62hLj.js.map} +1 -1
- package/dist/dashboard/{issue-service-singleton-Co__-6kL.js → issue-service-singleton-BGKf0A95.js} +1 -1
- package/dist/dashboard/{lifecycle-BcUmtkR4.js → lifecycle-Dpgg-IeP.js} +1 -1
- package/dist/dashboard/{merge-agent-CGN3TT0a.js → merge-agent-CqvQu-n_.js} +1 -1
- package/dist/dashboard/{merge-agent-yudQOPZc.js → merge-agent-Dxxc4JEE.js} +5 -5
- package/dist/dashboard/{merge-agent-yudQOPZc.js.map → merge-agent-Dxxc4JEE.js.map} +1 -1
- package/dist/dashboard/public/assets/{dist-C-wcq54x.js → dist-DS1gmhe1.js} +1 -1
- package/dist/dashboard/public/assets/index-DjGsaJLv.js +212 -0
- package/dist/dashboard/public/index.html +1 -1
- package/dist/dashboard/{review-status-BtXqWBhS.js → review-status-Dww2OKUX.js} +1 -1
- package/dist/dashboard/{review-status-Bymwzh2i.js → review-status-d_wOE-XQ.js} +3 -3
- package/dist/dashboard/{review-status-Bymwzh2i.js.map → review-status-d_wOE-XQ.js.map} +1 -1
- package/dist/dashboard/server.js +97 -97
- package/dist/dashboard/settings-BHlDG7TK.js.map +1 -1
- package/dist/dashboard/{spawn-planning-session-D5hrVdWM.js → spawn-planning-session-D5uEpHzf.js} +1 -1
- package/dist/dashboard/{spawn-planning-session-33Jf-d5T.js → spawn-planning-session-DtbNfA2Q.js} +3 -3
- package/dist/dashboard/{spawn-planning-session-33Jf-d5T.js.map → spawn-planning-session-DtbNfA2Q.js.map} +1 -1
- package/dist/dashboard/{specialist-context-DGukHSn8.js → specialist-context-CEKqWqyF.js} +4 -4
- package/dist/dashboard/{specialist-context-DGukHSn8.js.map → specialist-context-CEKqWqyF.js.map} +1 -1
- package/dist/dashboard/{specialist-logs-CIw4qfTy.js → specialist-logs-CBGVRoQF.js} +1 -1
- package/dist/dashboard/{specialists-Cp-PgspS.js → specialists-sIFlMd3s.js} +1 -1
- package/dist/dashboard/{specialists-B_zrayaP.js → specialists-saEYE0-z.js} +20 -20
- package/dist/dashboard/{specialists-B_zrayaP.js.map → specialists-saEYE0-z.js.map} +1 -1
- package/dist/dashboard/{test-agent-queue-ypF_ecHo.js → test-agent-queue-7jXB2KkN.js} +3 -3
- package/dist/dashboard/{test-agent-queue-ypF_ecHo.js.map → test-agent-queue-7jXB2KkN.js.map} +1 -1
- package/dist/dashboard/{tracker-config-BP59uH4V.js → tracker-config-BX6ijWOc.js} +1 -1
- package/dist/dashboard/{tracker-config-e7ph1QqT.js → tracker-config-tD22z5sv.js} +2 -2
- package/dist/dashboard/{tracker-config-e7ph1QqT.js.map → tracker-config-tD22z5sv.js.map} +1 -1
- package/dist/dashboard/{work-agent-prompt-fCg67nyo.js → work-agent-prompt-D3tPzPvb.js} +2 -2
- package/dist/dashboard/{work-agent-prompt-fCg67nyo.js.map → work-agent-prompt-D3tPzPvb.js.map} +1 -1
- package/dist/dashboard/{work-type-router-CWVW2Wk_.js → work-type-router-7kwLSwrP.js} +4 -2
- package/dist/dashboard/work-type-router-7kwLSwrP.js.map +1 -0
- package/dist/dashboard/{work-type-router-Di5gCQwh.js → work-type-router-ByOOudGz.js} +1 -1
- package/dist/dashboard/workflows-BDpPjK18.js +2 -0
- package/dist/dashboard/{workflows-BSMipN07.js → workflows-DcEeDkbS.js} +3 -3
- package/dist/dashboard/{workflows-BSMipN07.js.map → workflows-DcEeDkbS.js.map} +1 -1
- package/dist/{factory-BRBGw6OB.js → factory-BR48tuUR.js} +1 -1
- package/dist/{factory-DzsOiZVc.js → factory-D6LJaZ__.js} +2 -2
- package/dist/{factory-DzsOiZVc.js.map → factory-D6LJaZ__.js.map} +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +3 -3
- package/dist/{merge-agent-DlUiUanN.js → merge-agent-BBwHwpn2.js} +3 -3
- package/dist/{merge-agent-DlUiUanN.js.map → merge-agent-BBwHwpn2.js.map} +1 -1
- package/dist/{review-status-DEDvCKMP.js → review-status-Ba6llgCb.js} +3 -3
- package/dist/{review-status-DEDvCKMP.js.map → review-status-Ba6llgCb.js.map} +1 -1
- package/dist/{review-status-D6H2WOw8.js → review-status-Chxzuwn2.js} +1 -1
- package/dist/{settings-BcWPTrua.js → settings-A-CWz_ph.js} +6 -2
- package/dist/{settings-BcWPTrua.js.map → settings-A-CWz_ph.js.map} +1 -1
- package/dist/{specialist-context-BAUWL1Fl.js → specialist-context-B3lknlwi.js} +4 -4
- package/dist/{specialist-context-BAUWL1Fl.js.map → specialist-context-B3lknlwi.js.map} +1 -1
- package/dist/{specialist-logs-DQKKQV9B.js → specialist-logs-DDyY4xqo.js} +1 -1
- package/dist/{specialists-D7Kj5o6s.js → specialists-DvTYu1VZ.js} +20 -20
- package/dist/{specialists-D7Kj5o6s.js.map → specialists-DvTYu1VZ.js.map} +1 -1
- package/dist/{specialists-Bfb9ATzw.js → specialists-DyB4IRlM.js} +1 -1
- package/dist/sync-CLVqiGl4.js +2 -0
- package/dist/{sync-DMfgd389.js → sync-DTHFlEc-.js} +2 -2
- package/dist/{sync-DMfgd389.js.map → sync-DTHFlEc-.js.map} +1 -1
- package/dist/{tracker-BhYYvU3p.js → tracker-CYpb7oUa.js} +2 -2
- package/dist/{tracker-BhYYvU3p.js.map → tracker-CYpb7oUa.js.map} +1 -1
- package/dist/{work-type-router-CHjciPyS.js → work-type-router-oCgTPXsP.js} +4 -2
- package/dist/work-type-router-oCgTPXsP.js.map +1 -0
- package/package.json +1 -1
- package/dist/config-yaml-DGbLSMCa.js.map +0 -1
- package/dist/dashboard/public/assets/index-DKlrFY1k.js +0 -212
- package/dist/dashboard/work-type-router-CWVW2Wk_.js.map +0 -1
- package/dist/dashboard/workflows-DaYWQIS2.js +0 -2
- package/dist/sync-TL6y-8K6.js +0 -2
- package/dist/work-type-router-CHjciPyS.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"settings-BHlDG7TK.js","names":[],"sources":["../../src/lib/settings.ts"],"sourcesContent":["import { readFileSync, writeFileSync, existsSync } from 'fs';\nimport { SETTINGS_FILE } from './paths.js';\n\n// Model identifiers\nexport type AnthropicModel = 'claude-opus-4-6' | 'claude-sonnet-4-6' | 'claude-sonnet-4-5' | 'claude-haiku-4-5';\nexport type OpenAIModel = 'gpt-5.2-codex' | 'o3-deep-research' | 'gpt-4o' | 'gpt-4o-mini';\nexport type GoogleModel = 'gemini-3-pro-preview' | 'gemini-3-flash-preview' | 'gemini-2.5-pro' | 'gemini-2.5-flash';\nexport type ZAIModel = 'glm-4.7-flash';\nexport type KimiModel = 'kimi-k2' | 'kimi-k2.5';\nexport type MiniMaxModel = 'minimax-m2.7' | 'minimax-m2.7-highspeed';\nexport type ModelId = AnthropicModel | OpenAIModel | GoogleModel | ZAIModel | KimiModel | MiniMaxModel;\n\n// Task complexity levels\nexport type ComplexityLevel = 'trivial' | 'simple' | 'medium' | 'complex' | 'expert';\n\n// Specialist agent types\nexport interface SpecialistModels {\n review_agent: ModelId;\n test_agent: ModelId;\n merge_agent: ModelId;\n}\n\n// Complexity-based model mapping\nexport type ComplexityModels = {\n [K in ComplexityLevel]: ModelId;\n};\n\n// All model configuration\nexport interface ModelsConfig {\n specialists: SpecialistModels;\n status_review: ModelId;\n complexity: ComplexityModels;\n}\n\n// API keys for external providers\nexport interface ApiKeysConfig {\n openai?: string;\n google?: string;\n zai?: string;\n kimi?: string;\n}\n\n// Complete settings structure\nexport interface SettingsConfig {\n models: ModelsConfig;\n api_keys: ApiKeysConfig;\n}\n\n// Default settings - match optimal defaults from settings-api.ts\nconst DEFAULT_SETTINGS: SettingsConfig = {\n models: {\n specialists: {\n review_agent: 'claude-opus-4-6',\n test_agent: 'claude-sonnet-4-6',\n merge_agent: 'claude-sonnet-4-6',\n },\n status_review: 'claude-opus-4-6',\n complexity: {\n trivial: 'claude-haiku-4-5',\n simple: 'claude-haiku-4-5',\n medium: 'kimi-k2.5',\n complex: 'kimi-k2.5',\n expert: 'claude-opus-4-6',\n },\n },\n api_keys: {},\n};\n\n/**\n * Deep merge utility that recursively merges objects.\n * - Recursively merges nested objects\n * - User values take precedence over defaults\n */\nfunction deepMerge<T extends object>(defaults: T, overrides: Partial<T>): T {\n const result = { ...defaults };\n\n for (const key of Object.keys(overrides) as (keyof T)[]) {\n const defaultVal = defaults[key];\n const overrideVal = overrides[key];\n\n // Skip undefined values in overrides\n if (overrideVal === undefined) continue;\n\n // Deep merge if both values are non-array objects\n if (\n typeof defaultVal === 'object' &&\n defaultVal !== null &&\n !Array.isArray(defaultVal) &&\n typeof overrideVal === 'object' &&\n overrideVal !== null &&\n !Array.isArray(overrideVal)\n ) {\n result[key] = deepMerge(defaultVal, overrideVal as any);\n } else {\n // For primitives or null - override wins\n result[key] = overrideVal as T[keyof T];\n }\n }\n\n return result;\n}\n\n/**\n * Load settings from ~/.panopticon/settings.json\n * Returns default settings if file doesn't exist or is invalid\n * Also loads API keys from environment variables as fallback\n */\nexport function loadSettings(): SettingsConfig {\n let settings: SettingsConfig;\n\n if (!existsSync(SETTINGS_FILE)) {\n settings = getDefaultSettings();\n } else {\n try {\n const content = readFileSync(SETTINGS_FILE, 'utf8');\n const parsed = JSON.parse(content) as Partial<SettingsConfig>;\n settings = deepMerge(DEFAULT_SETTINGS, parsed);\n } catch (error) {\n console.error('Warning: Failed to parse settings.json, using defaults');\n settings = getDefaultSettings();\n }\n }\n\n // Load API keys from environment variables as fallback\n // This allows using ~/.panopticon.env for API keys\n const envApiKeys: ApiKeysConfig = {};\n if (process.env.OPENAI_API_KEY) envApiKeys.openai = process.env.OPENAI_API_KEY;\n if (process.env.GOOGLE_API_KEY) envApiKeys.google = process.env.GOOGLE_API_KEY;\n if (process.env.ZAI_API_KEY) envApiKeys.zai = process.env.ZAI_API_KEY;\n if (process.env.KIMI_API_KEY) envApiKeys.kimi = process.env.KIMI_API_KEY;\n\n // Merge env vars as fallback (settings.json takes precedence)\n settings.api_keys = {\n ...envApiKeys,\n ...settings.api_keys,\n };\n\n return settings;\n}\n\n/**\n * Save settings to ~/.panopticon/settings.json\n * Writes with pretty formatting (2-space indent)\n */\nexport function saveSettings(settings: SettingsConfig): void {\n const content = JSON.stringify(settings, null, 2);\n writeFileSync(SETTINGS_FILE, content, 'utf8');\n}\n\n/**\n * Validate settings structure and model IDs\n * Returns error message if invalid, null if valid\n */\nexport function validateSettings(settings: SettingsConfig): string | null {\n // Validate models structure\n if (!settings.models) {\n return 'Missing models configuration';\n }\n\n // Validate specialists\n if (!settings.models.specialists) {\n return 'Missing specialists configuration';\n }\n const specialists = settings.models.specialists;\n if (!specialists.review_agent || !specialists.test_agent || !specialists.merge_agent) {\n return 'Missing specialist agent model configuration';\n }\n\n // Validate complexity levels\n if (!settings.models.complexity) {\n return 'Missing complexity configuration';\n }\n const complexity = settings.models.complexity;\n const requiredLevels: ComplexityLevel[] = ['trivial', 'simple', 'medium', 'complex', 'expert'];\n for (const level of requiredLevels) {\n if (!complexity[level]) {\n return `Missing complexity level: ${level}`;\n }\n }\n\n // Validate api_keys structure (optional keys)\n if (!settings.api_keys) {\n return 'Missing api_keys configuration';\n }\n\n return null;\n}\n\n/**\n * Get a deep copy of the default settings\n */\nexport function getDefaultSettings(): SettingsConfig {\n return JSON.parse(JSON.stringify(DEFAULT_SETTINGS));\n}\n\n/**\n * Get available models for a provider based on configured API keys\n * Returns empty array if provider API key is not configured\n */\nexport function getAvailableModels(settings: SettingsConfig): {\n anthropic: AnthropicModel[];\n openai: OpenAIModel[];\n google: GoogleModel[];\n zai: ZAIModel[];\n kimi: KimiModel[];\n} {\n const anthropicModels: AnthropicModel[] = [\n 'claude-opus-4-6',\n 'claude-sonnet-4-6',\n 'claude-haiku-4-5',\n ];\n\n const openaiModels: OpenAIModel[] = settings.api_keys.openai\n ? ['gpt-5.2-codex', 'o3-deep-research', 'gpt-4o', 'gpt-4o-mini']\n : [];\n\n const googleModels: GoogleModel[] = settings.api_keys.google\n ? ['gemini-3-pro-preview', 'gemini-3-flash-preview']\n : [];\n\n const zaiModels: ZAIModel[] = settings.api_keys.zai\n ? ['glm-4.7-flash']\n : [];\n\n const kimiModels: KimiModel[] = settings.api_keys.kimi\n ? ['kimi-k2', 'kimi-k2.5']\n : [];\n\n return {\n anthropic: anthropicModels,\n openai: openaiModels,\n google: googleModels,\n zai: zaiModels,\n kimi: kimiModels,\n };\n}\n\n/**\n * Check if a model ID is an Anthropic model\n * Anthropic models can be run directly with `claude` CLI\n */\nexport function isAnthropicModel(modelId: ModelId | string): boolean {\n return modelId.startsWith('claude-');\n}\n\n/**\n * Get the Claude CLI model flag for an Anthropic model\n * Maps our model IDs to Claude's expected format\n */\nexport function getClaudeModelFlag(modelId: ModelId | string): string {\n const modelMap: Record<string, string> = {\n 'claude-opus-4-6': 'opus',\n 'claude-sonnet-4-6': 'sonnet',\n 'claude-sonnet-4-5': 'sonnet',\n 'claude-haiku-4-5': 'haiku',\n };\n return modelMap[modelId] || 'sonnet';\n}\n\n/**\n * Get the command to run an agent with a specific model\n * Always uses 'claude' CLI — non-Anthropic models work via ANTHROPIC_BASE_URL env var\n * pointing to their Anthropic-compatible endpoint.\n */\nexport function getAgentCommand(modelId: ModelId | string): { command: string; args: string[] } {\n if (isAnthropicModel(modelId)) {\n return {\n command: 'claude',\n args: ['--model', getClaudeModelFlag(modelId)],\n };\n }\n // Non-Anthropic direct providers: use claude CLI with the model name as-is.\n // The caller must set ANTHROPIC_BASE_URL and ANTHROPIC_AUTH_TOKEN env vars.\n return {\n command: 'claude',\n args: ['--model', modelId],\n };\n}\n"],"mappings":";;;YAC2C;;;;;AAgP3C,SAAgB,iBAAiB,SAAoC;AACnE,QAAO,QAAQ,WAAW,UAAU;;;;;;AAOtC,SAAgB,mBAAmB,SAAmC;AAOpE,QANyC;EACvC,mBAAmB;EACnB,qBAAqB;EACrB,qBAAqB;EACrB,oBAAoB;EACrB,CACe,YAAY;;;;;;;AAQ9B,SAAgB,gBAAgB,SAAgE;AAC9F,KAAI,iBAAiB,QAAQ,CAC3B,QAAO;EACL,SAAS;EACT,MAAM,CAAC,WAAW,mBAAmB,QAAQ,CAAC;EAC/C;AAIH,QAAO;EACL,SAAS;EACT,MAAM,CAAC,WAAW,QAAQ;EAC3B"}
|
|
1
|
+
{"version":3,"file":"settings-BHlDG7TK.js","names":[],"sources":["../../src/lib/settings.ts"],"sourcesContent":["import { readFileSync, writeFileSync, existsSync } from 'fs';\nimport { SETTINGS_FILE } from './paths.js';\n\n// Model identifiers\nexport type AnthropicModel = 'claude-opus-4-6' | 'claude-sonnet-4-6' | 'claude-sonnet-4-5' | 'claude-haiku-4-5';\nexport type OpenAIModel = 'gpt-5.2-codex' | 'o3-deep-research' | 'gpt-4o' | 'gpt-4o-mini';\nexport type GoogleModel = 'gemini-3-pro-preview' | 'gemini-3-flash-preview' | 'gemini-2.5-pro' | 'gemini-2.5-flash';\nexport type ZAIModel = 'glm-4.7' | 'glm-4.7-flash' | 'glm-5.1';\nexport type KimiModel = 'kimi-k2' | 'kimi-k2.5';\nexport type MiniMaxModel = 'minimax-m2.7' | 'minimax-m2.7-highspeed';\nexport type ModelId = AnthropicModel | OpenAIModel | GoogleModel | ZAIModel | KimiModel | MiniMaxModel;\n\n// Task complexity levels\nexport type ComplexityLevel = 'trivial' | 'simple' | 'medium' | 'complex' | 'expert';\n\n// Specialist agent types\nexport interface SpecialistModels {\n review_agent: ModelId;\n test_agent: ModelId;\n merge_agent: ModelId;\n}\n\n// Complexity-based model mapping\nexport type ComplexityModels = {\n [K in ComplexityLevel]: ModelId;\n};\n\n// All model configuration\nexport interface ModelsConfig {\n specialists: SpecialistModels;\n status_review: ModelId;\n complexity: ComplexityModels;\n}\n\n// API keys for external providers\nexport interface ApiKeysConfig {\n openai?: string;\n google?: string;\n zai?: string;\n kimi?: string;\n}\n\n// Complete settings structure\nexport interface SettingsConfig {\n models: ModelsConfig;\n api_keys: ApiKeysConfig;\n}\n\n// Default settings - match optimal defaults from settings-api.ts\nconst DEFAULT_SETTINGS: SettingsConfig = {\n models: {\n specialists: {\n review_agent: 'claude-opus-4-6',\n test_agent: 'claude-sonnet-4-6',\n merge_agent: 'claude-sonnet-4-6',\n },\n status_review: 'claude-opus-4-6',\n complexity: {\n trivial: 'claude-haiku-4-5',\n simple: 'claude-haiku-4-5',\n medium: 'kimi-k2.5',\n complex: 'kimi-k2.5',\n expert: 'claude-opus-4-6',\n },\n },\n api_keys: {},\n};\n\n/**\n * Deep merge utility that recursively merges objects.\n * - Recursively merges nested objects\n * - User values take precedence over defaults\n */\nfunction deepMerge<T extends object>(defaults: T, overrides: Partial<T>): T {\n const result = { ...defaults };\n\n for (const key of Object.keys(overrides) as (keyof T)[]) {\n const defaultVal = defaults[key];\n const overrideVal = overrides[key];\n\n // Skip undefined values in overrides\n if (overrideVal === undefined) continue;\n\n // Deep merge if both values are non-array objects\n if (\n typeof defaultVal === 'object' &&\n defaultVal !== null &&\n !Array.isArray(defaultVal) &&\n typeof overrideVal === 'object' &&\n overrideVal !== null &&\n !Array.isArray(overrideVal)\n ) {\n result[key] = deepMerge(defaultVal, overrideVal as any);\n } else {\n // For primitives or null - override wins\n result[key] = overrideVal as T[keyof T];\n }\n }\n\n return result;\n}\n\n/**\n * Load settings from ~/.panopticon/settings.json\n * Returns default settings if file doesn't exist or is invalid\n * Also loads API keys from environment variables as fallback\n */\nexport function loadSettings(): SettingsConfig {\n let settings: SettingsConfig;\n\n if (!existsSync(SETTINGS_FILE)) {\n settings = getDefaultSettings();\n } else {\n try {\n const content = readFileSync(SETTINGS_FILE, 'utf8');\n const parsed = JSON.parse(content) as Partial<SettingsConfig>;\n settings = deepMerge(DEFAULT_SETTINGS, parsed);\n } catch (error) {\n console.error('Warning: Failed to parse settings.json, using defaults');\n settings = getDefaultSettings();\n }\n }\n\n // Load API keys from environment variables as fallback\n // This allows using ~/.panopticon.env for API keys\n const envApiKeys: ApiKeysConfig = {};\n if (process.env.OPENAI_API_KEY) envApiKeys.openai = process.env.OPENAI_API_KEY;\n if (process.env.GOOGLE_API_KEY) envApiKeys.google = process.env.GOOGLE_API_KEY;\n if (process.env.ZAI_API_KEY) envApiKeys.zai = process.env.ZAI_API_KEY;\n if (process.env.KIMI_API_KEY) envApiKeys.kimi = process.env.KIMI_API_KEY;\n\n // Merge env vars as fallback (settings.json takes precedence)\n settings.api_keys = {\n ...envApiKeys,\n ...settings.api_keys,\n };\n\n return settings;\n}\n\n/**\n * Save settings to ~/.panopticon/settings.json\n * Writes with pretty formatting (2-space indent)\n */\nexport function saveSettings(settings: SettingsConfig): void {\n const content = JSON.stringify(settings, null, 2);\n writeFileSync(SETTINGS_FILE, content, 'utf8');\n}\n\n/**\n * Validate settings structure and model IDs\n * Returns error message if invalid, null if valid\n */\nexport function validateSettings(settings: SettingsConfig): string | null {\n // Validate models structure\n if (!settings.models) {\n return 'Missing models configuration';\n }\n\n // Validate specialists\n if (!settings.models.specialists) {\n return 'Missing specialists configuration';\n }\n const specialists = settings.models.specialists;\n if (!specialists.review_agent || !specialists.test_agent || !specialists.merge_agent) {\n return 'Missing specialist agent model configuration';\n }\n\n // Validate complexity levels\n if (!settings.models.complexity) {\n return 'Missing complexity configuration';\n }\n const complexity = settings.models.complexity;\n const requiredLevels: ComplexityLevel[] = ['trivial', 'simple', 'medium', 'complex', 'expert'];\n for (const level of requiredLevels) {\n if (!complexity[level]) {\n return `Missing complexity level: ${level}`;\n }\n }\n\n // Validate api_keys structure (optional keys)\n if (!settings.api_keys) {\n return 'Missing api_keys configuration';\n }\n\n return null;\n}\n\n/**\n * Get a deep copy of the default settings\n */\nexport function getDefaultSettings(): SettingsConfig {\n return JSON.parse(JSON.stringify(DEFAULT_SETTINGS));\n}\n\n/**\n * Get available models for a provider based on configured API keys\n * Returns empty array if provider API key is not configured\n */\nexport function getAvailableModels(settings: SettingsConfig): {\n anthropic: AnthropicModel[];\n openai: OpenAIModel[];\n google: GoogleModel[];\n zai: ZAIModel[];\n kimi: KimiModel[];\n} {\n const anthropicModels: AnthropicModel[] = [\n 'claude-opus-4-6',\n 'claude-sonnet-4-6',\n 'claude-haiku-4-5',\n ];\n\n const openaiModels: OpenAIModel[] = settings.api_keys.openai\n ? ['gpt-5.2-codex', 'o3-deep-research', 'gpt-4o', 'gpt-4o-mini']\n : [];\n\n const googleModels: GoogleModel[] = settings.api_keys.google\n ? ['gemini-3-pro-preview', 'gemini-3-flash-preview']\n : [];\n\n const zaiModels: ZAIModel[] = settings.api_keys.zai\n ? ['glm-4.7', 'glm-4.7-flash', 'glm-5.1']\n : [];\n\n const kimiModels: KimiModel[] = settings.api_keys.kimi\n ? ['kimi-k2', 'kimi-k2.5']\n : [];\n\n return {\n anthropic: anthropicModels,\n openai: openaiModels,\n google: googleModels,\n zai: zaiModels,\n kimi: kimiModels,\n };\n}\n\n/**\n * Check if a model ID is an Anthropic model\n * Anthropic models can be run directly with `claude` CLI\n */\nexport function isAnthropicModel(modelId: ModelId | string): boolean {\n return modelId.startsWith('claude-');\n}\n\n/**\n * Get the Claude CLI model flag for an Anthropic model\n * Maps our model IDs to Claude's expected format\n */\nexport function getClaudeModelFlag(modelId: ModelId | string): string {\n const modelMap: Record<string, string> = {\n 'claude-opus-4-6': 'opus',\n 'claude-sonnet-4-6': 'sonnet',\n 'claude-sonnet-4-5': 'sonnet',\n 'claude-haiku-4-5': 'haiku',\n };\n return modelMap[modelId] || 'sonnet';\n}\n\n/**\n * Get the command to run an agent with a specific model\n * Always uses 'claude' CLI — non-Anthropic models work via ANTHROPIC_BASE_URL env var\n * pointing to their Anthropic-compatible endpoint.\n */\nexport function getAgentCommand(modelId: ModelId | string): { command: string; args: string[] } {\n if (isAnthropicModel(modelId)) {\n return {\n command: 'claude',\n args: ['--model', getClaudeModelFlag(modelId)],\n };\n }\n // Non-Anthropic direct providers: use claude CLI with the model name as-is.\n // The caller must set ANTHROPIC_BASE_URL and ANTHROPIC_AUTH_TOKEN env vars.\n return {\n command: 'claude',\n args: ['--model', modelId],\n };\n}\n"],"mappings":";;;YAC2C;;;;;AAgP3C,SAAgB,iBAAiB,SAAoC;AACnE,QAAO,QAAQ,WAAW,UAAU;;;;;;AAOtC,SAAgB,mBAAmB,SAAmC;AAOpE,QANyC;EACvC,mBAAmB;EACnB,qBAAqB;EACrB,qBAAqB;EACrB,oBAAoB;EACrB,CACe,YAAY;;;;;;;AAQ9B,SAAgB,gBAAgB,SAAgE;AAC9F,KAAI,iBAAiB,QAAQ,CAC3B,QAAO;EACL,SAAS;EACT,MAAM,CAAC,WAAW,mBAAmB,QAAQ,CAAC;EAC/C;AAIH,QAAO;EACL,SAAS;EACT,MAAM,CAAC,WAAW,QAAQ;EAC3B"}
|
package/dist/dashboard/{spawn-planning-session-D5hrVdWM.js → spawn-planning-session-D5uEpHzf.js}
RENAMED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as spawnPlanningSession } from "./spawn-planning-session-
|
|
1
|
+
import { n as spawnPlanningSession } from "./spawn-planning-session-DtbNfA2Q.js";
|
|
2
2
|
export { spawnPlanningSession };
|
package/dist/dashboard/{spawn-planning-session-33Jf-d5T.js → spawn-planning-session-DtbNfA2Q.js}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { i as loadConfig, r as init_config_yaml } from "./config-yaml-
|
|
1
|
+
import { i as loadConfig, r as init_config_yaml } from "./config-yaml-DUu0JI25.js";
|
|
2
2
|
import { a as findProjectByTeam, i as findProjectByPath, p as init_projects, r as extractTeamPrefix } from "./projects-CFVl4oHn.js";
|
|
3
3
|
import { t as getAgentCommand } from "./settings-BHlDG7TK.js";
|
|
4
4
|
import { a as init_providers, i as getProviderForModel, r as getProviderEnv } from "./providers-B5Y4H2Mg.js";
|
|
@@ -417,7 +417,7 @@ async function spawnPlanningSession(opts) {
|
|
|
417
417
|
progress(3, "Loading specs & PRDs", `Searching for ${issue.identifier} specs`);
|
|
418
418
|
let settingsModel = "claude-opus-4-6";
|
|
419
419
|
try {
|
|
420
|
-
const { getModelId } = await import("./work-type-router-
|
|
420
|
+
const { getModelId } = await import("./work-type-router-ByOOudGz.js");
|
|
421
421
|
settingsModel = getModelId("planning-agent");
|
|
422
422
|
} catch {}
|
|
423
423
|
const planningModel = modelOverride || settingsModel;
|
|
@@ -518,4 +518,4 @@ while true; do sleep 60; done
|
|
|
518
518
|
//#endregion
|
|
519
519
|
export { spawnPlanningSession as n, buildPlanningPrompt as t };
|
|
520
520
|
|
|
521
|
-
//# sourceMappingURL=spawn-planning-session-
|
|
521
|
+
//# sourceMappingURL=spawn-planning-session-DtbNfA2Q.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"spawn-planning-session-33Jf-d5T.js","names":["loadYamlConfig"],"sources":["../../src/lib/planning/spawn-planning-session.ts"],"sourcesContent":["/**\n * Spawn Planning Session — background workspace + agent setup\n *\n * Extracted from the old Express /api/issues/:id/start-planning handler.\n * Creates workspace, writes planning prompt, spawns Claude Code in tmux.\n * Used by both the dashboard route and CLI.\n *\n * This runs as a background task after the API responds — the UI shows\n * \"Waiting for session to start...\" until the tmux session is ready.\n */\n\nimport { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { exec } from 'node:child_process';\nimport { promisify } from 'node:util';\nimport { extractTeamPrefix, findProjectByTeam, findProjectByPath } from '../projects.js';\nimport { getAgentCommand, isAnthropicModel } from '../settings.js';\nimport { loadConfig as loadYamlConfig } from '../config-yaml.js';\nimport { getProviderForModel, getProviderEnv } from '../providers.js';\nimport { createWorkspace } from '../workspace-manager.js';\n\nconst __dirname = fileURLToPath(new URL('.', import.meta.url));\n\nfunction getPackageVersion(): string {\n try {\n const pkgPath = resolve(__dirname, '../../../package.json');\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8')) as { version: string };\n return pkg.version;\n } catch {\n return '0.0.0';\n }\n}\n\n/**\n * Discover PRD files matching an issue ID from docs/prds directories.\n * Returns list of { path, label } for use in references template.\n */\nfunction discoverPrdFiles(workspacePath: string, issueId: string): Array<{ path: string; label: string }> {\n const issueLower = issueId.toLowerCase();\n const searchDirs = [\n join(workspacePath, 'docs', 'prds', 'planned'),\n join(workspacePath, 'docs', 'prds', 'active'),\n // Also check two levels up (worktrees)\n join(workspacePath, '..', '..', 'docs', 'prds', 'planned'),\n join(workspacePath, '..', '..', 'docs', 'prds', 'active'),\n ];\n\n const found: Array<{ path: string; label: string }> = [];\n for (const dir of searchDirs) {\n if (!existsSync(dir)) continue;\n try {\n const files = readdirSync(dir);\n for (const file of files) {\n if (file.toLowerCase().includes(issueLower)) {\n found.push({ path: join(dir, file), label: file });\n }\n }\n } catch { /* ignore read errors */ }\n }\n return found;\n}\n\nconst execAsync = promisify(exec);\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\nexport interface PlanningIssue {\n id: string;\n identifier: string;\n title: string;\n description: string;\n url: string;\n source: 'linear' | 'github' | 'rally';\n comments?: Array<{ author: string; body: string; createdAt: string }>;\n}\n\n/** Progress event emitted during planning session setup. */\nexport interface PlanningProgress {\n step: number;\n total: number;\n label: string;\n detail: string;\n status: 'active' | 'complete' | 'error';\n}\n\nexport interface SpawnPlanningOptions {\n issue: PlanningIssue;\n workspacePath: string;\n projectPath: string;\n sessionName: string;\n workspaceLocation: 'local' | 'remote';\n startDocker?: boolean;\n shadowMode?: boolean;\n /** Optional model override — if omitted, the planning-agent setting is used. */\n model?: string;\n /** Optional effort level — controls how thorough the planning agent is. */\n effort?: 'low' | 'medium' | 'high';\n /** Optional callback for streaming progress events to the client. */\n onProgress?: (event: PlanningProgress) => void;\n}\n\nexport interface SpawnPlanningResult {\n success: boolean;\n error?: string;\n}\n\n// ─── Helpers ─────────────────────────────────────────────────────────────────\n\nasync function ensureTmuxRunning(): Promise<void> {\n try {\n await execAsync('tmux list-sessions 2>/dev/null', { encoding: 'utf-8' });\n } catch {\n // Tmux server not running, start it\n try {\n await execAsync('tmux new-session -d -s panopticon-init', { encoding: 'utf-8' });\n console.log('Started tmux server');\n } catch (startErr) {\n console.error('Failed to start tmux server:', startErr);\n }\n }\n // Strip env vars from tmux global environment that should NOT leak into\n // agent sessions. The tmux server inherits the dashboard's process.env\n // (which includes all of .panopticon.env), but agents should only receive\n // explicitly-passed provider-specific vars via createSession().\n const varsToStrip = [\n 'CLAUDECODE', 'CLAUDE_CODE_ENTRYPOINT',\n 'OPENAI_API_KEY', 'LINEAR_API_KEY', 'GITHUB_TOKEN',\n 'ZAI_API_KEY', 'HUME_API_KEY', 'KIMI_API_KEY', 'GOOGLE_API_KEY',\n ];\n for (const envVar of varsToStrip) {\n try {\n await execAsync(`tmux set-environment -g -u ${envVar} 2>/dev/null`, { encoding: 'utf-8' });\n } catch {\n // Variable wasn't set — fine\n }\n }\n}\n\n// ─── Planning prompt builder ─────────────────────────────────────────────────\n\nexport function buildPlanningPrompt(issue: PlanningIssue, workspacePath: string, planningModel?: string, effort?: 'low' | 'medium' | 'high'): string {\n const issueLower = issue.identifier.toLowerCase();\n const version = getPackageVersion();\n const modelAuthor = planningModel ? `agent:${planningModel}` : 'agent:claude-opus-4-6';\n const prdFiles = discoverPrdFiles(workspacePath, issue.identifier);\n\n // Build comments section\n let commentsSection = '';\n if (issue.comments && issue.comments.length > 0) {\n const commentLines = issue.comments\n .sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime())\n .map(c => {\n const date = c.createdAt.slice(0, 10);\n const body = c.body.length > 2000 ? c.body.slice(0, 2000) + ' [truncated]' : c.body;\n return `### ${c.author} (${date}):\\n${body}`;\n });\n commentsSection = `\\n## Issue Comments\\n\\n**IMPORTANT: Read these comments carefully — they contain context, decisions, and references to previous work.**\\n\\n${commentLines.join('\\n\\n---\\n\\n')}\\n`;\n }\n\n // Check for spec file\n let specSection = '';\n const specSearchDirs = [\n join(workspacePath, 'docs', 'prds', 'active'),\n join(workspacePath, '..', '..', 'docs', 'prds', 'active'),\n ];\n for (const specDir of specSearchDirs) {\n if (!existsSync(specDir)) continue;\n try {\n const files = readdirSync(specDir);\n const specFile = files.find(f =>\n f.toLowerCase().includes(issueLower) && f.endsWith('-spec.md')\n );\n if (specFile) {\n const specContent = readFileSync(join(specDir, specFile), 'utf-8');\n specSection = `\n## Feature Spec (Human-Written)\n\n**A spec has been written for this feature.** This is your primary input — read it carefully before starting discovery.\n\n**File:** \\`${join(specDir, specFile)}\\`\n\n<spec>\n${specContent}\n</spec>\n\n`;\n break;\n }\n } catch { /* ignore read errors */ }\n }\n\n // Check for polyrepo structure\n const teamPrefix = extractTeamPrefix(issue.identifier);\n const projectConfig = teamPrefix ? findProjectByTeam(teamPrefix) : null;\n let projectStructureSection = '';\n if (projectConfig?.workspace?.type === 'polyrepo' && projectConfig.workspace.repos) {\n const repos = projectConfig.workspace.repos;\n projectStructureSection = `\n## Project Structure (Polyrepo)\n\n**IMPORTANT:** This project uses a **polyrepo** structure. The workspace root is NOT a git repository.\nEach subdirectory is a separate git worktree:\n\n| Directory | Purpose |\n|-----------|---------|\n${repos.map((r: any) => `| \\`${r.name}/\\` | Git worktree for ${r.path} |`).join('\\n')}\n\n**Git operations:**\n- Run \\`git status\\`, \\`git log\\`, etc. INSIDE the subdirectories (e.g., \\`cd fe && git status\\`)\n- The workspace root (\\`${workspacePath}\\`) has no \\`.git\\` directory\n- Each subdirectory has its own branch: \\`${repos[0]?.branch_prefix || 'feature/'}${issueLower}\\`\n\n`;\n }\n\n const effortSection = effort && effort !== 'medium' ? `\n## Planning Effort: ${effort === 'high' ? 'High (Deep Analysis)' : 'Low (Quick Planning)'}\n\n${effort === 'high'\n ? `**The user has requested HIGH effort planning.** Be exceptionally thorough:\n- Explore more of the codebase before concluding — check adjacent files, not just the obvious ones\n- Identify edge cases, potential failure modes, and risks\n- Consider multiple implementation approaches and explain tradeoffs\n- Ask more clarifying questions when scope is ambiguous\n- Break down tasks into finer-grained subtasks`\n : `**The user has requested LOW effort planning.** Be concise and fast:\n- Focus on the most critical decisions only\n- Keep the task list tight — 3–5 items max unless truly necessary\n- Skip deep exploration; read only the directly relevant files\n- Ask only essential clarifying questions`\n }\n\n` : '';\n\n return `<!-- panopticon:orchestration-context-start -->\n<!-- This is Panopticon orchestration context injected automatically.\n It contains planning session setup instructions, not agent reasoning.\n Session summarizers should SKIP this block and focus on the agent's\n actual work, decisions, and tradeoffs that follow. -->\n\n# Planning Session: ${issue.identifier}\n\n## CRITICAL: PLANNING ONLY - NO IMPLEMENTATION\n\n**YOU ARE IN PLANNING MODE. DO NOT:**\n- Write or modify any code files (except STATE.md)\n- Run implementation commands (npm install, docker compose, make, etc.)\n- Create actual features or functionality\n- Start implementing the solution\n\n**YOU SHOULD ONLY:**\n- Ask clarifying questions (use AskUserQuestion tool)\n- Explore the codebase to understand context (read files, grep)\n- Generate planning artifacts:\n - STATE.md (decisions, approach, architecture)\n - Beads tasks (via \\`bd create\\`)\n - Implementation plan at \\`docs/prds/active/{issue-id}/STATE.md\\` (copy of STATE.md, required for dashboard)\n- Present options and tradeoffs for the user to decide\n\nWhen planning is complete, STOP and tell the user: \"Planning complete - click Done when ready to hand off to an agent for implementation.\"\n\n---\n${effortSection}\n## Issue Details\n- **ID:** ${issue.identifier}\n- **Title:** ${issue.title}\n- **URL:** ${issue.url}\n\n## Description\n${issue.description || 'No description provided'}\n${commentsSection}${specSection}${projectStructureSection}\n---\n\n## Your Mission\n\nYou are a planning agent conducting a **discovery session** for this issue.\n\n### Phase 1: Understand Context\n1. **If a spec file was provided above**, read it thoroughly — it's your primary input\n2. Read the codebase to understand relevant files and patterns\n3. Identify what subsystems/files this issue affects\n4. Note any existing patterns we should follow\n\n### Phase 2: Discovery Conversation\nUse AskUserQuestion tool to ask contextual questions:\n- What's the scope? What's explicitly OUT of scope?\n- Any technical constraints or preferences?\n- What does \"done\" look like?\n- Are there edge cases we need to handle?\n\n### Difficulty Estimation\n\nFor each sub-task, estimate difficulty using this rubric:\n\n| Level | When to Use | Model |\n|-------|-------------|-------|\n| \\`trivial\\` | Typo, comment, formatting only | haiku |\n| \\`simple\\` | Bug fix, single file, obvious change | haiku |\n| \\`medium\\` | New feature, 3-5 files, standard patterns | sonnet |\n| \\`complex\\` | Refactor, migration, 6+ files, some risk | sonnet |\n| \\`expert\\` | Architecture, security, performance, high risk | opus |\n\n### Phase 3: Generate Artifacts (NO CODE!)\nWhen discovery is complete:\n1. Create STATE.md with decisions made\n2. Copy STATE.md to implementation plan at \\`docs/prds/active/{issue-id}/STATE.md\\` (required for dashboard)\n3. Create a vBRIEF plan file at \\`.planning/plan.vbrief.json\\` — **MUST follow the exact format below**\n4. Summarize the plan and STOP\n\n**DO NOT run \\`bd create\\` commands.** Beads tasks are created automatically from \\`plan.vbrief.json\\` by Cloister when planning completes.\n\n### vBRIEF Plan Format (REQUIRED)\n\nThe plan file MUST conform to vBRIEF v0.5 spec (https://github.com/deftai/vBRIEF).\nIt MUST have exactly two top-level keys: \\`vBRIEFInfo\\` and \\`plan\\`.\n\n\\`\\`\\`json\n{\n \"vBRIEFInfo\": {\n \"version\": \"0.5\",\n \"created\": \"<ISO 8601 timestamp>\",\n \"author\": \"panopticon-cli/${version}\",\n \"description\": \"Plan for ${issue.identifier}: <issue title>\"\n },\n \"plan\": {\n \"id\": \"${issueLower}\",\n \"title\": \"<issue title>\",\n \"status\": \"approved\",\n \"uid\": \"<generate a UUID v4>\",\n \"author\": \"${modelAuthor}\",\n \"sequence\": 1,\n \"created\": \"<ISO 8601 timestamp — same as vBRIEFInfo.created>\",\n \"updated\": \"<ISO 8601 timestamp — same as created>\",\n \"references\": [\n { \"uri\": \"${issue.url}\", \"label\": \"${issue.identifier}\", \"type\": \"issue\" }${prdFiles.length > 0 ? `,\n ${prdFiles.map(p => `{ \"uri\": \"${p.path}\", \"label\": \"${p.label}\", \"type\": \"prd\" }`).join(',\\n ')}` : ''}\n ],\n \"tags\": [\"<relevant tags>\"],\n \"narratives\": {\n \"Problem\": \"<what problem this solves>\",\n \"Proposal\": \"<the approach chosen>\"\n },\n \"items\": [\n {\n \"id\": \"<short-kebab-id>\",\n \"title\": \"<task title>\",\n \"status\": \"pending\",\n \"priority\": \"medium\",\n \"created\": \"<ISO 8601 timestamp>\",\n \"metadata\": {\n \"difficulty\": \"trivial|simple|medium|complex|expert\",\n \"issueLabel\": \"${issueLower}\"\n },\n \"narrative\": { \"Action\": \"<what needs to be done>\" },\n \"subItems\": [\n {\n \"id\": \"<parent-id>.ac1\",\n \"title\": \"<specific testable acceptance criterion>\",\n \"status\": \"pending\",\n \"metadata\": { \"kind\": \"acceptance_criterion\" }\n }\n ]\n }\n ],\n \"edges\": [\n { \"from\": \"<source-item-id>\", \"to\": \"<target-item-id>\", \"type\": \"blocks\" }\n ]\n }\n}\n\\`\\`\\`\n\n**CRITICAL vBRIEF rules:**\n- The file MUST have \\`vBRIEFInfo\\` and \\`plan\\` as the ONLY top-level keys\n- \\`plan.id\\` MUST be the issue ID in lowercase (e.g., \"${issueLower}\")\n- \\`plan.uid\\` MUST be a freshly generated UUID v4\n- Do NOT use \\`issue\\`, \\`issueId\\`, or \\`issue_id\\` — use \\`plan.id\\`\n- \\`items[].status\\` MUST be one of: draft, proposed, approved, pending, running, completed, blocked, cancelled\n- Acceptance criteria MUST be \\`subItems\\` with \\`metadata.kind: \"acceptance_criterion\"\\`\n- \\`metadata.difficulty\\` and \\`metadata.issueLabel\\` are Panopticon extensions to the vBRIEF spec\n- Edge types: \\`blocks\\` (hard dependency), \\`informs\\` (soft), \\`invalidates\\`, \\`suggests\\`\n\n**IMPORTANT:** Create the plan file BEFORE creating beads tasks.\n**NOTE:** \\`*-spec.md\\` files are human-written specs — do NOT overwrite them. Your output is \\`*-plan.md\\`.\n\n**Remember:** Be a thinking partner, not an interviewer. Ask questions that help clarify.\n\nStart by exploring the codebase to understand the context, then begin the discovery conversation.\n\n<!-- panopticon:orchestration-context-end -->\n`;\n}\n\n// ─── Main spawn function ─────────────────────────────────────────────────────\n\n/**\n * Spawn a planning agent session in the background.\n *\n * Creates workspace (if needed), writes planning prompt, and spawns Claude Code\n * in a tmux session. The agent state directory at ~/.panopticon/agents/<sessionName>/\n * must already exist with a preliminary state.json (status: 'starting').\n *\n * This function is designed to run as fire-and-forget after the API response\n * is sent. It updates agent state to 'running' on success or 'failed' on error.\n */\nexport async function spawnPlanningSession(opts: SpawnPlanningOptions): Promise<SpawnPlanningResult> {\n const { issue, workspacePath, projectPath, sessionName, workspaceLocation, startDocker, shadowMode, model: modelOverride, effort, onProgress } = opts;\n const issueLower = issue.identifier.toLowerCase();\n const agentStateDir = join(homedir(), '.panopticon', 'agents', sessionName);\n\n const TOTAL_STEPS = 5;\n const progress = (step: number, label: string, detail: string, status: 'active' | 'complete' | 'error' = 'active') => {\n onProgress?.({ step, total: TOTAL_STEPS, label, detail, status });\n };\n\n try {\n console.log(`[start-planning] Background setup starting for ${issue.identifier}`);\n\n // ── Step 1: Create workspace if needed ─────────────────────────────────\n progress(1, 'Creating workspace', `${issueLower} on ${projectPath.split('/').pop() || 'project'}`);\n\n let workspaceCreated = existsSync(workspacePath) &&\n !readdirSync(workspacePath).every((f: string) => f === '.planning');\n\n if (!workspaceCreated) {\n try {\n const projectConfig = findProjectByPath(projectPath) || findProjectByTeam(extractTeamPrefix(issue.identifier) || '');\n if (projectConfig?.workspace) {\n // Use library directly for real-time progress streaming\n console.log(`[start-planning] Creating workspace via library for ${issue.identifier}, projectConfig=${projectConfig.name}`);\n const wsResult = await createWorkspace({\n projectConfig,\n featureName: issueLower,\n startDocker,\n onProgress: (event) => {\n console.log(`[start-planning] Workspace progress: ${event.label} — ${event.detail} [${event.status}]`);\n // Forward workspace sub-step progress as step 1 sub-step events\n progress(1, event.label, event.detail, event.status);\n },\n });\n console.log(`[start-planning] Workspace result: success=${wsResult.success}, steps=${wsResult.steps.length}, errors=${wsResult.errors.length}`);\n if (wsResult.errors.length > 0) {\n console.error(`[start-planning] Workspace errors:`, wsResult.errors);\n }\n if (!wsResult.success) {\n throw new Error(wsResult.errors.join('; '));\n }\n } else {\n // Fallback: use CLI for projects without workspace config\n const dockerFlag = startDocker ? ' --docker' : '';\n const locationFlag = workspaceLocation === 'remote' ? ' --remote' : ' --local';\n const createCmd = `pan workspace create ${issue.identifier}${locationFlag}${dockerFlag}`;\n console.log(`[start-planning] Creating workspace via CLI: ${createCmd}`);\n await execAsync(createCmd, {\n cwd: projectPath,\n encoding: 'utf-8',\n timeout: startDocker ? 300000 : 120000,\n });\n }\n workspaceCreated = true;\n console.log(`[start-planning] Workspace created successfully`);\n } catch (err: any) {\n // CRITICAL: workspace MUST exist for local planning. If creation failed,\n // abort — never fall back to project root, which causes beads and planning\n // artifacts to land in the wrong place (PAN-358).\n const errorMsg = `Workspace creation failed: ${err.message}`;\n console.error(`[start-planning] ABORTING: ${errorMsg}`);\n progress(1, 'Creating workspace', errorMsg, 'error');\n writeFileSync(join(agentStateDir, 'state.json'), JSON.stringify({\n id: sessionName, issueId: issue.identifier, workspace: workspacePath,\n status: 'failed', error: errorMsg,\n startedAt: new Date().toISOString(), type: 'planning', location: workspaceLocation,\n }, null, 2));\n return { success: false, error: errorMsg };\n }\n }\n\n progress(1, 'Creating workspace', workspaceCreated ? 'Workspace ready' : 'Already exists', 'complete');\n\n // ── Step 2: Prepare planning environment ──────────────────────────────\n progress(2, 'Preparing planning environment', '.planning/ directory structure');\n\n // Kill existing planning session if any\n await execAsync(`tmux kill-session -t ${sessionName} 2>/dev/null || true`, { encoding: 'utf-8' });\n\n // Create planning directory structure\n const planningDir = join(workspacePath, '.planning');\n mkdirSync(planningDir, { recursive: true });\n for (const subdir of ['transcripts', 'discussions', 'notes']) {\n mkdirSync(join(planningDir, subdir), { recursive: true });\n }\n\n // Clear stale STATE.md and .planning-complete from previous session\n for (const staleFile of ['STATE.md', '.planning-complete']) {\n const stalePath = join(planningDir, staleFile);\n if (existsSync(stalePath)) {\n console.log(`[start-planning] Clearing stale ${staleFile}`);\n rmSync(stalePath, { force: true });\n }\n }\n\n // Initialize Shadow Engineering if enabled\n if (shadowMode) {\n const inferencePath = join(planningDir, 'INFERENCE.md');\n if (!existsSync(inferencePath)) {\n writeFileSync(inferencePath,\n `# Inference Document - ${issue.identifier.toUpperCase()}\\n\\n*This document is maintained by the Shadow Engineering Monitoring Agent.*\\n\\n## Status\\n\\nAwaiting initial artifact analysis.\\n`,\n 'utf-8',\n );\n console.log(`[start-planning] Shadow Engineering: Initialized INFERENCE.md`);\n }\n }\n\n progress(2, 'Preparing planning environment', 'Environment ready', 'complete');\n\n // ── Step 3: Load specs & PRDs ────────────────────────────────────────\n progress(3, 'Loading specs & PRDs', `Searching for ${issue.identifier} specs`);\n\n // Determine planning model — explicit override takes precedence over work-type router\n let settingsModel = 'claude-opus-4-6';\n try {\n const { getModelId } = await import('../work-type-router.js');\n settingsModel = getModelId('planning-agent');\n } catch { /* fall back to default */ }\n const planningModel = modelOverride || settingsModel;\n\n // Discover and copy PRD files to workspace\n const prdFiles = discoverPrdFiles(workspacePath, issue.identifier);\n if (prdFiles.length > 0) {\n const prdDestPath = join(planningDir, 'prd.md');\n if (!existsSync(prdDestPath)) {\n // Copy the first matching PRD (prefer active over planned)\n try {\n const prdContent = readFileSync(prdFiles[0].path, 'utf-8');\n writeFileSync(prdDestPath, prdContent, 'utf-8');\n console.log(`[start-planning] Copied PRD to ${prdDestPath} from ${prdFiles[0].path}`);\n } catch (err: any) {\n console.warn(`[start-planning] Could not copy PRD: ${err.message}`);\n }\n }\n }\n\n progress(3, 'Loading specs & PRDs', prdFiles.length > 0 ? prdFiles[0].label : 'No PRDs found', 'complete');\n\n // ── Step 4: Configure agent ─────────────────────────────────────────\n progress(4, 'Configuring agent', planningModel);\n\n const planningPromptPath = join(planningDir, 'PLANNING_PROMPT.md');\n const planningPrompt = buildPlanningPrompt(issue, workspacePath, planningModel, effort);\n writeFileSync(planningPromptPath, planningPrompt);\n const agentCmd = getAgentCommand(planningModel);\n const cmdWithArgs = agentCmd.args.length > 0\n ? `${agentCmd.command} ${agentCmd.args.join(' ')} --dangerously-skip-permissions`\n : `${agentCmd.command} --dangerously-skip-permissions`;\n\n // Get provider env vars for non-Anthropic models\n let providerExports = '';\n const provider = getProviderForModel(planningModel);\n if (provider.name !== 'anthropic') {\n const { config } = loadYamlConfig();\n const apiKey = config.apiKeys[provider.name as keyof typeof config.apiKeys];\n if (apiKey) {\n const envVars = getProviderEnv(provider, apiKey);\n providerExports = Object.entries(envVars)\n .map(([k, v]) => `export ${k}=\"${v.replace(/\"/g, '\\\\\"')}\"`)\n .join('\\n');\n }\n }\n\n // ── Write launcher script ──────────────────────────────────────────────\n const initMessage = `Please read the planning prompt file at ${planningPromptPath} and begin the planning session for ${issue.identifier}: ${issue.title}`;\n const promptFile = join(agentStateDir, 'init-prompt.txt');\n const launcherScript = join(agentStateDir, 'launcher.sh');\n writeFileSync(promptFile, initMessage);\n writeFileSync(launcherScript, `#!/bin/bash\n# Set terminal environment for proper rendering (match remote launcher)\nexport TERM=xterm-256color\nexport COLORTERM=truecolor\nexport LANG=C.UTF-8\nexport LC_ALL=C.UTF-8\nexport PANOPTICON_AGENT_ID=\"${sessionName}\"\nexport PANOPTICON_ISSUE_ID=\"${issue.identifier}\"\nexport PANOPTICON_SESSION_TYPE=\"planning\"\n${providerExports}\ncd \"${workspacePath}\"\nprompt=$(cat \"${promptFile}\")\ntrap '' HUP\necho \"[launcher] Claude starting at $(date)\" >> /tmp/pan-launcher-debug.log\n${cmdWithArgs} \"$prompt\"\nCLAUDE_EXIT=$?\necho \"[launcher] Claude exited with code $CLAUDE_EXIT at $(date)\" >> /tmp/pan-launcher-debug.log\n# Keep session alive after Claude exits so user can review and click Done\necho \"\"\necho \"Planning agent has exited. Session kept alive for review.\"\necho \"Click 'Done' in the dashboard when ready to hand off to implementation.\"\necho \"[launcher] Keep-alive loop starting at $(date)\" >> /tmp/pan-launcher-debug.log\nwhile true; do sleep 60; done\n`, { mode: 0o755 });\n\n progress(4, 'Configuring agent', `${planningModel} — prompt & launcher ready`, 'complete');\n\n // ── Step 5: Launch planning session ───────────────────────────────────\n progress(5, 'Launching planning session', sessionName);\n\n await ensureTmuxRunning();\n await execAsync(\n `TERM=xterm-256color tmux new-session -d -s ${sessionName} \"bash '${launcherScript}'\"`,\n { encoding: 'utf-8' },\n );\n // Protect the session from being destroyed when clients disconnect.\n // When the dashboard's WebSocket terminal attaches and then detaches,\n // tmux can destroy the session if destroy-unattached is on.\n await execAsync(`tmux set-option -t ${sessionName} destroy-unattached off 2>/dev/null || true`, { encoding: 'utf-8' });\n await execAsync(`tmux set-option -t ${sessionName} remain-on-exit on 2>/dev/null || true`, { encoding: 'utf-8' });\n\n // NOTE: No pre-resize of tmux window here. The WebSocket terminal handler\n // defers PTY spawn until the client sends its actual dimensions, so the\n // tmux window will be sized correctly from the start. Pre-resizing to\n // 200×50 caused a dimension cascade (200→120→actual) that garbled output.\n // See PAN-417 for the full forensic timeline.\n\n // ── Update agent state to running ──────────────────────────────────────\n writeFileSync(join(agentStateDir, 'state.json'), JSON.stringify({\n id: sessionName,\n issueId: issue.identifier,\n workspace: workspacePath,\n runtime: 'claude',\n model: planningModel,\n status: 'running',\n startedAt: new Date().toISOString(),\n type: 'planning',\n location: workspaceLocation,\n }, null, 2));\n\n progress(5, 'Launching planning session', 'Agent running', 'complete');\n\n console.log(`[start-planning] Started local planning agent ${sessionName}`);\n return { success: true };\n\n } catch (err: any) {\n console.error(`[start-planning] Agent spawn failed for ${issue.identifier}:`, err);\n // Update state file to reflect failure\n try {\n writeFileSync(join(agentStateDir, 'state.json'), JSON.stringify({\n id: sessionName,\n issueId: issue.identifier,\n workspace: workspacePath,\n status: 'failed',\n error: err.message,\n startedAt: new Date().toISOString(),\n type: 'planning',\n location: workspaceLocation,\n }, null, 2));\n } catch { /* ignore state write errors */ }\n return { success: false, error: err.message };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;eAiByF;kBAExB;gBACK;wBACZ;AAE1D,MAAM,YAAY,cAAc,I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{"version":3,"file":"spawn-planning-session-DtbNfA2Q.js","names":["loadYamlConfig"],"sources":["../../src/lib/planning/spawn-planning-session.ts"],"sourcesContent":["/**\n * Spawn Planning Session — background workspace + agent setup\n *\n * Extracted from the old Express /api/issues/:id/start-planning handler.\n * Creates workspace, writes planning prompt, spawns Claude Code in tmux.\n * Used by both the dashboard route and CLI.\n *\n * This runs as a background task after the API responds — the UI shows\n * \"Waiting for session to start...\" until the tmux session is ready.\n */\n\nimport { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { exec } from 'node:child_process';\nimport { promisify } from 'node:util';\nimport { extractTeamPrefix, findProjectByTeam, findProjectByPath } from '../projects.js';\nimport { getAgentCommand, isAnthropicModel } from '../settings.js';\nimport { loadConfig as loadYamlConfig } from '../config-yaml.js';\nimport { getProviderForModel, getProviderEnv } from '../providers.js';\nimport { createWorkspace } from '../workspace-manager.js';\n\nconst __dirname = fileURLToPath(new URL('.', import.meta.url));\n\nfunction getPackageVersion(): string {\n try {\n const pkgPath = resolve(__dirname, '../../../package.json');\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8')) as { version: string };\n return pkg.version;\n } catch {\n return '0.0.0';\n }\n}\n\n/**\n * Discover PRD files matching an issue ID from docs/prds directories.\n * Returns list of { path, label } for use in references template.\n */\nfunction discoverPrdFiles(workspacePath: string, issueId: string): Array<{ path: string; label: string }> {\n const issueLower = issueId.toLowerCase();\n const searchDirs = [\n join(workspacePath, 'docs', 'prds', 'planned'),\n join(workspacePath, 'docs', 'prds', 'active'),\n // Also check two levels up (worktrees)\n join(workspacePath, '..', '..', 'docs', 'prds', 'planned'),\n join(workspacePath, '..', '..', 'docs', 'prds', 'active'),\n ];\n\n const found: Array<{ path: string; label: string }> = [];\n for (const dir of searchDirs) {\n if (!existsSync(dir)) continue;\n try {\n const files = readdirSync(dir);\n for (const file of files) {\n if (file.toLowerCase().includes(issueLower)) {\n found.push({ path: join(dir, file), label: file });\n }\n }\n } catch { /* ignore read errors */ }\n }\n return found;\n}\n\nconst execAsync = promisify(exec);\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\nexport interface PlanningIssue {\n id: string;\n identifier: string;\n title: string;\n description: string;\n url: string;\n source: 'linear' | 'github' | 'rally';\n comments?: Array<{ author: string; body: string; createdAt: string }>;\n}\n\n/** Progress event emitted during planning session setup. */\nexport interface PlanningProgress {\n step: number;\n total: number;\n label: string;\n detail: string;\n status: 'active' | 'complete' | 'error';\n}\n\nexport interface SpawnPlanningOptions {\n issue: PlanningIssue;\n workspacePath: string;\n projectPath: string;\n sessionName: string;\n workspaceLocation: 'local' | 'remote';\n startDocker?: boolean;\n shadowMode?: boolean;\n /** Optional model override — if omitted, the planning-agent setting is used. */\n model?: string;\n /** Optional effort level — controls how thorough the planning agent is. */\n effort?: 'low' | 'medium' | 'high';\n /** Optional callback for streaming progress events to the client. */\n onProgress?: (event: PlanningProgress) => void;\n}\n\nexport interface SpawnPlanningResult {\n success: boolean;\n error?: string;\n}\n\n// ─── Helpers ─────────────────────────────────────────────────────────────────\n\nasync function ensureTmuxRunning(): Promise<void> {\n try {\n await execAsync('tmux list-sessions 2>/dev/null', { encoding: 'utf-8' });\n } catch {\n // Tmux server not running, start it\n try {\n await execAsync('tmux new-session -d -s panopticon-init', { encoding: 'utf-8' });\n console.log('Started tmux server');\n } catch (startErr) {\n console.error('Failed to start tmux server:', startErr);\n }\n }\n // Strip env vars from tmux global environment that should NOT leak into\n // agent sessions. The tmux server inherits the dashboard's process.env\n // (which includes all of .panopticon.env), but agents should only receive\n // explicitly-passed provider-specific vars via createSession().\n const varsToStrip = [\n 'CLAUDECODE', 'CLAUDE_CODE_ENTRYPOINT',\n 'OPENAI_API_KEY', 'LINEAR_API_KEY', 'GITHUB_TOKEN',\n 'ZAI_API_KEY', 'HUME_API_KEY', 'KIMI_API_KEY', 'GOOGLE_API_KEY',\n ];\n for (const envVar of varsToStrip) {\n try {\n await execAsync(`tmux set-environment -g -u ${envVar} 2>/dev/null`, { encoding: 'utf-8' });\n } catch {\n // Variable wasn't set — fine\n }\n }\n}\n\n// ─── Planning prompt builder ─────────────────────────────────────────────────\n\nexport function buildPlanningPrompt(issue: PlanningIssue, workspacePath: string, planningModel?: string, effort?: 'low' | 'medium' | 'high'): string {\n const issueLower = issue.identifier.toLowerCase();\n const version = getPackageVersion();\n const modelAuthor = planningModel ? `agent:${planningModel}` : 'agent:claude-opus-4-6';\n const prdFiles = discoverPrdFiles(workspacePath, issue.identifier);\n\n // Build comments section\n let commentsSection = '';\n if (issue.comments && issue.comments.length > 0) {\n const commentLines = issue.comments\n .sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime())\n .map(c => {\n const date = c.createdAt.slice(0, 10);\n const body = c.body.length > 2000 ? c.body.slice(0, 2000) + ' [truncated]' : c.body;\n return `### ${c.author} (${date}):\\n${body}`;\n });\n commentsSection = `\\n## Issue Comments\\n\\n**IMPORTANT: Read these comments carefully — they contain context, decisions, and references to previous work.**\\n\\n${commentLines.join('\\n\\n---\\n\\n')}\\n`;\n }\n\n // Check for spec file\n let specSection = '';\n const specSearchDirs = [\n join(workspacePath, 'docs', 'prds', 'active'),\n join(workspacePath, '..', '..', 'docs', 'prds', 'active'),\n ];\n for (const specDir of specSearchDirs) {\n if (!existsSync(specDir)) continue;\n try {\n const files = readdirSync(specDir);\n const specFile = files.find(f =>\n f.toLowerCase().includes(issueLower) && f.endsWith('-spec.md')\n );\n if (specFile) {\n const specContent = readFileSync(join(specDir, specFile), 'utf-8');\n specSection = `\n## Feature Spec (Human-Written)\n\n**A spec has been written for this feature.** This is your primary input — read it carefully before starting discovery.\n\n**File:** \\`${join(specDir, specFile)}\\`\n\n<spec>\n${specContent}\n</spec>\n\n`;\n break;\n }\n } catch { /* ignore read errors */ }\n }\n\n // Check for polyrepo structure\n const teamPrefix = extractTeamPrefix(issue.identifier);\n const projectConfig = teamPrefix ? findProjectByTeam(teamPrefix) : null;\n let projectStructureSection = '';\n if (projectConfig?.workspace?.type === 'polyrepo' && projectConfig.workspace.repos) {\n const repos = projectConfig.workspace.repos;\n projectStructureSection = `\n## Project Structure (Polyrepo)\n\n**IMPORTANT:** This project uses a **polyrepo** structure. The workspace root is NOT a git repository.\nEach subdirectory is a separate git worktree:\n\n| Directory | Purpose |\n|-----------|---------|\n${repos.map((r: any) => `| \\`${r.name}/\\` | Git worktree for ${r.path} |`).join('\\n')}\n\n**Git operations:**\n- Run \\`git status\\`, \\`git log\\`, etc. INSIDE the subdirectories (e.g., \\`cd fe && git status\\`)\n- The workspace root (\\`${workspacePath}\\`) has no \\`.git\\` directory\n- Each subdirectory has its own branch: \\`${repos[0]?.branch_prefix || 'feature/'}${issueLower}\\`\n\n`;\n }\n\n const effortSection = effort && effort !== 'medium' ? `\n## Planning Effort: ${effort === 'high' ? 'High (Deep Analysis)' : 'Low (Quick Planning)'}\n\n${effort === 'high'\n ? `**The user has requested HIGH effort planning.** Be exceptionally thorough:\n- Explore more of the codebase before concluding — check adjacent files, not just the obvious ones\n- Identify edge cases, potential failure modes, and risks\n- Consider multiple implementation approaches and explain tradeoffs\n- Ask more clarifying questions when scope is ambiguous\n- Break down tasks into finer-grained subtasks`\n : `**The user has requested LOW effort planning.** Be concise and fast:\n- Focus on the most critical decisions only\n- Keep the task list tight — 3–5 items max unless truly necessary\n- Skip deep exploration; read only the directly relevant files\n- Ask only essential clarifying questions`\n }\n\n` : '';\n\n return `<!-- panopticon:orchestration-context-start -->\n<!-- This is Panopticon orchestration context injected automatically.\n It contains planning session setup instructions, not agent reasoning.\n Session summarizers should SKIP this block and focus on the agent's\n actual work, decisions, and tradeoffs that follow. -->\n\n# Planning Session: ${issue.identifier}\n\n## CRITICAL: PLANNING ONLY - NO IMPLEMENTATION\n\n**YOU ARE IN PLANNING MODE. DO NOT:**\n- Write or modify any code files (except STATE.md)\n- Run implementation commands (npm install, docker compose, make, etc.)\n- Create actual features or functionality\n- Start implementing the solution\n\n**YOU SHOULD ONLY:**\n- Ask clarifying questions (use AskUserQuestion tool)\n- Explore the codebase to understand context (read files, grep)\n- Generate planning artifacts:\n - STATE.md (decisions, approach, architecture)\n - Beads tasks (via \\`bd create\\`)\n - Implementation plan at \\`docs/prds/active/{issue-id}/STATE.md\\` (copy of STATE.md, required for dashboard)\n- Present options and tradeoffs for the user to decide\n\nWhen planning is complete, STOP and tell the user: \"Planning complete - click Done when ready to hand off to an agent for implementation.\"\n\n---\n${effortSection}\n## Issue Details\n- **ID:** ${issue.identifier}\n- **Title:** ${issue.title}\n- **URL:** ${issue.url}\n\n## Description\n${issue.description || 'No description provided'}\n${commentsSection}${specSection}${projectStructureSection}\n---\n\n## Your Mission\n\nYou are a planning agent conducting a **discovery session** for this issue.\n\n### Phase 1: Understand Context\n1. **If a spec file was provided above**, read it thoroughly — it's your primary input\n2. Read the codebase to understand relevant files and patterns\n3. Identify what subsystems/files this issue affects\n4. Note any existing patterns we should follow\n\n### Phase 2: Discovery Conversation\nUse AskUserQuestion tool to ask contextual questions:\n- What's the scope? What's explicitly OUT of scope?\n- Any technical constraints or preferences?\n- What does \"done\" look like?\n- Are there edge cases we need to handle?\n\n### Difficulty Estimation\n\nFor each sub-task, estimate difficulty using this rubric:\n\n| Level | When to Use | Model |\n|-------|-------------|-------|\n| \\`trivial\\` | Typo, comment, formatting only | haiku |\n| \\`simple\\` | Bug fix, single file, obvious change | haiku |\n| \\`medium\\` | New feature, 3-5 files, standard patterns | sonnet |\n| \\`complex\\` | Refactor, migration, 6+ files, some risk | sonnet |\n| \\`expert\\` | Architecture, security, performance, high risk | opus |\n\n### Phase 3: Generate Artifacts (NO CODE!)\nWhen discovery is complete:\n1. Create STATE.md with decisions made\n2. Copy STATE.md to implementation plan at \\`docs/prds/active/{issue-id}/STATE.md\\` (required for dashboard)\n3. Create a vBRIEF plan file at \\`.planning/plan.vbrief.json\\` — **MUST follow the exact format below**\n4. Summarize the plan and STOP\n\n**DO NOT run \\`bd create\\` commands.** Beads tasks are created automatically from \\`plan.vbrief.json\\` by Cloister when planning completes.\n\n### vBRIEF Plan Format (REQUIRED)\n\nThe plan file MUST conform to vBRIEF v0.5 spec (https://github.com/deftai/vBRIEF).\nIt MUST have exactly two top-level keys: \\`vBRIEFInfo\\` and \\`plan\\`.\n\n\\`\\`\\`json\n{\n \"vBRIEFInfo\": {\n \"version\": \"0.5\",\n \"created\": \"<ISO 8601 timestamp>\",\n \"author\": \"panopticon-cli/${version}\",\n \"description\": \"Plan for ${issue.identifier}: <issue title>\"\n },\n \"plan\": {\n \"id\": \"${issueLower}\",\n \"title\": \"<issue title>\",\n \"status\": \"approved\",\n \"uid\": \"<generate a UUID v4>\",\n \"author\": \"${modelAuthor}\",\n \"sequence\": 1,\n \"created\": \"<ISO 8601 timestamp — same as vBRIEFInfo.created>\",\n \"updated\": \"<ISO 8601 timestamp — same as created>\",\n \"references\": [\n { \"uri\": \"${issue.url}\", \"label\": \"${issue.identifier}\", \"type\": \"issue\" }${prdFiles.length > 0 ? `,\n ${prdFiles.map(p => `{ \"uri\": \"${p.path}\", \"label\": \"${p.label}\", \"type\": \"prd\" }`).join(',\\n ')}` : ''}\n ],\n \"tags\": [\"<relevant tags>\"],\n \"narratives\": {\n \"Problem\": \"<what problem this solves>\",\n \"Proposal\": \"<the approach chosen>\"\n },\n \"items\": [\n {\n \"id\": \"<short-kebab-id>\",\n \"title\": \"<task title>\",\n \"status\": \"pending\",\n \"priority\": \"medium\",\n \"created\": \"<ISO 8601 timestamp>\",\n \"metadata\": {\n \"difficulty\": \"trivial|simple|medium|complex|expert\",\n \"issueLabel\": \"${issueLower}\"\n },\n \"narrative\": { \"Action\": \"<what needs to be done>\" },\n \"subItems\": [\n {\n \"id\": \"<parent-id>.ac1\",\n \"title\": \"<specific testable acceptance criterion>\",\n \"status\": \"pending\",\n \"metadata\": { \"kind\": \"acceptance_criterion\" }\n }\n ]\n }\n ],\n \"edges\": [\n { \"from\": \"<source-item-id>\", \"to\": \"<target-item-id>\", \"type\": \"blocks\" }\n ]\n }\n}\n\\`\\`\\`\n\n**CRITICAL vBRIEF rules:**\n- The file MUST have \\`vBRIEFInfo\\` and \\`plan\\` as the ONLY top-level keys\n- \\`plan.id\\` MUST be the issue ID in lowercase (e.g., \"${issueLower}\")\n- \\`plan.uid\\` MUST be a freshly generated UUID v4\n- Do NOT use \\`issue\\`, \\`issueId\\`, or \\`issue_id\\` — use \\`plan.id\\`\n- \\`items[].status\\` MUST be one of: draft, proposed, approved, pending, running, completed, blocked, cancelled\n- Acceptance criteria MUST be \\`subItems\\` with \\`metadata.kind: \"acceptance_criterion\"\\`\n- \\`metadata.difficulty\\` and \\`metadata.issueLabel\\` are Panopticon extensions to the vBRIEF spec\n- Edge types: \\`blocks\\` (hard dependency), \\`informs\\` (soft), \\`invalidates\\`, \\`suggests\\`\n\n**IMPORTANT:** Create the plan file BEFORE creating beads tasks.\n**NOTE:** \\`*-spec.md\\` files are human-written specs — do NOT overwrite them. Your output is \\`*-plan.md\\`.\n\n**Remember:** Be a thinking partner, not an interviewer. Ask questions that help clarify.\n\nStart by exploring the codebase to understand the context, then begin the discovery conversation.\n\n<!-- panopticon:orchestration-context-end -->\n`;\n}\n\n// ─── Main spawn function ─────────────────────────────────────────────────────\n\n/**\n * Spawn a planning agent session in the background.\n *\n * Creates workspace (if needed), writes planning prompt, and spawns Claude Code\n * in a tmux session. The agent state directory at ~/.panopticon/agents/<sessionName>/\n * must already exist with a preliminary state.json (status: 'starting').\n *\n * This function is designed to run as fire-and-forget after the API response\n * is sent. It updates agent state to 'running' on success or 'failed' on error.\n */\nexport async function spawnPlanningSession(opts: SpawnPlanningOptions): Promise<SpawnPlanningResult> {\n const { issue, workspacePath, projectPath, sessionName, workspaceLocation, startDocker, shadowMode, model: modelOverride, effort, onProgress } = opts;\n const issueLower = issue.identifier.toLowerCase();\n const agentStateDir = join(homedir(), '.panopticon', 'agents', sessionName);\n\n const TOTAL_STEPS = 5;\n const progress = (step: number, label: string, detail: string, status: 'active' | 'complete' | 'error' = 'active') => {\n onProgress?.({ step, total: TOTAL_STEPS, label, detail, status });\n };\n\n try {\n console.log(`[start-planning] Background setup starting for ${issue.identifier}`);\n\n // ── Step 1: Create workspace if needed ─────────────────────────────────\n progress(1, 'Creating workspace', `${issueLower} on ${projectPath.split('/').pop() || 'project'}`);\n\n let workspaceCreated = existsSync(workspacePath) &&\n !readdirSync(workspacePath).every((f: string) => f === '.planning');\n\n if (!workspaceCreated) {\n try {\n const projectConfig = findProjectByPath(projectPath) || findProjectByTeam(extractTeamPrefix(issue.identifier) || '');\n if (projectConfig?.workspace) {\n // Use library directly for real-time progress streaming\n console.log(`[start-planning] Creating workspace via library for ${issue.identifier}, projectConfig=${projectConfig.name}`);\n const wsResult = await createWorkspace({\n projectConfig,\n featureName: issueLower,\n startDocker,\n onProgress: (event) => {\n console.log(`[start-planning] Workspace progress: ${event.label} — ${event.detail} [${event.status}]`);\n // Forward workspace sub-step progress as step 1 sub-step events\n progress(1, event.label, event.detail, event.status);\n },\n });\n console.log(`[start-planning] Workspace result: success=${wsResult.success}, steps=${wsResult.steps.length}, errors=${wsResult.errors.length}`);\n if (wsResult.errors.length > 0) {\n console.error(`[start-planning] Workspace errors:`, wsResult.errors);\n }\n if (!wsResult.success) {\n throw new Error(wsResult.errors.join('; '));\n }\n } else {\n // Fallback: use CLI for projects without workspace config\n const dockerFlag = startDocker ? ' --docker' : '';\n const locationFlag = workspaceLocation === 'remote' ? ' --remote' : ' --local';\n const createCmd = `pan workspace create ${issue.identifier}${locationFlag}${dockerFlag}`;\n console.log(`[start-planning] Creating workspace via CLI: ${createCmd}`);\n await execAsync(createCmd, {\n cwd: projectPath,\n encoding: 'utf-8',\n timeout: startDocker ? 300000 : 120000,\n });\n }\n workspaceCreated = true;\n console.log(`[start-planning] Workspace created successfully`);\n } catch (err: any) {\n // CRITICAL: workspace MUST exist for local planning. If creation failed,\n // abort — never fall back to project root, which causes beads and planning\n // artifacts to land in the wrong place (PAN-358).\n const errorMsg = `Workspace creation failed: ${err.message}`;\n console.error(`[start-planning] ABORTING: ${errorMsg}`);\n progress(1, 'Creating workspace', errorMsg, 'error');\n writeFileSync(join(agentStateDir, 'state.json'), JSON.stringify({\n id: sessionName, issueId: issue.identifier, workspace: workspacePath,\n status: 'failed', error: errorMsg,\n startedAt: new Date().toISOString(), type: 'planning', location: workspaceLocation,\n }, null, 2));\n return { success: false, error: errorMsg };\n }\n }\n\n progress(1, 'Creating workspace', workspaceCreated ? 'Workspace ready' : 'Already exists', 'complete');\n\n // ── Step 2: Prepare planning environment ──────────────────────────────\n progress(2, 'Preparing planning environment', '.planning/ directory structure');\n\n // Kill existing planning session if any\n await execAsync(`tmux kill-session -t ${sessionName} 2>/dev/null || true`, { encoding: 'utf-8' });\n\n // Create planning directory structure\n const planningDir = join(workspacePath, '.planning');\n mkdirSync(planningDir, { recursive: true });\n for (const subdir of ['transcripts', 'discussions', 'notes']) {\n mkdirSync(join(planningDir, subdir), { recursive: true });\n }\n\n // Clear stale STATE.md and .planning-complete from previous session\n for (const staleFile of ['STATE.md', '.planning-complete']) {\n const stalePath = join(planningDir, staleFile);\n if (existsSync(stalePath)) {\n console.log(`[start-planning] Clearing stale ${staleFile}`);\n rmSync(stalePath, { force: true });\n }\n }\n\n // Initialize Shadow Engineering if enabled\n if (shadowMode) {\n const inferencePath = join(planningDir, 'INFERENCE.md');\n if (!existsSync(inferencePath)) {\n writeFileSync(inferencePath,\n `# Inference Document - ${issue.identifier.toUpperCase()}\\n\\n*This document is maintained by the Shadow Engineering Monitoring Agent.*\\n\\n## Status\\n\\nAwaiting initial artifact analysis.\\n`,\n 'utf-8',\n );\n console.log(`[start-planning] Shadow Engineering: Initialized INFERENCE.md`);\n }\n }\n\n progress(2, 'Preparing planning environment', 'Environment ready', 'complete');\n\n // ── Step 3: Load specs & PRDs ────────────────────────────────────────\n progress(3, 'Loading specs & PRDs', `Searching for ${issue.identifier} specs`);\n\n // Determine planning model — explicit override takes precedence over work-type router\n let settingsModel = 'claude-opus-4-6';\n try {\n const { getModelId } = await import('../work-type-router.js');\n settingsModel = getModelId('planning-agent');\n } catch { /* fall back to default */ }\n const planningModel = modelOverride || settingsModel;\n\n // Discover and copy PRD files to workspace\n const prdFiles = discoverPrdFiles(workspacePath, issue.identifier);\n if (prdFiles.length > 0) {\n const prdDestPath = join(planningDir, 'prd.md');\n if (!existsSync(prdDestPath)) {\n // Copy the first matching PRD (prefer active over planned)\n try {\n const prdContent = readFileSync(prdFiles[0].path, 'utf-8');\n writeFileSync(prdDestPath, prdContent, 'utf-8');\n console.log(`[start-planning] Copied PRD to ${prdDestPath} from ${prdFiles[0].path}`);\n } catch (err: any) {\n console.warn(`[start-planning] Could not copy PRD: ${err.message}`);\n }\n }\n }\n\n progress(3, 'Loading specs & PRDs', prdFiles.length > 0 ? prdFiles[0].label : 'No PRDs found', 'complete');\n\n // ── Step 4: Configure agent ─────────────────────────────────────────\n progress(4, 'Configuring agent', planningModel);\n\n const planningPromptPath = join(planningDir, 'PLANNING_PROMPT.md');\n const planningPrompt = buildPlanningPrompt(issue, workspacePath, planningModel, effort);\n writeFileSync(planningPromptPath, planningPrompt);\n const agentCmd = getAgentCommand(planningModel);\n const cmdWithArgs = agentCmd.args.length > 0\n ? `${agentCmd.command} ${agentCmd.args.join(' ')} --dangerously-skip-permissions`\n : `${agentCmd.command} --dangerously-skip-permissions`;\n\n // Get provider env vars for non-Anthropic models\n let providerExports = '';\n const provider = getProviderForModel(planningModel);\n if (provider.name !== 'anthropic') {\n const { config } = loadYamlConfig();\n const apiKey = config.apiKeys[provider.name as keyof typeof config.apiKeys];\n if (apiKey) {\n const envVars = getProviderEnv(provider, apiKey);\n providerExports = Object.entries(envVars)\n .map(([k, v]) => `export ${k}=\"${v.replace(/\"/g, '\\\\\"')}\"`)\n .join('\\n');\n }\n }\n\n // ── Write launcher script ──────────────────────────────────────────────\n const initMessage = `Please read the planning prompt file at ${planningPromptPath} and begin the planning session for ${issue.identifier}: ${issue.title}`;\n const promptFile = join(agentStateDir, 'init-prompt.txt');\n const launcherScript = join(agentStateDir, 'launcher.sh');\n writeFileSync(promptFile, initMessage);\n writeFileSync(launcherScript, `#!/bin/bash\n# Set terminal environment for proper rendering (match remote launcher)\nexport TERM=xterm-256color\nexport COLORTERM=truecolor\nexport LANG=C.UTF-8\nexport LC_ALL=C.UTF-8\nexport PANOPTICON_AGENT_ID=\"${sessionName}\"\nexport PANOPTICON_ISSUE_ID=\"${issue.identifier}\"\nexport PANOPTICON_SESSION_TYPE=\"planning\"\n${providerExports}\ncd \"${workspacePath}\"\nprompt=$(cat \"${promptFile}\")\ntrap '' HUP\necho \"[launcher] Claude starting at $(date)\" >> /tmp/pan-launcher-debug.log\n${cmdWithArgs} \"$prompt\"\nCLAUDE_EXIT=$?\necho \"[launcher] Claude exited with code $CLAUDE_EXIT at $(date)\" >> /tmp/pan-launcher-debug.log\n# Keep session alive after Claude exits so user can review and click Done\necho \"\"\necho \"Planning agent has exited. Session kept alive for review.\"\necho \"Click 'Done' in the dashboard when ready to hand off to implementation.\"\necho \"[launcher] Keep-alive loop starting at $(date)\" >> /tmp/pan-launcher-debug.log\nwhile true; do sleep 60; done\n`, { mode: 0o755 });\n\n progress(4, 'Configuring agent', `${planningModel} — prompt & launcher ready`, 'complete');\n\n // ── Step 5: Launch planning session ───────────────────────────────────\n progress(5, 'Launching planning session', sessionName);\n\n await ensureTmuxRunning();\n await execAsync(\n `TERM=xterm-256color tmux new-session -d -s ${sessionName} \"bash '${launcherScript}'\"`,\n { encoding: 'utf-8' },\n );\n // Protect the session from being destroyed when clients disconnect.\n // When the dashboard's WebSocket terminal attaches and then detaches,\n // tmux can destroy the session if destroy-unattached is on.\n await execAsync(`tmux set-option -t ${sessionName} destroy-unattached off 2>/dev/null || true`, { encoding: 'utf-8' });\n await execAsync(`tmux set-option -t ${sessionName} remain-on-exit on 2>/dev/null || true`, { encoding: 'utf-8' });\n\n // NOTE: No pre-resize of tmux window here. The WebSocket terminal handler\n // defers PTY spawn until the client sends its actual dimensions, so the\n // tmux window will be sized correctly from the start. Pre-resizing to\n // 200×50 caused a dimension cascade (200→120→actual) that garbled output.\n // See PAN-417 for the full forensic timeline.\n\n // ── Update agent state to running ──────────────────────────────────────\n writeFileSync(join(agentStateDir, 'state.json'), JSON.stringify({\n id: sessionName,\n issueId: issue.identifier,\n workspace: workspacePath,\n runtime: 'claude',\n model: planningModel,\n status: 'running',\n startedAt: new Date().toISOString(),\n type: 'planning',\n location: workspaceLocation,\n }, null, 2));\n\n progress(5, 'Launching planning session', 'Agent running', 'complete');\n\n console.log(`[start-planning] Started local planning agent ${sessionName}`);\n return { success: true };\n\n } catch (err: any) {\n console.error(`[start-planning] Agent spawn failed for ${issue.identifier}:`, err);\n // Update state file to reflect failure\n try {\n writeFileSync(join(agentStateDir, 'state.json'), JSON.stringify({\n id: sessionName,\n issueId: issue.identifier,\n workspace: workspacePath,\n status: 'failed',\n error: err.message,\n startedAt: new Date().toISOString(),\n type: 'planning',\n location: workspaceLocation,\n }, null, 2));\n } catch { /* ignore state write errors */ }\n return { success: false, error: err.message };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;eAiByF;kBAExB;gBACK;wBACZ;AAE1D,MAAM,YAAY,cAAc,IAAI,IAAI,KAAK,OAAO,KAAK,IAAI,CAAC;AAE9D,SAAS,oBAA4B;AACnC,KAAI;EACF,MAAM,UAAU,QAAQ,WAAW,wBAAwB;AAE3D,SADY,KAAK,MAAM,aAAa,SAAS,QAAQ,CAAC,CAC3C;SACL;AACN,SAAO;;;;;;;AAQX,SAAS,iBAAiB,eAAuB,SAAyD;CACxG,MAAM,aAAa,QAAQ,aAAa;CACxC,MAAM,aAAa;EACjB,KAAK,eAAe,QAAQ,QAAQ,UAAU;EAC9C,KAAK,eAAe,QAAQ,QAAQ,SAAS;EAE7C,KAAK,eAAe,MAAM,MAAM,QAAQ,QAAQ,UAAU;EAC1D,KAAK,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SAAS,CACtB;AAID,QAAM,UAAU,sBAAsB,YAAY,8CAA8C,EAAE,UAAU,SAAS,CAAC;AACtH,QAAM,UAAU,sBAAsB,YAAY,yCAAyC,EAAE,UAAU,SAAS,CAAC;AASjH,gBAAc,KAAK,eAAe,aAAa,EAAE,KAAK,UAAU;GAC9D,IAAI;GACJ,SAAS,MAAM;GACf,WAAW;GACX,SAAS;GACT,OAAO;GACP,QAAQ;GACR,4BAAW,IAAI,MAAM,EAAC,aAAa;GACnC,MAAM;GACN,UAAU;GACX,EAAE,MAAM,EAAE,CAAC;AAEZ,WAAS,GAAG,8BAA8B,iBAAiB,WAAW;AAEtE,UAAQ,IAAI,iDAAiD,cAAc;AAC3E,SAAO,EAAE,SAAS,MAAM;UAEjB,KAAU;AACjB,UAAQ,MAAM,2CAA2C,MAAM,WAAW,IAAI,IAAI;AAElF,MAAI;AACF,iBAAc,KAAK,eAAe,aAAa,EAAE,KAAK,UAAU;IAC9D,IAAI;IACJ,SAAS,MAAM;IACf,WAAW;IACX,QAAQ;IACR,OAAO,IAAI;IACX,4BAAW,IAAI,MAAM,EAAC,aAAa;IACnC,MAAM;IACN,UAAU;IACX,EAAE,MAAM,EAAE,CAAC;UACN;AACR,SAAO;GAAE,SAAS;GAAO,OAAO,IAAI;GAAS"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { n as __esmMin } from "./chunk-DORXReHP.js";
|
|
2
2
|
import { _ as init_paths, g as getPanopticonHome } from "./paths-BDyJ7BiV.js";
|
|
3
3
|
import { c as getProject, p as init_projects } from "./projects-CFVl4oHn.js";
|
|
4
|
-
import { mt as getRecentRunLogs, yt as init_specialist_logs } from "./specialists-
|
|
5
|
-
import { a as getModelId, s as init_work_type_router } from "./work-type-router-
|
|
4
|
+
import { mt as getRecentRunLogs, yt as init_specialist_logs } from "./specialists-saEYE0-z.js";
|
|
5
|
+
import { a as getModelId, s as init_work_type_router } from "./work-type-router-7kwLSwrP.js";
|
|
6
6
|
import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "fs";
|
|
7
7
|
import { join } from "path";
|
|
8
8
|
import { exec } from "child_process";
|
|
@@ -112,7 +112,7 @@ async function generateContextDigest(projectKey, specialistType, options = {}) {
|
|
|
112
112
|
if (!existsSync(tempDir)) mkdirSync(tempDir, { recursive: true });
|
|
113
113
|
const promptFile = join(tempDir, `digest-prompt-${Date.now()}.md`);
|
|
114
114
|
writeFileSync(promptFile, prompt, "utf-8");
|
|
115
|
-
const { getProviderEnvForModel } = await import("./agents-
|
|
115
|
+
const { getProviderEnvForModel } = await import("./agents-Dinc9j_8.js");
|
|
116
116
|
const providerEnv = getProviderEnvForModel(model);
|
|
117
117
|
const envPrefix = Object.entries(providerEnv).map(([k, v]) => `${k}="${v}"`).join(" ");
|
|
118
118
|
const { stdout, stderr } = await execAsync(`${envPrefix ? envPrefix + " " : ""}claude --dangerously-skip-permissions --model ${model} "$(cat '${promptFile}')"`, {
|
|
@@ -274,4 +274,4 @@ __esmMin((() => {
|
|
|
274
274
|
}))();
|
|
275
275
|
export { deleteContextDigest, generateContextDigest, getContextDigestPath, getContextDirectory, hasContextDigest, loadContextDigest, regenerateContextDigest, scheduleDigestGeneration };
|
|
276
276
|
|
|
277
|
-
//# sourceMappingURL=specialist-context-
|
|
277
|
+
//# sourceMappingURL=specialist-context-CEKqWqyF.js.map
|
package/dist/dashboard/{specialist-context-DGukHSn8.js.map → specialist-context-CEKqWqyF.js.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"specialist-context-DGukHSn8.js","names":[],"sources":["../../src/lib/cloister/specialist-context.ts"],"sourcesContent":["/**\n * Specialist Context Management\n *\n * Generates and manages AI-powered context digests from recent specialist runs.\n * These digests seed new specialist sessions with learned patterns and expertise.\n *\n * Directory structure:\n * ~/.panopticon/specialists/{projectKey}/{specialistType}/context/latest-digest.md\n */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync, unlinkSync } from 'fs';\nimport { join } from 'path';\nimport { exec } from 'child_process';\nimport { promisify } from 'util';\nimport { getPanopticonHome } from '../paths.js';\nimport { getRecentRunLogs, type RunLogEntry } from './specialist-logs.js';\nimport { getProject } from '../projects.js';\nimport { getModelId } from '../work-type-router.js';\n\nconst execAsync = promisify(exec);\n\n/** Get specialists directory (lazy to support test env overrides) */\nfunction getSpecialistsDir(): string {\n return join(getPanopticonHome(), 'specialists');\n}\n\n/**\n * Get the context directory for a project's specialist\n */\nexport function getContextDirectory(projectKey: string, specialistType: string): string {\n return join(getSpecialistsDir(), projectKey, specialistType, 'context');\n}\n\n/**\n * Get the path to the latest context digest file\n */\nexport function getContextDigestPath(projectKey: string, specialistType: string): string {\n const contextDir = getContextDirectory(projectKey, specialistType);\n return join(contextDir, 'latest-digest.md');\n}\n\n/**\n * Ensure context directory exists for a project's specialist\n */\nfunction ensureContextDirectory(projectKey: string, specialistType: string): void {\n const contextDir = getContextDirectory(projectKey, specialistType);\n if (!existsSync(contextDir)) {\n mkdirSync(contextDir, { recursive: true });\n }\n}\n\n/**\n * Load the context digest for a specialist\n *\n * @param projectKey - Project identifier\n * @param specialistType - Specialist type\n * @returns Context digest content or null if not found\n */\nexport function loadContextDigest(projectKey: string, specialistType: string): string | null {\n const digestPath = getContextDigestPath(projectKey, specialistType);\n\n if (!existsSync(digestPath)) {\n return null;\n }\n\n try {\n return readFileSync(digestPath, 'utf-8');\n } catch (error) {\n console.error(`[specialist-context] Failed to load digest for ${projectKey}/${specialistType}:`, error);\n return null;\n }\n}\n\n/**\n * Get the number of recent runs to include in context\n *\n * Reads from project config or uses default.\n *\n * @param projectKey - Project identifier\n * @returns Number of runs to include (default: 5)\n */\nfunction getContextRunsCount(projectKey: string): number {\n const project = getProject(projectKey);\n return project?.specialists?.context_runs ?? 5;\n}\n\n/**\n * Get the model to use for digest generation\n *\n * Reads from project config or uses the same model as the specialist.\n *\n * @param projectKey - Project identifier\n * @param specialistType - Specialist type\n * @returns Model ID to use\n */\nfunction getDigestModel(projectKey: string, specialistType: string): string {\n const project = getProject(projectKey);\n\n // Check for explicit digest model in project config\n if (project?.specialists?.digest_model) {\n return project.specialists.digest_model;\n }\n\n // Fall back to specialist's model\n try {\n const workTypeId = `specialist-${specialistType}` as any;\n return getModelId(workTypeId);\n } catch (error) {\n // Default to Sonnet if can't resolve\n return 'claude-sonnet-4-6';\n }\n}\n\n/**\n * Generate a context digest from recent runs using AI\n *\n * Creates an AI-generated summary of recent specialist runs to provide\n * context for the next run. This includes patterns, learnings, and common issues.\n *\n * @param projectKey - Project identifier\n * @param specialistType - Specialist type\n * @param options - Generation options\n * @returns Generated digest or null if generation failed\n */\nexport async function generateContextDigest(\n projectKey: string,\n specialistType: string,\n options: {\n runCount?: number;\n model?: string;\n force?: boolean; // Generate even if no recent runs\n } = {}\n): Promise<string | null> {\n ensureContextDirectory(projectKey, specialistType);\n\n // Get recent runs\n const runCount = options.runCount ?? getContextRunsCount(projectKey);\n const recentRuns = getRecentRunLogs(projectKey, specialistType, runCount);\n\n if (recentRuns.length === 0 && !options.force) {\n console.log(`[specialist-context] No recent runs for ${projectKey}/${specialistType}, skipping digest generation`);\n return null;\n }\n\n // Build prompt for digest generation\n const prompt = buildDigestPrompt(projectKey, specialistType, recentRuns);\n const model = options.model ?? getDigestModel(projectKey, specialistType);\n\n try {\n console.log(`[specialist-context] Generating digest for ${projectKey}/${specialistType} using ${model}...`);\n\n // Use Claude Code CLI to generate digest\n // Write prompt to temp file to avoid shell escaping issues\n const tempDir = join(getPanopticonHome(), 'tmp');\n if (!existsSync(tempDir)) {\n mkdirSync(tempDir, { recursive: true });\n }\n\n const promptFile = join(tempDir, `digest-prompt-${Date.now()}.md`);\n writeFileSync(promptFile, prompt, 'utf-8');\n\n // Run Claude Code with the prompt (include provider env vars for non-Anthropic models)\n const { getProviderEnvForModel } = await import('../agents.js');\n const providerEnv = getProviderEnvForModel(model);\n const envPrefix = Object.entries(providerEnv).map(([k, v]) => `${k}=\"${v}\"`).join(' ');\n const { stdout, stderr } = await execAsync(\n `${envPrefix ? envPrefix + ' ' : ''}claude --dangerously-skip-permissions --model ${model} \"$(cat '${promptFile}')\"`,\n {\n encoding: 'utf-8',\n maxBuffer: 10 * 1024 * 1024, // 10MB buffer\n timeout: 60000, // 60 second timeout\n }\n );\n\n // Clean up temp file\n try {\n unlinkSync(promptFile);\n } catch {\n // Ignore cleanup errors\n }\n\n if (stderr && !stderr.includes('warning')) {\n console.error(`[specialist-context] Claude stderr:`, stderr);\n }\n\n const digest = stdout.trim();\n\n if (!digest) {\n console.error(`[specialist-context] Empty digest generated`);\n return null;\n }\n\n // Save digest\n const digestPath = getContextDigestPath(projectKey, specialistType);\n writeFileSync(digestPath, digest, 'utf-8');\n\n console.log(`[specialist-context] Generated digest (${digest.length} chars)`);\n return digest;\n } catch (error: any) {\n console.error(`[specialist-context] Failed to generate digest:`, error.message);\n // Degrade gracefully - return null so specialist can continue without context\n return null;\n }\n}\n\n/**\n * Build the prompt for digest generation\n *\n * @param projectKey - Project identifier\n * @param specialistType - Specialist type\n * @param recentRuns - Recent run logs\n * @returns Prompt for Claude\n */\nfunction buildDigestPrompt(\n projectKey: string,\n specialistType: string,\n recentRuns: RunLogEntry[]\n): string {\n const project = getProject(projectKey);\n const projectName = project?.name || projectKey;\n\n let prompt = `You are analyzing the recent history of a ${specialistType} specialist for the ${projectName} project.\n\nYour task is to generate a concise context digest that will be provided to the specialist at the start of their next run. This digest should help them understand:\n- Common patterns and practices observed in recent runs\n- Recurring issues or failure modes\n- Successful approaches and best practices\n- Any project-specific context that would be helpful\n\nGenerate a digest in markdown format. Keep it focused and actionable - aim for 200-400 words total.\n\n## Recent Runs\n\n`;\n\n if (recentRuns.length === 0) {\n prompt += `No recent runs available yet. This is the specialist's first run.\\n\\n`;\n prompt += `Generate a brief introduction for the specialist explaining their role and what to expect.\\n`;\n } else {\n recentRuns.forEach((run, index) => {\n prompt += `### Run ${index + 1}: ${run.metadata.issueId} (${run.metadata.status || 'unknown'})\\n`;\n prompt += `Started: ${run.metadata.startedAt}\\n`;\n if (run.metadata.finishedAt) {\n prompt += `Finished: ${run.metadata.finishedAt}\\n`;\n }\n if (run.metadata.duration) {\n const durationSec = Math.floor(run.metadata.duration / 1000);\n const minutes = Math.floor(durationSec / 60);\n const seconds = durationSec % 60;\n prompt += `Duration: ${minutes}m ${seconds}s\\n`;\n }\n if (run.metadata.notes) {\n prompt += `Notes: ${run.metadata.notes}\\n`;\n }\n\n // Include snippets from the log if available\n try {\n const logContent = readFileSync(run.filePath, 'utf-8');\n // Extract key sections (limit to avoid overwhelming the prompt)\n const maxChars = 500;\n const transcriptMatch = logContent.match(/## Session Transcript\\n([\\s\\S]+?)(?=\\n## |$)/);\n if (transcriptMatch) {\n let transcript = transcriptMatch[1].trim();\n if (transcript.length > maxChars) {\n transcript = transcript.substring(0, maxChars) + '... [truncated]';\n }\n prompt += `\\nTranscript excerpt:\\n${transcript}\\n`;\n }\n } catch (error) {\n // If we can't read the log, skip the excerpt\n }\n\n prompt += `\\n`;\n });\n }\n\n prompt += `\\n## Your Task\n\nGenerate a context digest that summarizes the key insights from these runs. Format it as:\n\n# Recent ${specialistType} History for ${projectName}\n\n## Summary\n[2-3 sentence overview of patterns and trends]\n\n## Common Patterns\n[Bulleted list of observed patterns]\n\n## Recent Notable Runs\n[Brief highlights of 2-3 most interesting runs]\n\n## Recommendations\n[Specific guidance for the next run based on this history]\n\nKeep it concise, actionable, and focused on helping the specialist be more effective.`;\n\n return prompt;\n}\n\n/**\n * Regenerate the context digest\n *\n * Forces regeneration even if a digest already exists.\n *\n * @param projectKey - Project identifier\n * @param specialistType - Specialist type\n * @returns Generated digest or null if generation failed\n */\nexport async function regenerateContextDigest(\n projectKey: string,\n specialistType: string\n): Promise<string | null> {\n return generateContextDigest(projectKey, specialistType, { force: true });\n}\n\n/**\n * Generate digest after a run completes (async, fire-and-forget)\n *\n * This is called after a specialist finishes a run to update the context\n * for the next run. It runs asynchronously and failures are logged but not thrown.\n *\n * @param projectKey - Project identifier\n * @param specialistType - Specialist type\n */\nexport function scheduleDigestGeneration(projectKey: string, specialistType: string): void {\n // Run async without awaiting\n generateContextDigest(projectKey, specialistType).catch((error) => {\n console.error(\n `[specialist-context] Background digest generation failed for ${projectKey}/${specialistType}:`,\n error\n );\n });\n}\n\n/**\n * Check if a context digest exists\n *\n * @param projectKey - Project identifier\n * @param specialistType - Specialist type\n * @returns True if digest file exists\n */\nexport function hasContextDigest(projectKey: string, specialistType: string): boolean {\n const digestPath = getContextDigestPath(projectKey, specialistType);\n return existsSync(digestPath);\n}\n\n/**\n * Delete the context digest\n *\n * Useful for forcing a fresh start or clearing stale context.\n *\n * @param projectKey - Project identifier\n * @param specialistType - Specialist type\n * @returns True if digest was deleted, false if it didn't exist\n */\nexport function deleteContextDigest(projectKey: string, specialistType: string): boolean {\n const digestPath = getContextDigestPath(projectKey, specialistType);\n\n if (!existsSync(digestPath)) {\n return false;\n }\n\n try {\n unlinkSync(digestPath);\n return true;\n } catch (error) {\n console.error(`[specialist-context] Failed to delete digest:`, error);\n return false;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAsBA,SAAS,oBAA4B;AACnC,QAAO,KAAK,mBAAmB,EAAE,cAAc;;;;;AAMjD,SAAgB,oBAAoB,YAAoB,gBAAgC;AACtF,QAAO,KAAK,mBAAmB,EAAE,YAAY,gBAAgB,UAAU;;;;;AAMzE,SAAgB,qBAAqB,YAAoB,gBAAgC;AAEvF,QAAO,KADY,oBAAoB,YAAY,eAAe,EAC1C,mBAAmB;;;;;AAM7C,SAAS,uBAAuB,YAAoB,gBAA8B;CAChF,MAAM,aAAa,oBAAoB,YAAY,eAAe;AAClE,KAAI,CAAC,WAAW,WAAW,CACzB,WAAU,YAAY,EAAE,WAAW,MAAM,CAAC;;;;;;;;;AAW9C,SAAgB,kBAAkB,YAAoB,gBAAuC;CAC3F,MAAM,aAAa,qBAAqB,YAAY,eAAe;AAEnE,KAAI,CAAC,WAAW,WAAW,CACzB,QAAO;AAGT,K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IAAI,SAAS,MAAM;AAIzC,MAAI;GACF,MAAM,aAAa,aAAa,IAAI,UAAU,QAAQ;GAEtD,MAAM,WAAW;GACjB,MAAM,kBAAkB,WAAW,MAAM,+CAA+C;AACxF,OAAI,iBAAiB;IACnB,IAAI,aAAa,gBAAgB,GAAG,MAAM;AAC1C,QAAI,WAAW,SAAS,SACtB,cAAa,WAAW,UAAU,GAAG,SAAS,GAAG;AAEnD,cAAU,0BAA0B,WAAW;;WAE1C,OAAO;AAIhB,YAAU;GACV;AAGJ,WAAU;;;;WAID,eAAe,eAAe,YAAY;;;;;;;;;;;;;;;AAgBnD,QAAO;;;;;;;;;;;AAYT,eAAsB,wBACpB,YACA,gBACwB;AACxB,QAAO,sBAAsB,YAAY,gBAAgB,EAAE,OAAO,MAAM,CAAC;;;;;;;;;;;AAY3E,SAAgB,yBAAyB,YAAoB,gBAA8B;AAEzF,uBAAsB,YAAY,eAAe,CAAC,OAAO,UAAU;AACjE,UAAQ,MACN,gEAAgE,WAAW,GAAG,eAAe,IAC7F,MACD;GACD;;;;;;;;;AAUJ,SAAgB,iBAAiB,YAAoB,gBAAiC;AAEpF,QAAO,WADY,qBAAqB,YAAY,eAAe,CACtC;;;;;;;;;;;AAY/B,SAAgB,oBAAoB,YAAoB,gBAAiC;CACvF,MAAM,aAAa,qBAAqB,YAAY,eAAe;AAEnE,KAAI,CAAC,WAAW,WAAW,CACzB,QAAO;AAGT,KAAI;AACF,aAAW,WAAW;AACtB,SAAO;UACA,OAAO;AACd,UAAQ,MAAM,iDAAiD,MAAM;AACrE,SAAO;;;;;;aAjWqC;uBAC0B;gBAC9B;wBACQ;AAE9C,aAAY,UAAU,KAAK"}
|
|
1
|
+
{"version":3,"file":"specialist-context-CEKqWqyF.js","names":[],"sources":["../../src/lib/cloister/specialist-context.ts"],"sourcesContent":["/**\n * Specialist Context Management\n *\n * Generates and manages AI-powered context digests from recent specialist runs.\n * These digests seed new specialist sessions with learned patterns and expertise.\n *\n * Directory structure:\n * ~/.panopticon/specialists/{projectKey}/{specialistType}/context/latest-digest.md\n */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync, unlinkSync } from 'fs';\nimport { join } from 'path';\nimport { exec } from 'child_process';\nimport { promisify } from 'util';\nimport { getPanopticonHome } from '../paths.js';\nimport { getRecentRunLogs, type RunLogEntry } from './specialist-logs.js';\nimport { getProject } from '../projects.js';\nimport { getModelId } from '../work-type-router.js';\n\nconst execAsync = promisify(exec);\n\n/** Get specialists directory (lazy to support test env overrides) */\nfunction getSpecialistsDir(): string {\n return join(getPanopticonHome(), 'specialists');\n}\n\n/**\n * Get the context directory for a project's specialist\n */\nexport function getContextDirectory(projectKey: string, specialistType: string): string {\n return join(getSpecialistsDir(), projectKey, specialistType, 'context');\n}\n\n/**\n * Get the path to the latest context digest file\n */\nexport function getContextDigestPath(projectKey: string, specialistType: string): string {\n const contextDir = getContextDirectory(projectKey, specialistType);\n return join(contextDir, 'latest-digest.md');\n}\n\n/**\n * Ensure context directory exists for a project's specialist\n */\nfunction ensureContextDirectory(projectKey: string, specialistType: string): void {\n const contextDir = getContextDirectory(projectKey, specialistType);\n if (!existsSync(contextDir)) {\n mkdirSync(contextDir, { recursive: true });\n }\n}\n\n/**\n * Load the context digest for a specialist\n *\n * @param projectKey - Project identifier\n * @param specialistType - Specialist type\n * @returns Context digest content or null if not found\n */\nexport function loadContextDigest(projectKey: string, specialistType: string): string | null {\n const digestPath = getContextDigestPath(projectKey, specialistType);\n\n if (!existsSync(digestPath)) {\n return null;\n }\n\n try {\n return readFileSync(digestPath, 'utf-8');\n } catch (error) {\n console.error(`[specialist-context] Failed to load digest for ${projectKey}/${specialistType}:`, error);\n return null;\n }\n}\n\n/**\n * Get the number of recent runs to include in context\n *\n * Reads from project config or uses default.\n *\n * @param projectKey - Project identifier\n * @returns Number of runs to include (default: 5)\n */\nfunction getContextRunsCount(projectKey: string): number {\n const project = getProject(projectKey);\n return project?.specialists?.context_runs ?? 5;\n}\n\n/**\n * Get the model to use for digest generation\n *\n * Reads from project config or uses the same model as the specialist.\n *\n * @param projectKey - Project identifier\n * @param specialistType - Specialist type\n * @returns Model ID to use\n */\nfunction getDigestModel(projectKey: string, specialistType: string): string {\n const project = getProject(projectKey);\n\n // Check for explicit digest model in project config\n if (project?.specialists?.digest_model) {\n return project.specialists.digest_model;\n }\n\n // Fall back to specialist's model\n try {\n const workTypeId = `specialist-${specialistType}` as any;\n return getModelId(workTypeId);\n } catch (error) {\n // Default to Sonnet if can't resolve\n return 'claude-sonnet-4-6';\n }\n}\n\n/**\n * Generate a context digest from recent runs using AI\n *\n * Creates an AI-generated summary of recent specialist runs to provide\n * context for the next run. This includes patterns, learnings, and common issues.\n *\n * @param projectKey - Project identifier\n * @param specialistType - Specialist type\n * @param options - Generation options\n * @returns Generated digest or null if generation failed\n */\nexport async function generateContextDigest(\n projectKey: string,\n specialistType: string,\n options: {\n runCount?: number;\n model?: string;\n force?: boolean; // Generate even if no recent runs\n } = {}\n): Promise<string | null> {\n ensureContextDirectory(projectKey, specialistType);\n\n // Get recent runs\n const runCount = options.runCount ?? getContextRunsCount(projectKey);\n const recentRuns = getRecentRunLogs(projectKey, specialistType, runCount);\n\n if (recentRuns.length === 0 && !options.force) {\n console.log(`[specialist-context] No recent runs for ${projectKey}/${specialistType}, skipping digest generation`);\n return null;\n }\n\n // Build prompt for digest generation\n const prompt = buildDigestPrompt(projectKey, specialistType, recentRuns);\n const model = options.model ?? getDigestModel(projectKey, specialistType);\n\n try {\n console.log(`[specialist-context] Generating digest for ${projectKey}/${specialistType} using ${model}...`);\n\n // Use Claude Code CLI to generate digest\n // Write prompt to temp file to avoid shell escaping issues\n const tempDir = join(getPanopticonHome(), 'tmp');\n if (!existsSync(tempDir)) {\n mkdirSync(tempDir, { recursive: true });\n }\n\n const promptFile = join(tempDir, `digest-prompt-${Date.now()}.md`);\n writeFileSync(promptFile, prompt, 'utf-8');\n\n // Run Claude Code with the prompt (include provider env vars for non-Anthropic models)\n const { getProviderEnvForModel } = await import('../agents.js');\n const providerEnv = getProviderEnvForModel(model);\n const envPrefix = Object.entries(providerEnv).map(([k, v]) => `${k}=\"${v}\"`).join(' ');\n const { stdout, stderr } = await execAsync(\n `${envPrefix ? envPrefix + ' ' : ''}claude --dangerously-skip-permissions --model ${model} \"$(cat '${promptFile}')\"`,\n {\n encoding: 'utf-8',\n maxBuffer: 10 * 1024 * 1024, // 10MB buffer\n timeout: 60000, // 60 second timeout\n }\n );\n\n // Clean up temp file\n try {\n unlinkSync(promptFile);\n } catch {\n // Ignore cleanup errors\n }\n\n if (stderr && !stderr.includes('warning')) {\n console.error(`[specialist-context] Claude stderr:`, stderr);\n }\n\n const digest = stdout.trim();\n\n if (!digest) {\n console.error(`[specialist-context] Empty digest generated`);\n return null;\n }\n\n // Save digest\n const digestPath = getContextDigestPath(projectKey, specialistType);\n writeFileSync(digestPath, digest, 'utf-8');\n\n console.log(`[specialist-context] Generated digest (${digest.length} chars)`);\n return digest;\n } catch (error: any) {\n console.error(`[specialist-context] Failed to generate digest:`, error.message);\n // Degrade gracefully - return null so specialist can continue without context\n return null;\n }\n}\n\n/**\n * Build the prompt for digest generation\n *\n * @param projectKey - Project identifier\n * @param specialistType - Specialist type\n * @param recentRuns - Recent run logs\n * @returns Prompt for Claude\n */\nfunction buildDigestPrompt(\n projectKey: string,\n specialistType: string,\n recentRuns: RunLogEntry[]\n): string {\n const project = getProject(projectKey);\n const projectName = project?.name || projectKey;\n\n let prompt = `You are analyzing the recent history of a ${specialistType} specialist for the ${projectName} project.\n\nYour task is to generate a concise context digest that will be provided to the specialist at the start of their next run. This digest should help them understand:\n- Common patterns and practices observed in recent runs\n- Recurring issues or failure modes\n- Successful approaches and best practices\n- Any project-specific context that would be helpful\n\nGenerate a digest in markdown format. Keep it focused and actionable - aim for 200-400 words total.\n\n## Recent Runs\n\n`;\n\n if (recentRuns.length === 0) {\n prompt += `No recent runs available yet. This is the specialist's first run.\\n\\n`;\n prompt += `Generate a brief introduction for the specialist explaining their role and what to expect.\\n`;\n } else {\n recentRuns.forEach((run, index) => {\n prompt += `### Run ${index + 1}: ${run.metadata.issueId} (${run.metadata.status || 'unknown'})\\n`;\n prompt += `Started: ${run.metadata.startedAt}\\n`;\n if (run.metadata.finishedAt) {\n prompt += `Finished: ${run.metadata.finishedAt}\\n`;\n }\n if (run.metadata.duration) {\n const durationSec = Math.floor(run.metadata.duration / 1000);\n const minutes = Math.floor(durationSec / 60);\n const seconds = durationSec % 60;\n prompt += `Duration: ${minutes}m ${seconds}s\\n`;\n }\n if (run.metadata.notes) {\n prompt += `Notes: ${run.metadata.notes}\\n`;\n }\n\n // Include snippets from the log if available\n try {\n const logContent = readFileSync(run.filePath, 'utf-8');\n // Extract key sections (limit to avoid overwhelming the prompt)\n const maxChars = 500;\n const transcriptMatch = logContent.match(/## Session Transcript\\n([\\s\\S]+?)(?=\\n## |$)/);\n if (transcriptMatch) {\n let transcript = transcriptMatch[1].trim();\n if (transcript.length > maxChars) {\n transcript = transcript.substring(0, maxChars) + '... [truncated]';\n }\n prompt += `\\nTranscript excerpt:\\n${transcript}\\n`;\n }\n } catch (error) {\n // If we can't read the log, skip the excerpt\n }\n\n prompt += `\\n`;\n });\n }\n\n prompt += `\\n## Your Task\n\nGenerate a context digest that summarizes the key insights from these runs. Format it as:\n\n# Recent ${specialistType} History for ${projectName}\n\n## Summary\n[2-3 sentence overview of patterns and trends]\n\n## Common Patterns\n[Bulleted list of observed patterns]\n\n## Recent Notable Runs\n[Brief highlights of 2-3 most interesting runs]\n\n## Recommendations\n[Specific guidance for the next run based on this history]\n\nKeep it concise, actionable, and focused on helping the specialist be more effective.`;\n\n return prompt;\n}\n\n/**\n * Regenerate the context digest\n *\n * Forces regeneration even if a digest already exists.\n *\n * @param projectKey - Project identifier\n * @param specialistType - Specialist type\n * @returns Generated digest or null if generation failed\n */\nexport async function regenerateContextDigest(\n projectKey: string,\n specialistType: string\n): Promise<string | null> {\n return generateContextDigest(projectKey, specialistType, { force: true });\n}\n\n/**\n * Generate digest after a run completes (async, fire-and-forget)\n *\n * This is called after a specialist finishes a run to update the context\n * for the next run. It runs asynchronously and failures are logged but not thrown.\n *\n * @param projectKey - Project identifier\n * @param specialistType - Specialist type\n */\nexport function scheduleDigestGeneration(projectKey: string, specialistType: string): void {\n // Run async without awaiting\n generateContextDigest(projectKey, specialistType).catch((error) => {\n console.error(\n `[specialist-context] Background digest generation failed for ${projectKey}/${specialistType}:`,\n error\n );\n });\n}\n\n/**\n * Check if a context digest exists\n *\n * @param projectKey - Project identifier\n * @param specialistType - Specialist type\n * @returns True if digest file exists\n */\nexport function hasContextDigest(projectKey: string, specialistType: string): boolean {\n const digestPath = getContextDigestPath(projectKey, specialistType);\n return existsSync(digestPath);\n}\n\n/**\n * Delete the context digest\n *\n * Useful for forcing a fresh start or clearing stale context.\n *\n * @param projectKey - Project identifier\n * @param specialistType - Specialist type\n * @returns True if digest was deleted, false if it didn't exist\n */\nexport function deleteContextDigest(projectKey: string, specialistType: string): boolean {\n const digestPath = getContextDigestPath(projectKey, specialistType);\n\n if (!existsSync(digestPath)) {\n return false;\n }\n\n try {\n unlinkSync(digestPath);\n return true;\n } catch (error) {\n console.error(`[specialist-context] Failed to delete digest:`, error);\n return false;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAsBA,SAAS,oBAA4B;AACnC,QAAO,KAAK,mBAAmB,EAAE,cAAc;;;;;AAMjD,SAAgB,oBAAoB,YAAoB,gBAAgC;AACtF,QAAO,KAAK,mBAAmB,EAAE,YAAY,gBAAgB,UAAU;;;;;AAMzE,SAAgB,qBAAqB,YAAoB,gBAAgC;AAEvF,QAAO,KADY,oBAAoB,YAAY,eAAe,EAC1C,mBAAmB;;;;;AAM7C,SAAS,uBAAuB,YAAoB,gBAA8B;CAChF,MAAM,aAAa,oBAAoB,YAAY,eAAe;AAClE,KAAI,CAAC,WAAW,WAAW,CACzB,WAAU,YAAY,EAAE,WAAW,MAAM,CAAC;;;;;;;;;AAW9C,SAAgB,k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, ct as checkLogSizeLimit, dt as createRunLog, ft as finalizeRunLog, gt as getRunLogPath, ht as getRunLog, lt as cleanupAllLogs, mt as getRecentRunLogs, ot as MAX_LOG_SIZE, pt as generateRunId, st as appendToRunLog, ut as cleanupOldLogs, vt as getRunsDirectory, xt as listRunLogs, yt as init_specialist_logs } from "./specialists-
|
|
1
|
+
import { St as parseLogMetadata, _t as getRunLogSize, bt as isRunLogActive, ct as checkLogSizeLimit, dt as createRunLog, ft as finalizeRunLog, gt as getRunLogPath, ht as getRunLog, lt as cleanupAllLogs, mt as getRecentRunLogs, ot as MAX_LOG_SIZE, pt as generateRunId, st as appendToRunLog, ut as cleanupOldLogs, vt as getRunsDirectory, xt as listRunLogs, yt as init_specialist_logs } from "./specialists-saEYE0-z.js";
|
|
2
2
|
init_specialist_logs();
|
|
3
3
|
export { MAX_LOG_SIZE, appendToRunLog, checkLogSizeLimit, cleanupAllLogs, cleanupOldLogs, createRunLog, finalizeRunLog, generateRunId, getRecentRunLogs, getRunLog, getRunLogPath, getRunLogSize, getRunsDirectory, isRunLogActive, listRunLogs, parseLogMetadata };
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { $ as updateContextTokens, A as initSpecialistsDirectory, B as loadRegistry, C as getSessionGeneration, D as getSpecialistStatus, E as getSpecialistState, F as isInitialized, G as sendFeedbackToAgent, H as recordWake, I as isRunning, J as signalSpecialistCompletion, K as setCurrentRun, L as listProjectsWithSpecialists, M as initializeEnabledSpecialists, N as initializeSpecialist, O as getTmuxSessionName, P as isEnabled, Q as terminateSpecialist, R as listSessionFiles, S as getSessionFilePath, T as getSpecialistMetadata, U as resumeGracePeriod, V as pauseGracePeriod, W as saveRegistry, X as startGracePeriod, Y as spawnEphemeralSpecialist, Z as submitToSpecialistQueue, _ as getGracePeriodState, a as completeSpecialistTask, at as wakeSpecialistWithTask, b as getProjectSpecialistDir, c as enableSpecialist, d as findSessionFile, et as updateProjectSpecialistMetadata, f as getAllProjectSpecialistStatuses, g as getFeedbackStats, h as getEnabledSpecialists, i as clearSessionId, it as wakeSpecialistOrQueue, j as init_specialists, k as incrementProjectRunCount, l as ensureProjectSpecialistDir, m as getAllSpecialists, n as bumpSessionGeneration, nt as updateSpecialistMetadata, o as countContextTokens, p as getAllSpecialistStatus, q as setSessionId, r as checkSpecialistQueue, rt as wakeSpecialist, s as disableSpecialist, t as buildTestAgentPromptContent, tt as updateRunStatus, u as exitGracePeriod, v as getNextSpecialistTask, w as getSessionId, x as getProjectSpecialistMetadata, y as getPendingFeedback, z as listSpecialistsForProject } from "./specialists-
|
|
1
|
+
import { $ as updateContextTokens, A as initSpecialistsDirectory, B as loadRegistry, C as getSessionGeneration, D as getSpecialistStatus, E as getSpecialistState, F as isInitialized, G as sendFeedbackToAgent, H as recordWake, I as isRunning, J as signalSpecialistCompletion, K as setCurrentRun, L as listProjectsWithSpecialists, M as initializeEnabledSpecialists, N as initializeSpecialist, O as getTmuxSessionName, P as isEnabled, Q as terminateSpecialist, R as listSessionFiles, S as getSessionFilePath, T as getSpecialistMetadata, U as resumeGracePeriod, V as pauseGracePeriod, W as saveRegistry, X as startGracePeriod, Y as spawnEphemeralSpecialist, Z as submitToSpecialistQueue, _ as getGracePeriodState, a as completeSpecialistTask, at as wakeSpecialistWithTask, b as getProjectSpecialistDir, c as enableSpecialist, d as findSessionFile, et as updateProjectSpecialistMetadata, f as getAllProjectSpecialistStatuses, g as getFeedbackStats, h as getEnabledSpecialists, i as clearSessionId, it as wakeSpecialistOrQueue, j as init_specialists, k as incrementProjectRunCount, l as ensureProjectSpecialistDir, m as getAllSpecialists, n as bumpSessionGeneration, nt as updateSpecialistMetadata, o as countContextTokens, p as getAllSpecialistStatus, q as setSessionId, r as checkSpecialistQueue, rt as wakeSpecialist, s as disableSpecialist, t as buildTestAgentPromptContent, tt as updateRunStatus, u as exitGracePeriod, v as getNextSpecialistTask, w as getSessionId, x as getProjectSpecialistMetadata, y as getPendingFeedback, z as listSpecialistsForProject } from "./specialists-saEYE0-z.js";
|
|
2
2
|
init_specialists();
|
|
3
3
|
export { buildTestAgentPromptContent, bumpSessionGeneration, checkSpecialistQueue, clearSessionId, completeSpecialistTask, countContextTokens, disableSpecialist, enableSpecialist, ensureProjectSpecialistDir, exitGracePeriod, findSessionFile, getAllProjectSpecialistStatuses, getAllSpecialistStatus, getAllSpecialists, getEnabledSpecialists, getFeedbackStats, getGracePeriodState, getNextSpecialistTask, getPendingFeedback, getProjectSpecialistDir, getProjectSpecialistMetadata, getSessionFilePath, getSessionGeneration, getSessionId, getSpecialistMetadata, getSpecialistState, getSpecialistStatus, getTmuxSessionName, incrementProjectRunCount, initSpecialistsDirectory, initializeEnabledSpecialists, initializeSpecialist, isEnabled, isInitialized, isRunning, listProjectsWithSpecialists, listSessionFiles, listSpecialistsForProject, loadRegistry, pauseGracePeriod, recordWake, resumeGracePeriod, saveRegistry, sendFeedbackToAgent, setCurrentRun, setSessionId, signalSpecialistCompletion, spawnEphemeralSpecialist, startGracePeriod, submitToSpecialistQueue, terminateSpecialist, updateContextTokens, updateProjectSpecialistMetadata, updateRunStatus, updateSpecialistMetadata, wakeSpecialist, wakeSpecialistOrQueue, wakeSpecialistWithTask };
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import { a as __toCommonJS, n as __esmMin, r as __exportAll } from "./chunk-DORXReHP.js";
|
|
2
2
|
import { _ as init_paths, g as getPanopticonHome, h as encodeClaudeProjectDir, o as COSTS_DIR, s as PANOPTICON_HOME } from "./paths-BDyJ7BiV.js";
|
|
3
|
-
import { i as loadConfig, r as init_config_yaml } from "./config-yaml-
|
|
3
|
+
import { i as loadConfig, r as init_config_yaml } from "./config-yaml-DUu0JI25.js";
|
|
4
4
|
import { _ as projects_exports, c as getProject, p as init_projects } from "./projects-CFVl4oHn.js";
|
|
5
5
|
import { n as notifyPipeline, t as init_pipeline_notifier } from "./pipeline-notifier-CCSN-jar.js";
|
|
6
6
|
import { a as init_providers, i as getProviderForModel, n as clearCredentialFileAuth, o as setupCredentialFileAuth, r as getProviderEnv } from "./providers-B5Y4H2Mg.js";
|
|
7
7
|
import { f as waitForClaudePrompt, l as sendKeysAsync, n as capturePaneAsync, o as init_tmux, r as confirmDelivery } from "./tmux-LwG0tHhU.js";
|
|
8
8
|
import { a as init_config, i as getDevrootPath } from "./config-CDkGjnwy.js";
|
|
9
9
|
import { c as popFromHook, l as pushToHook, s as init_hooks, t as checkHook } from "./hooks-CjqXOlNb.js";
|
|
10
|
-
import { a as getModelId, s as init_work_type_router } from "./work-type-router-
|
|
10
|
+
import { a as getModelId, s as init_work_type_router } from "./work-type-router-7kwLSwrP.js";
|
|
11
11
|
import { i as readWorkspacePlan, n as init_io } from "./io-DKS6359z.js";
|
|
12
12
|
import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, statSync, unlinkSync, writeFileSync } from "fs";
|
|
13
13
|
import { basename, join } from "path";
|
|
@@ -1359,9 +1359,9 @@ function recordWake(name, sessionId) {
|
|
|
1359
1359
|
*/
|
|
1360
1360
|
async function spawnEphemeralSpecialist(projectKey, specialistType, task) {
|
|
1361
1361
|
ensureProjectSpecialistDir(projectKey, specialistType);
|
|
1362
|
-
const { loadContextDigest } = await import("./specialist-context-
|
|
1362
|
+
const { loadContextDigest } = await import("./specialist-context-CEKqWqyF.js");
|
|
1363
1363
|
const contextDigest = loadContextDigest(projectKey, specialistType);
|
|
1364
|
-
const { createRunLog } = await import("./specialist-logs-
|
|
1364
|
+
const { createRunLog } = await import("./specialist-logs-CBGVRoQF.js");
|
|
1365
1365
|
const { runId, filePath: logFilePath } = createRunLog(projectKey, specialistType, task.issueId, contextDigest || void 0);
|
|
1366
1366
|
setCurrentRun(projectKey, specialistType, runId);
|
|
1367
1367
|
incrementProjectRunCount(projectKey, specialistType);
|
|
@@ -1380,7 +1380,7 @@ ${basePrompt}`;
|
|
|
1380
1380
|
try {
|
|
1381
1381
|
const { stdout: sessions } = await execAsync("tmux list-sessions -F \"#{session_name}\" 2>/dev/null || echo \"\"", { encoding: "utf-8" });
|
|
1382
1382
|
if (sessions.split("\n").map((s) => s.trim()).includes(tmuxSession)) {
|
|
1383
|
-
const { getAgentRuntimeState } = await import("./agents-
|
|
1383
|
+
const { getAgentRuntimeState } = await import("./agents-Dinc9j_8.js");
|
|
1384
1384
|
const existingState = getAgentRuntimeState(tmuxSession);
|
|
1385
1385
|
if (existingState?.state === "active") {
|
|
1386
1386
|
if (await isRunning(specialistType, projectKey)) return {
|
|
@@ -1389,7 +1389,7 @@ ${basePrompt}`;
|
|
|
1389
1389
|
error: "specialist_busy"
|
|
1390
1390
|
};
|
|
1391
1391
|
console.log(`[specialist] ${tmuxSession} state=active but not running — clearing stale state`);
|
|
1392
|
-
const { saveAgentRuntimeState } = await import("./agents-
|
|
1392
|
+
const { saveAgentRuntimeState } = await import("./agents-Dinc9j_8.js");
|
|
1393
1393
|
saveAgentRuntimeState(tmuxSession, {
|
|
1394
1394
|
state: "idle",
|
|
1395
1395
|
lastActivity: (/* @__PURE__ */ new Date()).toISOString(),
|
|
@@ -1459,7 +1459,7 @@ script -qfec "bash '${innerScript}'" /dev/null 2>&1 | tee -a "${logFilePath}"
|
|
|
1459
1459
|
`, { mode: 493 });
|
|
1460
1460
|
await execAsync(`tmux kill-session -t "${tmuxSession}" 2>/dev/null || true`, { encoding: "utf-8" });
|
|
1461
1461
|
await execAsync(`tmux new-session -d -s "${tmuxSession}" -c "${cwd}"${envFlags} "bash '${launcherScript}'"`, { encoding: "utf-8" });
|
|
1462
|
-
const { saveAgentRuntimeState } = await import("./agents-
|
|
1462
|
+
const { saveAgentRuntimeState } = await import("./agents-Dinc9j_8.js");
|
|
1463
1463
|
saveAgentRuntimeState(tmuxSession, {
|
|
1464
1464
|
state: "active",
|
|
1465
1465
|
lastActivity: (/* @__PURE__ */ new Date()).toISOString(),
|
|
@@ -1782,7 +1782,7 @@ async function terminateSpecialist(projectKey, specialistType) {
|
|
|
1782
1782
|
console.error(`[specialist] Failed to kill tmux session ${tmuxSession}:`, error);
|
|
1783
1783
|
}
|
|
1784
1784
|
if (metadata.currentRun) {
|
|
1785
|
-
const { finalizeRunLog } = await import("./specialist-logs-
|
|
1785
|
+
const { finalizeRunLog } = await import("./specialist-logs-CBGVRoQF.js");
|
|
1786
1786
|
try {
|
|
1787
1787
|
finalizeRunLog(projectKey, specialistType, metadata.currentRun, {
|
|
1788
1788
|
status: metadata.lastRunStatus || "incomplete",
|
|
@@ -1795,12 +1795,12 @@ async function terminateSpecialist(projectKey, specialistType) {
|
|
|
1795
1795
|
}
|
|
1796
1796
|
const key = `${projectKey}-${specialistType}`;
|
|
1797
1797
|
gracePeriodStates.delete(key);
|
|
1798
|
-
const { saveAgentRuntimeState } = await import("./agents-
|
|
1798
|
+
const { saveAgentRuntimeState } = await import("./agents-Dinc9j_8.js");
|
|
1799
1799
|
saveAgentRuntimeState(tmuxSession, {
|
|
1800
1800
|
state: "suspended",
|
|
1801
1801
|
lastActivity: (/* @__PURE__ */ new Date()).toISOString()
|
|
1802
1802
|
});
|
|
1803
|
-
const { scheduleDigestGeneration } = await import("./specialist-context-
|
|
1803
|
+
const { scheduleDigestGeneration } = await import("./specialist-context-CEKqWqyF.js");
|
|
1804
1804
|
scheduleDigestGeneration(projectKey, specialistType);
|
|
1805
1805
|
scheduleLogCleanup(projectKey, specialistType);
|
|
1806
1806
|
}
|
|
@@ -1813,7 +1813,7 @@ async function terminateSpecialist(projectKey, specialistType) {
|
|
|
1813
1813
|
function scheduleLogCleanup(projectKey, specialistType) {
|
|
1814
1814
|
Promise.resolve().then(async () => {
|
|
1815
1815
|
try {
|
|
1816
|
-
const { cleanupOldLogs } = await import("./specialist-logs-
|
|
1816
|
+
const { cleanupOldLogs } = await import("./specialist-logs-CBGVRoQF.js");
|
|
1817
1817
|
const { getSpecialistRetention } = await import("./projects-C5ozxjwP.js");
|
|
1818
1818
|
const retention = getSpecialistRetention(projectKey);
|
|
1819
1819
|
const deleted = cleanupOldLogs(projectKey, specialistType, {
|
|
@@ -2066,7 +2066,7 @@ async function getSpecialistStatus(name, projectKey) {
|
|
|
2066
2066
|
const sessionId = getSessionId(name, projectKey);
|
|
2067
2067
|
const running = await isRunning(name, projectKey);
|
|
2068
2068
|
const contextTokens = countContextTokens(name);
|
|
2069
|
-
const { getAgentRuntimeState } = await import("./agents-
|
|
2069
|
+
const { getAgentRuntimeState } = await import("./agents-Dinc9j_8.js");
|
|
2070
2070
|
const runtimeState = getAgentRuntimeState(getTmuxSessionName(name, projectKey));
|
|
2071
2071
|
let state;
|
|
2072
2072
|
if (runtimeState) switch (runtimeState.state) {
|
|
@@ -2243,7 +2243,7 @@ async function wakeSpecialist(name, taskPrompt, options = {}) {
|
|
|
2243
2243
|
const sessionId = getSessionId(name);
|
|
2244
2244
|
const wasAlreadyRunning = await isRunning(name);
|
|
2245
2245
|
if (wasAlreadyRunning && !options.skipBusyGuard) {
|
|
2246
|
-
const { getAgentRuntimeState } = await import("./agents-
|
|
2246
|
+
const { getAgentRuntimeState } = await import("./agents-Dinc9j_8.js");
|
|
2247
2247
|
const runtimeState = getAgentRuntimeState(tmuxSession);
|
|
2248
2248
|
if (runtimeState?.state === "active") {
|
|
2249
2249
|
console.warn(`[specialist] ${name} is busy (working on ${runtimeState.currentIssue}), refusing to interrupt`);
|
|
@@ -2338,7 +2338,7 @@ async function wakeSpecialist(name, taskPrompt, options = {}) {
|
|
|
2338
2338
|
};
|
|
2339
2339
|
}
|
|
2340
2340
|
recordWake(name, sessionId || void 0);
|
|
2341
|
-
const { saveAgentRuntimeState } = await import("./agents-
|
|
2341
|
+
const { saveAgentRuntimeState } = await import("./agents-Dinc9j_8.js");
|
|
2342
2342
|
saveAgentRuntimeState(tmuxSession, {
|
|
2343
2343
|
state: "active",
|
|
2344
2344
|
lastActivity: (/* @__PURE__ */ new Date()).toISOString(),
|
|
@@ -2447,14 +2447,14 @@ CRITICAL: Do NOT delete the feature branch.`;
|
|
|
2447
2447
|
}
|
|
2448
2448
|
if (totalChangedFiles === 0) {
|
|
2449
2449
|
console.log(`[specialist] review-agent: stale branch detected for ${task.issueId} — 0 files changed vs main`);
|
|
2450
|
-
const { setReviewStatus } = await import("./review-status-
|
|
2450
|
+
const { setReviewStatus } = await import("./review-status-Dww2OKUX.js");
|
|
2451
2451
|
setReviewStatus(task.issueId.toUpperCase(), {
|
|
2452
2452
|
reviewStatus: "passed",
|
|
2453
2453
|
reviewNotes: "No changes to review — branch identical to main (already merged or stale)"
|
|
2454
2454
|
});
|
|
2455
2455
|
console.log(`[specialist] review-agent: auto-passed ${task.issueId} (stale branch)`);
|
|
2456
2456
|
const tmuxSession = getTmuxSessionName("review-agent");
|
|
2457
|
-
const { saveAgentRuntimeState } = await import("./agents-
|
|
2457
|
+
const { saveAgentRuntimeState } = await import("./agents-Dinc9j_8.js");
|
|
2458
2458
|
saveAgentRuntimeState(tmuxSession, {
|
|
2459
2459
|
state: "idle",
|
|
2460
2460
|
lastActivity: (/* @__PURE__ */ new Date()).toISOString()
|
|
@@ -2748,7 +2748,7 @@ async function wakeSpecialistOrQueue(name, task, options = {}) {
|
|
|
2748
2748
|
console.warn(`[specialist] Task readiness check failed for ${vbriefItemId}: ${readinessErr.message}`);
|
|
2749
2749
|
}
|
|
2750
2750
|
const running = await isRunning(name);
|
|
2751
|
-
const { getAgentRuntimeState } = await import("./agents-
|
|
2751
|
+
const { getAgentRuntimeState } = await import("./agents-Dinc9j_8.js");
|
|
2752
2752
|
const tmuxSession = getTmuxSessionName(name);
|
|
2753
2753
|
const runtimeState = getAgentRuntimeState(tmuxSession);
|
|
2754
2754
|
const idle = runtimeState?.state === "idle" || runtimeState?.state === "suspended";
|
|
@@ -2777,7 +2777,7 @@ async function wakeSpecialistOrQueue(name, task, options = {}) {
|
|
|
2777
2777
|
error: msg
|
|
2778
2778
|
};
|
|
2779
2779
|
}
|
|
2780
|
-
const { saveAgentRuntimeState } = await import("./agents-
|
|
2780
|
+
const { saveAgentRuntimeState } = await import("./agents-Dinc9j_8.js");
|
|
2781
2781
|
saveAgentRuntimeState(tmuxSession, {
|
|
2782
2782
|
state: "active",
|
|
2783
2783
|
lastActivity: (/* @__PURE__ */ new Date()).toISOString(),
|
|
@@ -2920,7 +2920,7 @@ async function sendFeedbackToAgent(feedback) {
|
|
|
2920
2920
|
return false;
|
|
2921
2921
|
}
|
|
2922
2922
|
try {
|
|
2923
|
-
const { messageAgent } = await import("./agents-
|
|
2923
|
+
const { messageAgent } = await import("./agents-Dinc9j_8.js");
|
|
2924
2924
|
await messageAgent(agentSession, `SPECIALIST FEEDBACK: ${fromSpecialist} reported ${feedback.feedbackType.toUpperCase()} for ${toIssueId}.\nRead and address: ${fileResult.relativePath}`);
|
|
2925
2925
|
console.log(`[specialist] Sent feedback from ${fromSpecialist} to ${agentSession} (file: ${fileResult.relativePath})`);
|
|
2926
2926
|
return true;
|
|
@@ -3054,4 +3054,4 @@ var init_specialists = __esmMin((() => {
|
|
|
3054
3054
|
//#endregion
|
|
3055
3055
|
export { updateContextTokens as $, initSpecialistsDirectory as A, getSessionFiles as At, loadRegistry as B, getSessionGeneration as C, getUnblockedItems as Ct, getSpecialistStatus as D, readSpecialistHandoffs as Dt, getSpecialistState as E, init_specialist_handoff_logger as Et, isInitialized as F, getPricing as Ft, sendFeedbackToAgent as G, recordWake as H, isRunning as I, init_cost as It, signalSpecialistCompletion as J, setCurrentRun as K, listProjectsWithSpecialists as L, initializeEnabledSpecialists as M, normalizeModelName as Mt, initializeSpecialist as N, parseClaudeSession as Nt, getTmuxSessionName as O, getActiveSessionModel as Ot, isEnabled as P, calculateCost as Pt, terminateSpecialist as Q, listSessionFiles as R, getSessionFilePath as S, parseLogMetadata as St, getSpecialistMetadata as T, getSpecialistHandoffStats as Tt, resumeGracePeriod as U, pauseGracePeriod as V, saveRegistry as W, startGracePeriod as X, spawnEphemeralSpecialist as Y, submitToSpecialistQueue as Z, getGracePeriodState as _, getRunLogSize as _t, completeSpecialistTask as a, wakeSpecialistWithTask as at, getProjectSpecialistDir as b, isRunLogActive as bt, enableSpecialist as c, checkLogSizeLimit as ct, findSessionFile as d, createRunLog as dt, updateProjectSpecialistMetadata as et, getAllProjectSpecialistStatuses as f, finalizeRunLog as ft, getFeedbackStats as g, getRunLogPath as gt, getEnabledSpecialists as h, getRunLog as ht, clearSessionId as i, wakeSpecialistOrQueue as it, init_specialists as j, init_jsonl_parser as jt, incrementProjectRunCount as k, getProjectDirs as kt, ensureProjectSpecialistDir as l, cleanupAllLogs as lt, getAllSpecialists as m, getRecentRunLogs as mt, bumpSessionGeneration as n, updateSpecialistMetadata as nt, countContextTokens as o, MAX_LOG_SIZE as ot, getAllSpecialistStatus as p, generateRunId as pt, setSessionId as q, checkSpecialistQueue as r, wakeSpecialist as rt, disableSpecialist as s, appendToRunLog as st, buildTestAgentPromptContent as t, updateRunStatus as tt, exitGracePeriod as u, cleanupOldLogs as ut, getNextSpecialistTask as v, getRunsDirectory as vt, getSessionId as w, init_task_readiness as wt, getProjectSpecialistMetadata as x, listRunLogs as xt, getPendingFeedback as y, init_specialist_logs as yt, listSpecialistsForProject as z };
|
|
3056
3056
|
|
|
3057
|
-
//# sourceMappingURL=specialists-
|
|
3057
|
+
//# sourceMappingURL=specialists-saEYE0-z.js.map
|