opencode-athena 0.11.0 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/index.js +17 -2
- package/dist/cli/index.js.map +1 -1
- package/dist/index.d.ts +31 -12
- package/dist/index.js +125 -34
- package/dist/index.js.map +1 -1
- package/dist/plugin/index.js +102 -22
- package/dist/plugin/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/plugin/utils/plugin-logger.ts","../src/plugin/utils/notifications.ts","../src/plugin/hooks/session-hooks.ts","../src/plugin/utils/bmad-finder.ts","../src/shared/types.ts","../src/plugin/utils/story-loader.ts","../src/plugin/utils/todo-sync.ts","../src/plugin/hooks/todo-hooks.ts","../src/plugin/hooks/tool-hooks.ts","../src/plugin/hooks/compaction-hook.ts","../src/plugin/utils/story-complexity.ts","../src/plugin/utils/story-parser.ts","../src/plugin/utils/story-decomposer.ts","../src/plugin/tools/analyze-story.ts","../src/shared/constants.ts","../src/plugin/tools/config.ts","../src/plugin/utils/yaml-handler.ts","../src/plugin/tools/decompose-story.ts","../src/plugin/tools/get-context.ts","../src/plugin/utils/context-builder.ts","../src/plugin/utils/story-file-updater.ts","../src/plugin/tools/get-story.ts","../src/plugin/tools/parallel.ts","../src/plugin/utils/oracle-parser.ts","../src/plugin/utils/persona-loader.ts","../src/plugin/utils/story-template.ts","../src/plugin/utils/story-updater.ts","../src/plugin/tools/party-discussion.ts","../src/plugin/tools/review-story.ts","../src/plugin/utils/agent-selector.ts","../src/plugin/tools/story-review-analyze.ts","../src/plugin/utils/response-synthesizer.ts","../src/plugin/tools/story-review-consult.ts","../src/plugin/tools/update-status.ts","../src/plugin/tools/index.ts","../src/plugin/tracker/story-tracker.ts","../src/shared/schemas.ts","../src/plugin/utils/config-loader.ts","../src/plugin/index.ts"],"names":["log","join","existsSync","parseYaml","path","readdir","readFile","result","fs","dirname","tool","lockData","writeFile","resolve","stringifyYaml","normalizeStoryId","updatedContent","progress","basename","nextId","getCategoryPrefix","mkdir","reviewFolder","analyzeStoryComplexity","detectReviewScope","parseModelConfig"],"mappings":";;;;;;;;;;;;;;AAaA,IAAM,QAAA,GAAW,IAAA,CAAK,MAAA,EAAO,EAAG,qBAAqB,CAAA;AACrD,IAAM,YAAA,GAAe,IAAI,IAAA,GAAO,IAAA;AAIhC,IAAM,cAAA,GAA2C;AAAA,EAC/C,KAAA,EAAO,SAAA;AAAA,EACP,IAAA,EAAM,QAAA;AAAA,EACN,IAAA,EAAM,QAAA;AAAA,EACN,KAAA,EAAO;AACT,CAAA;AAEA,SAAS,UAAU,KAAA,EAA0B;AAC3C,EAAA,IAAI,KAAA,KAAU,MAAA,IAAU,KAAA,KAAU,OAAA,EAAS,OAAO,IAAA;AAClD,EAAA,OAAO,QAAQ,GAAA,CAAI,YAAA,KAAiB,GAAA,IAAO,OAAA,CAAQ,IAAI,YAAA,KAAiB,MAAA;AAC1E;AAEA,SAAS,gBAAA,GAA4B;AACnC,EAAA,OAAO,QAAQ,GAAA,CAAI,YAAA,KAAiB,GAAA,IAAO,OAAA,CAAQ,IAAI,YAAA,KAAiB,MAAA;AAC1E;AAEA,SAAS,cAAA,CACP,KAAA,EACA,SAAA,EACA,OAAA,EACA,IAAA,EACQ;AACR,EAAA,MAAM,SAAA,GAAA,iBAAY,IAAI,IAAA,EAAK,EAAE,WAAA,EAAY;AACzC,EAAA,MAAM,MAAA,GAAS,eAAe,KAAK,CAAA;AACnC,EAAA,MAAM,UAAU,IAAA,GAAO,CAAA,CAAA,EAAI,KAAK,SAAA,CAAU,IAAI,CAAC,CAAA,CAAA,GAAK,EAAA;AACpD,EAAA,OAAO,CAAA,CAAA,EAAI,SAAS,CAAA,EAAA,EAAK,MAAM,KAAK,SAAS,CAAA,EAAA,EAAK,OAAO,CAAA,EAAG,OAAO;AAAA,CAAA;AACrE;AAEA,SAAS,iBAAA,GAA0B;AACj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C,CAAA;AAGD,EAAA,MAAM,MAAA,GAAS,MAAM,gBAAA,CAAiB,SAAS,CAAA;AAG/C,EAAA,MAAM,OAAA,GAAU,IAAI,YAAA,CAAa,SAAS,CAAA;AAC1C,EAAA,MAAM,QAAQ,UAAA,EAAW;AAGzB,EAAA,MAAM,KAAA,GAAQ,WAAA,CAAY,GAAA,EAAK,OAAA,EAAS,MAAM,CAAA;AAG9C,EAAA,MAAM,YAAA,GAAe,kBAAA,CAAmB,GAAA,EAAK,OAAA,EAAS,MAAM,CAAA;AAC5D,EAAA,MAAM,SAAA,GAAY,eAAA,CAAgB,GAAA,EAAK,OAAA,EAAS,MAAM,CAAA;AACtD,EAAA,MAAM,cAAA,GAAiB,oBAAA,CAAqB,OAAA,EAAS,MAAM,CAAA;AAE3D,EAAA,OAAO;AAAA;AAAA,IAEL,IAAA,EAAM,KAAA;AAAA;AAAA,IAGN,KAAA,EAAO,YAAA;AAAA;AAAA,IAGP,uBAAuB,SAAA,CAAU,MAAA;AAAA,IACjC,sBAAsB,SAAA,CAAU,KAAA;AAAA;AAAA,IAGhC,iCAAA,EAAmC;AAAA,GACrC;AACF","file":"index.js","sourcesContent":["/**\n * Plugin Logger - File-based logging for OpenCode Athena plugin runtime\n *\n * Follows oh-my-opencode logging pattern:\n * - Logs to temp file: ${TMPDIR}/opencode-athena.log\n * - Optional console output: ATHENA_DEBUG=1\n * - Silent failures to prevent breaking plugin execution\n */\n\nimport { appendFileSync, existsSync, statSync, truncateSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\n\nconst LOG_FILE = join(tmpdir(), \"opencode-athena.log\");\nconst MAX_LOG_SIZE = 5 * 1024 * 1024;\n\ntype LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\nconst LEVEL_PREFIXES: Record<LogLevel, string> = {\n debug: \"[DEBUG]\",\n info: \"[INFO]\",\n warn: \"[WARN]\",\n error: \"[ERROR]\",\n};\n\nfunction shouldLog(level: LogLevel): boolean {\n if (level === \"warn\" || level === \"error\") return true;\n return process.env.ATHENA_DEBUG === \"1\" || process.env.ATHENA_DEBUG === \"true\";\n}\n\nfunction shouldConsoleLog(): boolean {\n return process.env.ATHENA_DEBUG === \"1\" || process.env.ATHENA_DEBUG === \"true\";\n}\n\nfunction formatLogEntry(\n level: LogLevel,\n component: string,\n message: string,\n data?: Record<string, unknown>\n): string {\n const timestamp = new Date().toISOString();\n const prefix = LEVEL_PREFIXES[level];\n const dataStr = data ? ` ${JSON.stringify(data)}` : \"\";\n return `[${timestamp}] ${prefix} [${component}] ${message}${dataStr}\\n`;\n}\n\nfunction rotateLogIfNeeded(): void {\n try {\n if (existsSync(LOG_FILE)) {\n const stats = statSync(LOG_FILE);\n if (stats.size > MAX_LOG_SIZE) {\n truncateSync(LOG_FILE, 0);\n }\n }\n } catch {\n // Silent - logging infrastructure should never break plugin\n }\n}\n\nfunction writeLog(entry: string): void {\n try {\n rotateLogIfNeeded();\n appendFileSync(LOG_FILE, entry);\n } catch {\n // Silent - logging infrastructure should never break plugin\n }\n}\n\n/**\n * Create a scoped logger for a specific component.\n * Public API - docstring required for discoverability.\n *\n * @example\n * const log = createPluginLogger(\"party-discussion\");\n * log.debug(\"Starting session\", { sessionId: \"abc123\" });\n */\nexport function createPluginLogger(component: string) {\n return {\n debug: (message: string, data?: Record<string, unknown>): void => {\n if (!shouldLog(\"debug\")) return;\n const entry = formatLogEntry(\"debug\", component, message, data);\n writeLog(entry);\n if (shouldConsoleLog()) {\n console.debug(`[Athena:${component}] ${message}`, data ?? \"\");\n }\n },\n\n info: (message: string, data?: Record<string, unknown>): void => {\n if (!shouldLog(\"info\")) return;\n const entry = formatLogEntry(\"info\", component, message, data);\n writeLog(entry);\n if (shouldConsoleLog()) {\n console.info(`[Athena:${component}] ${message}`, data ?? \"\");\n }\n },\n\n warn: (message: string, data?: Record<string, unknown>): void => {\n const entry = formatLogEntry(\"warn\", component, message, data);\n writeLog(entry);\n if (shouldConsoleLog()) {\n console.warn(`[Athena:${component}] ${message}`, data ?? \"\");\n }\n },\n\n error: (message: string, data?: Record<string, unknown>): void => {\n const entry = formatLogEntry(\"error\", component, message, data);\n writeLog(entry);\n if (shouldConsoleLog()) {\n console.error(`[Athena:${component}] ${message}`, data ?? \"\");\n }\n },\n };\n}\n\n/** Returns log file path: ${TMPDIR}/opencode-athena.log */\nexport function getLogFilePath(): string {\n return LOG_FILE;\n}\n\n/** Truncates the log file to zero bytes */\nexport function clearLog(): void {\n try {\n if (existsSync(LOG_FILE)) {\n truncateSync(LOG_FILE, 0);\n }\n } catch {\n // Silent - logging infrastructure should never break plugin\n }\n}\n","/**\n * Cross-platform notification utility\n *\n * Sends desktop notifications on macOS/Linux, falls back to console on Windows.\n */\n\nimport { platform } from \"node:os\";\nimport type { PluginInput } from \"@opencode-ai/plugin\";\nimport { createPluginLogger } from \"./plugin-logger.js\";\n\ntype ShellExecutor = PluginInput[\"$\"];\n\nconst log = createPluginLogger(\"notifications\");\n\n/**\n * Send a desktop notification\n *\n * Platform support:\n * - macOS: Uses osascript (built-in)\n * - Linux: Uses notify-send (requires libnotify)\n * - Windows: Falls back to console.log\n *\n * @param message - The notification message\n * @param title - The notification title\n * @param $ - Shell executor from plugin context\n */\nexport async function sendNotification(\n message: string,\n title: string,\n $: ShellExecutor\n): Promise<void> {\n const os = platform();\n\n try {\n if (os === \"darwin\") {\n // macOS - use osascript (built-in)\n await $`osascript -e ${`display notification \"${escapeAppleScript(message)}\" with title \"${escapeAppleScript(title)}\"`}`;\n } else if (os === \"linux\") {\n // Linux - use notify-send (requires libnotify)\n await $`notify-send ${title} ${message}`;\n } else {\n // Windows and others - fall back to console\n logNotification(title, message);\n }\n } catch {\n // Silently fall back to console if notification fails\n logNotification(title, message);\n }\n}\n\n/**\n * Escape special characters for AppleScript strings\n */\nfunction escapeAppleScript(str: string): string {\n return str.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"');\n}\n\n/**\n * Log notification to log file as fallback\n */\nfunction logNotification(title: string, message: string): void {\n log.info(\"Desktop notification fallback\", { title, message });\n}\n","/**\n * Session event hooks\n *\n * Handles session lifecycle events like idle, created, and error.\n */\n\nimport type { PluginInput } from \"@opencode-ai/plugin\";\nimport type { AthenaConfig } from \"../../shared/types.js\";\nimport type { StoryTracker } from \"../tracker/story-tracker.js\";\nimport { sendNotification } from \"../utils/notifications.js\";\nimport { createPluginLogger } from \"../utils/plugin-logger.js\";\n\nconst log = createPluginLogger(\"session-hooks\");\n\n/**\n * Generic event type for session events\n */\ninterface SessionEvent {\n type?: string;\n error?: unknown;\n}\n\n/**\n * Create session event handler\n *\n * Handles:\n * - session.idle: Reminds about in-progress story when session goes idle\n * - session.created: Logs resume of tracked story\n * - session.error: Logs errors during story implementation\n */\nexport function createSessionHooks(ctx: PluginInput, tracker: StoryTracker, config: AthenaConfig) {\n return async ({ event }: { event: SessionEvent }) => {\n // Event type is in event.type for most events\n const eventType = (event as { type?: string }).type;\n\n switch (eventType) {\n case \"session.idle\":\n await handleSessionIdle(ctx, tracker, config);\n break;\n\n case \"session.created\":\n handleSessionCreated(tracker);\n break;\n\n case \"session.error\":\n handleSessionError(event, tracker);\n break;\n }\n };\n}\n\n/**\n * Handle session going idle\n *\n * If a story is in progress, send a reminder notification\n */\nasync function handleSessionIdle(\n ctx: PluginInput,\n tracker: StoryTracker,\n config: AthenaConfig\n): Promise<void> {\n const currentStory = tracker.getCurrentStory();\n\n if (currentStory && currentStory.status === \"in-progress\") {\n // Story is in progress but session went idle\n if (config.features?.notifications) {\n await sendNotification(\n `Story ${currentStory.id} in progress. Remember to update status when complete!`,\n \"OpenCode Athena\",\n ctx.$\n );\n }\n }\n}\n\n/**\n * Handle session creation\n *\n * Log if resuming with an active story\n */\nfunction handleSessionCreated(tracker: StoryTracker): void {\n const currentStory = tracker.getCurrentStory();\n\n if (currentStory) {\n log.info(\"Session created - resuming with story\", {\n storyId: currentStory.id,\n status: currentStory.status,\n });\n }\n}\n\n/**\n * Handle session errors\n *\n * Log errors that occur during story implementation\n */\nfunction handleSessionError(event: SessionEvent, tracker: StoryTracker): void {\n const currentStory = tracker.getCurrentStory();\n\n if (currentStory && event.error) {\n log.error(\"Session error during story implementation\", {\n storyId: currentStory.id,\n error: event.error,\n });\n }\n}\n","import { existsSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport { fdir } from \"fdir\";\nimport { parse as parseYaml } from \"yaml\";\nimport { createPluginLogger } from \"./plugin-logger.js\";\n\nconst log = createPluginLogger(\"bmad-finder\");\n\nconst BMAD_DIR_NAMES = [\"docs\", \".bmad\", \"bmad\"] as const;\n\nconst KNOWN_MANIFEST_PATHS = [\n \".bmad/_cfg/agent-manifest.csv\",\n \".bmad/config/agent-manifest.csv\",\n \"bmad/_cfg/agent-manifest.csv\",\n \"_bmad/_config/agent-manifest.csv\",\n] as const;\n\nconst KNOWN_AGENT_DIRS = [\n \"_bmad/bmm/agents\",\n \"src/modules/bmm/agents\",\n \".bmad/bmm/agents\",\n \"bmad/bmm/agents\",\n] as const;\n\nconst MANIFEST_SEARCH_EXCLUDE_DIRS = new Set([\n \"node_modules\",\n \".git\",\n \"dist\",\n \"build\",\n \".next\",\n \"coverage\",\n \".cache\",\n \".turbo\",\n]);\n\nconst manifestCache = new Map<string, string | null>();\nconst agentFilesCache = new Map<string, string[]>();\n\nconst BMAD_V6_DEFAULTS = {\n planningArtifacts: \"docs/project-planning-artifacts\",\n implementationArtifacts: \"docs/implementation-artifacts\",\n projectKnowledge: \"docs\",\n} as const;\n\nconst LEGACY_PATHS = {\n docsDir: \"docs\",\n storiesDir: \"docs/stories\",\n sprintArtifacts: \"docs/sprint-artifacts\",\n} as const;\n\ninterface BmadConfig {\n planning_artifacts?: string;\n implementation_artifacts?: string;\n sprint_artifacts?: string;\n project_knowledge?: string;\n output_folder?: string;\n}\n\ninterface BmadPaths {\n projectRoot: string;\n bmadDir: string | null;\n planningDir: string;\n implementationDir: string;\n storiesDir: string;\n sprintStatus: string;\n architecture: string;\n prd: string;\n epics: string;\n}\n\nexport async function findBmadDir(startDir: string): Promise<string | null> {\n let currentDir = startDir;\n const visited = new Set<string>();\n\n while (currentDir && !visited.has(currentDir)) {\n visited.add(currentDir);\n\n for (const dirName of BMAD_DIR_NAMES) {\n const bmadPath = join(currentDir, dirName);\n if (existsSync(bmadPath)) {\n return bmadPath;\n }\n }\n\n const parentDir = dirname(currentDir);\n if (parentDir === currentDir) {\n break;\n }\n\n currentDir = parentDir;\n }\n\n return null;\n}\n\nasync function readBmadConfig(bmadDir: string): Promise<BmadConfig | null> {\n const configPath = join(bmadDir, \"bmm\", \"config.yaml\");\n if (!existsSync(configPath)) {\n return null;\n }\n\n try {\n const content = await readFile(configPath, \"utf-8\");\n return parseYaml(content) as BmadConfig;\n } catch {\n return null;\n }\n}\n\n/**\n * Expand BMAD METHOD v6 placeholders in config paths.\n *\n * Strips {project-root}/ prefix to create relative paths that can be\n * joined with projectRoot. This handles the standard BMAD v6 placeholder\n * that is preserved during installation for runtime resolution.\n *\n * @param path - Path that may contain {project-root} placeholder\n * @returns Relative path with placeholder stripped, or undefined if input is undefined\n *\n * @example\n * expandBmadPlaceholder(\"{project-root}/docs/sprint-artifacts\") // → \"docs/sprint-artifacts\"\n * expandBmadPlaceholder(\"docs/sprint-artifacts\") // → \"docs/sprint-artifacts\"\n * expandBmadPlaceholder(undefined) // → undefined\n */\nfunction expandBmadPlaceholder(path: string | undefined): string | undefined {\n if (!path) return undefined;\n return path.replace(/^\\{project-root\\}\\/?/, \"\");\n}\n\n/**\n * Check if a directory contains story files.\n * Looks for files matching story naming patterns: 1-1.md, 2-3.md, story-2-3.md, etc.\n */\nasync function hasStoryFiles(dir: string): Promise<boolean> {\n if (!existsSync(dir)) return false;\n\n try {\n const { readdir } = await import(\"node:fs/promises\");\n const files = await readdir(dir);\n // Match story naming: 1-1.md, 2-3.md, story-2-3.md, etc.\n return files.some((f) => f.endsWith(\".md\") && /^(\\d+-\\d+|story-\\d+-\\d+)/.test(f));\n } catch {\n return false;\n }\n}\n\n/**\n * Detect stories directory by checking nested vs flat structure.\n * Tries nested path first (BMAD v6 standard), then flat structure, then legacy paths.\n */\nasync function detectStoriesDir(baseDir: string, projectRoot: string): Promise<string> {\n const nestedPath = join(baseDir, \"stories\");\n if (await hasStoryFiles(nestedPath)) {\n return nestedPath;\n }\n\n if (await hasStoryFiles(baseDir)) {\n return baseDir;\n }\n\n const legacySprintArtifacts = join(projectRoot, LEGACY_PATHS.sprintArtifacts);\n if (await hasStoryFiles(legacySprintArtifacts)) {\n return legacySprintArtifacts;\n }\n\n const legacyStoriesDir = join(projectRoot, LEGACY_PATHS.storiesDir);\n if (await hasStoryFiles(legacyStoriesDir)) {\n return legacyStoriesDir;\n }\n\n return nestedPath;\n}\n\n/**\n * Generate case variants for a filename.\n * For example, \"PRD.md\" → [\"PRD.md\", \"prd.md\", \"Prd.md\"]\n */\nfunction getCaseVariants(filename: string): string[] {\n const variants = new Set<string>();\n const [name, ext] = filename.split(\".\");\n\n variants.add(filename);\n variants.add(filename.toLowerCase());\n variants.add(filename.toUpperCase());\n\n if (name) {\n const firstCap = name.charAt(0).toUpperCase() + name.slice(1).toLowerCase();\n variants.add(ext ? `${firstCap}.${ext}` : firstCap);\n }\n\n return Array.from(variants);\n}\n\n/**\n * Search for a file with case-insensitive matching.\n * Tries exact match first, then case variants.\n */\nfunction searchForFileWithVariants(\n projectRoot: string,\n filename: string,\n searchPaths: string[]\n): string {\n const variants = getCaseVariants(filename);\n\n for (const searchPath of searchPaths) {\n for (const variant of variants) {\n const fullPath = join(projectRoot, searchPath, variant);\n if (existsSync(fullPath)) {\n return fullPath;\n }\n }\n }\n\n return join(projectRoot, searchPaths[0], filename);\n}\n\nexport async function getBmadPaths(\n startDir: string,\n athenaConfig?: {\n bmad?: {\n paths?: {\n stories?: string | null;\n sprintStatus?: string | null;\n prd?: string | null;\n architecture?: string | null;\n epics?: string | null;\n };\n };\n }\n): Promise<BmadPaths> {\n const bmadDir = await findBmadDir(startDir);\n const projectRoot = bmadDir ? dirname(bmadDir) : startDir;\n\n let config: BmadConfig | null = null;\n if (bmadDir) {\n config = await readBmadConfig(bmadDir);\n }\n\n const planningDir = join(\n projectRoot,\n expandBmadPlaceholder(config?.planning_artifacts) ?? BMAD_V6_DEFAULTS.planningArtifacts\n );\n\n const implementationDir = join(\n projectRoot,\n expandBmadPlaceholder(config?.implementation_artifacts) ??\n expandBmadPlaceholder(config?.sprint_artifacts) ??\n BMAD_V6_DEFAULTS.implementationArtifacts\n );\n\n const storiesDir = athenaConfig?.bmad?.paths?.stories\n ? join(projectRoot, athenaConfig.bmad.paths.stories)\n : await detectStoriesDir(implementationDir, projectRoot);\n\n const sprintStatusSearchPaths = [\n expandBmadPlaceholder(config?.implementation_artifacts) ||\n BMAD_V6_DEFAULTS.implementationArtifacts,\n expandBmadPlaceholder(config?.sprint_artifacts) || \"docs/sprint-artifacts\",\n LEGACY_PATHS.sprintArtifacts,\n LEGACY_PATHS.docsDir,\n ];\n const sprintStatus = athenaConfig?.bmad?.paths?.sprintStatus\n ? join(projectRoot, athenaConfig.bmad.paths.sprintStatus)\n : searchForFileWithVariants(projectRoot, \"sprint-status.yaml\", sprintStatusSearchPaths);\n\n const architectureSearchPaths = [\n expandBmadPlaceholder(config?.planning_artifacts) || BMAD_V6_DEFAULTS.planningArtifacts,\n LEGACY_PATHS.docsDir,\n ];\n const architecture = athenaConfig?.bmad?.paths?.architecture\n ? join(projectRoot, athenaConfig.bmad.paths.architecture)\n : searchForFileWithVariants(projectRoot, \"architecture.md\", architectureSearchPaths);\n\n const prdSearchPaths = [\n expandBmadPlaceholder(config?.planning_artifacts) || BMAD_V6_DEFAULTS.planningArtifacts,\n LEGACY_PATHS.docsDir,\n ];\n const prd = athenaConfig?.bmad?.paths?.prd\n ? join(projectRoot, athenaConfig.bmad.paths.prd)\n : searchForFileWithVariants(projectRoot, \"PRD.md\", prdSearchPaths);\n\n const epicsSearchPaths = [\n expandBmadPlaceholder(config?.planning_artifacts) || BMAD_V6_DEFAULTS.planningArtifacts,\n LEGACY_PATHS.docsDir,\n ];\n const epics = athenaConfig?.bmad?.paths?.epics\n ? join(projectRoot, athenaConfig.bmad.paths.epics)\n : searchForFileWithVariants(projectRoot, \"epics.md\", epicsSearchPaths);\n\n return {\n projectRoot,\n bmadDir,\n planningDir,\n implementationDir,\n storiesDir,\n sprintStatus,\n architecture,\n prd,\n epics,\n };\n}\n\nexport async function findManifest(projectRoot: string): Promise<string | null> {\n const cached = manifestCache.get(projectRoot);\n if (cached !== undefined) {\n return cached;\n }\n\n for (const knownPath of KNOWN_MANIFEST_PATHS) {\n const fullPath = join(projectRoot, knownPath);\n if (existsSync(fullPath)) {\n manifestCache.set(projectRoot, fullPath);\n return fullPath;\n }\n }\n\n const bmadDir = await findBmadDir(projectRoot);\n if (bmadDir) {\n try {\n const files = await new fdir()\n .withMaxDepth(3)\n .withBasePath()\n .exclude((dirName) => MANIFEST_SEARCH_EXCLUDE_DIRS.has(dirName))\n .filter((path) => path.endsWith(\"agent-manifest.csv\"))\n .crawl(bmadDir)\n .withPromise();\n\n if (files.length > 0) {\n manifestCache.set(projectRoot, files[0]);\n return files[0];\n }\n } catch (error) {\n log.warn(\"Failed to search for manifest in BMAD directory\", {\n bmadDir,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n try {\n const projectFiles = await new fdir()\n .withMaxDepth(5)\n .withBasePath()\n .exclude((dirName) => MANIFEST_SEARCH_EXCLUDE_DIRS.has(dirName))\n .filter((path) => path.endsWith(\"agent-manifest.csv\"))\n .crawl(projectRoot)\n .withPromise();\n\n const result = projectFiles.length > 0 ? projectFiles[0] : null;\n manifestCache.set(projectRoot, result);\n return result;\n } catch (error) {\n log.warn(\"Failed to search for manifest in project root\", {\n projectRoot,\n error: error instanceof Error ? error.message : String(error),\n });\n manifestCache.set(projectRoot, null);\n return null;\n }\n}\n\nexport function clearManifestCache(): void {\n manifestCache.clear();\n}\n\nexport async function findAgentFiles(projectRoot: string): Promise<string[]> {\n const cached = agentFilesCache.get(projectRoot);\n if (cached !== undefined) {\n return cached;\n }\n\n for (const knownDir of KNOWN_AGENT_DIRS) {\n const fullPath = join(projectRoot, knownDir);\n if (existsSync(fullPath)) {\n try {\n const files = await new fdir()\n .withBasePath()\n .filter((path) => path.endsWith(\".agent.yaml\"))\n .crawl(fullPath)\n .withPromise();\n\n if (files.length > 0) {\n agentFilesCache.set(projectRoot, files);\n return files;\n }\n } catch (error) {\n log.warn(\"Failed to search for agent files in known directory\", {\n directory: fullPath,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n }\n\n const bmadDir = await findBmadDir(projectRoot);\n if (bmadDir) {\n try {\n const files = await new fdir()\n .withMaxDepth(5)\n .withBasePath()\n .exclude((dirName) => MANIFEST_SEARCH_EXCLUDE_DIRS.has(dirName))\n .filter((path) => path.endsWith(\".agent.yaml\"))\n .crawl(bmadDir)\n .withPromise();\n\n if (files.length > 0) {\n agentFilesCache.set(projectRoot, files);\n return files;\n }\n } catch (error) {\n log.warn(\"Failed to search for agent files in BMAD directory\", {\n bmadDir,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n try {\n const projectFiles = await new fdir()\n .withMaxDepth(6)\n .withBasePath()\n .exclude((dirName) => MANIFEST_SEARCH_EXCLUDE_DIRS.has(dirName))\n .filter((path) => path.endsWith(\".agent.yaml\") && path.includes(\"/agents/\"))\n .crawl(projectRoot)\n .withPromise();\n\n agentFilesCache.set(projectRoot, projectFiles);\n return projectFiles;\n } catch (error) {\n log.warn(\"Failed to search for agent files in project root\", {\n projectRoot,\n error: error instanceof Error ? error.message : String(error),\n });\n agentFilesCache.set(projectRoot, []);\n return [];\n }\n}\n\nexport function clearAgentFilesCache(): void {\n agentFilesCache.clear();\n}\n","/**\n * Shared TypeScript type definitions for OpenCode Athena\n */\n\n// ============================================================================\n// CLI Types\n// ============================================================================\n\n/**\n * Options passed to the install command\n */\nexport interface InstallOptions {\n preset: string;\n yes: boolean;\n advanced: boolean;\n global: boolean;\n local: boolean;\n reconfigure?: boolean;\n}\n\n/**\n * Options passed to the upgrade command\n */\nexport interface UpgradeOptions {\n check: boolean;\n yes: boolean;\n}\n\n/**\n * Options passed to the doctor command\n */\nexport interface DoctorOptions {\n fix: boolean;\n}\n\n/**\n * Options passed to the uninstall command\n */\nexport interface UninstallOptions {\n keepConfig: boolean;\n keepDeps: boolean;\n}\n\n/**\n * Subscription information gathered during install\n */\nexport interface SubscriptionAnswers {\n hasClaude: boolean;\n claudeTier: \"max5x\" | \"max20x\" | \"pro\" | \"none\";\n hasOpenAI: boolean;\n hasGoogle: boolean;\n googleAuth: \"antigravity\" | \"personal\" | \"api\" | \"none\";\n hasGitHubCopilot: boolean;\n copilotPlan: \"free\" | \"pro\" | \"pro-plus\" | \"business\" | \"enterprise\" | \"none\";\n copilotEnabledModels?: string[];\n}\n\n/**\n * Methodology preferences gathered during install\n */\nexport interface MethodologyAnswers {\n defaultTrack: \"quick-flow\" | \"bmad-method\" | \"enterprise\";\n autoStatusUpdate: boolean;\n}\n\n/**\n * Feature selections gathered during install\n */\nexport interface FeatureAnswers {\n enabledFeatures: string[];\n mcps: string[];\n}\n\n/**\n * Advanced options gathered during install\n */\nexport interface AdvancedAnswers {\n parallelStoryLimit?: number;\n experimental?: string[];\n autoFallback?: boolean;\n}\n\n/**\n * Available model choices by provider\n */\nexport type LLMProvider = \"anthropic\" | \"openai\" | \"google\" | \"github-copilot\";\n\n/**\n * Model definition\n */\nexport interface ModelChoice {\n id: string;\n name: string;\n provider: LLMProvider;\n description?: string;\n}\n\n/**\n * Custom model definition for user-added models\n */\nexport interface CustomModelDefinition {\n id: string;\n name: string;\n provider: LLMProvider;\n description?: string;\n capabilities?: {\n thinking?: boolean;\n contextWindow?: number;\n supportsTemperature?: boolean;\n };\n}\n\n/**\n * Agent roles that require model assignment\n */\nexport type AgentRole =\n | \"sisyphus\"\n | \"oracle\"\n | \"librarian\"\n | \"frontend\"\n | \"documentWriter\"\n | \"multimodalLooker\"\n | \"explore\";\n\n/**\n * Thinking level for reasoning-capable models\n */\nexport type ThinkingLevel = \"off\" | \"low\" | \"medium\" | \"high\";\n\n/**\n * Agent-specific settings for temperature and thinking level\n */\nexport interface AgentSettings {\n temperature?: number; // 0.0 - 1.0\n thinkingLevel?: ThinkingLevel;\n}\n\n/**\n * Model assignments for each agent role\n */\nexport interface ModelAnswers {\n sisyphus: string;\n oracle: string;\n librarian: string;\n frontend?: string;\n documentWriter?: string;\n multimodalLooker?: string;\n explore?: string;\n settings?: {\n sisyphus?: AgentSettings;\n oracle?: AgentSettings;\n librarian?: AgentSettings;\n frontend?: AgentSettings;\n documentWriter?: AgentSettings;\n multimodalLooker?: AgentSettings;\n explore?: AgentSettings;\n overrides?: Record<string, AgentSettings>;\n };\n custom?: CustomModelDefinition[];\n}\n\n/**\n * All answers from the install wizard\n */\nexport interface InstallAnswers {\n subscriptions: SubscriptionAnswers;\n models: ModelAnswers;\n methodology: MethodologyAnswers;\n features: FeatureAnswers;\n advanced: AdvancedAnswers;\n installLocation: \"global\" | \"local\";\n}\n\n/**\n * A file to be generated/written by the installer\n */\nexport interface GeneratedFile {\n path: string;\n content: string;\n exists: boolean;\n}\n\n// ============================================================================\n// Configuration Types\n// ============================================================================\n\nexport interface AgentRouting {\n requiresThinking?: boolean;\n preferProvider?: LLMProvider;\n}\n\nexport interface RoutingConfig {\n providerPriority: LLMProvider[];\n modelFamilyPriority: {\n claude?: LLMProvider[];\n gpt?: LLMProvider[];\n gemini?: LLMProvider[];\n };\n agentOverrides: {\n sisyphus?: AgentRouting;\n oracle?: AgentRouting;\n librarian?: AgentRouting;\n frontend?: AgentRouting;\n documentWriter?: AgentRouting;\n multimodalLooker?: AgentRouting;\n };\n fallbackBehavior: {\n autoFallback: boolean;\n retryPeriodMs: number;\n notifyOnRateLimit: boolean;\n };\n}\n\n/**\n * Athena configuration file structure\n */\nexport interface AthenaConfig {\n $schema?: string;\n version: string;\n subscriptions: {\n claude: {\n enabled: boolean;\n tier: \"max5x\" | \"max20x\" | \"pro\" | \"none\";\n };\n openai: {\n enabled: boolean;\n };\n google: {\n enabled: boolean;\n authMethod: \"antigravity\" | \"personal\" | \"api\" | \"none\";\n };\n githubCopilot: {\n enabled: boolean;\n plan: \"free\" | \"pro\" | \"pro-plus\" | \"business\" | \"enterprise\" | \"none\";\n enabledModels?: string[];\n };\n };\n models: {\n sisyphus: string;\n oracle: string;\n librarian: string;\n frontend?: string;\n documentWriter?: string;\n multimodalLooker?: string;\n settings?: {\n sisyphus?: AgentSettings;\n oracle?: AgentSettings;\n librarian?: AgentSettings;\n frontend?: AgentSettings;\n documentWriter?: AgentSettings;\n multimodalLooker?: AgentSettings;\n explore?: AgentSettings;\n overrides?: Record<string, AgentSettings>;\n };\n custom?: CustomModelDefinition[];\n };\n bmad: {\n defaultTrack: \"quick-flow\" | \"bmad-method\" | \"enterprise\";\n autoStatusUpdate: boolean;\n parallelStoryLimit: number;\n paths?: {\n stories?: string | null;\n sprintStatus?: string | null;\n prd?: string | null;\n architecture?: string | null;\n epics?: string | null;\n };\n };\n features: {\n bmadBridge: boolean;\n autoStatus: boolean;\n parallelExecution: boolean;\n notifications: boolean;\n contextMonitor: boolean;\n commentChecker: boolean;\n lspTools: boolean;\n autoGitOperations: boolean;\n todoSync: boolean;\n };\n mcps: {\n context7: boolean;\n exa: boolean;\n grepApp: boolean;\n };\n routing: RoutingConfig;\n}\n\n/**\n * Prerequisites check result\n */\nexport interface Prerequisites {\n opencode: {\n installed: boolean;\n version?: string;\n compatible: boolean;\n };\n athena: {\n installed: boolean;\n version?: string;\n };\n node: {\n installed: boolean;\n version?: string;\n compatible: boolean;\n };\n}\n\n// ============================================================================\n// Plugin Types\n// ============================================================================\n\n// ============================================================================\n// BMAD v6 Status Types (Flat Map Structure)\n// ============================================================================\n\n/**\n * BMAD v6 story status values (hyphenated)\n * Flow: backlog → ready-for-dev → in-progress → review → done\n * \"blocked\" is an Athena extension for tracking external dependencies\n */\nexport type BmadStoryStatus =\n | \"backlog\"\n | \"ready-for-dev\"\n | \"in-progress\"\n | \"review\"\n | \"done\"\n | \"blocked\"; // Athena extension\n\n/**\n * BMAD v6 epic status values\n * Flow: backlog → in-progress → done\n */\nexport type BmadEpicStatus = \"backlog\" | \"in-progress\" | \"done\";\n\n/**\n * BMAD v6 retrospective status values\n */\nexport type BmadRetroStatus = \"optional\" | \"done\";\n\n/**\n * All possible status values in development_status map\n */\nexport type BmadDevelopmentStatus = BmadStoryStatus | BmadEpicStatus | BmadRetroStatus;\n\n/**\n * BMAD v6 sprint status structure (flat map format)\n *\n * Example:\n * ```yaml\n * generated: 2025-12-28T10:30:00Z\n * project: My Project\n * current_story: 2-3 # Athena extension\n *\n * development_status:\n * epic-1: in-progress\n * 1-1-user-auth: done\n * 1-2-api-setup: ready-for-dev\n * epic-1-retrospective: optional\n * ```\n */\nexport interface BmadSprintStatus {\n /** ISO timestamp when file was generated */\n generated?: string;\n /** Project name */\n project?: string;\n /** Project key for tracking system integration */\n project_key?: string;\n /** Tracking system type (e.g., \"file-system\") */\n tracking_system?: string;\n /** Path to story files */\n story_location?: string;\n\n // Athena extensions\n /** Currently active story (Athena extension for explicit tracking) */\n current_story?: string | null;\n /** Last modified timestamp (Athena extension) */\n last_modified?: string;\n\n /**\n * Flat map of all development items and their statuses.\n * Keys can be:\n * - Epic: \"epic-{num}\" (e.g., \"epic-1\")\n * - Story: \"{epic}-{story}\" or \"{epic}-{story}-{title}\" (e.g., \"2-3\" or \"2-3-user-auth\")\n * - Retrospective: \"epic-{num}-retrospective\" (e.g., \"epic-1-retrospective\")\n */\n development_status: Record<string, BmadDevelopmentStatus>;\n}\n\n/**\n * Parsed story key information\n */\nexport interface ParsedStoryKey {\n /** Epic number (e.g., \"2\") */\n epicNum: string;\n /** Story number (e.g., \"3\") */\n storyNum: string;\n /** Title slug if present (e.g., \"user-authentication\") */\n titleSlug?: string;\n /** Full original key (e.g., \"2-3-user-authentication\") */\n fullKey: string;\n /** Normalized ID without title (e.g., \"2-3\") */\n normalizedId: string;\n}\n\n/**\n * Parsed epic key information\n */\nexport interface ParsedEpicKey {\n /** Epic number (e.g., \"1\") */\n epicNum: string;\n /** Full original key (e.g., \"epic-1\") */\n fullKey: string;\n}\n\n/**\n * Parsed retrospective key information\n */\nexport interface ParsedRetroKey {\n /** Epic number (e.g., \"1\") */\n epicNum: string;\n /** Full original key (e.g., \"epic-1-retrospective\") */\n fullKey: string;\n}\n\n/**\n * Type of key in development_status map\n */\nexport type DevelopmentKeyType = \"story\" | \"epic\" | \"retrospective\" | \"unknown\";\n\n/**\n * Result of parsing a development_status key\n */\nexport type ParsedDevelopmentKey =\n | { type: \"story\"; parsed: ParsedStoryKey }\n | { type: \"epic\"; parsed: ParsedEpicKey }\n | { type: \"retrospective\"; parsed: ParsedRetroKey }\n | { type: \"unknown\"; key: string };\n\n// ============================================================================\n// Legacy Types (for backward compatibility - deprecated)\n// ============================================================================\n\n/**\n * @deprecated Use BmadStoryStatus instead. This type uses underscore format\n * which doesn't match BMAD v6's hyphenated format.\n */\nexport type StoryStatus = \"pending\" | \"in_progress\" | \"completed\" | \"blocked\" | \"needs_review\";\n\nexport type TrackerStatus = BmadStoryStatus | \"loading\";\n\n/**\n * Tracked story state\n */\nexport interface TrackedStory {\n id: string;\n content: string;\n status: TrackerStatus;\n startedAt: string;\n completedAt?: string;\n}\n\n/**\n * @deprecated Use BmadSprintStatus instead. This interface uses array-based\n * structure which doesn't match BMAD v6's flat map format.\n */\nexport interface SprintStatus {\n sprint_number?: number;\n current_epic?: string;\n current_story?: string | null;\n completed_stories: string[];\n pending_stories: string[];\n in_progress_stories: string[];\n blocked_stories: string[];\n stories_needing_review?: string[];\n story_updates?: Record<\n string,\n {\n status: StoryStatus;\n updated_at: string;\n notes?: string;\n completion_summary?: string;\n }\n >;\n last_modified?: string;\n}\n\n/**\n * Story tracker persistent state\n */\nexport interface TrackerState {\n currentStory: TrackedStory | null;\n sessionId: string;\n projectDir: string;\n history: Array<{\n storyId: string;\n status: string;\n timestamp: string;\n }>;\n currentTodos?: OpenCodeTodo[];\n}\n\n// ============================================================================\n// Tool Result Types\n// ============================================================================\n\n/**\n * Result from athena_get_story tool\n */\nexport interface GetStoryResult {\n storyId?: string;\n story?: string;\n architecture?: string;\n prd?: string;\n sprint?: {\n currentEpic: string;\n completedStories: number;\n pendingStories: number;\n blockedStories: number;\n };\n instructions?: string;\n error?: string;\n suggestion?: string;\n sprintProgress?: {\n completed: number;\n total: number;\n };\n}\n\n/**\n * Result from athena_update_status tool\n */\nexport interface UpdateStatusResult {\n success?: boolean;\n storyId?: string;\n newStatus?: StoryStatus;\n updatedAt?: string;\n sprintProgress?: {\n completed: number;\n inProgress: number;\n pending: number;\n blocked: number;\n total: number;\n percentComplete: number;\n };\n nextStory?: string | null;\n error?: string;\n}\n\n// ============================================================================\n// Party Review Types\n// ============================================================================\n\n/**\n * Scope of a party review\n */\nexport type ReviewScope = \"epic\" | \"story\";\n\n/**\n * Severity level of a review finding\n */\nexport type FindingSeverity = \"high\" | \"medium\" | \"low\";\n\n/**\n * Category of a review finding\n */\nexport type FindingCategory = \"security\" | \"logic\" | \"bestPractices\" | \"performance\";\n\n/**\n * User decision on a finding\n */\nexport type ReviewDecision = \"accept\" | \"defer\" | \"reject\" | \"pending\";\n\n/**\n * A single party review finding\n */\nexport interface PartyReviewFinding {\n id: string;\n category: FindingCategory;\n severity: FindingSeverity;\n title: string;\n description: string;\n impact: string;\n suggestion: string;\n storyId?: string;\n fileReference?: string;\n lineNumber?: number;\n decision?: ReviewDecision;\n decisionReason?: string;\n deferredTo?: string;\n}\n\n/**\n * Findings grouped by story\n */\nexport interface StoryFindings {\n storyId: string;\n title: string;\n filePath: string;\n findings: {\n security: PartyReviewFinding[];\n logic: PartyReviewFinding[];\n bestPractices: PartyReviewFinding[];\n performance: PartyReviewFinding[];\n };\n summary: {\n total: number;\n high: number;\n medium: number;\n low: number;\n };\n}\n\n/**\n * Cross-story issues found in epic reviews\n */\nexport interface CrossStoryIssue {\n id: string;\n category: FindingCategory;\n severity: FindingSeverity;\n title: string;\n description: string;\n affectedStories: string[];\n suggestion: string;\n decision?: ReviewDecision;\n decisionReason?: string;\n}\n\n/**\n * Model complexity assessment result\n */\nexport interface StoryComplexity {\n isSimple: boolean;\n reason: string;\n recommendedModel: string;\n factors: {\n acceptanceCriteriaCount: number;\n hasSecurityConcerns: boolean;\n hasDataModelChanges: boolean;\n hasApiChanges: boolean;\n isCrudOnly: boolean;\n };\n}\n\n/**\n * Reference to another review document\n */\nexport interface ReviewDocumentReference {\n type: \"epic\" | \"focused\";\n filePath: string;\n date: string;\n findingsCount: number;\n acceptedCount: number;\n deferredCount: number;\n rejectedCount: number;\n}\n\n/**\n * Complete party review document structure\n */\nexport interface PartyReviewDocument {\n scope: ReviewScope;\n identifier: string;\n date: string;\n reviewer: string;\n epicNumber?: string;\n storyId?: string;\n storiesReviewed?: string[];\n relatedReviews?: ReviewDocumentReference[];\n summary: {\n totalIssues: number;\n highSeverity: number;\n mediumSeverity: number;\n lowSeverity: number;\n recommendation: string;\n };\n storyFindings?: StoryFindings[];\n crossStoryIssues?: CrossStoryIssue[];\n previousFindings?: {\n accepted: PartyReviewFinding[];\n deferred: PartyReviewFinding[];\n rejected: PartyReviewFinding[];\n };\n newFindings?: {\n security: PartyReviewFinding[];\n logic: PartyReviewFinding[];\n bestPractices: PartyReviewFinding[];\n performance: PartyReviewFinding[];\n };\n oracleAnalysis?: string;\n}\n\n/**\n * Result from athena_review_story tool (prepares context for Oracle invocation)\n */\nexport interface ReviewStoryResult {\n success: boolean;\n scope: ReviewScope;\n identifier: string;\n documentPath?: string;\n document?: PartyReviewDocument;\n error?: string;\n suggestion?: string;\n // Context prepared for command file to invoke Oracle\n oraclePrompt?: string;\n storiesContent?: Array<{ id: string; content: string | null }>;\n architectureContent?: string;\n existingReviews?: ReviewDocumentReference[];\n complexity?: StoryComplexity;\n selectedModel?: string;\n reviewsDir?: string;\n}\n\n/**\n * Argument for applying review decisions\n */\nexport interface ApplyReviewDecisionsArgs {\n documentPath: string;\n decisions: Record<string, ReviewDecision>;\n decisionReasons?: Record<string, string>;\n deferredTargets?: Record<string, string>;\n}\n\n/**\n * Result from applying review decisions\n */\nexport interface ApplyReviewDecisionsResult {\n success: boolean;\n updatedStories: string[];\n updatedDocuments: string[];\n summary: {\n accepted: number;\n deferred: number;\n rejected: number;\n };\n error?: string;\n}\n\n/**\n * Action taken on a story during decision application\n */\nexport type StoryUpdateAction = \"updated\" | \"created\" | \"appended\";\n\n/**\n * Parsed defer target from user input\n */\nexport interface ParsedDeferTarget {\n /** The target type */\n type: \"exact\" | \"new-end\" | \"new-after\" | \"new-before\" | \"append-existing\";\n /** The story ID (existing or to be created) */\n storyId: string;\n /** For sub-numbering: the reference story ID */\n referenceStoryId?: string;\n /** Original user input */\n originalInput: string;\n}\n\n/**\n * Result of applying updates to a single story\n */\nexport interface AppliedStoryUpdate {\n /** Story ID (e.g., \"4.1\" or \"4.2a\") */\n storyId: string;\n /** Full path to the story file */\n filePath: string;\n /** What action was taken */\n action: StoryUpdateAction;\n /** Acceptance criteria added (for created/updated) */\n addedCriteria: string[];\n /** Implementation notes added */\n addedNotes: string[];\n /** Whether the operation succeeded */\n success: boolean;\n /** Error message if failed */\n error?: string;\n /** For created stories: the defer target that triggered creation */\n deferTarget?: ParsedDeferTarget;\n}\n\n/**\n * Complete result from applying all decisions\n */\nexport interface ApplyDecisionsResult {\n /** Overall success (true even if some individual updates failed) */\n success: boolean;\n /** Stories that were updated with new criteria/notes */\n storiesUpdated: AppliedStoryUpdate[];\n /** New stories that were created for deferred findings */\n storiesCreated: AppliedStoryUpdate[];\n /** Existing stories that had findings appended */\n storiesAppended: AppliedStoryUpdate[];\n /** Whether the review document was updated */\n reviewDocumentUpdated: boolean;\n /** Path to the decisions-applied.md summary document */\n decisionsAppliedDocument?: string;\n /** Summary counts */\n summary: {\n accepted: number;\n deferred: number;\n rejected: number;\n storiesModified: number;\n storiesCreated: number;\n };\n /** Warnings (e.g., vague defer targets) */\n warnings?: string[];\n /** Error if complete failure */\n error?: string;\n}\n\n// ============================================================================\n// Enhanced Party Review Types (3-Phase Architecture)\n// ============================================================================\n\n/**\n * BMAD agent types that can participate in party review\n */\nexport type BmadAgentType =\n | \"architect\"\n | \"dev\"\n | \"tea\"\n | \"pm\"\n | \"analyst\"\n | \"ux-designer\"\n | \"tech-writer\"\n | \"sm\";\n\n/**\n * BMAD agent persona details\n */\nexport interface BmadAgentPersona {\n type: BmadAgentType;\n name: string;\n title: string;\n expertise: string[];\n perspective: string;\n}\n\n/**\n * Mapping of BMAD agents with their personas\n */\nexport const BMAD_AGENTS: Record<BmadAgentType, BmadAgentPersona> = {\n architect: {\n type: \"architect\",\n name: \"Winston\",\n title: \"Software Architect\",\n expertise: [\"system design\", \"security architecture\", \"scalability\", \"technical debt\"],\n perspective: \"architecture and system design\",\n },\n dev: {\n type: \"dev\",\n name: \"Amelia\",\n title: \"Senior Developer\",\n expertise: [\"implementation\", \"code quality\", \"debugging\", \"performance optimization\"],\n perspective: \"implementation feasibility and code quality\",\n },\n tea: {\n type: \"tea\",\n name: \"Murat\",\n title: \"Test Engineer\",\n expertise: [\"testing strategy\", \"edge cases\", \"test automation\", \"quality assurance\"],\n perspective: \"testability and quality assurance\",\n },\n pm: {\n type: \"pm\",\n name: \"John\",\n title: \"Product Manager\",\n expertise: [\"requirements\", \"stakeholder needs\", \"prioritization\", \"business value\"],\n perspective: \"business impact and stakeholder value\",\n },\n analyst: {\n type: \"analyst\",\n name: \"Mary\",\n title: \"Business Analyst\",\n expertise: [\"requirements analysis\", \"user stories\", \"acceptance criteria\", \"edge cases\"],\n perspective: \"requirements completeness and clarity\",\n },\n \"ux-designer\": {\n type: \"ux-designer\",\n name: \"Sally\",\n title: \"UX Designer\",\n expertise: [\"user experience\", \"accessibility\", \"usability\", \"user flows\"],\n perspective: \"user experience and accessibility\",\n },\n \"tech-writer\": {\n type: \"tech-writer\",\n name: \"Paige\",\n title: \"Technical Writer\",\n expertise: [\"documentation\", \"API docs\", \"user guides\", \"clarity\"],\n perspective: \"documentation and clarity\",\n },\n sm: {\n type: \"sm\",\n name: \"Bob\",\n title: \"Scrum Master\",\n expertise: [\"process\", \"team dynamics\", \"sprint planning\", \"blockers\"],\n perspective: \"process and team coordination\",\n },\n};\n\n/**\n * Agent recommendation with reasoning\n */\nexport interface AgentRecommendation {\n agent: BmadAgentType;\n reason: string;\n relevantFindings: string[];\n priority: \"required\" | \"recommended\" | \"optional\";\n}\n\n/**\n * Cross-story pattern identified by an agent\n */\nexport interface CrossStoryPattern {\n id: string;\n pattern: string;\n affectedStories: string[];\n severity: FindingSeverity;\n recommendation: string;\n}\n\n/**\n * Single agent's analysis output (Phase 2)\n */\nexport interface AgentAnalysis {\n agent: BmadAgentType;\n agentName: string;\n analyzedAt: string;\n storiesAnalyzed: string[];\n perspective: string;\n findings: {\n agreements: string[];\n concerns: string[];\n suggestions: string[];\n };\n crossStoryPatterns: CrossStoryPattern[];\n prioritizedIssues: Array<{\n findingId: string;\n agentPriority: \"critical\" | \"important\" | \"minor\";\n rationale: string;\n }>;\n summary: string;\n}\n\n/**\n * Phase 1 context: Prepared by tool for Oracle invocation (before Oracle runs)\n */\nexport type Phase1Context = Phase1ContextSuccess | Phase1ContextError;\n\nexport interface Phase1ContextSuccess {\n success: true;\n scope: ReviewScope;\n identifier: string;\n reviewsDir: string;\n storiesContent: Array<{ id: string; content: string | null }>;\n architectureContent: string;\n oraclePrompt: string;\n selectedModel: string;\n complexity?: StoryComplexity;\n existingReviews?: ReviewDocumentReference[];\n}\n\nexport interface Phase1ContextError {\n success: false;\n scope: ReviewScope;\n identifier: string;\n error: string;\n suggestion?: string;\n}\n\n/**\n * Phase 1 summary: Minimal result returned to agent after Oracle analysis.\n * Large data (oracleAnalysis, storiesContent) is saved to file, not passed between tools.\n */\nexport interface Phase1Summary {\n success: boolean;\n scope: ReviewScope;\n identifier: string;\n error?: string;\n suggestion?: string;\n reviewFolderPath?: string;\n findings?: {\n total: number;\n high: number;\n medium: number;\n low: number;\n byCategory: Record<FindingCategory, number>;\n };\n recommendedAgents?: AgentRecommendation[];\n summary?: string;\n}\n\n/**\n * Phase 1 full data: Complete data saved to analysis.json file.\n * Includes large fields that should not be passed between tool calls.\n */\nexport interface Phase1FullData extends Phase1Summary {\n storiesContent?: Array<{ id: string; title?: string; content: string | null }>;\n architectureContent?: string;\n oracleAnalysis?: string;\n}\n\n/**\n * @deprecated Use Phase1Summary for tool returns, Phase1FullData for file storage\n */\nexport type Phase1Result = Phase1FullData;\n\n/**\n * Phase 2 result: Aggregated agent analyses\n */\nexport interface Phase2Result {\n success: boolean;\n identifier: string;\n agentAnalyses: AgentAnalysis[];\n consensusPoints: string[];\n debatePoints: Array<{\n topic: string;\n positions: Array<{\n agent: BmadAgentType;\n position: string;\n }>;\n }>;\n aggregatedPriorities: Array<{\n findingId: string;\n votes: Record<BmadAgentType, \"critical\" | \"important\" | \"minor\" | \"not-rated\">;\n consensus: \"strong\" | \"moderate\" | \"disputed\";\n }>;\n error?: string;\n}\n\n/**\n * Discussion context for Phase 3 party mode\n */\nexport interface DiscussionContext {\n scope: ReviewScope;\n identifier: string;\n epicNumber?: string;\n storyIds: string[];\n phase1Summary: {\n totalFindings: number;\n highSeverity: number;\n reviewDocumentPath: string;\n };\n agentAnalyses: AgentAnalysis[];\n agendaItems: Array<{\n id: string;\n topic: string;\n type: \"consensus\" | \"debate\" | \"decision-needed\";\n relatedFindings: string[];\n agentPositions?: Record<BmadAgentType, string>;\n }>;\n preloadedContext: string;\n}\n\n/**\n * Final review session result\n */\nexport interface ReviewSessionResult {\n success: boolean;\n identifier: string;\n decisions: Record<string, ReviewDecision>;\n decisionSummary: {\n accepted: number;\n deferred: number;\n rejected: number;\n discussed: number;\n };\n storyUpdates: Array<{\n storyId: string;\n addedCriteria: string[];\n modifiedCriteria: string[];\n }>;\n actionItems: Array<{\n description: string;\n assignedTo?: BmadAgentType;\n deferredToStory?: string;\n }>;\n sessionNotes: string;\n}\n\n// ============================================================================\n// Phase 3: Party Discussion Types\n// ============================================================================\n\n/**\n * Extended BMAD agent persona with full details from manifest\n */\nexport interface BmadAgentFullPersona extends BmadAgentPersona {\n icon: string;\n identity: string;\n communicationStyle: string;\n principles: string[];\n module?: string;\n}\n\n/**\n * Default full personas (fallback when BMAD manifest not available)\n */\nexport const BMAD_AGENT_FULL_PERSONAS: Record<BmadAgentType, BmadAgentFullPersona> = {\n architect: {\n type: \"architect\",\n name: \"Winston\",\n title: \"Software Architect\",\n icon: \"🏗️\",\n expertise: [\"system design\", \"security architecture\", \"scalability\", \"technical debt\"],\n perspective: \"architecture and system design\",\n identity:\n \"Senior architect with expertise in distributed systems, cloud infrastructure, and API design. Specializes in scalable patterns and technology selection.\",\n communicationStyle:\n \"Speaks in calm, pragmatic tones, balancing 'what could be' with 'what should be.' Champions boring technology that actually works.\",\n principles: [\n \"User journeys drive technical decisions\",\n \"Embrace boring technology for stability\",\n \"Design simple solutions that scale when needed\",\n \"Developer productivity is architecture\",\n ],\n },\n dev: {\n type: \"dev\",\n name: \"Amelia\",\n title: \"Senior Developer\",\n icon: \"💻\",\n expertise: [\"implementation\", \"code quality\", \"debugging\", \"performance optimization\"],\n perspective: \"implementation feasibility and code quality\",\n identity:\n \"Elite developer who thrives on clean implementations. Lives for readable code, sensible abstractions, and solutions that actually work in production.\",\n communicationStyle:\n \"Ultra-succinct. Speaks in file paths and AC IDs - every statement citable. No fluff, all precision.\",\n principles: [\n \"Code should be readable by humans first\",\n \"Ship incrementally, validate continuously\",\n \"Tests are documentation\",\n \"Complexity is the enemy\",\n ],\n },\n tea: {\n type: \"tea\",\n name: \"Murat\",\n title: \"Test Engineer Advocate\",\n icon: \"🧪\",\n expertise: [\"testing strategy\", \"edge cases\", \"test automation\", \"quality assurance\"],\n perspective: \"testability and quality assurance\",\n identity:\n \"Master test architect who sees quality as everyone's responsibility. Blends data with gut instinct to find bugs before they find users.\",\n communicationStyle:\n \"Blends data with gut instinct. 'Strong opinions, weakly held' is their mantra. Speaks in risk calculations and impact assessments.\",\n principles: [\n \"Test the behavior, not the implementation\",\n \"Edge cases reveal system character\",\n \"Automation enables confidence\",\n \"Quality is prevention, not detection\",\n ],\n },\n pm: {\n type: \"pm\",\n name: \"John\",\n title: \"Product Manager\",\n icon: \"📋\",\n expertise: [\"requirements\", \"stakeholder needs\", \"prioritization\", \"business value\"],\n perspective: \"business impact and stakeholder value\",\n identity:\n \"Investigative product strategist who asks 'WHY?' relentlessly. Connects every feature to user value and business outcomes.\",\n communicationStyle:\n \"Asks 'WHY?' relentlessly like a detective on a case. Direct and data-sharp, cuts through fluff to what actually matters.\",\n principles: [\n \"User problems drive solutions\",\n \"Data informs, intuition guides\",\n \"MVP means minimum VIABLE\",\n \"Say no to protect yes\",\n ],\n },\n analyst: {\n type: \"analyst\",\n name: \"Mary\",\n title: \"Business Analyst\",\n icon: \"📊\",\n expertise: [\"requirements analysis\", \"user stories\", \"acceptance criteria\", \"edge cases\"],\n perspective: \"requirements completeness and clarity\",\n identity:\n \"Strategic analyst who treats requirements like treasure hunts. Excited by patterns, thrilled when ambiguity becomes clarity.\",\n communicationStyle:\n \"Treats analysis like a treasure hunt - excited by every clue, thrilled when patterns emerge. Asks questions that spark 'aha!' moments.\",\n principles: [\n \"Ambiguity is the enemy of delivery\",\n \"Edge cases reveal true requirements\",\n \"Stakeholders often know what they need, not what they want\",\n \"Document decisions, not just outcomes\",\n ],\n },\n \"ux-designer\": {\n type: \"ux-designer\",\n name: \"Sally\",\n title: \"UX Designer\",\n icon: \"🎨\",\n expertise: [\"user experience\", \"accessibility\", \"usability\", \"user flows\"],\n perspective: \"user experience and accessibility\",\n identity:\n \"User advocate who designs experiences, not just interfaces. Champions accessibility and believes good UX is invisible.\",\n communicationStyle:\n \"Empathetic and user-focused. Uses stories and scenarios to illustrate points. Gentle but firm on accessibility.\",\n principles: [\n \"Design for the edges, the middle takes care of itself\",\n \"Accessibility is not optional\",\n \"Users don't read, they scan\",\n \"Friction is the enemy of conversion\",\n ],\n },\n \"tech-writer\": {\n type: \"tech-writer\",\n name: \"Paige\",\n title: \"Technical Writer\",\n icon: \"📚\",\n expertise: [\"documentation\", \"API docs\", \"user guides\", \"clarity\"],\n perspective: \"documentation and clarity\",\n identity:\n \"Knowledge curator who makes complex simple. Believes documentation is a product feature, not an afterthought.\",\n communicationStyle:\n \"Patient educator who explains like teaching a friend. Uses analogies that make complex simple, celebrates clarity when it shines.\",\n principles: [\n \"If it's not documented, it doesn't exist\",\n \"Good docs prevent support tickets\",\n \"Examples are worth a thousand words\",\n \"Write for the reader, not the writer\",\n ],\n },\n sm: {\n type: \"sm\",\n name: \"Bob\",\n title: \"Scrum Master\",\n icon: \"🎯\",\n expertise: [\"process\", \"team dynamics\", \"sprint planning\", \"blockers\"],\n perspective: \"process and team coordination\",\n identity:\n \"Servant leader who removes blockers and protects team focus. Facilitates rather than dictates.\",\n communicationStyle:\n \"Facilitative and inclusive. Asks powerful questions rather than giving answers. Celebrates team wins.\",\n principles: [\n \"The team knows best\",\n \"Process serves people, not vice versa\",\n \"Blockers are opportunities for improvement\",\n \"Sustainable pace enables sustainable delivery\",\n ],\n },\n};\n\n/**\n * Input for the party discussion tool\n */\nexport interface PartyDiscussionInput {\n /** Phase 1 results with Oracle findings */\n phase1Result: Phase1Result;\n /** Phase 2 agent analyses */\n phase2Result: Phase2Result;\n /** Stories content for context */\n storiesContent: Array<{ id: string; content: string }>;\n /** Optional: specific findings to discuss (defaults to all high severity + disputed) */\n findingsToDiscuss?: string[];\n}\n\n/**\n * A single agent's response in a discussion round\n */\nexport interface AgentDiscussionResponse {\n agent: BmadAgentType;\n agentName: string;\n icon: string;\n response: string;\n /** References to other agents in cross-talk */\n references?: Array<{\n agent: BmadAgentType;\n type: \"agrees\" | \"disagrees\" | \"builds-on\" | \"questions\";\n }>;\n /** Key points extracted from response */\n keyPoints: string[];\n}\n\n/**\n * A complete discussion round for a single finding\n */\nexport interface DiscussionRound {\n findingId: string;\n findingTitle: string;\n findingSeverity: FindingSeverity;\n findingCategory: FindingCategory;\n /** Agents who participated in this round */\n participants: BmadAgentType[];\n /** Agent responses in order */\n responses: AgentDiscussionResponse[];\n /** User's decision for this finding */\n decision?: ReviewDecision;\n /** User's reasoning for the decision */\n decisionReason?: string;\n /** If deferred, where to */\n deferredTo?: string;\n}\n\n/**\n * Discussion agenda item\n */\nexport interface DiscussionAgendaItem {\n id: string;\n findingId: string;\n topic: string;\n type: \"high-severity\" | \"disputed\" | \"cross-story\" | \"consensus\";\n severity: FindingSeverity;\n category: FindingCategory;\n /** Agents relevant to this topic */\n relevantAgents: BmadAgentType[];\n /** Pre-existing agent positions from Phase 2 */\n agentPositions: Partial<Record<BmadAgentType, string>>;\n /** Whether this item has been discussed */\n discussed: boolean;\n /** The discussion round if discussed */\n round?: DiscussionRound;\n}\n\n/**\n * Current state of the party discussion\n */\nexport interface PartyDiscussionState {\n /** Unique session ID */\n sessionId: string;\n /** Review scope */\n scope: ReviewScope;\n /** Epic or story identifier */\n identifier: string;\n /** Current agenda items */\n agenda: DiscussionAgendaItem[];\n /** Index of current agenda item */\n currentItemIndex: number;\n /** Completed discussion rounds */\n completedRounds: DiscussionRound[];\n /** Participating agents for this session */\n activeAgents: BmadAgentType[];\n /** When the discussion started */\n startedAt: string;\n /** Phase data for context */\n phase1Summary: Phase1Result[\"findings\"];\n phase2Summary?: {\n consensusCount: number;\n disputeCount: number;\n };\n}\n\n/**\n * Result from the party discussion tool\n */\nexport interface PartyDiscussionResult {\n success: boolean;\n /** Session ID for continuation */\n sessionId: string;\n /** Current state of the discussion */\n state: PartyDiscussionState;\n /** Current agenda item to display */\n currentItem?: DiscussionAgendaItem;\n /** Agent responses for current item (if generating discussion) */\n currentResponses?: AgentDiscussionResponse[];\n /** Summary when discussion is complete */\n summary?: {\n totalDiscussed: number;\n decisions: {\n accepted: number;\n deferred: number;\n rejected: number;\n pending: number;\n };\n /** @deprecated Use appliedUpdates instead - updates are now applied automatically */\n storyUpdatesNeeded: Array<{\n storyId: string;\n additions: string[];\n }>;\n };\n /** Result of automatically applying decisions to stories (on \"end\" action) */\n appliedUpdates?: ApplyDecisionsResult;\n /** Whether more items remain */\n hasMoreItems: boolean;\n /** Error if failed */\n error?: string;\n /** Suggestion for resolving error */\n suggestion?: string;\n}\n\n/**\n * Action to take in party discussion\n */\nexport type PartyDiscussionAction =\n | { type: \"start\"; input: PartyDiscussionInput }\n | { type: \"continue\"; sessionId: string }\n | {\n type: \"decide\";\n sessionId: string;\n findingId: string;\n decision: ReviewDecision;\n reason?: string;\n deferredTo?: string;\n }\n | { type: \"skip\"; sessionId: string; findingId: string }\n | { type: \"end\"; sessionId: string };\n\n// ============================================================================\n// BMAD ↔ Todo Sync Types\n// ============================================================================\n\n/**\n * OpenCode todo item format (matches oh-my-opencode/OpenCode schema)\n */\nexport interface OpenCodeTodo {\n /** Unique identifier for the todo item */\n id: string;\n /** Brief description of the task */\n content: string;\n /** Current status of the task */\n status: TodoStatus;\n /** Priority level of the task */\n priority: TodoPriority;\n}\n\n/**\n * Valid todo status values\n */\nexport type TodoStatus = \"pending\" | \"in_progress\" | \"completed\" | \"cancelled\";\n\n/**\n * Valid todo priority values\n */\nexport type TodoPriority = \"high\" | \"medium\" | \"low\";\n\n/**\n * BMAD section types that can contain checkboxes\n */\nexport type BmadSection = \"ac\" | \"tasks\" | \"impl-notes\";\n\n/**\n * A parsed task from a BMAD story file\n */\nexport interface BmadTask {\n /** Todo ID format: \"{storyId}:{section}:{lineNumber}\" */\n id: string;\n /** Story ID (e.g., \"2.3\") */\n storyId: string;\n /** Section where the checkbox was found */\n section: BmadSection;\n /** Index within the section (1-based) */\n sectionIndex: number;\n /** Line number in the file (0-based) */\n lineNumber: number;\n /** Task description text */\n content: string;\n /** Whether the checkbox is checked */\n checked: boolean;\n /** Detected or default priority */\n priority: TodoPriority;\n /** Indentation level for subtasks (number of spaces) */\n indent: number;\n}\n\n/**\n * Parsed todo ID components\n */\nexport interface ParsedTodoId {\n /** Story ID (e.g., \"2.3\") */\n storyId: string;\n /** Section type */\n section: BmadSection;\n /** Line number hint (may have shifted) */\n lineHint: number;\n}\n\n/**\n * Match type for todo matching\n */\nexport type TodoMatchType = \"id\" | \"exact-content\" | \"similar-content\" | \"none\";\n\n/**\n * Confidence thresholds for todo matching\n */\nexport const TODO_MATCH_THRESHOLDS = {\n AUTO_UPDATE: 0.7,\n WARN_USER: 0.5,\n} as const;\n\n/**\n * Result of attempting to match a todo with a previous todo\n */\nexport interface TodoMatchResult {\n /** The matched todo, if any */\n matched: OpenCodeTodo | null;\n /** How the match was found */\n matchType: TodoMatchType;\n /** Confidence score (0-1) */\n confidence: number;\n}\n\n// ============================================================================\n// Story Complexity & Decomposition Types\n// ============================================================================\n\n/**\n * Effort level for a task (maps to Fibonacci-ish points)\n */\nexport type TaskEffortLevel = \"trivial\" | \"small\" | \"medium\" | \"large\" | \"xlarge\";\n\n/**\n * Points mapping for effort levels\n */\nexport const EFFORT_POINTS: Record<TaskEffortLevel, number> = {\n trivial: 1,\n small: 2,\n medium: 3,\n large: 5,\n xlarge: 8,\n};\n\n/**\n * A parsed subtask from a story file\n */\nexport interface ParsedSubtask {\n /** Subtask ID within task (e.g., \"1.1\", \"1.2\") */\n id: string;\n /** Subtask description */\n description: string;\n /** Whether the checkbox is checked */\n completed: boolean;\n /** Line number in file (1-based) */\n lineNumber: number;\n}\n\n/**\n * A parsed task from a story file\n */\nexport interface ParsedTask {\n /** Task ID (e.g., \"1\", \"2\", \"3\") */\n id: string;\n /** Task description */\n description: string;\n /** Subtasks belonging to this task */\n subtasks: ParsedSubtask[];\n /** Whether the main task checkbox is checked */\n completed: boolean;\n /** Line number in file (1-based) */\n lineNumber: number;\n}\n\n/**\n * Effort estimate for a single task\n */\nexport interface TaskEffortEstimate {\n /** Task ID */\n taskId: string;\n /** Task description */\n description: string;\n /** Estimated effort level */\n effort: TaskEffortLevel;\n /** Story points (1, 2, 3, 5, 8) */\n points: number;\n /** Signals that contributed to this estimate */\n signals: string[];\n}\n\n/**\n * Complexity thresholds for story analysis\n */\nexport interface ComplexityThresholds {\n /** Maximum recommended tasks before warning */\n maxTasks: number;\n /** Critical task count - must split */\n criticalTasks: number;\n /** Maximum recommended story points before warning */\n maxPoints: number;\n /** Critical story points - must split */\n criticalPoints: number;\n /** Maximum recommended file size in KB */\n maxFileSizeKB: number;\n /** Critical file size - must split */\n criticalFileSizeKB: number;\n}\n\n/**\n * Default complexity thresholds (research-backed)\n */\nexport const DEFAULT_COMPLEXITY_THRESHOLDS: ComplexityThresholds = {\n maxTasks: 8,\n criticalTasks: 12,\n maxPoints: 8,\n criticalPoints: 13,\n maxFileSizeKB: 30,\n criticalFileSizeKB: 50,\n};\n\n/**\n * Recommendation for story complexity\n */\nexport type ComplexityRecommendation =\n | \"proceed\"\n | \"suggest-decomposition\"\n | \"require-decomposition\";\n\n/**\n * Story metrics from parsing\n */\nexport interface StoryMetrics {\n /** Number of tasks */\n taskCount: number;\n /** Total number of subtasks across all tasks */\n subtaskCount: number;\n /** Number of acceptance criteria (if separate from tasks) */\n acceptanceCriteriaCount: number;\n /** Story file size in KB */\n storyFileSizeKB: number;\n /** Story file line count */\n lineCount: number;\n}\n\n/**\n * Complete story complexity assessment\n */\nexport interface StoryComplexityAssessment {\n /** Story ID */\n storyId: string;\n /** Story filename */\n filename: string;\n /** Raw metrics */\n metrics: StoryMetrics;\n /** Task-level effort estimates */\n taskEfforts: TaskEffortEstimate[];\n /** Total estimated story points */\n totalPoints: number;\n /** Whether any threshold is exceeded */\n exceedsThreshold: boolean;\n /** Specific reasons for exceeding threshold */\n thresholdReasons: string[];\n /** Recommendation */\n recommendation: ComplexityRecommendation;\n /** Estimated context compactions needed */\n estimatedCompactions: number;\n}\n\n/**\n * Suggested split for story decomposition\n */\nexport interface DecompositionSplit {\n /** Suffix to append to original filename (e.g., \"a\", \"b\", \"c\") */\n suffix: string;\n /** Suggested title for the split story */\n title: string;\n /** Task IDs to include in this split */\n taskIds: string[];\n /** Estimated points for this split */\n estimatedPoints: number;\n /** Rationale for this grouping */\n rationale: string;\n /** Dependencies on other splits (by suffix) */\n dependencies: string[];\n}\n\n/**\n * Result from athena_analyze_story tool\n */\nexport interface AnalyzeStoryResult {\n success: boolean;\n /** Story ID analyzed */\n storyId: string;\n /** Story filename */\n filename: string;\n /** Full complexity assessment */\n assessment: StoryComplexityAssessment;\n /** Suggested decomposition splits (if recommended) */\n suggestedSplits?: DecompositionSplit[];\n /** Error if analysis failed */\n error?: string;\n /** Suggestion for resolving error */\n suggestion?: string;\n}\n\n/**\n * User-provided split configuration\n */\nexport interface UserSplitConfig {\n /** Suffix to append to original filename */\n suffix: string;\n /** Optional title override */\n title?: string;\n /** Task IDs to include */\n taskIds: string[];\n}\n\n/**\n * Arguments for athena_decompose_story tool\n */\nexport interface DecomposeStoryArgs {\n /** Story ID to decompose */\n storyId: string;\n /** Custom splits (if user modified suggestion) */\n splits?: UserSplitConfig[];\n /** Use the suggested splits from analysis (if no custom splits) */\n useSuggestedSplits?: boolean;\n /** Must be true to execute (safety check) */\n confirmed: boolean;\n}\n\n/**\n * Information about a created sub-story\n */\nexport interface CreatedSubStory {\n /** Story ID (e.g., \"3.2a\") */\n id: string;\n /** Filename (e.g., \"3-2a-reset-list-screen.md\") */\n filename: string;\n /** Full file path */\n filePath: string;\n /** Number of tasks in this story */\n taskCount: number;\n /** Estimated points */\n estimatedPoints: number;\n /** Status in sprint-status.yaml */\n status: \"ready-for-dev\" | \"backlog\";\n /** Dependencies on other sub-stories */\n dependencies: string[];\n /** Whether a verification task was added (for unorderable deps) */\n hasVerificationTask: boolean;\n}\n\n/**\n * Verification result for decomposition\n */\nexport interface DecompositionVerification {\n /** Original task count */\n originalTaskCount: number;\n /** Total tasks across all splits */\n totalTasksInSplits: number;\n /** Whether all tasks are accounted for */\n allTasksAccountedFor: boolean;\n /** Tasks missing from splits (should be empty) */\n missingTasks: string[];\n /** Tasks duplicated across splits (should be empty) */\n duplicatedTasks: string[];\n /** Whether dev notes were preserved */\n devNotesPreserved: boolean;\n}\n\n/**\n * Result from athena_decompose_story tool\n */\nexport interface DecomposeStoryResult {\n success: boolean;\n /** Created sub-stories */\n createdStories: CreatedSubStory[];\n /** Verification of completeness */\n verification: DecompositionVerification;\n /** Whether sprint-status.yaml was updated */\n sprintStatusUpdated: boolean;\n /** Whether original story was removed */\n originalStoryRemoved: boolean;\n /** First story to implement */\n nextStory: string;\n /** Error if decomposition failed */\n error?: string;\n /** Suggestion for resolving error */\n suggestion?: string;\n}\n","/**\n * Story loader utilities with flexible naming support.\n *\n * Supports multiple story naming conventions:\n * - story-{epic}-{number}.md (e.g., story-4-1.md) - BMAD standard\n * - story-{epic}-{number}-{title}.md (e.g., story-4-1-setup.md) - BMAD with title\n * - {epic}-{number}.md (e.g., 4-1.md) - minimal\n * - {epic}-{number}-{title}.md (e.g., 4-1-fastify-setup.md) - with title\n *\n * All matching is case-insensitive.\n * Files with \"story-\" prefix are prioritized over those without.\n */\n\nimport { existsSync } from \"node:fs\";\nimport { readFile, readdir } from \"node:fs/promises\";\nimport { basename, join, resolve } from \"node:path\";\n\n/**\n * Result of finding a story file.\n */\nexport interface StoryFileResult {\n /** Full path to the story file */\n path: string;\n /** Original filename as it exists on disk */\n filename: string;\n /** Normalized story ID (e.g., \"4.1\") */\n storyId: string;\n /** Whether multiple matches were found */\n hasMultipleMatches: boolean;\n /** Other matching files that were not selected */\n alternativeFiles?: string[];\n}\n\n/**\n * Information about a story found in a directory.\n */\nexport interface StoryInfo {\n /** Normalized story ID (e.g., \"4.1\") */\n id: string;\n /** Epic number */\n epic: string;\n /** Story number within the epic */\n number: string;\n /** Original filename */\n filename: string;\n /** Full path to the file */\n path: string;\n /** Whether this file has the story- prefix */\n hasStoryPrefix: boolean;\n}\n\n/**\n * Pattern for matching story files.\n * Matches: story-4-1.md, story-4-1-title.md, 4-1.md, 4-1-title.md\n * Groups: [1] = \"story-\" prefix (optional), [2] = epic, [3] = number\n */\nconst STORY_PATTERN = /^(story-)?(\\d+)-(\\d+)(?:-[a-zA-Z0-9-]+)?\\.md$/i;\n\n/**\n * Parse a story ID from a filename.\n * Returns null if the filename doesn't match a story pattern.\n *\n * @example\n * parseStoryIdFromFilename(\"story-4-1.md\") // { id: \"4.1\", epic: \"4\", number: \"1\", hasStoryPrefix: true }\n * parseStoryIdFromFilename(\"4-1-setup.md\") // { id: \"4.1\", epic: \"4\", number: \"1\", hasStoryPrefix: false }\n * parseStoryIdFromFilename(\"README.md\") // null\n */\nexport function parseStoryIdFromFilename(\n filename: string\n): { id: string; epic: string; number: string; hasStoryPrefix: boolean } | null {\n const match = filename.match(STORY_PATTERN);\n if (!match) {\n return null;\n }\n\n const hasStoryPrefix = !!match[1];\n const epic = match[2];\n const number = match[3];\n\n return {\n id: `${epic}.${number}`,\n epic,\n number,\n hasStoryPrefix,\n };\n}\n\n/**\n * Find a story file by its ID (e.g., \"4.1\" or \"4-1\").\n * Searches the directory for any file matching the story pattern.\n *\n * Priority:\n * 1. Files with \"story-\" prefix\n * 2. Files without prefix\n *\n * If multiple matches exist, selects the highest priority and logs alternatives.\n *\n * @param storiesDir - Directory containing story files\n * @param storyId - Story ID (e.g., \"4.1\", \"4-1\", or \"story-4-1\")\n * @param logger - Optional logger for warnings about multiple matches\n * @returns StoryFileResult or null if not found\n */\nexport async function findStoryFile(\n storiesDir: string,\n storyId: string,\n logger?: { warn: (msg: string) => void }\n): Promise<StoryFileResult | null> {\n if (!existsSync(storiesDir)) {\n return null;\n }\n\n // Normalize the story ID: \"story-4-1\" -> \"4.1\", \"4-1\" -> \"4.1\", \"4.1\" -> \"4.1\"\n const normalizedId = normalizeStoryId(storyId);\n const [epicNum, storyNum] = normalizedId.split(\".\");\n\n if (!epicNum || !storyNum) {\n return null;\n }\n\n const files = await readdir(storiesDir);\n const matches: StoryInfo[] = [];\n\n for (const file of files) {\n const parsed = parseStoryIdFromFilename(file);\n if (parsed && parsed.epic === epicNum && parsed.number === storyNum) {\n matches.push({\n ...parsed,\n filename: file,\n path: join(storiesDir, file),\n });\n }\n }\n\n if (matches.length === 0) {\n return null;\n }\n\n // Sort: story- prefix first, then alphabetically\n matches.sort((a, b) => {\n if (a.hasStoryPrefix !== b.hasStoryPrefix) {\n return a.hasStoryPrefix ? -1 : 1;\n }\n return a.filename.localeCompare(b.filename);\n });\n\n const selected = matches[0];\n const alternatives = matches.slice(1).map((m) => m.filename);\n\n if (alternatives.length > 0 && logger) {\n const reason = selected.hasStoryPrefix ? \"has story- prefix\" : \"alphabetically first\";\n const altLines = alternatives.map((f) => ` → ${f}`).join(\"\\n\");\n logger.warn(\n `Multiple story files found for ${normalizedId}:\\n → ${selected.filename} (selected - ${reason})\\n${altLines}`\n );\n }\n\n return {\n path: selected.path,\n filename: selected.filename,\n storyId: normalizedId,\n hasMultipleMatches: alternatives.length > 0,\n alternativeFiles: alternatives.length > 0 ? alternatives : undefined,\n };\n}\n\n/**\n * Find all stories for a given epic.\n * Returns stories sorted by story number.\n *\n * For duplicate story IDs (same epic-number but different filenames),\n * prioritizes files with \"story-\" prefix and logs alternatives.\n *\n * @param storiesDir - Directory containing story files\n * @param epicNumber - Epic number (e.g., \"4\" or \"epic-4\")\n * @param logger - Optional logger for warnings about duplicates\n * @returns Array of StoryInfo objects\n */\nexport async function findStoriesForEpic(\n storiesDir: string,\n epicNumber: string,\n logger?: { warn: (msg: string) => void }\n): Promise<StoryInfo[]> {\n if (!existsSync(storiesDir)) {\n return [];\n }\n\n // Normalize: \"epic-4\" -> \"4\"\n const epicNum = epicNumber.replace(/^epic-/i, \"\");\n\n const files = await readdir(storiesDir);\n const allMatches: StoryInfo[] = [];\n\n for (const file of files) {\n const parsed = parseStoryIdFromFilename(file);\n if (parsed && parsed.epic === epicNum) {\n allMatches.push({\n ...parsed,\n filename: file,\n path: join(storiesDir, file),\n });\n }\n }\n\n // Group by story ID to handle duplicates\n const byId = new Map<string, StoryInfo[]>();\n for (const match of allMatches) {\n const existing = byId.get(match.id) || [];\n existing.push(match);\n byId.set(match.id, existing);\n }\n\n // Select best match for each story ID\n const results: StoryInfo[] = [];\n for (const [id, matches] of byId) {\n // Sort: story- prefix first, then alphabetically\n matches.sort((a, b) => {\n if (a.hasStoryPrefix !== b.hasStoryPrefix) {\n return a.hasStoryPrefix ? -1 : 1;\n }\n return a.filename.localeCompare(b.filename);\n });\n\n const selected = matches[0];\n results.push(selected);\n\n if (matches.length > 1 && logger) {\n const alternatives = matches.slice(1).map((m) => m.filename);\n const reason = selected.hasStoryPrefix ? \"has story- prefix\" : \"alphabetically first\";\n const altLines = alternatives.map((f) => ` → ${f}`).join(\"\\n\");\n logger.warn(\n `Multiple story files found for ${id}:\\n → ${selected.filename} (selected - ${reason})\\n${altLines}`\n );\n }\n }\n\n // Sort by story number\n return results.sort((a, b) => {\n const numA = Number.parseInt(a.number, 10);\n const numB = Number.parseInt(b.number, 10);\n return numA - numB;\n });\n}\n\n/**\n * Load story file content by ID.\n * Convenience function that combines findStoryFile + readFile.\n *\n * @param storiesDir - Directory containing story files\n * @param storyId - Story ID (e.g., \"4.1\")\n * @param logger - Optional logger for warnings\n * @returns File content or null if not found\n */\nexport async function loadStoryContent(\n storiesDir: string,\n storyId: string,\n logger?: { warn: (msg: string) => void }\n): Promise<{ content: string; path: string; filename: string } | null> {\n const result = await findStoryFile(storiesDir, storyId, logger);\n if (!result) {\n return null;\n }\n\n try {\n const content = await readFile(result.path, \"utf-8\");\n return {\n content,\n path: result.path,\n filename: result.filename,\n };\n } catch {\n return null;\n }\n}\n\n/**\n * Normalize a story ID to the format \"epic.number\".\n *\n * @example\n * normalizeStoryId(\"story-4-1\") // \"4.1\"\n * normalizeStoryId(\"4-1\") // \"4.1\"\n * normalizeStoryId(\"4.1\") // \"4.1\"\n * normalizeStoryId(\"story-4-1-title.md\") // \"4.1\"\n */\nexport function normalizeStoryId(identifier: string): string {\n // Handle file paths\n if (identifier.includes(\"/\")) {\n const filename = identifier.split(\"/\").pop() || \"\";\n const parsed = parseStoryIdFromFilename(filename);\n if (parsed) {\n return parsed.id;\n }\n }\n\n // Handle filenames directly\n if (identifier.endsWith(\".md\")) {\n const parsed = parseStoryIdFromFilename(identifier);\n if (parsed) {\n return parsed.id;\n }\n }\n\n // Handle \"story-4-1\" or \"4-1\" format\n const cleaned = identifier.replace(/^story-/i, \"\");\n\n // Convert \"4-1\" to \"4.1\"\n if (cleaned.includes(\"-\") && !cleaned.includes(\".\")) {\n const parts = cleaned.split(\"-\");\n if (parts.length >= 2 && /^\\d+$/.test(parts[0]) && /^\\d+$/.test(parts[1])) {\n return `${parts[0]}.${parts[1]}`;\n }\n }\n\n return cleaned;\n}\n\n/**\n * Check if a filename matches a story pattern.\n * Used for filtering directory listings.\n */\nexport function isStoryFile(filename: string): boolean {\n return STORY_PATTERN.test(filename);\n}\n\n/**\n * Extract story ID from a finding ID.\n *\n * Handles multiple formats from different sources:\n * - story-{epic}-{num}-*: \"story-2-3-high-1\" → \"2.3\" (test/legacy format)\n * - S{storyId}-*: \"S2.3-SEC-1\" → \"2.3\" (Oracle storyFindings format)\n * - {storyId}-*: \"4.5-L1\" → \"4.5\" (direct story prefix)\n * - {epic}-{num}-*: \"2-3-high-1\" → \"2.3\" (dash-separated)\n *\n * Falls back to provided default for IDs without story info:\n * - \"high-1\", \"debate-3\", \"SEC-1\" → uses fallback\n *\n * @param findingId - The finding ID to parse\n * @param fallback - Default story ID if not extractable (typically session identifier)\n * @returns Normalized story ID (e.g., \"4.5\")\n */\nexport function extractStoryIdFromFindingId(findingId: string, fallback: string): string {\n // Pattern 1: story-{epic}-{num}-* (legacy/test format)\n // e.g., \"story-2-3-high-1\" → \"2.3\"\n const storyPrefixMatch = findingId.match(/^story-?(\\d+)[.-](\\d+[a-z]?)/i);\n if (storyPrefixMatch) {\n return `${storyPrefixMatch[1]}.${storyPrefixMatch[2]}`;\n }\n\n // Pattern 2: S{storyId}-* (Oracle storyFindings format)\n // e.g., \"S2.3-SEC-1\" → \"2.3\", \"S4.5a-LOG-1\" → \"4.5a\"\n const oracleMatch = findingId.match(/^S(\\d+)[.](\\d+[a-z]?)-/i);\n if (oracleMatch) {\n return `${oracleMatch[1]}.${oracleMatch[2]}`;\n }\n\n // Pattern 3: {storyId}-* (direct story ID prefix with dot)\n // e.g., \"4.5-L1\" → \"4.5\", \"2.3a-P1\" → \"2.3a\"\n const dotMatch = findingId.match(/^(\\d+)[.](\\d+[a-z]?)-/);\n if (dotMatch) {\n return `${dotMatch[1]}.${dotMatch[2]}`;\n }\n\n // Pattern 4: {epic}-{num}-* (dash-separated, no \"story\" prefix)\n // e.g., \"2-3-high-1\" → \"2.3\"\n // Must have something after the second number to distinguish from story IDs\n const dashMatch = findingId.match(/^(\\d+)-(\\d+[a-z]?)-[a-zA-Z]/);\n if (dashMatch) {\n return `${dashMatch[1]}.${dashMatch[2]}`;\n }\n\n // No story ID found in finding ID - use fallback\n // This handles: \"high-1\", \"debate-3\", \"SEC-1\", \"LOG-2\", etc.\n return normalizeStoryId(fallback);\n}\n\n/**\n * Get the expected filename patterns for a story ID.\n * Useful for error messages.\n *\n * @param storyId - Normalized story ID (e.g., \"4.1\")\n * @returns Array of example patterns\n */\nexport function getStoryFilenamePatterns(storyId: string): string[] {\n const [epic, number] = storyId.split(\".\");\n return [\n `story-${epic}-${number}.md`,\n `story-${epic}-${number}-*.md`,\n `${epic}-${number}.md`,\n `${epic}-${number}-*.md`,\n ];\n}\n\n/**\n * Strip @ prefix if present (OpenCode file reference syntax).\n * OpenCode uses @path/to/file to reference files in prompts.\n *\n * @example\n * stripAtPrefix(\"@docs/stories/story-4-1.md\") // \"docs/stories/story-4-1.md\"\n * stripAtPrefix(\"4.1\") // \"4.1\"\n * stripAtPrefix(\"story-4-1\") // \"story-4-1\"\n */\nexport function stripAtPrefix(identifier: string): string {\n return identifier.startsWith(\"@\") ? identifier.slice(1) : identifier;\n}\n\n/**\n * Check if identifier looks like a file path (vs a story ID).\n * Does NOT check if file exists - just pattern detection.\n *\n * @example\n * looksLikeFilePath(\"docs/stories/story-4-1.md\") // true\n * looksLikeFilePath(\"./story-4-1.md\") // true\n * looksLikeFilePath(\"/absolute/path/story.md\") // true\n * looksLikeFilePath(\"4.1\") // false\n * looksLikeFilePath(\"story-4-1\") // false\n */\nexport function looksLikeFilePath(identifier: string): boolean {\n // Contains path separator (forward or back slash)\n const hasPathSeparator = identifier.includes(\"/\") || identifier.includes(\"\\\\\");\n\n // Ends with .md extension\n const hasMdExtension = identifier.endsWith(\".md\");\n\n // Starts with ./ or ../ (relative path indicators)\n const hasRelativePrefix = identifier.startsWith(\"./\") || identifier.startsWith(\"../\");\n\n // Starts with / (absolute path on Unix)\n const hasAbsolutePrefix = identifier.startsWith(\"/\");\n\n // It's a file path if it has path separators, or has .md extension with relative/absolute prefix\n return hasPathSeparator || (hasMdExtension && (hasRelativePrefix || hasAbsolutePrefix));\n}\n\n/**\n * Load story content directly from a file path.\n * Extracts story ID from filename for tracking.\n *\n * @param filePath - Absolute or resolved path to the story file\n * @returns Story content with metadata, or null if file doesn't exist\n */\nexport async function loadStoryFromPath(\n filePath: string\n): Promise<{ content: string; path: string; filename: string; storyId: string } | null> {\n if (!existsSync(filePath)) {\n return null;\n }\n\n const filename = basename(filePath);\n const parsed = parseStoryIdFromFilename(filename);\n\n // Extract story ID from filename, or normalize the filename itself\n const storyId = parsed?.id ?? normalizeStoryId(filename);\n\n try {\n const content = await readFile(filePath, \"utf-8\");\n return { content, path: filePath, filename, storyId };\n } catch {\n return null;\n }\n}\n\n/**\n * Result of resolving a story identifier.\n */\nexport interface ResolvedStory {\n /** Story file content */\n content: string;\n /** Full path to the story file */\n path: string;\n /** Original filename */\n filename: string;\n /** Normalized story ID (e.g., \"4.1\") */\n storyId: string;\n}\n\n/**\n * Resolve a story identifier that might be a file path or story ID.\n *\n * Resolution order:\n * 1. Strip @ prefix if present (OpenCode file reference syntax)\n * 2. If it looks like a file path:\n * a. Try as absolute path\n * b. Try relative to projectRoot\n * 3. Fall back to searching in storiesDir (original behavior)\n *\n * @param storiesDir - Directory containing story files (for fallback)\n * @param identifier - Story ID (e.g., \"4.1\") or file path (e.g., \"docs/stories/story-4-1.md\")\n * @param projectRoot - Project root for resolving relative paths\n * @param logger - Optional logger for warnings\n * @returns Resolved story or null if not found\n *\n * @example\n * // File path (absolute)\n * await resolveStoryIdentifier(storiesDir, \"/home/user/project/docs/story-4-1.md\", projectRoot)\n *\n * // File path (relative)\n * await resolveStoryIdentifier(storiesDir, \"docs/stories/story-4-1.md\", projectRoot)\n *\n * // OpenCode @ reference\n * await resolveStoryIdentifier(storiesDir, \"@docs/stories/story-4-1.md\", projectRoot)\n *\n * // Story ID (fallback to storiesDir search)\n * await resolveStoryIdentifier(storiesDir, \"4.1\", projectRoot)\n */\nexport async function resolveStoryIdentifier(\n storiesDir: string,\n identifier: string,\n projectRoot?: string,\n logger?: { warn: (msg: string) => void }\n): Promise<ResolvedStory | null> {\n // 1. Strip @ prefix if present\n const cleaned = stripAtPrefix(identifier);\n\n // 2. Check if it looks like a file path\n if (looksLikeFilePath(cleaned)) {\n // 2a. Try as absolute path (or path that exists as-is)\n if (existsSync(cleaned)) {\n const result = await loadStoryFromPath(cleaned);\n if (result) return result;\n }\n\n // 2b. Try relative to project root\n if (projectRoot) {\n const absolutePath = resolve(projectRoot, cleaned);\n if (existsSync(absolutePath)) {\n const result = await loadStoryFromPath(absolutePath);\n if (result) return result;\n }\n }\n\n // File path was provided but doesn't exist - still try storiesDir as fallback\n // This handles cases where user provides \"story-4-1.md\" without full path\n }\n\n // 3. Fall back to storiesDir search (original behavior)\n const result = await loadStoryContent(storiesDir, cleaned, logger);\n if (result) {\n return {\n ...result,\n storyId: normalizeStoryId(cleaned),\n };\n }\n\n return null;\n}\n","import { readFile, writeFile } from \"node:fs/promises\";\nimport type {\n BmadSection,\n BmadTask,\n OpenCodeTodo,\n ParsedTodoId,\n TodoMatchResult,\n TodoPriority,\n TodoStatus,\n} from \"../../shared/types.js\";\nimport { TODO_MATCH_THRESHOLDS } from \"../../shared/types.js\";\n\nexport const ATHENA_SEPARATOR = \"Δ\";\n\nconst BMAD_TODO_PATTERN = /^\\s*\\[[\\d.]+Δ/;\n\nconst CHECKBOX_PATTERN = /^(\\s*)- \\[([ xX])\\] (.+)$/;\n\nconst SECTION_HEADERS: Record<string, BmadSection> = {\n \"acceptance criteria\": \"ac\",\n \"tasks / subtasks\": \"tasks\",\n \"tasks/subtasks\": \"tasks\",\n tasks: \"tasks\",\n subtasks: \"tasks\",\n \"implementation notes\": \"impl-notes\",\n};\n\nconst SECTION_LABELS: Record<BmadSection, string> = {\n ac: \"AC\",\n tasks: \"Task\",\n \"impl-notes\": \"Fix\",\n};\n\nexport function parseBmadTasks(content: string, storyId: string): BmadTask[] {\n const lines = content.split(\"\\n\");\n const tasks: BmadTask[] = [];\n\n let currentSection: BmadSection | null = null;\n let sectionIndex = 0;\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n\n const headerMatch = line.match(/^##\\s+(.+)$/);\n if (headerMatch) {\n const headerText = headerMatch[1].trim().toLowerCase();\n const matchedSection = Object.entries(SECTION_HEADERS).find(([key]) =>\n headerText.startsWith(key)\n );\n\n if (matchedSection) {\n currentSection = matchedSection[1];\n sectionIndex = 0;\n } else {\n currentSection = null;\n }\n continue;\n }\n\n if (!currentSection) continue;\n\n const checkboxMatch = line.match(CHECKBOX_PATTERN);\n if (!checkboxMatch) continue;\n\n sectionIndex++;\n const [, indent, checkState, taskText] = checkboxMatch;\n const checked = checkState.toLowerCase() === \"x\";\n const priority = detectPriority(taskText, currentSection);\n\n tasks.push({\n id: `${storyId}:${currentSection}:${i}`,\n storyId,\n section: currentSection,\n sectionIndex,\n lineNumber: i,\n content: taskText.trim(),\n checked,\n priority,\n indent: indent.length,\n });\n }\n\n return tasks;\n}\n\nfunction detectPriority(content: string, section: BmadSection): TodoPriority {\n const lower = content.toLowerCase();\n\n if (lower.includes(\"priority: critical\") || lower.includes(\"critical:\")) {\n return \"high\";\n }\n if (lower.includes(\"priority: high\")) {\n return \"high\";\n }\n if (lower.includes(\"priority: medium\")) {\n return \"medium\";\n }\n if (lower.includes(\"priority: low\")) {\n return \"low\";\n }\n\n if (lower.includes(\"must\")) {\n return \"high\";\n }\n if (lower.includes(\"should\")) {\n return \"medium\";\n }\n if (lower.includes(\"could\")) {\n return \"low\";\n }\n\n switch (section) {\n case \"ac\":\n return \"high\";\n case \"tasks\":\n return \"medium\";\n case \"impl-notes\":\n return \"medium\";\n }\n}\n\nexport function bmadTasksToTodos(tasks: BmadTask[]): OpenCodeTodo[] {\n return tasks.map((task) => {\n const label = SECTION_LABELS[task.section];\n const prefix = `[${task.storyId}${ATHENA_SEPARATOR}${label}${task.sectionIndex}]`;\n const indentation = \" \".repeat(task.indent);\n const status: TodoStatus = task.checked ? \"completed\" : \"pending\";\n\n return {\n id: task.id,\n content: `${indentation}${prefix} ${task.content}`,\n status,\n priority: task.priority,\n };\n });\n}\n\nexport function parseTodoId(todoId: string): ParsedTodoId | null {\n const parts = todoId.split(\":\");\n if (parts.length !== 3) return null;\n\n const [storyId, section, lineStr] = parts;\n const lineHint = Number.parseInt(lineStr, 10);\n\n if (!storyId || !section || Number.isNaN(lineHint)) return null;\n\n const validSections: BmadSection[] = [\"ac\", \"tasks\", \"impl-notes\"];\n if (!validSections.includes(section as BmadSection)) return null;\n\n return {\n storyId,\n section: section as BmadSection,\n lineHint,\n };\n}\n\nexport function isBmadTodo(todo: OpenCodeTodo): boolean {\n return BMAD_TODO_PATTERN.test(todo.content);\n}\n\nexport function extractStoryIdFromContent(content: string): string | null {\n const match = content.match(/^\\s*\\[([\\d.]+)Δ/);\n return match ? match[1] : null;\n}\n\nexport async function findCheckboxLine(\n storyPath: string,\n taskContent: string,\n lineHint: number\n): Promise<number | null> {\n const content = await readFile(storyPath, \"utf-8\");\n const lines = content.split(\"\\n\");\n\n const searchText = extractTaskText(taskContent);\n if (!searchText) return null;\n\n if (lineHint >= 0 && lineHint < lines.length) {\n if (matchesCheckbox(lines[lineHint], searchText)) {\n return lineHint;\n }\n }\n\n const searchRadius = 15;\n const startNearby = Math.max(0, lineHint - searchRadius);\n const endNearby = Math.min(lines.length, lineHint + searchRadius + 1);\n\n for (let i = startNearby; i < endNearby; i++) {\n if (i === lineHint) continue;\n if (matchesCheckbox(lines[i], searchText)) {\n return i;\n }\n }\n\n for (let i = 0; i < lines.length; i++) {\n if (i >= startNearby && i < endNearby) continue;\n if (matchesCheckbox(lines[i], searchText)) {\n return i;\n }\n }\n\n return null;\n}\n\nexport function extractTaskText(todoContent: string): string | null {\n const match = todoContent.match(/^\\s*\\[[\\d.]+Δ\\w+\\d*\\]\\s*(.+)$/);\n return match ? match[1].trim() : todoContent.trim();\n}\n\nfunction matchesCheckbox(line: string, searchText: string): boolean {\n const checkboxMatch = line.match(CHECKBOX_PATTERN);\n if (!checkboxMatch) return false;\n\n const checkboxText = checkboxMatch[3].trim().toLowerCase();\n const search = searchText.toLowerCase();\n\n if (checkboxText === search) return true;\n if (checkboxText.includes(search) || search.includes(checkboxText)) return true;\n\n const similarity = calculateSimilarity(checkboxText, search);\n return similarity > 0.7;\n}\n\nexport function calculateSimilarity(a: string, b: string): number {\n if (a === b) return 1;\n if (a.length === 0 || b.length === 0) return 0;\n\n const wordsA = new Set(a.split(/\\s+/));\n const wordsB = new Set(b.split(/\\s+/));\n\n let intersection = 0;\n for (const word of wordsA) {\n if (wordsB.has(word)) intersection++;\n }\n\n const union = wordsA.size + wordsB.size - intersection;\n return union > 0 ? intersection / union : 0;\n}\n\nexport async function updateBmadCheckbox(\n storyPath: string,\n lineNumber: number,\n checked: boolean\n): Promise<boolean> {\n const content = await readFile(storyPath, \"utf-8\");\n const lines = content.split(\"\\n\");\n\n if (lineNumber < 0 || lineNumber >= lines.length) {\n return false;\n }\n\n const line = lines[lineNumber];\n const checkboxMatch = line.match(CHECKBOX_PATTERN);\n\n if (!checkboxMatch) {\n return false;\n }\n\n if (checked) {\n lines[lineNumber] = line.replace(\"- [ ]\", \"- [x]\");\n } else {\n lines[lineNumber] = line.replace(/- \\[[xX]\\]/, \"- [ ]\");\n }\n\n await writeFile(storyPath, lines.join(\"\\n\"), \"utf-8\");\n return true;\n}\n\nexport function mergeTodos(\n existingTodos: OpenCodeTodo[],\n newBmadTodos: OpenCodeTodo[],\n loadingStoryId: string\n): OpenCodeTodo[] {\n const userTodos = existingTodos.filter((t) => !isBmadTodo(t));\n\n const otherStoryTodos = existingTodos.filter((t) => {\n if (!isBmadTodo(t)) return false;\n const todoStoryId = extractStoryIdFromContent(t.content);\n if (!todoStoryId) return false;\n return todoStoryId !== loadingStoryId && t.status !== \"completed\";\n });\n\n return [...userTodos, ...otherStoryTodos, ...newBmadTodos];\n}\n\nexport function findMatchingTodo(\n todo: OpenCodeTodo,\n previousTodos: OpenCodeTodo[]\n): TodoMatchResult {\n const idMatch = previousTodos.find((t) => t.id === todo.id);\n if (idMatch) {\n return { matched: idMatch, matchType: \"id\", confidence: 1.0 };\n }\n\n const todoText = extractTaskText(todo.content);\n if (!todoText) {\n return { matched: null, matchType: \"none\", confidence: 0 };\n }\n\n const bmadTodos = previousTodos.filter(isBmadTodo);\n\n for (const prev of bmadTodos) {\n const prevText = extractTaskText(prev.content);\n if (prevText && prevText.toLowerCase() === todoText.toLowerCase()) {\n return { matched: prev, matchType: \"exact-content\", confidence: 0.95 };\n }\n }\n\n let bestMatch: { todo: OpenCodeTodo; similarity: number } | null = null;\n for (const prev of bmadTodos) {\n const prevText = extractTaskText(prev.content);\n if (!prevText) continue;\n\n const similarity = calculateSimilarity(prevText.toLowerCase(), todoText.toLowerCase());\n if (\n similarity >= TODO_MATCH_THRESHOLDS.WARN_USER &&\n similarity > (bestMatch?.similarity ?? 0)\n ) {\n bestMatch = { todo: prev, similarity };\n }\n }\n\n if (bestMatch) {\n return {\n matched: bestMatch.todo,\n matchType: \"similar-content\",\n confidence: bestMatch.similarity,\n };\n }\n\n return { matched: null, matchType: \"none\", confidence: 0 };\n}\n","import type { AthenaConfig, OpenCodeTodo } from \"../../shared/types.js\";\nimport { TODO_MATCH_THRESHOLDS } from \"../../shared/types.js\";\nimport type { StoryTracker } from \"../tracker/story-tracker.js\";\nimport { createPluginLogger } from \"../utils/plugin-logger.js\";\nimport { findStoryFile } from \"../utils/story-loader.js\";\nimport {\n bmadTasksToTodos,\n extractStoryIdFromContent,\n findCheckboxLine,\n findMatchingTodo,\n isBmadTodo,\n mergeTodos,\n parseBmadTasks,\n parseTodoId,\n updateBmadCheckbox,\n} from \"../utils/todo-sync.js\";\n\nconst log = createPluginLogger(\"todo-hooks\");\n\nexport interface TodoSyncPaths {\n storiesDir: string;\n}\n\nexport interface StoryLoadedResult {\n mergedTodos: OpenCodeTodo[];\n newBmadTodos: OpenCodeTodo[];\n}\n\nexport async function onStoryLoaded(\n tracker: StoryTracker,\n config: AthenaConfig,\n storyId: string,\n storyContent: string\n): Promise<StoryLoadedResult> {\n if (!config.features.todoSync) {\n return { mergedTodos: [], newBmadTodos: [] };\n }\n\n try {\n const tasks = parseBmadTasks(storyContent, storyId);\n const newBmadTodos = bmadTasksToTodos(tasks);\n\n const existingTodos = tracker.getCurrentTodos() || [];\n const mergedTodos = mergeTodos(existingTodos, newBmadTodos, storyId);\n\n await tracker.setCurrentTodos(mergedTodos);\n\n log.info(\"Synced BMAD tasks to todos\", {\n storyId,\n newTasks: tasks.length,\n totalTodos: mergedTodos.length,\n });\n\n return { mergedTodos, newBmadTodos };\n } catch (error) {\n log.warn(\"Failed to sync BMAD tasks\", { storyId, error });\n return { mergedTodos: [], newBmadTodos: [] };\n }\n}\n\nexport async function onTodoWritten(\n tracker: StoryTracker,\n config: AthenaConfig,\n paths: TodoSyncPaths,\n todos: OpenCodeTodo[]\n): Promise<void> {\n if (!config.features.todoSync) {\n return;\n }\n\n const previousTodos = tracker.getCurrentTodos() || [];\n log.debug(\"Processing todowrite for BMAD sync\", {\n incomingTodos: todos.length,\n trackedTodos: previousTodos.length,\n });\n\n let processed = 0;\n let matchedById = 0;\n let matchedByContent = 0;\n let lowConfidenceSkipped = 0;\n let updated = 0;\n\n for (const todo of todos) {\n const matchResult = findMatchingTodo(todo, previousTodos);\n\n if (matchResult.matchType === \"none\" || !matchResult.matched) {\n if (isBmadTodo(todo)) {\n log.debug(\"No match found for BMAD-formatted todo\", {\n todoId: todo.id,\n content: todo.content.slice(0, 50),\n });\n }\n continue;\n }\n\n processed++;\n const previous = matchResult.matched;\n\n if (matchResult.matchType === \"id\") {\n matchedById++;\n } else {\n matchedByContent++;\n log.debug(\"Matched todo by content\", {\n matchType: matchResult.matchType,\n confidence: `${Math.round(matchResult.confidence * 100)}%`,\n incomingContent: todo.content.slice(0, 40),\n matchedContent: previous.content.slice(0, 40),\n });\n }\n\n if (\n matchResult.matchType === \"similar-content\" &&\n matchResult.confidence < TODO_MATCH_THRESHOLDS.AUTO_UPDATE\n ) {\n lowConfidenceSkipped++;\n log.info(\"Low-confidence match skipped (requires explicit completion)\", {\n confidence: `${Math.round(matchResult.confidence * 100)}%`,\n threshold: `${Math.round(TODO_MATCH_THRESHOLDS.AUTO_UPDATE * 100)}%`,\n todoContent: todo.content.slice(0, 50),\n possibleMatch: previous.content.slice(0, 50),\n });\n continue;\n }\n\n const statusChanged = previous.status !== todo.status;\n if (!statusChanged) {\n continue;\n }\n\n log.debug(\"Todo status changed\", {\n matchType: matchResult.matchType,\n from: previous.status,\n to: todo.status,\n });\n\n const storyId = extractStoryIdFromContent(previous.content);\n const parsed = parseTodoId(previous.id);\n\n if (!storyId && !parsed) {\n log.debug(\"Could not determine story ID from matched todo\", {\n todoId: previous.id,\n content: previous.content.slice(0, 50),\n });\n continue;\n }\n\n const targetStoryId = storyId || parsed?.storyId;\n const lineHint = parsed?.lineHint ?? 0;\n\n if (!targetStoryId) {\n log.warn(\"No story ID found for BMAD todo\", {\n todoId: previous.id,\n content: previous.content,\n });\n continue;\n }\n\n try {\n const storyFile = await findStoryFile(paths.storiesDir, targetStoryId);\n if (!storyFile) {\n log.warn(\"Story file not found for BMAD todo\", {\n storyId: targetStoryId,\n storiesDir: paths.storiesDir,\n });\n continue;\n }\n\n const lineNumber = await findCheckboxLine(storyFile.path, previous.content, lineHint);\n\n if (lineNumber === null) {\n log.warn(\"Checkbox not found in BMAD file\", {\n storyPath: storyFile.path,\n content: previous.content.slice(0, 50),\n lineHint,\n });\n continue;\n }\n\n const checked = todo.status === \"completed\";\n const wasUpdated = await updateBmadCheckbox(storyFile.path, lineNumber, checked);\n\n if (wasUpdated) {\n updated++;\n log.info(\"Updated BMAD checkbox\", {\n storyId: targetStoryId,\n line: lineNumber,\n checked,\n matchType: matchResult.matchType,\n content: previous.content.slice(0, 50),\n });\n } else {\n log.warn(\"Failed to update checkbox\", {\n storyId: targetStoryId,\n line: lineNumber,\n });\n }\n } catch (error) {\n log.warn(\"Error updating BMAD checkbox\", {\n storyId: targetStoryId,\n error: String(error),\n });\n }\n }\n\n log.debug(\"BMAD sync complete\", {\n processed,\n matchedById,\n matchedByContent,\n lowConfidenceSkipped,\n checkboxesUpdated: updated,\n });\n\n await tracker.setCurrentTodos(todos);\n}\n","/**\n * Tool execution hooks\n *\n * Implements safety net warnings for git operations and BMAD todo synchronization.\n */\n\nimport type { PluginInput } from \"@opencode-ai/plugin\";\nimport type { AthenaConfig, OpenCodeTodo } from \"../../shared/types.js\";\nimport type { StoryTracker } from \"../tracker/story-tracker.js\";\nimport { getBmadPaths } from \"../utils/bmad-finder.js\";\nimport { createPluginLogger } from \"../utils/plugin-logger.js\";\nimport { onStoryLoaded, onTodoWritten } from \"./todo-hooks.js\";\n\nconst log = createPluginLogger(\"tool-hooks\");\n\ninterface BeforeHookInput {\n tool: string;\n sessionID: string;\n callID: string;\n}\n\ninterface BeforeHookOutput {\n args: unknown;\n}\n\ninterface AfterHookInput {\n tool: string;\n sessionID: string;\n callID: string;\n}\n\ninterface AfterHookOutput {\n title: string;\n output: string;\n metadata: unknown;\n}\n\n/**\n * Git write operations that modify repository state.\n * These require explicit user permission when autoGitOperations is disabled.\n */\nconst GIT_WRITE_COMMANDS = [\n \"git commit\",\n \"git push\",\n \"git checkout -b\",\n \"git branch \",\n \"git switch -c\",\n \"git switch --create\",\n \"git merge\",\n \"git rebase\",\n \"git cherry-pick\",\n \"git stash\",\n \"git tag\",\n \"git reset\",\n \"gh pr create\",\n \"gh pr edit\",\n \"gh pr merge\",\n \"gh pr close\",\n \"gh pr review\",\n \"gh issue create\",\n \"gh issue edit\",\n \"gh issue close\",\n \"gh release create\",\n \"gh release edit\",\n \"gh release delete\",\n];\n\nfunction getBashCommand(metadata: unknown): string {\n if (!metadata || typeof metadata !== \"object\") {\n return \"\";\n }\n\n const cmd = (metadata as Record<string, unknown>).command;\n return typeof cmd === \"string\" ? cmd : \"\";\n}\n\nfunction containsGitWriteCommand(command: string): boolean {\n const normalized = command.trim().toLowerCase();\n\n // Split by common shell separators to check each command segment\n // This prevents false positives from strings like: echo \"git commit\"\n const segments = normalized.split(/[;&|]+/).map((s) => s.trim());\n\n return segments.some((segment) =>\n GIT_WRITE_COMMANDS.some((gitCmd) => segment.startsWith(gitCmd.toLowerCase()))\n );\n}\n\nexport function createToolHooks(ctx: PluginInput, tracker: StoryTracker, config: AthenaConfig) {\n return {\n before: async (_input: BeforeHookInput, _output: BeforeHookOutput): Promise<void> => {\n return;\n },\n\n after: async (input: AfterHookInput, output: AfterHookOutput): Promise<void> => {\n if (!config.features.autoGitOperations && input.tool === \"bash\") {\n const command = getBashCommand(output.metadata);\n\n if (containsGitWriteCommand(command)) {\n log.warn(\"Git write operation detected\", { command: command.slice(0, 100) });\n output.output +=\n \"\\n\\n⚠️ ATHENA GIT OPERATIONS POLICY REMINDER:\\n\" +\n \"Git operations should only be performed when explicitly requested by the user.\\n\" +\n \"If this command was run automatically (not requested by the user), please:\\n\" +\n \"1. Ask the user before proceeding with further git operations\\n\" +\n \"2. Use athena_update_status() to track story progress instead of git commits\\n\" +\n \"\\n\" +\n \"To enable automatic git operations, set features.autoGitOperations=true in athena.json\";\n }\n }\n\n if (input.tool === \"athena_get_story\" && config.features.todoSync) {\n await handleStoryLoaded(ctx, tracker, config, input.sessionID, output);\n }\n\n if (input.tool === \"todowrite\" && config.features.todoSync) {\n await handleTodoWritten(ctx, tracker, config, output);\n }\n },\n };\n}\n\nasync function handleStoryLoaded(\n ctx: PluginInput,\n tracker: StoryTracker,\n config: AthenaConfig,\n sessionID: string,\n output: AfterHookOutput\n): Promise<void> {\n try {\n const result = JSON.parse(output.output);\n if (!result.storyId || !result.story) {\n log.debug(\"Story load response missing storyId or story content\");\n return;\n }\n\n log.debug(\"Processing story load for todo sync\", { storyId: result.storyId });\n\n const { newBmadTodos, mergedTodos } = await onStoryLoaded(\n tracker,\n config,\n result.storyId,\n result.story\n );\n\n if (newBmadTodos.length > 0) {\n result.todos = {\n hint: \"Call todowrite with these todos to populate your task list. Marking todos complete updates BMAD checkboxes automatically.\",\n items: newBmadTodos,\n };\n output.output = JSON.stringify(result, null, 2);\n\n log.debug(\"Injected BMAD todos into story response\", {\n storyId: result.storyId,\n newTodos: newBmadTodos.length,\n totalTracked: mergedTodos.length,\n });\n\n await autoInjectTodos(ctx, sessionID, newBmadTodos);\n } else {\n log.debug(\"No BMAD todos found in story\", { storyId: result.storyId });\n }\n } catch (error) {\n log.warn(\"Failed to process story for todo sync\", { error: String(error) });\n }\n}\n\nasync function autoInjectTodos(\n ctx: PluginInput,\n sessionID: string,\n todos: OpenCodeTodo[]\n): Promise<void> {\n const client = ctx.client as unknown as Record<string, unknown> | undefined;\n const session = client?.session as Record<string, unknown> | undefined;\n const updateFn = session?.update as ((args: unknown) => Promise<unknown>) | undefined;\n\n if (!updateFn) {\n log.debug(\"OpenCode client session.update API not available\");\n return;\n }\n\n try {\n await updateFn({\n path: { id: sessionID },\n body: {\n update: {\n sessionUpdate: \"plan\",\n entries: todos.map((todo) => ({\n priority: todo.priority || \"medium\",\n status: todo.status === \"cancelled\" ? \"completed\" : todo.status,\n content: todo.content,\n })),\n },\n },\n });\n\n log.debug(\"Auto-injected BMAD todos via OpenCode API\", { count: todos.length });\n } catch (error) {\n log.debug(\"Could not auto-inject todos (API call failed)\", {\n error: String(error),\n });\n }\n}\n\nasync function handleTodoWritten(\n ctx: PluginInput,\n tracker: StoryTracker,\n config: AthenaConfig,\n output: AfterHookOutput\n): Promise<void> {\n const todos = extractTodosFromOutput(output);\n\n if (!todos || todos.length === 0) {\n log.debug(\"No todos found in todowrite output\");\n return;\n }\n\n try {\n const paths = await getBmadPaths(ctx.directory, config);\n await onTodoWritten(tracker, config, { storiesDir: paths.storiesDir }, todos);\n } catch (error) {\n log.warn(\"Error processing todowrite for BMAD sync\", { error: String(error) });\n }\n}\n\nfunction extractTodosFromOutput(output: AfterHookOutput): OpenCodeTodo[] | null {\n const metadata = output.metadata as Record<string, unknown> | undefined;\n if (metadata?.todos && Array.isArray(metadata.todos)) {\n log.debug(\"Extracted todos from metadata\", { count: metadata.todos.length });\n return metadata.todos as OpenCodeTodo[];\n }\n\n try {\n const result = JSON.parse(output.output);\n if (Array.isArray(result)) {\n log.debug(\"Extracted todos from output (array)\", { count: result.length });\n return result as OpenCodeTodo[];\n }\n if (result?.todos && Array.isArray(result.todos)) {\n log.debug(\"Extracted todos from output.todos\", { count: result.todos.length });\n return result.todos as OpenCodeTodo[];\n }\n } catch {\n log.debug(\"Could not parse output as JSON\");\n }\n\n return null;\n}\n","import type { AthenaConfig } from \"../../shared/types.js\";\nimport type { StoryTracker } from \"../tracker/story-tracker.js\";\nimport { isBmadTodo } from \"../utils/todo-sync.js\";\n\ninterface CompactionInput {\n sessionID: string;\n}\n\ninterface CompactionOutput {\n context: string[];\n}\n\nexport function createCompactionHook(tracker: StoryTracker, config: AthenaConfig) {\n const storiesPath = config.bmad?.paths?.stories ?? \"docs/stories\";\n\n return async (_input: CompactionInput, output: CompactionOutput): Promise<void> => {\n const storyContext = await tracker.getCurrentStoryContext();\n const todos = tracker.getCurrentTodos();\n const currentStory = tracker.getCurrentStory();\n\n const parts: string[] = [];\n\n if (todos && todos.length > 0) {\n const bmadTodos = todos.filter((t) => isBmadTodo(t));\n const pending = bmadTodos.filter((t) => t.status === \"pending\");\n const inProgress = bmadTodos.filter((t) => t.status === \"in_progress\");\n\n if (bmadTodos.length > 0 && (pending.length > 0 || inProgress.length > 0)) {\n parts.push(\"## ⚠️ MANDATORY POST-COMPACTION PROTOCOL\");\n parts.push(\"\");\n parts.push(\"**STOP. Before doing ANYTHING else:**\");\n parts.push(\"1. Call `todoread` to get your current task list\");\n parts.push(\"2. Review the todos below and compare to any 'next steps' you see\");\n parts.push(\"3. If any todo is marked `in_progress`, complete it FIRST\");\n parts.push(\"4. The TODO LIST is your source of truth, not the compaction summary\");\n parts.push(\"\");\n\n // Show in-progress todos with prominent warning\n if (inProgress.length > 0) {\n parts.push(\"### 🔄 IN PROGRESS (Complete these FIRST):\");\n for (const todo of inProgress) {\n parts.push(`- ${todo.content}`);\n }\n parts.push(\"\");\n }\n\n // Show pending todos (top 10 by priority)\n if (pending.length > 0) {\n parts.push(\"### ⏳ PENDING (Work queue):\");\n const sortedPending = pending.sort((a, b) => {\n const priorityOrder = { high: 0, medium: 1, low: 2 };\n return priorityOrder[a.priority] - priorityOrder[b.priority];\n });\n\n const todosToShow = sortedPending.slice(0, 10);\n for (const todo of todosToShow) {\n const icon = todo.priority === \"high\" ? \"🔴\" : todo.priority === \"medium\" ? \"🟡\" : \"🟢\";\n parts.push(`${icon} ${todo.content}`);\n }\n\n if (pending.length > 10) {\n parts.push(` ... and ${pending.length - 10} more (call todoread for full list)`);\n }\n parts.push(\"\");\n }\n\n // Verification step\n parts.push(\"### ✅ VERIFICATION REQUIRED\");\n parts.push(\"Call `todoread` NOW to confirm this matches your working state.\");\n parts.push(\n \"If it doesn't match, the todo list takes priority over any 'next steps' in this summary.\"\n );\n parts.push(\"\");\n parts.push(\"---\");\n parts.push(\"\");\n }\n }\n\n // STORY CONTEXT (comes after todo protocol)\n if (storyContext) {\n parts.push(\"## OpenCode Athena - Current BMAD Story Context\");\n parts.push(\"\");\n parts.push(storyContext);\n if (currentStory) {\n const storyFileName = `story-${currentStory.id.replace(\".\", \"-\")}.md`;\n parts.push(`**File:** ${storiesPath}/${storyFileName}`);\n }\n parts.push(\"\");\n }\n\n // TODO SYNC DOCUMENTATION (how it works)\n if (todos && todos.length > 0) {\n const bmadTodos = todos.filter((t) => isBmadTodo(t));\n const pending = bmadTodos.filter((t) => t.status === \"pending\").length;\n const inProgress = bmadTodos.filter((t) => t.status === \"in_progress\").length;\n const completed = bmadTodos.filter((t) => t.status === \"completed\").length;\n\n if (bmadTodos.length > 0) {\n parts.push(\"## Todo Sync (BMAD ↔ Todos)\");\n parts.push(\"\");\n parts.push(`**Progress:** ${completed}/${bmadTodos.length} BMAD tasks complete`);\n parts.push(`**Remaining:** ${pending} pending, ${inProgress} in progress`);\n parts.push(\"\");\n parts.push(\"**How todos work:**\");\n parts.push(\"- Format: `[{storyId}Δ{section}] {task}`\");\n parts.push(\"- Marking a todo complete updates the BMAD file automatically\");\n parts.push(\"- For task details, read the story file\");\n parts.push(\"\");\n if (currentStory) {\n const storyFileName = `story-${currentStory.id.replace(\".\", \"-\")}.md`;\n parts.push(\"**To look up task context:**\");\n parts.push(\"```\");\n parts.push(`Read ${storiesPath}/${storyFileName}`);\n parts.push(\"```\");\n parts.push(\"\");\n }\n }\n }\n\n if (storyContext || (todos && todos.length > 0)) {\n parts.push(\n \"IMPORTANT: You are implementing a BMAD story. Use athena_get_story to reload full context if needed. Use athena_update_status to update the story status when complete.\"\n );\n parts.push(\"\");\n\n output.context.push(parts.join(\"\\n\"));\n }\n };\n}\n","import type {\n ComplexityRecommendation,\n ComplexityThresholds,\n ParsedTask,\n StoryComplexityAssessment,\n StoryMetrics,\n TaskEffortEstimate,\n TaskEffortLevel,\n} from \"../../shared/types.js\";\nimport { DEFAULT_COMPLEXITY_THRESHOLDS } from \"../../shared/types.js\";\nimport type { ParsedStory } from \"./story-parser.js\";\n\nconst HIGH_EFFORT_KEYWORDS = [\n \"implement\",\n \"create\",\n \"integrate\",\n \"architect\",\n \"design\",\n \"refactor\",\n \"migrate\",\n];\nconst MEDIUM_EFFORT_KEYWORDS = [\"add\", \"update\", \"extend\", \"modify\", \"configure\"];\nconst EXTERNAL_DEPENDENCY_KEYWORDS = [\n \"api\",\n \"endpoint\",\n \"service\",\n \"firebase\",\n \"database\",\n \"auth\",\n \"external\",\n];\nconst TESTING_KEYWORDS = [\"test\", \"integration\", \"e2e\", \"manual\", \"verify\", \"validation\"];\n\nconst VAGUE_PATTERNS = [\n /^(implement|create|add|build)\\s+\\w+$/i,\n /^(task|todo):\\s*\\w+$/i,\n /^(do|make|handle)\\s+.{1,20}$/i,\n];\n\nfunction isVagueDescription(desc: string): boolean {\n if (VAGUE_PATTERNS.some((p) => p.test(desc.trim()))) {\n return true;\n }\n const hasSpecifics = /\\.(ts|js|dart|py|md)|\\/|:\\d+|\\d{2,}/.test(desc);\n return desc.length < 30 && !hasSpecifics;\n}\n\nfunction pointsToEffort(points: number): TaskEffortLevel {\n if (points <= 1) return \"trivial\";\n if (points <= 2) return \"small\";\n if (points <= 3) return \"medium\";\n if (points <= 5) return \"large\";\n return \"xlarge\";\n}\n\nfunction mapToFibonacci(points: number): number {\n const fibScale = [1, 2, 3, 5, 8];\n return fibScale.reduce((prev, curr) =>\n Math.abs(curr - points) < Math.abs(prev - points) ? curr : prev\n );\n}\n\nexport function estimateTaskEffort(task: ParsedTask): TaskEffortEstimate {\n let rawPoints = 1;\n const signals: string[] = [];\n const descLower = task.description.toLowerCase();\n\n if (task.subtasks.length > 5) {\n rawPoints += 3;\n signals.push(`${task.subtasks.length} subtasks (high complexity)`);\n } else if (task.subtasks.length > 2) {\n rawPoints += 1;\n signals.push(`${task.subtasks.length} subtasks`);\n }\n\n if (isVagueDescription(task.description)) {\n rawPoints += 2;\n signals.push(\"Vague description - hidden complexity likely\");\n }\n\n if (HIGH_EFFORT_KEYWORDS.some((k) => descLower.includes(k))) {\n rawPoints += 2;\n signals.push(\"High-effort action keyword\");\n } else if (MEDIUM_EFFORT_KEYWORDS.some((k) => descLower.includes(k))) {\n rawPoints += 1;\n signals.push(\"Medium-effort action keyword\");\n }\n\n if (TESTING_KEYWORDS.some((k) => descLower.includes(k))) {\n rawPoints += 1;\n signals.push(\"Testing/verification required\");\n }\n\n if (task.subtasks.some((s) => s.description.includes(\"/\"))) {\n rawPoints += 1;\n signals.push(\"Multiple file paths mentioned\");\n }\n\n if (EXTERNAL_DEPENDENCY_KEYWORDS.some((k) => descLower.includes(k))) {\n rawPoints += 1;\n signals.push(\"External system integration\");\n }\n\n const points = mapToFibonacci(rawPoints);\n\n return {\n taskId: task.id,\n description: task.description,\n effort: pointsToEffort(points),\n points,\n signals,\n };\n}\n\nexport function calculateStoryMetrics(\n parsedStory: ParsedStory,\n fileSizeBytes: number\n): StoryMetrics {\n const subtaskCount = parsedStory.tasks.reduce((sum, task) => sum + task.subtasks.length, 0);\n\n return {\n taskCount: parsedStory.tasks.length,\n subtaskCount,\n acceptanceCriteriaCount: parsedStory.acceptanceCriteriaCount,\n storyFileSizeKB: Math.round(fileSizeBytes / 1024),\n lineCount: parsedStory.lineCount,\n };\n}\n\nexport function assessStoryComplexity(\n parsedStory: ParsedStory,\n fileSizeBytes: number,\n thresholds: ComplexityThresholds = DEFAULT_COMPLEXITY_THRESHOLDS\n): StoryComplexityAssessment {\n const metrics = calculateStoryMetrics(parsedStory, fileSizeBytes);\n const taskEfforts = parsedStory.tasks.map(estimateTaskEffort);\n const totalPoints = taskEfforts.reduce((sum, te) => sum + te.points, 0);\n\n const thresholdReasons: string[] = [];\n let requireDecomp = false;\n let suggestDecomp = false;\n\n if (metrics.taskCount >= thresholds.criticalTasks) {\n thresholdReasons.push(\n `Task count (${metrics.taskCount}) exceeds critical limit (${thresholds.criticalTasks})`\n );\n requireDecomp = true;\n } else if (metrics.taskCount >= thresholds.maxTasks) {\n thresholdReasons.push(\n `Task count (${metrics.taskCount}) exceeds recommended limit (${thresholds.maxTasks})`\n );\n suggestDecomp = true;\n }\n\n if (totalPoints >= thresholds.criticalPoints) {\n thresholdReasons.push(\n `Story points (${totalPoints}) exceed critical limit (${thresholds.criticalPoints})`\n );\n requireDecomp = true;\n } else if (totalPoints >= thresholds.maxPoints) {\n thresholdReasons.push(\n `Story points (${totalPoints}) exceed recommended limit (${thresholds.maxPoints})`\n );\n suggestDecomp = true;\n }\n\n if (metrics.storyFileSizeKB >= thresholds.criticalFileSizeKB) {\n thresholdReasons.push(\n `File size (${metrics.storyFileSizeKB}KB) exceeds critical limit (${thresholds.criticalFileSizeKB}KB)`\n );\n requireDecomp = true;\n } else if (metrics.storyFileSizeKB >= thresholds.maxFileSizeKB) {\n thresholdReasons.push(\n `File size (${metrics.storyFileSizeKB}KB) exceeds recommended limit (${thresholds.maxFileSizeKB}KB)`\n );\n suggestDecomp = true;\n }\n\n const recommendation: ComplexityRecommendation = requireDecomp\n ? \"require-decomposition\"\n : suggestDecomp\n ? \"suggest-decomposition\"\n : \"proceed\";\n\n const estimatedCompactions = Math.max(0, Math.floor((totalPoints - 8) / 8));\n\n return {\n storyId: parsedStory.storyId,\n filename: \"\",\n metrics,\n taskEfforts,\n totalPoints,\n exceedsThreshold: thresholdReasons.length > 0,\n thresholdReasons,\n recommendation,\n estimatedCompactions,\n };\n}\n\nexport function formatEffortBar(points: number): string {\n const filled = Math.min(points, 5);\n const empty = 5 - filled;\n return `[${\"■\".repeat(filled)}${\"□\".repeat(empty)}]`;\n}\n\nexport function formatComplexityReport(assessment: StoryComplexityAssessment): string {\n const lines: string[] = [];\n const {\n metrics,\n taskEfforts,\n totalPoints,\n recommendation,\n thresholdReasons,\n estimatedCompactions,\n } = assessment;\n\n const taskStatus = metrics.taskCount >= 12 ? \"🔴\" : metrics.taskCount >= 8 ? \"⚠️\" : \"✅\";\n const pointsStatus = totalPoints >= 13 ? \"🔴\" : totalPoints >= 8 ? \"⚠️\" : \"✅\";\n const sizeStatus =\n metrics.storyFileSizeKB >= 50 ? \"🔴\" : metrics.storyFileSizeKB >= 30 ? \"⚠️\" : \"✅\";\n\n lines.push(\"📊 COMPLEXITY ANALYSIS\");\n lines.push(\"━\".repeat(45));\n lines.push(`Tasks: ${metrics.taskCount} / 8 recommended ${taskStatus}`);\n lines.push(`Points: ${totalPoints} / 8 threshold ${pointsStatus}`);\n lines.push(`File size: ${metrics.storyFileSizeKB}KB / 30KB ${sizeStatus}`);\n lines.push(`Estimated compactions: ${estimatedCompactions}`);\n lines.push(\"\");\n\n lines.push(\"📋 TASK EFFORT BREAKDOWN\");\n lines.push(\"━\".repeat(45));\n for (const te of taskEfforts) {\n const desc =\n te.description.length > 35\n ? `${te.description.substring(0, 32)}...`\n : te.description.padEnd(35);\n lines.push(`Task ${te.taskId}: ${desc} ${formatEffortBar(te.points)} ${te.points} pts`);\n if (te.signals.length > 0) {\n lines.push(` └─ Signals: ${te.signals.join(\", \")}`);\n }\n }\n lines.push(`Total: ${totalPoints} story points`);\n lines.push(\"\");\n\n if (recommendation === \"require-decomposition\") {\n lines.push(\"🔴 DECOMPOSITION REQUIRED\");\n lines.push(\" This story exceeds safe implementation limits and will likely\");\n lines.push(\" require multiple context compactions.\");\n } else if (recommendation === \"suggest-decomposition\") {\n lines.push(\"🟡 DECOMPOSITION SUGGESTED\");\n lines.push(\" This story can be implemented but may require compaction.\");\n lines.push(\" Splitting is recommended for cleaner implementation.\");\n } else {\n lines.push(\"🟢 COMPLEXITY OK\");\n lines.push(\" This story is within recommended limits.\");\n }\n\n if (thresholdReasons.length > 0) {\n lines.push(\"\");\n lines.push(\"Threshold issues:\");\n for (const reason of thresholdReasons) {\n lines.push(` • ${reason}`);\n }\n }\n\n return lines.join(\"\\n\");\n}\n","import type { ParsedTask } from \"../../shared/types.js\";\n\nconst TASK_REGEX = /^-\\s*\\[([ xX])\\]\\s*Task\\s*(\\d+):\\s*(.+)$/;\nconst SUBTASK_REGEX = /^(\\s+)-\\s*\\[([ xX])\\]\\s*(\\d+\\.\\d+):\\s*(.+)$/;\nconst SUBTASK_ALT_REGEX = /^(\\s+)-\\s*\\[([ xX])\\]\\s*(.+)$/;\n\nexport interface ParsedStory {\n storyId: string;\n title: string;\n tasks: ParsedTask[];\n acceptanceCriteriaCount: number;\n hasDevNotes: boolean;\n devNotesStartLine: number | null;\n devNotesEndLine: number | null;\n rawContent: string;\n lineCount: number;\n}\n\nfunction isChecked(mark: string): boolean {\n return mark.toLowerCase() === \"x\";\n}\n\nexport function parseStoryTasks(content: string, storyId: string): ParsedStory {\n const lines = content.split(\"\\n\");\n const tasks: ParsedTask[] = [];\n let currentTask: ParsedTask | null = null;\n let subtaskCounter = 0;\n\n let title = \"\";\n const titleMatch = content.match(/^#\\s+(?:Story\\s+[\\d.]+:\\s*)?(.+)$/m);\n if (titleMatch) {\n title = titleMatch[1].trim();\n }\n\n let acceptanceCriteriaCount = 0;\n const acSection = content.match(/##\\s*Acceptance\\s*Criteria[\\s\\S]*?(?=##|$)/i);\n if (acSection) {\n const givenMatches = acSection[0].match(/\\*\\*Given\\*\\*/gi);\n acceptanceCriteriaCount = givenMatches ? givenMatches.length : 0;\n }\n\n let hasDevNotes = false;\n let devNotesStartLine: number | null = null;\n let devNotesEndLine: number | null = null;\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n const lineNumber = i + 1;\n\n if (/^##\\s*Dev\\s*Notes/i.test(line)) {\n hasDevNotes = true;\n devNotesStartLine = lineNumber;\n for (let j = i + 1; j < lines.length; j++) {\n if (/^##\\s+/.test(lines[j]) && !/^##\\s*Dev\\s*Notes/i.test(lines[j])) {\n devNotesEndLine = j;\n break;\n }\n }\n if (devNotesEndLine === null) {\n devNotesEndLine = lines.length;\n }\n }\n\n const taskMatch = line.match(TASK_REGEX);\n if (taskMatch) {\n if (currentTask) {\n tasks.push(currentTask);\n }\n currentTask = {\n id: taskMatch[2],\n description: taskMatch[3].trim(),\n subtasks: [],\n completed: isChecked(taskMatch[1]),\n lineNumber,\n };\n subtaskCounter = 0;\n continue;\n }\n\n if (currentTask) {\n const subtaskMatch = line.match(SUBTASK_REGEX);\n if (subtaskMatch) {\n currentTask.subtasks.push({\n id: subtaskMatch[3],\n description: subtaskMatch[4].trim(),\n completed: isChecked(subtaskMatch[2]),\n lineNumber,\n });\n continue;\n }\n\n const altSubtaskMatch = line.match(SUBTASK_ALT_REGEX);\n if (altSubtaskMatch && altSubtaskMatch[1].length >= 2) {\n subtaskCounter++;\n currentTask.subtasks.push({\n id: `${currentTask.id}.${subtaskCounter}`,\n description: altSubtaskMatch[3].trim(),\n completed: isChecked(altSubtaskMatch[2]),\n lineNumber,\n });\n continue;\n }\n\n if (/^-\\s*\\[/.test(line) && !/^\\s+-/.test(line)) {\n tasks.push(currentTask);\n currentTask = null;\n }\n }\n }\n\n if (currentTask) {\n tasks.push(currentTask);\n }\n\n return {\n storyId,\n title,\n tasks,\n acceptanceCriteriaCount,\n hasDevNotes,\n devNotesStartLine,\n devNotesEndLine,\n rawContent: content,\n lineCount: lines.length,\n };\n}\n\nexport function extractDevNotesForTasks(content: string, taskIds: string[]): string {\n const lines = content.split(\"\\n\");\n const relevantSections: string[] = [];\n\n let inDevNotes = false;\n let currentSection: string[] = [];\n let currentSectionHeader = \"\";\n\n for (const line of lines) {\n if (/^##\\s*Dev\\s*Notes/i.test(line)) {\n inDevNotes = true;\n continue;\n }\n\n if (inDevNotes) {\n if (/^##\\s+/.test(line) && !/^###/.test(line)) {\n inDevNotes = false;\n if (currentSection.length > 0) {\n relevantSections.push(currentSection.join(\"\\n\"));\n }\n break;\n }\n\n if (/^###\\s+/.test(line)) {\n if (currentSection.length > 0 && shouldIncludeSection(currentSectionHeader, taskIds)) {\n relevantSections.push(currentSection.join(\"\\n\"));\n }\n currentSection = [line];\n currentSectionHeader = line;\n } else if (currentSection.length > 0 || line.trim()) {\n currentSection.push(line);\n }\n }\n }\n\n if (currentSection.length > 0 && shouldIncludeSection(currentSectionHeader, taskIds)) {\n relevantSections.push(currentSection.join(\"\\n\"));\n }\n\n const commonSections = extractCommonDevNotes(content);\n const combined = [...commonSections, ...relevantSections].filter(Boolean);\n\n return combined.length > 0 ? `## Dev Notes\\n\\n${combined.join(\"\\n\\n\")}` : \"\";\n}\n\nfunction shouldIncludeSection(header: string, taskIds: string[]): boolean {\n const commonPatterns = [\n /complexity/i,\n /architecture/i,\n /technical.*requirement/i,\n /library.*framework/i,\n /file.*structure/i,\n /testing.*requirement/i,\n /previous.*story/i,\n /project.*context/i,\n /feature.*context/i,\n /reference/i,\n ];\n\n if (commonPatterns.some((p) => p.test(header))) {\n return true;\n }\n\n for (const taskId of taskIds) {\n if (header.includes(`Task ${taskId}`) || header.includes(`Task${taskId}`)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction extractCommonDevNotes(content: string): string[] {\n const sections: string[] = [];\n const lines = content.split(\"\\n\");\n\n let inDevNotes = false;\n let currentSection: string[] = [];\n let currentHeader = \"\";\n\n const commonHeaders = [\n /complexity.*assessment/i,\n /manual.*testing/i,\n /pre-existing.*code/i,\n /architecture.*compliance/i,\n /technical.*requirement/i,\n /library.*framework/i,\n /file.*structure/i,\n /testing.*requirement/i,\n /previous.*story/i,\n /project.*context/i,\n /feature.*context/i,\n /reference/i,\n ];\n\n for (const line of lines) {\n if (/^##\\s*Dev\\s*Notes/i.test(line)) {\n inDevNotes = true;\n continue;\n }\n\n if (inDevNotes) {\n if (/^##\\s+/.test(line) && !/^###/.test(line)) {\n if (currentSection.length > 0 && commonHeaders.some((p) => p.test(currentHeader))) {\n sections.push(currentSection.join(\"\\n\"));\n }\n break;\n }\n\n if (/^###\\s+/.test(line)) {\n if (currentSection.length > 0 && commonHeaders.some((p) => p.test(currentHeader))) {\n sections.push(currentSection.join(\"\\n\"));\n }\n currentSection = [line];\n currentHeader = line;\n } else if (currentSection.length > 0 || line.trim()) {\n currentSection.push(line);\n }\n }\n }\n\n if (currentSection.length > 0 && commonHeaders.some((p) => p.test(currentHeader))) {\n sections.push(currentSection.join(\"\\n\"));\n }\n\n return sections;\n}\n\nexport function generateTaskSection(tasks: ParsedTask[]): string {\n const lines: string[] = [\"## Tasks / Subtasks\", \"\"];\n\n for (const task of tasks) {\n const checkbox = task.completed ? \"[x]\" : \"[ ]\";\n lines.push(`- ${checkbox} Task ${task.id}: ${task.description}`);\n\n for (const subtask of task.subtasks) {\n const subCheckbox = subtask.completed ? \"[x]\" : \"[ ]\";\n lines.push(` - ${subCheckbox} ${subtask.id}: ${subtask.description}`);\n }\n\n lines.push(\"\");\n }\n\n return lines.join(\"\\n\");\n}\n","import type {\n DecompositionSplit,\n ParsedTask,\n TaskEffortEstimate,\n UserSplitConfig,\n} from \"../../shared/types.js\";\nimport type { ParsedStory } from \"./story-parser.js\";\nimport { extractDevNotesForTasks, generateTaskSection } from \"./story-parser.js\";\n\nconst TARGET_POINTS_PER_SPLIT = 8;\nconst MAX_TASKS_PER_SPLIT = 6;\n\ninterface TaskWithEffort {\n task: ParsedTask;\n effort: TaskEffortEstimate;\n}\n\nexport function generateDecompositionSuggestions(\n parsedStory: ParsedStory,\n taskEfforts: TaskEffortEstimate[]\n): DecompositionSplit[] {\n const tasksWithEffort: TaskWithEffort[] = parsedStory.tasks.map((task) => ({\n task,\n effort: taskEfforts.find((e) => e.taskId === task.id) || {\n taskId: task.id,\n description: task.description,\n effort: \"medium\" as const,\n points: 3,\n signals: [],\n },\n }));\n\n const groups = groupTasksByConcern(tasksWithEffort);\n const balanced = balanceGroups(groups, TARGET_POINTS_PER_SPLIT);\n const withDeps = analyzeDependencies(balanced);\n\n return withDeps.map((group, index) => ({\n suffix: String.fromCharCode(97 + index),\n title: inferGroupTitle(group.tasks),\n taskIds: group.tasks.map((t) => t.task.id),\n estimatedPoints: group.totalPoints,\n rationale: group.rationale,\n dependencies: group.dependencies,\n }));\n}\n\ninterface TaskGroup {\n tasks: TaskWithEffort[];\n totalPoints: number;\n rationale: string;\n dependencies: string[];\n}\n\nfunction groupTasksByConcern(tasks: TaskWithEffort[]): TaskGroup[] {\n const testingTasks: TaskWithEffort[] = [];\n const uiTasks: TaskWithEffort[] = [];\n const integrationTasks: TaskWithEffort[] = [];\n const coreTasks: TaskWithEffort[] = [];\n\n for (const t of tasks) {\n const desc = t.task.description.toLowerCase();\n if (/test|verify|integration test|e2e|manual test/.test(desc)) {\n testingTasks.push(t);\n } else if (/widget|screen|card|component|ui|view|button|dialog/.test(desc)) {\n uiTasks.push(t);\n } else if (/navigation|route|integration|connect|hook up/.test(desc)) {\n integrationTasks.push(t);\n } else {\n coreTasks.push(t);\n }\n }\n\n const groups: TaskGroup[] = [];\n\n if (coreTasks.length > 0) {\n groups.push({\n tasks: coreTasks,\n totalPoints: coreTasks.reduce((s, t) => s + t.effort.points, 0),\n rationale: \"Core implementation tasks\",\n dependencies: [],\n });\n }\n\n if (uiTasks.length > 0) {\n groups.push({\n tasks: uiTasks,\n totalPoints: uiTasks.reduce((s, t) => s + t.effort.points, 0),\n rationale: \"UI component tasks\",\n dependencies: [],\n });\n }\n\n if (integrationTasks.length > 0) {\n groups.push({\n tasks: integrationTasks,\n totalPoints: integrationTasks.reduce((s, t) => s + t.effort.points, 0),\n rationale: \"Integration and wiring tasks\",\n dependencies: [],\n });\n }\n\n if (testingTasks.length > 0) {\n groups.push({\n tasks: testingTasks,\n totalPoints: testingTasks.reduce((s, t) => s + t.effort.points, 0),\n rationale: \"Testing and verification tasks\",\n dependencies: [],\n });\n }\n\n if (groups.length === 0 && tasks.length > 0) {\n return balanceByPoints(tasks, TARGET_POINTS_PER_SPLIT);\n }\n\n return groups;\n}\n\nfunction balanceGroups(groups: TaskGroup[], targetPoints: number): TaskGroup[] {\n const result: TaskGroup[] = [];\n\n for (const group of groups) {\n if (group.totalPoints <= targetPoints && group.tasks.length <= MAX_TASKS_PER_SPLIT) {\n result.push(group);\n } else {\n const subGroups = balanceByPoints(group.tasks, targetPoints);\n for (let i = 0; i < subGroups.length; i++) {\n result.push({\n ...subGroups[i],\n rationale: `${group.rationale} (part ${i + 1})`,\n });\n }\n }\n }\n\n return result;\n}\n\nfunction balanceByPoints(tasks: TaskWithEffort[], targetPoints: number): TaskGroup[] {\n const groups: TaskGroup[] = [];\n let currentGroup: TaskWithEffort[] = [];\n let currentPoints = 0;\n\n const sortedTasks = [...tasks].sort((a, b) => {\n const aNum = Number.parseInt(a.task.id, 10);\n const bNum = Number.parseInt(b.task.id, 10);\n return aNum - bNum;\n });\n\n for (const task of sortedTasks) {\n if (\n currentPoints + task.effort.points > targetPoints &&\n currentGroup.length > 0 &&\n currentGroup.length < MAX_TASKS_PER_SPLIT\n ) {\n groups.push({\n tasks: currentGroup,\n totalPoints: currentPoints,\n rationale: \"Balanced by effort\",\n dependencies: [],\n });\n currentGroup = [];\n currentPoints = 0;\n }\n\n currentGroup.push(task);\n currentPoints += task.effort.points;\n\n if (currentGroup.length >= MAX_TASKS_PER_SPLIT) {\n groups.push({\n tasks: currentGroup,\n totalPoints: currentPoints,\n rationale: \"Balanced by effort\",\n dependencies: [],\n });\n currentGroup = [];\n currentPoints = 0;\n }\n }\n\n if (currentGroup.length > 0) {\n groups.push({\n tasks: currentGroup,\n totalPoints: currentPoints,\n rationale: \"Balanced by effort\",\n dependencies: [],\n });\n }\n\n return groups;\n}\n\nfunction analyzeDependencies(groups: TaskGroup[]): TaskGroup[] {\n if (groups.length <= 1) return groups;\n\n const result = groups.map((g, i) => ({\n ...g,\n dependencies: [] as string[],\n index: i,\n }));\n\n for (let i = 1; i < result.length; i++) {\n const group = result[i];\n const hasTestingOrIntegration = group.tasks.some((t) => {\n const desc = t.task.description.toLowerCase();\n return /test|integration|verify|navigation|route|hook/.test(desc);\n });\n\n if (hasTestingOrIntegration) {\n for (let j = 0; j < i; j++) {\n group.dependencies.push(String.fromCharCode(97 + j));\n }\n }\n }\n\n return result;\n}\n\nfunction inferGroupTitle(tasks: TaskWithEffort[]): string {\n if (tasks.length === 0) return \"Empty Group\";\n\n const firstTask = tasks[0].task.description;\n const commonKeywords = extractKeywords(tasks.map((t) => t.task.description));\n\n if (commonKeywords.length > 0) {\n return commonKeywords.slice(0, 3).join(\" \");\n }\n\n const truncated = firstTask.length > 40 ? `${firstTask.substring(0, 37)}...` : firstTask;\n return truncated;\n}\n\nfunction extractKeywords(descriptions: string[]): string[] {\n const stopWords = new Set([\n \"the\",\n \"a\",\n \"an\",\n \"and\",\n \"or\",\n \"for\",\n \"to\",\n \"in\",\n \"on\",\n \"with\",\n \"task\",\n \"create\",\n \"add\",\n \"implement\",\n \"update\",\n ]);\n\n const wordCounts = new Map<string, number>();\n\n for (const desc of descriptions) {\n const words = desc.toLowerCase().split(/\\s+/);\n const seen = new Set<string>();\n for (const word of words) {\n const clean = word.replace(/[^a-z]/g, \"\");\n if (clean.length > 2 && !stopWords.has(clean) && !seen.has(clean)) {\n seen.add(clean);\n wordCounts.set(clean, (wordCounts.get(clean) || 0) + 1);\n }\n }\n }\n\n const sorted = [...wordCounts.entries()]\n .filter(([, count]) => count >= Math.ceil(descriptions.length / 2))\n .sort((a, b) => b[1] - a[1])\n .map(([word]) => word);\n\n return sorted;\n}\n\nexport function validateSplits(\n originalTasks: ParsedTask[],\n splits: UserSplitConfig[] | DecompositionSplit[]\n): { valid: boolean; missingTasks: string[]; duplicatedTasks: string[] } {\n const allSplitTaskIds = new Set<string>();\n const duplicated: string[] = [];\n\n for (const split of splits) {\n for (const taskId of split.taskIds) {\n if (allSplitTaskIds.has(taskId)) {\n duplicated.push(taskId);\n }\n allSplitTaskIds.add(taskId);\n }\n }\n\n const originalTaskIds = new Set(originalTasks.map((t) => t.id));\n const missing = [...originalTaskIds].filter((id) => !allSplitTaskIds.has(id));\n\n return {\n valid: missing.length === 0 && duplicated.length === 0,\n missingTasks: missing,\n duplicatedTasks: duplicated,\n };\n}\n\nexport function generateSubStoryContent(\n originalContent: string,\n parsedStory: ParsedStory,\n split: DecompositionSplit | UserSplitConfig,\n splitIndex: number,\n totalSplits: number,\n originalStoryId: string\n): string {\n const tasksForSplit = parsedStory.tasks.filter((t) => split.taskIds.includes(t.id));\n const devNotes = extractDevNotesForTasks(originalContent, split.taskIds);\n const taskSection = generateTaskSection(tasksForSplit);\n\n const suffix = \"suffix\" in split ? split.suffix : String.fromCharCode(97 + splitIndex);\n const title =\n \"title\" in split && split.title\n ? split.title\n : inferGroupTitle(\n tasksForSplit.map((t) => ({\n task: t,\n effort: {\n taskId: t.id,\n description: t.description,\n effort: \"medium\" as const,\n points: 3,\n signals: [],\n },\n }))\n );\n\n const storyMatch = originalContent.match(/^#\\s+(?:Story\\s+[\\d.]+:\\s*)?(.+)$/m);\n const originalTitle = storyMatch ? storyMatch[1].trim() : \"Untitled Story\";\n\n const statusMatch = originalContent.match(/^Status:\\s*(.+)$/m);\n const status = statusMatch ? statusMatch[1].trim() : \"ready-for-dev\";\n\n const storyUserSection = originalContent.match(\n /##\\s*Story[\\s\\S]*?(?=##\\s*Acceptance|##\\s*Tasks|$)/i\n );\n const userStory = storyUserSection ? storyUserSection[0].trim() : \"\";\n\n const acSection = originalContent.match(\n /##\\s*Acceptance\\s*Criteria[\\s\\S]*?(?=##\\s*Tasks|##\\s*Dev|$)/i\n );\n const acceptanceCriteria = acSection ? acSection[0].trim() : \"\";\n\n const lines: string[] = [\n `# Story ${originalStoryId}${suffix}: ${originalTitle} - ${title}`,\n \"\",\n `Status: ${status === \"done\" ? \"ready-for-dev\" : status}`,\n \"\",\n `> **Note:** This story was decomposed from Story ${originalStoryId} (part ${splitIndex + 1} of ${totalSplits})`,\n \"\",\n ];\n\n if (userStory) {\n lines.push(userStory);\n lines.push(\"\");\n }\n\n if (acceptanceCriteria) {\n lines.push(acceptanceCriteria);\n lines.push(\"\");\n }\n\n lines.push(taskSection);\n\n if (devNotes) {\n lines.push(\"\");\n lines.push(devNotes);\n }\n\n return lines.join(\"\\n\");\n}\n\nexport function formatDecompositionSuggestion(\n splits: DecompositionSplit[],\n storyId: string\n): string {\n const lines: string[] = [];\n\n lines.push(\"🔀 SUGGESTED DECOMPOSITION\");\n lines.push(\"━\".repeat(45));\n lines.push(\"\");\n\n for (const split of splits) {\n lines.push(`Story ${storyId}${split.suffix}: ${split.title}`);\n lines.push(`├─ Tasks: ${split.taskIds.join(\", \")}`);\n lines.push(`├─ Points: ~${split.estimatedPoints}`);\n lines.push(`├─ Rationale: ${split.rationale}`);\n if (split.dependencies.length > 0) {\n lines.push(`└─ Dependencies: ${split.dependencies.map((d) => `${storyId}${d}`).join(\", \")}`);\n } else {\n lines.push(\"└─ Dependencies: None\");\n }\n lines.push(\"\");\n }\n\n const totalTasks = splits.reduce((sum, s) => sum + s.taskIds.length, 0);\n lines.push(\"VERIFICATION:\");\n lines.push(`✅ All ${totalTasks} tasks accounted for`);\n lines.push(\"✅ No duplicate tasks\");\n lines.push(\"✅ Dependencies correctly ordered\");\n\n return lines.join(\"\\n\");\n}\n\nexport function getSubStoryFilename(originalFilename: string, suffix: string): string {\n const match = originalFilename.match(/^(\\d+-\\d+)(-.*)?\\.md$/);\n if (match) {\n const storyPart = match[1];\n const titlePart = match[2] || \"\";\n return `${storyPart}${suffix}${titlePart}.md`;\n }\n const noExt = originalFilename.replace(/\\.md$/, \"\");\n return `${noExt}${suffix}.md`;\n}\n\nexport function getSubStoryId(originalStoryId: string, suffix: string): string {\n return `${originalStoryId}${suffix}`;\n}\n","import * as fs from \"node:fs/promises\";\nimport { type ToolDefinition, tool } from \"@opencode-ai/plugin\";\nimport type { PluginInput } from \"@opencode-ai/plugin\";\nimport type { AnalyzeStoryResult, AthenaConfig } from \"../../shared/types.js\";\nimport { getBmadPaths } from \"../utils/bmad-finder.js\";\nimport { createPluginLogger } from \"../utils/plugin-logger.js\";\nimport { assessStoryComplexity, formatComplexityReport } from \"../utils/story-complexity.js\";\nimport {\n formatDecompositionSuggestion,\n generateDecompositionSuggestions,\n} from \"../utils/story-decomposer.js\";\nimport { normalizeStoryId, resolveStoryIdentifier, stripAtPrefix } from \"../utils/story-loader.js\";\nimport { parseStoryTasks } from \"../utils/story-parser.js\";\n\nconst log = createPluginLogger(\"analyze-story\");\n\nexport function createAnalyzeStoryTool(ctx: PluginInput, config: AthenaConfig): ToolDefinition {\n return tool({\n description: `Analyze a BMAD story's complexity and suggest decomposition if needed.\n\nReturns:\n- Story metrics (task count, subtasks, file size)\n- Task-level effort estimates with signals\n- Total story points\n- Recommendation: proceed, suggest-decomposition, or require-decomposition\n- Suggested splits if decomposition is recommended\n\nUse this tool before implementing large stories to check if they should be split.`,\n\n args: {\n storyId: tool.schema.string().describe(\"Story ID (e.g., '3.2') or file path to analyze\"),\n },\n\n async execute(args): Promise<string> {\n const result = await analyzeStoryComplexity(ctx, config, args.storyId);\n\n if (!result.success) {\n return JSON.stringify(result, null, 2);\n }\n\n const lines: string[] = [];\n lines.push(formatComplexityReport(result.assessment));\n\n if (result.suggestedSplits && result.suggestedSplits.length > 0) {\n lines.push(\"\");\n lines.push(formatDecompositionSuggestion(result.suggestedSplits, result.storyId));\n lines.push(\"\");\n lines.push(\"What would you like to do?\");\n lines.push(\"[D] Decompose into sub-stories\");\n lines.push(\"[P] Proceed with full story anyway\");\n lines.push(\"[M] Modify decomposition groupings\");\n }\n\n return lines.join(\"\\n\");\n },\n });\n}\n\nasync function analyzeStoryComplexity(\n ctx: PluginInput,\n config: AthenaConfig,\n requestedStoryId: string\n): Promise<AnalyzeStoryResult> {\n log.debug(\"Analyzing story complexity\", { requestedStoryId });\n\n const paths = await getBmadPaths(ctx.directory, config);\n if (!paths.storiesDir) {\n return {\n success: false,\n storyId: requestedStoryId,\n filename: \"\",\n assessment: null as unknown as AnalyzeStoryResult[\"assessment\"],\n error: \"No stories directory found\",\n suggestion: \"Ensure BMAD is set up with a stories directory.\",\n };\n }\n\n const identifier = stripAtPrefix(requestedStoryId);\n const storyId = normalizeStoryId(identifier);\n\n const resolved = await resolveStoryIdentifier(paths.storiesDir, identifier, ctx.directory);\n if (!resolved) {\n return {\n success: false,\n storyId,\n filename: \"\",\n assessment: null as unknown as AnalyzeStoryResult[\"assessment\"],\n error: `Story not found: ${requestedStoryId}`,\n suggestion: \"Check the story ID or file path and try again.\",\n };\n }\n\n const storyContent = resolved.content;\n const storyFilename = resolved.filename;\n const storyPath = resolved.path;\n\n let fileSizeBytes: number;\n try {\n const stats = await fs.stat(storyPath);\n fileSizeBytes = stats.size;\n } catch {\n fileSizeBytes = Buffer.byteLength(storyContent, \"utf-8\");\n }\n\n const parsedStory = parseStoryTasks(storyContent, storyId);\n const assessment = assessStoryComplexity(parsedStory, fileSizeBytes);\n assessment.filename = storyFilename;\n\n let suggestedSplits: AnalyzeStoryResult[\"suggestedSplits\"];\n\n if (assessment.recommendation !== \"proceed\") {\n suggestedSplits = generateDecompositionSuggestions(parsedStory, assessment.taskEfforts);\n }\n\n log.info(\"Story analysis complete\", {\n storyId,\n taskCount: assessment.metrics.taskCount,\n totalPoints: assessment.totalPoints,\n recommendation: assessment.recommendation,\n suggestedSplits: suggestedSplits?.length || 0,\n });\n\n return {\n success: true,\n storyId,\n filename: storyFilename,\n assessment,\n suggestedSplits,\n };\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\n/**\n * Get version from package.json at runtime.\n * Handles both bundled (dist/) and development (src/) scenarios.\n */\nfunction getPackageVersion(): string {\n try {\n const currentDir = dirname(fileURLToPath(import.meta.url));\n\n const possiblePaths = [\n join(currentDir, \"..\", \"..\", \"package.json\"),\n join(currentDir, \"..\", \"..\", \"..\", \"package.json\"),\n ];\n\n for (const pkgPath of possiblePaths) {\n if (!existsSync(pkgPath)) continue;\n\n const content = readFileSync(pkgPath, \"utf-8\");\n const pkg = JSON.parse(content);\n if (pkg.version) return pkg.version;\n }\n\n return \"0.0.0\";\n } catch (error) {\n if (error instanceof SyntaxError) {\n console.error(\"[opencode-athena] Warning: package.json contains invalid JSON\");\n }\n return \"0.0.0\";\n }\n}\n\n/**\n * Current version of OpenCode Athena\n * Dynamically read from package.json\n */\nexport const VERSION = getPackageVersion();\n\n/**\n * Package name for CLI display\n */\nexport const PACKAGE_NAME = \"opencode-athena\";\n\n/**\n * CLI display name\n */\nexport const DISPLAY_NAME = \"OpenCode Athena\";\n\n/**\n * Tagline for CLI header\n */\nexport const TAGLINE = \"Strategic wisdom meets practical execution\";\n\n/**\n * Configuration paths\n */\nexport const CONFIG_PATHS = {\n /** Global OpenCode config directory */\n globalConfigDir: join(homedir(), \".config\", \"opencode\"),\n\n /** Global Athena config file */\n globalAthenaConfig: join(homedir(), \".config\", \"opencode\", \"athena.json\"),\n\n /** Global OpenCode config file */\n globalOpencodeConfig: join(homedir(), \".config\", \"opencode\", \"opencode.json\"),\n\n /** Global oh-my-opencode config file */\n globalOmoConfig: join(homedir(), \".config\", \"opencode\", \"oh-my-opencode.json\"),\n\n /** Commands directory */\n commandsDir: join(homedir(), \".config\", \"opencode\", \"command\"),\n\n /** Plugin directory */\n pluginDir: join(homedir(), \".config\", \"opencode\", \"plugin\"),\n\n /** Athena internal files directory (state, backups) */\n athenaDir: join(homedir(), \".config\", \"opencode\", \"athena\"),\n\n /** Athena backups directory */\n backupsDir: join(homedir(), \".config\", \"opencode\", \"athena\", \"backups\"),\n\n /** Athena state file (for story tracking) */\n stateFile: join(homedir(), \".config\", \"opencode\", \"athena\", \"athena-state.json\"),\n\n /** Legacy state file path (for migration) */\n legacyStateFile: join(homedir(), \".config\", \"opencode\", \"athena-state.json\"),\n} as const;\n\n/**\n * Project-specific paths (relative to project root)\n */\nexport const PROJECT_PATHS = {\n /** Local Athena config */\n localConfig: \".opencode/athena.json\",\n\n /** BMAD directory */\n bmadDir: \"docs\",\n\n /** BMAD docs directory (deprecated - same as bmadDir in v6) */\n bmadDocsDir: \"docs\",\n\n /** Sprint status file */\n sprintStatus: \"docs/implementation-artifacts/sprint-status.yaml\",\n\n /** Stories directory */\n storiesDir: \"docs/implementation-artifacts/stories\",\n\n /** Architecture document */\n architecture: \"docs/project-planning-artifacts/architecture.md\",\n\n /** PRD document */\n prd: \"docs/project-planning-artifacts/PRD.md\",\n} as const;\n\n/**\n * Default configuration values\n */\nexport const DEFAULTS = {\n /** Default BMAD track for new projects */\n defaultTrack: \"bmad-method\" as const,\n\n /** Whether to auto-update sprint status */\n autoStatusUpdate: true,\n\n /** Maximum parallel stories */\n parallelStoryLimit: 3,\n\n /** Default features enabled */\n features: {\n bmadBridge: true,\n autoStatus: true,\n parallelExecution: true,\n notifications: true,\n contextMonitor: true,\n commentChecker: true,\n lspTools: true,\n autoGitOperations: false,\n todoSync: true,\n },\n\n /** Default MCPs enabled */\n mcps: {\n context7: true,\n exa: true,\n grepApp: true,\n },\n} as const;\n\n/**\n * Minimum compatible versions\n */\nexport const MIN_VERSIONS = {\n node: \"20.0.0\",\n opencode: \"1.0.132\",\n} as const;\n","/**\n * athena_config tool\n *\n * View current Athena configuration.\n */\n\nimport { type ToolDefinition, tool } from \"@opencode-ai/plugin\";\nimport { VERSION } from \"../../shared/constants.js\";\nimport type { AthenaConfig } from \"../../shared/types.js\";\n\n/**\n * Create the athena_config tool\n */\nexport function createConfigTool(config: AthenaConfig): ToolDefinition {\n return tool({\n description: `View the current OpenCode Athena configuration.\n\nShows:\n- Version information\n- Subscription settings (Claude, OpenAI, Google)\n- Model assignments for each agent role\n- BMAD integration settings\n- Enabled features and MCP servers`,\n\n args: {\n section: tool.schema\n .enum([\"all\", \"subscriptions\", \"models\", \"bmad\", \"features\", \"mcps\"])\n .optional()\n .describe(\"Specific section to view (default: all)\"),\n },\n\n async execute(args): Promise<string> {\n const section = args.section || \"all\";\n\n if (section === \"all\") {\n return JSON.stringify(\n {\n athenaVersion: VERSION,\n configVersion: config.version,\n subscriptions: config.subscriptions,\n models: config.models,\n bmad: config.bmad,\n features: config.features,\n mcps: config.mcps,\n },\n null,\n 2\n );\n }\n\n // Return specific section\n const sectionData: Record<string, unknown> = {\n subscriptions: config.subscriptions,\n models: config.models,\n bmad: config.bmad,\n features: config.features,\n mcps: config.mcps,\n };\n\n return JSON.stringify(\n {\n section,\n data: sectionData[section] || null,\n },\n null,\n 2\n );\n },\n });\n}\n","import { existsSync } from \"node:fs\";\nimport { mkdir, readFile, rm, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport { parse as parseYaml, stringify as stringifyYaml } from \"yaml\";\nimport type {\n BmadDevelopmentStatus,\n BmadSprintStatus,\n BmadStoryStatus,\n ParsedDevelopmentKey,\n ParsedEpicKey,\n ParsedStoryKey,\n} from \"../../shared/types.js\";\nimport { createPluginLogger } from \"./plugin-logger.js\";\n\nconst log = createPluginLogger(\"yaml-handler\");\n\nconst LOCK_EXT = \".lock\";\nconst LOCK_TIMEOUT = 10000;\nconst LOCK_RETRY_INTERVAL = 50;\nconst STALE_LOCK_AGE = 30000;\n\nasync function acquireLock(filePath: string): Promise<() => Promise<void>> {\n const lockPath = `${filePath}${LOCK_EXT}`;\n const startTime = Date.now();\n const lockId = `${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`;\n\n while (Date.now() - startTime < LOCK_TIMEOUT) {\n try {\n if (existsSync(lockPath)) {\n const lockContent = await readFile(lockPath, \"utf-8\").catch(() => null);\n if (lockContent) {\n try {\n const lockData = JSON.parse(lockContent);\n const lockAge = Date.now() - lockData.timestamp;\n if (lockAge > STALE_LOCK_AGE) {\n await rm(lockPath, { force: true });\n }\n } catch {\n await rm(lockPath, { force: true });\n }\n }\n }\n\n const lockData = JSON.stringify({\n id: lockId,\n pid: process.pid,\n timestamp: Date.now(),\n });\n\n await writeFile(lockPath, lockData, { flag: \"wx\" });\n\n return async () => {\n try {\n const currentContent = await readFile(lockPath, \"utf-8\").catch(() => null);\n if (currentContent) {\n const currentData = JSON.parse(currentContent);\n if (currentData.id === lockId) {\n await rm(lockPath, { force: true });\n }\n }\n } catch {\n // Ignore errors during unlock\n }\n };\n } catch (error: unknown) {\n const nodeError = error as NodeJS.ErrnoException;\n if (nodeError.code !== \"EEXIST\") {\n throw error;\n }\n await sleep(LOCK_RETRY_INTERVAL);\n }\n }\n\n throw new Error(`Failed to acquire lock for ${filePath} within ${LOCK_TIMEOUT}ms`);\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nexport async function readYamlFile<T = unknown>(filePath: string): Promise<T | null> {\n if (!existsSync(filePath)) {\n return null;\n }\n\n try {\n const content = await readFile(filePath, \"utf-8\");\n return parseYaml(content) as T;\n } catch (error) {\n log.warn(\"Failed to parse YAML file\", { filePath, error });\n return null;\n }\n}\n\nexport async function writeYamlFile<T = unknown>(filePath: string, data: T): Promise<void> {\n const content = stringifyYaml(data, {\n indent: 2,\n lineWidth: 120,\n });\n await writeFile(filePath, content, \"utf-8\");\n}\n\n// =============================================================================\n// BMAD v6 Key Parsing Functions\n// =============================================================================\n\nconst STORY_KEY_PATTERN = /^(\\d+)-(\\d+)(?:-(.+))?$/;\nconst EPIC_KEY_PATTERN = /^epic-(\\d+)$/;\nconst RETRO_KEY_PATTERN = /^epic-(\\d+)-retrospective$/;\n\nexport function parseStoryKey(key: string): ParsedStoryKey | null {\n const match = key.match(STORY_KEY_PATTERN);\n if (!match) return null;\n\n return {\n epicNum: match[1],\n storyNum: match[2],\n titleSlug: match[3] || undefined,\n fullKey: key,\n normalizedId: `${match[1]}-${match[2]}`,\n };\n}\n\nexport function parseEpicKey(key: string): ParsedEpicKey | null {\n const match = key.match(EPIC_KEY_PATTERN);\n if (!match) return null;\n\n return {\n epicNum: match[1],\n fullKey: key,\n };\n}\n\nexport function parseRetroKey(key: string): { epicNum: string; fullKey: string } | null {\n const match = key.match(RETRO_KEY_PATTERN);\n if (!match) return null;\n\n return {\n epicNum: match[1],\n fullKey: key,\n };\n}\n\nexport function parseDevelopmentKey(key: string): ParsedDevelopmentKey {\n const retroParsed = parseRetroKey(key);\n if (retroParsed) {\n return { type: \"retrospective\", parsed: retroParsed };\n }\n\n const epicParsed = parseEpicKey(key);\n if (epicParsed) {\n return { type: \"epic\", parsed: epicParsed };\n }\n\n const storyParsed = parseStoryKey(key);\n if (storyParsed) {\n return { type: \"story\", parsed: storyParsed };\n }\n\n return { type: \"unknown\", key };\n}\n\nexport function normalizeStoryId(storyId: string): string {\n return storyId.replace(\".\", \"-\");\n}\n\nexport function storyIdToDotFormat(storyId: string): string {\n const match = storyId.match(/^(\\d+)-(\\d+)/);\n if (match) {\n return `${match[1]}.${match[2]}`;\n }\n return storyId;\n}\n\nexport function slugify(title: string): string {\n return title\n .toLowerCase()\n .trim()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-|-$/g, \"\");\n}\n\n// =============================================================================\n// BMAD v6 Sprint Status Read/Write\n// =============================================================================\n\nexport async function readBmadSprintStatus(filePath: string): Promise<BmadSprintStatus | null> {\n const raw = await readYamlFile<Partial<BmadSprintStatus>>(filePath);\n\n if (!raw) {\n return null;\n }\n\n return {\n development_status: {},\n ...raw,\n };\n}\n\nexport async function writeBmadSprintStatus(\n filePath: string,\n status: BmadSprintStatus\n): Promise<void> {\n const dir = dirname(filePath);\n if (!existsSync(dir)) {\n await mkdir(dir, { recursive: true });\n }\n\n const releaseLock = await acquireLock(filePath);\n\n try {\n const currentStatus = await readBmadSprintStatus(filePath);\n\n let statusToWrite = status;\n\n if (currentStatus) {\n if (\n status.last_modified &&\n currentStatus.last_modified &&\n currentStatus.last_modified !== status.last_modified\n ) {\n statusToWrite = mergeBmadSprintStatus(currentStatus, status);\n }\n }\n\n statusToWrite.last_modified = new Date().toISOString();\n await writeYamlFile(filePath, statusToWrite);\n } finally {\n await releaseLock();\n }\n}\n\nfunction mergeBmadSprintStatus(\n current: BmadSprintStatus,\n incoming: BmadSprintStatus\n): BmadSprintStatus {\n const merged: BmadSprintStatus = {\n ...current,\n development_status: { ...current.development_status },\n };\n\n for (const [key, status] of Object.entries(incoming.development_status)) {\n merged.development_status[key] = status;\n }\n\n if (incoming.current_story !== undefined) {\n merged.current_story = incoming.current_story;\n }\n\n return merged;\n}\n\n// =============================================================================\n// Story Status Operations (BMAD v6)\n// =============================================================================\n\nexport interface StorySearchResult {\n key: string;\n status: BmadDevelopmentStatus;\n parsed: ParsedStoryKey;\n}\n\nexport function findStoryInStatus(\n status: BmadSprintStatus,\n storyId: string\n): StorySearchResult | null {\n const normalizedSearch = normalizeStoryId(storyId);\n\n for (const [key, statusValue] of Object.entries(status.development_status)) {\n const parsed = parseStoryKey(key);\n if (parsed && parsed.normalizedId === normalizedSearch) {\n return {\n key,\n status: statusValue,\n parsed,\n };\n }\n }\n\n return null;\n}\n\nexport function findStoriesByStatus(\n status: BmadSprintStatus,\n targetStatus: BmadStoryStatus\n): StorySearchResult[] {\n const results: StorySearchResult[] = [];\n\n for (const [key, statusValue] of Object.entries(status.development_status)) {\n if (statusValue !== targetStatus) continue;\n\n const parsed = parseStoryKey(key);\n if (parsed) {\n results.push({ key, status: statusValue, parsed });\n }\n }\n\n return results.sort((a, b) => compareStoryKeys(a.parsed, b.parsed));\n}\n\nfunction compareStoryKeys(a: ParsedStoryKey, b: ParsedStoryKey): number {\n const epicA = Number.parseInt(a.epicNum, 10);\n const epicB = Number.parseInt(b.epicNum, 10);\n if (epicA !== epicB) return epicA - epicB;\n\n const numA = Number.parseInt(a.storyNum, 10);\n const numB = Number.parseInt(b.storyNum, 10);\n return numA - numB;\n}\n\nexport function findNextReadyStory(status: BmadSprintStatus): StorySearchResult | null {\n if (status.current_story) {\n const current = findStoryInStatus(status, status.current_story);\n if (current) return current;\n }\n\n const inProgress = findStoriesByStatus(status, \"in-progress\");\n if (inProgress.length > 0) return inProgress[0];\n\n const readyForDev = findStoriesByStatus(status, \"ready-for-dev\");\n if (readyForDev.length > 0) return readyForDev[0];\n\n const backlog = findStoriesByStatus(status, \"backlog\");\n if (backlog.length > 0) return backlog[0];\n\n return null;\n}\n\nexport async function updateStoryStatus(\n filePath: string,\n storyId: string,\n newStatus: BmadStoryStatus,\n storyTitle?: string\n): Promise<{ success: boolean; key: string; previousStatus?: BmadDevelopmentStatus }> {\n const status = await readBmadSprintStatus(filePath);\n if (!status) {\n return { success: false, key: \"\" };\n }\n\n const existing = findStoryInStatus(status, storyId);\n\n let key: string;\n let previousStatus: BmadDevelopmentStatus | undefined;\n\n if (existing) {\n key = existing.key;\n previousStatus = existing.status;\n } else {\n const normalizedId = normalizeStoryId(storyId);\n key = storyTitle ? `${normalizedId}-${slugify(storyTitle)}` : normalizedId;\n }\n\n status.development_status[key] = newStatus;\n\n if (newStatus === \"in-progress\") {\n status.current_story = normalizeStoryId(storyId);\n } else if (newStatus === \"done\" || newStatus === \"blocked\") {\n if (status.current_story === normalizeStoryId(storyId)) {\n status.current_story = null;\n }\n }\n\n await writeBmadSprintStatus(filePath, status);\n\n return { success: true, key, previousStatus };\n}\n\n// =============================================================================\n// Epic Status Operations (BMAD v6)\n// =============================================================================\n\nexport function findEpicKey(status: BmadSprintStatus, epicNum: string): string | null {\n const epicKey = `epic-${epicNum}`;\n if (epicKey in status.development_status) {\n return epicKey;\n }\n return null;\n}\n\nexport function getStoriesForEpic(status: BmadSprintStatus, epicNum: string): StorySearchResult[] {\n const results: StorySearchResult[] = [];\n\n for (const [key, statusValue] of Object.entries(status.development_status)) {\n const parsed = parseStoryKey(key);\n if (parsed && parsed.epicNum === epicNum) {\n results.push({ key, status: statusValue, parsed });\n }\n }\n\n return results.sort((a, b) => compareStoryKeys(a.parsed, b.parsed));\n}\n\nexport async function updateEpicStatusIfNeeded(\n filePath: string,\n epicNum: string\n): Promise<{ updated: boolean; newStatus?: BmadDevelopmentStatus }> {\n const status = await readBmadSprintStatus(filePath);\n if (!status) {\n return { updated: false };\n }\n\n const epicKey = findEpicKey(status, epicNum);\n if (!epicKey) {\n return { updated: false };\n }\n\n const currentEpicStatus = status.development_status[epicKey];\n const stories = getStoriesForEpic(status, epicNum);\n\n if (stories.length === 0) {\n return { updated: false };\n }\n\n const allDone = stories.every((s) => s.status === \"done\");\n const anyInProgress = stories.some(\n (s) => s.status === \"in-progress\" || s.status === \"review\" || s.status === \"ready-for-dev\"\n );\n\n let newStatus: BmadDevelopmentStatus | undefined;\n\n if (allDone && currentEpicStatus !== \"done\") {\n newStatus = \"done\";\n } else if (anyInProgress && currentEpicStatus === \"backlog\") {\n newStatus = \"in-progress\";\n }\n\n if (newStatus) {\n status.development_status[epicKey] = newStatus;\n await writeBmadSprintStatus(filePath, status);\n return { updated: true, newStatus };\n }\n\n return { updated: false };\n}\n\n// =============================================================================\n// Add Story to Sprint Status (BMAD v6)\n// =============================================================================\n\nexport async function addStoryToBmadSprintStatus(\n filePath: string,\n storyId: string,\n storyTitle?: string,\n initialStatus: BmadStoryStatus = \"backlog\"\n): Promise<{ success: boolean; key: string }> {\n const status = await readBmadSprintStatus(filePath);\n if (!status) {\n return { success: false, key: \"\" };\n }\n\n const existing = findStoryInStatus(status, storyId);\n if (existing) {\n return { success: true, key: existing.key };\n }\n\n const normalizedId = normalizeStoryId(storyId);\n const key = storyTitle ? `${normalizedId}-${slugify(storyTitle)}` : normalizedId;\n\n status.development_status[key] = initialStatus;\n await writeBmadSprintStatus(filePath, status);\n\n return { success: true, key };\n}\n\n// =============================================================================\n// Sprint Progress Calculation (BMAD v6)\n// =============================================================================\n\nexport interface SprintProgress {\n total: number;\n done: number;\n inProgress: number;\n readyForDev: number;\n backlog: number;\n blocked: number;\n review: number;\n percentComplete: number;\n}\n\nexport function calculateSprintProgress(status: BmadSprintStatus): SprintProgress {\n let total = 0;\n let done = 0;\n let inProgress = 0;\n let readyForDev = 0;\n let backlog = 0;\n let blocked = 0;\n let review = 0;\n\n for (const [key, statusValue] of Object.entries(status.development_status)) {\n const parsed = parseStoryKey(key);\n if (!parsed) continue;\n\n total++;\n switch (statusValue) {\n case \"done\":\n done++;\n break;\n case \"in-progress\":\n inProgress++;\n break;\n case \"ready-for-dev\":\n readyForDev++;\n break;\n case \"backlog\":\n backlog++;\n break;\n case \"blocked\":\n blocked++;\n break;\n case \"review\":\n review++;\n break;\n }\n }\n\n const percentComplete = total > 0 ? Math.round((done / total) * 100) : 0;\n\n return {\n total,\n done,\n inProgress,\n readyForDev,\n backlog,\n blocked,\n review,\n percentComplete,\n };\n}\n\n// =============================================================================\n// Legacy Compatibility (Deprecated)\n// =============================================================================\n\nimport type { SprintStatus } from \"../../shared/types.js\";\n\n/** @deprecated Use readBmadSprintStatus instead */\nexport async function readSprintStatus(filePath: string): Promise<SprintStatus | null> {\n const raw = await readYamlFile<Partial<SprintStatus>>(filePath);\n\n if (!raw) {\n return null;\n }\n\n return {\n completed_stories: [],\n pending_stories: [],\n in_progress_stories: [],\n blocked_stories: [],\n ...raw,\n };\n}\n\n/** @deprecated Use writeBmadSprintStatus instead */\nexport async function writeSprintStatus(filePath: string, status: SprintStatus): Promise<void> {\n const dir = dirname(filePath);\n if (!existsSync(dir)) {\n await mkdir(dir, { recursive: true });\n }\n\n const releaseLock = await acquireLock(filePath);\n\n try {\n status.last_modified = new Date().toISOString();\n await writeYamlFile(filePath, status);\n } finally {\n await releaseLock();\n }\n}\n\n/** @deprecated Use addStoryToBmadSprintStatus instead */\nexport async function addStoryToSprintStatus(\n filePath: string,\n storyId: string,\n _status: \"pending\" | \"backlog\" = \"backlog\"\n): Promise<void> {\n await addStoryToBmadSprintStatus(filePath, storyId, undefined, \"backlog\");\n}\n\n/** @deprecated No longer needed with flat map structure */\nexport function insertStoryInOrder(stories: string[], newStoryId: string): string[] {\n const normalizedId = newStoryId.replace(\".\", \"-\");\n\n if (stories.includes(normalizedId)) {\n return stories;\n }\n\n const result = [...stories, normalizedId];\n result.sort((a, b) => {\n const parsedA = parseStoryKey(a);\n const parsedB = parseStoryKey(b);\n if (!parsedA || !parsedB) return 0;\n return compareStoryKeys(parsedA, parsedB);\n });\n return result;\n}\n","import * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport { type ToolDefinition, tool } from \"@opencode-ai/plugin\";\nimport type { PluginInput } from \"@opencode-ai/plugin\";\nimport type {\n AthenaConfig,\n CreatedSubStory,\n DecomposeStoryResult,\n DecompositionSplit,\n DecompositionVerification,\n UserSplitConfig,\n} from \"../../shared/types.js\";\nimport { getBmadPaths } from \"../utils/bmad-finder.js\";\nimport { createPluginLogger } from \"../utils/plugin-logger.js\";\nimport { assessStoryComplexity } from \"../utils/story-complexity.js\";\nimport {\n generateDecompositionSuggestions,\n generateSubStoryContent,\n getSubStoryFilename,\n getSubStoryId,\n validateSplits,\n} from \"../utils/story-decomposer.js\";\nimport { normalizeStoryId, resolveStoryIdentifier, stripAtPrefix } from \"../utils/story-loader.js\";\nimport { parseStoryTasks } from \"../utils/story-parser.js\";\nimport {\n readBmadSprintStatus,\n storyIdToDotFormat,\n writeBmadSprintStatus,\n} from \"../utils/yaml-handler.js\";\n\nconst log = createPluginLogger(\"decompose-story\");\n\nexport function createDecomposeStoryTool(ctx: PluginInput, config: AthenaConfig): ToolDefinition {\n return tool({\n description: `Decompose a large BMAD story into smaller sub-stories.\n\nUse after athena_analyze_story recommends decomposition.\n\nWhat this tool does:\n1. Validates that all tasks are accounted for (no missing/duplicates)\n2. Creates new story files with suffix (e.g., 3-2a.md, 3-2b.md)\n3. Updates sprint-status.yaml (removes original, adds sub-stories)\n4. Preserves applicable dev notes in each sub-story\n5. Returns the first story to implement\n\nIMPORTANT: Requires confirmed=true to execute (safety check).`,\n\n args: {\n storyId: tool.schema.string().describe(\"Story ID to decompose (e.g., '3.2')\"),\n splits: tool.schema\n .array(\n tool.schema.object({\n suffix: tool.schema.string().describe(\"Suffix for sub-story (e.g., 'a', 'b')\"),\n title: tool.schema.string().optional().describe(\"Optional title override\"),\n taskIds: tool.schema\n .array(tool.schema.string())\n .describe(\"Task IDs to include in this split\"),\n })\n )\n .optional()\n .describe(\"Custom splits (if not provided, uses suggested splits from analysis)\"),\n useSuggestedSplits: tool.schema\n .boolean()\n .optional()\n .describe(\"Use suggested splits from analysis (default: true if no custom splits)\"),\n confirmed: tool.schema\n .boolean()\n .describe(\"Must be true to execute decomposition (safety check)\"),\n },\n\n async execute(args): Promise<string> {\n const result = await handleDecomposeStory(ctx, config, {\n storyId: args.storyId,\n splits: args.splits as UserSplitConfig[] | undefined,\n useSuggestedSplits: args.useSuggestedSplits,\n confirmed: args.confirmed,\n });\n\n return JSON.stringify(result, null, 2);\n },\n });\n}\n\ninterface DecomposeArgs {\n storyId: string;\n splits?: UserSplitConfig[];\n useSuggestedSplits?: boolean;\n confirmed: boolean;\n}\n\nasync function handleDecomposeStory(\n ctx: PluginInput,\n config: AthenaConfig,\n args: DecomposeArgs\n): Promise<DecomposeStoryResult> {\n const { confirmed, splits: customSplits, useSuggestedSplits } = args;\n const rawStoryId = stripAtPrefix(args.storyId);\n const storyId = normalizeStoryId(rawStoryId);\n\n log.debug(\"Decomposing story\", { storyId, confirmed, hasCustomSplits: !!customSplits });\n\n if (!confirmed) {\n return createErrorResult(\n \"Safety check failed: confirmed must be true to execute decomposition\",\n \"Set confirmed=true to proceed with story decomposition.\"\n );\n }\n\n const paths = await getBmadPaths(ctx.directory, config);\n if (!paths.storiesDir) {\n return createErrorResult(\n \"No stories directory found\",\n \"Ensure BMAD is set up with a stories directory.\"\n );\n }\n\n const resolved = await resolveStoryIdentifier(paths.storiesDir, rawStoryId, ctx.directory);\n if (!resolved) {\n return createErrorResult(\n `Story not found: ${args.storyId}`,\n \"Check the story ID and try again.\"\n );\n }\n\n const { content: storyContent, filename: originalFilename, path: storyPath } = resolved;\n const parsedStory = parseStoryTasks(storyContent, storyId);\n\n if (parsedStory.tasks.length === 0) {\n return createErrorResult(\n \"No tasks found in story\",\n \"Story must have tasks to decompose. Check the story format.\"\n );\n }\n\n const splitsToUse = determineSplits(customSplits, useSuggestedSplits, parsedStory, storyContent);\n\n if (\"error\" in splitsToUse) {\n return createErrorResult(splitsToUse.error, splitsToUse.suggestion, parsedStory.tasks.length);\n }\n\n const validation = validateSplits(parsedStory.tasks, splitsToUse);\n if (!validation.valid) {\n return {\n success: false,\n createdStories: [],\n verification: {\n originalTaskCount: parsedStory.tasks.length,\n totalTasksInSplits: splitsToUse.reduce((sum, s) => sum + s.taskIds.length, 0),\n allTasksAccountedFor: false,\n missingTasks: validation.missingTasks,\n duplicatedTasks: validation.duplicatedTasks,\n devNotesPreserved: false,\n },\n sprintStatusUpdated: false,\n originalStoryRemoved: false,\n nextStory: \"\",\n error: formatValidationError(validation),\n suggestion: \"Ensure all tasks are included exactly once across all splits.\",\n };\n }\n\n const createdStories = await createSubStoryFiles(\n splitsToUse,\n storyContent,\n parsedStory,\n storyId,\n originalFilename,\n paths.storiesDir\n );\n\n if (\"error\" in createdStories) {\n return {\n success: false,\n createdStories: createdStories.created,\n verification: createPartialVerification(parsedStory.tasks.length, splitsToUse),\n sprintStatusUpdated: false,\n originalStoryRemoved: false,\n nextStory: \"\",\n error: createdStories.error,\n suggestion: \"Check file system permissions.\",\n };\n }\n\n const sprintUpdate = await updateSprintStatus(paths.sprintStatus, storyId, createdStories);\n await archiveOriginalStory(storyPath);\n\n const firstReadyStory = createdStories.find((s) => s.status === \"ready-for-dev\");\n const nextStory = firstReadyStory\n ? storyIdToDotFormat(firstReadyStory.id)\n : storyIdToDotFormat(createdStories[0].id);\n\n log.info(\"Story decomposition complete\", {\n storyId,\n createdCount: createdStories.length,\n nextStory,\n sprintStatusUpdated: sprintUpdate.updated,\n originalStoryRemoved: sprintUpdate.originalRemoved,\n });\n\n return {\n success: true,\n createdStories,\n verification: {\n originalTaskCount: parsedStory.tasks.length,\n totalTasksInSplits: splitsToUse.reduce((sum, s) => sum + s.taskIds.length, 0),\n allTasksAccountedFor: true,\n missingTasks: [],\n duplicatedTasks: [],\n devNotesPreserved:\n storyContent.includes(\"## Dev Notes\") || storyContent.includes(\"## Implementation Notes\"),\n },\n sprintStatusUpdated: sprintUpdate.updated,\n originalStoryRemoved: sprintUpdate.originalRemoved,\n nextStory,\n };\n}\n\nfunction createErrorResult(\n error: string,\n suggestion: string,\n originalTaskCount = 0\n): DecomposeStoryResult {\n return {\n success: false,\n createdStories: [],\n verification: {\n originalTaskCount,\n totalTasksInSplits: 0,\n allTasksAccountedFor: false,\n missingTasks: [],\n duplicatedTasks: [],\n devNotesPreserved: false,\n },\n sprintStatusUpdated: false,\n originalStoryRemoved: false,\n nextStory: \"\",\n error,\n suggestion,\n };\n}\n\nfunction determineSplits(\n customSplits: UserSplitConfig[] | undefined,\n useSuggestedSplits: boolean | undefined,\n parsedStory: ReturnType<typeof parseStoryTasks>,\n storyContent: string\n): DecompositionSplit[] | { error: string; suggestion: string } {\n if (customSplits && customSplits.length > 0) {\n return customSplits.map((split, index) => ({\n suffix: split.suffix,\n title: split.title || `Part ${index + 1}`,\n taskIds: split.taskIds,\n estimatedPoints: 0,\n rationale: \"User-defined split\",\n dependencies: [],\n }));\n }\n\n if (useSuggestedSplits === false) {\n return {\n error: \"No splits provided and useSuggestedSplits is false\",\n suggestion: \"Either provide custom splits or set useSuggestedSplits=true.\",\n };\n }\n\n const fileSizeBytes = Buffer.byteLength(storyContent, \"utf-8\");\n const assessment = assessStoryComplexity(parsedStory, fileSizeBytes);\n const suggestedSplits = generateDecompositionSuggestions(parsedStory, assessment.taskEfforts);\n\n if (suggestedSplits.length === 0) {\n return {\n error: \"Could not generate decomposition suggestions\",\n suggestion: \"Provide custom splits using the 'splits' parameter.\",\n };\n }\n\n return suggestedSplits;\n}\n\nfunction formatValidationError(validation: {\n missingTasks: string[];\n duplicatedTasks: string[];\n}): string {\n const parts: string[] = [];\n if (validation.missingTasks.length > 0) {\n parts.push(`missing tasks: ${validation.missingTasks.join(\", \")}`);\n }\n if (validation.duplicatedTasks.length > 0) {\n parts.push(`duplicated tasks: ${validation.duplicatedTasks.join(\", \")}`);\n }\n return `Invalid splits: ${parts.join(\"; \")}`;\n}\n\nfunction createPartialVerification(\n originalTaskCount: number,\n splits: DecompositionSplit[]\n): DecompositionVerification {\n return {\n originalTaskCount,\n totalTasksInSplits: splits.reduce((sum, s) => sum + s.taskIds.length, 0),\n allTasksAccountedFor: false,\n missingTasks: [],\n duplicatedTasks: [],\n devNotesPreserved: false,\n };\n}\n\nasync function createSubStoryFiles(\n splits: DecompositionSplit[],\n storyContent: string,\n parsedStory: ReturnType<typeof parseStoryTasks>,\n storyId: string,\n originalFilename: string,\n storiesDir: string\n): Promise<CreatedSubStory[] | { error: string; created: CreatedSubStory[] }> {\n const createdStories: CreatedSubStory[] = [];\n\n for (let i = 0; i < splits.length; i++) {\n const split = splits[i];\n const subStoryFilename = getSubStoryFilename(originalFilename, split.suffix);\n const subStoryId = getSubStoryId(storyId, split.suffix);\n const subStoryPath = path.join(storiesDir, subStoryFilename);\n\n const subStoryContent = generateSubStoryContent(\n storyContent,\n parsedStory,\n split,\n i,\n splits.length,\n storyId\n );\n\n try {\n await fs.writeFile(subStoryPath, subStoryContent, \"utf-8\");\n log.info(\"Created sub-story file\", { path: subStoryPath });\n } catch (err) {\n log.error(\"Failed to write sub-story file\", { path: subStoryPath, error: err });\n return {\n error: `Failed to create sub-story file: ${subStoryFilename}`,\n created: createdStories,\n };\n }\n\n const hasDependencies = split.dependencies.length > 0;\n const status: \"ready-for-dev\" | \"backlog\" = hasDependencies ? \"backlog\" : \"ready-for-dev\";\n\n createdStories.push({\n id: subStoryId,\n filename: subStoryFilename,\n filePath: subStoryPath,\n taskCount: split.taskIds.length,\n estimatedPoints: split.estimatedPoints,\n status,\n dependencies: split.dependencies.map((d) => getSubStoryId(storyId, d)),\n hasVerificationTask: false,\n });\n }\n\n return createdStories;\n}\n\nasync function updateSprintStatus(\n sprintStatusPath: string | undefined,\n storyId: string,\n createdStories: CreatedSubStory[]\n): Promise<{ updated: boolean; originalRemoved: boolean }> {\n if (!sprintStatusPath) {\n return { updated: false, originalRemoved: false };\n }\n\n try {\n const sprintStatus = await readBmadSprintStatus(sprintStatusPath);\n if (!sprintStatus) {\n return { updated: false, originalRemoved: false };\n }\n\n let originalRemoved = false;\n const originalKeyPattern = new RegExp(`^${storyId.replace(\".\", \"-\")}(-.*)?$`);\n\n for (const key of Object.keys(sprintStatus.development_status)) {\n if (originalKeyPattern.test(key) && !key.includes(\"retrospective\")) {\n delete sprintStatus.development_status[key];\n originalRemoved = true;\n log.info(\"Removed original story from sprint status\", { key });\n }\n }\n\n for (const subStory of createdStories) {\n const subStoryKey = subStory.id.replace(\".\", \"-\");\n sprintStatus.development_status[subStoryKey] = subStory.status;\n log.info(\"Added sub-story to sprint status\", { key: subStoryKey, status: subStory.status });\n }\n\n if (sprintStatus.current_story) {\n const currentNormalized = normalizeStoryId(sprintStatus.current_story);\n if (currentNormalized === storyId) {\n const firstReady = createdStories.find((s) => s.status === \"ready-for-dev\");\n sprintStatus.current_story = firstReady\n ? firstReady.id.replace(\".\", \"-\")\n : createdStories[0].id.replace(\".\", \"-\");\n }\n }\n\n sprintStatus.last_modified = new Date().toISOString();\n await writeBmadSprintStatus(sprintStatusPath, sprintStatus);\n\n return { updated: true, originalRemoved };\n } catch (err) {\n log.warn(\"Failed to update sprint-status.yaml\", { error: err });\n return { updated: false, originalRemoved: false };\n }\n}\n\nasync function archiveOriginalStory(storyPath: string): Promise<void> {\n try {\n const archivedPath = storyPath.replace(\".md\", \".decomposed.md\");\n await fs.rename(storyPath, archivedPath);\n log.info(\"Archived original story\", { from: storyPath, to: archivedPath });\n } catch (err) {\n log.warn(\"Failed to archive original story file\", { error: err });\n }\n}\n","/**\n * athena_get_context tool\n *\n * Quick access to current story context from tracker.\n */\n\nimport { type ToolDefinition, tool } from \"@opencode-ai/plugin\";\nimport type { AthenaConfig } from \"../../shared/types.js\";\nimport type { StoryTracker } from \"../tracker/story-tracker.js\";\n\n/**\n * Create the athena_get_context tool\n */\nexport function createGetContextTool(tracker: StoryTracker, _config: AthenaConfig): ToolDefinition {\n return tool({\n description: `Get the current story context without reloading from files.\n\nReturns the cached context from the story tracker including:\n- Current story ID and status\n- When the story was started\n- Recent activity history\n\nUse this for quick status checks. Use athena_get_story to reload full context from files.`,\n\n args: {},\n\n async execute(): Promise<string> {\n const currentStory = tracker.getCurrentStory();\n\n if (!currentStory) {\n return JSON.stringify({\n status: \"no_active_story\",\n message: \"No story is currently being tracked. Use athena_get_story to load a story.\",\n });\n }\n\n const context = await tracker.getCurrentStoryContext();\n const history = tracker.getHistory().slice(-10);\n\n return JSON.stringify(\n {\n currentStory: {\n id: currentStory.id,\n status: currentStory.status,\n startedAt: currentStory.startedAt,\n completedAt: currentStory.completedAt,\n },\n contextSummary: context,\n recentHistory: history,\n sessionId: tracker.getSessionId(),\n },\n null,\n 2\n );\n },\n });\n}\n","/**\n * Context builder for BMAD story implementation\n *\n * Extracts relevant sections from architecture and PRD documents\n * based on story content keywords.\n */\n\nimport { existsSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { createPluginLogger } from \"./plugin-logger.js\";\n\nconst log = createPluginLogger(\"context-builder\");\n\n/**\n * Extract relevant architecture sections based on story content\n *\n * Always includes:\n * - Tech Stack section\n * - Patterns/Conventions section\n *\n * Conditionally includes based on keywords:\n * - Data Model section (if story mentions data/database/model/schema)\n * - API section (if story mentions api/endpoint/route)\n *\n * @param archPath - Path to architecture.md\n * @param storyContent - Content of the story file\n * @returns Extracted architecture sections\n */\nexport async function extractRelevantArchitecture(\n archPath: string,\n storyContent: string\n): Promise<string> {\n if (!existsSync(archPath)) {\n return \"\";\n }\n\n try {\n const archContent = await readFile(archPath, \"utf-8\");\n const sections: string[] = [];\n\n // Always include tech stack section\n const techStackMatch = archContent.match(/## Tech(?:nology)? Stack[\\s\\S]*?(?=\\n## |$)/i);\n if (techStackMatch) {\n sections.push(techStackMatch[0].trim());\n }\n\n // Always include patterns/conventions section\n const patternsMatch = archContent.match(\n /## (?:Patterns|Conventions|Standards|Coding Standards)[\\s\\S]*?(?=\\n## |$)/i\n );\n if (patternsMatch) {\n sections.push(patternsMatch[0].trim());\n }\n\n // Include data model section if story mentions data/database\n if (/data|database|model|schema|entity/i.test(storyContent)) {\n const dataMatch = archContent.match(\n /## (?:Data Model|Database|Schema|Data Layer)[\\s\\S]*?(?=\\n## |$)/i\n );\n if (dataMatch) {\n sections.push(dataMatch[0].trim());\n }\n }\n\n // Include API section if story mentions API/endpoint\n if (/api|endpoint|route|rest|graphql/i.test(storyContent)) {\n const apiMatch = archContent.match(\n /## (?:API|Endpoints|Routes|REST|GraphQL)[\\s\\S]*?(?=\\n## |$)/i\n );\n if (apiMatch) {\n sections.push(apiMatch[0].trim());\n }\n }\n\n // Include UI/component section if story mentions UI\n if (/ui|component|view|page|screen|frontend/i.test(storyContent)) {\n const uiMatch = archContent.match(\n /## (?:UI|Components|Views|Frontend|User Interface)[\\s\\S]*?(?=\\n## |$)/i\n );\n if (uiMatch) {\n sections.push(uiMatch[0].trim());\n }\n }\n\n return sections.length > 0\n ? sections.join(\"\\n\\n---\\n\\n\")\n : \"See full architecture document for details.\";\n } catch (error) {\n log.warn(\"Failed to read architecture file\", { archPath, error });\n return \"\";\n }\n}\n\n/**\n * Extract relevant PRD sections based on story content\n *\n * Looks for functional requirement (FR) references in the story\n * and extracts those sections from the PRD.\n *\n * @param prdPath - Path to PRD.md\n * @param storyContent - Content of the story file\n * @returns Extracted PRD sections\n */\nexport async function extractRelevantPRD(prdPath: string, storyContent: string): Promise<string> {\n if (!existsSync(prdPath)) {\n return \"\";\n }\n\n try {\n const prdContent = await readFile(prdPath, \"utf-8\");\n\n // Extract FR references from story (e.g., FR-1, FR1, FR-001)\n const frMatches = storyContent.match(/FR-?\\d+/gi);\n\n if (!frMatches || frMatches.length === 0) {\n return \"\";\n }\n\n // Deduplicate FR references\n const uniqueFRs = [...new Set(frMatches.map((fr) => fr.toUpperCase()))];\n const sections: string[] = [];\n\n for (const fr of uniqueFRs) {\n // Try to find the FR section in the PRD\n // Match patterns like \"### FR-1\" or \"#### FR1\" or \"### FR-001: Title\"\n const normalizedFR = fr.replace(\"-\", \"-?\");\n const regex = new RegExp(`###+ ${normalizedFR}[:\\\\s][\\\\s\\\\S]*?(?=\\\\n###+ |$)`, \"i\");\n const match = prdContent.match(regex);\n\n if (match) {\n sections.push(match[0].trim());\n }\n }\n\n return sections.join(\"\\n\\n\");\n } catch (error) {\n log.warn(\"Failed to read PRD file\", { prdPath, error });\n return \"\";\n }\n}\n\n/**\n * Generate implementation instructions for a story\n *\n * @param storyId - The story ID\n * @returns Markdown instructions for implementing the story\n */\nexport function generateImplementationInstructions(storyId: string): string {\n return `\n## Implementation Instructions for Story ${storyId}\n\nYou are implementing this story using OpenCode Athena's full capabilities.\n\n### Available Subagents\n- **@oracle** - Use for complex debugging, architectural decisions, or strategic code choices\n- **@librarian** - Use for finding implementation examples, researching patterns, exploring documentation\n- **@explore** - Use for fast codebase searches and pattern matching\n- **@frontend-ui-ux-engineer** - Use for UI component implementation (if applicable)\n\n### Available Tools\n- **LSP Tools** - Use lsp_rename, lsp_find_references, lsp_code_actions for refactoring\n- **AST-Grep** - Use ast_grep_search and ast_grep_replace for structural code changes\n\n### Quality Standards\n1. Meet ALL acceptance criteria listed in the story\n2. Follow architecture patterns exactly as specified\n3. Keep comments minimal - code should be self-documenting\n4. Run tests before marking complete\n5. Ensure no regressions in existing functionality\n\n### Completion\nWhen implementation is complete:\n1. Call **athena_update_status** with status \"completed\" and a completion summary\n2. The sprint-status.yaml will be automatically updated\n3. Report what was implemented and any decisions made\n\n### If You Get Stuck\n- Call @oracle for debugging help\n- Call @librarian to find similar implementations\n- Check the architecture document for patterns\n`.trim();\n}\n","import { existsSync } from \"node:fs\";\nimport { readFile, writeFile } from \"node:fs/promises\";\nimport type { BmadStoryStatus } from \"../../shared/types.js\";\nimport { createPluginLogger } from \"./plugin-logger.js\";\n\nconst log = createPluginLogger(\"story-file-updater\");\n\nconst STATUS_LINE_PATTERN = /^Status:\\s*(.+)$/im;\nconst STORY_TITLE_PATTERN = /^#\\s*Story\\s*[\\d.]+:\\s*(.+)$/im;\n\nexport interface StoryFileUpdateResult {\n success: boolean;\n previousStatus?: string;\n newStatus?: BmadStoryStatus;\n error?: string;\n}\n\nexport interface StoryFileInfo {\n status: string | null;\n title: string | null;\n}\n\nexport async function getStoryFileInfo(storyPath: string): Promise<StoryFileInfo | null> {\n if (!existsSync(storyPath)) {\n return null;\n }\n\n try {\n const content = await readFile(storyPath, \"utf-8\");\n\n const statusMatch = content.match(STATUS_LINE_PATTERN);\n const titleMatch = content.match(STORY_TITLE_PATTERN);\n\n return {\n status: statusMatch ? statusMatch[1].trim() : null,\n title: titleMatch ? titleMatch[1].trim() : null,\n };\n } catch (error) {\n log.warn(\"Failed to read story file\", { storyPath, error });\n return null;\n }\n}\n\nexport async function updateStoryFileStatus(\n storyPath: string,\n newStatus: BmadStoryStatus\n): Promise<StoryFileUpdateResult> {\n if (!existsSync(storyPath)) {\n return {\n success: false,\n error: `Story file not found: ${storyPath}`,\n };\n }\n\n try {\n const content = await readFile(storyPath, \"utf-8\");\n const statusMatch = content.match(STATUS_LINE_PATTERN);\n\n if (!statusMatch) {\n const lines = content.split(\"\\n\");\n let insertIndex = 0;\n\n if (lines[0]?.startsWith(\"#\")) {\n insertIndex = 1;\n while (insertIndex < lines.length && lines[insertIndex]?.trim() === \"\") {\n insertIndex++;\n }\n }\n\n lines.splice(insertIndex, 0, \"\", `Status: ${newStatus}`, \"\");\n const updatedContent = lines.join(\"\\n\");\n\n await writeFile(storyPath, updatedContent, \"utf-8\");\n\n log.info(\"Added Status line to story file\", { storyPath, newStatus });\n\n return {\n success: true,\n previousStatus: undefined,\n newStatus,\n };\n }\n\n const previousStatus = statusMatch[1].trim();\n\n if (previousStatus === newStatus) {\n return {\n success: true,\n previousStatus,\n newStatus,\n };\n }\n\n const updatedContent = content.replace(STATUS_LINE_PATTERN, `Status: ${newStatus}`);\n\n await writeFile(storyPath, updatedContent, \"utf-8\");\n\n log.info(\"Updated story file status\", {\n storyPath,\n previousStatus,\n newStatus,\n });\n\n return {\n success: true,\n previousStatus,\n newStatus,\n };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n log.error(\"Failed to update story file status\", { storyPath, error });\n\n return {\n success: false,\n error: `Failed to update story file: ${errorMessage}`,\n };\n }\n}\n\nexport async function getStoryTitle(storyPath: string): Promise<string | null> {\n const info = await getStoryFileInfo(storyPath);\n return info?.title ?? null;\n}\n\nexport function extractTitleFromContent(content: string): string | null {\n const match = content.match(STORY_TITLE_PATTERN);\n return match ? match[1].trim() : null;\n}\n","import { type ToolDefinition, tool } from \"@opencode-ai/plugin\";\nimport type { PluginInput } from \"@opencode-ai/plugin\";\nimport type { AthenaConfig, GetStoryResult } from \"../../shared/types.js\";\nimport type { StoryTracker } from \"../tracker/story-tracker.js\";\nimport { getBmadPaths } from \"../utils/bmad-finder.js\";\nimport {\n extractRelevantArchitecture,\n extractRelevantPRD,\n generateImplementationInstructions,\n} from \"../utils/context-builder.js\";\nimport { createPluginLogger } from \"../utils/plugin-logger.js\";\nimport { getStoryTitle, updateStoryFileStatus } from \"../utils/story-file-updater.js\";\nimport { normalizeStoryId, resolveStoryIdentifier, stripAtPrefix } from \"../utils/story-loader.js\";\nimport {\n calculateSprintProgress,\n findNextReadyStory,\n findStoryInStatus,\n readBmadSprintStatus,\n storyIdToDotFormat,\n updateEpicStatusIfNeeded,\n updateStoryStatus,\n} from \"../utils/yaml-handler.js\";\n\nconst log = createPluginLogger(\"get-story\");\n\nexport function createGetStoryTool(\n ctx: PluginInput,\n tracker: StoryTracker,\n config: AthenaConfig\n): ToolDefinition {\n return tool({\n description: `Load the current BMAD story context for implementation.\n\nReturns:\n- Story file content with requirements and acceptance criteria\n- Relevant architecture sections\n- Sprint progress information\n- Implementation instructions for using Sisyphus and subagents\n\nWhen loading a 'ready-for-dev' story, it will automatically be transitioned to 'in-progress'.\n\nUse this tool before starting story implementation to get full context.`,\n\n args: {\n storyId: tool.schema\n .string()\n .optional()\n .describe(\n \"Story ID (e.g., '2.3') or file path (e.g., 'docs/stories/story-2-3.md'). If omitted, loads the next ready story.\"\n ),\n },\n\n async execute(args): Promise<string> {\n const result = await getStoryContext(ctx, tracker, config, args.storyId);\n return JSON.stringify(result, null, 2);\n },\n });\n}\n\nasync function getStoryContext(\n ctx: PluginInput,\n tracker: StoryTracker,\n config: AthenaConfig,\n requestedStoryId?: string\n): Promise<GetStoryResult> {\n log.debug(\"Getting story context\", { requestedStoryId, directory: ctx.directory });\n\n const paths = await getBmadPaths(ctx.directory, config);\n if (!paths.bmadDir) {\n log.warn(\"BMAD directory not found\", { directory: ctx.directory });\n return {\n error: \"No BMAD directory found\",\n suggestion: \"Run 'npx bmad-method@alpha install' to set up BMAD in this project.\",\n };\n }\n\n log.debug(\"Reading sprint status\", { sprintStatusPath: paths.sprintStatus });\n const sprint = await readBmadSprintStatus(paths.sprintStatus);\n if (!sprint) {\n log.warn(\"Sprint status file not found\", { sprintStatusPath: paths.sprintStatus });\n return {\n error: \"No sprint-status.yaml found\",\n suggestion: \"Run the sprint-planning workflow with BMAD's SM agent first.\",\n };\n }\n\n let resolvedStoryId: string;\n let storyStatus: string | undefined;\n // Keep original input for resolveStoryIdentifier (handles both paths and IDs)\n let storyIdentifier: string | undefined;\n\n if (requestedStoryId) {\n storyIdentifier = stripAtPrefix(requestedStoryId);\n resolvedStoryId = normalizeStoryId(storyIdentifier);\n const found = findStoryInStatus(sprint, resolvedStoryId);\n storyStatus = found?.status;\n } else {\n const nextStory = findNextReadyStory(sprint);\n if (!nextStory) {\n const progress = calculateSprintProgress(sprint);\n log.info(\"No ready stories found\", { progress });\n return {\n error: \"No ready stories found\",\n sprintProgress: {\n completed: progress.done,\n total: progress.total,\n },\n suggestion:\n progress.done === progress.total\n ? \"All stories in current sprint are complete!\"\n : \"No stories are ready-for-dev. Run create-story workflow to create new stories.\",\n };\n }\n resolvedStoryId = nextStory.parsed.normalizedId;\n storyIdentifier = resolvedStoryId;\n storyStatus = nextStory.status;\n }\n\n log.debug(\"Loading story file\", {\n storyId: resolvedStoryId,\n storyIdentifier,\n storiesDir: paths.storiesDir,\n });\n\n const storyResult = await resolveStoryIdentifier(\n paths.storiesDir,\n storyIdentifier,\n ctx.directory\n );\n\n if (!storyResult) {\n log.error(\"Story file not found\", { storyId: resolvedStoryId, storiesDir: paths.storiesDir });\n return {\n error: `Story file not found for ${storyIdToDotFormat(resolvedStoryId)}`,\n suggestion: \"Run 'create-story' workflow with BMAD's SM agent.\",\n };\n }\n\n const storyContent = storyResult.content;\n const storyPath = storyResult.path;\n\n if (storyStatus === \"ready-for-dev\") {\n log.info(\"Auto-transitioning story from ready-for-dev to in-progress\", {\n storyId: resolvedStoryId,\n });\n\n const storyTitle = (await getStoryTitle(storyPath)) ?? undefined;\n\n await updateStoryStatus(paths.sprintStatus, resolvedStoryId, \"in-progress\", storyTitle);\n\n await updateStoryFileStatus(storyPath, \"in-progress\");\n\n const storyKeyInfo = findStoryInStatus(sprint, resolvedStoryId);\n if (storyKeyInfo) {\n await updateEpicStatusIfNeeded(paths.sprintStatus, storyKeyInfo.parsed.epicNum);\n }\n\n storyStatus = \"in-progress\";\n }\n\n log.debug(\"Extracting relevant architecture sections\", {\n architecturePath: paths.architecture,\n });\n const archContent = await extractRelevantArchitecture(paths.architecture, storyContent);\n\n log.debug(\"Extracting relevant PRD sections\", { prdPath: paths.prd });\n const prdContent = await extractRelevantPRD(paths.prd, storyContent);\n\n log.debug(\"Updating story tracker\", { storyId: resolvedStoryId, status: storyStatus });\n await tracker.setCurrentStory(resolvedStoryId, {\n content: storyContent,\n status: (storyStatus as \"in-progress\") || \"in-progress\",\n startedAt: new Date().toISOString(),\n });\n\n const updatedSprint = await readBmadSprintStatus(paths.sprintStatus);\n const progress = updatedSprint ? calculateSprintProgress(updatedSprint) : null;\n\n log.info(\"Story context loaded successfully\", {\n storyId: resolvedStoryId,\n hasArchitecture: !!archContent,\n hasPRD: !!prdContent,\n progress,\n });\n\n return {\n storyId: storyIdToDotFormat(resolvedStoryId),\n story: storyContent,\n architecture: archContent || \"No architecture document found.\",\n prd: prdContent || \"No PRD document found.\",\n sprint: {\n currentEpic: sprint.current_story ? sprint.current_story.split(\"-\")[0] : \"Unknown\",\n completedStories: progress?.done ?? 0,\n pendingStories: (progress?.backlog ?? 0) + (progress?.readyForDev ?? 0),\n blockedStories: progress?.blocked ?? 0,\n },\n instructions: generateImplementationInstructions(storyIdToDotFormat(resolvedStoryId)),\n };\n}\n","/**\n * athena_parallel tool (STUB)\n *\n * Multi-story parallel execution using background agents.\n *\n * TODO: This tool depends on oh-my-opencode's background agent feature.\n * Implementation should:\n * 1. Validate that stories are independent (no file conflicts)\n * 2. Mark all stories as in_progress\n * 3. Spawn background agents for each story\n * 4. Coordinate completion and status updates\n *\n * See: https://github.com/code-yeongyu/oh-my-opencode for background agent API\n */\n\nimport { type ToolDefinition, tool } from \"@opencode-ai/plugin\";\n\n/**\n * Create the athena_parallel tool (stub)\n */\nexport function createParallelTool(): ToolDefinition {\n return tool({\n description: `Execute multiple independent stories in parallel using background agents.\n\nNOTE: This feature is not yet implemented. It requires integration with oh-my-opencode's background agent system.\n\nWhen implemented, this tool will:\n1. Validate that the specified stories have no file conflicts\n2. Mark all stories as in_progress in sprint-status.yaml\n3. Spawn background agents to implement each story\n4. Coordinate completion and report results`,\n\n args: {\n storyIds: tool.schema\n .array(tool.schema.string())\n .describe(\"Array of story IDs to execute in parallel\"),\n waitForCompletion: tool.schema\n .boolean()\n .optional()\n .describe(\"Whether to wait for all stories to complete (default: true)\"),\n },\n\n async execute(args): Promise<string> {\n // TODO: Implement parallel story execution with oh-my-opencode background agents\n return JSON.stringify(\n {\n error: \"Not implemented\",\n message:\n \"Parallel story execution is not yet implemented. This feature requires integration with oh-my-opencode's background agent system.\",\n requestedStories: args.storyIds,\n suggestion: \"For now, implement stories sequentially using /athena-dev for each story.\",\n },\n null,\n 2\n );\n },\n });\n}\n","import type { FindingCategory, FindingSeverity } from \"../../shared/types.js\";\nimport type { FindingCounts } from \"./agent-selector.js\";\n\nexport interface FindingDetail {\n id: string;\n category: FindingCategory;\n severity: FindingSeverity;\n title: string;\n description: string;\n impact: string;\n suggestion: string;\n}\n\nexport interface OracleResponseSummary {\n totalIssues: number;\n highSeverity: number;\n mediumSeverity: number;\n lowSeverity: number;\n recommendation: string;\n}\n\nexport interface OracleResponseFindings {\n security: FindingDetail[];\n logic: FindingDetail[];\n bestPractices: FindingDetail[];\n performance: FindingDetail[];\n}\n\nexport interface StoryFinding {\n storyId: string;\n title: string;\n findings: Partial<OracleResponseFindings>;\n}\n\nexport interface CrossStoryIssue {\n id: string;\n category: FindingCategory;\n severity: FindingSeverity;\n title: string;\n description: string;\n affectedStories: string[];\n suggestion: string;\n}\n\nexport interface ParsedOracleResponse {\n summary: OracleResponseSummary;\n findings?: OracleResponseFindings;\n storyFindings?: StoryFinding[];\n crossStoryIssues?: CrossStoryIssue[];\n}\n\nexport function parseOracleResponse(response: string | null | undefined): ParsedOracleResponse {\n if (!response || typeof response !== \"string\") {\n return createEmptyResponse(\"No response provided\");\n }\n\n try {\n const jsonMatch = response.match(/\\{[\\s\\S]*\\}/);\n if (!jsonMatch) {\n return createEmptyResponse(\"No JSON found in Oracle response\");\n }\n\n const parsed = JSON.parse(jsonMatch[0]) as ParsedOracleResponse;\n\n if (!parsed.summary) {\n return createEmptyResponse(\"No summary in Oracle response\");\n }\n\n return parsed;\n } catch {\n return createEmptyResponse(\"Failed to parse Oracle response as JSON\");\n }\n}\n\nfunction createEmptyResponse(reason: string): ParsedOracleResponse {\n return {\n summary: {\n totalIssues: 0,\n highSeverity: 0,\n mediumSeverity: 0,\n lowSeverity: 0,\n recommendation: reason,\n },\n findings: {\n security: [],\n logic: [],\n bestPractices: [],\n performance: [],\n },\n };\n}\n\nexport function countFindings(parsed: ParsedOracleResponse): FindingCounts {\n const counts: FindingCounts = {\n total: parsed.summary.totalIssues,\n high: parsed.summary.highSeverity,\n medium: parsed.summary.mediumSeverity,\n low: parsed.summary.lowSeverity,\n byCategory: {\n security: 0,\n logic: 0,\n bestPractices: 0,\n performance: 0,\n },\n };\n\n if (parsed.findings) {\n counts.byCategory.security = parsed.findings.security?.length || 0;\n counts.byCategory.logic = parsed.findings.logic?.length || 0;\n counts.byCategory.bestPractices = parsed.findings.bestPractices?.length || 0;\n counts.byCategory.performance = parsed.findings.performance?.length || 0;\n }\n\n if (parsed.storyFindings) {\n for (const story of parsed.storyFindings) {\n counts.byCategory.security += story.findings.security?.length || 0;\n counts.byCategory.logic += story.findings.logic?.length || 0;\n counts.byCategory.bestPractices += story.findings.bestPractices?.length || 0;\n counts.byCategory.performance += story.findings.performance?.length || 0;\n }\n }\n\n return counts;\n}\n\nexport function extractAllFindings(parsed: ParsedOracleResponse): FindingDetail[] {\n const allFindings: FindingDetail[] = [];\n\n if (parsed.findings) {\n for (const category of [\"security\", \"logic\", \"bestPractices\", \"performance\"] as const) {\n const findings = parsed.findings[category] || [];\n for (const finding of findings) {\n allFindings.push({ ...finding, category });\n }\n }\n }\n\n if (parsed.storyFindings) {\n for (const story of parsed.storyFindings) {\n for (const category of [\"security\", \"logic\", \"bestPractices\", \"performance\"] as const) {\n const findings = story.findings[category] || [];\n for (const finding of findings) {\n allFindings.push({ ...finding, category });\n }\n }\n }\n }\n\n return allFindings;\n}\n\nexport function sortFindingsBySeverity(findings: FindingDetail[]): FindingDetail[] {\n const severityOrder: Record<FindingSeverity, number> = { high: 0, medium: 1, low: 2 };\n return [...findings].sort((a, b) => severityOrder[a.severity] - severityOrder[b.severity]);\n}\n","import { readFile } from \"node:fs/promises\";\nimport { basename } from \"node:path\";\nimport { parse as parseYaml } from \"yaml\";\nimport type { BmadAgentFullPersona, BmadAgentType } from \"../../shared/types.js\";\nimport { BMAD_AGENT_FULL_PERSONAS } from \"../../shared/types.js\";\nimport { findAgentFiles } from \"./bmad-finder.js\";\nimport { createPluginLogger } from \"./plugin-logger.js\";\n\nconst log = createPluginLogger(\"persona-loader\");\n\ninterface BmadAgentYaml {\n agent: {\n metadata: {\n id: string;\n name: string;\n title: string;\n icon: string;\n module?: string;\n };\n persona: {\n role: string;\n identity: string;\n communication_style: string;\n principles: string;\n };\n };\n}\n\nfunction filenameToAgentType(filename: string): BmadAgentType | null {\n const base = basename(filename, \".agent.yaml\");\n\n const typeMap: Record<string, BmadAgentType> = {\n analyst: \"analyst\",\n architect: \"architect\",\n dev: \"dev\",\n pm: \"pm\",\n sm: \"sm\",\n tea: \"tea\",\n \"tech-writer\": \"tech-writer\",\n \"ux-designer\": \"ux-designer\",\n };\n\n return typeMap[base] || null;\n}\n\nfunction parsePrinciples(principlesText: string): string[] {\n const lines = principlesText\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter(Boolean);\n\n return lines\n .filter((line) => line.startsWith(\"-\"))\n .map((line) => line.substring(1).trim())\n .filter(Boolean);\n}\n\n/**\n * Parse a BMAD agent YAML file into a persona object.\n *\n * YAML-to-TypeScript field mappings:\n * - agent.persona.role → persona.perspective\n * - agent.persona.communication_style → persona.communicationStyle\n *\n * Falls back to built-in personas for missing or invalid fields.\n */\nasync function parseAgentYaml(\n filePath: string\n): Promise<{ type: BmadAgentType; persona: BmadAgentFullPersona } | null> {\n const agentType = filenameToAgentType(filePath);\n if (!agentType) {\n return null;\n }\n\n try {\n const content = await readFile(filePath, \"utf-8\");\n const data = parseYaml(content) as BmadAgentYaml;\n\n if (!data?.agent?.metadata || !data?.agent?.persona) {\n return null;\n }\n\n const { metadata, persona: personaData } = data.agent;\n const fallback = BMAD_AGENT_FULL_PERSONAS[agentType];\n\n const principles = personaData.principles\n ? parsePrinciples(personaData.principles)\n : fallback.principles;\n\n const persona: BmadAgentFullPersona = {\n type: agentType,\n name: metadata.name || fallback.name,\n title: metadata.title || fallback.title,\n icon: metadata.icon || fallback.icon,\n expertise: fallback.expertise,\n perspective: personaData.role || fallback.perspective,\n identity: personaData.identity || fallback.identity,\n communicationStyle: personaData.communication_style || fallback.communicationStyle,\n principles,\n };\n\n return { type: agentType, persona };\n } catch (error) {\n log.warn(\"Failed to parse agent YAML file\", {\n filePath,\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n return null;\n }\n}\n\nasync function loadFromYamlFiles(\n agentFiles: string[]\n): Promise<Map<BmadAgentType, BmadAgentFullPersona>> {\n const personas = new Map<BmadAgentType, BmadAgentFullPersona>();\n\n for (const filePath of agentFiles) {\n const result = await parseAgentYaml(filePath);\n if (result) {\n personas.set(result.type, result.persona);\n }\n }\n\n return personas;\n}\n\nexport async function loadPersonas(\n projectRoot: string\n): Promise<Map<BmadAgentType, BmadAgentFullPersona>> {\n const agentFiles = await findAgentFiles(projectRoot);\n\n if (agentFiles.length > 0) {\n const yamlPersonas = await loadFromYamlFiles(agentFiles);\n\n if (yamlPersonas.size > 0) {\n const merged = new Map<BmadAgentType, BmadAgentFullPersona>();\n\n for (const [type, persona] of Object.entries(BMAD_AGENT_FULL_PERSONAS)) {\n merged.set(type as BmadAgentType, persona);\n }\n\n for (const [type, persona] of yamlPersonas) {\n merged.set(type, persona);\n }\n\n return merged;\n }\n }\n\n return new Map(\n Object.entries(BMAD_AGENT_FULL_PERSONAS) as [BmadAgentType, BmadAgentFullPersona][]\n );\n}\n\nexport function getPersona(\n personas: Map<BmadAgentType, BmadAgentFullPersona>,\n agentType: BmadAgentType\n): BmadAgentFullPersona {\n return personas.get(agentType) || BMAD_AGENT_FULL_PERSONAS[agentType];\n}\n\nexport function selectAgentsForFinding(category: string, severity: string): BmadAgentType[] {\n const agents: BmadAgentType[] = [];\n\n switch (category) {\n case \"security\":\n agents.push(\"architect\", \"dev\", \"tea\");\n break;\n case \"logic\":\n agents.push(\"dev\", \"tea\", \"analyst\");\n break;\n case \"performance\":\n agents.push(\"architect\", \"dev\");\n break;\n case \"bestPractices\":\n agents.push(\"dev\", \"tech-writer\");\n break;\n default:\n agents.push(\"dev\", \"architect\");\n }\n\n if (severity === \"high\" && !agents.includes(\"pm\")) {\n agents.push(\"pm\");\n }\n\n return agents.slice(0, 3);\n}\n\nexport function buildAgentSystemPrompt(\n persona: BmadAgentFullPersona,\n phase2Analysis?: string\n): string {\n const principlesList = persona.principles.map((p) => `- ${p}`).join(\"\\n\");\n\n let prompt = `You are ${persona.name}, the ${persona.title} from the BMAD team.\n\n**Your Icon**: ${persona.icon}\n**Your Expertise**: ${persona.expertise.join(\", \")}\n**Your Perspective**: ${persona.perspective}\n\n**Your Identity**:\n${persona.identity}\n\n**Your Communication Style**:\n${persona.communicationStyle}\n\n**Your Principles**:\n${principlesList}\n\n**Response Guidelines**:\n- Stay in character as ${persona.name}\n- Speak from your ${persona.perspective} perspective\n- Be concise but substantive (2-4 sentences per point)\n- Reference other agents by name when building on or disagreeing with their points\n- Use your icon ${persona.icon} at the start of your responses`;\n\n if (phase2Analysis) {\n prompt += `\n\n**Your Previous Analysis** (from Phase 2):\n${phase2Analysis}\n\nUse your previous analysis to inform this discussion. You already have context on these findings.`;\n }\n\n return prompt;\n}\n\nexport const _testExports = {\n filenameToAgentType,\n parsePrinciples,\n parseAgentYaml,\n loadFromYamlFiles,\n};\n","import { existsSync } from \"node:fs\";\nimport { readFile, readdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport type { DiscussionRound, FindingCategory, ParsedDeferTarget } from \"../../shared/types.js\";\nimport { findStoriesForEpic } from \"./story-loader.js\";\n\ninterface DeferredFinding {\n id: string;\n title: string;\n description?: string;\n category: FindingCategory;\n severity: string;\n reason?: string;\n originalStoryId: string;\n}\n\ninterface StoryTemplateContext {\n storyId: string;\n epicNumber: string;\n storyNumber: string;\n title: string;\n findings: DeferredFinding[];\n originalStoryId: string;\n reviewDate: string;\n reviewDocumentPath?: string;\n}\n\nexport function parseDeferTarget(\n input: string,\n epicNumber: string,\n existingStoryIds: string[]\n): ParsedDeferTarget {\n const normalized = input.trim().toLowerCase();\n const originalInput = input.trim();\n\n const exactMatch = originalInput.match(/^(\\d+)\\.(\\d+[a-z]?)$/i);\n if (exactMatch) {\n const storyId = `${exactMatch[1]}.${exactMatch[2]}`;\n const exists = existingStoryIds.includes(storyId);\n return {\n type: exists ? \"append-existing\" : \"exact\",\n storyId,\n originalInput,\n };\n }\n\n const dashMatch = originalInput.match(/^(\\d+)-(\\d+[a-z]?)$/i);\n if (dashMatch) {\n const storyId = `${dashMatch[1]}.${dashMatch[2]}`;\n const exists = existingStoryIds.includes(storyId);\n return {\n type: exists ? \"append-existing\" : \"exact\",\n storyId,\n originalInput,\n };\n }\n\n if (normalized.includes(\"new story after\")) {\n const afterMatch = normalized.match(/after\\s+(\\d+\\.?\\d*[a-z]?)/);\n if (afterMatch) {\n const refId = afterMatch[1].includes(\".\") ? afterMatch[1] : `${epicNumber}.${afterMatch[1]}`;\n const nextSubId = getNextSubNumber(refId, existingStoryIds);\n return {\n type: \"new-after\",\n storyId: nextSubId,\n referenceStoryId: refId,\n originalInput,\n };\n }\n }\n\n if (normalized.includes(\"new story before\")) {\n const beforeMatch = normalized.match(/before\\s+(\\d+\\.?\\d*[a-z]?)/);\n if (beforeMatch) {\n const refId = beforeMatch[1].includes(\".\")\n ? beforeMatch[1]\n : `${epicNumber}.${beforeMatch[1]}`;\n const [epicNum, storyNum] = refId.split(\".\");\n const prevNum = Number.parseInt(storyNum, 10) - 1;\n if (prevNum > 0) {\n const prevId = `${epicNum}.${prevNum}`;\n const nextSubId = getNextSubNumber(prevId, existingStoryIds);\n return {\n type: \"new-before\",\n storyId: nextSubId,\n referenceStoryId: refId,\n originalInput,\n };\n }\n }\n }\n\n if (normalized.includes(\"new story\") || normalized === \"new\" || normalized === \"end of epic\") {\n const nextId = getNextStoryNumber(epicNumber, existingStoryIds);\n return {\n type: \"new-end\",\n storyId: nextId,\n originalInput,\n };\n }\n\n if (\n normalized.includes(\"next sprint\") ||\n normalized.includes(\"later\") ||\n normalized.includes(\"backlog\")\n ) {\n const nextId = getNextStoryNumber(epicNumber, existingStoryIds);\n return {\n type: \"new-end\",\n storyId: nextId,\n originalInput,\n };\n }\n\n const storyIdMatch = originalInput.match(/(\\d+)[.\\-](\\d+[a-z]?)/i);\n if (storyIdMatch) {\n const storyId = `${storyIdMatch[1]}.${storyIdMatch[2]}`;\n const exists = existingStoryIds.includes(storyId);\n return {\n type: exists ? \"append-existing\" : \"exact\",\n storyId,\n originalInput,\n };\n }\n\n const nextId = getNextStoryNumber(epicNumber, existingStoryIds);\n return {\n type: \"new-end\",\n storyId: nextId,\n originalInput,\n };\n}\n\nexport function getNextSubNumber(afterStoryId: string, existingIds: string[]): string {\n const [epicNum, storyNum] = afterStoryId.split(\".\");\n const baseNum = storyNum.replace(/[a-z]+$/i, \"\");\n\n const existingSubs = existingIds\n .filter((id) => {\n const [e, s] = id.split(\".\");\n return e === epicNum && s.startsWith(baseNum) && /[a-z]$/i.test(s);\n })\n .map((id) => {\n const suffix = id.split(\".\")[1].replace(/^\\d+/, \"\");\n return suffix;\n })\n .filter((s) => s.length > 0)\n .sort();\n\n if (existingSubs.length === 0) {\n return `${epicNum}.${baseNum}a`;\n }\n\n const lastSuffix = existingSubs[existingSubs.length - 1];\n const nextChar = String.fromCharCode(lastSuffix.charCodeAt(lastSuffix.length - 1) + 1);\n return `${epicNum}.${baseNum}${nextChar}`;\n}\n\nexport function getNextStoryNumber(epicNumber: string, existingIds: string[]): string {\n const epicIds = existingIds\n .filter((id) => id.startsWith(`${epicNumber}.`))\n .map((id) => {\n const num = id.split(\".\")[1];\n const baseNum = Number.parseInt(num.replace(/[a-z]+$/i, \"\"), 10);\n return Number.isNaN(baseNum) ? 0 : baseNum;\n });\n\n const maxNum = epicIds.length > 0 ? Math.max(...epicIds) : 0;\n return `${epicNumber}.${maxNum + 1}`;\n}\n\nexport async function getExistingStoryIds(\n storiesDir: string,\n epicNumber: string\n): Promise<string[]> {\n const stories = await findStoriesForEpic(storiesDir, epicNumber);\n return stories.map((s) => s.id);\n}\n\nexport async function loadTemplateFromExistingStory(\n storiesDir: string,\n epicNumber: string\n): Promise<string | null> {\n if (!existsSync(storiesDir)) {\n return null;\n }\n\n const files = await readdir(storiesDir);\n const epicPattern = new RegExp(`^(story-)?${epicNumber}-(\\\\d+)`, \"i\");\n\n const epicFiles = files.filter((f) => epicPattern.test(f) && f.endsWith(\".md\")).sort();\n\n if (epicFiles.length === 0) {\n return null;\n }\n\n const templateFile = epicFiles[0];\n const content = await readFile(join(storiesDir, templateFile), \"utf-8\");\n return content;\n}\n\nfunction extractTemplateStructure(existingContent: string): string[] {\n const lines = existingContent.split(\"\\n\");\n const sections: string[] = [];\n let currentSection = \"\";\n\n for (const line of lines) {\n if (line.startsWith(\"# \") || line.startsWith(\"## \")) {\n if (currentSection) {\n sections.push(currentSection.trim());\n }\n currentSection = line;\n } else {\n currentSection += `\\n${line}`;\n }\n }\n\n if (currentSection) {\n sections.push(currentSection.trim());\n }\n\n return sections;\n}\n\nexport function generateStoryContent(\n context: StoryTemplateContext,\n _existingTemplate?: string\n): string {\n const { storyId, title, findings, originalStoryId, reviewDate, reviewDocumentPath } = context;\n\n const acceptanceCriteria = findings\n .map((f) => {\n const prefix = getCategoryPrefix(f.category);\n return `- [ ] ${prefix}: ${f.title}${f.description ? ` - ${f.description}` : \"\"}`;\n })\n .join(\"\\n\");\n\n const devNotes = findings\n .map((f) => {\n return `- **${f.title}**\n - Severity: ${f.severity}\n - Category: ${f.category}\n - Reason for deferral: ${f.reason || \"Deferred from party review\"}`;\n })\n .join(\"\\n\");\n\n const content = `# Story ${storyId}: ${title}\n\nStatus: backlog\n\n## Story\n\nAs a developer,\nI want to address the deferred findings from the party review,\nso that the codebase maintains quality standards.\n\n## Acceptance Criteria\n\n${acceptanceCriteria}\n\n## Tasks / Subtasks\n\n- [ ] Review each deferred finding\n- [ ] Implement fixes for each acceptance criterion\n- [ ] Run quality checks (LSP diagnostics, build, tests)\n\n## Dev Notes\n\nThese findings were deferred from the party review of Story ${originalStoryId} on ${reviewDate}.\n\n### Original Context\n\n${devNotes}\n\n### References\n\n${reviewDocumentPath ? `- Party Review: ${reviewDocumentPath}` : \"\"}\n- Original Story: Story ${originalStoryId}\n\n## Dev Agent Record\n\n### Agent Model Used\n\n(To be filled during implementation)\n\n### Completion Notes List\n\n(To be filled during implementation)\n\n### File List\n\n(To be filled during implementation)\n`;\n\n return content;\n}\n\nfunction getCategoryPrefix(category: FindingCategory): string {\n switch (category) {\n case \"security\":\n return \"[Security]\";\n case \"performance\":\n return \"[Performance]\";\n case \"bestPractices\":\n return \"[Quality]\";\n default:\n return \"[Logic]\";\n }\n}\n\nexport function generateTitleFromFindings(findings: DeferredFinding[]): string {\n if (findings.length === 1) {\n const f = findings[0];\n const shortTitle = f.title.length > 50 ? `${f.title.substring(0, 47)}...` : f.title;\n return shortTitle;\n }\n\n const categories = [...new Set(findings.map((f) => f.category))];\n if (categories.length === 1) {\n return `Deferred ${formatCategory(categories[0])} Findings`;\n }\n\n return \"Deferred Findings from Party Review\";\n}\n\nfunction formatCategory(category: FindingCategory): string {\n switch (category) {\n case \"security\":\n return \"Security\";\n case \"performance\":\n return \"Performance\";\n case \"bestPractices\":\n return \"Quality\";\n default:\n return \"Logic\";\n }\n}\n\nexport function roundsToFindings(\n rounds: DiscussionRound[],\n originalStoryId: string\n): DeferredFinding[] {\n return rounds.map((round) => ({\n id: round.findingId,\n title: round.findingTitle,\n category: round.findingCategory,\n severity: round.findingSeverity,\n reason: round.decisionReason,\n originalStoryId,\n }));\n}\n\nexport function storyIdToFilename(storyId: string, title?: string): string {\n const [epic, num] = storyId.split(\".\");\n const kebabTitle = title\n ? `-${title\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-|-$/g, \"\")\n .substring(0, 30)}`\n : \"\";\n return `story-${epic}-${num}${kebabTitle}.md`;\n}\n\nexport const _testExports = {\n extractTemplateStructure,\n getCategoryPrefix,\n formatCategory,\n};\n","import { existsSync } from \"node:fs\";\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport type {\n AppliedStoryUpdate,\n ApplyDecisionsResult,\n AthenaConfig,\n DiscussionRound,\n ParsedDeferTarget,\n PartyDiscussionState,\n} from \"../../shared/types.js\";\nimport { getBmadPaths } from \"./bmad-finder.js\";\nimport { extractStoryIdFromFindingId, findStoryFile } from \"./story-loader.js\";\nimport {\n generateStoryContent,\n generateTitleFromFindings,\n getExistingStoryIds,\n loadTemplateFromExistingStory,\n parseDeferTarget,\n roundsToFindings,\n storyIdToFilename,\n} from \"./story-template.js\";\nimport { addStoryToSprintStatus } from \"./yaml-handler.js\";\n\ninterface StoryUpdate {\n storyId: string;\n filePath: string;\n addedCriteria: string[];\n addedNotes: string[];\n success: boolean;\n error?: string;\n}\n\nfunction groupDecisionsByStory(\n rounds: DiscussionRound[],\n sessionIdentifier: string\n): Map<string, DiscussionRound[]> {\n const byStory = new Map<string, DiscussionRound[]>();\n\n for (const round of rounds) {\n const storyId = extractStoryIdFromFindingId(round.findingId, sessionIdentifier);\n\n const existing = byStory.get(storyId) || [];\n existing.push(round);\n byStory.set(storyId, existing);\n }\n\n return byStory;\n}\n\nfunction groupDeferredByTarget(\n rounds: DiscussionRound[],\n epicNumber: string,\n existingStoryIds: string[]\n): Map<string, { target: ParsedDeferTarget; rounds: DiscussionRound[] }> {\n const byTarget = new Map<string, { target: ParsedDeferTarget; rounds: DiscussionRound[] }>();\n\n for (const round of rounds) {\n if (round.decision !== \"defer\" || !round.deferredTo) continue;\n\n const target = parseDeferTarget(round.deferredTo, epicNumber, existingStoryIds);\n const key = target.storyId;\n\n const existing = byTarget.get(key);\n if (existing) {\n existing.rounds.push(round);\n } else {\n byTarget.set(key, { target, rounds: [round] });\n }\n }\n\n return byTarget;\n}\n\nfunction generateAcceptanceCriteria(round: DiscussionRound): string {\n const prefix = getCategoryPrefix(round.findingCategory);\n return `- [ ] ${prefix}: ${round.findingTitle}`;\n}\n\nfunction getCategoryPrefix(category: string): string {\n switch (category) {\n case \"security\":\n return \"[Security]\";\n case \"performance\":\n return \"[Performance]\";\n case \"bestPractices\":\n return \"[Quality]\";\n default:\n return \"[Logic]\";\n }\n}\n\nfunction generateImplementationNote(round: DiscussionRound): string {\n const date = new Date().toISOString().split(\"T\")[0];\n let note = `### ${round.findingTitle} (${date})\\n`;\n note += `- **Category**: ${round.findingCategory}\\n`;\n note += `- **Severity**: ${round.findingSeverity}\\n`;\n note += `- **Decision**: ${round.decision}`;\n\n if (round.decisionReason) {\n note += `\\n- **Reason**: ${round.decisionReason}`;\n }\n\n if (round.deferredTo) {\n note += `\\n- **Deferred to**: Story ${round.deferredTo}`;\n }\n\n return note;\n}\n\nasync function updateStoryFile(\n filePath: string,\n acceptedRounds: DiscussionRound[],\n deferredRounds: DiscussionRound[]\n): Promise<StoryUpdate> {\n const storyId = filePath.match(/story-(\\d+-\\d+[a-z]?)/)?.[1]?.replace(\"-\", \".\") || \"unknown\";\n\n if (!existsSync(filePath)) {\n return {\n storyId,\n filePath,\n addedCriteria: [],\n addedNotes: [],\n success: false,\n error: `Story file not found: ${filePath}`,\n };\n }\n\n try {\n let content = await readFile(filePath, \"utf-8\");\n const addedCriteria: string[] = [];\n const addedNotes: string[] = [];\n\n if (acceptedRounds.length > 0) {\n const acSection = content.match(/## Acceptance Criteria[\\s\\S]*?(?=\\n##|\\n---|$)/);\n\n if (acSection && acSection.index !== undefined) {\n const newCriteria = acceptedRounds.map(generateAcceptanceCriteria);\n const insertPoint = acSection.index + acSection[0].length;\n\n const criteriaText = newCriteria.join(\"\\n\");\n const insertion = `\\n\\n### From Party Review\\n${criteriaText}`;\n content = `${content.slice(0, insertPoint)}${insertion}${content.slice(insertPoint)}`;\n\n addedCriteria.push(...newCriteria);\n }\n }\n\n if (deferredRounds.length > 0 || acceptedRounds.length > 0) {\n const hasNotesSection = content.includes(\"## Implementation Notes\");\n\n const notes = [\n ...acceptedRounds.map(generateImplementationNote),\n ...deferredRounds.map(generateImplementationNote),\n ];\n\n if (hasNotesSection) {\n const notesMatch = content.match(/## Implementation Notes/);\n if (notesMatch && notesMatch.index !== undefined) {\n const insertPoint = notesMatch.index + notesMatch[0].length;\n const notesText = notes.join(\"\\n\\n\");\n const insertion = `\\n\\n${notesText}`;\n content = `${content.slice(0, insertPoint)}${insertion}${content.slice(insertPoint)}`;\n }\n } else {\n const notesText = notes.join(\"\\n\\n\");\n content = `${content}\\n\\n## Implementation Notes\\n\\n${notesText}`;\n }\n\n addedNotes.push(...notes);\n }\n\n await writeFile(filePath, content, \"utf-8\");\n\n return {\n storyId,\n filePath,\n addedCriteria,\n addedNotes,\n success: true,\n };\n } catch (error) {\n return {\n storyId,\n filePath,\n addedCriteria: [],\n addedNotes: [],\n success: false,\n error: error instanceof Error ? error.message : \"Unknown error\",\n };\n }\n}\n\nasync function appendToExistingStory(\n filePath: string,\n rounds: DiscussionRound[],\n originalStoryId: string\n): Promise<AppliedStoryUpdate> {\n const storyId = filePath.match(/story-(\\d+-\\d+[a-z]?)/)?.[1]?.replace(\"-\", \".\") || \"unknown\";\n\n if (!existsSync(filePath)) {\n return {\n storyId,\n filePath,\n action: \"appended\",\n addedCriteria: [],\n addedNotes: [],\n success: false,\n error: `Story file not found: ${filePath}`,\n };\n }\n\n try {\n let content = await readFile(filePath, \"utf-8\");\n const addedCriteria: string[] = [];\n const addedNotes: string[] = [];\n const date = new Date().toISOString().split(\"T\")[0];\n\n const hasNotesSection = content.includes(\"## Implementation Notes\");\n const deferralHeader = `\\n\\n### Deferred from Story ${originalStoryId} (${date})\\n\\n`;\n const notes = rounds.map((r) => {\n const prefix = getCategoryPrefix(r.findingCategory);\n return `- [ ] ${prefix}: ${r.findingTitle}${r.decisionReason ? ` (${r.decisionReason})` : \"\"}`;\n });\n const notesText = deferralHeader + notes.join(\"\\n\");\n\n if (hasNotesSection) {\n const notesMatch = content.match(/## Implementation Notes/);\n if (notesMatch && notesMatch.index !== undefined) {\n const insertPoint = notesMatch.index + notesMatch[0].length;\n content = `${content.slice(0, insertPoint)}${notesText}${content.slice(insertPoint)}`;\n }\n } else {\n content = `${content}\\n\\n## Implementation Notes${notesText}`;\n }\n\n addedNotes.push(...notes);\n\n await writeFile(filePath, content, \"utf-8\");\n\n return {\n storyId,\n filePath,\n action: \"appended\",\n addedCriteria,\n addedNotes,\n success: true,\n };\n } catch (error) {\n return {\n storyId,\n filePath,\n action: \"appended\",\n addedCriteria: [],\n addedNotes: [],\n success: false,\n error: error instanceof Error ? error.message : \"Unknown error\",\n };\n }\n}\n\nasync function createStoryFromDeferredFindings(\n storiesDir: string,\n target: ParsedDeferTarget,\n rounds: DiscussionRound[],\n originalStoryId: string,\n sprintStatusPath: string,\n reviewDocumentPath?: string\n): Promise<AppliedStoryUpdate> {\n const epicNumber = target.storyId.split(\".\")[0];\n const findings = roundsToFindings(rounds, originalStoryId);\n const title = generateTitleFromFindings(findings);\n const date = new Date().toISOString().split(\"T\")[0];\n\n const template = await loadTemplateFromExistingStory(storiesDir, epicNumber);\n\n const context = {\n storyId: target.storyId,\n epicNumber,\n storyNumber: target.storyId.split(\".\")[1],\n title,\n findings,\n originalStoryId,\n reviewDate: date,\n reviewDocumentPath,\n };\n\n const content = generateStoryContent(context, template || undefined);\n const filename = storyIdToFilename(target.storyId, title);\n const filePath = join(storiesDir, filename);\n\n try {\n if (!existsSync(storiesDir)) {\n await mkdir(storiesDir, { recursive: true });\n }\n\n await writeFile(filePath, content, \"utf-8\");\n\n await addStoryToSprintStatus(sprintStatusPath, target.storyId, \"backlog\");\n\n return {\n storyId: target.storyId,\n filePath,\n action: \"created\",\n addedCriteria: findings.map((f) => `- [ ] [${f.category}]: ${f.title}`),\n addedNotes: [],\n success: true,\n deferTarget: target,\n };\n } catch (error) {\n return {\n storyId: target.storyId,\n filePath,\n action: \"created\",\n addedCriteria: [],\n addedNotes: [],\n success: false,\n error: error instanceof Error ? error.message : \"Unknown error\",\n deferTarget: target,\n };\n }\n}\n\nasync function updateReviewDocument(\n reviewPath: string,\n state: PartyDiscussionState\n): Promise<boolean> {\n if (!existsSync(reviewPath)) {\n return false;\n }\n\n try {\n let content = await readFile(reviewPath, \"utf-8\");\n\n const decisionSection = generateDecisionSection(state);\n content = `${content}\\n\\n---\\n\\n${decisionSection}`;\n\n await writeFile(reviewPath, content, \"utf-8\");\n return true;\n } catch {\n return false;\n }\n}\n\nfunction generateDecisionSection(state: PartyDiscussionState): string {\n const counts = { accepted: 0, deferred: 0, rejected: 0 };\n\n for (const round of state.completedRounds) {\n if (round.decision === \"accept\") counts.accepted++;\n else if (round.decision === \"defer\") counts.deferred++;\n else if (round.decision === \"reject\") counts.rejected++;\n }\n\n const date = new Date().toISOString().split(\"T\")[0];\n const findingLines: string[] = [];\n\n for (const round of state.completedRounds) {\n const icon = round.decision === \"accept\" ? \"✅\" : round.decision === \"defer\" ? \"⏸️\" : \"❌\";\n const lines = [`${icon} **${round.findingTitle}**`, `- Decision: ${round.decision}`];\n if (round.decisionReason) {\n lines.push(`- Reason: ${round.decisionReason}`);\n }\n if (round.deferredTo) {\n lines.push(`- Deferred to: Story ${round.deferredTo}`);\n }\n findingLines.push(lines.join(\"\\n\"));\n }\n\n return `## Party Discussion Decisions\n\n**Date**: ${date}\n**Session ID**: ${state.sessionId}\n\n### Summary\n- ✅ Accepted: ${counts.accepted}\n- ⏸️ Deferred: ${counts.deferred}\n- ❌ Rejected: ${counts.rejected}\n\n### Decisions by Finding\n\n${findingLines.join(\"\\n\\n\")}`;\n}\n\nexport async function generateDecisionsAppliedDocument(\n reviewFolderPath: string,\n state: PartyDiscussionState,\n result: ApplyDecisionsResult\n): Promise<string | null> {\n const date = new Date().toISOString().split(\"T\")[0];\n const docPath = join(reviewFolderPath, \"decisions-applied.md\");\n\n const storiesUpdatedList = result.storiesUpdated\n .filter((s) => s.success)\n .map(\n (s) =>\n `- ✅ Updated: ${s.filePath} (${s.addedCriteria.length} criteria, ${s.addedNotes.length} notes)`\n )\n .join(\"\\n\");\n\n const storiesCreatedList = result.storiesCreated\n .filter((s) => s.success)\n .map((s) => `- 📝 Created: ${s.filePath} (${s.addedCriteria.length} criteria)`)\n .join(\"\\n\");\n\n const storiesAppendedList = result.storiesAppended\n .filter((s) => s.success)\n .map((s) => `- 📎 Appended to: ${s.filePath} (${s.addedNotes.length} items)`)\n .join(\"\\n\");\n\n const failedList = [...result.storiesUpdated, ...result.storiesCreated, ...result.storiesAppended]\n .filter((s) => !s.success)\n .map((s) => `- ❌ Failed: ${s.storyId} - ${s.error}`)\n .join(\"\\n\");\n\n const content = `# Decisions Applied\n\n**Date**: ${date}\n**Session ID**: ${state.sessionId}\n**Scope**: ${state.scope} - ${state.identifier}\n\n## Summary\n\n| Metric | Count |\n|--------|-------|\n| Findings Accepted | ${result.summary.accepted} |\n| Findings Deferred | ${result.summary.deferred} |\n| Findings Rejected | ${result.summary.rejected} |\n| Stories Modified | ${result.summary.storiesModified} |\n| Stories Created | ${result.summary.storiesCreated} |\n\n## Applied Changes\n\n### Stories Updated\n${storiesUpdatedList || \"(none)\"}\n\n### Stories Created\n${storiesCreatedList || \"(none)\"}\n\n### Stories Appended To\n${storiesAppendedList || \"(none)\"}\n\n${failedList ? `### Failed Operations\\n${failedList}` : \"\"}\n\n${result.warnings && result.warnings.length > 0 ? `## Warnings\\n${result.warnings.map((w) => `- ⚠️ ${w}`).join(\"\\n\")}` : \"\"}\n\n## Next Steps\n\n${result.storiesCreated.length > 0 ? \"- New stories created with status 'backlog' and added to sprint-status.yaml\" : \"\"}\n${result.storiesUpdated.length > 0 ? \"- Updated stories have new acceptance criteria from the party review\" : \"\"}\n${result.storiesAppended.length > 0 ? \"- Existing stories have deferred findings in their Implementation Notes section\" : \"\"}\n- Run \\`/athena-dev\\` to implement the next story\n\n---\n\n*Generated by OpenCode Athena Party Review*\n`;\n\n try {\n await writeFile(docPath, content, \"utf-8\");\n return docPath;\n } catch {\n return null;\n }\n}\n\nexport async function applyDecisions(\n projectRoot: string,\n state: PartyDiscussionState,\n reviewDocumentPath?: string,\n config?: AthenaConfig\n): Promise<ApplyDecisionsResult> {\n const paths = await getBmadPaths(projectRoot, config);\n const byStory = groupDecisionsByStory(state.completedRounds, state.identifier);\n const epicNumber = state.identifier.split(\".\")[0];\n\n const existingStoryIds = await getExistingStoryIds(paths.storiesDir, epicNumber);\n\n const storiesUpdated: AppliedStoryUpdate[] = [];\n const storiesCreated: AppliedStoryUpdate[] = [];\n const storiesAppended: AppliedStoryUpdate[] = [];\n const warnings: string[] = [];\n\n let totalAccepted = 0;\n let totalDeferred = 0;\n let totalRejected = 0;\n\n for (const [storyId, rounds] of byStory) {\n const storyFileResult = await findStoryFile(paths.storiesDir, storyId);\n if (!storyFileResult) {\n continue;\n }\n\n const accepted = rounds.filter((r) => r.decision === \"accept\");\n const deferred = rounds.filter((r) => r.decision === \"defer\");\n const rejected = rounds.filter((r) => r.decision === \"reject\");\n\n totalAccepted += accepted.length;\n totalDeferred += deferred.length;\n totalRejected += rejected.length;\n\n if (accepted.length > 0 || deferred.length > 0) {\n const update = await updateStoryFile(storyFileResult.path, accepted, deferred);\n storiesUpdated.push({\n ...update,\n action: \"updated\",\n });\n }\n }\n\n const deferredRounds = state.completedRounds.filter(\n (r) => r.decision === \"defer\" && r.deferredTo\n );\n const deferredByTarget = groupDeferredByTarget(deferredRounds, epicNumber, existingStoryIds);\n\n for (const [targetId, { target, rounds }] of deferredByTarget) {\n const originalStoryId = state.identifier;\n\n if (target.type === \"append-existing\") {\n const storyFileResult = await findStoryFile(paths.storiesDir, targetId);\n if (storyFileResult) {\n const appendResult = await appendToExistingStory(\n storyFileResult.path,\n rounds,\n originalStoryId\n );\n storiesAppended.push(appendResult);\n } else {\n warnings.push(`Could not find story ${targetId} to append deferred findings`);\n }\n } else if (\n target.type === \"exact\" ||\n target.type === \"new-end\" ||\n target.type === \"new-after\" ||\n target.type === \"new-before\"\n ) {\n const reviewFolder = reviewDocumentPath ? dirname(reviewDocumentPath) : undefined;\n const createResult = await createStoryFromDeferredFindings(\n paths.storiesDir,\n target,\n rounds,\n originalStoryId,\n paths.sprintStatus,\n reviewFolder\n );\n storiesCreated.push(createResult);\n\n if (\n target.originalInput.toLowerCase().includes(\"next sprint\") ||\n target.originalInput.toLowerCase().includes(\"later\")\n ) {\n warnings.push(\n `Story ${targetId} created for vague defer target \"${target.originalInput}\" - review sprint-status.yaml for correct ordering`\n );\n }\n }\n }\n\n let reviewDocumentUpdated = false;\n if (reviewDocumentPath) {\n reviewDocumentUpdated = await updateReviewDocument(reviewDocumentPath, state);\n }\n\n const result: ApplyDecisionsResult = {\n success: true,\n storiesUpdated,\n storiesCreated,\n storiesAppended,\n reviewDocumentUpdated,\n summary: {\n accepted: totalAccepted,\n deferred: totalDeferred,\n rejected: totalRejected,\n storiesModified: storiesUpdated.filter((u) => u.success).length,\n storiesCreated: storiesCreated.filter((u) => u.success).length,\n },\n warnings: warnings.length > 0 ? warnings : undefined,\n };\n\n const reviewFolder = reviewDocumentPath ? dirname(reviewDocumentPath) : null;\n if (reviewFolder) {\n const docPath = await generateDecisionsAppliedDocument(reviewFolder, state, result);\n if (docPath) {\n result.decisionsAppliedDocument = docPath;\n }\n }\n\n return result;\n}\n\nexport function formatAppliedUpdatesSummary(result: ApplyDecisionsResult): string {\n const parts: string[] = [];\n\n parts.push(\"## Decisions Applied\\n\");\n parts.push(\"**Summary**:\");\n parts.push(`- ✅ Accepted findings: ${result.summary.accepted}`);\n parts.push(`- ⏸️ Deferred findings: ${result.summary.deferred}`);\n parts.push(`- ❌ Rejected findings: ${result.summary.rejected}`);\n parts.push(`- 📝 Stories modified: ${result.summary.storiesModified}`);\n parts.push(`- 📄 Stories created: ${result.summary.storiesCreated}`);\n parts.push(\"\");\n\n if (result.storiesUpdated.length > 0) {\n parts.push(\"### Updated Stories\\n\");\n for (const update of result.storiesUpdated) {\n if (update.success) {\n parts.push(`- ✅ ${update.filePath}`);\n if (update.addedCriteria.length > 0) {\n parts.push(` - Added ${update.addedCriteria.length} acceptance criteria`);\n }\n if (update.addedNotes.length > 0) {\n parts.push(` - Added ${update.addedNotes.length} implementation notes`);\n }\n } else {\n parts.push(`- ❌ ${update.filePath}: ${update.error}`);\n }\n }\n parts.push(\"\");\n }\n\n if (result.storiesCreated.length > 0) {\n parts.push(\"### Created Stories\\n\");\n for (const created of result.storiesCreated) {\n if (created.success) {\n parts.push(`- 📄 ${created.filePath}`);\n parts.push(` - Story ID: ${created.storyId}`);\n parts.push(\n ` - ${created.addedCriteria.length} acceptance criteria from deferred findings`\n );\n } else {\n parts.push(`- ❌ Failed to create ${created.storyId}: ${created.error}`);\n }\n }\n parts.push(\"\");\n }\n\n if (result.storiesAppended.length > 0) {\n parts.push(\"### Appended to Existing Stories\\n\");\n for (const appended of result.storiesAppended) {\n if (appended.success) {\n parts.push(`- 📎 ${appended.filePath}`);\n parts.push(\n ` - ${appended.addedNotes.length} deferred items added to Implementation Notes`\n );\n } else {\n parts.push(`- ❌ Failed to append to ${appended.storyId}: ${appended.error}`);\n }\n }\n parts.push(\"\");\n }\n\n if (result.warnings && result.warnings.length > 0) {\n parts.push(\"### Warnings\\n\");\n for (const warning of result.warnings) {\n parts.push(`- ⚠️ ${warning}`);\n }\n parts.push(\"\");\n }\n\n if (result.decisionsAppliedDocument) {\n parts.push(\"### Documentation\\n\");\n parts.push(`- 📋 Decisions applied document: ${result.decisionsAppliedDocument}`);\n }\n\n if (result.reviewDocumentUpdated) {\n parts.push(\"- 📄 Review document updated with decisions\");\n }\n\n return parts.join(\"\\n\");\n}\n\nexport function formatUpdateSummary(result: ApplyDecisionsResult): string {\n return formatAppliedUpdatesSummary(result);\n}\n","import { randomUUID } from \"node:crypto\";\nimport { existsSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { type ToolDefinition, tool } from \"@opencode-ai/plugin\";\nimport type { PluginInput } from \"@opencode-ai/plugin\";\nimport type {\n AgentDiscussionResponse,\n AthenaConfig,\n BmadAgentFullPersona,\n BmadAgentType,\n DiscussionAgendaItem,\n DiscussionRound,\n FindingCategory,\n FindingSeverity,\n PartyDiscussionResult,\n PartyDiscussionState,\n Phase1FullData,\n Phase2Result,\n ReviewDecision,\n} from \"../../shared/types.js\";\nimport { extractAllFindings, parseOracleResponse } from \"../utils/oracle-parser.js\";\nimport { getPersona, loadPersonas, selectAgentsForFinding } from \"../utils/persona-loader.js\";\nimport { createPluginLogger } from \"../utils/plugin-logger.js\";\nimport { applyDecisions } from \"../utils/story-updater.js\";\n\nconst log = createPluginLogger(\"party-discussion\");\nconst SESSION_TTL_MS = 30 * 60 * 1000;\nconst MAX_SESSIONS = 10;\n\ninterface SessionWithMeta {\n state: PartyDiscussionState;\n lastAccessedAt: number;\n reviewFolderPath?: string;\n}\n\nconst activeSessions = new Map<string, SessionWithMeta>();\n\nfunction cleanupStaleSessions(): void {\n const now = Date.now();\n const sessionsToDelete: string[] = [];\n\n for (const [id, session] of activeSessions) {\n if (now - session.lastAccessedAt > SESSION_TTL_MS) {\n sessionsToDelete.push(id);\n }\n }\n\n for (const id of sessionsToDelete) {\n activeSessions.delete(id);\n }\n\n const capacityThreshold = Math.ceil(MAX_SESSIONS * 0.8);\n if (activeSessions.size >= capacityThreshold && activeSessions.size < MAX_SESSIONS) {\n log.warn(\"Party discussion session capacity warning\", {\n currentSessions: activeSessions.size,\n maxSessions: MAX_SESSIONS,\n utilizationPercent: Math.round((activeSessions.size / MAX_SESSIONS) * 100),\n message: \"Approaching session limit. Oldest sessions will be evicted when limit is reached.\",\n });\n }\n\n if (activeSessions.size > MAX_SESSIONS) {\n const sortedSessions = Array.from(activeSessions.entries()).sort(\n (a, b) => a[1].lastAccessedAt - b[1].lastAccessedAt\n );\n\n const toRemove = sortedSessions.slice(0, activeSessions.size - MAX_SESSIONS);\n for (const [id] of toRemove) {\n activeSessions.delete(id);\n }\n }\n}\n\nfunction getSession(sessionId: string): PartyDiscussionState | null {\n const session = activeSessions.get(sessionId);\n if (!session) return null;\n\n session.lastAccessedAt = Date.now();\n return session.state;\n}\n\nfunction getSessionWithMeta(sessionId: string): SessionWithMeta | null {\n const session = activeSessions.get(sessionId);\n if (!session) return null;\n\n session.lastAccessedAt = Date.now();\n return session;\n}\n\nfunction setSession(state: PartyDiscussionState, reviewFolderPath?: string): void {\n activeSessions.set(state.sessionId, {\n state,\n lastAccessedAt: Date.now(),\n reviewFolderPath,\n });\n}\n\nfunction buildAgenda(phase1: Phase1FullData, phase2?: Phase2Result): DiscussionAgendaItem[] {\n const agenda: DiscussionAgendaItem[] = [];\n\n const highSeverityFindings = extractHighSeverityFindings(phase1);\n for (const finding of highSeverityFindings) {\n const agentPositions = phase2 ? getAgentPositionsForFinding(finding.id, phase2) : {};\n agenda.push({\n id: `agenda-${finding.id}`,\n findingId: finding.id,\n topic: finding.title,\n type: \"high-severity\",\n severity: finding.severity,\n category: finding.category,\n relevantAgents: selectAgentsForFinding(finding.category, finding.severity),\n agentPositions,\n discussed: false,\n });\n }\n\n if (phase2) {\n for (const debate of phase2.debatePoints) {\n const existingItem = agenda.find((a) => a.topic === debate.topic);\n if (!existingItem) {\n const positions: Partial<Record<BmadAgentType, string>> = {};\n for (const pos of debate.positions) {\n positions[pos.agent] = pos.position;\n }\n agenda.push({\n id: `agenda-debate-${agenda.length}`,\n findingId: `debate-${agenda.length}`,\n topic: debate.topic,\n type: \"disputed\",\n severity: \"medium\",\n category: \"logic\",\n relevantAgents: debate.positions.map((p) => p.agent),\n agentPositions: positions,\n discussed: false,\n });\n }\n }\n }\n\n return agenda;\n}\n\ninterface FindingInfo {\n id: string;\n title: string;\n severity: FindingSeverity;\n category: FindingCategory;\n}\n\nfunction extractHighSeverityFindings(phase1: Phase1FullData): FindingInfo[] {\n const highCount = phase1.findings?.high ?? 0;\n\n // Handle missing oracleAnalysis gracefully\n if (!phase1.oracleAnalysis) {\n // Fallback to placeholder findings based on count\n if (highCount > 0) {\n return Array.from({ length: highCount }, (_, i) => ({\n id: `high-${i + 1}`,\n title: `High severity finding ${i + 1}`,\n severity: \"high\" as const,\n category: \"logic\" as FindingCategory,\n }));\n }\n return [];\n }\n\n // Use proper JSON parsing from oracle-parser\n const parsed = parseOracleResponse(phase1.oracleAnalysis);\n const allFindings = extractAllFindings(parsed);\n const highFindings = allFindings.filter((f) => f.severity === \"high\");\n\n if (highFindings.length > 0) {\n return highFindings.map((f, i) => ({\n id: f.id || `high-${i + 1}`,\n title: f.title,\n severity: \"high\" as const,\n category: f.category,\n }));\n }\n\n // Fallback if parsing didn't find high findings but count says otherwise\n if (highCount > 0) {\n return Array.from({ length: highCount }, (_, i) => ({\n id: `high-${i + 1}`,\n title: `High severity finding ${i + 1}`,\n severity: \"high\" as const,\n category: \"logic\" as FindingCategory,\n }));\n }\n\n return [];\n}\n\nfunction inferCategory(title: string): FindingCategory {\n const lower = title.toLowerCase();\n if (lower.includes(\"security\") || lower.includes(\"auth\") || lower.includes(\"pii\")) {\n return \"security\";\n }\n if (lower.includes(\"performance\") || lower.includes(\"query\") || lower.includes(\"cache\")) {\n return \"performance\";\n }\n if (lower.includes(\"test\") || lower.includes(\"pattern\") || lower.includes(\"practice\")) {\n return \"bestPractices\";\n }\n return \"logic\";\n}\n\nfunction getAgentPositionsForFinding(\n findingId: string,\n phase2: Phase2Result\n): Partial<Record<BmadAgentType, string>> {\n const positions: Partial<Record<BmadAgentType, string>> = {};\n\n for (const analysis of phase2.agentAnalyses) {\n const prioritized = analysis.prioritizedIssues.find((p) =>\n p.findingId.toLowerCase().includes(findingId.toLowerCase())\n );\n if (prioritized) {\n positions[analysis.agent] = `${prioritized.agentPriority}: ${prioritized.rationale}`;\n } else if (analysis.findings.concerns.length > 0) {\n positions[analysis.agent] = analysis.findings.concerns[0];\n }\n }\n\n return positions;\n}\n\nfunction initializeSession(\n phase1: Phase1FullData,\n phase2?: Phase2Result,\n reviewFolderPath?: string\n): PartyDiscussionState {\n const sessionId = randomUUID();\n const agenda = buildAgenda(phase1, phase2);\n\n const activeAgents = new Set<BmadAgentType>();\n for (const item of agenda) {\n for (const agent of item.relevantAgents) {\n activeAgents.add(agent);\n }\n }\n\n const state: PartyDiscussionState = {\n sessionId,\n scope: phase1.scope,\n identifier: phase1.identifier,\n agenda,\n currentItemIndex: 0,\n completedRounds: [],\n activeAgents: Array.from(activeAgents),\n startedAt: new Date().toISOString(),\n phase1Summary: phase1.findings ?? {\n total: 0,\n high: 0,\n medium: 0,\n low: 0,\n byCategory: {} as Record<FindingCategory, number>,\n },\n phase2Summary: phase2\n ? {\n consensusCount: phase2.consensusPoints.length,\n disputeCount: phase2.debatePoints.length,\n }\n : undefined,\n };\n\n setSession(state, reviewFolderPath);\n return state;\n}\n\nasync function generateAgentResponses(\n item: DiscussionAgendaItem,\n personas: Map<BmadAgentType, BmadAgentFullPersona>,\n phase2?: Phase2Result\n): Promise<AgentDiscussionResponse[]> {\n const responses: AgentDiscussionResponse[] = [];\n\n for (const agentType of item.relevantAgents) {\n const persona = getPersona(personas, agentType);\n\n const phase2Analysis = phase2?.agentAnalyses.find((a) => a.agent === agentType);\n const previousPosition = item.agentPositions[agentType];\n\n const response = generateInCharacterResponse(\n persona,\n item,\n previousPosition,\n phase2Analysis?.summary,\n responses\n );\n\n responses.push({\n agent: agentType,\n agentName: persona.name,\n icon: persona.icon,\n response,\n references: extractReferences(response, responses),\n keyPoints: extractKeyPoints(response),\n });\n }\n\n return responses;\n}\n\nfunction generateInCharacterResponse(\n persona: BmadAgentFullPersona,\n item: DiscussionAgendaItem,\n previousPosition?: string,\n phase2Summary?: string,\n previousResponses?: AgentDiscussionResponse[]\n): string {\n const intro = getResponseIntro(persona, item);\n const position = previousPosition || phase2Summary || getDefaultPosition(persona, item);\n const crossTalk = generateCrossTalk(persona, previousResponses);\n\n return `${intro} ${position}${crossTalk}`;\n}\n\nfunction getResponseIntro(persona: BmadAgentFullPersona, item: DiscussionAgendaItem): string {\n const intros: Record<BmadAgentType, string> = {\n architect: `From an architecture perspective on \"${item.topic}\":`,\n dev: `Looking at implementation for \"${item.topic}\":`,\n tea: `From a testing standpoint on \"${item.topic}\":`,\n pm: `Considering business impact of \"${item.topic}\":`,\n analyst: `Analyzing requirements around \"${item.topic}\":`,\n \"ux-designer\": `From a user experience view on \"${item.topic}\":`,\n \"tech-writer\": `Regarding documentation for \"${item.topic}\":`,\n sm: `From a process perspective on \"${item.topic}\":`,\n };\n\n return intros[persona.type] || `Regarding \"${item.topic}\":`;\n}\n\nfunction getDefaultPosition(_persona: BmadAgentFullPersona, item: DiscussionAgendaItem): string {\n if (item.severity === \"high\") {\n return `This is a ${item.severity} severity ${item.category} issue that needs attention before we proceed.`;\n }\n return `This ${item.category} concern should be addressed to maintain quality.`;\n}\n\nfunction generateCrossTalk(\n persona: BmadAgentFullPersona,\n previousResponses?: AgentDiscussionResponse[]\n): string {\n if (!previousResponses || previousResponses.length === 0) return \"\";\n\n const collaborativeTypes: BmadAgentType[] = [\"architect\", \"pm\", \"analyst\"];\n const shouldCrossTalk =\n previousResponses.length >= 1 && collaborativeTypes.includes(persona.type);\n\n if (shouldCrossTalk) {\n const lastResponse = previousResponses[previousResponses.length - 1];\n return ` Building on ${lastResponse.agentName}'s point, I'd add that we should prioritize this appropriately.`;\n }\n return \"\";\n}\n\nfunction extractReferences(\n response: string,\n previousResponses: AgentDiscussionResponse[]\n): AgentDiscussionResponse[\"references\"] {\n const references: AgentDiscussionResponse[\"references\"] = [];\n\n for (const prev of previousResponses) {\n if (response.includes(prev.agentName)) {\n const type = response.toLowerCase().includes(\"disagree\")\n ? \"disagrees\"\n : response.toLowerCase().includes(\"building on\")\n ? \"builds-on\"\n : \"agrees\";\n references.push({ agent: prev.agent, type });\n }\n }\n\n return references;\n}\n\nfunction extractKeyPoints(response: string): string[] {\n const sentences = response.split(/[.!?]+/).filter((s) => s.trim().length > 10);\n return sentences.slice(0, 2).map((s) => s.trim());\n}\n\nfunction recordDecision(\n state: PartyDiscussionState,\n findingId: string,\n decision: ReviewDecision,\n reason?: string,\n deferredTo?: string\n): PartyDiscussionState {\n const itemIndex = state.agenda.findIndex((a) => a.findingId === findingId);\n if (itemIndex === -1) return state;\n\n const item = state.agenda[itemIndex];\n item.discussed = true;\n\n const round: DiscussionRound = {\n findingId,\n findingTitle: item.topic,\n findingSeverity: item.severity,\n findingCategory: item.category,\n participants: item.relevantAgents,\n responses: [],\n decision,\n decisionReason: reason,\n deferredTo,\n };\n\n item.round = round;\n state.completedRounds.push(round);\n\n if (state.currentItemIndex === itemIndex) {\n state.currentItemIndex = findNextUndiscussedIndex(state);\n }\n\n return state;\n}\n\nfunction findNextUndiscussedIndex(state: PartyDiscussionState): number {\n for (let i = 0; i < state.agenda.length; i++) {\n if (!state.agenda[i].discussed) {\n return i;\n }\n }\n return state.agenda.length;\n}\n\nfunction calculateSummary(state: PartyDiscussionState): PartyDiscussionResult[\"summary\"] {\n const decisions = { accepted: 0, deferred: 0, rejected: 0, pending: 0 };\n const storyUpdates = new Map<string, string[]>();\n\n for (const round of state.completedRounds) {\n switch (round.decision) {\n case \"accept\":\n decisions.accepted++;\n break;\n case \"defer\":\n decisions.deferred++;\n if (round.deferredTo) {\n const existing = storyUpdates.get(round.deferredTo) || [];\n existing.push(`Deferred: ${round.findingTitle}`);\n storyUpdates.set(round.deferredTo, existing);\n }\n break;\n case \"reject\":\n decisions.rejected++;\n break;\n default:\n decisions.pending++;\n }\n }\n\n for (const item of state.agenda) {\n if (!item.discussed) {\n decisions.pending++;\n }\n }\n\n return {\n totalDiscussed: state.completedRounds.length,\n decisions,\n storyUpdatesNeeded: Array.from(storyUpdates.entries()).map(([storyId, additions]) => ({\n storyId,\n additions,\n })),\n };\n}\n\nexport function createPartyDiscussionTool(ctx: PluginInput, config: AthenaConfig): ToolDefinition {\n return tool({\n description: `Orchestrate Phase 3 party discussion for BMAD story review.\n\nThis tool manages an informed discussion where BMAD agents debate findings from Phase 1 (Oracle analysis) and optionally Phase 2 (parallel agent analysis).\n\nModes:\n- Quick mode: Only analysis.json exists in review folder (Oracle findings only)\n- Full mode: Both analysis.json and phase2.json exist (includes agent perspectives)\n\nActions:\n- start: Initialize discussion from review folder (loads analysis.json and optionally phase2.json)\n- continue: Get next agenda item and agent responses\n- decide: Record user decision for a finding (accept/defer/reject)\n- skip: Skip current finding without decision\n- end: End discussion and get summary\n\nThe tool maintains session state across calls, enabling multi-turn discussion.`,\n\n args: {\n action: tool.schema\n .enum([\"start\", \"continue\", \"decide\", \"skip\", \"end\"])\n .describe(\"Action to perform\"),\n sessionId: tool.schema\n .string()\n .optional()\n .describe(\"Session ID (required for continue/decide/skip/end)\"),\n reviewFolderPath: tool.schema\n .string()\n .optional()\n .describe(\"Path to review folder from athena_story_review_analyze (required for start)\"),\n findingId: tool.schema.string().optional().describe(\"Finding ID (required for decide)\"),\n decision: tool.schema\n .enum([\"accept\", \"defer\", \"reject\"])\n .optional()\n .describe(\"Decision (required for decide)\"),\n reason: tool.schema.string().optional().describe(\"Reason for decision\"),\n deferredTo: tool.schema\n .string()\n .optional()\n .describe(\"Story ID to defer to (for defer decisions)\"),\n },\n\n async execute(args): Promise<string> {\n const result = await executePartyDiscussion(ctx, config, args);\n return JSON.stringify(result, null, 2);\n },\n });\n}\n\ninterface ToolArgs {\n action: \"start\" | \"continue\" | \"decide\" | \"skip\" | \"end\";\n sessionId?: string;\n reviewFolderPath?: string;\n findingId?: string;\n decision?: \"accept\" | \"defer\" | \"reject\";\n reason?: string;\n deferredTo?: string;\n}\n\nasync function executePartyDiscussion(\n ctx: PluginInput,\n config: AthenaConfig,\n args: ToolArgs\n): Promise<PartyDiscussionResult> {\n cleanupStaleSessions();\n const personas = await loadPersonas(ctx.directory);\n\n switch (args.action) {\n case \"start\": {\n if (!args.reviewFolderPath) {\n log.warn(\"start called without reviewFolderPath\");\n return {\n success: false,\n sessionId: \"\",\n state: {} as PartyDiscussionState,\n hasMoreItems: false,\n error: \"reviewFolderPath is required for start action\",\n suggestion: \"Pass the reviewFolderPath from athena_story_review_analyze result\",\n };\n }\n\n const analysisPath = join(args.reviewFolderPath, \"analysis.json\");\n const phase2Path = join(args.reviewFolderPath, \"phase2.json\");\n\n if (!existsSync(analysisPath)) {\n return {\n success: false,\n sessionId: \"\",\n state: {} as PartyDiscussionState,\n hasMoreItems: false,\n error: `Analysis file not found: ${analysisPath}`,\n suggestion: \"Run athena_story_review_analyze first to generate the review folder\",\n };\n }\n\n let phase1: Phase1FullData;\n let phase2: Phase2Result | undefined;\n try {\n const analysisContent = await readFile(analysisPath, \"utf-8\");\n phase1 = JSON.parse(analysisContent);\n\n if (existsSync(phase2Path)) {\n const phase2Content = await readFile(phase2Path, \"utf-8\");\n phase2 = JSON.parse(phase2Content);\n }\n } catch (e) {\n log.error(\"Failed to load review files\", {\n error: e instanceof Error ? e.message : String(e),\n reviewFolderPath: args.reviewFolderPath,\n });\n return {\n success: false,\n sessionId: \"\",\n state: {} as PartyDiscussionState,\n hasMoreItems: false,\n error: `Failed to load review files: ${e instanceof Error ? e.message : String(e)}`,\n suggestion: \"Ensure the review folder contains valid analysis.json\",\n };\n }\n\n if (!phase1.findings) {\n return {\n success: false,\n sessionId: \"\",\n state: {} as PartyDiscussionState,\n hasMoreItems: false,\n error: \"analysis.json missing required 'findings' field\",\n suggestion: \"Ensure athena_story_review_analyze completed successfully\",\n };\n }\n\n if (!phase1.oracleAnalysis && phase1.findings.high > 0) {\n console.warn(\n \"[Athena] analysis.json missing oracleAnalysis field - using placeholder findings for\",\n phase1.identifier\n );\n }\n\n const state = initializeSession(phase1, phase2, args.reviewFolderPath);\n log.info(\"Session started\", {\n sessionId: state.sessionId,\n identifier: state.identifier,\n agendaItems: state.agenda.length,\n hasPhase2: !!phase2,\n });\n\n const currentItem = state.agenda[0];\n const responses = currentItem\n ? await generateAgentResponses(currentItem, personas, phase2)\n : undefined;\n\n return {\n success: true,\n sessionId: state.sessionId,\n state,\n currentItem,\n currentResponses: responses,\n hasMoreItems: state.agenda.length > 1,\n };\n }\n\n case \"continue\": {\n if (!args.sessionId) {\n return {\n success: false,\n sessionId: \"\",\n state: {} as PartyDiscussionState,\n hasMoreItems: false,\n error: \"sessionId is required for continue action\",\n };\n }\n\n const state = getSession(args.sessionId);\n if (!state) {\n return {\n success: false,\n sessionId: args.sessionId,\n state: {} as PartyDiscussionState,\n hasMoreItems: false,\n error: \"Session not found\",\n };\n }\n\n const currentItem = state.agenda[state.currentItemIndex];\n if (!currentItem || currentItem.discussed) {\n const nextIndex = findNextUndiscussedIndex(state);\n if (nextIndex >= state.agenda.length) {\n return {\n success: true,\n sessionId: state.sessionId,\n state,\n hasMoreItems: false,\n summary: calculateSummary(state),\n };\n }\n state.currentItemIndex = nextIndex;\n }\n\n const nextItem = state.agenda[state.currentItemIndex];\n const emptyPhase2Result: Phase2Result = {\n success: true,\n identifier: state.identifier,\n agentAnalyses: [],\n consensusPoints: [],\n debatePoints: [],\n aggregatedPriorities: [],\n };\n\n const responses = await generateAgentResponses(nextItem, personas, emptyPhase2Result);\n\n return {\n success: true,\n sessionId: state.sessionId,\n state,\n currentItem: nextItem,\n currentResponses: responses,\n hasMoreItems: state.currentItemIndex < state.agenda.length - 1,\n };\n }\n\n case \"decide\": {\n if (!args.sessionId || !args.findingId || !args.decision) {\n return {\n success: false,\n sessionId: args.sessionId || \"\",\n state: {} as PartyDiscussionState,\n hasMoreItems: false,\n error: \"sessionId, findingId, and decision are required for decide action\",\n };\n }\n\n const state = getSession(args.sessionId);\n if (!state) {\n return {\n success: false,\n sessionId: args.sessionId,\n state: {} as PartyDiscussionState,\n hasMoreItems: false,\n error: \"Session not found\",\n };\n }\n\n const updatedState = recordDecision(\n state,\n args.findingId,\n args.decision,\n args.reason,\n args.deferredTo\n );\n log.debug(\"Decision recorded\", {\n sessionId: args.sessionId,\n findingId: args.findingId,\n decision: args.decision,\n });\n\n const hasMore = updatedState.currentItemIndex < updatedState.agenda.length;\n\n return {\n success: true,\n sessionId: updatedState.sessionId,\n state: updatedState,\n hasMoreItems: hasMore,\n summary: !hasMore ? calculateSummary(updatedState) : undefined,\n };\n }\n\n case \"skip\": {\n if (!args.sessionId || !args.findingId) {\n return {\n success: false,\n sessionId: args.sessionId || \"\",\n state: {} as PartyDiscussionState,\n hasMoreItems: false,\n error: \"sessionId and findingId are required for skip action\",\n };\n }\n\n const state = getSession(args.sessionId);\n if (!state) {\n return {\n success: false,\n sessionId: args.sessionId,\n state: {} as PartyDiscussionState,\n hasMoreItems: false,\n error: \"Session not found\",\n };\n }\n\n const itemIndex = state.agenda.findIndex((a) => a.findingId === args.findingId);\n if (itemIndex !== -1) {\n state.agenda[itemIndex].discussed = true;\n state.currentItemIndex = findNextUndiscussedIndex(state);\n }\n\n return {\n success: true,\n sessionId: state.sessionId,\n state,\n hasMoreItems: state.currentItemIndex < state.agenda.length,\n };\n }\n\n case \"end\": {\n if (!args.sessionId) {\n return {\n success: false,\n sessionId: \"\",\n state: {} as PartyDiscussionState,\n hasMoreItems: false,\n error: \"sessionId is required for end action\",\n };\n }\n\n const sessionMeta = getSessionWithMeta(args.sessionId);\n if (!sessionMeta) {\n return {\n success: false,\n sessionId: args.sessionId,\n state: {} as PartyDiscussionState,\n hasMoreItems: false,\n error: \"Session not found\",\n };\n }\n\n const state = sessionMeta.state;\n const reviewFolderPath = sessionMeta.reviewFolderPath;\n\n activeSessions.delete(args.sessionId);\n const endSummary = calculateSummary(state);\n\n const reviewDocPath = reviewFolderPath ? join(reviewFolderPath, \"review.md\") : undefined;\n const appliedUpdates = await applyDecisions(ctx.directory, state, reviewDocPath, config);\n\n log.info(\"Session ended with decisions applied\", {\n sessionId: args.sessionId,\n totalDiscussed: endSummary?.totalDiscussed ?? 0,\n decisions: endSummary?.decisions,\n storiesModified: appliedUpdates.summary.storiesModified,\n storiesCreated: appliedUpdates.summary.storiesCreated,\n });\n\n return {\n success: true,\n sessionId: state.sessionId,\n state,\n hasMoreItems: false,\n summary: endSummary,\n appliedUpdates,\n };\n }\n\n default:\n return {\n success: false,\n sessionId: \"\",\n state: {} as PartyDiscussionState,\n hasMoreItems: false,\n error: `Unknown action: ${args.action}`,\n };\n }\n}\n\nexport const _testExports = {\n buildAgenda,\n extractHighSeverityFindings,\n inferCategory,\n getAgentPositionsForFinding,\n initializeSession,\n generateAgentResponses,\n recordDecision,\n calculateSummary,\n activeSessions,\n cleanupStaleSessions,\n getSession,\n getSessionWithMeta,\n setSession,\n SESSION_TTL_MS,\n MAX_SESSIONS,\n};\n","import { existsSync } from \"node:fs\";\nimport { mkdir, readFile, readdir, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { type ToolDefinition, tool } from \"@opencode-ai/plugin\";\nimport type { PluginInput } from \"@opencode-ai/plugin\";\nimport type {\n AthenaConfig,\n CrossStoryIssue,\n FindingCategory,\n FindingSeverity,\n PartyReviewDocument,\n Phase1Context,\n ReviewDocumentReference,\n ReviewScope,\n StoryComplexity,\n StoryFindings,\n} from \"../../shared/types.js\";\nimport { getBmadPaths } from \"../utils/bmad-finder.js\";\nimport {\n findStoriesForEpic as findStoriesForEpicShared,\n getStoryFilenamePatterns,\n normalizeStoryId as normalizeStoryIdShared,\n resolveStoryIdentifier,\n stripAtPrefix,\n} from \"../utils/story-loader.js\";\n\ninterface BmadPaths {\n projectRoot: string;\n bmadDir: string | null;\n planningDir: string;\n implementationDir: string;\n storiesDir: string;\n sprintStatus: string;\n architecture: string;\n prd: string;\n epics: string;\n}\n\ninterface OracleResponseSummary {\n totalIssues: number;\n highSeverity: number;\n mediumSeverity: number;\n lowSeverity: number;\n recommendation: string;\n}\n\ninterface OracleResponseFindings {\n security: FindingDetail[];\n logic: FindingDetail[];\n bestPractices: FindingDetail[];\n performance: FindingDetail[];\n}\n\ninterface ParsedOracleResponse {\n summary: OracleResponseSummary;\n findings?: OracleResponseFindings;\n storyFindings?: StoryFinding[];\n crossStoryIssues?: CrossStoryIssue[];\n}\n\ninterface StoryFinding {\n storyId: string;\n title: string;\n findings: {\n security?: FindingDetail[];\n logic?: FindingDetail[];\n bestPractices?: FindingDetail[];\n performance?: FindingDetail[];\n };\n}\n\ninterface FindingDetail {\n id: string;\n category: FindingCategory;\n severity: FindingSeverity;\n title: string;\n description: string;\n impact: string;\n suggestion: string;\n}\n\nexport function createReviewStoryTool(ctx: PluginInput, config: AthenaConfig): ToolDefinition {\n return tool({\n description: `Run a party review on BMAD stories to find security, logic, best practice, and performance gaps.\n\nThis command generates a comprehensive review document BEFORE development starts, catching issues when they're cheap to fix (in markdown, not code).\n\nThe command is smart about argument types:\n- Epic: \"2\", \"epic-2\" → Reviews all stories in the epic\n- Story: \"2.3\", \"story-2-3\" → Deep dive on a single story \n- Path: \"docs/stories/story-2-3.md\" → Review specific file\n- Flag: --thorough → Force advanced model (ignores complexity detection)\n\nReturns:\n- Review document path (saved to docs/reviews/)\n- Structured findings by severity and category\n- Recommendations for next steps\n\nUse this tool after story creation but before development to improve story quality.`,\n\n args: {\n identifier: tool.schema\n .string()\n .describe(\"Epic number (e.g., '2'), Story ID (e.g., '2.3'), or file path. Required.\"),\n thorough: tool.schema\n .boolean()\n .optional()\n .describe(\"Force advanced model for review (default: auto-detect based on complexity)\"),\n },\n\n async execute(args): Promise<string> {\n const result = await executePartyReview(ctx, config, args.identifier, args.thorough);\n return JSON.stringify(result, null, 2);\n },\n });\n}\n\nasync function executePartyReview(\n ctx: PluginInput,\n config: AthenaConfig,\n identifier: string,\n forceAdvancedModel?: boolean\n): Promise<Phase1Context> {\n const paths = await getBmadPaths(ctx.directory, config);\n if (!paths.bmadDir) {\n return {\n success: false,\n scope: \"story\",\n identifier,\n error: \"No BMAD directory found\",\n suggestion: \"Run 'npx bmad-method@alpha install' to set up BMAD in this project.\",\n };\n }\n\n const scope = detectReviewScope(identifier);\n const reviewsDir = join(paths.bmadDir, \"reviews\");\n\n await ensureReviewsDirectory(reviewsDir);\n\n if (scope === \"epic\") {\n return await executeEpicReview(ctx, config, paths, identifier, reviewsDir, forceAdvancedModel);\n }\n\n return await executeStoryReview(ctx, config, paths, identifier, reviewsDir, forceAdvancedModel);\n}\n\nfunction detectReviewScope(identifier: string): ReviewScope {\n const isFilePath = identifier.includes(\"/\") || identifier.endsWith(\".md\");\n if (isFilePath) {\n return \"story\";\n }\n\n const cleanId = identifier.replace(/^(epic|story)-/, \"\");\n const isEpic = !cleanId.includes(\".\") && !cleanId.includes(\"-\");\n\n return isEpic ? \"epic\" : \"story\";\n}\n\nasync function ensureReviewsDirectory(reviewsDir: string): Promise<void> {\n if (!existsSync(reviewsDir)) {\n await mkdir(reviewsDir, { recursive: true });\n }\n}\n\nasync function executeEpicReview(\n ctx: PluginInput,\n config: AthenaConfig,\n paths: BmadPaths,\n identifier: string,\n reviewsDir: string,\n forceAdvancedModel?: boolean\n): Promise<Phase1Context> {\n const epicNumber = identifier.replace(/^epic-/, \"\");\n\n const stories = await findStoriesInEpic(paths.storiesDir, epicNumber);\n if (stories.length === 0) {\n const patterns = getStoryFilenamePatterns(`${epicNumber}.1`);\n return {\n success: false,\n scope: \"epic\",\n identifier,\n error: `No stories found for Epic ${epicNumber}`,\n suggestion: `Check that story files exist in ${paths.storiesDir} matching: ${patterns.join(\", \")}`,\n };\n }\n\n const storyContents = await Promise.all(\n stories.map(async (storyId) => {\n const result = await loadStoryFile(paths.storiesDir, storyId, ctx.directory);\n return {\n id: result?.storyId ?? storyId,\n content: result?.content ?? null,\n };\n })\n );\n\n const architectureContent = await loadArchitecture(paths.architecture);\n\n const selectedModel = forceAdvancedModel ? config.models.oracle : config.models.oracle;\n\n const oraclePrompt = buildEpicReviewPrompt(epicNumber, storyContents, architectureContent);\n\n return {\n success: true,\n scope: \"epic\",\n identifier: epicNumber,\n oraclePrompt,\n storiesContent: storyContents,\n architectureContent,\n selectedModel,\n reviewsDir,\n };\n}\n\nasync function executeStoryReview(\n ctx: PluginInput,\n config: AthenaConfig,\n paths: BmadPaths,\n identifier: string,\n reviewsDir: string,\n forceAdvancedModel?: boolean\n): Promise<Phase1Context> {\n const storyResult = await loadStoryFile(paths.storiesDir, identifier, ctx.directory);\n if (!storyResult) {\n const normalizedId = normalizeStoryId(identifier);\n const patterns = getStoryFilenamePatterns(normalizedId);\n return {\n success: false,\n scope: \"story\",\n identifier: normalizedId,\n error: `Story ${normalizedId} not found`,\n suggestion: `Check that the story file exists in ${paths.storiesDir} matching: ${patterns.join(\", \")}`,\n };\n }\n\n const storyId = storyResult.storyId;\n const storyContent = storyResult.content;\n\n const existingReviews = await findExistingReviews(reviewsDir, storyId);\n const epicReview = existingReviews.find((r) => r.type === \"epic\");\n\n const architectureContent = await loadArchitecture(paths.architecture);\n\n const complexity = await analyzeStoryComplexity(storyContent);\n const selectedModel = forceAdvancedModel\n ? config.models.oracle\n : selectReviewModel(config, complexity);\n\n const oraclePrompt = buildFocusedReviewPrompt(\n storyId,\n storyContent,\n architectureContent,\n epicReview\n );\n\n return {\n success: true,\n scope: \"story\",\n identifier: storyId,\n oraclePrompt,\n storiesContent: [{ id: storyId, content: storyContent }],\n architectureContent,\n existingReviews,\n complexity,\n selectedModel,\n reviewsDir,\n };\n}\n\nasync function findStoriesInEpic(storiesDir: string, epicNumber: string): Promise<string[]> {\n const stories = await findStoriesForEpicShared(storiesDir, epicNumber);\n return stories.map((s) => s.id);\n}\n\nasync function loadStoryFile(\n storiesDir: string,\n storyId: string,\n projectRoot?: string\n): Promise<{ content: string; storyId: string } | null> {\n const cleaned = stripAtPrefix(storyId);\n const result = await resolveStoryIdentifier(storiesDir, cleaned, projectRoot);\n if (!result) return null;\n return { content: result.content, storyId: result.storyId };\n}\n\nasync function loadArchitecture(architectureFile: string): Promise<string> {\n if (!existsSync(architectureFile)) {\n return \"\";\n }\n return await readFile(architectureFile, \"utf-8\");\n}\n\nfunction normalizeStoryId(identifier: string): string {\n return normalizeStoryIdShared(identifier);\n}\n\nasync function findExistingReviews(\n reviewsDir: string,\n storyId: string\n): Promise<ReviewDocumentReference[]> {\n if (!existsSync(reviewsDir)) {\n return [];\n }\n\n const files = await readdir(reviewsDir);\n\n const reviews: ReviewDocumentReference[] = [];\n const [epicNum] = storyId.split(\".\");\n\n for (const file of files) {\n if (file.startsWith(`party-review-epic-${epicNum}-`)) {\n const filePath = join(reviewsDir, file);\n const match = file.match(/(\\d{4}-\\d{2}-\\d{2})/);\n\n reviews.push({\n type: \"epic\",\n filePath,\n date: match ? match[1] : \"\",\n findingsCount: 0,\n acceptedCount: 0,\n deferredCount: 0,\n rejectedCount: 0,\n });\n }\n }\n\n return reviews;\n}\n\nasync function analyzeStoryComplexity(storyContent: string): Promise<StoryComplexity> {\n const acMatches = storyContent.match(/^- /gm) || [];\n const acceptanceCriteriaCount = acMatches.length;\n\n const securityKeywords = /\\b(auth|login|password|token|secret|encrypt|permission|role|access)\\b/i;\n const hasSecurityConcerns = securityKeywords.test(storyContent);\n\n const dataKeywords = /\\b(database|schema|migration|model|table|collection)\\b/i;\n const hasDataModelChanges = dataKeywords.test(storyContent);\n\n const apiKeywords = /\\b(api|endpoint|route|controller|handler)\\b/i;\n const hasApiChanges = apiKeywords.test(storyContent);\n\n const crudPattern = /\\b(create|read|update|delete|get|post|put|patch|list)\\b/gi;\n const crudMatches = storyContent.match(crudPattern) || [];\n const isCrudOnly = crudMatches.length > 0 && !hasSecurityConcerns && !hasDataModelChanges;\n\n const isSimple =\n acceptanceCriteriaCount < 5 && !hasSecurityConcerns && !hasDataModelChanges && isCrudOnly;\n\n return {\n isSimple,\n reason: isSimple\n ? `Simple story: ${acceptanceCriteriaCount} ACs, CRUD-only, no security/data concerns`\n : `Complex story: ${acceptanceCriteriaCount} ACs, security=${hasSecurityConcerns}, data=${hasDataModelChanges}, API=${hasApiChanges}`,\n recommendedModel: isSimple ? \"anthropic/claude-3-5-haiku-20241022\" : \"openai/gpt-5.2\",\n factors: {\n acceptanceCriteriaCount,\n hasSecurityConcerns,\n hasDataModelChanges,\n hasApiChanges,\n isCrudOnly,\n },\n };\n}\n\nfunction selectReviewModel(config: AthenaConfig, complexity: StoryComplexity): string {\n return complexity.isSimple ? \"anthropic/claude-3-5-haiku-20241022\" : config.models.oracle;\n}\n\nfunction buildEpicReviewPrompt(\n epicNumber: string,\n storyContents: Array<{ id: string; content: string | null }>,\n architectureContent: string\n): string {\n const storiesText = storyContents\n .map((s) => `## Story ${s.id}\\n\\n${s.content || \"(empty)\"}`)\n .join(\"\\n\\n---\\n\\n\");\n\n return `You are a security, logic, and performance expert conducting a \"party review\" of BMAD stories BEFORE development begins.\n\n**Your Role**: Find issues while they're cheap to fix (in markdown, not code).\n\n**Focus Areas**:\n1. 🔒 **Security Gaps**: Missing auth/authorization, input validation, data exposure risks, credential handling\n2. 🧠 **Logic Gaps**: Edge cases not covered, error scenarios missing, validation rules incomplete, race conditions\n3. ✨ **Best Practice Flaws**: Anti-patterns in requirements, testing strategy gaps, accessibility concerns, unclear specifications\n4. ⚡ **Performance Issues**: Potential N+1 queries, missing caching strategy, large data handling not addressed, client-side bundle concerns\n\n**Scope**: Epic ${epicNumber} - Review ALL stories for issues AND cross-story patterns\n\n**Architecture Context**:\n${architectureContent || \"(No architecture documented)\"}\n\n**Stories to Review**:\n${storiesText}\n\n**Output Format** (JSON):\n{\n \"summary\": {\n \"totalIssues\": number,\n \"highSeverity\": number,\n \"mediumSeverity\": number,\n \"lowSeverity\": number,\n \"recommendation\": \"string\"\n },\n \"storyFindings\": [\n {\n \"storyId\": \"string\",\n \"title\": \"string\",\n \"findings\": {\n \"security\": [\n {\n \"id\": \"unique-id\",\n \"severity\": \"high\" | \"medium\" | \"low\",\n \"title\": \"Brief title\",\n \"description\": \"What's wrong\",\n \"impact\": \"Why it matters\",\n \"suggestion\": \"How to fix\"\n }\n ],\n \"logic\": [...],\n \"bestPractices\": [...],\n \"performance\": [...]\n }\n }\n ],\n \"crossStoryIssues\": [\n {\n \"id\": \"unique-id\",\n \"category\": \"security\" | \"logic\" | \"bestPractices\" | \"performance\",\n \"severity\": \"high\" | \"medium\" | \"low\",\n \"title\": \"Pattern or issue across multiple stories\",\n \"description\": \"Details\",\n \"affectedStories\": [\"2.1\", \"2.3\"],\n \"suggestion\": \"How to address\"\n }\n ]\n}\n\n**Instructions**:\n- Be thorough but practical\n- Prioritize high-impact issues\n- Provide actionable suggestions\n- Consider the architecture constraints\n- Flag missing requirements as logic gaps\n- Look for inconsistencies across stories`;\n}\n\nfunction buildFocusedReviewPrompt(\n storyId: string,\n storyContent: string,\n architectureContent: string,\n epicReview?: ReviewDocumentReference\n): string {\n const epicContext = epicReview\n ? `\\n\\n**Previous Epic Review**: An epic-level review was conducted on ${epicReview.date}. This focused review should find NEW issues not caught in the broader epic review.`\n : \"\";\n\n return `You are a security, logic, and performance expert conducting a DEEP DIVE \"party review\" of a single BMAD story BEFORE development begins.\n\n**Your Role**: Find issues while they're cheap to fix (in markdown, not code). This is a FOCUSED review, so be more thorough than a broad epic review.\n\n**Focus Areas**:\n1. 🔒 **Security Gaps**: Missing auth/authorization, input validation, data exposure risks, credential handling, session management\n2. 🧠 **Logic Gaps**: Edge cases not covered, error scenarios missing, validation rules incomplete, race conditions, state management\n3. ✨ **Best Practice Flaws**: Anti-patterns in requirements, testing strategy gaps, accessibility concerns, unclear specifications, maintainability\n4. ⚡ **Performance Issues**: Potential N+1 queries, missing caching strategy, large data handling, client-side bundle size, database indexes${epicContext}\n\n**Story**: ${storyId}\n\n**Architecture Context**:\n${architectureContent || \"(No architecture documented)\"}\n\n**Story Content**:\n${storyContent}\n\n**Output Format** (JSON):\n{\n \"summary\": {\n \"totalIssues\": number,\n \"highSeverity\": number,\n \"mediumSeverity\": number,\n \"lowSeverity\": number,\n \"recommendation\": \"string\"\n },\n \"findings\": {\n \"security\": [\n {\n \"id\": \"unique-id\",\n \"severity\": \"high\" | \"medium\" | \"low\",\n \"title\": \"Brief title\",\n \"description\": \"What's wrong\",\n \"impact\": \"Why it matters\",\n \"suggestion\": \"How to fix (be specific)\"\n }\n ],\n \"logic\": [...],\n \"bestPractices\": [...],\n \"performance\": [...]\n }\n}\n\n**Instructions**:\n- Be EXTREMELY thorough - this is a deep dive\n- Think like an adversarial tester trying to break the implementation\n- Question every assumption in the requirements\n- Look for vague or incomplete acceptance criteria\n- Consider security implications of every data flow\n- Flag missing error handling scenarios\n- Identify performance bottlenecks before they're coded\n- Provide highly specific, actionable suggestions`;\n}\n\nfunction parseOracleResponse(_response: string, _scope: ReviewScope): ParsedOracleResponse {\n try {\n return JSON.parse(_response) as ParsedOracleResponse;\n } catch {\n return {\n summary: {\n totalIssues: 0,\n highSeverity: 0,\n mediumSeverity: 0,\n lowSeverity: 0,\n recommendation: \"Failed to parse Oracle response\",\n },\n findings: {\n security: [],\n logic: [],\n bestPractices: [],\n performance: [],\n },\n };\n }\n}\n\nfunction buildEpicReviewDocument(\n epicNumber: string,\n stories: string[],\n findings: ParsedOracleResponse,\n oracleAnalysis: string\n): PartyReviewDocument {\n const timestamp = new Date().toISOString().split(\"T\")[0];\n\n return {\n scope: \"epic\",\n identifier: epicNumber,\n date: timestamp,\n reviewer: \"Oracle (Party Mode)\",\n epicNumber,\n storiesReviewed: stories,\n summary: findings.summary,\n storyFindings: findings.storyFindings as unknown as StoryFindings[],\n crossStoryIssues: findings.crossStoryIssues,\n oracleAnalysis,\n };\n}\n\nfunction buildFocusedReviewDocument(\n storyId: string,\n findings: ParsedOracleResponse,\n epicReview: ReviewDocumentReference | undefined,\n oracleAnalysis: string\n): PartyReviewDocument {\n const timestamp = new Date().toISOString().split(\"T\")[0];\n const [epicNum] = storyId.split(\".\");\n\n return {\n scope: \"story\",\n identifier: storyId,\n date: timestamp,\n reviewer: \"Oracle (Party Mode - Deep Dive)\",\n epicNumber: epicNum,\n storyId,\n relatedReviews: epicReview ? [epicReview] : [],\n summary: findings.summary,\n newFindings: findings.findings,\n oracleAnalysis,\n };\n}\n\nasync function saveReviewDocument(\n documentPath: string,\n document: PartyReviewDocument\n): Promise<void> {\n const markdown = formatReviewDocumentAsMarkdown(document);\n await writeFile(documentPath, markdown, \"utf-8\");\n}\n\nfunction formatReviewDocumentAsMarkdown(doc: PartyReviewDocument): string {\n const title =\n doc.scope === \"epic\"\n ? `# 🎉 Party Review: Epic ${doc.epicNumber}\\n`\n : `# 🎉 Party Review: Story ${doc.storyId} (Focused Review)\\n`;\n\n const metadata = `**Date**: ${doc.date}\n**Reviewer**: ${doc.reviewer}\n${doc.scope === \"epic\" ? `**Stories Reviewed**: ${doc.storiesReviewed?.join(\", \")}` : `**Epic**: ${doc.epicNumber}`}\n\n---\n\n## Executive Summary\n- **Total Issues**: ${doc.summary.totalIssues}\n- **High Severity**: ${doc.summary.highSeverity} issues (MUST address)\n- **Medium Severity**: ${doc.summary.mediumSeverity} issues (SHOULD address)\n- **Low Severity**: ${doc.summary.lowSeverity} issues (NICE to address)\n\n**Recommendation**: ${doc.summary.recommendation}\n\n---\n\n`;\n\n const relatedReviews = doc.relatedReviews?.length\n ? `## 🔗 Related Reviews\\n${doc.relatedReviews\n .map(\n (r) =>\n `- **${r.type === \"epic\" ? \"Epic Review\" : \"Focused Review\"}**: [${r.filePath.split(\"/\").pop() ?? \"review\"}](${r.filePath}) (${r.date})`\n )\n .join(\"\\n\")}\\n\\n---\\n\\n`\n : \"\";\n\n const findingsSection =\n doc.scope === \"epic\" && doc.storyFindings\n ? formatEpicFindings(doc.storyFindings, doc.crossStoryIssues)\n : formatStoryFindings(doc.newFindings);\n\n const appendix = `\\n---\\n\\n## Appendix: Oracle's Full Analysis\\n<details>\\n<summary>Click to expand detailed reasoning</summary>\\n\\n${doc.oracleAnalysis ?? \"\"}\\n\\n</details>\\n`;\n\n return title + metadata + relatedReviews + findingsSection + appendix;\n}\n\nfunction formatEpicFindings(\n storyFindings: StoryFindings[],\n crossStoryIssues?: CrossStoryIssue[]\n): string {\n let output = \"\";\n\n for (const story of storyFindings) {\n const typedStory = story as unknown as StoryFinding;\n output += `## Story ${typedStory.storyId}: ${typedStory.title}\\n\\n`;\n\n for (const category of [\"security\", \"logic\", \"bestPractices\", \"performance\"] as const) {\n const findings = (typedStory.findings[category] || []) as FindingDetail[];\n if (findings.length > 0) {\n const icon = getCategoryIcon(category);\n output += `### ${icon} ${formatCategoryName(category)} (${findings.length} issues)\\n\\n`;\n\n for (const finding of findings) {\n const severity = finding.severity.toUpperCase();\n output += `#### [${severity}] ${finding.title}\\n`;\n output += `**Finding**: ${finding.description}\\n`;\n output += `**Impact**: ${finding.impact}\\n`;\n output += `**Suggestion**: ${finding.suggestion}\\n`;\n output += \"**Decision**: [ ] Accept [ ] Defer [ ] Reject\\n\\n\";\n }\n }\n }\n\n output += \"---\\n\\n\";\n }\n\n if (crossStoryIssues && crossStoryIssues.length > 0) {\n output += \"## Cross-Story Issues\\n\\n\";\n for (const issue of crossStoryIssues) {\n const icon = getCategoryIcon(issue.category);\n output += `### ${icon} [${issue.severity.toUpperCase()}] ${issue.title}\\n`;\n output += `**Stories Affected**: ${issue.affectedStories.join(\", \")}\\n`;\n output += `**Finding**: ${issue.description}\\n`;\n output += `**Suggestion**: ${issue.suggestion}\\n`;\n output += \"**Decision**: [ ] Accept [ ] Defer [ ] Reject\\n\\n\";\n }\n }\n\n return output;\n}\n\nfunction formatStoryFindings(findings: unknown): string {\n if (!findings) return \"\";\n\n const typedFindings = findings as OracleResponseFindings;\n let output = \"\";\n\n for (const category of [\"security\", \"logic\", \"bestPractices\", \"performance\"] as const) {\n const items = (typedFindings[category] || []) as FindingDetail[];\n if (items.length > 0) {\n const icon = getCategoryIcon(category);\n output += `## ${icon} ${formatCategoryName(category)} (${items.length} issues)\\n\\n`;\n\n for (const finding of items) {\n const severity = finding.severity.toUpperCase();\n output += `### [${severity}] ${finding.title}\\n`;\n output += `**Finding**: ${finding.description}\\n`;\n output += `**Impact**: ${finding.impact}\\n`;\n output += `**Suggestion**: ${finding.suggestion}\\n`;\n output += \"**Decision**: [ ] Accept [ ] Defer [ ] Reject\\n\\n\";\n }\n\n output += \"---\\n\\n\";\n }\n }\n\n return output;\n}\n\nfunction getCategoryIcon(category: FindingCategory): string {\n switch (category) {\n case \"security\":\n return \"🔒\";\n case \"logic\":\n return \"🧠\";\n case \"bestPractices\":\n return \"✨\";\n case \"performance\":\n return \"⚡\";\n }\n}\n\nfunction formatCategoryName(category: FindingCategory): string {\n switch (category) {\n case \"security\":\n return \"Security Issues\";\n case \"logic\":\n return \"Logic Issues\";\n case \"bestPractices\":\n return \"Best Practices\";\n case \"performance\":\n return \"Performance Issues\";\n }\n}\n\nasync function updateEpicReviewDocument(\n _epicReviewPath: string,\n _storyId: string,\n _focusedReviewPath: string,\n _findings: ParsedOracleResponse\n): Promise<void> {\n return;\n}\n\n// Export internal functions for testing\ninterface FindingCounts {\n total: number;\n high: number;\n medium: number;\n low: number;\n byCategory: Record<FindingCategory, number>;\n}\n\ninterface AgentRecommendation {\n agent: string;\n reason: string;\n relevantFindings: string[];\n priority: \"required\" | \"recommended\" | \"optional\";\n}\n\nconst _AGENT_EXPERTISE: Record<string, FindingCategory[]> = {\n architect: [\"security\", \"performance\"],\n dev: [\"logic\", \"performance\", \"bestPractices\"],\n tea: [\"logic\", \"bestPractices\"],\n pm: [\"logic\", \"bestPractices\"],\n analyst: [\"logic\"],\n \"ux-designer\": [\"bestPractices\"],\n \"tech-writer\": [\"bestPractices\"],\n};\n\nfunction selectAgentsForReview(findings: FindingCounts): AgentRecommendation[] {\n const recommendations: AgentRecommendation[] = [];\n\n if (findings.byCategory.security > 0) {\n recommendations.push({\n agent: \"architect\",\n reason: `${findings.byCategory.security} security finding(s) require architecture review`,\n relevantFindings: [\"security\"],\n priority: findings.high > 0 ? \"required\" : \"recommended\",\n });\n recommendations.push({\n agent: \"dev\",\n reason: \"Security findings need implementation perspective\",\n relevantFindings: [\"security\"],\n priority: \"recommended\",\n });\n recommendations.push({\n agent: \"tea\",\n reason: \"Security findings need test coverage review\",\n relevantFindings: [\"security\"],\n priority: \"recommended\",\n });\n }\n\n if (findings.byCategory.logic > 0) {\n if (!recommendations.find((r) => r.agent === \"dev\")) {\n recommendations.push({\n agent: \"dev\",\n reason: `${findings.byCategory.logic} logic gap(s) need implementation review`,\n relevantFindings: [\"logic\"],\n priority: findings.high > 0 ? \"required\" : \"recommended\",\n });\n }\n if (!recommendations.find((r) => r.agent === \"tea\")) {\n recommendations.push({\n agent: \"tea\",\n reason: \"Logic gaps need test scenario review\",\n relevantFindings: [\"logic\"],\n priority: \"recommended\",\n });\n }\n recommendations.push({\n agent: \"analyst\",\n reason: \"Logic gaps may indicate incomplete requirements\",\n relevantFindings: [\"logic\"],\n priority: \"optional\",\n });\n }\n\n if (findings.byCategory.performance > 0) {\n if (!recommendations.find((r) => r.agent === \"architect\")) {\n recommendations.push({\n agent: \"architect\",\n reason: `${findings.byCategory.performance} performance issue(s) need architecture review`,\n relevantFindings: [\"performance\"],\n priority: \"recommended\",\n });\n }\n if (!recommendations.find((r) => r.agent === \"dev\")) {\n recommendations.push({\n agent: \"dev\",\n reason: \"Performance issues need implementation perspective\",\n relevantFindings: [\"performance\"],\n priority: \"recommended\",\n });\n }\n }\n\n if (findings.byCategory.bestPractices > 0) {\n if (!recommendations.find((r) => r.agent === \"dev\")) {\n recommendations.push({\n agent: \"dev\",\n reason: `${findings.byCategory.bestPractices} best practice issue(s) need code review`,\n relevantFindings: [\"bestPractices\"],\n priority: \"optional\",\n });\n }\n recommendations.push({\n agent: \"tech-writer\",\n reason: \"Best practice issues may need documentation updates\",\n relevantFindings: [\"bestPractices\"],\n priority: \"optional\",\n });\n }\n\n if (findings.high > 0) {\n recommendations.push({\n agent: \"pm\",\n reason: `${findings.high} high severity issue(s) need product impact assessment`,\n relevantFindings: [\"high-severity\"],\n priority: \"required\",\n });\n }\n\n const requiredCount = recommendations.filter((r) => r.priority === \"required\").length;\n if (requiredCount === 0 && recommendations.length > 0) {\n recommendations[0].priority = \"required\";\n }\n\n return recommendations;\n}\n\nexport const _testExports = {\n detectReviewScope,\n normalizeStoryId,\n analyzeStoryComplexity,\n selectReviewModel,\n findStoriesInEpic,\n loadStoryFile,\n findExistingReviews,\n parseOracleResponse,\n buildEpicReviewPrompt,\n buildFocusedReviewPrompt,\n buildEpicReviewDocument,\n buildFocusedReviewDocument,\n saveReviewDocument,\n formatReviewDocumentAsMarkdown,\n getCategoryIcon,\n formatCategoryName,\n updateEpicReviewDocument,\n selectAgentsForReview,\n};\n","import type { BmadAgentType, FindingCategory } from \"../../shared/types.js\";\n\nexport interface FindingCounts {\n total: number;\n high: number;\n medium: number;\n low: number;\n byCategory: Record<FindingCategory, number>;\n}\n\nexport interface AgentRecommendation {\n agent: BmadAgentType;\n reason: string;\n relevantFindings: string[];\n priority: \"required\" | \"recommended\" | \"optional\";\n}\n\nconst AGENT_EXPERTISE: Record<BmadAgentType, FindingCategory[]> = {\n architect: [\"security\", \"performance\"],\n dev: [\"logic\", \"performance\", \"bestPractices\"],\n tea: [\"logic\", \"bestPractices\"],\n pm: [\"logic\", \"bestPractices\"],\n analyst: [\"logic\"],\n \"ux-designer\": [\"bestPractices\"],\n \"tech-writer\": [\"bestPractices\"],\n sm: [\"bestPractices\"],\n};\n\nexport function selectAgentsForReview(findings: FindingCounts): AgentRecommendation[] {\n const recommendations: AgentRecommendation[] = [];\n\n if (findings.byCategory.security > 0) {\n addSecurityAgents(recommendations, findings);\n }\n\n if (findings.byCategory.logic > 0) {\n addLogicAgents(recommendations, findings);\n }\n\n if (findings.byCategory.performance > 0) {\n addPerformanceAgents(recommendations);\n }\n\n if (findings.byCategory.bestPractices > 0) {\n addBestPracticesAgents(recommendations, findings);\n }\n\n if (findings.high > 0) {\n recommendations.push({\n agent: \"pm\",\n reason: `${findings.high} high severity issue(s) need product impact assessment`,\n relevantFindings: [\"high-severity\"],\n priority: \"required\",\n });\n }\n\n ensureAtLeastOneRequired(recommendations);\n\n return recommendations;\n}\n\nfunction addSecurityAgents(recommendations: AgentRecommendation[], findings: FindingCounts): void {\n recommendations.push({\n agent: \"architect\",\n reason: `${findings.byCategory.security} security finding(s) require architecture review`,\n relevantFindings: [\"security\"],\n priority: findings.high > 0 ? \"required\" : \"recommended\",\n });\n recommendations.push({\n agent: \"dev\",\n reason: \"Security findings need implementation perspective\",\n relevantFindings: [\"security\"],\n priority: \"recommended\",\n });\n recommendations.push({\n agent: \"tea\",\n reason: \"Security findings need test coverage review\",\n relevantFindings: [\"security\"],\n priority: \"recommended\",\n });\n}\n\nfunction addLogicAgents(recommendations: AgentRecommendation[], findings: FindingCounts): void {\n if (!recommendations.find((r) => r.agent === \"dev\")) {\n recommendations.push({\n agent: \"dev\",\n reason: `${findings.byCategory.logic} logic gap(s) need implementation review`,\n relevantFindings: [\"logic\"],\n priority: findings.high > 0 ? \"required\" : \"recommended\",\n });\n }\n if (!recommendations.find((r) => r.agent === \"tea\")) {\n recommendations.push({\n agent: \"tea\",\n reason: \"Logic gaps need test scenario review\",\n relevantFindings: [\"logic\"],\n priority: \"recommended\",\n });\n }\n recommendations.push({\n agent: \"analyst\",\n reason: \"Logic gaps may indicate incomplete requirements\",\n relevantFindings: [\"logic\"],\n priority: \"optional\",\n });\n}\n\nfunction addPerformanceAgents(recommendations: AgentRecommendation[]): void {\n if (!recommendations.find((r) => r.agent === \"architect\")) {\n recommendations.push({\n agent: \"architect\",\n reason: \"Performance issues need architecture review\",\n relevantFindings: [\"performance\"],\n priority: \"recommended\",\n });\n }\n if (!recommendations.find((r) => r.agent === \"dev\")) {\n recommendations.push({\n agent: \"dev\",\n reason: \"Performance issues need implementation perspective\",\n relevantFindings: [\"performance\"],\n priority: \"recommended\",\n });\n }\n}\n\nfunction addBestPracticesAgents(\n recommendations: AgentRecommendation[],\n findings: FindingCounts\n): void {\n if (!recommendations.find((r) => r.agent === \"dev\")) {\n recommendations.push({\n agent: \"dev\",\n reason: `${findings.byCategory.bestPractices} best practice issue(s) need code review`,\n relevantFindings: [\"bestPractices\"],\n priority: \"optional\",\n });\n }\n recommendations.push({\n agent: \"tech-writer\",\n reason: \"Best practice issues may need documentation updates\",\n relevantFindings: [\"bestPractices\"],\n priority: \"optional\",\n });\n}\n\nfunction ensureAtLeastOneRequired(recommendations: AgentRecommendation[]): void {\n const requiredCount = recommendations.filter((r) => r.priority === \"required\").length;\n if (requiredCount === 0 && recommendations.length > 0) {\n recommendations[0].priority = \"required\";\n }\n}\n\nexport function getRecommendedAgentTypes(recommendations: AgentRecommendation[]): BmadAgentType[] {\n const seen = new Set<BmadAgentType>();\n const agents: BmadAgentType[] = [];\n\n for (const rec of recommendations) {\n if (!seen.has(rec.agent)) {\n seen.add(rec.agent);\n agents.push(rec.agent);\n }\n }\n\n return agents;\n}\n\nexport function filterByPriority(\n recommendations: AgentRecommendation[],\n minPriority: \"required\" | \"recommended\" | \"optional\"\n): AgentRecommendation[] {\n const priorityOrder = { required: 0, recommended: 1, optional: 2 };\n const minLevel = priorityOrder[minPriority];\n\n return recommendations.filter((r) => priorityOrder[r.priority] <= minLevel);\n}\n\nexport { AGENT_EXPERTISE };\n","import { existsSync } from \"node:fs\";\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { type ToolDefinition, tool } from \"@opencode-ai/plugin\";\nimport type { PluginInput } from \"@opencode-ai/plugin\";\nimport type {\n AthenaConfig,\n Phase1FullData,\n Phase1Summary,\n ReviewScope,\n} from \"../../shared/types.js\";\nimport {\n type AgentRecommendation,\n type FindingCounts,\n selectAgentsForReview,\n} from \"../utils/agent-selector.js\";\nimport { getBmadPaths } from \"../utils/bmad-finder.js\";\nimport {\n type ParsedOracleResponse,\n countFindings,\n parseOracleResponse,\n} from \"../utils/oracle-parser.js\";\nimport {\n findStoriesForEpic,\n resolveStoryIdentifier,\n stripAtPrefix,\n} from \"../utils/story-loader.js\";\nimport { updateStoryStatus } from \"../utils/yaml-handler.js\";\n\nexport function createStoryReviewAnalyzeTool(\n ctx: PluginInput,\n config: AthenaConfig\n): ToolDefinition {\n return tool({\n description: `Analyze BMAD stories for security, logic, best practice, and performance gaps.\n\nThis tool performs Phase 1 of the party review workflow:\n1. Loads stories and architecture context\n2. Spawns Oracle agent to analyze for issues\n3. Parses findings by severity and category\n4. Recommends BMAD agents for discussion\n5. Generates and saves a review document\n\nReturns a complete Phase 1 result that can be passed to Phase 2 (athena_story_review_consult) or Phase 3 (athena_party_discussion).\n\nUse this AFTER story creation but BEFORE development to catch issues early.`,\n\n args: {\n identifier: tool.schema\n .string()\n .describe(\"Epic number (e.g., '2'), Story ID (e.g., '2.3'), or file path\"),\n thorough: tool.schema\n .boolean()\n .optional()\n .describe(\"Force advanced model for deeper analysis (default: auto-detect)\"),\n },\n\n async execute(args): Promise<string> {\n const result = await executePhase1Analysis(ctx, config, args.identifier, args.thorough);\n return JSON.stringify(result, null, 2);\n },\n });\n}\n\nasync function executePhase1Analysis(\n ctx: PluginInput,\n config: AthenaConfig,\n identifier: string,\n forceAdvancedModel?: boolean\n): Promise<Phase1Summary> {\n const paths = await getBmadPaths(ctx.directory, config);\n if (!paths.bmadDir) {\n return {\n success: false,\n scope: \"story\",\n identifier,\n error: \"No BMAD directory found\",\n suggestion: \"Run 'npx bmad-method@alpha install' to set up BMAD in this project.\",\n };\n }\n\n const scope = detectReviewScope(identifier);\n const reviewsDir = join(paths.bmadDir, \"reviews\");\n await ensureDirectory(reviewsDir);\n\n const storiesContent =\n scope === \"epic\"\n ? await loadEpicStories(paths.storiesDir, identifier)\n : await loadSingleStory(paths.storiesDir, identifier, ctx.directory);\n\n if (storiesContent.length === 0) {\n return {\n success: false,\n scope,\n identifier,\n error: `No stories found for ${scope} ${identifier}`,\n suggestion: `Check that story files exist in ${paths.storiesDir}`,\n };\n }\n\n const architectureContent = await loadFile(paths.architecture);\n\n const oraclePrompt = buildOraclePrompt(scope, identifier, storiesContent, architectureContent);\n\n const oracleResponse = await spawnOracleAndWait(ctx, config, oraclePrompt, forceAdvancedModel);\n\n if (!oracleResponse.success) {\n return {\n success: false,\n scope,\n identifier,\n error: oracleResponse.error || \"Oracle analysis failed\",\n suggestion: \"Check that the Oracle agent is configured correctly.\",\n };\n }\n\n const parsed = parseOracleResponse(oracleResponse.content || \"\");\n const findings = countFindings(parsed);\n const recommendedAgents = selectAgentsForReview(findings);\n const summary = buildSummary(findings, recommendedAgents);\n\n const reviewFolderPath = await saveReviewFolder(\n reviewsDir,\n scope,\n identifier,\n storiesContent,\n parsed,\n oracleResponse.content || \"\",\n findings,\n recommendedAgents,\n summary\n );\n\n if (scope === \"story\") {\n await updateStoryStatus(paths.sprintStatus, identifier, \"ready-for-dev\");\n } else {\n for (const story of storiesContent) {\n await updateStoryStatus(paths.sprintStatus, story.id, \"ready-for-dev\");\n }\n }\n\n return {\n success: true,\n scope,\n identifier,\n findings,\n recommendedAgents,\n reviewFolderPath,\n summary,\n };\n}\n\nfunction detectReviewScope(identifier: string): ReviewScope {\n const isFilePath = identifier.includes(\"/\") || identifier.endsWith(\".md\");\n if (isFilePath) return \"story\";\n\n const cleanId = identifier.replace(/^(epic|story)-/, \"\");\n return !cleanId.includes(\".\") && !cleanId.includes(\"-\") ? \"epic\" : \"story\";\n}\n\nasync function ensureDirectory(dir: string): Promise<void> {\n if (!existsSync(dir)) {\n await mkdir(dir, { recursive: true });\n }\n}\n\nasync function loadEpicStories(\n storiesDir: string,\n epicId: string\n): Promise<Array<{ id: string; content: string | null }>> {\n const stories = await findStoriesForEpic(storiesDir, epicId);\n const results: Array<{ id: string; content: string | null }> = [];\n\n for (const story of stories) {\n const content = await loadFile(story.path);\n results.push({ id: story.id, content });\n }\n\n return results;\n}\n\nasync function loadSingleStory(\n storiesDir: string,\n identifier: string,\n projectRoot?: string\n): Promise<Array<{ id: string; content: string | null }>> {\n const cleaned = stripAtPrefix(identifier);\n const result = await resolveStoryIdentifier(storiesDir, cleaned, projectRoot);\n if (!result) return [];\n\n return [{ id: result.storyId, content: result.content }];\n}\n\nasync function loadFile(filePath: string): Promise<string | null> {\n if (!existsSync(filePath)) return null;\n try {\n return await readFile(filePath, \"utf-8\");\n } catch {\n return null;\n }\n}\n\nfunction buildOraclePrompt(\n scope: ReviewScope,\n identifier: string,\n stories: Array<{ id: string; content: string | null }>,\n architecture: string | null\n): string {\n const storiesText = stories\n .map((s) => `## Story ${s.id}\\n\\n${s.content || \"(empty)\"}`)\n .join(\"\\n\\n---\\n\\n\");\n\n const scopeDescription =\n scope === \"epic\"\n ? `Epic ${identifier} - Review ALL stories for issues AND cross-story patterns`\n : `Story ${identifier} - Deep dive focused review`;\n\n return `You are a security, logic, and performance expert conducting a \"party review\" of BMAD stories BEFORE development begins.\n\n**Your Role**: Find issues while they're cheap to fix (in markdown, not code).\n\n**Focus Areas**:\n1. 🔒 **Security Gaps**: Missing auth/authorization, input validation, data exposure risks\n2. 🧠 **Logic Gaps**: Edge cases not covered, error scenarios missing, validation rules incomplete\n3. ✨ **Best Practice Flaws**: Anti-patterns, testing strategy gaps, accessibility concerns\n4. ⚡ **Performance Issues**: N+1 queries, missing caching, large data handling\n\n**Scope**: ${scopeDescription}\n\n**Architecture Context**:\n${architecture || \"(No architecture documented)\"}\n\n**Stories to Review**:\n${storiesText}\n\n**Output Format** (JSON):\n{\n \"summary\": {\n \"totalIssues\": number,\n \"highSeverity\": number,\n \"mediumSeverity\": number,\n \"lowSeverity\": number,\n \"recommendation\": \"string\"\n },\n ${\n scope === \"epic\"\n ? `\"storyFindings\": [\n {\n \"storyId\": \"string\",\n \"title\": \"string\",\n \"findings\": {\n \"security\": [{ \"id\": \"unique\", \"severity\": \"high|medium|low\", \"title\": \"...\", \"description\": \"...\", \"impact\": \"...\", \"suggestion\": \"...\" }],\n \"logic\": [...],\n \"bestPractices\": [...],\n \"performance\": [...]\n }\n }\n ],\n \"crossStoryIssues\": [\n { \"id\": \"unique\", \"category\": \"security|logic|bestPractices|performance\", \"severity\": \"high|medium|low\", \"title\": \"...\", \"description\": \"...\", \"affectedStories\": [\"2.1\", \"2.3\"], \"suggestion\": \"...\" }\n ]`\n : `\"findings\": {\n \"security\": [{ \"id\": \"unique\", \"severity\": \"high|medium|low\", \"title\": \"...\", \"description\": \"...\", \"impact\": \"...\", \"suggestion\": \"...\" }],\n \"logic\": [...],\n \"bestPractices\": [...],\n \"performance\": [...]\n }`\n }\n}\n\n**Instructions**:\n- Be thorough but practical\n- Prioritize high-impact issues\n- Provide actionable suggestions\n- Flag missing requirements as logic gaps`;\n}\n\ninterface OracleResult {\n success: boolean;\n content?: string;\n error?: string;\n}\n\nasync function spawnOracleAndWait(\n ctx: PluginInput,\n config: AthenaConfig,\n prompt: string,\n _forceAdvancedModel?: boolean\n): Promise<OracleResult> {\n try {\n const createResult = await ctx.client.session.create({\n body: {\n title: \"Party Review - Oracle Analysis\",\n },\n });\n\n if (!createResult.data?.id) {\n return { success: false, error: \"Failed to create Oracle session\" };\n }\n\n const sessionId = createResult.data.id;\n\n const promptResult = await ctx.client.session.prompt({\n path: { id: sessionId },\n body: {\n model: parseModelConfig(config.models.oracle),\n parts: [{ type: \"text\", text: prompt }],\n },\n });\n\n if (!promptResult.data) {\n return { success: false, error: \"No response from Oracle\" };\n }\n\n const messagesResult = await ctx.client.session.messages({\n path: { id: sessionId },\n });\n\n const lastMessage = messagesResult.data?.at(-1);\n if (!lastMessage) {\n return { success: false, error: \"No messages in Oracle session\" };\n }\n\n const textParts = lastMessage.parts?.filter((p) => p.type === \"text\") || [];\n const content = textParts.map((p) => (p as { text: string }).text).join(\"\\n\");\n\n return { success: true, content };\n } catch (error) {\n const message = error instanceof Error ? error.message : \"Unknown error\";\n return { success: false, error: `Oracle spawn failed: ${message}` };\n }\n}\n\nfunction parseModelConfig(modelString: string): { providerID: string; modelID: string } {\n const [providerID, modelID] = modelString.split(\"/\");\n return { providerID: providerID || \"openai\", modelID: modelID || modelString };\n}\n\nasync function saveReviewFolder(\n reviewsDir: string,\n scope: ReviewScope,\n identifier: string,\n stories: Array<{ id: string; content: string | null }>,\n parsed: ParsedOracleResponse,\n oracleAnalysis: string,\n findings: FindingCounts,\n recommendedAgents: AgentRecommendation[],\n summaryText: string\n): Promise<string> {\n const date = new Date().toISOString().split(\"T\")[0];\n const folderName = `party-review-${scope}-${identifier.replace(\".\", \"-\")}-${date}`;\n const folderPath = join(reviewsDir, folderName);\n\n await ensureDirectory(folderPath);\n\n const storyList = stories.map((s) => s.id).join(\", \");\n const { summary } = parsed;\n\n const markdown = `# Party Review: ${scope === \"epic\" ? `Epic ${identifier}` : `Story ${identifier}`}\n\n**Date**: ${date}\n**Reviewer**: Oracle (Party Mode)\n**Stories Reviewed**: ${storyList}\n\n---\n\n## Executive Summary\n\n- **Total Issues**: ${summary.totalIssues}\n- **High Severity**: ${summary.highSeverity} issues (MUST address)\n- **Medium Severity**: ${summary.mediumSeverity} issues (SHOULD address)\n- **Low Severity**: ${summary.lowSeverity} issues (NICE to address)\n\n**Recommendation**: ${summary.recommendation}\n\n---\n\n## Findings\n\n${formatFindings(parsed)}\n\n---\n\n## Appendix: Oracle's Full Analysis\n\n<details>\n<summary>Click to expand detailed reasoning</summary>\n\n${oracleAnalysis}\n\n</details>\n`;\n\n const fullData: Phase1FullData = {\n success: true,\n scope,\n identifier,\n findings,\n recommendedAgents,\n reviewFolderPath: folderPath,\n summary: summaryText,\n storiesContent: stories,\n oracleAnalysis,\n };\n\n await writeFile(join(folderPath, \"review.md\"), markdown, \"utf-8\");\n await writeFile(join(folderPath, \"analysis.json\"), JSON.stringify(fullData, null, 2), \"utf-8\");\n\n return folderPath;\n}\n\nfunction formatFindings(parsed: ParsedOracleResponse): string {\n let output = \"\";\n\n const categoryIcons: Record<string, string> = {\n security: \"🔒\",\n logic: \"🧠\",\n bestPractices: \"✨\",\n performance: \"⚡\",\n };\n\n if (parsed.findings) {\n for (const [category, findings] of Object.entries(parsed.findings)) {\n if (findings && findings.length > 0) {\n output += `### ${categoryIcons[category] || \"\"} ${formatCategoryName(category)} (${findings.length} issues)\\n\\n`;\n for (const finding of findings) {\n output += `#### [${finding.severity.toUpperCase()}] ${finding.title}\\n`;\n output += `**Finding**: ${finding.description}\\n`;\n output += `**Impact**: ${finding.impact}\\n`;\n output += `**Suggestion**: ${finding.suggestion}\\n`;\n output += \"**Decision**: [ ] Accept [ ] Defer [ ] Reject\\n\\n\";\n }\n }\n }\n }\n\n if (parsed.storyFindings) {\n for (const story of parsed.storyFindings) {\n output += `### Story ${story.storyId}: ${story.title}\\n\\n`;\n for (const [category, findings] of Object.entries(story.findings)) {\n if (findings && findings.length > 0) {\n output += `#### ${categoryIcons[category] || \"\"} ${formatCategoryName(category)}\\n\\n`;\n for (const finding of findings) {\n output += `- [${finding.severity.toUpperCase()}] **${finding.title}**: ${finding.description}\\n`;\n }\n output += \"\\n\";\n }\n }\n }\n }\n\n if (parsed.crossStoryIssues && parsed.crossStoryIssues.length > 0) {\n output += \"### Cross-Story Issues\\n\\n\";\n for (const issue of parsed.crossStoryIssues) {\n output += `#### [${issue.severity.toUpperCase()}] ${issue.title}\\n`;\n output += `**Stories Affected**: ${issue.affectedStories.join(\", \")}\\n`;\n output += `**Description**: ${issue.description}\\n`;\n output += `**Suggestion**: ${issue.suggestion}\\n\\n`;\n }\n }\n\n return output || \"No findings detected.\";\n}\n\nfunction formatCategoryName(category: string): string {\n const names: Record<string, string> = {\n security: \"Security Issues\",\n logic: \"Logic Issues\",\n bestPractices: \"Best Practices\",\n performance: \"Performance Issues\",\n };\n return names[category] || category;\n}\n\nfunction buildSummary(findings: FindingCounts, agents: AgentRecommendation[]): string {\n const agentList = agents\n .filter((a) => a.priority !== \"optional\")\n .map((a) => a.agent)\n .join(\", \");\n\n return `Found ${findings.total} issues (${findings.high} high, ${findings.medium} medium, ${findings.low} low). Recommended agents: ${agentList || \"none\"}.`;\n}\n","import type { BmadAgentType } from \"../../shared/types.js\";\n\nexport interface AgentAnalysis {\n agent: BmadAgentType;\n perspective: string;\n findings: {\n agreements: string[];\n concerns: string[];\n suggestions: string[];\n };\n crossStoryPatterns: Array<{\n pattern: string;\n affectedStories: string[];\n recommendation: string;\n }>;\n prioritizedIssues: Array<{\n findingId: string;\n agentPriority: \"critical\" | \"important\" | \"minor\";\n rationale: string;\n }>;\n summary: string;\n}\n\nexport interface ConsensusPoint {\n topic: string;\n agents: BmadAgentType[];\n position: string;\n}\n\nexport interface DebatePoint {\n topic: string;\n positions: Array<{\n agent: BmadAgentType;\n position: string;\n }>;\n}\n\nexport interface AggregatedPriority {\n findingId: string;\n votes: Partial<Record<BmadAgentType, \"critical\" | \"important\" | \"minor\">>;\n consensusLevel: \"strong\" | \"moderate\" | \"disputed\";\n averagePriority: \"critical\" | \"important\" | \"minor\";\n}\n\nexport interface SynthesizedResult {\n agentAnalyses: AgentAnalysis[];\n consensusPoints: ConsensusPoint[];\n debatePoints: DebatePoint[];\n aggregatedPriorities: AggregatedPriority[];\n}\n\nexport function synthesizeAgentResponses(analyses: AgentAnalysis[]): SynthesizedResult {\n const consensusPoints = findConsensusPoints(analyses);\n const debatePoints = findDebatePoints(analyses);\n const aggregatedPriorities = aggregatePriorities(analyses);\n\n return {\n agentAnalyses: analyses,\n consensusPoints,\n debatePoints,\n aggregatedPriorities,\n };\n}\n\nfunction calculateConsensusThreshold(totalAgents: number): number {\n const minimumAgents = 2;\n const proportionalThreshold = Math.ceil(totalAgents * 0.5);\n return Math.max(minimumAgents, proportionalThreshold);\n}\n\nfunction findConsensusPoints(analyses: AgentAnalysis[]): ConsensusPoint[] {\n const concernMap = new Map<string, { agents: BmadAgentType[]; positions: string[] }>();\n\n for (const analysis of analyses) {\n for (const concern of analysis.findings.concerns) {\n const key = normalizeForComparison(concern);\n const existing = concernMap.get(key) || { agents: [], positions: [] };\n existing.agents.push(analysis.agent);\n existing.positions.push(concern);\n concernMap.set(key, existing);\n }\n\n for (const agreement of analysis.findings.agreements) {\n const key = normalizeForComparison(agreement);\n const existing = concernMap.get(key) || { agents: [], positions: [] };\n existing.agents.push(analysis.agent);\n existing.positions.push(agreement);\n concernMap.set(key, existing);\n }\n }\n\n const consensusThreshold = calculateConsensusThreshold(analyses.length);\n const consensusPoints: ConsensusPoint[] = [];\n\n for (const [_, data] of concernMap) {\n if (data.agents.length >= consensusThreshold) {\n consensusPoints.push({\n topic: data.positions[0],\n agents: data.agents,\n position: data.positions[0],\n });\n }\n }\n\n return consensusPoints;\n}\n\nfunction findDebatePoints(analyses: AgentAnalysis[]): DebatePoint[] {\n const debatePoints: DebatePoint[] = [];\n const processedPairs = new Set<string>();\n\n for (let i = 0; i < analyses.length; i++) {\n for (let j = i + 1; j < analyses.length; j++) {\n const agent1 = analyses[i];\n const agent2 = analyses[j];\n const pairKey = `${agent1.agent}-${agent2.agent}`;\n\n if (processedPairs.has(pairKey)) continue;\n processedPairs.add(pairKey);\n\n const conflictingPriorities = findConflictingPriorities(agent1, agent2);\n for (const conflict of conflictingPriorities) {\n debatePoints.push({\n topic: `Priority disagreement on ${conflict.findingId}`,\n positions: [\n { agent: agent1.agent, position: `${conflict.priority1}: ${conflict.rationale1}` },\n { agent: agent2.agent, position: `${conflict.priority2}: ${conflict.rationale2}` },\n ],\n });\n }\n }\n }\n\n return debatePoints;\n}\n\ninterface PriorityConflict {\n findingId: string;\n priority1: string;\n rationale1: string;\n priority2: string;\n rationale2: string;\n}\n\nfunction findConflictingPriorities(\n agent1: AgentAnalysis,\n agent2: AgentAnalysis\n): PriorityConflict[] {\n const conflicts: PriorityConflict[] = [];\n const priorityOrder = { critical: 0, important: 1, minor: 2 };\n\n for (const issue1 of agent1.prioritizedIssues) {\n const matchingIssue = agent2.prioritizedIssues.find((i) =>\n i.findingId.toLowerCase().includes(issue1.findingId.toLowerCase())\n );\n\n if (matchingIssue) {\n const diff = Math.abs(\n priorityOrder[issue1.agentPriority] - priorityOrder[matchingIssue.agentPriority]\n );\n if (diff >= 2) {\n conflicts.push({\n findingId: issue1.findingId,\n priority1: issue1.agentPriority,\n rationale1: issue1.rationale,\n priority2: matchingIssue.agentPriority,\n rationale2: matchingIssue.rationale,\n });\n }\n }\n }\n\n return conflicts;\n}\n\nfunction aggregatePriorities(analyses: AgentAnalysis[]): AggregatedPriority[] {\n const priorityMap = new Map<\n string,\n { votes: Partial<Record<BmadAgentType, \"critical\" | \"important\" | \"minor\">>; count: number }\n >();\n\n for (const analysis of analyses) {\n for (const issue of analysis.prioritizedIssues) {\n const existing = priorityMap.get(issue.findingId) || { votes: {}, count: 0 };\n existing.votes[analysis.agent] = issue.agentPriority;\n existing.count++;\n priorityMap.set(issue.findingId, existing);\n }\n }\n\n const aggregated: AggregatedPriority[] = [];\n for (const [findingId, data] of priorityMap) {\n const votes = Object.values(data.votes);\n const consensusLevel = calculateConsensusLevel(votes);\n const averagePriority = calculateAveragePriority(votes);\n\n aggregated.push({\n findingId,\n votes: data.votes,\n consensusLevel,\n averagePriority,\n });\n }\n\n return aggregated;\n}\n\nfunction calculateConsensusLevel(\n votes: Array<\"critical\" | \"important\" | \"minor\">\n): \"strong\" | \"moderate\" | \"disputed\" {\n if (votes.length <= 1) return \"strong\";\n\n const uniqueVotes = new Set(votes);\n if (uniqueVotes.size === 1) return \"strong\";\n if (uniqueVotes.size === 2) return \"moderate\";\n return \"disputed\";\n}\n\nfunction calculateAveragePriority(\n votes: Array<\"critical\" | \"important\" | \"minor\">\n): \"critical\" | \"important\" | \"minor\" {\n if (votes.length === 0) return \"minor\";\n\n const priorityOrder = { critical: 0, important: 1, minor: 2 };\n const sum = votes.reduce((acc, v) => acc + priorityOrder[v], 0);\n const avg = sum / votes.length;\n\n if (avg < 0.5) return \"critical\";\n if (avg < 1.5) return \"important\";\n return \"minor\";\n}\n\nfunction normalizeForComparison(text: string): string {\n return text\n .toLowerCase()\n .replace(/[^\\w\\s]/g, \"\")\n .split(/\\s+/)\n .slice(0, 5)\n .join(\" \");\n}\n\nexport function parseAgentResponse(responseText: string | null | undefined): AgentAnalysis | null {\n if (!responseText || typeof responseText !== \"string\") {\n return null;\n }\n\n try {\n const jsonMatch = responseText.match(/\\{[\\s\\S]*\\}/);\n if (!jsonMatch) return null;\n\n const parsed = JSON.parse(jsonMatch[0]) as AgentAnalysis;\n\n if (!parsed.agent || !parsed.findings) return null;\n\n return {\n agent: parsed.agent,\n perspective: parsed.perspective || \"\",\n findings: {\n agreements: parsed.findings.agreements || [],\n concerns: parsed.findings.concerns || [],\n suggestions: parsed.findings.suggestions || [],\n },\n crossStoryPatterns: parsed.crossStoryPatterns || [],\n prioritizedIssues: parsed.prioritizedIssues || [],\n summary: parsed.summary || \"\",\n };\n } catch {\n return null;\n }\n}\n","import { existsSync } from \"node:fs\";\nimport { readFile, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { type ToolDefinition, tool } from \"@opencode-ai/plugin\";\nimport type { PluginInput } from \"@opencode-ai/plugin\";\nimport type { AthenaConfig, BmadAgentType, Phase1FullData } from \"../../shared/types.js\";\nimport { getRecommendedAgentTypes } from \"../utils/agent-selector.js\";\nimport { getPersona, loadPersonas } from \"../utils/persona-loader.js\";\nimport {\n type AgentAnalysis,\n type SynthesizedResult,\n parseAgentResponse,\n synthesizeAgentResponses,\n} from \"../utils/response-synthesizer.js\";\n\nexport interface Phase2ConsultResult {\n success: boolean;\n identifier: string;\n reviewFolderPath?: string;\n error?: string;\n suggestion?: string;\n\n agentAnalyses?: AgentAnalysis[];\n consensusPoints?: SynthesizedResult[\"consensusPoints\"];\n debatePoints?: SynthesizedResult[\"debatePoints\"];\n aggregatedPriorities?: SynthesizedResult[\"aggregatedPriorities\"];\n summary?: string;\n}\n\nexport function createStoryReviewConsultTool(\n ctx: PluginInput,\n config: AthenaConfig\n): ToolDefinition {\n return tool({\n description: `Consult BMAD expert agents for their perspectives on review findings.\n\nThis tool performs Phase 2 of the party review workflow:\n1. Loads the full analysis from the review folder (analysis.json)\n2. Spawns parallel sessions for each recommended BMAD agent\n3. Each agent reads the analysis file and provides their perspective\n4. Waits for all agents to complete (blocking)\n5. Synthesizes responses to find consensus and debates\n\nUse this after Phase 1 (athena_story_review_analyze) and before Phase 3 (athena_party_discussion).`,\n\n args: {\n reviewFolderPath: tool.schema\n .string()\n .describe(\n \"Path to the review folder from athena_story_review_analyze (contains analysis.json)\"\n ),\n agents: tool.schema\n .array(tool.schema.string())\n .optional()\n .describe(\"Override agent list (default: use recommended from phase1)\"),\n },\n\n async execute(args): Promise<string> {\n const result = await executePhase2Consultation(\n ctx,\n config,\n args.reviewFolderPath,\n args.agents\n );\n return JSON.stringify(result, null, 2);\n },\n });\n}\n\nasync function executePhase2Consultation(\n ctx: PluginInput,\n config: AthenaConfig,\n reviewFolderPath: string,\n overrideAgents?: string[]\n): Promise<Phase2ConsultResult> {\n const analysisPath = join(reviewFolderPath, \"analysis.json\");\n\n if (!existsSync(analysisPath)) {\n return {\n success: false,\n identifier: \"\",\n error: `Analysis file not found: ${analysisPath}`,\n suggestion: \"Run athena_story_review_analyze first to generate the review folder\",\n };\n }\n\n let phase1: Phase1FullData;\n try {\n const analysisContent = await readFile(analysisPath, \"utf-8\");\n phase1 = JSON.parse(analysisContent);\n } catch (err) {\n const message = err instanceof Error ? err.message : \"Unknown error\";\n return {\n success: false,\n identifier: \"\",\n error: `Failed to load analysis.json: ${message}`,\n suggestion: \"Ensure the review folder contains a valid analysis.json file\",\n };\n }\n\n if (!phase1.success || !phase1.oracleAnalysis) {\n return {\n success: false,\n identifier: phase1.identifier,\n error: \"Phase 1 was not successful or missing oracle analysis\",\n suggestion: \"Run athena_story_review_analyze first\",\n };\n }\n\n const agents = overrideAgents\n ? (overrideAgents as BmadAgentType[])\n : getRecommendedAgentTypes(phase1.recommendedAgents || []);\n\n if (agents.length === 0) {\n return {\n success: false,\n identifier: phase1.identifier,\n error: \"No agents to consult\",\n suggestion: \"Specify agents or ensure Phase 1 has recommendations\",\n };\n }\n\n const personas = await loadPersonas(ctx.directory);\n\n const agentPromises = agents.map((agentType) =>\n spawnAgentAndWait(ctx, config, agentType, phase1, personas)\n );\n\n const agentResults = await Promise.all(agentPromises);\n\n const successfulAnalyses = agentResults.filter((r) => r !== null) as AgentAnalysis[];\n\n if (successfulAnalyses.length === 0) {\n return {\n success: false,\n identifier: phase1.identifier,\n error: \"All agent consultations failed\",\n suggestion: \"Check agent configuration and try again\",\n };\n }\n\n const synthesized = synthesizeAgentResponses(successfulAnalyses);\n\n const summary = buildConsultationSummary(synthesized, agents.length);\n\n const result: Phase2ConsultResult = {\n success: true,\n identifier: phase1.identifier,\n reviewFolderPath,\n agentAnalyses: synthesized.agentAnalyses,\n consensusPoints: synthesized.consensusPoints,\n debatePoints: synthesized.debatePoints,\n aggregatedPriorities: synthesized.aggregatedPriorities,\n summary,\n };\n\n const phase2Path = join(reviewFolderPath, \"phase2.json\");\n await writeFile(phase2Path, JSON.stringify(result, null, 2), \"utf-8\");\n\n return result;\n}\n\nasync function spawnAgentAndWait(\n ctx: PluginInput,\n config: AthenaConfig,\n agentType: BmadAgentType,\n phase1: Phase1FullData,\n personas: Map<BmadAgentType, import(\"../../shared/types.js\").BmadAgentFullPersona>\n): Promise<AgentAnalysis | null> {\n try {\n const persona = getPersona(personas, agentType);\n const prompt = buildAgentPrompt(persona, phase1);\n\n const createResult = await ctx.client.session.create({\n body: {\n title: `Party Review - ${persona.name} Analysis`,\n },\n });\n\n if (!createResult.data?.id) {\n console.warn(`[Athena] Failed to create session for ${agentType}`);\n return null;\n }\n\n const sessionId = createResult.data.id;\n\n await ctx.client.session.prompt({\n path: { id: sessionId },\n body: {\n model: parseModelConfig(config.models.sisyphus),\n parts: [{ type: \"text\", text: prompt }],\n },\n });\n\n const messagesResult = await ctx.client.session.messages({\n path: { id: sessionId },\n });\n\n const lastMessage = messagesResult.data?.at(-1);\n if (!lastMessage) {\n console.warn(`[Athena] No response from ${agentType}`);\n return null;\n }\n\n const textParts = lastMessage.parts?.filter((p) => p.type === \"text\") || [];\n const content = textParts.map((p) => (p as { text: string }).text).join(\"\\n\");\n\n const parsed = parseAgentResponse(content);\n if (!parsed) {\n return createFallbackAnalysis(agentType, persona.name, content);\n }\n\n return parsed;\n } catch (error) {\n const message = error instanceof Error ? error.message : \"Unknown error\";\n console.warn(`[Athena] Agent ${agentType} consultation failed: ${message}`);\n return null;\n }\n}\n\nfunction buildAgentPrompt(\n persona: import(\"../../shared/types.js\").BmadAgentFullPersona,\n phase1: Phase1FullData\n): string {\n const storiesContext = phase1.storiesContent\n ?.map((s: { id: string; content: string | null }) => {\n const preview = s.content?.substring(0, 2000) || \"(empty)\";\n const truncated = s.content && s.content.length > 2000 ? \"...[truncated]\" : \"\";\n return `Story ${s.id}:\\n${preview}${truncated}`;\n })\n .join(\"\\n\\n\");\n\n return `You are ${persona.name}, the ${persona.title} from the BMAD team.\n\n**Your Icon**: ${persona.icon}\n**Your Expertise**: ${persona.expertise.join(\", \")}\n**Your Perspective**: ${persona.perspective}\n\n**Your Task**: Analyze the following Oracle review findings from your ${persona.type} perspective.\n\n**Stories Being Reviewed**:\n${storiesContext || \"(No story content available)\"}\n\n**Oracle's Findings**:\n${phase1.oracleAnalysis || \"(No analysis available)\"}\n\n**Your Analysis Instructions**:\n1. Review each finding from your ${persona.perspective} perspective\n2. Note findings you agree with and why\n3. Raise any concerns specific to your expertise\n4. Suggest additional considerations\n5. Prioritize issues based on ${persona.expertise[0] || \"your expertise\"} impact\n\n**Return JSON** (MUST be valid JSON):\n{\n \"agent\": \"${persona.type}\",\n \"perspective\": \"${persona.perspective}\",\n \"findings\": {\n \"agreements\": [\"I agree with X because...\"],\n \"concerns\": [\"From my perspective, Y is concerning because...\"],\n \"suggestions\": [\"Consider also Z...\"]\n },\n \"crossStoryPatterns\": [\n { \"pattern\": \"...\", \"affectedStories\": [\"2.1\"], \"recommendation\": \"...\" }\n ],\n \"prioritizedIssues\": [\n { \"findingId\": \"...\", \"agentPriority\": \"critical|important|minor\", \"rationale\": \"...\" }\n ],\n \"summary\": \"Brief 2-3 sentence summary of my analysis\"\n}`;\n}\n\nfunction createFallbackAnalysis(\n agentType: BmadAgentType,\n agentName: string,\n rawContent: string\n): AgentAnalysis {\n return {\n agent: agentType,\n perspective: `${agentName}'s perspective`,\n findings: {\n agreements: [],\n concerns: [rawContent.substring(0, 200)],\n suggestions: [],\n },\n crossStoryPatterns: [],\n prioritizedIssues: [],\n summary: `${agentName} provided analysis but response was not in expected JSON format.`,\n };\n}\n\nfunction parseModelConfig(modelString: string): { providerID: string; modelID: string } {\n const [providerID, modelID] = modelString.split(\"/\");\n return { providerID: providerID || \"anthropic\", modelID: modelID || modelString };\n}\n\nfunction buildConsultationSummary(synthesized: SynthesizedResult, totalAgents: number): string {\n const successCount = synthesized.agentAnalyses.length;\n const consensusCount = synthesized.consensusPoints.length;\n const debateCount = synthesized.debatePoints.length;\n\n return `Consulted ${successCount}/${totalAgents} agents. Found ${consensusCount} consensus points and ${debateCount} debate points.`;\n}\n","import { type ToolDefinition, tool } from \"@opencode-ai/plugin\";\nimport type { PluginInput } from \"@opencode-ai/plugin\";\nimport type { AthenaConfig, BmadStoryStatus } from \"../../shared/types.js\";\nimport type { StoryTracker } from \"../tracker/story-tracker.js\";\nimport { getBmadPaths } from \"../utils/bmad-finder.js\";\nimport { sendNotification } from \"../utils/notifications.js\";\nimport { createPluginLogger } from \"../utils/plugin-logger.js\";\nimport { getStoryTitle, updateStoryFileStatus } from \"../utils/story-file-updater.js\";\nimport { findStoryFile, normalizeStoryId, stripAtPrefix } from \"../utils/story-loader.js\";\nimport {\n calculateSprintProgress,\n findNextReadyStory,\n parseStoryKey,\n readBmadSprintStatus,\n storyIdToDotFormat,\n updateEpicStatusIfNeeded,\n updateStoryStatus as updateSprintStoryStatus,\n} from \"../utils/yaml-handler.js\";\n\nconst log = createPluginLogger(\"update-status\");\n\nexport interface UpdateStatusResult {\n success?: boolean;\n storyId?: string;\n newStatus?: BmadStoryStatus;\n previousStatus?: string;\n updatedAt?: string;\n storyFileUpdated?: boolean;\n epicStatusUpdated?: boolean;\n epicNewStatus?: string;\n sprintProgress?: {\n total: number;\n done: number;\n inProgress: number;\n readyForDev: number;\n backlog: number;\n blocked: number;\n review: number;\n percentComplete: number;\n };\n nextStory?: string | null;\n error?: string;\n}\n\nexport function createUpdateStatusTool(\n ctx: PluginInput,\n tracker: StoryTracker,\n config: AthenaConfig\n): ToolDefinition {\n return tool({\n description: `Update the BMAD sprint status for a story.\n\nCall this tool when:\n- Starting a story (status: \"in-progress\")\n- Completing a story (status: \"done\") - requires completionSummary\n- Blocking on an issue (status: \"blocked\") - requires notes explaining blocker\n- Requesting review (status: \"review\")\n\nBoth sprint-status.yaml and the story file's Status field will be updated.`,\n\n args: {\n storyId: tool.schema.string().describe(\"Story ID (e.g., '2.3' or '2-3') or file path\"),\n status: tool.schema\n .enum([\"in-progress\", \"review\", \"done\", \"blocked\"])\n .describe(\"The new status (BMAD v6 hyphenated format)\"),\n notes: tool.schema\n .string()\n .optional()\n .describe(\"Notes about the status change (required for 'blocked')\"),\n completionSummary: tool.schema\n .string()\n .optional()\n .describe(\"Summary of what was implemented (required for 'done')\"),\n },\n\n async execute(args): Promise<string> {\n const result = await handleUpdateStatus(ctx, tracker, config, args);\n return JSON.stringify(result, null, 2);\n },\n });\n}\n\ninterface UpdateStatusArgs {\n storyId: string;\n status: \"in-progress\" | \"review\" | \"done\" | \"blocked\";\n notes?: string;\n completionSummary?: string;\n}\n\nasync function handleUpdateStatus(\n ctx: PluginInput,\n tracker: StoryTracker,\n config: AthenaConfig,\n args: UpdateStatusArgs\n): Promise<UpdateStatusResult> {\n const { status, notes, completionSummary } = args;\n const rawStoryId = stripAtPrefix(args.storyId);\n const normalizedId = normalizeStoryId(rawStoryId);\n\n log.debug(\"Updating story status\", {\n storyId: normalizedId,\n status,\n hasNotes: !!notes,\n hasSummary: !!completionSummary,\n });\n\n if (status === \"done\" && !completionSummary) {\n log.warn(\"Validation failed: completionSummary required for done status\", {\n storyId: normalizedId,\n });\n return { error: \"completionSummary is required when marking a story done\" };\n }\n\n if (status === \"blocked\" && !notes) {\n log.warn(\"Validation failed: notes required for blocked status\", { storyId: normalizedId });\n return { error: \"notes are required when blocking a story (explain the blocker)\" };\n }\n\n const paths = await getBmadPaths(ctx.directory, config);\n if (!paths.bmadDir) {\n log.warn(\"BMAD directory not found\", { directory: ctx.directory });\n return { error: \"No BMAD directory found\" };\n }\n\n if (!paths.sprintStatus) {\n log.error(\"Sprint status file not found\");\n return { error: \"No sprint-status.yaml found\" };\n }\n\n const sprintStatus = await readBmadSprintStatus(paths.sprintStatus);\n if (!sprintStatus) {\n log.error(\"Failed to read sprint status file\", { path: paths.sprintStatus });\n return { error: \"Failed to read sprint-status.yaml\" };\n }\n\n let storyTitle: string | undefined;\n const storyFile = await findStoryFile(paths.storiesDir, normalizedId);\n if (storyFile) {\n storyTitle = (await getStoryTitle(storyFile.path)) ?? undefined;\n }\n\n const updateResult = await updateSprintStoryStatus(\n paths.sprintStatus,\n normalizedId,\n status,\n storyTitle\n );\n\n if (!updateResult.success) {\n log.error(\"Failed to update sprint status\", { storyId: normalizedId });\n return { error: \"Failed to update sprint-status.yaml\" };\n }\n\n let storyFileUpdated = false;\n if (storyFile) {\n const fileUpdateResult = await updateStoryFileStatus(storyFile.path, status);\n storyFileUpdated = fileUpdateResult.success;\n if (!fileUpdateResult.success) {\n log.warn(\"Failed to update story file status\", {\n path: storyFile.path,\n error: fileUpdateResult.error,\n });\n }\n }\n\n const parsed = parseStoryKey(updateResult.key);\n let epicStatusUpdated = false;\n let epicNewStatus: string | undefined;\n\n if (parsed) {\n const epicUpdate = await updateEpicStatusIfNeeded(paths.sprintStatus, parsed.epicNum);\n if (epicUpdate.updated) {\n epicStatusUpdated = true;\n epicNewStatus = epicUpdate.newStatus;\n log.info(\"Auto-updated epic status\", {\n epicNum: parsed.epicNum,\n newStatus: epicUpdate.newStatus,\n });\n }\n }\n\n const now = new Date().toISOString();\n await tracker.updateStoryStatus(normalizedId, status);\n\n if (config.features?.notifications && status === \"done\") {\n log.debug(\"Sending completion notification\", { storyId: normalizedId });\n await sendNotification(\n `Story ${storyIdToDotFormat(normalizedId)} completed!`,\n \"OpenCode Athena\",\n ctx.$\n );\n }\n\n const updatedStatus = await readBmadSprintStatus(paths.sprintStatus);\n const progress = updatedStatus ? calculateSprintProgress(updatedStatus) : null;\n\n let nextStory: string | null = null;\n if (status === \"done\" && updatedStatus) {\n const next = findNextReadyStory(updatedStatus);\n nextStory = next ? storyIdToDotFormat(next.parsed.normalizedId) : null;\n }\n\n log.info(\"Story status updated successfully\", {\n storyId: normalizedId,\n status,\n previousStatus: updateResult.previousStatus,\n storyFileUpdated,\n epicStatusUpdated,\n progress,\n });\n\n return {\n success: true,\n storyId: storyIdToDotFormat(normalizedId),\n newStatus: status,\n previousStatus: updateResult.previousStatus,\n updatedAt: now,\n storyFileUpdated,\n epicStatusUpdated,\n epicNewStatus,\n sprintProgress: progress ?? undefined,\n nextStory,\n };\n}\n","import type { PluginInput, ToolDefinition } from \"@opencode-ai/plugin\";\nimport type { AthenaConfig } from \"../../shared/types.js\";\nimport type { StoryTracker } from \"../tracker/story-tracker.js\";\nimport { createAnalyzeStoryTool } from \"./analyze-story.js\";\nimport { createConfigTool } from \"./config.js\";\nimport { createDecomposeStoryTool } from \"./decompose-story.js\";\nimport { createGetContextTool } from \"./get-context.js\";\nimport { createGetStoryTool } from \"./get-story.js\";\nimport { createParallelTool } from \"./parallel.js\";\nimport { createPartyDiscussionTool } from \"./party-discussion.js\";\nimport { createReviewStoryTool } from \"./review-story.js\";\nimport { createStoryReviewAnalyzeTool } from \"./story-review-analyze.js\";\nimport { createStoryReviewConsultTool } from \"./story-review-consult.js\";\nimport { createUpdateStatusTool } from \"./update-status.js\";\n\n/**\n * Create all Athena tools\n *\n * @param ctx - Plugin context from OpenCode\n * @param tracker - Story tracker instance\n * @param config - Athena configuration\n * @returns Object containing all tool definitions\n */\nexport function createTools(\n ctx: PluginInput,\n tracker: StoryTracker,\n config: AthenaConfig\n): Record<string, ToolDefinition> {\n return {\n athena_get_story: createGetStoryTool(ctx, tracker, config),\n athena_update_status: createUpdateStatusTool(ctx, tracker, config),\n athena_get_context: createGetContextTool(tracker, config),\n athena_parallel: createParallelTool(),\n athena_config: createConfigTool(config),\n athena_review_story: createReviewStoryTool(ctx, config),\n athena_story_review_analyze: createStoryReviewAnalyzeTool(ctx, config),\n athena_story_review_consult: createStoryReviewConsultTool(ctx, config),\n athena_party_discussion: createPartyDiscussionTool(ctx, config),\n athena_analyze_story: createAnalyzeStoryTool(ctx, config),\n athena_decompose_story: createDecomposeStoryTool(ctx, config),\n };\n}\n","/**\n * Story Tracker\n *\n * Tracks the current story state and persists it across sessions.\n * State is stored in ~/.config/opencode/athena/athena-state.json\n */\n\nimport { existsSync } from \"node:fs\";\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport { CONFIG_PATHS } from \"../../shared/constants.js\";\nimport type {\n OpenCodeTodo,\n TrackedStory,\n TrackerState,\n TrackerStatus,\n} from \"../../shared/types.js\";\nimport { createPluginLogger } from \"../utils/plugin-logger.js\";\n\nconst log = createPluginLogger(\"story-tracker\");\n\n/**\n * Story tracker that persists state across sessions.\n *\n * Features:\n * - Tracks current story being implemented\n * - Maintains history of story status changes\n * - Persists state to disk for session recovery\n * - Scoped to project directory\n */\nexport class StoryTracker {\n private state: TrackerState;\n private stateFilePath: string;\n private projectDir: string;\n\n constructor(projectDir: string) {\n this.projectDir = projectDir;\n this.stateFilePath = CONFIG_PATHS.stateFile;\n this.state = {\n currentStory: null,\n sessionId: crypto.randomUUID(),\n projectDir,\n history: [],\n };\n }\n\n /**\n * Initialize the tracker by loading existing state\n */\n async initialize(): Promise<void> {\n if (existsSync(this.stateFilePath)) {\n try {\n const content = await readFile(this.stateFilePath, \"utf-8\");\n const savedState = JSON.parse(content) as TrackerState;\n\n // Only restore if same project directory\n if (savedState.projectDir === this.projectDir) {\n this.state = {\n ...savedState,\n sessionId: crypto.randomUUID(), // Always generate new session ID\n };\n }\n } catch {\n // Ignore errors, start with fresh state\n }\n }\n }\n\n /**\n * Set the current story being worked on\n */\n async setCurrentStory(storyId: string, data: Omit<TrackedStory, \"id\">): Promise<void> {\n this.state.currentStory = { id: storyId, ...data };\n this.addHistoryEntry(storyId, data.status);\n await this.saveState();\n }\n\n /**\n * Update the status of a story\n */\n async updateStoryStatus(storyId: string, status: TrackerStatus): Promise<void> {\n if (this.state.currentStory?.id === storyId) {\n this.state.currentStory.status = status;\n if (status === \"done\") {\n this.state.currentStory.completedAt = new Date().toISOString();\n }\n }\n this.addHistoryEntry(storyId, status);\n await this.saveState();\n }\n\n /**\n * Get the current story being tracked\n */\n getCurrentStory(): TrackedStory | null {\n return this.state.currentStory;\n }\n\n /**\n * Get a formatted context string for the current story\n * Used for compaction hooks to preserve context\n */\n async getCurrentStoryContext(): Promise<string | null> {\n if (!this.state.currentStory) {\n return null;\n }\n\n const story = this.state.currentStory;\n const recentHistory = this.state.history\n .slice(-5)\n .map((h) => `- ${h.storyId}: ${h.status} at ${h.timestamp}`)\n .join(\"\\n\");\n\n return `\nCurrent Story: ${story.id}\nStatus: ${story.status}\nStarted: ${story.startedAt}\n${story.completedAt ? `Completed: ${story.completedAt}` : \"\"}\n\nRecent Activity:\n${recentHistory}\n`.trim();\n }\n\n /**\n * Clear the current story (e.g., when completed or cancelled)\n */\n async clearCurrentStory(): Promise<void> {\n this.state.currentStory = null;\n await this.saveState();\n }\n\n /**\n * Get the current session ID\n */\n getSessionId(): string {\n return this.state.sessionId;\n }\n\n /**\n * Get the history of status changes\n */\n getHistory(): TrackerState[\"history\"] {\n return this.state.history;\n }\n\n getCurrentTodos(): OpenCodeTodo[] | null {\n return this.state.currentTodos || null;\n }\n\n async setCurrentTodos(todos: OpenCodeTodo[]): Promise<void> {\n this.state.currentTodos = todos;\n await this.saveState();\n }\n\n async clearTodos(): Promise<void> {\n this.state.currentTodos = undefined;\n await this.saveState();\n }\n\n /**\n * Add an entry to the history\n */\n private addHistoryEntry(storyId: string, status: string): void {\n this.state.history.push({\n storyId,\n status,\n timestamp: new Date().toISOString(),\n });\n\n // Keep history bounded (last 100 entries)\n if (this.state.history.length > 100) {\n this.state.history = this.state.history.slice(-100);\n }\n }\n\n /**\n * Save state to disk\n */\n private async saveState(): Promise<void> {\n try {\n const dir = dirname(this.stateFilePath);\n if (!existsSync(dir)) {\n await mkdir(dir, { recursive: true });\n }\n await writeFile(this.stateFilePath, JSON.stringify(this.state, null, 2), \"utf-8\");\n } catch (error) {\n log.warn(\"Failed to save tracker state\", { error });\n }\n }\n}\n","import { z } from \"zod\";\n\n/**\n * Zod validation schemas for OpenCode Athena\n */\n\n// ============================================================================\n// Configuration Schemas\n// ============================================================================\n\n/**\n * Schema for subscription configuration\n */\nexport const SubscriptionSchema = z.object({\n claude: z.object({\n enabled: z.boolean(),\n tier: z.enum([\"max5x\", \"max20x\", \"pro\", \"none\"]),\n }),\n openai: z.object({\n enabled: z.boolean(),\n }),\n google: z.object({\n enabled: z.boolean(),\n authMethod: z.enum([\"antigravity\", \"personal\", \"api\", \"none\"]),\n }),\n githubCopilot: z.object({\n enabled: z.boolean(),\n plan: z.enum([\"free\", \"pro\", \"pro-plus\", \"business\", \"enterprise\", \"none\"]),\n enabledModels: z.array(z.string()).optional(),\n }),\n});\n\n/**\n * Schema for BMAD configuration\n */\nexport const BmadConfigSchema = z.object({\n defaultTrack: z.enum([\"quick-flow\", \"bmad-method\", \"enterprise\"]),\n autoStatusUpdate: z.boolean(),\n parallelStoryLimit: z.number().int().min(0).max(10),\n paths: z\n .object({\n stories: z\n .string()\n .nullable()\n .optional()\n .describe(\"Custom path to stories directory (null = auto-detect)\"),\n sprintStatus: z\n .string()\n .nullable()\n .optional()\n .describe(\"Custom path to sprint-status.yaml file (null = auto-detect)\"),\n prd: z\n .string()\n .nullable()\n .optional()\n .describe(\"Custom path to PRD.md file (null = auto-detect)\"),\n architecture: z\n .string()\n .nullable()\n .optional()\n .describe(\"Custom path to architecture.md file (null = auto-detect)\"),\n epics: z\n .string()\n .nullable()\n .optional()\n .describe(\"Custom path to epics.md file (null = auto-detect)\"),\n })\n .optional(),\n});\n\n/**\n * Schema for feature flags\n */\nexport const FeaturesSchema = z.object({\n bmadBridge: z.boolean(),\n autoStatus: z.boolean(),\n parallelExecution: z.boolean(),\n notifications: z.boolean(),\n contextMonitor: z.boolean(),\n commentChecker: z.boolean(),\n lspTools: z.boolean(),\n autoGitOperations: z.boolean().default(false),\n todoSync: z.boolean().default(true),\n});\n\n/**\n * Schema for MCP configuration\n */\nexport const McpsSchema = z.object({\n context7: z.boolean(),\n exa: z.boolean(),\n grepApp: z.boolean(),\n});\n\n/**\n * Schema for LLM provider\n */\nexport const LLMProviderSchema = z.enum([\"anthropic\", \"openai\", \"google\", \"github-copilot\"]);\n\n/**\n * Schema for agent routing configuration\n */\nexport const AgentRoutingSchema = z.object({\n requiresThinking: z.boolean().optional(),\n preferProvider: LLMProviderSchema.optional(),\n});\n\n/**\n * Schema for routing configuration\n */\nexport const RoutingConfigSchema = z.object({\n providerPriority: z.array(LLMProviderSchema),\n modelFamilyPriority: z.object({\n claude: z.array(LLMProviderSchema).optional(),\n gpt: z.array(LLMProviderSchema).optional(),\n gemini: z.array(LLMProviderSchema).optional(),\n }),\n agentOverrides: z.object({\n sisyphus: AgentRoutingSchema.optional(),\n oracle: AgentRoutingSchema.optional(),\n librarian: AgentRoutingSchema.optional(),\n frontend: AgentRoutingSchema.optional(),\n documentWriter: AgentRoutingSchema.optional(),\n multimodalLooker: AgentRoutingSchema.optional(),\n }),\n fallbackBehavior: z.object({\n autoFallback: z.boolean(),\n retryPeriodMs: z.number().min(0),\n notifyOnRateLimit: z.boolean(),\n }),\n});\n\n/**\n * Schema for thinking level\n */\nexport const ThinkingLevelSchema = z.enum([\"off\", \"low\", \"medium\", \"high\"]);\n\n/**\n * Schema for agent settings (temperature and thinking level)\n */\nexport const AgentSettingsSchema = z.object({\n temperature: z.number().min(0).max(1).optional(),\n thinkingLevel: ThinkingLevelSchema.optional(),\n});\n\n/**\n * Schema for custom model definition\n */\nexport const CustomModelDefinitionSchema = z.object({\n id: z.string(),\n name: z.string(),\n provider: z.enum([\"anthropic\", \"openai\", \"google\", \"github-copilot\"]),\n description: z.string().optional(),\n capabilities: z\n .object({\n thinking: z.boolean().optional(),\n contextWindow: z.number().optional(),\n supportsTemperature: z.boolean().optional(),\n })\n .optional(),\n});\n\n/**\n * Schema for agent model assignments\n */\nexport const ModelsSchema = z.object({\n sisyphus: z.string().describe(\"Model for main orchestrator agent\"),\n oracle: z.string().describe(\"Model for debugging/reasoning agent\"),\n librarian: z.string().describe(\"Model for research/documentation agent\"),\n frontend: z.string().optional().describe(\"Model for UI/UX agent\"),\n documentWriter: z.string().optional().describe(\"Model for documentation generation agent\"),\n multimodalLooker: z.string().optional().describe(\"Model for image analysis agent\"),\n settings: z\n .object({\n sisyphus: AgentSettingsSchema.optional(),\n oracle: AgentSettingsSchema.optional(),\n librarian: AgentSettingsSchema.optional(),\n frontend: AgentSettingsSchema.optional(),\n documentWriter: AgentSettingsSchema.optional(),\n multimodalLooker: AgentSettingsSchema.optional(),\n overrides: z.record(z.string(), AgentSettingsSchema).optional(),\n })\n .optional(),\n custom: z.array(CustomModelDefinitionSchema).optional(),\n});\n\n/**\n * Complete Athena configuration schema\n */\nexport const AthenaConfigSchema = z.object({\n $schema: z.string().optional(),\n version: z.string(),\n subscriptions: SubscriptionSchema,\n models: ModelsSchema,\n bmad: BmadConfigSchema,\n features: FeaturesSchema,\n mcps: McpsSchema,\n routing: RoutingConfigSchema,\n});\n\n// ============================================================================\n// Tool Argument Schemas\n// ============================================================================\n\n/**\n * Schema for athena_get_story arguments\n */\nexport const GetStoryArgsSchema = z.object({\n storyId: z\n .string()\n .optional()\n .describe(\n \"Specific story ID (e.g., '2.3'). If omitted, loads the next pending story from sprint-status.yaml.\"\n ),\n});\n\nexport const UpdateStatusArgsSchema = z.object({\n storyId: z.string().describe(\"The story ID (e.g., '2.3' or '2-3')\"),\n status: z\n .enum([\"in-progress\", \"review\", \"done\", \"blocked\"])\n .describe(\"The new status for the story (BMAD v6 hyphenated format)\"),\n notes: z\n .string()\n .optional()\n .describe(\"Notes about the status change (required for 'blocked' status)\"),\n completionSummary: z\n .string()\n .optional()\n .describe(\"Summary of what was implemented (required for 'done' status)\"),\n});\n\n/**\n * Schema for athena_get_context arguments\n */\nexport const GetContextArgsSchema = z.object({\n includeArchitecture: z.boolean().optional().default(true),\n includePrd: z.boolean().optional().default(false),\n includeSprintStatus: z.boolean().optional().default(true),\n});\n\n/**\n * Schema for athena_parallel arguments\n */\nexport const ParallelArgsSchema = z.object({\n storyIds: z.array(z.string()).describe(\"Array of story IDs to implement in parallel\"),\n maxConcurrent: z.number().int().min(1).max(5).optional().default(3),\n});\n\n/**\n * Schema for athena_config arguments\n */\nexport const ConfigArgsSchema = z.object({\n action: z.enum([\"get\", \"set\", \"reset\"]).describe(\"Configuration action to perform\"),\n key: z\n .string()\n .optional()\n .describe(\"Configuration key (dot notation, e.g., 'bmad.autoStatusUpdate')\"),\n value: z.unknown().optional().describe(\"Value to set (for 'set' action)\"),\n});\n\n// ============================================================================\n// BMAD v6 Sprint Status Schemas (Flat Map Structure)\n// ============================================================================\n\nexport const BmadStoryStatusEnum = z.enum([\n \"backlog\",\n \"ready-for-dev\",\n \"in-progress\",\n \"review\",\n \"done\",\n \"blocked\",\n]);\n\nexport const BmadEpicStatusEnum = z.enum([\"backlog\", \"in-progress\", \"done\"]);\n\nexport const BmadRetroStatusEnum = z.enum([\"optional\", \"done\"]);\n\nexport const BmadDevelopmentStatusEnum = z.enum([\n \"backlog\",\n \"ready-for-dev\",\n \"in-progress\",\n \"review\",\n \"done\",\n \"blocked\",\n \"optional\",\n]);\n\nexport const BmadSprintStatusSchema = z.object({\n generated: z.string().optional(),\n project: z.string().optional(),\n project_key: z.string().optional(),\n tracking_system: z.string().optional(),\n story_location: z.string().optional(),\n current_story: z.string().nullable().optional(),\n last_modified: z.string().optional(),\n development_status: z.record(z.string(), BmadDevelopmentStatusEnum),\n});\n\nexport const BmadUpdateStatusArgsSchema = z.object({\n storyId: z.string().describe(\"The story ID (e.g., '2.3' or '2-3')\"),\n status: BmadStoryStatusEnum.describe(\"The new status for the story\"),\n notes: z.string().optional().describe(\"Notes about the status change (required for 'blocked')\"),\n completionSummary: z\n .string()\n .optional()\n .describe(\"Summary of implementation (required for 'done')\"),\n});\n\n// ============================================================================\n// Legacy Sprint Status Schema (Deprecated - Array-based)\n// ============================================================================\n\n/** @deprecated Use BmadStoryStatusEnum */\nexport const StoryStatusEnum = z.enum([\n \"pending\",\n \"in_progress\",\n \"completed\",\n \"blocked\",\n \"needs_review\",\n]);\n\n/** @deprecated Use BmadStoryStatusEnum with \"loading\" handled separately */\nexport const TrackerStatusEnum = z.enum([\n \"backlog\",\n \"ready-for-dev\",\n \"in-progress\",\n \"review\",\n \"done\",\n \"blocked\",\n \"loading\",\n]);\n\n/** @deprecated Use BmadSprintStatusSchema */\nexport const SprintStatusSchema = z.object({\n sprint_number: z.number().int().optional(),\n current_epic: z.string().optional(),\n current_story: z.string().nullable().optional(),\n completed_stories: z.array(z.string()).default([]),\n pending_stories: z.array(z.string()).default([]),\n in_progress_stories: z.array(z.string()).default([]),\n blocked_stories: z.array(z.string()).default([]),\n stories_needing_review: z.array(z.string()).optional(),\n story_updates: z\n .record(\n z.object({\n status: StoryStatusEnum,\n updated_at: z.string(),\n notes: z.string().optional(),\n completion_summary: z.string().optional(),\n })\n )\n .optional(),\n last_modified: z.string().optional(),\n});\n\n// ============================================================================\n// Type Exports (inferred from schemas)\n// ============================================================================\n\nexport type SubscriptionConfig = z.infer<typeof SubscriptionSchema>;\nexport type BmadConfig = z.infer<typeof BmadConfigSchema>;\nexport type FeaturesConfig = z.infer<typeof FeaturesSchema>;\nexport type McpsConfig = z.infer<typeof McpsSchema>;\nexport type ModelsConfig = z.infer<typeof ModelsSchema>;\nexport type RoutingConfigValidated = z.infer<typeof RoutingConfigSchema>;\nexport type AthenaConfigValidated = z.infer<typeof AthenaConfigSchema>;\nexport type BmadSprintStatusValidated = z.infer<typeof BmadSprintStatusSchema>;\nexport type BmadStoryStatusValidated = z.infer<typeof BmadStoryStatusEnum>;\nexport type BmadDevelopmentStatusValidated = z.infer<typeof BmadDevelopmentStatusEnum>;\n/** @deprecated Use BmadSprintStatusValidated */\nexport type SprintStatusValidated = z.infer<typeof SprintStatusSchema>;\n","/**\n * Configuration loader for Athena plugin\n *\n * Loads AthenaConfig from project-local or global config files.\n * Project config takes priority over global config.\n * Uses Zod validation for type safety and clear error messages.\n */\n\nimport { existsSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { CONFIG_PATHS, DEFAULTS } from \"../../shared/constants.js\";\nimport { AthenaConfigSchema } from \"../../shared/schemas.js\";\nimport type { AthenaConfig } from \"../../shared/types.js\";\nimport { createPluginLogger } from \"./plugin-logger.js\";\n\nconst log = createPluginLogger(\"config-loader\");\n\n/**\n * Load Athena configuration from available config files.\n *\n * Priority order:\n * 1. Project-local: [projectDir]/.opencode/athena.json\n * 2. Global: ~/.config/opencode/athena.json\n * 3. Default values if no config found\n *\n * @param projectDir - The project directory to search for local config\n * @returns The merged Athena configuration\n */\nexport async function loadAthenaConfig(projectDir: string): Promise<AthenaConfig> {\n // Try project-local config first\n const localConfigPath = join(projectDir, \".opencode\", \"athena.json\");\n const localConfig = await loadConfigFile(localConfigPath);\n\n // Try global config\n const globalConfig = await loadConfigFile(CONFIG_PATHS.globalAthenaConfig);\n\n // Merge configs: local overrides global, both override defaults\n const merged = mergeConfigs(getDefaultConfig(), globalConfig, localConfig);\n\n // Validate the final merged config\n return validateConfig(merged);\n}\n\n/**\n * Load and parse a JSON config file\n */\nasync function loadConfigFile(filePath: string): Promise<Partial<AthenaConfig> | null> {\n if (!existsSync(filePath)) {\n return null;\n }\n\n try {\n const content = await readFile(filePath, \"utf-8\");\n const parsed = JSON.parse(content);\n\n // Perform partial validation to catch obvious errors early\n // We don't require all fields since this is a partial config\n return validatePartialConfig(parsed, filePath);\n } catch (error) {\n if (error instanceof SyntaxError) {\n log.warn(\"Invalid JSON in config file\", { filePath, message: error.message });\n } else {\n log.warn(\"Failed to load config file\", { filePath, error });\n }\n return null;\n }\n}\n\n/**\n * Validate a partial config file and return it with warnings for invalid fields\n */\nfunction validatePartialConfig(config: unknown, filePath: string): Partial<AthenaConfig> | null {\n if (typeof config !== \"object\" || config === null) {\n log.warn(\"Config file must be an object\", { filePath });\n return null;\n }\n\n const result: Partial<AthenaConfig> = {};\n const configObj = config as Record<string, unknown>;\n\n // Validate and copy each top-level field\n if (\"version\" in configObj && typeof configObj.version === \"string\") {\n result.version = configObj.version;\n }\n\n if (\"$schema\" in configObj && typeof configObj.$schema === \"string\") {\n result.$schema = configObj.$schema;\n }\n\n // Validate subscriptions\n if (\"subscriptions\" in configObj && typeof configObj.subscriptions === \"object\") {\n const subs = configObj.subscriptions as Record<string, unknown>;\n result.subscriptions = {} as AthenaConfig[\"subscriptions\"];\n\n if (subs.claude && typeof subs.claude === \"object\") {\n const claude = subs.claude as Record<string, unknown>;\n result.subscriptions.claude = {\n enabled: typeof claude.enabled === \"boolean\" ? claude.enabled : false,\n tier: isValidTier(claude.tier) ? claude.tier : \"none\",\n };\n }\n\n if (subs.openai && typeof subs.openai === \"object\") {\n const openai = subs.openai as Record<string, unknown>;\n result.subscriptions.openai = {\n enabled: typeof openai.enabled === \"boolean\" ? openai.enabled : false,\n };\n }\n\n if (subs.google && typeof subs.google === \"object\") {\n const google = subs.google as Record<string, unknown>;\n result.subscriptions.google = {\n enabled: typeof google.enabled === \"boolean\" ? google.enabled : false,\n authMethod: isValidAuthMethod(google.authMethod) ? google.authMethod : \"none\",\n };\n }\n\n if (subs.githubCopilot && typeof subs.githubCopilot === \"object\") {\n const copilot = subs.githubCopilot as Record<string, unknown>;\n result.subscriptions.githubCopilot = {\n enabled: typeof copilot.enabled === \"boolean\" ? copilot.enabled : false,\n plan: isValidCopilotPlan(copilot.plan) ? copilot.plan : \"none\",\n enabledModels: Array.isArray(copilot.enabledModels)\n ? copilot.enabledModels.filter((m): m is string => typeof m === \"string\")\n : undefined,\n };\n }\n }\n\n // Validate models\n if (\"models\" in configObj && typeof configObj.models === \"object\") {\n const models = configObj.models as Record<string, unknown>;\n result.models = {} as AthenaConfig[\"models\"];\n\n const modelKeys = [\n \"sisyphus\",\n \"oracle\",\n \"librarian\",\n \"frontend\",\n \"documentWriter\",\n \"multimodalLooker\",\n ] as const;\n\n for (const key of modelKeys) {\n if (key in models && typeof models[key] === \"string\") {\n (result.models as unknown as Record<string, string>)[key] = models[key] as string;\n }\n }\n\n if (\"settings\" in models && typeof models.settings === \"object\" && models.settings !== null) {\n result.models.settings = validateModelSettings(models.settings as Record<string, unknown>);\n }\n\n if (\"custom\" in models && Array.isArray(models.custom)) {\n result.models.custom = validateCustomModels(models.custom);\n }\n }\n\n // Validate bmad\n if (\"bmad\" in configObj && typeof configObj.bmad === \"object\") {\n const bmad = configObj.bmad as Record<string, unknown>;\n result.bmad = {} as AthenaConfig[\"bmad\"];\n\n if (isValidTrack(bmad.defaultTrack)) {\n result.bmad.defaultTrack = bmad.defaultTrack;\n }\n if (typeof bmad.autoStatusUpdate === \"boolean\") {\n result.bmad.autoStatusUpdate = bmad.autoStatusUpdate;\n }\n if (typeof bmad.parallelStoryLimit === \"number\") {\n result.bmad.parallelStoryLimit = Math.max(0, Math.min(10, bmad.parallelStoryLimit));\n }\n }\n\n // Validate features\n if (\"features\" in configObj && typeof configObj.features === \"object\") {\n const features = configObj.features as Record<string, unknown>;\n result.features = {} as AthenaConfig[\"features\"];\n\n for (const key of [\n \"bmadBridge\",\n \"autoStatus\",\n \"parallelExecution\",\n \"notifications\",\n \"contextMonitor\",\n \"commentChecker\",\n \"lspTools\",\n ]) {\n if (key in features && typeof features[key] === \"boolean\") {\n (result.features as Record<string, boolean>)[key] = features[key] as boolean;\n }\n }\n }\n\n // Validate mcps\n if (\"mcps\" in configObj && typeof configObj.mcps === \"object\") {\n const mcps = configObj.mcps as Record<string, unknown>;\n result.mcps = {} as AthenaConfig[\"mcps\"];\n\n for (const key of [\"context7\", \"exa\", \"grepApp\"]) {\n if (key in mcps && typeof mcps[key] === \"boolean\") {\n (result.mcps as Record<string, boolean>)[key] = mcps[key] as boolean;\n }\n }\n }\n\n return result;\n}\n\n/**\n * Type guard for valid Claude tier\n */\nfunction isValidTier(value: unknown): value is \"max5x\" | \"max20x\" | \"pro\" | \"none\" {\n return typeof value === \"string\" && [\"max5x\", \"max20x\", \"pro\", \"none\"].includes(value);\n}\n\n/**\n * Type guard for valid Google auth method\n */\nfunction isValidAuthMethod(value: unknown): value is \"antigravity\" | \"personal\" | \"api\" | \"none\" {\n return typeof value === \"string\" && [\"antigravity\", \"personal\", \"api\", \"none\"].includes(value);\n}\n\n/**\n * Type guard for valid GitHub Copilot plan\n */\nfunction isValidCopilotPlan(\n value: unknown\n): value is \"free\" | \"pro\" | \"pro-plus\" | \"business\" | \"enterprise\" | \"none\" {\n return (\n typeof value === \"string\" &&\n [\"free\", \"pro\", \"pro-plus\", \"business\", \"enterprise\", \"none\"].includes(value)\n );\n}\n\n/**\n * Type guard for valid BMAD track\n */\nfunction isValidTrack(value: unknown): value is \"quick-flow\" | \"bmad-method\" | \"enterprise\" {\n return typeof value === \"string\" && [\"quick-flow\", \"bmad-method\", \"enterprise\"].includes(value);\n}\n\nfunction isValidThinkingLevel(value: unknown): value is \"off\" | \"low\" | \"medium\" | \"high\" {\n return typeof value === \"string\" && [\"off\", \"low\", \"medium\", \"high\"].includes(value);\n}\n\nfunction isValidProvider(\n value: unknown\n): value is \"anthropic\" | \"openai\" | \"google\" | \"github-copilot\" {\n return (\n typeof value === \"string\" && [\"anthropic\", \"openai\", \"google\", \"github-copilot\"].includes(value)\n );\n}\n\nfunction validateAgentSettings(settings: unknown): AthenaConfig[\"models\"][\"settings\"] {\n if (typeof settings !== \"object\" || settings === null) {\n return undefined;\n }\n\n const result: AthenaConfig[\"models\"][\"settings\"] = {};\n const settingsObj = settings as Record<string, unknown>;\n const agentKeys = [\n \"sisyphus\",\n \"oracle\",\n \"librarian\",\n \"frontend\",\n \"documentWriter\",\n \"multimodalLooker\",\n ] as const;\n\n for (const key of agentKeys) {\n if (key in settingsObj && typeof settingsObj[key] === \"object\" && settingsObj[key] !== null) {\n const agentSetting = settingsObj[key] as Record<string, unknown>;\n const validated: { temperature?: number; thinkingLevel?: \"off\" | \"low\" | \"medium\" | \"high\" } =\n {};\n\n if (\n typeof agentSetting.temperature === \"number\" &&\n agentSetting.temperature >= 0 &&\n agentSetting.temperature <= 2\n ) {\n validated.temperature = agentSetting.temperature;\n }\n\n if (isValidThinkingLevel(agentSetting.thinkingLevel)) {\n validated.thinkingLevel = agentSetting.thinkingLevel;\n }\n\n if (Object.keys(validated).length > 0) {\n result[key] = validated;\n }\n }\n }\n\n if (\n \"overrides\" in settingsObj &&\n typeof settingsObj.overrides === \"object\" &&\n settingsObj.overrides !== null\n ) {\n const overrides = settingsObj.overrides as Record<string, unknown>;\n result.overrides = {};\n\n for (const [modelId, modelSettings] of Object.entries(overrides)) {\n if (typeof modelSettings === \"object\" && modelSettings !== null) {\n const ms = modelSettings as Record<string, unknown>;\n const validated: {\n temperature?: number;\n thinkingLevel?: \"off\" | \"low\" | \"medium\" | \"high\";\n } = {};\n\n if (typeof ms.temperature === \"number\" && ms.temperature >= 0 && ms.temperature <= 2) {\n validated.temperature = ms.temperature;\n }\n\n if (isValidThinkingLevel(ms.thinkingLevel)) {\n validated.thinkingLevel = ms.thinkingLevel;\n }\n\n if (Object.keys(validated).length > 0) {\n result.overrides[modelId] = validated;\n }\n }\n }\n }\n\n return Object.keys(result).length > 0 ? result : undefined;\n}\n\nfunction validateModelSettings(\n settings: Record<string, unknown>\n): AthenaConfig[\"models\"][\"settings\"] {\n return validateAgentSettings(settings);\n}\n\nfunction validateCustomModels(models: unknown[]): AthenaConfig[\"models\"][\"custom\"] {\n const validated: AthenaConfig[\"models\"][\"custom\"] = [];\n\n for (const model of models) {\n if (typeof model !== \"object\" || model === null) continue;\n\n const m = model as Record<string, unknown>;\n if (typeof m.id !== \"string\" || typeof m.name !== \"string\" || !isValidProvider(m.provider)) {\n continue;\n }\n\n const customModel: {\n id: string;\n name: string;\n provider: \"anthropic\" | \"openai\" | \"google\" | \"github-copilot\";\n description?: string;\n capabilities?: { thinking?: boolean; contextWindow?: number; supportsTemperature?: boolean };\n } = {\n id: m.id,\n name: m.name,\n provider: m.provider,\n };\n\n if (typeof m.description === \"string\") {\n customModel.description = m.description;\n }\n\n if (typeof m.capabilities === \"object\" && m.capabilities !== null) {\n const caps = m.capabilities as Record<string, unknown>;\n customModel.capabilities = {};\n\n if (typeof caps.thinking === \"boolean\") {\n customModel.capabilities.thinking = caps.thinking;\n }\n if (typeof caps.contextWindow === \"number\") {\n customModel.capabilities.contextWindow = caps.contextWindow;\n }\n if (typeof caps.supportsTemperature === \"boolean\") {\n customModel.capabilities.supportsTemperature = caps.supportsTemperature;\n }\n }\n\n validated.push(customModel);\n }\n\n return validated.length > 0 ? validated : undefined;\n}\n\n/**\n * Validate the final merged config using Zod schema\n */\nfunction validateConfig(config: AthenaConfig): AthenaConfig {\n const result = AthenaConfigSchema.safeParse(config);\n\n if (!result.success) {\n // Log validation errors but don't fail - use defaults for invalid fields\n log.warn(\"Configuration validation warnings\", {\n errors: result.error.errors.map((e) => ({\n path: e.path.join(\".\"),\n message: e.message,\n })),\n });\n\n // Return the original config since we already have defaults\n // The individual fields will be used even if some are invalid\n return config;\n }\n\n return result.data;\n}\n\n/**\n * Get default configuration values\n */\nfunction getDefaultConfig(): AthenaConfig {\n return {\n version: \"0.0.1\",\n subscriptions: {\n claude: { enabled: false, tier: \"none\" },\n openai: { enabled: false },\n google: { enabled: false, authMethod: \"none\" },\n githubCopilot: { enabled: false, plan: \"none\" },\n },\n models: {\n sisyphus: \"anthropic/claude-sonnet-4\",\n oracle: \"anthropic/claude-sonnet-4\",\n librarian: \"anthropic/claude-sonnet-4\",\n },\n bmad: {\n defaultTrack: DEFAULTS.defaultTrack,\n autoStatusUpdate: DEFAULTS.autoStatusUpdate,\n parallelStoryLimit: DEFAULTS.parallelStoryLimit,\n },\n features: { ...DEFAULTS.features },\n mcps: { ...DEFAULTS.mcps },\n routing: {\n providerPriority: [\"anthropic\", \"openai\", \"google\", \"github-copilot\"],\n modelFamilyPriority: {\n claude: [\"anthropic\", \"github-copilot\"],\n gpt: [\"openai\", \"github-copilot\"],\n gemini: [\"google\", \"github-copilot\"],\n },\n agentOverrides: {\n oracle: {\n requiresThinking: true,\n },\n },\n fallbackBehavior: {\n autoFallback: false,\n retryPeriodMs: 300000,\n notifyOnRateLimit: true,\n },\n },\n };\n}\n\n/**\n * Deep merge multiple config objects\n * Later configs override earlier ones\n */\nfunction mergeConfigs(...configs: (Partial<AthenaConfig> | null)[]): AthenaConfig {\n const result = getDefaultConfig();\n\n for (const config of configs) {\n if (!config) continue;\n\n // Merge top-level primitives\n if (config.version) result.version = config.version;\n\n // Merge subscriptions\n if (config.subscriptions) {\n if (config.subscriptions.claude) {\n result.subscriptions.claude = {\n ...result.subscriptions.claude,\n ...config.subscriptions.claude,\n };\n }\n if (config.subscriptions.openai) {\n result.subscriptions.openai = {\n ...result.subscriptions.openai,\n ...config.subscriptions.openai,\n };\n }\n if (config.subscriptions.google) {\n result.subscriptions.google = {\n ...result.subscriptions.google,\n ...config.subscriptions.google,\n };\n }\n if (config.subscriptions.githubCopilot) {\n result.subscriptions.githubCopilot = {\n ...result.subscriptions.githubCopilot,\n ...config.subscriptions.githubCopilot,\n };\n }\n }\n\n // Merge models\n if (config.models) {\n result.models = { ...result.models, ...config.models };\n }\n\n // Merge bmad settings\n if (config.bmad) {\n result.bmad = { ...result.bmad, ...config.bmad };\n }\n\n // Merge features\n if (config.features) {\n result.features = { ...result.features, ...config.features };\n }\n\n // Merge mcps\n if (config.mcps) {\n result.mcps = { ...result.mcps, ...config.mcps };\n }\n }\n\n return result;\n}\n","/**\n * OpenCode Athena Plugin\n *\n * The main OpenCode plugin that provides BMAD integration tools and hooks.\n */\n\nimport type { Plugin } from \"@opencode-ai/plugin\";\nimport { createCompactionHook, createSessionHooks, createToolHooks } from \"./hooks/index.js\";\nimport { createTools } from \"./tools/index.js\";\nimport { StoryTracker } from \"./tracker/story-tracker.js\";\nimport { loadAthenaConfig } from \"./utils/config-loader.js\";\nimport { createPluginLogger } from \"./utils/plugin-logger.js\";\n\nconst log = createPluginLogger(\"plugin-init\");\n\n/**\n * OpenCode Athena plugin factory.\n *\n * Provides:\n * - Custom tools for BMAD story management\n * - Session hooks for context tracking\n * - Tool execution hooks for status updates\n * - Compaction hooks to preserve BMAD context\n */\nexport const OpenCodeAthena: Plugin = async (ctx) => {\n const { directory } = ctx;\n\n log.info(\"OpenCode Athena plugin loading\", {\n directory,\n timestamp: new Date().toISOString(),\n });\n\n // Load Athena configuration (project-local takes priority over global)\n const config = await loadAthenaConfig(directory);\n\n // Initialize story tracker for session state persistence\n const tracker = new StoryTracker(directory);\n await tracker.initialize();\n\n // Create tools\n const tools = createTools(ctx, tracker, config);\n\n // Create hooks\n const sessionHooks = createSessionHooks(ctx, tracker, config);\n const toolHooks = createToolHooks(ctx, tracker, config);\n const compactionHook = createCompactionHook(tracker, config);\n\n return {\n // Custom tools for BMAD integration\n tool: tools,\n\n // Session event handlers\n event: sessionHooks,\n\n // Tool execution hooks (stubs for now)\n \"tool.execute.before\": toolHooks.before,\n \"tool.execute.after\": toolHooks.after,\n\n // Compaction hook to preserve BMAD context\n \"experimental.session.compacting\": compactionHook,\n };\n};\n\n// Default export for OpenCode plugin loader\nexport default OpenCodeAthena;\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/plugin/utils/plugin-logger.ts","../src/plugin/utils/notifications.ts","../src/plugin/hooks/session-hooks.ts","../src/plugin/utils/bmad-finder.ts","../src/shared/types.ts","../src/plugin/utils/story-loader.ts","../src/plugin/utils/todo-sync.ts","../src/plugin/hooks/todo-hooks.ts","../src/plugin/hooks/tool-hooks.ts","../src/plugin/hooks/compaction-hook.ts","../src/plugin/utils/story-complexity.ts","../src/plugin/utils/story-parser.ts","../src/plugin/utils/story-decomposer.ts","../src/plugin/tools/analyze-story.ts","../src/shared/constants.ts","../src/plugin/tools/config.ts","../src/plugin/utils/yaml-handler.ts","../src/plugin/tools/decompose-story.ts","../src/plugin/tools/get-context.ts","../src/plugin/utils/context-builder.ts","../src/plugin/utils/story-file-updater.ts","../src/plugin/tools/get-story.ts","../src/plugin/tools/parallel.ts","../src/plugin/utils/oracle-parser.ts","../src/plugin/utils/persona-loader.ts","../src/plugin/utils/story-template.ts","../src/plugin/utils/story-updater.ts","../src/plugin/tools/party-discussion.ts","../src/plugin/tools/review-story.ts","../src/plugin/utils/agent-selector.ts","../src/plugin/tools/story-review-analyze.ts","../src/plugin/utils/response-synthesizer.ts","../src/plugin/tools/story-review-consult.ts","../src/plugin/tools/update-status.ts","../src/plugin/tools/index.ts","../src/plugin/tracker/story-tracker.ts","../src/shared/schemas.ts","../src/plugin/utils/config-loader.ts","../src/plugin/index.ts"],"names":["log","join","existsSync","parseYaml","path","readdir","readFile","result","fs","dirname","tool","lockData","writeFile","resolve","stringifyYaml","normalizeStoryId","updatedContent","progress","basename","nextId","getCategoryPr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AmB,aAAa,CAAA;AAWrC,IAAM,cAAA,GAAyB,OAAO,GAAA,KAAQ;AACnD,EAAA,MAAM,EAAE,WAAU,GAAI,GAAA;AAEtB,EAAAA,KAAAA,CAAI,KAAK,gCAAA,EAAkC;AAAA,IACzC,SAAA;AAAA,IACA,SAAA,EAAA,iBAAW,IAAI,IAAA,EAAK,EAAE,WAAA;AAAY,GACnC,CAAA;AAGD,EAAA,MAAM,MAAA,GAAS,MAAM,gBAAA,CAAiB,SAAS,CAAA;AAG/C,EAAA,MAAM,OAAA,GAAU,IAAI,YAAA,CAAa,SAAS,CAAA;AAC1C,EAAA,MAAM,QAAQ,UAAA,EAAW;AAGzB,EAAA,MAAM,KAAA,GAAQ,WAAA,CAAY,GAAA,EAAK,OAAA,EAAS,MAAM,CAAA;AAG9C,EAAA,MAAM,YAAA,GAAe,kBAAA,CAAmB,GAAA,EAAK,OAAA,EAAS,MAAM,CAAA;AAC5D,EAAA,MAAM,SAAA,GAAY,eAAA,CAAgB,GAAA,EAAK,OAAA,EAAS,MAAM,CAAA;AACtD,EAAA,MAAM,cAAA,GAAiB,oBAAA,CAAqB,OAAA,EAAS,MAAA,EAAQ,SAAS,CAAA;AAEtE,EAAA,OAAO;AAAA;AAAA,IAEL,IAAA,EAAM,KAAA;AAAA;AAAA,IAGN,KAAA,EAAO,YAAA;AAAA;AAAA,IAGP,uBAAuB,SAAA,CAAU,MAAA;AAAA,IACjC,sBAAsB,SAAA,CAAU,KAAA;AAAA;AAAA,IAGhC,iCAAA,EAAmC;AAAA,GACrC;AACF","file":"index.js","sourcesContent":["/**\n * Plugin Logger - File-based logging for OpenCode Athena plugin runtime\n *\n * Follows oh-my-opencode logging pattern:\n * - Logs to temp file: ${TMPDIR}/opencode-athena.log\n * - Optional console output: ATHENA_DEBUG=1\n * - Silent failures to prevent breaking plugin execution\n */\n\nimport { appendFileSync, existsSync, statSync, truncateSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\n\nconst LOG_FILE = join(tmpdir(), \"opencode-athena.log\");\nconst MAX_LOG_SIZE = 5 * 1024 * 1024;\n\ntype LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\nconst LEVEL_PREFIXES: Record<LogLevel, string> = {\n debug: \"[DEBUG]\",\n info: \"[INFO]\",\n warn: \"[WARN]\",\n error: \"[ERROR]\",\n};\n\nfunction shouldLog(level: LogLevel): boolean {\n if (level === \"warn\" || level === \"error\") return true;\n return process.env.ATHENA_DEBUG === \"1\" || process.env.ATHENA_DEBUG === \"true\";\n}\n\nfunction shouldConsoleLog(): boolean {\n return process.env.ATHENA_DEBUG === \"1\" || process.env.ATHENA_DEBUG === \"true\";\n}\n\nfunction formatLogEntry(\n level: LogLevel,\n component: string,\n message: string,\n data?: Record<string, unknown>\n): string {\n const timestamp = new Date().toISOString();\n const prefix = LEVEL_PREFIXES[level];\n const dataStr = data ? ` ${JSON.stringify(data)}` : \"\";\n return `[${timestamp}] ${prefix} [${component}] ${message}${dataStr}\\n`;\n}\n\nfunction rotateLogIfNeeded(): void {\n try {\n if (existsSync(LOG_FILE)) {\n const stats = statSync(LOG_FILE);\n if (stats.size > MAX_LOG_SIZE) {\n truncateSync(LOG_FILE, 0);\n }\n }\n } catch {\n // Silent - logging infrastructure should never break plugin\n }\n}\n\nfunction writeLog(entry: string): void {\n try {\n rotateLogIfNeeded();\n appendFileSync(LOG_FILE, entry);\n } catch {\n // Silent - logging infrastructure should never break plugin\n }\n}\n\n/**\n * Create a scoped logger for a specific component.\n * Public API - docstring required for discoverability.\n *\n * @example\n * const log = createPluginLogger(\"party-discussion\");\n * log.debug(\"Starting session\", { sessionId: \"abc123\" });\n */\nexport function createPluginLogger(component: string) {\n return {\n debug: (message: string, data?: Record<string, unknown>): void => {\n if (!shouldLog(\"debug\")) return;\n const entry = formatLogEntry(\"debug\", component, message, data);\n writeLog(entry);\n if (shouldConsoleLog()) {\n console.debug(`[Athena:${component}] ${message}`, data ?? \"\");\n }\n },\n\n info: (message: string, data?: Record<string, unknown>): void => {\n if (!shouldLog(\"info\")) return;\n const entry = formatLogEntry(\"info\", component, message, data);\n writeLog(entry);\n if (shouldConsoleLog()) {\n console.info(`[Athena:${component}] ${message}`, data ?? \"\");\n }\n },\n\n warn: (message: string, data?: Record<string, unknown>): void => {\n const entry = formatLogEntry(\"warn\", component, message, data);\n writeLog(entry);\n if (shouldConsoleLog()) {\n console.warn(`[Athena:${component}] ${message}`, data ?? \"\");\n }\n },\n\n error: (message: string, data?: Record<string, unknown>): void => {\n const entry = formatLogEntry(\"error\", component, message, data);\n writeLog(entry);\n if (shouldConsoleLog()) {\n console.error(`[Athena:${component}] ${message}`, data ?? \"\");\n }\n },\n };\n}\n\n/** Returns log file path: ${TMPDIR}/opencode-athena.log */\nexport function getLogFilePath(): string {\n return LOG_FILE;\n}\n\n/** Truncates the log file to zero bytes */\nexport function clearLog(): void {\n try {\n if (existsSync(LOG_FILE)) {\n truncateSync(LOG_FILE, 0);\n }\n } catch {\n // Silent - logging infrastructure should never break plugin\n }\n}\n","/**\n * Cross-platform notification utility\n *\n * Sends desktop notifications on macOS/Linux, falls back to console on Windows.\n */\n\nimport { platform } from \"node:os\";\nimport type { PluginInput } from \"@opencode-ai/plugin\";\nimport { createPluginLogger } from \"./plugin-logger.js\";\n\ntype ShellExecutor = PluginInput[\"$\"];\n\nconst log = createPluginLogger(\"notifications\");\n\n/**\n * Send a desktop notification\n *\n * Platform support:\n * - macOS: Uses osascript (built-in)\n * - Linux: Uses notify-send (requires libnotify)\n * - Windows: Falls back to console.log\n *\n * @param message - The notification message\n * @param title - The notification title\n * @param $ - Shell executor from plugin context\n */\nexport async function sendNotification(\n message: string,\n title: string,\n $: ShellExecutor\n): Promise<void> {\n const os = platform();\n\n try {\n if (os === \"darwin\") {\n // macOS - use osascript (built-in)\n await $`osascript -e ${`display notification \"${escapeAppleScript(message)}\" with title \"${escapeAppleScript(title)}\"`}`;\n } else if (os === \"linux\") {\n // Linux - use notify-send (requires libnotify)\n await $`notify-send ${title} ${message}`;\n } else {\n // Windows and others - fall back to console\n logNotification(title, message);\n }\n } catch {\n // Silently fall back to console if notification fails\n logNotification(title, message);\n }\n}\n\n/**\n * Escape special characters for AppleScript strings\n */\nfunction escapeAppleScript(str: string): string {\n return str.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"');\n}\n\n/**\n * Log notification to log file as fallback\n */\nfunction logNotification(title: string, message: string): void {\n log.info(\"Desktop notification fallback\", { title, message });\n}\n","/**\n * Session event hooks\n *\n * Handles session lifecycle events like idle, created, and error.\n */\n\nimport type { PluginInput } from \"@opencode-ai/plugin\";\nimport type { AthenaConfig } from \"../../shared/types.js\";\nimport type { StoryTracker } from \"../tracker/story-tracker.js\";\nimport { sendNotification } from \"../utils/notifications.js\";\nimport { createPluginLogger } from \"../utils/plugin-logger.js\";\n\nconst log = createPluginLogger(\"session-hooks\");\n\n/**\n * Generic event type for session events\n */\ninterface SessionEvent {\n type?: string;\n error?: unknown;\n}\n\n/**\n * Create session event handler\n *\n * Handles:\n * - session.idle: Reminds about in-progress story when session goes idle\n * - session.created: Logs resume of tracked story\n * - session.error: Logs errors during story implementation\n */\nexport function createSessionHooks(ctx: PluginInput, tracker: StoryTracker, config: AthenaConfig) {\n return async ({ event }: { event: SessionEvent }) => {\n // Event type is in event.type for most events\n const eventType = (event as { type?: string }).type;\n\n switch (eventType) {\n case \"session.idle\":\n await handleSessionIdle(ctx, tracker, config);\n break;\n\n case \"session.created\":\n handleSessionCreated(tracker);\n break;\n\n case \"session.error\":\n handleSessionError(event, tracker);\n break;\n }\n };\n}\n\n/**\n * Handle session going idle\n *\n * If a story is in progress, send a reminder notification\n */\nasync function handleSessionIdle(\n ctx: PluginInput,\n tracker: StoryTracker,\n config: AthenaConfig\n): Promise<void> {\n const currentStory = tracker.getCurrentStory();\n\n if (currentStory && currentStory.status === \"in-progress\") {\n // Story is in progress but session went idle\n if (config.features?.notifications) {\n await sendNotification(\n `Story ${currentStory.id} in progress. Remember to update status when complete!`,\n \"OpenCode Athena\",\n ctx.$\n );\n }\n }\n}\n\n/**\n * Handle session creation\n *\n * Log if resuming with an active story\n */\nfunction handleSessionCreated(tracker: StoryTracker): void {\n const currentStory = tracker.getCurrentStory();\n\n if (currentStory) {\n log.info(\"Session created - resuming with story\", {\n storyId: currentStory.id,\n status: currentStory.status,\n });\n }\n}\n\n/**\n * Handle session errors\n *\n * Log errors that occur during story implementation\n */\nfunction handleSessionError(event: SessionEvent, tracker: StoryTracker): void {\n const currentStory = tracker.getCurrentStory();\n\n if (currentStory && event.error) {\n log.error(\"Session error during story implementation\", {\n storyId: currentStory.id,\n error: event.error,\n });\n }\n}\n","import { existsSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport { fdir } from \"fdir\";\nimport { parse as parseYaml } from \"yaml\";\nimport { createPluginLogger } from \"./plugin-logger.js\";\n\nconst log = createPluginLogger(\"bmad-finder\");\n\nconst BMAD_DIR_NAMES = [\"_bmad\", \"docs\", \".bmad\", \"bmad\"] as const;\n\nconst KNOWN_MANIFEST_PATHS = [\n \".bmad/_cfg/agent-manifest.csv\",\n \".bmad/config/agent-manifest.csv\",\n \"bmad/_cfg/agent-manifest.csv\",\n \"_bmad/_config/agent-manifest.csv\",\n] as const;\n\nconst KNOWN_AGENT_DIRS = [\n \"_bmad/bmm/agents\",\n \"src/modules/bmm/agents\",\n \".bmad/bmm/agents\",\n \"bmad/bmm/agents\",\n] as const;\n\nconst MANIFEST_SEARCH_EXCLUDE_DIRS = new Set([\n \"node_modules\",\n \".git\",\n \"dist\",\n \"build\",\n \".next\",\n \"coverage\",\n \".cache\",\n \".turbo\",\n]);\n\nconst manifestCache = new Map<string, string | null>();\nconst agentFilesCache = new Map<string, string[]>();\n\nconst BMAD_V6_DEFAULTS = {\n planningArtifacts: \"docs/project-planning-artifacts\",\n implementationArtifacts: \"docs/implementation-artifacts\",\n projectKnowledge: \"docs\",\n} as const;\n\nconst LEGACY_PATHS = {\n docsDir: \"docs\",\n storiesDir: \"docs/stories\",\n sprintArtifacts: \"docs/sprint-artifacts\",\n} as const;\n\ninterface BmadConfig {\n planning_artifacts?: string;\n implementation_artifacts?: string;\n sprint_artifacts?: string;\n project_knowledge?: string;\n output_folder?: string;\n}\n\ninterface BmadPaths {\n projectRoot: string;\n bmadDir: string | null;\n outputDir: string | null;\n planningDir: string;\n implementationDir: string;\n storiesDir: string;\n sprintStatus: string;\n architecture: string;\n prd: string;\n epics: string;\n structureVersion?: \"v6-alpha\" | \"legacy\" | \"unknown\";\n suggestion?: string;\n}\n\nexport async function findBmadDir(startDir: string): Promise<string | null> {\n let currentDir = startDir;\n const visited = new Set<string>();\n\n while (currentDir && !visited.has(currentDir)) {\n visited.add(currentDir);\n\n for (const dirName of BMAD_DIR_NAMES) {\n const bmadPath = join(currentDir, dirName);\n if (existsSync(bmadPath)) {\n return bmadPath;\n }\n }\n\n const parentDir = dirname(currentDir);\n if (parentDir === currentDir) {\n break;\n }\n\n currentDir = parentDir;\n }\n\n return null;\n}\n\nasync function readBmadConfig(bmadDir: string): Promise<BmadConfig | null> {\n let config: BmadConfig = {};\n\n const bmmConfigPath = join(bmadDir, \"bmm\", \"config.yaml\");\n if (existsSync(bmmConfigPath)) {\n try {\n const content = await readFile(bmmConfigPath, \"utf-8\");\n const bmmConfig = parseYaml(content) as BmadConfig;\n config = { ...config, ...bmmConfig };\n } catch {\n /* continue to try core config */\n }\n }\n\n const coreConfigPath = join(bmadDir, \"core\", \"config.yaml\");\n if (existsSync(coreConfigPath)) {\n try {\n const content = await readFile(coreConfigPath, \"utf-8\");\n const coreConfig = parseYaml(content) as BmadConfig;\n config = { ...config, ...coreConfig };\n } catch {\n /* return whatever we have */\n }\n }\n\n return Object.keys(config).length > 0 ? config : null;\n}\n\n/**\n * Expand BMAD METHOD v6 placeholders in config paths.\n *\n * Strips {project-root}/ prefix to create relative paths that can be\n * joined with projectRoot. This handles the standard BMAD v6 placeholder\n * that is preserved during installation for runtime resolution.\n *\n * @param path - Path that may contain {project-root} placeholder\n * @returns Relative path with placeholder stripped, or undefined if input is undefined\n *\n * @example\n * expandBmadPlaceholder(\"{project-root}/docs/sprint-artifacts\") // → \"docs/sprint-artifacts\"\n * expandBmadPlaceholder(\"docs/sprint-artifacts\") // → \"docs/sprint-artifacts\"\n * expandBmadPlaceholder(undefined) // → undefined\n */\nfunction expandBmadPlaceholder(path: string | undefined): string | undefined {\n if (!path) return undefined;\n return path.replace(/^\\{project-root\\}\\/?/, \"\");\n}\n\n/**\n * Check if a directory contains story files.\n * Looks for files matching story naming patterns: 1-1.md, 2-3.md, story-2-3.md, etc.\n */\nasync function hasStoryFiles(dir: string): Promise<boolean> {\n if (!existsSync(dir)) return false;\n\n try {\n const { readdir } = await import(\"node:fs/promises\");\n const files = await readdir(dir);\n // Match story naming: 1-1.md, 2-3.md, story-2-3.md, etc.\n return files.some((f) => f.endsWith(\".md\") && /^(\\d+-\\d+|story-\\d+-\\d+)/.test(f));\n } catch {\n return false;\n }\n}\n\n/**\n * Detect stories directory by checking nested vs flat structure.\n * Tries nested path first (BMAD v6 standard), then flat structure, then legacy paths.\n */\nasync function detectStoriesDir(baseDir: string, projectRoot: string): Promise<string> {\n const nestedPath = join(baseDir, \"stories\");\n if (await hasStoryFiles(nestedPath)) {\n return nestedPath;\n }\n\n if (await hasStoryFiles(baseDir)) {\n return baseDir;\n }\n\n const legacySprintArtifacts = join(projectRoot, LEGACY_PATHS.sprintArtifacts);\n if (await hasStoryFiles(legacySprintArtifacts)) {\n return legacySprintArtifacts;\n }\n\n const legacyStoriesDir = join(projectRoot, LEGACY_PATHS.storiesDir);\n if (await hasStoryFiles(legacyStoriesDir)) {\n return legacyStoriesDir;\n }\n\n return nestedPath;\n}\n\n/**\n * Generate case variants for a filename.\n * For example, \"PRD.md\" → [\"PRD.md\", \"prd.md\", \"Prd.md\"]\n */\nfunction getCaseVariants(filename: string): string[] {\n const variants = new Set<string>();\n const [name, ext] = filename.split(\".\");\n\n variants.add(filename);\n variants.add(filename.toLowerCase());\n variants.add(filename.toUpperCase());\n\n if (name) {\n const firstCap = name.charAt(0).toUpperCase() + name.slice(1).toLowerCase();\n variants.add(ext ? `${firstCap}.${ext}` : firstCap);\n }\n\n return Array.from(variants);\n}\n\n/**\n * Search for a file with case-insensitive matching.\n * Tries exact match first, then case variants.\n */\nfunction searchForFileWithVariants(\n projectRoot: string,\n filename: string,\n searchPaths: string[]\n): string {\n const variants = getCaseVariants(filename);\n\n for (const searchPath of searchPaths) {\n for (const variant of variants) {\n const fullPath = join(projectRoot, searchPath, variant);\n if (existsSync(fullPath)) {\n return fullPath;\n }\n }\n }\n\n return join(projectRoot, searchPaths[0], filename);\n}\n\ninterface BmadStructureInfo {\n version: \"v6-alpha\" | \"legacy\" | \"none\";\n bmadDir: string | null;\n outputDir: string | null;\n configRead: boolean;\n suggestion?: string;\n}\n\nasync function detectBmadStructure(projectRoot: string): Promise<BmadStructureInfo> {\n const bmadDir = join(projectRoot, \"_bmad\");\n const hasNewBmadDir = existsSync(bmadDir);\n\n if (hasNewBmadDir) {\n const config = await readBmadConfig(bmadDir);\n const outputFolder = expandBmadPlaceholder(config?.output_folder) ?? \"_bmad-output\";\n const outputDir = join(projectRoot, outputFolder);\n const hasOutputDir = existsSync(outputDir);\n\n if (hasOutputDir) {\n return {\n version: \"v6-alpha\",\n bmadDir,\n outputDir,\n configRead: config !== null,\n };\n }\n\n return {\n version: \"none\",\n bmadDir,\n outputDir: null,\n configRead: config !== null,\n suggestion: `Found _bmad/ directory but no ${outputFolder}/. Your BMAD setup may be incomplete. Run 'npx bmad-method@alpha install' to complete setup.`,\n };\n }\n\n const docsDir = join(projectRoot, \"docs\");\n const hasDocsDir = existsSync(docsDir);\n\n if (hasDocsDir) {\n const hasImplementation =\n existsSync(join(docsDir, \"implementation-artifacts\")) ||\n existsSync(join(docsDir, \"sprint-artifacts\"));\n const hasPlanning = existsSync(join(docsDir, \"project-planning-artifacts\"));\n\n if (hasImplementation || hasPlanning) {\n return {\n version: \"legacy\",\n bmadDir: docsDir,\n outputDir: null,\n configRead: false,\n suggestion: `Detected legacy BMAD folder structure (docs/). BMAD METHOD v6 alpha uses _bmad/ and _bmad-output/. To upgrade, run 'npx bmad-method@alpha install' and migrate your artifacts to the new structure.`,\n };\n }\n }\n\n return {\n version: \"none\",\n bmadDir: null,\n outputDir: null,\n configRead: false,\n suggestion: `No BMAD directory found. Run 'npx bmad-method@alpha install' to set up BMAD METHOD in this project.`,\n };\n}\n\nexport async function getBmadPaths(\n startDir: string,\n athenaConfig?: {\n bmad?: {\n paths?: {\n stories?: string | null;\n sprintStatus?: string | null;\n prd?: string | null;\n architecture?: string | null;\n epics?: string | null;\n outputFolder?: string | null;\n };\n };\n }\n): Promise<BmadPaths> {\n const bmadDir = await findBmadDir(startDir);\n const projectRoot = bmadDir ? dirname(bmadDir) : startDir;\n\n let config: BmadConfig | null = null;\n if (bmadDir) {\n config = await readBmadConfig(bmadDir);\n }\n\n const structure = await detectBmadStructure(projectRoot);\n\n const outputFolder =\n athenaConfig?.bmad?.paths?.outputFolder ??\n expandBmadPlaceholder(config?.output_folder) ??\n \"_bmad-output\";\n const outputDir = structure.outputDir ?? join(projectRoot, outputFolder);\n\n const planningDir = join(\n projectRoot,\n expandBmadPlaceholder(config?.planning_artifacts) ??\n (structure.version === \"v6-alpha\"\n ? join(outputFolder, \"planning-artifacts\")\n : BMAD_V6_DEFAULTS.planningArtifacts)\n );\n\n const implementationDir = join(\n projectRoot,\n expandBmadPlaceholder(config?.implementation_artifacts) ??\n expandBmadPlaceholder(config?.sprint_artifacts) ??\n (structure.version === \"v6-alpha\"\n ? join(outputFolder, \"implementation-artifacts\")\n : BMAD_V6_DEFAULTS.implementationArtifacts)\n );\n\n const storiesDir = athenaConfig?.bmad?.paths?.stories\n ? join(projectRoot, athenaConfig.bmad.paths.stories)\n : await detectStoriesDir(implementationDir, projectRoot);\n\n const sprintStatusSearchPaths = [\n expandBmadPlaceholder(config?.implementation_artifacts) ||\n BMAD_V6_DEFAULTS.implementationArtifacts,\n expandBmadPlaceholder(config?.sprint_artifacts) || \"docs/sprint-artifacts\",\n LEGACY_PATHS.sprintArtifacts,\n LEGACY_PATHS.docsDir,\n ];\n const sprintStatus = athenaConfig?.bmad?.paths?.sprintStatus\n ? join(projectRoot, athenaConfig.bmad.paths.sprintStatus)\n : searchForFileWithVariants(projectRoot, \"sprint-status.yaml\", sprintStatusSearchPaths);\n\n const architectureSearchPaths = [\n expandBmadPlaceholder(config?.planning_artifacts) || BMAD_V6_DEFAULTS.planningArtifacts,\n LEGACY_PATHS.docsDir,\n ];\n const architecture = athenaConfig?.bmad?.paths?.architecture\n ? join(projectRoot, athenaConfig.bmad.paths.architecture)\n : searchForFileWithVariants(projectRoot, \"architecture.md\", architectureSearchPaths);\n\n const prdSearchPaths = [\n expandBmadPlaceholder(config?.planning_artifacts) || BMAD_V6_DEFAULTS.planningArtifacts,\n LEGACY_PATHS.docsDir,\n ];\n const prd = athenaConfig?.bmad?.paths?.prd\n ? join(projectRoot, athenaConfig.bmad.paths.prd)\n : searchForFileWithVariants(projectRoot, \"PRD.md\", prdSearchPaths);\n\n const epicsSearchPaths = [\n expandBmadPlaceholder(config?.planning_artifacts) || BMAD_V6_DEFAULTS.planningArtifacts,\n LEGACY_PATHS.docsDir,\n ];\n const epics = athenaConfig?.bmad?.paths?.epics\n ? join(projectRoot, athenaConfig.bmad.paths.epics)\n : searchForFileWithVariants(projectRoot, \"epics.md\", epicsSearchPaths);\n\n return {\n projectRoot,\n bmadDir,\n outputDir,\n planningDir,\n implementationDir,\n storiesDir,\n sprintStatus,\n architecture,\n prd,\n epics,\n structureVersion: structure.version === \"none\" ? \"unknown\" : structure.version,\n suggestion: structure.suggestion,\n };\n}\n\nexport async function findManifest(projectRoot: string): Promise<string | null> {\n const cached = manifestCache.get(projectRoot);\n if (cached !== undefined) {\n return cached;\n }\n\n for (const knownPath of KNOWN_MANIFEST_PATHS) {\n const fullPath = join(projectRoot, knownPath);\n if (existsSync(fullPath)) {\n manifestCache.set(projectRoot, fullPath);\n return fullPath;\n }\n }\n\n const bmadDir = await findBmadDir(projectRoot);\n if (bmadDir) {\n try {\n const files = await new fdir()\n .withMaxDepth(3)\n .withBasePath()\n .exclude((dirName) => MANIFEST_SEARCH_EXCLUDE_DIRS.has(dirName))\n .filter((path) => path.endsWith(\"agent-manifest.csv\"))\n .crawl(bmadDir)\n .withPromise();\n\n if (files.length > 0) {\n manifestCache.set(projectRoot, files[0]);\n return files[0];\n }\n } catch (error) {\n log.warn(\"Failed to search for manifest in BMAD directory\", {\n bmadDir,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n try {\n const projectFiles = await new fdir()\n .withMaxDepth(5)\n .withBasePath()\n .exclude((dirName) => MANIFEST_SEARCH_EXCLUDE_DIRS.has(dirName))\n .filter((path) => path.endsWith(\"agent-manifest.csv\"))\n .crawl(projectRoot)\n .withPromise();\n\n const result = projectFiles.length > 0 ? projectFiles[0] : null;\n manifestCache.set(projectRoot, result);\n return result;\n } catch (error) {\n log.warn(\"Failed to search for manifest in project root\", {\n projectRoot,\n error: error instanceof Error ? error.message : String(error),\n });\n manifestCache.set(projectRoot, null);\n return null;\n }\n}\n\nexport function clearManifestCache(): void {\n manifestCache.clear();\n}\n\nexport async function findAgentFiles(projectRoot: string): Promise<string[]> {\n const cached = agentFilesCache.get(projectRoot);\n if (cached !== undefined) {\n return cached;\n }\n\n for (const knownDir of KNOWN_AGENT_DIRS) {\n const fullPath = join(projectRoot, knownDir);\n if (existsSync(fullPath)) {\n try {\n const files = await new fdir()\n .withBasePath()\n .filter((path) => path.endsWith(\".agent.yaml\"))\n .crawl(fullPath)\n .withPromise();\n\n if (files.length > 0) {\n agentFilesCache.set(projectRoot, files);\n return files;\n }\n } catch (error) {\n log.warn(\"Failed to search for agent files in known directory\", {\n directory: fullPath,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n }\n\n const bmadDir = await findBmadDir(projectRoot);\n if (bmadDir) {\n try {\n const files = await new fdir()\n .withMaxDepth(5)\n .withBasePath()\n .exclude((dirName) => MANIFEST_SEARCH_EXCLUDE_DIRS.has(dirName))\n .filter((path) => path.endsWith(\".agent.yaml\"))\n .crawl(bmadDir)\n .withPromise();\n\n if (files.length > 0) {\n agentFilesCache.set(projectRoot, files);\n return files;\n }\n } catch (error) {\n log.warn(\"Failed to search for agent files in BMAD directory\", {\n bmadDir,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n try {\n const projectFiles = await new fdir()\n .withMaxDepth(6)\n .withBasePath()\n .exclude((dirName) => MANIFEST_SEARCH_EXCLUDE_DIRS.has(dirName))\n .filter((path) => path.endsWith(\".agent.yaml\") && path.includes(\"/agents/\"))\n .crawl(projectRoot)\n .withPromise();\n\n agentFilesCache.set(projectRoot, projectFiles);\n return projectFiles;\n } catch (error) {\n log.warn(\"Failed to search for agent files in project root\", {\n projectRoot,\n error: error instanceof Error ? error.message : String(error),\n });\n agentFilesCache.set(projectRoot, []);\n return [];\n }\n}\n\nexport function clearAgentFilesCache(): void {\n agentFilesCache.clear();\n}\n","/**\n * Shared TypeScript type definitions for OpenCode Athena\n */\n\n// ============================================================================\n// CLI Types\n// ============================================================================\n\n/**\n * Options passed to the install command\n */\nexport interface InstallOptions {\n preset: string;\n yes: boolean;\n advanced: boolean;\n global: boolean;\n local: boolean;\n reconfigure?: boolean;\n}\n\n/**\n * Options passed to the upgrade command\n */\nexport interface UpgradeOptions {\n check: boolean;\n yes: boolean;\n}\n\n/**\n * Options passed to the doctor command\n */\nexport interface DoctorOptions {\n fix: boolean;\n}\n\n/**\n * Options passed to the uninstall command\n */\nexport interface UninstallOptions {\n keepConfig: boolean;\n keepDeps: boolean;\n}\n\n/**\n * Subscription information gathered during install\n */\nexport interface SubscriptionAnswers {\n hasClaude: boolean;\n claudeTier: \"max5x\" | \"max20x\" | \"pro\" | \"none\";\n hasOpenAI: boolean;\n hasGoogle: boolean;\n googleAuth: \"antigravity\" | \"personal\" | \"api\" | \"none\";\n hasGitHubCopilot: boolean;\n copilotPlan: \"free\" | \"pro\" | \"pro-plus\" | \"business\" | \"enterprise\" | \"none\";\n copilotEnabledModels?: string[];\n}\n\n/**\n * Methodology preferences gathered during install\n */\nexport interface MethodologyAnswers {\n defaultTrack: \"quick-flow\" | \"bmad-method\" | \"enterprise\";\n autoStatusUpdate: boolean;\n}\n\n/**\n * Feature selections gathered during install\n */\nexport interface FeatureAnswers {\n enabledFeatures: string[];\n mcps: string[];\n}\n\n/**\n * Advanced options gathered during install\n */\nexport interface AdvancedAnswers {\n parallelStoryLimit?: number;\n experimental?: string[];\n autoFallback?: boolean;\n}\n\n/**\n * Available model choices by provider\n */\nexport type LLMProvider = \"anthropic\" | \"openai\" | \"google\" | \"github-copilot\";\n\n/**\n * Model definition\n */\nexport interface ModelChoice {\n id: string;\n name: string;\n provider: LLMProvider;\n description?: string;\n}\n\n/**\n * Custom model definition for user-added models\n */\nexport interface CustomModelDefinition {\n id: string;\n name: string;\n provider: LLMProvider;\n description?: string;\n capabilities?: {\n thinking?: boolean;\n contextWindow?: number;\n supportsTemperature?: boolean;\n };\n}\n\n/**\n * Agent roles that require model assignment\n */\nexport type AgentRole =\n | \"sisyphus\"\n | \"oracle\"\n | \"librarian\"\n | \"frontend\"\n | \"documentWriter\"\n | \"multimodalLooker\"\n | \"explore\";\n\n/**\n * Thinking level for reasoning-capable models\n */\nexport type ThinkingLevel = \"off\" | \"low\" | \"medium\" | \"high\";\n\n/**\n * Agent-specific settings for temperature and thinking level\n */\nexport interface AgentSettings {\n temperature?: number; // 0.0 - 1.0\n thinkingLevel?: ThinkingLevel;\n}\n\n/**\n * Model assignments for each agent role\n */\nexport interface ModelAnswers {\n sisyphus: string;\n oracle: string;\n librarian: string;\n frontend?: string;\n documentWriter?: string;\n multimodalLooker?: string;\n explore?: string;\n settings?: {\n sisyphus?: AgentSettings;\n oracle?: AgentSettings;\n librarian?: AgentSettings;\n frontend?: AgentSettings;\n documentWriter?: AgentSettings;\n multimodalLooker?: AgentSettings;\n explore?: AgentSettings;\n overrides?: Record<string, AgentSettings>;\n };\n custom?: CustomModelDefinition[];\n}\n\n/**\n * All answers from the install wizard\n */\nexport interface InstallAnswers {\n subscriptions: SubscriptionAnswers;\n models: ModelAnswers;\n methodology: MethodologyAnswers;\n features: FeatureAnswers;\n advanced: AdvancedAnswers;\n installLocation: \"global\" | \"local\";\n}\n\n/**\n * A file to be generated/written by the installer\n */\nexport interface GeneratedFile {\n path: string;\n content: string;\n exists: boolean;\n}\n\n// ============================================================================\n// Configuration Types\n// ============================================================================\n\nexport interface AgentRouting {\n requiresThinking?: boolean;\n preferProvider?: LLMProvider;\n}\n\nexport interface RoutingConfig {\n providerPriority: LLMProvider[];\n modelFamilyPriority: {\n claude?: LLMProvider[];\n gpt?: LLMProvider[];\n gemini?: LLMProvider[];\n };\n agentOverrides: {\n sisyphus?: AgentRouting;\n oracle?: AgentRouting;\n librarian?: AgentRouting;\n frontend?: AgentRouting;\n documentWriter?: AgentRouting;\n multimodalLooker?: AgentRouting;\n };\n fallbackBehavior: {\n autoFallback: boolean;\n retryPeriodMs: number;\n notifyOnRateLimit: boolean;\n };\n}\n\n/**\n * Athena configuration file structure\n */\nexport interface AthenaConfig {\n $schema?: string;\n version: string;\n subscriptions: {\n claude: {\n enabled: boolean;\n tier: \"max5x\" | \"max20x\" | \"pro\" | \"none\";\n };\n openai: {\n enabled: boolean;\n };\n google: {\n enabled: boolean;\n authMethod: \"antigravity\" | \"personal\" | \"api\" | \"none\";\n };\n githubCopilot: {\n enabled: boolean;\n plan: \"free\" | \"pro\" | \"pro-plus\" | \"business\" | \"enterprise\" | \"none\";\n enabledModels?: string[];\n };\n };\n models: {\n sisyphus: string;\n oracle: string;\n librarian: string;\n frontend?: string;\n documentWriter?: string;\n multimodalLooker?: string;\n settings?: {\n sisyphus?: AgentSettings;\n oracle?: AgentSettings;\n librarian?: AgentSettings;\n frontend?: AgentSettings;\n documentWriter?: AgentSettings;\n multimodalLooker?: AgentSettings;\n explore?: AgentSettings;\n overrides?: Record<string, AgentSettings>;\n };\n custom?: CustomModelDefinition[];\n };\n bmad: {\n defaultTrack: \"quick-flow\" | \"bmad-method\" | \"enterprise\";\n autoStatusUpdate: boolean;\n parallelStoryLimit: number;\n paths?: {\n stories?: string | null;\n sprintStatus?: string | null;\n prd?: string | null;\n architecture?: string | null;\n epics?: string | null;\n outputFolder?: string | null;\n };\n };\n features: {\n bmadBridge: boolean;\n autoStatus: boolean;\n parallelExecution: boolean;\n notifications: boolean;\n contextMonitor: boolean;\n commentChecker: boolean;\n lspTools: boolean;\n autoGitOperations: boolean;\n todoSync: boolean;\n };\n mcps: {\n context7: boolean;\n exa: boolean;\n grepApp: boolean;\n };\n routing: RoutingConfig;\n}\n\n/**\n * Prerequisites check result\n */\nexport interface Prerequisites {\n opencode: {\n installed: boolean;\n version?: string;\n compatible: boolean;\n };\n athena: {\n installed: boolean;\n version?: string;\n };\n node: {\n installed: boolean;\n version?: string;\n compatible: boolean;\n };\n}\n\n// ============================================================================\n// Plugin Types\n// ============================================================================\n\n// ============================================================================\n// BMAD v6 Status Types (Flat Map Structure)\n// ============================================================================\n\n/**\n * BMAD v6 story status values (hyphenated)\n * Flow: backlog → ready-for-dev → in-progress → review → done\n * \"blocked\" is an Athena extension for tracking external dependencies\n */\nexport type BmadStoryStatus =\n | \"backlog\"\n | \"ready-for-dev\"\n | \"in-progress\"\n | \"review\"\n | \"done\"\n | \"blocked\"; // Athena extension\n\n/**\n * BMAD v6 epic status values\n * Flow: backlog → in-progress → done\n */\nexport type BmadEpicStatus = \"backlog\" | \"in-progress\" | \"done\";\n\n/**\n * BMAD v6 retrospective status values\n */\nexport type BmadRetroStatus = \"optional\" | \"done\";\n\n/**\n * All possible status values in development_status map\n */\nexport type BmadDevelopmentStatus = BmadStoryStatus | BmadEpicStatus | BmadRetroStatus;\n\n/**\n * BMAD v6 sprint status structure (flat map format)\n *\n * Example:\n * ```yaml\n * generated: 2025-12-28T10:30:00Z\n * project: My Project\n * current_story: 2-3 # Athena extension\n *\n * development_status:\n * epic-1: in-progress\n * 1-1-user-auth: done\n * 1-2-api-setup: ready-for-dev\n * epic-1-retrospective: optional\n * ```\n */\nexport interface BmadSprintStatus {\n /** ISO timestamp when file was generated */\n generated?: string;\n /** Project name */\n project?: string;\n /** Project key for tracking system integration */\n project_key?: string;\n /** Tracking system type (e.g., \"file-system\") */\n tracking_system?: string;\n /** Path to story files */\n story_location?: string;\n\n // Athena extensions\n /** Currently active story (Athena extension for explicit tracking) */\n current_story?: string | null;\n /** Last modified timestamp (Athena extension) */\n last_modified?: string;\n\n /**\n * Flat map of all development items and their statuses.\n * Keys can be:\n * - Epic: \"epic-{num}\" (e.g., \"epic-1\")\n * - Story: \"{epic}-{story}\" or \"{epic}-{story}-{title}\" (e.g., \"2-3\" or \"2-3-user-auth\")\n * - Retrospective: \"epic-{num}-retrospective\" (e.g., \"epic-1-retrospective\")\n */\n development_status: Record<string, BmadDevelopmentStatus>;\n}\n\n/**\n * Parsed story key information\n */\nexport interface ParsedStoryKey {\n /** Epic number (e.g., \"2\") */\n epicNum: string;\n /** Story number (e.g., \"3\") */\n storyNum: string;\n /** Title slug if present (e.g., \"user-authentication\") */\n titleSlug?: string;\n /** Full original key (e.g., \"2-3-user-authentication\") */\n fullKey: string;\n /** Normalized ID without title (e.g., \"2-3\") */\n normalizedId: string;\n}\n\n/**\n * Parsed epic key information\n */\nexport interface ParsedEpicKey {\n /** Epic number (e.g., \"1\") */\n epicNum: string;\n /** Full original key (e.g., \"epic-1\") */\n fullKey: string;\n}\n\n/**\n * Parsed retrospective key information\n */\nexport interface ParsedRetroKey {\n /** Epic number (e.g., \"1\") */\n epicNum: string;\n /** Full original key (e.g., \"epic-1-retrospective\") */\n fullKey: string;\n}\n\n/**\n * Type of key in development_status map\n */\nexport type DevelopmentKeyType = \"story\" | \"epic\" | \"retrospective\" | \"unknown\";\n\n/**\n * Result of parsing a development_status key\n */\nexport type ParsedDevelopmentKey =\n | { type: \"story\"; parsed: ParsedStoryKey }\n | { type: \"epic\"; parsed: ParsedEpicKey }\n | { type: \"retrospective\"; parsed: ParsedRetroKey }\n | { type: \"unknown\"; key: string };\n\n// ============================================================================\n// Legacy Types (for backward compatibility - deprecated)\n// ============================================================================\n\n/**\n * @deprecated Use BmadStoryStatus instead. This type uses underscore format\n * which doesn't match BMAD v6's hyphenated format.\n */\nexport type StoryStatus = \"pending\" | \"in_progress\" | \"completed\" | \"blocked\" | \"needs_review\";\n\nexport type TrackerStatus = BmadStoryStatus | \"loading\";\n\n/**\n * Tracked story state\n */\nexport interface TrackedStory {\n id: string;\n content: string;\n status: TrackerStatus;\n startedAt: string;\n completedAt?: string;\n}\n\n/**\n * @deprecated Use BmadSprintStatus instead. This interface uses array-based\n * structure which doesn't match BMAD v6's flat map format.\n */\nexport interface SprintStatus {\n sprint_number?: number;\n current_epic?: string;\n current_story?: string | null;\n completed_stories: string[];\n pending_stories: string[];\n in_progress_stories: string[];\n blocked_stories: string[];\n stories_needing_review?: string[];\n story_updates?: Record<\n string,\n {\n status: StoryStatus;\n updated_at: string;\n notes?: string;\n completion_summary?: string;\n }\n >;\n last_modified?: string;\n}\n\n/**\n * Story tracker persistent state\n */\nexport interface TrackerState {\n currentStory: TrackedStory | null;\n sessionId: string;\n projectDir: string;\n history: Array<{\n storyId: string;\n status: string;\n timestamp: string;\n }>;\n currentTodos?: OpenCodeTodo[];\n}\n\n// ============================================================================\n// Tool Result Types\n// ============================================================================\n\n/**\n * Result from athena_get_story tool\n */\nexport interface GetStoryResult {\n storyId?: string;\n story?: string;\n architecture?: string;\n prd?: string;\n sprint?: {\n currentEpic: string;\n completedStories: number;\n pendingStories: number;\n blockedStories: number;\n };\n instructions?: string;\n error?: string;\n suggestion?: string;\n sprintProgress?: {\n completed: number;\n total: number;\n };\n}\n\n/**\n * Result from athena_update_status tool\n */\nexport interface UpdateStatusResult {\n success?: boolean;\n storyId?: string;\n newStatus?: StoryStatus;\n updatedAt?: string;\n sprintProgress?: {\n completed: number;\n inProgress: number;\n pending: number;\n blocked: number;\n total: number;\n percentComplete: number;\n };\n nextStory?: string | null;\n error?: string;\n}\n\n// ============================================================================\n// Party Review Types\n// ============================================================================\n\n/**\n * Scope of a party review\n */\nexport type ReviewScope = \"epic\" | \"story\";\n\n/**\n * Severity level of a review finding\n */\nexport type FindingSeverity = \"high\" | \"medium\" | \"low\";\n\n/**\n * Category of a review finding\n */\nexport type FindingCategory = \"security\" | \"logic\" | \"bestPractices\" | \"performance\";\n\n/**\n * User decision on a finding\n */\nexport type ReviewDecision = \"accept\" | \"defer\" | \"reject\" | \"pending\";\n\n/**\n * A single party review finding\n */\nexport interface PartyReviewFinding {\n id: string;\n category: FindingCategory;\n severity: FindingSeverity;\n title: string;\n description: string;\n impact: string;\n suggestion: string;\n storyId?: string;\n fileReference?: string;\n lineNumber?: number;\n decision?: ReviewDecision;\n decisionReason?: string;\n deferredTo?: string;\n}\n\n/**\n * Findings grouped by story\n */\nexport interface StoryFindings {\n storyId: string;\n title: string;\n filePath: string;\n findings: {\n security: PartyReviewFinding[];\n logic: PartyReviewFinding[];\n bestPractices: PartyReviewFinding[];\n performance: PartyReviewFinding[];\n };\n summary: {\n total: number;\n high: number;\n medium: number;\n low: number;\n };\n}\n\n/**\n * Cross-story issues found in epic reviews\n */\nexport interface CrossStoryIssue {\n id: string;\n category: FindingCategory;\n severity: FindingSeverity;\n title: string;\n description: string;\n affectedStories: string[];\n suggestion: string;\n decision?: ReviewDecision;\n decisionReason?: string;\n}\n\n/**\n * Model complexity assessment result\n */\nexport interface StoryComplexity {\n isSimple: boolean;\n reason: string;\n recommendedModel: string;\n factors: {\n acceptanceCriteriaCount: number;\n hasSecurityConcerns: boolean;\n hasDataModelChanges: boolean;\n hasApiChanges: boolean;\n isCrudOnly: boolean;\n };\n}\n\n/**\n * Reference to another review document\n */\nexport interface ReviewDocumentReference {\n type: \"epic\" | \"focused\";\n filePath: string;\n date: string;\n findingsCount: number;\n acceptedCount: number;\n deferredCount: number;\n rejectedCount: number;\n}\n\n/**\n * Complete party review document structure\n */\nexport interface PartyReviewDocument {\n scope: ReviewScope;\n identifier: string;\n date: string;\n reviewer: string;\n epicNumber?: string;\n storyId?: string;\n storiesReviewed?: string[];\n relatedReviews?: ReviewDocumentReference[];\n summary: {\n totalIssues: number;\n highSeverity: number;\n mediumSeverity: number;\n lowSeverity: number;\n recommendation: string;\n };\n storyFindings?: StoryFindings[];\n crossStoryIssues?: CrossStoryIssue[];\n previousFindings?: {\n accepted: PartyReviewFinding[];\n deferred: PartyReviewFinding[];\n rejected: PartyReviewFinding[];\n };\n newFindings?: {\n security: PartyReviewFinding[];\n logic: PartyReviewFinding[];\n bestPractices: PartyReviewFinding[];\n performance: PartyReviewFinding[];\n };\n oracleAnalysis?: string;\n}\n\n/**\n * Result from athena_review_story tool (prepares context for Oracle invocation)\n */\nexport interface ReviewStoryResult {\n success: boolean;\n scope: ReviewScope;\n identifier: string;\n documentPath?: string;\n document?: PartyReviewDocument;\n error?: string;\n suggestion?: string;\n // Context prepared for command file to invoke Oracle\n oraclePrompt?: string;\n storiesContent?: Array<{ id: string; content: string | null }>;\n architectureContent?: string;\n existingReviews?: ReviewDocumentReference[];\n complexity?: StoryComplexity;\n selectedModel?: string;\n reviewsDir?: string;\n}\n\n/**\n * Argument for applying review decisions\n */\nexport interface ApplyReviewDecisionsArgs {\n documentPath: string;\n decisions: Record<string, ReviewDecision>;\n decisionReasons?: Record<string, string>;\n deferredTargets?: Record<string, string>;\n}\n\n/**\n * Result from applying review decisions\n */\nexport interface ApplyReviewDecisionsResult {\n success: boolean;\n updatedStories: string[];\n updatedDocuments: string[];\n summary: {\n accepted: number;\n deferred: number;\n rejected: number;\n };\n error?: string;\n}\n\n/**\n * Action taken on a story during decision application\n */\nexport type StoryUpdateAction = \"updated\" | \"created\" | \"appended\";\n\n/**\n * Parsed defer target from user input\n */\nexport interface ParsedDeferTarget {\n /** The target type */\n type: \"exact\" | \"new-end\" | \"new-after\" | \"new-before\" | \"append-existing\";\n /** The story ID (existing or to be created) */\n storyId: string;\n /** For sub-numbering: the reference story ID */\n referenceStoryId?: string;\n /** Original user input */\n originalInput: string;\n}\n\n/**\n * Result of applying updates to a single story\n */\nexport interface AppliedStoryUpdate {\n /** Story ID (e.g., \"4.1\" or \"4.2a\") */\n storyId: string;\n /** Full path to the story file */\n filePath: string;\n /** What action was taken */\n action: StoryUpdateAction;\n /** Acceptance criteria added (for created/updated) */\n addedCriteria: string[];\n /** Implementation notes added */\n addedNotes: string[];\n /** Whether the operation succeeded */\n success: boolean;\n /** Error message if failed */\n error?: string;\n /** For created stories: the defer target that triggered creation */\n deferTarget?: ParsedDeferTarget;\n}\n\n/**\n * Complete result from applying all decisions\n */\nexport interface ApplyDecisionsResult {\n /** Overall success (true even if some individual updates failed) */\n success: boolean;\n /** Stories that were updated with new criteria/notes */\n storiesUpdated: AppliedStoryUpdate[];\n /** New stories that were created for deferred findings */\n storiesCreated: AppliedStoryUpdate[];\n /** Existing stories that had findings appended */\n storiesAppended: AppliedStoryUpdate[];\n /** Whether the review document was updated */\n reviewDocumentUpdated: boolean;\n /** Path to the decisions-applied.md summary document */\n decisionsAppliedDocument?: string;\n /** Summary counts */\n summary: {\n accepted: number;\n deferred: number;\n rejected: number;\n storiesModified: number;\n storiesCreated: number;\n };\n /** Warnings (e.g., vague defer targets) */\n warnings?: string[];\n /** Error if complete failure */\n error?: string;\n}\n\n// ============================================================================\n// Enhanced Party Review Types (3-Phase Architecture)\n// ============================================================================\n\n/**\n * BMAD agent types that can participate in party review\n */\nexport type BmadAgentType =\n | \"architect\"\n | \"dev\"\n | \"tea\"\n | \"pm\"\n | \"analyst\"\n | \"ux-designer\"\n | \"tech-writer\"\n | \"sm\";\n\n/**\n * BMAD agent persona details\n */\nexport interface BmadAgentPersona {\n type: BmadAgentType;\n name: string;\n title: string;\n expertise: string[];\n perspective: string;\n}\n\n/**\n * Mapping of BMAD agents with their personas\n */\nexport const BMAD_AGENTS: Record<BmadAgentType, BmadAgentPersona> = {\n architect: {\n type: \"architect\",\n name: \"Winston\",\n title: \"Software Architect\",\n expertise: [\"system design\", \"security architecture\", \"scalability\", \"technical debt\"],\n perspective: \"architecture and system design\",\n },\n dev: {\n type: \"dev\",\n name: \"Amelia\",\n title: \"Senior Developer\",\n expertise: [\"implementation\", \"code quality\", \"debugging\", \"performance optimization\"],\n perspective: \"implementation feasibility and code quality\",\n },\n tea: {\n type: \"tea\",\n name: \"Murat\",\n title: \"Test Engineer\",\n expertise: [\"testing strategy\", \"edge cases\", \"test automation\", \"quality assurance\"],\n perspective: \"testability and quality assurance\",\n },\n pm: {\n type: \"pm\",\n name: \"John\",\n title: \"Product Manager\",\n expertise: [\"requirements\", \"stakeholder needs\", \"prioritization\", \"business value\"],\n perspective: \"business impact and stakeholder value\",\n },\n analyst: {\n type: \"analyst\",\n name: \"Mary\",\n title: \"Business Analyst\",\n expertise: [\"requirements analysis\", \"user stories\", \"acceptance criteria\", \"edge cases\"],\n perspective: \"requirements completeness and clarity\",\n },\n \"ux-designer\": {\n type: \"ux-designer\",\n name: \"Sally\",\n title: \"UX Designer\",\n expertise: [\"user experience\", \"accessibility\", \"usability\", \"user flows\"],\n perspective: \"user experience and accessibility\",\n },\n \"tech-writer\": {\n type: \"tech-writer\",\n name: \"Paige\",\n title: \"Technical Writer\",\n expertise: [\"documentation\", \"API docs\", \"user guides\", \"clarity\"],\n perspective: \"documentation and clarity\",\n },\n sm: {\n type: \"sm\",\n name: \"Bob\",\n title: \"Scrum Master\",\n expertise: [\"process\", \"team dynamics\", \"sprint planning\", \"blockers\"],\n perspective: \"process and team coordination\",\n },\n};\n\n/**\n * Agent recommendation with reasoning\n */\nexport interface AgentRecommendation {\n agent: BmadAgentType;\n reason: string;\n relevantFindings: string[];\n priority: \"required\" | \"recommended\" | \"optional\";\n}\n\n/**\n * Cross-story pattern identified by an agent\n */\nexport interface CrossStoryPattern {\n id: string;\n pattern: string;\n affectedStories: string[];\n severity: FindingSeverity;\n recommendation: string;\n}\n\n/**\n * Single agent's analysis output (Phase 2)\n */\nexport interface AgentAnalysis {\n agent: BmadAgentType;\n agentName: string;\n analyzedAt: string;\n storiesAnalyzed: string[];\n perspective: string;\n findings: {\n agreements: string[];\n concerns: string[];\n suggestions: string[];\n };\n crossStoryPatterns: CrossStoryPattern[];\n prioritizedIssues: Array<{\n findingId: string;\n agentPriority: \"critical\" | \"important\" | \"minor\";\n rationale: string;\n }>;\n summary: string;\n}\n\n/**\n * Phase 1 context: Prepared by tool for Oracle invocation (before Oracle runs)\n */\nexport type Phase1Context = Phase1ContextSuccess | Phase1ContextError;\n\nexport interface Phase1ContextSuccess {\n success: true;\n scope: ReviewScope;\n identifier: string;\n reviewsDir: string;\n storiesContent: Array<{ id: string; content: string | null }>;\n architectureContent: string;\n oraclePrompt: string;\n selectedModel: string;\n complexity?: StoryComplexity;\n existingReviews?: ReviewDocumentReference[];\n}\n\nexport interface Phase1ContextError {\n success: false;\n scope: ReviewScope;\n identifier: string;\n error: string;\n suggestion?: string;\n}\n\n/**\n * Phase 1 summary: Minimal result returned to agent after Oracle analysis.\n * Large data (oracleAnalysis, storiesContent) is saved to file, not passed between tools.\n */\nexport interface Phase1Summary {\n success: boolean;\n scope: ReviewScope;\n identifier: string;\n error?: string;\n suggestion?: string;\n reviewFolderPath?: string;\n findings?: {\n total: number;\n high: number;\n medium: number;\n low: number;\n byCategory: Record<FindingCategory, number>;\n };\n recommendedAgents?: AgentRecommendation[];\n summary?: string;\n}\n\n/**\n * Phase 1 full data: Complete data saved to analysis.json file.\n * Includes large fields that should not be passed between tool calls.\n */\nexport interface Phase1FullData extends Phase1Summary {\n storiesContent?: Array<{ id: string; title?: string; content: string | null }>;\n architectureContent?: string;\n oracleAnalysis?: string;\n}\n\n/**\n * @deprecated Use Phase1Summary for tool returns, Phase1FullData for file storage\n */\nexport type Phase1Result = Phase1FullData;\n\n/**\n * Phase 2 result: Aggregated agent analyses\n */\nexport interface Phase2Result {\n success: boolean;\n identifier: string;\n agentAnalyses: AgentAnalysis[];\n consensusPoints: string[];\n debatePoints: Array<{\n topic: string;\n positions: Array<{\n agent: BmadAgentType;\n position: string;\n }>;\n }>;\n aggregatedPriorities: Array<{\n findingId: string;\n votes: Record<BmadAgentType, \"critical\" | \"important\" | \"minor\" | \"not-rated\">;\n consensus: \"strong\" | \"moderate\" | \"disputed\";\n }>;\n error?: string;\n}\n\n/**\n * Discussion context for Phase 3 party mode\n */\nexport interface DiscussionContext {\n scope: ReviewScope;\n identifier: string;\n epicNumber?: string;\n storyIds: string[];\n phase1Summary: {\n totalFindings: number;\n highSeverity: number;\n reviewDocumentPath: string;\n };\n agentAnalyses: AgentAnalysis[];\n agendaItems: Array<{\n id: string;\n topic: string;\n type: \"consensus\" | \"debate\" | \"decision-needed\";\n relatedFindings: string[];\n agentPositions?: Record<BmadAgentType, string>;\n }>;\n preloadedContext: string;\n}\n\n/**\n * Final review session result\n */\nexport interface ReviewSessionResult {\n success: boolean;\n identifier: string;\n decisions: Record<string, ReviewDecision>;\n decisionSummary: {\n accepted: number;\n deferred: number;\n rejected: number;\n discussed: number;\n };\n storyUpdates: Array<{\n storyId: string;\n addedCriteria: string[];\n modifiedCriteria: string[];\n }>;\n actionItems: Array<{\n description: string;\n assignedTo?: BmadAgentType;\n deferredToStory?: string;\n }>;\n sessionNotes: string;\n}\n\n// ============================================================================\n// Phase 3: Party Discussion Types\n// ============================================================================\n\n/**\n * Extended BMAD agent persona with full details from manifest\n */\nexport interface BmadAgentFullPersona extends BmadAgentPersona {\n icon: string;\n identity: string;\n communicationStyle: string;\n principles: string[];\n module?: string;\n}\n\n/**\n * Default full personas (fallback when BMAD manifest not available)\n */\nexport const BMAD_AGENT_FULL_PERSONAS: Record<BmadAgentType, BmadAgentFullPersona> = {\n architect: {\n type: \"architect\",\n name: \"Winston\",\n title: \"Software Architect\",\n icon: \"🏗️\",\n expertise: [\"system design\", \"security architecture\", \"scalability\", \"technical debt\"],\n perspective: \"architecture and system design\",\n identity:\n \"Senior architect with expertise in distributed systems, cloud infrastructure, and API design. Specializes in scalable patterns and technology selection.\",\n communicationStyle:\n \"Speaks in calm, pragmatic tones, balancing 'what could be' with 'what should be.' Champions boring technology that actually works.\",\n principles: [\n \"User journeys drive technical decisions\",\n \"Embrace boring technology for stability\",\n \"Design simple solutions that scale when needed\",\n \"Developer productivity is architecture\",\n ],\n },\n dev: {\n type: \"dev\",\n name: \"Amelia\",\n title: \"Senior Developer\",\n icon: \"💻\",\n expertise: [\"implementation\", \"code quality\", \"debugging\", \"performance optimization\"],\n perspective: \"implementation feasibility and code quality\",\n identity:\n \"Elite developer who thrives on clean implementations. Lives for readable code, sensible abstractions, and solutions that actually work in production.\",\n communicationStyle:\n \"Ultra-succinct. Speaks in file paths and AC IDs - every statement citable. No fluff, all precision.\",\n principles: [\n \"Code should be readable by humans first\",\n \"Ship incrementally, validate continuously\",\n \"Tests are documentation\",\n \"Complexity is the enemy\",\n ],\n },\n tea: {\n type: \"tea\",\n name: \"Murat\",\n title: \"Test Engineer Advocate\",\n icon: \"🧪\",\n expertise: [\"testing strategy\", \"edge cases\", \"test automation\", \"quality assurance\"],\n perspective: \"testability and quality assurance\",\n identity:\n \"Master test architect who sees quality as everyone's responsibility. Blends data with gut instinct to find bugs before they find users.\",\n communicationStyle:\n \"Blends data with gut instinct. 'Strong opinions, weakly held' is their mantra. Speaks in risk calculations and impact assessments.\",\n principles: [\n \"Test the behavior, not the implementation\",\n \"Edge cases reveal system character\",\n \"Automation enables confidence\",\n \"Quality is prevention, not detection\",\n ],\n },\n pm: {\n type: \"pm\",\n name: \"John\",\n title: \"Product Manager\",\n icon: \"📋\",\n expertise: [\"requirements\", \"stakeholder needs\", \"prioritization\", \"business value\"],\n perspective: \"business impact and stakeholder value\",\n identity:\n \"Investigative product strategist who asks 'WHY?' relentlessly. Connects every feature to user value and business outcomes.\",\n communicationStyle:\n \"Asks 'WHY?' relentlessly like a detective on a case. Direct and data-sharp, cuts through fluff to what actually matters.\",\n principles: [\n \"User problems drive solutions\",\n \"Data informs, intuition guides\",\n \"MVP means minimum VIABLE\",\n \"Say no to protect yes\",\n ],\n },\n analyst: {\n type: \"analyst\",\n name: \"Mary\",\n title: \"Business Analyst\",\n icon: \"📊\",\n expertise: [\"requirements analysis\", \"user stories\", \"acceptance criteria\", \"edge cases\"],\n perspective: \"requirements completeness and clarity\",\n identity:\n \"Strategic analyst who treats requirements like treasure hunts. Excited by patterns, thrilled when ambiguity becomes clarity.\",\n communicationStyle:\n \"Treats analysis like a treasure hunt - excited by every clue, thrilled when patterns emerge. Asks questions that spark 'aha!' moments.\",\n principles: [\n \"Ambiguity is the enemy of delivery\",\n \"Edge cases reveal true requirements\",\n \"Stakeholders often know what they need, not what they want\",\n \"Document decisions, not just outcomes\",\n ],\n },\n \"ux-designer\": {\n type: \"ux-designer\",\n name: \"Sally\",\n title: \"UX Designer\",\n icon: \"🎨\",\n expertise: [\"user experience\", \"accessibility\", \"usability\", \"user flows\"],\n perspective: \"user experience and accessibility\",\n identity:\n \"User advocate who designs experiences, not just interfaces. Champions accessibility and believes good UX is invisible.\",\n communicationStyle:\n \"Empathetic and user-focused. Uses stories and scenarios to illustrate points. Gentle but firm on accessibility.\",\n principles: [\n \"Design for the edges, the middle takes care of itself\",\n \"Accessibility is not optional\",\n \"Users don't read, they scan\",\n \"Friction is the enemy of conversion\",\n ],\n },\n \"tech-writer\": {\n type: \"tech-writer\",\n name: \"Paige\",\n title: \"Technical Writer\",\n icon: \"📚\",\n expertise: [\"documentation\", \"API docs\", \"user guides\", \"clarity\"],\n perspective: \"documentation and clarity\",\n identity:\n \"Knowledge curator who makes complex simple. Believes documentation is a product feature, not an afterthought.\",\n communicationStyle:\n \"Patient educator who explains like teaching a friend. Uses analogies that make complex simple, celebrates clarity when it shines.\",\n principles: [\n \"If it's not documented, it doesn't exist\",\n \"Good docs prevent support tickets\",\n \"Examples are worth a thousand words\",\n \"Write for the reader, not the writer\",\n ],\n },\n sm: {\n type: \"sm\",\n name: \"Bob\",\n title: \"Scrum Master\",\n icon: \"🎯\",\n expertise: [\"process\", \"team dynamics\", \"sprint planning\", \"blockers\"],\n perspective: \"process and team coordination\",\n identity:\n \"Servant leader who removes blockers and protects team focus. Facilitates rather than dictates.\",\n communicationStyle:\n \"Facilitative and inclusive. Asks powerful questions rather than giving answers. Celebrates team wins.\",\n principles: [\n \"The team knows best\",\n \"Process serves people, not vice versa\",\n \"Blockers are opportunities for improvement\",\n \"Sustainable pace enables sustainable delivery\",\n ],\n },\n};\n\n/**\n * Input for the party discussion tool\n */\nexport interface PartyDiscussionInput {\n /** Phase 1 results with Oracle findings */\n phase1Result: Phase1Result;\n /** Phase 2 agent analyses */\n phase2Result: Phase2Result;\n /** Stories content for context */\n storiesContent: Array<{ id: string; content: string }>;\n /** Optional: specific findings to discuss (defaults to all high severity + disputed) */\n findingsToDiscuss?: string[];\n}\n\n/**\n * A single agent's response in a discussion round\n */\nexport interface AgentDiscussionResponse {\n agent: BmadAgentType;\n agentName: string;\n icon: string;\n response: string;\n /** References to other agents in cross-talk */\n references?: Array<{\n agent: BmadAgentType;\n type: \"agrees\" | \"disagrees\" | \"builds-on\" | \"questions\";\n }>;\n /** Key points extracted from response */\n keyPoints: string[];\n}\n\n/**\n * A complete discussion round for a single finding\n */\nexport interface DiscussionRound {\n findingId: string;\n findingTitle: string;\n findingSeverity: FindingSeverity;\n findingCategory: FindingCategory;\n /** Agents who participated in this round */\n participants: BmadAgentType[];\n /** Agent responses in order */\n responses: AgentDiscussionResponse[];\n /** User's decision for this finding */\n decision?: ReviewDecision;\n /** User's reasoning for the decision */\n decisionReason?: string;\n /** If deferred, where to */\n deferredTo?: string;\n}\n\n/**\n * Discussion agenda item\n */\nexport interface DiscussionAgendaItem {\n id: string;\n findingId: string;\n topic: string;\n type: \"high-severity\" | \"disputed\" | \"cross-story\" | \"consensus\";\n severity: FindingSeverity;\n category: FindingCategory;\n /** Agents relevant to this topic */\n relevantAgents: BmadAgentType[];\n /** Pre-existing agent positions from Phase 2 */\n agentPositions: Partial<Record<BmadAgentType, string>>;\n /** Whether this item has been discussed */\n discussed: boolean;\n /** The discussion round if discussed */\n round?: DiscussionRound;\n}\n\n/**\n * Current state of the party discussion\n */\nexport interface PartyDiscussionState {\n /** Unique session ID */\n sessionId: string;\n /** Review scope */\n scope: ReviewScope;\n /** Epic or story identifier */\n identifier: string;\n /** Current agenda items */\n agenda: DiscussionAgendaItem[];\n /** Index of current agenda item */\n currentItemIndex: number;\n /** Completed discussion rounds */\n completedRounds: DiscussionRound[];\n /** Participating agents for this session */\n activeAgents: BmadAgentType[];\n /** When the discussion started */\n startedAt: string;\n /** Phase data for context */\n phase1Summary: Phase1Result[\"findings\"];\n phase2Summary?: {\n consensusCount: number;\n disputeCount: number;\n };\n}\n\n/**\n * Result from the party discussion tool\n */\nexport interface PartyDiscussionResult {\n success: boolean;\n /** Session ID for continuation */\n sessionId: string;\n /** Current state of the discussion */\n state: PartyDiscussionState;\n /** Current agenda item to display */\n currentItem?: DiscussionAgendaItem;\n /** Agent responses for current item (if generating discussion) */\n currentResponses?: AgentDiscussionResponse[];\n /** Summary when discussion is complete */\n summary?: {\n totalDiscussed: number;\n decisions: {\n accepted: number;\n deferred: number;\n rejected: number;\n pending: number;\n };\n /** @deprecated Use appliedUpdates instead - updates are now applied automatically */\n storyUpdatesNeeded: Array<{\n storyId: string;\n additions: string[];\n }>;\n };\n /** Result of automatically applying decisions to stories (on \"end\" action) */\n appliedUpdates?: ApplyDecisionsResult;\n /** Whether more items remain */\n hasMoreItems: boolean;\n /** Error if failed */\n error?: string;\n /** Suggestion for resolving error */\n suggestion?: string;\n}\n\n/**\n * Action to take in party discussion\n */\nexport type PartyDiscussionAction =\n | { type: \"start\"; input: PartyDiscussionInput }\n | { type: \"continue\"; sessionId: string }\n | {\n type: \"decide\";\n sessionId: string;\n findingId: string;\n decision: ReviewDecision;\n reason?: string;\n deferredTo?: string;\n }\n | { type: \"skip\"; sessionId: string; findingId: string }\n | { type: \"end\"; sessionId: string };\n\n// ============================================================================\n// BMAD ↔ Todo Sync Types\n// ============================================================================\n\n/**\n * OpenCode todo item format (matches oh-my-opencode/OpenCode schema)\n */\nexport interface OpenCodeTodo {\n /** Unique identifier for the todo item */\n id: string;\n /** Brief description of the task */\n content: string;\n /** Current status of the task */\n status: TodoStatus;\n /** Priority level of the task */\n priority: TodoPriority;\n}\n\n/**\n * Valid todo status values\n */\nexport type TodoStatus = \"pending\" | \"in_progress\" | \"completed\" | \"cancelled\";\n\n/**\n * Valid todo priority values\n */\nexport type TodoPriority = \"high\" | \"medium\" | \"low\";\n\n/**\n * BMAD section types that can contain checkboxes\n */\nexport type BmadSection = \"ac\" | \"tasks\" | \"impl-notes\";\n\n/**\n * A parsed task from a BMAD story file\n */\nexport interface BmadTask {\n /** Todo ID format: \"{storyId}:{section}:{lineNumber}\" */\n id: string;\n /** Story ID (e.g., \"2.3\") */\n storyId: string;\n /** Section where the checkbox was found */\n section: BmadSection;\n /** Index within the section (1-based) */\n sectionIndex: number;\n /** Line number in the file (0-based) */\n lineNumber: number;\n /** Task description text */\n content: string;\n /** Whether the checkbox is checked */\n checked: boolean;\n /** Detected or default priority */\n priority: TodoPriority;\n /** Indentation level for subtasks (number of spaces) */\n indent: number;\n}\n\n/**\n * Parsed todo ID components\n */\nexport interface ParsedTodoId {\n /** Story ID (e.g., \"2.3\") */\n storyId: string;\n /** Section type */\n section: BmadSection;\n /** Line number hint (may have shifted) */\n lineHint: number;\n}\n\n/**\n * Match type for todo matching\n */\nexport type TodoMatchType = \"id\" | \"exact-content\" | \"similar-content\" | \"none\";\n\n/**\n * Confidence thresholds for todo matching\n */\nexport const TODO_MATCH_THRESHOLDS = {\n AUTO_UPDATE: 0.7,\n WARN_USER: 0.5,\n} as const;\n\n/**\n * Result of attempting to match a todo with a previous todo\n */\nexport interface TodoMatchResult {\n /** The matched todo, if any */\n matched: OpenCodeTodo | null;\n /** How the match was found */\n matchType: TodoMatchType;\n /** Confidence score (0-1) */\n confidence: number;\n}\n\n// ============================================================================\n// Story Complexity & Decomposition Types\n// ============================================================================\n\n/**\n * Effort level for a task (maps to Fibonacci-ish points)\n */\nexport type TaskEffortLevel = \"trivial\" | \"small\" | \"medium\" | \"large\" | \"xlarge\";\n\n/**\n * Points mapping for effort levels\n */\nexport const EFFORT_POINTS: Record<TaskEffortLevel, number> = {\n trivial: 1,\n small: 2,\n medium: 3,\n large: 5,\n xlarge: 8,\n};\n\n/**\n * A parsed subtask from a story file\n */\nexport interface ParsedSubtask {\n /** Subtask ID within task (e.g., \"1.1\", \"1.2\") */\n id: string;\n /** Subtask description */\n description: string;\n /** Whether the checkbox is checked */\n completed: boolean;\n /** Line number in file (1-based) */\n lineNumber: number;\n}\n\n/**\n * A parsed task from a story file\n */\nexport interface ParsedTask {\n /** Task ID (e.g., \"1\", \"2\", \"3\") */\n id: string;\n /** Task description */\n description: string;\n /** Subtasks belonging to this task */\n subtasks: ParsedSubtask[];\n /** Whether the main task checkbox is checked */\n completed: boolean;\n /** Line number in file (1-based) */\n lineNumber: number;\n}\n\n/**\n * Effort estimate for a single task\n */\nexport interface TaskEffortEstimate {\n /** Task ID */\n taskId: string;\n /** Task description */\n description: string;\n /** Estimated effort level */\n effort: TaskEffortLevel;\n /** Story points (1, 2, 3, 5, 8) */\n points: number;\n /** Signals that contributed to this estimate */\n signals: string[];\n}\n\n/**\n * Complexity thresholds for story analysis\n */\nexport interface ComplexityThresholds {\n /** Maximum recommended tasks before warning */\n maxTasks: number;\n /** Critical task count - must split */\n criticalTasks: number;\n /** Maximum recommended story points before warning */\n maxPoints: number;\n /** Critical story points - must split */\n criticalPoints: number;\n /** Maximum recommended file size in KB */\n maxFileSizeKB: number;\n /** Critical file size - must split */\n criticalFileSizeKB: number;\n}\n\n/**\n * Default complexity thresholds (research-backed)\n */\nexport const DEFAULT_COMPLEXITY_THRESHOLDS: ComplexityThresholds = {\n maxTasks: 8,\n criticalTasks: 12,\n maxPoints: 8,\n criticalPoints: 13,\n maxFileSizeKB: 30,\n criticalFileSizeKB: 50,\n};\n\n/**\n * Recommendation for story complexity\n */\nexport type ComplexityRecommendation =\n | \"proceed\"\n | \"suggest-decomposition\"\n | \"require-decomposition\";\n\n/**\n * Story metrics from parsing\n */\nexport interface StoryMetrics {\n /** Number of tasks */\n taskCount: number;\n /** Total number of subtasks across all tasks */\n subtaskCount: number;\n /** Number of acceptance criteria (if separate from tasks) */\n acceptanceCriteriaCount: number;\n /** Story file size in KB */\n storyFileSizeKB: number;\n /** Story file line count */\n lineCount: number;\n}\n\n/**\n * Complete story complexity assessment\n */\nexport interface StoryComplexityAssessment {\n /** Story ID */\n storyId: string;\n /** Story filename */\n filename: string;\n /** Raw metrics */\n metrics: StoryMetrics;\n /** Task-level effort estimates */\n taskEfforts: TaskEffortEstimate[];\n /** Total estimated story points */\n totalPoints: number;\n /** Whether any threshold is exceeded */\n exceedsThreshold: boolean;\n /** Specific reasons for exceeding threshold */\n thresholdReasons: string[];\n /** Recommendation */\n recommendation: ComplexityRecommendation;\n /** Estimated context compactions needed */\n estimatedCompactions: number;\n}\n\n/**\n * Suggested split for story decomposition\n */\nexport interface DecompositionSplit {\n /** Suffix to append to original filename (e.g., \"a\", \"b\", \"c\") */\n suffix: string;\n /** Suggested title for the split story */\n title: string;\n /** Task IDs to include in this split */\n taskIds: string[];\n /** Estimated points for this split */\n estimatedPoints: number;\n /** Rationale for this grouping */\n rationale: string;\n /** Dependencies on other splits (by suffix) */\n dependencies: string[];\n}\n\n/**\n * Result from athena_analyze_story tool\n */\nexport interface AnalyzeStoryResult {\n success: boolean;\n /** Story ID analyzed */\n storyId: string;\n /** Story filename */\n filename: string;\n /** Full complexity assessment */\n assessment: StoryComplexityAssessment;\n /** Suggested decomposition splits (if recommended) */\n suggestedSplits?: DecompositionSplit[];\n /** Error if analysis failed */\n error?: string;\n /** Suggestion for resolving error */\n suggestion?: string;\n}\n\n/**\n * User-provided split configuration\n */\nexport interface UserSplitConfig {\n /** Suffix to append to original filename */\n suffix: string;\n /** Optional title override */\n title?: string;\n /** Task IDs to include */\n taskIds: string[];\n}\n\n/**\n * Arguments for athena_decompose_story tool\n */\nexport interface DecomposeStoryArgs {\n /** Story ID to decompose */\n storyId: string;\n /** Custom splits (if user modified suggestion) */\n splits?: UserSplitConfig[];\n /** Use the suggested splits from analysis (if no custom splits) */\n useSuggestedSplits?: boolean;\n /** Must be true to execute (safety check) */\n confirmed: boolean;\n}\n\n/**\n * Information about a created sub-story\n */\nexport interface CreatedSubStory {\n /** Story ID (e.g., \"3.2a\") */\n id: string;\n /** Filename (e.g., \"3-2a-reset-list-screen.md\") */\n filename: string;\n /** Full file path */\n filePath: string;\n /** Number of tasks in this story */\n taskCount: number;\n /** Estimated points */\n estimatedPoints: number;\n /** Status in sprint-status.yaml */\n status: \"ready-for-dev\" | \"backlog\";\n /** Dependencies on other sub-stories */\n dependencies: string[];\n /** Whether a verification task was added (for unorderable deps) */\n hasVerificationTask: boolean;\n}\n\n/**\n * Verification result for decomposition\n */\nexport interface DecompositionVerification {\n /** Original task count */\n originalTaskCount: number;\n /** Total tasks across all splits */\n totalTasksInSplits: number;\n /** Whether all tasks are accounted for */\n allTasksAccountedFor: boolean;\n /** Tasks missing from splits (should be empty) */\n missingTasks: string[];\n /** Tasks duplicated across splits (should be empty) */\n duplicatedTasks: string[];\n /** Whether dev notes were preserved */\n devNotesPreserved: boolean;\n}\n\n/**\n * Result from athena_decompose_story tool\n */\nexport interface DecomposeStoryResult {\n success: boolean;\n /** Created sub-stories */\n createdStories: CreatedSubStory[];\n /** Verification of completeness */\n verification: DecompositionVerification;\n /** Whether sprint-status.yaml was updated */\n sprintStatusUpdated: boolean;\n /** Whether original story was removed */\n originalStoryRemoved: boolean;\n /** First story to implement */\n nextStory: string;\n /** Error if decomposition failed */\n error?: string;\n /** Suggestion for resolving error */\n suggestion?: string;\n}\n","/**\n * Story loader utilities with flexible naming support.\n *\n * Supports multiple story naming conventions:\n * - story-{epic}-{number}.md (e.g., story-4-1.md) - BMAD standard\n * - story-{epic}-{number}-{title}.md (e.g., story-4-1-setup.md) - BMAD with title\n * - {epic}-{number}.md (e.g., 4-1.md) - minimal\n * - {epic}-{number}-{title}.md (e.g., 4-1-fastify-setup.md) - with title\n *\n * All matching is case-insensitive.\n * Files with \"story-\" prefix are prioritized over those without.\n */\n\nimport { existsSync } from \"node:fs\";\nimport { readFile, readdir } from \"node:fs/promises\";\nimport { basename, join, resolve } from \"node:path\";\n\n/**\n * Result of finding a story file.\n */\nexport interface StoryFileResult {\n /** Full path to the story file */\n path: string;\n /** Original filename as it exists on disk */\n filename: string;\n /** Normalized story ID (e.g., \"4.1\") */\n storyId: string;\n /** Whether multiple matches were found */\n hasMultipleMatches: boolean;\n /** Other matching files that were not selected */\n alternativeFiles?: string[];\n}\n\n/**\n * Information about a story found in a directory.\n */\nexport interface StoryInfo {\n /** Normalized story ID (e.g., \"4.1\") */\n id: string;\n /** Epic number */\n epic: string;\n /** Story number within the epic */\n number: string;\n /** Original filename */\n filename: string;\n /** Full path to the file */\n path: string;\n /** Whether this file has the story- prefix */\n hasStoryPrefix: boolean;\n}\n\n/**\n * Pattern for matching story files.\n * Matches: story-4-1.md, story-4-1-title.md, 4-1.md, 4-1-title.md\n * Groups: [1] = \"story-\" prefix (optional), [2] = epic, [3] = number\n */\nconst STORY_PATTERN = /^(story-)?(\\d+)-(\\d+)(?:-[a-zA-Z0-9-]+)?\\.md$/i;\n\n/**\n * Parse a story ID from a filename.\n * Returns null if the filename doesn't match a story pattern.\n *\n * @example\n * parseStoryIdFromFilename(\"story-4-1.md\") // { id: \"4.1\", epic: \"4\", number: \"1\", hasStoryPrefix: true }\n * parseStoryIdFromFilename(\"4-1-setup.md\") // { id: \"4.1\", epic: \"4\", number: \"1\", hasStoryPrefix: false }\n * parseStoryIdFromFilename(\"README.md\") // null\n */\nexport function parseStoryIdFromFilename(\n filename: string\n): { id: string; epic: string; number: string; hasStoryPrefix: boolean } | null {\n const match = filename.match(STORY_PATTERN);\n if (!match) {\n return null;\n }\n\n const hasStoryPrefix = !!match[1];\n const epic = match[2];\n const number = match[3];\n\n return {\n id: `${epic}.${number}`,\n epic,\n number,\n hasStoryPrefix,\n };\n}\n\n/**\n * Find a story file by its ID (e.g., \"4.1\" or \"4-1\").\n * Searches the directory for any file matching the story pattern.\n *\n * Priority:\n * 1. Files with \"story-\" prefix\n * 2. Files without prefix\n *\n * If multiple matches exist, selects the highest priority and logs alternatives.\n *\n * @param storiesDir - Directory containing story files\n * @param storyId - Story ID (e.g., \"4.1\", \"4-1\", or \"story-4-1\")\n * @param logger - Optional logger for warnings about multiple matches\n * @returns StoryFileResult or null if not found\n */\nexport async function findStoryFile(\n storiesDir: string,\n storyId: string,\n logger?: { warn: (msg: string) => void }\n): Promise<StoryFileResult | null> {\n if (!existsSync(storiesDir)) {\n return null;\n }\n\n // Normalize the story ID: \"story-4-1\" -> \"4.1\", \"4-1\" -> \"4.1\", \"4.1\" -> \"4.1\"\n const normalizedId = normalizeStoryId(storyId);\n const [epicNum, storyNum] = normalizedId.split(\".\");\n\n if (!epicNum || !storyNum) {\n return null;\n }\n\n const files = await readdir(storiesDir);\n const matches: StoryInfo[] = [];\n\n for (const file of files) {\n const parsed = parseStoryIdFromFilename(file);\n if (parsed && parsed.epic === epicNum && parsed.number === storyNum) {\n matches.push({\n ...parsed,\n filename: file,\n path: join(storiesDir, file),\n });\n }\n }\n\n if (matches.length === 0) {\n return null;\n }\n\n // Sort: story- prefix first, then alphabetically\n matches.sort((a, b) => {\n if (a.hasStoryPrefix !== b.hasStoryPrefix) {\n return a.hasStoryPrefix ? -1 : 1;\n }\n return a.filename.localeCompare(b.filename);\n });\n\n const selected = matches[0];\n const alternatives = matches.slice(1).map((m) => m.filename);\n\n if (alternatives.length > 0 && logger) {\n const reason = selected.hasStoryPrefix ? \"has story- prefix\" : \"alphabetically first\";\n const altLines = alternatives.map((f) => ` → ${f}`).join(\"\\n\");\n logger.warn(\n `Multiple story files found for ${normalizedId}:\\n → ${selected.filename} (selected - ${reason})\\n${altLines}`\n );\n }\n\n return {\n path: selected.path,\n filename: selected.filename,\n storyId: normalizedId,\n hasMultipleMatches: alternatives.length > 0,\n alternativeFiles: alternatives.length > 0 ? alternatives : undefined,\n };\n}\n\n/**\n * Find all stories for a given epic.\n * Returns stories sorted by story number.\n *\n * For duplicate story IDs (same epic-number but different filenames),\n * prioritizes files with \"story-\" prefix and logs alternatives.\n *\n * @param storiesDir - Directory containing story files\n * @param epicNumber - Epic number (e.g., \"4\" or \"epic-4\")\n * @param logger - Optional logger for warnings about duplicates\n * @returns Array of StoryInfo objects\n */\nexport async function findStoriesForEpic(\n storiesDir: string,\n epicNumber: string,\n logger?: { warn: (msg: string) => void }\n): Promise<StoryInfo[]> {\n if (!existsSync(storiesDir)) {\n return [];\n }\n\n // Normalize: \"epic-4\" -> \"4\"\n const epicNum = epicNumber.replace(/^epic-/i, \"\");\n\n const files = await readdir(storiesDir);\n const allMatches: StoryInfo[] = [];\n\n for (const file of files) {\n const parsed = parseStoryIdFromFilename(file);\n if (parsed && parsed.epic === epicNum) {\n allMatches.push({\n ...parsed,\n filename: file,\n path: join(storiesDir, file),\n });\n }\n }\n\n // Group by story ID to handle duplicates\n const byId = new Map<string, StoryInfo[]>();\n for (const match of allMatches) {\n const existing = byId.get(match.id) || [];\n existing.push(match);\n byId.set(match.id, existing);\n }\n\n // Select best match for each story ID\n const results: StoryInfo[] = [];\n for (const [id, matches] of byId) {\n // Sort: story- prefix first, then alphabetically\n matches.sort((a, b) => {\n if (a.hasStoryPrefix !== b.hasStoryPrefix) {\n return a.hasStoryPrefix ? -1 : 1;\n }\n return a.filename.localeCompare(b.filename);\n });\n\n const selected = matches[0];\n results.push(selected);\n\n if (matches.length > 1 && logger) {\n const alternatives = matches.slice(1).map((m) => m.filename);\n const reason = selected.hasStoryPrefix ? \"has story- prefix\" : \"alphabetically first\";\n const altLines = alternatives.map((f) => ` → ${f}`).join(\"\\n\");\n logger.warn(\n `Multiple story files found for ${id}:\\n → ${selected.filename} (selected - ${reason})\\n${altLines}`\n );\n }\n }\n\n // Sort by story number\n return results.sort((a, b) => {\n const numA = Number.parseInt(a.number, 10);\n const numB = Number.parseInt(b.number, 10);\n return numA - numB;\n });\n}\n\n/**\n * Load story file content by ID.\n * Convenience function that combines findStoryFile + readFile.\n *\n * @param storiesDir - Directory containing story files\n * @param storyId - Story ID (e.g., \"4.1\")\n * @param logger - Optional logger for warnings\n * @returns File content or null if not found\n */\nexport async function loadStoryContent(\n storiesDir: string,\n storyId: string,\n logger?: { warn: (msg: string) => void }\n): Promise<{ content: string; path: string; filename: string } | null> {\n const result = await findStoryFile(storiesDir, storyId, logger);\n if (!result) {\n return null;\n }\n\n try {\n const content = await readFile(result.path, \"utf-8\");\n return {\n content,\n path: result.path,\n filename: result.filename,\n };\n } catch {\n return null;\n }\n}\n\n/**\n * Normalize a story ID to the format \"epic.number\".\n *\n * @example\n * normalizeStoryId(\"story-4-1\") // \"4.1\"\n * normalizeStoryId(\"4-1\") // \"4.1\"\n * normalizeStoryId(\"4.1\") // \"4.1\"\n * normalizeStoryId(\"story-4-1-title.md\") // \"4.1\"\n */\nexport function normalizeStoryId(identifier: string): string {\n // Handle file paths\n if (identifier.includes(\"/\")) {\n const filename = identifier.split(\"/\").pop() || \"\";\n const parsed = parseStoryIdFromFilename(filename);\n if (parsed) {\n return parsed.id;\n }\n }\n\n // Handle filenames directly\n if (identifier.endsWith(\".md\")) {\n const parsed = parseStoryIdFromFilename(identifier);\n if (parsed) {\n return parsed.id;\n }\n }\n\n // Handle \"story-4-1\" or \"4-1\" format\n const cleaned = identifier.replace(/^story-/i, \"\");\n\n // Convert \"4-1\" to \"4.1\"\n if (cleaned.includes(\"-\") && !cleaned.includes(\".\")) {\n const parts = cleaned.split(\"-\");\n if (parts.length >= 2 && /^\\d+$/.test(parts[0]) && /^\\d+$/.test(parts[1])) {\n return `${parts[0]}.${parts[1]}`;\n }\n }\n\n return cleaned;\n}\n\n/**\n * Check if a filename matches a story pattern.\n * Used for filtering directory listings.\n */\nexport function isStoryFile(filename: string): boolean {\n return STORY_PATTERN.test(filename);\n}\n\n/**\n * Extract story ID from a finding ID.\n *\n * Handles multiple formats from different sources:\n * - story-{epic}-{num}-*: \"story-2-3-high-1\" → \"2.3\" (test/legacy format)\n * - S{storyId}-*: \"S2.3-SEC-1\" → \"2.3\" (Oracle storyFindings format)\n * - {storyId}-*: \"4.5-L1\" → \"4.5\" (direct story prefix)\n * - {epic}-{num}-*: \"2-3-high-1\" → \"2.3\" (dash-separated)\n *\n * Falls back to provided default for IDs without story info:\n * - \"high-1\", \"debate-3\", \"SEC-1\" → uses fallback\n *\n * @param findingId - The finding ID to parse\n * @param fallback - Default story ID if not extractable (typically session identifier)\n * @returns Normalized story ID (e.g., \"4.5\")\n */\nexport function extractStoryIdFromFindingId(findingId: string, fallback: string): string {\n // Pattern 1: story-{epic}-{num}-* (legacy/test format)\n // e.g., \"story-2-3-high-1\" → \"2.3\"\n const storyPrefixMatch = findingId.match(/^story-?(\\d+)[.-](\\d+[a-z]?)/i);\n if (storyPrefixMatch) {\n return `${storyPrefixMatch[1]}.${storyPrefixMatch[2]}`;\n }\n\n // Pattern 2: S{storyId}-* (Oracle storyFindings format)\n // e.g., \"S2.3-SEC-1\" → \"2.3\", \"S4.5a-LOG-1\" → \"4.5a\"\n const oracleMatch = findingId.match(/^S(\\d+)[.](\\d+[a-z]?)-/i);\n if (oracleMatch) {\n return `${oracleMatch[1]}.${oracleMatch[2]}`;\n }\n\n // Pattern 3: {storyId}-* (direct story ID prefix with dot)\n // e.g., \"4.5-L1\" → \"4.5\", \"2.3a-P1\" → \"2.3a\"\n const dotMatch = findingId.match(/^(\\d+)[.](\\d+[a-z]?)-/);\n if (dotMatch) {\n return `${dotMatch[1]}.${dotMatch[2]}`;\n }\n\n // Pattern 4: {epic}-{num}-* (dash-separated, no \"story\" prefix)\n // e.g., \"2-3-high-1\" → \"2.3\"\n // Must have something after the second number to distinguish from story IDs\n const dashMatch = findingId.match(/^(\\d+)-(\\d+[a-z]?)-[a-zA-Z]/);\n if (dashMatch) {\n return `${dashMatch[1]}.${dashMatch[2]}`;\n }\n\n // No story ID found in finding ID - use fallback\n // This handles: \"high-1\", \"debate-3\", \"SEC-1\", \"LOG-2\", etc.\n return normalizeStoryId(fallback);\n}\n\n/**\n * Get the expected filename patterns for a story ID.\n * Useful for error messages.\n *\n * @param storyId - Normalized story ID (e.g., \"4.1\")\n * @returns Array of example patterns\n */\nexport function getStoryFilenamePatterns(storyId: string): string[] {\n const [epic, number] = storyId.split(\".\");\n return [\n `story-${epic}-${number}.md`,\n `story-${epic}-${number}-*.md`,\n `${epic}-${number}.md`,\n `${epic}-${number}-*.md`,\n ];\n}\n\n/**\n * Strip @ prefix if present (OpenCode file reference syntax).\n * OpenCode uses @path/to/file to reference files in prompts.\n *\n * @example\n * stripAtPrefix(\"@docs/stories/story-4-1.md\") // \"docs/stories/story-4-1.md\"\n * stripAtPrefix(\"4.1\") // \"4.1\"\n * stripAtPrefix(\"story-4-1\") // \"story-4-1\"\n */\nexport function stripAtPrefix(identifier: string): string {\n return identifier.startsWith(\"@\") ? identifier.slice(1) : identifier;\n}\n\n/**\n * Check if identifier looks like a file path (vs a story ID).\n * Does NOT check if file exists - just pattern detection.\n *\n * @example\n * looksLikeFilePath(\"docs/stories/story-4-1.md\") // true\n * looksLikeFilePath(\"./story-4-1.md\") // true\n * looksLikeFilePath(\"/absolute/path/story.md\") // true\n * looksLikeFilePath(\"4.1\") // false\n * looksLikeFilePath(\"story-4-1\") // false\n */\nexport function looksLikeFilePath(identifier: string): boolean {\n // Contains path separator (forward or back slash)\n const hasPathSeparator = identifier.includes(\"/\") || identifier.includes(\"\\\\\");\n\n // Ends with .md extension\n const hasMdExtension = identifier.endsWith(\".md\");\n\n // Starts with ./ or ../ (relative path indicators)\n const hasRelativePrefix = identifier.startsWith(\"./\") || identifier.startsWith(\"../\");\n\n // Starts with / (absolute path on Unix)\n const hasAbsolutePrefix = identifier.startsWith(\"/\");\n\n // It's a file path if it has path separators, or has .md extension with relative/absolute prefix\n return hasPathSeparator || (hasMdExtension && (hasRelativePrefix || hasAbsolutePrefix));\n}\n\n/**\n * Load story content directly from a file path.\n * Extracts story ID from filename for tracking.\n *\n * @param filePath - Absolute or resolved path to the story file\n * @returns Story content with metadata, or null if file doesn't exist\n */\nexport async function loadStoryFromPath(\n filePath: string\n): Promise<{ content: string; path: string; filename: string; storyId: string } | null> {\n if (!existsSync(filePath)) {\n return null;\n }\n\n const filename = basename(filePath);\n const parsed = parseStoryIdFromFilename(filename);\n\n // Extract story ID from filename, or normalize the filename itself\n const storyId = parsed?.id ?? normalizeStoryId(filename);\n\n try {\n const content = await readFile(filePath, \"utf-8\");\n return { content, path: filePath, filename, storyId };\n } catch {\n return null;\n }\n}\n\n/**\n * Result of resolving a story identifier.\n */\nexport interface ResolvedStory {\n /** Story file content */\n content: string;\n /** Full path to the story file */\n path: string;\n /** Original filename */\n filename: string;\n /** Normalized story ID (e.g., \"4.1\") */\n storyId: string;\n}\n\n/**\n * Resolve a story identifier that might be a file path or story ID.\n *\n * Resolution order:\n * 1. Strip @ prefix if present (OpenCode file reference syntax)\n * 2. If it looks like a file path:\n * a. Try as absolute path\n * b. Try relative to projectRoot\n * 3. Fall back to searching in storiesDir (original behavior)\n *\n * @param storiesDir - Directory containing story files (for fallback)\n * @param identifier - Story ID (e.g., \"4.1\") or file path (e.g., \"docs/stories/story-4-1.md\")\n * @param projectRoot - Project root for resolving relative paths\n * @param logger - Optional logger for warnings\n * @returns Resolved story or null if not found\n *\n * @example\n * // File path (absolute)\n * await resolveStoryIdentifier(storiesDir, \"/home/user/project/docs/story-4-1.md\", projectRoot)\n *\n * // File path (relative)\n * await resolveStoryIdentifier(storiesDir, \"docs/stories/story-4-1.md\", projectRoot)\n *\n * // OpenCode @ reference\n * await resolveStoryIdentifier(storiesDir, \"@docs/stories/story-4-1.md\", projectRoot)\n *\n * // Story ID (fallback to storiesDir search)\n * await resolveStoryIdentifier(storiesDir, \"4.1\", projectRoot)\n */\nexport async function resolveStoryIdentifier(\n storiesDir: string,\n identifier: string,\n projectRoot?: string,\n logger?: { warn: (msg: string) => void }\n): Promise<ResolvedStory | null> {\n // 1. Strip @ prefix if present\n const cleaned = stripAtPrefix(identifier);\n\n // 2. Check if it looks like a file path\n if (looksLikeFilePath(cleaned)) {\n // 2a. Try as absolute path (or path that exists as-is)\n if (existsSync(cleaned)) {\n const result = await loadStoryFromPath(cleaned);\n if (result) return result;\n }\n\n // 2b. Try with .md extension if not present (absolute path)\n if (!cleaned.endsWith(\".md\")) {\n const withExt = `${cleaned}.md`;\n if (existsSync(withExt)) {\n const result = await loadStoryFromPath(withExt);\n if (result) return result;\n }\n }\n\n // 2c. Try relative to project root\n if (projectRoot) {\n const absolutePath = resolve(projectRoot, cleaned);\n if (existsSync(absolutePath)) {\n const result = await loadStoryFromPath(absolutePath);\n if (result) return result;\n }\n\n // Try relative path with .md extension\n if (!cleaned.endsWith(\".md\")) {\n const absoluteWithExt = resolve(projectRoot, `${cleaned}.md`);\n if (existsSync(absoluteWithExt)) {\n const result = await loadStoryFromPath(absoluteWithExt);\n if (result) return result;\n }\n }\n }\n\n // File path was provided but doesn't exist - still try storiesDir as fallback\n }\n\n // 3. Fall back to storiesDir search (original behavior)\n const result = await loadStoryContent(storiesDir, cleaned, logger);\n if (result) {\n return {\n ...result,\n storyId: normalizeStoryId(cleaned),\n };\n }\n\n return null;\n}\n","import { readFile, writeFile } from \"node:fs/promises\";\nimport type {\n BmadSection,\n BmadTask,\n OpenCodeTodo,\n ParsedTodoId,\n TodoMatchResult,\n TodoPriority,\n TodoStatus,\n} from \"../../shared/types.js\";\nimport { TODO_MATCH_THRESHOLDS } from \"../../shared/types.js\";\n\nexport const ATHENA_SEPARATOR = \"Δ\";\n\nconst BMAD_TODO_PATTERN = /^\\s*\\[[\\d.]+Δ/;\n\nconst CHECKBOX_PATTERN = /^(\\s*)- \\[([ xX])\\] (.+)$/;\n\nconst SECTION_HEADERS: Record<string, BmadSection> = {\n \"acceptance criteria\": \"ac\",\n \"tasks / subtasks\": \"tasks\",\n \"tasks/subtasks\": \"tasks\",\n tasks: \"tasks\",\n subtasks: \"tasks\",\n \"implementation notes\": \"impl-notes\",\n};\n\nconst SECTION_LABELS: Record<BmadSection, string> = {\n ac: \"AC\",\n tasks: \"Task\",\n \"impl-notes\": \"Fix\",\n};\n\nexport function parseBmadTasks(content: string, storyId: string): BmadTask[] {\n const lines = content.split(\"\\n\");\n const tasks: BmadTask[] = [];\n\n let currentSection: BmadSection | null = null;\n let sectionIndex = 0;\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n\n const headerMatch = line.match(/^##\\s+(.+)$/);\n if (headerMatch) {\n const headerText = headerMatch[1].trim().toLowerCase();\n const matchedSection = Object.entries(SECTION_HEADERS).find(([key]) =>\n headerText.startsWith(key)\n );\n\n if (matchedSection) {\n currentSection = matchedSection[1];\n sectionIndex = 0;\n } else {\n currentSection = null;\n }\n continue;\n }\n\n if (!currentSection) continue;\n\n const checkboxMatch = line.match(CHECKBOX_PATTERN);\n if (!checkboxMatch) continue;\n\n sectionIndex++;\n const [, indent, checkState, taskText] = checkboxMatch;\n const checked = checkState.toLowerCase() === \"x\";\n const priority = detectPriority(taskText, currentSection);\n\n tasks.push({\n id: `${storyId}:${currentSection}:${i}`,\n storyId,\n section: currentSection,\n sectionIndex,\n lineNumber: i,\n content: taskText.trim(),\n checked,\n priority,\n indent: indent.length,\n });\n }\n\n return tasks;\n}\n\nfunction detectPriority(content: string, section: BmadSection): TodoPriority {\n const lower = content.toLowerCase();\n\n if (lower.includes(\"priority: critical\") || lower.includes(\"critical:\")) {\n return \"high\";\n }\n if (lower.includes(\"priority: high\")) {\n return \"high\";\n }\n if (lower.includes(\"priority: medium\")) {\n return \"medium\";\n }\n if (lower.includes(\"priority: low\")) {\n return \"low\";\n }\n\n if (lower.includes(\"must\")) {\n return \"high\";\n }\n if (lower.includes(\"should\")) {\n return \"medium\";\n }\n if (lower.includes(\"could\")) {\n return \"low\";\n }\n\n switch (section) {\n case \"ac\":\n return \"high\";\n case \"tasks\":\n return \"medium\";\n case \"impl-notes\":\n return \"medium\";\n }\n}\n\nexport function bmadTasksToTodos(tasks: BmadTask[]): OpenCodeTodo[] {\n return tasks.map((task) => {\n const label = SECTION_LABELS[task.section];\n const prefix = `[${task.storyId}${ATHENA_SEPARATOR}${label}${task.sectionIndex}]`;\n const indentation = \" \".repeat(task.indent);\n const status: TodoStatus = task.checked ? \"completed\" : \"pending\";\n\n return {\n id: task.id,\n content: `${indentation}${prefix} ${task.content}`,\n status,\n priority: task.priority,\n };\n });\n}\n\nexport function parseTodoId(todoId: string): ParsedTodoId | null {\n const parts = todoId.split(\":\");\n if (parts.length !== 3) return null;\n\n const [storyId, section, lineStr] = parts;\n const lineHint = Number.parseInt(lineStr, 10);\n\n if (!storyId || !section || Number.isNaN(lineHint)) return null;\n\n const validSections: BmadSection[] = [\"ac\", \"tasks\", \"impl-notes\"];\n if (!validSections.includes(section as BmadSection)) return null;\n\n return {\n storyId,\n section: section as BmadSection,\n lineHint,\n };\n}\n\nexport function isBmadTodo(todo: OpenCodeTodo): boolean {\n return BMAD_TODO_PATTERN.test(todo.content);\n}\n\nexport function extractStoryIdFromContent(content: string): string | null {\n const match = content.match(/^\\s*\\[([\\d.]+)Δ/);\n return match ? match[1] : null;\n}\n\nexport async function findCheckboxLine(\n storyPath: string,\n taskContent: string,\n lineHint: number\n): Promise<number | null> {\n const content = await readFile(storyPath, \"utf-8\");\n const lines = content.split(\"\\n\");\n\n const searchText = extractTaskText(taskContent);\n if (!searchText) return null;\n\n if (lineHint >= 0 && lineHint < lines.length) {\n if (matchesCheckbox(lines[lineHint], searchText)) {\n return lineHint;\n }\n }\n\n const searchRadius = 15;\n const startNearby = Math.max(0, lineHint - searchRadius);\n const endNearby = Math.min(lines.length, lineHint + searchRadius + 1);\n\n for (let i = startNearby; i < endNearby; i++) {\n if (i === lineHint) continue;\n if (matchesCheckbox(lines[i], searchText)) {\n return i;\n }\n }\n\n for (let i = 0; i < lines.length; i++) {\n if (i >= startNearby && i < endNearby) continue;\n if (matchesCheckbox(lines[i], searchText)) {\n return i;\n }\n }\n\n return null;\n}\n\nexport function extractTaskText(todoContent: string): string | null {\n const match = todoContent.match(/^\\s*\\[[\\d.]+Δ\\w+\\d*\\]\\s*(.+)$/);\n return match ? match[1].trim() : todoContent.trim();\n}\n\nfunction matchesCheckbox(line: string, searchText: string): boolean {\n const checkboxMatch = line.match(CHECKBOX_PATTERN);\n if (!checkboxMatch) return false;\n\n const checkboxText = checkboxMatch[3].trim().toLowerCase();\n const search = searchText.toLowerCase();\n\n if (checkboxText === search) return true;\n if (checkboxText.includes(search) || search.includes(checkboxText)) return true;\n\n const similarity = calculateSimilarity(checkboxText, search);\n return similarity > 0.7;\n}\n\nexport function calculateSimilarity(a: string, b: string): number {\n if (a === b) return 1;\n if (a.length === 0 || b.length === 0) return 0;\n\n const wordsA = new Set(a.split(/\\s+/));\n const wordsB = new Set(b.split(/\\s+/));\n\n let intersection = 0;\n for (const word of wordsA) {\n if (wordsB.has(word)) intersection++;\n }\n\n const union = wordsA.size + wordsB.size - intersection;\n return union > 0 ? intersection / union : 0;\n}\n\nexport async function updateBmadCheckbox(\n storyPath: string,\n lineNumber: number,\n checked: boolean\n): Promise<boolean> {\n const content = await readFile(storyPath, \"utf-8\");\n const lines = content.split(\"\\n\");\n\n if (lineNumber < 0 || lineNumber >= lines.length) {\n return false;\n }\n\n const line = lines[lineNumber];\n const checkboxMatch = line.match(CHECKBOX_PATTERN);\n\n if (!checkboxMatch) {\n return false;\n }\n\n if (checked) {\n lines[lineNumber] = line.replace(\"- [ ]\", \"- [x]\");\n } else {\n lines[lineNumber] = line.replace(/- \\[[xX]\\]/, \"- [ ]\");\n }\n\n await writeFile(storyPath, lines.join(\"\\n\"), \"utf-8\");\n return true;\n}\n\nexport function mergeTodos(\n existingTodos: OpenCodeTodo[],\n newBmadTodos: OpenCodeTodo[],\n loadingStoryId: string\n): OpenCodeTodo[] {\n const userTodos = existingTodos.filter((t) => !isBmadTodo(t));\n\n const otherStoryTodos = existingTodos.filter((t) => {\n if (!isBmadTodo(t)) return false;\n const todoStoryId = extractStoryIdFromContent(t.content);\n if (!todoStoryId) return false;\n return todoStoryId !== loadingStoryId && t.status !== \"completed\";\n });\n\n return [...userTodos, ...otherStoryTodos, ...newBmadTodos];\n}\n\nexport function findMatchingTodo(\n todo: OpenCodeTodo,\n previousTodos: OpenCodeTodo[]\n): TodoMatchResult {\n const idMatch = previousTodos.find((t) => t.id === todo.id);\n if (idMatch) {\n return { matched: idMatch, matchType: \"id\", confidence: 1.0 };\n }\n\n const todoText = extractTaskText(todo.content);\n if (!todoText) {\n return { matched: null, matchType: \"none\", confidence: 0 };\n }\n\n const bmadTodos = previousTodos.filter(isBmadTodo);\n\n for (const prev of bmadTodos) {\n const prevText = extractTaskText(prev.content);\n if (prevText && prevText.toLowerCase() === todoText.toLowerCase()) {\n return { matched: prev, matchType: \"exact-content\", confidence: 0.95 };\n }\n }\n\n let bestMatch: { todo: OpenCodeTodo; similarity: number } | null = null;\n for (const prev of bmadTodos) {\n const prevText = extractTaskText(prev.content);\n if (!prevText) continue;\n\n const similarity = calculateSimilarity(prevText.toLowerCase(), todoText.toLowerCase());\n if (\n similarity >= TODO_MATCH_THRESHOLDS.WARN_USER &&\n similarity > (bestMatch?.similarity ?? 0)\n ) {\n bestMatch = { todo: prev, similarity };\n }\n }\n\n if (bestMatch) {\n return {\n matched: bestMatch.todo,\n matchType: \"similar-content\",\n confidence: bestMatch.similarity,\n };\n }\n\n return { matched: null, matchType: \"none\", confidence: 0 };\n}\n","import type { AthenaConfig, OpenCodeTodo } from \"../../shared/types.js\";\nimport { TODO_MATCH_THRESHOLDS } from \"../../shared/types.js\";\nimport type { StoryTracker } from \"../tracker/story-tracker.js\";\nimport { createPluginLogger } from \"../utils/plugin-logger.js\";\nimport { findStoryFile } from \"../utils/story-loader.js\";\nimport {\n bmadTasksToTodos,\n extractStoryIdFromContent,\n findCheckboxLine,\n findMatchingTodo,\n isBmadTodo,\n mergeTodos,\n parseBmadTasks,\n parseTodoId,\n updateBmadCheckbox,\n} from \"../utils/todo-sync.js\";\n\nconst log = createPluginLogger(\"todo-hooks\");\n\nexport interface TodoSyncPaths {\n storiesDir: string;\n}\n\nexport interface StoryLoadedResult {\n mergedTodos: OpenCodeTodo[];\n newBmadTodos: OpenCodeTodo[];\n}\n\nexport async function onStoryLoaded(\n tracker: StoryTracker,\n config: AthenaConfig,\n storyId: string,\n storyContent: string\n): Promise<StoryLoadedResult> {\n if (!config.features.todoSync) {\n return { mergedTodos: [], newBmadTodos: [] };\n }\n\n try {\n const tasks = parseBmadTasks(storyContent, storyId);\n const newBmadTodos = bmadTasksToTodos(tasks);\n\n const existingTodos = tracker.getCurrentTodos() || [];\n const mergedTodos = mergeTodos(existingTodos, newBmadTodos, storyId);\n\n await tracker.setCurrentTodos(mergedTodos);\n\n log.info(\"Synced BMAD tasks to todos\", {\n storyId,\n newTasks: tasks.length,\n totalTodos: mergedTodos.length,\n });\n\n return { mergedTodos, newBmadTodos };\n } catch (error) {\n log.warn(\"Failed to sync BMAD tasks\", { storyId, error });\n return { mergedTodos: [], newBmadTodos: [] };\n }\n}\n\nexport async function onTodoWritten(\n tracker: StoryTracker,\n config: AthenaConfig,\n paths: TodoSyncPaths,\n todos: OpenCodeTodo[]\n): Promise<void> {\n if (!config.features.todoSync) {\n return;\n }\n\n const previousTodos = tracker.getCurrentTodos() || [];\n log.debug(\"Processing todowrite for BMAD sync\", {\n incomingTodos: todos.length,\n trackedTodos: previousTodos.length,\n });\n\n let processed = 0;\n let matchedById = 0;\n let matchedByContent = 0;\n let lowConfidenceSkipped = 0;\n let updated = 0;\n\n for (const todo of todos) {\n const matchResult = findMatchingTodo(todo, previousTodos);\n\n if (matchResult.matchType === \"none\" || !matchResult.matched) {\n if (isBmadTodo(todo)) {\n log.debug(\"No match found for BMAD-formatted todo\", {\n todoId: todo.id,\n content: todo.content.slice(0, 50),\n });\n }\n continue;\n }\n\n processed++;\n const previous = matchResult.matched;\n\n if (matchResult.matchType === \"id\") {\n matchedById++;\n } else {\n matchedByContent++;\n log.debug(\"Matched todo by content\", {\n matchType: matchResult.matchType,\n confidence: `${Math.round(matchResult.confidence * 100)}%`,\n incomingContent: todo.content.slice(0, 40),\n matchedContent: previous.content.slice(0, 40),\n });\n }\n\n if (\n matchResult.matchType === \"similar-content\" &&\n matchResult.confidence < TODO_MATCH_THRESHOLDS.AUTO_UPDATE\n ) {\n lowConfidenceSkipped++;\n log.info(\"Low-confidence match skipped (requires explicit completion)\", {\n confidence: `${Math.round(matchResult.confidence * 100)}%`,\n threshold: `${Math.round(TODO_MATCH_THRESHOLDS.AUTO_UPDATE * 100)}%`,\n todoContent: todo.content.slice(0, 50),\n possibleMatch: previous.content.slice(0, 50),\n });\n continue;\n }\n\n const statusChanged = previous.status !== todo.status;\n if (!statusChanged) {\n continue;\n }\n\n log.debug(\"Todo status changed\", {\n matchType: matchResult.matchType,\n from: previous.status,\n to: todo.status,\n });\n\n const storyId = extractStoryIdFromContent(previous.content);\n const parsed = parseTodoId(previous.id);\n\n if (!storyId && !parsed) {\n log.debug(\"Could not determine story ID from matched todo\", {\n todoId: previous.id,\n content: previous.content.slice(0, 50),\n });\n continue;\n }\n\n const targetStoryId = storyId || parsed?.storyId;\n const lineHint = parsed?.lineHint ?? 0;\n\n if (!targetStoryId) {\n log.warn(\"No story ID found for BMAD todo\", {\n todoId: previous.id,\n content: previous.content,\n });\n continue;\n }\n\n try {\n const storyFile = await findStoryFile(paths.storiesDir, targetStoryId);\n if (!storyFile) {\n log.warn(\"Story file not found for BMAD todo\", {\n storyId: targetStoryId,\n storiesDir: paths.storiesDir,\n });\n continue;\n }\n\n const lineNumber = await findCheckboxLine(storyFile.path, previous.content, lineHint);\n\n if (lineNumber === null) {\n log.warn(\"Checkbox not found in BMAD file\", {\n storyPath: storyFile.path,\n content: previous.content.slice(0, 50),\n lineHint,\n });\n continue;\n }\n\n const checked = todo.status === \"completed\";\n const wasUpdated = await updateBmadCheckbox(storyFile.path, lineNumber, checked);\n\n if (wasUpdated) {\n updated++;\n log.info(\"Updated BMAD checkbox\", {\n storyId: targetStoryId,\n line: lineNumber,\n checked,\n matchType: matchResult.matchType,\n content: previous.content.slice(0, 50),\n });\n } else {\n log.warn(\"Failed to update checkbox\", {\n storyId: targetStoryId,\n line: lineNumber,\n });\n }\n } catch (error) {\n log.warn(\"Error updating BMAD checkbox\", {\n storyId: targetStoryId,\n error: String(error),\n });\n }\n }\n\n log.debug(\"BMAD sync complete\", {\n processed,\n matchedById,\n matchedByContent,\n lowConfidenceSkipped,\n checkboxesUpdated: updated,\n });\n\n await tracker.setCurrentTodos(todos);\n}\n","/**\n * Tool execution hooks\n *\n * Implements safety net warnings for git operations and BMAD todo synchronization.\n */\n\nimport type { PluginInput } from \"@opencode-ai/plugin\";\nimport type { AthenaConfig, OpenCodeTodo } from \"../../shared/types.js\";\nimport type { StoryTracker } from \"../tracker/story-tracker.js\";\nimport { getBmadPaths } from \"../utils/bmad-finder.js\";\nimport { createPluginLogger } from \"../utils/plugin-logger.js\";\nimport { onStoryLoaded, onTodoWritten } from \"./todo-hooks.js\";\n\nconst log = createPluginLogger(\"tool-hooks\");\n\ninterface BeforeHookInput {\n tool: string;\n sessionID: string;\n callID: string;\n}\n\ninterface BeforeHookOutput {\n args: unknown;\n}\n\ninterface AfterHookInput {\n tool: string;\n sessionID: string;\n callID: string;\n}\n\ninterface AfterHookOutput {\n title: string;\n output: string;\n metadata: unknown;\n}\n\n/**\n * Git write operations that modify repository state.\n * These require explicit user permission when autoGitOperations is disabled.\n */\nconst GIT_WRITE_COMMANDS = [\n \"git commit\",\n \"git push\",\n \"git checkout -b\",\n \"git branch \",\n \"git switch -c\",\n \"git switch --create\",\n \"git merge\",\n \"git rebase\",\n \"git cherry-pick\",\n \"git stash\",\n \"git tag\",\n \"git reset\",\n \"gh pr create\",\n \"gh pr edit\",\n \"gh pr merge\",\n \"gh pr close\",\n \"gh pr review\",\n \"gh issue create\",\n \"gh issue edit\",\n \"gh issue close\",\n \"gh release create\",\n \"gh release edit\",\n \"gh release delete\",\n];\n\nfunction getBashCommand(metadata: unknown): string {\n if (!metadata || typeof metadata !== \"object\") {\n return \"\";\n }\n\n const cmd = (metadata as Record<string, unknown>).command;\n return typeof cmd === \"string\" ? cmd : \"\";\n}\n\nfunction containsGitWriteCommand(command: string): boolean {\n const normalized = command.trim().toLowerCase();\n\n // Split by common shell separators to check each command segment\n // This prevents false positives from strings like: echo \"git commit\"\n const segments = normalized.split(/[;&|]+/).map((s) => s.trim());\n\n return segments.some((segment) =>\n GIT_WRITE_COMMANDS.some((gitCmd) => segment.startsWith(gitCmd.toLowerCase()))\n );\n}\n\nexport function createToolHooks(ctx: PluginInput, tracker: StoryTracker, config: AthenaConfig) {\n return {\n before: async (_input: BeforeHookInput, _output: BeforeHookOutput): Promise<void> => {\n return;\n },\n\n after: async (input: AfterHookInput, output: AfterHookOutput): Promise<void> => {\n if (!config.features.autoGitOperations && input.tool === \"bash\") {\n const command = getBashCommand(output.metadata);\n\n if (containsGitWriteCommand(command)) {\n log.warn(\"Git write operation detected\", { command: command.slice(0, 100) });\n output.output +=\n \"\\n\\n⚠️ ATHENA GIT OPERATIONS POLICY REMINDER:\\n\" +\n \"Git operations should only be performed when explicitly requested by the user.\\n\" +\n \"If this command was run automatically (not requested by the user), please:\\n\" +\n \"1. Ask the user before proceeding with further git operations\\n\" +\n \"2. Use athena_update_status() to track story progress instead of git commits\\n\" +\n \"\\n\" +\n \"To enable automatic git operations, set features.autoGitOperations=true in athena.json\";\n }\n }\n\n if (input.tool === \"athena_get_story\" && config.features.todoSync) {\n await handleStoryLoaded(ctx, tracker, config, input.sessionID, output);\n }\n\n if (input.tool === \"todowrite\" && config.features.todoSync) {\n await handleTodoWritten(ctx, tracker, config, output);\n }\n },\n };\n}\n\nasync function handleStoryLoaded(\n ctx: PluginInput,\n tracker: StoryTracker,\n config: AthenaConfig,\n sessionID: string,\n output: AfterHookOutput\n): Promise<void> {\n try {\n const result = JSON.parse(output.output);\n if (!result.storyId || !result.story) {\n log.debug(\"Story load response missing storyId or story content\");\n return;\n }\n\n log.debug(\"Processing story load for todo sync\", { storyId: result.storyId });\n\n const { newBmadTodos, mergedTodos } = await onStoryLoaded(\n tracker,\n config,\n result.storyId,\n result.story\n );\n\n if (newBmadTodos.length > 0) {\n result.todos = {\n hint: \"Call todowrite with these todos to populate your task list. Marking todos complete updates BMAD checkboxes automatically.\",\n items: newBmadTodos,\n };\n output.output = JSON.stringify(result, null, 2);\n\n log.debug(\"Injected BMAD todos into story response\", {\n storyId: result.storyId,\n newTodos: newBmadTodos.length,\n totalTracked: mergedTodos.length,\n });\n\n await autoInjectTodos(ctx, sessionID, newBmadTodos);\n } else {\n log.debug(\"No BMAD todos found in story\", { storyId: result.storyId });\n }\n } catch (error) {\n log.warn(\"Failed to process story for todo sync\", { error: String(error) });\n }\n}\n\nasync function autoInjectTodos(\n ctx: PluginInput,\n sessionID: string,\n todos: OpenCodeTodo[]\n): Promise<void> {\n const client = ctx.client as unknown as Record<string, unknown> | undefined;\n const session = client?.session as Record<string, unknown> | undefined;\n const updateFn = session?.update as ((args: unknown) => Promise<unknown>) | undefined;\n\n if (!updateFn) {\n log.debug(\"OpenCode client session.update API not available\");\n return;\n }\n\n try {\n await updateFn({\n path: { id: sessionID },\n body: {\n update: {\n sessionUpdate: \"plan\",\n entries: todos.map((todo) => ({\n priority: todo.priority || \"medium\",\n status: todo.status === \"cancelled\" ? \"completed\" : todo.status,\n content: todo.content,\n })),\n },\n },\n });\n\n log.debug(\"Auto-injected BMAD todos via OpenCode API\", { count: todos.length });\n } catch (error) {\n log.debug(\"Could not auto-inject todos (API call failed)\", {\n error: String(error),\n });\n }\n}\n\nasync function handleTodoWritten(\n ctx: PluginInput,\n tracker: StoryTracker,\n config: AthenaConfig,\n output: AfterHookOutput\n): Promise<void> {\n const todos = extractTodosFromOutput(output);\n\n if (!todos || todos.length === 0) {\n log.debug(\"No todos found in todowrite output\");\n return;\n }\n\n try {\n const paths = await getBmadPaths(ctx.directory, config);\n await onTodoWritten(tracker, config, { storiesDir: paths.storiesDir }, todos);\n } catch (error) {\n log.warn(\"Error processing todowrite for BMAD sync\", { error: String(error) });\n }\n}\n\nfunction extractTodosFromOutput(output: AfterHookOutput): OpenCodeTodo[] | null {\n const metadata = output.metadata as Record<string, unknown> | undefined;\n if (metadata?.todos && Array.isArray(metadata.todos)) {\n log.debug(\"Extracted todos from metadata\", { count: metadata.todos.length });\n return metadata.todos as OpenCodeTodo[];\n }\n\n try {\n const result = JSON.parse(output.output);\n if (Array.isArray(result)) {\n log.debug(\"Extracted todos from output (array)\", { count: result.length });\n return result as OpenCodeTodo[];\n }\n if (result?.todos && Array.isArray(result.todos)) {\n log.debug(\"Extracted todos from output.todos\", { count: result.todos.length });\n return result.todos as OpenCodeTodo[];\n }\n } catch {\n log.debug(\"Could not parse output as JSON\");\n }\n\n return null;\n}\n","import type { AthenaConfig } from \"../../shared/types.js\";\nimport type { StoryTracker } from \"../tracker/story-tracker.js\";\nimport { getBmadPaths } from \"../utils/bmad-finder.js\";\nimport { isBmadTodo } from \"../utils/todo-sync.js\";\n\ninterface CompactionInput {\n sessionID: string;\n}\n\ninterface CompactionOutput {\n context: string[];\n}\n\nexport function createCompactionHook(\n tracker: StoryTracker,\n config: AthenaConfig,\n projectDirectory: string\n) {\n return async (_input: CompactionInput, output: CompactionOutput): Promise<void> => {\n // Dynamically resolve BMAD paths to support both legacy and v6-alpha structures\n const paths = await getBmadPaths(projectDirectory, config);\n const storiesPath = paths.storiesDir || \"docs/stories\";\n\n const storyContext = await tracker.getCurrentStoryContext();\n const todos = tracker.getCurrentTodos();\n const currentStory = tracker.getCurrentStory();\n\n const parts: string[] = [];\n\n if (todos && todos.length > 0) {\n const bmadTodos = todos.filter((t) => isBmadTodo(t));\n const pending = bmadTodos.filter((t) => t.status === \"pending\");\n const inProgress = bmadTodos.filter((t) => t.status === \"in_progress\");\n\n if (bmadTodos.length > 0 && (pending.length > 0 || inProgress.length > 0)) {\n parts.push(\"## ⚠️ MANDATORY POST-COMPACTION PROTOCOL\");\n parts.push(\"\");\n parts.push(\"**STOP. Before doing ANYTHING else:**\");\n parts.push(\"1. Call `todoread` to get your current task list\");\n parts.push(\"2. Review the todos below and compare to any 'next steps' you see\");\n parts.push(\"3. If any todo is marked `in_progress`, complete it FIRST\");\n parts.push(\"4. The TODO LIST is your source of truth, not the compaction summary\");\n parts.push(\"\");\n\n // Show in-progress todos with prominent warning\n if (inProgress.length > 0) {\n parts.push(\"### 🔄 IN PROGRESS (Complete these FIRST):\");\n for (const todo of inProgress) {\n parts.push(`- ${todo.content}`);\n }\n parts.push(\"\");\n }\n\n // Show pending todos (top 10 by priority)\n if (pending.length > 0) {\n parts.push(\"### ⏳ PENDING (Work queue):\");\n const sortedPending = pending.sort((a, b) => {\n const priorityOrder = { high: 0, medium: 1, low: 2 };\n return priorityOrder[a.priority] - priorityOrder[b.priority];\n });\n\n const todosToShow = sortedPending.slice(0, 10);\n for (const todo of todosToShow) {\n const icon = todo.priority === \"high\" ? \"🔴\" : todo.priority === \"medium\" ? \"🟡\" : \"🟢\";\n parts.push(`${icon} ${todo.content}`);\n }\n\n if (pending.length > 10) {\n parts.push(` ... and ${pending.length - 10} more (call todoread for full list)`);\n }\n parts.push(\"\");\n }\n\n // Verification step\n parts.push(\"### ✅ VERIFICATION REQUIRED\");\n parts.push(\"Call `todoread` NOW to confirm this matches your working state.\");\n parts.push(\n \"If it doesn't match, the todo list takes priority over any 'next steps' in this summary.\"\n );\n parts.push(\"\");\n parts.push(\"---\");\n parts.push(\"\");\n }\n }\n\n // STORY CONTEXT (comes after todo protocol)\n if (storyContext) {\n parts.push(\"## OpenCode Athena - Current BMAD Story Context\");\n parts.push(\"\");\n parts.push(storyContext);\n if (currentStory) {\n const storyFileName = `story-${currentStory.id.replace(\".\", \"-\")}.md`;\n parts.push(`**File:** ${storiesPath}/${storyFileName}`);\n }\n parts.push(\"\");\n }\n\n // TODO SYNC DOCUMENTATION (how it works)\n if (todos && todos.length > 0) {\n const bmadTodos = todos.filter((t) => isBmadTodo(t));\n const pending = bmadTodos.filter((t) => t.status === \"pending\").length;\n const inProgress = bmadTodos.filter((t) => t.status === \"in_progress\").length;\n const completed = bmadTodos.filter((t) => t.status === \"completed\").length;\n\n if (bmadTodos.length > 0) {\n parts.push(\"## Todo Sync (BMAD ↔ Todos)\");\n parts.push(\"\");\n parts.push(`**Progress:** ${completed}/${bmadTodos.length} BMAD tasks complete`);\n parts.push(`**Remaining:** ${pending} pending, ${inProgress} in progress`);\n parts.push(\"\");\n parts.push(\"**How todos work:**\");\n parts.push(\"- Format: `[{storyId}Δ{section}] {task}`\");\n parts.push(\"- Marking a todo complete updates the BMAD file automatically\");\n parts.push(\"- For task details, read the story file\");\n parts.push(\"\");\n if (currentStory) {\n const storyFileName = `story-${currentStory.id.replace(\".\", \"-\")}.md`;\n parts.push(\"**To look up task context:**\");\n parts.push(\"```\");\n parts.push(`Read ${storiesPath}/${storyFileName}`);\n parts.push(\"```\");\n parts.push(\"\");\n }\n }\n }\n\n if (storyContext || (todos && todos.length > 0)) {\n parts.push(\n \"IMPORTANT: You are implementing a BMAD story. Use athena_get_story to reload full context if needed. Use athena_update_status to update the story status when complete.\"\n );\n parts.push(\"\");\n\n output.context.push(parts.join(\"\\n\"));\n }\n };\n}\n","import type {\n ComplexityRecommendation,\n ComplexityThresholds,\n ParsedTask,\n StoryComplexityAssessment,\n StoryMetrics,\n TaskEffortEstimate,\n TaskEffortLevel,\n} from \"../../shared/types.js\";\nimport { DEFAULT_COMPLEXITY_THRESHOLDS } from \"../../shared/types.js\";\nimport type { ParsedStory } from \"./story-parser.js\";\n\nconst HIGH_EFFORT_KEYWORDS = [\n \"implement\",\n \"create\",\n \"integrate\",\n \"architect\",\n \"design\",\n \"refactor\",\n \"migrate\",\n];\nconst MEDIUM_EFFORT_KEYWORDS = [\"add\", \"update\", \"extend\", \"modify\", \"configure\"];\nconst EXTERNAL_DEPENDENCY_KEYWORDS = [\n \"api\",\n \"endpoint\",\n \"service\",\n \"firebase\",\n \"database\",\n \"auth\",\n \"external\",\n];\nconst TESTING_KEYWORDS = [\"test\", \"integration\", \"e2e\", \"manual\", \"verify\", \"validation\"];\n\nconst VAGUE_PATTERNS = [\n /^(implement|create|add|build)\\s+\\w+$/i,\n /^(task|todo):\\s*\\w+$/i,\n /^(do|make|handle)\\s+.{1,20}$/i,\n];\n\nfunction isVagueDescription(desc: string): boolean {\n if (VAGUE_PATTERNS.some((p) => p.test(desc.trim()))) {\n return true;\n }\n const hasSpecifics = /\\.(ts|js|dart|py|md)|\\/|:\\d+|\\d{2,}/.test(desc);\n return desc.length < 30 && !hasSpecifics;\n}\n\nfunction pointsToEffort(points: number): TaskEffortLevel {\n if (points <= 1) return \"trivial\";\n if (points <= 2) return \"small\";\n if (points <= 3) return \"medium\";\n if (points <= 5) return \"large\";\n return \"xlarge\";\n}\n\nfunction mapToFibonacci(points: number): number {\n const fibScale = [1, 2, 3, 5, 8];\n return fibScale.reduce((prev, curr) =>\n Math.abs(curr - points) < Math.abs(prev - points) ? curr : prev\n );\n}\n\nexport function estimateTaskEffort(task: ParsedTask): TaskEffortEstimate {\n let rawPoints = 1;\n const signals: string[] = [];\n const descLower = task.description.toLowerCase();\n\n if (task.subtasks.length > 5) {\n rawPoints += 3;\n signals.push(`${task.subtasks.length} subtasks (high complexity)`);\n } else if (task.subtasks.length > 2) {\n rawPoints += 1;\n signals.push(`${task.subtasks.length} subtasks`);\n }\n\n if (isVagueDescription(task.description)) {\n rawPoints += 2;\n signals.push(\"Vague description - hidden complexity likely\");\n }\n\n if (HIGH_EFFORT_KEYWORDS.some((k) => descLower.includes(k))) {\n rawPoints += 2;\n signals.push(\"High-effort action keyword\");\n } else if (MEDIUM_EFFORT_KEYWORDS.some((k) => descLower.includes(k))) {\n rawPoints += 1;\n signals.push(\"Medium-effort action keyword\");\n }\n\n if (TESTING_KEYWORDS.some((k) => descLower.includes(k))) {\n rawPoints += 1;\n signals.push(\"Testing/verification required\");\n }\n\n if (task.subtasks.some((s) => s.description.includes(\"/\"))) {\n rawPoints += 1;\n signals.push(\"Multiple file paths mentioned\");\n }\n\n if (EXTERNAL_DEPENDENCY_KEYWORDS.some((k) => descLower.includes(k))) {\n rawPoints += 1;\n signals.push(\"External system integration\");\n }\n\n const points = mapToFibonacci(rawPoints);\n\n return {\n taskId: task.id,\n description: task.description,\n effort: pointsToEffort(points),\n points,\n signals,\n };\n}\n\nexport function calculateStoryMetrics(\n parsedStory: ParsedStory,\n fileSizeBytes: number\n): StoryMetrics {\n const subtaskCount = parsedStory.tasks.reduce((sum, task) => sum + task.subtasks.length, 0);\n\n return {\n taskCount: parsedStory.tasks.length,\n subtaskCount,\n acceptanceCriteriaCount: parsedStory.acceptanceCriteriaCount,\n storyFileSizeKB: Math.round(fileSizeBytes / 1024),\n lineCount: parsedStory.lineCount,\n };\n}\n\nexport function assessStoryComplexity(\n parsedStory: ParsedStory,\n fileSizeBytes: number,\n thresholds: ComplexityThresholds = DEFAULT_COMPLEXITY_THRESHOLDS\n): StoryComplexityAssessment {\n const metrics = calculateStoryMetrics(parsedStory, fileSizeBytes);\n const taskEfforts = parsedStory.tasks.map(estimateTaskEffort);\n const totalPoints = taskEfforts.reduce((sum, te) => sum + te.points, 0);\n\n const thresholdReasons: string[] = [];\n let requireDecomp = false;\n let suggestDecomp = false;\n\n if (metrics.taskCount >= thresholds.criticalTasks) {\n thresholdReasons.push(\n `Task count (${metrics.taskCount}) exceeds critical limit (${thresholds.criticalTasks})`\n );\n requireDecomp = true;\n } else if (metrics.taskCount >= thresholds.maxTasks) {\n thresholdReasons.push(\n `Task count (${metrics.taskCount}) exceeds recommended limit (${thresholds.maxTasks})`\n );\n suggestDecomp = true;\n }\n\n if (totalPoints >= thresholds.criticalPoints) {\n thresholdReasons.push(\n `Story points (${totalPoints}) exceed critical limit (${thresholds.criticalPoints})`\n );\n requireDecomp = true;\n } else if (totalPoints >= thresholds.maxPoints) {\n thresholdReasons.push(\n `Story points (${totalPoints}) exceed recommended limit (${thresholds.maxPoints})`\n );\n suggestDecomp = true;\n }\n\n if (metrics.storyFileSizeKB >= thresholds.criticalFileSizeKB) {\n thresholdReasons.push(\n `File size (${metrics.storyFileSizeKB}KB) exceeds critical limit (${thresholds.criticalFileSizeKB}KB)`\n );\n requireDecomp = true;\n } else if (metrics.storyFileSizeKB >= thresholds.maxFileSizeKB) {\n thresholdReasons.push(\n `File size (${metrics.storyFileSizeKB}KB) exceeds recommended limit (${thresholds.maxFileSizeKB}KB)`\n );\n suggestDecomp = true;\n }\n\n const recommendation: ComplexityRecommendation = requireDecomp\n ? \"require-decomposition\"\n : suggestDecomp\n ? \"suggest-decomposition\"\n : \"proceed\";\n\n const estimatedCompactions = Math.max(0, Math.floor((totalPoints - 8) / 8));\n\n return {\n storyId: parsedStory.storyId,\n filename: \"\",\n metrics,\n taskEfforts,\n totalPoints,\n exceedsThreshold: thresholdReasons.length > 0,\n thresholdReasons,\n recommendation,\n estimatedCompactions,\n };\n}\n\nexport function formatEffortBar(points: number): string {\n const filled = Math.min(points, 5);\n const empty = 5 - filled;\n return `[${\"■\".repeat(filled)}${\"□\".repeat(empty)}]`;\n}\n\nexport function formatComplexityReport(assessment: StoryComplexityAssessment): string {\n const lines: string[] = [];\n const {\n metrics,\n taskEfforts,\n totalPoints,\n recommendation,\n thresholdReasons,\n estimatedCompactions,\n } = assessment;\n\n const taskStatus = metrics.taskCount >= 12 ? \"🔴\" : metrics.taskCount >= 8 ? \"⚠️\" : \"✅\";\n const pointsStatus = totalPoints >= 13 ? \"🔴\" : totalPoints >= 8 ? \"⚠️\" : \"✅\";\n const sizeStatus =\n metrics.storyFileSizeKB >= 50 ? \"🔴\" : metrics.storyFileSizeKB >= 30 ? \"⚠️\" : \"✅\";\n\n lines.push(\"📊 COMPLEXITY ANALYSIS\");\n lines.push(\"━\".repeat(45));\n lines.push(`Tasks: ${metrics.taskCount} / 8 recommended ${taskStatus}`);\n lines.push(`Points: ${totalPoints} / 8 threshold ${pointsStatus}`);\n lines.push(`File size: ${metrics.storyFileSizeKB}KB / 30KB ${sizeStatus}`);\n lines.push(`Estimated compactions: ${estimatedCompactions}`);\n lines.push(\"\");\n\n lines.push(\"📋 TASK EFFORT BREAKDOWN\");\n lines.push(\"━\".repeat(45));\n for (const te of taskEfforts) {\n const desc =\n te.description.length > 35\n ? `${te.description.substring(0, 32)}...`\n : te.description.padEnd(35);\n lines.push(`Task ${te.taskId}: ${desc} ${formatEffortBar(te.points)} ${te.points} pts`);\n if (te.signals.length > 0) {\n lines.push(` └─ Signals: ${te.signals.join(\", \")}`);\n }\n }\n lines.push(`Total: ${totalPoints} story points`);\n lines.push(\"\");\n\n if (recommendation === \"require-decomposition\") {\n lines.push(\"🔴 DECOMPOSITION REQUIRED\");\n lines.push(\" This story exceeds safe implementation limits and will likely\");\n lines.push(\" require multiple context compactions.\");\n } else if (recommendation === \"suggest-decomposition\") {\n lines.push(\"🟡 DECOMPOSITION SUGGESTED\");\n lines.push(\" This story can be implemented but may require compaction.\");\n lines.push(\" Splitting is recommended for cleaner implementation.\");\n } else {\n lines.push(\"🟢 COMPLEXITY OK\");\n lines.push(\" This story is within recommended limits.\");\n }\n\n if (thresholdReasons.length > 0) {\n lines.push(\"\");\n lines.push(\"Threshold issues:\");\n for (const reason of thresholdReasons) {\n lines.push(` • ${reason}`);\n }\n }\n\n return lines.join(\"\\n\");\n}\n","import type { ParsedTask } from \"../../shared/types.js\";\n\nconst TASK_REGEX = /^-\\s*\\[([ xX])\\]\\s*Task\\s*(\\d+):\\s*(.+)$/;\nconst SUBTASK_REGEX = /^(\\s+)-\\s*\\[([ xX])\\]\\s*(\\d+\\.\\d+):\\s*(.+)$/;\nconst SUBTASK_ALT_REGEX = /^(\\s+)-\\s*\\[([ xX])\\]\\s*(.+)$/;\n\nexport interface ParsedStory {\n storyId: string;\n title: string;\n tasks: ParsedTask[];\n acceptanceCriteriaCount: number;\n hasDevNotes: boolean;\n devNotesStartLine: number | null;\n devNotesEndLine: number | null;\n rawContent: string;\n lineCount: number;\n}\n\nfunction isChecked(mark: string): boolean {\n return mark.toLowerCase() === \"x\";\n}\n\nexport function parseStoryTasks(content: string, storyId: string): ParsedStory {\n const lines = content.split(\"\\n\");\n const tasks: ParsedTask[] = [];\n let currentTask: ParsedTask | null = null;\n let subtaskCounter = 0;\n\n let title = \"\";\n const titleMatch = content.match(/^#\\s+(?:Story\\s+[\\d.]+:\\s*)?(.+)$/m);\n if (titleMatch) {\n title = titleMatch[1].trim();\n }\n\n let acceptanceCriteriaCount = 0;\n const acSection = content.match(/##\\s*Acceptance\\s*Criteria[\\s\\S]*?(?=##|$)/i);\n if (acSection) {\n const givenMatches = acSection[0].match(/\\*\\*Given\\*\\*/gi);\n acceptanceCriteriaCount = givenMatches ? givenMatches.length : 0;\n }\n\n let hasDevNotes = false;\n let devNotesStartLine: number | null = null;\n let devNotesEndLine: number | null = null;\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n const lineNumber = i + 1;\n\n if (/^##\\s*Dev\\s*Notes/i.test(line)) {\n hasDevNotes = true;\n devNotesStartLine = lineNumber;\n for (let j = i + 1; j < lines.length; j++) {\n if (/^##\\s+/.test(lines[j]) && !/^##\\s*Dev\\s*Notes/i.test(lines[j])) {\n devNotesEndLine = j;\n break;\n }\n }\n if (devNotesEndLine === null) {\n devNotesEndLine = lines.length;\n }\n }\n\n const taskMatch = line.match(TASK_REGEX);\n if (taskMatch) {\n if (currentTask) {\n tasks.push(currentTask);\n }\n currentTask = {\n id: taskMatch[2],\n description: taskMatch[3].trim(),\n subtasks: [],\n completed: isChecked(taskMatch[1]),\n lineNumber,\n };\n subtaskCounter = 0;\n continue;\n }\n\n if (currentTask) {\n const subtaskMatch = line.match(SUBTASK_REGEX);\n if (subtaskMatch) {\n currentTask.subtasks.push({\n id: subtaskMatch[3],\n description: subtaskMatch[4].trim(),\n completed: isChecked(subtaskMatch[2]),\n lineNumber,\n });\n continue;\n }\n\n const altSubtaskMatch = line.match(SUBTASK_ALT_REGEX);\n if (altSubtaskMatch && altSubtaskMatch[1].length >= 2) {\n subtaskCounter++;\n currentTask.subtasks.push({\n id: `${currentTask.id}.${subtaskCounter}`,\n description: altSubtaskMatch[3].trim(),\n completed: isChecked(altSubtaskMatch[2]),\n lineNumber,\n });\n continue;\n }\n\n if (/^-\\s*\\[/.test(line) && !/^\\s+-/.test(line)) {\n tasks.push(currentTask);\n currentTask = null;\n }\n }\n }\n\n if (currentTask) {\n tasks.push(currentTask);\n }\n\n return {\n storyId,\n title,\n tasks,\n acceptanceCriteriaCount,\n hasDevNotes,\n devNotesStartLine,\n devNotesEndLine,\n rawContent: content,\n lineCount: lines.length,\n };\n}\n\nexport function extractDevNotesForTasks(content: string, taskIds: string[]): string {\n const lines = content.split(\"\\n\");\n const relevantSections: string[] = [];\n\n let inDevNotes = false;\n let currentSection: string[] = [];\n let currentSectionHeader = \"\";\n\n for (const line of lines) {\n if (/^##\\s*Dev\\s*Notes/i.test(line)) {\n inDevNotes = true;\n continue;\n }\n\n if (inDevNotes) {\n if (/^##\\s+/.test(line) && !/^###/.test(line)) {\n inDevNotes = false;\n if (currentSection.length > 0) {\n relevantSections.push(currentSection.join(\"\\n\"));\n }\n break;\n }\n\n if (/^###\\s+/.test(line)) {\n if (currentSection.length > 0 && shouldIncludeSection(currentSectionHeader, taskIds)) {\n relevantSections.push(currentSection.join(\"\\n\"));\n }\n currentSection = [line];\n currentSectionHeader = line;\n } else if (currentSection.length > 0 || line.trim()) {\n currentSection.push(line);\n }\n }\n }\n\n if (currentSection.length > 0 && shouldIncludeSection(currentSectionHeader, taskIds)) {\n relevantSections.push(currentSection.join(\"\\n\"));\n }\n\n const commonSections = extractCommonDevNotes(content);\n const combined = [...commonSections, ...relevantSections].filter(Boolean);\n\n return combined.length > 0 ? `## Dev Notes\\n\\n${combined.join(\"\\n\\n\")}` : \"\";\n}\n\nfunction shouldIncludeSection(header: string, taskIds: string[]): boolean {\n const commonPatterns = [\n /complexity/i,\n /architecture/i,\n /technical.*requirement/i,\n /library.*framework/i,\n /file.*structure/i,\n /testing.*requirement/i,\n /previous.*story/i,\n /project.*context/i,\n /feature.*context/i,\n /reference/i,\n ];\n\n if (commonPatterns.some((p) => p.test(header))) {\n return true;\n }\n\n for (const taskId of taskIds) {\n if (header.includes(`Task ${taskId}`) || header.includes(`Task${taskId}`)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction extractCommonDevNotes(content: string): string[] {\n const sections: string[] = [];\n const lines = content.split(\"\\n\");\n\n let inDevNotes = false;\n let currentSection: string[] = [];\n let currentHeader = \"\";\n\n const commonHeaders = [\n /complexity.*assessment/i,\n /manual.*testing/i,\n /pre-existing.*code/i,\n /architecture.*compliance/i,\n /technical.*requirement/i,\n /library.*framework/i,\n /file.*structure/i,\n /testing.*requirement/i,\n /previous.*story/i,\n /project.*context/i,\n /feature.*context/i,\n /reference/i,\n ];\n\n for (const line of lines) {\n if (/^##\\s*Dev\\s*Notes/i.test(line)) {\n inDevNotes = true;\n continue;\n }\n\n if (inDevNotes) {\n if (/^##\\s+/.test(line) && !/^###/.test(line)) {\n if (currentSection.length > 0 && commonHeaders.some((p) => p.test(currentHeader))) {\n sections.push(currentSection.join(\"\\n\"));\n }\n break;\n }\n\n if (/^###\\s+/.test(line)) {\n if (currentSection.length > 0 && commonHeaders.some((p) => p.test(currentHeader))) {\n sections.push(currentSection.join(\"\\n\"));\n }\n currentSection = [line];\n currentHeader = line;\n } else if (currentSection.length > 0 || line.trim()) {\n currentSection.push(line);\n }\n }\n }\n\n if (currentSection.length > 0 && commonHeaders.some((p) => p.test(currentHeader))) {\n sections.push(currentSection.join(\"\\n\"));\n }\n\n return sections;\n}\n\nexport function generateTaskSection(tasks: ParsedTask[]): string {\n const lines: string[] = [\"## Tasks / Subtasks\", \"\"];\n\n for (const task of tasks) {\n const checkbox = task.completed ? \"[x]\" : \"[ ]\";\n lines.push(`- ${checkbox} Task ${task.id}: ${task.description}`);\n\n for (const subtask of task.subtasks) {\n const subCheckbox = subtask.completed ? \"[x]\" : \"[ ]\";\n lines.push(` - ${subCheckbox} ${subtask.id}: ${subtask.description}`);\n }\n\n lines.push(\"\");\n }\n\n return lines.join(\"\\n\");\n}\n","import type {\n DecompositionSplit,\n ParsedTask,\n TaskEffortEstimate,\n UserSplitConfig,\n} from \"../../shared/types.js\";\nimport type { ParsedStory } from \"./story-parser.js\";\nimport { extractDevNotesForTasks, generateTaskSection } from \"./story-parser.js\";\n\nconst TARGET_POINTS_PER_SPLIT = 8;\nconst MAX_TASKS_PER_SPLIT = 6;\n\ninterface TaskWithEffort {\n task: ParsedTask;\n effort: TaskEffortEstimate;\n}\n\nexport function generateDecompositionSuggestions(\n parsedStory: ParsedStory,\n taskEfforts: TaskEffortEstimate[]\n): DecompositionSplit[] {\n const tasksWithEffort: TaskWithEffort[] = parsedStory.tasks.map((task) => ({\n task,\n effort: taskEfforts.find((e) => e.taskId === task.id) || {\n taskId: task.id,\n description: task.description,\n effort: \"medium\" as const,\n points: 3,\n signals: [],\n },\n }));\n\n const groups = groupTasksByConcern(tasksWithEffort);\n const balanced = balanceGroups(groups, TARGET_POINTS_PER_SPLIT);\n const withDeps = analyzeDependencies(balanced);\n\n return withDeps.map((group, index) => ({\n suffix: String.fromCharCode(97 + index),\n title: inferGroupTitle(group.tasks),\n taskIds: group.tasks.map((t) => t.task.id),\n estimatedPoints: group.totalPoints,\n rationale: group.rationale,\n dependencies: group.dependencies,\n }));\n}\n\ninterface TaskGroup {\n tasks: TaskWithEffort[];\n totalPoints: number;\n rationale: string;\n dependencies: string[];\n}\n\nfunction groupTasksByConcern(tasks: TaskWithEffort[]): TaskGroup[] {\n const testingTasks: TaskWithEffort[] = [];\n const uiTasks: TaskWithEffort[] = [];\n const integrationTasks: TaskWithEffort[] = [];\n const coreTasks: TaskWithEffort[] = [];\n\n for (const t of tasks) {\n const desc = t.task.description.toLowerCase();\n if (/test|verify|integration test|e2e|manual test/.test(desc)) {\n testingTasks.push(t);\n } else if (/widget|screen|card|component|ui|view|button|dialog/.test(desc)) {\n uiTasks.push(t);\n } else if (/navigation|route|integration|connect|hook up/.test(desc)) {\n integrationTasks.push(t);\n } else {\n coreTasks.push(t);\n }\n }\n\n const groups: TaskGroup[] = [];\n\n if (coreTasks.length > 0) {\n groups.push({\n tasks: coreTasks,\n totalPoints: coreTasks.reduce((s, t) => s + t.effort.points, 0),\n rationale: \"Core implementation tasks\",\n dependencies: [],\n });\n }\n\n if (uiTasks.length > 0) {\n groups.push({\n tasks: uiTasks,\n totalPoints: uiTasks.reduce((s, t) => s + t.effort.points, 0),\n rationale: \"UI component tasks\",\n dependencies: [],\n });\n }\n\n if (integrationTasks.length > 0) {\n groups.push({\n tasks: integrationTasks,\n totalPoints: integrationTasks.reduce((s, t) => s + t.effort.points, 0),\n rationale: \"Integration and wiring tasks\",\n dependencies: [],\n });\n }\n\n if (testingTasks.length > 0) {\n groups.push({\n tasks: testingTasks,\n totalPoints: testingTasks.reduce((s, t) => s + t.effort.points, 0),\n rationale: \"Testing and verification tasks\",\n dependencies: [],\n });\n }\n\n if (groups.length === 0 && tasks.length > 0) {\n return balanceByPoints(tasks, TARGET_POINTS_PER_SPLIT);\n }\n\n return groups;\n}\n\nfunction balanceGroups(groups: TaskGroup[], targetPoints: number): TaskGroup[] {\n const result: TaskGroup[] = [];\n\n for (const group of groups) {\n if (group.totalPoints <= targetPoints && group.tasks.length <= MAX_TASKS_PER_SPLIT) {\n result.push(group);\n } else {\n const subGroups = balanceByPoints(group.tasks, targetPoints);\n for (let i = 0; i < subGroups.length; i++) {\n result.push({\n ...subGroups[i],\n rationale: `${group.rationale} (part ${i + 1})`,\n });\n }\n }\n }\n\n return result;\n}\n\nfunction balanceByPoints(tasks: TaskWithEffort[], targetPoints: number): TaskGroup[] {\n const groups: TaskGroup[] = [];\n let currentGroup: TaskWithEffort[] = [];\n let currentPoints = 0;\n\n const sortedTasks = [...tasks].sort((a, b) => {\n const aNum = Number.parseInt(a.task.id, 10);\n const bNum = Number.parseInt(b.task.id, 10);\n return aNum - bNum;\n });\n\n for (const task of sortedTasks) {\n if (\n currentPoints + task.effort.points > targetPoints &&\n currentGroup.length > 0 &&\n currentGroup.length < MAX_TASKS_PER_SPLIT\n ) {\n groups.push({\n tasks: currentGroup,\n totalPoints: currentPoints,\n rationale: \"Balanced by effort\",\n dependencies: [],\n });\n currentGroup = [];\n currentPoints = 0;\n }\n\n currentGroup.push(task);\n currentPoints += task.effort.points;\n\n if (currentGroup.length >= MAX_TASKS_PER_SPLIT) {\n groups.push({\n tasks: currentGroup,\n totalPoints: currentPoints,\n rationale: \"Balanced by effort\",\n dependencies: [],\n });\n currentGroup = [];\n currentPoints = 0;\n }\n }\n\n if (currentGroup.length > 0) {\n groups.push({\n tasks: currentGroup,\n totalPoints: currentPoints,\n rationale: \"Balanced by effort\",\n dependencies: [],\n });\n }\n\n return groups;\n}\n\nfunction analyzeDependencies(groups: TaskGroup[]): TaskGroup[] {\n if (groups.length <= 1) return groups;\n\n const result = groups.map((g, i) => ({\n ...g,\n dependencies: [] as string[],\n index: i,\n }));\n\n for (let i = 1; i < result.length; i++) {\n const group = result[i];\n const hasTestingOrIntegration = group.tasks.some((t) => {\n const desc = t.task.description.toLowerCase();\n return /test|integration|verify|navigation|route|hook/.test(desc);\n });\n\n if (hasTestingOrIntegration) {\n for (let j = 0; j < i; j++) {\n group.dependencies.push(String.fromCharCode(97 + j));\n }\n }\n }\n\n return result;\n}\n\nfunction inferGroupTitle(tasks: TaskWithEffort[]): string {\n if (tasks.length === 0) return \"Empty Group\";\n\n const firstTask = tasks[0].task.description;\n const commonKeywords = extractKeywords(tasks.map((t) => t.task.description));\n\n if (commonKeywords.length > 0) {\n return commonKeywords.slice(0, 3).join(\" \");\n }\n\n const truncated = firstTask.length > 40 ? `${firstTask.substring(0, 37)}...` : firstTask;\n return truncated;\n}\n\nfunction extractKeywords(descriptions: string[]): string[] {\n const stopWords = new Set([\n \"the\",\n \"a\",\n \"an\",\n \"and\",\n \"or\",\n \"for\",\n \"to\",\n \"in\",\n \"on\",\n \"with\",\n \"task\",\n \"create\",\n \"add\",\n \"implement\",\n \"update\",\n ]);\n\n const wordCounts = new Map<string, number>();\n\n for (const desc of descriptions) {\n const words = desc.toLowerCase().split(/\\s+/);\n const seen = new Set<string>();\n for (const word of words) {\n const clean = word.replace(/[^a-z]/g, \"\");\n if (clean.length > 2 && !stopWords.has(clean) && !seen.has(clean)) {\n seen.add(clean);\n wordCounts.set(clean, (wordCounts.get(clean) || 0) + 1);\n }\n }\n }\n\n const sorted = [...wordCounts.entries()]\n .filter(([, count]) => count >= Math.ceil(descriptions.length / 2))\n .sort((a, b) => b[1] - a[1])\n .map(([word]) => word);\n\n return sorted;\n}\n\nexport function validateSplits(\n originalTasks: ParsedTask[],\n splits: UserSplitConfig[] | DecompositionSplit[]\n): { valid: boolean; missingTasks: string[]; duplicatedTasks: string[] } {\n const allSplitTaskIds = new Set<string>();\n const duplicated: string[] = [];\n\n for (const split of splits) {\n for (const taskId of split.taskIds) {\n if (allSplitTaskIds.has(taskId)) {\n duplicated.push(taskId);\n }\n allSplitTaskIds.add(taskId);\n }\n }\n\n const originalTaskIds = new Set(originalTasks.map((t) => t.id));\n const missing = [...originalTaskIds].filter((id) => !allSplitTaskIds.has(id));\n\n return {\n valid: missing.length === 0 && duplicated.length === 0,\n missingTasks: missing,\n duplicatedTasks: duplicated,\n };\n}\n\nexport function generateSubStoryContent(\n originalContent: string,\n parsedStory: ParsedStory,\n split: DecompositionSplit | UserSplitConfig,\n splitIndex: number,\n totalSplits: number,\n originalStoryId: string\n): string {\n const tasksForSplit = parsedStory.tasks.filter((t) => split.taskIds.includes(t.id));\n const devNotes = extractDevNotesForTasks(originalContent, split.taskIds);\n const taskSection = generateTaskSection(tasksForSplit);\n\n const suffix = \"suffix\" in split ? split.suffix : String.fromCharCode(97 + splitIndex);\n const title =\n \"title\" in split && split.title\n ? split.title\n : inferGroupTitle(\n tasksForSplit.map((t) => ({\n task: t,\n effort: {\n taskId: t.id,\n description: t.description,\n effort: \"medium\" as const,\n points: 3,\n signals: [],\n },\n }))\n );\n\n const storyMatch = originalContent.match(/^#\\s+(?:Story\\s+[\\d.]+:\\s*)?(.+)$/m);\n const originalTitle = storyMatch ? storyMatch[1].trim() : \"Untitled Story\";\n\n const statusMatch = originalContent.match(/^Status:\\s*(.+)$/m);\n const status = statusMatch ? statusMatch[1].trim() : \"ready-for-dev\";\n\n const storyUserSection = originalContent.match(\n /##\\s*Story[\\s\\S]*?(?=##\\s*Acceptance|##\\s*Tasks|$)/i\n );\n const userStory = storyUserSection ? storyUserSection[0].trim() : \"\";\n\n const acSection = originalContent.match(\n /##\\s*Acceptance\\s*Criteria[\\s\\S]*?(?=##\\s*Tasks|##\\s*Dev|$)/i\n );\n const acceptanceCriteria = acSection ? acSection[0].trim() : \"\";\n\n const lines: string[] = [\n `# Story ${originalStoryId}${suffix}: ${originalTitle} - ${title}`,\n \"\",\n `Status: ${status === \"done\" ? \"ready-for-dev\" : status}`,\n \"\",\n `> **Note:** This story was decomposed from Story ${originalStoryId} (part ${splitIndex + 1} of ${totalSplits})`,\n \"\",\n ];\n\n if (userStory) {\n lines.push(userStory);\n lines.push(\"\");\n }\n\n if (acceptanceCriteria) {\n lines.push(acceptanceCriteria);\n lines.push(\"\");\n }\n\n lines.push(taskSection);\n\n if (devNotes) {\n lines.push(\"\");\n lines.push(devNotes);\n }\n\n return lines.join(\"\\n\");\n}\n\nexport function formatDecompositionSuggestion(\n splits: DecompositionSplit[],\n storyId: string\n): string {\n const lines: string[] = [];\n\n lines.push(\"🔀 SUGGESTED DECOMPOSITION\");\n lines.push(\"━\".repeat(45));\n lines.push(\"\");\n\n for (const split of splits) {\n lines.push(`Story ${storyId}${split.suffix}: ${split.title}`);\n lines.push(`├─ Tasks: ${split.taskIds.join(\", \")}`);\n lines.push(`├─ Points: ~${split.estimatedPoints}`);\n lines.push(`├─ Rationale: ${split.rationale}`);\n if (split.dependencies.length > 0) {\n lines.push(`└─ Dependencies: ${split.dependencies.map((d) => `${storyId}${d}`).join(\", \")}`);\n } else {\n lines.push(\"└─ Dependencies: None\");\n }\n lines.push(\"\");\n }\n\n const totalTasks = splits.reduce((sum, s) => sum + s.taskIds.length, 0);\n lines.push(\"VERIFICATION:\");\n lines.push(`✅ All ${totalTasks} tasks accounted for`);\n lines.push(\"✅ No duplicate tasks\");\n lines.push(\"✅ Dependencies correctly ordered\");\n\n return lines.join(\"\\n\");\n}\n\nexport function getSubStoryFilename(originalFilename: string, suffix: string): string {\n const match = originalFilename.match(/^(\\d+-\\d+)(-.*)?\\.md$/);\n if (match) {\n const storyPart = match[1];\n const titlePart = match[2] || \"\";\n return `${storyPart}${suffix}${titlePart}.md`;\n }\n const noExt = originalFilename.replace(/\\.md$/, \"\");\n return `${noExt}${suffix}.md`;\n}\n\nexport function getSubStoryId(originalStoryId: string, suffix: string): string {\n return `${originalStoryId}${suffix}`;\n}\n","import * as fs from \"node:fs/promises\";\nimport { type ToolDefinition, tool } from \"@opencode-ai/plugin\";\nimport type { PluginInput } from \"@opencode-ai/plugin\";\nimport type { AnalyzeStoryResult, AthenaConfig } from \"../../shared/types.js\";\nimport { getBmadPaths } from \"../utils/bmad-finder.js\";\nimport { createPluginLogger } from \"../utils/plugin-logger.js\";\nimport { assessStoryComplexity, formatComplexityReport } from \"../utils/story-complexity.js\";\nimport {\n formatDecompositionSuggestion,\n generateDecompositionSuggestions,\n} from \"../utils/story-decomposer.js\";\nimport { normalizeStoryId, resolveStoryIdentifier, stripAtPrefix } from \"../utils/story-loader.js\";\nimport { parseStoryTasks } from \"../utils/story-parser.js\";\n\nconst log = createPluginLogger(\"analyze-story\");\n\nexport function createAnalyzeStoryTool(ctx: PluginInput, config: AthenaConfig): ToolDefinition {\n return tool({\n description: `Analyze a BMAD story's complexity and suggest decomposition if needed.\n\nReturns:\n- Story metrics (task count, subtasks, file size)\n- Task-level effort estimates with signals\n- Total story points\n- Recommendation: proceed, suggest-decomposition, or require-decomposition\n- Suggested splits if decomposition is recommended\n\nUse this tool before implementing large stories to check if they should be split.`,\n\n args: {\n storyId: tool.schema.string().describe(\"Story ID (e.g., '3.2') or file path to analyze\"),\n },\n\n async execute(args): Promise<string> {\n const result = await analyzeStoryComplexity(ctx, config, args.storyId);\n\n if (!result.success) {\n return JSON.stringify(result, null, 2);\n }\n\n const lines: string[] = [];\n lines.push(formatComplexityReport(result.assessment));\n\n if (result.suggestedSplits && result.suggestedSplits.length > 0) {\n lines.push(\"\");\n lines.push(formatDecompositionSuggestion(result.suggestedSplits, result.storyId));\n lines.push(\"\");\n lines.push(\"What would you like to do?\");\n lines.push(\"[D] Decompose into sub-stories\");\n lines.push(\"[P] Proceed with full story anyway\");\n lines.push(\"[M] Modify decomposition groupings\");\n }\n\n return lines.join(\"\\n\");\n },\n });\n}\n\nasync function analyzeStoryComplexity(\n ctx: PluginInput,\n config: AthenaConfig,\n requestedStoryId: string\n): Promise<AnalyzeStoryResult> {\n log.debug(\"Analyzing story complexity\", { requestedStoryId });\n\n const paths = await getBmadPaths(ctx.directory, config);\n if (!paths.storiesDir) {\n return {\n success: false,\n storyId: requestedStoryId,\n filename: \"\",\n assessment: null as unknown as AnalyzeStoryResult[\"assessment\"],\n error: \"No stories directory found\",\n suggestion:\n paths.suggestion ||\n \"Ensure BMAD is set up with a stories directory. Athena supports both legacy (docs/) and v6-alpha (_bmad/ + _bmad-output/) structures.\",\n };\n }\n\n const identifier = stripAtPrefix(requestedStoryId);\n const storyId = normalizeStoryId(identifier);\n\n const resolved = await resolveStoryIdentifier(paths.storiesDir, identifier, ctx.directory);\n if (!resolved) {\n return {\n success: false,\n storyId,\n filename: \"\",\n assessment: null as unknown as AnalyzeStoryResult[\"assessment\"],\n error: `Story not found: ${requestedStoryId}`,\n suggestion: \"Check the story ID or file path and try again.\",\n };\n }\n\n const storyContent = resolved.content;\n const storyFilename = resolved.filename;\n const storyPath = resolved.path;\n\n let fileSizeBytes: number;\n try {\n const stats = await fs.stat(storyPath);\n fileSizeBytes = stats.size;\n } catch {\n fileSizeBytes = Buffer.byteLength(storyContent, \"utf-8\");\n }\n\n const parsedStory = parseStoryTasks(storyContent, storyId);\n const assessment = assessStoryComplexity(parsedStory, fileSizeBytes);\n assessment.filename = storyFilename;\n\n let suggestedSplits: AnalyzeStoryResult[\"suggestedSplits\"];\n\n if (assessment.recommendation !== \"proceed\") {\n suggestedSplits = generateDecompositionSuggestions(parsedStory, assessment.taskEfforts);\n }\n\n log.info(\"Story analysis complete\", {\n storyId,\n taskCount: assessment.metrics.taskCount,\n totalPoints: assessment.totalPoints,\n recommendation: assessment.recommendation,\n suggestedSplits: suggestedSplits?.length || 0,\n });\n\n return {\n success: true,\n storyId,\n filename: storyFilename,\n assessment,\n suggestedSplits,\n };\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\n/**\n * Get version from package.json at runtime.\n * Handles both bundled (dist/) and development (src/) scenarios.\n */\nfunction getPackageVersion(): string {\n try {\n const currentDir = dirname(fileURLToPath(import.meta.url));\n\n const possiblePaths = [\n join(currentDir, \"..\", \"..\", \"package.json\"),\n join(currentDir, \"..\", \"..\", \"..\", \"package.json\"),\n ];\n\n for (const pkgPath of possiblePaths) {\n if (!existsSync(pkgPath)) continue;\n\n const content = readFileSync(pkgPath, \"utf-8\");\n const pkg = JSON.parse(content);\n if (pkg.version) return pkg.version;\n }\n\n return \"0.0.0\";\n } catch (error) {\n if (error instanceof SyntaxError) {\n console.error(\"[opencode-athena] Warning: package.json contains invalid JSON\");\n }\n return \"0.0.0\";\n }\n}\n\n/**\n * Current version of OpenCode Athena\n * Dynamically read from package.json\n */\nexport const VERSION = getPackageVersion();\n\n/**\n * Package name for CLI display\n */\nexport const PACKAGE_NAME = \"opencode-athena\";\n\n/**\n * CLI display name\n */\nexport const DISPLAY_NAME = \"OpenCode Athena\";\n\n/**\n * Tagline for CLI header\n */\nexport const TAGLINE = \"Strategic wisdom meets practical execution\";\n\n/**\n * Configuration paths\n */\nexport const CONFIG_PATHS = {\n /** Global OpenCode config directory */\n globalConfigDir: join(homedir(), \".config\", \"opencode\"),\n\n /** Global Athena config file */\n globalAthenaConfig: join(homedir(), \".config\", \"opencode\", \"athena.json\"),\n\n /** Global OpenCode config file */\n globalOpencodeConfig: join(homedir(), \".config\", \"opencode\", \"opencode.json\"),\n\n /** Global oh-my-opencode config file */\n globalOmoConfig: join(homedir(), \".config\", \"opencode\", \"oh-my-opencode.json\"),\n\n /** Commands directory */\n commandsDir: join(homedir(), \".config\", \"opencode\", \"command\"),\n\n /** Plugin directory */\n pluginDir: join(homedir(), \".config\", \"opencode\", \"plugin\"),\n\n /** Athena internal files directory (state, backups) */\n athenaDir: join(homedir(), \".config\", \"opencode\", \"athena\"),\n\n /** Athena backups directory */\n backupsDir: join(homedir(), \".config\", \"opencode\", \"athena\", \"backups\"),\n\n /** Athena state file (for story tracking) */\n stateFile: join(homedir(), \".config\", \"opencode\", \"athena\", \"athena-state.json\"),\n\n /** Legacy state file path (for migration) */\n legacyStateFile: join(homedir(), \".config\", \"opencode\", \"athena-state.json\"),\n} as const;\n\n/**\n * Project-specific paths (relative to project root)\n */\nexport const PROJECT_PATHS = {\n /** Local Athena config */\n localConfig: \".opencode/athena.json\",\n\n /** BMAD installation directory (v6 alpha) */\n bmadDir: \"_bmad\",\n\n /** BMAD output directory (v6 alpha) */\n bmadOutputDir: \"_bmad-output\",\n\n /** Legacy BMAD directory */\n legacyBmadDir: \"docs\",\n\n /** Sprint status file (v6 alpha) */\n sprintStatus: \"_bmad-output/implementation-artifacts/sprint-status.yaml\",\n\n /** Stories directory (v6 alpha) */\n storiesDir: \"_bmad-output/implementation-artifacts/stories\",\n\n /** Architecture document (v6 alpha) */\n architecture: \"_bmad-output/planning-artifacts/architecture.md\",\n\n /** PRD document (v6 alpha) */\n prd: \"_bmad-output/planning-artifacts/prd.md\",\n\n /** Epics document (v6 alpha) */\n epics: \"_bmad-output/planning-artifacts/epics.md\",\n\n /** Legacy paths for backward compatibility */\n legacy: {\n sprintStatus: \"docs/implementation-artifacts/sprint-status.yaml\",\n storiesDir: \"docs/implementation-artifacts/stories\",\n architecture: \"docs/project-planning-artifacts/architecture.md\",\n prd: \"docs/project-planning-artifacts/PRD.md\",\n },\n} as const;\n\n/**\n * Default configuration values\n */\nexport const DEFAULTS = {\n /** Default BMAD track for new projects */\n defaultTrack: \"bmad-method\" as const,\n\n /** Whether to auto-update sprint status */\n autoStatusUpdate: true,\n\n /** Maximum parallel stories */\n parallelStoryLimit: 3,\n\n /** Default features enabled */\n features: {\n bmadBridge: true,\n autoStatus: true,\n parallelExecution: true,\n notifications: true,\n contextMonitor: true,\n commentChecker: true,\n lspTools: true,\n autoGitOperations: false,\n todoSync: true,\n },\n\n /** Default MCPs enabled */\n mcps: {\n context7: true,\n exa: true,\n grepApp: true,\n },\n} as const;\n\n/**\n * Minimum compatible versions\n */\nexport const MIN_VERSIONS = {\n node: \"20.0.0\",\n opencode: \"1.0.132\",\n} as const;\n","/**\n * athena_config tool\n *\n * View current Athena configuration.\n */\n\nimport { type ToolDefinition, tool } from \"@opencode-ai/plugin\";\nimport { VERSION } from \"../../shared/constants.js\";\nimport type { AthenaConfig } from \"../../shared/types.js\";\n\n/**\n * Create the athena_config tool\n */\nexport function createConfigTool(config: AthenaConfig): ToolDefinition {\n return tool({\n description: `View the current OpenCode Athena configuration.\n\nShows:\n- Version information\n- Subscription settings (Claude, OpenAI, Google)\n- Model assignments for each agent role\n- BMAD integration settings\n- Enabled features and MCP servers`,\n\n args: {\n section: tool.schema\n .enum([\"all\", \"subscriptions\", \"models\", \"bmad\", \"features\", \"mcps\"])\n .optional()\n .describe(\"Specific section to view (default: all)\"),\n },\n\n async execute(args): Promise<string> {\n const section = args.section || \"all\";\n\n if (section === \"all\") {\n return JSON.stringify(\n {\n athenaVersion: VERSION,\n configVersion: config.version,\n subscriptions: config.subscriptions,\n models: config.models,\n bmad: config.bmad,\n features: config.features,\n mcps: config.mcps,\n },\n null,\n 2\n );\n }\n\n // Return specific section\n const sectionData: Record<string, unknown> = {\n subscriptions: config.subscriptions,\n models: config.models,\n bmad: config.bmad,\n features: config.features,\n mcps: config.mcps,\n };\n\n return JSON.stringify(\n {\n section,\n data: sectionData[section] || null,\n },\n null,\n 2\n );\n },\n });\n}\n","import { existsSync } from \"node:fs\";\nimport { mkdir, readFile, rm, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport { parse as parseYaml, stringify as stringifyYaml } from \"yaml\";\nimport type {\n BmadDevelopmentStatus,\n BmadSprintStatus,\n BmadStoryStatus,\n ParsedDevelopmentKey,\n ParsedEpicKey,\n ParsedStoryKey,\n} from \"../../shared/types.js\";\nimport { createPluginLogger } from \"./plugin-logger.js\";\n\nconst log = createPluginLogger(\"yaml-handler\");\n\nconst LOCK_EXT = \".lock\";\nconst LOCK_TIMEOUT = 10000;\nconst LOCK_RETRY_INTERVAL = 50;\nconst STALE_LOCK_AGE = 30000;\n\nasync function acquireLock(filePath: string): Promise<() => Promise<void>> {\n const lockPath = `${filePath}${LOCK_EXT}`;\n const startTime = Date.now();\n const lockId = `${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`;\n\n while (Date.now() - startTime < LOCK_TIMEOUT) {\n try {\n if (existsSync(lockPath)) {\n const lockContent = await readFile(lockPath, \"utf-8\").catch(() => null);\n if (lockContent) {\n try {\n const lockData = JSON.parse(lockContent);\n const lockAge = Date.now() - lockData.timestamp;\n if (lockAge > STALE_LOCK_AGE) {\n await rm(lockPath, { force: true });\n }\n } catch {\n await rm(lockPath, { force: true });\n }\n }\n }\n\n const lockData = JSON.stringify({\n id: lockId,\n pid: process.pid,\n timestamp: Date.now(),\n });\n\n await writeFile(lockPath, lockData, { flag: \"wx\" });\n\n return async () => {\n try {\n const currentContent = await readFile(lockPath, \"utf-8\").catch(() => null);\n if (currentContent) {\n const currentData = JSON.parse(currentContent);\n if (currentData.id === lockId) {\n await rm(lockPath, { force: true });\n }\n }\n } catch {\n // Ignore errors during unlock\n }\n };\n } catch (error: unknown) {\n const nodeError = error as NodeJS.ErrnoException;\n if (nodeError.code !== \"EEXIST\") {\n throw error;\n }\n await sleep(LOCK_RETRY_INTERVAL);\n }\n }\n\n throw new Error(`Failed to acquire lock for ${filePath} within ${LOCK_TIMEOUT}ms`);\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nexport async function readYamlFile<T = unknown>(filePath: string): Promise<T | null> {\n if (!existsSync(filePath)) {\n return null;\n }\n\n try {\n const content = await readFile(filePath, \"utf-8\");\n return parseYaml(content) as T;\n } catch (error) {\n log.warn(\"Failed to parse YAML file\", { filePath, error });\n return null;\n }\n}\n\nexport async function writeYamlFile<T = unknown>(filePath: string, data: T): Promise<void> {\n const content = stringifyYaml(data, {\n indent: 2,\n lineWidth: 120,\n });\n await writeFile(filePath, content, \"utf-8\");\n}\n\n// =============================================================================\n// BMAD v6 Key Parsing Functions\n// =============================================================================\n\nconst STORY_KEY_PATTERN = /^(\\d+)-(\\d+)(?:-(.+))?$/;\nconst EPIC_KEY_PATTERN = /^epic-(\\d+)$/;\nconst RETRO_KEY_PATTERN = /^epic-(\\d+)-retrospective$/;\n\nexport function parseStoryKey(key: string): ParsedStoryKey | null {\n const match = key.match(STORY_KEY_PATTERN);\n if (!match) return null;\n\n return {\n epicNum: match[1],\n storyNum: match[2],\n titleSlug: match[3] || undefined,\n fullKey: key,\n normalizedId: `${match[1]}-${match[2]}`,\n };\n}\n\nexport function parseEpicKey(key: string): ParsedEpicKey | null {\n const match = key.match(EPIC_KEY_PATTERN);\n if (!match) return null;\n\n return {\n epicNum: match[1],\n fullKey: key,\n };\n}\n\nexport function parseRetroKey(key: string): { epicNum: string; fullKey: string } | null {\n const match = key.match(RETRO_KEY_PATTERN);\n if (!match) return null;\n\n return {\n epicNum: match[1],\n fullKey: key,\n };\n}\n\nexport function parseDevelopmentKey(key: string): ParsedDevelopmentKey {\n const retroParsed = parseRetroKey(key);\n if (retroParsed) {\n return { type: \"retrospective\", parsed: retroParsed };\n }\n\n const epicParsed = parseEpicKey(key);\n if (epicParsed) {\n return { type: \"epic\", parsed: epicParsed };\n }\n\n const storyParsed = parseStoryKey(key);\n if (storyParsed) {\n return { type: \"story\", parsed: storyParsed };\n }\n\n return { type: \"unknown\", key };\n}\n\nexport function normalizeStoryId(storyId: string): string {\n return storyId.replace(\".\", \"-\");\n}\n\nexport function storyIdToDotFormat(storyId: string): string {\n const match = storyId.match(/^(\\d+)-(\\d+)/);\n if (match) {\n return `${match[1]}.${match[2]}`;\n }\n return storyId;\n}\n\nexport function slugify(title: string): string {\n return title\n .toLowerCase()\n .trim()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-|-$/g, \"\");\n}\n\n// =============================================================================\n// BMAD v6 Sprint Status Read/Write\n// =============================================================================\n\nexport async function readBmadSprintStatus(filePath: string): Promise<BmadSprintStatus | null> {\n const raw = await readYamlFile<Partial<BmadSprintStatus>>(filePath);\n\n if (!raw) {\n return null;\n }\n\n return {\n development_status: {},\n ...raw,\n };\n}\n\nexport async function writeBmadSprintStatus(\n filePath: string,\n status: BmadSprintStatus\n): Promise<void> {\n const dir = dirname(filePath);\n if (!existsSync(dir)) {\n await mkdir(dir, { recursive: true });\n }\n\n const releaseLock = await acquireLock(filePath);\n\n try {\n const currentStatus = await readBmadSprintStatus(filePath);\n\n let statusToWrite = status;\n\n if (currentStatus) {\n if (\n status.last_modified &&\n currentStatus.last_modified &&\n currentStatus.last_modified !== status.last_modified\n ) {\n statusToWrite = mergeBmadSprintStatus(currentStatus, status);\n }\n }\n\n statusToWrite.last_modified = new Date().toISOString();\n await writeYamlFile(filePath, statusToWrite);\n } finally {\n await releaseLock();\n }\n}\n\nfunction mergeBmadSprintStatus(\n current: BmadSprintStatus,\n incoming: BmadSprintStatus\n): BmadSprintStatus {\n const merged: BmadSprintStatus = {\n ...current,\n development_status: { ...current.development_status },\n };\n\n for (const [key, status] of Object.entries(incoming.development_status)) {\n merged.development_status[key] = status;\n }\n\n if (incoming.current_story !== undefined) {\n merged.current_story = incoming.current_story;\n }\n\n return merged;\n}\n\n// =============================================================================\n// Story Status Operations (BMAD v6)\n// =============================================================================\n\nexport interface StorySearchResult {\n key: string;\n status: BmadDevelopmentStatus;\n parsed: ParsedStoryKey;\n}\n\nexport function findStoryInStatus(\n status: BmadSprintStatus,\n storyId: string\n): StorySearchResult | null {\n const normalizedSearch = normalizeStoryId(storyId);\n\n for (const [key, statusValue] of Object.entries(status.development_status)) {\n const parsed = parseStoryKey(key);\n if (parsed && parsed.normalizedId === normalizedSearch) {\n return {\n key,\n status: statusValue,\n parsed,\n };\n }\n }\n\n return null;\n}\n\nexport function findStoriesByStatus(\n status: BmadSprintStatus,\n targetStatus: BmadStoryStatus\n): StorySearchResult[] {\n const results: StorySearchResult[] = [];\n\n for (const [key, statusValue] of Object.entries(status.development_status)) {\n if (statusValue !== targetStatus) continue;\n\n const parsed = parseStoryKey(key);\n if (parsed) {\n results.push({ key, status: statusValue, parsed });\n }\n }\n\n return results.sort((a, b) => compareStoryKeys(a.parsed, b.parsed));\n}\n\nfunction compareStoryKeys(a: ParsedStoryKey, b: ParsedStoryKey): number {\n const epicA = Number.parseInt(a.epicNum, 10);\n const epicB = Number.parseInt(b.epicNum, 10);\n if (epicA !== epicB) return epicA - epicB;\n\n const numA = Number.parseInt(a.storyNum, 10);\n const numB = Number.parseInt(b.storyNum, 10);\n return numA - numB;\n}\n\nexport function findNextReadyStory(status: BmadSprintStatus): StorySearchResult | null {\n if (status.current_story) {\n const current = findStoryInStatus(status, status.current_story);\n if (current) return current;\n }\n\n const inProgress = findStoriesByStatus(status, \"in-progress\");\n if (inProgress.length > 0) return inProgress[0];\n\n const readyForDev = findStoriesByStatus(status, \"ready-for-dev\");\n if (readyForDev.length > 0) return readyForDev[0];\n\n const backlog = findStoriesByStatus(status, \"backlog\");\n if (backlog.length > 0) return backlog[0];\n\n return null;\n}\n\nexport async function updateStoryStatus(\n filePath: string,\n storyId: string,\n newStatus: BmadStoryStatus,\n storyTitle?: string\n): Promise<{ success: boolean; key: string; previousStatus?: BmadDevelopmentStatus }> {\n const status = await readBmadSprintStatus(filePath);\n if (!status) {\n return { success: false, key: \"\" };\n }\n\n const existing = findStoryInStatus(status, storyId);\n\n let key: string;\n let previousStatus: BmadDevelopmentStatus | undefined;\n\n if (existing) {\n key = existing.key;\n previousStatus = existing.status;\n } else {\n const normalizedId = normalizeStoryId(storyId);\n key = storyTitle ? `${normalizedId}-${slugify(storyTitle)}` : normalizedId;\n }\n\n status.development_status[key] = newStatus;\n\n if (newStatus === \"in-progress\") {\n status.current_story = normalizeStoryId(storyId);\n } else if (newStatus === \"done\" || newStatus === \"blocked\") {\n if (status.current_story === normalizeStoryId(storyId)) {\n status.current_story = null;\n }\n }\n\n await writeBmadSprintStatus(filePath, status);\n\n return { success: true, key, previousStatus };\n}\n\n// =============================================================================\n// Epic Status Operations (BMAD v6)\n// =============================================================================\n\nexport function findEpicKey(status: BmadSprintStatus, epicNum: string): string | null {\n const epicKey = `epic-${epicNum}`;\n if (epicKey in status.development_status) {\n return epicKey;\n }\n return null;\n}\n\nexport function getStoriesForEpic(status: BmadSprintStatus, epicNum: string): StorySearchResult[] {\n const results: StorySearchResult[] = [];\n\n for (const [key, statusValue] of Object.entries(status.development_status)) {\n const parsed = parseStoryKey(key);\n if (parsed && parsed.epicNum === epicNum) {\n results.push({ key, status: statusValue, parsed });\n }\n }\n\n return results.sort((a, b) => compareStoryKeys(a.parsed, b.parsed));\n}\n\nexport async function updateEpicStatusIfNeeded(\n filePath: string,\n epicNum: string\n): Promise<{ updated: boolean; newStatus?: BmadDevelopmentStatus }> {\n const status = await readBmadSprintStatus(filePath);\n if (!status) {\n return { updated: false };\n }\n\n const epicKey = findEpicKey(status, epicNum);\n if (!epicKey) {\n return { updated: false };\n }\n\n const currentEpicStatus = status.development_status[epicKey];\n const stories = getStoriesForEpic(status, epicNum);\n\n if (stories.length === 0) {\n return { updated: false };\n }\n\n const allDone = stories.every((s) => s.status === \"done\");\n const anyInProgress = stories.some(\n (s) => s.status === \"in-progress\" || s.status === \"review\" || s.status === \"ready-for-dev\"\n );\n\n let newStatus: BmadDevelopmentStatus | undefined;\n\n if (allDone && currentEpicStatus !== \"done\") {\n newStatus = \"done\";\n } else if (anyInProgress && currentEpicStatus === \"backlog\") {\n newStatus = \"in-progress\";\n }\n\n if (newStatus) {\n status.development_status[epicKey] = newStatus;\n await writeBmadSprintStatus(filePath, status);\n return { updated: true, newStatus };\n }\n\n return { updated: false };\n}\n\n// =============================================================================\n// Add Story to Sprint Status (BMAD v6)\n// =============================================================================\n\nexport async function addStoryToBmadSprintStatus(\n filePath: string,\n storyId: string,\n storyTitle?: string,\n initialStatus: BmadStoryStatus = \"backlog\"\n): Promise<{ success: boolean; key: string }> {\n const status = await readBmadSprintStatus(filePath);\n if (!status) {\n return { success: false, key: \"\" };\n }\n\n const existing = findStoryInStatus(status, storyId);\n if (existing) {\n return { success: true, key: existing.key };\n }\n\n const normalizedId = normalizeStoryId(storyId);\n const key = storyTitle ? `${normalizedId}-${slugify(storyTitle)}` : normalizedId;\n\n status.development_status[key] = initialStatus;\n await writeBmadSprintStatus(filePath, status);\n\n return { success: true, key };\n}\n\n// =============================================================================\n// Sprint Progress Calculation (BMAD v6)\n// =============================================================================\n\nexport interface SprintProgress {\n total: number;\n done: number;\n inProgress: number;\n readyForDev: number;\n backlog: number;\n blocked: number;\n review: number;\n percentComplete: number;\n}\n\nexport function calculateSprintProgress(status: BmadSprintStatus): SprintProgress {\n let total = 0;\n let done = 0;\n let inProgress = 0;\n let readyForDev = 0;\n let backlog = 0;\n let blocked = 0;\n let review = 0;\n\n for (const [key, statusValue] of Object.entries(status.development_status)) {\n const parsed = parseStoryKey(key);\n if (!parsed) continue;\n\n total++;\n switch (statusValue) {\n case \"done\":\n done++;\n break;\n case \"in-progress\":\n inProgress++;\n break;\n case \"ready-for-dev\":\n readyForDev++;\n break;\n case \"backlog\":\n backlog++;\n break;\n case \"blocked\":\n blocked++;\n break;\n case \"review\":\n review++;\n break;\n }\n }\n\n const percentComplete = total > 0 ? Math.round((done / total) * 100) : 0;\n\n return {\n total,\n done,\n inProgress,\n readyForDev,\n backlog,\n blocked,\n review,\n percentComplete,\n };\n}\n\n// =============================================================================\n// Legacy Compatibility (Deprecated)\n// =============================================================================\n\nimport type { SprintStatus } from \"../../shared/types.js\";\n\n/** @deprecated Use readBmadSprintStatus instead */\nexport async function readSprintStatus(filePath: string): Promise<SprintStatus | null> {\n const raw = await readYamlFile<Partial<SprintStatus>>(filePath);\n\n if (!raw) {\n return null;\n }\n\n return {\n completed_stories: [],\n pending_stories: [],\n in_progress_stories: [],\n blocked_stories: [],\n ...raw,\n };\n}\n\n/** @deprecated Use writeBmadSprintStatus instead */\nexport async function writeSprintStatus(filePath: string, status: SprintStatus): Promise<void> {\n const dir = dirname(filePath);\n if (!existsSync(dir)) {\n await mkdir(dir, { recursive: true });\n }\n\n const releaseLock = await acquireLock(filePath);\n\n try {\n status.last_modified = new Date().toISOString();\n await writeYamlFile(filePath, status);\n } finally {\n await releaseLock();\n }\n}\n\n/** @deprecated Use addStoryToBmadSprintStatus instead */\nexport async function addStoryToSprintStatus(\n filePath: string,\n storyId: string,\n _status: \"pending\" | \"backlog\" = \"backlog\"\n): Promise<void> {\n await addStoryToBmadSprintStatus(filePath, storyId, undefined, \"backlog\");\n}\n\n/** @deprecated No longer needed with flat map structure */\nexport function insertStoryInOrder(stories: string[], newStoryId: string): string[] {\n const normalizedId = newStoryId.replace(\".\", \"-\");\n\n if (stories.includes(normalizedId)) {\n return stories;\n }\n\n const result = [...stories, normalizedId];\n result.sort((a, b) => {\n const parsedA = parseStoryKey(a);\n const parsedB = parseStoryKey(b);\n if (!parsedA || !parsedB) return 0;\n return compareStoryKeys(parsedA, parsedB);\n });\n return result;\n}\n","import * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport { type ToolDefinition, tool } from \"@opencode-ai/plugin\";\nimport type { PluginInput } from \"@opencode-ai/plugin\";\nimport type {\n AthenaConfig,\n CreatedSubStory,\n DecomposeStoryResult,\n DecompositionSplit,\n DecompositionVerification,\n UserSplitConfig,\n} from \"../../shared/types.js\";\nimport { getBmadPaths } from \"../utils/bmad-finder.js\";\nimport { createPluginLogger } from \"../utils/plugin-logger.js\";\nimport { assessStoryComplexity } from \"../utils/story-complexity.js\";\nimport {\n generateDecompositionSuggestions,\n generateSubStoryContent,\n getSubStoryFilename,\n getSubStoryId,\n validateSplits,\n} from \"../utils/story-decomposer.js\";\nimport { normalizeStoryId, resolveStoryIdentifier, stripAtPrefix } from \"../utils/story-loader.js\";\nimport { parseStoryTasks } from \"../utils/story-parser.js\";\nimport {\n readBmadSprintStatus,\n storyIdToDotFormat,\n writeBmadSprintStatus,\n} from \"../utils/yaml-handler.js\";\n\nconst log = createPluginLogger(\"decompose-story\");\n\nexport function createDecomposeStoryTool(ctx: PluginInput, config: AthenaConfig): ToolDefinition {\n return tool({\n description: `Decompose a large BMAD story into smaller sub-stories.\n\nUse after athena_analyze_story recommends decomposition.\n\nWhat this tool does:\n1. Validates that all tasks are accounted for (no missing/duplicates)\n2. Creates new story files with suffix (e.g., 3-2a.md, 3-2b.md)\n3. Updates sprint-status.yaml (removes original, adds sub-stories)\n4. Preserves applicable dev notes in each sub-story\n5. Returns the first story to implement\n\nIMPORTANT: Requires confirmed=true to execute (safety check).`,\n\n args: {\n storyId: tool.schema.string().describe(\"Story ID to decompose (e.g., '3.2')\"),\n splits: tool.schema\n .array(\n tool.schema.object({\n suffix: tool.schema.string().describe(\"Suffix for sub-story (e.g., 'a', 'b')\"),\n title: tool.schema.string().optional().describe(\"Optional title override\"),\n taskIds: tool.schema\n .array(tool.schema.string())\n .describe(\"Task IDs to include in this split\"),\n })\n )\n .optional()\n .describe(\"Custom splits (if not provided, uses suggested splits from analysis)\"),\n useSuggestedSplits: tool.schema\n .boolean()\n .optional()\n .describe(\"Use suggested splits from analysis (default: true if no custom splits)\"),\n confirmed: tool.schema\n .boolean()\n .describe(\"Must be true to execute decomposition (safety check)\"),\n },\n\n async execute(args): Promise<string> {\n const result = await handleDecomposeStory(ctx, config, {\n storyId: args.storyId,\n splits: args.splits as UserSplitConfig[] | undefined,\n useSuggestedSplits: args.useSuggestedSplits,\n confirmed: args.confirmed,\n });\n\n return JSON.stringify(result, null, 2);\n },\n });\n}\n\ninterface DecomposeArgs {\n storyId: string;\n splits?: UserSplitConfig[];\n useSuggestedSplits?: boolean;\n confirmed: boolean;\n}\n\nasync function handleDecomposeStory(\n ctx: PluginInput,\n config: AthenaConfig,\n args: DecomposeArgs\n): Promise<DecomposeStoryResult> {\n const { confirmed, splits: customSplits, useSuggestedSplits } = args;\n const rawStoryId = stripAtPrefix(args.storyId);\n const storyId = normalizeStoryId(rawStoryId);\n\n log.debug(\"Decomposing story\", { storyId, confirmed, hasCustomSplits: !!customSplits });\n\n if (!confirmed) {\n return createErrorResult(\n \"Safety check failed: confirmed must be true to execute decomposition\",\n \"Set confirmed=true to proceed with story decomposition.\"\n );\n }\n\n const paths = await getBmadPaths(ctx.directory, config);\n if (!paths.storiesDir) {\n return createErrorResult(\n \"No stories directory found\",\n paths.suggestion ||\n \"Ensure BMAD is set up with a stories directory. Athena supports both legacy (docs/) and v6-alpha (_bmad/ + _bmad-output/) structures.\"\n );\n }\n\n const resolved = await resolveStoryIdentifier(paths.storiesDir, rawStoryId, ctx.directory);\n if (!resolved) {\n return createErrorResult(\n `Story not found: ${args.storyId}`,\n \"Check the story ID and try again.\"\n );\n }\n\n const { content: storyContent, filename: originalFilename, path: storyPath } = resolved;\n const parsedStory = parseStoryTasks(storyContent, storyId);\n\n if (parsedStory.tasks.length === 0) {\n return createErrorResult(\n \"No tasks found in story\",\n \"Story must have tasks to decompose. Check the story format.\"\n );\n }\n\n const splitsToUse = determineSplits(customSplits, useSuggestedSplits, parsedStory, storyContent);\n\n if (\"error\" in splitsToUse) {\n return createErrorResult(splitsToUse.error, splitsToUse.suggestion, parsedStory.tasks.length);\n }\n\n const validation = validateSplits(parsedStory.tasks, splitsToUse);\n if (!validation.valid) {\n return {\n success: false,\n createdStories: [],\n verification: {\n originalTaskCount: parsedStory.tasks.length,\n totalTasksInSplits: splitsToUse.reduce((sum, s) => sum + s.taskIds.length, 0),\n allTasksAccountedFor: false,\n missingTasks: validation.missingTasks,\n duplicatedTasks: validation.duplicatedTasks,\n devNotesPreserved: false,\n },\n sprintStatusUpdated: false,\n originalStoryRemoved: false,\n nextStory: \"\",\n error: formatValidationError(validation),\n suggestion: \"Ensure all tasks are included exactly once across all splits.\",\n };\n }\n\n const createdStories = await createSubStoryFiles(\n splitsToUse,\n storyContent,\n parsedStory,\n storyId,\n originalFilename,\n paths.storiesDir\n );\n\n if (\"error\" in createdStories) {\n return {\n success: false,\n createdStories: createdStories.created,\n verification: createPartialVerification(parsedStory.tasks.length, splitsToUse),\n sprintStatusUpdated: false,\n originalStoryRemoved: false,\n nextStory: \"\",\n error: createdStories.error,\n suggestion: \"Check file system permissions.\",\n };\n }\n\n const sprintUpdate = await updateSprintStatus(paths.sprintStatus, storyId, createdStories);\n await archiveOriginalStory(storyPath);\n\n const firstReadyStory = createdStories.find((s) => s.status === \"ready-for-dev\");\n const nextStory = firstReadyStory\n ? storyIdToDotFormat(firstReadyStory.id)\n : storyIdToDotFormat(createdStories[0].id);\n\n log.info(\"Story decomposition complete\", {\n storyId,\n createdCount: createdStories.length,\n nextStory,\n sprintStatusUpdated: sprintUpdate.updated,\n originalStoryRemoved: sprintUpdate.originalRemoved,\n });\n\n return {\n success: true,\n createdStories,\n verification: {\n originalTaskCount: parsedStory.tasks.length,\n totalTasksInSplits: splitsToUse.reduce((sum, s) => sum + s.taskIds.length, 0),\n allTasksAccountedFor: true,\n missingTasks: [],\n duplicatedTasks: [],\n devNotesPreserved:\n storyContent.includes(\"## Dev Notes\") || storyContent.includes(\"## Implementation Notes\"),\n },\n sprintStatusUpdated: sprintUpdate.updated,\n originalStoryRemoved: sprintUpdate.originalRemoved,\n nextStory,\n };\n}\n\nfunction createErrorResult(\n error: string,\n suggestion: string,\n originalTaskCount = 0\n): DecomposeStoryResult {\n return {\n success: false,\n createdStories: [],\n verification: {\n originalTaskCount,\n totalTasksInSplits: 0,\n allTasksAccountedFor: false,\n missingTasks: [],\n duplicatedTasks: [],\n devNotesPreserved: false,\n },\n sprintStatusUpdated: false,\n originalStoryRemoved: false,\n nextStory: \"\",\n error,\n suggestion,\n };\n}\n\nfunction determineSplits(\n customSplits: UserSplitConfig[] | undefined,\n useSuggestedSplits: boolean | undefined,\n parsedStory: ReturnType<typeof parseStoryTasks>,\n storyContent: string\n): DecompositionSplit[] | { error: string; suggestion: string } {\n if (customSplits && customSplits.length > 0) {\n return customSplits.map((split, index) => ({\n suffix: split.suffix,\n title: split.title || `Part ${index + 1}`,\n taskIds: split.taskIds,\n estimatedPoints: 0,\n rationale: \"User-defined split\",\n dependencies: [],\n }));\n }\n\n if (useSuggestedSplits === false) {\n return {\n error: \"No splits provided and useSuggestedSplits is false\",\n suggestion: \"Either provide custom splits or set useSuggestedSplits=true.\",\n };\n }\n\n const fileSizeBytes = Buffer.byteLength(storyContent, \"utf-8\");\n const assessment = assessStoryComplexity(parsedStory, fileSizeBytes);\n const suggestedSplits = generateDecompositionSuggestions(parsedStory, assessment.taskEfforts);\n\n if (suggestedSplits.length === 0) {\n return {\n error: \"Could not generate decomposition suggestions\",\n suggestion: \"Provide custom splits using the 'splits' parameter.\",\n };\n }\n\n return suggestedSplits;\n}\n\nfunction formatValidationError(validation: {\n missingTasks: string[];\n duplicatedTasks: string[];\n}): string {\n const parts: string[] = [];\n if (validation.missingTasks.length > 0) {\n parts.push(`missing tasks: ${validation.missingTasks.join(\", \")}`);\n }\n if (validation.duplicatedTasks.length > 0) {\n parts.push(`duplicated tasks: ${validation.duplicatedTasks.join(\", \")}`);\n }\n return `Invalid splits: ${parts.join(\"; \")}`;\n}\n\nfunction createPartialVerification(\n originalTaskCount: number,\n splits: DecompositionSplit[]\n): DecompositionVerification {\n return {\n originalTaskCount,\n totalTasksInSplits: splits.reduce((sum, s) => sum + s.taskIds.length, 0),\n allTasksAccountedFor: false,\n missingTasks: [],\n duplicatedTasks: [],\n devNotesPreserved: false,\n };\n}\n\nasync function createSubStoryFiles(\n splits: DecompositionSplit[],\n storyContent: string,\n parsedStory: ReturnType<typeof parseStoryTasks>,\n storyId: string,\n originalFilename: string,\n storiesDir: string\n): Promise<CreatedSubStory[] | { error: string; created: CreatedSubStory[] }> {\n const createdStories: CreatedSubStory[] = [];\n\n for (let i = 0; i < splits.length; i++) {\n const split = splits[i];\n const subStoryFilename = getSubStoryFilename(originalFilename, split.suffix);\n const subStoryId = getSubStoryId(storyId, split.suffix);\n const subStoryPath = path.join(storiesDir, subStoryFilename);\n\n const subStoryContent = generateSubStoryContent(\n storyContent,\n parsedStory,\n split,\n i,\n splits.length,\n storyId\n );\n\n try {\n await fs.writeFile(subStoryPath, subStoryContent, \"utf-8\");\n log.info(\"Created sub-story file\", { path: subStoryPath });\n } catch (err) {\n log.error(\"Failed to write sub-story file\", { path: subStoryPath, error: err });\n return {\n error: `Failed to create sub-story file: ${subStoryFilename}`,\n created: createdStories,\n };\n }\n\n const hasDependencies = split.dependencies.length > 0;\n const status: \"ready-for-dev\" | \"backlog\" = hasDependencies ? \"backlog\" : \"ready-for-dev\";\n\n createdStories.push({\n id: subStoryId,\n filename: subStoryFilename,\n filePath: subStoryPath,\n taskCount: split.taskIds.length,\n estimatedPoints: split.estimatedPoints,\n status,\n dependencies: split.dependencies.map((d) => getSubStoryId(storyId, d)),\n hasVerificationTask: false,\n });\n }\n\n return createdStories;\n}\n\nasync function updateSprintStatus(\n sprintStatusPath: string | undefined,\n storyId: string,\n createdStories: CreatedSubStory[]\n): Promise<{ updated: boolean; originalRemoved: boolean }> {\n if (!sprintStatusPath) {\n return { updated: false, originalRemoved: false };\n }\n\n try {\n const sprintStatus = await readBmadSprintStatus(sprintStatusPath);\n if (!sprintStatus) {\n return { updated: false, originalRemoved: false };\n }\n\n let originalRemoved = false;\n const originalKeyPattern = new RegExp(`^${storyId.replace(\".\", \"-\")}(-.*)?$`);\n\n for (const key of Object.keys(sprintStatus.development_status)) {\n if (originalKeyPattern.test(key) && !key.includes(\"retrospective\")) {\n delete sprintStatus.development_status[key];\n originalRemoved = true;\n log.info(\"Removed original story from sprint status\", { key });\n }\n }\n\n for (const subStory of createdStories) {\n const subStoryKey = subStory.id.replace(\".\", \"-\");\n sprintStatus.development_status[subStoryKey] = subStory.status;\n log.info(\"Added sub-story to sprint status\", { key: subStoryKey, status: subStory.status });\n }\n\n if (sprintStatus.current_story) {\n const currentNormalized = normalizeStoryId(sprintStatus.current_story);\n if (currentNormalized === storyId) {\n const firstReady = createdStories.find((s) => s.status === \"ready-for-dev\");\n sprintStatus.current_story = firstReady\n ? firstReady.id.replace(\".\", \"-\")\n : createdStories[0].id.replace(\".\", \"-\");\n }\n }\n\n sprintStatus.last_modified = new Date().toISOString();\n await writeBmadSprintStatus(sprintStatusPath, sprintStatus);\n\n return { updated: true, originalRemoved };\n } catch (err) {\n log.warn(\"Failed to update sprint-status.yaml\", { error: err });\n return { updated: false, originalRemoved: false };\n }\n}\n\nasync function archiveOriginalStory(storyPath: string): Promise<void> {\n try {\n const archivedPath = storyPath.replace(\".md\", \".decomposed.md\");\n await fs.rename(storyPath, archivedPath);\n log.info(\"Archived original story\", { from: storyPath, to: archivedPath });\n } catch (err) {\n log.warn(\"Failed to archive original story file\", { error: err });\n }\n}\n","/**\n * athena_get_context tool\n *\n * Quick access to current story context from tracker.\n */\n\nimport { type ToolDefinition, tool } from \"@opencode-ai/plugin\";\nimport type { AthenaConfig } from \"../../shared/types.js\";\nimport type { StoryTracker } from \"../tracker/story-tracker.js\";\n\n/**\n * Create the athena_get_context tool\n */\nexport function createGetContextTool(tracker: StoryTracker, _config: AthenaConfig): ToolDefinition {\n return tool({\n description: `Get the current story context without reloading from files.\n\nReturns the cached context from the story tracker including:\n- Current story ID and status\n- When the story was started\n- Recent activity history\n\nUse this for quick status checks. Use athena_get_story to reload full context from files.`,\n\n args: {},\n\n async execute(): Promise<string> {\n const currentStory = tracker.getCurrentStory();\n\n if (!currentStory) {\n return JSON.stringify({\n status: \"no_active_story\",\n message: \"No story is currently being tracked. Use athena_get_story to load a story.\",\n });\n }\n\n const context = await tracker.getCurrentStoryContext();\n const history = tracker.getHistory().slice(-10);\n\n return JSON.stringify(\n {\n currentStory: {\n id: currentStory.id,\n status: currentStory.status,\n startedAt: currentStory.startedAt,\n completedAt: currentStory.completedAt,\n },\n contextSummary: context,\n recentHistory: history,\n sessionId: tracker.getSessionId(),\n },\n null,\n 2\n );\n },\n });\n}\n","/**\n * Context builder for BMAD story implementation\n *\n * Extracts relevant sections from architecture and PRD documents\n * based on story content keywords.\n */\n\nimport { existsSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { createPluginLogger } from \"./plugin-logger.js\";\n\nconst log = createPluginLogger(\"context-builder\");\n\n/**\n * Extract relevant architecture sections based on story content\n *\n * Always includes:\n * - Tech Stack section\n * - Patterns/Conventions section\n *\n * Conditionally includes based on keywords:\n * - Data Model section (if story mentions data/database/model/schema)\n * - API section (if story mentions api/endpoint/route)\n *\n * @param archPath - Path to architecture.md\n * @param storyContent - Content of the story file\n * @returns Extracted architecture sections\n */\nexport async function extractRelevantArchitecture(\n archPath: string,\n storyContent: string\n): Promise<string> {\n if (!existsSync(archPath)) {\n return \"\";\n }\n\n try {\n const archContent = await readFile(archPath, \"utf-8\");\n const sections: string[] = [];\n\n // Always include tech stack section\n const techStackMatch = archContent.match(/## Tech(?:nology)? Stack[\\s\\S]*?(?=\\n## |$)/i);\n if (techStackMatch) {\n sections.push(techStackMatch[0].trim());\n }\n\n // Always include patterns/conventions section\n const patternsMatch = archContent.match(\n /## (?:Patterns|Conventions|Standards|Coding Standards)[\\s\\S]*?(?=\\n## |$)/i\n );\n if (patternsMatch) {\n sections.push(patternsMatch[0].trim());\n }\n\n // Include data model section if story mentions data/database\n if (/data|database|model|schema|entity/i.test(storyContent)) {\n const dataMatch = archContent.match(\n /## (?:Data Model|Database|Schema|Data Layer)[\\s\\S]*?(?=\\n## |$)/i\n );\n if (dataMatch) {\n sections.push(dataMatch[0].trim());\n }\n }\n\n // Include API section if story mentions API/endpoint\n if (/api|endpoint|route|rest|graphql/i.test(storyContent)) {\n const apiMatch = archContent.match(\n /## (?:API|Endpoints|Routes|REST|GraphQL)[\\s\\S]*?(?=\\n## |$)/i\n );\n if (apiMatch) {\n sections.push(apiMatch[0].trim());\n }\n }\n\n // Include UI/component section if story mentions UI\n if (/ui|component|view|page|screen|frontend/i.test(storyContent)) {\n const uiMatch = archContent.match(\n /## (?:UI|Components|Views|Frontend|User Interface)[\\s\\S]*?(?=\\n## |$)/i\n );\n if (uiMatch) {\n sections.push(uiMatch[0].trim());\n }\n }\n\n return sections.length > 0\n ? sections.join(\"\\n\\n---\\n\\n\")\n : \"See full architecture document for details.\";\n } catch (error) {\n log.warn(\"Failed to read architecture file\", { archPath, error });\n return \"\";\n }\n}\n\n/**\n * Extract relevant PRD sections based on story content\n *\n * Looks for functional requirement (FR) references in the story\n * and extracts those sections from the PRD.\n *\n * @param prdPath - Path to PRD.md\n * @param storyContent - Content of the story file\n * @returns Extracted PRD sections\n */\nexport async function extractRelevantPRD(prdPath: string, storyContent: string): Promise<string> {\n if (!existsSync(prdPath)) {\n return \"\";\n }\n\n try {\n const prdContent = await readFile(prdPath, \"utf-8\");\n\n // Extract FR references from story (e.g., FR-1, FR1, FR-001)\n const frMatches = storyContent.match(/FR-?\\d+/gi);\n\n if (!frMatches || frMatches.length === 0) {\n return \"\";\n }\n\n // Deduplicate FR references\n const uniqueFRs = [...new Set(frMatches.map((fr) => fr.toUpperCase()))];\n const sections: string[] = [];\n\n for (const fr of uniqueFRs) {\n // Try to find the FR section in the PRD\n // Match patterns like \"### FR-1\" or \"#### FR1\" or \"### FR-001: Title\"\n const normalizedFR = fr.replace(\"-\", \"-?\");\n const regex = new RegExp(`###+ ${normalizedFR}[:\\\\s][\\\\s\\\\S]*?(?=\\\\n###+ |$)`, \"i\");\n const match = prdContent.match(regex);\n\n if (match) {\n sections.push(match[0].trim());\n }\n }\n\n return sections.join(\"\\n\\n\");\n } catch (error) {\n log.warn(\"Failed to read PRD file\", { prdPath, error });\n return \"\";\n }\n}\n\n/**\n * Generate implementation instructions for a story\n *\n * @param storyId - The story ID\n * @returns Markdown instructions for implementing the story\n */\nexport function generateImplementationInstructions(storyId: string): string {\n return `\n## Implementation Instructions for Story ${storyId}\n\nYou are implementing this story using OpenCode Athena's full capabilities.\n\n### Available Subagents\n- **@oracle** - Use for complex debugging, architectural decisions, or strategic code choices\n- **@librarian** - Use for finding implementation examples, researching patterns, exploring documentation\n- **@explore** - Use for fast codebase searches and pattern matching\n- **@frontend-ui-ux-engineer** - Use for UI component implementation (if applicable)\n\n### Available Tools\n- **LSP Tools** - Use lsp_rename, lsp_find_references, lsp_code_actions for refactoring\n- **AST-Grep** - Use ast_grep_search and ast_grep_replace for structural code changes\n\n### Quality Standards\n1. Meet ALL acceptance criteria listed in the story\n2. Follow architecture patterns exactly as specified\n3. Keep comments minimal - code should be self-documenting\n4. Run tests before marking complete\n5. Ensure no regressions in existing functionality\n\n### Completion\nWhen implementation is complete:\n1. Call **athena_update_status** with status \"completed\" and a completion summary\n2. The sprint-status.yaml will be automatically updated\n3. Report what was implemented and any decisions made\n\n### If You Get Stuck\n- Call @oracle for debugging help\n- Call @librarian to find similar implementations\n- Check the architecture document for patterns\n`.trim();\n}\n","import { existsSync } from \"node:fs\";\nimport { readFile, writeFile } from \"node:fs/promises\";\nimport type { BmadStoryStatus } from \"../../shared/types.js\";\nimport { createPluginLogger } from \"./plugin-logger.js\";\n\nconst log = createPluginLogger(\"story-file-updater\");\n\nconst STATUS_LINE_PATTERN = /^Status:\\s*(.+)$/im;\nconst STORY_TITLE_PATTERN = /^#\\s*Story\\s*[\\d.]+:\\s*(.+)$/im;\n\nexport interface StoryFileUpdateResult {\n success: boolean;\n previousStatus?: string;\n newStatus?: BmadStoryStatus;\n error?: string;\n}\n\nexport interface StoryFileInfo {\n status: string | null;\n title: string | null;\n}\n\nexport async function getStoryFileInfo(storyPath: string): Promise<StoryFileInfo | null> {\n if (!existsSync(storyPath)) {\n return null;\n }\n\n try {\n const content = await readFile(storyPath, \"utf-8\");\n\n const statusMatch = content.match(STATUS_LINE_PATTERN);\n const titleMatch = content.match(STORY_TITLE_PATTERN);\n\n return {\n status: statusMatch ? statusMatch[1].trim() : null,\n title: titleMatch ? titleMatch[1].trim() : null,\n };\n } catch (error) {\n log.warn(\"Failed to read story file\", { storyPath, error });\n return null;\n }\n}\n\nexport async function updateStoryFileStatus(\n storyPath: string,\n newStatus: BmadStoryStatus\n): Promise<StoryFileUpdateResult> {\n if (!existsSync(storyPath)) {\n return {\n success: false,\n error: `Story file not found: ${storyPath}`,\n };\n }\n\n try {\n const content = await readFile(storyPath, \"utf-8\");\n const statusMatch = content.match(STATUS_LINE_PATTERN);\n\n if (!statusMatch) {\n const lines = content.split(\"\\n\");\n let insertIndex = 0;\n\n if (lines[0]?.startsWith(\"#\")) {\n insertIndex = 1;\n while (insertIndex < lines.length && lines[insertIndex]?.trim() === \"\") {\n insertIndex++;\n }\n }\n\n lines.splice(insertIndex, 0, \"\", `Status: ${newStatus}`, \"\");\n const updatedContent = lines.join(\"\\n\");\n\n await writeFile(storyPath, updatedContent, \"utf-8\");\n\n log.info(\"Added Status line to story file\", { storyPath, newStatus });\n\n return {\n success: true,\n previousStatus: undefined,\n newStatus,\n };\n }\n\n const previousStatus = statusMatch[1].trim();\n\n if (previousStatus === newStatus) {\n return {\n success: true,\n previousStatus,\n newStatus,\n };\n }\n\n const updatedContent = content.replace(STATUS_LINE_PATTERN, `Status: ${newStatus}`);\n\n await writeFile(storyPath, updatedContent, \"utf-8\");\n\n log.info(\"Updated story file status\", {\n storyPath,\n previousStatus,\n newStatus,\n });\n\n return {\n success: true,\n previousStatus,\n newStatus,\n };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n log.error(\"Failed to update story file status\", { storyPath, error });\n\n return {\n success: false,\n error: `Failed to update story file: ${errorMessage}`,\n };\n }\n}\n\nexport async function getStoryTitle(storyPath: string): Promise<string | null> {\n const info = await getStoryFileInfo(storyPath);\n return info?.title ?? null;\n}\n\nexport function extractTitleFromContent(content: string): string | null {\n const match = content.match(STORY_TITLE_PATTERN);\n return match ? match[1].trim() : null;\n}\n","import { type ToolDefinition, tool } from \"@opencode-ai/plugin\";\nimport type { PluginInput } from \"@opencode-ai/plugin\";\nimport type { AthenaConfig, GetStoryResult } from \"../../shared/types.js\";\nimport type { StoryTracker } from \"../tracker/story-tracker.js\";\nimport { getBmadPaths } from \"../utils/bmad-finder.js\";\nimport {\n extractRelevantArchitecture,\n extractRelevantPRD,\n generateImplementationInstructions,\n} from \"../utils/context-builder.js\";\nimport { createPluginLogger } from \"../utils/plugin-logger.js\";\nimport { getStoryTitle, updateStoryFileStatus } from \"../utils/story-file-updater.js\";\nimport { normalizeStoryId, resolveStoryIdentifier, stripAtPrefix } from \"../utils/story-loader.js\";\nimport {\n calculateSprintProgress,\n findNextReadyStory,\n findStoryInStatus,\n readBmadSprintStatus,\n storyIdToDotFormat,\n updateEpicStatusIfNeeded,\n updateStoryStatus,\n} from \"../utils/yaml-handler.js\";\n\nconst log = createPluginLogger(\"get-story\");\n\nexport function createGetStoryTool(\n ctx: PluginInput,\n tracker: StoryTracker,\n config: AthenaConfig\n): ToolDefinition {\n return tool({\n description: `Load the current BMAD story context for implementation.\n\nReturns:\n- Story file content with requirements and acceptance criteria\n- Relevant architecture sections\n- Sprint progress information\n- Implementation instructions for using Sisyphus and subagents\n\nWhen loading a 'ready-for-dev' story, it will automatically be transitioned to 'in-progress'.\n\nUse this tool before starting story implementation to get full context.`,\n\n args: {\n storyId: tool.schema\n .string()\n .optional()\n .describe(\n \"Story ID (e.g., '2.3') or file path (e.g., 'docs/stories/story-2-3.md'). If omitted, loads the next ready story.\"\n ),\n },\n\n async execute(args): Promise<string> {\n const result = await getStoryContext(ctx, tracker, config, args.storyId);\n return JSON.stringify(result, null, 2);\n },\n });\n}\n\nasync function getStoryContext(\n ctx: PluginInput,\n tracker: StoryTracker,\n config: AthenaConfig,\n requestedStoryId?: string\n): Promise<GetStoryResult> {\n log.debug(\"Getting story context\", { requestedStoryId, directory: ctx.directory });\n\n const paths = await getBmadPaths(ctx.directory, config);\n if (!paths.bmadDir) {\n log.warn(\"BMAD directory not found\", { directory: ctx.directory });\n return {\n error: \"No BMAD directory found\",\n suggestion:\n paths.suggestion ||\n \"Run 'npx bmad-method@alpha install' to set up BMAD in this project. Athena supports both legacy (docs/) and v6-alpha (_bmad/ + _bmad-output/) structures.\",\n };\n }\n\n log.debug(\"Reading sprint status\", { sprintStatusPath: paths.sprintStatus });\n const sprint = await readBmadSprintStatus(paths.sprintStatus);\n if (!sprint) {\n log.warn(\"Sprint status file not found\", { sprintStatusPath: paths.sprintStatus });\n return {\n error: \"No sprint-status.yaml found\",\n suggestion: \"Run the sprint-planning workflow with BMAD's SM agent first.\",\n };\n }\n\n let resolvedStoryId: string;\n let storyStatus: string | undefined;\n // Keep original input for resolveStoryIdentifier (handles both paths and IDs)\n let storyIdentifier: string | undefined;\n\n if (requestedStoryId) {\n storyIdentifier = stripAtPrefix(requestedStoryId);\n resolvedStoryId = normalizeStoryId(storyIdentifier);\n const found = findStoryInStatus(sprint, resolvedStoryId);\n storyStatus = found?.status;\n } else {\n const nextStory = findNextReadyStory(sprint);\n if (!nextStory) {\n const progress = calculateSprintProgress(sprint);\n log.info(\"No ready stories found\", { progress });\n return {\n error: \"No ready stories found\",\n sprintProgress: {\n completed: progress.done,\n total: progress.total,\n },\n suggestion:\n progress.done === progress.total\n ? \"All stories in current sprint are complete!\"\n : \"No stories are ready-for-dev. Run create-story workflow to create new stories.\",\n };\n }\n resolvedStoryId = nextStory.parsed.normalizedId;\n storyIdentifier = resolvedStoryId;\n storyStatus = nextStory.status;\n }\n\n log.debug(\"Loading story file\", {\n storyId: resolvedStoryId,\n storyIdentifier,\n storiesDir: paths.storiesDir,\n });\n\n const storyResult = await resolveStoryIdentifier(\n paths.storiesDir,\n storyIdentifier,\n ctx.directory\n );\n\n if (!storyResult) {\n log.error(\"Story file not found\", { storyId: resolvedStoryId, storiesDir: paths.storiesDir });\n return {\n error: `Story file not found for ${storyIdToDotFormat(resolvedStoryId)}`,\n suggestion: \"Run 'create-story' workflow with BMAD's SM agent.\",\n };\n }\n\n const storyContent = storyResult.content;\n const storyPath = storyResult.path;\n\n if (storyStatus === \"ready-for-dev\") {\n log.info(\"Auto-transitioning story from ready-for-dev to in-progress\", {\n storyId: resolvedStoryId,\n });\n\n const storyTitle = (await getStoryTitle(storyPath)) ?? undefined;\n\n await updateStoryStatus(paths.sprintStatus, resolvedStoryId, \"in-progress\", storyTitle);\n\n await updateStoryFileStatus(storyPath, \"in-progress\");\n\n const storyKeyInfo = findStoryInStatus(sprint, resolvedStoryId);\n if (storyKeyInfo) {\n await updateEpicStatusIfNeeded(paths.sprintStatus, storyKeyInfo.parsed.epicNum);\n }\n\n storyStatus = \"in-progress\";\n }\n\n log.debug(\"Extracting relevant architecture sections\", {\n architecturePath: paths.architecture,\n });\n const archContent = await extractRelevantArchitecture(paths.architecture, storyContent);\n\n log.debug(\"Extracting relevant PRD sections\", { prdPath: paths.prd });\n const prdContent = await extractRelevantPRD(paths.prd, storyContent);\n\n log.debug(\"Updating story tracker\", { storyId: resolvedStoryId, status: storyStatus });\n await tracker.setCurrentStory(resolvedStoryId, {\n content: storyContent,\n status: (storyStatus as \"in-progress\") || \"in-progress\",\n startedAt: new Date().toISOString(),\n });\n\n const updatedSprint = await readBmadSprintStatus(paths.sprintStatus);\n const progress = updatedSprint ? calculateSprintProgress(updatedSprint) : null;\n\n log.info(\"Story context loaded successfully\", {\n storyId: resolvedStoryId,\n hasArchitecture: !!archContent,\n hasPRD: !!prdContent,\n progress,\n });\n\n return {\n storyId: storyIdToDotFormat(resolvedStoryId),\n story: storyContent,\n architecture: archContent || \"No architecture document found.\",\n prd: prdContent || \"No PRD document found.\",\n sprint: {\n currentEpic: sprint.current_story ? sprint.current_story.split(\"-\")[0] : \"Unknown\",\n completedStories: progress?.done ?? 0,\n pendingStories: (progress?.backlog ?? 0) + (progress?.readyForDev ?? 0),\n blockedStories: progress?.blocked ?? 0,\n },\n instructions: generateImplementationInstructions(storyIdToDotFormat(resolvedStoryId)),\n };\n}\n","/**\n * athena_parallel tool (STUB)\n *\n * Multi-story parallel execution using background agents.\n *\n * TODO: This tool depends on oh-my-opencode's background agent feature.\n * Implementation should:\n * 1. Validate that stories are independent (no file conflicts)\n * 2. Mark all stories as in_progress\n * 3. Spawn background agents for each story\n * 4. Coordinate completion and status updates\n *\n * See: https://github.com/code-yeongyu/oh-my-opencode for background agent API\n */\n\nimport { type ToolDefinition, tool } from \"@opencode-ai/plugin\";\n\n/**\n * Create the athena_parallel tool (stub)\n */\nexport function createParallelTool(): ToolDefinition {\n return tool({\n description: `Execute multiple independent stories in parallel using background agents.\n\nNOTE: This feature is not yet implemented. It requires integration with oh-my-opencode's background agent system.\n\nWhen implemented, this tool will:\n1. Validate that the specified stories have no file conflicts\n2. Mark all stories as in_progress in sprint-status.yaml\n3. Spawn background agents to implement each story\n4. Coordinate completion and report results`,\n\n args: {\n storyIds: tool.schema\n .array(tool.schema.string())\n .describe(\"Array of story IDs to execute in parallel\"),\n waitForCompletion: tool.schema\n .boolean()\n .optional()\n .describe(\"Whether to wait for all stories to complete (default: true)\"),\n },\n\n async execute(args): Promise<string> {\n // TODO: Implement parallel story execution with oh-my-opencode background agents\n return JSON.stringify(\n {\n error: \"Not implemented\",\n message:\n \"Parallel story execution is not yet implemented. This feature requires integration with oh-my-opencode's background agent system.\",\n requestedStories: args.storyIds,\n suggestion: \"For now, implement stories sequentially using /athena-dev for each story.\",\n },\n null,\n 2\n );\n },\n });\n}\n","import type { FindingCategory, FindingSeverity } from \"../../shared/types.js\";\nimport type { FindingCounts } from \"./agent-selector.js\";\n\nexport interface FindingDetail {\n id: string;\n category: FindingCategory;\n severity: FindingSeverity;\n title: string;\n description: string;\n impact: string;\n suggestion: string;\n}\n\nexport interface OracleResponseSummary {\n totalIssues: number;\n highSeverity: number;\n mediumSeverity: number;\n lowSeverity: number;\n recommendation: string;\n}\n\nexport interface OracleResponseFindings {\n security: FindingDetail[];\n logic: FindingDetail[];\n bestPractices: FindingDetail[];\n performance: FindingDetail[];\n}\n\nexport interface StoryFinding {\n storyId: string;\n title: string;\n findings: Partial<OracleResponseFindings>;\n}\n\nexport interface CrossStoryIssue {\n id: string;\n category: FindingCategory;\n severity: FindingSeverity;\n title: string;\n description: string;\n affectedStories: string[];\n suggestion: string;\n}\n\nexport interface ParsedOracleResponse {\n summary: OracleResponseSummary;\n findings?: OracleResponseFindings;\n storyFindings?: StoryFinding[];\n crossStoryIssues?: CrossStoryIssue[];\n}\n\nexport function parseOracleResponse(response: string | null | undefined): ParsedOracleResponse {\n if (!response || typeof response !== \"string\") {\n return createEmptyResponse(\"No response provided\");\n }\n\n try {\n const jsonMatch = response.match(/\\{[\\s\\S]*\\}/);\n if (!jsonMatch) {\n return createEmptyResponse(\"No JSON found in Oracle response\");\n }\n\n const parsed = JSON.parse(jsonMatch[0]) as ParsedOracleResponse;\n\n if (!parsed.summary) {\n return createEmptyResponse(\"No summary in Oracle response\");\n }\n\n return parsed;\n } catch {\n return createEmptyResponse(\"Failed to parse Oracle response as JSON\");\n }\n}\n\nfunction createEmptyResponse(reason: string): ParsedOracleResponse {\n return {\n summary: {\n totalIssues: 0,\n highSeverity: 0,\n mediumSeverity: 0,\n lowSeverity: 0,\n recommendation: reason,\n },\n findings: {\n security: [],\n logic: [],\n bestPractices: [],\n performance: [],\n },\n };\n}\n\nexport function countFindings(parsed: ParsedOracleResponse): FindingCounts {\n const counts: FindingCounts = {\n total: parsed.summary.totalIssues,\n high: parsed.summary.highSeverity,\n medium: parsed.summary.mediumSeverity,\n low: parsed.summary.lowSeverity,\n byCategory: {\n security: 0,\n logic: 0,\n bestPractices: 0,\n performance: 0,\n },\n };\n\n if (parsed.findings) {\n counts.byCategory.security = parsed.findings.security?.length || 0;\n counts.byCategory.logic = parsed.findings.logic?.length || 0;\n counts.byCategory.bestPractices = parsed.findings.bestPractices?.length || 0;\n counts.byCategory.performance = parsed.findings.performance?.length || 0;\n }\n\n if (parsed.storyFindings) {\n for (const story of parsed.storyFindings) {\n counts.byCategory.security += story.findings.security?.length || 0;\n counts.byCategory.logic += story.findings.logic?.length || 0;\n counts.byCategory.bestPractices += story.findings.bestPractices?.length || 0;\n counts.byCategory.performance += story.findings.performance?.length || 0;\n }\n }\n\n return counts;\n}\n\nexport function extractAllFindings(parsed: ParsedOracleResponse): FindingDetail[] {\n const allFindings: FindingDetail[] = [];\n\n if (parsed.findings) {\n for (const category of [\"security\", \"logic\", \"bestPractices\", \"performance\"] as const) {\n const findings = parsed.findings[category] || [];\n for (const finding of findings) {\n allFindings.push({ ...finding, category });\n }\n }\n }\n\n if (parsed.storyFindings) {\n for (const story of parsed.storyFindings) {\n for (const category of [\"security\", \"logic\", \"bestPractices\", \"performance\"] as const) {\n const findings = story.findings[category] || [];\n for (const finding of findings) {\n allFindings.push({ ...finding, category });\n }\n }\n }\n }\n\n return allFindings;\n}\n\nexport function sortFindingsBySeverity(findings: FindingDetail[]): FindingDetail[] {\n const severityOrder: Record<FindingSeverity, number> = { high: 0, medium: 1, low: 2 };\n return [...findings].sort((a, b) => severityOrder[a.severity] - severityOrder[b.severity]);\n}\n","import { readFile } from \"node:fs/promises\";\nimport { basename } from \"node:path\";\nimport { parse as parseYaml } from \"yaml\";\nimport type { BmadAgentFullPersona, BmadAgentType } from \"../../shared/types.js\";\nimport { BMAD_AGENT_FULL_PERSONAS } from \"../../shared/types.js\";\nimport { findAgentFiles } from \"./bmad-finder.js\";\nimport { createPluginLogger } from \"./plugin-logger.js\";\n\nconst log = createPluginLogger(\"persona-loader\");\n\ninterface BmadAgentYaml {\n agent: {\n metadata: {\n id: string;\n name: string;\n title: string;\n icon: string;\n module?: string;\n };\n persona: {\n role: string;\n identity: string;\n communication_style: string;\n principles: string;\n };\n };\n}\n\nfunction filenameToAgentType(filename: string): BmadAgentType | null {\n const base = basename(filename, \".agent.yaml\");\n\n const typeMap: Record<string, BmadAgentType> = {\n analyst: \"analyst\",\n architect: \"architect\",\n dev: \"dev\",\n pm: \"pm\",\n sm: \"sm\",\n tea: \"tea\",\n \"tech-writer\": \"tech-writer\",\n \"ux-designer\": \"ux-designer\",\n };\n\n return typeMap[base] || null;\n}\n\nfunction parsePrinciples(principlesText: string): string[] {\n const lines = principlesText\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter(Boolean);\n\n return lines\n .filter((line) => line.startsWith(\"-\"))\n .map((line) => line.substring(1).trim())\n .filter(Boolean);\n}\n\n/**\n * Parse a BMAD agent YAML file into a persona object.\n *\n * YAML-to-TypeScript field mappings:\n * - agent.persona.role → persona.perspective\n * - agent.persona.communication_style → persona.communicationStyle\n *\n * Falls back to built-in personas for missing or invalid fields.\n */\nasync function parseAgentYaml(\n filePath: string\n): Promise<{ type: BmadAgentType; persona: BmadAgentFullPersona } | null> {\n const agentType = filenameToAgentType(filePath);\n if (!agentType) {\n return null;\n }\n\n try {\n const content = await readFile(filePath, \"utf-8\");\n const data = parseYaml(content) as BmadAgentYaml;\n\n if (!data?.agent?.metadata || !data?.agent?.persona) {\n return null;\n }\n\n const { metadata, persona: personaData } = data.agent;\n const fallback = BMAD_AGENT_FULL_PERSONAS[agentType];\n\n const principles = personaData.principles\n ? parsePrinciples(personaData.principles)\n : fallback.principles;\n\n const persona: BmadAgentFullPersona = {\n type: agentType,\n name: metadata.name || fallback.name,\n title: metadata.title || fallback.title,\n icon: metadata.icon || fallback.icon,\n expertise: fallback.expertise,\n perspective: personaData.role || fallback.perspective,\n identity: personaData.identity || fallback.identity,\n communicationStyle: personaData.communication_style || fallback.communicationStyle,\n principles,\n };\n\n return { type: agentType, persona };\n } catch (error) {\n log.warn(\"Failed to parse agent YAML file\", {\n filePath,\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n return null;\n }\n}\n\nasync function loadFromYamlFiles(\n agentFiles: string[]\n): Promise<Map<BmadAgentType, BmadAgentFullPersona>> {\n const personas = new Map<BmadAgentType, BmadAgentFullPersona>();\n\n for (const filePath of agentFiles) {\n const result = await parseAgentYaml(filePath);\n if (result) {\n personas.set(result.type, result.persona);\n }\n }\n\n return personas;\n}\n\nexport async function loadPersonas(\n projectRoot: string\n): Promise<Map<BmadAgentType, BmadAgentFullPersona>> {\n const agentFiles = await findAgentFiles(projectRoot);\n\n if (agentFiles.length > 0) {\n const yamlPersonas = await loadFromYamlFiles(agentFiles);\n\n if (yamlPersonas.size > 0) {\n const merged = new Map<BmadAgentType, BmadAgentFullPersona>();\n\n for (const [type, persona] of Object.entries(BMAD_AGENT_FULL_PERSONAS)) {\n merged.set(type as BmadAgentType, persona);\n }\n\n for (const [type, persona] of yamlPersonas) {\n merged.set(type, persona);\n }\n\n return merged;\n }\n }\n\n return new Map(\n Object.entries(BMAD_AGENT_FULL_PERSONAS) as [BmadAgentType, BmadAgentFullPersona][]\n );\n}\n\nexport function getPersona(\n personas: Map<BmadAgentType, BmadAgentFullPersona>,\n agentType: BmadAgentType\n): BmadAgentFullPersona {\n return personas.get(agentType) || BMAD_AGENT_FULL_PERSONAS[agentType];\n}\n\nexport function selectAgentsForFinding(category: string, severity: string): BmadAgentType[] {\n const agents: BmadAgentType[] = [];\n\n switch (category) {\n case \"security\":\n agents.push(\"architect\", \"dev\", \"tea\");\n break;\n case \"logic\":\n agents.push(\"dev\", \"tea\", \"analyst\");\n break;\n case \"performance\":\n agents.push(\"architect\", \"dev\");\n break;\n case \"bestPractices\":\n agents.push(\"dev\", \"tech-writer\");\n break;\n default:\n agents.push(\"dev\", \"architect\");\n }\n\n if (severity === \"high\" && !agents.includes(\"pm\")) {\n agents.push(\"pm\");\n }\n\n return agents.slice(0, 3);\n}\n\nexport function buildAgentSystemPrompt(\n persona: BmadAgentFullPersona,\n phase2Analysis?: string\n): string {\n const principlesList = persona.principles.map((p) => `- ${p}`).join(\"\\n\");\n\n let prompt = `You are ${persona.name}, the ${persona.title} from the BMAD team.\n\n**Your Icon**: ${persona.icon}\n**Your Expertise**: ${persona.expertise.join(\", \")}\n**Your Perspective**: ${persona.perspective}\n\n**Your Identity**:\n${persona.identity}\n\n**Your Communication Style**:\n${persona.communicationStyle}\n\n**Your Principles**:\n${principlesList}\n\n**Response Guidelines**:\n- Stay in character as ${persona.name}\n- Speak from your ${persona.perspective} perspective\n- Be concise but substantive (2-4 sentences per point)\n- Reference other agents by name when building on or disagreeing with their points\n- Use your icon ${persona.icon} at the start of your responses`;\n\n if (phase2Analysis) {\n prompt += `\n\n**Your Previous Analysis** (from Phase 2):\n${phase2Analysis}\n\nUse your previous analysis to inform this discussion. You already have context on these findings.`;\n }\n\n return prompt;\n}\n\nexport const _testExports = {\n filenameToAgentType,\n parsePrinciples,\n parseAgentYaml,\n loadFromYamlFiles,\n};\n","import { existsSync } from \"node:fs\";\nimport { readFile, readdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport type { DiscussionRound, FindingCategory, ParsedDeferTarget } from \"../../shared/types.js\";\nimport { findStoriesForEpic } from \"./story-loader.js\";\n\ninterface DeferredFinding {\n id: string;\n title: string;\n description?: string;\n category: FindingCategory;\n severity: string;\n reason?: string;\n originalStoryId: string;\n}\n\ninterface StoryTemplateContext {\n storyId: string;\n epicNumber: string;\n storyNumber: string;\n title: string;\n findings: DeferredFinding[];\n originalStoryId: string;\n reviewDate: string;\n reviewDocumentPath?: string;\n}\n\nexport function parseDeferTarget(\n input: string,\n epicNumber: string,\n existingStoryIds: string[]\n): ParsedDeferTarget {\n const normalized = input.trim().toLowerCase();\n const originalInput = input.trim();\n\n const exactMatch = originalInput.match(/^(\\d+)\\.(\\d+[a-z]?)$/i);\n if (exactMatch) {\n const storyId = `${exactMatch[1]}.${exactMatch[2]}`;\n const exists = existingStoryIds.includes(storyId);\n return {\n type: exists ? \"append-existing\" : \"exact\",\n storyId,\n originalInput,\n };\n }\n\n const dashMatch = originalInput.match(/^(\\d+)-(\\d+[a-z]?)$/i);\n if (dashMatch) {\n const storyId = `${dashMatch[1]}.${dashMatch[2]}`;\n const exists = existingStoryIds.includes(storyId);\n return {\n type: exists ? \"append-existing\" : \"exact\",\n storyId,\n originalInput,\n };\n }\n\n if (normalized.includes(\"new story after\")) {\n const afterMatch = normalized.match(/after\\s+(\\d+\\.?\\d*[a-z]?)/);\n if (afterMatch) {\n const refId = afterMatch[1].includes(\".\") ? afterMatch[1] : `${epicNumber}.${afterMatch[1]}`;\n const nextSubId = getNextSubNumber(refId, existingStoryIds);\n return {\n type: \"new-after\",\n storyId: nextSubId,\n referenceStoryId: refId,\n originalInput,\n };\n }\n }\n\n if (normalized.includes(\"new story before\")) {\n const beforeMatch = normalized.match(/before\\s+(\\d+\\.?\\d*[a-z]?)/);\n if (beforeMatch) {\n const refId = beforeMatch[1].includes(\".\")\n ? beforeMatch[1]\n : `${epicNumber}.${beforeMatch[1]}`;\n const [epicNum, storyNum] = refId.split(\".\");\n const prevNum = Number.parseInt(storyNum, 10) - 1;\n if (prevNum > 0) {\n const prevId = `${epicNum}.${prevNum}`;\n const nextSubId = getNextSubNumber(prevId, existingStoryIds);\n return {\n type: \"new-before\",\n storyId: nextSubId,\n referenceStoryId: refId,\n originalInput,\n };\n }\n }\n }\n\n if (normalized.includes(\"new story\") || normalized === \"new\" || normalized === \"end of epic\") {\n const nextId = getNextStoryNumber(epicNumber, existingStoryIds);\n return {\n type: \"new-end\",\n storyId: nextId,\n originalInput,\n };\n }\n\n if (\n normalized.includes(\"next sprint\") ||\n normalized.includes(\"later\") ||\n normalized.includes(\"backlog\")\n ) {\n const nextId = getNextStoryNumber(epicNumber, existingStoryIds);\n return {\n type: \"new-end\",\n storyId: nextId,\n originalInput,\n };\n }\n\n const storyIdMatch = originalInput.match(/(\\d+)[.\\-](\\d+[a-z]?)/i);\n if (storyIdMatch) {\n const storyId = `${storyIdMatch[1]}.${storyIdMatch[2]}`;\n const exists = existingStoryIds.includes(storyId);\n return {\n type: exists ? \"append-existing\" : \"exact\",\n storyId,\n originalInput,\n };\n }\n\n const nextId = getNextStoryNumber(epicNumber, existingStoryIds);\n return {\n type: \"new-end\",\n storyId: nextId,\n originalInput,\n };\n}\n\nexport function getNextSubNumber(afterStoryId: string, existingIds: string[]): string {\n const [epicNum, storyNum] = afterStoryId.split(\".\");\n const baseNum = storyNum.replace(/[a-z]+$/i, \"\");\n\n const existingSubs = existingIds\n .filter((id) => {\n const [e, s] = id.split(\".\");\n return e === epicNum && s.startsWith(baseNum) && /[a-z]$/i.test(s);\n })\n .map((id) => {\n const suffix = id.split(\".\")[1].replace(/^\\d+/, \"\");\n return suffix;\n })\n .filter((s) => s.length > 0)\n .sort();\n\n if (existingSubs.length === 0) {\n return `${epicNum}.${baseNum}a`;\n }\n\n const lastSuffix = existingSubs[existingSubs.length - 1];\n const nextChar = String.fromCharCode(lastSuffix.charCodeAt(lastSuffix.length - 1) + 1);\n return `${epicNum}.${baseNum}${nextChar}`;\n}\n\nexport function getNextStoryNumber(epicNumber: string, existingIds: string[]): string {\n const epicIds = existingIds\n .filter((id) => id.startsWith(`${epicNumber}.`))\n .map((id) => {\n const num = id.split(\".\")[1];\n const baseNum = Number.parseInt(num.replace(/[a-z]+$/i, \"\"), 10);\n return Number.isNaN(baseNum) ? 0 : baseNum;\n });\n\n const maxNum = epicIds.length > 0 ? Math.max(...epicIds) : 0;\n return `${epicNumber}.${maxNum + 1}`;\n}\n\nexport async function getExistingStoryIds(\n storiesDir: string,\n epicNumber: string\n): Promise<string[]> {\n const stories = await findStoriesForEpic(storiesDir, epicNumber);\n return stories.map((s) => s.id);\n}\n\nexport async function loadTemplateFromExistingStory(\n storiesDir: string,\n epicNumber: string\n): Promise<string | null> {\n if (!existsSync(storiesDir)) {\n return null;\n }\n\n const files = await readdir(storiesDir);\n const epicPattern = new RegExp(`^(story-)?${epicNumber}-(\\\\d+)`, \"i\");\n\n const epicFiles = files.filter((f) => epicPattern.test(f) && f.endsWith(\".md\")).sort();\n\n if (epicFiles.length === 0) {\n return null;\n }\n\n const templateFile = epicFiles[0];\n const content = await readFile(join(storiesDir, templateFile), \"utf-8\");\n return content;\n}\n\nfunction extractTemplateStructure(existingContent: string): string[] {\n const lines = existingContent.split(\"\\n\");\n const sections: string[] = [];\n let currentSection = \"\";\n\n for (const line of lines) {\n if (line.startsWith(\"# \") || line.startsWith(\"## \")) {\n if (currentSection) {\n sections.push(currentSection.trim());\n }\n currentSection = line;\n } else {\n currentSection += `\\n${line}`;\n }\n }\n\n if (currentSection) {\n sections.push(currentSection.trim());\n }\n\n return sections;\n}\n\nexport function generateStoryContent(\n context: StoryTemplateContext,\n _existingTemplate?: string\n): string {\n const { storyId, title, findings, originalStoryId, reviewDate, reviewDocumentPath } = context;\n\n const acceptanceCriteria = findings\n .map((f) => {\n const prefix = getCategoryPrefix(f.category);\n return `- [ ] ${prefix}: ${f.title}${f.description ? ` - ${f.description}` : \"\"}`;\n })\n .join(\"\\n\");\n\n const devNotes = findings\n .map((f) => {\n return `- **${f.title}**\n - Severity: ${f.severity}\n - Category: ${f.category}\n - Reason for deferral: ${f.reason || \"Deferred from party review\"}`;\n })\n .join(\"\\n\");\n\n const content = `# Story ${storyId}: ${title}\n\nStatus: backlog\n\n## Story\n\nAs a developer,\nI want to address the deferred findings from the party review,\nso that the codebase maintains quality standards.\n\n## Acceptance Criteria\n\n${acceptanceCriteria}\n\n## Tasks / Subtasks\n\n- [ ] Review each deferred finding\n- [ ] Implement fixes for each acceptance criterion\n- [ ] Run quality checks (LSP diagnostics, build, tests)\n\n## Dev Notes\n\nThese findings were deferred from the party review of Story ${originalStoryId} on ${reviewDate}.\n\n### Original Context\n\n${devNotes}\n\n### References\n\n${reviewDocumentPath ? `- Party Review: ${reviewDocumentPath}` : \"\"}\n- Original Story: Story ${originalStoryId}\n\n## Dev Agent Record\n\n### Agent Model Used\n\n(To be filled during implementation)\n\n### Completion Notes List\n\n(To be filled during implementation)\n\n### File List\n\n(To be filled during implementation)\n`;\n\n return content;\n}\n\nfunction getCategoryPrefix(category: FindingCategory): string {\n switch (category) {\n case \"security\":\n return \"[Security]\";\n case \"performance\":\n return \"[Performance]\";\n case \"bestPractices\":\n return \"[Quality]\";\n default:\n return \"[Logic]\";\n }\n}\n\nexport function generateTitleFromFindings(findings: DeferredFinding[]): string {\n if (findings.length === 1) {\n const f = findings[0];\n const shortTitle = f.title.length > 50 ? `${f.title.substring(0, 47)}...` : f.title;\n return shortTitle;\n }\n\n const categories = [...new Set(findings.map((f) => f.category))];\n if (categories.length === 1) {\n return `Deferred ${formatCategory(categories[0])} Findings`;\n }\n\n return \"Deferred Findings from Party Review\";\n}\n\nfunction formatCategory(category: FindingCategory): string {\n switch (category) {\n case \"security\":\n return \"Security\";\n case \"performance\":\n return \"Performance\";\n case \"bestPractices\":\n return \"Quality\";\n default:\n return \"Logic\";\n }\n}\n\nexport function roundsToFindings(\n rounds: DiscussionRound[],\n originalStoryId: string\n): DeferredFinding[] {\n return rounds.map((round) => ({\n id: round.findingId,\n title: round.findingTitle,\n category: round.findingCategory,\n severity: round.findingSeverity,\n reason: round.decisionReason,\n originalStoryId,\n }));\n}\n\nexport function storyIdToFilename(storyId: string, title?: string): string {\n const [epic, num] = storyId.split(\".\");\n const kebabTitle = title\n ? `-${title\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-|-$/g, \"\")\n .substring(0, 30)}`\n : \"\";\n return `story-${epic}-${num}${kebabTitle}.md`;\n}\n\nexport const _testExports = {\n extractTemplateStructure,\n getCategoryPrefix,\n formatCategory,\n};\n","import { existsSync } from \"node:fs\";\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport type {\n AppliedStoryUpdate,\n ApplyDecisionsResult,\n AthenaConfig,\n DiscussionRound,\n ParsedDeferTarget,\n PartyDiscussionState,\n} from \"../../shared/types.js\";\nimport { getBmadPaths } from \"./bmad-finder.js\";\nimport { extractStoryIdFromFindingId, findStoryFile } from \"./story-loader.js\";\nimport {\n generateStoryContent,\n generateTitleFromFindings,\n getExistingStoryIds,\n loadTemplateFromExistingStory,\n parseDeferTarget,\n roundsToFindings,\n storyIdToFilename,\n} from \"./story-template.js\";\nimport { addStoryToSprintStatus } from \"./yaml-handler.js\";\n\ninterface StoryUpdate {\n storyId: string;\n filePath: string;\n addedCriteria: string[];\n addedNotes: string[];\n success: boolean;\n error?: string;\n}\n\nfunction groupDecisionsByStory(\n rounds: DiscussionRound[],\n sessionIdentifier: string\n): Map<string, DiscussionRound[]> {\n const byStory = new Map<string, DiscussionRound[]>();\n\n for (const round of rounds) {\n const storyId = extractStoryIdFromFindingId(round.findingId, sessionIdentifier);\n\n const existing = byStory.get(storyId) || [];\n existing.push(round);\n byStory.set(storyId, existing);\n }\n\n return byStory;\n}\n\nfunction groupDeferredByTarget(\n rounds: DiscussionRound[],\n epicNumber: string,\n existingStoryIds: string[]\n): Map<string, { target: ParsedDeferTarget; rounds: DiscussionRound[] }> {\n const byTarget = new Map<string, { target: ParsedDeferTarget; rounds: DiscussionRound[] }>();\n\n for (const round of rounds) {\n if (round.decision !== \"defer\" || !round.deferredTo) continue;\n\n const target = parseDeferTarget(round.deferredTo, epicNumber, existingStoryIds);\n const key = target.storyId;\n\n const existing = byTarget.get(key);\n if (existing) {\n existing.rounds.push(round);\n } else {\n byTarget.set(key, { target, rounds: [round] });\n }\n }\n\n return byTarget;\n}\n\nfunction generateAcceptanceCriteria(round: DiscussionRound): string {\n const prefix = getCategoryPrefix(round.findingCategory);\n return `- [ ] ${prefix}: ${round.findingTitle}`;\n}\n\nfunction getCategoryPrefix(category: string): string {\n switch (category) {\n case \"security\":\n return \"[Security]\";\n case \"performance\":\n return \"[Performance]\";\n case \"bestPractices\":\n return \"[Quality]\";\n default:\n return \"[Logic]\";\n }\n}\n\nfunction generateImplementationNote(round: DiscussionRound): string {\n const date = new Date().toISOString().split(\"T\")[0];\n let note = `### ${round.findingTitle} (${date})\\n`;\n note += `- **Category**: ${round.findingCategory}\\n`;\n note += `- **Severity**: ${round.findingSeverity}\\n`;\n note += `- **Decision**: ${round.decision}`;\n\n if (round.decisionReason) {\n note += `\\n- **Reason**: ${round.decisionReason}`;\n }\n\n if (round.deferredTo) {\n note += `\\n- **Deferred to**: Story ${round.deferredTo}`;\n }\n\n return note;\n}\n\nasync function updateStoryFile(\n filePath: string,\n acceptedRounds: DiscussionRound[],\n deferredRounds: DiscussionRound[]\n): Promise<StoryUpdate> {\n const storyId = filePath.match(/story-(\\d+-\\d+[a-z]?)/)?.[1]?.replace(\"-\", \".\") || \"unknown\";\n\n if (!existsSync(filePath)) {\n return {\n storyId,\n filePath,\n addedCriteria: [],\n addedNotes: [],\n success: false,\n error: `Story file not found: ${filePath}`,\n };\n }\n\n try {\n let content = await readFile(filePath, \"utf-8\");\n const addedCriteria: string[] = [];\n const addedNotes: string[] = [];\n\n if (acceptedRounds.length > 0) {\n const acSection = content.match(/## Acceptance Criteria[\\s\\S]*?(?=\\n##|\\n---|$)/);\n\n if (acSection && acSection.index !== undefined) {\n const newCriteria = acceptedRounds.map(generateAcceptanceCriteria);\n const insertPoint = acSection.index + acSection[0].length;\n\n const criteriaText = newCriteria.join(\"\\n\");\n const insertion = `\\n\\n### From Party Review\\n${criteriaText}`;\n content = `${content.slice(0, insertPoint)}${insertion}${content.slice(insertPoint)}`;\n\n addedCriteria.push(...newCriteria);\n }\n }\n\n if (deferredRounds.length > 0 || acceptedRounds.length > 0) {\n const hasNotesSection = content.includes(\"## Implementation Notes\");\n\n const notes = [\n ...acceptedRounds.map(generateImplementationNote),\n ...deferredRounds.map(generateImplementationNote),\n ];\n\n if (hasNotesSection) {\n const notesMatch = content.match(/## Implementation Notes/);\n if (notesMatch && notesMatch.index !== undefined) {\n const insertPoint = notesMatch.index + notesMatch[0].length;\n const notesText = notes.join(\"\\n\\n\");\n const insertion = `\\n\\n${notesText}`;\n content = `${content.slice(0, insertPoint)}${insertion}${content.slice(insertPoint)}`;\n }\n } else {\n const notesText = notes.join(\"\\n\\n\");\n content = `${content}\\n\\n## Implementation Notes\\n\\n${notesText}`;\n }\n\n addedNotes.push(...notes);\n }\n\n await writeFile(filePath, content, \"utf-8\");\n\n return {\n storyId,\n filePath,\n addedCriteria,\n addedNotes,\n success: true,\n };\n } catch (error) {\n return {\n storyId,\n filePath,\n addedCriteria: [],\n addedNotes: [],\n success: false,\n error: error instanceof Error ? error.message : \"Unknown error\",\n };\n }\n}\n\nasync function appendToExistingStory(\n filePath: string,\n rounds: DiscussionRound[],\n originalStoryId: string\n): Promise<AppliedStoryUpdate> {\n const storyId = filePath.match(/story-(\\d+-\\d+[a-z]?)/)?.[1]?.replace(\"-\", \".\") || \"unknown\";\n\n if (!existsSync(filePath)) {\n return {\n storyId,\n filePath,\n action: \"appended\",\n addedCriteria: [],\n addedNotes: [],\n success: false,\n error: `Story file not found: ${filePath}`,\n };\n }\n\n try {\n let content = await readFile(filePath, \"utf-8\");\n const addedCriteria: string[] = [];\n const addedNotes: string[] = [];\n const date = new Date().toISOString().split(\"T\")[0];\n\n const hasNotesSection = content.includes(\"## Implementation Notes\");\n const deferralHeader = `\\n\\n### Deferred from Story ${originalStoryId} (${date})\\n\\n`;\n const notes = rounds.map((r) => {\n const prefix = getCategoryPrefix(r.findingCategory);\n return `- [ ] ${prefix}: ${r.findingTitle}${r.decisionReason ? ` (${r.decisionReason})` : \"\"}`;\n });\n const notesText = deferralHeader + notes.join(\"\\n\");\n\n if (hasNotesSection) {\n const notesMatch = content.match(/## Implementation Notes/);\n if (notesMatch && notesMatch.index !== undefined) {\n const insertPoint = notesMatch.index + notesMatch[0].length;\n content = `${content.slice(0, insertPoint)}${notesText}${content.slice(insertPoint)}`;\n }\n } else {\n content = `${content}\\n\\n## Implementation Notes${notesText}`;\n }\n\n addedNotes.push(...notes);\n\n await writeFile(filePath, content, \"utf-8\");\n\n return {\n storyId,\n filePath,\n action: \"appended\",\n addedCriteria,\n addedNotes,\n success: true,\n };\n } catch (error) {\n return {\n storyId,\n filePath,\n action: \"appended\",\n addedCriteria: [],\n addedNotes: [],\n success: false,\n error: error instanceof Error ? error.message : \"Unknown error\",\n };\n }\n}\n\nasync function createStoryFromDeferredFindings(\n storiesDir: string,\n target: ParsedDeferTarget,\n rounds: DiscussionRound[],\n originalStoryId: string,\n sprintStatusPath: string,\n reviewDocumentPath?: string\n): Promise<AppliedStoryUpdate> {\n const epicNumber = target.storyId.split(\".\")[0];\n const findings = roundsToFindings(rounds, originalStoryId);\n const title = generateTitleFromFindings(findings);\n const date = new Date().toISOString().split(\"T\")[0];\n\n const template = await loadTemplateFromExistingStory(storiesDir, epicNumber);\n\n const context = {\n storyId: target.storyId,\n epicNumber,\n storyNumber: target.storyId.split(\".\")[1],\n title,\n findings,\n originalStoryId,\n reviewDate: date,\n reviewDocumentPath,\n };\n\n const content = generateStoryContent(context, template || undefined);\n const filename = storyIdToFilename(target.storyId, title);\n const filePath = join(storiesDir, filename);\n\n try {\n if (!existsSync(storiesDir)) {\n await mkdir(storiesDir, { recursive: true });\n }\n\n await writeFile(filePath, content, \"utf-8\");\n\n await addStoryToSprintStatus(sprintStatusPath, target.storyId, \"backlog\");\n\n return {\n storyId: target.storyId,\n filePath,\n action: \"created\",\n addedCriteria: findings.map((f) => `- [ ] [${f.category}]: ${f.title}`),\n addedNotes: [],\n success: true,\n deferTarget: target,\n };\n } catch (error) {\n return {\n storyId: target.storyId,\n filePath,\n action: \"created\",\n addedCriteria: [],\n addedNotes: [],\n success: false,\n error: error instanceof Error ? error.message : \"Unknown error\",\n deferTarget: target,\n };\n }\n}\n\nasync function updateReviewDocument(\n reviewPath: string,\n state: PartyDiscussionState\n): Promise<boolean> {\n if (!existsSync(reviewPath)) {\n return false;\n }\n\n try {\n let content = await readFile(reviewPath, \"utf-8\");\n\n const decisionSection = generateDecisionSection(state);\n content = `${content}\\n\\n---\\n\\n${decisionSection}`;\n\n await writeFile(reviewPath, content, \"utf-8\");\n return true;\n } catch {\n return false;\n }\n}\n\nfunction generateDecisionSection(state: PartyDiscussionState): string {\n const counts = { accepted: 0, deferred: 0, rejected: 0 };\n\n for (const round of state.completedRounds) {\n if (round.decision === \"accept\") counts.accepted++;\n else if (round.decision === \"defer\") counts.deferred++;\n else if (round.decision === \"reject\") counts.rejected++;\n }\n\n const date = new Date().toISOString().split(\"T\")[0];\n const findingLines: string[] = [];\n\n for (const round of state.completedRounds) {\n const icon = round.decision === \"accept\" ? \"✅\" : round.decision === \"defer\" ? \"⏸️\" : \"❌\";\n const lines = [`${icon} **${round.findingTitle}**`, `- Decision: ${round.decision}`];\n if (round.decisionReason) {\n lines.push(`- Reason: ${round.decisionReason}`);\n }\n if (round.deferredTo) {\n lines.push(`- Deferred to: Story ${round.deferredTo}`);\n }\n findingLines.push(lines.join(\"\\n\"));\n }\n\n return `## Party Discussion Decisions\n\n**Date**: ${date}\n**Session ID**: ${state.sessionId}\n\n### Summary\n- ✅ Accepted: ${counts.accepted}\n- ⏸️ Deferred: ${counts.deferred}\n- ❌ Rejected: ${counts.rejected}\n\n### Decisions by Finding\n\n${findingLines.join(\"\\n\\n\")}`;\n}\n\nexport async function generateDecisionsAppliedDocument(\n reviewFolderPath: string,\n state: PartyDiscussionState,\n result: ApplyDecisionsResult\n): Promise<string | null> {\n const date = new Date().toISOString().split(\"T\")[0];\n const docPath = join(reviewFolderPath, \"decisions-applied.md\");\n\n const storiesUpdatedList = result.storiesUpdated\n .filter((s) => s.success)\n .map(\n (s) =>\n `- ✅ Updated: ${s.filePath} (${s.addedCriteria.length} criteria, ${s.addedNotes.length} notes)`\n )\n .join(\"\\n\");\n\n const storiesCreatedList = result.storiesCreated\n .filter((s) => s.success)\n .map((s) => `- 📝 Created: ${s.filePath} (${s.addedCriteria.length} criteria)`)\n .join(\"\\n\");\n\n const storiesAppendedList = result.storiesAppended\n .filter((s) => s.success)\n .map((s) => `- 📎 Appended to: ${s.filePath} (${s.addedNotes.length} items)`)\n .join(\"\\n\");\n\n const failedList = [...result.storiesUpdated, ...result.storiesCreated, ...result.storiesAppended]\n .filter((s) => !s.success)\n .map((s) => `- ❌ Failed: ${s.storyId} - ${s.error}`)\n .join(\"\\n\");\n\n const content = `# Decisions Applied\n\n**Date**: ${date}\n**Session ID**: ${state.sessionId}\n**Scope**: ${state.scope} - ${state.identifier}\n\n## Summary\n\n| Metric | Count |\n|--------|-------|\n| Findings Accepted | ${result.summary.accepted} |\n| Findings Deferred | ${result.summary.deferred} |\n| Findings Rejected | ${result.summary.rejected} |\n| Stories Modified | ${result.summary.storiesModified} |\n| Stories Created | ${result.summary.storiesCreated} |\n\n## Applied Changes\n\n### Stories Updated\n${storiesUpdatedList || \"(none)\"}\n\n### Stories Created\n${storiesCreatedList || \"(none)\"}\n\n### Stories Appended To\n${storiesAppendedList || \"(none)\"}\n\n${failedList ? `### Failed Operations\\n${failedList}` : \"\"}\n\n${result.warnings && result.warnings.length > 0 ? `## Warnings\\n${result.warnings.map((w) => `- ⚠️ ${w}`).join(\"\\n\")}` : \"\"}\n\n## Next Steps\n\n${result.storiesCreated.length > 0 ? \"- New stories created with status 'backlog' and added to sprint-status.yaml\" : \"\"}\n${result.storiesUpdated.length > 0 ? \"- Updated stories have new acceptance criteria from the party review\" : \"\"}\n${result.storiesAppended.length > 0 ? \"- Existing stories have deferred findings in their Implementation Notes section\" : \"\"}\n- Run \\`/athena-dev\\` to implement the next story\n\n---\n\n*Generated by OpenCode Athena Party Review*\n`;\n\n try {\n await writeFile(docPath, content, \"utf-8\");\n return docPath;\n } catch {\n return null;\n }\n}\n\nexport async function applyDecisions(\n projectRoot: string,\n state: PartyDiscussionState,\n reviewDocumentPath?: string,\n config?: AthenaConfig\n): Promise<ApplyDecisionsResult> {\n const paths = await getBmadPaths(projectRoot, config);\n const byStory = groupDecisionsByStory(state.completedRounds, state.identifier);\n const epicNumber = state.identifier.split(\".\")[0];\n\n const existingStoryIds = await getExistingStoryIds(paths.storiesDir, epicNumber);\n\n const storiesUpdated: AppliedStoryUpdate[] = [];\n const storiesCreated: AppliedStoryUpdate[] = [];\n const storiesAppended: AppliedStoryUpdate[] = [];\n const warnings: string[] = [];\n\n let totalAccepted = 0;\n let totalDeferred = 0;\n let totalRejected = 0;\n\n for (const [storyId, rounds] of byStory) {\n const storyFileResult = await findStoryFile(paths.storiesDir, storyId);\n if (!storyFileResult) {\n continue;\n }\n\n const accepted = rounds.filter((r) => r.decision === \"accept\");\n const deferred = rounds.filter((r) => r.decision === \"defer\");\n const rejected = rounds.filter((r) => r.decision === \"reject\");\n\n totalAccepted += accepted.length;\n totalDeferred += deferred.length;\n totalRejected += rejected.length;\n\n if (accepted.length > 0 || deferred.length > 0) {\n const update = await updateStoryFile(storyFileResult.path, accepted, deferred);\n storiesUpdated.push({\n ...update,\n action: \"updated\",\n });\n }\n }\n\n const deferredRounds = state.completedRounds.filter(\n (r) => r.decision === \"defer\" && r.deferredTo\n );\n const deferredByTarget = groupDeferredByTarget(deferredRounds, epicNumber, existingStoryIds);\n\n for (const [targetId, { target, rounds }] of deferredByTarget) {\n const originalStoryId = state.identifier;\n\n if (target.type === \"append-existing\") {\n const storyFileResult = await findStoryFile(paths.storiesDir, targetId);\n if (storyFileResult) {\n const appendResult = await appendToExistingStory(\n storyFileResult.path,\n rounds,\n originalStoryId\n );\n storiesAppended.push(appendResult);\n } else {\n warnings.push(`Could not find story ${targetId} to append deferred findings`);\n }\n } else if (\n target.type === \"exact\" ||\n target.type === \"new-end\" ||\n target.type === \"new-after\" ||\n target.type === \"new-before\"\n ) {\n const reviewFolder = reviewDocumentPath ? dirname(reviewDocumentPath) : undefined;\n const createResult = await createStoryFromDeferredFindings(\n paths.storiesDir,\n target,\n rounds,\n originalStoryId,\n paths.sprintStatus,\n reviewFolder\n );\n storiesCreated.push(createResult);\n\n if (\n target.originalInput.toLowerCase().includes(\"next sprint\") ||\n target.originalInput.toLowerCase().includes(\"later\")\n ) {\n warnings.push(\n `Story ${targetId} created for vague defer target \"${target.originalInput}\" - review sprint-status.yaml for correct ordering`\n );\n }\n }\n }\n\n let reviewDocumentUpdated = false;\n if (reviewDocumentPath) {\n reviewDocumentUpdated = await updateReviewDocument(reviewDocumentPath, state);\n }\n\n const result: ApplyDecisionsResult = {\n success: true,\n storiesUpdated,\n storiesCreated,\n storiesAppended,\n reviewDocumentUpdated,\n summary: {\n accepted: totalAccepted,\n deferred: totalDeferred,\n rejected: totalRejected,\n storiesModified: storiesUpdated.filter((u) => u.success).length,\n storiesCreated: storiesCreated.filter((u) => u.success).length,\n },\n warnings: warnings.length > 0 ? warnings : undefined,\n };\n\n const reviewFolder = reviewDocumentPath ? dirname(reviewDocumentPath) : null;\n if (reviewFolder) {\n const docPath = await generateDecisionsAppliedDocument(reviewFolder, state, result);\n if (docPath) {\n result.decisionsAppliedDocument = docPath;\n }\n }\n\n return result;\n}\n\nexport function formatAppliedUpdatesSummary(result: ApplyDecisionsResult): string {\n const parts: string[] = [];\n\n parts.push(\"## Decisions Applied\\n\");\n parts.push(\"**Summary**:\");\n parts.push(`- ✅ Accepted findings: ${result.summary.accepted}`);\n parts.push(`- ⏸️ Deferred findings: ${result.summary.deferred}`);\n parts.push(`- ❌ Rejected findings: ${result.summary.rejected}`);\n parts.push(`- 📝 Stories modified: ${result.summary.storiesModified}`);\n parts.push(`- 📄 Stories created: ${result.summary.storiesCreated}`);\n parts.push(\"\");\n\n if (result.storiesUpdated.length > 0) {\n parts.push(\"### Updated Stories\\n\");\n for (const update of result.storiesUpdated) {\n if (update.success) {\n parts.push(`- ✅ ${update.filePath}`);\n if (update.addedCriteria.length > 0) {\n parts.push(` - Added ${update.addedCriteria.length} acceptance criteria`);\n }\n if (update.addedNotes.length > 0) {\n parts.push(` - Added ${update.addedNotes.length} implementation notes`);\n }\n } else {\n parts.push(`- ❌ ${update.filePath}: ${update.error}`);\n }\n }\n parts.push(\"\");\n }\n\n if (result.storiesCreated.length > 0) {\n parts.push(\"### Created Stories\\n\");\n for (const created of result.storiesCreated) {\n if (created.success) {\n parts.push(`- 📄 ${created.filePath}`);\n parts.push(` - Story ID: ${created.storyId}`);\n parts.push(\n ` - ${created.addedCriteria.length} acceptance criteria from deferred findings`\n );\n } else {\n parts.push(`- ❌ Failed to create ${created.storyId}: ${created.error}`);\n }\n }\n parts.push(\"\");\n }\n\n if (result.storiesAppended.length > 0) {\n parts.push(\"### Appended to Existing Stories\\n\");\n for (const appended of result.storiesAppended) {\n if (appended.success) {\n parts.push(`- 📎 ${appended.filePath}`);\n parts.push(\n ` - ${appended.addedNotes.length} deferred items added to Implementation Notes`\n );\n } else {\n parts.push(`- ❌ Failed to append to ${appended.storyId}: ${appended.error}`);\n }\n }\n parts.push(\"\");\n }\n\n if (result.warnings && result.warnings.length > 0) {\n parts.push(\"### Warnings\\n\");\n for (const warning of result.warnings) {\n parts.push(`- ⚠️ ${warning}`);\n }\n parts.push(\"\");\n }\n\n if (result.decisionsAppliedDocument) {\n parts.push(\"### Documentation\\n\");\n parts.push(`- 📋 Decisions applied document: ${result.decisionsAppliedDocument}`);\n }\n\n if (result.reviewDocumentUpdated) {\n parts.push(\"- 📄 Review document updated with decisions\");\n }\n\n return parts.join(\"\\n\");\n}\n\nexport function formatUpdateSummary(result: ApplyDecisionsResult): string {\n return formatAppliedUpdatesSummary(result);\n}\n","import { randomUUID } from \"node:crypto\";\nimport { existsSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { type ToolDefinition, tool } from \"@opencode-ai/plugin\";\nimport type { PluginInput } from \"@opencode-ai/plugin\";\nimport type {\n AgentDiscussionResponse,\n AthenaConfig,\n BmadAgentFullPersona,\n BmadAgentType,\n DiscussionAgendaItem,\n DiscussionRound,\n FindingCategory,\n FindingSeverity,\n PartyDiscussionResult,\n PartyDiscussionState,\n Phase1FullData,\n Phase2Result,\n ReviewDecision,\n} from \"../../shared/types.js\";\nimport { extractAllFindings, parseOracleResponse } from \"../utils/oracle-parser.js\";\nimport { getPersona, loadPersonas, selectAgentsForFinding } from \"../utils/persona-loader.js\";\nimport { createPluginLogger } from \"../utils/plugin-logger.js\";\nimport { applyDecisions } from \"../utils/story-updater.js\";\n\nconst log = createPluginLogger(\"party-discussion\");\nconst SESSION_TTL_MS = 30 * 60 * 1000;\nconst MAX_SESSIONS = 10;\n\ninterface SessionWithMeta {\n state: PartyDiscussionState;\n lastAccessedAt: number;\n reviewFolderPath?: string;\n}\n\nconst activeSessions = new Map<string, SessionWithMeta>();\n\nfunction cleanupStaleSessions(): void {\n const now = Date.now();\n const sessionsToDelete: string[] = [];\n\n for (const [id, session] of activeSessions) {\n if (now - session.lastAccessedAt > SESSION_TTL_MS) {\n sessionsToDelete.push(id);\n }\n }\n\n for (const id of sessionsToDelete) {\n activeSessions.delete(id);\n }\n\n const capacityThreshold = Math.ceil(MAX_SESSIONS * 0.8);\n if (activeSessions.size >= capacityThreshold && activeSessions.size < MAX_SESSIONS) {\n log.warn(\"Party discussion session capacity warning\", {\n currentSessions: activeSessions.size,\n maxSessions: MAX_SESSIONS,\n utilizationPercent: Math.round((activeSessions.size / MAX_SESSIONS) * 100),\n message: \"Approaching session limit. Oldest sessions will be evicted when limit is reached.\",\n });\n }\n\n if (activeSessions.size > MAX_SESSIONS) {\n const sortedSessions = Array.from(activeSessions.entries()).sort(\n (a, b) => a[1].lastAccessedAt - b[1].lastAccessedAt\n );\n\n const toRemove = sortedSessions.slice(0, activeSessions.size - MAX_SESSIONS);\n for (const [id] of toRemove) {\n activeSessions.delete(id);\n }\n }\n}\n\nfunction getSession(sessionId: string): PartyDiscussionState | null {\n const session = activeSessions.get(sessionId);\n if (!session) return null;\n\n session.lastAccessedAt = Date.now();\n return session.state;\n}\n\nfunction getSessionWithMeta(sessionId: string): SessionWithMeta | null {\n const session = activeSessions.get(sessionId);\n if (!session) return null;\n\n session.lastAccessedAt = Date.now();\n return session;\n}\n\nfunction setSession(state: PartyDiscussionState, reviewFolderPath?: string): void {\n activeSessions.set(state.sessionId, {\n state,\n lastAccessedAt: Date.now(),\n reviewFolderPath,\n });\n}\n\nfunction buildAgenda(phase1: Phase1FullData, phase2?: Phase2Result): DiscussionAgendaItem[] {\n const agenda: DiscussionAgendaItem[] = [];\n\n const highSeverityFindings = extractHighSeverityFindings(phase1);\n for (const finding of highSeverityFindings) {\n const agentPositions = phase2 ? getAgentPositionsForFinding(finding.id, phase2) : {};\n agenda.push({\n id: `agenda-${finding.id}`,\n findingId: finding.id,\n topic: finding.title,\n type: \"high-severity\",\n severity: finding.severity,\n category: finding.category,\n relevantAgents: selectAgentsForFinding(finding.category, finding.severity),\n agentPositions,\n discussed: false,\n });\n }\n\n if (phase2) {\n for (const debate of phase2.debatePoints) {\n const existingItem = agenda.find((a) => a.topic === debate.topic);\n if (!existingItem) {\n const positions: Partial<Record<BmadAgentType, string>> = {};\n for (const pos of debate.positions) {\n positions[pos.agent] = pos.position;\n }\n agenda.push({\n id: `agenda-debate-${agenda.length}`,\n findingId: `debate-${agenda.length}`,\n topic: debate.topic,\n type: \"disputed\",\n severity: \"medium\",\n category: \"logic\",\n relevantAgents: debate.positions.map((p) => p.agent),\n agentPositions: positions,\n discussed: false,\n });\n }\n }\n }\n\n return agenda;\n}\n\ninterface FindingInfo {\n id: string;\n title: string;\n severity: FindingSeverity;\n category: FindingCategory;\n}\n\nfunction extractHighSeverityFindings(phase1: Phase1FullData): FindingInfo[] {\n const highCount = phase1.findings?.high ?? 0;\n\n // Handle missing oracleAnalysis gracefully\n if (!phase1.oracleAnalysis) {\n // Fallback to placeholder findings based on count\n if (highCount > 0) {\n return Array.from({ length: highCount }, (_, i) => ({\n id: `high-${i + 1}`,\n title: `High severity finding ${i + 1}`,\n severity: \"high\" as const,\n category: \"logic\" as FindingCategory,\n }));\n }\n return [];\n }\n\n // Use proper JSON parsing from oracle-parser\n const parsed = parseOracleResponse(phase1.oracleAnalysis);\n const allFindings = extractAllFindings(parsed);\n const highFindings = allFindings.filter((f) => f.severity === \"high\");\n\n if (highFindings.length > 0) {\n return highFindings.map((f, i) => ({\n id: f.id || `high-${i + 1}`,\n title: f.title,\n severity: \"high\" as const,\n category: f.category,\n }));\n }\n\n // Fallback if parsing didn't find high findings but count says otherwise\n if (highCount > 0) {\n return Array.from({ length: highCount }, (_, i) => ({\n id: `high-${i + 1}`,\n title: `High severity finding ${i + 1}`,\n severity: \"high\" as const,\n category: \"logic\" as FindingCategory,\n }));\n }\n\n return [];\n}\n\nfunction inferCategory(title: string): FindingCategory {\n const lower = title.toLowerCase();\n if (lower.includes(\"security\") || lower.includes(\"auth\") || lower.includes(\"pii\")) {\n return \"security\";\n }\n if (lower.includes(\"performance\") || lower.includes(\"query\") || lower.includes(\"cache\")) {\n return \"performance\";\n }\n if (lower.includes(\"test\") || lower.includes(\"pattern\") || lower.includes(\"practice\")) {\n return \"bestPractices\";\n }\n return \"logic\";\n}\n\nfunction getAgentPositionsForFinding(\n findingId: string,\n phase2: Phase2Result\n): Partial<Record<BmadAgentType, string>> {\n const positions: Partial<Record<BmadAgentType, string>> = {};\n\n for (const analysis of phase2.agentAnalyses) {\n const prioritized = analysis.prioritizedIssues.find((p) =>\n p.findingId.toLowerCase().includes(findingId.toLowerCase())\n );\n if (prioritized) {\n positions[analysis.agent] = `${prioritized.agentPriority}: ${prioritized.rationale}`;\n } else if (analysis.findings.concerns.length > 0) {\n positions[analysis.agent] = analysis.findings.concerns[0];\n }\n }\n\n return positions;\n}\n\nfunction initializeSession(\n phase1: Phase1FullData,\n phase2?: Phase2Result,\n reviewFolderPath?: string\n): PartyDiscussionState {\n const sessionId = randomUUID();\n const agenda = buildAgenda(phase1, phase2);\n\n const activeAgents = new Set<BmadAgentType>();\n for (const item of agenda) {\n for (const agent of item.relevantAgents) {\n activeAgents.add(agent);\n }\n }\n\n const state: PartyDiscussionState = {\n sessionId,\n scope: phase1.scope,\n identifier: phase1.identifier,\n agenda,\n currentItemIndex: 0,\n completedRounds: [],\n activeAgents: Array.from(activeAgents),\n startedAt: new Date().toISOString(),\n phase1Summary: phase1.findings ?? {\n total: 0,\n high: 0,\n medium: 0,\n low: 0,\n byCategory: {} as Record<FindingCategory, number>,\n },\n phase2Summary: phase2\n ? {\n consensusCount: phase2.consensusPoints.length,\n disputeCount: phase2.debatePoints.length,\n }\n : undefined,\n };\n\n setSession(state, reviewFolderPath);\n return state;\n}\n\nasync function generateAgentResponses(\n item: DiscussionAgendaItem,\n personas: Map<BmadAgentType, BmadAgentFullPersona>,\n phase2?: Phase2Result\n): Promise<AgentDiscussionResponse[]> {\n const responses: AgentDiscussionResponse[] = [];\n\n for (const agentType of item.relevantAgents) {\n const persona = getPersona(personas, agentType);\n\n const phase2Analysis = phase2?.agentAnalyses.find((a) => a.agent === agentType);\n const previousPosition = item.agentPositions[agentType];\n\n const response = generateInCharacterResponse(\n persona,\n item,\n previousPosition,\n phase2Analysis?.summary,\n responses\n );\n\n responses.push({\n agent: agentType,\n agentName: persona.name,\n icon: persona.icon,\n response,\n references: extractReferences(response, responses),\n keyPoints: extractKeyPoints(response),\n });\n }\n\n return responses;\n}\n\nfunction generateInCharacterResponse(\n persona: BmadAgentFullPersona,\n item: DiscussionAgendaItem,\n previousPosition?: string,\n phase2Summary?: string,\n previousResponses?: AgentDiscussionResponse[]\n): string {\n const intro = getResponseIntro(persona, item);\n const position = previousPosition || phase2Summary || getDefaultPosition(persona, item);\n const crossTalk = generateCrossTalk(persona, previousResponses);\n\n return `${intro} ${position}${crossTalk}`;\n}\n\nfunction getResponseIntro(persona: BmadAgentFullPersona, item: DiscussionAgendaItem): string {\n const intros: Record<BmadAgentType, string> = {\n architect: `From an architecture perspective on \"${item.topic}\":`,\n dev: `Looking at implementation for \"${item.topic}\":`,\n tea: `From a testing standpoint on \"${item.topic}\":`,\n pm: `Considering business impact of \"${item.topic}\":`,\n analyst: `Analyzing requirements around \"${item.topic}\":`,\n \"ux-designer\": `From a user experience view on \"${item.topic}\":`,\n \"tech-writer\": `Regarding documentation for \"${item.topic}\":`,\n sm: `From a process perspective on \"${item.topic}\":`,\n };\n\n return intros[persona.type] || `Regarding \"${item.topic}\":`;\n}\n\nfunction getDefaultPosition(_persona: BmadAgentFullPersona, item: DiscussionAgendaItem): string {\n if (item.severity === \"high\") {\n return `This is a ${item.severity} severity ${item.category} issue that needs attention before we proceed.`;\n }\n return `This ${item.category} concern should be addressed to maintain quality.`;\n}\n\nfunction generateCrossTalk(\n persona: BmadAgentFullPersona,\n previousResponses?: AgentDiscussionResponse[]\n): string {\n if (!previousResponses || previousResponses.length === 0) return \"\";\n\n const collaborativeTypes: BmadAgentType[] = [\"architect\", \"pm\", \"analyst\"];\n const shouldCrossTalk =\n previousResponses.length >= 1 && collaborativeTypes.includes(persona.type);\n\n if (shouldCrossTalk) {\n const lastResponse = previousResponses[previousResponses.length - 1];\n return ` Building on ${lastResponse.agentName}'s point, I'd add that we should prioritize this appropriately.`;\n }\n return \"\";\n}\n\nfunction extractReferences(\n response: string,\n previousResponses: AgentDiscussionResponse[]\n): AgentDiscussionResponse[\"references\"] {\n const references: AgentDiscussionResponse[\"references\"] = [];\n\n for (const prev of previousResponses) {\n if (response.includes(prev.agentName)) {\n const type = response.toLowerCase().includes(\"disagree\")\n ? \"disagrees\"\n : response.toLowerCase().includes(\"building on\")\n ? \"builds-on\"\n : \"agrees\";\n references.push({ agent: prev.agent, type });\n }\n }\n\n return references;\n}\n\nfunction extractKeyPoints(response: string): string[] {\n const sentences = response.split(/[.!?]+/).filter((s) => s.trim().length > 10);\n return sentences.slice(0, 2).map((s) => s.trim());\n}\n\nfunction recordDecision(\n state: PartyDiscussionState,\n findingId: string,\n decision: ReviewDecision,\n reason?: string,\n deferredTo?: string\n): PartyDiscussionState {\n const itemIndex = state.agenda.findIndex((a) => a.findingId === findingId);\n if (itemIndex === -1) return state;\n\n const item = state.agenda[itemIndex];\n item.discussed = true;\n\n const round: DiscussionRound = {\n findingId,\n findingTitle: item.topic,\n findingSeverity: item.severity,\n findingCategory: item.category,\n participants: item.relevantAgents,\n responses: [],\n decision,\n decisionReason: reason,\n deferredTo,\n };\n\n item.round = round;\n state.completedRounds.push(round);\n\n if (state.currentItemIndex === itemIndex) {\n state.currentItemIndex = findNextUndiscussedIndex(state);\n }\n\n return state;\n}\n\nfunction findNextUndiscussedIndex(state: PartyDiscussionState): number {\n for (let i = 0; i < state.agenda.length; i++) {\n if (!state.agenda[i].discussed) {\n return i;\n }\n }\n return state.agenda.length;\n}\n\nfunction calculateSummary(state: PartyDiscussionState): PartyDiscussionResult[\"summary\"] {\n const decisions = { accepted: 0, deferred: 0, rejected: 0, pending: 0 };\n const storyUpdates = new Map<string, string[]>();\n\n for (const round of state.completedRounds) {\n switch (round.decision) {\n case \"accept\":\n decisions.accepted++;\n break;\n case \"defer\":\n decisions.deferred++;\n if (round.deferredTo) {\n const existing = storyUpdates.get(round.deferredTo) || [];\n existing.push(`Deferred: ${round.findingTitle}`);\n storyUpdates.set(round.deferredTo, existing);\n }\n break;\n case \"reject\":\n decisions.rejected++;\n break;\n default:\n decisions.pending++;\n }\n }\n\n for (const item of state.agenda) {\n if (!item.discussed) {\n decisions.pending++;\n }\n }\n\n return {\n totalDiscussed: state.completedRounds.length,\n decisions,\n storyUpdatesNeeded: Array.from(storyUpdates.entries()).map(([storyId, additions]) => ({\n storyId,\n additions,\n })),\n };\n}\n\nexport function createPartyDiscussionTool(ctx: PluginInput, config: AthenaConfig): ToolDefinition {\n return tool({\n description: `Orchestrate Phase 3 party discussion for BMAD story review.\n\nThis tool manages an informed discussion where BMAD agents debate findings from Phase 1 (Oracle analysis) and optionally Phase 2 (parallel agent analysis).\n\nModes:\n- Quick mode: Only analysis.json exists in review folder (Oracle findings only)\n- Full mode: Both analysis.json and phase2.json exist (includes agent perspectives)\n\nActions:\n- start: Initialize discussion from review folder (loads analysis.json and optionally phase2.json)\n- continue: Get next agenda item and agent responses\n- decide: Record user decision for a finding (accept/defer/reject)\n- skip: Skip current finding without decision\n- end: End discussion and get summary\n\nThe tool maintains session state across calls, enabling multi-turn discussion.`,\n\n args: {\n action: tool.schema\n .enum([\"start\", \"continue\", \"decide\", \"skip\", \"end\"])\n .describe(\"Action to perform\"),\n sessionId: tool.schema\n .string()\n .optional()\n .describe(\"Session ID (required for continue/decide/skip/end)\"),\n reviewFolderPath: tool.schema\n .string()\n .optional()\n .describe(\"Path to review folder from athena_story_review_analyze (required for start)\"),\n findingId: tool.schema.string().optional().describe(\"Finding ID (required for decide)\"),\n decision: tool.schema\n .enum([\"accept\", \"defer\", \"reject\"])\n .optional()\n .describe(\"Decision (required for decide)\"),\n reason: tool.schema.string().optional().describe(\"Reason for decision\"),\n deferredTo: tool.schema\n .string()\n .optional()\n .describe(\"Story ID to defer to (for defer decisions)\"),\n },\n\n async execute(args): Promise<string> {\n const result = await executePartyDiscussion(ctx, config, args);\n return JSON.stringify(result, null, 2);\n },\n });\n}\n\ninterface ToolArgs {\n action: \"start\" | \"continue\" | \"decide\" | \"skip\" | \"end\";\n sessionId?: string;\n reviewFolderPath?: string;\n findingId?: string;\n decision?: \"accept\" | \"defer\" | \"reject\";\n reason?: string;\n deferredTo?: string;\n}\n\nasync function executePartyDiscussion(\n ctx: PluginInput,\n config: AthenaConfig,\n args: ToolArgs\n): Promise<PartyDiscussionResult> {\n cleanupStaleSessions();\n const personas = await loadPersonas(ctx.directory);\n\n switch (args.action) {\n case \"start\": {\n if (!args.reviewFolderPath) {\n log.warn(\"start called without reviewFolderPath\");\n return {\n success: false,\n sessionId: \"\",\n state: {} as PartyDiscussionState,\n hasMoreItems: false,\n error: \"reviewFolderPath is required for start action\",\n suggestion: \"Pass the reviewFolderPath from athena_story_review_analyze result\",\n };\n }\n\n const analysisPath = join(args.reviewFolderPath, \"analysis.json\");\n const phase2Path = join(args.reviewFolderPath, \"phase2.json\");\n\n if (!existsSync(analysisPath)) {\n return {\n success: false,\n sessionId: \"\",\n state: {} as PartyDiscussionState,\n hasMoreItems: false,\n error: `Analysis file not found: ${analysisPath}`,\n suggestion: \"Run athena_story_review_analyze first to generate the review folder\",\n };\n }\n\n let phase1: Phase1FullData;\n let phase2: Phase2Result | undefined;\n try {\n const analysisContent = await readFile(analysisPath, \"utf-8\");\n phase1 = JSON.parse(analysisContent);\n\n if (existsSync(phase2Path)) {\n const phase2Content = await readFile(phase2Path, \"utf-8\");\n phase2 = JSON.parse(phase2Content);\n }\n } catch (e) {\n log.error(\"Failed to load review files\", {\n error: e instanceof Error ? e.message : String(e),\n reviewFolderPath: args.reviewFolderPath,\n });\n return {\n success: false,\n sessionId: \"\",\n state: {} as PartyDiscussionState,\n hasMoreItems: false,\n error: `Failed to load review files: ${e instanceof Error ? e.message : String(e)}`,\n suggestion: \"Ensure the review folder contains valid analysis.json\",\n };\n }\n\n if (!phase1.findings) {\n return {\n success: false,\n sessionId: \"\",\n state: {} as PartyDiscussionState,\n hasMoreItems: false,\n error: \"analysis.json missing required 'findings' field\",\n suggestion: \"Ensure athena_story_review_analyze completed successfully\",\n };\n }\n\n if (!phase1.oracleAnalysis && phase1.findings.high > 0) {\n console.warn(\n \"[Athena] analysis.json missing oracleAnalysis field - using placeholder findings for\",\n phase1.identifier\n );\n }\n\n const state = initializeSession(phase1, phase2, args.reviewFolderPath);\n log.info(\"Session started\", {\n sessionId: state.sessionId,\n identifier: state.identifier,\n agendaItems: state.agenda.length,\n hasPhase2: !!phase2,\n });\n\n const currentItem = state.agenda[0];\n const responses = currentItem\n ? await generateAgentResponses(currentItem, personas, phase2)\n : undefined;\n\n return {\n success: true,\n sessionId: state.sessionId,\n state,\n currentItem,\n currentResponses: responses,\n hasMoreItems: state.agenda.length > 1,\n };\n }\n\n case \"continue\": {\n if (!args.sessionId) {\n return {\n success: false,\n sessionId: \"\",\n state: {} as PartyDiscussionState,\n hasMoreItems: false,\n error: \"sessionId is required for continue action\",\n };\n }\n\n const state = getSession(args.sessionId);\n if (!state) {\n return {\n success: false,\n sessionId: args.sessionId,\n state: {} as PartyDiscussionState,\n hasMoreItems: false,\n error: \"Session not found\",\n };\n }\n\n const currentItem = state.agenda[state.currentItemIndex];\n if (!currentItem || currentItem.discussed) {\n const nextIndex = findNextUndiscussedIndex(state);\n if (nextIndex >= state.agenda.length) {\n return {\n success: true,\n sessionId: state.sessionId,\n state,\n hasMoreItems: false,\n summary: calculateSummary(state),\n };\n }\n state.currentItemIndex = nextIndex;\n }\n\n const nextItem = state.agenda[state.currentItemIndex];\n const emptyPhase2Result: Phase2Result = {\n success: true,\n identifier: state.identifier,\n agentAnalyses: [],\n consensusPoints: [],\n debatePoints: [],\n aggregatedPriorities: [],\n };\n\n const responses = await generateAgentResponses(nextItem, personas, emptyPhase2Result);\n\n return {\n success: true,\n sessionId: state.sessionId,\n state,\n currentItem: nextItem,\n currentResponses: responses,\n hasMoreItems: state.currentItemIndex < state.agenda.length - 1,\n };\n }\n\n case \"decide\": {\n if (!args.sessionId || !args.findingId || !args.decision) {\n return {\n success: false,\n sessionId: args.sessionId || \"\",\n state: {} as PartyDiscussionState,\n hasMoreItems: false,\n error: \"sessionId, findingId, and decision are required for decide action\",\n };\n }\n\n const state = getSession(args.sessionId);\n if (!state) {\n return {\n success: false,\n sessionId: args.sessionId,\n state: {} as PartyDiscussionState,\n hasMoreItems: false,\n error: \"Session not found\",\n };\n }\n\n const updatedState = recordDecision(\n state,\n args.findingId,\n args.decision,\n args.reason,\n args.deferredTo\n );\n log.debug(\"Decision recorded\", {\n sessionId: args.sessionId,\n findingId: args.findingId,\n decision: args.decision,\n });\n\n const hasMore = updatedState.currentItemIndex < updatedState.agenda.length;\n\n return {\n success: true,\n sessionId: updatedState.sessionId,\n state: updatedState,\n hasMoreItems: hasMore,\n summary: !hasMore ? calculateSummary(updatedState) : undefined,\n };\n }\n\n case \"skip\": {\n if (!args.sessionId || !args.findingId) {\n return {\n success: false,\n sessionId: args.sessionId || \"\",\n state: {} as PartyDiscussionState,\n hasMoreItems: false,\n error: \"sessionId and findingId are required for skip action\",\n };\n }\n\n const state = getSession(args.sessionId);\n if (!state) {\n return {\n success: false,\n sessionId: args.sessionId,\n state: {} as PartyDiscussionState,\n hasMoreItems: false,\n error: \"Session not found\",\n };\n }\n\n const itemIndex = state.agenda.findIndex((a) => a.findingId === args.findingId);\n if (itemIndex !== -1) {\n state.agenda[itemIndex].discussed = true;\n state.currentItemIndex = findNextUndiscussedIndex(state);\n }\n\n return {\n success: true,\n sessionId: state.sessionId,\n state,\n hasMoreItems: state.currentItemIndex < state.agenda.length,\n };\n }\n\n case \"end\": {\n if (!args.sessionId) {\n return {\n success: false,\n sessionId: \"\",\n state: {} as PartyDiscussionState,\n hasMoreItems: false,\n error: \"sessionId is required for end action\",\n };\n }\n\n const sessionMeta = getSessionWithMeta(args.sessionId);\n if (!sessionMeta) {\n return {\n success: false,\n sessionId: args.sessionId,\n state: {} as PartyDiscussionState,\n hasMoreItems: false,\n error: \"Session not found\",\n };\n }\n\n const state = sessionMeta.state;\n const reviewFolderPath = sessionMeta.reviewFolderPath;\n\n activeSessions.delete(args.sessionId);\n const endSummary = calculateSummary(state);\n\n const reviewDocPath = reviewFolderPath ? join(reviewFolderPath, \"review.md\") : undefined;\n const appliedUpdates = await applyDecisions(ctx.directory, state, reviewDocPath, config);\n\n log.info(\"Session ended with decisions applied\", {\n sessionId: args.sessionId,\n totalDiscussed: endSummary?.totalDiscussed ?? 0,\n decisions: endSummary?.decisions,\n storiesModified: appliedUpdates.summary.storiesModified,\n storiesCreated: appliedUpdates.summary.storiesCreated,\n });\n\n return {\n success: true,\n sessionId: state.sessionId,\n state,\n hasMoreItems: false,\n summary: endSummary,\n appliedUpdates,\n };\n }\n\n default:\n return {\n success: false,\n sessionId: \"\",\n state: {} as PartyDiscussionState,\n hasMoreItems: false,\n error: `Unknown action: ${args.action}`,\n };\n }\n}\n\nexport const _testExports = {\n buildAgenda,\n extractHighSeverityFindings,\n inferCategory,\n getAgentPositionsForFinding,\n initializeSession,\n generateAgentResponses,\n recordDecision,\n calculateSummary,\n activeSessions,\n cleanupStaleSessions,\n getSession,\n getSessionWithMeta,\n setSession,\n SESSION_TTL_MS,\n MAX_SESSIONS,\n};\n","import { existsSync } from \"node:fs\";\nimport { mkdir, readFile, readdir, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { type ToolDefinition, tool } from \"@opencode-ai/plugin\";\nimport type { PluginInput } from \"@opencode-ai/plugin\";\nimport type {\n AthenaConfig,\n CrossStoryIssue,\n FindingCategory,\n FindingSeverity,\n PartyReviewDocument,\n Phase1Context,\n ReviewDocumentReference,\n ReviewScope,\n StoryComplexity,\n StoryFindings,\n} from \"../../shared/types.js\";\nimport { getBmadPaths } from \"../utils/bmad-finder.js\";\nimport {\n findStoriesForEpic as findStoriesForEpicShared,\n getStoryFilenamePatterns,\n normalizeStoryId as normalizeStoryIdShared,\n resolveStoryIdentifier,\n stripAtPrefix,\n} from \"../utils/story-loader.js\";\n\ninterface BmadPaths {\n projectRoot: string;\n bmadDir: string | null;\n outputDir: string | null;\n planningDir: string;\n implementationDir: string;\n storiesDir: string;\n sprintStatus: string;\n architecture: string;\n prd: string;\n epics: string;\n structureVersion?: \"v6-alpha\" | \"legacy\" | \"unknown\";\n suggestion?: string;\n}\n\ninterface OracleResponseSummary {\n totalIssues: number;\n highSeverity: number;\n mediumSeverity: number;\n lowSeverity: number;\n recommendation: string;\n}\n\ninterface OracleResponseFindings {\n security: FindingDetail[];\n logic: FindingDetail[];\n bestPractices: FindingDetail[];\n performance: FindingDetail[];\n}\n\ninterface ParsedOracleResponse {\n summary: OracleResponseSummary;\n findings?: OracleResponseFindings;\n storyFindings?: StoryFinding[];\n crossStoryIssues?: CrossStoryIssue[];\n}\n\ninterface StoryFinding {\n storyId: string;\n title: string;\n findings: {\n security?: FindingDetail[];\n logic?: FindingDetail[];\n bestPractices?: FindingDetail[];\n performance?: FindingDetail[];\n };\n}\n\ninterface FindingDetail {\n id: string;\n category: FindingCategory;\n severity: FindingSeverity;\n title: string;\n description: string;\n impact: string;\n suggestion: string;\n}\n\nexport function createReviewStoryTool(ctx: PluginInput, config: AthenaConfig): ToolDefinition {\n return tool({\n description: `Run a party review on BMAD stories to find security, logic, best practice, and performance gaps.\n\nThis command generates a comprehensive review document BEFORE development starts, catching issues when they're cheap to fix (in markdown, not code).\n\nThe command is smart about argument types:\n- Epic: \"2\", \"epic-2\" → Reviews all stories in the epic\n- Story: \"2.3\", \"story-2-3\" → Deep dive on a single story \n- Path: \"docs/stories/story-2-3.md\" → Review specific file\n- Flag: --thorough → Force advanced model (ignores complexity detection)\n\nReturns:\n- Review document path (saved to docs/reviews/)\n- Structured findings by severity and category\n- Recommendations for next steps\n\nUse this tool after story creation but before development to improve story quality.`,\n\n args: {\n identifier: tool.schema\n .string()\n .describe(\"Epic number (e.g., '2'), Story ID (e.g., '2.3'), or file path. Required.\"),\n thorough: tool.schema\n .boolean()\n .optional()\n .describe(\"Force advanced model for review (default: auto-detect based on complexity)\"),\n },\n\n async execute(args): Promise<string> {\n const result = await executePartyReview(ctx, config, args.identifier, args.thorough);\n return JSON.stringify(result, null, 2);\n },\n });\n}\n\nasync function executePartyReview(\n ctx: PluginInput,\n config: AthenaConfig,\n identifier: string,\n forceAdvancedModel?: boolean\n): Promise<Phase1Context> {\n const paths = await getBmadPaths(ctx.directory, config);\n if (!paths.bmadDir) {\n return {\n success: false,\n scope: \"story\",\n identifier,\n error: \"No BMAD directory found\",\n suggestion:\n paths.suggestion ||\n \"Run 'npx bmad-method@alpha install' to set up BMAD in this project. Athena supports both legacy (docs/) and v6-alpha (_bmad/ + _bmad-output/) structures.\",\n };\n }\n\n const scope = detectReviewScope(identifier);\n const reviewsDir = join(paths.bmadDir, \"reviews\");\n\n await ensureReviewsDirectory(reviewsDir);\n\n if (scope === \"epic\") {\n return await executeEpicReview(ctx, config, paths, identifier, reviewsDir, forceAdvancedModel);\n }\n\n return await executeStoryReview(ctx, config, paths, identifier, reviewsDir, forceAdvancedModel);\n}\n\nfunction detectReviewScope(identifier: string): ReviewScope {\n const isFilePath = identifier.includes(\"/\") || identifier.endsWith(\".md\");\n if (isFilePath) {\n return \"story\";\n }\n\n const cleanId = identifier.replace(/^(epic|story)-/, \"\");\n const isEpic = !cleanId.includes(\".\") && !cleanId.includes(\"-\");\n\n return isEpic ? \"epic\" : \"story\";\n}\n\nasync function ensureReviewsDirectory(reviewsDir: string): Promise<void> {\n if (!existsSync(reviewsDir)) {\n await mkdir(reviewsDir, { recursive: true });\n }\n}\n\nasync function executeEpicReview(\n ctx: PluginInput,\n config: AthenaConfig,\n paths: BmadPaths,\n identifier: string,\n reviewsDir: string,\n forceAdvancedModel?: boolean\n): Promise<Phase1Context> {\n const epicNumber = identifier.replace(/^epic-/, \"\");\n\n const stories = await findStoriesInEpic(paths.storiesDir, epicNumber);\n if (stories.length === 0) {\n const patterns = getStoryFilenamePatterns(`${epicNumber}.1`);\n return {\n success: false,\n scope: \"epic\",\n identifier,\n error: `No stories found for Epic ${epicNumber}`,\n suggestion: `Check that story files exist in ${paths.storiesDir} matching: ${patterns.join(\", \")}`,\n };\n }\n\n const storyContents = await Promise.all(\n stories.map(async (storyId) => {\n const result = await loadStoryFile(paths.storiesDir, storyId, ctx.directory);\n return {\n id: result?.storyId ?? storyId,\n content: result?.content ?? null,\n };\n })\n );\n\n const architectureContent = await loadArchitecture(paths.architecture);\n\n const selectedModel = forceAdvancedModel ? config.models.oracle : config.models.oracle;\n\n const oraclePrompt = buildEpicReviewPrompt(epicNumber, storyContents, architectureContent);\n\n return {\n success: true,\n scope: \"epic\",\n identifier: epicNumber,\n oraclePrompt,\n storiesContent: storyContents,\n architectureContent,\n selectedModel,\n reviewsDir,\n };\n}\n\nasync function executeStoryReview(\n ctx: PluginInput,\n config: AthenaConfig,\n paths: BmadPaths,\n identifier: string,\n reviewsDir: string,\n forceAdvancedModel?: boolean\n): Promise<Phase1Context> {\n const storyResult = await loadStoryFile(paths.storiesDir, identifier, ctx.directory);\n if (!storyResult) {\n const normalizedId = normalizeStoryId(identifier);\n const patterns = getStoryFilenamePatterns(normalizedId);\n return {\n success: false,\n scope: \"story\",\n identifier: normalizedId,\n error: `Story ${normalizedId} not found`,\n suggestion: `Check that the story file exists in ${paths.storiesDir} matching: ${patterns.join(\", \")}`,\n };\n }\n\n const storyId = storyResult.storyId;\n const storyContent = storyResult.content;\n\n const existingReviews = await findExistingReviews(reviewsDir, storyId);\n const epicReview = existingReviews.find((r) => r.type === \"epic\");\n\n const architectureContent = await loadArchitecture(paths.architecture);\n\n const complexity = await analyzeStoryComplexity(storyContent);\n const selectedModel = forceAdvancedModel\n ? config.models.oracle\n : selectReviewModel(config, complexity);\n\n const oraclePrompt = buildFocusedReviewPrompt(\n storyId,\n storyContent,\n architectureContent,\n epicReview\n );\n\n return {\n success: true,\n scope: \"story\",\n identifier: storyId,\n oraclePrompt,\n storiesContent: [{ id: storyId, content: storyContent }],\n architectureContent,\n existingReviews,\n complexity,\n selectedModel,\n reviewsDir,\n };\n}\n\nasync function findStoriesInEpic(storiesDir: string, epicNumber: string): Promise<string[]> {\n const stories = await findStoriesForEpicShared(storiesDir, epicNumber);\n return stories.map((s) => s.id);\n}\n\nasync function loadStoryFile(\n storiesDir: string,\n storyId: string,\n projectRoot?: string\n): Promise<{ content: string; storyId: string } | null> {\n const cleaned = stripAtPrefix(storyId);\n const result = await resolveStoryIdentifier(storiesDir, cleaned, projectRoot);\n if (!result) return null;\n return { content: result.content, storyId: result.storyId };\n}\n\nasync function loadArchitecture(architectureFile: string): Promise<string> {\n if (!existsSync(architectureFile)) {\n return \"\";\n }\n return await readFile(architectureFile, \"utf-8\");\n}\n\nfunction normalizeStoryId(identifier: string): string {\n return normalizeStoryIdShared(identifier);\n}\n\nasync function findExistingReviews(\n reviewsDir: string,\n storyId: string\n): Promise<ReviewDocumentReference[]> {\n if (!existsSync(reviewsDir)) {\n return [];\n }\n\n const files = await readdir(reviewsDir);\n\n const reviews: ReviewDocumentReference[] = [];\n const [epicNum] = storyId.split(\".\");\n\n for (const file of files) {\n if (file.startsWith(`party-review-epic-${epicNum}-`)) {\n const filePath = join(reviewsDir, file);\n const match = file.match(/(\\d{4}-\\d{2}-\\d{2})/);\n\n reviews.push({\n type: \"epic\",\n filePath,\n date: match ? match[1] : \"\",\n findingsCount: 0,\n acceptedCount: 0,\n deferredCount: 0,\n rejectedCount: 0,\n });\n }\n }\n\n return reviews;\n}\n\nasync function analyzeStoryComplexity(storyContent: string): Promise<StoryComplexity> {\n const acMatches = storyContent.match(/^- /gm) || [];\n const acceptanceCriteriaCount = acMatches.length;\n\n const securityKeywords = /\\b(auth|login|password|token|secret|encrypt|permission|role|access)\\b/i;\n const hasSecurityConcerns = securityKeywords.test(storyContent);\n\n const dataKeywords = /\\b(database|schema|migration|model|table|collection)\\b/i;\n const hasDataModelChanges = dataKeywords.test(storyContent);\n\n const apiKeywords = /\\b(api|endpoint|route|controller|handler)\\b/i;\n const hasApiChanges = apiKeywords.test(storyContent);\n\n const crudPattern = /\\b(create|read|update|delete|get|post|put|patch|list)\\b/gi;\n const crudMatches = storyContent.match(crudPattern) || [];\n const isCrudOnly = crudMatches.length > 0 && !hasSecurityConcerns && !hasDataModelChanges;\n\n const isSimple =\n acceptanceCriteriaCount < 5 && !hasSecurityConcerns && !hasDataModelChanges && isCrudOnly;\n\n return {\n isSimple,\n reason: isSimple\n ? `Simple story: ${acceptanceCriteriaCount} ACs, CRUD-only, no security/data concerns`\n : `Complex story: ${acceptanceCriteriaCount} ACs, security=${hasSecurityConcerns}, data=${hasDataModelChanges}, API=${hasApiChanges}`,\n recommendedModel: isSimple ? \"anthropic/claude-3-5-haiku-20241022\" : \"openai/gpt-5.2\",\n factors: {\n acceptanceCriteriaCount,\n hasSecurityConcerns,\n hasDataModelChanges,\n hasApiChanges,\n isCrudOnly,\n },\n };\n}\n\nfunction selectReviewModel(config: AthenaConfig, complexity: StoryComplexity): string {\n return complexity.isSimple ? \"anthropic/claude-3-5-haiku-20241022\" : config.models.oracle;\n}\n\nfunction buildEpicReviewPrompt(\n epicNumber: string,\n storyContents: Array<{ id: string; content: string | null }>,\n architectureContent: string\n): string {\n const storiesText = storyContents\n .map((s) => `## Story ${s.id}\\n\\n${s.content || \"(empty)\"}`)\n .join(\"\\n\\n---\\n\\n\");\n\n return `You are a security, logic, and performance expert conducting a \"party review\" of BMAD stories BEFORE development begins.\n\n**Your Role**: Find issues while they're cheap to fix (in markdown, not code).\n\n**Focus Areas**:\n1. 🔒 **Security Gaps**: Missing auth/authorization, input validation, data exposure risks, credential handling\n2. 🧠 **Logic Gaps**: Edge cases not covered, error scenarios missing, validation rules incomplete, race conditions\n3. ✨ **Best Practice Flaws**: Anti-patterns in requirements, testing strategy gaps, accessibility concerns, unclear specifications\n4. ⚡ **Performance Issues**: Potential N+1 queries, missing caching strategy, large data handling not addressed, client-side bundle concerns\n\n**Scope**: Epic ${epicNumber} - Review ALL stories for issues AND cross-story patterns\n\n**Architecture Context**:\n${architectureContent || \"(No architecture documented)\"}\n\n**Stories to Review**:\n${storiesText}\n\n**Output Format** (JSON):\n{\n \"summary\": {\n \"totalIssues\": number,\n \"highSeverity\": number,\n \"mediumSeverity\": number,\n \"lowSeverity\": number,\n \"recommendation\": \"string\"\n },\n \"storyFindings\": [\n {\n \"storyId\": \"string\",\n \"title\": \"string\",\n \"findings\": {\n \"security\": [\n {\n \"id\": \"unique-id\",\n \"severity\": \"high\" | \"medium\" | \"low\",\n \"title\": \"Brief title\",\n \"description\": \"What's wrong\",\n \"impact\": \"Why it matters\",\n \"suggestion\": \"How to fix\"\n }\n ],\n \"logic\": [...],\n \"bestPractices\": [...],\n \"performance\": [...]\n }\n }\n ],\n \"crossStoryIssues\": [\n {\n \"id\": \"unique-id\",\n \"category\": \"security\" | \"logic\" | \"bestPractices\" | \"performance\",\n \"severity\": \"high\" | \"medium\" | \"low\",\n \"title\": \"Pattern or issue across multiple stories\",\n \"description\": \"Details\",\n \"affectedStories\": [\"2.1\", \"2.3\"],\n \"suggestion\": \"How to address\"\n }\n ]\n}\n\n**Instructions**:\n- Be thorough but practical\n- Prioritize high-impact issues\n- Provide actionable suggestions\n- Consider the architecture constraints\n- Flag missing requirements as logic gaps\n- Look for inconsistencies across stories`;\n}\n\nfunction buildFocusedReviewPrompt(\n storyId: string,\n storyContent: string,\n architectureContent: string,\n epicReview?: ReviewDocumentReference\n): string {\n const epicContext = epicReview\n ? `\\n\\n**Previous Epic Review**: An epic-level review was conducted on ${epicReview.date}. This focused review should find NEW issues not caught in the broader epic review.`\n : \"\";\n\n return `You are a security, logic, and performance expert conducting a DEEP DIVE \"party review\" of a single BMAD story BEFORE development begins.\n\n**Your Role**: Find issues while they're cheap to fix (in markdown, not code). This is a FOCUSED review, so be more thorough than a broad epic review.\n\n**Focus Areas**:\n1. 🔒 **Security Gaps**: Missing auth/authorization, input validation, data exposure risks, credential handling, session management\n2. 🧠 **Logic Gaps**: Edge cases not covered, error scenarios missing, validation rules incomplete, race conditions, state management\n3. ✨ **Best Practice Flaws**: Anti-patterns in requirements, testing strategy gaps, accessibility concerns, unclear specifications, maintainability\n4. ⚡ **Performance Issues**: Potential N+1 queries, missing caching strategy, large data handling, client-side bundle size, database indexes${epicContext}\n\n**Story**: ${storyId}\n\n**Architecture Context**:\n${architectureContent || \"(No architecture documented)\"}\n\n**Story Content**:\n${storyContent}\n\n**Output Format** (JSON):\n{\n \"summary\": {\n \"totalIssues\": number,\n \"highSeverity\": number,\n \"mediumSeverity\": number,\n \"lowSeverity\": number,\n \"recommendation\": \"string\"\n },\n \"findings\": {\n \"security\": [\n {\n \"id\": \"unique-id\",\n \"severity\": \"high\" | \"medium\" | \"low\",\n \"title\": \"Brief title\",\n \"description\": \"What's wrong\",\n \"impact\": \"Why it matters\",\n \"suggestion\": \"How to fix (be specific)\"\n }\n ],\n \"logic\": [...],\n \"bestPractices\": [...],\n \"performance\": [...]\n }\n}\n\n**Instructions**:\n- Be EXTREMELY thorough - this is a deep dive\n- Think like an adversarial tester trying to break the implementation\n- Question every assumption in the requirements\n- Look for vague or incomplete acceptance criteria\n- Consider security implications of every data flow\n- Flag missing error handling scenarios\n- Identify performance bottlenecks before they're coded\n- Provide highly specific, actionable suggestions`;\n}\n\nfunction parseOracleResponse(_response: string, _scope: ReviewScope): ParsedOracleResponse {\n try {\n return JSON.parse(_response) as ParsedOracleResponse;\n } catch {\n return {\n summary: {\n totalIssues: 0,\n highSeverity: 0,\n mediumSeverity: 0,\n lowSeverity: 0,\n recommendation: \"Failed to parse Oracle response\",\n },\n findings: {\n security: [],\n logic: [],\n bestPractices: [],\n performance: [],\n },\n };\n }\n}\n\nfunction buildEpicReviewDocument(\n epicNumber: string,\n stories: string[],\n findings: ParsedOracleResponse,\n oracleAnalysis: string\n): PartyReviewDocument {\n const timestamp = new Date().toISOString().split(\"T\")[0];\n\n return {\n scope: \"epic\",\n identifier: epicNumber,\n date: timestamp,\n reviewer: \"Oracle (Party Mode)\",\n epicNumber,\n storiesReviewed: stories,\n summary: findings.summary,\n storyFindings: findings.storyFindings as unknown as StoryFindings[],\n crossStoryIssues: findings.crossStoryIssues,\n oracleAnalysis,\n };\n}\n\nfunction buildFocusedReviewDocument(\n storyId: string,\n findings: ParsedOracleResponse,\n epicReview: ReviewDocumentReference | undefined,\n oracleAnalysis: string\n): PartyReviewDocument {\n const timestamp = new Date().toISOString().split(\"T\")[0];\n const [epicNum] = storyId.split(\".\");\n\n return {\n scope: \"story\",\n identifier: storyId,\n date: timestamp,\n reviewer: \"Oracle (Party Mode - Deep Dive)\",\n epicNumber: epicNum,\n storyId,\n relatedReviews: epicReview ? [epicReview] : [],\n summary: findings.summary,\n newFindings: findings.findings,\n oracleAnalysis,\n };\n}\n\nasync function saveReviewDocument(\n documentPath: string,\n document: PartyReviewDocument\n): Promise<void> {\n const markdown = formatReviewDocumentAsMarkdown(document);\n await writeFile(documentPath, markdown, \"utf-8\");\n}\n\nfunction formatReviewDocumentAsMarkdown(doc: PartyReviewDocument): string {\n const title =\n doc.scope === \"epic\"\n ? `# 🎉 Party Review: Epic ${doc.epicNumber}\\n`\n : `# 🎉 Party Review: Story ${doc.storyId} (Focused Review)\\n`;\n\n const metadata = `**Date**: ${doc.date}\n**Reviewer**: ${doc.reviewer}\n${doc.scope === \"epic\" ? `**Stories Reviewed**: ${doc.storiesReviewed?.join(\", \")}` : `**Epic**: ${doc.epicNumber}`}\n\n---\n\n## Executive Summary\n- **Total Issues**: ${doc.summary.totalIssues}\n- **High Severity**: ${doc.summary.highSeverity} issues (MUST address)\n- **Medium Severity**: ${doc.summary.mediumSeverity} issues (SHOULD address)\n- **Low Severity**: ${doc.summary.lowSeverity} issues (NICE to address)\n\n**Recommendation**: ${doc.summary.recommendation}\n\n---\n\n`;\n\n const relatedReviews = doc.relatedReviews?.length\n ? `## 🔗 Related Reviews\\n${doc.relatedReviews\n .map(\n (r) =>\n `- **${r.type === \"epic\" ? \"Epic Review\" : \"Focused Review\"}**: [${r.filePath.split(\"/\").pop() ?? \"review\"}](${r.filePath}) (${r.date})`\n )\n .join(\"\\n\")}\\n\\n---\\n\\n`\n : \"\";\n\n const findingsSection =\n doc.scope === \"epic\" && doc.storyFindings\n ? formatEpicFindings(doc.storyFindings, doc.crossStoryIssues)\n : formatStoryFindings(doc.newFindings);\n\n const appendix = `\\n---\\n\\n## Appendix: Oracle's Full Analysis\\n<details>\\n<summary>Click to expand detailed reasoning</summary>\\n\\n${doc.oracleAnalysis ?? \"\"}\\n\\n</details>\\n`;\n\n return title + metadata + relatedReviews + findingsSection + appendix;\n}\n\nfunction formatEpicFindings(\n storyFindings: StoryFindings[],\n crossStoryIssues?: CrossStoryIssue[]\n): string {\n let output = \"\";\n\n for (const story of storyFindings) {\n const typedStory = story as unknown as StoryFinding;\n output += `## Story ${typedStory.storyId}: ${typedStory.title}\\n\\n`;\n\n for (const category of [\"security\", \"logic\", \"bestPractices\", \"performance\"] as const) {\n const findings = (typedStory.findings[category] || []) as FindingDetail[];\n if (findings.length > 0) {\n const icon = getCategoryIcon(category);\n output += `### ${icon} ${formatCategoryName(category)} (${findings.length} issues)\\n\\n`;\n\n for (const finding of findings) {\n const severity = finding.severity.toUpperCase();\n output += `#### [${severity}] ${finding.title}\\n`;\n output += `**Finding**: ${finding.description}\\n`;\n output += `**Impact**: ${finding.impact}\\n`;\n output += `**Suggestion**: ${finding.suggestion}\\n`;\n output += \"**Decision**: [ ] Accept [ ] Defer [ ] Reject\\n\\n\";\n }\n }\n }\n\n output += \"---\\n\\n\";\n }\n\n if (crossStoryIssues && crossStoryIssues.length > 0) {\n output += \"## Cross-Story Issues\\n\\n\";\n for (const issue of crossStoryIssues) {\n const icon = getCategoryIcon(issue.category);\n output += `### ${icon} [${issue.severity.toUpperCase()}] ${issue.title}\\n`;\n output += `**Stories Affected**: ${issue.affectedStories.join(\", \")}\\n`;\n output += `**Finding**: ${issue.description}\\n`;\n output += `**Suggestion**: ${issue.suggestion}\\n`;\n output += \"**Decision**: [ ] Accept [ ] Defer [ ] Reject\\n\\n\";\n }\n }\n\n return output;\n}\n\nfunction formatStoryFindings(findings: unknown): string {\n if (!findings) return \"\";\n\n const typedFindings = findings as OracleResponseFindings;\n let output = \"\";\n\n for (const category of [\"security\", \"logic\", \"bestPractices\", \"performance\"] as const) {\n const items = (typedFindings[category] || []) as FindingDetail[];\n if (items.length > 0) {\n const icon = getCategoryIcon(category);\n output += `## ${icon} ${formatCategoryName(category)} (${items.length} issues)\\n\\n`;\n\n for (const finding of items) {\n const severity = finding.severity.toUpperCase();\n output += `### [${severity}] ${finding.title}\\n`;\n output += `**Finding**: ${finding.description}\\n`;\n output += `**Impact**: ${finding.impact}\\n`;\n output += `**Suggestion**: ${finding.suggestion}\\n`;\n output += \"**Decision**: [ ] Accept [ ] Defer [ ] Reject\\n\\n\";\n }\n\n output += \"---\\n\\n\";\n }\n }\n\n return output;\n}\n\nfunction getCategoryIcon(category: FindingCategory): string {\n switch (category) {\n case \"security\":\n return \"🔒\";\n case \"logic\":\n return \"🧠\";\n case \"bestPractices\":\n return \"✨\";\n case \"performance\":\n return \"⚡\";\n }\n}\n\nfunction formatCategoryName(category: FindingCategory): string {\n switch (category) {\n case \"security\":\n return \"Security Issues\";\n case \"logic\":\n return \"Logic Issues\";\n case \"bestPractices\":\n return \"Best Practices\";\n case \"performance\":\n return \"Performance Issues\";\n }\n}\n\nasync function updateEpicReviewDocument(\n _epicReviewPath: string,\n _storyId: string,\n _focusedReviewPath: string,\n _findings: ParsedOracleResponse\n): Promise<void> {\n return;\n}\n\n// Export internal functions for testing\ninterface FindingCounts {\n total: number;\n high: number;\n medium: number;\n low: number;\n byCategory: Record<FindingCategory, number>;\n}\n\ninterface AgentRecommendation {\n agent: string;\n reason: string;\n relevantFindings: string[];\n priority: \"required\" | \"recommended\" | \"optional\";\n}\n\nconst _AGENT_EXPERTISE: Record<string, FindingCategory[]> = {\n architect: [\"security\", \"performance\"],\n dev: [\"logic\", \"performance\", \"bestPractices\"],\n tea: [\"logic\", \"bestPractices\"],\n pm: [\"logic\", \"bestPractices\"],\n analyst: [\"logic\"],\n \"ux-designer\": [\"bestPractices\"],\n \"tech-writer\": [\"bestPractices\"],\n};\n\nfunction selectAgentsForReview(findings: FindingCounts): AgentRecommendation[] {\n const recommendations: AgentRecommendation[] = [];\n\n if (findings.byCategory.security > 0) {\n recommendations.push({\n agent: \"architect\",\n reason: `${findings.byCategory.security} security finding(s) require architecture review`,\n relevantFindings: [\"security\"],\n priority: findings.high > 0 ? \"required\" : \"recommended\",\n });\n recommendations.push({\n agent: \"dev\",\n reason: \"Security findings need implementation perspective\",\n relevantFindings: [\"security\"],\n priority: \"recommended\",\n });\n recommendations.push({\n agent: \"tea\",\n reason: \"Security findings need test coverage review\",\n relevantFindings: [\"security\"],\n priority: \"recommended\",\n });\n }\n\n if (findings.byCategory.logic > 0) {\n if (!recommendations.find((r) => r.agent === \"dev\")) {\n recommendations.push({\n agent: \"dev\",\n reason: `${findings.byCategory.logic} logic gap(s) need implementation review`,\n relevantFindings: [\"logic\"],\n priority: findings.high > 0 ? \"required\" : \"recommended\",\n });\n }\n if (!recommendations.find((r) => r.agent === \"tea\")) {\n recommendations.push({\n agent: \"tea\",\n reason: \"Logic gaps need test scenario review\",\n relevantFindings: [\"logic\"],\n priority: \"recommended\",\n });\n }\n recommendations.push({\n agent: \"analyst\",\n reason: \"Logic gaps may indicate incomplete requirements\",\n relevantFindings: [\"logic\"],\n priority: \"optional\",\n });\n }\n\n if (findings.byCategory.performance > 0) {\n if (!recommendations.find((r) => r.agent === \"architect\")) {\n recommendations.push({\n agent: \"architect\",\n reason: `${findings.byCategory.performance} performance issue(s) need architecture review`,\n relevantFindings: [\"performance\"],\n priority: \"recommended\",\n });\n }\n if (!recommendations.find((r) => r.agent === \"dev\")) {\n recommendations.push({\n agent: \"dev\",\n reason: \"Performance issues need implementation perspective\",\n relevantFindings: [\"performance\"],\n priority: \"recommended\",\n });\n }\n }\n\n if (findings.byCategory.bestPractices > 0) {\n if (!recommendations.find((r) => r.agent === \"dev\")) {\n recommendations.push({\n agent: \"dev\",\n reason: `${findings.byCategory.bestPractices} best practice issue(s) need code review`,\n relevantFindings: [\"bestPractices\"],\n priority: \"optional\",\n });\n }\n recommendations.push({\n agent: \"tech-writer\",\n reason: \"Best practice issues may need documentation updates\",\n relevantFindings: [\"bestPractices\"],\n priority: \"optional\",\n });\n }\n\n if (findings.high > 0) {\n recommendations.push({\n agent: \"pm\",\n reason: `${findings.high} high severity issue(s) need product impact assessment`,\n relevantFindings: [\"high-severity\"],\n priority: \"required\",\n });\n }\n\n const requiredCount = recommendations.filter((r) => r.priority === \"required\").length;\n if (requiredCount === 0 && recommendations.length > 0) {\n recommendations[0].priority = \"required\";\n }\n\n return recommendations;\n}\n\nexport const _testExports = {\n detectReviewScope,\n normalizeStoryId,\n analyzeStoryComplexity,\n selectReviewModel,\n findStoriesInEpic,\n loadStoryFile,\n findExistingReviews,\n parseOracleResponse,\n buildEpicReviewPrompt,\n buildFocusedReviewPrompt,\n buildEpicReviewDocument,\n buildFocusedReviewDocument,\n saveReviewDocument,\n formatReviewDocumentAsMarkdown,\n getCategoryIcon,\n formatCategoryName,\n updateEpicReviewDocument,\n selectAgentsForReview,\n};\n","import type { BmadAgentType, FindingCategory } from \"../../shared/types.js\";\n\nexport interface FindingCounts {\n total: number;\n high: number;\n medium: number;\n low: number;\n byCategory: Record<FindingCategory, number>;\n}\n\nexport interface AgentRecommendation {\n agent: BmadAgentType;\n reason: string;\n relevantFindings: string[];\n priority: \"required\" | \"recommended\" | \"optional\";\n}\n\nconst AGENT_EXPERTISE: Record<BmadAgentType, FindingCategory[]> = {\n architect: [\"security\", \"performance\"],\n dev: [\"logic\", \"performance\", \"bestPractices\"],\n tea: [\"logic\", \"bestPractices\"],\n pm: [\"logic\", \"bestPractices\"],\n analyst: [\"logic\"],\n \"ux-designer\": [\"bestPractices\"],\n \"tech-writer\": [\"bestPractices\"],\n sm: [\"bestPractices\"],\n};\n\nexport function selectAgentsForReview(findings: FindingCounts): AgentRecommendation[] {\n const recommendations: AgentRecommendation[] = [];\n\n if (findings.byCategory.security > 0) {\n addSecurityAgents(recommendations, findings);\n }\n\n if (findings.byCategory.logic > 0) {\n addLogicAgents(recommendations, findings);\n }\n\n if (findings.byCategory.performance > 0) {\n addPerformanceAgents(recommendations);\n }\n\n if (findings.byCategory.bestPractices > 0) {\n addBestPracticesAgents(recommendations, findings);\n }\n\n if (findings.high > 0) {\n recommendations.push({\n agent: \"pm\",\n reason: `${findings.high} high severity issue(s) need product impact assessment`,\n relevantFindings: [\"high-severity\"],\n priority: \"required\",\n });\n }\n\n ensureAtLeastOneRequired(recommendations);\n\n return recommendations;\n}\n\nfunction addSecurityAgents(recommendations: AgentRecommendation[], findings: FindingCounts): void {\n recommendations.push({\n agent: \"architect\",\n reason: `${findings.byCategory.security} security finding(s) require architecture review`,\n relevantFindings: [\"security\"],\n priority: findings.high > 0 ? \"required\" : \"recommended\",\n });\n recommendations.push({\n agent: \"dev\",\n reason: \"Security findings need implementation perspective\",\n relevantFindings: [\"security\"],\n priority: \"recommended\",\n });\n recommendations.push({\n agent: \"tea\",\n reason: \"Security findings need test coverage review\",\n relevantFindings: [\"security\"],\n priority: \"recommended\",\n });\n}\n\nfunction addLogicAgents(recommendations: AgentRecommendation[], findings: FindingCounts): void {\n if (!recommendations.find((r) => r.agent === \"dev\")) {\n recommendations.push({\n agent: \"dev\",\n reason: `${findings.byCategory.logic} logic gap(s) need implementation review`,\n relevantFindings: [\"logic\"],\n priority: findings.high > 0 ? \"required\" : \"recommended\",\n });\n }\n if (!recommendations.find((r) => r.agent === \"tea\")) {\n recommendations.push({\n agent: \"tea\",\n reason: \"Logic gaps need test scenario review\",\n relevantFindings: [\"logic\"],\n priority: \"recommended\",\n });\n }\n recommendations.push({\n agent: \"analyst\",\n reason: \"Logic gaps may indicate incomplete requirements\",\n relevantFindings: [\"logic\"],\n priority: \"optional\",\n });\n}\n\nfunction addPerformanceAgents(recommendations: AgentRecommendation[]): void {\n if (!recommendations.find((r) => r.agent === \"architect\")) {\n recommendations.push({\n agent: \"architect\",\n reason: \"Performance issues need architecture review\",\n relevantFindings: [\"performance\"],\n priority: \"recommended\",\n });\n }\n if (!recommendations.find((r) => r.agent === \"dev\")) {\n recommendations.push({\n agent: \"dev\",\n reason: \"Performance issues need implementation perspective\",\n relevantFindings: [\"performance\"],\n priority: \"recommended\",\n });\n }\n}\n\nfunction addBestPracticesAgents(\n recommendations: AgentRecommendation[],\n findings: FindingCounts\n): void {\n if (!recommendations.find((r) => r.agent === \"dev\")) {\n recommendations.push({\n agent: \"dev\",\n reason: `${findings.byCategory.bestPractices} best practice issue(s) need code review`,\n relevantFindings: [\"bestPractices\"],\n priority: \"optional\",\n });\n }\n recommendations.push({\n agent: \"tech-writer\",\n reason: \"Best practice issues may need documentation updates\",\n relevantFindings: [\"bestPractices\"],\n priority: \"optional\",\n });\n}\n\nfunction ensureAtLeastOneRequired(recommendations: AgentRecommendation[]): void {\n const requiredCount = recommendations.filter((r) => r.priority === \"required\").length;\n if (requiredCount === 0 && recommendations.length > 0) {\n recommendations[0].priority = \"required\";\n }\n}\n\nexport function getRecommendedAgentTypes(recommendations: AgentRecommendation[]): BmadAgentType[] {\n const seen = new Set<BmadAgentType>();\n const agents: BmadAgentType[] = [];\n\n for (const rec of recommendations) {\n if (!seen.has(rec.agent)) {\n seen.add(rec.agent);\n agents.push(rec.agent);\n }\n }\n\n return agents;\n}\n\nexport function filterByPriority(\n recommendations: AgentRecommendation[],\n minPriority: \"required\" | \"recommended\" | \"optional\"\n): AgentRecommendation[] {\n const priorityOrder = { required: 0, recommended: 1, optional: 2 };\n const minLevel = priorityOrder[minPriority];\n\n return recommendations.filter((r) => priorityOrder[r.priority] <= minLevel);\n}\n\nexport { AGENT_EXPERTISE };\n","import { existsSync } from \"node:fs\";\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { type ToolDefinition, tool } from \"@opencode-ai/plugin\";\nimport type { PluginInput } from \"@opencode-ai/plugin\";\nimport type {\n AthenaConfig,\n Phase1FullData,\n Phase1Summary,\n ReviewScope,\n} from \"../../shared/types.js\";\nimport {\n type AgentRecommendation,\n type FindingCounts,\n selectAgentsForReview,\n} from \"../utils/agent-selector.js\";\nimport { getBmadPaths } from \"../utils/bmad-finder.js\";\nimport {\n type ParsedOracleResponse,\n countFindings,\n parseOracleResponse,\n} from \"../utils/oracle-parser.js\";\nimport {\n findStoriesForEpic,\n resolveStoryIdentifier,\n stripAtPrefix,\n} from \"../utils/story-loader.js\";\nimport { updateStoryStatus } from \"../utils/yaml-handler.js\";\n\nexport function createStoryReviewAnalyzeTool(\n ctx: PluginInput,\n config: AthenaConfig\n): ToolDefinition {\n return tool({\n description: `Analyze BMAD stories for security, logic, best practice, and performance gaps.\n\nThis tool performs Phase 1 of the party review workflow:\n1. Loads stories and architecture context\n2. Spawns Oracle agent to analyze for issues\n3. Parses findings by severity and category\n4. Recommends BMAD agents for discussion\n5. Generates and saves a review document\n\nReturns a complete Phase 1 result that can be passed to Phase 2 (athena_story_review_consult) or Phase 3 (athena_party_discussion).\n\nUse this AFTER story creation but BEFORE development to catch issues early.`,\n\n args: {\n identifier: tool.schema\n .string()\n .describe(\"Epic number (e.g., '2'), Story ID (e.g., '2.3'), or file path\"),\n thorough: tool.schema\n .boolean()\n .optional()\n .describe(\"Force advanced model for deeper analysis (default: auto-detect)\"),\n },\n\n async execute(args): Promise<string> {\n const result = await executePhase1Analysis(ctx, config, args.identifier, args.thorough);\n return JSON.stringify(result, null, 2);\n },\n });\n}\n\nasync function executePhase1Analysis(\n ctx: PluginInput,\n config: AthenaConfig,\n identifier: string,\n forceAdvancedModel?: boolean\n): Promise<Phase1Summary> {\n const paths = await getBmadPaths(ctx.directory, config);\n if (!paths.bmadDir) {\n return {\n success: false,\n scope: \"story\",\n identifier,\n error: \"No BMAD directory found\",\n suggestion:\n paths.suggestion ||\n \"Run 'npx bmad-method@alpha install' to set up BMAD in this project. Athena supports both legacy (docs/) and v6-alpha (_bmad/ + _bmad-output/) structures.\",\n };\n }\n\n const scope = detectReviewScope(identifier);\n const reviewsDir = join(paths.bmadDir, \"reviews\");\n await ensureDirectory(reviewsDir);\n\n const storiesContent =\n scope === \"epic\"\n ? await loadEpicStories(paths.storiesDir, identifier)\n : await loadSingleStory(paths.storiesDir, identifier, ctx.directory);\n\n if (storiesContent.length === 0) {\n return {\n success: false,\n scope,\n identifier,\n error: `No stories found for ${scope} ${identifier}`,\n suggestion: `Check that story files exist in ${paths.storiesDir}`,\n };\n }\n\n const architectureContent = await loadFile(paths.architecture);\n\n const oraclePrompt = buildOraclePrompt(scope, identifier, storiesContent, architectureContent);\n\n const oracleResponse = await spawnOracleAndWait(ctx, config, oraclePrompt, forceAdvancedModel);\n\n if (!oracleResponse.success) {\n return {\n success: false,\n scope,\n identifier,\n error: oracleResponse.error || \"Oracle analysis failed\",\n suggestion: \"Check that the Oracle agent is configured correctly.\",\n };\n }\n\n const parsed = parseOracleResponse(oracleResponse.content || \"\");\n const findings = countFindings(parsed);\n const recommendedAgents = selectAgentsForReview(findings);\n const summary = buildSummary(findings, recommendedAgents);\n\n const reviewFolderPath = await saveReviewFolder(\n reviewsDir,\n scope,\n identifier,\n storiesContent,\n parsed,\n oracleResponse.content || \"\",\n findings,\n recommendedAgents,\n summary\n );\n\n if (scope === \"story\") {\n await updateStoryStatus(paths.sprintStatus, identifier, \"ready-for-dev\");\n } else {\n for (const story of storiesContent) {\n await updateStoryStatus(paths.sprintStatus, story.id, \"ready-for-dev\");\n }\n }\n\n return {\n success: true,\n scope,\n identifier,\n findings,\n recommendedAgents,\n reviewFolderPath,\n summary,\n };\n}\n\nfunction detectReviewScope(identifier: string): ReviewScope {\n const isFilePath = identifier.includes(\"/\") || identifier.endsWith(\".md\");\n if (isFilePath) return \"story\";\n\n const cleanId = identifier.replace(/^(epic|story)-/, \"\");\n return !cleanId.includes(\".\") && !cleanId.includes(\"-\") ? \"epic\" : \"story\";\n}\n\nasync function ensureDirectory(dir: string): Promise<void> {\n if (!existsSync(dir)) {\n await mkdir(dir, { recursive: true });\n }\n}\n\nasync function loadEpicStories(\n storiesDir: string,\n epicId: string\n): Promise<Array<{ id: string; content: string | null }>> {\n const stories = await findStoriesForEpic(storiesDir, epicId);\n const results: Array<{ id: string; content: string | null }> = [];\n\n for (const story of stories) {\n const content = await loadFile(story.path);\n results.push({ id: story.id, content });\n }\n\n return results;\n}\n\nasync function loadSingleStory(\n storiesDir: string,\n identifier: string,\n projectRoot?: string\n): Promise<Array<{ id: string; content: string | null }>> {\n const cleaned = stripAtPrefix(identifier);\n const result = await resolveStoryIdentifier(storiesDir, cleaned, projectRoot);\n if (!result) return [];\n\n return [{ id: result.storyId, content: result.content }];\n}\n\nasync function loadFile(filePath: string): Promise<string | null> {\n if (!existsSync(filePath)) return null;\n try {\n return await readFile(filePath, \"utf-8\");\n } catch {\n return null;\n }\n}\n\nfunction buildOraclePrompt(\n scope: ReviewScope,\n identifier: string,\n stories: Array<{ id: string; content: string | null }>,\n architecture: string | null\n): string {\n const storiesText = stories\n .map((s) => `## Story ${s.id}\\n\\n${s.content || \"(empty)\"}`)\n .join(\"\\n\\n---\\n\\n\");\n\n const scopeDescription =\n scope === \"epic\"\n ? `Epic ${identifier} - Review ALL stories for issues AND cross-story patterns`\n : `Story ${identifier} - Deep dive focused review`;\n\n return `You are a security, logic, and performance expert conducting a \"party review\" of BMAD stories BEFORE development begins.\n\n**Your Role**: Find issues while they're cheap to fix (in markdown, not code).\n\n**Focus Areas**:\n1. 🔒 **Security Gaps**: Missing auth/authorization, input validation, data exposure risks\n2. 🧠 **Logic Gaps**: Edge cases not covered, error scenarios missing, validation rules incomplete\n3. ✨ **Best Practice Flaws**: Anti-patterns, testing strategy gaps, accessibility concerns\n4. ⚡ **Performance Issues**: N+1 queries, missing caching, large data handling\n\n**Scope**: ${scopeDescription}\n\n**Architecture Context**:\n${architecture || \"(No architecture documented)\"}\n\n**Stories to Review**:\n${storiesText}\n\n**Output Format** (JSON):\n{\n \"summary\": {\n \"totalIssues\": number,\n \"highSeverity\": number,\n \"mediumSeverity\": number,\n \"lowSeverity\": number,\n \"recommendation\": \"string\"\n },\n ${\n scope === \"epic\"\n ? `\"storyFindings\": [\n {\n \"storyId\": \"string\",\n \"title\": \"string\",\n \"findings\": {\n \"security\": [{ \"id\": \"unique\", \"severity\": \"high|medium|low\", \"title\": \"...\", \"description\": \"...\", \"impact\": \"...\", \"suggestion\": \"...\" }],\n \"logic\": [...],\n \"bestPractices\": [...],\n \"performance\": [...]\n }\n }\n ],\n \"crossStoryIssues\": [\n { \"id\": \"unique\", \"category\": \"security|logic|bestPractices|performance\", \"severity\": \"high|medium|low\", \"title\": \"...\", \"description\": \"...\", \"affectedStories\": [\"2.1\", \"2.3\"], \"suggestion\": \"...\" }\n ]`\n : `\"findings\": {\n \"security\": [{ \"id\": \"unique\", \"severity\": \"high|medium|low\", \"title\": \"...\", \"description\": \"...\", \"impact\": \"...\", \"suggestion\": \"...\" }],\n \"logic\": [...],\n \"bestPractices\": [...],\n \"performance\": [...]\n }`\n }\n}\n\n**Instructions**:\n- Be thorough but practical\n- Prioritize high-impact issues\n- Provide actionable suggestions\n- Flag missing requirements as logic gaps`;\n}\n\ninterface OracleResult {\n success: boolean;\n content?: string;\n error?: string;\n}\n\nasync function spawnOracleAndWait(\n ctx: PluginInput,\n config: AthenaConfig,\n prompt: string,\n _forceAdvancedModel?: boolean\n): Promise<OracleResult> {\n try {\n const createResult = await ctx.client.session.create({\n body: {\n title: \"Party Review - Oracle Analysis\",\n },\n });\n\n if (!createResult.data?.id) {\n return { success: false, error: \"Failed to create Oracle session\" };\n }\n\n const sessionId = createResult.data.id;\n\n const promptResult = await ctx.client.session.prompt({\n path: { id: sessionId },\n body: {\n model: parseModelConfig(config.models.oracle),\n parts: [{ type: \"text\", text: prompt }],\n },\n });\n\n if (!promptResult.data) {\n return { success: false, error: \"No response from Oracle\" };\n }\n\n const messagesResult = await ctx.client.session.messages({\n path: { id: sessionId },\n });\n\n const lastMessage = messagesResult.data?.at(-1);\n if (!lastMessage) {\n return { success: false, error: \"No messages in Oracle session\" };\n }\n\n const textParts = lastMessage.parts?.filter((p) => p.type === \"text\") || [];\n const content = textParts.map((p) => (p as { text: string }).text).join(\"\\n\");\n\n return { success: true, content };\n } catch (error) {\n const message = error instanceof Error ? error.message : \"Unknown error\";\n return { success: false, error: `Oracle spawn failed: ${message}` };\n }\n}\n\nfunction parseModelConfig(modelString: string): { providerID: string; modelID: string } {\n const [providerID, modelID] = modelString.split(\"/\");\n return { providerID: providerID || \"openai\", modelID: modelID || modelString };\n}\n\nasync function saveReviewFolder(\n reviewsDir: string,\n scope: ReviewScope,\n identifier: string,\n stories: Array<{ id: string; content: string | null }>,\n parsed: ParsedOracleResponse,\n oracleAnalysis: string,\n findings: FindingCounts,\n recommendedAgents: AgentRecommendation[],\n summaryText: string\n): Promise<string> {\n const date = new Date().toISOString().split(\"T\")[0];\n const folderName = `party-review-${scope}-${identifier.replace(\".\", \"-\")}-${date}`;\n const folderPath = join(reviewsDir, folderName);\n\n await ensureDirectory(folderPath);\n\n const storyList = stories.map((s) => s.id).join(\", \");\n const { summary } = parsed;\n\n const markdown = `# Party Review: ${scope === \"epic\" ? `Epic ${identifier}` : `Story ${identifier}`}\n\n**Date**: ${date}\n**Reviewer**: Oracle (Party Mode)\n**Stories Reviewed**: ${storyList}\n\n---\n\n## Executive Summary\n\n- **Total Issues**: ${summary.totalIssues}\n- **High Severity**: ${summary.highSeverity} issues (MUST address)\n- **Medium Severity**: ${summary.mediumSeverity} issues (SHOULD address)\n- **Low Severity**: ${summary.lowSeverity} issues (NICE to address)\n\n**Recommendation**: ${summary.recommendation}\n\n---\n\n## Findings\n\n${formatFindings(parsed)}\n\n---\n\n## Appendix: Oracle's Full Analysis\n\n<details>\n<summary>Click to expand detailed reasoning</summary>\n\n${oracleAnalysis}\n\n</details>\n`;\n\n const fullData: Phase1FullData = {\n success: true,\n scope,\n identifier,\n findings,\n recommendedAgents,\n reviewFolderPath: folderPath,\n summary: summaryText,\n storiesContent: stories,\n oracleAnalysis,\n };\n\n await writeFile(join(folderPath, \"review.md\"), markdown, \"utf-8\");\n await writeFile(join(folderPath, \"analysis.json\"), JSON.stringify(fullData, null, 2), \"utf-8\");\n\n return folderPath;\n}\n\nfunction formatFindings(parsed: ParsedOracleResponse): string {\n let output = \"\";\n\n const categoryIcons: Record<string, string> = {\n security: \"🔒\",\n logic: \"🧠\",\n bestPractices: \"✨\",\n performance: \"⚡\",\n };\n\n if (parsed.findings) {\n for (const [category, findings] of Object.entries(parsed.findings)) {\n if (findings && findings.length > 0) {\n output += `### ${categoryIcons[category] || \"\"} ${formatCategoryName(category)} (${findings.length} issues)\\n\\n`;\n for (const finding of findings) {\n output += `#### [${finding.severity.toUpperCase()}] ${finding.title}\\n`;\n output += `**Finding**: ${finding.description}\\n`;\n output += `**Impact**: ${finding.impact}\\n`;\n output += `**Suggestion**: ${finding.suggestion}\\n`;\n output += \"**Decision**: [ ] Accept [ ] Defer [ ] Reject\\n\\n\";\n }\n }\n }\n }\n\n if (parsed.storyFindings) {\n for (const story of parsed.storyFindings) {\n output += `### Story ${story.storyId}: ${story.title}\\n\\n`;\n for (const [category, findings] of Object.entries(story.findings)) {\n if (findings && findings.length > 0) {\n output += `#### ${categoryIcons[category] || \"\"} ${formatCategoryName(category)}\\n\\n`;\n for (const finding of findings) {\n output += `- [${finding.severity.toUpperCase()}] **${finding.title}**: ${finding.description}\\n`;\n }\n output += \"\\n\";\n }\n }\n }\n }\n\n if (parsed.crossStoryIssues && parsed.crossStoryIssues.length > 0) {\n output += \"### Cross-Story Issues\\n\\n\";\n for (const issue of parsed.crossStoryIssues) {\n output += `#### [${issue.severity.toUpperCase()}] ${issue.title}\\n`;\n output += `**Stories Affected**: ${issue.affectedStories.join(\", \")}\\n`;\n output += `**Description**: ${issue.description}\\n`;\n output += `**Suggestion**: ${issue.suggestion}\\n\\n`;\n }\n }\n\n return output || \"No findings detected.\";\n}\n\nfunction formatCategoryName(category: string): string {\n const names: Record<string, string> = {\n security: \"Security Issues\",\n logic: \"Logic Issues\",\n bestPractices: \"Best Practices\",\n performance: \"Performance Issues\",\n };\n return names[category] || category;\n}\n\nfunction buildSummary(findings: FindingCounts, agents: AgentRecommendation[]): string {\n const agentList = agents\n .filter((a) => a.priority !== \"optional\")\n .map((a) => a.agent)\n .join(\", \");\n\n return `Found ${findings.total} issues (${findings.high} high, ${findings.medium} medium, ${findings.low} low). Recommended agents: ${agentList || \"none\"}.`;\n}\n","import type { BmadAgentType } from \"../../shared/types.js\";\n\nexport interface AgentAnalysis {\n agent: BmadAgentType;\n perspective: string;\n findings: {\n agreements: string[];\n concerns: string[];\n suggestions: string[];\n };\n crossStoryPatterns: Array<{\n pattern: string;\n affectedStories: string[];\n recommendation: string;\n }>;\n prioritizedIssues: Array<{\n findingId: string;\n agentPriority: \"critical\" | \"important\" | \"minor\";\n rationale: string;\n }>;\n summary: string;\n}\n\nexport interface ConsensusPoint {\n topic: string;\n agents: BmadAgentType[];\n position: string;\n}\n\nexport interface DebatePoint {\n topic: string;\n positions: Array<{\n agent: BmadAgentType;\n position: string;\n }>;\n}\n\nexport interface AggregatedPriority {\n findingId: string;\n votes: Partial<Record<BmadAgentType, \"critical\" | \"important\" | \"minor\">>;\n consensusLevel: \"strong\" | \"moderate\" | \"disputed\";\n averagePriority: \"critical\" | \"important\" | \"minor\";\n}\n\nexport interface SynthesizedResult {\n agentAnalyses: AgentAnalysis[];\n consensusPoints: ConsensusPoint[];\n debatePoints: DebatePoint[];\n aggregatedPriorities: AggregatedPriority[];\n}\n\nexport function synthesizeAgentResponses(analyses: AgentAnalysis[]): SynthesizedResult {\n const consensusPoints = findConsensusPoints(analyses);\n const debatePoints = findDebatePoints(analyses);\n const aggregatedPriorities = aggregatePriorities(analyses);\n\n return {\n agentAnalyses: analyses,\n consensusPoints,\n debatePoints,\n aggregatedPriorities,\n };\n}\n\nfunction calculateConsensusThreshold(totalAgents: number): number {\n const minimumAgents = 2;\n const proportionalThreshold = Math.ceil(totalAgents * 0.5);\n return Math.max(minimumAgents, proportionalThreshold);\n}\n\nfunction findConsensusPoints(analyses: AgentAnalysis[]): ConsensusPoint[] {\n const concernMap = new Map<string, { agents: BmadAgentType[]; positions: string[] }>();\n\n for (const analysis of analyses) {\n for (const concern of analysis.findings.concerns) {\n const key = normalizeForComparison(concern);\n const existing = concernMap.get(key) || { agents: [], positions: [] };\n existing.agents.push(analysis.agent);\n existing.positions.push(concern);\n concernMap.set(key, existing);\n }\n\n for (const agreement of analysis.findings.agreements) {\n const key = normalizeForComparison(agreement);\n const existing = concernMap.get(key) || { agents: [], positions: [] };\n existing.agents.push(analysis.agent);\n existing.positions.push(agreement);\n concernMap.set(key, existing);\n }\n }\n\n const consensusThreshold = calculateConsensusThreshold(analyses.length);\n const consensusPoints: ConsensusPoint[] = [];\n\n for (const [_, data] of concernMap) {\n if (data.agents.length >= consensusThreshold) {\n consensusPoints.push({\n topic: data.positions[0],\n agents: data.agents,\n position: data.positions[0],\n });\n }\n }\n\n return consensusPoints;\n}\n\nfunction findDebatePoints(analyses: AgentAnalysis[]): DebatePoint[] {\n const debatePoints: DebatePoint[] = [];\n const processedPairs = new Set<string>();\n\n for (let i = 0; i < analyses.length; i++) {\n for (let j = i + 1; j < analyses.length; j++) {\n const agent1 = analyses[i];\n const agent2 = analyses[j];\n const pairKey = `${agent1.agent}-${agent2.agent}`;\n\n if (processedPairs.has(pairKey)) continue;\n processedPairs.add(pairKey);\n\n const conflictingPriorities = findConflictingPriorities(agent1, agent2);\n for (const conflict of conflictingPriorities) {\n debatePoints.push({\n topic: `Priority disagreement on ${conflict.findingId}`,\n positions: [\n { agent: agent1.agent, position: `${conflict.priority1}: ${conflict.rationale1}` },\n { agent: agent2.agent, position: `${conflict.priority2}: ${conflict.rationale2}` },\n ],\n });\n }\n }\n }\n\n return debatePoints;\n}\n\ninterface PriorityConflict {\n findingId: string;\n priority1: string;\n rationale1: string;\n priority2: string;\n rationale2: string;\n}\n\nfunction findConflictingPriorities(\n agent1: AgentAnalysis,\n agent2: AgentAnalysis\n): PriorityConflict[] {\n const conflicts: PriorityConflict[] = [];\n const priorityOrder = { critical: 0, important: 1, minor: 2 };\n\n for (const issue1 of agent1.prioritizedIssues) {\n const matchingIssue = agent2.prioritizedIssues.find((i) =>\n i.findingId.toLowerCase().includes(issue1.findingId.toLowerCase())\n );\n\n if (matchingIssue) {\n const diff = Math.abs(\n priorityOrder[issue1.agentPriority] - priorityOrder[matchingIssue.agentPriority]\n );\n if (diff >= 2) {\n conflicts.push({\n findingId: issue1.findingId,\n priority1: issue1.agentPriority,\n rationale1: issue1.rationale,\n priority2: matchingIssue.agentPriority,\n rationale2: matchingIssue.rationale,\n });\n }\n }\n }\n\n return conflicts;\n}\n\nfunction aggregatePriorities(analyses: AgentAnalysis[]): AggregatedPriority[] {\n const priorityMap = new Map<\n string,\n { votes: Partial<Record<BmadAgentType, \"critical\" | \"important\" | \"minor\">>; count: number }\n >();\n\n for (const analysis of analyses) {\n for (const issue of analysis.prioritizedIssues) {\n const existing = priorityMap.get(issue.findingId) || { votes: {}, count: 0 };\n existing.votes[analysis.agent] = issue.agentPriority;\n existing.count++;\n priorityMap.set(issue.findingId, existing);\n }\n }\n\n const aggregated: AggregatedPriority[] = [];\n for (const [findingId, data] of priorityMap) {\n const votes = Object.values(data.votes);\n const consensusLevel = calculateConsensusLevel(votes);\n const averagePriority = calculateAveragePriority(votes);\n\n aggregated.push({\n findingId,\n votes: data.votes,\n consensusLevel,\n averagePriority,\n });\n }\n\n return aggregated;\n}\n\nfunction calculateConsensusLevel(\n votes: Array<\"critical\" | \"important\" | \"minor\">\n): \"strong\" | \"moderate\" | \"disputed\" {\n if (votes.length <= 1) return \"strong\";\n\n const uniqueVotes = new Set(votes);\n if (uniqueVotes.size === 1) return \"strong\";\n if (uniqueVotes.size === 2) return \"moderate\";\n return \"disputed\";\n}\n\nfunction calculateAveragePriority(\n votes: Array<\"critical\" | \"important\" | \"minor\">\n): \"critical\" | \"important\" | \"minor\" {\n if (votes.length === 0) return \"minor\";\n\n const priorityOrder = { critical: 0, important: 1, minor: 2 };\n const sum = votes.reduce((acc, v) => acc + priorityOrder[v], 0);\n const avg = sum / votes.length;\n\n if (avg < 0.5) return \"critical\";\n if (avg < 1.5) return \"important\";\n return \"minor\";\n}\n\nfunction normalizeForComparison(text: string): string {\n return text\n .toLowerCase()\n .replace(/[^\\w\\s]/g, \"\")\n .split(/\\s+/)\n .slice(0, 5)\n .join(\" \");\n}\n\nexport function parseAgentResponse(responseText: string | null | undefined): AgentAnalysis | null {\n if (!responseText || typeof responseText !== \"string\") {\n return null;\n }\n\n try {\n const jsonMatch = responseText.match(/\\{[\\s\\S]*\\}/);\n if (!jsonMatch) return null;\n\n const parsed = JSON.parse(jsonMatch[0]) as AgentAnalysis;\n\n if (!parsed.agent || !parsed.findings) return null;\n\n return {\n agent: parsed.agent,\n perspective: parsed.perspective || \"\",\n findings: {\n agreements: parsed.findings.agreements || [],\n concerns: parsed.findings.concerns || [],\n suggestions: parsed.findings.suggestions || [],\n },\n crossStoryPatterns: parsed.crossStoryPatterns || [],\n prioritizedIssues: parsed.prioritizedIssues || [],\n summary: parsed.summary || \"\",\n };\n } catch {\n return null;\n }\n}\n","import { existsSync } from \"node:fs\";\nimport { readFile, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { type ToolDefinition, tool } from \"@opencode-ai/plugin\";\nimport type { PluginInput } from \"@opencode-ai/plugin\";\nimport type { AthenaConfig, BmadAgentType, Phase1FullData } from \"../../shared/types.js\";\nimport { getRecommendedAgentTypes } from \"../utils/agent-selector.js\";\nimport { getPersona, loadPersonas } from \"../utils/persona-loader.js\";\nimport {\n type AgentAnalysis,\n type SynthesizedResult,\n parseAgentResponse,\n synthesizeAgentResponses,\n} from \"../utils/response-synthesizer.js\";\n\nexport interface Phase2ConsultResult {\n success: boolean;\n identifier: string;\n reviewFolderPath?: string;\n error?: string;\n suggestion?: string;\n\n agentAnalyses?: AgentAnalysis[];\n consensusPoints?: SynthesizedResult[\"consensusPoints\"];\n debatePoints?: SynthesizedResult[\"debatePoints\"];\n aggregatedPriorities?: SynthesizedResult[\"aggregatedPriorities\"];\n summary?: string;\n}\n\nexport function createStoryReviewConsultTool(\n ctx: PluginInput,\n config: AthenaConfig\n): ToolDefinition {\n return tool({\n description: `Consult BMAD expert agents for their perspectives on review findings.\n\nThis tool performs Phase 2 of the party review workflow:\n1. Loads the full analysis from the review folder (analysis.json)\n2. Spawns parallel sessions for each recommended BMAD agent\n3. Each agent reads the analysis file and provides their perspective\n4. Waits for all agents to complete (blocking)\n5. Synthesizes responses to find consensus and debates\n\nUse this after Phase 1 (athena_story_review_analyze) and before Phase 3 (athena_party_discussion).`,\n\n args: {\n reviewFolderPath: tool.schema\n .string()\n .describe(\n \"Path to the review folder from athena_story_review_analyze (contains analysis.json)\"\n ),\n agents: tool.schema\n .array(tool.schema.string())\n .optional()\n .describe(\"Override agent list (default: use recommended from phase1)\"),\n },\n\n async execute(args): Promise<string> {\n const result = await executePhase2Consultation(\n ctx,\n config,\n args.reviewFolderPath,\n args.agents\n );\n return JSON.stringify(result, null, 2);\n },\n });\n}\n\nasync function executePhase2Consultation(\n ctx: PluginInput,\n config: AthenaConfig,\n reviewFolderPath: string,\n overrideAgents?: string[]\n): Promise<Phase2ConsultResult> {\n const analysisPath = join(reviewFolderPath, \"analysis.json\");\n\n if (!existsSync(analysisPath)) {\n return {\n success: false,\n identifier: \"\",\n error: `Analysis file not found: ${analysisPath}`,\n suggestion: \"Run athena_story_review_analyze first to generate the review folder\",\n };\n }\n\n let phase1: Phase1FullData;\n try {\n const analysisContent = await readFile(analysisPath, \"utf-8\");\n phase1 = JSON.parse(analysisContent);\n } catch (err) {\n const message = err instanceof Error ? err.message : \"Unknown error\";\n return {\n success: false,\n identifier: \"\",\n error: `Failed to load analysis.json: ${message}`,\n suggestion: \"Ensure the review folder contains a valid analysis.json file\",\n };\n }\n\n if (!phase1.success || !phase1.oracleAnalysis) {\n return {\n success: false,\n identifier: phase1.identifier,\n error: \"Phase 1 was not successful or missing oracle analysis\",\n suggestion: \"Run athena_story_review_analyze first\",\n };\n }\n\n const agents = overrideAgents\n ? (overrideAgents as BmadAgentType[])\n : getRecommendedAgentTypes(phase1.recommendedAgents || []);\n\n if (agents.length === 0) {\n return {\n success: false,\n identifier: phase1.identifier,\n error: \"No agents to consult\",\n suggestion: \"Specify agents or ensure Phase 1 has recommendations\",\n };\n }\n\n const personas = await loadPersonas(ctx.directory);\n\n const agentPromises = agents.map((agentType) =>\n spawnAgentAndWait(ctx, config, agentType, phase1, personas)\n );\n\n const agentResults = await Promise.all(agentPromises);\n\n const successfulAnalyses = agentResults.filter((r) => r !== null) as AgentAnalysis[];\n\n if (successfulAnalyses.length === 0) {\n return {\n success: false,\n identifier: phase1.identifier,\n error: \"All agent consultations failed\",\n suggestion: \"Check agent configuration and try again\",\n };\n }\n\n const synthesized = synthesizeAgentResponses(successfulAnalyses);\n\n const summary = buildConsultationSummary(synthesized, agents.length);\n\n const result: Phase2ConsultResult = {\n success: true,\n identifier: phase1.identifier,\n reviewFolderPath,\n agentAnalyses: synthesized.agentAnalyses,\n consensusPoints: synthesized.consensusPoints,\n debatePoints: synthesized.debatePoints,\n aggregatedPriorities: synthesized.aggregatedPriorities,\n summary,\n };\n\n const phase2Path = join(reviewFolderPath, \"phase2.json\");\n await writeFile(phase2Path, JSON.stringify(result, null, 2), \"utf-8\");\n\n return result;\n}\n\nasync function spawnAgentAndWait(\n ctx: PluginInput,\n config: AthenaConfig,\n agentType: BmadAgentType,\n phase1: Phase1FullData,\n personas: Map<BmadAgentType, import(\"../../shared/types.js\").BmadAgentFullPersona>\n): Promise<AgentAnalysis | null> {\n try {\n const persona = getPersona(personas, agentType);\n const prompt = buildAgentPrompt(persona, phase1);\n\n const createResult = await ctx.client.session.create({\n body: {\n title: `Party Review - ${persona.name} Analysis`,\n },\n });\n\n if (!createResult.data?.id) {\n console.warn(`[Athena] Failed to create session for ${agentType}`);\n return null;\n }\n\n const sessionId = createResult.data.id;\n\n await ctx.client.session.prompt({\n path: { id: sessionId },\n body: {\n model: parseModelConfig(config.models.sisyphus),\n parts: [{ type: \"text\", text: prompt }],\n },\n });\n\n const messagesResult = await ctx.client.session.messages({\n path: { id: sessionId },\n });\n\n const lastMessage = messagesResult.data?.at(-1);\n if (!lastMessage) {\n console.warn(`[Athena] No response from ${agentType}`);\n return null;\n }\n\n const textParts = lastMessage.parts?.filter((p) => p.type === \"text\") || [];\n const content = textParts.map((p) => (p as { text: string }).text).join(\"\\n\");\n\n const parsed = parseAgentResponse(content);\n if (!parsed) {\n return createFallbackAnalysis(agentType, persona.name, content);\n }\n\n return parsed;\n } catch (error) {\n const message = error instanceof Error ? error.message : \"Unknown error\";\n console.warn(`[Athena] Agent ${agentType} consultation failed: ${message}`);\n return null;\n }\n}\n\nfunction buildAgentPrompt(\n persona: import(\"../../shared/types.js\").BmadAgentFullPersona,\n phase1: Phase1FullData\n): string {\n const storiesContext = phase1.storiesContent\n ?.map((s: { id: string; content: string | null }) => {\n const preview = s.content?.substring(0, 2000) || \"(empty)\";\n const truncated = s.content && s.content.length > 2000 ? \"...[truncated]\" : \"\";\n return `Story ${s.id}:\\n${preview}${truncated}`;\n })\n .join(\"\\n\\n\");\n\n return `You are ${persona.name}, the ${persona.title} from the BMAD team.\n\n**Your Icon**: ${persona.icon}\n**Your Expertise**: ${persona.expertise.join(\", \")}\n**Your Perspective**: ${persona.perspective}\n\n**Your Task**: Analyze the following Oracle review findings from your ${persona.type} perspective.\n\n**Stories Being Reviewed**:\n${storiesContext || \"(No story content available)\"}\n\n**Oracle's Findings**:\n${phase1.oracleAnalysis || \"(No analysis available)\"}\n\n**Your Analysis Instructions**:\n1. Review each finding from your ${persona.perspective} perspective\n2. Note findings you agree with and why\n3. Raise any concerns specific to your expertise\n4. Suggest additional considerations\n5. Prioritize issues based on ${persona.expertise[0] || \"your expertise\"} impact\n\n**Return JSON** (MUST be valid JSON):\n{\n \"agent\": \"${persona.type}\",\n \"perspective\": \"${persona.perspective}\",\n \"findings\": {\n \"agreements\": [\"I agree with X because...\"],\n \"concerns\": [\"From my perspective, Y is concerning because...\"],\n \"suggestions\": [\"Consider also Z...\"]\n },\n \"crossStoryPatterns\": [\n { \"pattern\": \"...\", \"affectedStories\": [\"2.1\"], \"recommendation\": \"...\" }\n ],\n \"prioritizedIssues\": [\n { \"findingId\": \"...\", \"agentPriority\": \"critical|important|minor\", \"rationale\": \"...\" }\n ],\n \"summary\": \"Brief 2-3 sentence summary of my analysis\"\n}`;\n}\n\nfunction createFallbackAnalysis(\n agentType: BmadAgentType,\n agentName: string,\n rawContent: string\n): AgentAnalysis {\n return {\n agent: agentType,\n perspective: `${agentName}'s perspective`,\n findings: {\n agreements: [],\n concerns: [rawContent.substring(0, 200)],\n suggestions: [],\n },\n crossStoryPatterns: [],\n prioritizedIssues: [],\n summary: `${agentName} provided analysis but response was not in expected JSON format.`,\n };\n}\n\nfunction parseModelConfig(modelString: string): { providerID: string; modelID: string } {\n const [providerID, modelID] = modelString.split(\"/\");\n return { providerID: providerID || \"anthropic\", modelID: modelID || modelString };\n}\n\nfunction buildConsultationSummary(synthesized: SynthesizedResult, totalAgents: number): string {\n const successCount = synthesized.agentAnalyses.length;\n const consensusCount = synthesized.consensusPoints.length;\n const debateCount = synthesized.debatePoints.length;\n\n return `Consulted ${successCount}/${totalAgents} agents. Found ${consensusCount} consensus points and ${debateCount} debate points.`;\n}\n","import { type ToolDefinition, tool } from \"@opencode-ai/plugin\";\nimport type { PluginInput } from \"@opencode-ai/plugin\";\nimport type { AthenaConfig, BmadStoryStatus } from \"../../shared/types.js\";\nimport type { StoryTracker } from \"../tracker/story-tracker.js\";\nimport { getBmadPaths } from \"../utils/bmad-finder.js\";\nimport { sendNotification } from \"../utils/notifications.js\";\nimport { createPluginLogger } from \"../utils/plugin-logger.js\";\nimport { getStoryTitle, updateStoryFileStatus } from \"../utils/story-file-updater.js\";\nimport { findStoryFile, normalizeStoryId, stripAtPrefix } from \"../utils/story-loader.js\";\nimport {\n calculateSprintProgress,\n findNextReadyStory,\n parseStoryKey,\n readBmadSprintStatus,\n storyIdToDotFormat,\n updateEpicStatusIfNeeded,\n updateStoryStatus as updateSprintStoryStatus,\n} from \"../utils/yaml-handler.js\";\n\nconst log = createPluginLogger(\"update-status\");\n\nexport interface UpdateStatusResult {\n success?: boolean;\n storyId?: string;\n newStatus?: BmadStoryStatus;\n previousStatus?: string;\n updatedAt?: string;\n storyFileUpdated?: boolean;\n epicStatusUpdated?: boolean;\n epicNewStatus?: string;\n sprintProgress?: {\n total: number;\n done: number;\n inProgress: number;\n readyForDev: number;\n backlog: number;\n blocked: number;\n review: number;\n percentComplete: number;\n };\n nextStory?: string | null;\n error?: string;\n}\n\nexport function createUpdateStatusTool(\n ctx: PluginInput,\n tracker: StoryTracker,\n config: AthenaConfig\n): ToolDefinition {\n return tool({\n description: `Update the BMAD sprint status for a story.\n\nCall this tool when:\n- Starting a story (status: \"in-progress\")\n- Completing a story (status: \"done\") - requires completionSummary\n- Blocking on an issue (status: \"blocked\") - requires notes explaining blocker\n- Requesting review (status: \"review\")\n\nBoth sprint-status.yaml and the story file's Status field will be updated.`,\n\n args: {\n storyId: tool.schema.string().describe(\"Story ID (e.g., '2.3' or '2-3') or file path\"),\n status: tool.schema\n .enum([\"in-progress\", \"review\", \"done\", \"blocked\"])\n .describe(\"The new status (BMAD v6 hyphenated format)\"),\n notes: tool.schema\n .string()\n .optional()\n .describe(\"Notes about the status change (required for 'blocked')\"),\n completionSummary: tool.schema\n .string()\n .optional()\n .describe(\"Summary of what was implemented (required for 'done')\"),\n },\n\n async execute(args): Promise<string> {\n const result = await handleUpdateStatus(ctx, tracker, config, args);\n return JSON.stringify(result, null, 2);\n },\n });\n}\n\ninterface UpdateStatusArgs {\n storyId: string;\n status: \"in-progress\" | \"review\" | \"done\" | \"blocked\";\n notes?: string;\n completionSummary?: string;\n}\n\nasync function handleUpdateStatus(\n ctx: PluginInput,\n tracker: StoryTracker,\n config: AthenaConfig,\n args: UpdateStatusArgs\n): Promise<UpdateStatusResult> {\n const { status, notes, completionSummary } = args;\n const rawStoryId = stripAtPrefix(args.storyId);\n const normalizedId = normalizeStoryId(rawStoryId);\n\n log.debug(\"Updating story status\", {\n storyId: normalizedId,\n status,\n hasNotes: !!notes,\n hasSummary: !!completionSummary,\n });\n\n if (status === \"done\" && !completionSummary) {\n log.warn(\"Validation failed: completionSummary required for done status\", {\n storyId: normalizedId,\n });\n return { error: \"completionSummary is required when marking a story done\" };\n }\n\n if (status === \"blocked\" && !notes) {\n log.warn(\"Validation failed: notes required for blocked status\", { storyId: normalizedId });\n return { error: \"notes are required when blocking a story (explain the blocker)\" };\n }\n\n const paths = await getBmadPaths(ctx.directory, config);\n if (!paths.bmadDir) {\n log.warn(\"BMAD directory not found\", { directory: ctx.directory });\n const suggestion =\n paths.suggestion ||\n \"Run 'npx bmad-method@alpha install' to set up BMAD in this project. Athena supports both legacy (docs/) and v6-alpha (_bmad/ + _bmad-output/) structures.\";\n return { error: `No BMAD directory found. ${suggestion}` };\n }\n\n if (!paths.sprintStatus) {\n log.error(\"Sprint status file not found\");\n return { error: \"No sprint-status.yaml found\" };\n }\n\n const sprintStatus = await readBmadSprintStatus(paths.sprintStatus);\n if (!sprintStatus) {\n log.error(\"Failed to read sprint status file\", { path: paths.sprintStatus });\n return { error: \"Failed to read sprint-status.yaml\" };\n }\n\n let storyTitle: string | undefined;\n const storyFile = await findStoryFile(paths.storiesDir, normalizedId);\n if (storyFile) {\n storyTitle = (await getStoryTitle(storyFile.path)) ?? undefined;\n }\n\n const updateResult = await updateSprintStoryStatus(\n paths.sprintStatus,\n normalizedId,\n status,\n storyTitle\n );\n\n if (!updateResult.success) {\n log.error(\"Failed to update sprint status\", { storyId: normalizedId });\n return { error: \"Failed to update sprint-status.yaml\" };\n }\n\n let storyFileUpdated = false;\n if (storyFile) {\n const fileUpdateResult = await updateStoryFileStatus(storyFile.path, status);\n storyFileUpdated = fileUpdateResult.success;\n if (!fileUpdateResult.success) {\n log.warn(\"Failed to update story file status\", {\n path: storyFile.path,\n error: fileUpdateResult.error,\n });\n }\n }\n\n const parsed = parseStoryKey(updateResult.key);\n let epicStatusUpdated = false;\n let epicNewStatus: string | undefined;\n\n if (parsed) {\n const epicUpdate = await updateEpicStatusIfNeeded(paths.sprintStatus, parsed.epicNum);\n if (epicUpdate.updated) {\n epicStatusUpdated = true;\n epicNewStatus = epicUpdate.newStatus;\n log.info(\"Auto-updated epic status\", {\n epicNum: parsed.epicNum,\n newStatus: epicUpdate.newStatus,\n });\n }\n }\n\n const now = new Date().toISOString();\n await tracker.updateStoryStatus(normalizedId, status);\n\n if (config.features?.notifications && status === \"done\") {\n log.debug(\"Sending completion notification\", { storyId: normalizedId });\n await sendNotification(\n `Story ${storyIdToDotFormat(normalizedId)} completed!`,\n \"OpenCode Athena\",\n ctx.$\n );\n }\n\n const updatedStatus = await readBmadSprintStatus(paths.sprintStatus);\n const progress = updatedStatus ? calculateSprintProgress(updatedStatus) : null;\n\n let nextStory: string | null = null;\n if (status === \"done\" && updatedStatus) {\n const next = findNextReadyStory(updatedStatus);\n nextStory = next ? storyIdToDotFormat(next.parsed.normalizedId) : null;\n }\n\n log.info(\"Story status updated successfully\", {\n storyId: normalizedId,\n status,\n previousStatus: updateResult.previousStatus,\n storyFileUpdated,\n epicStatusUpdated,\n progress,\n });\n\n return {\n success: true,\n storyId: storyIdToDotFormat(normalizedId),\n newStatus: status,\n previousStatus: updateResult.previousStatus,\n updatedAt: now,\n storyFileUpdated,\n epicStatusUpdated,\n epicNewStatus,\n sprintProgress: progress ?? undefined,\n nextStory,\n };\n}\n","import type { PluginInput, ToolDefinition } from \"@opencode-ai/plugin\";\nimport type { AthenaConfig } from \"../../shared/types.js\";\nimport type { StoryTracker } from \"../tracker/story-tracker.js\";\nimport { createAnalyzeStoryTool } from \"./analyze-story.js\";\nimport { createConfigTool } from \"./config.js\";\nimport { createDecomposeStoryTool } from \"./decompose-story.js\";\nimport { createGetContextTool } from \"./get-context.js\";\nimport { createGetStoryTool } from \"./get-story.js\";\nimport { createParallelTool } from \"./parallel.js\";\nimport { createPartyDiscussionTool } from \"./party-discussion.js\";\nimport { createReviewStoryTool } from \"./review-story.js\";\nimport { createStoryReviewAnalyzeTool } from \"./story-review-analyze.js\";\nimport { createStoryReviewConsultTool } from \"./story-review-consult.js\";\nimport { createUpdateStatusTool } from \"./update-status.js\";\n\n/**\n * Create all Athena tools\n *\n * @param ctx - Plugin context from OpenCode\n * @param tracker - Story tracker instance\n * @param config - Athena configuration\n * @returns Object containing all tool definitions\n */\nexport function createTools(\n ctx: PluginInput,\n tracker: StoryTracker,\n config: AthenaConfig\n): Record<string, ToolDefinition> {\n return {\n athena_get_story: createGetStoryTool(ctx, tracker, config),\n athena_update_status: createUpdateStatusTool(ctx, tracker, config),\n athena_get_context: createGetContextTool(tracker, config),\n athena_parallel: createParallelTool(),\n athena_config: createConfigTool(config),\n athena_review_story: createReviewStoryTool(ctx, config),\n athena_story_review_analyze: createStoryReviewAnalyzeTool(ctx, config),\n athena_story_review_consult: createStoryReviewConsultTool(ctx, config),\n athena_party_discussion: createPartyDiscussionTool(ctx, config),\n athena_analyze_story: createAnalyzeStoryTool(ctx, config),\n athena_decompose_story: createDecomposeStoryTool(ctx, config),\n };\n}\n","/**\n * Story Tracker\n *\n * Tracks the current story state and persists it across sessions.\n * State is stored in ~/.config/opencode/athena/athena-state.json\n */\n\nimport { existsSync } from \"node:fs\";\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport { CONFIG_PATHS } from \"../../shared/constants.js\";\nimport type {\n OpenCodeTodo,\n TrackedStory,\n TrackerState,\n TrackerStatus,\n} from \"../../shared/types.js\";\nimport { createPluginLogger } from \"../utils/plugin-logger.js\";\n\nconst log = createPluginLogger(\"story-tracker\");\n\n/**\n * Story tracker that persists state across sessions.\n *\n * Features:\n * - Tracks current story being implemented\n * - Maintains history of story status changes\n * - Persists state to disk for session recovery\n * - Scoped to project directory\n */\nexport class StoryTracker {\n private state: TrackerState;\n private stateFilePath: string;\n private projectDir: string;\n\n constructor(projectDir: string) {\n this.projectDir = projectDir;\n this.stateFilePath = CONFIG_PATHS.stateFile;\n this.state = {\n currentStory: null,\n sessionId: crypto.randomUUID(),\n projectDir,\n history: [],\n };\n }\n\n /**\n * Initialize the tracker by loading existing state\n */\n async initialize(): Promise<void> {\n if (existsSync(this.stateFilePath)) {\n try {\n const content = await readFile(this.stateFilePath, \"utf-8\");\n const savedState = JSON.parse(content) as TrackerState;\n\n // Only restore if same project directory\n if (savedState.projectDir === this.projectDir) {\n this.state = {\n ...savedState,\n sessionId: crypto.randomUUID(), // Always generate new session ID\n };\n }\n } catch {\n // Ignore errors, start with fresh state\n }\n }\n }\n\n /**\n * Set the current story being worked on\n */\n async setCurrentStory(storyId: string, data: Omit<TrackedStory, \"id\">): Promise<void> {\n this.state.currentStory = { id: storyId, ...data };\n this.addHistoryEntry(storyId, data.status);\n await this.saveState();\n }\n\n /**\n * Update the status of a story\n */\n async updateStoryStatus(storyId: string, status: TrackerStatus): Promise<void> {\n if (this.state.currentStory?.id === storyId) {\n this.state.currentStory.status = status;\n if (status === \"done\") {\n this.state.currentStory.completedAt = new Date().toISOString();\n }\n }\n this.addHistoryEntry(storyId, status);\n await this.saveState();\n }\n\n /**\n * Get the current story being tracked\n */\n getCurrentStory(): TrackedStory | null {\n return this.state.currentStory;\n }\n\n /**\n * Get a formatted context string for the current story\n * Used for compaction hooks to preserve context\n */\n async getCurrentStoryContext(): Promise<string | null> {\n if (!this.state.currentStory) {\n return null;\n }\n\n const story = this.state.currentStory;\n const recentHistory = this.state.history\n .slice(-5)\n .map((h) => `- ${h.storyId}: ${h.status} at ${h.timestamp}`)\n .join(\"\\n\");\n\n return `\nCurrent Story: ${story.id}\nStatus: ${story.status}\nStarted: ${story.startedAt}\n${story.completedAt ? `Completed: ${story.completedAt}` : \"\"}\n\nRecent Activity:\n${recentHistory}\n`.trim();\n }\n\n /**\n * Clear the current story (e.g., when completed or cancelled)\n */\n async clearCurrentStory(): Promise<void> {\n this.state.currentStory = null;\n await this.saveState();\n }\n\n /**\n * Get the current session ID\n */\n getSessionId(): string {\n return this.state.sessionId;\n }\n\n /**\n * Get the history of status changes\n */\n getHistory(): TrackerState[\"history\"] {\n return this.state.history;\n }\n\n getCurrentTodos(): OpenCodeTodo[] | null {\n return this.state.currentTodos || null;\n }\n\n async setCurrentTodos(todos: OpenCodeTodo[]): Promise<void> {\n this.state.currentTodos = todos;\n await this.saveState();\n }\n\n async clearTodos(): Promise<void> {\n this.state.currentTodos = undefined;\n await this.saveState();\n }\n\n /**\n * Add an entry to the history\n */\n private addHistoryEntry(storyId: string, status: string): void {\n this.state.history.push({\n storyId,\n status,\n timestamp: new Date().toISOString(),\n });\n\n // Keep history bounded (last 100 entries)\n if (this.state.history.length > 100) {\n this.state.history = this.state.history.slice(-100);\n }\n }\n\n /**\n * Save state to disk\n */\n private async saveState(): Promise<void> {\n try {\n const dir = dirname(this.stateFilePath);\n if (!existsSync(dir)) {\n await mkdir(dir, { recursive: true });\n }\n await writeFile(this.stateFilePath, JSON.stringify(this.state, null, 2), \"utf-8\");\n } catch (error) {\n log.warn(\"Failed to save tracker state\", { error });\n }\n }\n}\n","import { z } from \"zod\";\n\n/**\n * Zod validation schemas for OpenCode Athena\n */\n\n// ============================================================================\n// Configuration Schemas\n// ============================================================================\n\n/**\n * Schema for subscription configuration\n */\nexport const SubscriptionSchema = z.object({\n claude: z.object({\n enabled: z.boolean(),\n tier: z.enum([\"max5x\", \"max20x\", \"pro\", \"none\"]),\n }),\n openai: z.object({\n enabled: z.boolean(),\n }),\n google: z.object({\n enabled: z.boolean(),\n authMethod: z.enum([\"antigravity\", \"personal\", \"api\", \"none\"]),\n }),\n githubCopilot: z.object({\n enabled: z.boolean(),\n plan: z.enum([\"free\", \"pro\", \"pro-plus\", \"business\", \"enterprise\", \"none\"]),\n enabledModels: z.array(z.string()).optional(),\n }),\n});\n\n/**\n * Schema for BMAD configuration\n */\nexport const BmadConfigSchema = z.object({\n defaultTrack: z.enum([\"quick-flow\", \"bmad-method\", \"enterprise\"]),\n autoStatusUpdate: z.boolean(),\n parallelStoryLimit: z.number().int().min(0).max(10),\n paths: z\n .object({\n stories: z\n .string()\n .nullable()\n .optional()\n .describe(\"Custom path to stories directory (null = auto-detect)\"),\n sprintStatus: z\n .string()\n .nullable()\n .optional()\n .describe(\"Custom path to sprint-status.yaml file (null = auto-detect)\"),\n prd: z\n .string()\n .nullable()\n .optional()\n .describe(\"Custom path to PRD.md file (null = auto-detect)\"),\n architecture: z\n .string()\n .nullable()\n .optional()\n .describe(\"Custom path to architecture.md file (null = auto-detect)\"),\n epics: z\n .string()\n .nullable()\n .optional()\n .describe(\"Custom path to epics.md file (null = auto-detect)\"),\n outputFolder: z\n .string()\n .nullable()\n .optional()\n .describe(\"Custom path to BMAD output folder (null = auto-detect _bmad-output)\"),\n })\n .optional(),\n});\n\n/**\n * Schema for feature flags\n */\nexport const FeaturesSchema = z.object({\n bmadBridge: z.boolean(),\n autoStatus: z.boolean(),\n parallelExecution: z.boolean(),\n notifications: z.boolean(),\n contextMonitor: z.boolean(),\n commentChecker: z.boolean(),\n lspTools: z.boolean(),\n autoGitOperations: z.boolean().default(false),\n todoSync: z.boolean().default(true),\n});\n\n/**\n * Schema for MCP configuration\n */\nexport const McpsSchema = z.object({\n context7: z.boolean(),\n exa: z.boolean(),\n grepApp: z.boolean(),\n});\n\n/**\n * Schema for LLM provider\n */\nexport const LLMProviderSchema = z.enum([\"anthropic\", \"openai\", \"google\", \"github-copilot\"]);\n\n/**\n * Schema for agent routing configuration\n */\nexport const AgentRoutingSchema = z.object({\n requiresThinking: z.boolean().optional(),\n preferProvider: LLMProviderSchema.optional(),\n});\n\n/**\n * Schema for routing configuration\n */\nexport const RoutingConfigSchema = z.object({\n providerPriority: z.array(LLMProviderSchema),\n modelFamilyPriority: z.object({\n claude: z.array(LLMProviderSchema).optional(),\n gpt: z.array(LLMProviderSchema).optional(),\n gemini: z.array(LLMProviderSchema).optional(),\n }),\n agentOverrides: z.object({\n sisyphus: AgentRoutingSchema.optional(),\n oracle: AgentRoutingSchema.optional(),\n librarian: AgentRoutingSchema.optional(),\n frontend: AgentRoutingSchema.optional(),\n documentWriter: AgentRoutingSchema.optional(),\n multimodalLooker: AgentRoutingSchema.optional(),\n }),\n fallbackBehavior: z.object({\n autoFallback: z.boolean(),\n retryPeriodMs: z.number().min(0),\n notifyOnRateLimit: z.boolean(),\n }),\n});\n\n/**\n * Schema for thinking level\n */\nexport const ThinkingLevelSchema = z.enum([\"off\", \"low\", \"medium\", \"high\"]);\n\n/**\n * Schema for agent settings (temperature and thinking level)\n */\nexport const AgentSettingsSchema = z.object({\n temperature: z.number().min(0).max(1).optional(),\n thinkingLevel: ThinkingLevelSchema.optional(),\n});\n\n/**\n * Schema for custom model definition\n */\nexport const CustomModelDefinitionSchema = z.object({\n id: z.string(),\n name: z.string(),\n provider: z.enum([\"anthropic\", \"openai\", \"google\", \"github-copilot\"]),\n description: z.string().optional(),\n capabilities: z\n .object({\n thinking: z.boolean().optional(),\n contextWindow: z.number().optional(),\n supportsTemperature: z.boolean().optional(),\n })\n .optional(),\n});\n\n/**\n * Schema for agent model assignments\n */\nexport const ModelsSchema = z.object({\n sisyphus: z.string().describe(\"Model for main orchestrator agent\"),\n oracle: z.string().describe(\"Model for debugging/reasoning agent\"),\n librarian: z.string().describe(\"Model for research/documentation agent\"),\n frontend: z.string().optional().describe(\"Model for UI/UX agent\"),\n documentWriter: z.string().optional().describe(\"Model for documentation generation agent\"),\n multimodalLooker: z.string().optional().describe(\"Model for image analysis agent\"),\n settings: z\n .object({\n sisyphus: AgentSettingsSchema.optional(),\n oracle: AgentSettingsSchema.optional(),\n librarian: AgentSettingsSchema.optional(),\n frontend: AgentSettingsSchema.optional(),\n documentWriter: AgentSettingsSchema.optional(),\n multimodalLooker: AgentSettingsSchema.optional(),\n overrides: z.record(z.string(), AgentSettingsSchema).optional(),\n })\n .optional(),\n custom: z.array(CustomModelDefinitionSchema).optional(),\n});\n\n/**\n * Complete Athena configuration schema\n */\nexport const AthenaConfigSchema = z.object({\n $schema: z.string().optional(),\n version: z.string(),\n subscriptions: SubscriptionSchema,\n models: ModelsSchema,\n bmad: BmadConfigSchema,\n features: FeaturesSchema,\n mcps: McpsSchema,\n routing: RoutingConfigSchema,\n});\n\n// ============================================================================\n// Tool Argument Schemas\n// ============================================================================\n\n/**\n * Schema for athena_get_story arguments\n */\nexport const GetStoryArgsSchema = z.object({\n storyId: z\n .string()\n .optional()\n .describe(\n \"Specific story ID (e.g., '2.3'). If omitted, loads the next pending story from sprint-status.yaml.\"\n ),\n});\n\nexport const UpdateStatusArgsSchema = z.object({\n storyId: z.string().describe(\"The story ID (e.g., '2.3' or '2-3')\"),\n status: z\n .enum([\"in-progress\", \"review\", \"done\", \"blocked\"])\n .describe(\"The new status for the story (BMAD v6 hyphenated format)\"),\n notes: z\n .string()\n .optional()\n .describe(\"Notes about the status change (required for 'blocked' status)\"),\n completionSummary: z\n .string()\n .optional()\n .describe(\"Summary of what was implemented (required for 'done' status)\"),\n});\n\n/**\n * Schema for athena_get_context arguments\n */\nexport const GetContextArgsSchema = z.object({\n includeArchitecture: z.boolean().optional().default(true),\n includePrd: z.boolean().optional().default(false),\n includeSprintStatus: z.boolean().optional().default(true),\n});\n\n/**\n * Schema for athena_parallel arguments\n */\nexport const ParallelArgsSchema = z.object({\n storyIds: z.array(z.string()).describe(\"Array of story IDs to implement in parallel\"),\n maxConcurrent: z.number().int().min(1).max(5).optional().default(3),\n});\n\n/**\n * Schema for athena_config arguments\n */\nexport const ConfigArgsSchema = z.object({\n action: z.enum([\"get\", \"set\", \"reset\"]).describe(\"Configuration action to perform\"),\n key: z\n .string()\n .optional()\n .describe(\"Configuration key (dot notation, e.g., 'bmad.autoStatusUpdate')\"),\n value: z.unknown().optional().describe(\"Value to set (for 'set' action)\"),\n});\n\n// ============================================================================\n// BMAD v6 Sprint Status Schemas (Flat Map Structure)\n// ============================================================================\n\nexport const BmadStoryStatusEnum = z.enum([\n \"backlog\",\n \"ready-for-dev\",\n \"in-progress\",\n \"review\",\n \"done\",\n \"blocked\",\n]);\n\nexport const BmadEpicStatusEnum = z.enum([\"backlog\", \"in-progress\", \"done\"]);\n\nexport const BmadRetroStatusEnum = z.enum([\"optional\", \"done\"]);\n\nexport const BmadDevelopmentStatusEnum = z.enum([\n \"backlog\",\n \"ready-for-dev\",\n \"in-progress\",\n \"review\",\n \"done\",\n \"blocked\",\n \"optional\",\n]);\n\nexport const BmadSprintStatusSchema = z.object({\n generated: z.string().optional(),\n project: z.string().optional(),\n project_key: z.string().optional(),\n tracking_system: z.string().optional(),\n story_location: z.string().optional(),\n current_story: z.string().nullable().optional(),\n last_modified: z.string().optional(),\n development_status: z.record(z.string(), BmadDevelopmentStatusEnum),\n});\n\nexport const BmadUpdateStatusArgsSchema = z.object({\n storyId: z.string().describe(\"The story ID (e.g., '2.3' or '2-3')\"),\n status: BmadStoryStatusEnum.describe(\"The new status for the story\"),\n notes: z.string().optional().describe(\"Notes about the status change (required for 'blocked')\"),\n completionSummary: z\n .string()\n .optional()\n .describe(\"Summary of implementation (required for 'done')\"),\n});\n\n// ============================================================================\n// Legacy Sprint Status Schema (Deprecated - Array-based)\n// ============================================================================\n\n/** @deprecated Use BmadStoryStatusEnum */\nexport const StoryStatusEnum = z.enum([\n \"pending\",\n \"in_progress\",\n \"completed\",\n \"blocked\",\n \"needs_review\",\n]);\n\n/** @deprecated Use BmadStoryStatusEnum with \"loading\" handled separately */\nexport const TrackerStatusEnum = z.enum([\n \"backlog\",\n \"ready-for-dev\",\n \"in-progress\",\n \"review\",\n \"done\",\n \"blocked\",\n \"loading\",\n]);\n\n/** @deprecated Use BmadSprintStatusSchema */\nexport const SprintStatusSchema = z.object({\n sprint_number: z.number().int().optional(),\n current_epic: z.string().optional(),\n current_story: z.string().nullable().optional(),\n completed_stories: z.array(z.string()).default([]),\n pending_stories: z.array(z.string()).default([]),\n in_progress_stories: z.array(z.string()).default([]),\n blocked_stories: z.array(z.string()).default([]),\n stories_needing_review: z.array(z.string()).optional(),\n story_updates: z\n .record(\n z.object({\n status: StoryStatusEnum,\n updated_at: z.string(),\n notes: z.string().optional(),\n completion_summary: z.string().optional(),\n })\n )\n .optional(),\n last_modified: z.string().optional(),\n});\n\n// ============================================================================\n// Type Exports (inferred from schemas)\n// ============================================================================\n\nexport type SubscriptionConfig = z.infer<typeof SubscriptionSchema>;\nexport type BmadConfig = z.infer<typeof BmadConfigSchema>;\nexport type FeaturesConfig = z.infer<typeof FeaturesSchema>;\nexport type McpsConfig = z.infer<typeof McpsSchema>;\nexport type ModelsConfig = z.infer<typeof ModelsSchema>;\nexport type RoutingConfigValidated = z.infer<typeof RoutingConfigSchema>;\nexport type AthenaConfigValidated = z.infer<typeof AthenaConfigSchema>;\nexport type BmadSprintStatusValidated = z.infer<typeof BmadSprintStatusSchema>;\nexport type BmadStoryStatusValidated = z.infer<typeof BmadStoryStatusEnum>;\nexport type BmadDevelopmentStatusValidated = z.infer<typeof BmadDevelopmentStatusEnum>;\n/** @deprecated Use BmadSprintStatusValidated */\nexport type SprintStatusValidated = z.infer<typeof SprintStatusSchema>;\n","/**\n * Configuration loader for Athena plugin\n *\n * Loads AthenaConfig from project-local or global config files.\n * Project config takes priority over global config.\n * Uses Zod validation for type safety and clear error messages.\n */\n\nimport { existsSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { CONFIG_PATHS, DEFAULTS } from \"../../shared/constants.js\";\nimport { AthenaConfigSchema } from \"../../shared/schemas.js\";\nimport type { AthenaConfig } from \"../../shared/types.js\";\nimport { createPluginLogger } from \"./plugin-logger.js\";\n\nconst log = createPluginLogger(\"config-loader\");\n\n/**\n * Load Athena configuration from available config files.\n *\n * Priority order:\n * 1. Project-local: [projectDir]/.opencode/athena.json\n * 2. Global: ~/.config/opencode/athena.json\n * 3. Default values if no config found\n *\n * @param projectDir - The project directory to search for local config\n * @returns The merged Athena configuration\n */\nexport async function loadAthenaConfig(projectDir: string): Promise<AthenaConfig> {\n // Try project-local config first\n const localConfigPath = join(projectDir, \".opencode\", \"athena.json\");\n const localConfig = await loadConfigFile(localConfigPath);\n\n // Try global config\n const globalConfig = await loadConfigFile(CONFIG_PATHS.globalAthenaConfig);\n\n // Merge configs: local overrides global, both override defaults\n const merged = mergeConfigs(getDefaultConfig(), globalConfig, localConfig);\n\n // Validate the final merged config\n return validateConfig(merged);\n}\n\n/**\n * Load and parse a JSON config file\n */\nasync function loadConfigFile(filePath: string): Promise<Partial<AthenaConfig> | null> {\n if (!existsSync(filePath)) {\n return null;\n }\n\n try {\n const content = await readFile(filePath, \"utf-8\");\n const parsed = JSON.parse(content);\n\n // Perform partial validation to catch obvious errors early\n // We don't require all fields since this is a partial config\n return validatePartialConfig(parsed, filePath);\n } catch (error) {\n if (error instanceof SyntaxError) {\n log.warn(\"Invalid JSON in config file\", { filePath, message: error.message });\n } else {\n log.warn(\"Failed to load config file\", { filePath, error });\n }\n return null;\n }\n}\n\n/**\n * Validate a partial config file and return it with warnings for invalid fields\n */\nfunction validatePartialConfig(config: unknown, filePath: string): Partial<AthenaConfig> | null {\n if (typeof config !== \"object\" || config === null) {\n log.warn(\"Config file must be an object\", { filePath });\n return null;\n }\n\n const result: Partial<AthenaConfig> = {};\n const configObj = config as Record<string, unknown>;\n\n // Validate and copy each top-level field\n if (\"version\" in configObj && typeof configObj.version === \"string\") {\n result.version = configObj.version;\n }\n\n if (\"$schema\" in configObj && typeof configObj.$schema === \"string\") {\n result.$schema = configObj.$schema;\n }\n\n // Validate subscriptions\n if (\"subscriptions\" in configObj && typeof configObj.subscriptions === \"object\") {\n const subs = configObj.subscriptions as Record<string, unknown>;\n result.subscriptions = {} as AthenaConfig[\"subscriptions\"];\n\n if (subs.claude && typeof subs.claude === \"object\") {\n const claude = subs.claude as Record<string, unknown>;\n result.subscriptions.claude = {\n enabled: typeof claude.enabled === \"boolean\" ? claude.enabled : false,\n tier: isValidTier(claude.tier) ? claude.tier : \"none\",\n };\n }\n\n if (subs.openai && typeof subs.openai === \"object\") {\n const openai = subs.openai as Record<string, unknown>;\n result.subscriptions.openai = {\n enabled: typeof openai.enabled === \"boolean\" ? openai.enabled : false,\n };\n }\n\n if (subs.google && typeof subs.google === \"object\") {\n const google = subs.google as Record<string, unknown>;\n result.subscriptions.google = {\n enabled: typeof google.enabled === \"boolean\" ? google.enabled : false,\n authMethod: isValidAuthMethod(google.authMethod) ? google.authMethod : \"none\",\n };\n }\n\n if (subs.githubCopilot && typeof subs.githubCopilot === \"object\") {\n const copilot = subs.githubCopilot as Record<string, unknown>;\n result.subscriptions.githubCopilot = {\n enabled: typeof copilot.enabled === \"boolean\" ? copilot.enabled : false,\n plan: isValidCopilotPlan(copilot.plan) ? copilot.plan : \"none\",\n enabledModels: Array.isArray(copilot.enabledModels)\n ? copilot.enabledModels.filter((m): m is string => typeof m === \"string\")\n : undefined,\n };\n }\n }\n\n // Validate models\n if (\"models\" in configObj && typeof configObj.models === \"object\") {\n const models = configObj.models as Record<string, unknown>;\n result.models = {} as AthenaConfig[\"models\"];\n\n const modelKeys = [\n \"sisyphus\",\n \"oracle\",\n \"librarian\",\n \"frontend\",\n \"documentWriter\",\n \"multimodalLooker\",\n ] as const;\n\n for (const key of modelKeys) {\n if (key in models && typeof models[key] === \"string\") {\n (result.models as unknown as Record<string, string>)[key] = models[key] as string;\n }\n }\n\n if (\"settings\" in models && typeof models.settings === \"object\" && models.settings !== null) {\n result.models.settings = validateModelSettings(models.settings as Record<string, unknown>);\n }\n\n if (\"custom\" in models && Array.isArray(models.custom)) {\n result.models.custom = validateCustomModels(models.custom);\n }\n }\n\n // Validate bmad\n if (\"bmad\" in configObj && typeof configObj.bmad === \"object\") {\n const bmad = configObj.bmad as Record<string, unknown>;\n result.bmad = {} as AthenaConfig[\"bmad\"];\n\n if (isValidTrack(bmad.defaultTrack)) {\n result.bmad.defaultTrack = bmad.defaultTrack;\n }\n if (typeof bmad.autoStatusUpdate === \"boolean\") {\n result.bmad.autoStatusUpdate = bmad.autoStatusUpdate;\n }\n if (typeof bmad.parallelStoryLimit === \"number\") {\n result.bmad.parallelStoryLimit = Math.max(0, Math.min(10, bmad.parallelStoryLimit));\n }\n }\n\n // Validate features\n if (\"features\" in configObj && typeof configObj.features === \"object\") {\n const features = configObj.features as Record<string, unknown>;\n result.features = {} as AthenaConfig[\"features\"];\n\n for (const key of [\n \"bmadBridge\",\n \"autoStatus\",\n \"parallelExecution\",\n \"notifications\",\n \"contextMonitor\",\n \"commentChecker\",\n \"lspTools\",\n ]) {\n if (key in features && typeof features[key] === \"boolean\") {\n (result.features as Record<string, boolean>)[key] = features[key] as boolean;\n }\n }\n }\n\n // Validate mcps\n if (\"mcps\" in configObj && typeof configObj.mcps === \"object\") {\n const mcps = configObj.mcps as Record<string, unknown>;\n result.mcps = {} as AthenaConfig[\"mcps\"];\n\n for (const key of [\"context7\", \"exa\", \"grepApp\"]) {\n if (key in mcps && typeof mcps[key] === \"boolean\") {\n (result.mcps as Record<string, boolean>)[key] = mcps[key] as boolean;\n }\n }\n }\n\n return result;\n}\n\n/**\n * Type guard for valid Claude tier\n */\nfunction isValidTier(value: unknown): value is \"max5x\" | \"max20x\" | \"pro\" | \"none\" {\n return typeof value === \"string\" && [\"max5x\", \"max20x\", \"pro\", \"none\"].includes(value);\n}\n\n/**\n * Type guard for valid Google auth method\n */\nfunction isValidAuthMethod(value: unknown): value is \"antigravity\" | \"personal\" | \"api\" | \"none\" {\n return typeof value === \"string\" && [\"antigravity\", \"personal\", \"api\", \"none\"].includes(value);\n}\n\n/**\n * Type guard for valid GitHub Copilot plan\n */\nfunction isValidCopilotPlan(\n value: unknown\n): value is \"free\" | \"pro\" | \"pro-plus\" | \"business\" | \"enterprise\" | \"none\" {\n return (\n typeof value === \"string\" &&\n [\"free\", \"pro\", \"pro-plus\", \"business\", \"enterprise\", \"none\"].includes(value)\n );\n}\n\n/**\n * Type guard for valid BMAD track\n */\nfunction isValidTrack(value: unknown): value is \"quick-flow\" | \"bmad-method\" | \"enterprise\" {\n return typeof value === \"string\" && [\"quick-flow\", \"bmad-method\", \"enterprise\"].includes(value);\n}\n\nfunction isValidThinkingLevel(value: unknown): value is \"off\" | \"low\" | \"medium\" | \"high\" {\n return typeof value === \"string\" && [\"off\", \"low\", \"medium\", \"high\"].includes(value);\n}\n\nfunction isValidProvider(\n value: unknown\n): value is \"anthropic\" | \"openai\" | \"google\" | \"github-copilot\" {\n return (\n typeof value === \"string\" && [\"anthropic\", \"openai\", \"google\", \"github-copilot\"].includes(value)\n );\n}\n\nfunction validateAgentSettings(settings: unknown): AthenaConfig[\"models\"][\"settings\"] {\n if (typeof settings !== \"object\" || settings === null) {\n return undefined;\n }\n\n const result: AthenaConfig[\"models\"][\"settings\"] = {};\n const settingsObj = settings as Record<string, unknown>;\n const agentKeys = [\n \"sisyphus\",\n \"oracle\",\n \"librarian\",\n \"frontend\",\n \"documentWriter\",\n \"multimodalLooker\",\n ] as const;\n\n for (const key of agentKeys) {\n if (key in settingsObj && typeof settingsObj[key] === \"object\" && settingsObj[key] !== null) {\n const agentSetting = settingsObj[key] as Record<string, unknown>;\n const validated: { temperature?: number; thinkingLevel?: \"off\" | \"low\" | \"medium\" | \"high\" } =\n {};\n\n if (\n typeof agentSetting.temperature === \"number\" &&\n agentSetting.temperature >= 0 &&\n agentSetting.temperature <= 2\n ) {\n validated.temperature = agentSetting.temperature;\n }\n\n if (isValidThinkingLevel(agentSetting.thinkingLevel)) {\n validated.thinkingLevel = agentSetting.thinkingLevel;\n }\n\n if (Object.keys(validated).length > 0) {\n result[key] = validated;\n }\n }\n }\n\n if (\n \"overrides\" in settingsObj &&\n typeof settingsObj.overrides === \"object\" &&\n settingsObj.overrides !== null\n ) {\n const overrides = settingsObj.overrides as Record<string, unknown>;\n result.overrides = {};\n\n for (const [modelId, modelSettings] of Object.entries(overrides)) {\n if (typeof modelSettings === \"object\" && modelSettings !== null) {\n const ms = modelSettings as Record<string, unknown>;\n const validated: {\n temperature?: number;\n thinkingLevel?: \"off\" | \"low\" | \"medium\" | \"high\";\n } = {};\n\n if (typeof ms.temperature === \"number\" && ms.temperature >= 0 && ms.temperature <= 2) {\n validated.temperature = ms.temperature;\n }\n\n if (isValidThinkingLevel(ms.thinkingLevel)) {\n validated.thinkingLevel = ms.thinkingLevel;\n }\n\n if (Object.keys(validated).length > 0) {\n result.overrides[modelId] = validated;\n }\n }\n }\n }\n\n return Object.keys(result).length > 0 ? result : undefined;\n}\n\nfunction validateModelSettings(\n settings: Record<string, unknown>\n): AthenaConfig[\"models\"][\"settings\"] {\n return validateAgentSettings(settings);\n}\n\nfunction validateCustomModels(models: unknown[]): AthenaConfig[\"models\"][\"custom\"] {\n const validated: AthenaConfig[\"models\"][\"custom\"] = [];\n\n for (const model of models) {\n if (typeof model !== \"object\" || model === null) continue;\n\n const m = model as Record<string, unknown>;\n if (typeof m.id !== \"string\" || typeof m.name !== \"string\" || !isValidProvider(m.provider)) {\n continue;\n }\n\n const customModel: {\n id: string;\n name: string;\n provider: \"anthropic\" | \"openai\" | \"google\" | \"github-copilot\";\n description?: string;\n capabilities?: { thinking?: boolean; contextWindow?: number; supportsTemperature?: boolean };\n } = {\n id: m.id,\n name: m.name,\n provider: m.provider,\n };\n\n if (typeof m.description === \"string\") {\n customModel.description = m.description;\n }\n\n if (typeof m.capabilities === \"object\" && m.capabilities !== null) {\n const caps = m.capabilities as Record<string, unknown>;\n customModel.capabilities = {};\n\n if (typeof caps.thinking === \"boolean\") {\n customModel.capabilities.thinking = caps.thinking;\n }\n if (typeof caps.contextWindow === \"number\") {\n customModel.capabilities.contextWindow = caps.contextWindow;\n }\n if (typeof caps.supportsTemperature === \"boolean\") {\n customModel.capabilities.supportsTemperature = caps.supportsTemperature;\n }\n }\n\n validated.push(customModel);\n }\n\n return validated.length > 0 ? validated : undefined;\n}\n\n/**\n * Validate the final merged config using Zod schema\n */\nfunction validateConfig(config: AthenaConfig): AthenaConfig {\n const result = AthenaConfigSchema.safeParse(config);\n\n if (!result.success) {\n // Log validation errors but don't fail - use defaults for invalid fields\n log.warn(\"Configuration validation warnings\", {\n errors: result.error.errors.map((e) => ({\n path: e.path.join(\".\"),\n message: e.message,\n })),\n });\n\n // Return the original config since we already have defaults\n // The individual fields will be used even if some are invalid\n return config;\n }\n\n return result.data;\n}\n\n/**\n * Get default configuration values\n */\nfunction getDefaultConfig(): AthenaConfig {\n return {\n version: \"0.0.1\",\n subscriptions: {\n claude: { enabled: false, tier: \"none\" },\n openai: { enabled: false },\n google: { enabled: false, authMethod: \"none\" },\n githubCopilot: { enabled: false, plan: \"none\" },\n },\n models: {\n sisyphus: \"anthropic/claude-sonnet-4\",\n oracle: \"anthropic/claude-sonnet-4\",\n librarian: \"anthropic/claude-sonnet-4\",\n },\n bmad: {\n defaultTrack: DEFAULTS.defaultTrack,\n autoStatusUpdate: DEFAULTS.autoStatusUpdate,\n parallelStoryLimit: DEFAULTS.parallelStoryLimit,\n },\n features: { ...DEFAULTS.features },\n mcps: { ...DEFAULTS.mcps },\n routing: {\n providerPriority: [\"anthropic\", \"openai\", \"google\", \"github-copilot\"],\n modelFamilyPriority: {\n claude: [\"anthropic\", \"github-copilot\"],\n gpt: [\"openai\", \"github-copilot\"],\n gemini: [\"google\", \"github-copilot\"],\n },\n agentOverrides: {\n oracle: {\n requiresThinking: true,\n },\n },\n fallbackBehavior: {\n autoFallback: false,\n retryPeriodMs: 300000,\n notifyOnRateLimit: true,\n },\n },\n };\n}\n\n/**\n * Deep merge multiple config objects\n * Later configs override earlier ones\n */\nfunction mergeConfigs(...configs: (Partial<AthenaConfig> | null)[]): AthenaConfig {\n const result = getDefaultConfig();\n\n for (const config of configs) {\n if (!config) continue;\n\n // Merge top-level primitives\n if (config.version) result.version = config.version;\n\n // Merge subscriptions\n if (config.subscriptions) {\n if (config.subscriptions.claude) {\n result.subscriptions.claude = {\n ...result.subscriptions.claude,\n ...config.subscriptions.claude,\n };\n }\n if (config.subscriptions.openai) {\n result.subscriptions.openai = {\n ...result.subscriptions.openai,\n ...config.subscriptions.openai,\n };\n }\n if (config.subscriptions.google) {\n result.subscriptions.google = {\n ...result.subscriptions.google,\n ...config.subscriptions.google,\n };\n }\n if (config.subscriptions.githubCopilot) {\n result.subscriptions.githubCopilot = {\n ...result.subscriptions.githubCopilot,\n ...config.subscriptions.githubCopilot,\n };\n }\n }\n\n // Merge models\n if (config.models) {\n result.models = { ...result.models, ...config.models };\n }\n\n // Merge bmad settings\n if (config.bmad) {\n result.bmad = { ...result.bmad, ...config.bmad };\n }\n\n // Merge features\n if (config.features) {\n result.features = { ...result.features, ...config.features };\n }\n\n // Merge mcps\n if (config.mcps) {\n result.mcps = { ...result.mcps, ...config.mcps };\n }\n }\n\n return result;\n}\n","/**\n * OpenCode Athena Plugin\n *\n * The main OpenCode plugin that provides BMAD integration tools and hooks.\n */\n\nimport type { Plugin } from \"@opencode-ai/plugin\";\nimport { createCompactionHook, createSessionHooks, createToolHooks } from \"./hooks/index.js\";\nimport { createTools } from \"./tools/index.js\";\nimport { StoryTracker } from \"./tracker/story-tracker.js\";\nimport { loadAthenaConfig } from \"./utils/config-loader.js\";\nimport { createPluginLogger } from \"./utils/plugin-logger.js\";\n\nconst log = createPluginLogger(\"plugin-init\");\n\n/**\n * OpenCode Athena plugin factory.\n *\n * Provides:\n * - Custom tools for BMAD story management\n * - Session hooks for context tracking\n * - Tool execution hooks for status updates\n * - Compaction hooks to preserve BMAD context\n */\nexport const OpenCodeAthena: Plugin = async (ctx) => {\n const { directory } = ctx;\n\n log.info(\"OpenCode Athena plugin loading\", {\n directory,\n timestamp: new Date().toISOString(),\n });\n\n // Load Athena configuration (project-local takes priority over global)\n const config = await loadAthenaConfig(directory);\n\n // Initialize story tracker for session state persistence\n const tracker = new StoryTracker(directory);\n await tracker.initialize();\n\n // Create tools\n const tools = createTools(ctx, tracker, config);\n\n // Create hooks\n const sessionHooks = createSessionHooks(ctx, tracker, config);\n const toolHooks = createToolHooks(ctx, tracker, config);\n const compactionHook = createCompactionHook(tracker, config, directory);\n\n return {\n // Custom tools for BMAD integration\n tool: tools,\n\n // Session event handlers\n event: sessionHooks,\n\n // Tool execution hooks (stubs for now)\n \"tool.execute.before\": toolHooks.before,\n \"tool.execute.after\": toolHooks.after,\n\n // Compaction hook to preserve BMAD context\n \"experimental.session.compacting\": compactionHook,\n };\n};\n\n// Default export for OpenCode plugin loader\nexport default OpenCodeAthena;\n"]}
|