@aman_asmuei/aman-agent 0.41.0 → 0.42.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/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/token-budget.ts","../src/logger.ts","../src/user-model.ts","../src/server/registry.ts","../src/delegate-remote.ts","../src/orchestrator/types.ts","../src/orchestrator/dag.ts","../src/orchestrator/decompose.ts","../src/dev/stack-detector.ts","../src/github/types.ts","../src/github/cli.ts","../src/github/issue-planner.ts","../src/github/pr-manager.ts","../src/github/ci-gate.ts","../src/github/index.ts","../src/dev/context-builder.ts","../src/dev/claude-md-writer.ts","../src/dev/dev-command.ts","../src/index.ts","../src/config.ts","../src/migrate.ts","../src/prompt.ts","../src/user-identity.ts","../src/llm/anthropic.ts","../src/llm/claude-code.ts","../src/llm/copilot.ts","../src/llm/ollama.ts","../src/llm/openai-compat.ts","../src/llm/openai.ts","../src/llm/index.ts","../src/mcp/client.ts","../src/retry.ts","../src/agent.ts","../src/commands.ts","../src/layers/parsers.ts","../src/memory.ts","../src/profile-templates.ts","../src/profiles/orchestrator-profiles.ts","../src/onboarding.ts","../src/showcase-bridge.ts","../src/files.ts","../src/delegate.ts","../src/hooks.ts","../src/personality.ts","../src/postmortem.ts","../src/observation.ts","../src/crystallization.ts","../src/orchestrator/index.ts","../src/orchestrator/state-machine.ts","../src/orchestrator/model-router.ts","../src/orchestrator/audit.ts","../src/orchestrator/scheduler.ts","../src/orchestrator/review-loop.ts","../src/orchestrator/circuit-breaker.ts","../src/orchestrator/checkpoint.ts","../src/orchestrator/cost-tracker.ts","../src/orchestrator/policy.ts","../src/orchestrator/runner.ts","../src/orchestrator/smart-orchestrate.ts","../src/orchestrator/templates/index.ts","../src/project/detector.ts","../src/profiles/auto-install.ts","../src/teams.ts","../src/plans.ts","../src/background.ts","../src/context-manager.ts","../src/memory-extractor.ts","../src/skill-engine.ts","../src/errors.ts","../src/hints.ts","../src/presets.ts","../src/server/serve-command.ts","../src/server/index.ts","../src/server/transport.ts","../src/server/inbox.ts","../package.json","../src/server/tools/info.ts","../src/server/tools/send.ts","../src/server/tools/delegate.ts"],"sourcesContent":["// Rough token estimation: ~1.3 tokens per word for English markdown\nexport function estimateTokens(text: string): number {\n return Math.round(text.split(/\\s+/).filter(Boolean).length * 1.3);\n}\n\n// Priority order for system prompt components (highest to lowest)\nconst PRIORITIES = [\n \"identity\", // core.md — always include\n \"user\", // user.md — user profile, always include\n \"guardrails\", // rules.md — safety critical\n \"workflows\", // flow.md — behavioral\n \"tools\", // kit.md — capabilities\n \"skills\", // skills.md — can be truncated\n];\n\nexport interface PromptComponent {\n name: string;\n content: string;\n tokens: number;\n}\n\nexport function buildBudgetedPrompt(\n components: PromptComponent[],\n maxTokens: number = 8000, // default budget for system prompt\n): { prompt: string; included: string[]; truncated: string[]; totalTokens: number } {\n const included: string[] = [];\n const truncated: string[] = [];\n const parts: string[] = [];\n let totalTokens = 0;\n\n // Sort by priority\n const sorted = [...components].sort((a, b) => {\n const aPri = PRIORITIES.indexOf(a.name);\n const bPri = PRIORITIES.indexOf(b.name);\n return (aPri === -1 ? 99 : aPri) - (bPri === -1 ? 99 : bPri);\n });\n\n for (const comp of sorted) {\n if (totalTokens + comp.tokens <= maxTokens) {\n parts.push(comp.content);\n included.push(comp.name);\n totalTokens += comp.tokens;\n } else {\n // Try to include a truncated version (first 50% of content)\n const halfContent = comp.content.slice(0, Math.floor(comp.content.length / 2));\n const halfTokens = estimateTokens(halfContent);\n if (totalTokens + halfTokens <= maxTokens) {\n parts.push(halfContent + \"\\n\\n[... truncated for context budget ...]\");\n included.push(comp.name + \" (partial)\");\n totalTokens += halfTokens;\n } else {\n truncated.push(comp.name);\n }\n }\n }\n\n return {\n prompt: parts.join(\"\\n\\n---\\n\\n\"),\n included,\n truncated,\n totalTokens,\n };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport os from \"node:os\";\n\nconst LOG_DIR = path.join(os.homedir(), \".aman-agent\");\nexport const LOG_PATH = path.join(LOG_DIR, \"debug.log\");\nconst MAX_LOG_SIZE = 1_048_576; // 1MB\n\ninterface LogEntry {\n timestamp: string;\n level: \"debug\" | \"warn\" | \"error\";\n module: string;\n message: string;\n data?: string;\n}\n\nfunction ensureDir(): void {\n if (!fs.existsSync(LOG_DIR)) {\n fs.mkdirSync(LOG_DIR, { recursive: true });\n }\n}\n\nfunction maybeRotate(): void {\n try {\n if (!fs.existsSync(LOG_PATH)) return;\n const stat = fs.statSync(LOG_PATH);\n if (stat.size >= MAX_LOG_SIZE) {\n const backupPath = LOG_PATH + \".1\";\n if (fs.existsSync(backupPath)) fs.unlinkSync(backupPath);\n fs.renameSync(LOG_PATH, backupPath);\n }\n } catch {\n // Rotation failure is non-critical\n }\n}\n\nfunction write(level: LogEntry[\"level\"], module: string, message: string, data?: unknown): void {\n try {\n ensureDir();\n maybeRotate();\n const entry: LogEntry = {\n timestamp: new Date().toISOString(),\n level,\n module,\n message,\n };\n if (data !== undefined) {\n entry.data = data instanceof Error ? data.message : String(data);\n }\n fs.appendFileSync(LOG_PATH, JSON.stringify(entry) + \"\\n\");\n } catch {\n // Logger must never throw\n }\n}\n\nexport const log = {\n debug: (module: string, message: string, data?: unknown) => write(\"debug\", module, message, data),\n warn: (module: string, message: string, data?: unknown) => write(\"warn\", module, message, data),\n error: (module: string, message: string, data?: unknown) => write(\"error\", module, message, data),\n};\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport os from \"node:os\";\nimport { log } from \"./logger.js\";\n\n// ── Types ──\n\nexport interface SessionSnapshot {\n sessionId: string;\n date: string;\n durationMinutes: number;\n turnCount: number;\n\n dominantSentiment: string;\n avgFrustration: number;\n avgExcitement: number;\n avgConfusion: number;\n avgFatigue: number;\n\n toolCalls: number;\n toolErrors: number;\n blockers: number;\n milestones: number;\n topicShifts: number;\n\n peakEnergy: string;\n primaryMode: string;\n timePeriod: string;\n\n rating?: string;\n hadPostmortem: boolean;\n wellbeingNudges: string[];\n}\n\nexport interface UserProfile {\n trustScore: number;\n trustTrajectory: \"ascending\" | \"stable\" | \"declining\";\n totalSessions: number;\n\n preferredTimePeriod: string;\n energyDistribution: Record<string, number>;\n avgSessionMinutes: number;\n\n baselineFrustration: number;\n baselineExcitement: number;\n sentimentTrend: \"improving\" | \"stable\" | \"worsening\";\n\n frustrationCorrelations: {\n toolErrors: number;\n longSessions: number;\n lateNight: number;\n };\n\n avgTurnsPerSession: number;\n engagementTrend: \"increasing\" | \"stable\" | \"decreasing\";\n\n nudgeStats: Record<string, { fired: number; sessionRatingAfter: number }>;\n}\n\nexport interface UserModel {\n version: 1;\n sessions: SessionSnapshot[];\n profile: UserProfile;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface PersonalityOverrides {\n energyOverride?: string;\n compactGreeting: boolean;\n frustrationNudgeThreshold: number;\n defaultToPersonalMode: boolean;\n}\n\n// ── Constants ──\n\nconst MAX_SESSIONS = 30;\nconst TRUST_ALPHA = 0.3;\nconst MIN_SESSIONS_FOR_FEED_FORWARD = 5;\nconst MIN_SESSIONS_FOR_CORRELATIONS = 10;\n\n// ── Default model path ──\n\nexport function defaultModelPath(): string {\n return path.join(os.homedir(), \".acore\", \"user-model.json\");\n}\n\n// ── Factory ──\n\nexport function createEmptyModel(): UserModel {\n const now = new Date().toISOString();\n return {\n version: 1,\n sessions: [],\n profile: emptyProfile(),\n createdAt: now,\n updatedAt: now,\n };\n}\n\nfunction emptyProfile(): UserProfile {\n return {\n trustScore: 0.5,\n trustTrajectory: \"stable\",\n totalSessions: 0,\n preferredTimePeriod: \"afternoon\",\n energyDistribution: {},\n avgSessionMinutes: 0,\n baselineFrustration: 0,\n baselineExcitement: 0,\n sentimentTrend: \"stable\",\n frustrationCorrelations: { toolErrors: 0, longSessions: 0, lateNight: 0 },\n avgTurnsPerSession: 0,\n engagementTrend: \"stable\",\n nudgeStats: {},\n };\n}\n\n// ── I/O ──\n\nexport async function loadUserModel(filePath?: string): Promise<UserModel | null> {\n const fp = filePath ?? defaultModelPath();\n try {\n const raw = await fs.readFile(fp, \"utf-8\");\n const parsed = JSON.parse(raw);\n if (parsed?.version !== 1) return null;\n return parsed as UserModel;\n } catch {\n return null;\n }\n}\n\nexport async function saveUserModel(model: UserModel, filePath?: string): Promise<void> {\n const fp = filePath ?? defaultModelPath();\n const dir = path.dirname(fp);\n await fs.mkdir(dir, { recursive: true });\n\n const tmp = fp + `.tmp-${Date.now()}`;\n await fs.writeFile(tmp, JSON.stringify(model, null, 2), \"utf-8\");\n await fs.rename(tmp, fp);\n}\n\n// ── Aggregation ──\n\nexport function aggregateSession(model: UserModel, snapshot: SessionSnapshot): UserModel {\n const sessions = [...model.sessions, snapshot];\n\n // Enforce rolling window\n while (sessions.length > MAX_SESSIONS) {\n sessions.shift();\n }\n\n const totalSessions = model.profile.totalSessions + 1;\n const profile = computeProfile(sessions, totalSessions);\n\n return {\n ...model,\n sessions,\n profile,\n updatedAt: new Date().toISOString(),\n };\n}\n\n// ── Profile Computation ──\n\nexport function computeProfile(sessions: SessionSnapshot[], totalSessions: number): UserProfile {\n if (sessions.length === 0) return { ...emptyProfile(), totalSessions };\n\n const n = sessions.length;\n\n // ── Trust Score (EMA) ──\n let trustScore = 0.5;\n for (const s of sessions) {\n trustScore = TRUST_ALPHA * ratingSignal(s) + (1 - TRUST_ALPHA) * trustScore;\n }\n\n // Trust trajectory: compare last 5 vs previous 5\n const trustTrajectory = computeTrustTrajectory(sessions);\n\n // ── Sentiment Baselines ──\n const baselineFrustration = avg(sessions.map((s) => s.avgFrustration));\n const baselineExcitement = avg(sessions.map((s) => s.avgExcitement));\n const sentimentTrend = computeSentimentTrend(sessions);\n\n // ── Energy Distribution ──\n const energyDistribution: Record<string, number> = {};\n for (const s of sessions) {\n energyDistribution[s.timePeriod] = (energyDistribution[s.timePeriod] || 0) + 1;\n }\n const preferredTimePeriod = Object.entries(energyDistribution).sort(\n (a, b) => b[1] - a[1],\n )[0]?.[0] ?? \"afternoon\";\n\n // ── Session Duration ──\n const avgSessionMinutes = avg(sessions.map((s) => s.durationMinutes));\n\n // ── Engagement ──\n const avgTurnsPerSession = avg(sessions.map((s) => s.turnCount));\n const engagementTrend = computeLinearTrend(sessions.map((s) => s.turnCount));\n\n // ── Frustration Correlations ──\n const frustrationCorrelations =\n n >= MIN_SESSIONS_FOR_CORRELATIONS\n ? {\n toolErrors: pearsonR(\n sessions.map((s) => s.avgFrustration),\n sessions.map((s) => s.toolErrors),\n ),\n longSessions: pearsonR(\n sessions.map((s) => s.avgFrustration),\n sessions.map((s) => s.durationMinutes),\n ),\n lateNight: pearsonR(\n sessions.map((s) => s.avgFrustration),\n sessions.map((s) => (s.timePeriod === \"late-night\" || s.timePeriod === \"night\" ? 1 : 0)),\n ),\n }\n : { toolErrors: 0, longSessions: 0, lateNight: 0 };\n\n // ── Nudge Stats ──\n const nudgeStats: Record<string, { fired: number; sessionRatingAfter: number }> = {};\n for (const s of sessions) {\n const ratingVal = ratingToNumber(s.rating);\n for (const nudge of s.wellbeingNudges) {\n if (!nudgeStats[nudge]) nudgeStats[nudge] = { fired: 0, sessionRatingAfter: 0 };\n nudgeStats[nudge].fired++;\n nudgeStats[nudge].sessionRatingAfter += ratingVal;\n }\n }\n for (const key of Object.keys(nudgeStats)) {\n if (nudgeStats[key].fired > 0) {\n nudgeStats[key].sessionRatingAfter /= nudgeStats[key].fired;\n }\n }\n\n return {\n trustScore,\n trustTrajectory,\n totalSessions,\n preferredTimePeriod,\n energyDistribution,\n avgSessionMinutes,\n baselineFrustration,\n baselineExcitement,\n sentimentTrend,\n frustrationCorrelations,\n avgTurnsPerSession,\n engagementTrend,\n nudgeStats,\n };\n}\n\n// ── Feed-Forward ──\n\nexport function feedForward(model: UserModel): PersonalityOverrides | null {\n if (model.profile.totalSessions < MIN_SESSIONS_FOR_FEED_FORWARD) return null;\n\n const p = model.profile;\n const overrides: PersonalityOverrides = {\n compactGreeting: false,\n frustrationNudgeThreshold: 0.6,\n defaultToPersonalMode: false,\n };\n\n // Night owl calibration: if 70%+ sessions are late-night/night with low frustration,\n // don't default to \"reflective\" — use \"steady\"\n const nightSessions =\n (p.energyDistribution[\"late-night\"] || 0) + (p.energyDistribution[\"night\"] || 0);\n const totalInWindow = model.sessions.length;\n if (totalInWindow > 0 && nightSessions / totalInWindow >= 0.7 && p.baselineFrustration < 0.3) {\n overrides.energyOverride = \"steady\";\n }\n\n // High trust → compact greeting\n if (p.trustScore > 0.8) {\n overrides.compactGreeting = true;\n }\n\n // Tool error frustration correlation → lower nudge threshold\n if (p.frustrationCorrelations.toolErrors > 0.4) {\n overrides.frustrationNudgeThreshold = 0.4;\n }\n\n // Worsening sentiment → default to Personal mode more readily\n if (p.sentimentTrend === \"worsening\") {\n overrides.defaultToPersonalMode = true;\n }\n\n return overrides;\n}\n\n// ── Burnout Predictor ──\n\nexport interface BurnoutPrediction {\n risk: number; // 0-1\n factors: string[];\n recommendation?: string;\n}\n\n/**\n * Predict burnout risk from session patterns.\n * Looks at recent 7 sessions for:\n * - Rising frustration trend\n * - Declining session ratings\n * - Long sessions without breaks\n * - Late-night clustering\n * - High blocker frequency\n */\nexport function predictBurnout(\n sessions: SessionSnapshot[],\n currentSession?: { minutes: number; frustration: number; timePeriod: string },\n): BurnoutPrediction {\n const recent = sessions.slice(-7);\n if (recent.length < 3) {\n return { risk: 0, factors: [] };\n }\n\n const factors: string[] = [];\n let risk = 0;\n\n // Factor 1: Rising frustration (compare first half vs second half)\n const mid = Math.floor(recent.length / 2);\n const firstHalf = recent.slice(0, mid);\n const secondHalf = recent.slice(mid);\n const avgFrustFirst = avg(firstHalf.map((s) => s.avgFrustration));\n const avgFrustSecond = avg(secondHalf.map((s) => s.avgFrustration));\n if (avgFrustSecond > avgFrustFirst + 0.1 && avgFrustSecond > 0.4) {\n risk += 0.25;\n factors.push(\"rising frustration trend\");\n }\n\n // Factor 2: Declining ratings\n const ratings = recent.filter((s) => s.rating).map((s) => ratingSignal(s));\n if (ratings.length >= 3) {\n const lastThree = ratings.slice(-3);\n const avgLast3 = avg(lastThree);\n if (avgLast3 < 0.5) {\n risk += 0.2;\n factors.push(\"low recent ratings\");\n }\n }\n\n // Factor 3: Long sessions (avg > 90 min)\n const avgMins = avg(recent.map((s) => s.durationMinutes));\n if (avgMins > 90) {\n risk += 0.15;\n factors.push(\"consistently long sessions\");\n }\n\n // Factor 4: Late-night clustering\n const lateNightCount = recent.filter((s) => s.timePeriod === \"late-night\" || s.timePeriod === \"night\").length;\n if (lateNightCount / recent.length > 0.5) {\n risk += 0.15;\n factors.push(\"frequent late-night sessions\");\n }\n\n // Factor 5: High blocker frequency\n const avgBlockers = avg(recent.map((s) => s.blockers));\n if (avgBlockers > 1) {\n risk += 0.15;\n factors.push(\"frequent blockers\");\n }\n\n // Current session amplifier\n if (currentSession) {\n if (currentSession.minutes > 120 && currentSession.frustration > 0.5) {\n risk += 0.1;\n factors.push(\"current session: long + frustrated\");\n }\n }\n\n risk = clamp(risk, 0, 1);\n\n let recommendation: string | undefined;\n if (risk > 0.7) {\n recommendation = \"Consider taking a longer break. You've been pushing hard — rest is productive too.\";\n } else if (risk > 0.5) {\n recommendation = \"Watch for signs of fatigue. A change of pace or shorter sessions might help.\";\n }\n\n return { risk, factors, recommendation };\n}\n\n// ── Math Utilities ──\n\nfunction clamp(val: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, val));\n}\n\nfunction avg(values: number[]): number {\n if (values.length === 0) return 0;\n return values.reduce((sum, v) => sum + v, 0) / values.length;\n}\n\nfunction ratingSignal(session: SessionSnapshot): number {\n if (session.rating === \"great\") return 1.0;\n if (session.rating === \"good\") return 0.75;\n if (session.rating === \"okay\") return 0.5;\n if (session.rating === \"frustrating\") return 0.25;\n\n // No explicit rating — infer from signals\n let implicit = 1.0;\n implicit -= session.avgFrustration * 0.4;\n implicit -= session.toolErrors > 3 ? 0.2 : 0;\n implicit -= session.blockers > 2 ? 0.2 : 0;\n implicit += session.milestones > 0 ? 0.1 : 0;\n return clamp(implicit, 0, 1);\n}\n\nfunction ratingToNumber(rating?: string): number {\n if (rating === \"great\") return 1.0;\n if (rating === \"good\") return 0.75;\n if (rating === \"okay\") return 0.5;\n if (rating === \"frustrating\") return 0.25;\n return 0.5;\n}\n\nfunction pearsonR(x: number[], y: number[]): number {\n const n = x.length;\n if (n < 3) return 0;\n\n const mx = avg(x);\n const my = avg(y);\n\n let num = 0;\n let dx2 = 0;\n let dy2 = 0;\n\n for (let i = 0; i < n; i++) {\n const dx = x[i] - mx;\n const dy = y[i] - my;\n num += dx * dy;\n dx2 += dx * dx;\n dy2 += dy * dy;\n }\n\n const denom = Math.sqrt(dx2 * dy2);\n if (denom === 0) return 0;\n return num / denom;\n}\n\nfunction computeTrustTrajectory(\n sessions: SessionSnapshot[],\n): \"ascending\" | \"stable\" | \"declining\" {\n if (sessions.length < 10) return \"stable\";\n\n const recent5 = sessions.slice(-5).map(ratingSignal);\n const prev5 = sessions.slice(-10, -5).map(ratingSignal);\n\n const recentAvg = avg(recent5);\n const prevAvg = avg(prev5);\n const delta = recentAvg - prevAvg;\n\n if (delta > 0.1) return \"ascending\";\n if (delta < -0.1) return \"declining\";\n return \"stable\";\n}\n\nfunction computeSentimentTrend(sessions: SessionSnapshot[]): \"improving\" | \"stable\" | \"worsening\" {\n if (sessions.length < 5) return \"stable\";\n\n const frustrations = sessions.slice(-10).map((s) => s.avgFrustration);\n const slope = linearSlope(frustrations);\n\n if (slope > 0.02) return \"worsening\"; // frustration increasing = worsening\n if (slope < -0.02) return \"improving\"; // frustration decreasing = improving\n return \"stable\";\n}\n\nfunction computeLinearTrend(values: number[]): \"increasing\" | \"stable\" | \"decreasing\" {\n if (values.length < 5) return \"stable\";\n\n const recent = values.slice(-10);\n const slope = linearSlope(recent);\n\n // Normalize slope relative to mean to detect meaningful changes\n const mean = avg(recent);\n const relativeSlope = mean > 0 ? slope / mean : slope;\n\n if (relativeSlope > 0.03) return \"increasing\";\n if (relativeSlope < -0.03) return \"decreasing\";\n return \"stable\";\n}\n\nfunction linearSlope(values: number[]): number {\n const n = values.length;\n if (n < 2) return 0;\n\n let sumX = 0;\n let sumY = 0;\n let sumXY = 0;\n let sumX2 = 0;\n\n for (let i = 0; i < n; i++) {\n sumX += i;\n sumY += values[i];\n sumXY += i * values[i];\n sumX2 += i * i;\n }\n\n const denom = n * sumX2 - sumX * sumX;\n if (denom === 0) return 0;\n return (n * sumXY - sumX * sumY) / denom;\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport os from \"node:os\";\nimport { log } from \"../logger.js\";\n\nexport interface AgentEntry {\n name: string; // unique handle, used as @name\n profile: string; // aman-agent profile this server loaded\n pid: number; // process id for liveness check\n port: number; // 127.0.0.1 port\n token: string; // 32-byte hex bearer\n started_at: number; // epoch ms\n version: string; // package version\n}\n\nexport interface ListOptions {\n prune?: boolean; // write the pruned registry back\n isAlive?: (pid: number) => boolean; // injectable for tests\n}\n\nfunction amanAgentHome(): string {\n return process.env.AMAN_AGENT_HOME || path.join(os.homedir(), \".aman-agent\");\n}\n\nfunction registryPath(): string {\n return path.join(amanAgentHome(), \"registry.json\");\n}\n\nasync function ensureHome(): Promise<void> {\n await fs.mkdir(amanAgentHome(), { recursive: true });\n}\n\nasync function readRaw(): Promise<AgentEntry[]> {\n try {\n const buf = await fs.readFile(registryPath(), \"utf-8\");\n const parsed = JSON.parse(buf);\n return Array.isArray(parsed) ? parsed : [];\n } catch (err: unknown) {\n const code = (err as { code?: string }).code;\n if (code === \"ENOENT\") return [];\n const message = err instanceof Error ? err.message : String(err);\n log.warn(\"registry\", `failed to read registry: ${message}`);\n return [];\n }\n}\n\nasync function writeAtomic(entries: AgentEntry[]): Promise<void> {\n await ensureHome();\n const tmp = registryPath() + \".tmp\";\n await fs.writeFile(tmp, JSON.stringify(entries, null, 2), { mode: 0o600 });\n await fs.rename(tmp, registryPath());\n // Ensure mode even if file already existed (chmod is idempotent).\n try {\n await fs.chmod(registryPath(), 0o600);\n } catch {\n // best effort\n }\n}\n\nfunction defaultIsAlive(pid: number): boolean {\n try {\n // Signal 0 probes existence without sending anything.\n process.kill(pid, 0);\n return true;\n } catch {\n return false;\n }\n}\n\nexport async function registerAgent(entry: AgentEntry): Promise<void> {\n const current = await readRaw();\n const filtered = current.filter((e) => e.name !== entry.name);\n if (filtered.length !== current.length) {\n log.warn(\"registry\", `replacing existing entry for name=\"${entry.name}\"`);\n }\n filtered.push(entry);\n await writeAtomic(filtered);\n}\n\nexport async function unregisterAgent(name: string): Promise<void> {\n const current = await readRaw();\n const next = current.filter((e) => e.name !== name);\n if (next.length !== current.length) {\n await writeAtomic(next);\n }\n}\n\nexport async function listAgents(opts: ListOptions = {}): Promise<AgentEntry[]> {\n const isAlive = opts.isAlive ?? defaultIsAlive;\n const raw = await readRaw();\n const alive = raw.filter((e) => isAlive(e.pid));\n if (opts.prune && alive.length !== raw.length) {\n await writeAtomic(alive);\n }\n return alive;\n}\n\nexport async function findAgent(name: string): Promise<AgentEntry | null> {\n const all = await listAgents();\n return all.find((e) => e.name === name) ?? null;\n}\n","import { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { StreamableHTTPClientTransport } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport { findAgent } from \"./server/registry.js\";\nimport type { DelegationResult } from \"./delegate.js\";\nimport { log } from \"./logger.js\";\n\nexport interface RemoteDelegateOptions {\n context?: string;\n timeoutMs?: number;\n}\n\nconst DEFAULT_TIMEOUT_MS = 120_000;\n\n/**\n * Dial another aman-agent running as an A2A server on the same machine\n * and run a task through its `agent.delegate` MCP tool. Returns a\n * DelegationResult matching the shape of the local `delegateTask` so\n * callers can treat local and remote delegation uniformly.\n *\n * Trust model: same user, same machine — bearer comes from the local\n * registry file (mode 0600). See plan docs for the broader discussion.\n */\nexport async function delegateRemote(\n task: string,\n agentName: string,\n options: RemoteDelegateOptions = {},\n): Promise<DelegationResult> {\n const entry = await findAgent(agentName);\n if (!entry) {\n return {\n profile: `@${agentName}`,\n task,\n response: \"\",\n toolsUsed: [],\n turns: 0,\n success: false,\n error: `agent not found: ${agentName}`,\n };\n }\n\n const url = new URL(`http://127.0.0.1:${entry.port}/mcp`);\n const transport = new StreamableHTTPClientTransport(url, {\n requestInit: {\n headers: { Authorization: `Bearer ${entry.token}` },\n },\n // Disable SSE reconnection scheduling. On close(), the SDK aborts\n // the controller; without this override, the SSE stream's error\n // handler races to schedule a new _reconnectionTimeout AFTER close()\n // cleared the old one, and the timer (plus its referenced socket)\n // pins Node's event loop until the undici keepalive times out. A\n // delegateRemote caller then can't exit cleanly. maxRetries: 0\n // drops the schedule-on-error path entirely; we're doing a single\n // RPC, not a persistent stream, so reconnection has no value here.\n reconnectionOptions: {\n maxRetries: 0,\n initialReconnectionDelay: 1,\n maxReconnectionDelay: 1,\n reconnectionDelayGrowFactor: 1,\n },\n });\n const client = new Client({ name: \"aman-agent-a2a-caller\", version: \"0.1.0\" });\n\n try {\n await client.connect(transport);\n\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const call = client.callTool({\n name: \"agent.delegate\",\n arguments: {\n task,\n ...(options.context ? { context: options.context } : {}),\n },\n });\n\n // Promise.race picks a winner but does NOT cancel the losing promise's\n // resources. Capturing the timer id lets us clear it after the call\n // resolves — otherwise the setTimeout keeps a Timeout handle alive for\n // the full timeoutMs (120 s default) and pins Node's event loop long\n // after the caller thinks the RPC is done. Equivalent effect to using\n // AbortSignal.timeout() but keeps the existing error message.\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<never>((_, rej) => {\n timeoutId = setTimeout(\n () => rej(new Error(`remote delegate timed out after ${timeoutMs}ms`)),\n timeoutMs,\n );\n });\n let result;\n try {\n result = await Promise.race([call, timeout]);\n } finally {\n if (timeoutId !== undefined) clearTimeout(timeoutId);\n }\n\n const text = Array.isArray(result.content)\n ? (result.content as Array<{ type: string; text?: string }>)\n .filter((c) => c.type === \"text\")\n .map((c) => c.text ?? \"\")\n .join(\"\")\n : \"\";\n\n // MCP tool-level errors arrive as { isError: true, content: [{text: \"...\"}] }.\n // Surface them distinctly from JSON.parse failures and from empty responses.\n if ((result as { isError?: boolean }).isError) {\n return {\n profile: `@${agentName}`,\n task,\n response: \"\",\n toolsUsed: [],\n turns: 0,\n success: false,\n error: `remote tool error: ${text || \"(no details)\"}`,\n };\n }\n\n const parsed = text ? JSON.parse(text) : { ok: false, error: \"empty response\" };\n\n log.debug(\"delegate-remote\", `@${agentName} ok=${parsed.ok}`);\n\n if (!parsed.ok) {\n return {\n profile: `@${agentName}`,\n task,\n response: \"\",\n toolsUsed: [],\n turns: 0,\n success: false,\n error: parsed.error ?? \"unknown remote error\",\n };\n }\n\n return {\n profile: `@${agentName}`,\n task,\n response: parsed.text ?? \"\",\n toolsUsed: parsed.tools_used ?? [],\n turns: parsed.turns ?? 0,\n success: true,\n };\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n const lower = msg.toLowerCase();\n const normalized =\n lower.includes(\"401\") || lower.includes(\"unauthor\")\n ? `unauthorized: ${msg}`\n : msg;\n return {\n profile: `@${agentName}`,\n task,\n response: \"\",\n toolsUsed: [],\n turns: 0,\n success: false,\n error: normalized,\n };\n } finally {\n // Teardown order matters:\n // 1. terminateSession() sends an MCP DELETE to drop the server-side\n // session. This needs the transport's abort controller to still\n // be alive, so it MUST run BEFORE client.close() (which aborts\n // the controller). Earlier order threw DOMException[AbortError].\n // 2. client.close() then releases SDK-side state and aborts the\n // transport. Combined with reconnectionOptions: { maxRetries: 0 }\n // on construction, this leaves zero handles pinning the event\n // loop — verified via process.getActiveResourcesInfo() === [].\n // 3. transport.close() is a no-op after client.close() (which\n // transitively closes the transport) but kept for symmetry.\n // All three are best-effort: any throw here is swallowed so a\n // teardown failure never masks a real result from the caller.\n try { await transport.terminateSession(); } catch { /* best effort */ }\n try { await client.close(); } catch { /* best effort */ }\n try { await transport.close(); } catch { /* best effort */ }\n }\n}\n","import { z } from \"zod\";\n\n// ── Model Tiers ──────────────────────────────────────────────────────\nexport const ModelTierEnum = z.enum([\"fast\", \"standard\", \"advanced\"]);\nexport type ModelTier = z.infer<typeof ModelTierEnum>;\n\n// ── TaskNode — a single unit of work in the DAG ─────────────────────\nexport const TaskNodeSchema = z.object({\n id: z.string().min(1),\n name: z.string().min(1),\n description: z.string().optional(),\n profile: z.string().min(1),\n tier: ModelTierEnum,\n dependencies: z.array(z.string()).default([]),\n phase: z.string().optional(),\n context: z.string().optional(),\n metadata: z.record(z.unknown()).optional(),\n});\nexport type TaskNode = z.infer<typeof TaskNodeSchema>;\n\n// ── PhaseGate — a gate between phases ────────────────────────────────\nexport const PhaseGateTypeEnum = z.enum([\n \"approval\",\n \"ci_pass\",\n \"test_pass\",\n \"custom\",\n]);\nexport type PhaseGateType = z.infer<typeof PhaseGateTypeEnum>;\n\nexport const PhaseGateSchema = z.object({\n id: z.string().min(1),\n name: z.string().min(1),\n type: PhaseGateTypeEnum,\n afterNodes: z.array(z.string()),\n beforeNodes: z.array(z.string()),\n metadata: z.record(z.unknown()).optional(),\n});\nexport type PhaseGate = z.infer<typeof PhaseGateSchema>;\n\n// ── TaskDAG — the complete directed acyclic graph ────────────────────\nexport const TaskDAGSchema = z.object({\n id: z.string().min(1),\n name: z.string().min(1),\n goal: z.string().min(1),\n nodes: z.array(TaskNodeSchema).min(1),\n gates: z.array(PhaseGateSchema).default([]),\n metadata: z.record(z.unknown()).optional(),\n});\nexport type TaskDAG = z.infer<typeof TaskDAGSchema>;\n\n// ── OrchestrationStatus ──────────────────────────────────────────────\nexport const OrchestrationStatusEnum = z.enum([\n \"pending\",\n \"running\",\n \"awaiting_approval\",\n \"approved\",\n \"paused\",\n \"completed\",\n \"failed\",\n \"cancelled\",\n]);\nexport type OrchestrationStatus = z.infer<typeof OrchestrationStatusEnum>;\n\n// ── TaskStatus ───────────────────────────────────────────────────────\nexport const TaskStatusEnum = z.enum([\n \"pending\",\n \"ready\",\n \"running\",\n \"completed\",\n \"failed\",\n \"skipped\",\n \"blocked\",\n]);\nexport type TaskStatus = z.infer<typeof TaskStatusEnum>;\n\n// ── TaskResult (plain TS — no Zod) ──────────────────────────────────\nexport interface TaskResult {\n nodeId: string;\n status: TaskStatus;\n output?: string;\n error?: string;\n toolsUsed: string[];\n turns: number;\n startedAt: number;\n completedAt?: number;\n tier: ModelTier;\n}\n\n// ── OrchestrationState (plain TS — uses Maps) ───────────────────────\nexport interface OrchestrationState {\n dag: TaskDAG;\n status: OrchestrationStatus;\n taskStatuses: Map<string, TaskStatus>;\n taskResults: Map<string, TaskResult>;\n activeGate: string | null;\n startedAt: number;\n updatedAt: number;\n completedAt?: number;\n error?: string;\n}\n\n// ── OrchestrationConfig ──────────────────────────────────────────────\nexport const OrchestrationConfigSchema = z.object({\n maxParallelTasks: z.number().int().positive().default(4),\n defaultTier: ModelTierEnum.default(\"standard\"),\n requireApprovalForPhaseTransition: z.boolean().default(true),\n taskTimeoutMs: z.number().int().positive().default(300_000),\n orchestrationTimeoutMs: z.number().int().positive().default(3_600_000),\n});\nexport type OrchestrationConfig = z.infer<typeof OrchestrationConfigSchema>;\n","import type { TaskDAG, TaskStatus } from \"./types.js\";\n\n// ── Error ───────────────────────────────────────────────────────────\n\nexport class DAGValidationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"DAGValidationError\";\n }\n}\n\n// ── Validation ──────────────────────────────────────────────────────\n\nexport function validateDAG(dag: TaskDAG): void {\n const nodeIds = new Set<string>();\n\n // Check for duplicate ids\n for (const node of dag.nodes) {\n if (nodeIds.has(node.id)) {\n throw new DAGValidationError(`Duplicate node id: \"${node.id}\"`);\n }\n nodeIds.add(node.id);\n }\n\n // Check that all dependencies reference existing nodes\n for (const node of dag.nodes) {\n for (const dep of node.dependencies) {\n if (!nodeIds.has(dep)) {\n throw new DAGValidationError(\n `Node \"${node.id}\" depends on nonexistent node \"${dep}\"`,\n );\n }\n }\n }\n\n // Validate gate references\n for (const gate of dag.gates) {\n for (const id of gate.afterNodes) {\n if (!nodeIds.has(id)) {\n throw new DAGValidationError(\n `Gate \"${gate.id}\" references nonexistent afterNode \"${id}\"`,\n );\n }\n }\n for (const id of gate.beforeNodes) {\n if (!nodeIds.has(id)) {\n throw new DAGValidationError(\n `Gate \"${gate.id}\" references nonexistent beforeNode \"${id}\"`,\n );\n }\n }\n }\n\n // Cycle detection via Kahn's algorithm\n const inDegree = new Map<string, number>();\n const adj = new Map<string, string[]>();\n\n for (const node of dag.nodes) {\n inDegree.set(node.id, 0);\n adj.set(node.id, []);\n }\n\n for (const node of dag.nodes) {\n for (const dep of node.dependencies) {\n adj.get(dep)!.push(node.id);\n inDegree.set(node.id, inDegree.get(node.id)! + 1);\n }\n }\n\n const queue: string[] = [];\n for (const [id, deg] of inDegree) {\n if (deg === 0) queue.push(id);\n }\n\n let visited = 0;\n while (queue.length > 0) {\n const current = queue.shift()!;\n visited++;\n for (const neighbor of adj.get(current)!) {\n const newDeg = inDegree.get(neighbor)! - 1;\n inDegree.set(neighbor, newDeg);\n if (newDeg === 0) queue.push(neighbor);\n }\n }\n\n if (visited !== dag.nodes.length) {\n throw new DAGValidationError(\n \"DAG contains a cycle — not all nodes were reachable via topological ordering\",\n );\n }\n}\n\n// ── Topological Sort (Kahn's) ───────────────────────────────────────\n\nexport function topologicalSort(dag: TaskDAG): string[] {\n const inDegree = new Map<string, number>();\n const adj = new Map<string, string[]>();\n\n for (const node of dag.nodes) {\n inDegree.set(node.id, 0);\n adj.set(node.id, []);\n }\n\n for (const node of dag.nodes) {\n for (const dep of node.dependencies) {\n adj.get(dep)!.push(node.id);\n inDegree.set(node.id, inDegree.get(node.id)! + 1);\n }\n }\n\n const queue: string[] = [];\n for (const [id, deg] of inDegree) {\n if (deg === 0) queue.push(id);\n }\n\n const result: string[] = [];\n while (queue.length > 0) {\n const current = queue.shift()!;\n result.push(current);\n for (const neighbor of adj.get(current)!) {\n const newDeg = inDegree.get(neighbor)! - 1;\n inDegree.set(neighbor, newDeg);\n if (newDeg === 0) queue.push(neighbor);\n }\n }\n\n return result;\n}\n\n// ── Ready-Node Resolution ───────────────────────────────────────────\n\nexport function getReadyNodes(\n dag: TaskDAG,\n taskStatuses: Map<string, TaskStatus>,\n resolvedGates?: Set<string>,\n): string[] {\n // Build set of nodes blocked by unresolved gates\n const gateBlocked = new Set<string>();\n for (const gate of dag.gates) {\n if (resolvedGates?.has(gate.id)) continue;\n // If all afterNodes are completed, the gate is active but unresolved => block beforeNodes\n const allAfterDone = gate.afterNodes.every(\n (id) => taskStatuses.get(id) === \"completed\",\n );\n if (allAfterDone) {\n for (const id of gate.beforeNodes) {\n gateBlocked.add(id);\n }\n }\n }\n\n const ready: string[] = [];\n\n for (const node of dag.nodes) {\n if (taskStatuses.get(node.id) !== \"pending\") continue;\n if (gateBlocked.has(node.id)) continue;\n\n const allDepsCompleted = node.dependencies.every(\n (dep) => taskStatuses.get(dep) === \"completed\",\n );\n if (allDepsCompleted) {\n ready.push(node.id);\n }\n }\n\n return ready;\n}\n\n// ── Dependents ──────────────────────────────────────────────────────\n\nexport function getDependents(dag: TaskDAG, nodeId: string): string[] {\n return dag.nodes\n .filter((n) => n.dependencies.includes(nodeId))\n .map((n) => n.id);\n}\n","import { TaskDAGSchema, type TaskDAG } from \"./types.js\";\nimport { validateDAG } from \"./dag.js\";\nimport type { LLMClient } from \"../llm/types.js\";\n\n// ── System prompt for decomposition ────────────────────────────────\n\nexport const DECOMPOSITION_SYSTEM_PROMPT = `You are a software project decomposer. Given a requirement, break it into a task DAG for parallel agent execution.\n\nReturn ONLY valid JSON matching this schema:\n{\n \"id\": \"orch-<short-id>\",\n \"name\": \"<short name>\",\n \"goal\": \"<one-line goal>\",\n \"nodes\": [\n {\n \"id\": \"<unique-id>\",\n \"name\": \"<task name>\",\n \"description\": \"<what to do>\",\n \"profile\": \"<architect|coder|tester|reviewer|security>\",\n \"tier\": \"<fast|standard|advanced>\",\n \"dependencies\": [\"<prerequisite task ids>\"]\n }\n ],\n \"gates\": [\n {\n \"id\": \"<gate-id>\",\n \"name\": \"<gate description>\",\n \"type\": \"approval\",\n \"afterNodes\": [\"<completed before gate>\"],\n \"beforeNodes\": [\"<blocked until gate resolves>\"]\n }\n ]\n}\n\nRules:\n- architect profile = tier advanced\n- coder/tester/reviewer = tier standard\n- Maximize parallelism\n- Add approval gate before destructive actions\n- 3-12 tasks for most features`;\n\n// ── Parse + validate an LLM response into a TaskDAG ────────────────\n\nexport function parseDecompositionResponse(response: string): TaskDAG {\n let jsonStr: string;\n\n // 1. Try to extract JSON from markdown code block\n const codeBlockMatch = response.match(/```(?:json)?\\s*\\n([\\s\\S]*?)\\n```/);\n if (codeBlockMatch) {\n jsonStr = codeBlockMatch[1];\n } else {\n // 2. Try the whole response as JSON\n jsonStr = response;\n }\n\n // 3. Parse JSON\n let raw: unknown;\n try {\n raw = JSON.parse(jsonStr);\n } catch {\n throw new Error(\n `Failed to parse decomposition response as JSON: ${jsonStr.slice(0, 200)}`,\n );\n }\n\n // 4. Validate through Zod schema\n const parsed = TaskDAGSchema.parse(raw);\n\n // 5. Validate DAG structure (cycles, refs)\n validateDAG(parsed);\n\n return parsed;\n}\n\n// ── LLM-driven requirement decomposition ───────────────────────────\n\nexport async function decomposeRequirement(\n requirement: string,\n client: LLMClient,\n): Promise<TaskDAG> {\n const response = await client.chat(\n DECOMPOSITION_SYSTEM_PROMPT,\n [{ role: \"user\", content: requirement }],\n () => {}, // stream chunks are unused; we read the final message\n );\n\n // Extract text from response\n const text =\n typeof response.message.content === \"string\"\n ? response.message.content\n : response.message.content\n .filter((b) => b.type === \"text\")\n .map((b) => (b as { type: \"text\"; text: string }).text)\n .join(\"\");\n\n return parseDecompositionResponse(text);\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\n\nexport interface StackProfile {\n projectName: string;\n languages: string[];\n frameworks: string[];\n databases: string[];\n infra: string[];\n isMonorepo: boolean;\n detectedAt: number;\n}\n\nconst FRAMEWORK_MAP: Record<string, string> = {\n next: \"next\", react: \"react\", remix: \"remix\", express: \"express\",\n fastify: \"fastify\", hono: \"hono\", \"@nestjs/core\": \"nestjs\",\n vue: \"vue\", svelte: \"svelte\", nuxt: \"nuxt\",\n};\n\nconst DB_IMAGE_MAP: Record<string, string> = {\n postgres: \"postgresql\", mysql: \"mysql\", mariadb: \"mariadb\",\n mongo: \"mongodb\", redis: \"redis\", timescaledb: \"timescaledb\",\n};\n\nexport function scanStack(projectPath: string): StackProfile {\n const languages: string[] = [];\n const frameworks: string[] = [];\n const databases: string[] = [];\n const infra: string[] = [];\n let isMonorepo = false;\n let projectName = path.basename(projectPath);\n\n // --- Go ---\n const goModPath = path.join(projectPath, \"go.mod\");\n if (fs.existsSync(goModPath)) {\n languages.push(\"go\");\n const content = fs.readFileSync(goModPath, \"utf-8\");\n const moduleMatch = content.match(/^module\\s+(.+)$/m);\n if (moduleMatch) {\n const parts = moduleMatch[1].trim().split(\"/\");\n projectName = parts[parts.length - 1];\n }\n if (content.includes(\"gofiber/fiber\")) frameworks.push(\"fiber\");\n if (content.includes(\"gin-gonic/gin\")) frameworks.push(\"gin\");\n if (content.includes(\"go-chi/chi\")) frameworks.push(\"chi\");\n if (content.includes(\"labstack/echo\")) frameworks.push(\"echo\");\n }\n\n // --- Node/TypeScript ---\n const pkgPath = path.join(projectPath, \"package.json\");\n const hasTsConfig = fs.existsSync(path.join(projectPath, \"tsconfig.json\"));\n if (fs.existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(fs.readFileSync(pkgPath, \"utf-8\"));\n if (pkg.name) projectName = pkg.name;\n if (hasTsConfig) {\n languages.push(\"typescript\");\n } else {\n languages.push(\"javascript\");\n }\n const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };\n for (const [dep, fwName] of Object.entries(FRAMEWORK_MAP)) {\n if (allDeps?.[dep]) frameworks.push(fwName);\n }\n if (pkg.workspaces) isMonorepo = true;\n } catch {\n if (hasTsConfig) languages.push(\"typescript\");\n }\n } else if (hasTsConfig) {\n languages.push(\"typescript\");\n }\n\n // --- Rust ---\n const cargoPath = path.join(projectPath, \"Cargo.toml\");\n if (fs.existsSync(cargoPath)) {\n languages.push(\"rust\");\n const content = fs.readFileSync(cargoPath, \"utf-8\");\n if (content.includes(\"[workspace]\")) isMonorepo = true;\n const nameMatch = content.match(/^\\s*name\\s*=\\s*\"([^\"]+)\"/m);\n if (nameMatch && !isMonorepo) projectName = nameMatch[1];\n }\n\n // --- Python ---\n const pyprojectPath = path.join(projectPath, \"pyproject.toml\");\n if (fs.existsSync(pyprojectPath)) {\n languages.push(\"python\");\n const content = fs.readFileSync(pyprojectPath, \"utf-8\");\n if (content.includes(\"django\")) frameworks.push(\"django\");\n if (content.includes(\"fastapi\")) frameworks.push(\"fastapi\");\n if (content.includes(\"flask\")) frameworks.push(\"flask\");\n }\n\n // --- Flutter/Dart ---\n if (fs.existsSync(path.join(projectPath, \"pubspec.yaml\"))) {\n languages.push(\"dart\");\n frameworks.push(\"flutter\");\n }\n\n // --- Docker ---\n if (fs.existsSync(path.join(projectPath, \"Dockerfile\"))) {\n infra.push(\"docker\");\n }\n\n // --- Docker Compose (databases) ---\n const composeNames = [\"docker-compose.yml\", \"docker-compose.yaml\", \"compose.yml\", \"compose.yaml\"];\n for (const name of composeNames) {\n const composePath = path.join(projectPath, name);\n if (fs.existsSync(composePath)) {\n if (!infra.includes(\"docker\")) infra.push(\"docker\");\n const content = fs.readFileSync(composePath, \"utf-8\");\n for (const [pattern, dbName] of Object.entries(DB_IMAGE_MAP)) {\n if (content.includes(pattern) && !databases.includes(dbName)) {\n databases.push(dbName);\n }\n }\n break;\n }\n }\n\n // --- CI/CD ---\n if (fs.existsSync(path.join(projectPath, \".github\", \"workflows\"))) {\n infra.push(\"github-actions\");\n }\n\n // --- Kubernetes ---\n for (const dir of [\"k3s\", \"k8s\", \"deploy\"]) {\n if (fs.existsSync(path.join(projectPath, dir))) {\n infra.push(\"kubernetes\");\n break;\n }\n }\n\n // --- Makefile ---\n if (fs.existsSync(path.join(projectPath, \"Makefile\"))) {\n infra.push(\"make\");\n }\n\n return {\n projectName,\n languages,\n frameworks,\n databases,\n infra,\n isMonorepo,\n detectedAt: Date.now(),\n };\n}\n","import { z } from \"zod\";\n\n// ---------- Issue ----------\nexport const GitHubIssueSchema = z.object({\n number: z.number().int().positive(),\n title: z.string().min(1),\n body: z.string().nullable().default(null),\n state: z.enum([\"OPEN\", \"CLOSED\"]),\n url: z.string().url(),\n labels: z.array(z.object({ name: z.string() })).default([]),\n assignees: z.array(z.object({ login: z.string() })).default([]),\n author: z.object({ login: z.string() }).optional(),\n createdAt: z.string(),\n updatedAt: z.string(),\n});\nexport type GitHubIssue = z.infer<typeof GitHubIssueSchema>;\n\n// ---------- Pull Request ----------\nexport const GitHubPRSchema = z.object({\n number: z.number().int().positive(),\n title: z.string().min(1),\n body: z.string().nullable().default(null),\n state: z.enum([\"OPEN\", \"CLOSED\", \"MERGED\"]),\n url: z.string().url(),\n headRefName: z.string(),\n baseRefName: z.string(),\n isDraft: z.boolean().default(false),\n mergeable: z\n .enum([\"MERGEABLE\", \"CONFLICTING\", \"UNKNOWN\"])\n .default(\"UNKNOWN\"),\n labels: z.array(z.object({ name: z.string() })).default([]),\n author: z.object({ login: z.string() }).optional(),\n createdAt: z.string(),\n updatedAt: z.string(),\n});\nexport type GitHubPR = z.infer<typeof GitHubPRSchema>;\n\n// ---------- Workflow Run (CI) ----------\nexport const WorkflowRunSchema = z.object({\n databaseId: z.number().int().positive(),\n name: z.string(),\n workflowName: z.string().optional(),\n status: z.enum([\n \"queued\",\n \"in_progress\",\n \"completed\",\n \"waiting\",\n \"requested\",\n \"pending\",\n ]),\n conclusion: z\n .enum([\n \"success\",\n \"failure\",\n \"cancelled\",\n \"skipped\",\n \"timed_out\",\n \"action_required\",\n \"neutral\",\n \"stale\",\n \"\",\n ])\n .nullable()\n .default(null),\n url: z.string().url(),\n headBranch: z.string(),\n event: z.string(),\n createdAt: z.string(),\n updatedAt: z.string(),\n});\nexport type WorkflowRun = z.infer<typeof WorkflowRunSchema>;\n\n// ---------- Check Status (simplified) ----------\nexport const CheckStatusSchema = z.object({\n passed: z.boolean(),\n pending: z.boolean(),\n failing: z.boolean(),\n total: z.number().int().nonnegative(),\n details: z\n .array(\n z.object({\n name: z.string(),\n status: z.string(),\n conclusion: z.string().nullable(),\n }),\n )\n .default([]),\n});\nexport type CheckStatus = z.infer<typeof CheckStatusSchema>;\n\n// ---------- gh CLI result wrapper ----------\nexport const GhResultSchema = z.object({\n success: z.boolean(),\n stdout: z.string(),\n stderr: z.string(),\n exitCode: z.number().int(),\n});\nexport type GhResult = z.infer<typeof GhResultSchema>;\n","import { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport type { GhResult } from \"./types.js\";\n\nconst execFileAsync = promisify(execFile);\n\nexport interface GhOptions {\n /** Working directory for the command */\n cwd?: string;\n /** Timeout in ms (default: 30_000) */\n timeoutMs?: number;\n /** Additional environment variables */\n env?: Record<string, string>;\n}\n\nexport class GhError extends Error {\n constructor(\n message: string,\n public readonly exitCode: number,\n public readonly stderr: string,\n ) {\n super(message);\n this.name = \"GhError\";\n }\n}\n\n/**\n * Run a gh CLI command safely via execFile (no shell).\n * Returns structured GhResult with stdout, stderr, exitCode.\n * Does NOT throw on non-zero exit — returns { success: false, exitCode, stderr }.\n */\nexport async function gh(\n args: string[],\n options?: GhOptions,\n): Promise<GhResult> {\n const ghBin = options?.env?.GH_PATH ?? process.env.GH_PATH ?? \"gh\";\n const timeout = options?.timeoutMs ?? 30_000;\n\n const execOpts: Record<string, unknown> = {\n timeout,\n ...(options?.cwd ? { cwd: options.cwd } : {}),\n ...(options?.env\n ? { env: { ...process.env, ...options.env } }\n : {}),\n };\n\n try {\n const { stdout, stderr } = await execFileAsync(ghBin, args, execOpts);\n return { success: true, stdout, stderr, exitCode: 0 };\n } catch (err: unknown) {\n const e = err as {\n code?: number;\n stdout?: string;\n stderr?: string;\n };\n const exitCode = typeof e.code === \"number\" ? e.code : 1;\n return {\n success: false,\n stdout: e.stdout ?? \"\",\n stderr: e.stderr ?? \"\",\n exitCode,\n };\n }\n}\n\n/**\n * Run gh and parse JSON output. Throws if gh fails or output isn't valid JSON.\n */\nexport async function ghJson<T>(\n args: string[],\n options?: GhOptions,\n): Promise<T> {\n const result = await gh(args, options);\n\n if (!result.success) {\n throw new GhError(\n `gh command failed: ${result.stderr}`,\n result.exitCode,\n result.stderr,\n );\n }\n\n try {\n return JSON.parse(result.stdout) as T;\n } catch {\n throw new GhError(\n `Failed to parse JSON from gh output: ${result.stdout.slice(0, 200)}`,\n 0,\n result.stderr,\n );\n }\n}\n\n/**\n * Check if gh CLI is available and authenticated.\n */\nexport async function ghAvailable(): Promise<boolean> {\n const result = await gh([\"auth\", \"status\"]);\n return result.success;\n}\n\n/**\n * Get the current repo owner/name from gh CLI.\n */\nexport async function ghCurrentRepo(): Promise<{\n owner: string;\n name: string;\n} | null> {\n try {\n const data = await ghJson<{ owner: { login: string }; name: string }>(\n [\"repo\", \"view\", \"--json\", \"owner,name\"],\n );\n return { owner: data.owner.login, name: data.name };\n } catch {\n return null;\n }\n}\n","import type { LLMClient } from \"../llm/types.js\";\nimport type { TaskDAG } from \"../orchestrator/types.js\";\nimport type { GitHubIssue } from \"./types.js\";\nimport { ghJson } from \"./cli.js\";\nimport { GitHubIssueSchema } from \"./types.js\";\nimport { decomposeRequirement } from \"../orchestrator/decompose.js\";\n\nconst ISSUE_JSON_FIELDS =\n \"number,title,body,state,url,labels,assignees,author,createdAt,updatedAt\";\n\n/**\n * Fetch a GitHub issue by number.\n */\nexport async function fetchIssue(\n issueNumber: number,\n options?: { repo?: string; cwd?: string },\n): Promise<GitHubIssue> {\n const args = [\n \"issue\",\n \"view\",\n String(issueNumber),\n \"--json\",\n ISSUE_JSON_FIELDS,\n ];\n\n if (options?.repo) {\n args.push(\"--repo\", options.repo);\n }\n\n const raw = await ghJson<unknown>(args, { cwd: options?.cwd });\n return GitHubIssueSchema.parse(raw);\n}\n\n/**\n * Format an issue into a requirement string for the decomposer.\n */\nexport function formatIssueAsRequirement(issue: GitHubIssue): string {\n const parts: string[] = [`# ${issue.title}`];\n\n if (issue.body) {\n parts.push(\"\", issue.body);\n }\n\n const extras: string[] = [];\n\n if (issue.labels.length > 0) {\n extras.push(`Labels: ${issue.labels.map((l) => l.name).join(\", \")}`);\n }\n\n if (issue.assignees.length > 0) {\n extras.push(\n `Assignees: ${issue.assignees.map((a) => a.login).join(\", \")}`,\n );\n }\n\n if (extras.length > 0) {\n parts.push(\"\", ...extras);\n }\n\n return parts.join(\"\\n\");\n}\n\n/**\n * Fetch a GitHub issue and decompose it into a TaskDAG.\n */\nexport async function planFromIssue(\n issueNumber: number,\n client: LLMClient,\n options?: { repo?: string; cwd?: string },\n): Promise<{ issue: GitHubIssue; dag: TaskDAG }> {\n const issue = await fetchIssue(issueNumber, options);\n const requirement = formatIssueAsRequirement(issue);\n const dag = await decomposeRequirement(requirement, client);\n return { issue, dag };\n}\n","import { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { gh, ghJson } from \"./cli.js\";\nimport { GitHubPRSchema } from \"./types.js\";\nimport type { GitHubPR } from \"./types.js\";\n\nconst execFileAsync = promisify(execFile);\n\n/** JSON fields requested from gh for PR objects. */\nconst PR_JSON_FIELDS =\n \"number,title,body,state,url,headRefName,baseRefName,isDraft,mergeable,labels,author,createdAt,updatedAt\";\n\n// ---------- types ----------\n\nexport interface CreatePROptions {\n title: string;\n body: string;\n head: string;\n base?: string;\n draft?: boolean;\n labels?: string[];\n repo?: string;\n cwd?: string;\n}\n\n// ---------- createPR ----------\n\n/**\n * Create a pull request via gh CLI.\n */\nexport async function createPR(options: CreatePROptions): Promise<GitHubPR> {\n const args: string[] = [\n \"pr\",\n \"create\",\n \"--title\",\n options.title,\n \"--body\",\n options.body,\n \"--head\",\n options.head,\n ];\n\n if (options.base) {\n args.push(\"--base\", options.base);\n }\n if (options.draft) {\n args.push(\"--draft\");\n }\n if (options.labels) {\n for (const label of options.labels) {\n args.push(\"--label\", label);\n }\n }\n if (options.repo) {\n args.push(\"--repo\", options.repo);\n }\n\n const ghOpts = options.cwd ? { cwd: options.cwd } : undefined;\n\n // Create the PR — gh prints the URL on success\n const result = await gh(args, ghOpts);\n if (!result.success) {\n const { GhError } = await import(\"./cli.js\");\n throw new GhError(\n `Failed to create PR: ${result.stderr}`,\n result.exitCode,\n result.stderr,\n );\n }\n\n // Extract PR number from the URL (last path segment)\n const url = result.stdout.trim();\n const prNumber = parseInt(url.split(\"/\").pop()!, 10);\n\n // Fetch full PR data\n return getPR(prNumber, { repo: options.repo, cwd: options.cwd });\n}\n\n// ---------- listPRs ----------\n\n/**\n * List open PRs, optionally filtered.\n */\nexport async function listPRs(options?: {\n state?: \"open\" | \"closed\" | \"merged\" | \"all\";\n head?: string;\n limit?: number;\n repo?: string;\n cwd?: string;\n}): Promise<GitHubPR[]> {\n const args: string[] = [\"pr\", \"list\", \"--json\", PR_JSON_FIELDS];\n\n if (options?.state) {\n args.push(\"--state\", options.state);\n }\n if (options?.head) {\n args.push(\"--head\", options.head);\n }\n if (options?.limit != null) {\n args.push(\"--limit\", String(options.limit));\n }\n if (options?.repo) {\n args.push(\"--repo\", options.repo);\n }\n\n const ghOpts = options?.cwd ? { cwd: options.cwd } : undefined;\n const raw = await ghJson<unknown[]>(args, ghOpts);\n\n return raw.map((item) => GitHubPRSchema.parse(item));\n}\n\n// ---------- getPR ----------\n\n/**\n * Get a specific PR by number.\n */\nexport async function getPR(\n prNumber: number,\n options?: { repo?: string; cwd?: string },\n): Promise<GitHubPR> {\n const args: string[] = [\n \"pr\",\n \"view\",\n String(prNumber),\n \"--json\",\n PR_JSON_FIELDS,\n ];\n\n if (options?.repo) {\n args.push(\"--repo\", options.repo);\n }\n\n const ghOpts = options?.cwd ? { cwd: options.cwd } : undefined;\n const raw = await ghJson<unknown>(args, ghOpts);\n\n return GitHubPRSchema.parse(raw);\n}\n\n// ---------- commentOnPR ----------\n\n/**\n * Post a review comment on a PR.\n */\nexport async function commentOnPR(\n prNumber: number,\n body: string,\n options?: { repo?: string; cwd?: string },\n): Promise<void> {\n const args: string[] = [\"pr\", \"comment\", String(prNumber), \"--body\", body];\n\n if (options?.repo) {\n args.push(\"--repo\", options.repo);\n }\n\n const ghOpts = options?.cwd ? { cwd: options.cwd } : undefined;\n const result = await gh(args, ghOpts);\n\n if (!result.success) {\n const { GhError } = await import(\"./cli.js\");\n throw new GhError(\n `Failed to comment on PR #${prNumber}: ${result.stderr}`,\n result.exitCode,\n result.stderr,\n );\n }\n}\n\n// ---------- createBranch ----------\n\n/**\n * Create a git branch (via git, not gh).\n */\nexport async function createBranch(\n branchName: string,\n options?: { baseBranch?: string; cwd?: string },\n): Promise<void> {\n const args = [\"checkout\", \"-b\", branchName];\n\n if (options?.baseBranch) {\n args.push(options.baseBranch);\n }\n\n const execOpts: Record<string, unknown> = {};\n if (options?.cwd) {\n execOpts.cwd = options.cwd;\n }\n\n await execFileAsync(\"git\", args, execOpts);\n}\n","import { ghJson } from \"./cli.js\";\nimport { WorkflowRunSchema, CheckStatusSchema } from \"./types.js\";\nimport type { WorkflowRun, CheckStatus } from \"./types.js\";\n\nconst RUN_JSON_FIELDS =\n \"databaseId,name,workflowName,status,conclusion,url,headBranch,event,createdAt,updatedAt\";\n\n/**\n * Get the latest workflow run for a branch.\n */\nexport async function getLatestRun(\n branch: string,\n options?: { workflow?: string; repo?: string; cwd?: string },\n): Promise<WorkflowRun | null> {\n const args = [\n \"run\",\n \"list\",\n \"--branch\",\n branch,\n \"--limit\",\n \"1\",\n \"--json\",\n RUN_JSON_FIELDS,\n ];\n\n if (options?.workflow) {\n args.push(\"--workflow\", options.workflow);\n }\n if (options?.repo) {\n args.push(\"--repo\", options.repo);\n }\n\n const runs = await ghJson<unknown[]>(args, { cwd: options?.cwd });\n\n if (!runs.length) return null;\n\n return WorkflowRunSchema.parse(runs[0]);\n}\n\n/**\n * Get check status for a specific commit or PR.\n */\nexport async function getCheckStatus(\n ref: string,\n options?: { repo?: string; cwd?: string },\n): Promise<CheckStatus> {\n // If ref looks like a PR number, use `gh pr checks`\n const isPRNumber = /^\\d+$/.test(ref);\n\n if (isPRNumber) {\n const args = [\"pr\", \"checks\", ref, \"--json\", \"name,status,conclusion\"];\n if (options?.repo) args.push(\"--repo\", options.repo);\n\n const checks = await ghJson<\n Array<{ name: string; status: string; conclusion: string | null }>\n >(args, { cwd: options?.cwd });\n\n const details = checks.map((c) => ({\n name: c.name,\n status: c.status,\n conclusion: c.conclusion,\n }));\n\n const passed = details.every(\n (d) => d.status === \"completed\" && d.conclusion === \"success\",\n );\n const pending = details.some((d) => d.status !== \"completed\");\n const failing = details.some(\n (d) =>\n d.status === \"completed\" &&\n d.conclusion !== \"success\" &&\n d.conclusion !== \"skipped\" &&\n d.conclusion !== \"neutral\",\n );\n\n return CheckStatusSchema.parse({\n passed: passed && details.length > 0,\n pending,\n failing,\n total: details.length,\n details,\n });\n }\n\n // For commit SHAs, fall back to run list\n const run = await getLatestRun(ref, options);\n\n if (!run) {\n return CheckStatusSchema.parse({\n passed: false,\n pending: false,\n failing: false,\n total: 0,\n details: [],\n });\n }\n\n return CheckStatusSchema.parse({\n passed: run.status === \"completed\" && run.conclusion === \"success\",\n pending: run.status !== \"completed\",\n failing:\n run.status === \"completed\" &&\n run.conclusion !== \"success\" &&\n run.conclusion !== \"skipped\" &&\n run.conclusion !== \"neutral\",\n total: 1,\n details: [\n { name: run.name, status: run.status, conclusion: run.conclusion },\n ],\n });\n}\n\n/**\n * Wait for CI to complete on a branch. Polls at interval.\n */\nexport async function waitForCI(\n branch: string,\n options?: {\n workflow?: string;\n repo?: string;\n cwd?: string;\n pollIntervalMs?: number;\n timeoutMs?: number;\n },\n): Promise<{ passed: boolean; run: WorkflowRun | null }> {\n const pollInterval = options?.pollIntervalMs ?? 10_000;\n const timeout = options?.timeoutMs ?? 600_000;\n const deadline = Date.now() + timeout;\n\n while (Date.now() < deadline) {\n const run = await getLatestRun(branch, options);\n\n if (run && run.status === \"completed\") {\n return { passed: run.conclusion === \"success\", run };\n }\n\n // Check if we'd exceed deadline after sleeping\n if (Date.now() + pollInterval >= deadline) break;\n\n await new Promise((resolve) => setTimeout(resolve, pollInterval));\n }\n\n return { passed: false, run: null };\n}\n\n/**\n * Check if CI is passing for a branch (non-blocking snapshot).\n */\nexport async function isCIPassing(\n branch: string,\n options?: { workflow?: string; repo?: string; cwd?: string },\n): Promise<boolean> {\n const run = await getLatestRun(branch, options);\n return run !== null && run.status === \"completed\" && run.conclusion === \"success\";\n}\n","// Types\nexport {\n type GitHubIssue, type GitHubPR, type WorkflowRun, type CheckStatus, type GhResult,\n GitHubIssueSchema, GitHubPRSchema, WorkflowRunSchema, CheckStatusSchema, GhResultSchema,\n} from \"./types.js\";\n\n// CLI\nexport { gh, ghJson, ghAvailable, ghCurrentRepo, GhError } from \"./cli.js\";\n\n// Issue Planner\nexport { fetchIssue, formatIssueAsRequirement, planFromIssue } from \"./issue-planner.js\";\n\n// PR Manager\nexport { createPR, listPRs, getPR, commentOnPR, createBranch, type CreatePROptions } from \"./pr-manager.js\";\n\n// CI Gate\nexport { getLatestRun, getCheckStatus, waitForCI, isCIPassing } from \"./ci-gate.js\";\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport os from \"node:os\";\nimport { createDatabase, recall } from \"@aman_asmuei/amem-core\";\nimport {\n getIdentity as acoreGetIdentity,\n} from \"@aman_asmuei/acore-core\";\nimport {\n listRuleCategories as arulesListCategories,\n} from \"@aman_asmuei/arules-core\";\nimport type { StackProfile } from \"./stack-detector.js\";\nimport type { ProjectContext } from \"./claude-md-writer.js\";\nimport { estimateTokens } from \"../token-budget.js\";\n\nconst AGENT_SCOPE = process.env.AMAN_AGENT_SCOPE ?? \"dev:agent\";\n\nconst TOKEN_LIMITS: Record<string, number> = {\n conventions: 1500,\n decisions: 1200,\n corrections: 800,\n preferences: 500,\n rules: 800,\n};\n\nfunction trimToTokenBudget(items: string[], maxTokens: number): string[] {\n const result: string[] = [];\n let total = 0;\n for (const item of items) {\n if (typeof item !== \"string\" || !item) continue;\n const tokens = estimateTokens(item);\n if (total + tokens > maxTokens) break;\n result.push(item);\n total += tokens;\n }\n return result;\n}\n\nexport interface BuildOptions {\n smart?: boolean;\n llmClient?: unknown;\n}\n\nexport async function buildContext(\n stack: StackProfile,\n opts?: BuildOptions,\n): Promise<ProjectContext> {\n const conventions: string[] = [];\n const decisions: string[] = [];\n const corrections: string[] = [];\n const preferences: string[] = [];\n const rules: string[] = [];\n let memoriesUsed = 0;\n\n // --- Query amem ---\n try {\n const amemDir = process.env.AMEM_DIR ?? path.join(os.homedir(), \".amem\");\n const dbPath = process.env.AMEM_DB ?? path.join(amemDir, \"memory.db\");\n\n // Skip if database doesn't exist — avoids loading HuggingFace models for nothing\n // But allow override via AMEM_DB env var (also needed for tests with mocked createDatabase)\n if (!process.env.AMEM_DB && !fs.existsSync(dbPath)) throw new Error(\"no db\");\n\n const db = createDatabase(dbPath);\n\n // Build a project-focused query\n const queryParts = [stack.projectName, ...stack.languages, ...stack.frameworks];\n const query = queryParts.join(\" \");\n\n // Build relevance keywords for post-recall filtering\n // Only keep memories that mention the project name, stack languages, or frameworks\n const relevanceKeywords = queryParts\n .map((k) => k.toLowerCase())\n .filter(Boolean);\n\n // rerank: false skips the cross-encoder model — much faster startup\n // Fetch more candidates so we have enough after filtering\n const result = await recall(db, { query, limit: 40, compact: false, rerank: false });\n\n // Max content length per memory entry (prevents one huge memory from filling the budget)\n const MAX_CONTENT_LENGTH = 500;\n\n for (const mem of result.memories) {\n let content = (mem as any).content;\n if (typeof content !== \"string\" || !content) continue;\n\n // Project relevance filter: memory must mention at least one keyword\n // from the project name, language, or framework\n const contentLower = content.toLowerCase();\n const isRelevant = relevanceKeywords.length === 0 ||\n relevanceKeywords.some((kw) => {\n // Short keywords (e.g. \"go\") use word boundary match to avoid false positives\n if (kw.length <= 3) {\n return new RegExp(`\\\\b${kw}\\\\b`, \"i\").test(contentLower);\n }\n return contentLower.includes(kw);\n });\n if (!isRelevant) continue;\n\n // Truncate very long memories to keep CLAUDE.md focused\n if (content.length > MAX_CONTENT_LENGTH) {\n content = content.slice(0, MAX_CONTENT_LENGTH).trimEnd() + \"...\";\n }\n\n switch ((mem as any).type) {\n case \"pattern\":\n if (!conventions.includes(content)) conventions.push(content);\n break;\n case \"decision\":\n if (!decisions.includes(content)) decisions.push(content);\n break;\n case \"correction\":\n if (!corrections.includes(content)) corrections.push(content);\n break;\n case \"preference\":\n if (!preferences.includes(content)) preferences.push(content);\n break;\n }\n memoriesUsed++;\n }\n } catch {\n // amem not available — continue without memories\n }\n\n // --- Query acore for identity/preferences ---\n try {\n const identity = await acoreGetIdentity(AGENT_SCOPE);\n if (identity?.content) {\n const lines = identity.content.split(\"\\n\").filter((l: string) =>\n l.startsWith(\"- \") && (\n l.toLowerCase().includes(\"prefer\") ||\n l.toLowerCase().includes(\"style\") ||\n l.toLowerCase().includes(\"convention\")\n ),\n );\n for (const line of lines) {\n const text = line.replace(/^-\\s*/, \"\").trim();\n if (text && !preferences.includes(text)) preferences.push(text);\n }\n }\n } catch {\n // acore not available\n }\n\n // --- Query arules ---\n try {\n const categories = await arulesListCategories(AGENT_SCOPE);\n // arules-core returns { name: string; rules: string[] } — rules are already filtered to active-only\n for (const cat of categories) {\n for (const ruleText of cat.rules) {\n if (typeof ruleText === \"string\" && ruleText && !rules.includes(ruleText)) {\n rules.push(ruleText);\n }\n }\n }\n } catch {\n // arules not available\n }\n\n // --- Smart mode: LLM synthesis ---\n if (opts?.smart && opts.llmClient) {\n try {\n const client = opts.llmClient as { chat: (system: string, msgs: { role: string; content: string }[], onChunk: () => void) => Promise<{ message: { content: string | { text?: string }[] } }> };\n const rawData = [\n `Project: ${stack.projectName}`,\n `Stack: ${stack.languages.join(\", \")} + ${stack.frameworks.join(\", \")}`,\n `Databases: ${stack.databases.join(\", \") || \"none detected\"}`,\n \"\",\n conventions.length > 0 ? `Conventions:\\n${conventions.map((c) => `- ${c}`).join(\"\\n\")}` : \"\",\n decisions.length > 0 ? `Decisions:\\n${decisions.map((d) => `- ${d}`).join(\"\\n\")}` : \"\",\n corrections.length > 0 ? `Corrections:\\n${corrections.map((c) => `- ${c}`).join(\"\\n\")}` : \"\",\n preferences.length > 0 ? `Preferences:\\n${preferences.map((p) => `- ${p}`).join(\"\\n\")}` : \"\",\n rules.length > 0 ? `Rules:\\n${rules.map((r) => `- ${r}`).join(\"\\n\")}` : \"\",\n ].filter(Boolean).join(\"\\n\\n\");\n\n const response = await client.chat(\n \"You are a developer context assembler. Given raw developer history, output a merged, deduplicated set of conventions and decisions as markdown bullet lists. Group by: Conventions, Decisions, Corrections, Preferences, Rules. Be specific, not generic. Max 3000 tokens.\",\n [{ role: \"user\", content: rawData }],\n () => {},\n );\n\n // Parse LLM response to extract synthesized sections\n const text = typeof response.message.content === \"string\"\n ? response.message.content\n : response.message.content.map((b: { text?: string }) => b.text ?? \"\").join(\"\");\n\n // Extract bullet points from each section the LLM generated\n const extractSection = (sectionName: string): string[] => {\n const regex = new RegExp(`##?\\\\s*${sectionName}[\\\\s\\\\S]*?(?=##|$)`, \"i\");\n const match = text.match(regex);\n if (!match) return [];\n return match[0].split(\"\\n\").filter((l) => l.startsWith(\"- \")).map((l) => l.replace(/^-\\s*/, \"\").trim());\n };\n\n const smartConventions = extractSection(\"Conventions\");\n const smartDecisions = extractSection(\"Decisions\");\n const smartCorrections = extractSection(\"Corrections\");\n const smartPreferences = extractSection(\"Preferences\");\n const smartRules = extractSection(\"Rules\");\n\n return {\n stack,\n conventions: trimToTokenBudget(smartConventions.length > 0 ? smartConventions : conventions, TOKEN_LIMITS.conventions),\n decisions: trimToTokenBudget(smartDecisions.length > 0 ? smartDecisions : decisions, TOKEN_LIMITS.decisions),\n corrections: trimToTokenBudget(smartCorrections.length > 0 ? smartCorrections : corrections, TOKEN_LIMITS.corrections),\n preferences: trimToTokenBudget(smartPreferences.length > 0 ? smartPreferences : preferences, TOKEN_LIMITS.preferences),\n rules: trimToTokenBudget(smartRules.length > 0 ? smartRules : rules, TOKEN_LIMITS.rules),\n metadata: {\n generatedAt: Date.now(),\n mode: \"smart\" as const,\n memoriesUsed,\n },\n };\n } catch {\n // LLM failed — fall through to template mode\n }\n }\n\n // --- Apply token budgets ---\n return {\n stack,\n conventions: trimToTokenBudget(conventions, TOKEN_LIMITS.conventions),\n decisions: trimToTokenBudget(decisions, TOKEN_LIMITS.decisions),\n corrections: trimToTokenBudget(corrections, TOKEN_LIMITS.corrections),\n preferences: trimToTokenBudget(preferences, TOKEN_LIMITS.preferences),\n rules: trimToTokenBudget(rules, TOKEN_LIMITS.rules),\n metadata: {\n generatedAt: Date.now(),\n mode: \"template\" as const,\n memoriesUsed,\n },\n };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { StackProfile } from \"./stack-detector.js\";\n\nexport interface ProjectContext {\n stack: StackProfile;\n conventions: string[];\n decisions: string[];\n corrections: string[];\n preferences: string[];\n rules: string[];\n metadata: {\n generatedAt: number;\n mode: \"template\" | \"smart\";\n memoriesUsed: number;\n };\n}\n\nexport interface MarkerInfo {\n generatedAt: Date;\n memories: number;\n mode: string;\n}\n\nexport interface WriteResult {\n written: boolean;\n backedUp: boolean;\n path: string;\n}\n\nexport interface StalenessResult {\n status: \"missing\" | \"no-marker\" | \"fresh\" | \"stale\";\n generatedAt?: Date;\n}\n\nfunction formatStack(stack: StackProfile): string {\n const parts: string[] = [];\n const goFrameworks = [\"fiber\", \"gin\", \"chi\", \"echo\"];\n const jsFrameworks = [\"next\", \"react\", \"remix\", \"express\", \"fastify\", \"hono\", \"nestjs\", \"vue\", \"svelte\", \"nuxt\"];\n const pyFrameworks = [\"django\", \"fastapi\", \"flask\"];\n\n for (const lang of stack.languages) {\n const fw = stack.frameworks.filter((f) => {\n if (lang === \"go\" && goFrameworks.includes(f)) return true;\n if ((lang === \"typescript\" || lang === \"javascript\") && jsFrameworks.includes(f)) return true;\n if (lang === \"python\" && pyFrameworks.includes(f)) return true;\n if (lang === \"dart\" && f === \"flutter\") return true;\n return false;\n });\n const name = lang.charAt(0).toUpperCase() + lang.slice(1);\n if (fw.length > 0) {\n parts.push(`${name} (${fw.map((f) => f.charAt(0).toUpperCase() + f.slice(1)).join(\", \")})`);\n } else {\n parts.push(name);\n }\n }\n if (stack.databases.length > 0) {\n parts.push(...stack.databases.map((d) => d.charAt(0).toUpperCase() + d.slice(1)));\n }\n return parts.join(\" + \");\n}\n\nexport function renderToString(ctx: ProjectContext): string {\n const lines: string[] = [];\n const ts = new Date(ctx.metadata.generatedAt).toISOString();\n\n lines.push(`# Project: ${ctx.stack.projectName}`);\n lines.push(`<!-- aman-agent:dev generated=${ts} memories=${ctx.metadata.memoriesUsed} mode=${ctx.metadata.mode} -->`);\n lines.push(\"\");\n\n const stackLine = formatStack(ctx.stack);\n if (stackLine || ctx.stack.infra.length > 0) {\n lines.push(\"## Stack\");\n if (stackLine) lines.push(`- ${stackLine}`);\n if (ctx.stack.infra.length > 0) {\n lines.push(`- Infra: ${ctx.stack.infra.join(\", \")}`);\n }\n if (ctx.stack.isMonorepo) {\n lines.push(\"- Monorepo\");\n }\n lines.push(\"\");\n }\n\n if (ctx.conventions.length > 0) {\n lines.push(\"## Conventions\");\n for (const c of ctx.conventions) lines.push(`- ${c}`);\n lines.push(\"\");\n }\n\n if (ctx.decisions.length > 0) {\n lines.push(\"## Past Decisions\");\n for (const d of ctx.decisions) lines.push(`- ${d}`);\n lines.push(\"\");\n }\n\n if (ctx.corrections.length > 0) {\n lines.push(\"## Corrections\");\n for (const c of ctx.corrections) lines.push(`- ${c}`);\n lines.push(\"\");\n }\n\n if (ctx.preferences.length > 0) {\n lines.push(\"## Developer Preferences\");\n for (const p of ctx.preferences) lines.push(`- ${p}`);\n lines.push(\"\");\n }\n\n if (ctx.rules.length > 0) {\n lines.push(\"## Rules\");\n for (const r of ctx.rules) lines.push(`- ${r}`);\n lines.push(\"\");\n }\n\n return lines.join(\"\\n\");\n}\n\nexport function parseMarker(content: string): MarkerInfo | null {\n const match = content.match(\n /<!--\\s*aman-agent:dev\\s+generated=(\\S+)\\s+memories=(\\d+)\\s+mode=(\\S+)\\s*-->/,\n );\n if (!match) return null;\n return {\n generatedAt: new Date(match[1]),\n memories: parseInt(match[2], 10),\n mode: match[3],\n };\n}\n\n// --- Editor target definitions ---\n\nexport type EditorName = \"claude\" | \"copilot\" | \"cursor\";\n\nexport interface EditorTarget {\n name: EditorName;\n contextFile: string; // relative path from project root\n launchCmd: string; // binary to launch\n launchArgs: string[]; // default args\n yoloArgs?: string[]; // extra args for --yolo mode\n gitignoreEntry: string; // what to add to .gitignore\n displayName: string; // for terminal output\n}\n\nexport const EDITOR_TARGETS: Record<EditorName, EditorTarget> = {\n claude: {\n name: \"claude\",\n contextFile: \"CLAUDE.md\",\n launchCmd: \"claude\",\n launchArgs: [],\n yoloArgs: [\"--dangerously-skip-permissions\"],\n gitignoreEntry: \"CLAUDE.md\",\n displayName: \"Claude Code\",\n },\n copilot: {\n name: \"copilot\",\n contextFile: \".github/copilot-instructions.md\",\n launchCmd: \"code\",\n launchArgs: [\".\"],\n gitignoreEntry: \".github/copilot-instructions.md\",\n displayName: \"VS Code (Copilot)\",\n },\n cursor: {\n name: \"cursor\",\n contextFile: \".cursorrules\",\n launchCmd: \"cursor\",\n launchArgs: [\".\"],\n gitignoreEntry: \".cursorrules\",\n displayName: \"Cursor\",\n },\n};\n\nexport function checkStaleness(projectPath: string, editor: EditorName = \"claude\"): StalenessResult {\n const target = EDITOR_TARGETS[editor];\n const filePath = path.join(projectPath, target.contextFile);\n if (!fs.existsSync(filePath)) {\n return { status: \"missing\" };\n }\n const content = fs.readFileSync(filePath, \"utf-8\");\n const marker = parseMarker(content);\n if (!marker) {\n return { status: \"no-marker\" };\n }\n return { status: \"fresh\", generatedAt: marker.generatedAt };\n}\n\nexport function writeContextFile(ctx: ProjectContext, projectPath: string, editor: EditorName = \"claude\"): WriteResult {\n const target = EDITOR_TARGETS[editor];\n const filePath = path.join(projectPath, target.contextFile);\n let backedUp = false;\n\n // Ensure parent directory exists (e.g. .github/ for copilot)\n const parentDir = path.dirname(filePath);\n if (!fs.existsSync(parentDir)) {\n fs.mkdirSync(parentDir, { recursive: true });\n }\n\n if (fs.existsSync(filePath)) {\n const content = fs.readFileSync(filePath, \"utf-8\");\n const marker = parseMarker(content);\n if (!marker) {\n fs.copyFileSync(filePath, `${filePath}.bak`);\n backedUp = true;\n }\n }\n\n const md = renderToString(ctx);\n fs.writeFileSync(filePath, md, \"utf-8\");\n\n return { written: true, backedUp, path: filePath };\n}\n\n// Backward compat alias\nexport const writeClaudeMd = writeContextFile;\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { scanStack, type StackProfile } from \"./stack-detector.js\";\nimport { buildContext } from \"./context-builder.js\";\nimport {\n renderToString,\n writeContextFile,\n checkStaleness,\n EDITOR_TARGETS,\n type EditorName,\n} from \"./claude-md-writer.js\";\nimport type { ProjectContext } from \"./claude-md-writer.js\";\n\nexport interface DevFlags {\n smart?: boolean;\n noLaunch?: boolean;\n force?: boolean;\n diff?: boolean;\n editor?: EditorName;\n}\n\nexport interface DevResult {\n success: boolean;\n generated: boolean;\n skippedReason?: string;\n diff?: string;\n context?: ProjectContext;\n error?: string;\n}\n\nfunction ensureGitignore(projectPath: string, editor: EditorName): void {\n const gitignorePath = path.join(projectPath, \".gitignore\");\n if (!fs.existsSync(gitignorePath)) return;\n const content = fs.readFileSync(gitignorePath, \"utf-8\");\n const target = EDITOR_TARGETS[editor];\n if (content.includes(target.gitignoreEntry)) return;\n fs.appendFileSync(gitignorePath, `\\n# Generated by aman-agent dev\\n${target.gitignoreEntry}\\n`);\n}\n\nexport async function runDev(\n projectPath: string,\n flags: DevFlags = {},\n precomputedStack?: StackProfile,\n): Promise<DevResult> {\n const resolved = path.resolve(projectPath);\n const editor = flags.editor ?? \"claude\";\n\n if (!fs.existsSync(resolved)) {\n return { success: false, generated: false, error: `Directory not found: ${resolved}` };\n }\n\n const stack = precomputedStack ?? scanStack(resolved);\n\n // Handle --diff\n if (flags.diff) {\n const ctx = await buildContext(stack, { smart: flags.smart });\n const newContent = renderToString(ctx);\n const target = EDITOR_TARGETS[editor];\n const existingPath = path.join(resolved, target.contextFile);\n const existing = fs.existsSync(existingPath)\n ? fs.readFileSync(existingPath, \"utf-8\")\n : \"\";\n return {\n success: true,\n generated: false,\n diff: existing === newContent ? \"(no changes)\" : newContent,\n context: ctx,\n };\n }\n\n // Check staleness\n // --smart always regenerates (user explicitly wants LLM synthesis)\n if (!flags.force && !flags.smart) {\n const staleness = checkStaleness(resolved, editor);\n if (staleness.status === \"fresh\") {\n // Check if context file is older than 1 hour — if so, regenerate\n if (staleness.generatedAt) {\n const ageMs = Date.now() - staleness.generatedAt.getTime();\n const ONE_HOUR = 60 * 60 * 1000;\n if (ageMs < ONE_HOUR) {\n return { success: true, generated: false, skippedReason: \"fresh\" };\n }\n } else {\n return { success: true, generated: false, skippedReason: \"fresh\" };\n }\n }\n }\n\n // Build context and write\n const ctx = await buildContext(stack, { smart: flags.smart });\n writeContextFile(ctx, resolved, editor);\n\n ensureGitignore(resolved, editor);\n\n return {\n success: true,\n generated: true,\n context: ctx,\n };\n}\n","import { Command } from \"commander\";\nimport * as p from \"@clack/prompts\";\nimport pc from \"picocolors\";\nimport { loadConfig, saveConfig, identityDir, rulesDir, workflowsDir, skillsDir, memoryDir, homeDir } from \"./config.js\";\nimport { migrateIfNeeded } from \"./migrate.js\";\nimport { assembleSystemPrompt, getProfileAiName } from \"./prompt.js\";\nimport { pickLLMClient } from \"./llm/index.js\";\nimport { isClaudeCliInstalled } from \"./llm/claude-code.js\";\nimport { isCopilotCliInstalled, isCopilotCliAuthenticated } from \"./llm/copilot.js\";\nimport { McpManager } from \"./mcp/client.js\";\nimport { runAgent } from \"./agent.js\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { applyPreset, PRESETS, type PresetName } from \"./presets.js\";\nimport { initMemory, memoryConsolidate, isMemoryInitialized, setMemoryConfig } from \"./memory.js\";\nimport { hasUserIdentity, loadUserIdentity } from \"./user-identity.js\";\nimport { runOnboarding } from \"./onboarding.js\";\nimport { runServe } from \"./server/serve-command.js\";\n\ndeclare const __VERSION__: string;\n\ninterface AutoDetectedConfig {\n provider: \"anthropic\" | \"openai\" | \"ollama\" | \"claude-code\" | \"copilot\";\n apiKey: string;\n model: string;\n}\n\nasync function autoDetectConfig(): Promise<AutoDetectedConfig | null> {\n // Skip auto-detect if user just ran /reset config\n const reconfigMarker = path.join(homeDir(), \".reconfig\");\n if (fs.existsSync(reconfigMarker)) {\n fs.unlinkSync(reconfigMarker);\n return null; // Force interactive prompt\n }\n\n const anthropicKey = process.env.ANTHROPIC_API_KEY;\n if (anthropicKey) {\n return { provider: \"anthropic\", apiKey: anthropicKey, model: \"claude-sonnet-4-6\" };\n }\n const openaiKey = process.env.OPENAI_API_KEY;\n if (openaiKey) {\n return { provider: \"openai\", apiKey: openaiKey, model: \"gpt-4o\" };\n }\n // Check Ollama — verify it's running AND has at least one model\n try {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), 2000);\n const res = await fetch(\"http://localhost:11434/api/tags\", { signal: controller.signal });\n clearTimeout(timeout);\n if (res.ok) {\n const data = await res.json() as { models?: Array<{ name: string }> };\n const models = data.models || [];\n if (models.length > 0) {\n // Pick the first available model\n const modelName = models[0].name.replace(/:latest$/, \"\");\n return { provider: \"ollama\", apiKey: \"ollama\", model: modelName };\n }\n // Ollama running but no models downloaded — skip\n }\n } catch { /* Ollama not available */ }\n return null;\n}\n\nfunction bootstrapEcosystem(): boolean {\n const corePath = path.join(identityDir(), \"core.md\");\n if (fs.existsSync(corePath)) return false;\n\n fs.mkdirSync(identityDir(), { recursive: true });\n fs.writeFileSync(corePath, [\n \"# Aman\",\n \"\",\n \"## Personality\",\n \"Helpful, adaptive, and thoughtful. Matches the user's tone and needs.\",\n \"\",\n \"## Style\",\n \"Clear and concise. Prioritizes usefulness over verbosity.\",\n \"\",\n \"## Session\",\n \"_New companion — no prior sessions._\",\n ].join(\"\\n\"), \"utf-8\");\n\n const rulesPath = path.join(rulesDir(), \"rules.md\");\n if (!fs.existsSync(rulesPath)) {\n fs.mkdirSync(rulesDir(), { recursive: true });\n fs.writeFileSync(rulesPath, [\n \"# Guardrails\",\n \"\",\n \"## safety\",\n \"- Never execute destructive commands without explicit confirmation\",\n \"- Never expose API keys, passwords, or secrets in responses\",\n \"\",\n \"## behavior\",\n '- Be honest when uncertain — say \"I\\'m not sure\" rather than guessing',\n \"- Respect the user's preferences stored in memory\",\n ].join(\"\\n\"), \"utf-8\");\n }\n\n const flowPath = path.join(workflowsDir(), \"flow.md\");\n if (!fs.existsSync(flowPath)) {\n fs.mkdirSync(workflowsDir(), { recursive: true });\n fs.writeFileSync(flowPath, \"# Workflows\\n\\n_No workflows defined yet. Use /workflows add to create one._\\n\", \"utf-8\");\n }\n\n const skillPath = path.join(skillsDir(), \"skills.md\");\n if (!fs.existsSync(skillPath)) {\n fs.mkdirSync(skillsDir(), { recursive: true });\n fs.writeFileSync(skillPath, \"# Skills\\n\\n_No skills installed yet. Use /skills install to add domain expertise._\\n\", \"utf-8\");\n }\n\n return true;\n}\n\nconst program = new Command();\n\nprogram\n .name(\"aman-agent\")\n .description(\"Your AI companion, running locally\")\n .version(__VERSION__)\n .option(\"--model <model>\", \"Override LLM model\")\n .option(\"--budget <tokens>\", \"Token budget for system prompt (default: 8000)\", parseInt)\n .option(\"--profile <name>\", \"Use a specific agent profile (e.g., coder, writer, researcher)\")\n .action(async (options) => {\n p.intro(pc.bold(\"aman agent\") + pc.dim(\" — your AI companion\"));\n\n // Setup config if needed\n let config = loadConfig();\n if (!config) {\n const detected = await autoDetectConfig();\n if (detected) {\n config = detected;\n const providerLabel =\n detected.provider === \"anthropic\" ? \"Anthropic API key\" :\n detected.provider === \"openai\" ? \"OpenAI API key\" : \"Ollama\";\n p.log.success(`Auto-detected ${providerLabel}. Using ${pc.bold(detected.model)}.`);\n p.log.info(pc.dim(\"Change anytime with /reset config\"));\n saveConfig(config);\n } else {\n // Non-interactive (systemd, Docker without -it, CI) — fail clearly\n if (!process.stdin.isTTY) {\n console.error(\"Error: No LLM provider configured.\");\n console.error(\"Set ANTHROPIC_API_KEY or OPENAI_API_KEY, or run interactively: aman-agent\");\n process.exit(1);\n }\n\n p.log.info(\"First-time setup — configure your LLM connection.\");\n\n const provider = (await p.select({\n message: \"LLM provider\",\n options: [\n {\n value: \"claude-code\",\n label: \"Claude (Anthropic)\",\n hint: \"recommended\",\n },\n {\n value: \"copilot\",\n label: \"GitHub Copilot\",\n hint: \"uses GitHub Models\",\n },\n { value: \"openai\", label: \"GPT (OpenAI)\" },\n { value: \"ollama\", label: \"Ollama (local)\", hint: \"free, runs offline\" },\n ],\n initialValue: \"claude-code\",\n })) as \"openai\" | \"ollama\" | \"claude-code\" | \"copilot\";\n if (p.isCancel(provider)) process.exit(0);\n\n let apiKey = \"\";\n let defaultModel = \"\";\n\n if (provider === \"ollama\") {\n apiKey = \"ollama\";\n const modelInput = (await p.text({\n message: \"Ollama model name\",\n placeholder: \"llama3.2\",\n defaultValue: \"llama3.2\",\n })) as string;\n if (p.isCancel(modelInput)) process.exit(0);\n defaultModel = modelInput || \"llama3.2\";\n } else if (provider === \"claude-code\") {\n // Claude via Claude Code CLI — handles subscription, API, and 3rd-party auth\n p.note(\n [\n `${pc.bold(\"Claude Plans:\")}`,\n \"\",\n ` ${pc.cyan(\"Free\")} $0/mo Basic access`,\n ` ${pc.cyan(\"Pro\")} $20/mo Full models + Claude Code`,\n ` ${pc.cyan(\"Max 5x\")} $100/mo 5× usage + Claude Code`,\n ` ${pc.cyan(\"Max 20x\")} $200/mo 20× usage + Opus 4.6 + 1M context`,\n ` ${pc.cyan(\"Team\")} $25+/seat Collaborative workspace`,\n ` ${pc.cyan(\"Enterprise\")} Custom SSO, admin, dedicated support`,\n \"\",\n `${pc.dim(\"Authentication is handled by Claude Code CLI.\")}`,\n `${pc.dim(\"Supports: subscription, API billing, Bedrock, Vertex AI.\")}`,\n ].join(\"\\n\"),\n \"Claude Plans\",\n );\n\n // Check if claude CLI is installed\n if (!isClaudeCliInstalled()) {\n p.log.error(\"Claude Code CLI is not installed.\");\n p.log.info(\"Install it with:\");\n p.log.step(pc.bold(\"npm install -g @anthropic-ai/claude-code\"));\n p.log.info(pc.dim(\"Then re-run aman-agent to continue setup.\"));\n process.exit(1);\n }\n\n p.log.success(\"Claude Code CLI detected.\");\n\n // Check auth / offer login\n const authAction = (await p.select({\n message: \"Authentication\",\n options: [\n { value: \"logged-in\", label: \"Already logged in to Claude Code\" },\n { value: \"login\", label: \"Log in now\", hint: \"runs: claude login\" },\n ],\n })) as string;\n if (p.isCancel(authAction)) process.exit(0);\n\n if (authAction === \"login\") {\n p.log.step(\"Launching Claude Code login...\");\n const { spawnSync } = await import(\"node:child_process\");\n const loginResult = spawnSync(\"claude\", [\"login\"], {\n stdio: \"inherit\",\n });\n if (loginResult.status !== 0) {\n p.log.error(\"Login failed or was cancelled. Please try again.\");\n process.exit(1);\n }\n p.log.success(\"Login successful.\");\n }\n\n apiKey = \"claude-code\"; // Sentinel — auth handled by CLI\n\n const modelChoice = (await p.select({\n message: \"Claude model\",\n options: [\n { value: \"claude-sonnet-4-6\", label: \"Claude Sonnet 4.6\", hint: \"fast, recommended\" },\n { value: \"claude-opus-4-6\", label: \"Claude Opus 4.6\", hint: \"most capable\" },\n { value: \"claude-haiku-4-5-20251001\", label: \"Claude Haiku 4.5\", hint: \"fastest\" },\n { value: \"custom\", label: \"Custom model ID\" },\n ],\n initialValue: \"claude-sonnet-4-6\",\n })) as string;\n if (p.isCancel(modelChoice)) process.exit(0);\n\n if (modelChoice === \"custom\") {\n const customModel = (await p.text({\n message: \"Model ID\",\n placeholder: \"claude-sonnet-4-6\",\n validate: (v) => v.length === 0 ? \"Model ID is required\" : undefined,\n })) as string;\n if (p.isCancel(customModel)) process.exit(0);\n defaultModel = customModel;\n } else {\n defaultModel = modelChoice;\n }\n } else if (provider === \"copilot\") {\n // GitHub Copilot via Copilot CLI\n p.note(\n [\n `${pc.bold(\"GitHub Copilot Plans:\")}`,\n \"\",\n ` ${pc.cyan(\"Free\")} $0/mo 2,000 code completions + 50 chat msgs`,\n ` ${pc.cyan(\"Pro\")} $10/mo Unlimited completions + chat`,\n ` ${pc.cyan(\"Pro+\")} $39/mo Unlimited + Opus/o1 + agent mode`,\n ` ${pc.cyan(\"Business\")} $19/user/mo Team admin + policy controls`,\n ` ${pc.cyan(\"Enterprise\")} $39/user/mo SSO, audit logs, IP indemnity`,\n \"\",\n `${pc.dim(\"Authentication is handled by the Copilot CLI.\")}`,\n `${pc.dim(\"Subscribe at: https://github.com/features/copilot\")}`,\n ].join(\"\\n\"),\n \"Copilot Plans\",\n );\n\n // Check if copilot CLI is installed\n if (!isCopilotCliInstalled()) {\n p.log.error(\"Copilot CLI is not installed.\");\n p.log.info(\"Install it from:\");\n p.log.step(pc.bold(\"https://docs.github.com/copilot/how-tos/copilot-cli\"));\n p.log.info(pc.dim(\"Then re-run aman-agent to continue setup.\"));\n process.exit(1);\n }\n\n p.log.success(\"Copilot CLI detected.\");\n\n // Check auth / offer login\n const copilotAuth = isCopilotCliAuthenticated();\n if (copilotAuth) {\n p.log.success(\"Copilot authentication found.\");\n } else {\n p.log.warn(\"Not logged in to Copilot.\");\n const authAction = (await p.select({\n message: \"Authentication\",\n options: [\n { value: \"login\", label: \"Log in now\", hint: \"runs: copilot login\" },\n { value: \"skip\", label: \"Skip (I'll log in later)\" },\n ],\n })) as string;\n if (p.isCancel(authAction)) process.exit(0);\n\n if (authAction === \"login\") {\n p.log.step(\"Launching Copilot login...\");\n const { spawnSync } = await import(\"node:child_process\");\n const loginResult = spawnSync(\"copilot\", [\"login\"], {\n stdio: \"inherit\",\n });\n if (loginResult.status !== 0) {\n p.log.error(\"Login failed or was cancelled.\");\n process.exit(1);\n }\n p.log.success(\"Copilot login successful.\");\n }\n }\n\n apiKey = \"copilot\"; // Sentinel — auth handled by CLI\n\n const modelChoice = (await p.select({\n message: \"Model\",\n options: [\n { value: \"default\", label: \"Default\", hint: \"Copilot's default model\" },\n { value: \"gpt-4o\", label: \"GPT-4o\", hint: \"fast\" },\n { value: \"gpt-5.2\", label: \"GPT-5.2\", hint: \"most capable\" },\n { value: \"o3-mini\", label: \"o3-mini\", hint: \"reasoning\" },\n { value: \"custom\", label: \"Custom model ID\" },\n ],\n initialValue: \"default\",\n })) as string;\n if (p.isCancel(modelChoice)) process.exit(0);\n\n if (modelChoice === \"custom\") {\n const customModel = (await p.text({\n message: \"Model ID (run copilot --help for available models)\",\n placeholder: \"gpt-4o\",\n validate: (v) => v.length === 0 ? \"Model ID is required\" : undefined,\n })) as string;\n if (p.isCancel(customModel)) process.exit(0);\n defaultModel = customModel;\n } else if (modelChoice === \"default\") {\n defaultModel = \"\";\n } else {\n defaultModel = modelChoice;\n }\n } else {\n // OpenAI\n apiKey = (await p.text({\n message: \"API key\",\n validate: (v) => v.length === 0 ? \"API key is required\" : undefined,\n })) as string;\n if (p.isCancel(apiKey)) process.exit(0);\n\n const modelChoice = (await p.select({\n message: \"OpenAI model\",\n options: [\n { value: \"gpt-4o\", label: \"GPT-4o\", hint: \"recommended\" },\n { value: \"gpt-4o-mini\", label: \"GPT-4o Mini\", hint: \"faster, cheaper\" },\n { value: \"o3\", label: \"o3\", hint: \"reasoning model\" },\n { value: \"custom\", label: \"Custom model ID\" },\n ],\n initialValue: \"gpt-4o\",\n })) as string;\n if (p.isCancel(modelChoice)) process.exit(0);\n\n if (modelChoice === \"custom\") {\n const customModel = (await p.text({\n message: \"Model ID\",\n placeholder: \"gpt-4o\",\n validate: (v) => v.length === 0 ? \"Model ID is required\" : undefined,\n })) as string;\n if (p.isCancel(customModel)) process.exit(0);\n defaultModel = customModel;\n } else {\n defaultModel = modelChoice;\n }\n }\n\n config = { provider, apiKey, model: defaultModel };\n saveConfig(config);\n p.log.success(\"Config saved to ~/.aman-agent/config.json\");\n }\n }\n\n // Override model if specified\n const model = options.model || config.model;\n\n // Spinner: bootstrap ecosystem + load system prompt\n const s = p.spinner();\n s.start(\"Loading ecosystem\");\n\n // Migrate old scattered directories to consolidated layout\n const migration = migrateIfNeeded();\n if (migration.migrated.length > 0) {\n for (const dir of migration.migrated) {\n p.log.info(`Migrated → ~/.aman-agent/${dir}/`);\n }\n }\n\n // Point ecosystem libs at consolidated layout\n process.env.ACORE_HOME = identityDir();\n process.env.ARULES_HOME = rulesDir();\n process.env.AMEM_DIR = memoryDir();\n\n const isFirstRun = bootstrapEcosystem();\n\n // User onboarding — runs once on first launch\n if (!hasUserIdentity()) {\n s.stop(\"Ecosystem loaded\");\n const user = await runOnboarding();\n if (!user) {\n p.log.info(\"Skipped profile setup. You can set it up later with /profile edit\");\n }\n s.start(\"Loading ecosystem\");\n }\n\n // Resolve profile\n const profile = options.profile || process.env.AMAN_PROFILE || undefined;\n if (profile) {\n p.log.info(`Profile: ${pc.bold(profile)}`);\n }\n\n // Assemble system prompt from ecosystem with token budget\n const budget = options.budget || undefined;\n const { prompt: systemPrompt, layers, truncated, totalTokens } = assembleSystemPrompt(budget, profile);\n\n s.stop(\"Ecosystem loaded\");\n\n if (layers.length === 0) {\n p.log.warning(\n \"No ecosystem configured. Run \" +\n pc.bold(\"npx @aman_asmuei/aman\") +\n \" first.\",\n );\n p.log.info(\"Starting with empty system prompt.\");\n } else {\n p.log.success(\n `Loaded: ${layers.join(\", \")} ${pc.dim(`(${totalTokens.toLocaleString()} tokens)`)}`,\n );\n if (truncated.length > 0) {\n p.log.warning(`Truncated: ${truncated.join(\", \")} ${pc.dim(\"(over budget)\")}`);\n }\n }\n\n // Extract AI name from core.md\n const aiName = getProfileAiName(profile);\n\n // Initialize memory (in-process, replaces amem MCP)\n if (config.memory) setMemoryConfig(config.memory);\n try {\n await initMemory();\n } catch (err) {\n p.log.warning(`Memory initialization failed: ${err instanceof Error ? err.message : String(err)}`);\n }\n\n // Memory consolidation (in-process via amem-core)\n if (isMemoryInitialized()) {\n const memSpinner = p.spinner();\n memSpinner.start(\"Consolidating memory\");\n try {\n const report = memoryConsolidate();\n memSpinner.stop(\"Memory consolidated\");\n if (report.merged > 0 || report.pruned > 0 || report.promoted > 0) {\n p.log.info(\n `Memory health: ${report.healthScore ?? \"?\"}% ` +\n pc.dim(`(merged ${report.merged}, pruned ${report.pruned}, promoted ${report.promoted})`),\n );\n }\n } catch {\n memSpinner.stop(\"Memory consolidation skipped\");\n }\n }\n\n // Start MCP servers\n const mcpManager = new McpManager();\n\n const mcpSpinner = p.spinner();\n mcpSpinner.start(\"Connecting to MCP servers\");\n\n // Core MCP servers (always connect) + custom servers — all in parallel\n const connections: Promise<void>[] = [\n mcpManager.connect(\"aman\", \"npx\", [\"-y\", \"@aman_asmuei/aman-mcp\"]),\n ];\n if (config.mcpServers) {\n for (const [name, serverConfig] of Object.entries(config.mcpServers)) {\n if (name === \"aman\" || name === \"amem\") continue;\n connections.push(mcpManager.connect(name, serverConfig.command, serverConfig.args, serverConfig.env));\n }\n }\n await Promise.all(connections);\n\n const mcpTools = mcpManager.getTools();\n\n mcpSpinner.stop(\"MCP connected\");\n\n if (mcpTools.length > 0) {\n p.log.success(`${mcpTools.length} MCP tools available`);\n } else {\n p.log.info(\n \"No MCP tools connected (install aman-mcp for tool support)\",\n );\n }\n\n // Convert ToolDef[] to ToolDefinition[] for the LLM\n const toolDefs = mcpTools.map((t) => ({\n name: t.name,\n description: t.description,\n input_schema: t.input_schema,\n }));\n\n // Create LLM client\n const client = pickLLMClient(config, model);\n\n const userIdentity = loadUserIdentity();\n if (userIdentity) {\n p.log.success(`${pc.bold(aiName)} is ready for ${pc.bold(userIdentity.name)}. Model: ${pc.dim(model)}`);\n } else {\n p.log.success(`${pc.bold(aiName)} is ready. Model: ${pc.dim(model)}`);\n }\n\n // Run the agent\n await runAgent(\n client,\n systemPrompt,\n aiName,\n model,\n toolDefs.length > 0 ? toolDefs : undefined,\n toolDefs.length > 0 ? mcpManager : undefined,\n config.hooks,\n );\n\n // Cleanup on exit\n await mcpManager.disconnect();\n });\n\nprogram\n .command(\"init\")\n .description(\"Set up your AI companion with a guided wizard\")\n .action(async () => {\n p.intro(pc.bold(\"aman agent init\") + pc.dim(\" — set up your companion\"));\n\n const name = (await p.text({\n message: \"What should your companion be called?\",\n placeholder: \"Aman\",\n defaultValue: \"Aman\",\n })) as string;\n if (p.isCancel(name)) process.exit(0);\n\n const preset = (await p.select({\n message: \"What kind of companion do you need?\",\n options: [\n { value: \"coding\", label: \"Coding Partner\", hint: \"direct, technical, concise\" },\n { value: \"creative\", label: \"Creative Collaborator\", hint: \"warm, imaginative\" },\n { value: \"assistant\", label: \"Personal Assistant\", hint: \"organized, action-oriented\" },\n { value: \"learning\", label: \"Learning Buddy\", hint: \"patient, Socratic\" },\n { value: \"minimal\", label: \"Minimal\", hint: \"just chat, I'll customize later\" },\n ],\n initialValue: \"coding\",\n })) as PresetName;\n if (p.isCancel(preset)) process.exit(0);\n\n const result = applyPreset(preset, name || \"Aman\");\n\n fs.mkdirSync(identityDir(), { recursive: true });\n fs.writeFileSync(path.join(identityDir(), \"core.md\"), result.coreMd, \"utf-8\");\n p.log.success(`Identity created — ${PRESETS[preset].identity.personality.split(\".\")[0].toLowerCase()}`);\n\n if (result.rulesMd) {\n fs.mkdirSync(rulesDir(), { recursive: true });\n fs.writeFileSync(path.join(rulesDir(), \"rules.md\"), result.rulesMd, \"utf-8\");\n const ruleCount = (result.rulesMd.match(/^- /gm) || []).length;\n p.log.success(`${ruleCount} rules set`);\n }\n\n if (result.flowMd) {\n fs.mkdirSync(workflowsDir(), { recursive: true });\n fs.writeFileSync(path.join(workflowsDir(), \"flow.md\"), result.flowMd, \"utf-8\");\n const wfCount = (result.flowMd.match(/^## /gm) || []).length;\n p.log.success(`${wfCount} workflow${wfCount > 1 ? \"s\" : \"\"} added`);\n }\n\n // Detect if running via npx (temp install)\n const isNpx = process.argv[1]?.includes(\"_npx\") || !process.argv[1]?.includes(\"node_modules/.bin\");\n\n p.outro(\"Your companion is ready.\");\n\n console.log(\"\");\n if (isNpx) {\n console.log(` ${pc.bold(\"Start chatting:\")} npx @aman_asmuei/aman-agent`);\n console.log(\"\");\n console.log(` ${pc.dim(\"Tip: Install globally to use\")} ${pc.bold(\"aman-agent\")} ${pc.dim(\"directly:\")}`);\n console.log(` ${pc.dim(\" npm install -g @aman_asmuei/aman-agent\")}`);\n } else {\n console.log(` ${pc.bold(\"Start chatting:\")} aman-agent`);\n }\n console.log(\"\");\n console.log(` ${pc.dim(\"Add tools:\")} npx @aman_asmuei/akit add github`);\n console.log(` ${pc.dim(\"Browse:\")} npx @aman_asmuei/akit search <query>`);\n console.log(\"\");\n });\n\nprogram\n .command(\"serve\")\n .description(\"Run aman-agent as a local MCP server other agents can delegate to\")\n .requiredOption(\"--name <name>\", \"Unique handle for @-mention (e.g. 'coder')\")\n .option(\"--profile <profile>\", \"Which profile to load\", \"default\")\n .action(async (opts) => {\n try {\n await runServe({ name: opts.name, profile: opts.profile });\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.error(pc.red(`aman-agent serve failed: ${msg}`));\n process.exit(1);\n }\n });\n\nprogram\n .command(\"dev [path]\")\n .description(\"Set up project context and launch your editor (Claude Code, Copilot, or Cursor)\")\n .option(\"--smart\", \"Use LLM to synthesize context file\")\n .option(\"--no-launch\", \"Generate context file only, don't launch editor\")\n .option(\"--force\", \"Regenerate even if context file is fresh\")\n .option(\"--diff\", \"Show what would change without writing\")\n .option(\"--yolo\", \"Launch with skip-permissions (Claude Code only)\")\n .option(\"--copilot\", \"Target GitHub Copilot (writes .github/copilot-instructions.md, opens VS Code)\")\n .option(\"--cursor\", \"Target Cursor editor (writes .cursorrules, opens Cursor)\")\n .action(async (projectPath: string | undefined, opts: Record<string, boolean>) => {\n const { runDev } = await import(\"./dev/dev-command.js\");\n const { scanStack } = await import(\"./dev/stack-detector.js\");\n const { EDITOR_TARGETS } = await import(\"./dev/claude-md-writer.js\");\n\n // Determine editor target\n const editorName = opts.copilot ? \"copilot\" as const : opts.cursor ? \"cursor\" as const : \"claude\" as const;\n const target = EDITOR_TARGETS[editorName];\n\n const targetPath = projectPath ?? process.cwd();\n const stack = scanStack(targetPath);\n\n // Print detection\n const stackParts = stack.languages.map((l: string) => l.charAt(0).toUpperCase() + l.slice(1));\n if (stack.frameworks.length > 0) {\n stackParts.push(`(${stack.frameworks.map((f: string) => f.charAt(0).toUpperCase() + f.slice(1)).join(\", \")})`);\n }\n if (stack.databases.length > 0) {\n stackParts.push(...stack.databases.map((d: string) => d.charAt(0).toUpperCase() + d.slice(1)));\n }\n if (stack.infra.length > 0) {\n stackParts.push(...stack.infra.map((i: string) => i.charAt(0).toUpperCase() + i.slice(1)));\n }\n\n if (stack.languages.length > 0) {\n console.log(`\\n ${pc.cyan(\"Detected:\")} ${stackParts.join(\" + \")}`);\n } else {\n console.log(`\\n ${pc.dim(\"No stack detected — generating minimal context\")}`);\n }\n\n const result = await runDev(targetPath, {\n smart: opts.smart,\n noLaunch: opts.launch === false,\n force: opts.force,\n diff: opts.diff,\n editor: editorName,\n }, stack);\n\n if (!result.success) {\n console.error(` ${pc.red(\"Error:\")} ${result.error}`);\n process.exit(1);\n }\n\n if (result.diff) {\n console.log(`\\n${result.diff}`);\n return;\n }\n\n if (result.generated) {\n const mode = opts.smart ? \"smart\" : \"template\";\n const memCount = result.context?.metadata.memoriesUsed ?? 0;\n console.log(` ${pc.cyan(\"Recalled:\")} ${memCount} memories`);\n console.log(` ${pc.green(\"✓\")} ${target.contextFile} written (${mode} mode)\\n`);\n } else if (result.skippedReason === \"fresh\") {\n console.log(` ${pc.green(\"✓\")} ${target.contextFile} is up to date\\n`);\n }\n\n // Launch editor\n if (opts.launch !== false && !opts.diff) {\n const { execFileSync } = await import(\"node:child_process\");\n try {\n execFileSync(\"which\", [target.launchCmd], { stdio: \"ignore\" });\n } catch {\n console.log(` ${pc.yellow(`${target.displayName} not found.`)} Ensure '${target.launchCmd}' is in your PATH.`);\n process.exit(1);\n }\n const launchArgs = [...target.launchArgs];\n if (opts.yolo && target.yoloArgs) {\n launchArgs.push(...target.yoloArgs);\n console.log(` ${pc.cyan(`Launching ${target.displayName}`)} ${pc.yellow(\"(skip-permissions)\")}...\\n`);\n } else {\n console.log(` ${pc.cyan(`Launching ${target.displayName}...`)}\\n`);\n }\n execFileSync(target.launchCmd, launchArgs, { cwd: targetPath, stdio: \"inherit\" });\n }\n });\n\nprogram\n .command(\"setup\")\n .description(\"Run the full configuration wizard (provider, identity, presets)\")\n .action(async () => {\n p.intro(pc.bold(\"aman agent setup\") + pc.dim(\" — full configuration wizard\"));\n\n // Create .reconfig marker to force interactive provider selection on next run\n const reconfigPath = path.join(homeDir(), \".reconfig\");\n fs.mkdirSync(homeDir(), { recursive: true });\n fs.writeFileSync(reconfigPath, \"\", \"utf-8\");\n\n p.log.info(\"Configuration reset. Restart aman-agent to complete setup.\");\n });\n\nprogram\n .command(\"update\")\n .description(\"Update aman-agent to the latest version\")\n .action(async () => {\n const { execFileSync } = await import(\"node:child_process\");\n const isVendored = process.execPath.includes(path.join(\".aman-agent\", \"node\"));\n\n if (isVendored) {\n const npmPath = path.join(homeDir(), \"node\", \"bin\", \"npm\");\n console.log(\"Updating aman-agent...\");\n try {\n execFileSync(npmPath, [\"install\", \"-g\", \"@aman_asmuei/aman-agent@latest\"], {\n stdio: \"inherit\",\n env: { ...process.env, PREFIX: homeDir() },\n });\n console.log(\"✓ Updated successfully.\");\n } catch {\n console.error(\"Update failed. Try manually: npm install -g @aman_asmuei/aman-agent@latest\");\n process.exit(1);\n }\n } else {\n console.log(\"Updating via npm...\");\n try {\n execFileSync(\"npm\", [\"install\", \"-g\", \"@aman_asmuei/aman-agent@latest\"], {\n stdio: \"inherit\",\n });\n console.log(\"✓ Updated successfully.\");\n } catch {\n console.error(\"Update failed. Try manually: npm install -g @aman_asmuei/aman-agent@latest\");\n process.exit(1);\n }\n }\n });\n\nprogram\n .command(\"uninstall\")\n .description(\"Remove aman-agent and all its data\")\n .action(async () => {\n const home = homeDir();\n\n if (!process.stdin.isTTY) {\n fs.rmSync(home, { recursive: true, force: true });\n console.log(\"✓ Removed \" + home);\n return;\n }\n\n const confirm = await p.confirm({\n message: `This will delete ${home} and all your data (memory, identity, config). Continue?`,\n });\n if (!confirm || p.isCancel(confirm)) {\n console.log(\"Cancelled.\");\n return;\n }\n\n fs.rmSync(home, { recursive: true, force: true });\n console.log(\"✓ Removed \" + home);\n console.log(\"\");\n console.log(\"To complete uninstall, remove the PATH line from your shell config:\");\n console.log(' Remove: export PATH=\"$HOME/.aman-agent/bin:$PATH\"');\n });\n\nprogram.parse();\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport os from \"node:os\";\n\nexport interface HooksConfig {\n memoryRecall?: boolean;\n sessionResume?: boolean;\n rulesCheck?: boolean;\n workflowSuggest?: boolean;\n evalPrompt?: boolean;\n autoSessionSave?: boolean;\n extractMemories?: boolean;\n featureHints?: boolean;\n personalityAdapt?: boolean;\n recordObservations?: boolean;\n autoPostmortem?: boolean;\n}\n\nconst DEFAULT_HOOKS: HooksConfig = {\n memoryRecall: true,\n sessionResume: true,\n rulesCheck: true,\n workflowSuggest: true,\n evalPrompt: true,\n autoSessionSave: true,\n extractMemories: true,\n featureHints: true,\n personalityAdapt: true,\n};\n\nexport interface McpServerEntry {\n command: string;\n args: string[];\n env?: Record<string, string>;\n}\n\nexport interface MemoryConfig {\n maxStaleDays?: number;\n minConfidence?: number;\n minAccessCount?: number;\n maxRecallTokens?: number;\n}\n\nexport interface AgentConfig {\n provider: \"anthropic\" | \"openai\" | \"ollama\" | \"claude-code\" | \"copilot\";\n apiKey: string;\n model: string;\n ollamaUrl?: string;\n maxOutputTokens?: number;\n hooks?: HooksConfig;\n mcpServers?: Record<string, McpServerEntry>;\n memory?: MemoryConfig;\n orchestrator?: {\n maxParallelTasks?: number;\n defaultTier?: \"fast\" | \"standard\" | \"advanced\";\n requireApprovalForPhaseTransition?: boolean;\n taskTimeoutMs?: number;\n orchestrationTimeoutMs?: number;\n };\n github?: {\n defaultRepo?: string; // owner/repo format\n defaultBranch?: string; // default: \"main\"\n autoCreatePR?: boolean; // auto-create PR after orchestration\n ciGateEnabled?: boolean; // wait for CI before merging\n };\n}\n\n/**\n * Resolve the aman-agent home directory.\n * Priority: $AMAN_HOME > $AMAN_AGENT_HOME > ~/.aman-agent\n *\n * Previously `configDir()` was the sole entry point and only checked\n * `AMAN_AGENT_HOME`. Now `homeDir()` is canonical, and `configDir()`\n * delegates to it. Recorded as feedback memory\n * `feedback_aman_agent_hermetic_tests.md`.\n */\nexport function homeDir(): string {\n return process.env.AMAN_HOME || process.env.AMAN_AGENT_HOME || path.join(os.homedir(), \".aman-agent\");\n}\n\nexport function identityDir(): string { return path.join(homeDir(), \"identity\"); }\nexport function rulesDir(): string { return path.join(homeDir(), \"rules\"); }\nexport function memoryDir(): string { return path.join(homeDir(), \"memory\"); }\nexport function workflowsDir(): string { return path.join(homeDir(), \"workflows\"); }\nexport function skillsDir(): string { return path.join(homeDir(), \"skills\"); }\nexport function evalDir(): string { return path.join(homeDir(), \"eval\"); }\n\nfunction configDir(): string {\n return homeDir();\n}\n\nfunction configPath(): string {\n return path.join(configDir(), \"config.json\");\n}\n\nexport function loadConfig(): AgentConfig | null {\n const p = configPath();\n if (!fs.existsSync(p)) return null;\n try {\n const raw = JSON.parse(fs.readFileSync(p, \"utf-8\")) as AgentConfig;\n raw.hooks = { ...DEFAULT_HOOKS, ...raw.hooks };\n return raw;\n } catch {\n return null;\n }\n}\n\nexport function saveConfig(config: AgentConfig): void {\n fs.mkdirSync(configDir(), { recursive: true });\n fs.writeFileSync(\n configPath(),\n JSON.stringify(config, null, 2) + \"\\n\",\n \"utf-8\",\n );\n}\n\nexport function configExists(): boolean {\n return fs.existsSync(configPath());\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport os from \"node:os\";\nimport { homeDir } from \"./config.js\";\n\ninterface MigrationResult {\n migrated: string[];\n}\n\nconst MIGRATION_MAP: Array<{ oldName: string; newSubdir: string }> = [\n { oldName: \".acore\", newSubdir: \"identity\" },\n { oldName: \".arules\", newSubdir: \"rules\" },\n { oldName: \".aflow\", newSubdir: \"workflows\" },\n { oldName: \".askill\", newSubdir: \"skills\" },\n { oldName: \".amem\", newSubdir: \"memory\" },\n { oldName: \".aeval\", newSubdir: \"eval\" },\n];\n\n/**\n * Migrate old scattered dot-directories into the consolidated ~/.aman-agent/ layout.\n * Safe: skips if new directory already has content, idempotent.\n */\nexport function migrateIfNeeded(): MigrationResult {\n const home = os.homedir();\n const target = homeDir();\n const migrated: string[] = [];\n\n for (const { oldName, newSubdir } of MIGRATION_MAP) {\n const oldDir = path.join(home, oldName);\n const newDir = path.join(target, newSubdir);\n\n if (!fs.existsSync(oldDir)) continue;\n if (fs.existsSync(newDir) && fs.readdirSync(newDir).length > 0) continue;\n\n fs.mkdirSync(newDir, { recursive: true });\n for (const entry of fs.readdirSync(oldDir)) {\n fs.renameSync(path.join(oldDir, entry), path.join(newDir, entry));\n }\n\n fs.rmSync(oldDir, { recursive: true, force: true });\n migrated.push(newSubdir);\n }\n\n return { migrated };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport os from \"node:os\";\nimport { estimateTokens, buildBudgetedPrompt } from \"./token-budget.js\";\nimport type { PromptComponent } from \"./token-budget.js\";\nimport { loadUserIdentity, formatUserContext } from \"./user-identity.js\";\n\ninterface EcosystemFile {\n name: string;\n dir: string;\n file: string;\n profileOverridable?: boolean; // can be overridden by profile-specific file\n}\n\nconst ECOSYSTEM_FILES: EcosystemFile[] = [\n { name: \"identity\", dir: \".acore\", file: \"core.md\", profileOverridable: true },\n { name: \"tools\", dir: \".akit\", file: \"kit.md\" },\n { name: \"workflows\", dir: \".aflow\", file: \"flow.md\" },\n { name: \"guardrails\", dir: \".arules\", file: \"rules.md\", profileOverridable: true },\n { name: \"skills\", dir: \".askill\", file: \"skills.md\", profileOverridable: true },\n];\n\n/**\n * Resolve the file path for an ecosystem layer, checking profile override first.\n */\nfunction resolveLayerPath(entry: EcosystemFile, home: string, profile?: string): string | null {\n // Check profile-specific override first\n if (profile && entry.profileOverridable) {\n const profilePath = path.join(home, \".acore\", \"profiles\", profile, entry.file);\n if (fs.existsSync(profilePath)) return profilePath;\n\n // For rules/skills, also check profile dir with original filename\n if (entry.name === \"guardrails\") {\n const altPath = path.join(home, \".acore\", \"profiles\", profile, \"rules.md\");\n if (fs.existsSync(altPath)) return altPath;\n }\n if (entry.name === \"skills\") {\n const altPath = path.join(home, \".acore\", \"profiles\", profile, \"skills.md\");\n if (fs.existsSync(altPath)) return altPath;\n }\n }\n\n // Fall back to global path\n const globalPath = path.join(home, entry.dir, entry.file);\n if (fs.existsSync(globalPath)) return globalPath;\n\n return null;\n}\n\nexport function assembleSystemPrompt(\n maxTokens?: number,\n profile?: string,\n): {\n prompt: string;\n layers: string[];\n truncated: string[];\n totalTokens: number;\n profile?: string;\n} {\n const home = os.homedir();\n const components: PromptComponent[] = [];\n\n for (const entry of ECOSYSTEM_FILES) {\n const filePath = resolveLayerPath(entry, home, profile);\n if (filePath) {\n const content = fs.readFileSync(filePath, \"utf-8\").trim();\n components.push({\n name: entry.name,\n content,\n tokens: estimateTokens(content),\n });\n }\n }\n\n // Project context (not prioritized — appended as extra)\n const contextPath = path.join(process.cwd(), \".acore\", \"context.md\");\n if (fs.existsSync(contextPath)) {\n const content = fs.readFileSync(contextPath, \"utf-8\").trim();\n components.push({\n name: \"context\",\n content,\n tokens: estimateTokens(content),\n });\n }\n\n // User identity — always included if available (high priority, low token cost)\n const userIdentity = loadUserIdentity();\n if (userIdentity) {\n const userContent = formatUserContext(userIdentity);\n components.push({\n name: \"user\",\n content: userContent,\n tokens: estimateTokens(userContent),\n });\n }\n\n const budgeted = buildBudgetedPrompt(components, maxTokens);\n\n return {\n prompt: budgeted.prompt,\n layers: budgeted.included,\n truncated: budgeted.truncated,\n totalTokens: budgeted.totalTokens,\n profile,\n };\n}\n\n/**\n * List available profiles.\n */\nexport function listProfiles(): Array<{ name: string; aiName: string; personality: string }> {\n const profilesDir = path.join(os.homedir(), \".acore\", \"profiles\");\n if (!fs.existsSync(profilesDir)) return [];\n\n const profiles: Array<{ name: string; aiName: string; personality: string }> = [];\n for (const entry of fs.readdirSync(profilesDir, { withFileTypes: true })) {\n if (!entry.isDirectory()) continue;\n const corePath = path.join(profilesDir, entry.name, \"core.md\");\n if (!fs.existsSync(corePath)) continue;\n\n const content = fs.readFileSync(corePath, \"utf-8\");\n const nameMatch = content.match(/^# (.+)/m);\n const personalityMatch = content.match(/- Personality:\\s*(.+)/);\n\n profiles.push({\n name: entry.name,\n aiName: nameMatch?.[1]?.trim() || entry.name,\n personality: personalityMatch?.[1]?.trim() || \"default\",\n });\n }\n\n return profiles;\n}\n\n/**\n * Get the AI name for a profile (or default).\n */\nexport function getProfileAiName(profile?: string): string {\n const home = os.homedir();\n let corePath: string;\n\n if (profile) {\n const profileCorePath = path.join(home, \".acore\", \"profiles\", profile, \"core.md\");\n corePath = fs.existsSync(profileCorePath) ? profileCorePath : path.join(home, \".acore\", \"core.md\");\n } else {\n corePath = path.join(home, \".acore\", \"core.md\");\n }\n\n if (!fs.existsSync(corePath)) return \"Assistant\";\n const content = fs.readFileSync(corePath, \"utf-8\");\n const match = content.match(/^# (.+)$/m);\n return match?.[1]?.trim() || \"Assistant\";\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { identityDir } from \"./config.js\";\n\nexport interface UserIdentity {\n name: string;\n role: \"developer\" | \"designer\" | \"student\" | \"manager\" | \"generalist\";\n roleLabel: string;\n expertise: \"beginner\" | \"intermediate\" | \"advanced\" | \"expert\";\n expertiseLabel: string;\n style: \"concise\" | \"balanced\" | \"thorough\" | \"socratic\";\n styleLabel: string;\n workingOn?: string;\n notes?: string;\n createdAt: string;\n updatedAt: string;\n}\n\nconst USER_FILE = path.join(identityDir(), \"user.md\");\n\n/**\n * Check if user identity exists.\n */\nexport function hasUserIdentity(): boolean {\n return fs.existsSync(USER_FILE);\n}\n\n/**\n * Load user identity from ~/.acore/user.md.\n * Returns null if file doesn't exist or is malformed.\n */\nexport function loadUserIdentity(): UserIdentity | null {\n if (!fs.existsSync(USER_FILE)) return null;\n\n try {\n const content = fs.readFileSync(USER_FILE, \"utf-8\");\n\n const get = (key: string): string => {\n const match = content.match(new RegExp(`^- ${key}:\\\\s*(.+)$`, \"m\"));\n return match?.[1]?.trim() ?? \"\";\n };\n\n const getSection = (heading: string): string => {\n const pattern = new RegExp(`## ${heading}\\\\n([\\\\s\\\\S]*?)(?=\\\\n## |$)`);\n const match = content.match(pattern);\n if (!match) return \"\";\n // Strip leading \"- Key: value\" lines, return freeform text\n return match[1]\n .split(\"\\n\")\n .filter((line) => !line.startsWith(\"- \") && line.trim().length > 0)\n .join(\"\\n\")\n .trim();\n };\n\n const name = get(\"Name\");\n if (!name) return null;\n\n return {\n name,\n role: (get(\"Role\") || \"generalist\") as UserIdentity[\"role\"],\n roleLabel: get(\"Role Label\") || get(\"Role\") || \"Generalist\",\n expertise: (get(\"Expertise\") || \"intermediate\") as UserIdentity[\"expertise\"],\n expertiseLabel: get(\"Expertise Label\") || get(\"Expertise\") || \"Intermediate\",\n style: (get(\"Style\") || \"balanced\") as UserIdentity[\"style\"],\n styleLabel: get(\"Style Label\") || get(\"Style\") || \"Balanced\",\n workingOn: getSection(\"Working On\") || undefined,\n notes: getSection(\"Notes\") || undefined,\n createdAt: get(\"Created\") || new Date().toISOString().split(\"T\")[0],\n updatedAt: get(\"Updated\") || new Date().toISOString().split(\"T\")[0],\n };\n } catch {\n return null;\n }\n}\n\n/**\n * Save user identity to ~/.acore/user.md.\n */\nexport function saveUserIdentity(user: UserIdentity): void {\n const dir = path.dirname(USER_FILE);\n if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });\n\n const lines: string[] = [\n \"# User Profile\",\n \"\",\n \"## About\",\n `- Name: ${user.name}`,\n `- Role: ${user.role}`,\n `- Role Label: ${user.roleLabel}`,\n `- Expertise: ${user.expertise}`,\n `- Expertise Label: ${user.expertiseLabel}`,\n `- Style: ${user.style}`,\n `- Style Label: ${user.styleLabel}`,\n ];\n\n if (user.workingOn) {\n lines.push(\"\", \"## Working On\", user.workingOn);\n }\n\n if (user.notes) {\n lines.push(\"\", \"## Notes\", user.notes);\n }\n\n lines.push(\n \"\",\n \"## Meta\",\n `- Created: ${user.createdAt}`,\n `- Updated: ${user.updatedAt}`,\n );\n\n fs.writeFileSync(USER_FILE, lines.join(\"\\n\") + \"\\n\", \"utf-8\");\n}\n\n/**\n * Format user identity for injection into system prompt.\n */\nexport function formatUserContext(user: UserIdentity): string {\n const parts: string[] = [\n `<user-profile>`,\n `The person you're talking to:`,\n `- Name: ${user.name}`,\n `- Role: ${user.roleLabel}`,\n `- Expertise: ${user.expertiseLabel}`,\n ];\n\n // Style instructions\n switch (user.style) {\n case \"concise\":\n parts.push(\"- Prefers: short, direct answers. Code first, explain after. No fluff.\");\n break;\n case \"balanced\":\n parts.push(\"- Prefers: explain the reasoning briefly, then show the solution.\");\n break;\n case \"thorough\":\n parts.push(\"- Prefers: detailed explanations with context. Help them understand deeply.\");\n break;\n case \"socratic\":\n parts.push(\"- Prefers: ask guiding questions. Help them figure it out themselves.\");\n break;\n }\n\n // Expertise calibration\n switch (user.expertise) {\n case \"beginner\":\n parts.push(\"- Calibration: explain concepts clearly, define terms, show examples. Be patient.\");\n break;\n case \"intermediate\":\n parts.push(\"- Calibration: skip basic explanations, focus on the task. Explain non-obvious things.\");\n break;\n case \"advanced\":\n parts.push(\"- Calibration: be direct. Skip explanations unless asked. Focus on edge cases and trade-offs.\");\n break;\n case \"expert\":\n parts.push(\"- Calibration: peer-level discussion. Challenge assumptions. Focus on architecture and nuance.\");\n break;\n }\n\n if (user.workingOn) {\n parts.push(`- Currently working on: ${user.workingOn}`);\n }\n\n if (user.notes) {\n parts.push(`- Notes: ${user.notes}`);\n }\n\n parts.push(\n \"\",\n `Use their name naturally (not every message). Adapt to their level and style.`,\n `</user-profile>`,\n );\n\n return parts.join(\"\\n\");\n}\n","import Anthropic from \"@anthropic-ai/sdk\";\nimport type {\n LLMClient,\n Message,\n StreamChunk,\n ToolDefinition,\n ChatResponse,\n ChatOptions,\n ContentBlock,\n} from \"./types.js\";\n\nfunction toAnthropicMessages(\n messages: Message[],\n): Anthropic.Messages.MessageParam[] {\n return messages.map((m) => {\n if (typeof m.content === \"string\") {\n return { role: m.role, content: m.content };\n }\n // Complex content blocks (text, image, tool_use, tool_result)\n return {\n role: m.role,\n content: m.content.map((block) => {\n if (block.type === \"text\") {\n return { type: \"text\" as const, text: block.text };\n }\n if (block.type === \"image\") {\n return {\n type: \"image\" as const,\n source: {\n type: \"base64\" as const,\n media_type: block.source.media_type,\n data: block.source.data,\n },\n };\n }\n if (block.type === \"tool_use\") {\n return {\n type: \"tool_use\" as const,\n id: block.id,\n name: block.name,\n input: block.input,\n };\n }\n if (block.type === \"tool_result\") {\n return {\n type: \"tool_result\" as const,\n tool_use_id: block.tool_use_id,\n content: block.content,\n };\n }\n return { type: \"text\" as const, text: \"\" };\n }),\n };\n });\n}\n\nexport function createAnthropicClient(\n apiKey: string,\n model: string,\n): LLMClient {\n const client = new Anthropic({ apiKey });\n\n return {\n async chat(\n systemPrompt: string,\n messages: Message[],\n onChunk: (chunk: StreamChunk) => void,\n tools?: ToolDefinition[],\n options?: ChatOptions,\n ): Promise<ChatResponse> {\n const anthropicMessages = toAnthropicMessages(messages);\n const hasTools = tools && tools.length > 0;\n\n try {\n let fullText = \"\";\n const toolUseBlocks: Array<{\n id: string;\n name: string;\n inputJson: string;\n }> = [];\n let currentBlockType: \"text\" | \"tool_use\" | null = null;\n let currentBlockIndex = -1;\n\n const createParams: Record<string, unknown> = {\n model,\n max_tokens: options?.maxOutputTokens ?? 8192,\n system: systemPrompt,\n messages: anthropicMessages,\n stream: true,\n };\n\n if (hasTools) {\n createParams.tools = tools.map((t) => ({\n name: t.name,\n description: t.description,\n input_schema:\n t.input_schema as Anthropic.Messages.Tool[\"input_schema\"],\n }));\n }\n\n const stream = await client.messages.create(\n createParams as unknown as Anthropic.Messages.MessageCreateParamsStreaming,\n );\n\n for await (const event of stream) {\n if (event.type === \"content_block_start\") {\n currentBlockIndex = event.index;\n if (event.content_block.type === \"text\") {\n currentBlockType = \"text\";\n } else if (event.content_block.type === \"tool_use\") {\n currentBlockType = \"tool_use\";\n toolUseBlocks.push({\n id: event.content_block.id,\n name: event.content_block.name,\n inputJson: \"\",\n });\n }\n } else if (event.type === \"content_block_delta\") {\n if (\n currentBlockType === \"text\" &&\n event.delta.type === \"text_delta\"\n ) {\n const text = event.delta.text;\n fullText += text;\n onChunk({ type: \"text\", text });\n } else if (\n currentBlockType === \"tool_use\" &&\n event.delta.type === \"input_json_delta\"\n ) {\n const lastTool = toolUseBlocks[toolUseBlocks.length - 1];\n if (lastTool) {\n lastTool.inputJson += event.delta.partial_json;\n }\n }\n } else if (event.type === \"content_block_stop\") {\n currentBlockType = null;\n }\n }\n\n // Parse tool inputs from accumulated JSON\n const toolUses = toolUseBlocks.map((block) => ({\n id: block.id,\n name: block.name,\n input: (block.inputJson\n ? JSON.parse(block.inputJson)\n : {}) as Record<string, unknown>,\n }));\n\n // Signal done\n onChunk({ type: \"done\" });\n\n // Build content blocks for the message\n if (toolUses.length > 0) {\n const contentBlocks: ContentBlock[] = [];\n if (fullText) {\n contentBlocks.push({ type: \"text\" as const, text: fullText });\n }\n for (const tu of toolUses) {\n contentBlocks.push({\n type: \"tool_use\" as const,\n id: tu.id,\n name: tu.name,\n input: tu.input,\n });\n }\n return {\n message: { role: \"assistant\", content: contentBlocks },\n toolUses,\n };\n }\n\n return {\n message: { role: \"assistant\", content: fullText },\n toolUses: [],\n };\n } catch (error) {\n if (error instanceof Anthropic.AuthenticationError) {\n throw new Error(\n \"Invalid API key. Run with --model flag or delete ~/.aman-agent/config.json to reconfigure.\",\n );\n }\n if (error instanceof Anthropic.RateLimitError) {\n throw new Error(\"Rate limited by Anthropic. Please wait and retry.\");\n }\n throw error;\n }\n },\n };\n}\n","import { spawn, execFileSync } from \"node:child_process\";\nimport type {\n LLMClient,\n Message,\n StreamChunk,\n ToolDefinition,\n ChatResponse,\n ChatOptions,\n ContentBlock,\n} from \"./types.js\";\n\n/**\n * Check if the `claude` CLI is installed and accessible.\n */\nexport function isClaudeCliInstalled(): boolean {\n try {\n execFileSync(\"which\", [\"claude\"], { stdio: \"ignore\" });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Check if the `claude` CLI is authenticated (has an active session).\n */\nexport function isClaudeCliAuthenticated(): boolean {\n try {\n const result = execFileSync(\"claude\", [\"--version\"], {\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n timeout: 5000,\n });\n return result.toString().trim().length > 0;\n } catch {\n return false;\n }\n}\n\nfunction extractText(content: string | ContentBlock[]): string {\n if (typeof content === \"string\") return content;\n return content\n .map((block) => {\n if (block.type === \"text\") return block.text;\n if (block.type === \"tool_result\")\n return `[Tool result for ${block.tool_use_id}]: ${block.content}`;\n if (block.type === \"tool_use\") return `[Used tool: ${block.name}]`;\n return \"\";\n })\n .filter(Boolean)\n .join(\"\\n\");\n}\n\n/**\n * Format conversation history into a single prompt for the CLI.\n * The claude CLI in print mode is single-turn, so we flatten the\n * multi-turn conversation into context.\n */\nfunction formatConversation(\n systemPrompt: string,\n messages: Message[],\n tools?: ToolDefinition[],\n): { prompt: string; systemPrompt: string } {\n const parts: string[] = [];\n\n // Include tool definitions in context if present\n let fullSystem = systemPrompt;\n if (tools && tools.length > 0) {\n fullSystem += \"\\n\\n## Available Tools\\n\";\n fullSystem +=\n \"You have access to the following tools. To use a tool, respond with a JSON block in this exact format:\\n\";\n fullSystem +=\n '```json\\n{\"tool_use\": {\"id\": \"call_1\", \"name\": \"tool_name\", \"input\": {…}}}\\n```\\n\\n';\n for (const tool of tools) {\n fullSystem += `### ${tool.name}\\n${tool.description}\\nParameters: ${JSON.stringify(tool.input_schema)}\\n\\n`;\n }\n fullSystem +=\n \"You may include multiple tool_use blocks. After each tool use, you will receive the result and can continue.\\n\";\n }\n\n // Build conversation history (skip system, it goes via --system-prompt)\n if (messages.length > 1) {\n parts.push(\"<conversation_history>\");\n for (let i = 0; i < messages.length - 1; i++) {\n const msg = messages[i];\n const role = msg.role === \"user\" ? \"User\" : \"Assistant\";\n const text = extractText(msg.content);\n parts.push(`[${role}]: ${text}`);\n }\n parts.push(\"</conversation_history>\\n\");\n }\n\n // Last message is the current user prompt\n const lastMsg = messages[messages.length - 1];\n if (lastMsg) {\n parts.push(extractText(lastMsg.content));\n }\n\n return { prompt: parts.join(\"\\n\"), systemPrompt: fullSystem };\n}\n\n/**\n * Parse tool_use JSON blocks from the assistant's text response.\n */\nfunction parseToolUses(\n text: string,\n): Array<{ id: string; name: string; input: Record<string, unknown> }> {\n const toolUses: Array<{\n id: string;\n name: string;\n input: Record<string, unknown>;\n }> = [];\n\n // Match ```json blocks containing tool_use\n const codeBlockRegex = /```json\\s*\\n?([\\s\\S]*?)```/g;\n let match;\n while ((match = codeBlockRegex.exec(text)) !== null) {\n try {\n const parsed = JSON.parse(match[1].trim());\n if (parsed.tool_use) {\n toolUses.push({\n id: parsed.tool_use.id || `call_${toolUses.length + 1}`,\n name: parsed.tool_use.name,\n input: parsed.tool_use.input || {},\n });\n }\n } catch {\n // Not valid JSON, skip\n }\n }\n\n // Also match inline {\"tool_use\": ...} patterns\n if (toolUses.length === 0) {\n const inlineRegex =\n /\\{\"tool_use\"\\s*:\\s*\\{[^}]*\"name\"\\s*:\\s*\"[^\"]+?\"[^}]*\\}\\s*\\}/g;\n while ((match = inlineRegex.exec(text)) !== null) {\n try {\n const parsed = JSON.parse(match[0]);\n if (parsed.tool_use) {\n toolUses.push({\n id: parsed.tool_use.id || `call_${toolUses.length + 1}`,\n name: parsed.tool_use.name,\n input: parsed.tool_use.input || {},\n });\n }\n } catch {\n // Not valid JSON, skip\n }\n }\n }\n\n return toolUses;\n}\n\nexport function createClaudeCodeClient(model?: string): LLMClient {\n return {\n async chat(\n systemPrompt: string,\n messages: Message[],\n onChunk: (chunk: StreamChunk) => void,\n tools?: ToolDefinition[],\n options?: ChatOptions,\n ): Promise<ChatResponse> {\n const { prompt, systemPrompt: fullSystem } = formatConversation(\n systemPrompt,\n messages,\n tools,\n );\n\n return new Promise((resolve, reject) => {\n const args = [\n \"--print\",\n \"--output-format\",\n \"stream-json\",\n \"--system-prompt\",\n fullSystem,\n ];\n\n if (model) {\n args.push(\"--model\", model);\n }\n\n if (options?.maxOutputTokens) {\n args.push(\"--max-tokens\", String(options.maxOutputTokens));\n }\n\n // Pass prompt via stdin to avoid shell escaping issues\n const proc = spawn(\"claude\", args, {\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n });\n\n let fullText = \"\";\n let buffer = \"\";\n let stderrOutput = \"\";\n\n proc.stdin.write(prompt);\n proc.stdin.end();\n\n proc.stdout.on(\"data\", (data: Buffer) => {\n buffer += data.toString();\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n if (!line.trim()) continue;\n try {\n const event = JSON.parse(line);\n\n // Handle different stream-json event formats\n if (event.type === \"assistant\") {\n if (event.subtype === \"text\" && event.content) {\n fullText += event.content;\n onChunk({ type: \"text\", text: event.content });\n }\n } else if (event.type === \"content_block_delta\") {\n if (event.delta?.type === \"text_delta\" && event.delta.text) {\n fullText += event.delta.text;\n onChunk({ type: \"text\", text: event.delta.text });\n }\n } else if (event.type === \"message\" && event.message?.content) {\n for (const block of event.message.content) {\n if (block.type === \"text\" && block.text) {\n fullText += block.text;\n onChunk({ type: \"text\", text: block.text });\n }\n }\n }\n // \"result\" type is final summary — skip to avoid duplication\n } catch {\n // Not JSON, treat as raw text\n if (line.trim()) {\n fullText += line;\n onChunk({ type: \"text\", text: line });\n }\n }\n }\n });\n\n proc.stderr.on(\"data\", (data: Buffer) => {\n stderrOutput += data.toString();\n });\n\n proc.on(\"close\", (code) => {\n // Process remaining buffer\n if (buffer.trim()) {\n try {\n const event = JSON.parse(buffer);\n if (\n event.type === \"assistant\" &&\n event.subtype === \"text\" &&\n event.content\n ) {\n fullText += event.content;\n onChunk({ type: \"text\", text: event.content });\n }\n } catch {\n if (buffer.trim()) {\n fullText += buffer;\n onChunk({ type: \"text\", text: buffer });\n }\n }\n }\n\n onChunk({ type: \"done\" });\n\n if (code !== 0 && !fullText) {\n reject(\n new Error(\n `Claude CLI exited with code ${code}${stderrOutput ? `: ${stderrOutput.trim()}` : \"\"}`,\n ),\n );\n return;\n }\n\n // Check for tool use in the response\n const hasTools = tools && tools.length > 0;\n if (hasTools) {\n const toolUses = parseToolUses(fullText);\n if (toolUses.length > 0) {\n // Strip the JSON tool_use blocks from the visible text\n let cleanText = fullText;\n const stripRegex =\n /```json\\s*\\n?\\s*\\{\"tool_use\"[\\s\\S]*?```/g;\n cleanText = cleanText.replace(stripRegex, \"\").trim();\n\n const contentBlocks: ContentBlock[] = [];\n if (cleanText) {\n contentBlocks.push({ type: \"text\", text: cleanText });\n }\n for (const tu of toolUses) {\n contentBlocks.push({\n type: \"tool_use\",\n id: tu.id,\n name: tu.name,\n input: tu.input,\n });\n }\n\n resolve({\n message: { role: \"assistant\", content: contentBlocks },\n toolUses,\n });\n return;\n }\n }\n\n resolve({\n message: { role: \"assistant\", content: fullText },\n toolUses: [],\n });\n });\n\n proc.on(\"error\", (err) => {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n reject(\n new Error(\n \"Claude CLI not found. Install it with: npm install -g @anthropic-ai/claude-code\",\n ),\n );\n } else {\n reject(err);\n }\n });\n });\n },\n };\n}\n","import { spawn, execFileSync } from \"node:child_process\";\nimport type {\n LLMClient,\n Message,\n StreamChunk,\n ToolDefinition,\n ChatResponse,\n ChatOptions,\n ContentBlock,\n} from \"./types.js\";\n\n/**\n * Check if the `copilot` CLI is installed.\n */\nexport function isCopilotCliInstalled(): boolean {\n try {\n execFileSync(\"which\", [\"copilot\"], { stdio: \"ignore\" });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Check if the `copilot` CLI is authenticated.\n */\nexport function isCopilotCliAuthenticated(): boolean {\n try {\n const result = execFileSync(\"copilot\", [\"--version\"], {\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n timeout: 5000,\n });\n return result.toString().trim().length > 0;\n } catch {\n return false;\n }\n}\n\nfunction extractText(content: string | ContentBlock[]): string {\n if (typeof content === \"string\") return content;\n return content\n .map((block) => {\n if (block.type === \"text\") return block.text;\n if (block.type === \"tool_result\")\n return `[Tool result for ${block.tool_use_id}]: ${block.content}`;\n if (block.type === \"tool_use\") return `[Used tool: ${block.name}]`;\n return \"\";\n })\n .filter(Boolean)\n .join(\"\\n\");\n}\n\n/**\n * Format conversation history into a single prompt for the CLI.\n * The copilot CLI in print mode is single-turn, so we flatten the\n * multi-turn conversation into context.\n */\nfunction formatConversation(\n systemPrompt: string,\n messages: Message[],\n tools?: ToolDefinition[],\n): { prompt: string; systemPrompt: string } {\n const parts: string[] = [];\n\n let fullSystem = systemPrompt;\n if (tools && tools.length > 0) {\n fullSystem += \"\\n\\n## Available Tools\\n\";\n fullSystem +=\n \"You have access to the following tools. To use a tool, respond with a JSON block in this exact format:\\n\";\n fullSystem +=\n '```json\\n{\"tool_use\": {\"id\": \"call_1\", \"name\": \"tool_name\", \"input\": {…}}}\\n```\\n\\n';\n for (const tool of tools) {\n fullSystem += `### ${tool.name}\\n${tool.description}\\nParameters: ${JSON.stringify(tool.input_schema)}\\n\\n`;\n }\n fullSystem +=\n \"You may include multiple tool_use blocks. After each tool use, you will receive the result and can continue.\\n\";\n }\n\n if (messages.length > 1) {\n parts.push(\"<conversation_history>\");\n for (let i = 0; i < messages.length - 1; i++) {\n const msg = messages[i];\n const role = msg.role === \"user\" ? \"User\" : \"Assistant\";\n const text = extractText(msg.content);\n parts.push(`[${role}]: ${text}`);\n }\n parts.push(\"</conversation_history>\\n\");\n }\n\n const lastMsg = messages[messages.length - 1];\n if (lastMsg) {\n parts.push(extractText(lastMsg.content));\n }\n\n return { prompt: parts.join(\"\\n\"), systemPrompt: fullSystem };\n}\n\n/**\n * Parse tool_use JSON blocks from the assistant's text response.\n */\nfunction parseToolUses(\n text: string,\n): Array<{ id: string; name: string; input: Record<string, unknown> }> {\n const toolUses: Array<{\n id: string;\n name: string;\n input: Record<string, unknown>;\n }> = [];\n\n const codeBlockRegex = /```json\\s*\\n?([\\s\\S]*?)```/g;\n let match;\n while ((match = codeBlockRegex.exec(text)) !== null) {\n try {\n const parsed = JSON.parse(match[1].trim());\n if (parsed.tool_use) {\n toolUses.push({\n id: parsed.tool_use.id || `call_${toolUses.length + 1}`,\n name: parsed.tool_use.name,\n input: parsed.tool_use.input || {},\n });\n }\n } catch {\n // Not valid JSON\n }\n }\n\n if (toolUses.length === 0) {\n const inlineRegex =\n /\\{\"tool_use\"\\s*:\\s*\\{[^}]*\"name\"\\s*:\\s*\"[^\"]+?\"[^}]*\\}\\s*\\}/g;\n while ((match = inlineRegex.exec(text)) !== null) {\n try {\n const parsed = JSON.parse(match[0]);\n if (parsed.tool_use) {\n toolUses.push({\n id: parsed.tool_use.id || `call_${toolUses.length + 1}`,\n name: parsed.tool_use.name,\n input: parsed.tool_use.input || {},\n });\n }\n } catch {\n // Not valid JSON\n }\n }\n }\n\n return toolUses;\n}\n\nexport function createCopilotClient(model?: string): LLMClient {\n return {\n async chat(\n systemPrompt: string,\n messages: Message[],\n onChunk: (chunk: StreamChunk) => void,\n tools?: ToolDefinition[],\n options?: ChatOptions,\n ): Promise<ChatResponse> {\n const { prompt, systemPrompt: fullSystem } = formatConversation(\n systemPrompt,\n messages,\n tools,\n );\n\n return new Promise((resolve, reject) => {\n // The GitHub Copilot CLI renamed its non-interactive flag from\n // --print (positional prompt) to --prompt <text>. The old form\n // was silently broken in v0.30 and earlier once Copilot shipped\n // the rename. Surfaced by an A2A round-trip smoke test on\n // 2026-04-11: `copilot --print` now errors with \"unknown option\n // '--print' (Did you mean --prompt?)\".\n const args = [\n \"--prompt\", prompt,\n \"--output-format\", \"json\",\n \"--silent\",\n \"--no-custom-instructions\",\n ];\n\n if (model) {\n args.push(\"--model\", model);\n }\n\n const proc = spawn(\"copilot\", args, {\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n env: {\n ...process.env,\n COPILOT_SYSTEM_PROMPT: fullSystem,\n },\n });\n\n let fullText = \"\";\n let buffer = \"\";\n let stderrOutput = \"\";\n\n proc.stdout.on(\"data\", (data: Buffer) => {\n buffer += data.toString();\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n if (!line.trim()) continue;\n try {\n const event = JSON.parse(line);\n\n // Handle JSONL output from copilot CLI\n if (event.type === \"assistant\" && event.content) {\n fullText += event.content;\n onChunk({ type: \"text\", text: event.content });\n } else if (event.type === \"message\" && event.message?.content) {\n for (const block of event.message.content) {\n if (block.type === \"text\" && block.text) {\n fullText += block.text;\n onChunk({ type: \"text\", text: block.text });\n }\n }\n } else if (event.type === \"content_block_delta\") {\n if (event.delta?.type === \"text_delta\" && event.delta.text) {\n fullText += event.delta.text;\n onChunk({ type: \"text\", text: event.delta.text });\n }\n } else if (event.role === \"assistant\" && event.content) {\n // Some formats return {role, content} directly\n const text =\n typeof event.content === \"string\"\n ? event.content\n : event.content\n .map((b: { text?: string }) => b.text || \"\")\n .join(\"\");\n if (text) {\n fullText += text;\n onChunk({ type: \"text\", text });\n }\n }\n // Skip \"result\" type to avoid duplication\n } catch {\n // Not JSON — treat as raw text\n if (line.trim()) {\n fullText += line;\n onChunk({ type: \"text\", text: line });\n }\n }\n }\n });\n\n proc.stderr.on(\"data\", (data: Buffer) => {\n stderrOutput += data.toString();\n });\n\n proc.on(\"close\", (code) => {\n // Process remaining buffer\n if (buffer.trim()) {\n try {\n const event = JSON.parse(buffer);\n if (event.type === \"assistant\" && event.content) {\n fullText += event.content;\n onChunk({ type: \"text\", text: event.content });\n } else if (\n event.role === \"assistant\" &&\n typeof event.content === \"string\"\n ) {\n fullText += event.content;\n onChunk({ type: \"text\", text: event.content });\n }\n } catch {\n if (buffer.trim()) {\n fullText += buffer;\n onChunk({ type: \"text\", text: buffer });\n }\n }\n }\n\n onChunk({ type: \"done\" });\n\n if (code !== 0 && !fullText) {\n reject(\n new Error(\n `Copilot CLI exited with code ${code}${stderrOutput ? `: ${stderrOutput.trim()}` : \"\"}`,\n ),\n );\n return;\n }\n\n // Check for tool use in the response\n const hasTools = tools && tools.length > 0;\n if (hasTools) {\n const toolUses = parseToolUses(fullText);\n if (toolUses.length > 0) {\n let cleanText = fullText;\n const stripRegex = /```json\\s*\\n?\\s*\\{\"tool_use\"[\\s\\S]*?```/g;\n cleanText = cleanText.replace(stripRegex, \"\").trim();\n\n const contentBlocks: ContentBlock[] = [];\n if (cleanText) {\n contentBlocks.push({ type: \"text\", text: cleanText });\n }\n for (const tu of toolUses) {\n contentBlocks.push({\n type: \"tool_use\",\n id: tu.id,\n name: tu.name,\n input: tu.input,\n });\n }\n\n resolve({\n message: { role: \"assistant\", content: contentBlocks },\n toolUses,\n });\n return;\n }\n }\n\n resolve({\n message: { role: \"assistant\", content: fullText },\n toolUses: [],\n });\n });\n\n proc.on(\"error\", (err) => {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n reject(\n new Error(\n \"Copilot CLI not found. Install it from: https://docs.github.com/copilot/how-tos/copilot-cli\",\n ),\n );\n } else {\n reject(err);\n }\n });\n });\n },\n };\n}\n","import OpenAI from \"openai\";\nimport type {\n LLMClient,\n Message,\n StreamChunk,\n ToolDefinition,\n ChatResponse,\n ChatOptions,\n} from \"./types.js\";\nimport { toOpenAICompatibleMessages } from \"./openai-compat.js\";\n\nexport function createOllamaClient(\n model: string,\n baseURL?: string,\n): LLMClient {\n const client = new OpenAI({\n baseURL: baseURL || \"http://localhost:11434/v1\",\n apiKey: \"ollama\", // Ollama doesn't require a real key\n });\n\n return {\n async chat(\n systemPrompt: string,\n messages: Message[],\n onChunk: (chunk: StreamChunk) => void,\n tools?: ToolDefinition[],\n options?: ChatOptions,\n ): Promise<ChatResponse> {\n const ollamaMessages = toOpenAICompatibleMessages(systemPrompt, messages);\n const hasTools = tools && tools.length > 0;\n\n try {\n let fullText = \"\";\n const toolCallAccumulators: Map<\n number,\n { id: string; name: string; arguments: string }\n > = new Map();\n\n const createParams: Record<string, unknown> = {\n model,\n max_tokens: options?.maxOutputTokens ?? 4096,\n messages: ollamaMessages,\n stream: true,\n };\n\n if (hasTools) {\n createParams.tools = tools.map((t) => ({\n type: \"function\" as const,\n function: {\n name: t.name,\n description: t.description,\n parameters: t.input_schema,\n },\n }));\n }\n\n const stream = await client.chat.completions.create(\n createParams as unknown as OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming,\n );\n\n for await (const chunk of stream) {\n const delta = chunk.choices[0]?.delta;\n if (!delta) continue;\n\n // Stream text content\n if (delta.content) {\n fullText += delta.content;\n onChunk({ type: \"text\", text: delta.content });\n }\n\n // Accumulate tool calls\n if (delta.tool_calls) {\n for (const tc of delta.tool_calls) {\n const idx = tc.index;\n let acc = toolCallAccumulators.get(idx);\n if (!acc) {\n acc = { id: \"\", name: \"\", arguments: \"\" };\n toolCallAccumulators.set(idx, acc);\n }\n if (tc.id) {\n acc.id = tc.id;\n }\n if (tc.function?.name) {\n acc.name = tc.function.name;\n }\n if (tc.function?.arguments) {\n acc.arguments += tc.function.arguments;\n }\n }\n }\n }\n\n // Parse accumulated tool calls\n const toolUses = Array.from(toolCallAccumulators.entries())\n .sort(([a], [b]) => a - b)\n .map(([, acc]) => ({\n id: acc.id,\n name: acc.name,\n input: JSON.parse(acc.arguments || \"{}\") as Record<\n string,\n unknown\n >,\n }));\n\n // Signal done\n onChunk({ type: \"done\" });\n\n // Build response\n if (toolUses.length > 0) {\n const contentBlocks = [\n ...(fullText\n ? [{ type: \"text\" as const, text: fullText }]\n : []),\n ...toolUses.map((tu) => ({\n type: \"tool_use\" as const,\n id: tu.id,\n name: tu.name,\n input: tu.input,\n })),\n ];\n return {\n message: { role: \"assistant\", content: contentBlocks },\n toolUses,\n };\n }\n\n return {\n message: { role: \"assistant\", content: fullText },\n toolUses: [],\n };\n } catch (error) {\n if (\n error instanceof Error &&\n error.message.includes(\"ECONNREFUSED\")\n ) {\n throw new Error(\n \"Cannot connect to Ollama. Make sure it's running: ollama serve\",\n );\n }\n throw error;\n }\n },\n };\n}\n","import type OpenAI from \"openai\";\nimport type { Message } from \"./types.js\";\n\n/**\n * Converts internal Message[] to OpenAI-compatible chat completion messages.\n * Shared by both the OpenAI and Ollama clients since they use the same format.\n */\nexport function toOpenAICompatibleMessages(\n systemPrompt: string,\n messages: Message[],\n): OpenAI.Chat.Completions.ChatCompletionMessageParam[] {\n const result: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [\n { role: \"system\", content: systemPrompt },\n ];\n\n for (const m of messages) {\n if (typeof m.content === \"string\") {\n result.push({\n role: m.role as \"user\" | \"assistant\",\n content: m.content,\n });\n } else if (m.role === \"assistant\") {\n // Assistant message with tool calls\n const textParts = m.content.filter((b) => b.type === \"text\");\n const toolUseParts = m.content.filter((b) => b.type === \"tool_use\");\n const text = textParts.map((b) => (\"text\" in b ? b.text : \"\")).join(\"\");\n\n if (toolUseParts.length > 0) {\n result.push({\n role: \"assistant\",\n content: text || null,\n tool_calls: toolUseParts.map((b) => ({\n id: \"id\" in b ? b.id : \"\",\n type: \"function\" as const,\n function: {\n name: \"name\" in b ? b.name : \"\",\n arguments: JSON.stringify(\"input\" in b ? b.input : {}),\n },\n })),\n });\n } else {\n result.push({ role: \"assistant\", content: text });\n }\n } else if (m.role === \"user\") {\n // Check if it contains tool results\n const toolResults = m.content.filter((b) => b.type === \"tool_result\");\n if (toolResults.length > 0) {\n for (const tr of toolResults) {\n if (tr.type === \"tool_result\") {\n result.push({\n role: \"tool\",\n tool_call_id: tr.tool_use_id,\n content: tr.content,\n });\n }\n }\n } else {\n // User message — may contain text + images\n const hasImages = m.content.some((b) => b.type === \"image\");\n if (hasImages) {\n const parts: Array<Record<string, unknown>> = [];\n for (const b of m.content) {\n if (b.type === \"text\") {\n parts.push({ type: \"text\", text: b.text });\n } else if (b.type === \"image\") {\n parts.push({\n type: \"image_url\",\n image_url: {\n url: `data:${b.source.media_type};base64,${b.source.data}`,\n },\n });\n }\n }\n result.push({ role: \"user\", content: parts as never });\n } else {\n const text = m.content\n .map((b) => (\"text\" in b ? b.text : \"\"))\n .join(\"\");\n result.push({ role: \"user\", content: text });\n }\n }\n }\n }\n\n return result;\n}\n","import OpenAI from \"openai\";\nimport type {\n LLMClient,\n Message,\n StreamChunk,\n ToolDefinition,\n ChatResponse,\n ChatOptions,\n} from \"./types.js\";\nimport { toOpenAICompatibleMessages } from \"./openai-compat.js\";\n\nexport function createOpenAIClient(apiKey: string, model: string): LLMClient {\n const client = new OpenAI({ apiKey });\n\n return {\n async chat(\n systemPrompt: string,\n messages: Message[],\n onChunk: (chunk: StreamChunk) => void,\n tools?: ToolDefinition[],\n options?: ChatOptions,\n ): Promise<ChatResponse> {\n const openaiMessages = toOpenAICompatibleMessages(systemPrompt, messages);\n const hasTools = tools && tools.length > 0;\n\n try {\n let fullText = \"\";\n const toolCallAccumulators: Map<\n number,\n { id: string; name: string; arguments: string }\n > = new Map();\n\n const createParams: Record<string, unknown> = {\n model,\n max_tokens: options?.maxOutputTokens ?? 8192,\n messages: openaiMessages,\n stream: true,\n };\n\n if (hasTools) {\n createParams.tools = tools.map((t) => ({\n type: \"function\" as const,\n function: {\n name: t.name,\n description: t.description,\n parameters: t.input_schema,\n },\n }));\n }\n\n const stream = await client.chat.completions.create(\n createParams as unknown as OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming,\n );\n\n for await (const chunk of stream) {\n const delta = chunk.choices[0]?.delta;\n if (!delta) continue;\n\n // Stream text content\n if (delta.content) {\n fullText += delta.content;\n onChunk({ type: \"text\", text: delta.content });\n }\n\n // Accumulate tool calls\n if (delta.tool_calls) {\n for (const tc of delta.tool_calls) {\n const idx = tc.index;\n let acc = toolCallAccumulators.get(idx);\n if (!acc) {\n acc = { id: \"\", name: \"\", arguments: \"\" };\n toolCallAccumulators.set(idx, acc);\n }\n if (tc.id) {\n acc.id = tc.id;\n }\n if (tc.function?.name) {\n acc.name = tc.function.name;\n }\n if (tc.function?.arguments) {\n acc.arguments += tc.function.arguments;\n }\n }\n }\n }\n\n // Parse accumulated tool calls\n const toolUses = Array.from(toolCallAccumulators.entries())\n .sort(([a], [b]) => a - b)\n .map(([, acc]) => ({\n id: acc.id,\n name: acc.name,\n input: JSON.parse(acc.arguments || \"{}\") as Record<\n string,\n unknown\n >,\n }));\n\n // Signal done\n onChunk({ type: \"done\" });\n\n // Build response\n if (toolUses.length > 0) {\n const contentBlocks = [\n ...(fullText\n ? [{ type: \"text\" as const, text: fullText }]\n : []),\n ...toolUses.map((tu) => ({\n type: \"tool_use\" as const,\n id: tu.id,\n name: tu.name,\n input: tu.input,\n })),\n ];\n return {\n message: { role: \"assistant\", content: contentBlocks },\n toolUses,\n };\n }\n\n return {\n message: { role: \"assistant\", content: fullText },\n toolUses: [],\n };\n } catch (error) {\n if (error instanceof OpenAI.AuthenticationError) {\n throw new Error(\n \"Invalid API key. Run with --model flag or delete ~/.aman-agent/config.json to reconfigure.\",\n );\n }\n if (error instanceof OpenAI.RateLimitError) {\n throw new Error(\"Rate limited by OpenAI. Please wait and retry.\");\n }\n throw error;\n }\n },\n };\n}\n","import type {\n ChatOptions,\n ChatResponse,\n LLMClient,\n Message,\n StreamChunk,\n ToolDefinition,\n} from \"./types.js\";\nimport { createAnthropicClient } from \"./anthropic.js\";\nimport { createClaudeCodeClient } from \"./claude-code.js\";\nimport { createCopilotClient } from \"./copilot.js\";\nimport { createOllamaClient } from \"./ollama.js\";\nimport { createOpenAIClient } from \"./openai.js\";\nimport type { AgentConfig } from \"../config.js\";\n\nexport type { LLMClient };\n\n/**\n * Factory for constructing an LLM client from the user's config.\n *\n * When `AMAN_AGENT_FAKE_LLM=1` is set, returns a deterministic stub client\n * that echoes the last user message and never calls tools. Used exclusively\n * by the A2A integration test so it can run in a hermetic CI environment\n * without network, real API keys, or spawning aman-mcp.\n */\nexport function pickLLMClient(config: AgentConfig, model: string): LLMClient {\n if (process.env.AMAN_AGENT_FAKE_LLM === \"1\") {\n return createFakeClient();\n }\n if (config.provider === \"claude-code\") return createClaudeCodeClient(model);\n if (config.provider === \"copilot\") return createCopilotClient(model);\n if (config.provider === \"anthropic\")\n return createAnthropicClient(config.apiKey, model);\n if (config.provider === \"ollama\") return createOllamaClient(model);\n return createOpenAIClient(config.apiKey, model);\n}\n\n/**\n * Deterministic stub LLM client for the A2A integration test.\n *\n * Echoes the last user message as plain text and never emits tool calls.\n * Must satisfy `LLMClient` exactly so `serve-command.ts` compiles against\n * the real type — do not loosen.\n */\nfunction createFakeClient(): LLMClient {\n return {\n async chat(\n _systemPrompt: string,\n messages: Message[],\n onChunk: (chunk: StreamChunk) => void,\n _tools?: ToolDefinition[],\n _options?: ChatOptions,\n ): Promise<ChatResponse> {\n const last = messages[messages.length - 1];\n const text =\n typeof last?.content === \"string\"\n ? last.content\n : \"[fake-llm] ok\";\n const reply = `[fake-llm] received: ${text}`;\n onChunk({ type: \"text\", text: reply });\n onChunk({ type: \"done\" });\n return {\n message: { role: \"assistant\", content: reply },\n toolUses: [],\n };\n },\n };\n}\n","import { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { StdioClientTransport } from \"@modelcontextprotocol/sdk/client/stdio.js\";\nimport { log } from \"../logger.js\";\nimport { withRetry } from \"../retry.js\";\n\ninterface McpConnection {\n name: string;\n client: Client;\n transport: StdioClientTransport;\n /** Original params stored for reconnect */\n connectParams: { command: string; args: string[]; env?: Record<string, string> };\n}\n\nexport interface ToolDef {\n name: string;\n description: string;\n input_schema: Record<string, unknown>;\n serverName: string;\n}\n\nconst TOOL_CALL_TIMEOUT_MS = 30_000;\n\nexport class McpManager {\n private connections: McpConnection[] = [];\n private tools: ToolDef[] = [];\n\n async connect(\n name: string,\n command: string,\n args: string[],\n env?: Record<string, string>,\n ): Promise<void> {\n try {\n const transport = new StdioClientTransport({\n command,\n args,\n stderr: \"pipe\",\n env: env ? env : undefined,\n });\n const client = new Client({\n name: `aman-agent-${name}`,\n version: \"0.1.0\",\n });\n await client.connect(transport);\n\n // Redirect stderr to debug log instead of terminal\n if (transport.stderr) {\n transport.stderr.on(\"data\", (chunk: Buffer) => {\n log.debug(\"mcp\", `[${name} stderr] ${chunk.toString().trim()}`);\n });\n }\n\n this.connections.push({ name, client, transport, connectParams: { command, args, env } });\n\n // List tools from this server\n const toolsResult = await client.listTools();\n for (const tool of toolsResult.tools) {\n // Fix 4: Warn on tool name collisions\n const existing = this.tools.find((t) => t.name === tool.name);\n if (existing) {\n log.warn(\n \"mcp\",\n `Warning: tool \"${tool.name}\" from server \"${name}\" shadows existing tool from \"${existing.serverName}\"`,\n );\n }\n\n this.tools.push({\n name: tool.name,\n description: tool.description || \"\",\n input_schema: tool.inputSchema as Record<string, unknown>,\n serverName: name,\n });\n }\n } catch (err) {\n log.error(\"mcp\", \"Failed to connect to \" + name + \" MCP server\", err);\n console.error(` Warning: Could not connect to ${name} MCP server`);\n }\n }\n\n getTools(): ToolDef[] {\n return this.tools;\n }\n\n async callTool(\n toolName: string,\n args: Record<string, unknown>,\n ): Promise<string> {\n const tool = this.tools.find((t) => t.name === toolName);\n if (!tool) return `Error: tool ${toolName} not found`;\n\n const conn = this.connections.find((c) => c.name === tool.serverName);\n if (!conn) return `Error: server ${tool.serverName} not connected`;\n\n const executeTool = async () => {\n const currentConn = this.connections.find((c) => c.name === tool.serverName);\n if (!currentConn) throw new Error(`Server ${tool.serverName} disconnected`);\n\n const result = await Promise.race([\n currentConn.client.callTool({ name: toolName, arguments: args }),\n new Promise<never>((_, reject) =>\n setTimeout(\n () => reject(new Error(`Tool ${toolName} timed out after 30s`)),\n TOOL_CALL_TIMEOUT_MS,\n ),\n ),\n ]);\n\n if (result.content && Array.isArray(result.content)) {\n return (result.content as Array<{ type: string; text?: string }>)\n .filter((c) => c.type === \"text\")\n .map((c) => c.text ?? \"\")\n .join(\"\\n\");\n }\n return JSON.stringify(result);\n };\n\n try {\n return await withRetry(executeTool, {\n maxAttempts: 2,\n baseDelay: 500,\n retryable: (err) => err.message.includes(\"ETIMEDOUT\") || err.message.includes(\"timeout\"),\n });\n } catch (error) {\n const errMsg = error instanceof Error ? error.message : String(error);\n // Detect connection failures and auto-reconnect once\n const isConnectionError = errMsg.includes(\"EPIPE\") || errMsg.includes(\"ECONNRESET\") ||\n errMsg.includes(\"channel closed\") || errMsg.includes(\"disconnected\") ||\n errMsg.includes(\"not connected\") || errMsg.includes(\"write after end\") ||\n errMsg.includes(\"socket hang up\") || errMsg.includes(\"spawn\");\n if (isConnectionError) {\n log.warn(\"mcp\", `Connection error for ${tool.serverName}, attempting reconnect: ${errMsg}`);\n try {\n await this.reconnect(tool.serverName);\n return await executeTool();\n } catch (reconnectErr) {\n return `Error calling ${toolName}: reconnect failed — ${reconnectErr instanceof Error ? reconnectErr.message : String(reconnectErr)}`;\n }\n }\n return `Error calling ${toolName}: ${errMsg}`;\n }\n }\n\n async reconnect(name: string): Promise<void> {\n const connIndex = this.connections.findIndex((c) => c.name === name);\n if (connIndex === -1) {\n log.error(\"mcp\", `Cannot reconnect: no connection found for \"${name}\"`);\n return;\n }\n\n const conn = this.connections[connIndex];\n const { command, args, env } = conn.connectParams;\n\n // Kill old connection\n try {\n await conn.client.close();\n } catch (err) {\n log.debug(\"mcp\", `Error closing old connection for ${name}`, err);\n }\n\n // Remove old connection and its tools\n this.connections.splice(connIndex, 1);\n this.tools = this.tools.filter((t) => t.serverName !== name);\n\n // Re-connect with same params\n await this.connect(name, command, args, env);\n }\n\n async disconnect(): Promise<void> {\n for (const conn of this.connections) {\n try {\n await conn.client.close();\n } catch (err) {\n log.debug(\"mcp\", \"Cleanup error disconnecting \" + conn.name, err);\n }\n }\n this.connections = [];\n this.tools = [];\n }\n}\n","export interface RetryOptions {\n maxAttempts: number;\n baseDelay: number;\n retryable: (err: Error) => boolean;\n}\n\nexport async function withRetry<T>(\n fn: () => Promise<T>,\n options: RetryOptions,\n): Promise<T> {\n const { maxAttempts, baseDelay, retryable } = options;\n let lastError: Error | undefined;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n try {\n return await fn();\n } catch (err) {\n lastError = err instanceof Error ? err : new Error(String(err));\n if (!retryable(lastError) || attempt === maxAttempts) {\n throw lastError;\n }\n const delay = baseDelay * Math.pow(2, attempt - 1) * (0.5 + Math.random() * 0.5);\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n }\n\n throw lastError;\n}\n","import * as readline from \"node:readline\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport os from \"node:os\";\nimport pc from \"picocolors\";\nimport { marked } from \"marked\";\nimport { markedTerminal } from \"marked-terminal\";\nimport logUpdate from \"log-update\";\nimport type {\n LLMClient,\n Message,\n ContentBlock,\n ToolDefinition,\n ToolResultBlock,\n ImageBlock,\n StreamChunk,\n} from \"./llm/types.js\";\nimport { handleCommand } from \"./commands.js\";\nimport type { McpManager } from \"./mcp/client.js\";\nimport {\n onSessionStart,\n onBeforeToolExec,\n onWorkflowMatch,\n onSessionEnd,\n getSessionStartTime,\n type HookContext,\n} from \"./hooks.js\";\nimport {\n computePersonality,\n syncPersonalityToCore,\n formatWellbeingNudge,\n shouldFireNudge,\n} from \"./personality.js\";\nimport type { HooksConfig } from \"./config.js\";\nimport { trimConversation } from \"./context-manager.js\";\nimport { log } from \"./logger.js\";\nimport { withRetry } from \"./retry.js\";\nimport { extractMemories as runExtraction, type ExtractorState } from \"./memory-extractor.js\";\nimport { memoryRecall, memoryLog, getMaxRecallTokens } from \"./memory.js\";\nimport { autoTriggerSkills, matchKnowledge } from \"./skill-engine.js\";\nimport { BackgroundTaskManager, shouldRunInBackground } from \"./background.js\";\nimport { getActivePlan, formatPlanForPrompt } from \"./plans.js\";\nimport { estimateTokens } from \"./token-budget.js\";\nimport { delegateTask } from \"./delegate.js\";\nimport { listProfiles } from \"./prompt.js\";\nimport { listTeams, loadTeam, runTeam, formatTeamResult } from \"./teams.js\";\nimport { humanizeError } from \"./errors.js\";\nimport { getHint, loadShownHints, saveShownHints, type HintState } from \"./hints.js\";\nimport {\n createObservationSession,\n recordEvent,\n flushEvents,\n detectTopicShift,\n cleanupOldObservations,\n type ObservationSession,\n} from \"./observation.js\";\n\n// markedTerminal() returns a MarkedExtension — types lag behind, cast is safe\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nmarked.use(markedTerminal() as any);\n\ninterface AgentRecallResult {\n text: string;\n tokenEstimate: number;\n}\n\nasync function recallForMessage(\n input: string,\n): Promise<AgentRecallResult | null> {\n try {\n const result = await memoryRecall(input, { limit: 5, compact: true });\n if (result.total === 0) {\n return null;\n }\n const tokenEstimate = result.tokenEstimate ?? Math.round(result.text.split(/\\s+/).filter(Boolean).length * 1.3);\n const MAX_MEMORY_TOKENS = getMaxRecallTokens();\n let memoryText = result.text;\n if (tokenEstimate > MAX_MEMORY_TOKENS) {\n // Truncate to fit within the token ceiling (rough char estimate: 1 token ≈ 4 chars)\n const maxChars = MAX_MEMORY_TOKENS * 4;\n memoryText = memoryText.slice(0, maxChars) + \"\\n[... memory truncated to fit token budget]\";\n log.debug(\"agent\", `memory recall truncated from ~${tokenEstimate} to ~${MAX_MEMORY_TOKENS} tokens`);\n }\n return {\n text: `\\n\\n<relevant-memories>\\n${memoryText}\\n</relevant-memories>`,\n tokenEstimate: Math.min(tokenEstimate, MAX_MEMORY_TOKENS),\n };\n } catch (err) {\n log.debug(\"agent\", \"memory recall failed\", err);\n return null;\n }\n}\n\n// Generate a session ID for conversation logging\nfunction generateSessionId(): string {\n const now = new Date();\n const pad = (n: number) => n.toString().padStart(2, \"0\");\n return `session-${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}`;\n}\n\nexport async function runAgent(\n client: LLMClient,\n systemPrompt: string,\n aiName: string,\n model: string,\n tools?: ToolDefinition[],\n mcpManager?: McpManager,\n hooksConfig?: HooksConfig,\n): Promise<void> {\n const messages: Message[] = [];\n const sessionId = generateSessionId();\n const extractorState: ExtractorState = { turnsSinceLastExtraction: 0, lastExtractionCount: 0 };\n const bgTasks = new BackgroundTaskManager();\n let abortController: AbortController | null = null;\n let isStreaming = false;\n let lastCheckpointTurn = 0;\n const CHECKPOINT_INTERVAL = 10; // auto-save every N user turns\n\n // Add virtual tools for delegation and teams\n const profiles = listProfiles();\n const teams = listTeams();\n if (tools && (profiles.length > 0 || teams.length > 0)) {\n const virtualTools: ToolDefinition[] = [];\n\n if (profiles.length > 0) {\n virtualTools.push({\n name: \"delegate_task\",\n description: `Delegate a task to a specialist sub-agent with a different profile. Available profiles: ${profiles.map((p) => `${p.name} (${p.personality})`).join(\", \")}. IMPORTANT: Always ask the user for permission before delegating.`,\n input_schema: {\n type: \"object\",\n properties: {\n profile: { type: \"string\", description: \"Profile name to delegate to\" },\n task: { type: \"string\", description: \"The task description for the sub-agent\" },\n },\n required: [\"profile\", \"task\"],\n },\n });\n }\n\n if (teams.length > 0) {\n virtualTools.push({\n name: \"team_run\",\n description: `Run a task with a named agent team. Available teams: ${teams.map((t) => `${t.name} (${t.workflow}: ${t.members.map((m) => m.profile).join(\"→\")})`).join(\", \")}. IMPORTANT: Always ask the user for permission before running a team.`,\n input_schema: {\n type: \"object\",\n properties: {\n team: { type: \"string\", description: \"Team name\" },\n task: { type: \"string\", description: \"The task for the team\" },\n },\n required: [\"team\", \"task\"],\n },\n });\n }\n\n tools = [...tools, ...virtualTools];\n }\n const hintState: HintState = {\n turnCount: 0,\n shownHints: loadShownHints(),\n hintShownThisSession: false,\n };\n\n const isRetryable = (err: Error) =>\n err.message.includes(\"Rate limit\") ||\n err.message.includes(\"rate limit\") ||\n err.message.includes(\"ECONNRESET\") ||\n err.message.includes(\"ETIMEDOUT\") ||\n err.message.includes(\"fetch failed\") ||\n err.message.includes(\"socket hang up\") ||\n err.message.includes(\"network socket disconnected\") ||\n err.message.includes(\"ENOTFOUND\") ||\n err.message.includes(\"EAI_AGAIN\");\n\n let responseBuffer = \"\";\n\n const onChunkHandler = (chunk: StreamChunk) => {\n if (chunk.type === \"text\" && chunk.text) {\n responseBuffer += chunk.text;\n if (process.stdout.isTTY) {\n logUpdate(responseBuffer);\n } else {\n process.stdout.write(chunk.text);\n }\n }\n if (chunk.type === \"done\") {\n if (process.stdout.isTTY && responseBuffer.trim()) {\n try {\n const rendered = marked(responseBuffer.trim()) as string;\n logUpdate(rendered);\n logUpdate.done();\n } catch {\n logUpdate.done();\n }\n } else {\n process.stdout.write(\"\\n\");\n }\n responseBuffer = \"\";\n }\n };\n\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n // Handle Ctrl+C gracefully — abort current stream or exit\n let sigintCount = 0;\n rl.on(\"SIGINT\", async () => {\n // If streaming, abort the current response instead of exiting\n if (isStreaming && abortController) {\n abortController.abort();\n sigintCount = 0;\n process.stdout.write(pc.yellow(\"\\n [response cancelled]\\n\"));\n return;\n }\n\n sigintCount++;\n // Double Ctrl+C to exit\n if (sigintCount < 2) {\n process.stdout.write(pc.dim(\"\\n Press Ctrl+C again to exit.\\n\"));\n setTimeout(() => { sigintCount = 0; }, 2000);\n return;\n }\n\n // Wait for background tasks before exiting\n if (bgTasks.pendingCount > 0) {\n await bgTasks.waitAll();\n bgTasks.displayCompleted();\n }\n if (observationSession) {\n await flushEvents(observationSession).catch(() => {});\n }\n if (mcpManager && hooksConfig) {\n try {\n const hookCtx: HookContext = { mcpManager, config: hooksConfig, llmClient: client };\n await onSessionEnd(hookCtx, messages, sessionId, observationSession);\n } catch (err) { log.debug(\"agent\", \"session end hook failed on SIGINT\", err); }\n }\n console.log(pc.dim(\"\\nGoodbye.\\n\"));\n rl.close();\n process.exit(0);\n });\n\n const prompt = (): Promise<string> => {\n return new Promise<string>((resolve) => {\n rl.question(pc.green(\"\\nYou > \"), (answer) => {\n resolve(answer);\n });\n });\n };\n\n console.log(\n `\\nType a message, ${pc.dim(\"/help\")} for commands, or ${pc.dim(\"/quit\")} to exit.\\n`,\n );\n\n if (mcpManager && hooksConfig) {\n const hookCtx: HookContext = { mcpManager, config: hooksConfig };\n try {\n const session = await onSessionStart(hookCtx);\n\n if (!session.firstRun) {\n if (session.resumeTopic) {\n console.log(pc.dim(` Welcome back. Last time we talked about ${session.resumeTopic}`));\n } else {\n console.log(pc.dim(\" Welcome back.\"));\n }\n }\n\n if (session.visibleReminders && session.visibleReminders.length > 0) {\n for (const reminder of session.visibleReminders) {\n console.log(pc.yellow(` Reminder: ${reminder}`));\n }\n }\n\n if (session.contextInjection) {\n messages.push({ role: \"user\", content: session.contextInjection });\n if (session.firstRun) {\n messages.push({ role: \"assistant\", content: \"acknowledged\" });\n } else {\n messages.push({ role: \"assistant\", content: \"I have context from our previous sessions. How can I help?\" });\n }\n }\n } catch (err) { log.warn(\"agent\", \"session start hook failed\", err); }\n }\n\n // Initialize observation session (passive session telemetry)\n let observationSession: ObservationSession | undefined;\n let prevSentiment: string | undefined;\n if (hooksConfig?.recordObservations !== false) {\n observationSession = createObservationSession(sessionId);\n // Cleanup old observation files (non-blocking, fire-and-forget)\n cleanupOldObservations().catch(() => {});\n }\n\n while (true) {\n // Check for completed background tasks — inject as proper tool results\n if (bgTasks.hasCompleted) {\n const completed = bgTasks.collectCompleted();\n const bgToolResults: ToolResultBlock[] = [];\n for (const task of completed) {\n const elapsed = ((Date.now() - task.startedAt) / 1000).toFixed(1);\n if (task.error) {\n process.stdout.write(pc.yellow(`\\n [${task.id}] ${task.toolName} failed after ${elapsed}s: ${task.error}\\n`));\n bgToolResults.push({\n type: \"tool_result\" as const,\n tool_use_id: task.toolUseId,\n content: `[Background] ${task.toolName} failed: ${task.error}`,\n is_error: true,\n });\n } else {\n process.stdout.write(pc.green(`\\n [${task.id}] ${task.toolName} completed in ${elapsed}s\\n`));\n const preview = (task.result || \"\").slice(0, 200);\n if (preview) {\n process.stdout.write(pc.dim(` ${preview}${(task.result || \"\").length > 200 ? \"...\" : \"\"}\\n`));\n }\n bgToolResults.push({\n type: \"tool_result\" as const,\n tool_use_id: task.toolUseId,\n content: `[Background] ${task.toolName} completed:\\n${task.result}`,\n });\n }\n }\n if (bgToolResults.length > 0) {\n messages.push({ role: \"user\", content: bgToolResults });\n }\n }\n\n const input = await prompt();\n if (!input.trim()) continue;\n\n // Handle slash commands\n const cmdResult = await handleCommand(input, {\n model,\n mcpManager,\n llmClient: client,\n tools,\n observationSession,\n messages,\n });\n if (cmdResult.handled) {\n if (cmdResult.quit) {\n if (observationSession) {\n await flushEvents(observationSession).catch(() => {});\n }\n if (mcpManager && hooksConfig) {\n try {\n const hookCtx: HookContext = { mcpManager, config: hooksConfig, llmClient: client };\n await onSessionEnd(hookCtx, messages, sessionId, observationSession);\n } catch (err) { log.debug(\"agent\", \"session end hook failed on quit\", err); }\n }\n console.log(pc.dim(\"\\nGoodbye.\\n\"));\n rl.close();\n return;\n }\n if (cmdResult.exportConversation) {\n try {\n const exportDir = path.join(os.homedir(), \".aman-agent\", \"exports\");\n fs.mkdirSync(exportDir, { recursive: true });\n const exportPath = path.join(exportDir, `${sessionId}.md`);\n\n const lines: string[] = [\n `# Conversation — ${new Date().toLocaleString()}`,\n `**Model:** ${model}`,\n \"\",\n \"---\",\n \"\",\n ];\n\n for (const msg of messages) {\n if (typeof msg.content === \"string\") {\n const label = msg.role === \"user\" ? \"**You:**\" : `**${aiName}:**`;\n lines.push(`${label} ${msg.content}`, \"\");\n }\n }\n\n fs.writeFileSync(exportPath, lines.join(\"\\n\"), \"utf-8\");\n console.log(pc.green(`Exported to ${exportPath}`));\n } catch {\n console.log(pc.red(\"Failed to export conversation.\"));\n }\n continue;\n }\n if (cmdResult.saveConversation) {\n try {\n await saveConversationToMemory(messages, sessionId);\n console.log(pc.green(\"Conversation saved to memory.\"));\n } catch {\n console.log(pc.red(\"Failed to save conversation.\"));\n }\n continue;\n }\n if (cmdResult.output) {\n console.log(cmdResult.output);\n }\n if (cmdResult.clearHistory) {\n messages.length = 0;\n }\n continue;\n }\n\n // Check for workflow match\n let activeSystemPrompt = systemPrompt;\n if (mcpManager && hooksConfig) {\n try {\n const hookCtx: HookContext = { mcpManager, config: hooksConfig };\n const wfMatch = await onWorkflowMatch(input, hookCtx);\n if (wfMatch) {\n const useIt = await new Promise<boolean>((resolve) => {\n rl.question(pc.dim(` Workflow \"${wfMatch.name}\" matches. Use it? (y/N) `), (answer) => resolve(answer.toLowerCase() === \"y\"));\n });\n if (useIt) {\n activeSystemPrompt = systemPrompt + `\\n\\n<active-workflow>\\n${wfMatch.steps}\\n</active-workflow>`;\n console.log(pc.dim(` Using \"${wfMatch.name}\" workflow.`));\n }\n }\n } catch (err) { log.debug(\"agent\", \"workflow match failed\", err); }\n }\n\n // Inject active plan into context\n const activePlan = getActivePlan();\n if (activePlan) {\n activeSystemPrompt += \"\\n\\n\" + formatPlanForPrompt(activePlan);\n }\n\n // Auto-trigger skills based on conversation context\n if (mcpManager) {\n try {\n const skillContext = await autoTriggerSkills(input, mcpManager);\n if (skillContext) {\n activeSystemPrompt += \"\\n\\n\" + skillContext;\n }\n } catch (err) { log.debug(\"agent\", \"skill auto-trigger failed\", err); }\n\n // Auto-suggest knowledge library items\n const knowledgeItem = matchKnowledge(input);\n if (knowledgeItem) {\n activeSystemPrompt += `\\n\\n<knowledge name=\"${knowledgeItem.name}\" category=\"${knowledgeItem.category}\">\n${knowledgeItem.description}\n\n${knowledgeItem.content}\n</knowledge>`;\n }\n }\n\n // Auto-trim conversation if approaching token limits\n await trimConversation(messages, client);\n\n // Detect and process file paths + image URLs in user input\n const textExts = new Set([\n \".txt\", \".md\", \".json\", \".js\", \".ts\", \".jsx\", \".tsx\", \".py\",\n \".html\", \".css\", \".yml\", \".yaml\", \".toml\", \".xml\", \".csv\",\n \".sh\", \".bash\", \".zsh\", \".env\", \".cfg\", \".ini\", \".log\",\n \".sql\", \".graphql\", \".rs\", \".go\", \".java\", \".rb\", \".php\",\n \".c\", \".cpp\", \".h\", \".swift\", \".kt\", \".r\", \".lua\",\n ]);\n const imageExts = new Set([\".png\", \".jpg\", \".jpeg\", \".gif\", \".webp\", \".bmp\"]);\n const docExts = new Set([\".docx\", \".doc\", \".pdf\", \".pptx\", \".ppt\", \".xlsx\", \".xls\", \".odt\", \".rtf\", \".epub\"]);\n const mimeMap: Record<string, ImageBlock[\"source\"][\"media_type\"]> = {\n \".png\": \"image/png\", \".jpg\": \"image/jpeg\", \".jpeg\": \"image/jpeg\",\n \".gif\": \"image/gif\", \".webp\": \"image/webp\", \".bmp\": \"image/png\",\n };\n const maxImageBytes = 20 * 1024 * 1024; // 20MB\n\n let textContent = input;\n const imageBlocks: ImageBlock[] = [];\n\n // Detect all local file paths\n const filePathMatches = [...input.matchAll(/(\\/[\\w./-]+|~\\/[\\w./-]+)/g)];\n for (const match of filePathMatches) {\n let filePath = match[1];\n if (filePath.startsWith(\"~/\")) {\n filePath = path.join(os.homedir(), filePath.slice(2));\n }\n if (!fs.existsSync(filePath) || !fs.statSync(filePath).isFile()) continue;\n\n const ext = path.extname(filePath).toLowerCase();\n\n if (imageExts.has(ext)) {\n // Image file — base64 encode\n try {\n const stat = fs.statSync(filePath);\n if (stat.size > maxImageBytes) {\n process.stdout.write(pc.yellow(` [skipped: ${path.basename(filePath)} — exceeds 20MB limit]\\n`));\n continue;\n }\n const data = fs.readFileSync(filePath).toString(\"base64\");\n const mediaType = mimeMap[ext] || \"image/png\";\n imageBlocks.push({\n type: \"image\",\n source: { type: \"base64\", media_type: mediaType, data },\n });\n process.stdout.write(pc.dim(` [attached image: ${path.basename(filePath)} (${(stat.size / 1024).toFixed(1)}KB)]\\n`));\n } catch {\n process.stdout.write(pc.dim(` [could not read image: ${filePath}]\\n`));\n }\n } else if (textExts.has(ext) || ext === \"\") {\n // Text file — inline as XML\n try {\n const content = fs.readFileSync(filePath, \"utf-8\");\n const maxChars = 50000;\n const trimmed = content.length > maxChars\n ? content.slice(0, maxChars) + `\\n\\n[... truncated, ${content.length - maxChars} chars remaining]`\n : content;\n textContent += `\\n\\n<file path=\"${filePath}\" size=\"${content.length} chars\">\\n${trimmed}\\n</file>`;\n process.stdout.write(pc.dim(` [attached: ${path.basename(filePath)} (${(content.length / 1024).toFixed(1)}KB)]\\n`));\n } catch {\n process.stdout.write(pc.dim(` [could not read: ${filePath}]\\n`));\n }\n } else if (docExts.has(ext)) {\n // Binary document — convert via MCP\n if (mcpManager) {\n try {\n process.stdout.write(pc.dim(` [converting: ${path.basename(filePath)}...]\\n`));\n const converted = await mcpManager.callTool(\"doc_convert\", { path: filePath });\n if (converted && !converted.startsWith(\"Error\") && !converted.includes(\"Could not convert\")) {\n textContent += `\\n\\n<file path=\"${filePath}\" format=\"${ext}\">\\n${converted.slice(0, 50000)}\\n</file>`;\n process.stdout.write(pc.dim(` [attached: ${path.basename(filePath)} (converted from ${ext})]\\n`));\n } else {\n textContent += `\\n\\n<file-error path=\"${filePath}\">\\n${converted}\\n</file-error>`;\n process.stdout.write(pc.yellow(` [conversion note: ${converted.split(\"\\n\")[0]}]\\n`));\n }\n } catch {\n process.stdout.write(pc.dim(` [could not convert: ${path.basename(filePath)}]\\n`));\n }\n } else {\n process.stdout.write(pc.yellow(` Binary file (${ext}) — install Docling for document support: pip install docling\\n`));\n }\n }\n }\n\n // Detect image URLs in user input\n const urlImageMatches = [...input.matchAll(/https?:\\/\\/\\S+\\.(?:png|jpg|jpeg|gif|webp)(?:\\?\\S*)?/gi)];\n for (const match of urlImageMatches) {\n const url = match[0];\n try {\n process.stdout.write(pc.dim(` [fetching image: ${url.slice(0, 60)}...]\\n`));\n const response = await fetch(url);\n if (!response.ok) {\n process.stdout.write(pc.yellow(` [could not fetch: HTTP ${response.status}]\\n`));\n continue;\n }\n const buffer = Buffer.from(await response.arrayBuffer());\n if (buffer.length > maxImageBytes) {\n process.stdout.write(pc.yellow(` [skipped: image URL exceeds 20MB limit]\\n`));\n continue;\n }\n const contentType = response.headers.get(\"content-type\") || \"\";\n let mediaType: ImageBlock[\"source\"][\"media_type\"] = \"image/png\";\n if (contentType.includes(\"jpeg\") || contentType.includes(\"jpg\")) mediaType = \"image/jpeg\";\n else if (contentType.includes(\"gif\")) mediaType = \"image/gif\";\n else if (contentType.includes(\"webp\")) mediaType = \"image/webp\";\n else if (contentType.includes(\"png\")) mediaType = \"image/png\";\n\n imageBlocks.push({\n type: \"image\",\n source: { type: \"base64\", media_type: mediaType, data: buffer.toString(\"base64\") },\n });\n process.stdout.write(pc.dim(` [attached image URL: (${(buffer.length / 1024).toFixed(1)}KB)]\\n`));\n } catch {\n process.stdout.write(pc.dim(` [could not fetch image: ${url}]\\n`));\n }\n }\n\n // Build user message: structured ContentBlock[] if images present, string otherwise\n if (imageBlocks.length > 0) {\n const blocks: ContentBlock[] = [\n { type: \"text\", text: textContent },\n ...imageBlocks,\n ];\n messages.push({ role: \"user\", content: blocks });\n } else {\n messages.push({ role: \"user\", content: textContent });\n }\n\n // Per-message memory recall\n let augmentedSystemPrompt = activeSystemPrompt;\n let memoryTokens = 0;\n {\n const recall = await recallForMessage(input);\n if (recall) {\n augmentedSystemPrompt = activeSystemPrompt + recall.text;\n memoryTokens = recall.tokenEstimate;\n }\n }\n\n // Personality refresh with sentiment (every 5 turns)\n const userTurnCount = messages.filter((m) => m.role === \"user\").length;\n if (mcpManager && hooksConfig?.personalityAdapt !== false && userTurnCount > 0 && userTurnCount % 5 === 0) {\n const hour = new Date().getHours();\n let period: string;\n if (hour < 6) period = \"late-night\";\n else if (hour < 12) period = \"morning\";\n else if (hour < 17) period = \"afternoon\";\n else if (hour < 21) period = \"evening\";\n else period = \"night\";\n\n // Collect recent user messages for sentiment analysis\n const recentUserMsgs = messages\n .filter((m) => m.role === \"user\" && typeof m.content === \"string\")\n .slice(-5)\n .map((m) => m.content as string);\n\n const sessionMinutes = Math.round((Date.now() - getSessionStartTime()) / 60000);\n const state = computePersonality({\n timePeriod: period,\n sessionMinutes,\n turnCount: userTurnCount,\n recentMessages: recentUserMsgs,\n });\n\n syncPersonalityToCore(state, mcpManager).catch(() => {});\n\n // Record sentiment shift observation\n if (observationSession && prevSentiment !== state.sentiment.dominant) {\n recordEvent(observationSession, {\n type: \"sentiment_shift\",\n summary: `${prevSentiment ?? \"neutral\"} → ${state.sentiment.dominant}`,\n data: { from: prevSentiment ?? \"neutral\", to: state.sentiment.dominant },\n });\n prevSentiment = state.sentiment.dominant;\n }\n\n // Record blocker observation on sustained frustration\n if (observationSession && state.sentiment.frustration > 0.6) {\n recordEvent(observationSession, {\n type: \"blocker\",\n summary: \"User expressing frustration\",\n data: { frustrationLevel: state.sentiment.frustration },\n });\n }\n\n // Detect topic shift based on recent vs prior user messages\n if (observationSession && recentUserMsgs.length >= 6) {\n const recent = recentUserMsgs.slice(-3);\n const previous = recentUserMsgs.slice(-6, -3);\n const shift = detectTopicShift(recent, previous);\n if (shift.shifted) {\n recordEvent(observationSession, {\n type: \"topic_shift\",\n summary: `Topics: ${shift.newTopics.join(\", \")}`,\n data: { newTopics: shift.newTopics },\n });\n }\n }\n\n const nudge = formatWellbeingNudge(state);\n if (nudge && state.wellbeingNudge) {\n // Adaptive nudge: check user model stats before firing\n let fireNudge = true;\n try {\n const { loadUserModel, computeProfile } = await import(\"./user-model.js\");\n const model = await loadUserModel();\n if (model && model.sessions.length >= 5) {\n const profile = computeProfile(model.sessions, model.sessions.length);\n fireNudge = shouldFireNudge(state.wellbeingNudge, profile);\n }\n } catch {\n // No model yet — always fire\n }\n if (fireNudge) {\n augmentedSystemPrompt += \"\\n\" + nudge;\n }\n }\n\n // Feed-forward v2: preemptive context from frustration correlations\n try {\n const { loadUserModel, computeProfile } = await import(\"./user-model.js\");\n const model = await loadUserModel();\n if (model && model.sessions.length >= 10) {\n const profile = computeProfile(model.sessions, model.sessions.length);\n const preemptive: string[] = [];\n\n // Late night + high correlation → extra gentle mode\n const hour = new Date().getHours();\n const isLate = hour >= 21 || hour < 6;\n if (isLate && profile.frustrationCorrelations.lateNight > 0.4) {\n preemptive.push(\n \"Based on past patterns, late-night sessions tend to increase frustration for this user. \" +\n \"Be extra concise, proactive about blockers, and gently suggest wrapping up if frustration rises.\"\n );\n }\n\n // Long session + high correlation → preemptive break suggestion\n const sessionMins = Math.round((Date.now() - getSessionStartTime()) / 60000);\n if (sessionMins > 60 && profile.frustrationCorrelations.longSessions > 0.4) {\n preemptive.push(\n \"This session is getting long and past patterns show long sessions correlate with frustration. \" +\n \"Proactively suggest natural breakpoints.\"\n );\n }\n\n if (preemptive.length > 0) {\n augmentedSystemPrompt += `\\n<feed-forward-v2>\\n${preemptive.join(\"\\n\")}\\n</feed-forward-v2>`;\n }\n }\n } catch {\n // No model — skip feed-forward v2\n }\n\n // Burnout predictor\n try {\n const { loadUserModel, predictBurnout } = await import(\"./user-model.js\");\n const model = await loadUserModel();\n if (model && model.sessions.length >= 5) {\n const sessionMins = Math.round((Date.now() - getSessionStartTime()) / 60000);\n const burnout = predictBurnout(model.sessions, {\n minutes: sessionMins,\n frustration: state.sentiment.frustration,\n timePeriod: period,\n });\n if (burnout.risk > 0.7) {\n const burnoutState = { ...state, wellbeingNudge: \"burnout-warning\" };\n const burnoutNudge = formatWellbeingNudge(burnoutState);\n if (burnoutNudge) {\n augmentedSystemPrompt += \"\\n\" + burnoutNudge;\n }\n }\n }\n } catch {\n // No model — skip\n }\n }\n\n // Cap augmented system prompt to prevent unbounded growth\n const MAX_SYSTEM_TOKENS = 16_000;\n const systemTokens = estimateTokens(augmentedSystemPrompt);\n if (systemTokens > MAX_SYSTEM_TOKENS) {\n // Trim from the end (memories, knowledge, skills are appended last)\n const maxChars = MAX_SYSTEM_TOKENS * 4; // ~4 chars per token\n augmentedSystemPrompt = augmentedSystemPrompt.slice(0, maxChars) + \"\\n[... system context truncated to fit token budget]\";\n log.debug(\"agent\", `system prompt trimmed from ~${systemTokens} to ~${MAX_SYSTEM_TOKENS} tokens`);\n }\n\n const divider = \"─\".repeat(Math.min(process.stdout.columns || 60, 60) - aiName.length - 2);\n process.stdout.write(`\\n ${pc.cyan(pc.bold(aiName))} ${pc.dim(divider)}\\n\\n`);\n\n try {\n abortController = new AbortController();\n isStreaming = true;\n let response = await withRetry(\n () => client.chat(augmentedSystemPrompt, messages, onChunkHandler, tools),\n { maxAttempts: 3, baseDelay: 1000, retryable: isRetryable },\n );\n isStreaming = false;\n\n // Add assistant message to history\n messages.push(response.message);\n\n // Agentic tool loop: execute tools until LLM stops requesting them\n const MAX_TOOL_TURNS = 20;\n let toolTurnCount = 0;\n while (response.toolUses.length > 0 && mcpManager) {\n toolTurnCount++;\n if (toolTurnCount > MAX_TOOL_TURNS) {\n messages.push({\n role: \"assistant\",\n content: \"Tool execution limit reached (20). Breaking to prevent infinite loop.\",\n });\n console.log(pc.yellow(\"\\n Tool execution limit reached (20). Breaking to prevent infinite loop.\"));\n break;\n }\n const toolResults: ToolResultBlock[] = await Promise.all(\n response.toolUses.map(async (toolUse) => {\n if (hooksConfig) {\n const hookCtx: HookContext = { mcpManager: mcpManager!, config: hooksConfig };\n const check = await onBeforeToolExec(toolUse.name, toolUse.input, hookCtx);\n if (!check.allow) {\n process.stdout.write(pc.red(` [BLOCKED: ${check.reason}]\\n`));\n return {\n type: \"tool_result\" as const,\n tool_use_id: toolUse.id,\n content: `BLOCKED by guardrail: ${check.reason}`,\n is_error: true,\n };\n }\n }\n\n // Handle delegate_task virtual tool\n if (toolUse.name === \"delegate_task\" && mcpManager) {\n const input = toolUse.input as { profile: string; task: string };\n // Confirmation: ask user before delegating\n const confirmed = await new Promise<boolean>((resolve) => {\n rl.question(\n pc.cyan(` Delegate to ${pc.bold(input.profile)}? `) + pc.dim(`\"${input.task.slice(0, 80)}${input.task.length > 80 ? \"...\" : \"\"}\" (y/N) `),\n (answer) => resolve(answer.toLowerCase() === \"y\"),\n );\n });\n if (!confirmed) {\n return {\n type: \"tool_result\" as const,\n tool_use_id: toolUse.id,\n content: \"User declined delegation.\",\n is_error: true,\n };\n }\n process.stdout.write(pc.dim(`\\n [delegating to ${input.profile}...]\\n\\n`));\n const result = await delegateTask(input.task, input.profile, client, mcpManager, { tools, hooksConfig });\n const output = result.success\n ? `[${input.profile}] completed:\\n\\n${result.response}`\n : `[${input.profile}] failed: ${result.error}`;\n return {\n type: \"tool_result\" as const,\n tool_use_id: toolUse.id,\n content: output,\n };\n }\n\n // Handle team_run virtual tool\n if (toolUse.name === \"team_run\" && mcpManager) {\n const input = toolUse.input as { team: string; task: string };\n // Confirmation: ask user before launching team\n const confirmed = await new Promise<boolean>((resolve) => {\n rl.question(\n pc.cyan(` Run team ${pc.bold(input.team)}? `) + pc.dim(`\"${input.task.slice(0, 80)}${input.task.length > 80 ? \"...\" : \"\"}\" (y/N) `),\n (answer) => resolve(answer.toLowerCase() === \"y\"),\n );\n });\n if (!confirmed) {\n return {\n type: \"tool_result\" as const,\n tool_use_id: toolUse.id,\n content: \"User declined team execution.\",\n is_error: true,\n };\n }\n const team = loadTeam(input.team);\n if (!team) {\n return {\n type: \"tool_result\" as const,\n tool_use_id: toolUse.id,\n content: `Team not found: ${input.team}`,\n is_error: true,\n };\n }\n const result = await runTeam(team, input.task, client, mcpManager, tools);\n return {\n type: \"tool_result\" as const,\n tool_use_id: toolUse.id,\n content: result.success\n ? formatTeamResult(result)\n : `Team execution failed: ${result.finalOutput}`,\n };\n }\n\n // Check if tool should run in background\n if (shouldRunInBackground(toolUse.name)) {\n const task = bgTasks.launch(toolUse.name, toolUse.id, mcpManager, toolUse.input);\n return {\n type: \"tool_result\" as const,\n tool_use_id: toolUse.id,\n content: `[${toolUse.name} launched in background (${task.id}). Results will appear when ready. Continue with other work.]`,\n };\n }\n\n process.stdout.write(pc.dim(` [using ${toolUse.name}...]\\n`));\n const toolStartMs = Date.now();\n let result: string;\n try {\n result = await mcpManager.callTool(toolUse.name, toolUse.input);\n } catch (toolErr) {\n const errMsg = toolErr instanceof Error ? toolErr.message : String(toolErr);\n if (observationSession) {\n recordEvent(observationSession, {\n type: \"tool_error\",\n summary: `${toolUse.name}: ${errMsg}`,\n data: { tool: toolUse.name, error: errMsg },\n });\n }\n throw toolErr;\n }\n\n // Record successful tool call observation\n if (observationSession) {\n const durationMs = Date.now() - toolStartMs;\n recordEvent(observationSession, {\n type: \"tool_call\",\n summary: `${toolUse.name} (${durationMs}ms)`,\n data: { tool: toolUse.name, durationMs, success: true },\n });\n\n // Detect file-modifying tools and record file_change events\n const FILE_TOOLS = new Set([\"file_write\", \"file_edit\", \"file_create\", \"file_delete\"]);\n if (FILE_TOOLS.has(toolUse.name)) {\n const filePath = (toolUse.input as Record<string, unknown>)?.path ?? \"unknown\";\n recordEvent(observationSession, {\n type: \"file_change\",\n summary: `${toolUse.name}: ${String(filePath)}`,\n data: { tool: toolUse.name, path: filePath },\n });\n }\n }\n\n // Log tool observation to memory (passive capture, fire-and-forget)\n const skipLogging = [\"memory_log\", \"memory_recall\", \"memory_context\", \"memory_detail\", \"reminder_check\"].includes(toolUse.name);\n if (!skipLogging) {\n try {\n memoryLog(sessionId, \"system\", `[tool:${toolUse.name}] input=${JSON.stringify(toolUse.input).slice(0, 500)} result=${result.slice(0, 500)}`);\n } catch {}\n }\n\n return {\n type: \"tool_result\" as const,\n tool_use_id: toolUse.id,\n content: result,\n };\n }),\n );\n\n // Add tool results as a user message\n messages.push({\n role: \"user\",\n content: toolResults,\n });\n\n // Trim conversation if tool results pushed us over token limits\n await trimConversation(messages, client);\n\n // Call LLM again with tool results\n abortController = new AbortController();\n isStreaming = true;\n response = await withRetry(\n () => client.chat(augmentedSystemPrompt, messages, onChunkHandler, tools),\n { maxAttempts: 3, baseDelay: 1000, retryable: isRetryable },\n );\n isStreaming = false;\n\n // Add assistant response to history\n messages.push(response.message);\n }\n\n // Response footer\n const footerParts: string[] = [];\n if (memoryTokens > 0) footerParts.push(`memories: ~${memoryTokens} tokens`);\n const footer = footerParts.length > 0 ? ` ${footerParts.join(\" | \")}` : \"\";\n const footerDivider = \"─\".repeat(Math.min(process.stdout.columns || 60, 60) - footer.length - 1);\n process.stdout.write(pc.dim(` ${footerDivider}${footer}\\n`));\n\n // Periodic session checkpoint (fire-and-forget — prevents data loss on crash)\n const currentTurn = messages.filter((m) => m.role === \"user\").length;\n if (hooksConfig?.autoSessionSave && currentTurn - lastCheckpointTurn >= CHECKPOINT_INTERVAL) {\n lastCheckpointTurn = currentTurn;\n saveConversationToMemory(messages, sessionId).catch(() => {});\n log.debug(\"agent\", `checkpoint saved at turn ${currentTurn}`);\n }\n\n // Periodic flush of buffered observation events (fire-and-forget)\n if (observationSession && observationSession.events.length >= 5) {\n flushEvents(observationSession).catch(() => {});\n }\n\n // Memory extraction (fire-and-forget — never blocks the prompt)\n if (hooksConfig?.extractMemories) {\n const assistantText = typeof response.message.content === \"string\"\n ? response.message.content\n : response.message.content\n .filter((b) => b.type === \"text\")\n .map((b) => (\"text\" in b ? b.text : \"\"))\n .join(\"\");\n\n if (assistantText) {\n runExtraction(\n input, assistantText, client, extractorState,\n ).then((count) => {\n if (count > 0) {\n process.stdout.write(pc.dim(` [${count} memory${count > 1 ? \"ies\" : \"\"} stored]\\n`));\n }\n }).catch(() => {});\n }\n } else {\n extractorState.turnsSinceLastExtraction++;\n }\n\n // Progressive hints\n if (hooksConfig?.featureHints) {\n hintState.turnCount++;\n const hasWorkflows = fs.existsSync(path.join(os.homedir(), \".aflow\", \"flow.md\"));\n const memoryCount = memoryTokens > 0 ? Math.floor(memoryTokens / 5) : 0;\n const hint = getHint(hintState, { hasWorkflows, memoryCount });\n if (hint) {\n process.stdout.write(pc.dim(` ${hint}\\n`));\n saveShownHints(hintState.shownHints);\n }\n }\n } catch (error) {\n isStreaming = false;\n // If aborted by user (Ctrl+C), just add partial response and continue\n if (abortController?.signal.aborted) {\n if (responseBuffer.trim()) {\n messages.push({ role: \"assistant\", content: responseBuffer.trim() });\n if (process.stdout.isTTY) {\n try { logUpdate(marked(responseBuffer.trim()) as string); logUpdate.done(); } catch { logUpdate.done(); }\n }\n responseBuffer = \"\";\n }\n continue;\n }\n const rawMessage = error instanceof Error ? error.message : \"Unknown error occurred\";\n const friendly = humanizeError(rawMessage);\n console.error(pc.red(`\\n ${friendly}`));\n // Don't remove the user message — keep for retry\n }\n }\n}\n\n// Save conversation messages to memory log\nasync function saveConversationToMemory(\n messages: Message[],\n sessionId: string,\n): Promise<void> {\n // Save last 50 messages\n const recentMessages = messages.slice(-50);\n\n for (const msg of recentMessages) {\n if (typeof msg.content !== \"string\") continue;\n try {\n memoryLog(sessionId, msg.role, msg.content.slice(0, 5000));\n } catch (err) {\n log.debug(\"agent\", \"memory_log write failed\", err);\n }\n }\n}\n","declare const __VERSION__: string;\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport os from \"node:os\";\nimport { execFileSync } from \"node:child_process\";\nimport pc from \"picocolors\";\nimport type { McpManager } from \"./mcp/client.js\";\nimport { getEcosystemStatus } from \"./layers/parsers.js\";\nimport { memoryContext, memoryRecall, memoryMultiRecall, memoryForget, memoryStats, memoryExport, memorySince, memorySearch, isMemoryInitialized, reminderSet, reminderList, reminderCheck, reminderComplete, memoryDoctor, memoryRepair, memoryConfig, memoryReflect, memoryConsolidate, memoryTier, memoryDetail, memoryRelate, memoryExpire, memoryVersions, memorySync } from \"./memory.js\";\nimport { listProfiles } from \"./prompt.js\";\nimport { BUILT_IN_PROFILES, installProfileTemplate } from \"./profile-templates.js\";\nimport { loadUserIdentity, hasUserIdentity } from \"./user-identity.js\";\nimport { runOnboarding, editProfile } from \"./onboarding.js\";\nimport { loadShowcaseManifest, installShowcaseTemplate } from \"./showcase-bridge.js\";\nimport { readFile, listFiles } from \"./files.js\";\nimport { delegateTask, delegatePipeline } from \"./delegate.js\";\nimport { smartOrchestrate, createModelRouter } from \"./orchestrator/index.js\";\nimport { listAgents, findAgent } from \"./server/registry.js\";\nimport { StreamableHTTPClientTransport } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport {\n createTeam,\n loadTeam,\n listTeams,\n deleteTeam,\n runTeam,\n formatTeam,\n formatTeamResult,\n BUILT_IN_TEAMS,\n type Team,\n} from \"./teams.js\";\nimport {\n createPlan,\n getActivePlan,\n listPlans,\n loadPlan,\n markStepDone,\n markStepUndone,\n setActivePlan,\n formatPlan,\n} from \"./plans.js\";\nimport {\n type ObservationSession,\n recordEvent,\n getSessionStats,\n pauseObservation,\n resumeObservation,\n} from \"./observation.js\";\nimport {\n generatePostmortemReport,\n savePostmortem,\n listPostmortems,\n readPostmortem,\n analyzePostmortemRange,\n formatPostmortemMarkdown,\n} from \"./postmortem.js\";\nimport {\n ghAvailable,\n ghCurrentRepo,\n listPRs,\n fetchIssue,\n formatIssueAsRequirement,\n isCIPassing,\n} from \"./github/index.js\";\nimport {\n validateCandidate,\n writeSkillToFile,\n appendCrystallizationLog,\n loadSuggestionCounts,\n} from \"./crystallization.js\";\nimport {\n loadUserModel,\n defaultModelPath,\n computeProfile,\n predictBurnout,\n} from \"./user-model.js\";\nimport { loadTaskLog } from \"./background.js\";\n\n// ── aman engine layers (Phase 5: replace file IO + mcpWrite for identity/rules) ──\nimport {\n getIdentity as acoreGetIdentity,\n updateSection as acoreUpdateSection,\n updateDynamics as acoreUpdateDynamics,\n} from \"@aman_asmuei/acore-core\";\nimport {\n listRuleCategories as arulesListCategories,\n addRule as arulesAddRule,\n removeRule as arulesRemoveRule,\n toggleRuleAt as arulesToggleRule,\n checkAction as arulesCheckAction,\n} from \"@aman_asmuei/arules-core\";\n\n/**\n * Canonical scope for aman-agent's slash commands. The CLI runtime is\n * the dev's `dev:agent` surface — distinct from `dev:plugin` (Claude Code)\n * and `dev:default` (the legacy single-tenant catch-all).\n *\n * Override at runtime with $AMAN_AGENT_SCOPE if you want a different\n * default (e.g. `dev:work` vs `dev:personal`).\n */\nconst AGENT_SCOPE: string =\n process.env.AMAN_AGENT_SCOPE ?? \"dev:agent\";\n\nexport interface CommandResult {\n handled: boolean;\n output?: string;\n quit?: boolean;\n clearHistory?: boolean;\n saveConversation?: boolean;\n exportConversation?: boolean;\n}\n\nexport interface CommandContext {\n model?: string;\n mcpManager?: McpManager;\n llmClient?: import(\"./llm/types.js\").LLMClient;\n tools?: import(\"./llm/types.js\").ToolDefinition[];\n observationSession?: ObservationSession;\n messages?: import(\"./llm/types.js\").Message[];\n}\n\nfunction readEcosystemFile(filePath: string, label: string): string {\n if (!fs.existsSync(filePath)) {\n return pc.dim(`No ${label} file found at ${filePath}`);\n }\n return fs.readFileSync(filePath, \"utf-8\").trim();\n}\n\nfunction parseCommand(input: string): { base: string; action?: string; args: string[] } {\n const trimmed = input.trim();\n const parts = trimmed.split(/\\s+/);\n const base = parts[0].toLowerCase().replace(/^\\//, \"\");\n let action = parts.length > 1 ? parts[1].toLowerCase() : undefined;\n if (action === \"--help\" || action === \"-h\") action = \"help\";\n const args = parts.slice(2);\n return { base, action, args };\n}\n\n/**\n * Parse dot-notation key (e.g. \"consolidation.maxStaleDays\") into nested object.\n * Returns { consolidation: { maxStaleDays: val } } instead of { \"consolidation.maxStaleDays\": val }\n */\nfunction buildNestedUpdate(key: string, val: unknown): Record<string, unknown> {\n const parts = key.split(\".\");\n if (parts.length === 1) return { [key]: val };\n const result: Record<string, unknown> = {};\n let curr = result;\n for (let i = 0; i < parts.length - 1; i++) {\n curr[parts[i]] = {};\n curr = curr[parts[i]] as Record<string, unknown>;\n }\n curr[parts[parts.length - 1]] = val;\n return result;\n}\n\nasync function mcpWrite(\n ctx: CommandContext,\n layer: string,\n tool: string,\n args: Record<string, unknown>,\n): Promise<string> {\n if (!ctx.mcpManager) {\n return pc.red(`Cannot modify ${layer}: aman-mcp not connected. Start it with: npx @aman_asmuei/aman-mcp`);\n }\n const result = await ctx.mcpManager.callTool(tool, args);\n if (result.startsWith(\"Error\")) {\n return pc.red(result);\n }\n return pc.green(result);\n}\n\n// --- Layer Handlers ---\n\nasync function handleIdentityCommand(\n action: string | undefined,\n args: string[],\n _ctx: CommandContext,\n): Promise<CommandResult> {\n if (!action) {\n const identity = await acoreGetIdentity(AGENT_SCOPE);\n if (!identity) {\n return {\n handled: true,\n output: pc.dim(\n `No identity configured for ${AGENT_SCOPE}. Run: npx @aman_asmuei/acore`,\n ),\n };\n }\n return { handled: true, output: identity.content.trim() };\n }\n if (action === \"update\") {\n if (args.length === 0) {\n return {\n handled: true,\n output: pc.yellow(\n \"Usage: /identity update <section>\\nTip: describe changes in natural language and the AI will update via acore-core.\",\n ),\n };\n }\n const section = args[0];\n const content = args.slice(1).join(\" \");\n if (!content) {\n return {\n handled: true,\n output: pc.yellow(\n \"Usage: /identity update <section> <new content...>\\nExample: /identity update Personality Warm, curious, and direct.\",\n ),\n };\n }\n try {\n await acoreUpdateSection(section, content, AGENT_SCOPE);\n return { handled: true, output: pc.green(`Updated section: ${section}`) };\n } catch (err) {\n return {\n handled: true,\n output: pc.red(\n `Failed to update ${section}: ${\n err instanceof Error ? err.message : String(err)\n }`,\n ),\n };\n }\n }\n if (action === \"dynamics\") {\n // --json flag: raw JSON output\n if (args.includes(\"--json\")) {\n const model = await loadUserModel();\n if (!model) return { handled: true, output: pc.dim(\"No user model yet. Complete a few sessions first.\") };\n return { handled: true, output: JSON.stringify(model, null, 2) };\n }\n\n // --reset flag: delete model\n if (args.includes(\"--reset\")) {\n const modelPath = defaultModelPath();\n if (fs.existsSync(modelPath)) {\n fs.unlinkSync(modelPath);\n return { handled: true, output: pc.green(\"User model reset. Starting fresh.\") };\n }\n return { handled: true, output: pc.dim(\"No user model to reset.\") };\n }\n\n // key=val args: manual dynamics override (existing behavior)\n const updates: Record<string, string> = {};\n for (const arg of args) {\n const eq = arg.indexOf(\"=\");\n if (eq > 0) updates[arg.slice(0, eq)] = arg.slice(eq + 1);\n }\n if (Object.keys(updates).length > 0) {\n try {\n await acoreUpdateDynamics({\n energy: updates.energy,\n activeMode: updates.mode,\n currentRead: updates.read,\n }, AGENT_SCOPE);\n return { handled: true, output: `Dynamics updated: ${Object.entries(updates).map(([k, v]) => `${k}=${v}`).join(\", \")}` };\n } catch (err) {\n return { handled: true, output: pc.red(`Dynamics error: ${err instanceof Error ? err.message : String(err)}`) };\n }\n }\n\n // No args: show user model summary\n const model = await loadUserModel();\n if (!model) {\n return { handled: true, output: pc.dim(\"No user model yet. Complete a few sessions to start building your profile.\") };\n }\n\n const p = model.profile;\n const trustBar = \"█\".repeat(Math.round(p.trustScore * 10)) + \"░\".repeat(10 - Math.round(p.trustScore * 10));\n const frustBar = \"█\".repeat(Math.round(p.baselineFrustration * 10)) + \"░\".repeat(10 - Math.round(p.baselineFrustration * 10));\n\n const lines = [\n pc.bold(\" Dynamic User Model\"),\n \"\",\n ` ${pc.cyan(\"Trust\")} ${trustBar} ${(p.trustScore * 100).toFixed(0)}% ${p.trustTrajectory === \"ascending\" ? pc.green(\"↑\") : p.trustTrajectory === \"declining\" ? pc.red(\"↓\") : \"→\"}`,\n ` ${pc.cyan(\"Sessions\")} ${p.totalSessions} total (${model.sessions.length} in window)`,\n ` ${pc.cyan(\"Sentiment\")} ${frustBar} frustration baseline ${p.sentimentTrend === \"improving\" ? pc.green(\"improving\") : p.sentimentTrend === \"worsening\" ? pc.red(\"worsening\") : \"stable\"}`,\n \"\",\n ` ${pc.cyan(\"Preferred\")} ${p.preferredTimePeriod} (${Object.entries(p.energyDistribution).map(([k, v]) => `${k}: ${v}`).join(\", \")})`,\n ` ${pc.cyan(\"Avg session\")} ${p.avgSessionMinutes.toFixed(0)} min, ${p.avgTurnsPerSession.toFixed(0)} turns ${p.engagementTrend === \"increasing\" ? pc.green(\"↑\") : p.engagementTrend === \"decreasing\" ? pc.red(\"↓\") : \"→\"}`,\n ];\n\n // Frustration correlations (only show if enough data)\n if (p.totalSessions >= 10) {\n const corrs: string[] = [];\n if (Math.abs(p.frustrationCorrelations.toolErrors) > 0.3) {\n corrs.push(`tool errors (${p.frustrationCorrelations.toolErrors.toFixed(2)})`);\n }\n if (Math.abs(p.frustrationCorrelations.longSessions) > 0.3) {\n corrs.push(`long sessions (${p.frustrationCorrelations.longSessions.toFixed(2)})`);\n }\n if (Math.abs(p.frustrationCorrelations.lateNight) > 0.3) {\n corrs.push(`late night (${p.frustrationCorrelations.lateNight.toFixed(2)})`);\n }\n if (corrs.length > 0) {\n lines.push(` ${pc.cyan(\"Frustration\")} correlates with: ${corrs.join(\", \")}`);\n }\n }\n\n // Nudge stats\n const nudgeKeys = Object.keys(p.nudgeStats);\n if (nudgeKeys.length > 0) {\n lines.push(\"\");\n lines.push(` ${pc.cyan(\"Nudges\")} ${nudgeKeys.map(k => `${k}: ${p.nudgeStats[k].fired}×`).join(\", \")}`);\n }\n\n lines.push(\"\");\n lines.push(pc.dim(` Use --json for raw data, --reset to start fresh`));\n\n return { handled: true, output: lines.join(\"\\n\") };\n }\n if (action === \"summary\") {\n try {\n const identity = await acoreGetIdentity(AGENT_SCOPE);\n if (!identity) return { handled: true, output: pc.yellow(\"No identity configured.\") };\n const nameMatch = identity.content.match(/\\*\\*Name:\\*\\*\\s*(.+)/);\n const lines = [\n `**Identity Summary**`,\n nameMatch ? `Name: ${nameMatch[1].trim()}` : \"\",\n `Scope: ${AGENT_SCOPE}`,\n ].filter(Boolean);\n return { handled: true, output: lines.join(\"\\n\") };\n } catch (err) {\n return { handled: true, output: pc.red(`Summary error: ${err instanceof Error ? err.message : String(err)}`) };\n }\n }\n if (action === \"help\") {\n return {\n handled: true,\n output: [\n pc.bold(\"Identity commands:\"),\n ` ${pc.cyan(\"/identity\")} View current identity`,\n ` ${pc.cyan(\"/identity update\")} <section> Update a section`,\n ` ${pc.cyan(\"/identity dynamics\")} View user model (trust, sentiment, patterns)`,\n ` ${pc.cyan(\"/identity dynamics\")} key=val Update dynamic fields (energy, mode, read)`,\n ` ${pc.cyan(\"/identity dynamics\")} --json Raw JSON user model`,\n ` ${pc.cyan(\"/identity dynamics\")} --reset Reset user model`,\n ` ${pc.cyan(\"/identity summary\")} Show structured identity summary`,\n ].join(\"\\n\"),\n };\n }\n return {\n handled: true,\n output: pc.yellow(\n `Unknown action: /identity ${action}. Try /identity --help`,\n ),\n };\n}\n\nasync function handleRulesCommand(\n action: string | undefined,\n args: string[],\n _ctx: CommandContext,\n): Promise<CommandResult> {\n if (!action) {\n const cats = await arulesListCategories(AGENT_SCOPE);\n if (cats.length === 0) {\n return {\n handled: true,\n output: pc.dim(\n `No rules configured for ${AGENT_SCOPE}. Run: npx @aman_asmuei/arules`,\n ),\n };\n }\n const lines: string[] = [];\n for (const cat of cats) {\n lines.push(pc.bold(`## ${cat.name}`));\n for (const rule of cat.rules) {\n lines.push(` - ${rule}`);\n }\n lines.push(\"\");\n }\n return { handled: true, output: lines.join(\"\\n\").trim() };\n }\n if (action === \"add\") {\n if (args.length < 2) {\n return {\n handled: true,\n output: pc.yellow(\"Usage: /rules add <category> <rule text...>\"),\n };\n }\n const category = args[0];\n const rule = args.slice(1).join(\" \");\n try {\n await arulesAddRule(category, rule, AGENT_SCOPE);\n return {\n handled: true,\n output: pc.green(`Added rule to \"${category}\": ${rule}`),\n };\n } catch (err) {\n return {\n handled: true,\n output: pc.red(\n `Failed: ${err instanceof Error ? err.message : String(err)}`,\n ),\n };\n }\n }\n if (action === \"remove\") {\n if (args.length < 2) {\n return {\n handled: true,\n output: pc.yellow(\"Usage: /rules remove <category> <index>\"),\n };\n }\n const category = args[0];\n const idx = parseInt(args[1], 10);\n if (isNaN(idx) || idx < 1) {\n return {\n handled: true,\n output: pc.yellow(\"Index must be a positive integer.\"),\n };\n }\n try {\n await arulesRemoveRule(category, idx, AGENT_SCOPE);\n return {\n handled: true,\n output: pc.green(`Removed rule ${idx} from \"${category}\"`),\n };\n } catch (err) {\n return {\n handled: true,\n output: pc.red(\n `Failed: ${err instanceof Error ? err.message : String(err)}`,\n ),\n };\n }\n }\n if (action === \"toggle\") {\n if (args.length < 2) {\n return {\n handled: true,\n output: pc.yellow(\"Usage: /rules toggle <category> <index>\"),\n };\n }\n const category = args[0];\n const idx = parseInt(args[1], 10);\n if (isNaN(idx) || idx < 1) {\n return {\n handled: true,\n output: pc.yellow(\"Index must be a positive integer.\"),\n };\n }\n try {\n await arulesToggleRule(category, idx, AGENT_SCOPE);\n return {\n handled: true,\n output: pc.green(`Toggled rule ${idx} in \"${category}\"`),\n };\n } catch (err) {\n return {\n handled: true,\n output: pc.red(\n `Failed: ${err instanceof Error ? err.message : String(err)}`,\n ),\n };\n }\n }\n if (action === \"check\") {\n if (args.length === 0) {\n return { handled: true, output: pc.yellow(\"Usage: /rules check <action description...>\") };\n }\n const description = args.join(\" \");\n try {\n const result = await arulesCheckAction(description, AGENT_SCOPE);\n if (result.safe) {\n return { handled: true, output: pc.green(`Action is allowed: \"${description}\"`) };\n }\n return {\n handled: true,\n output: pc.red(`Action blocked: \"${description}\"\\nViolations:\\n${result.violations.map(v => ` - ${v}`).join(\"\\n\")}`),\n };\n } catch (err) {\n return { handled: true, output: pc.red(`Check error: ${err instanceof Error ? err.message : String(err)}`) };\n }\n }\n if (action === \"help\") {\n return {\n handled: true,\n output: [\n pc.bold(\"Rules commands:\"),\n ` ${pc.cyan(\"/rules\")} View current rules`,\n ` ${pc.cyan(\"/rules add\")} <category> <text> Add a rule`,\n ` ${pc.cyan(\"/rules remove\")} <category> <idx> Remove a rule`,\n ` ${pc.cyan(\"/rules toggle\")} <category> <idx> Toggle a rule`,\n ` ${pc.cyan(\"/rules check\")} <action...> Check if an action is allowed`,\n ].join(\"\\n\"),\n };\n }\n return {\n handled: true,\n output: pc.yellow(`Unknown action: /rules ${action}. Try /rules --help`),\n };\n}\n\nasync function handleWorkflowsCommand(\n action: string | undefined,\n args: string[],\n ctx: CommandContext,\n): Promise<CommandResult> {\n const home = os.homedir();\n if (!action) {\n const content = readEcosystemFile(path.join(home, \".aflow\", \"flow.md\"), \"workflows (aflow)\");\n return { handled: true, output: content };\n }\n if (action === \"add\") {\n if (args.length < 1) {\n return { handled: true, output: pc.yellow(\"Usage: /workflows add <name>\") };\n }\n const output = await mcpWrite(ctx, \"workflows\", \"workflow_add\", { name: args.join(\" \") });\n return { handled: true, output };\n }\n if (action === \"remove\") {\n if (args.length < 1) {\n return { handled: true, output: pc.yellow(\"Usage: /workflows remove <name>\") };\n }\n const output = await mcpWrite(ctx, \"workflows\", \"workflow_remove\", { name: args.join(\" \") });\n return { handled: true, output };\n }\n if (action === \"get\") {\n if (args.length === 0) {\n return { handled: true, output: pc.yellow(\"Usage: /workflows get <name>\") };\n }\n const name = args.join(\" \").toLowerCase();\n const raw = readEcosystemFile(path.join(home, \".aflow\", \"flow.md\"), \"workflows (aflow)\");\n if (raw.startsWith(\"No \")) {\n return { handled: true, output: raw };\n }\n // Parse sections: ## WorkflowName\\n<steps>\n const sections = raw.split(/^## /m).slice(1);\n const match = sections.find(s => s.split(\"\\n\")[0].trim().toLowerCase() === name);\n if (!match) {\n return { handled: true, output: pc.yellow(`No workflow found: \"${args.join(\" \")}\"`) };\n }\n const title = match.split(\"\\n\")[0].trim();\n const body = match.split(\"\\n\").slice(1).join(\"\\n\").trim();\n return { handled: true, output: `## ${title}\\n\\n${body}` };\n }\n if (action === \"help\") {\n return { handled: true, output: [\n pc.bold(\"Workflow commands:\"),\n ` ${pc.cyan(\"/workflows\")} View current workflows`,\n ` ${pc.cyan(\"/workflows add\")} <name> Add a workflow`,\n ` ${pc.cyan(\"/workflows remove\")} <name> Remove a workflow`,\n ` ${pc.cyan(\"/workflows get\")} <name> Show a specific workflow`,\n ].join(\"\\n\") };\n }\n return { handled: true, output: pc.yellow(`Unknown action: /workflows ${action}. Try /workflows --help`) };\n}\n\n// ── /akit slash command — Phase 5 cleanup ───────────────────────────────────\n//\n// The hardcoded AKIT_REGISTRY (17 entries kept \"in sync\" with akit's own\n// registry by hand), the AkitTool/InstalledTool interfaces, and the\n// loadAkitInstalled / saveAkitInstalled / addToAmanAgentConfig /\n// removeFromAmanAgentConfig helpers all lived here in commands.ts. They were\n// a parallel implementation of `akit/src/lib/registry.ts` and `lib/kit.ts`,\n// flagged by the Phase 0 audit as the worst duplication site in aman-agent.\n//\n// Per engine v1 D4: akit is reclassified as DORMANT — it stays as the\n// standalone CLI tool installer, and aman-agent no longer reimplements its\n// registry. This /akit slash command becomes informational, pointing the\n// user at the canonical CLI.\n\nfunction handleAkitCommand(\n _action: string | undefined,\n _args: string[],\n): CommandResult {\n return {\n handled: true,\n output: [\n pc.bold(\"akit — Tool Management\"),\n \"\",\n pc.dim(\n \"Tool management is now handled by the standalone akit CLI rather than\",\n ),\n pc.dim(\n \"duplicated inside aman-agent. The akit slash command is informational only.\",\n ),\n \"\",\n ` ${pc.cyan(\"npx @aman_asmuei/akit list\")} List installed tools`,\n ` ${pc.cyan(\"npx @aman_asmuei/akit search <query>\")} Search the tool registry`,\n ` ${pc.cyan(\"npx @aman_asmuei/akit add <tool>\")} Install a tool`,\n ` ${pc.cyan(\"npx @aman_asmuei/akit remove <tool>\")} Uninstall a tool`,\n \"\",\n pc.dim(\n \"Restart aman-agent after installing/removing tools to pick up changes.\",\n ),\n ].join(\"\\n\"),\n };\n}\n\nasync function handleToolsCommand(\n action: string | undefined,\n args: string[],\n _ctx: CommandContext,\n): Promise<CommandResult> {\n if (!action || action === \"list\") {\n // Informational stub — actual tool management is via akit CLI\n return handleAkitCommand(action, args);\n }\n if (action === \"search\") {\n if (args.length === 0) {\n return { handled: true, output: pc.yellow(\"Usage: /tools search <query...>\") };\n }\n const query = args.join(\" \").toLowerCase();\n const home = os.homedir();\n const toolsFile = path.join(home, \".akit\", \"tools.md\");\n if (!fs.existsSync(toolsFile)) {\n return { handled: true, output: pc.dim(`No tools file found. Use 'npx @aman_asmuei/akit search ${args.join(\" \")}' to search the registry.`) };\n }\n const raw = fs.readFileSync(toolsFile, \"utf-8\").trim();\n const lines = raw.split(\"\\n\");\n const matches = lines.filter(l => l.toLowerCase().includes(query));\n if (matches.length === 0) {\n return { handled: true, output: pc.dim(`No tools matching \"${query}\".`) };\n }\n return { handled: true, output: [pc.bold(`Tools matching \"${query}\":`), ...matches].join(\"\\n\") };\n }\n return handleAkitCommand(action, args);\n}\n\nasync function handleSkillsCommand(\n action: string | undefined,\n args: string[],\n ctx: CommandContext,\n): Promise<CommandResult> {\n const home = os.homedir();\n if (!action) {\n const content = readEcosystemFile(path.join(home, \".askill\", \"skills.md\"), \"skills (askill)\");\n return { handled: true, output: content };\n }\n if (action === \"install\") {\n if (args.length < 1) {\n return { handled: true, output: pc.yellow(\"Usage: /skills install <name>\") };\n }\n const output = await mcpWrite(ctx, \"skills\", \"skill_install\", { name: args.join(\" \") });\n return { handled: true, output };\n }\n if (action === \"uninstall\") {\n if (args.length < 1) {\n return { handled: true, output: pc.yellow(\"Usage: /skills uninstall <name>\") };\n }\n const output = await mcpWrite(ctx, \"skills\", \"skill_uninstall\", { name: args.join(\" \") });\n return { handled: true, output };\n }\n if (action === \"search\") {\n if (args.length === 0) {\n return { handled: true, output: pc.yellow(\"Usage: /skills search <query...>\") };\n }\n const query = args.join(\" \").toLowerCase();\n const home = os.homedir();\n const raw = readEcosystemFile(path.join(home, \".askill\", \"skills.md\"), \"skills (askill)\");\n if (raw.startsWith(\"No \")) {\n return { handled: true, output: raw };\n }\n const lines = raw.split(\"\\n\");\n const matches = lines.filter(l => l.toLowerCase().includes(query));\n if (matches.length === 0) {\n return { handled: true, output: pc.dim(`No skills matching \"${query}\".`) };\n }\n return { handled: true, output: [pc.bold(`Skills matching \"${query}\":`), ...matches].join(\"\\n\") };\n }\n if (action === \"list\") {\n const autoOnly = args.includes(\"--auto\");\n if (autoOnly) {\n const logPath = path.join(os.homedir(), \".aman-agent\", \"crystallization-log.json\");\n try {\n const content = fs.readFileSync(logPath, \"utf-8\");\n const entries = JSON.parse(content) as Array<{\n name: string;\n createdAt: string;\n fromPostmortem: string;\n confidence: number;\n triggers: string[];\n }>;\n if (entries.length === 0) {\n return { handled: true, output: pc.dim(\"No crystallized skills yet.\") };\n }\n const suggestionsPath = path.join(os.homedir(), \".aman-agent\", \"crystallization-suggestions.json\");\n let sugCounts: Record<string, number> = {};\n try {\n const sc = fs.readFileSync(suggestionsPath, \"utf-8\");\n sugCounts = JSON.parse(sc);\n } catch { /* noop */ }\n\n // Count archived versions per skill from skills.md\n let versionCounts: Record<string, number> = {};\n try {\n const skillsContent = fs.readFileSync(path.join(os.homedir(), \".askill\", \"skills.md\"), \"utf-8\");\n const versionRe = /^# (.+)\\.v(\\d+)$/gm;\n let vMatch;\n while ((vMatch = versionRe.exec(skillsContent)) !== null) {\n const skillHeading = vMatch[1].toLowerCase().replace(/ /g, \"-\");\n const ver = parseInt(vMatch[2], 10);\n versionCounts[skillHeading] = Math.max(versionCounts[skillHeading] || 0, ver);\n }\n } catch { /* noop */ }\n\n const lines = [pc.bold(`Crystallized skills (${entries.length}):`)];\n for (const entry of entries) {\n const date = entry.createdAt.slice(0, 10);\n const count = sugCounts[entry.name];\n const reinforced = count && count >= 3 ? pc.green(` ★ reinforced (${count}×)`) : \"\";\n const versions = versionCounts[entry.name];\n const versionLabel = versions ? pc.dim(` [v${versions + 1}]`) : \"\";\n lines.push(` ${pc.cyan(entry.name)} (${date}, conf ${entry.confidence})${reinforced}${versionLabel}`);\n lines.push(pc.dim(` triggers: ${entry.triggers.join(\", \")}`));\n }\n return { handled: true, output: lines.join(\"\\n\") };\n } catch {\n return { handled: true, output: pc.dim(\"No crystallized skills yet.\") };\n }\n }\n const content = readEcosystemFile(path.join(home, \".askill\", \"skills.md\"), \"skills (askill)\");\n return { handled: true, output: content };\n }\n if (action === \"crystallize\") {\n const pmDir = path.join(os.homedir(), \".acore\", \"postmortems\");\n try {\n const files = fs.readdirSync(pmDir);\n const jsonFiles = files.filter((f) => f.endsWith(\".json\")).sort().reverse();\n if (jsonFiles.length === 0) {\n return {\n handled: true,\n output: pc.dim(\"No post-mortems found. Run a session that triggers a post-mortem first.\"),\n };\n }\n const latest = jsonFiles[0];\n const content = fs.readFileSync(path.join(pmDir, latest), \"utf-8\");\n const report = JSON.parse(content);\n if (\n !report.crystallizationCandidates ||\n report.crystallizationCandidates.length === 0\n ) {\n return {\n handled: true,\n output: pc.dim(`No crystallization candidates in the most recent post-mortem (${latest}). Run a longer session or wait for the next auto-postmortem.`),\n };\n }\n\n const skillsMdPath = path.join(os.homedir(), \".askill\", \"skills.md\");\n const logPath = path.join(os.homedir(), \".aman-agent\", \"crystallization-log.json\");\n const postmortemFilename = latest.replace(/\\.json$/, \".md\");\n\n const lines: string[] = [\n pc.bold(`Found ${report.crystallizationCandidates.length} candidate(s) in ${latest}:`),\n ];\n let written = 0;\n for (const raw of report.crystallizationCandidates) {\n const candidate = validateCandidate(raw);\n if (!candidate) {\n const rawName = (raw as { name?: string }).name ?? \"unknown\";\n lines.push(pc.dim(` ⊘ ${rawName} — failed validation`));\n continue;\n }\n const result = await writeSkillToFile(candidate, skillsMdPath, postmortemFilename);\n if (result.written) {\n written++;\n lines.push(pc.green(` ✓ Crystallized: ${candidate.name}`));\n await appendCrystallizationLog(\n {\n name: candidate.name,\n createdAt: new Date().toISOString(),\n fromPostmortem: postmortemFilename,\n confidence: candidate.confidence,\n triggers: candidate.triggers,\n },\n logPath,\n );\n } else {\n lines.push(pc.yellow(` ⊘ ${candidate.name} — ${result.reason}`));\n }\n }\n\n if (written > 0) {\n lines.push(\"\");\n lines.push(pc.dim(`Crystallized skills will auto-activate in your next session.`));\n }\n\n return { handled: true, output: lines.join(\"\\n\") };\n } catch (err) {\n return {\n handled: true,\n output: pc.red(`Failed to load post-mortems: ${err instanceof Error ? err.message : String(err)}`),\n };\n }\n }\n if (action === \"help\") {\n return { handled: true, output: [\n pc.bold(\"Skills commands:\"),\n ` ${pc.cyan(\"/skills\")} View installed skills`,\n ` ${pc.cyan(\"/skills install\")} <name> Install a skill`,\n ` ${pc.cyan(\"/skills uninstall\")} <name> Uninstall a skill`,\n ` ${pc.cyan(\"/skills search\")} <query> Search skills by name/description`,\n ` ${pc.cyan(\"/skills crystallize\")} Crystallize skills from most recent post-mortem`,\n ` ${pc.cyan(\"/skills list --auto\")} List crystallized (auto-created) skills`,\n ].join(\"\\n\") };\n }\n return { handled: true, output: pc.yellow(`Unknown action: /skills ${action}. Try /skills --help`) };\n}\n\nasync function handleEvalCommand(\n action: string | undefined,\n args: string[],\n ctx: CommandContext,\n): Promise<CommandResult> {\n const home = os.homedir();\n if (!action) {\n const content = readEcosystemFile(path.join(home, \".aeval\", \"eval.md\"), \"evaluation (aeval)\");\n return { handled: true, output: content };\n }\n if (action === \"milestone\") {\n if (args.length < 1) {\n return { handled: true, output: pc.yellow(\"Usage: /eval milestone <text...>\") };\n }\n const text = args.join(\" \");\n const output = await mcpWrite(ctx, \"eval\", \"eval_milestone\", { text });\n return { handled: true, output };\n }\n if (action === \"report\") {\n const evalFile = path.join(home, \".aeval\", \"eval.md\");\n const lines: string[] = [pc.bold(\"📊 Eval Report\")];\n\n // Raw eval log\n if (fs.existsSync(evalFile)) {\n lines.push(\"\", fs.readFileSync(evalFile, \"utf-8\").trim());\n } else {\n lines.push(\"\", pc.dim(\"No eval log yet. Use /eval milestone <text> to start.\"));\n }\n\n // Analytics from user model\n try {\n const model = await loadUserModel();\n if (model && model.sessions.length >= 3) {\n const profile = computeProfile(model.sessions, model.profile.totalSessions);\n const burnout = predictBurnout(model.sessions);\n lines.push(\"\", pc.bold(\"── Analytics ──\"));\n lines.push(` Sessions tracked: ${pc.cyan(String(profile.totalSessions))}`);\n lines.push(` Trust score: ${pc.cyan(profile.trustScore.toFixed(2))}`);\n lines.push(` Sentiment trend: ${pc.cyan(profile.sentimentTrend)}`);\n\n // Energy distribution\n const topEnergy = Object.entries(profile.energyDistribution)\n .sort((a, b) => b[1] - a[1])\n .slice(0, 2)\n .map(([k, v]) => `${k} ${(v * 100).toFixed(0)}%`);\n lines.push(` Top energy: ${pc.cyan(topEnergy.join(\", \"))}`);\n\n // Burnout\n const riskColor = burnout.risk > 0.7 ? pc.red : burnout.risk > 0.4 ? pc.yellow : pc.green;\n lines.push(` Burnout risk: ${riskColor((burnout.risk * 100).toFixed(0) + \"%\")} ${burnout.factors.length > 0 ? pc.dim(\"(\" + burnout.factors.join(\", \") + \")\") : \"\"}`);\n\n // Frustration correlations\n const cors = Object.entries(profile.frustrationCorrelations)\n .filter(([, v]) => Math.abs(v) > 0.3)\n .sort((a, b) => Math.abs(b[1]) - Math.abs(a[1]))\n .slice(0, 3);\n if (cors.length > 0) {\n lines.push(` Frustration corr: ${cors.map(([k, v]) => `${k} ${v > 0 ? \"↑\" : \"↓\"}${Math.abs(v).toFixed(2)}`).join(\", \")}`);\n }\n }\n } catch {\n // User model unavailable — skip analytics silently\n }\n\n // Background task history\n try {\n const taskLog = loadTaskLog();\n if (taskLog.length > 0) {\n const completed = taskLog.filter((t) => t.status === \"completed\").length;\n const failed = taskLog.filter((t) => t.status === \"failed\").length;\n const interrupted = taskLog.filter((t) => t.status === \"interrupted\").length;\n lines.push(\"\", pc.bold(\"── Background Tasks ──\"));\n lines.push(` Total: ${taskLog.length} ✅ ${completed} ❌ ${failed} ⚠️ ${interrupted}`);\n }\n } catch {\n // Task log unavailable — skip\n }\n\n return { handled: true, output: lines.join(\"\\n\") };\n }\n return { handled: true, output: pc.yellow(`Unknown action: /eval ${action}. Use /eval, /eval report, or /eval milestone <text>.`) };\n}\n\nasync function handleMemoryCommand(\n action: string | undefined,\n args: string[],\n ctx: CommandContext,\n): Promise<CommandResult> {\n if (!action) {\n // Default: show recent memory context\n try {\n const result = await memoryContext(\"recent context\");\n if (result.memoriesUsed === 0) {\n return { handled: true, output: pc.dim(\"No memories yet. Start chatting and I'll remember what matters.\") };\n }\n return { handled: true, output: result.text };\n } catch (err) {\n return { handled: true, output: pc.red(`Memory error: ${err instanceof Error ? err.message : String(err)}`) };\n }\n }\n // /memory <topic> — shortcut for context on a specific topic\n if (action && ![\"search\", \"clear\", \"timeline\", \"stats\", \"export\", \"since\", \"fts\", \"help\", \"doctor\", \"repair\", \"config\", \"reflect\", \"consolidate\", \"tier\", \"detail\", \"relate\", \"expire\", \"versions\", \"sync\"].includes(action)) {\n try {\n const topic = [action, ...args].join(\" \");\n const result = await memoryContext(topic);\n if (result.memoriesUsed === 0) {\n return { handled: true, output: pc.dim(`No memories found for: \"${topic}\".`) };\n }\n return { handled: true, output: result.text };\n } catch (err) {\n return { handled: true, output: pc.red(`Memory error: ${err instanceof Error ? err.message : String(err)}`) };\n }\n }\n if (action === \"search\") {\n if (args.length < 1) {\n return { handled: true, output: pc.yellow(\"Usage: /memory search <query...>\") };\n }\n const query = args.join(\" \");\n try {\n const result = await memoryMultiRecall(query, { limit: 10 });\n if (result.total === 0) {\n return { handled: true, output: pc.dim(\"No memories found.\") };\n }\n const header = `Search results for \"${query}\" (${result.total}):`;\n const lines: string[] = [pc.bold(header), \"\"];\n for (const m of result.memories) {\n const tags = m.tags?.length > 0\n ? ` ${pc.dim(m.tags.map((t: string) => `#${t}`).join(\" \"))}`\n : \"\";\n lines.push(` [${m.type}] ${m.content}${tags}`);\n }\n return { handled: true, output: lines.join(\"\\n\") };\n } catch (err) {\n return { handled: true, output: pc.red(`Memory error: ${err instanceof Error ? err.message : String(err)}`) };\n }\n }\n if (action === \"clear\") {\n if (args.length < 1) {\n return { handled: true, output: pc.yellow(\"Usage: /memory clear <query> — delete memories matching a search query\\n /memory clear --type <type> — delete all memories of a type (correction|decision|pattern|preference|topology|fact)\") };\n }\n try {\n // Support --type <type> for category-based delete\n if (args[0] === \"--type\" && args[1]) {\n const result = await memoryForget({ type: args[1] });\n return { handled: true, output: result.deleted > 0 ? pc.green(result.message) : pc.dim(result.message) };\n }\n const result = await memoryForget({ query: args.join(\" \") });\n return { handled: true, output: result.deleted > 0 ? pc.green(result.message) : pc.dim(result.message) };\n } catch (err) {\n return { handled: true, output: pc.red(`Memory error: ${err instanceof Error ? err.message : String(err)}`) };\n }\n }\n if (action === \"timeline\") {\n try {\n const result = await memoryRecall(\"*\", { limit: 500, compact: false });\n if (result.total === 0) {\n return { handled: true, output: pc.dim(\"No memories yet. Start chatting and I'll remember what matters.\") };\n }\n const memories = result.memories;\n if (memories.length > 0) {\n const byDate = new Map<string, number>();\n for (const mem of memories) {\n const createdAt = (mem as { created_at?: number }).created_at;\n const date = createdAt\n ? new Date(createdAt).toLocaleDateString(\"en-US\", { month: \"short\", day: \"numeric\" })\n : \"Unknown\";\n byDate.set(date, (byDate.get(date) || 0) + 1);\n }\n const maxCount = Math.max(...byDate.values());\n const barWidth = 10;\n const lines: string[] = [pc.bold(\"Memory Timeline:\"), \"\"];\n for (const [date, count] of byDate) {\n const filled = Math.round((count / maxCount) * barWidth);\n const bar = \"█\".repeat(filled) + \"░\".repeat(barWidth - filled);\n lines.push(` ${date.padEnd(8)} ${bar} ${count} memories`);\n }\n const tags = new Map<string, number>();\n for (const mem of memories) {\n const memTags = (mem as { tags?: string[] }).tags;\n if (Array.isArray(memTags)) {\n for (const tag of memTags) {\n tags.set(tag, (tags.get(tag) || 0) + 1);\n }\n }\n }\n lines.push(\"\");\n lines.push(` Total: ${result.total} memories`);\n if (tags.size > 0) {\n const topTags = [...tags.entries()]\n .sort((a, b) => b[1] - a[1])\n .slice(0, 5)\n .map(([tag, count]) => `#${tag} (${count})`)\n .join(\", \");\n lines.push(` Top tags: ${topTags}`);\n }\n return { handled: true, output: lines.join(\"\\n\") };\n }\n return { handled: true, output: `Total memories: ${result.total} entries.` };\n } catch {\n return { handled: true, output: pc.red(\"Failed to retrieve memory timeline.\") };\n }\n }\n if (action === \"stats\") {\n try {\n const stats = memoryStats();\n const lines: string[] = [pc.bold(\"Memory Statistics:\"), \"\"];\n lines.push(` Total memories: ${pc.bold(String(stats.total))}`);\n if (Object.keys(stats.byType).length > 0) {\n lines.push(\"\");\n lines.push(` ${pc.dim(\"By type:\")}`);\n for (const [type, count] of Object.entries(stats.byType)) {\n lines.push(` ${type.padEnd(16)} ${count}`);\n }\n }\n return { handled: true, output: lines.join(\"\\n\") };\n } catch (err) {\n return { handled: true, output: pc.red(`Memory error: ${err instanceof Error ? err.message : String(err)}`) };\n }\n }\n if (action === \"export\") {\n try {\n const format = args[0] === \"json\" ? \"json\" : \"markdown\";\n const memories = memoryExport();\n if (memories.length === 0) {\n return { handled: true, output: pc.dim(\"No memories to export.\") };\n }\n if (format === \"json\") {\n const jsonOut = memories.map(m => ({ id: m.id, type: m.type, content: m.content, tags: m.tags, confidence: m.confidence, createdAt: m.createdAt, tier: m.tier }));\n return { handled: true, output: JSON.stringify(jsonOut, null, 2) };\n }\n const lines: string[] = [`# Memory Export (${memories.length} memories)`, \"\"];\n for (const m of memories) {\n const date = new Date(m.createdAt).toLocaleDateString();\n const tags = m.tags.length > 0 ? ` [${m.tags.map(t => `#${t}`).join(\", \")}]` : \"\";\n lines.push(`- **[${m.type}]** ${m.content}${tags} ${pc.dim(`(${date}, ${Math.round(m.confidence * 100)}%)`)}`);\n }\n return { handled: true, output: lines.join(\"\\n\") };\n } catch (err) {\n return { handled: true, output: pc.red(`Memory error: ${err instanceof Error ? err.message : String(err)}`) };\n }\n }\n if (action === \"since\") {\n try {\n let hours = 24;\n if (args[0]) {\n const match = args[0].match(/^(\\d+)(h|d|w)$/);\n if (match) {\n const value = parseInt(match[1], 10);\n const unit = match[2];\n if (unit === \"h\") hours = value;\n else if (unit === \"d\") hours = value * 24;\n else if (unit === \"w\") hours = value * 24 * 7;\n } else {\n return { handled: true, output: pc.yellow(\"Usage: /memory since <Nh|Nd|Nw> (e.g., 24h, 7d, 1w)\") };\n }\n }\n const memories = memorySince(hours);\n if (memories.length === 0) {\n return { handled: true, output: pc.dim(`No memories in the last ${args[0] || \"24h\"}.`) };\n }\n const lines: string[] = [pc.bold(`Memories since ${args[0] || \"24h\"} (${memories.length}):`), \"\"];\n for (const m of memories) {\n const age = Math.round((Date.now() - m.createdAt) / 3600000);\n const ageStr = age < 1 ? \"<1h ago\" : `${age}h ago`;\n lines.push(` ${pc.dim(ageStr.padEnd(10))} [${m.type}] ${m.content}`);\n }\n return { handled: true, output: lines.join(\"\\n\") };\n } catch (err) {\n return { handled: true, output: pc.red(`Memory error: ${err instanceof Error ? err.message : String(err)}`) };\n }\n }\n if (action === \"fts\") {\n if (args.length < 1) {\n return { handled: true, output: pc.yellow(\"Usage: /memory fts <query...> — full-text search\") };\n }\n try {\n const query = args.join(\" \");\n const results = memorySearch(query, 20);\n if (results.length === 0) {\n return { handled: true, output: pc.dim(`No results for full-text search: \"${query}\".`) };\n }\n const lines: string[] = [pc.bold(`FTS results for \"${query}\" (${results.length}):`), \"\"];\n for (const m of results) {\n const tags = m.tags.length > 0 ? ` ${pc.dim(m.tags.map(t => `#${t}`).join(\" \"))}` : \"\";\n lines.push(` [${m.type}] ${m.content}${tags}`);\n }\n return { handled: true, output: lines.join(\"\\n\") };\n } catch (err) {\n return { handled: true, output: pc.red(`Memory error: ${err instanceof Error ? err.message : String(err)}`) };\n }\n }\n if (action === \"help\") {\n return { handled: true, output: [\n pc.bold(\"Memory commands:\"),\n ` ${pc.cyan(\"/memory\")} View recent context`,\n ` ${pc.cyan(\"/memory\")} <topic> Context for a topic`,\n ` ${pc.cyan(\"/memory search\")} <query> Search memories (semantic)`,\n ` ${pc.cyan(\"/memory fts\")} <query> Full-text search (FTS5)`,\n ` ${pc.cyan(\"/memory since\")} <Nh|Nd|Nw> Memories from time window`,\n ` ${pc.cyan(\"/memory stats\")} Show memory statistics`,\n ` ${pc.cyan(\"/memory export\")} [json] Export all memories`,\n ` ${pc.cyan(\"/memory timeline\")} View memory timeline`,\n ` ${pc.cyan(\"/memory clear\")} <query> Delete matching memories`,\n ` ${pc.cyan(\"/memory clear --type\")} <type> Delete all of a type`,\n ` ${pc.cyan(\"/memory doctor\")} Run memory diagnostics`,\n ` ${pc.cyan(\"/memory repair\")} Dry-run repair (safe)`,\n ` ${pc.cyan(\"/memory config\")} [key=value] View or update config (e.g. consolidation.maxStaleDays=60)`,\n ].join(\"\\n\") };\n }\n if (action === \"doctor\") {\n try {\n const diag = await memoryDoctor();\n const statusIcon = diag.status === \"healthy\" ? \"✅\" : \"⚠️\";\n const lines: string[] = [\n `**Memory Diagnostics**`,\n `Status: ${statusIcon} ${diag.status}`,\n ];\n if (diag.issues?.length) {\n lines.push(\"\", \"**Issues:**\");\n for (const issue of diag.issues) {\n lines.push(`- ${typeof issue === \"string\" ? issue : (issue as { message?: string }).message ?? String(issue)}`);\n }\n lines.push(\"\", \"_Run `/memory repair` (dry-run) or `/memory repair --apply` to fix._\");\n }\n return { handled: true, output: lines.join(\"\\n\") };\n } catch (err) {\n return { handled: true, output: pc.red(`Memory doctor error: ${err instanceof Error ? err.message : String(err)}`) };\n }\n }\n if (action === \"repair\") {\n try {\n const dryRun = !args.includes(\"--apply\");\n const result = await memoryRepair({ dryRun });\n const prefix = dryRun ? \"[DRY RUN] \" : \"\";\n const lines: string[] = [`**${prefix}Memory Repair**`];\n if (result.actions?.length) {\n lines.push(\"\", \"**Actions:**\");\n for (const act of result.actions) {\n lines.push(`- ${act}`);\n }\n } else {\n lines.push(\"No actions needed.\");\n }\n if (dryRun) {\n lines.push(\"\", \"_Run `/memory repair --apply` to execute._\");\n }\n return { handled: true, output: lines.join(\"\\n\") };\n } catch (err) {\n return { handled: true, output: pc.red(`Memory repair error: ${err instanceof Error ? err.message : String(err)}`) };\n }\n }\n if (action === \"config\") {\n try {\n const kvArg = args.find((a: string) => a.includes(\"=\") && !a.startsWith(\"-\"));\n if (kvArg) {\n const eqIdx = kvArg.indexOf(\"=\");\n const key = kvArg.slice(0, eqIdx);\n const rawVal = kvArg.slice(eqIdx + 1);\n if (!rawVal) {\n return { handled: true, output: pc.yellow(`Usage: /memory config <key>=<value>`) };\n }\n const val = isNaN(Number(rawVal)) ? rawVal : Number(rawVal);\n const update = buildNestedUpdate(key, val);\n await memoryConfig(update);\n return { handled: true, output: `✅ Set \\`${key}\\` → \\`${val}\\`` };\n }\n const config = await memoryConfig();\n const lines = [\"**Memory Config**\", \"```\"];\n for (const [k, v] of Object.entries(config as Record<string, unknown>)) {\n if (typeof v === \"object\" && v !== null) {\n for (const [sk, sv] of Object.entries(v as Record<string, unknown>)) {\n lines.push(`${k}.${sk}: ${sv}`);\n }\n } else {\n lines.push(`${k}: ${v}`);\n }\n }\n lines.push(\"```\", \"\", \"_Use `/memory config key=value` to change a setting._\");\n return { handled: true, output: lines.join(\"\\n\") };\n } catch (err) {\n return { handled: true, output: pc.red(`Memory config error: ${err instanceof Error ? err.message : String(err)}`) };\n }\n }\n if (action === \"reflect\") {\n try {\n const report = await memoryReflect();\n const lines = [\n pc.bold(\"Reflection complete\"),\n `Clusters: ${report.clusters.length}`,\n `Contradictions: ${report.contradictions.length}`,\n `Synthesis candidates: ${report.synthesisCandidates.length}`,\n `Knowledge gaps: ${report.knowledgeGaps.length}`,\n `Health score: ${(report.stats.healthScore * 100).toFixed(0)}%`,\n `Duration: ${report.durationMs}ms`,\n ];\n return { handled: true, output: lines.join(\"\\n\") };\n } catch (err) {\n return { handled: true, output: pc.red(`Reflect error: ${err instanceof Error ? err.message : String(err)}`) };\n }\n }\n if (action === \"consolidate\") {\n const apply = args.includes(\"--apply\");\n try {\n const report = memoryConsolidate(!apply);\n const lines = [\n apply ? pc.bold(\"Consolidation applied\") : pc.bold(\"Consolidation dry-run\"),\n `Merged: ${report.merged}`,\n `Pruned: ${report.pruned}`,\n `Promoted: ${report.promoted}`,\n `Decayed: ${report.decayed}`,\n `Health score: ${(report.healthScore * 100).toFixed(0)}%`,\n `Before: ${report.before.total} → After: ${report.after.total}`,\n ];\n if (!apply) lines.push(pc.dim(\"Run with --apply to execute.\"));\n return { handled: true, output: lines.join(\"\\n\") };\n } catch (err) {\n return { handled: true, output: pc.red(`Consolidate error: ${err instanceof Error ? err.message : String(err)}`) };\n }\n }\n if (action === \"tier\") {\n const id = args[0];\n const tier = args[1];\n if (!id || !tier) {\n return { handled: true, output: pc.yellow(\"Usage: /memory tier <id> <core|working|archival>\") };\n }\n const tierResult = memoryTier(id, tier);\n if (!tierResult.ok) {\n return { handled: true, output: pc.red(`Tier error: ${tierResult.error}`) };\n }\n return { handled: true, output: `✅ Memory ${tierResult.id} moved to tier: ${tierResult.tier}` };\n }\n if (action === \"detail\") {\n const id = args[0];\n if (!id) {\n return { handled: true, output: pc.yellow(\"Usage: /memory detail <id>\") };\n }\n const memory = memoryDetail(id);\n if (!memory) {\n return { handled: true, output: pc.dim(`Memory not found: ${id}`) };\n }\n const lines = [\n pc.bold(`Memory: ${memory.id}`),\n `Content: ${memory.content}`,\n `Type: ${memory.type}`,\n `Confidence: ${memory.confidence}`,\n `Tier: ${(memory as any).tier ?? \"working\"}`,\n `Access count: ${memory.accessCount}`,\n `Created: ${new Date(memory.createdAt).toISOString()}`,\n memory.tags?.length ? `Tags: ${memory.tags.join(\", \")}` : \"\",\n ].filter(Boolean);\n return { handled: true, output: lines.join(\"\\n\") };\n }\n if (action === \"relate\") {\n const [fromId, toId, relType, strengthStr] = args;\n if (!fromId || !toId || !relType) {\n return { handled: true, output: pc.yellow(\"Usage: /memory relate <fromId> <toId> <type> [strength]\") };\n }\n const strength = strengthStr !== undefined ? parseFloat(strengthStr) : undefined;\n const relResult = memoryRelate(fromId, toId, relType, strength);\n if (!relResult.ok) {\n return { handled: true, output: pc.red(`Relate error: ${relResult.error}`) };\n }\n return { handled: true, output: `✅ Relation created: ${fromId} --[${relType}]--> ${toId} (id: ${relResult.relationId})` };\n }\n if (action === \"expire\") {\n const id = args[0];\n if (!id) {\n return { handled: true, output: pc.yellow(\"Usage: /memory expire <id> [reason]\") };\n }\n const reason = args.slice(1).join(\" \") || undefined;\n const expireResult = memoryExpire(id, reason);\n if (!expireResult.ok) {\n return { handled: true, output: pc.red(`Expire error: ${expireResult.error}`) };\n }\n return { handled: true, output: `✅ Memory ${expireResult.id} expired${reason ? `: ${reason}` : \"\"}` };\n }\n if (action === \"versions\") {\n const id = args[0];\n if (!id) {\n return { handled: true, output: pc.yellow(\"Usage: /memory versions <id>\") };\n }\n const versions = memoryVersions(id);\n if (!versions.length) {\n return { handled: true, output: pc.dim(`No version history for: ${id}`) };\n }\n const lines = [pc.bold(`Version history for ${id}:`)];\n for (const v of versions) {\n lines.push(` [${new Date(v.editedAt).toISOString()}] ${v.content.slice(0, 80)}${v.content.length > 80 ? \"\\u2026\" : \"\"}`);\n }\n return { handled: true, output: lines.join(\"\\n\") };\n }\n if (action === \"sync\") {\n const syncAction = args[0] as \"import-claude\" | \"export-team\" | \"import-team\" | \"sync-copilot\" | undefined;\n if (!syncAction) {\n return { handled: true, output: pc.yellow(\"Usage: /memory sync <import-claude|export-team|import-team|sync-copilot>\") };\n }\n try {\n const opts: Record<string, string | boolean | undefined> = {};\n for (const arg of args.slice(1)) {\n if (arg.startsWith(\"--\")) {\n const [k, v] = arg.slice(2).split(\"=\");\n opts[k] = v ?? true;\n }\n }\n const result = await memorySync(syncAction, opts as any);\n return { handled: true, output: `✅ Sync [${syncAction}] complete:\\n${JSON.stringify(result, null, 2)}` };\n } catch (err) {\n return { handled: true, output: pc.red(`Sync error: ${err instanceof Error ? err.message : String(err)}`) };\n }\n }\n return { handled: true, output: pc.yellow(`Unknown action: /memory ${action}. Try /memory --help`) };\n}\n\nfunction handleStatusCommand(ctx: CommandContext): CommandResult {\n const mcpToolCount = ctx.mcpManager ? ctx.mcpManager.getTools().length : 0;\n const amemConnected = isMemoryInitialized();\n const status = getEcosystemStatus(mcpToolCount, amemConnected);\n\n const lines: string[] = [pc.bold(\"Aman Ecosystem Dashboard\"), \"\"];\n\n for (const layer of status.layers) {\n const icon = layer.exists ? pc.green(\"●\") : pc.dim(\"○\");\n const name = pc.bold(layer.name.padEnd(12));\n const summary = layer.exists ? layer.summary : pc.dim(\"not configured\");\n lines.push(` ${icon} ${name} ${summary}`);\n }\n\n lines.push(\"\");\n lines.push(` ${status.mcpConnected ? pc.green(\"●\") : pc.dim(\"○\")} ${pc.bold(\"MCP\".padEnd(12))} ${status.mcpConnected ? `${status.mcpToolCount} tools available` : pc.dim(\"not connected\")}`);\n lines.push(` ${status.amemConnected ? pc.green(\"●\") : pc.dim(\"○\")} ${pc.bold(\"Memory\".padEnd(12))} ${status.amemConnected ? \"connected\" : pc.dim(\"not connected\")}`);\n\n return { handled: true, output: lines.join(\"\\n\") };\n}\n\nfunction handleDoctorCommand(ctx: CommandContext): CommandResult {\n const mcpToolCount = ctx.mcpManager ? ctx.mcpManager.getTools().length : 0;\n const amemConnected = isMemoryInitialized();\n const status = getEcosystemStatus(mcpToolCount, amemConnected);\n\n const lines: string[] = [pc.bold(\"Aman Health Check\"), \"\"];\n let healthy = 0;\n let fixes = 0;\n let suggestions = 0;\n\n for (const layer of status.layers) {\n if (layer.exists) {\n lines.push(` ${pc.green(\"✓\")} ${layer.name.padEnd(12)} ${pc.green(layer.summary)}`);\n healthy++;\n } else {\n const isRequired = [\"identity\", \"rules\"].includes(layer.name.toLowerCase());\n if (isRequired) {\n lines.push(` ${pc.red(\"✗\")} ${layer.name.padEnd(12)} ${pc.red(\"missing\")}`);\n lines.push(` ${pc.dim(\"→ Fix: aman-agent init\")}`);\n fixes++;\n } else {\n lines.push(` ${pc.yellow(\"⚠\")} ${layer.name.padEnd(12)} ${pc.yellow(\"empty\")}`);\n const cmd = layer.name.toLowerCase() === \"workflows\" ? \"/workflows add <name>\"\n : layer.name.toLowerCase() === \"tools\" ? \"/tools add <name> <type> <desc>\"\n : layer.name.toLowerCase() === \"skills\" ? \"/skills install <name>\"\n : \"\";\n if (cmd) lines.push(` ${pc.dim(`→ Add with ${cmd}`)}`);\n suggestions++;\n }\n }\n }\n\n lines.push(\"\");\n lines.push(` ${status.mcpConnected ? pc.green(\"✓\") : pc.red(\"✗\")} ${\"MCP\".padEnd(12)} ${status.mcpConnected ? pc.green(`${status.mcpToolCount} tools`) : pc.red(\"not connected\")}`);\n if (!status.mcpConnected) {\n lines.push(` ${pc.dim(\"→ Fix: ensure npx is available and network is connected\")}`);\n fixes++;\n } else {\n healthy++;\n }\n\n lines.push(` ${status.amemConnected ? pc.green(\"✓\") : pc.red(\"✗\")} ${\"Memory\".padEnd(12)} ${status.amemConnected ? pc.green(\"connected\") : pc.red(\"not connected\")}`);\n if (!status.amemConnected) {\n lines.push(` ${pc.dim(\"→ Fix: restart aman-agent (memory initializes automatically)\")}`);\n fixes++;\n } else {\n healthy++;\n }\n\n const total = healthy + fixes + suggestions;\n lines.push(\"\");\n lines.push(` Overall: ${healthy}/${total} healthy.${fixes > 0 ? ` ${fixes} fix${fixes > 1 ? \"es\" : \"\"} needed.` : \"\"}${suggestions > 0 ? ` ${suggestions} suggestion${suggestions > 1 ? \"s\" : \"\"}.` : \"\"}`);\n\n return { handled: true, output: lines.join(\"\\n\") };\n}\n\nfunction handleHelp(): CommandResult {\n return {\n handled: true,\n output: [\n pc.bold(\"Commands:\"),\n ` ${pc.cyan(\"/help\")} Show this help`,\n ` ${pc.cyan(\"/identity\")} View identity [update <section>]`,\n ` ${pc.cyan(\"/rules\")} View rules [add|remove|toggle ...]`,\n ` ${pc.cyan(\"/workflows\")} View workflows [add|remove ...]`,\n ` ${pc.cyan(\"/akit\")} Manage tools [add|remove <tool>]`,\n ` ${pc.cyan(\"/skills\")} View skills [install|uninstall|crystallize|list --auto]`,\n ` ${pc.cyan(\"/eval\")} View evaluation [milestone ...]`,\n ` ${pc.cyan(\"/memory\")} View recent memories [search|fts|since|stats|export|clear|timeline]`,\n ` ${pc.cyan(\"/reminder\")} Manage reminders [set|check|done]`,\n ` ${pc.cyan(\"/status\")} Ecosystem dashboard`,\n ` ${pc.cyan(\"/doctor\")} Health check all layers`,\n ` ${pc.cyan(\"/decisions\")} View decision log [<project>]`,\n ` ${pc.cyan(\"/export\")} Export conversation to markdown`,\n ` ${pc.cyan(\"/debug\")} Show debug log`,\n ` ${pc.cyan(\"/save\")} Save conversation to memory`,\n ` ${pc.cyan(\"/model\")} Show current LLM model`,\n ` ${pc.cyan(\"/plan\")} Manage multi-step plans`,\n ` ${pc.cyan(\"/profile me\")} View your profile`,\n ` ${pc.cyan(\"/profile edit\")} Edit your profile`,\n ` ${pc.cyan(\"/profile\")} List agent profiles`,\n ` ${pc.cyan(\"/showcase\")} Browse & switch companion templates`,\n ` ${pc.cyan(\"/delegate\")} Delegate tasks to sub-agents`,\n ` ${pc.cyan(\"/team\")} Manage agent teams`,\n ` ${pc.cyan(\"/observe\")} Session observation dashboard [pause|resume]`,\n ` ${pc.cyan(\"/postmortem\")} Generate post-mortem [last|list|--since 7d]`,\n ` ${pc.cyan(\"/update\")} Check for updates`,\n ` ${pc.cyan(\"/reset\")} Full reset [all|memory|config|identity|rules]`,\n ` ${pc.cyan(\"/clear\")} Clear conversation history`,\n ` ${pc.cyan(\"/quit\")} Exit`,\n ].join(\"\\n\"),\n };\n}\n\nfunction handleSave(): CommandResult {\n return { handled: true, saveConversation: true };\n}\n\nfunction handleReset(action: string | undefined): CommandResult {\n const dirs = {\n config: path.join(os.homedir(), \".aman-agent\"),\n memory: path.join(os.homedir(), \".amem\"),\n identity: path.join(os.homedir(), \".acore\"),\n rules: path.join(os.homedir(), \".arules\"),\n };\n\n if (action === \"help\" || !action) {\n return {\n handled: true,\n output: [\n pc.bold(\"Reset options:\"),\n ` ${pc.cyan(\"/reset all\")} Full reset — config, memory, identity, rules`,\n ` ${pc.cyan(\"/reset memory\")} Clear all memories only`,\n ` ${pc.cyan(\"/reset config\")} Reset LLM config only`,\n ` ${pc.cyan(\"/reset identity\")} Reset persona/identity only`,\n ` ${pc.cyan(\"/reset rules\")} Reset guardrails only`,\n \"\",\n pc.dim(\"Directories:\"),\n ...Object.entries(dirs).map(([k, v]) => ` ${k}: ${pc.dim(v)}`),\n ].join(\"\\n\"),\n };\n }\n\n const targets: Array<keyof typeof dirs> =\n action === \"all\" ? [\"config\", \"memory\", \"identity\", \"rules\"] : [action as keyof typeof dirs];\n\n if (!targets.every((t) => t in dirs)) {\n return { handled: true, output: pc.red(`Unknown target: ${action}. Use /reset help`) };\n }\n\n const removed: string[] = [];\n for (const target of targets) {\n const dir = dirs[target];\n if (fs.existsSync(dir)) {\n fs.rmSync(dir, { recursive: true, force: true });\n removed.push(target);\n }\n }\n\n // Write .reconfig marker so next run forces interactive LLM prompt\n if (targets.includes(\"config\")) {\n const configDir = dirs.config;\n fs.mkdirSync(configDir, { recursive: true });\n fs.writeFileSync(path.join(configDir, \".reconfig\"), \"\", \"utf-8\");\n }\n\n if (removed.length === 0) {\n return { handled: true, output: pc.dim(\"Nothing to reset — directories don't exist.\") };\n }\n\n return {\n handled: true,\n quit: true,\n output: [\n pc.green(`Reset complete: ${removed.join(\", \")}`),\n \"Restart aman-agent to begin fresh.\",\n ].join(\"\\n\"),\n };\n}\n\nfunction handleUpdate(): CommandResult {\n try {\n const current = execFileSync(\"npm\", [\"view\", \"@aman_asmuei/aman-agent\", \"version\"], { encoding: \"utf-8\" }).trim();\n const local = typeof __VERSION__ !== \"undefined\" ? __VERSION__ : \"unknown\";\n if (current === local) {\n return { handled: true, output: `${pc.green(\"Up to date\")} — v${local}` };\n }\n // Detect vendored install (node lives inside ~/.aman-agent/node/)\n const isVendored = process.execPath.includes(path.join(\".aman-agent\", \"node\"));\n const updateCmd = isVendored\n ? \"aman-agent update\"\n : \"npm install -g @aman_asmuei/aman-agent@latest\";\n\n return {\n handled: true,\n output: [\n `${pc.yellow(\"Update available:\")} v${local} → v${current}`,\n \"\",\n `Run this in your terminal:`,\n ` ${pc.bold(updateCmd)}`,\n ].join(\"\\n\"),\n };\n } catch {\n return {\n handled: true,\n output: [\n `To update, run in your terminal:`,\n ` ${pc.bold(\"npm install -g @aman_asmuei/aman-agent@latest\")}`,\n ].join(\"\\n\"),\n };\n }\n}\n\nasync function handleDecisionsCommand(\n action: string | undefined,\n _args: string[],\n _ctx: CommandContext,\n): Promise<CommandResult> {\n try {\n const result = await memoryRecall(\"decision\", { type: \"decision\", limit: 20 });\n if (result.total === 0) {\n return { handled: true, output: pc.dim(\"No decisions recorded yet.\") };\n }\n return { handled: true, output: pc.bold(\"Decision Log:\\n\") + result.text };\n } catch (err) {\n return { handled: true, output: pc.red(`Memory error: ${err instanceof Error ? err.message : String(err)}`) };\n }\n}\n\nfunction handleExportCommand(): CommandResult {\n return { handled: true, exportConversation: true };\n}\n\nfunction handleDebugCommand(): CommandResult {\n const logPath = path.join(os.homedir(), \".aman-agent\", \"debug.log\");\n if (!fs.existsSync(logPath)) {\n return { handled: true, output: pc.dim(\"No debug log found.\") };\n }\n const content = fs.readFileSync(logPath, \"utf-8\");\n const lines = content.trim().split(\"\\n\");\n const last20 = lines.slice(-20).join(\"\\n\");\n return { handled: true, output: pc.bold(\"Debug Log (last 20 entries):\\n\") + pc.dim(last20) };\n}\n\n// --- Main Router ---\n\n// --- Teams ---\n\nasync function handleTeamCommand(action: string | undefined, args: string[], ctx: CommandContext): Promise<CommandResult> {\n if (!action || action === \"list\") {\n const teams = listTeams();\n if (teams.length === 0) {\n return {\n handled: true,\n output: pc.dim(\"No teams yet. Create one:\") +\n \"\\n /team create <name> Create from built-in template\" +\n \"\\n /team create Show available templates\",\n };\n }\n const lines = teams.map((t) => {\n const members = t.members.map((m) => m.profile).join(\", \");\n return ` ${pc.bold(t.name)} (${t.workflow}) — ${members}`;\n });\n return { handled: true, output: \"Teams:\\n\" + lines.join(\"\\n\") };\n }\n\n switch (action) {\n case \"create\": {\n const name = args[0];\n if (!name) {\n const lines = BUILT_IN_TEAMS.map((t) => {\n const members = t.members.map((m) => m.profile).join(\" → \");\n return ` ${pc.bold(t.name)} (${t.workflow}) — ${members}\\n ${pc.dim(t.goal)}`;\n });\n return {\n handled: true,\n output: \"Built-in teams:\\n\" + lines.join(\"\\n\\n\") +\n \"\\n\\nUsage:\\n /team create content-team Install built-in\" +\n \"\\n /team create <name> <mode> <profile1:role>,<profile2:role> Custom\",\n };\n }\n\n // Check if it's a built-in template\n const builtIn = BUILT_IN_TEAMS.find((t) => t.name === name);\n if (builtIn) {\n createTeam(builtIn);\n return { handled: true, output: pc.green(`Team installed: ${builtIn.name}`) + \"\\n\\n\" + formatTeam(builtIn) };\n }\n\n // Custom team: /team create <name> <mode> <profile:role>,<profile:role>\n const mode = args[1] as Team[\"workflow\"];\n const membersStr = args[2];\n if (!mode || !membersStr) {\n return { handled: true, output: pc.yellow(\"Usage: /team create <name> <pipeline|parallel|coordinator> <profile1:role>,<profile2:role>\") };\n }\n if (![\"pipeline\", \"parallel\", \"coordinator\"].includes(mode)) {\n return { handled: true, output: pc.yellow(\"Mode must be: pipeline, parallel, or coordinator\") };\n }\n\n const members = membersStr.split(\",\").map((m) => {\n const [profile, ...roleParts] = m.trim().split(\":\");\n return { profile: profile.trim(), role: roleParts.join(\":\").trim() || profile.trim() };\n });\n\n const team: Team = {\n name,\n goal: `Team: ${name}`,\n coordinator: \"default\",\n members,\n workflow: mode,\n };\n createTeam(team);\n return { handled: true, output: pc.green(`Team created!`) + \"\\n\\n\" + formatTeam(team) };\n }\n\n case \"run\": {\n const teamName = args[0];\n const task = args.slice(1).join(\" \");\n if (!teamName || !task) {\n return { handled: true, output: pc.yellow(\"Usage: /team run <team-name> <task description>\") };\n }\n\n const team = loadTeam(teamName);\n if (!team) return { handled: true, output: pc.red(`Team not found: ${teamName}`) };\n\n if (!ctx.llmClient || !ctx.mcpManager) {\n return { handled: true, output: pc.red(\"Team execution requires LLM client and MCP.\") };\n }\n\n const result = await runTeam(team, task, ctx.llmClient, ctx.mcpManager, ctx.tools);\n return { handled: true, output: formatTeamResult(result) };\n }\n\n case \"show\": {\n const name = args[0];\n if (!name) return { handled: true, output: pc.yellow(\"Usage: /team show <name>\") };\n const team = loadTeam(name);\n if (!team) return { handled: true, output: pc.red(`Team not found: ${name}`) };\n return { handled: true, output: formatTeam(team) };\n }\n\n case \"delete\": {\n const name = args[0];\n if (!name) return { handled: true, output: pc.yellow(\"Usage: /team delete <name>\") };\n if (!deleteTeam(name)) return { handled: true, output: pc.red(`Team not found: ${name}`) };\n return { handled: true, output: pc.dim(`Team deleted: ${name}`) };\n }\n\n case \"help\":\n return { handled: true, output: `Team commands:\n /team List all teams\n /team create Show built-in templates\n /team create <name> Install built-in team\n /team create <n> <mode> <m> Custom team (mode: pipeline|parallel|coordinator)\n /team run <name> <task> Run a task with a team\n /team show <name> Show team details\n /team delete <name> Delete a team\n\nModes:\n pipeline Sequential: agent1 → agent2 → agent3\n parallel All agents work concurrently, coordinator merges\n coordinator Coordinator LLM decides how to split the task\n\nExamples:\n /team create content-team\n /team run content-team Write a blog post about AI companions\n /team create review-squad pipeline coder:implement,researcher:review\n /team run review-squad Build a rate limiter in TypeScript` };\n\n default:\n return { handled: true, output: pc.yellow(`Unknown team action: ${action}. Try /team help`) };\n }\n}\n\n// --- Delegation ---\n\nasync function handleDelegateCommand(action: string | undefined, args: string[], ctx: CommandContext): Promise<CommandResult> {\n if (!action) {\n return { handled: true, output: `Delegate commands:\n /delegate <profile> <task> Delegate a task to a local profile\n /delegate @<name> <task> Delegate to another running aman-agent (A2A)\n /delegate pipeline <p1> <p2> ... Run a sequential pipeline\n /delegate help Show help\n\nExamples:\n /delegate writer Write a blog post about AI companions\n /delegate coder Review this code for security issues\n /delegate @reviewer Review PR #42 for security issues\n /delegate pipeline writer,researcher Write and fact-check an article about quantum computing` };\n }\n\n if (action === \"help\") {\n return { handled: true, output: `Delegate a task to a sub-agent with a specific profile.\n\nThe sub-agent runs with its own identity, rules, and skills but shares\nyour memory and tools. Results come back to you.\n\nUsage:\n /delegate <profile> <task> Local sub-agent with named profile\n /delegate @<name> <task> Remote aman-agent (A2A via MCP)\n /delegate pipeline <profile1>,<profile2> <task>\n\nUse /agents list to see which remote agents are running.\n\nThe pipeline mode passes each agent's output to the next:\n writer drafts → researcher reviews → writer polishes` };\n }\n\n if (!ctx.llmClient || !ctx.mcpManager) {\n return { handled: true, output: pc.red(\"Delegation requires LLM client and MCP. Not available.\") };\n }\n\n if (action === \"pipeline\") {\n // /delegate pipeline writer,researcher,writer Write an article about AI\n const profileList = args[0];\n const task = args.slice(1).join(\" \");\n if (!profileList || !task) {\n return { handled: true, output: pc.yellow(\"Usage: /delegate pipeline <profile1>,<profile2> <task>\") };\n }\n\n const profiles = profileList.split(\",\").map((p) => p.trim());\n const steps = profiles.map((profile, i) => {\n if (i === 0) {\n return { profile, taskTemplate: task };\n }\n return { profile, taskTemplate: `Review and improve the following:\\n\\n{{input}}` };\n });\n\n process.stdout.write(pc.dim(`\\n Pipeline: ${profiles.join(\" → \")}\\n`));\n\n const results = await delegatePipeline(steps, task, ctx.llmClient, ctx.mcpManager, { tools: ctx.tools });\n\n const output: string[] = [];\n for (const r of results) {\n if (r.success) {\n output.push(`\\n${pc.bold(`[${r.profile}]`)} ${pc.green(\"✓\")} (${r.turns} tool turns)`);\n output.push(r.response.slice(0, 2000));\n if (r.toolsUsed.length > 0) output.push(pc.dim(` Tools: ${r.toolsUsed.join(\", \")}`));\n } else {\n output.push(`\\n${pc.bold(`[${r.profile}]`)} ${pc.red(\"✗\")} ${r.error}`);\n }\n }\n\n return { handled: true, output: output.join(\"\\n\") };\n }\n\n // /delegate <profile> <task>\n const profile = action;\n const task = args.join(\" \");\n if (!task) {\n return { handled: true, output: pc.yellow(`Usage: /delegate ${profile} <task description>`) };\n }\n\n process.stdout.write(pc.dim(`\\n [delegating to ${profile}...]\\n\\n`));\n\n const result = await delegateTask(task, profile, ctx.llmClient, ctx.mcpManager, { tools: ctx.tools });\n\n if (!result.success) {\n return { handled: true, output: pc.red(`Delegation failed: ${result.error}`) };\n }\n\n const meta: string[] = [];\n if (result.toolsUsed.length > 0) meta.push(`Tools: ${result.toolsUsed.join(\", \")}`);\n if (result.turns > 0) meta.push(`${result.turns} tool turns`);\n\n return {\n handled: true,\n output: `\\n${pc.bold(`[${profile}]`)} ${pc.green(\"✓\")}${meta.length > 0 ? \" \" + pc.dim(`(${meta.join(\", \")})`) : \"\"}\\n\\n${result.response}`,\n };\n}\n\n// --- Agents (A2A discovery + health) ---\n\nasync function handleAgentsCommand(\n action: string | undefined,\n args: string[],\n): Promise<CommandResult> {\n const sub = action ?? \"list\";\n\n if (sub === \"list\") {\n const all = await listAgents();\n if (all.length === 0) {\n return { handled: true, output: \"No agents running.\" };\n }\n const rows = all.map((a) => {\n const uptime = Math.round((Date.now() - a.started_at) / 1000);\n return ` @${a.name.padEnd(12)} ${a.profile.padEnd(12)} pid=${String(a.pid).padEnd(6)} port=${a.port} up ${uptime}s`;\n });\n return { handled: true, output: [\"Running agents:\", ...rows].join(\"\\n\") };\n }\n\n if (sub === \"info\") {\n const name = args[0];\n if (!name) {\n return { handled: true, output: pc.yellow(\"Usage: /agents info <name>\") };\n }\n const entry = await findAgent(name);\n if (!entry) {\n return { handled: true, output: `No such agent: ${name}` };\n }\n const url = new URL(`http://127.0.0.1:${entry.port}/mcp`);\n const transport = new StreamableHTTPClientTransport(url, {\n requestInit: { headers: { Authorization: `Bearer ${entry.token}` } },\n });\n const client = new Client({ name: \"aman-agent-cli\", version: \"0.1.0\" });\n try {\n await client.connect(transport);\n const res = await client.callTool({ name: \"agent.info\", arguments: {} });\n const text = Array.isArray(res.content)\n ? (res.content as Array<{ type: string; text?: string }>)\n .filter((c) => c.type === \"text\")\n .map((c) => c.text ?? \"\")\n .join(\"\")\n : \"\";\n return { handled: true, output: `@${entry.name}:\\n${text}` };\n } catch (err) {\n return {\n handled: true,\n output: pc.red(\n `Error calling @${name}: ${err instanceof Error ? err.message : String(err)}`,\n ),\n };\n } finally {\n try {\n await client.close();\n } catch {\n /* best effort */\n }\n }\n }\n\n if (sub === \"ping\") {\n const name = args[0];\n if (!name) {\n return { handled: true, output: pc.yellow(\"Usage: /agents ping <name>\") };\n }\n const entry = await findAgent(name);\n if (!entry) {\n return { handled: true, output: `No such agent: ${name}` };\n }\n const t0 = Date.now();\n try {\n const res = await fetch(`http://127.0.0.1:${entry.port}/health`, {\n headers: { Authorization: `Bearer ${entry.token}` },\n });\n if (!res.ok) {\n return { handled: true, output: `@${name}: HTTP ${res.status}` };\n }\n return { handled: true, output: `@${name}: ok (${Date.now() - t0}ms)` };\n } catch (err) {\n return {\n handled: true,\n output: `@${name}: ${err instanceof Error ? err.message : String(err)}`,\n };\n }\n }\n\n return {\n handled: true,\n output: pc.yellow(\"Usage: /agents [list|info <name>|ping <name>]\"),\n };\n}\n\n// --- Profile management ---\n\nfunction handleProfileCommand(action: string | undefined, args: string[]): CommandResult {\n const profilesDir = path.join(os.homedir(), \".acore\", \"profiles\");\n\n // User identity commands (separate from AI agent profiles)\n if (action === \"me\") {\n const user = loadUserIdentity();\n if (!user) {\n return { handled: true, output: pc.dim(\"No user profile yet. Run /profile edit to set one up.\") };\n }\n const lines = [\n ` ${pc.bold(\"Name:\")} ${user.name}`,\n ` ${pc.bold(\"Role:\")} ${user.roleLabel}`,\n ` ${pc.bold(\"Expertise:\")} ${user.expertiseLabel}`,\n ` ${pc.bold(\"Style:\")} ${user.styleLabel}`,\n ];\n if (user.workingOn) lines.push(` ${pc.bold(\"Working on:\")} ${user.workingOn}`);\n if (user.notes) lines.push(` ${pc.bold(\"Notes:\")} ${user.notes}`);\n lines.push(` ${pc.dim(`Updated: ${user.updatedAt}`)}`);\n return { handled: true, output: `Your profile:\\n${lines.join(\"\\n\")}\\n\\n${pc.dim(\"Edit with: /profile edit\")}` };\n }\n\n if (action === \"edit\") {\n const current = loadUserIdentity();\n if (!current) {\n // No profile yet — run full onboarding\n runOnboarding().then(() => {}).catch(() => {});\n return { handled: true, output: \"\" }; // onboarding handles its own output\n }\n // Edit existing profile\n editProfile(current).then(() => {}).catch(() => {});\n return { handled: true, output: \"\" }; // editProfile handles its own output\n }\n\n if (action === \"setup\") {\n // Force re-run full onboarding\n runOnboarding().then(() => {}).catch(() => {});\n return { handled: true, output: \"\" };\n }\n\n if (!action || action === \"list\") {\n const profiles = listProfiles();\n const user = loadUserIdentity();\n const userLine = user\n ? `${pc.bold(\"You:\")} ${user.name} (${user.roleLabel}, ${user.expertiseLabel})\\n\\n`\n : `${pc.dim(\"No user profile. Set up with: /profile edit\")}\\n\\n`;\n\n if (profiles.length === 0) {\n return { handled: true, output: userLine + pc.dim(\"No agent profiles yet. Create one with: /profile create <name>\") };\n }\n const lines = profiles.map((p) =>\n ` ${pc.bold(p.name)} — ${p.aiName} (${pc.dim(p.personality)})`\n );\n return { handled: true, output: userLine + \"Agent profiles:\\n\" + lines.join(\"\\n\") + \"\\n\\n\" + pc.dim(\"Switch with: aman-agent --profile <name>\") };\n }\n\n switch (action) {\n case \"create\": {\n const name = args[0];\n if (!name) {\n // Show available templates\n const lines = BUILT_IN_PROFILES.map((t) =>\n ` ${pc.bold(t.name)} — ${t.label}: ${pc.dim(t.description)}`\n );\n return {\n handled: true,\n output: \"Built-in profiles:\\n\" + lines.join(\"\\n\") +\n \"\\n\\nUsage:\\n /profile create coder Install built-in template\" +\n \"\\n /profile create <custom> Create blank profile\",\n };\n }\n\n const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, \"-\");\n const profileDir = path.join(profilesDir, slug);\n\n if (fs.existsSync(profileDir)) {\n return { handled: true, output: pc.yellow(`Profile already exists: ${slug}`) };\n }\n\n // Check if it's a built-in template\n const builtIn = BUILT_IN_PROFILES.find((t) => t.name === slug);\n if (builtIn) {\n const err = installProfileTemplate(slug);\n if (err) return { handled: true, output: pc.red(err) };\n return {\n handled: true,\n output: pc.green(`Profile installed: ${builtIn.label}`) +\n `\\n AI name: ${builtIn.core.match(/^# (.+)/m)?.[1] || slug}` +\n `\\n ${pc.dim(builtIn.description)}` +\n `\\n\\n Use: aman-agent --profile ${slug}`,\n };\n }\n\n // Custom profile — create from default\n fs.mkdirSync(profileDir, { recursive: true });\n const globalCore = path.join(os.homedir(), \".acore\", \"core.md\");\n if (fs.existsSync(globalCore)) {\n let content = fs.readFileSync(globalCore, \"utf-8\");\n const aiName = name.charAt(0).toUpperCase() + name.slice(1);\n content = content.replace(/^# .+$/m, `# ${aiName}`);\n fs.writeFileSync(path.join(profileDir, \"core.md\"), content, \"utf-8\");\n } else {\n const aiName = name.charAt(0).toUpperCase() + name.slice(1);\n fs.writeFileSync(path.join(profileDir, \"core.md\"), `# ${aiName}\\n\\n## Identity\\n- Role: ${aiName} is your AI companion\\n- Personality: helpful, adaptive\\n- Communication: clear and concise\\n- Values: honesty, simplicity\\n- Boundaries: won't pretend to be human\\n`, \"utf-8\");\n }\n\n return {\n handled: true,\n output: pc.green(`Profile created: ${slug}`) +\n `\\n Edit: ${path.join(profileDir, \"core.md\")}` +\n `\\n Use: aman-agent --profile ${slug}` +\n `\\n\\n ${pc.dim(\"Add rules.md or skills.md for profile-specific overrides.\")}`,\n };\n }\n\n case \"show\": {\n const name = args[0];\n if (!name) return { handled: true, output: pc.yellow(\"Usage: /profile show <name>\") };\n const profileDir = path.join(profilesDir, name);\n if (!fs.existsSync(profileDir)) return { handled: true, output: pc.red(`Profile not found: ${name}`) };\n\n const files = fs.readdirSync(profileDir).filter((f) => f.endsWith(\".md\"));\n const lines = files.map((f) => ` ${f}`);\n return { handled: true, output: `Profile: ${pc.bold(name)}\\nFiles:\\n${lines.join(\"\\n\")}` };\n }\n\n case \"delete\": {\n const name = args[0];\n if (!name) return { handled: true, output: pc.yellow(\"Usage: /profile delete <name>\") };\n const profileDir = path.join(profilesDir, name);\n if (!fs.existsSync(profileDir)) return { handled: true, output: pc.red(`Profile not found: ${name}`) };\n\n fs.rmSync(profileDir, { recursive: true });\n return { handled: true, output: pc.dim(`Profile deleted: ${name}`) };\n }\n\n case \"help\":\n return { handled: true, output: `Profile commands:\n\n ${pc.bold(\"Your profile:\")}\n /profile me View your profile\n /profile edit Edit your profile\n /profile setup Re-run full profile setup\n\n ${pc.bold(\"Agent profiles:\")}\n /profile List all profiles\n /profile create <n> Create new agent profile\n /profile show <n> Show agent profile files\n /profile delete <n> Delete an agent profile\n\n ${pc.bold(\"Use agent profiles:\")}\n aman-agent --profile <name>\n AMAN_PROFILE=<name> aman-agent` };\n\n default:\n return { handled: true, output: pc.yellow(`Unknown profile action: ${action}. Try /profile help`) };\n }\n}\n\n// --- Plan management ---\n\nfunction handlePlanCommand(action: string | undefined, args: string[], ctx?: CommandContext): CommandResult {\n if (!action) {\n // /plan — show active plan\n const active = getActivePlan();\n if (!active) {\n return { handled: true, output: pc.dim(\"No active plan. Create one with: /plan create <name> | <goal> | <step1>, <step2>, ...\") };\n }\n return { handled: true, output: formatPlan(active) };\n }\n\n switch (action) {\n case \"create\": {\n // /plan create <name> | <goal> | <step1>, <step2>, ...\n const fullArgs = args.join(\" \");\n const parts = fullArgs.split(\"|\").map((p) => p.trim());\n if (parts.length < 3) {\n return { handled: true, output: pc.yellow(\"Usage: /plan create <name> | <goal> | <step1>, <step2>, ...\") };\n }\n const name = parts[0];\n const goal = parts[1];\n const steps = parts[2].split(\",\").map((s) => s.trim()).filter(Boolean);\n if (steps.length === 0) {\n return { handled: true, output: pc.yellow(\"Need at least one step. Separate steps with commas.\") };\n }\n const plan = createPlan(name, goal, steps);\n return { handled: true, output: pc.green(`Plan created!\\n\\n`) + formatPlan(plan) };\n }\n\n case \"done\": {\n // /plan done [step number]\n const active = getActivePlan();\n if (!active) return { handled: true, output: pc.yellow(\"No active plan.\") };\n\n const recordPlanMilestone = (stepIndex: number) => {\n if (ctx?.observationSession) {\n const step = active.steps[stepIndex];\n recordEvent(ctx.observationSession, {\n type: \"milestone\",\n summary: `Plan step done: ${step.text}`,\n data: { plan: active.name, stepIndex, stepText: step.text },\n });\n }\n };\n\n if (args.length > 0) {\n const stepNum = parseInt(args[0], 10);\n if (isNaN(stepNum) || stepNum < 1 || stepNum > active.steps.length) {\n return { handled: true, output: pc.yellow(`Invalid step number. Range: 1-${active.steps.length}`) };\n }\n markStepDone(active, stepNum - 1);\n recordPlanMilestone(stepNum - 1);\n return { handled: true, output: pc.green(`Step ${stepNum} done!`) + \"\\n\\n\" + formatPlan(active) };\n }\n\n // No step specified — mark next incomplete step\n const next = active.steps.findIndex((s) => !s.done);\n if (next < 0) return { handled: true, output: pc.green(\"All steps already complete!\") };\n markStepDone(active, next);\n recordPlanMilestone(next);\n return { handled: true, output: pc.green(`Step ${next + 1} done!`) + \"\\n\\n\" + formatPlan(active) };\n }\n\n case \"undo\": {\n // /plan undo <step number>\n const active = getActivePlan();\n if (!active) return { handled: true, output: pc.yellow(\"No active plan.\") };\n const stepNum = parseInt(args[0], 10);\n if (isNaN(stepNum) || stepNum < 1 || stepNum > active.steps.length) {\n return { handled: true, output: pc.yellow(`Invalid step number. Range: 1-${active.steps.length}`) };\n }\n markStepUndone(active, stepNum - 1);\n return { handled: true, output: pc.dim(`Step ${stepNum} unmarked.`) + \"\\n\\n\" + formatPlan(active) };\n }\n\n case \"list\": {\n // /plan list — show all plans\n const plans = listPlans();\n if (plans.length === 0) return { handled: true, output: pc.dim(\"No plans yet.\") };\n const lines = plans.map((p) => {\n const done = p.steps.filter((s) => s.done).length;\n const total = p.steps.length;\n const status = p.active ? pc.green(\"active\") : pc.dim(\"inactive\");\n return ` ${p.name} — ${done}/${total} steps (${status})`;\n });\n return { handled: true, output: \"Plans:\\n\" + lines.join(\"\\n\") };\n }\n\n case \"switch\": {\n // /plan switch <name>\n const name = args.join(\" \");\n if (!name) return { handled: true, output: pc.yellow(\"Usage: /plan switch <name>\") };\n const plan = setActivePlan(name);\n if (!plan) return { handled: true, output: pc.red(`Plan not found: ${name}`) };\n return { handled: true, output: pc.green(`Switched to: ${plan.name}`) + \"\\n\\n\" + formatPlan(plan) };\n }\n\n case \"show\": {\n // /plan show <name>\n const name = args.join(\" \");\n if (!name) return { handled: true, output: pc.yellow(\"Usage: /plan show <name>\") };\n const plan = loadPlan(name);\n if (!plan) return { handled: true, output: pc.red(`Plan not found: ${name}`) };\n return { handled: true, output: formatPlan(plan) };\n }\n\n case \"help\":\n return { handled: true, output: `Plan commands:\n /plan Show active plan\n /plan create <name> | <goal> | <step1>, <step2>, ...\n /plan done [step#] Mark step complete (next if no number)\n /plan undo <step#> Unmark a step\n /plan list List all plans\n /plan switch <name> Switch active plan\n /plan show <name> Show a specific plan` };\n\n default:\n return { handled: true, output: pc.yellow(`Unknown plan action: ${action}. Try /plan help`) };\n }\n}\n\nasync function handleReminderCommand(\n action: string | undefined,\n args: string[],\n): Promise<CommandResult> {\n if (!action || action === \"list\") {\n try {\n const reminders = reminderList();\n if (reminders.length === 0) return { handled: true, output: pc.dim(\"No reminders.\") };\n const lines: string[] = [pc.bold(`Reminders (${reminders.length}):`), \"\"];\n for (const r of reminders) {\n const status = r.completed ? pc.green(\"[done]\") : pc.yellow(\"[todo]\");\n const due = r.dueAt ? ` ${pc.dim(`due: ${new Date(r.dueAt).toLocaleString()}`)}` : \"\";\n lines.push(` ${status} ${r.content}${due} ${pc.dim(`(${r.id.slice(0, 8)})`)}`);\n }\n return { handled: true, output: lines.join(\"\\n\") };\n } catch (err) {\n return { handled: true, output: pc.red(`Reminder error: ${err instanceof Error ? err.message : String(err)}`) };\n }\n }\n\n if (action === \"set\" || action === \"add\") {\n if (args.length === 0) return { handled: true, output: pc.yellow(\"Usage: /reminder set <text> [--due <time>]\\n Time formats: 1h, 2d, 1w, or ISO date (2026-04-10)\") };\n // Parse --due flag\n let dueAt: number | undefined;\n const dueIdx = args.indexOf(\"--due\");\n let contentArgs = args;\n if (dueIdx >= 0 && args[dueIdx + 1]) {\n const dueStr = args[dueIdx + 1];\n contentArgs = [...args.slice(0, dueIdx), ...args.slice(dueIdx + 2)];\n // Parse relative time: 1h, 2d, 1w\n const relMatch = dueStr.match(/^(\\d+)(h|d|w)$/);\n if (relMatch) {\n const num = parseInt(relMatch[1], 10);\n const unit = relMatch[2];\n const ms = unit === \"h\" ? num * 3600000 : unit === \"d\" ? num * 86400000 : num * 604800000;\n dueAt = Date.now() + ms;\n } else {\n // Try ISO date\n const parsed = Date.parse(dueStr);\n if (!isNaN(parsed)) dueAt = parsed;\n }\n }\n const content = contentArgs.join(\" \");\n if (!content) return { handled: true, output: pc.yellow(\"Usage: /reminder set <text> [--due <time>]\") };\n try {\n const id = reminderSet(content, dueAt);\n const dueInfo = dueAt ? ` (due: ${new Date(dueAt).toLocaleDateString()})` : \"\";\n return { handled: true, output: pc.green(`Reminder set: \"${content}\"${dueInfo} (ID: ${id.slice(0, 8)})`) };\n } catch (err) {\n return { handled: true, output: pc.red(`Reminder error: ${err instanceof Error ? err.message : String(err)}`) };\n }\n }\n\n if (action === \"done\" || action === \"complete\") {\n if (!args[0]) return { handled: true, output: pc.yellow(\"Usage: /reminder done <id>\") };\n try {\n const result = reminderComplete(args[0]);\n return { handled: true, output: result ? pc.green(\"Reminder completed.\") : pc.yellow(\"Reminder not found.\") };\n } catch (err) {\n return { handled: true, output: pc.red(`Reminder error: ${err instanceof Error ? err.message : String(err)}`) };\n }\n }\n\n if (action === \"check\") {\n try {\n const reminders = reminderCheck();\n if (reminders.length === 0) return { handled: true, output: pc.dim(\"No pending reminders.\") };\n const lines: string[] = [pc.bold(\"Pending Reminders:\"), \"\"];\n for (const r of reminders) {\n const icon = r.status === \"overdue\" ? pc.red(\"!!!\") : r.status === \"today\" ? pc.yellow(\"(!)\") : pc.dim(\"( )\");\n const due = r.dueAt ? ` ${pc.dim(`due: ${new Date(r.dueAt).toLocaleString()}`)}` : \"\";\n lines.push(` ${icon} ${r.content}${due} ${pc.dim(`[${r.status}]`)}`);\n }\n return { handled: true, output: lines.join(\"\\n\") };\n } catch (err) {\n return { handled: true, output: pc.red(`Reminder error: ${err instanceof Error ? err.message : String(err)}`) };\n }\n }\n\n if (action === \"help\") {\n return { handled: true, output: [\n pc.bold(\"Reminder commands:\"),\n ` ${pc.cyan(\"/reminder\")} List all reminders`,\n ` ${pc.cyan(\"/reminder set\")} <text> Create a reminder [--due 1h|2d|1w|date]`,\n ` ${pc.cyan(\"/reminder check\")} Show overdue/upcoming`,\n ` ${pc.cyan(\"/reminder done\")} <id> Mark as completed`,\n ].join(\"\\n\") };\n }\n\n return { handled: true, output: pc.yellow(`Unknown action: /reminder ${action}. Try /reminder --help`) };\n}\n\n// --- Showcase templates ---\n\nfunction handleShowcaseCommand(action: string | undefined, args: string[]): CommandResult {\n const showcases = loadShowcaseManifest();\n\n if (showcases.length === 0) {\n return {\n handled: true,\n output: pc.dim(\"No showcase templates found.\") +\n \"\\n\\n Install aman-showcase to get 13 pre-built companion personalities:\" +\n `\\n ${pc.bold(\"npm install -g @aman_asmuei/aman-showcase\")}` +\n \"\\n Or place it as a sibling directory to aman-agent.\",\n };\n }\n\n // Detect current showcase from core.md\n const corePath = path.join(os.homedir(), \".acore\", \"core.md\");\n let currentShowcase: string | null = null;\n if (fs.existsSync(corePath)) {\n const content = fs.readFileSync(corePath, \"utf-8\");\n const nameMatch = content.match(/^# (.+)/m);\n if (nameMatch) {\n const coreName = nameMatch[1].trim().toLowerCase();\n const match = showcases.find((s) => coreName.includes(s.name) || coreName.includes(s.title.split(\"—\")[0].trim().toLowerCase()));\n if (match) currentShowcase = match.name;\n }\n }\n\n if (!action || action === \"list\") {\n const lines = showcases.map((s) => {\n const active = s.name === currentShowcase ? pc.green(\" ← active\") : \"\";\n const langBadge = s.language === \"ms\" ? \" [BM]\" : s.language === \"en+ms\" ? \" [EN/BM]\" : \"\";\n return ` ${pc.bold(s.name.padEnd(12))} ${s.title}${langBadge}${active}`;\n });\n const currentLine = currentShowcase\n ? `\\nCurrent: ${pc.bold(currentShowcase)}\\n`\n : `\\nNo showcase active (using default personality)\\n`;\n return {\n handled: true,\n output: `Showcase templates (${showcases.length}):\\n\\n${lines.join(\"\\n\")}\\n${currentLine}\\n${pc.dim(\"Switch with: /showcase install <name>\")}`,\n };\n }\n\n if (action === \"install\" || action === \"switch\" || action === \"use\") {\n const name = args[0];\n if (!name) {\n return { handled: true, output: pc.yellow(\"Usage: /showcase install <name>\\n\\nRun /showcase list to see available templates.\") };\n }\n\n const entry = showcases.find((s) => s.name === name);\n if (!entry) {\n return { handled: true, output: pc.red(`Showcase not found: ${name}`) + `\\n\\nAvailable: ${showcases.map((s) => s.name).join(\", \")}` };\n }\n\n if (name === currentShowcase) {\n return { handled: true, output: pc.dim(`${entry.title} is already active.`) };\n }\n\n try {\n const result = installShowcaseTemplate(name);\n const lines = [pc.green(`Installed ${pc.bold(entry.title)}`)];\n for (const f of result.installed) {\n lines.push(pc.dim(` ${f}`));\n }\n if (result.backed_up.length > 0) {\n lines.push(pc.dim(`\\n Backed up ${result.backed_up.length} existing file(s) (.bak)`));\n }\n lines.push(\"\");\n lines.push(pc.yellow(\"Restart aman-agent to use the new personality.\"));\n lines.push(pc.dim(\"Your user profile (/profile me) is unchanged — only the AI personality switched.\"));\n return { handled: true, output: lines.join(\"\\n\") };\n } catch (err) {\n return { handled: true, output: pc.red(`Failed to install: ${err instanceof Error ? err.message : String(err)}`) };\n }\n }\n\n if (action === \"current\") {\n if (currentShowcase) {\n const entry = showcases.find((s) => s.name === currentShowcase);\n return { handled: true, output: `Active showcase: ${pc.bold(entry?.title || currentShowcase)}\\n${pc.dim(entry?.description || \"\")}` };\n }\n return { handled: true, output: pc.dim(\"No showcase active — using default personality.\") + `\\n${pc.dim(\"Install one with: /showcase install <name>\")}` };\n }\n\n if (action === \"help\") {\n return { handled: true, output: `Showcase commands:\n\n /showcase List all available templates\n /showcase install <n> Install/switch to a template\n /showcase current Show active template\n\n${pc.dim(\"Showcase templates replace your AI's personality, workflows, rules, and skills.\")}\n${pc.dim(\"Your user profile (/profile me) stays unchanged — only the AI personality switches.\")}\n${pc.dim(\"Existing files are backed up (.bak) before overwriting.\")}` };\n }\n\n return { handled: true, output: pc.yellow(`Unknown action: /showcase ${action}. Try /showcase help`) };\n}\n\nasync function handleFileCommand(\n action: string | undefined,\n args: string[],\n): Promise<CommandResult> {\n if (!action) {\n return {\n handled: true,\n output: [\n pc.bold(\"File commands:\"),\n ` ${pc.cyan(\"/file read\")} <path> Read a text file (max 50 KB)`,\n ` ${pc.cyan(\"/file convert\")} <path> Attempt to read binary file as text`,\n ` ${pc.cyan(\"/file list\")} <path> [--recursive] List directory contents`,\n ].join(\"\\n\"),\n };\n }\n\n if (action === \"read\" || action === \"convert\") {\n const filePath = args[0];\n if (!filePath) {\n return { handled: true, output: pc.yellow(`Usage: /file ${action} <path>`) };\n }\n try {\n const result = await readFile(filePath);\n const lines: string[] = [\n pc.bold(`📄 ${result.path}`) + pc.dim(` (${(result.size / 1024).toFixed(1)} KB)`),\n \"\",\n result.content,\n ];\n if (result.truncated) {\n lines.push(\"\", pc.yellow(`⚠ File truncated at 50 KB. Use a text editor for the full file.`));\n }\n return { handled: true, output: lines.join(\"\\n\") };\n } catch (err) {\n return { handled: true, output: pc.red(`File error: ${err instanceof Error ? err.message : String(err)}`) };\n }\n }\n\n if (action === \"list\") {\n const dirPath = args.find((a) => !a.startsWith(\"-\"));\n if (!dirPath) {\n return { handled: true, output: pc.yellow(`Usage: /file list <path> [--recursive]`) };\n }\n const recursive = args.includes(\"--recursive\") || args.includes(\"-r\");\n try {\n const result = await listFiles(dirPath, { recursive });\n const lines: string[] = [\n pc.bold(`📁 ${result.path}`) + pc.dim(` (${result.total} items)`),\n \"\",\n ];\n for (const entry of result.entries) {\n if (entry.type === \"dir\") {\n lines.push(` ${pc.cyan(entry.name + \"/\")}`);\n } else {\n const kb = entry.size > 0 ? pc.dim(` ${(entry.size / 1024).toFixed(1)} KB`) : \"\";\n lines.push(` ${entry.name}${kb}`);\n }\n }\n return { handled: true, output: lines.join(\"\\n\") };\n } catch (err) {\n return { handled: true, output: pc.red(`File error: ${err instanceof Error ? err.message : String(err)}`) };\n }\n }\n\n return { handled: true, output: pc.yellow(`Unknown /file subcommand: ${action}. Try /file for help.`) };\n}\n\nasync function handleOrchestrateCommand(\n action: string | undefined,\n args: string[],\n ctx: CommandContext,\n): Promise<CommandResult> {\n if (!action) {\n return {\n handled: true,\n output: [\n \"Usage: /orchestrate <requirement>\",\n \"\",\n \"Decomposes a requirement into a task DAG and executes it with parallel agents.\",\n \"Auto-detects project type, selects template, runs policy check, and tracks cost.\",\n \"\",\n \"Options (pass as first arg):\",\n \" --template <name> Force a template (full-feature, bug-fix, security-audit)\",\n \" --no-review Skip self-review loop\",\n \" --no-policy Skip policy check\",\n \"\",\n \"Alias: /orch\",\n ].join(\"\\n\"),\n };\n }\n\n if (!ctx.llmClient) {\n return { handled: true, output: pc.red(\"Orchestration requires an LLM client. Not available.\") };\n }\n\n // Parse flags\n let templateName: string | undefined;\n let enableSelfReview = true;\n let enablePolicyCheck = true;\n const filtered: string[] = [];\n\n const allArgs = [action, ...args];\n for (let i = 0; i < allArgs.length; i++) {\n if (allArgs[i] === \"--template\" && allArgs[i + 1]) {\n templateName = allArgs[++i];\n } else if (allArgs[i] === \"--no-review\") {\n enableSelfReview = false;\n } else if (allArgs[i] === \"--no-policy\") {\n enablePolicyCheck = false;\n } else {\n filtered.push(allArgs[i]);\n }\n }\n\n const requirement = filtered.join(\" \");\n if (!requirement.trim()) {\n return { handled: true, output: pc.red(\"Please provide a requirement to orchestrate.\") };\n }\n\n try {\n const router = createModelRouter({ standard: ctx.llmClient });\n const result = await smartOrchestrate({\n requirement,\n client: ctx.llmClient,\n router,\n projectPath: process.cwd(),\n templateName,\n enablePolicyCheck,\n enableSelfReview,\n enableCostTracking: true,\n });\n\n return { handled: true, output: result.summary };\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n return { handled: true, output: pc.red(`Orchestration failed: ${msg}`) };\n }\n}\n\nasync function handleGitHubCommand(\n action: string | undefined,\n args: string[],\n ctx: CommandContext,\n): Promise<CommandResult> {\n // No subcommand → show repo info\n if (!action) {\n const available = await ghAvailable();\n if (!available) {\n return { handled: true, output: pc.red(\"GitHub CLI (gh) is not available or not authenticated. Run: gh auth login\") };\n }\n const repo = await ghCurrentRepo();\n if (!repo) {\n return { handled: true, output: pc.yellow(\"Not inside a GitHub repository.\") };\n }\n return { handled: true, output: `GitHub repo: ${pc.bold(`${repo.owner}/${repo.name}`)}` };\n }\n\n switch (action) {\n case \"issues\": {\n // Quick issue list via gh CLI\n const { gh: ghExec } = await import(\"./github/index.js\");\n const repoArgs = args.length > 0 ? [\"--repo\", args[0]] : [];\n const result = await ghExec([\"issue\", \"list\", \"--limit\", \"10\", ...repoArgs]);\n if (!result.success) {\n return { handled: true, output: pc.red(`Failed to list issues: ${result.stderr}`) };\n }\n return { handled: true, output: result.stdout.trim() || pc.dim(\"No open issues.\") };\n }\n\n case \"prs\": {\n const repoArgs: { repo?: string } = args.length > 0 ? { repo: args[0] } : {};\n try {\n const prs = await listPRs({ state: \"open\", limit: 10, ...repoArgs });\n if (prs.length === 0) {\n return { handled: true, output: pc.dim(\"No open PRs.\") };\n }\n const lines = prs.map(\n (pr) => `#${pr.number} ${pr.title} (${pr.headRefName} → ${pr.baseRefName})${pr.isDraft ? \" [draft]\" : \"\"}`,\n );\n return { handled: true, output: lines.join(\"\\n\") };\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n return { handled: true, output: pc.red(`Failed to list PRs: ${msg}`) };\n }\n }\n\n case \"plan\": {\n const issueNum = parseInt(args[0], 10);\n if (!issueNum || isNaN(issueNum)) {\n return { handled: true, output: pc.red(\"Usage: /github plan <issue-number>\") };\n }\n if (!ctx.llmClient) {\n return { handled: true, output: pc.red(\"Planning requires an LLM client. Not available.\") };\n }\n try {\n const issue = await fetchIssue(issueNum);\n const requirement = formatIssueAsRequirement(issue);\n const router = createModelRouter({ standard: ctx.llmClient });\n const result = await smartOrchestrate({\n requirement,\n client: ctx.llmClient,\n router,\n projectPath: process.cwd(),\n enablePolicyCheck: true,\n enableSelfReview: false,\n enableCostTracking: true,\n });\n return {\n handled: true,\n output: `${pc.bold(`Plan for #${issue.number}: ${issue.title}`)}\\n\\n${result.summary}`,\n };\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n return { handled: true, output: pc.red(`Failed to plan issue #${issueNum}: ${msg}`) };\n }\n }\n\n case \"ci\": {\n const branch = args[0];\n if (!branch) {\n return { handled: true, output: pc.red(\"Usage: /github ci <branch>\") };\n }\n try {\n const passing = await isCIPassing(branch);\n return {\n handled: true,\n output: passing\n ? pc.green(`CI is passing on ${branch}`)\n : pc.yellow(`CI is NOT passing on ${branch}`),\n };\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n return { handled: true, output: pc.red(`Failed to check CI: ${msg}`) };\n }\n }\n\n default:\n return {\n handled: true,\n output: [\n `Usage: /github [subcommand]`,\n ``,\n `Subcommands:`,\n ` (none) Show current repo info`,\n ` issues [repo] List open issues`,\n ` prs [repo] List open PRs`,\n ` plan <number> Plan from a GitHub issue`,\n ` ci <branch> Check CI status for a branch`,\n ].join(\"\\n\"),\n };\n }\n}\n\nconst KNOWN_COMMANDS = new Set([\n \"quit\", \"exit\", \"q\", \"help\", \"clear\", \"model\", \"identity\", \"rules\",\n \"workflows\", \"tools\", \"akit\", \"skills\", \"eval\", \"memory\", \"status\", \"doctor\",\n \"save\", \"decisions\", \"export\", \"debug\", \"reset\", \"reminder\",\n \"update\", \"upgrade\", \"plan\", \"profile\", \"delegate\", \"team\", \"agents\", \"showcase\", \"file\",\n \"observe\", \"postmortem\", \"orchestrate\", \"orch\", \"github\",\n]);\n\nasync function handleObserveCommand(\n action: string | undefined,\n ctx: CommandContext,\n): Promise<CommandResult> {\n if (!ctx.observationSession) {\n return {\n handled: true,\n output: pc.dim(\"Observation is disabled. Enable with recordObservations: true in config.\"),\n };\n }\n\n switch (action) {\n case \"pause\":\n pauseObservation(ctx.observationSession);\n return { handled: true, output: pc.dim(\"Observation paused. Use /observe resume to continue.\") };\n\n case \"resume\":\n resumeObservation(ctx.observationSession);\n return { handled: true, output: pc.dim(\"Observation resumed.\") };\n\n default:\n return { handled: true, output: getSessionStats(ctx.observationSession) };\n }\n}\n\nasync function handlePostmortemCommand(\n action: string | undefined,\n args: string[],\n ctx: CommandContext,\n): Promise<CommandResult> {\n switch (action) {\n case \"last\": {\n const files = await listPostmortems();\n if (files.length === 0) return { handled: true, output: pc.dim(\"No post-mortems found.\") };\n const content = await readPostmortem(files[0]);\n return { handled: true, output: content ?? pc.red(\"Could not read post-mortem.\") };\n }\n\n case \"list\": {\n const files = await listPostmortems();\n if (files.length === 0) return { handled: true, output: pc.dim(\"No post-mortems found.\") };\n return { handled: true, output: \"Post-mortems:\\n\" + files.map((f) => ` ${f}`).join(\"\\n\") };\n }\n\n default: {\n // Check for --since flag (in either action or args position)\n const allArgs = action ? [action, ...args] : args;\n const sinceIdx = allArgs.indexOf(\"--since\");\n if (sinceIdx !== -1 && allArgs[sinceIdx + 1]) {\n const daysStr = allArgs[sinceIdx + 1];\n const days = parseInt(daysStr.replace(\"d\", \"\"), 10) || 7;\n if (!ctx.llmClient) {\n return { handled: true, output: pc.red(\"LLM client not available for analysis.\") };\n }\n const analysis = await analyzePostmortemRange(days, ctx.llmClient);\n return { handled: true, output: analysis ?? pc.red(\"Could not analyze post-mortems.\") };\n }\n\n // Generate post-mortem for current session\n if (!ctx.observationSession || !ctx.llmClient || !ctx.messages) {\n return {\n handled: true,\n output: pc.dim(\"Cannot generate post-mortem: missing session context.\"),\n };\n }\n const report = await generatePostmortemReport(\n ctx.observationSession.sessionId,\n ctx.messages,\n ctx.observationSession,\n ctx.llmClient,\n );\n if (!report) return { handled: true, output: pc.red(\"Could not generate post-mortem.\") };\n const filePath = await savePostmortem(report);\n return {\n handled: true,\n output: formatPostmortemMarkdown(report) + `\\n\\n${pc.dim(`Saved → ${filePath}`)}`,\n };\n }\n }\n}\n\nexport async function handleCommand(input: string, ctx: CommandContext): Promise<CommandResult> {\n const trimmed = input.trim();\n if (!trimmed.startsWith(\"/\")) return { handled: false };\n\n const { base, action, args } = parseCommand(trimmed);\n\n // Don't treat file paths (e.g., /Users/...) as commands\n if (!KNOWN_COMMANDS.has(base)) return { handled: false };\n\n switch (base) {\n case \"quit\":\n case \"exit\":\n case \"q\":\n return { handled: true, quit: true };\n case \"help\":\n return handleHelp();\n case \"clear\":\n return { handled: true, output: pc.dim(\"Conversation cleared.\"), clearHistory: true };\n case \"model\":\n return { handled: true, output: ctx.model ? `Model: ${pc.bold(ctx.model)}` : \"Model: unknown\" };\n case \"identity\":\n return handleIdentityCommand(action, args, ctx);\n case \"rules\":\n return handleRulesCommand(action, args, ctx);\n case \"workflows\":\n return handleWorkflowsCommand(action, args, ctx);\n case \"tools\":\n return handleToolsCommand(action, args, ctx);\n case \"akit\":\n return handleAkitCommand(action, args);\n case \"skills\":\n return handleSkillsCommand(action, args, ctx);\n case \"eval\":\n return handleEvalCommand(action, args, ctx);\n case \"memory\":\n return handleMemoryCommand(action, args, ctx);\n case \"status\":\n return handleStatusCommand(ctx);\n case \"doctor\":\n return handleDoctorCommand(ctx);\n case \"save\":\n return handleSave();\n case \"decisions\":\n return handleDecisionsCommand(action, args, ctx);\n case \"export\":\n return handleExportCommand();\n case \"debug\":\n return handleDebugCommand();\n case \"reset\":\n return handleReset(action);\n case \"plan\":\n return handlePlanCommand(action, args, ctx);\n case \"profile\":\n return handleProfileCommand(action, args);\n case \"delegate\":\n return handleDelegateCommand(action, args, ctx);\n case \"team\":\n return handleTeamCommand(action, args, ctx);\n case \"agents\":\n return handleAgentsCommand(action, args);\n case \"reminder\":\n return handleReminderCommand(action, args);\n case \"showcase\":\n return handleShowcaseCommand(action, args);\n case \"file\":\n return handleFileCommand(action, args);\n case \"update\":\n case \"upgrade\":\n return handleUpdate();\n case \"observe\":\n return handleObserveCommand(action, ctx);\n case \"postmortem\":\n return handlePostmortemCommand(action, args, ctx);\n case \"orchestrate\":\n case \"orch\":\n return handleOrchestrateCommand(action, args, ctx);\n case \"github\":\n return handleGitHubCommand(action, args, ctx);\n default:\n return { handled: false }; // Pass to LLM if not matched\n }\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport os from \"node:os\";\n\nconst home = os.homedir();\n\ninterface LayerStatus {\n name: string;\n exists: boolean;\n path: string;\n summary: string;\n}\n\nexport interface EcosystemStatus {\n layers: LayerStatus[];\n mcpConnected: boolean;\n mcpToolCount: number;\n amemConnected: boolean;\n}\n\nconst LAYER_FILES = [\n { name: \"identity\", dir: \".acore\", file: \"core.md\" },\n { name: \"rules\", dir: \".arules\", file: \"rules.md\" },\n { name: \"workflows\", dir: \".aflow\", file: \"flow.md\" },\n { name: \"tools\", dir: \".akit\", file: \"kit.md\" },\n { name: \"skills\", dir: \".askill\", file: \"skills.md\" },\n { name: \"eval\", dir: \".aeval\", file: \"eval.md\" },\n] as const;\n\nfunction countLines(content: string, pattern: RegExp): number {\n return (content.match(pattern) || []).length;\n}\n\nfunction getLayerSummary(name: string, content: string): string {\n switch (name) {\n case \"identity\": {\n const nameMatch = content.match(/^# (.+)/m);\n return nameMatch ? nameMatch[1] : \"configured\";\n }\n case \"rules\":\n return `${countLines(content, /^- /gm)} rules`;\n case \"workflows\":\n return `${countLines(content, /^## /gm)} workflows`;\n case \"tools\":\n return `${countLines(content, /^- \\*\\*/gm)} tools`;\n case \"skills\":\n return `${countLines(content, /^### /gm)} skills`;\n case \"eval\": {\n const sessions = countLines(content, /^### Session/gm);\n return `${sessions} sessions logged`;\n }\n default:\n return \"unknown\";\n }\n}\n\nexport function getEcosystemStatus(\n mcpToolCount: number,\n amemConnected: boolean,\n): EcosystemStatus {\n const layers: LayerStatus[] = LAYER_FILES.map((entry) => {\n const filePath = path.join(home, entry.dir, entry.file);\n const exists = fs.existsSync(filePath);\n let summary = \"not configured\";\n\n if (exists) {\n const content = fs.readFileSync(filePath, \"utf-8\");\n summary = getLayerSummary(entry.name, content);\n }\n\n return { name: entry.name, exists, path: filePath, summary };\n });\n\n return {\n layers,\n mcpConnected: mcpToolCount > 0,\n mcpToolCount,\n amemConnected,\n };\n}\n\nexport function readLayerFile(name: string): string | null {\n const entry = LAYER_FILES.find((l) => l.name === name);\n if (!entry) return null;\n const filePath = path.join(home, entry.dir, entry.file);\n if (!fs.existsSync(filePath)) return null;\n return fs.readFileSync(filePath, \"utf-8\").trim();\n}\n","import {\n createDatabase,\n recall,\n buildContext,\n storeMemory,\n consolidateMemories,\n cosineSimilarity,\n preloadEmbeddings,\n buildVectorIndex,\n recallMemories,\n generateEmbedding,\n getVectorIndex,\n runDiagnostics,\n repairDatabase,\n loadConfig,\n saveConfig,\n multiStrategyRecall,\n reflect,\n isReflectionDue,\n syncFromClaude,\n exportForTeam,\n importFromTeam,\n syncToCopilot,\n type AmemDatabase,\n type RecallResult,\n type ContextResult,\n type StoreResult,\n type StoreOptions,\n type ConsolidationReport,\n type MemoryStats,\n type Memory,\n type MemoryVersion,\n type MemoryRelation,\n type DiagnosticReport,\n type ReflectionReport,\n type ReflectionConfig,\n type AmemConfig,\n type SyncResult,\n type TeamExportOptions,\n type TeamImportOptions,\n type TeamImportResult,\n type CopilotSyncOptions,\n type CopilotSyncResult,\n} from \"@aman_asmuei/amem-core\";\n\ntype DeepPartial<T> = { [K in keyof T]?: T[K] extends object ? DeepPartial<T[K]> : T[K] };\nimport path from \"node:path\";\nimport os from \"node:os\";\nimport fs from \"node:fs\";\n\nlet db: AmemDatabase | null = null;\nlet currentProject = \"global\";\n\nexport async function initMemory(project?: string): Promise<AmemDatabase> {\n if (db) return db;\n\n const amemDir = process.env.AMEM_DIR ?? path.join(os.homedir(), \".amem\");\n if (!fs.existsSync(amemDir)) fs.mkdirSync(amemDir, { recursive: true });\n\n const dbPath = process.env.AMEM_DB ?? path.join(amemDir, \"memory.db\");\n\n try {\n db = createDatabase(dbPath);\n } catch (err) {\n // Attempt recovery: if DB is corrupted, back it up and create fresh\n const backupPath = `${dbPath}.corrupt.${Date.now()}`;\n try {\n if (fs.existsSync(dbPath)) {\n fs.renameSync(dbPath, backupPath);\n // Remove WAL/SHM files too\n if (fs.existsSync(`${dbPath}-wal`)) fs.unlinkSync(`${dbPath}-wal`);\n if (fs.existsSync(`${dbPath}-shm`)) fs.unlinkSync(`${dbPath}-shm`);\n console.error(`[amem] Database corrupted — backed up to ${backupPath}`);\n console.error(\"[amem] Creating fresh database. Previous memories are in the backup file.\");\n db = createDatabase(dbPath);\n } else {\n throw err;\n }\n } catch {\n console.error(`[amem] Failed to initialize memory: ${err instanceof Error ? err.message : String(err)}`);\n console.error(`[amem] Try deleting ${amemDir} to reset: rm -rf ${amemDir}`);\n throw err;\n }\n }\n\n currentProject = project ?? \"global\";\n\n preloadEmbeddings();\n\n setTimeout(() => {\n try { buildVectorIndex(db!); } catch {}\n }, 1000);\n\n return db;\n}\n\nexport function getDb(): AmemDatabase {\n if (!db) throw new Error(\"Memory not initialized — call initMemory() first\");\n return db;\n}\n\nexport function getProject(): string {\n return currentProject;\n}\n\nexport async function memoryRecall(query: string, opts?: {\n limit?: number;\n compact?: boolean;\n type?: string;\n tag?: string;\n minConfidence?: number;\n explain?: boolean;\n}): Promise<RecallResult> {\n return recall(getDb(), {\n query,\n limit: opts?.limit ?? 10,\n compact: opts?.compact ?? true,\n type: opts?.type,\n tag: opts?.tag,\n minConfidence: opts?.minConfidence,\n explain: opts?.explain,\n scope: currentProject,\n });\n}\n\nexport async function memoryContext(topic: string, maxTokens?: number): Promise<ContextResult> {\n return buildContext(getDb(), topic, { maxTokens, scope: currentProject });\n}\n\nexport async function memoryStore(opts: StoreOptions): Promise<StoreResult> {\n return storeMemory(getDb(), opts);\n}\n\nexport function memoryLog(sessionId: string, role: string, content: string): string {\n return getDb().appendLog({\n sessionId,\n role: role as \"user\" | \"assistant\" | \"system\",\n content,\n project: currentProject,\n metadata: {},\n });\n}\n\nexport function reminderCheck(): Array<{ id: string; content: string; dueAt: number | null; status: \"overdue\" | \"today\" | \"upcoming\"; scope: string }> {\n const all = getDb().checkReminders();\n return all.filter((r) => r.scope === \"global\" || r.scope === currentProject);\n}\n\nexport async function memoryForget(opts: { id?: string; query?: string; type?: string }): Promise<{ deleted: number; message: string }> {\n const db = getDb();\n if (opts.id) {\n const fullId = db.resolveId(opts.id) ?? opts.id;\n const memory = db.getById(fullId);\n if (!memory) return { deleted: 0, message: `Memory ${opts.id} not found.` };\n db.deleteMemory(fullId);\n const vecIdx = getVectorIndex();\n if (vecIdx) vecIdx.remove(fullId);\n return { deleted: 1, message: `Deleted: \"${memory.content}\" (${memory.type})` };\n }\n // Type-based delete: delete all memories of a given type\n if (opts.type) {\n const all = db.getAllForProject(currentProject);\n const matches = all.filter((m) => m.type === opts.type);\n if (matches.length === 0) return { deleted: 0, message: `No memories of type \"${opts.type}\" found.` };\n const vecIdx = getVectorIndex();\n for (const m of matches) {\n db.deleteMemory(m.id);\n if (vecIdx) vecIdx.remove(m.id);\n }\n return { deleted: matches.length, message: `Deleted ${matches.length} \"${opts.type}\" memories.` };\n }\n if (opts.query) {\n const queryEmbedding = await generateEmbedding(opts.query);\n const matches = recallMemories(db, { query: opts.query, queryEmbedding, limit: 50, minConfidence: 0, scope: currentProject });\n if (matches.length === 0) return { deleted: 0, message: `No memories found matching \"${opts.query}\".` };\n const vecIdx = getVectorIndex();\n for (const m of matches) {\n db.deleteMemory(m.id);\n if (vecIdx) vecIdx.remove(m.id);\n }\n return { deleted: matches.length, message: `Deleted ${matches.length} memories matching \"${opts.query}\".` };\n }\n return { deleted: 0, message: \"Provide an id, type, or query to forget.\" };\n}\n\nlet _localMemoryConfig: { maxStaleDays?: number; minConfidence?: number; minAccessCount?: number; maxRecallTokens?: number } = {};\n\nexport function setMemoryConfig(config: typeof _localMemoryConfig): void {\n _localMemoryConfig = config;\n}\n\nexport function getMaxRecallTokens(): number {\n return _localMemoryConfig.maxRecallTokens ?? 1500;\n}\n\nexport function memoryConsolidate(dryRun = false): ConsolidationReport {\n return consolidateMemories(getDb(), cosineSimilarity, {\n dryRun,\n maxStaleDays: _localMemoryConfig.maxStaleDays ?? 90,\n minConfidence: _localMemoryConfig.minConfidence ?? 0.3,\n minAccessCount: _localMemoryConfig.minAccessCount ?? 0,\n });\n}\n\nexport function isMemoryInitialized(): boolean {\n return db !== null;\n}\n\nexport function memoryStats(): MemoryStats {\n return getDb().getStats();\n}\n\nexport function memoryExport(): Memory[] {\n return getDb().getAllForProject(currentProject);\n}\n\nexport function memorySince(hours: number): Memory[] {\n const since = Date.now() - hours * 60 * 60 * 1000;\n const all = getDb().getMemoriesSince(since);\n return all.filter((m) => m.scope === \"global\" || m.scope === currentProject);\n}\n\nexport function memorySearch(query: string, limit?: number): Memory[] {\n return getDb().fullTextSearch(query, limit, currentProject);\n}\n\nexport function reminderSet(content: string, dueAt?: number): string {\n return getDb().insertReminder(content, dueAt ?? null, currentProject);\n}\n\nexport function reminderList(includeCompleted?: boolean): Array<{ id: string; content: string; dueAt: number | null; completed: boolean; createdAt: number; scope: string }> {\n return getDb().listReminders(includeCompleted, currentProject);\n}\n\nexport function reminderComplete(id: string): boolean {\n const fullId = getDb().resolveReminderId(id) ?? id;\n return getDb().completeReminder(fullId);\n}\n\nexport { type RecallResult, type ContextResult, type StoreResult, type StoreOptions, type ConsolidationReport, type MemoryStats, type Memory };\n\n// ─── Admin: Doctor ───────────────────────────────────────────────────────────\n\n/**\n * Run read-only health diagnostics on the amem database.\n * Returns a structured report with status, stats, and a list of issues.\n */\nexport async function memoryDoctor(): Promise<DiagnosticReport> {\n return runDiagnostics(getDb());\n}\n\n// ─── Admin: Repair ───────────────────────────────────────────────────────────\n\nexport interface MemoryRepairResult {\n dryRun: boolean;\n status: \"healthy\" | \"warning\" | \"critical\";\n issues: string[];\n actions: string[];\n}\n\n/**\n * Diagnose and optionally repair the memory database.\n * By default runs in dry-run mode — set dryRun:false to apply fixes.\n */\nexport async function memoryRepair(\n opts: { dryRun?: boolean } = {}\n): Promise<MemoryRepairResult> {\n const dryRun = opts.dryRun ?? true;\n if (dryRun) {\n // Dry-run: run diagnostics and surface what would be repaired\n const diag = runDiagnostics(getDb());\n return {\n dryRun: true,\n status: diag.status,\n issues: diag.issues.map((issue) => issue.message),\n actions: diag.issues.map((issue) => `Would fix: ${issue.suggestion}`),\n };\n }\n // Actual repair: call repairDatabase with the DB path\n const dbPath = process.env.AMEM_DB ?? path.join(os.homedir(), \".amem\", \"memory.db\");\n const result = repairDatabase(dbPath);\n return {\n dryRun: false,\n status: result.status === \"repaired\" ? \"warning\" : result.status === \"failed\" ? \"critical\" : \"healthy\",\n issues: [],\n actions: result.memoriesRecovered > 0 ? [`Recovered ${result.memoriesRecovered} memories`] : [],\n };\n}\n\n// ─── Admin: Config ───────────────────────────────────────────────────────────\n\n/**\n * Read or update the amem configuration.\n * With no args, returns the current config.\n * With updates, deep-merges and saves the new config, then returns authoritative post-save state.\n */\nexport async function memoryConfig(\n updates?: DeepPartial<AmemConfig>\n): Promise<AmemConfig> {\n const current = loadConfig();\n if (updates && Object.keys(updates).length > 0) {\n saveConfig(updates as Partial<AmemConfig>);\n return loadConfig(); // read back authoritative merged state\n }\n return current;\n}\n\n// ─── Advanced Recall ─────────────────────────────────────────────────────────\n\n/**\n * Multi-strategy recall: combines semantic, FTS5, knowledge graph, and\n * temporal scoring into a unified ranked result.\n */\nexport async function memoryMultiRecall(\n query: string,\n opts: { limit?: number; scope?: string } = {}\n): Promise<{ memories: Awaited<ReturnType<typeof multiStrategyRecall>>; total: number }> {\n const queryEmbedding = await generateEmbedding(query);\n const memories = await multiStrategyRecall(getDb(), {\n query,\n queryEmbedding,\n limit: opts.limit ?? 10,\n scope: opts.scope ?? currentProject ?? undefined,\n });\n return { memories, total: memories.length };\n}\n\n// ─── Reflection ──────────────────────────────────────────────────────────────\n\n/**\n * Run the self-evolving memory reflection engine.\n * Returns clusters, contradictions, and synthesis candidates.\n */\nexport async function memoryReflect(\n config?: Partial<ReflectionConfig>\n): Promise<ReflectionReport> {\n return reflect(getDb(), config);\n}\n\n/**\n * Check whether a reflection run is due based on last-run metadata.\n */\nexport function checkReflectionDue(): { due: boolean; reason: string } {\n return isReflectionDue(getDb());\n}\n\n// ─── Tier ────────────────────────────────────────────────────────────────────\n\n/**\n * Move a memory between tiers: \"core\" | \"working\" | \"archival\".\n */\nexport function memoryTier(\n id: string,\n tier: string,\n): { id: string; tier: string; ok: true } | { ok: false; error: string } {\n try {\n const db = getDb();\n const fullId = db.resolveId(id) ?? id;\n db.updateTier(fullId, tier);\n return { id: fullId, tier, ok: true };\n } catch (err) {\n return { ok: false, error: err instanceof Error ? err.message : String(err) };\n }\n}\n\n// ─── Detail ──────────────────────────────────────────────────────────────────\n\n/**\n * Get the full Memory object for a given id. Returns null if not found.\n */\nexport function memoryDetail(id: string): Memory | null {\n const db = getDb();\n const fullId = db.resolveId(id) ?? id;\n return db.getById(fullId);\n}\n\n// ─── Relate ──────────────────────────────────────────────────────────────────\n\n/**\n * Add a knowledge-graph relation between two memories.\n */\nexport function memoryRelate(\n fromId: string,\n toId: string,\n type: string,\n strength?: number,\n): { ok: true; relationId: string } | { ok: false; error: string } {\n try {\n const relationId = getDb().addRelation(fromId, toId, type, strength);\n return { ok: true, relationId };\n } catch (err) {\n return { ok: false, error: err instanceof Error ? err.message : String(err) };\n }\n}\n\n// ─── Expire ──────────────────────────────────────────────────────────────────\n\n/**\n * Mark a memory as expired (sets valid_until to now).\n * The optional `reason` string is for caller-side logging only — the db\n * itself stores the timestamp rather than a reason field.\n */\nexport function memoryExpire(\n id: string,\n reason?: string,\n): { ok: true; id: string; reason?: string } | { ok: false; error: string } {\n try {\n const db = getDb();\n const fullId = db.resolveId(id) ?? id;\n db.expireMemory(fullId);\n return { ok: true, id: fullId, ...(reason !== undefined ? { reason } : {}) };\n } catch (err) {\n return { ok: false, error: err instanceof Error ? err.message : String(err) };\n }\n}\n\n// ─── Versions ────────────────────────────────────────────────────────────────\n\n/**\n * Return the full version history for a memory.\n */\nexport function memoryVersions(id: string): MemoryVersion[] {\n const db = getDb();\n const fullId = db.resolveId(id) ?? id;\n return db.getVersionHistory(fullId);\n}\n\n// ─── Sync ────────────────────────────────────────────────────────────────────\n\nexport type MemorySyncAction = \"import-claude\" | \"export-team\" | \"import-team\" | \"sync-copilot\";\n\nexport interface MemorySyncOptions {\n /** For import-claude: filter to a specific project path */\n projectFilter?: string;\n /** For import-claude / export-team: skip actual writes */\n dryRun?: boolean;\n /** For export-team: output directory */\n outputDir?: string;\n /** For export-team: userId identifier in the export manifest */\n userId?: string;\n /** For import-team: path to the JSON export file */\n filePath?: string;\n /** For sync-copilot: options forwarded to syncToCopilot */\n copilotOptions?: CopilotSyncOptions;\n /** For import-team: options forwarded to importFromTeam */\n importOptions?: TeamImportOptions;\n}\n\n/**\n * Sync memories with Claude Code auto-memory or team members.\n *\n * Actions:\n * - \"import-claude\" — read Claude Code memory files and import into amem\n * - \"export-team\" — write a shareable JSON export for teammates\n * - \"import-team\" — merge a teammate's JSON export into amem\n * - \"sync-copilot\" — update the Copilot instructions file from amem memories\n */\nexport async function memorySync(\n action: MemorySyncAction,\n opts: MemorySyncOptions = {},\n): Promise<SyncResult | TeamImportResult | { file: string; count: number } | CopilotSyncResult | { ok: false; error: string }> {\n const db = getDb();\n try {\n switch (action) {\n case \"import-claude\":\n return await syncFromClaude(db, opts.projectFilter, opts.dryRun ?? false);\n\n case \"export-team\": {\n const exportOptions: TeamExportOptions = {\n userId: opts.userId ?? currentProject,\n };\n return await exportForTeam(db, opts.outputDir ?? process.cwd(), exportOptions);\n }\n\n case \"import-team\":\n if (!opts.filePath) {\n return { ok: false, error: \"filePath is required for import-team\" };\n }\n return await importFromTeam(db, opts.filePath, opts.importOptions);\n\n case \"sync-copilot\":\n return syncToCopilot(db, opts.copilotOptions);\n\n default:\n return { ok: false, error: `Unknown sync action: ${action as string}` };\n }\n } catch (err) {\n return { ok: false, error: err instanceof Error ? err.message : String(err) };\n }\n}\n\nexport type { MemoryVersion, MemoryRelation, SyncResult, TeamImportResult, CopilotSyncResult };\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport os from \"node:os\";\n\nimport { ORCHESTRATOR_PROFILES } from \"./profiles/orchestrator-profiles.js\";\n\nexport interface ProfileTemplate {\n name: string;\n label: string;\n description: string;\n core: string;\n rules?: string;\n skills?: string;\n}\n\nexport const BUILT_IN_PROFILES: ProfileTemplate[] = [\n {\n name: \"coder\",\n label: \"Coder\",\n description: \"Direct, technical, code-first. Skips pleasantries, shows code.\",\n core: `# Coder\n\n## Identity\n- Role: Coder is your technical pair programmer\n- Personality: direct, precise, efficient — code speaks louder than words\n- Communication: lead with code, explain after. No fluff.\n- Values: simplicity over cleverness, working code over perfect code, tests over trust\n- Boundaries: won't pretend to be human, flags when out of depth\n\n### Appearance\n- Base: focused developer, dark hoodie, terminal glow\n- Style: minimal\n- Palette: green on black`,\n rules: `# Coder Rules\n\n## Always\n- Show code before explaining\n- Include error handling\n- Suggest tests for new code\n\n## Never\n- Write code without understanding the requirement\n- Push to main without tests\n- Ignore security implications`,\n },\n {\n name: \"writer\",\n label: \"Writer\",\n description: \"Creative, eloquent, story-driven. Focuses on narrative and engagement.\",\n core: `# Muse\n\n## Identity\n- Role: Muse is your creative writing partner\n- Personality: eloquent, imaginative, encouraging — finds the story in everything\n- Communication: explore ideas together, offer alternatives, celebrate good writing\n- Values: authenticity over formulas, voice over grammar, emotion over information\n- Boundaries: won't write without understanding the audience, flags when content is sensitive\n\n### Appearance\n- Base: warm expression, creative energy, pen in hand\n- Style: illustrated\n- Palette: warm amber and cream`,\n rules: `# Writer Rules\n\n## Always\n- Ask about the target audience\n- Offer 2-3 angle options before drafting\n- Read drafts aloud mentally for rhythm\n\n## Never\n- Use cliches without subverting them\n- Write without a clear hook\n- Ignore tone consistency`,\n },\n {\n name: \"researcher\",\n label: \"Researcher\",\n description: \"Analytical, thorough, citation-focused. Digs deep, verifies claims.\",\n core: `# Scholar\n\n## Identity\n- Role: Scholar is your research analyst\n- Personality: analytical, thorough, intellectually curious — never takes claims at face value\n- Communication: present findings with evidence, flag uncertainty, compare perspectives\n- Values: accuracy over speed, nuance over simplification, primary sources over summaries\n- Boundaries: clearly marks speculation vs fact, flags when evidence is insufficient\n\n### Appearance\n- Base: thoughtful expression, glasses, surrounded by notes\n- Style: minimal\n- Palette: navy and white`,\n rules: `# Researcher Rules\n\n## Always\n- Cite sources when making factual claims\n- Flag confidence level (high/medium/low)\n- Present multiple perspectives on contested topics\n\n## Never\n- Present speculation as fact\n- Ignore contradicting evidence\n- Oversimplify complex topics`,\n },\n ...ORCHESTRATOR_PROFILES,\n];\n\n/**\n * Install a built-in profile template.\n */\nexport function installProfileTemplate(templateName: string, userName?: string): string | null {\n const template = BUILT_IN_PROFILES.find((t) => t.name === templateName);\n if (!template) return null;\n\n const profileDir = path.join(os.homedir(), \".acore\", \"profiles\", template.name);\n if (fs.existsSync(profileDir)) return `Profile already exists: ${template.name}`;\n\n fs.mkdirSync(profileDir, { recursive: true });\n\n // Write core.md\n let core = template.core;\n if (userName) {\n core += `\\n\\n---\\n\\n## Relationship\\n- Name: ${userName}\\n- Nicknames: []\\n- Communication: [updated over time]\\n- Detail level: balanced\\n`;\n }\n fs.writeFileSync(path.join(profileDir, \"core.md\"), core, \"utf-8\");\n\n // Write rules.md if template has one\n if (template.rules) {\n fs.writeFileSync(path.join(profileDir, \"rules.md\"), template.rules, \"utf-8\");\n }\n\n // Write skills.md if template has one\n if (template.skills) {\n fs.writeFileSync(path.join(profileDir, \"skills.md\"), template.skills, \"utf-8\");\n }\n\n return null; // success\n}\n","import type { ProfileTemplate } from \"../profile-templates.js\";\n\nexport const architectProfile: ProfileTemplate = {\n name: \"architect\",\n label: \"System Architect\",\n description: \"Designs system architecture, decomposes features into modules, plans file structure and interfaces\",\n core: `# System Architect\n\nYou are a system architect. Your job is to:\n- Analyze requirements and design the overall system structure\n- Define module boundaries, interfaces, and data flows\n- Plan file structure and naming conventions\n- Identify dependencies and integration points\n- Choose appropriate patterns and abstractions\n- Consider scalability, maintainability, and testability\n\n## Output Format\nProduce a clear, structured design document with:\n1. **Architecture overview** — high-level components and their relationships\n2. **File structure** — exact paths for new/modified files\n3. **Interfaces** — key types, function signatures, and data contracts\n4. **Dependencies** — what depends on what, build order\n5. **Risks** — potential issues and mitigation strategies\n\nBe precise with file paths and interface definitions. The implementation agents will follow your design exactly.`,\n rules: `- Never write implementation code — design only\n- Always specify exact file paths\n- Consider existing codebase patterns before proposing new ones\n- Flag breaking changes explicitly`,\n};\n\nexport const securityProfile: ProfileTemplate = {\n name: \"security\",\n label: \"Security Analyst\",\n description: \"Reviews code for security vulnerabilities, runs SAST checks, audits dependencies\",\n core: `# Security Analyst\n\nYou are a security analyst. Your job is to:\n- Review code for OWASP Top 10 vulnerabilities\n- Check for injection flaws (SQL, command, XSS)\n- Verify authentication and authorization patterns\n- Audit dependency versions for known CVEs\n- Check for secrets/credentials in code\n- Validate input sanitization and output encoding\n- Review error handling for information leakage\n\n## Output Format\nProduce a security report with:\n1. **Critical** — must fix before merge (injection, auth bypass, secrets)\n2. **High** — should fix (missing validation, weak crypto)\n3. **Medium** — recommended (verbose errors, missing rate limiting)\n4. **Low** — informational (best practice suggestions)\n\nFor each finding: file path, line number, description, remediation.`,\n rules: `- Never approve code with Critical findings\n- Always check for hardcoded secrets\n- Flag any use of eval, exec, or shell string concatenation\n- Verify all user input is validated at system boundaries`,\n};\n\nexport const testerProfile: ProfileTemplate = {\n name: \"tester\",\n label: \"Test Engineer\",\n description: \"Writes comprehensive tests, identifies edge cases, ensures coverage\",\n core: `# Test Engineer\n\nYou are a test engineer. Your job is to:\n- Write comprehensive unit and integration tests\n- Identify edge cases and boundary conditions\n- Test error paths and failure modes\n- Verify behavior against specifications\n- Ensure tests are deterministic and fast\n- Follow existing test patterns in the codebase\n\n## Testing Principles\n- Test behavior, not implementation details\n- Each test should verify one specific thing\n- Use descriptive test names that explain the expected behavior\n- Arrange-Act-Assert pattern\n- Mock external dependencies, test internal logic directly\n- Prefer integration tests for complex interactions\n\n## Output Format\nProduce test files following the project's existing patterns (Vitest, Jest, pytest, etc.).\nInclude: happy path, error cases, edge cases, boundary values.`,\n rules: `- Never skip error path testing\n- Always test boundary conditions\n- Tests must be deterministic (no timing dependencies, no random values)\n- Follow the project's existing test framework and patterns`,\n};\n\nexport const reviewerProfile: ProfileTemplate = {\n name: \"reviewer\",\n label: \"Code Reviewer\",\n description: \"Reviews code for quality, correctness, and adherence to patterns\",\n core: `# Code Reviewer\n\nYou are a code reviewer. Your job is to:\n- Check code correctness and logic errors\n- Verify adherence to project conventions and patterns\n- Identify potential performance issues\n- Assess readability and maintainability\n- Check error handling completeness\n- Verify tests adequately cover the changes\n\n## Review Approach\n- Focus on correctness first, style second\n- Flag bugs and logic errors as Critical\n- Flag missing error handling as High\n- Flag style and convention issues as Medium\n- Acknowledge good patterns and clean code\n\n## Output Format\nProduce a review with confidence-scored findings:\n- **CRITICAL** (confidence > 0.9) — definite bugs or security issues\n- **IMPORTANT** (confidence > 0.7) — likely problems or missing handling\n- **SUGGESTION** (confidence > 0.5) — improvements worth considering\n- **PRAISE** — highlight good patterns\n\nInclude file path, line range, and specific explanation for each finding.`,\n rules: `- Never rubber-stamp — always provide substantive review\n- Focus on what matters: correctness > performance > style\n- Be specific: cite exact lines and explain why something is wrong\n- Distinguish between \"must fix\" and \"nice to have\"`,\n};\n\nexport const ORCHESTRATOR_PROFILES: ProfileTemplate[] = [\n architectProfile,\n securityProfile,\n testerProfile,\n reviewerProfile,\n];\n\n/** Get a profile by name */\nexport function getOrchestratorProfile(name: string): ProfileTemplate | undefined {\n return ORCHESTRATOR_PROFILES.find((p) => p.name === name);\n}\n\n/** Get all profile names */\nexport function getOrchestratorProfileNames(): string[] {\n return ORCHESTRATOR_PROFILES.map((p) => p.name);\n}\n","import * as p from \"@clack/prompts\";\nimport pc from \"picocolors\";\nimport type { UserIdentity } from \"./user-identity.js\";\nimport { saveUserIdentity } from \"./user-identity.js\";\nimport { loadShowcaseManifest, installShowcaseTemplate, type ShowcaseOption } from \"./showcase-bridge.js\";\n\n/**\n * Run the interactive onboarding flow for first-time users.\n * Captures user identity with personality-driven questions.\n * Returns the saved UserIdentity.\n */\nexport async function runOnboarding(): Promise<UserIdentity | null> {\n console.log(\"\");\n p.intro(pc.bold(\"Let's get to know each other\"));\n p.log.info(pc.dim(\"Quick setup so I can be actually useful to you. Takes ~30 seconds.\"));\n\n // --- Name ---\n const name = await p.text({\n message: \"What should I call you?\",\n placeholder: \"Your name or nickname\",\n validate: (v) => (v.trim().length === 0 ? \"I need something to call you!\" : undefined),\n });\n if (p.isCancel(name)) return null;\n\n // --- Role ---\n const role = await p.select({\n message: `Nice to meet you, ${pc.bold(name)}! What's your main thing?`,\n options: [\n { value: \"developer\", label: \"Building things\", hint: \"developer, engineer, maker\" },\n { value: \"designer\", label: \"Designing things\", hint: \"UI/UX, creative, visual\" },\n { value: \"student\", label: \"Learning things\", hint: \"student, researcher, exploring\" },\n { value: \"manager\", label: \"Running things\", hint: \"lead, PM, coordinator\" },\n { value: \"generalist\", label: \"A bit of everything\", hint: \"jack of all trades\" },\n ],\n initialValue: \"developer\",\n });\n if (p.isCancel(role)) return null;\n\n const ROLE_LABELS: Record<string, string> = {\n developer: \"Developer / Engineer\",\n designer: \"Designer / Creative\",\n student: \"Student / Researcher\",\n manager: \"Lead / Manager\",\n generalist: \"Generalist\",\n };\n\n // --- Expertise ---\n const expertise = await p.select({\n message: \"How deep in the game are you?\",\n options: [\n { value: \"beginner\", label: \"Just getting started\", hint: \"explain everything, I'm here to learn\" },\n { value: \"intermediate\", label: \"Know my way around\", hint: \"skip the basics, get to the point\" },\n { value: \"advanced\", label: \"Been at it for years\", hint: \"show me the advanced stuff\" },\n { value: \"expert\", label: \"I wrote the book\", hint: \"challenge me, peer-level talk\" },\n ],\n initialValue: \"intermediate\",\n });\n if (p.isCancel(expertise)) return null;\n\n const EXPERTISE_LABELS: Record<string, string> = {\n beginner: \"Getting Started\",\n intermediate: \"Intermediate\",\n advanced: \"Advanced\",\n expert: \"Expert\",\n };\n\n // --- Communication Style ---\n const style = await p.select({\n message: \"How do you like your answers?\",\n options: [\n { value: \"concise\", label: \"Short and sharp\", hint: \"code first, talk later\" },\n { value: \"balanced\", label: \"Balanced\", hint: \"explain the why, show the how\" },\n { value: \"thorough\", label: \"Deep and detailed\", hint: \"I want to understand everything\" },\n { value: \"socratic\", label: \"Make me think\", hint: \"ask questions, guide me there\" },\n ],\n initialValue: \"balanced\",\n });\n if (p.isCancel(style)) return null;\n\n const STYLE_LABELS: Record<string, string> = {\n concise: \"Concise — code first, talk later\",\n balanced: \"Balanced — explain and show\",\n thorough: \"Thorough — deep explanations\",\n socratic: \"Socratic — guide with questions\",\n };\n\n // --- Working On (optional) ---\n const workingOn = await p.text({\n message: \"What are you working on right now? \" + pc.dim(\"(optional, press Enter to skip)\"),\n placeholder: \"e.g. a React app, a CLI tool, learning Python...\",\n defaultValue: \"\",\n });\n if (p.isCancel(workingOn)) return null;\n\n // --- Notes (optional) ---\n const notes = await p.text({\n message: \"Anything else I should know about you? \" + pc.dim(\"(optional)\"),\n placeholder: \"e.g. I prefer TypeScript, I work on a Mac, I'm in GMT+8...\",\n defaultValue: \"\",\n });\n if (p.isCancel(notes)) return null;\n\n // --- Build and save ---\n const today = new Date().toISOString().split(\"T\")[0];\n\n const user: UserIdentity = {\n name: (name as string).trim(),\n role: role as UserIdentity[\"role\"],\n roleLabel: ROLE_LABELS[role as string] || \"Generalist\",\n expertise: expertise as UserIdentity[\"expertise\"],\n expertiseLabel: EXPERTISE_LABELS[expertise as string] || \"Intermediate\",\n style: style as UserIdentity[\"style\"],\n styleLabel: STYLE_LABELS[style as string] || \"Balanced\",\n workingOn: (workingOn as string).trim() || undefined,\n notes: (notes as string).trim() || undefined,\n createdAt: today,\n updatedAt: today,\n };\n\n saveUserIdentity(user);\n\n // --- Showcase Template (optional) ---\n let showcaseInstalled: string | null = null;\n const showcases = loadShowcaseManifest();\n if (showcases.length > 0) {\n console.log(\"\");\n const wantShowcase = await p.confirm({\n message: \"Want to give your companion a specialty? \" + pc.dim(\"(pre-built personalities with workflows)\"),\n initialValue: false,\n });\n\n if (!p.isCancel(wantShowcase) && wantShowcase) {\n // Group by category for nicer display\n const categories = new Map<string, ShowcaseOption[]>();\n for (const s of showcases) {\n if (!categories.has(s.category)) categories.set(s.category, []);\n categories.get(s.category)!.push(s);\n }\n\n const options: Array<{ value: string; label: string; hint: string }> = [];\n for (const [category, items] of categories) {\n for (const item of items) {\n const langBadge = item.language === \"ms\" ? \" [BM]\" : item.language === \"en+ms\" ? \" [EN/BM]\" : \"\";\n options.push({\n value: item.name,\n label: `${item.title}${langBadge}`,\n hint: item.description.slice(0, 70) + (item.description.length > 70 ? \"...\" : \"\"),\n });\n }\n }\n\n const chosen = await p.select({\n message: \"Pick a companion specialty\",\n options,\n });\n\n if (!p.isCancel(chosen)) {\n const chosenName = chosen as string;\n try {\n const result = installShowcaseTemplate(chosenName);\n if (result.installed.length > 0) {\n showcaseInstalled = chosenName;\n const entry = showcases.find((s) => s.name === chosenName);\n p.log.success(`Installed ${pc.bold(entry?.title || chosenName)}`);\n for (const f of result.installed) {\n process.stdout.write(pc.dim(` ${f}\\n`));\n }\n if (result.backed_up.length > 0) {\n p.log.info(pc.dim(`Backed up ${result.backed_up.length} existing file(s) (.bak)`));\n }\n }\n } catch (err) {\n p.log.warning(`Could not install showcase: ${err instanceof Error ? err.message : String(err)}`);\n }\n }\n }\n }\n\n // --- Confirmation ---\n console.log(\"\");\n p.log.success(`Profile saved for ${pc.bold(user.name)}`);\n\n const summary = [\n ` ${pc.dim(\"Role:\")} ${user.roleLabel}`,\n ` ${pc.dim(\"Level:\")} ${user.expertiseLabel}`,\n ` ${pc.dim(\"Style:\")} ${user.styleLabel}`,\n ];\n if (user.workingOn) {\n summary.push(` ${pc.dim(\"Working on:\")} ${user.workingOn}`);\n }\n if (showcaseInstalled) {\n const entry = showcases.find((s) => s.name === showcaseInstalled);\n summary.push(` ${pc.dim(\"Specialty:\")} ${entry?.title || showcaseInstalled}`);\n }\n console.log(summary.join(\"\\n\"));\n console.log(\"\");\n\n p.log.info(pc.dim(\"Update anytime with /profile edit\"));\n\n return user;\n}\n\n/**\n * Quick profile update — edit specific fields.\n * Returns updated identity or null if cancelled.\n */\nexport async function editProfile(current: UserIdentity): Promise<UserIdentity | null> {\n const field = await p.select({\n message: \"What do you want to update?\",\n options: [\n { value: \"name\", label: \"Name\", hint: `currently: ${current.name}` },\n { value: \"role\", label: \"Role\", hint: `currently: ${current.roleLabel}` },\n { value: \"expertise\", label: \"Expertise level\", hint: `currently: ${current.expertiseLabel}` },\n { value: \"style\", label: \"Communication style\", hint: `currently: ${current.styleLabel}` },\n { value: \"workingOn\", label: \"What you're working on\", hint: current.workingOn || \"not set\" },\n { value: \"notes\", label: \"Notes\", hint: current.notes ? current.notes.slice(0, 40) : \"not set\" },\n ],\n });\n if (p.isCancel(field)) return null;\n\n const updated = { ...current, updatedAt: new Date().toISOString().split(\"T\")[0] };\n\n switch (field) {\n case \"name\": {\n const val = await p.text({ message: \"New name\", defaultValue: current.name });\n if (p.isCancel(val)) return null;\n updated.name = (val as string).trim();\n break;\n }\n case \"role\": {\n const val = await p.select({\n message: \"New role\",\n options: [\n { value: \"developer\", label: \"Building things\" },\n { value: \"designer\", label: \"Designing things\" },\n { value: \"student\", label: \"Learning things\" },\n { value: \"manager\", label: \"Running things\" },\n { value: \"generalist\", label: \"A bit of everything\" },\n ],\n initialValue: current.role,\n });\n if (p.isCancel(val)) return null;\n updated.role = val as UserIdentity[\"role\"];\n const labels: Record<string, string> = { developer: \"Developer / Engineer\", designer: \"Designer / Creative\", student: \"Student / Researcher\", manager: \"Lead / Manager\", generalist: \"Generalist\" };\n updated.roleLabel = labels[val as string] || \"Generalist\";\n break;\n }\n case \"expertise\": {\n const val = await p.select({\n message: \"New expertise level\",\n options: [\n { value: \"beginner\", label: \"Just getting started\" },\n { value: \"intermediate\", label: \"Know my way around\" },\n { value: \"advanced\", label: \"Been at it for years\" },\n { value: \"expert\", label: \"I wrote the book\" },\n ],\n initialValue: current.expertise,\n });\n if (p.isCancel(val)) return null;\n updated.expertise = val as UserIdentity[\"expertise\"];\n const labels: Record<string, string> = { beginner: \"Getting Started\", intermediate: \"Intermediate\", advanced: \"Advanced\", expert: \"Expert\" };\n updated.expertiseLabel = labels[val as string] || \"Intermediate\";\n break;\n }\n case \"style\": {\n const val = await p.select({\n message: \"New communication style\",\n options: [\n { value: \"concise\", label: \"Short and sharp\" },\n { value: \"balanced\", label: \"Balanced\" },\n { value: \"thorough\", label: \"Deep and detailed\" },\n { value: \"socratic\", label: \"Make me think\" },\n ],\n initialValue: current.style,\n });\n if (p.isCancel(val)) return null;\n updated.style = val as UserIdentity[\"style\"];\n const labels: Record<string, string> = { concise: \"Concise — code first, talk later\", balanced: \"Balanced — explain and show\", thorough: \"Thorough — deep explanations\", socratic: \"Socratic — guide with questions\" };\n updated.styleLabel = labels[val as string] || \"Balanced\";\n break;\n }\n case \"workingOn\": {\n const val = await p.text({ message: \"What are you working on?\", defaultValue: current.workingOn || \"\" });\n if (p.isCancel(val)) return null;\n updated.workingOn = (val as string).trim() || undefined;\n break;\n }\n case \"notes\": {\n const val = await p.text({ message: \"Notes about you\", defaultValue: current.notes || \"\" });\n if (p.isCancel(val)) return null;\n updated.notes = (val as string).trim() || undefined;\n break;\n }\n }\n\n saveUserIdentity(updated);\n p.log.success(\"Profile updated!\");\n return updated;\n}\n","/**\n * Bridge to @aman_asmuei/aman-showcase.\n * Safely handles the case where the showcase package isn't installed.\n * All imports are dynamic to avoid hard dependency.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport os from \"node:os\";\nimport { log } from \"./logger.js\";\n\nexport interface ShowcaseOption {\n name: string;\n title: string;\n description: string;\n category: string;\n language: string;\n tags: string[];\n}\n\nexport interface ShowcaseInstallResult {\n installed: string[];\n backed_up: string[];\n env_example: string;\n}\n\nlet cachedManifest: ShowcaseOption[] | null = null;\nlet cachedShowcaseRoot: string | null = null;\n\n/**\n * Find the aman-showcase package root directory.\n */\nfunction findShowcaseRoot(): string | null {\n const candidates = [\n // Sibling in monorepo\n path.join(os.homedir(), \"project-aman\", \"aman-showcase\"),\n path.join(process.cwd(), \"..\", \"aman-showcase\"),\n // npm global install\n path.join(process.cwd(), \"node_modules\", \"@aman_asmuei\", \"aman-showcase\"),\n ];\n\n for (const candidate of candidates) {\n if (fs.existsSync(path.join(candidate, \"src\", \"manifest.ts\")) ||\n fs.existsSync(path.join(candidate, \"dist\", \"index.js\"))) {\n return candidate;\n }\n }\n\n return null;\n}\n\n/**\n * Parse showcase entries from manifest.ts source (works without building).\n */\nfunction parseManifestSource(source: string): ShowcaseOption[] {\n const entries: ShowcaseOption[] = [];\n // Match each showcase entry object\n const regex = /\\{\\s*name:\\s*\"([^\"]+)\"[\\s\\S]*?title:\\s*\"([^\"]+)\"[\\s\\S]*?description:\\s*\"([^\"]+)\"[\\s\\S]*?category:\\s*\"([^\"]+)\"[\\s\\S]*?language:\\s*\"([^\"]+)\"[\\s\\S]*?tags:\\s*\\[([^\\]]*)\\]/g;\n\n let match;\n while ((match = regex.exec(source)) !== null) {\n entries.push({\n name: match[1],\n title: match[2],\n description: match[3],\n category: match[4],\n language: match[5],\n tags: match[6].split(\",\").map((t) => t.trim().replace(/\"/g, \"\")).filter(Boolean),\n });\n }\n\n return entries;\n}\n\n/**\n * Load showcase manifest from @aman_asmuei/aman-showcase.\n * Returns empty array if the package isn't available.\n */\nexport function loadShowcaseManifest(): ShowcaseOption[] {\n if (cachedManifest !== null) return cachedManifest;\n\n const root = findShowcaseRoot();\n if (!root) {\n cachedManifest = [];\n return cachedManifest;\n }\n\n cachedShowcaseRoot = root;\n\n // Try reading manifest source directly (works without dist build)\n const manifestSrc = path.join(root, \"src\", \"manifest.ts\");\n if (fs.existsSync(manifestSrc)) {\n try {\n const content = fs.readFileSync(manifestSrc, \"utf-8\");\n const parsed = parseManifestSource(content);\n if (parsed.length > 0) {\n cachedManifest = parsed;\n return cachedManifest;\n }\n } catch {\n log.debug(\"showcase\", \"Failed to parse manifest.ts\");\n }\n }\n\n // Fallback: scan directories for showcases\n try {\n const dirs = fs.readdirSync(root, { withFileTypes: true })\n .filter((d) => d.isDirectory() && !d.name.startsWith(\".\") &&\n ![\"node_modules\", \"dist\", \"src\", \"bin\", \"docs\"].includes(d.name))\n .filter((d) => fs.existsSync(path.join(root, d.name, \"identity\")));\n\n cachedManifest = dirs.map((d) => ({\n name: d.name,\n title: d.name.charAt(0).toUpperCase() + d.name.slice(1),\n description: \"\",\n category: \"other\",\n language: \"en\",\n tags: [],\n }));\n } catch {\n cachedManifest = [];\n }\n\n return cachedManifest;\n}\n\n/**\n * Install a showcase template by name.\n * Copies identity, rules, workflows, and skills from the showcase package.\n */\nexport function installShowcaseTemplate(name: string): ShowcaseInstallResult {\n const root = cachedShowcaseRoot || findShowcaseRoot();\n if (!root) {\n throw new Error(\"aman-showcase package not found. Install it or check the path.\");\n }\n\n const showcaseDir = path.join(root, name);\n if (!fs.existsSync(showcaseDir) || !fs.existsSync(path.join(showcaseDir, \"identity\"))) {\n throw new Error(`Showcase \"${name}\" not found in ${root}`);\n }\n\n const result: ShowcaseInstallResult = { installed: [], backed_up: [], env_example: \"\" };\n const home = os.homedir();\n\n const copies: Array<{ src: string; dest: string; label: string }> = [\n {\n src: path.join(showcaseDir, \"identity\", \"core.md\"),\n dest: path.join(home, \".acore\", \"core.md\"),\n label: \"~/.acore/core.md (identity)\",\n },\n {\n src: path.join(showcaseDir, \"workflows\", \"flow.md\"),\n dest: path.join(home, \".aflow\", \"flow.md\"),\n label: \"~/.aflow/flow.md (workflows)\",\n },\n {\n src: path.join(showcaseDir, \"rules\", \"rules.md\"),\n dest: path.join(home, \".arules\", \"rules.md\"),\n label: \"~/.arules/rules.md (guardrails)\",\n },\n ];\n\n // Skills — consolidate individual skill files into ~/.askill/skills.md\n const skillsSrc = path.join(showcaseDir, \"skills\");\n if (fs.existsSync(skillsSrc)) {\n const skillFiles = fs.readdirSync(skillsSrc).filter((f: string) => f.endsWith(\".md\"));\n if (skillFiles.length > 0) {\n // Read all skill files and merge into a single skills.md\n const skillParts: string[] = [];\n for (const skillFile of skillFiles) {\n const content = fs.readFileSync(path.join(skillsSrc, skillFile), \"utf-8\").trim();\n if (content) skillParts.push(content);\n }\n\n if (skillParts.length > 0) {\n const skillsDest = path.join(home, \".askill\", \"skills.md\");\n const consolidated = `# Skills\\n\\n${skillParts.join(\"\\n\\n---\\n\\n\")}\\n`;\n\n // Backup existing\n if (fs.existsSync(skillsDest)) {\n fs.copyFileSync(skillsDest, `${skillsDest}.bak`);\n result.backed_up.push(\"~/.askill/skills.md (skills)\");\n }\n\n fs.mkdirSync(path.dirname(skillsDest), { recursive: true });\n fs.writeFileSync(skillsDest, consolidated, \"utf-8\");\n result.installed.push(`~/.askill/skills.md (${skillFiles.length} skill${skillFiles.length > 1 ? \"s\" : \"\"} consolidated)`);\n }\n }\n }\n\n for (const { src, dest, label } of copies) {\n if (!fs.existsSync(src)) continue;\n\n // Backup existing files\n if (fs.existsSync(dest)) {\n const backup = `${dest}.bak`;\n fs.copyFileSync(dest, backup);\n result.backed_up.push(label);\n }\n\n fs.mkdirSync(path.dirname(dest), { recursive: true });\n fs.copyFileSync(src, dest);\n result.installed.push(label);\n }\n\n // Copy env example if present\n const envExample = path.join(showcaseDir, \"config\", \"telegram.env.example\");\n if (fs.existsSync(envExample)) {\n const destEnv = path.join(process.cwd(), \".env.example\");\n fs.copyFileSync(envExample, destEnv);\n result.env_example = destEnv;\n }\n\n log.debug(\"showcase\", `Installed showcase: ${name} (${result.installed.length} files)`);\n return result;\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport os from \"node:os\";\n\nconst MAX_READ_BYTES = 50_000;\nconst HOME = fs.realpathSync(os.homedir());\nconst TMPDIR = fs.realpathSync(os.tmpdir());\nconst CWD = fs.realpathSync(process.cwd());\n\nfunction realOrBest(p: string): string {\n // Walk up the path until we find an existing ancestor, then append the rest.\n // This handles non-existent files under symlinked directories (e.g. macOS /var → /private/var).\n const parts = p.split(path.sep);\n for (let i = parts.length; i > 0; i--) {\n const candidate = parts.slice(0, i).join(path.sep) || path.sep;\n try {\n const real = fs.realpathSync(candidate);\n const remainder = parts.slice(i).join(path.sep);\n return remainder ? `${real}${path.sep}${remainder}` : real;\n } catch {\n // keep walking up\n }\n }\n return p;\n}\n\nfunction isUnderDir(real: string, dir: string): boolean {\n return real === dir || real.startsWith(dir + path.sep);\n}\n\nfunction assertSafePath(filePath: string): string {\n const resolved = path.resolve(filePath);\n const real = realOrBest(resolved);\n if (!isUnderDir(real, HOME) && !isUnderDir(real, CWD) && !isUnderDir(real, TMPDIR)) {\n throw new Error(`Path is outside allowed directories (home or cwd): ${real}`);\n }\n return resolved;\n}\n\nexport interface ReadFileResult {\n path: string;\n content: string;\n size: number;\n truncated: boolean;\n encoding: \"utf-8\";\n}\n\nexport async function readFile(filePath: string): Promise<ReadFileResult> {\n const resolved = assertSafePath(filePath);\n if (!fs.existsSync(resolved)) {\n throw new Error(`File not found: ${resolved}`);\n }\n const stat = fs.statSync(resolved);\n if (stat.isDirectory()) {\n throw new Error(`Path is a directory, not a file: ${resolved}. Use /file list instead.`);\n }\n const size = stat.size;\n const buf = Buffer.alloc(Math.min(size, MAX_READ_BYTES));\n const fd = fs.openSync(resolved, \"r\");\n try {\n fs.readSync(fd, buf, 0, buf.length, 0);\n } finally {\n fs.closeSync(fd);\n }\n return {\n path: resolved,\n content: buf.toString(\"utf-8\"),\n size,\n truncated: size > MAX_READ_BYTES,\n encoding: \"utf-8\",\n };\n}\n\nexport interface FileEntry {\n name: string;\n type: \"file\" | \"dir\";\n size: number;\n}\n\nexport interface ListFilesResult {\n path: string;\n entries: FileEntry[];\n total: number;\n}\n\nexport async function listFiles(\n dirPath: string,\n opts: { recursive?: boolean } = {}\n): Promise<ListFilesResult> {\n const resolved = assertSafePath(dirPath);\n if (!fs.existsSync(resolved)) {\n throw new Error(`Directory not found: ${resolved}`);\n }\n const stat = fs.statSync(resolved);\n if (!stat.isDirectory()) {\n throw new Error(`Path is a file, not a directory: ${resolved}. Use /file read instead.`);\n }\n\n const entries: FileEntry[] = [];\n\n function walk(dir: string, prefix: string) {\n const items = fs.readdirSync(dir, { withFileTypes: true });\n for (const item of items) {\n const rel = prefix ? `${prefix}/${item.name}` : item.name;\n if (item.isDirectory()) {\n entries.push({ name: rel, type: \"dir\", size: 0 });\n if (opts.recursive) walk(path.join(dir, item.name), rel);\n } else {\n const s = fs.statSync(path.join(dir, item.name));\n entries.push({ name: rel, type: \"file\", size: s.size });\n }\n }\n }\n\n walk(resolved, \"\");\n return { path: resolved, entries, total: entries.length };\n}\n","import pc from \"picocolors\";\nimport type {\n LLMClient,\n Message,\n ToolDefinition,\n ToolResultBlock,\n StreamChunk,\n} from \"./llm/types.js\";\nimport type { McpManager } from \"./mcp/client.js\";\nimport { assembleSystemPrompt } from \"./prompt.js\";\nimport { withRetry } from \"./retry.js\";\nimport { log } from \"./logger.js\";\nimport { onBeforeToolExec, type HookContext } from \"./hooks.js\";\nimport { memoryRecall } from \"./memory.js\";\nimport type { HooksConfig } from \"./config.js\";\n\nexport interface DelegationResult {\n profile: string;\n task: string;\n response: string;\n toolsUsed: string[];\n turns: number;\n success: boolean;\n error?: string;\n}\n\nexport interface DelegateOptions {\n maxTurns?: number; // max tool loop iterations (default: 10)\n silent?: boolean; // suppress output (default: false)\n tools?: ToolDefinition[]; // tools available to sub-agent\n hooksConfig?: HooksConfig; // guardrail config for tool execution\n}\n\nconst isRetryable = (err: unknown): boolean => {\n if (err instanceof Error) {\n const msg = err.message.toLowerCase();\n return msg.includes(\"rate\") || msg.includes(\"timeout\") || msg.includes(\"econnreset\");\n }\n return false;\n};\n\n/**\n * Run a task with a specific profile as a non-interactive sub-agent.\n * The sub-agent gets its own system prompt (from profile), runs a mini agent loop\n * (LLM → tools → LLM → ...), and returns the final text response.\n *\n * Reuses the parent's LLM client and MCP connections.\n */\nexport async function delegateTask(\n task: string,\n profile: string,\n client: LLMClient,\n mcpManager: McpManager,\n options: DelegateOptions = {},\n): Promise<DelegationResult> {\n // Route @name profiles to remote delegation via MCP server mode.\n if (profile.startsWith(\"@\")) {\n const remoteName = profile.slice(1).trim();\n if (!remoteName) {\n return {\n profile,\n task,\n response: \"\",\n toolsUsed: [],\n turns: 0,\n success: false,\n error: \"empty remote agent name\",\n };\n }\n // Lazy import to insulate against future cycles between delegate.ts\n // and delegate-remote.ts → server/*. The static graph is acyclic today\n // but this is cheap insurance.\n const { delegateRemote } = await import(\"./delegate-remote.js\");\n return delegateRemote(task, remoteName, {});\n }\n\n const maxTurns = options.maxTurns ?? 10;\n const silent = options.silent ?? false;\n const tools = options.tools;\n\n try {\n // Load profile-specific system prompt\n const { prompt: systemPrompt } = assembleSystemPrompt(undefined, profile);\n\n // Build the delegation prompt\n const delegationPrompt = `${systemPrompt}\n\n<delegation>\nYou are being delegated a specific task by the primary agent. Complete this task thoroughly and return your result. You have access to tools if needed. Focus on the task — do not ask follow-up questions, just do your best with what you have.\n</delegation>`;\n\n // Inject relevant memories into delegation prompt\n let finalDelegationPrompt = delegationPrompt;\n try {\n const recall = await memoryRecall(task, { limit: 3, compact: true });\n if (recall.total > 0) {\n finalDelegationPrompt += `\\n\\n<relevant-memories>\\n${recall.text}\\n</relevant-memories>`;\n }\n } catch { /* memory unavailable, proceed without */ }\n\n const messages: Message[] = [\n { role: \"user\", content: task },\n ];\n\n const toolsUsed: string[] = [];\n let turns = 0;\n\n // Collect streamed text\n const onChunk: (chunk: StreamChunk) => void = silent\n ? () => {}\n : (chunk) => {\n if (chunk.type === \"text\" && chunk.text) {\n process.stdout.write(chunk.text);\n }\n };\n\n // Initial LLM call\n let response = await withRetry(\n () => client.chat(finalDelegationPrompt, messages, onChunk, tools),\n { maxAttempts: 2, baseDelay: 1000, retryable: isRetryable },\n );\n\n messages.push(response.message);\n\n // Tool loop (same pattern as agent.ts)\n while (response.toolUses.length > 0 && turns < maxTurns) {\n turns++;\n\n const toolResults: ToolResultBlock[] = await Promise.all(\n response.toolUses.map(async (toolUse) => {\n if (!silent) {\n process.stdout.write(pc.dim(` [${profile}:${toolUse.name}...]\\n`));\n }\n toolsUsed.push(toolUse.name);\n\n // Guardrail check (same as main agent)\n if (options.hooksConfig?.rulesCheck) {\n try {\n const hookCtx: HookContext = { mcpManager, config: options.hooksConfig };\n const check = await onBeforeToolExec(toolUse.name, toolUse.input, hookCtx);\n if (!check.allow) {\n return {\n type: \"tool_result\" as const,\n tool_use_id: toolUse.id,\n content: `BLOCKED by guardrail: ${check.reason}`,\n is_error: true,\n };\n }\n } catch { /* guardrail check failed, allow */ }\n }\n\n try {\n const result = await mcpManager.callTool(toolUse.name, toolUse.input);\n return {\n type: \"tool_result\" as const,\n tool_use_id: toolUse.id,\n content: result,\n };\n } catch (err) {\n return {\n type: \"tool_result\" as const,\n tool_use_id: toolUse.id,\n content: `Error: ${err instanceof Error ? err.message : String(err)}`,\n is_error: true,\n };\n }\n }),\n );\n\n messages.push({ role: \"user\", content: toolResults });\n\n response = await withRetry(\n () => client.chat(finalDelegationPrompt, messages, onChunk, tools),\n { maxAttempts: 2, baseDelay: 1000, retryable: isRetryable },\n );\n\n messages.push(response.message);\n }\n\n // Extract final text response\n const finalMessage = response.message;\n const responseText = typeof finalMessage.content === \"string\"\n ? finalMessage.content\n : finalMessage.content\n .filter((b) => b.type === \"text\")\n .map((b) => (\"text\" in b ? b.text : \"\"))\n .join(\"\");\n\n return {\n profile,\n task,\n response: responseText,\n toolsUsed: [...new Set(toolsUsed)],\n turns,\n success: true,\n };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n log.warn(\"delegate\", `Delegation to ${profile} failed: ${error}`);\n return {\n profile,\n task,\n response: \"\",\n toolsUsed: [],\n turns: 0,\n success: false,\n error,\n };\n }\n}\n\n/**\n * Delegate a task to multiple profiles in parallel.\n * Useful for: write + review, research + summarize, etc.\n */\nexport async function delegateParallel(\n tasks: Array<{ task: string; profile: string }>,\n client: LLMClient,\n mcpManager: McpManager,\n options: DelegateOptions = {},\n): Promise<DelegationResult[]> {\n return Promise.all(\n tasks.map(({ task, profile }) =>\n delegateTask(task, profile, client, mcpManager, { ...options, silent: true }),\n ),\n );\n}\n\n/**\n * Delegate a pipeline of tasks sequentially — each task receives the previous result.\n * Useful for: draft → review → polish pipelines.\n */\nexport async function delegatePipeline(\n steps: Array<{ profile: string; taskTemplate: string }>,\n initialInput: string,\n client: LLMClient,\n mcpManager: McpManager,\n options: DelegateOptions = {},\n): Promise<DelegationResult[]> {\n const results: DelegationResult[] = [];\n let previousResult = initialInput;\n\n for (const step of steps) {\n const task = step.taskTemplate.replace(\"{{input}}\", previousResult);\n\n if (!options.silent) {\n process.stdout.write(pc.dim(`\\n [delegating to ${step.profile}...]\\n`));\n }\n\n const result = await delegateTask(task, step.profile, client, mcpManager, {\n ...options,\n silent: true,\n });\n results.push(result);\n\n if (!result.success) break;\n previousResult = result.response;\n }\n\n return results;\n}\n","import pc from \"picocolors\";\nimport * as p from \"@clack/prompts\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport os from \"node:os\";\nimport type { McpManager } from \"./mcp/client.js\";\nimport type { LLMClient, Message } from \"./llm/types.js\";\nimport type { HooksConfig } from \"./config.js\";\nimport { log } from \"./logger.js\";\nimport {\n computePersonality,\n syncPersonalityToCore,\n formatWellbeingNudge,\n shouldFireNudge,\n} from \"./personality.js\";\nimport { memoryRecall, memoryContext, reminderCheck, memoryLog, isMemoryInitialized, memoryStore } from \"./memory.js\";\nimport { loadUserIdentity } from \"./user-identity.js\";\nimport { shouldAutoPostmortem, generatePostmortemReport, savePostmortem } from \"./postmortem.js\";\nimport {\n validateCandidate,\n writeSkillToFile,\n mergeSkillInFile,\n appendCrystallizationLog,\n appendRejection,\n loadRejectedNames,\n incrementSuggestionCount,\n loadSuggestionCounts,\n} from \"./crystallization.js\";\nimport type { ObservationSession } from \"./observation.js\";\nimport {\n loadUserModel,\n saveUserModel,\n createEmptyModel,\n aggregateSession,\n computeProfile,\n feedForward,\n type SessionSnapshot,\n type PersonalityOverrides,\n} from \"./user-model.js\";\n\nfunction getTimeContext(): string {\n const now = new Date();\n const hour = now.getHours();\n const days = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"];\n const day = days[now.getDay()];\n\n let period: string;\n if (hour < 6) period = \"late-night\";\n else if (hour < 12) period = \"morning\";\n else if (hour < 17) period = \"afternoon\";\n else if (hour < 21) period = \"evening\";\n else period = \"night\";\n\n const timeStr = now.toLocaleTimeString([], { hour: \"2-digit\", minute: \"2-digit\" });\n const dateStr = now.toLocaleDateString();\n\n return `<time-context>\\nCurrent time: ${dateStr} ${timeStr} (${period}, ${day})\\nAdapt your tone naturally — don't announce the time, just be contextually appropriate.\\n</time-context>`;\n}\n\nexport interface HookContext {\n mcpManager: McpManager;\n config: HooksConfig;\n llmClient?: LLMClient; // needed for auto-postmortem generation\n}\n\nlet isHookCall = false;\nlet sessionStartTime: number = Date.now();\n\nexport function getSessionStartTime(): number {\n return sessionStartTime;\n}\n\nexport async function onSessionStart(\n ctx: HookContext,\n): Promise<{ greeting?: string; contextInjection?: string; firstRun?: boolean; visibleReminders?: string[]; resumeTopic?: string }> {\n let greeting = \"\";\n let contextInjection = \"\";\n let firstRun = false;\n let resumeTopic: string | undefined;\n const visibleReminders: string[] = [];\n\n // Detect first run via memory_recall\n if (!isMemoryInitialized()) {\n // Memory system failed to init — skip memory operations but don't treat as first run\n firstRun = false;\n } else {\n try {\n isHookCall = true;\n const recallResult = await memoryRecall(\"*\", { limit: 1 });\n firstRun = recallResult.total === 0;\n } catch {\n firstRun = true;\n } finally {\n isHookCall = false;\n }\n }\n\n if (firstRun) {\n const userIdentity = loadUserIdentity();\n\n if (userIdentity) {\n // First run WITH user profile — personalized introduction\n contextInjection = `<first-session>\nThis is your FIRST conversation with ${userIdentity.name}. They just set up their profile:\n- Role: ${userIdentity.roleLabel}\n- Expertise: ${userIdentity.expertiseLabel}\n- Style preference: ${userIdentity.styleLabel}\n${userIdentity.workingOn ? `- Working on: ${userIdentity.workingOn}` : \"\"}\n${userIdentity.notes ? `- Notes: ${userIdentity.notes}` : \"\"}\n\nIntroduce yourself warmly:\n- Greet them by name\n- Acknowledge what they do and what they're working on (if provided)\n- Show you understand their style preference (e.g., if they want concise answers, keep it tight)\n- Mention you'll remember what matters across conversations\n- Keep it to 3-5 sentences, natural tone — make them feel like you GET them\n</first-session>`;\n } else {\n // First run WITHOUT user profile — generic introduction\n contextInjection = `<first-session>\nThis is your FIRST conversation with this user. Introduce yourself warmly:\n- Share your name and that you're their personal AI companion\n- Mention you'll remember what matters across conversations\n- Ask what they'd like to be called\n- Mention they can set up their profile with /profile edit for a more personalized experience\n- Keep it to 3-4 sentences, natural tone\n</first-session>`;\n }\n\n // Still add time context\n const timeContext = getTimeContext();\n contextInjection = `<session-context>\\n${timeContext}\\n</session-context>\\n${contextInjection}`;\n\n return {\n greeting: undefined,\n contextInjection,\n firstRun,\n visibleReminders,\n resumeTopic: undefined,\n };\n }\n\n // Returning user flow\n if (ctx.config.memoryRecall) {\n try {\n isHookCall = true;\n const contextResult = await memoryContext(\"session context\");\n if (contextResult.memoriesUsed > 0) {\n greeting += contextResult.text;\n }\n } catch (err) {\n log.warn(\"hooks\", \"memory_context recall failed\", err);\n } finally {\n isHookCall = false;\n }\n }\n\n if (ctx.config.sessionResume) {\n try {\n isHookCall = true;\n const result = await ctx.mcpManager.callTool(\"identity_summary\", {});\n if (result && !result.startsWith(\"Error\")) {\n if (greeting) greeting += \"\\n\";\n greeting += result;\n\n // Extract resume topic\n const topicMatch = result.match(/(?:resume|last|topic)[:\\s]*(.+?)(?:\\n|$)/i);\n if (topicMatch) {\n resumeTopic = topicMatch[1].trim();\n }\n }\n } catch (err) {\n log.warn(\"hooks\", \"identity_summary failed\", err);\n } finally {\n isHookCall = false;\n }\n }\n\n // Time context\n const timeContext = getTimeContext();\n if (greeting) greeting += \"\\n\" + timeContext;\n else greeting = timeContext;\n\n // Check reminders\n try {\n isHookCall = true;\n const reminders = reminderCheck();\n if (reminders.length > 0) {\n const reminderText = reminders.map(r => r.content).join(\"\\n\");\n greeting += \"\\n\\n<pending-reminders>\\n\" + reminderText + \"\\n</pending-reminders>\";\n for (const r of reminders) {\n visibleReminders.push(r.content);\n }\n }\n } catch (err) {\n log.debug(\"hooks\", \"reminder_check failed\", err);\n } finally {\n isHookCall = false;\n }\n\n // Compute initial personality state (with feed-forward from user model)\n if (ctx.config.personalityAdapt !== false) {\n sessionStartTime = Date.now();\n const hour = new Date().getHours();\n let period: string;\n if (hour < 6) period = \"late-night\";\n else if (hour < 12) period = \"morning\";\n else if (hour < 17) period = \"afternoon\";\n else if (hour < 21) period = \"evening\";\n else period = \"night\";\n\n const state = computePersonality({\n timePeriod: period,\n sessionMinutes: 0,\n turnCount: 0,\n });\n\n // Load user model for feed-forward overrides\n try {\n const model = await loadUserModel();\n if (model) {\n const overrides = feedForward(model);\n if (overrides) {\n log.debug(\"hooks\", `Feed-forward active (trust=${model.profile.trustScore.toFixed(2)}, sessions=${model.profile.totalSessions})`);\n\n // Apply energy override (e.g., night owls stay \"steady\" instead of \"reflective\")\n if (overrides.energyOverride && (period === \"late-night\" || period === \"night\")) {\n (state as { energy: string }).energy = overrides.energyOverride as typeof state.energy;\n }\n\n // Apply default-to-Personal-mode when sentiment is worsening\n if (overrides.defaultToPersonalMode && state.activeMode === \"Default\") {\n (state as { activeMode: string }).activeMode = \"Personal\";\n }\n\n // Inject trust context into greeting\n if (overrides.compactGreeting) {\n greeting += \"\\n<user-model-context>High trust user (score: \" +\n model.profile.trustScore.toFixed(2) +\n \", \" + model.profile.totalSessions +\n \" sessions). Keep greeting compact — they know you well.</user-model-context>\";\n }\n\n // Surface sentiment trend if concerning\n if (model.profile.sentimentTrend === \"worsening\") {\n greeting += \"\\n<user-model-context>Sentiment trend is worsening across recent sessions. Be more attentive and patient.</user-model-context>\";\n }\n }\n }\n } catch (err) {\n log.debug(\"hooks\", \"user model feed-forward failed\", err);\n }\n\n // Sync to acore (fire-and-forget)\n syncPersonalityToCore(state, ctx.mcpManager).catch(() => {});\n\n // Add wellbeing nudge to context if applicable (with adaptive filtering)\n const nudge = formatWellbeingNudge(state);\n if (nudge && state.wellbeingNudge) {\n let fireNudge = true;\n try {\n const model = await loadUserModel();\n if (model && model.sessions.length >= 5) {\n const profile = computeProfile(model.sessions, model.sessions.length);\n fireNudge = shouldFireNudge(state.wellbeingNudge, profile);\n }\n } catch {\n // No model yet — always fire\n }\n if (fireNudge) {\n greeting += \"\\n\" + nudge;\n }\n }\n }\n\n if (greeting) {\n contextInjection = `<session-context>\\n${greeting}\\n</session-context>`;\n }\n\n return {\n greeting: greeting || undefined,\n contextInjection: contextInjection || undefined,\n firstRun,\n visibleReminders,\n resumeTopic,\n };\n}\n\nexport async function onBeforeToolExec(\n toolName: string,\n toolArgs: Record<string, unknown>,\n ctx: HookContext,\n): Promise<{ allow: boolean; reason?: string }> {\n if (!ctx.config.rulesCheck || isHookCall) {\n return { allow: true };\n }\n\n if (toolName === \"rules_check\") {\n return { allow: true };\n }\n\n try {\n isHookCall = true;\n const description = `${toolName}(${JSON.stringify(toolArgs)})`;\n const result = await ctx.mcpManager.callTool(\"rules_check\", {\n action: description,\n });\n\n try {\n const parsed = JSON.parse(result) as {\n violations?: string[];\n };\n if (parsed.violations && parsed.violations.length > 0) {\n return {\n allow: false,\n reason: parsed.violations.join(\"; \"),\n };\n }\n } catch (err) {\n log.debug(\"hooks\", \"rules_check parse failed\", err);\n }\n\n return { allow: true };\n } catch (err) {\n log.warn(\"hooks\", \"rules_check call failed\", err);\n return { allow: true };\n } finally {\n isHookCall = false;\n }\n}\n\nexport async function onWorkflowMatch(\n userInput: string,\n ctx: HookContext,\n): Promise<{ name: string; steps: string } | null> {\n if (!ctx.config.workflowSuggest) {\n return null;\n }\n\n try {\n isHookCall = true;\n const result = await ctx.mcpManager.callTool(\"workflow_list\", {});\n\n const workflows = JSON.parse(result) as Array<{\n name: string;\n description?: string;\n steps?: string[];\n }>;\n\n const inputLower = userInput.toLowerCase();\n\n for (const wf of workflows) {\n const nameLower = wf.name.toLowerCase();\n\n // Check if user input contains workflow name\n if (inputLower.includes(nameLower)) {\n const steps = (wf.steps || [])\n .map((s, i) => `${i + 1}. ${s}`)\n .join(\"\\n\");\n return { name: wf.name, steps };\n }\n\n // Check significant words from description\n if (wf.description) {\n const words = wf.description\n .split(/\\s+/)\n .filter((w) => w.length > 4)\n .map((w) => w.toLowerCase());\n\n for (const word of words) {\n if (inputLower.includes(word)) {\n const steps = (wf.steps || [])\n .map((s, i) => `${i + 1}. ${s}`)\n .join(\"\\n\");\n return { name: wf.name, steps };\n }\n }\n }\n }\n\n return null;\n } catch (err) {\n log.debug(\"hooks\", \"workflow_list failed\", err);\n return null;\n } finally {\n isHookCall = false;\n }\n}\n\nexport async function onSessionEnd(\n ctx: HookContext,\n messages: Message[],\n sessionId: string,\n observationSession?: ObservationSession,\n): Promise<void> {\n try {\n // Auto-save conversation to amem memory_log\n if (ctx.config.autoSessionSave && messages.length > 2) {\n console.log(pc.dim(\"\\n Saving conversation to memory...\"));\n\n // Save last 50 text messages to memory_log\n const textMessages = messages\n .filter((m) => typeof m.content === \"string\")\n .slice(-50);\n\n for (const msg of textMessages) {\n try {\n isHookCall = true;\n memoryLog(sessionId, msg.role, (msg.content as string).slice(0, 5000));\n } catch (err) {\n log.debug(\"hooks\", \"memory_log write failed for \" + sessionId, err);\n } finally {\n isHookCall = false;\n }\n }\n\n // Update session resume in identity\n let lastUserMsg = \"\";\n for (let i = messages.length - 1; i >= 0; i--) {\n if (\n messages[i].role === \"user\" &&\n typeof messages[i].content === \"string\"\n ) {\n lastUserMsg = messages[i].content as string;\n break;\n }\n }\n\n if (lastUserMsg) {\n try {\n isHookCall = true;\n await ctx.mcpManager.callTool(\"identity_update_session\", {\n resume: lastUserMsg.slice(0, 200),\n topics: \"See conversation history\",\n decisions: \"See conversation history\",\n });\n } finally {\n isHookCall = false;\n }\n }\n\n console.log(pc.dim(` Saved ${textMessages.length} messages (session: ${sessionId})`));\n }\n\n // Update per-project .acore/context.md if it exists\n const projectContextPath = path.join(process.cwd(), \".acore\", \"context.md\");\n if (fs.existsSync(projectContextPath) && messages.length > 2) {\n try {\n let contextContent = fs.readFileSync(projectContextPath, \"utf-8\");\n const now = new Date().toISOString().split(\"T\")[0];\n\n // Extract last user message for resume\n let lastUserMsg = \"\";\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i].role === \"user\" && typeof messages[i].content === \"string\") {\n lastUserMsg = (messages[i].content as string).slice(0, 200);\n break;\n }\n }\n\n // Update Session section in context.md\n const sessionPattern = /## Session\\n[\\s\\S]*?(?=\\n## |$)/;\n if (sessionPattern.test(contextContent)) {\n const newSession = `## Session\\n- Last updated: ${now}\\n- Resume: ${lastUserMsg || \"See conversation history\"}\\n- Active topics: [see memory]\\n- Recent decisions: [see memory]\\n- Temp notes: [cleared]`;\n contextContent = contextContent.replace(sessionPattern, newSession);\n fs.writeFileSync(projectContextPath, contextContent, \"utf-8\");\n log.debug(\"hooks\", `Updated project context: ${projectContextPath}`);\n }\n } catch (err) {\n log.debug(\"hooks\", \"project context update failed\", err);\n }\n }\n\n // Persist final personality state\n const sessionMinutes = Math.round((Date.now() - sessionStartTime) / 60000);\n const hour = new Date().getHours();\n let period: string;\n if (hour < 6) period = \"late-night\";\n else if (hour < 12) period = \"morning\";\n else if (hour < 17) period = \"afternoon\";\n else if (hour < 21) period = \"evening\";\n else period = \"night\";\n\n const turnCount = messages.filter((m) => m.role === \"user\").length;\n const finalState = computePersonality({\n timePeriod: period,\n sessionMinutes,\n turnCount,\n });\n\n if (ctx.config.personalityAdapt !== false) {\n try {\n isHookCall = true;\n await syncPersonalityToCore(finalState, ctx.mcpManager);\n } finally {\n isHookCall = false;\n }\n }\n\n // Session rating prompt\n let sessionRating: string | undefined;\n if (ctx.config.evalPrompt) {\n const rating = await p.select({\n message: \"Quick rating for this session?\",\n options: [\n { value: \"great\", label: \"Great\" },\n { value: \"good\", label: \"Good\" },\n { value: \"okay\", label: \"Okay\" },\n { value: \"skip\", label: \"Skip\" },\n ],\n initialValue: \"skip\",\n });\n\n if (!p.isCancel(rating) && rating !== \"skip\") {\n sessionRating = rating as string;\n try {\n isHookCall = true;\n await ctx.mcpManager.callTool(\"eval_log\", {\n rating: sessionRating,\n highlights: \"Quick session rating\",\n improvements: \"\",\n });\n } finally {\n isHookCall = false;\n }\n }\n }\n\n // Aggregate session into user model (v0.27)\n if (turnCount >= 2 && sessionMinutes >= 1) {\n try {\n const snapshot: SessionSnapshot = {\n sessionId,\n date: new Date().toISOString().split(\"T\")[0],\n durationMinutes: sessionMinutes,\n turnCount,\n dominantSentiment: finalState.sentiment.dominant,\n avgFrustration: finalState.sentiment.frustration,\n avgExcitement: finalState.sentiment.excitement,\n avgConfusion: finalState.sentiment.confusion,\n avgFatigue: finalState.sentiment.fatigue,\n toolCalls: observationSession?.stats.toolCalls ?? 0,\n toolErrors: observationSession?.stats.toolErrors ?? 0,\n blockers: observationSession?.stats.blockers ?? 0,\n milestones: observationSession?.stats.milestones ?? 0,\n topicShifts: observationSession?.stats.topicShifts ?? 0,\n peakEnergy: finalState.energy,\n primaryMode: finalState.activeMode,\n timePeriod: period,\n rating: sessionRating,\n hadPostmortem: false, // updated below if postmortem is generated\n wellbeingNudges: finalState.wellbeingNudge ? [finalState.wellbeingNudge] : [],\n };\n\n const model = (await loadUserModel()) ?? createEmptyModel();\n const updated = aggregateSession(model, snapshot);\n await saveUserModel(updated);\n log.debug(\"hooks\", `User model updated (session ${updated.profile.totalSessions})`);\n\n // Sync model metrics to acore dynamics section\n if (ctx.config.personalityAdapt !== false) {\n try {\n isHookCall = true;\n await syncPersonalityToCore(finalState, ctx.mcpManager, {\n trustScore: updated.profile.trustScore,\n totalSessions: updated.profile.totalSessions,\n sentimentTrend: updated.profile.sentimentTrend,\n });\n } finally {\n isHookCall = false;\n }\n }\n } catch (err) {\n log.debug(\"hooks\", \"user model aggregation failed\", err);\n }\n }\n\n // Auto post-mortem (smart trigger)\n if (\n ctx.config.autoPostmortem !== false &&\n observationSession &&\n shouldAutoPostmortem(observationSession, messages)\n ) {\n try {\n const client = ctx.llmClient;\n if (client) {\n // Load rejected skill names for feedback loop\n const rejectionsPath = path.join(\n os.homedir(),\n \".aman-agent\",\n \"crystallization-rejections.json\",\n );\n const rejectedNames = await loadRejectedNames(rejectionsPath);\n\n const report = await generatePostmortemReport(\n sessionId,\n messages,\n observationSession,\n client,\n undefined,\n rejectedNames,\n );\n if (report) {\n const filePath = await savePostmortem(report);\n console.log(pc.dim(`\\n Post-mortem saved → ${filePath}`));\n\n // Store actionable patterns as memories\n for (const pattern of report.patterns) {\n try {\n await memoryStore({\n content: pattern,\n type: \"pattern\",\n tags: [\"postmortem\", \"auto\"],\n confidence: 0.7,\n });\n } catch {\n // Silent — don't block exit\n }\n }\n\n // Crystallization prompt loop (v0.26 + v0.28 reinforcement)\n if (\n report.crystallizationCandidates &&\n report.crystallizationCandidates.length > 0\n ) {\n const skillsMdPath = path.join(os.homedir(), \".askill\", \"skills.md\");\n const logPath = path.join(\n os.homedir(),\n \".aman-agent\",\n \"crystallization-log.json\",\n );\n const rejectionsPath2 = path.join(\n os.homedir(),\n \".aman-agent\",\n \"crystallization-rejections.json\",\n );\n const suggestionsPath = path.join(\n os.homedir(),\n \".aman-agent\",\n \"crystallization-suggestions.json\",\n );\n const postmortemFilename = `${report.date}-${report.sessionId.slice(0, 4)}.md`;\n\n console.log(\n pc.dim(`\\n Crystallization candidates: ${report.crystallizationCandidates.length}`),\n );\n\n let skipAll = false;\n for (const rawCandidate of report.crystallizationCandidates) {\n if (skipAll) break;\n const candidate = validateCandidate(rawCandidate);\n if (!candidate) {\n log.debug(\"hooks\", \"candidate failed validation\");\n continue;\n }\n\n // Track suggestion count for reinforcement\n const suggestCount = await incrementSuggestionCount(candidate.name, suggestionsPath);\n const reinforced = suggestCount >= 3;\n\n const message = reinforced\n ? `Crystallize \"${candidate.name}\"? (suggested ${suggestCount}× across sessions — high confidence)`\n : `Crystallize \"${candidate.name}\" as a reusable skill?`;\n\n const choice = await p.select({\n message,\n options: [\n { value: \"accept\", label: reinforced ? \"Yes — recommended (seen multiple times)\" : \"Yes — write to ~/.askill/skills.md\" },\n { value: \"reject\", label: \"No — skip this one\" },\n { value: \"skip-all\", label: \"Skip all crystallization for this session\" },\n ],\n initialValue: reinforced ? \"accept\" : \"reject\",\n });\n\n if (p.isCancel(choice) || choice === \"skip-all\") {\n skipAll = true;\n break;\n }\n\n if (choice === \"accept\") {\n const result = await writeSkillToFile(\n candidate,\n skillsMdPath,\n postmortemFilename,\n );\n if (result.written) {\n console.log(\n pc.green(` ✓ Crystallized: ${candidate.name} → ${result.filePath}`),\n );\n console.log(pc.dim(` Triggers: ${candidate.triggers.join(\", \")}`));\n console.log(pc.dim(` Will auto-activate next session.`));\n await appendCrystallizationLog(\n {\n name: candidate.name,\n createdAt: new Date().toISOString(),\n fromPostmortem: postmortemFilename,\n confidence: candidate.confidence,\n triggers: candidate.triggers,\n },\n logPath,\n );\n } else if (result.collidesWith) {\n // Collision detected — offer merge\n const mergeChoice = await p.select({\n message: `\"${candidate.name}\" collides with existing \"${result.collidesWith}\". Merge?`,\n options: [\n { value: \"merge\", label: `Yes — replace \"${result.collidesWith}\" with updated version` },\n { value: \"skip\", label: \"No — keep existing\" },\n ],\n initialValue: \"merge\",\n });\n\n if (!p.isCancel(mergeChoice) && mergeChoice === \"merge\") {\n const mergeResult = await mergeSkillInFile(\n candidate,\n result.collidesWith,\n skillsMdPath,\n postmortemFilename,\n );\n if (mergeResult.written) {\n console.log(pc.green(` ✓ Merged: ${candidate.name} (replaced \"${result.collidesWith}\")`));\n await appendCrystallizationLog(\n {\n name: candidate.name,\n createdAt: new Date().toISOString(),\n fromPostmortem: postmortemFilename,\n confidence: candidate.confidence,\n triggers: candidate.triggers,\n },\n logPath,\n );\n } else {\n console.log(pc.yellow(` ⊘ Merge failed: ${mergeResult.reason}`));\n }\n } else {\n console.log(pc.dim(` Kept existing: ${result.collidesWith}`));\n }\n } else {\n console.log(pc.yellow(` ⊘ Could not crystallize: ${result.reason}`));\n }\n } else {\n console.log(pc.dim(` Skipped: ${candidate.name}`));\n await appendRejection(candidate, postmortemFilename, rejectionsPath2);\n }\n }\n }\n }\n }\n } catch (err) {\n log.debug(\"hooks\", \"auto post-mortem failed\", err);\n }\n }\n } catch (err) {\n log.warn(\"hooks\", \"session end hook failed\", err);\n }\n}\n","import type { McpManager } from \"./mcp/client.js\";\nimport type { UserProfile } from \"./user-model.js\";\nimport { log } from \"./logger.js\";\n\nexport interface PersonalityState {\n currentRead: string;\n energy: \"high-drive\" | \"steady\" | \"reflective\";\n activeMode: \"Default\" | \"Focused Work\" | \"Creative\" | \"Personal\";\n sleepReminder: boolean;\n wellbeingNudge: string | null;\n sentiment: SentimentRead;\n}\n\nexport interface SentimentRead {\n frustration: number; // 0-1\n excitement: number; // 0-1\n confusion: number; // 0-1\n fatigue: number; // 0-1\n dominant: \"neutral\" | \"frustrated\" | \"excited\" | \"confused\" | \"fatigued\";\n}\n\nexport interface PersonalitySignals {\n timePeriod: string;\n sessionMinutes: number;\n turnCount: number;\n recentMessages?: string[]; // last N user messages for sentiment analysis\n}\n\n// --- Sentiment Detection (keyword-based, zero latency) ---\n\nconst FRUSTRATION_SIGNALS = [\n /\\b(ugh|argh|damn|dammit|wtf|ffs|shit|fuck|crap|hate this|stupid|broken|still not|doesn't work|not working|won't work|keeps failing|again\\?!|what the hell|for the love of|give up|giving up|fed up)\\b/i,\n /\\b(why (is|does|won't|can't|isn't)|same (error|issue|problem|bug)|tried everything|nothing works|no idea|lost|stuck|frustrated|annoying|impossible)\\b/i,\n /!{2,}/, // multiple exclamation marks\n /\\?{2,}/, // multiple question marks (exasperation)\n];\n\nconst EXCITEMENT_SIGNALS = [\n /\\b(amazing|awesome|perfect|brilliant|love it|yes!|nice!|great!|finally|it works|nailed it|beautiful|incredible|exactly|that's it|hell yeah|wow|woah|let's go)\\b/i,\n /\\b(excited|pumped|stoked|can't wait|this is great|so cool|love this)\\b/i,\n /!{1,}.*(!|🎉|🚀|✨|💪|🔥)/,\n];\n\nconst CONFUSION_SIGNALS = [\n /\\b(confused|don't understand|what do you mean|huh\\??|makes no sense|i'm lost|unclear|what\\?|how does that|wait what|can you explain|i don't get)\\b/i,\n /\\b(which one|what's the difference|should i|not sure (if|what|how|why|whether))\\b/i,\n];\n\nconst FATIGUE_SIGNALS = [\n /\\b(tired|exhausted|long day|need (a )?break|calling it|wrapping up|done for (now|today)|heading (to bed|off)|good night|gn|signing off|one more thing then|last one)\\b/i,\n /\\b(brain (is )?fried|can't think|eyes (are )?heavy|running on fumes|barely awake)\\b/i,\n];\n\nfunction scorePatterns(text: string, patterns: RegExp[]): number {\n let hits = 0;\n for (const p of patterns) {\n if (p.test(text)) hits++;\n }\n return Math.min(hits / patterns.length, 1);\n}\n\n/**\n * Detect sentiment from recent user messages.\n * Lightweight keyword-based analysis — no LLM calls.\n */\nexport function detectSentiment(recentMessages: string[]): SentimentRead {\n if (recentMessages.length === 0) {\n return { frustration: 0, excitement: 0, confusion: 0, fatigue: 0, dominant: \"neutral\" };\n }\n\n // Weight recent messages more heavily (last message = 1.0, second-last = 0.6, third = 0.3)\n const weights = [1.0, 0.6, 0.3, 0.2, 0.1];\n let frustration = 0, excitement = 0, confusion = 0, fatigue = 0;\n let totalWeight = 0;\n\n for (let i = 0; i < Math.min(recentMessages.length, weights.length); i++) {\n const msg = recentMessages[recentMessages.length - 1 - i];\n const w = weights[i];\n totalWeight += w;\n\n frustration += scorePatterns(msg, FRUSTRATION_SIGNALS) * w;\n excitement += scorePatterns(msg, EXCITEMENT_SIGNALS) * w;\n confusion += scorePatterns(msg, CONFUSION_SIGNALS) * w;\n fatigue += scorePatterns(msg, FATIGUE_SIGNALS) * w;\n }\n\n if (totalWeight > 0) {\n frustration /= totalWeight;\n excitement /= totalWeight;\n confusion /= totalWeight;\n fatigue /= totalWeight;\n }\n\n // Determine dominant sentiment\n const scores = { frustrated: frustration, excited: excitement, confused: confusion, fatigued: fatigue };\n const maxKey = Object.entries(scores).reduce((a, b) => a[1] > b[1] ? a : b);\n const dominant = maxKey[1] > 0.15 ? maxKey[0] as SentimentRead[\"dominant\"] : \"neutral\";\n\n return { frustration, excitement, confusion, fatigue, dominant };\n}\n\n// --- Personality Computation ---\n\n/**\n * Compute personality state from current signals including sentiment.\n * Pure function — no side effects.\n */\nexport function computePersonality(signals: PersonalitySignals): PersonalityState {\n const { timePeriod, sessionMinutes, turnCount, recentMessages } = signals;\n\n // Detect sentiment from recent messages\n const sentiment = detectSentiment(recentMessages || []);\n\n // Energy curve: time + session + sentiment\n let energy: PersonalityState[\"energy\"] = \"steady\";\n if (timePeriod === \"morning\" && sentiment.dominant !== \"fatigued\") {\n energy = \"high-drive\";\n } else if (timePeriod === \"late-night\" || (timePeriod === \"night\" && sessionMinutes > 45)) {\n energy = \"reflective\";\n } else if (sentiment.dominant === \"fatigued\") {\n energy = \"reflective\";\n } else if (sentiment.dominant === \"excited\") {\n energy = \"high-drive\"; // match their energy\n } else if (timePeriod === \"afternoon\" && turnCount > 20) {\n energy = \"reflective\";\n }\n\n // Active mode: time + sentiment\n let activeMode: PersonalityState[\"activeMode\"] = \"Default\";\n if (timePeriod === \"late-night\") {\n activeMode = \"Personal\";\n } else if (sentiment.dominant === \"frustrated\" || sentiment.dominant === \"fatigued\") {\n activeMode = \"Personal\"; // warm, patient when they're struggling\n }\n\n // Current read: combines time context + sentiment\n const readParts: string[] = [];\n\n // Time-based read\n switch (timePeriod) {\n case \"late-night\":\n readParts.push(\"late night session\");\n if (sessionMinutes > 60) readParts.push(\"been going a while\");\n else readParts.push(\"quiet hours\");\n break;\n case \"morning\":\n readParts.push(\"morning session\");\n if (turnCount <= 3) readParts.push(\"just getting started\");\n else readParts.push(\"building momentum\");\n break;\n case \"afternoon\":\n readParts.push(\"afternoon session\");\n if (turnCount > 15) readParts.push(\"deep in flow\");\n else readParts.push(\"steady pace\");\n break;\n case \"evening\":\n readParts.push(\"evening session\");\n if (sessionMinutes > 60) readParts.push(\"long session\");\n break;\n case \"night\":\n readParts.push(\"night session\");\n if (sessionMinutes > 45) readParts.push(\"getting late\");\n break;\n }\n\n // Sentiment-based read\n switch (sentiment.dominant) {\n case \"frustrated\":\n readParts.push(\"user seems stuck or frustrated\");\n break;\n case \"excited\":\n readParts.push(\"user is energized and making progress\");\n break;\n case \"confused\":\n readParts.push(\"user may need clearer explanations\");\n break;\n case \"fatigued\":\n readParts.push(\"user seems tired\");\n break;\n }\n\n const currentRead = readParts.join(\", \");\n\n // Sleep guardian\n const sleepReminder =\n (timePeriod === \"late-night\" && sessionMinutes > 60) ||\n (timePeriod === \"night\" && sessionMinutes > 90);\n\n // Wellbeing nudges (beyond sleep)\n let wellbeingNudge: string | null = null;\n\n if (sleepReminder && sentiment.dominant === \"frustrated\") {\n wellbeingNudge = \"sleep-frustrated\";\n } else if (sleepReminder) {\n wellbeingNudge = \"sleep\";\n } else if (sentiment.dominant === \"frustrated\" && sessionMinutes > 90) {\n wellbeingNudge = \"break-frustrated\";\n } else if (sentiment.dominant === \"frustrated\" && turnCount > 15) {\n wellbeingNudge = \"step-back\";\n } else if (sentiment.dominant === \"fatigued\") {\n wellbeingNudge = \"rest\";\n } else if (sessionMinutes > 120) {\n wellbeingNudge = \"break-long-session\";\n }\n\n return { currentRead, energy, activeMode, sleepReminder, wellbeingNudge, sentiment };\n}\n\n// --- Wellbeing Nudge Formatting ---\n\nconst WELLBEING_NUDGES: Record<string, string> = {\n \"sleep\": `<wellbeing>\nIt's late and this session has been running a while. When there's a natural pause, gently mention they might want to wrap up soon. One brief mention is enough — don't be pushy.\n</wellbeing>`,\n\n \"sleep-frustrated\": `<wellbeing>\nIt's late, the session has been long, and the user seems frustrated. This is a tough combination. Acknowledge what they're dealing with is hard, suggest they sleep on it — fresh eyes in the morning often solve what hours of late-night debugging can't. Be warm, not condescending.\n</wellbeing>`,\n\n \"break-frustrated\": `<wellbeing>\nThe user has been at this for over 90 minutes and seems frustrated. If the conversation allows, gently suggest stepping away for a few minutes — a short break often unblocks what persistence can't. Frame it as a strategy, not giving up.\n</wellbeing>`,\n\n \"step-back\": `<wellbeing>\nThe user seems stuck or frustrated. Consider: offer to re-approach the problem from a different angle, break it into smaller pieces, or explain the underlying concept. Match their directness — don't over-soothe, just help them find a way forward.\n</wellbeing>`,\n\n \"rest\": `<wellbeing>\nThe user seems tired. Keep responses concise and to the point. If they mention wrapping up, support that. Don't add extra complexity or tangents.\n</wellbeing>`,\n\n \"break-long-session\": `<wellbeing>\nThis session has been running for over 2 hours. If there's a natural moment, a brief mention that a short break might help maintain focus is fine. Once is enough.\n</wellbeing>`,\n\n \"burnout-warning\": `<wellbeing>\nRecent patterns suggest the user may be approaching burnout — rising frustration, declining satisfaction, long or late sessions. Be extra mindful: keep responses concise, celebrate small wins, gently suggest breaks or scope reduction. Don't mention burnout directly unless they bring it up.\n</wellbeing>`,\n};\n\n/**\n * Format the appropriate wellbeing nudge for the current state.\n */\nexport function formatWellbeingNudge(state: PersonalityState): string | null {\n if (!state.wellbeingNudge) return null;\n return WELLBEING_NUDGES[state.wellbeingNudge] || null;\n}\n\n/**\n * Check whether a nudge should fire based on user model nudge stats.\n * If a nudge type has been fired 5+ times with avg rating below 0.4 (on 0-1 scale),\n * suppress it (return false). Otherwise allow (return true).\n * If no profile provided, always allows.\n */\nexport function shouldFireNudge(nudgeType: string, profile?: UserProfile): boolean {\n if (!profile) return true;\n\n const stats = profile.nudgeStats[nudgeType];\n if (!stats || stats.fired < 5) return true;\n\n // sessionRatingAfter is avg on 0-1 scale (0=frustrating, 1=great)\n // If avg rating after nudge is < 0.4, this nudge is hurting more than helping\n if (stats.sessionRatingAfter < 0.4) {\n log.debug(\"personality\", `suppressing nudge \"${nudgeType}\" — low avg rating ${stats.sessionRatingAfter.toFixed(2)} after ${stats.fired} fires`);\n return false;\n }\n\n return true;\n}\n\n/**\n * Push current personality state to acore via identity_update_dynamics.\n * Optionally includes user model metrics (trust, sessions, sentiment trend).\n * Fire-and-forget — failures are logged but don't block.\n */\nexport async function syncPersonalityToCore(\n state: PersonalityState,\n mcpManager: McpManager,\n modelMetrics?: { trustScore: number; totalSessions: number; sentimentTrend: string },\n): Promise<void> {\n try {\n const payload: Record<string, unknown> = {\n currentRead: state.currentRead,\n energy: state.energy,\n activeMode: state.activeMode,\n };\n if (modelMetrics) {\n payload.trust = `${(modelMetrics.trustScore * 100).toFixed(0)}%`;\n payload.sessions = modelMetrics.totalSessions;\n payload.sentimentTrend = modelMetrics.sentimentTrend;\n }\n await mcpManager.callTool(\"identity_update_dynamics\", payload);\n } catch (err) {\n log.debug(\"personality\", \"identity_update_dynamics failed\", err);\n }\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport os from \"node:os\";\nimport { readObservationEvents, type ObservationSession } from \"./observation.js\";\nimport type { LLMClient, Message } from \"./llm/types.js\";\nimport { log } from \"./logger.js\";\nimport type { SkillCandidate } from \"./crystallization.js\";\n\n// ── Types ──\n\nexport interface PostmortemReport {\n sessionId: string;\n date: string;\n duration: number;\n turnCount: number;\n summary: string;\n goals: string[];\n completed: string[];\n blockers: string[];\n decisions: string[];\n toolUsage: { name: string; count: number; errorRate: number }[];\n fileChanges: string[];\n topicProgression: string[];\n sentimentArc: string;\n patterns: string[];\n recommendations: string[];\n crystallizationCandidates?: SkillCandidate[];\n}\n\n// ── Default directories ──\n\nexport function defaultPostmortemsDir(): string {\n return path.join(os.homedir(), \".acore\", \"postmortems\");\n}\n\nfunction defaultObservationsDir(): string {\n return path.join(os.homedir(), \".acore\", \"observations\");\n}\n\n// ── Smart trigger ──\n\nexport function shouldAutoPostmortem(\n session: ObservationSession,\n messages: Message[],\n): boolean {\n if (messages.length < 6) return false;\n\n const durationMs = Date.now() - session.startedAt;\n return (\n session.stats.toolErrors >= 3 ||\n session.stats.blockers >= 2 ||\n durationMs > 60 * 60_000 ||\n hasAbandonedPlanSteps(messages) ||\n hasSustainedFrustration(session, 5)\n );\n}\n\nfunction hasAbandonedPlanSteps(messages: Message[]): boolean {\n // Check if any message mentions incomplete plan steps (e.g., /plan output with unchecked items)\n const text = messages\n .map((m) => (typeof m.content === \"string\" ? m.content : \"\"))\n .join(\"\\n\");\n const unchecked = (text.match(/- \\[ \\]/g) ?? []).length;\n const checked = (text.match(/- \\[x\\]/g) ?? []).length;\n // If there are plan steps and some are unchecked, the plan was abandoned\n return checked > 0 && unchecked > 0 && unchecked >= checked;\n}\n\nfunction hasSustainedFrustration(session: ObservationSession, threshold: number): boolean {\n // Use stats counter — events may have been flushed to disk\n return session.stats.blockers >= threshold;\n}\n\n// ── Helper: extract text from message content ──\n\nfunction messageContentToText(content: Message[\"content\"]): string {\n if (typeof content === \"string\") return content;\n return content\n .filter((b) => b.type === \"text\")\n .map((b) => (\"text\" in b ? b.text : \"\"))\n .join(\"\");\n}\n\n// ── Report generation ──\n\nconst POSTMORTEM_PROMPT = `Analyze this session and generate a structured post-mortem report.\nReturn ONLY valid JSON matching this schema (no markdown, no explanation):\n\n{\n \"summary\": \"2-3 sentence overview\",\n \"goals\": [\"what the user tried to accomplish\"],\n \"completed\": [\"what actually got done\"],\n \"blockers\": [\"what caused friction\"],\n \"decisions\": [\"key choices made with rationale\"],\n \"sentimentArc\": \"how mood evolved during session\",\n \"patterns\": [\"recurring behaviors worth remembering for future sessions\"],\n \"recommendations\": [\"actionable suggestions for next session\"],\n \"crystallizationCandidates\": [\n {\n \"name\": \"lowercase-kebab-name\",\n \"description\": \"1-sentence description of when this would be useful\",\n \"triggers\": [\"3-8\", \"trigger\", \"keywords\"],\n \"approach\": \"1-paragraph context: when and why to use this procedure\",\n \"steps\": [\"ordered step 1\", \"ordered step 2\"],\n \"gotchas\": [\"common mistake 1\"],\n \"confidence\": 0.0\n }\n ]\n}\n\nCRYSTALLIZATION RULES:\n- Only suggest 0-2 candidates per session — if nothing qualifies, return an empty array\n- Only suggest REUSABLE procedures (not one-off tasks specific to today's work)\n- The user must have demonstrated the procedure in this session\n- Confidence < 0.6 → don't suggest at all\n- Skip vague things like \"use library X\" — that's not procedural knowledge\n- Prefer narrow specific procedures over broad generalizations\n- Trigger keywords should be highly specific (avoid generic words like \"code\", \"fix\", \"the\")`;\n\nexport async function generatePostmortemReport(\n sessionId: string,\n messages: Message[],\n session: ObservationSession,\n client: LLMClient,\n obsDir?: string,\n rejectedSkillNames?: string[],\n): Promise<PostmortemReport | null> {\n try {\n const events = await readObservationEvents(sessionId, obsDir ?? defaultObservationsDir());\n\n // Compute tool usage from events\n const toolMap = new Map<string, { calls: number; errors: number }>();\n const fileChanges: string[] = [];\n const topicProgression: string[] = [];\n\n for (const event of events) {\n if (event.type === \"tool_call\") {\n const name = (event.data.tool as string) ?? \"unknown\";\n const entry = toolMap.get(name) ?? { calls: 0, errors: 0 };\n entry.calls++;\n toolMap.set(name, entry);\n } else if (event.type === \"tool_error\") {\n const name = (event.data.tool as string) ?? \"unknown\";\n const entry = toolMap.get(name) ?? { calls: 0, errors: 0 };\n entry.errors++;\n toolMap.set(name, entry);\n } else if (event.type === \"file_change\") {\n const p = (event.data.path as string) ?? \"unknown\";\n if (!fileChanges.includes(p)) fileChanges.push(p);\n } else if (event.type === \"topic_shift\") {\n const topics = (event.data.newTopics as string[]) ?? [];\n topicProgression.push(...topics);\n }\n }\n\n const toolUsage = [...toolMap.entries()].map(([name, { calls, errors }]) => ({\n name,\n count: calls,\n errorRate: calls > 0 ? Math.round((errors / calls) * 100) / 100 : 0,\n }));\n\n // Build LLM prompt with capped context\n const recentMessages = messages.slice(-20).map((m) => {\n const text = messageContentToText(m.content);\n return `${m.role}: ${text.slice(0, 200)}`;\n });\n const obsSnapshot = events.slice(-30).map((e) => `[${e.type}] ${e.summary}`);\n\n const durationMin = Math.round((Date.now() - session.startedAt) / 60_000);\n\n const prompt = `${POSTMORTEM_PROMPT}${\n rejectedSkillNames && rejectedSkillNames.length > 0\n ? `\\n\\nPREVIOUSLY REJECTED SKILLS (do NOT suggest these again):\\n${rejectedSkillNames.map((n) => `- ${n}`).join(\"\\n\")}`\n : \"\"\n }\n\nSession ID: ${sessionId}\nDuration: ${durationMin} minutes\nTurns: ${messages.length}\nTool calls: ${session.stats.toolCalls} (${session.stats.toolErrors} errors)\nBlockers: ${session.stats.blockers}\nMilestones: ${session.stats.milestones}\n\nRecent messages:\n${recentMessages.join(\"\\n\")}\n\nObservations:\n${obsSnapshot.join(\"\\n\")}`;\n\n const response = await client.chat(\n \"You are a session analyst. Output only valid JSON.\",\n [{ role: \"user\", content: prompt }],\n () => {}, // no-op onChunk — postmortem runs silently\n );\n\n const text = messageContentToText(response.message.content);\n const jsonMatch = text.match(/\\{[\\s\\S]*\\}/);\n if (!jsonMatch) {\n log.debug(\"postmortem\", \"LLM returned non-JSON response\");\n return null;\n }\n\n const parsed = JSON.parse(jsonMatch[0]);\n\n return {\n sessionId,\n date: new Date().toISOString().slice(0, 10),\n duration: durationMin,\n turnCount: messages.length,\n summary: parsed.summary ?? \"\",\n goals: parsed.goals ?? [],\n completed: parsed.completed ?? [],\n blockers: parsed.blockers ?? [],\n decisions: parsed.decisions ?? [],\n toolUsage,\n fileChanges,\n topicProgression: [...new Set(topicProgression)],\n sentimentArc: parsed.sentimentArc ?? \"\",\n patterns: parsed.patterns ?? [],\n recommendations: parsed.recommendations ?? [],\n crystallizationCandidates: Array.isArray(parsed.crystallizationCandidates)\n ? parsed.crystallizationCandidates\n : undefined,\n };\n } catch (err) {\n log.debug(\"postmortem\", \"Failed to generate post-mortem\", err);\n return null;\n }\n}\n\n// ── Markdown formatting ──\n\nexport function formatPostmortemMarkdown(report: PostmortemReport): string {\n const lines: string[] = [\n `# Post-Mortem: ${report.date}`,\n \"\",\n `**Session:** ${report.sessionId} | **Duration:** ${report.duration} min | **Turns:** ${report.turnCount}`,\n \"\",\n \"## Summary\",\n report.summary,\n \"\",\n ];\n\n if (report.goals.length > 0) {\n lines.push(\"## Goals\");\n report.goals.forEach((g) => lines.push(`- ${g}`));\n lines.push(\"\");\n }\n\n if (report.completed.length > 0) {\n lines.push(\"## Completed\");\n report.completed.forEach((c) => lines.push(`- [x] ${c}`));\n lines.push(\"\");\n }\n\n if (report.blockers.length > 0) {\n lines.push(\"## Blockers\");\n report.blockers.forEach((b) => lines.push(`- ${b}`));\n lines.push(\"\");\n }\n\n if (report.decisions.length > 0) {\n lines.push(\"## Decisions\");\n report.decisions.forEach((d) => lines.push(`- ${d}`));\n lines.push(\"\");\n }\n\n if (report.toolUsage.length > 0) {\n lines.push(\"## Tool Usage\");\n lines.push(\"| Tool | Calls | Error Rate |\");\n lines.push(\"|------|-------|------------|\");\n report.toolUsage.forEach((t) =>\n lines.push(`| ${t.name} | ${t.count} | ${Math.round(t.errorRate * 100)}% |`),\n );\n lines.push(\"\");\n }\n\n if (report.fileChanges.length > 0) {\n lines.push(\"## Files Changed\");\n report.fileChanges.forEach((f) => lines.push(`- \\`${f}\\``));\n lines.push(\"\");\n }\n\n if (report.topicProgression.length > 0) {\n lines.push(`## Topics`);\n lines.push(report.topicProgression.join(\" → \"));\n lines.push(\"\");\n }\n\n if (report.sentimentArc) {\n lines.push(\"## Sentiment Arc\");\n lines.push(report.sentimentArc);\n lines.push(\"\");\n }\n\n if (report.patterns.length > 0) {\n lines.push(\"## Patterns\");\n report.patterns.forEach((p) => lines.push(`- ${p}`));\n lines.push(\"\");\n }\n\n if (report.recommendations.length > 0) {\n lines.push(\"## Recommendations\");\n report.recommendations.forEach((r) => lines.push(`- ${r}`));\n lines.push(\"\");\n }\n\n if (\n report.crystallizationCandidates &&\n report.crystallizationCandidates.length > 0\n ) {\n lines.push(\"## Crystallization Candidates\");\n report.crystallizationCandidates.forEach((c) => {\n lines.push(`- **${c.name}** (confidence ${c.confidence})`);\n lines.push(` ${c.description}`);\n });\n lines.push(\"\");\n }\n\n return lines.join(\"\\n\");\n}\n\n// ── Save & read post-mortems ──\n\nexport async function savePostmortem(\n report: PostmortemReport,\n dir?: string,\n): Promise<string> {\n const pmDir = dir ?? defaultPostmortemsDir();\n await fs.mkdir(pmDir, { recursive: true });\n\n const shortId = report.sessionId.slice(0, 4);\n const fileName = `${report.date}-${shortId}.md`;\n const filePath = path.join(pmDir, fileName);\n\n const markdown = formatPostmortemMarkdown(report);\n await fs.writeFile(filePath, markdown, \"utf-8\");\n\n // Also write a JSON sidecar for lossless re-parsing\n const jsonPath = filePath.replace(/\\.md$/, \".json\");\n try {\n await fs.writeFile(jsonPath, JSON.stringify(report, null, 2), \"utf-8\");\n } catch (err) {\n log.debug(\"postmortem\", \"JSON sidecar write failed\", err);\n }\n\n return filePath;\n}\n\nexport async function listPostmortems(dir?: string): Promise<string[]> {\n const pmDir = dir ?? defaultPostmortemsDir();\n try {\n const files = await fs.readdir(pmDir);\n return files\n .filter((f) => f.endsWith(\".md\"))\n .sort()\n .reverse();\n } catch {\n return [];\n }\n}\n\nexport async function readPostmortem(\n name: string,\n dir?: string,\n): Promise<string | null> {\n const pmDir = dir ?? defaultPostmortemsDir();\n const fileName = name.endsWith(\".md\") ? name : `${name}.md`;\n try {\n return await fs.readFile(path.join(pmDir, fileName), \"utf-8\");\n } catch {\n return null;\n }\n}\n\nexport async function analyzePostmortemRange(\n sinceDays: number,\n client: LLMClient,\n dir?: string,\n): Promise<string | null> {\n const pmDir = dir ?? defaultPostmortemsDir();\n try {\n const files = await listPostmortems(pmDir);\n const cutoffDate = new Date(Date.now() - sinceDays * 24 * 60 * 60 * 1000)\n .toISOString()\n .slice(0, 10);\n\n const recentFiles = files.filter((f) => f >= cutoffDate);\n if (recentFiles.length === 0) return \"No post-mortems found in the specified range.\";\n\n const contents: string[] = [];\n for (const f of recentFiles.slice(0, 10)) {\n const content = await readPostmortem(f, pmDir);\n if (content) contents.push(content);\n }\n\n const response = await client.chat(\n \"You are a session analyst. Analyze these post-mortems and identify trends.\",\n [\n {\n role: \"user\",\n content: `Analyze these ${contents.length} post-mortem reports from the last ${sinceDays} days. Identify:\n1. Recurring blockers\n2. Productivity patterns\n3. Tool reliability issues\n4. Topic continuity across sessions\n5. Actionable recommendations\n\nReports:\n${contents.join(\"\\n\\n---\\n\\n\")}`,\n },\n ],\n () => {}, // no-op onChunk\n );\n\n const text = messageContentToText(response.message.content);\n return text || null;\n } catch (err) {\n log.debug(\"postmortem\", \"Failed to analyze range\", err);\n return null;\n }\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport os from \"node:os\";\n\n// ── Types ──\n\nexport type ObservationEventType =\n | \"tool_call\"\n | \"tool_error\"\n | \"topic_shift\"\n | \"decision\"\n | \"blocker\"\n | \"milestone\"\n | \"file_change\"\n | \"sentiment_shift\"\n | \"error\"\n | \"phase_start\"\n | \"phase_complete\"\n | \"approval_gate\"\n | \"task_delegated\";\n\nexport interface ObservationEvent {\n timestamp: number;\n type: ObservationEventType;\n summary: string;\n data: Record<string, unknown>;\n}\n\nexport interface ObservationSession {\n sessionId: string;\n startedAt: number;\n events: ObservationEvent[];\n paused: boolean;\n stats: {\n toolCalls: number;\n toolErrors: number;\n topicShifts: number;\n blockers: number;\n milestones: number;\n fileChanges: number;\n };\n}\n\n// ── Stat counters by event type ──\n\nconst STAT_MAP: Partial<Record<ObservationEventType, keyof ObservationSession[\"stats\"]>> = {\n tool_call: \"toolCalls\",\n tool_error: \"toolErrors\",\n topic_shift: \"topicShifts\",\n blocker: \"blockers\",\n milestone: \"milestones\",\n file_change: \"fileChanges\",\n};\n\n// ── Default observations directory ──\n\nexport function defaultObservationsDir(): string {\n return path.join(os.homedir(), \".acore\", \"observations\");\n}\n\n// ── Core functions ──\n\nexport function createObservationSession(sessionId: string): ObservationSession {\n return {\n sessionId,\n startedAt: Date.now(),\n events: [],\n paused: false,\n stats: {\n toolCalls: 0,\n toolErrors: 0,\n topicShifts: 0,\n blockers: 0,\n milestones: 0,\n fileChanges: 0,\n },\n };\n}\n\nexport function recordEvent(\n session: ObservationSession,\n event: Omit<ObservationEvent, \"timestamp\">,\n): void {\n if (session.paused) return;\n\n const full: ObservationEvent = { ...event, timestamp: Date.now() };\n session.events.push(full);\n\n const statKey = STAT_MAP[event.type];\n if (statKey) {\n session.stats[statKey]++;\n }\n}\n\nexport function pauseObservation(session: ObservationSession): void {\n session.paused = true;\n}\n\nexport function resumeObservation(session: ObservationSession): void {\n session.paused = false;\n}\n\nexport async function flushEvents(\n session: ObservationSession,\n dir?: string,\n): Promise<void> {\n if (session.events.length === 0) return;\n\n const obsDir = dir ?? defaultObservationsDir();\n await fs.mkdir(obsDir, { recursive: true });\n\n const filePath = path.join(obsDir, `${session.sessionId}.jsonl`);\n const lines = session.events.map((e) => JSON.stringify(e)).join(\"\\n\") + \"\\n\";\n await fs.appendFile(filePath, lines, \"utf-8\");\n\n session.events.length = 0;\n}\n\nexport async function readObservationEvents(\n sessionId: string,\n dir?: string,\n): Promise<ObservationEvent[]> {\n const obsDir = dir ?? defaultObservationsDir();\n const filePath = path.join(obsDir, `${sessionId}.jsonl`);\n\n try {\n const content = await fs.readFile(filePath, \"utf-8\");\n return content\n .trim()\n .split(\"\\n\")\n .filter((line) => line.length > 0)\n .map((line) => JSON.parse(line) as ObservationEvent);\n } catch {\n return [];\n }\n}\n\nexport function getSessionStats(session: ObservationSession): string {\n const elapsed = Math.round((Date.now() - session.startedAt) / 60_000);\n const s = session.stats;\n const parts = [\n `Session: ${elapsed} min`,\n `Tools: ${s.toolCalls} calls (${s.toolErrors} error${s.toolErrors !== 1 ? \"s\" : \"\"})`,\n `Files: ${s.fileChanges} changed`,\n `Blockers: ${s.blockers}`,\n `Milestones: ${s.milestones}`,\n ];\n if (s.topicShifts > 0) parts.push(`Topic shifts: ${s.topicShifts}`);\n if (session.paused) parts.push(\"(paused)\");\n return parts.join(\" | \");\n}\n\nexport async function cleanupOldObservations(\n dir?: string,\n maxAgeDays = 30,\n): Promise<void> {\n const obsDir = dir ?? defaultObservationsDir();\n try {\n const files = await fs.readdir(obsDir);\n const cutoff = Date.now() - maxAgeDays * 24 * 60 * 60 * 1000;\n\n for (const file of files) {\n if (!file.endsWith(\".jsonl\")) continue;\n const filePath = path.join(obsDir, file);\n const stat = await fs.stat(filePath);\n if (stat.mtimeMs < cutoff) {\n await fs.unlink(filePath);\n }\n }\n } catch {\n // Directory may not exist yet — that's fine\n }\n}\n\n// ── Topic shift detection ──\n\nexport function detectTopicShift(\n recentMessages: string[],\n previousMessages: string[],\n): { shifted: boolean; newTopics: string[] } {\n const extractKeywords = (msgs: string[]): Set<string> => {\n const words = msgs\n .join(\" \")\n .toLowerCase()\n .split(/\\W+/)\n .filter((w) => w.length > 3);\n return new Set(words);\n };\n\n const recent = extractKeywords(recentMessages);\n const previous = extractKeywords(previousMessages);\n\n if (previous.size === 0) return { shifted: false, newTopics: [] };\n\n let overlap = 0;\n for (const word of recent) {\n if (previous.has(word)) overlap++;\n }\n\n const overlapRatio = previous.size > 0 ? overlap / previous.size : 1;\n const shifted = overlapRatio < 0.3;\n\n const newTopics = shifted\n ? [...recent].filter((w) => !previous.has(w)).slice(0, 5)\n : [];\n\n return { shifted, newTopics };\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { log } from \"./logger.js\";\n\n// ── Types ──\n\nexport interface SkillCandidate {\n name: string;\n description: string;\n triggers: string[];\n approach: string;\n steps: string[];\n gotchas: string[];\n confidence: number;\n}\n\nexport interface CrystallizationResult {\n written: boolean;\n filePath: string;\n skillName: string;\n reason?: string;\n collidesWith?: string;\n}\n\nexport interface MarkerData {\n source: string;\n date: string;\n confidence: number;\n triggers: string[];\n}\n\nexport interface CrystallizationLogEntry {\n name: string;\n createdAt: string;\n fromPostmortem: string;\n confidence: number;\n triggers: string[];\n}\n\nexport interface RejectionLogEntry {\n name: string;\n rejectedAt: string;\n fromPostmortem: string;\n triggers: string[];\n}\n\nexport interface CollisionResult {\n collides: boolean;\n collidesWith?: string;\n reason?: string;\n}\n\n// ── Constants ──\n\nconst STOPWORDS = new Set([\n \"the\", \"and\", \"is\", \"to\", \"of\", \"a\", \"in\", \"for\", \"on\", \"with\",\n \"this\", \"that\", \"it\", \"as\", \"be\", \"by\", \"or\", \"at\", \"an\", \"from\",\n \"code\", \"fix\", \"do\", \"use\", \"make\", \"get\", \"set\", \"run\", \"we\", \"i\",\n]);\n\nconst MAX_REJECTIONS = 100;\nconst MARKER_RE = /<!--\\s*aman-auto\\s+([^>]+?)\\s*-->/;\n\n// ── sanitizeName ──\n\nexport function sanitizeName(input: string): string {\n const cleaned = input\n .toLowerCase()\n .trim()\n .replace(/[^a-z0-9\\s-]/g, \" \")\n .replace(/\\s+/g, \"-\")\n .replace(/-+/g, \"-\")\n .replace(/^-|-$/g, \"\");\n\n if (cleaned.length === 0) {\n throw new Error(`Cannot sanitize name: \"${input}\" produced empty result`);\n }\n return cleaned;\n}\n\n// ── validateCandidate ──\n\nexport function validateCandidate(raw: unknown): SkillCandidate | null {\n if (!raw || typeof raw !== \"object\") return null;\n const c = raw as Record<string, unknown>;\n\n if (typeof c.name !== \"string\" || c.name.trim() === \"\") return null;\n if (typeof c.description !== \"string\") return null;\n if (typeof c.approach !== \"string\") return null;\n if (!Array.isArray(c.triggers) || c.triggers.length === 0) return null;\n if (c.triggers.length > 10) return null;\n if (!Array.isArray(c.steps)) return null;\n if (typeof c.confidence !== \"number\") return null;\n if (!Number.isFinite(c.confidence)) return null;\n\n if (c.confidence < 0.6) return null;\n\n const triggers = Array.from(\n new Set(\n c.triggers\n .filter((t): t is string => typeof t === \"string\")\n .map((t) => t.toLowerCase().trim())\n .filter((t) => t.length > 0 && !STOPWORDS.has(t))\n )\n );\n\n if (triggers.length === 0) return null;\n\n let name: string;\n try {\n name = sanitizeName(c.name);\n } catch {\n return null;\n }\n\n return {\n name,\n description: c.description,\n triggers,\n approach: c.approach,\n steps: c.steps.filter((s): s is string => typeof s === \"string\"),\n gotchas: Array.isArray(c.gotchas)\n ? c.gotchas.filter((g): g is string => typeof g === \"string\")\n : [],\n confidence: Math.min(1, Math.max(0, c.confidence)),\n };\n}\n\n// ── formatSkillMarkdown ──\n\nfunction toTitleCase(kebab: string): string {\n return kebab\n .split(\"-\")\n .map((w) => w.charAt(0).toUpperCase() + w.slice(1))\n .join(\" \");\n}\n\nexport function formatSkillMarkdown(\n candidate: SkillCandidate,\n postmortemFilename: string,\n): string {\n const date = new Date().toISOString().slice(0, 10);\n const heading = toTitleCase(candidate.name);\n const triggerStr = candidate.triggers.join(\",\");\n\n const lines: string[] = [\n `# ${heading}`,\n `<!-- aman-auto source=postmortem date=${date} confidence=${candidate.confidence} triggers=\"${triggerStr}\" -->`,\n \"\",\n \"## When to use\",\n candidate.approach,\n \"\",\n \"## Steps\",\n ...candidate.steps.map((s, i) => `${i + 1}. ${s}`),\n \"\",\n ];\n\n if (candidate.gotchas.length > 0) {\n lines.push(\"## Gotchas\");\n lines.push(...candidate.gotchas.map((g) => `- ${g}`));\n lines.push(\"\");\n }\n\n lines.push(`<!-- generated from ${postmortemFilename} -->`);\n lines.push(\"\");\n\n return lines.join(\"\\n\");\n}\n\n// ── parseMarkerComment ──\n\nexport function parseMarkerComment(line: string): MarkerData | null {\n const match = line.match(MARKER_RE);\n if (!match) return null;\n\n const attrs: Record<string, string> = {};\n const attrRe = /(\\w+)=(?:\"([^\"]*)\"|(\\S+))/g;\n let m: RegExpExecArray | null;\n while ((m = attrRe.exec(match[1])) !== null) {\n attrs[m[1]] = m[2] ?? m[3] ?? \"\";\n }\n\n if (!attrs.triggers) return null;\n\n const triggers = attrs.triggers\n .split(\",\")\n .map((t) => t.trim())\n .filter((t) => t.length > 0);\n\n if (triggers.length === 0) return null;\n\n return {\n source: attrs.source ?? \"unknown\",\n date: attrs.date ?? \"\",\n confidence: attrs.confidence ? Number(attrs.confidence) : 0,\n triggers,\n };\n}\n\n// ── extractSkillsWithMarkers ──\n\nexport function extractSkillsWithMarkers(\n skillsMdContent: string,\n): Map<string, MarkerData> {\n const result = new Map<string, MarkerData>();\n const lines = skillsMdContent.split(\"\\n\");\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n if (line.startsWith(\"# \") && i + 1 < lines.length) {\n const headingText = line.slice(2).trim();\n const nextLine = lines[i + 1];\n const marker = parseMarkerComment(nextLine);\n if (marker) {\n try {\n const skillName = sanitizeName(headingText);\n result.set(skillName, marker);\n } catch {\n log.debug(\"crystallization\", `cannot sanitize heading: ${headingText}`);\n }\n }\n }\n }\n\n return result;\n}\n\n// ── findCollision ──\n\nexport function findCollision(\n name: string,\n triggers: string[],\n existing: Map<string, MarkerData>,\n): CollisionResult {\n if (existing.has(name)) {\n return { collides: true, collidesWith: name, reason: \"exact name match\" };\n }\n\n const triggerSet = new Set(triggers);\n for (const [otherName, otherData] of existing) {\n const otherTriggers = new Set(otherData.triggers);\n const intersection = [...triggerSet].filter((t) => otherTriggers.has(t)).length;\n const union = new Set([...triggerSet, ...otherTriggers]).size;\n const overlap = union > 0 ? intersection / union : 0;\n if (overlap >= 0.8) {\n return {\n collides: true,\n collidesWith: otherName,\n reason: `${Math.round(overlap * 100)}% trigger overlap`,\n };\n }\n }\n\n return { collides: false };\n}\n\n// ── writeSkillToFile ──\n\nexport async function writeSkillToFile(\n candidate: SkillCandidate,\n skillsMdPath: string,\n postmortemFilename: string,\n): Promise<CrystallizationResult> {\n try {\n await fs.mkdir(path.dirname(skillsMdPath), { recursive: true });\n\n let existingContent = \"\";\n try {\n existingContent = await fs.readFile(skillsMdPath, \"utf-8\");\n } catch {\n existingContent = \"# Skills\\n\\n\";\n }\n\n if (existingContent.trim() === \"\") {\n existingContent = \"# Skills\\n\\n\";\n }\n\n const existingSkills = extractSkillsWithMarkers(existingContent);\n const collision = findCollision(candidate.name, candidate.triggers, existingSkills);\n if (collision.collides) {\n log.debug(\"crystallization\", `collision detected: ${collision.reason}`);\n return {\n written: false,\n filePath: skillsMdPath,\n skillName: candidate.name,\n reason: `collision with \"${collision.collidesWith}\" (${collision.reason})`,\n collidesWith: collision.collidesWith,\n };\n }\n\n const skillMarkdown = formatSkillMarkdown(candidate, postmortemFilename);\n const separator = existingContent.endsWith(\"\\n\\n\")\n ? \"\"\n : existingContent.endsWith(\"\\n\")\n ? \"\\n\"\n : \"\\n\\n\";\n await fs.writeFile(\n skillsMdPath,\n existingContent + separator + skillMarkdown,\n \"utf-8\",\n );\n\n return {\n written: true,\n filePath: skillsMdPath,\n skillName: candidate.name,\n };\n } catch (err) {\n log.warn(\"crystallization\", \"writeSkillToFile failed\", err);\n return {\n written: false,\n filePath: skillsMdPath,\n skillName: candidate.name,\n reason: err instanceof Error ? err.message : String(err),\n };\n }\n}\n\n// ── mergeSkillInFile ──\n\n/**\n * Replace an existing skill block in skills.md with a new candidate.\n * Finds the heading for `existingName`, removes everything up to the next heading or EOF,\n * and writes the new candidate in its place.\n */\nexport async function mergeSkillInFile(\n candidate: SkillCandidate,\n existingName: string,\n skillsMdPath: string,\n postmortemFilename: string,\n): Promise<CrystallizationResult> {\n try {\n const content = await fs.readFile(skillsMdPath, \"utf-8\");\n const lines = content.split(\"\\n\");\n\n // Find the heading line for the existing skill\n const heading = toTitleCase(existingName);\n let startIdx = -1;\n for (let i = 0; i < lines.length; i++) {\n if (lines[i].startsWith(\"# \") && lines[i].slice(2).trim() === heading) {\n startIdx = i;\n break;\n }\n }\n\n if (startIdx === -1) {\n return writeSkillToFile(candidate, skillsMdPath, postmortemFilename);\n }\n\n // Find the end of this skill block (next heading or EOF)\n let endIdx = lines.length;\n for (let i = startIdx + 1; i < lines.length; i++) {\n if (lines[i].startsWith(\"# \") && !lines[i].startsWith(\"## \")) {\n endIdx = i;\n break;\n }\n }\n\n // Determine version number — count existing archived versions\n const versionPattern = new RegExp(`^# ${heading.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}\\\\.v\\\\d+`);\n let maxVersion = 0;\n for (const line of lines) {\n if (versionPattern.test(line)) {\n const vMatch = line.match(/\\.v(\\d+)/);\n if (vMatch) maxVersion = Math.max(maxVersion, parseInt(vMatch[1], 10));\n }\n }\n const archiveVersion = maxVersion + 1;\n\n // Archive the old version by renaming its heading\n const oldBlock = lines.slice(startIdx, endIdx);\n oldBlock[0] = `# ${heading}.v${archiveVersion}`;\n // Add archive marker\n const archiveMarker = `<!-- aman-archived version=${archiveVersion} archived-at=${new Date().toISOString().slice(0, 10)} -->`;\n if (oldBlock.length > 1 && oldBlock[1].includes(\"aman-auto\")) {\n oldBlock.splice(2, 0, archiveMarker);\n } else {\n oldBlock.splice(1, 0, archiveMarker);\n }\n\n // Write: archived old block + new candidate\n const newSkillMarkdown = formatSkillMarkdown(candidate, postmortemFilename);\n const before = lines.slice(0, startIdx);\n const after = lines.slice(endIdx);\n const merged = [...before, ...oldBlock, \"\", newSkillMarkdown, ...after].join(\"\\n\");\n\n await fs.writeFile(skillsMdPath, merged, \"utf-8\");\n\n return {\n written: true,\n filePath: skillsMdPath,\n skillName: candidate.name,\n reason: `merged with \"${existingName}\" (archived as .v${archiveVersion})`,\n };\n } catch (err) {\n log.warn(\"crystallization\", \"mergeSkillInFile failed\", err);\n return {\n written: false,\n filePath: skillsMdPath,\n skillName: candidate.name,\n reason: err instanceof Error ? err.message : String(err),\n };\n }\n}\n\n// ── Logs ──\n\nexport async function appendCrystallizationLog(\n entry: CrystallizationLogEntry,\n logPath: string,\n): Promise<void> {\n try {\n await fs.mkdir(path.dirname(logPath), { recursive: true });\n let existing: CrystallizationLogEntry[] = [];\n try {\n const content = await fs.readFile(logPath, \"utf-8\");\n existing = JSON.parse(content);\n if (!Array.isArray(existing)) existing = [];\n } catch {\n existing = [];\n }\n existing.push(entry);\n await fs.writeFile(logPath, JSON.stringify(existing, null, 2), \"utf-8\");\n } catch (err) {\n log.debug(\"crystallization\", \"appendCrystallizationLog failed\", err);\n }\n}\n\nexport async function appendRejection(\n candidate: SkillCandidate,\n postmortemFilename: string,\n rejectionsPath: string,\n): Promise<void> {\n try {\n await fs.mkdir(path.dirname(rejectionsPath), { recursive: true });\n let existing: RejectionLogEntry[] = [];\n try {\n const content = await fs.readFile(rejectionsPath, \"utf-8\");\n existing = JSON.parse(content);\n if (!Array.isArray(existing)) existing = [];\n } catch {\n existing = [];\n }\n\n existing.push({\n name: candidate.name,\n rejectedAt: new Date().toISOString(),\n fromPostmortem: postmortemFilename,\n triggers: candidate.triggers,\n });\n\n while (existing.length > MAX_REJECTIONS) {\n existing.shift();\n }\n\n await fs.writeFile(rejectionsPath, JSON.stringify(existing, null, 2), \"utf-8\");\n } catch (err) {\n log.debug(\"crystallization\", \"appendRejection failed\", err);\n }\n}\n\n/**\n * Load rejected skill names from the rejections log.\n * Returns unique names. Never throws.\n */\nexport async function loadRejectedNames(rejectionsPath: string): Promise<string[]> {\n try {\n const content = await fs.readFile(rejectionsPath, \"utf-8\");\n const entries: RejectionLogEntry[] = JSON.parse(content);\n if (!Array.isArray(entries)) return [];\n return [...new Set(entries.map((e) => e.name))];\n } catch {\n return [];\n }\n}\n\n// ── Suggestion tracking (cross-session reinforcement) ──\n\nexport interface SuggestionCounts {\n [name: string]: number;\n}\n\n/**\n * Load suggestion counts. Never throws.\n */\nexport async function loadSuggestionCounts(suggestionsPath: string): Promise<SuggestionCounts> {\n try {\n const content = await fs.readFile(suggestionsPath, \"utf-8\");\n const parsed = JSON.parse(content);\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) return {};\n return parsed as SuggestionCounts;\n } catch {\n return {};\n }\n}\n\n/**\n * Increment suggestion count for a candidate name. Returns the new count.\n */\nexport async function incrementSuggestionCount(\n name: string,\n suggestionsPath: string,\n): Promise<number> {\n try {\n await fs.mkdir(path.dirname(suggestionsPath), { recursive: true });\n const counts = await loadSuggestionCounts(suggestionsPath);\n counts[name] = (counts[name] || 0) + 1;\n await fs.writeFile(suggestionsPath, JSON.stringify(counts, null, 2), \"utf-8\");\n return counts[name];\n } catch (err) {\n log.debug(\"crystallization\", \"incrementSuggestionCount failed\", err);\n return 0;\n }\n}\n","// ── Public API for the orchestrator module ──────────────────────────\n\n// Re-exports: types\nexport {\n type TaskNode,\n type TaskDAG,\n type PhaseGate,\n type OrchestrationState,\n type OrchestrationConfig,\n type TaskResult,\n type ModelTier,\n TaskNodeSchema,\n TaskDAGSchema,\n PhaseGateSchema,\n OrchestrationConfigSchema,\n OrchestrationStatusEnum,\n TaskStatusEnum,\n ModelTierEnum,\n PhaseGateTypeEnum,\n} from \"./types.js\";\n\n// Re-exports: state machine\nexport {\n createOrchestrationState,\n transition,\n canTransition,\n getValidTransitions,\n transitionTask,\n InvalidTransitionError,\n} from \"./state-machine.js\";\n\n// Re-exports: DAG\nexport {\n validateDAG,\n topologicalSort,\n getReadyNodes,\n getDependents,\n DAGValidationError,\n} from \"./dag.js\";\n\n// Re-exports: model router\nexport {\n createModelRouter,\n suggestTier,\n type ModelRouter,\n} from \"./model-router.js\";\n\n// Re-exports: audit\nexport {\n createAuditLog,\n recordAuditEvent,\n getAuditTrail,\n formatAuditTrail,\n type AuditLog,\n type AuditEvent,\n type AuditEventType,\n} from \"./audit.js\";\n\n// Re-exports: decompose\nexport {\n decomposeRequirement,\n parseDecompositionResponse,\n} from \"./decompose.js\";\n\n// Re-exports: scheduler\nexport {\n runScheduler,\n type SchedulerCallbacks,\n type SchedulerResult,\n} from \"./scheduler.js\";\n\n// Re-exports: review loop\nexport {\n buildReviewDAG,\n runReviewLoop,\n type ReviewLoopOptions,\n type ReviewResult,\n} from \"./review-loop.js\";\n\n// Re-exports: circuit breaker\nexport {\n createCircuitBreaker,\n createCircuitBreakerRegistry,\n type CircuitState,\n type CircuitBreaker,\n type CircuitBreakerOptions,\n type CircuitBreakerRegistry,\n} from \"./circuit-breaker.js\";\n\n// Re-exports: checkpoint\nexport {\n createCheckpoint,\n serializeCheckpoint,\n deserializeCheckpoint,\n saveCheckpoint,\n loadCheckpoint,\n restoreMaps,\n type CheckpointData,\n} from \"./checkpoint.js\";\n\n// Re-exports: cost tracker\nexport {\n createCostTracker,\n DEFAULT_TIER_COSTS,\n type CostTracker,\n type CostTrackerOptions,\n type CostEntry,\n type TierCost,\n} from \"./cost-tracker.js\";\n\n// Re-exports: policy\nexport {\n evaluatePolicy,\n getDefaultPolicies,\n formatPolicyResult,\n type PolicySeverity,\n type PolicyViolation,\n type PolicyResult,\n type PolicyRule,\n} from \"./policy.js\";\n\n// Re-exports: runner (unified orchestration)\nexport {\n runOrchestrationFull,\n type FullOrchestrationOptions,\n type FullOrchestrationResult,\n} from \"./runner.js\";\n\n// Re-exports: smart orchestrate\nexport {\n smartOrchestrate,\n formatSmartResult,\n type SmartOrchestrationOptions,\n type SmartOrchestrationResult,\n} from \"./smart-orchestrate.js\";\n\n// Re-exports: templates\nexport {\n fullFeatureTemplate,\n bugFixTemplate,\n securityAuditTemplate,\n getTemplate,\n listTemplates,\n type TemplateOptions,\n} from \"./templates/index.js\";\n\n// ── Convenience functions ───────────────────────────────────────────\n\nimport type { TaskDAG, TaskNode, PhaseGate, OrchestrationState } from \"./types.js\";\nimport type { ModelRouter } from \"./model-router.js\";\nimport type { SchedulerCallbacks, SchedulerResult } from \"./scheduler.js\";\nimport { validateDAG } from \"./dag.js\";\nimport { createOrchestrationState } from \"./state-machine.js\";\nimport { runScheduler } from \"./scheduler.js\";\n\n/**\n * Formats a TaskDAG for human-readable CLI display.\n */\nexport function formatDAGForDisplay(dag: TaskDAG): string {\n const lines: string[] = [];\n lines.push(`## ${dag.name}`);\n lines.push(`**Goal:** ${dag.goal}`);\n lines.push(`**Tasks:** ${dag.nodes.length} | **Gates:** ${dag.gates.length}`);\n lines.push(\"\");\n\n for (const node of dag.nodes) {\n const depLabel =\n node.dependencies.length === 0\n ? \"(root)\"\n : `(after: ${node.dependencies.join(\", \")})`;\n lines.push(`- **${node.name}** \\u2192 ${node.profile} [${node.tier}] ${depLabel}`);\n }\n\n for (const gate of dag.gates) {\n lines.push(`- \\uD83D\\uDD12 **${gate.name}** [${gate.type}]`);\n }\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Validates DAG (throws DAGValidationError if invalid), then creates\n * initial orchestration state.\n */\nexport function createOrchestration(dag: TaskDAG): OrchestrationState {\n validateDAG(dag);\n return createOrchestrationState(dag);\n}\n\n/**\n * Convenience wrapper: validates DAG and runs the scheduler end-to-end.\n */\nexport async function runOrchestration(\n dag: TaskDAG,\n router: ModelRouter,\n options?: { maxParallelTasks?: number; taskTimeoutMs?: number },\n callbacks?: SchedulerCallbacks,\n): Promise<SchedulerResult> {\n return runScheduler(dag, router, options, callbacks);\n}\n","import type {\n TaskDAG,\n OrchestrationState,\n OrchestrationStatus,\n TaskStatus,\n} from \"./types.js\";\n\n// ── Transition tables ───────────────────────────────────────────────\n\nconst ORCHESTRATION_TRANSITIONS: Record<OrchestrationStatus, OrchestrationStatus[]> = {\n pending: [\"running\", \"cancelled\"],\n running: [\"awaiting_approval\", \"paused\", \"completed\", \"failed\", \"cancelled\"],\n awaiting_approval: [\"approved\", \"cancelled\", \"failed\"],\n approved: [\"running\", \"cancelled\"],\n paused: [\"running\", \"cancelled\", \"failed\"],\n completed: [],\n failed: [],\n cancelled: [],\n};\n\nconst TASK_TRANSITIONS: Record<TaskStatus, TaskStatus[]> = {\n pending: [\"ready\", \"skipped\", \"blocked\"],\n ready: [\"running\", \"skipped\", \"blocked\"],\n running: [\"completed\", \"failed\"],\n completed: [],\n failed: [\"ready\"],\n skipped: [],\n blocked: [\"ready\", \"skipped\"],\n};\n\nconst TERMINAL_ORCHESTRATION: Set<OrchestrationStatus> = new Set([\n \"completed\",\n \"failed\",\n \"cancelled\",\n]);\n\n// ── InvalidTransitionError ──────────────────────────────────────────\n\nexport class InvalidTransitionError extends Error {\n constructor(\n public readonly from: string,\n public readonly to: string,\n public readonly entity: string = \"orchestration\",\n ) {\n super(\n `Invalid ${entity} transition: ${from} → ${to}`,\n );\n this.name = \"InvalidTransitionError\";\n }\n}\n\n// ── Factory ─────────────────────────────────────────────────────────\n\nexport function createOrchestrationState(dag: TaskDAG): OrchestrationState {\n const now = Date.now();\n const taskStatuses = new Map<string, TaskStatus>();\n for (const node of dag.nodes) {\n taskStatuses.set(node.id, \"pending\");\n }\n return {\n dag,\n status: \"pending\",\n taskStatuses,\n taskResults: new Map(),\n activeGate: null,\n startedAt: now,\n updatedAt: now,\n };\n}\n\n// ── Query helpers ───────────────────────────────────────────────────\n\nexport function canTransition(\n state: OrchestrationState,\n to: OrchestrationStatus,\n): boolean {\n return ORCHESTRATION_TRANSITIONS[state.status].includes(to);\n}\n\nexport function getValidTransitions(\n state: OrchestrationState,\n): OrchestrationStatus[] {\n return [...ORCHESTRATION_TRANSITIONS[state.status]];\n}\n\n// ── Orchestration transition ────────────────────────────────────────\n\nfunction cloneState(state: OrchestrationState): OrchestrationState {\n return {\n ...state,\n taskStatuses: new Map(state.taskStatuses),\n taskResults: new Map(state.taskResults),\n updatedAt: Date.now(),\n };\n}\n\nexport function transition(\n state: OrchestrationState,\n to: OrchestrationStatus,\n error?: string,\n): OrchestrationState {\n if (!canTransition(state, to)) {\n throw new InvalidTransitionError(state.status, to);\n }\n\n const next = cloneState(state);\n next.status = to;\n\n if (TERMINAL_ORCHESTRATION.has(to)) {\n next.completedAt = next.updatedAt;\n }\n\n if (error !== undefined) {\n next.error = error;\n }\n\n return next;\n}\n\n// ── Task transition ─────────────────────────────────────────────────\n\nexport function transitionTask(\n state: OrchestrationState,\n taskId: string,\n to: TaskStatus,\n): OrchestrationState {\n const current = state.taskStatuses.get(taskId);\n if (current === undefined) {\n throw new Error(`Unknown task id: ${taskId}`);\n }\n\n if (!TASK_TRANSITIONS[current].includes(to)) {\n throw new InvalidTransitionError(current, to, \"task\");\n }\n\n const next = cloneState(state);\n next.taskStatuses.set(taskId, to);\n return next;\n}\n","import type { LLMClient } from \"../llm/types.js\";\nimport type { ModelTier, TaskNode } from \"./types.js\";\n\n// ── Profile → tier mapping sets ─────────────────────────────────────\nexport const ADVANCED_PROFILES = new Set([\"architect\", \"planner\", \"designer\"]);\nexport const FAST_PROFILES = new Set([\"linter\", \"formatter\", \"validator\"]);\n\n// ── ModelRouter interface ───────────────────────────────────────────\nexport interface ModelRouter {\n getClient(tier: ModelTier): LLMClient;\n}\n\nexport interface ModelRouterClients {\n fast?: LLMClient;\n standard: LLMClient; // required, used as fallback\n advanced?: LLMClient;\n}\n\n// ── Factory ─────────────────────────────────────────────────────────\nexport function createModelRouter(clients: ModelRouterClients): ModelRouter {\n return {\n getClient(tier: ModelTier): LLMClient {\n if (tier === \"fast\") return clients.fast ?? clients.standard;\n if (tier === \"advanced\") return clients.advanced ?? clients.standard;\n return clients.standard;\n },\n };\n}\n\n// ── Tier suggestion based on task profile ───────────────────────────\nexport function suggestTier(node: TaskNode): ModelTier {\n if (ADVANCED_PROFILES.has(node.profile)) return \"advanced\";\n if (FAST_PROFILES.has(node.profile)) return \"fast\";\n return \"standard\";\n}\n","// ── Audit Logging ───────────────────────────────────────────────────\n\nexport type AuditEventType =\n | \"orchestration_started\"\n | \"orchestration_completed\"\n | \"orchestration_failed\"\n | \"orchestration_cancelled\"\n | \"task_started\"\n | \"task_completed\"\n | \"task_failed\"\n | \"task_skipped\"\n | \"approval_requested\"\n | \"approval_granted\"\n | \"approval_denied\"\n | \"gate_resolved\"\n | \"phase_transition\"\n | \"state_transition\";\n\nexport interface AuditEvent {\n timestamp: number;\n type: AuditEventType;\n message: string;\n taskId?: string;\n gateId?: string;\n data?: Record<string, unknown>;\n}\n\nexport interface AuditLog {\n orchestrationId: string;\n events: AuditEvent[];\n}\n\n/** Create an empty audit log for the given orchestration. */\nexport function createAuditLog(orchestrationId: string): AuditLog {\n return { orchestrationId, events: [] };\n}\n\n/** Append an event with a Date.now() timestamp. Mutates the log. */\nexport function recordAuditEvent(\n log: AuditLog,\n event: Omit<AuditEvent, \"timestamp\">,\n): void {\n log.events.push({ ...event, timestamp: Date.now() });\n}\n\n/** Return all events, optionally filtered by type. */\nexport function getAuditTrail(\n log: AuditLog,\n type?: AuditEventType,\n): AuditEvent[] {\n if (type === undefined) return [...log.events];\n return log.events.filter((e) => e.type === type);\n}\n\n/** Return a human-readable formatted string of the audit trail. */\nexport function formatAuditTrail(log: AuditLog): string {\n return log.events\n .map((e) => {\n const iso = new Date(e.timestamp).toISOString();\n const taskPart = e.taskId ? ` [${e.taskId}]` : \"\";\n const gatePart = e.gateId ? ` [gate:${e.gateId}]` : \"\";\n return `${iso} ${e.type}${taskPart}${gatePart} — ${e.message}`;\n })\n .join(\"\\n\");\n}\n","import type {\n TaskDAG,\n TaskResult,\n OrchestrationStatus,\n OrchestrationState,\n ModelTier,\n} from \"./types.js\";\nimport type { ModelRouter } from \"./model-router.js\";\nimport type { McpManager } from \"../mcp/client.js\";\nimport type { AuditLog } from \"./audit.js\";\n\nimport { validateDAG, getReadyNodes } from \"./dag.js\";\nimport {\n createOrchestrationState,\n transition,\n transitionTask,\n} from \"./state-machine.js\";\nimport { createAuditLog, recordAuditEvent } from \"./audit.js\";\nimport { delegateTask } from \"../delegate.js\";\n\n// ── Public interfaces ───────────────────────────────────────────────\n\nexport interface SchedulerCallbacks {\n onTaskStarted?: (nodeId: string, nodeName: string) => Promise<void>;\n onTaskCompleted?: (nodeId: string, nodeName: string, result: TaskResult) => Promise<void>;\n onTaskFailed?: (nodeId: string, nodeName: string, error: string) => Promise<void>;\n onApprovalRequired?: (gateId: string, gateName: string) => Promise<boolean>;\n onPhaseTransition?: (from: OrchestrationStatus, to: OrchestrationStatus) => Promise<void>;\n}\n\nexport interface SchedulerOptions {\n maxParallelTasks?: number; // default 4\n taskTimeoutMs?: number; // default 300_000\n mcpManager?: McpManager;\n}\n\nexport interface SchedulerResult {\n status: OrchestrationStatus;\n taskResults: Map<string, TaskResult>;\n auditLog: AuditLog;\n error?: string;\n durationMs: number;\n}\n\n// ── Scheduler ───────────────────────────────────────────────────────\n\nexport async function runScheduler(\n dag: TaskDAG,\n router: ModelRouter,\n options?: SchedulerOptions,\n callbacks?: SchedulerCallbacks,\n): Promise<SchedulerResult> {\n const startTime = Date.now();\n const maxParallel = options?.maxParallelTasks ?? 4;\n const mcpManager = options?.mcpManager ?? (null as unknown as McpManager);\n\n // 1. Validate DAG\n validateDAG(dag);\n\n // 2. Create initial state and audit log\n let state = createOrchestrationState(dag);\n const auditLog = createAuditLog(dag.id);\n\n // 3. Transition to running\n state = transition(state, \"running\");\n recordAuditEvent(auditLog, {\n type: \"orchestration_started\",\n message: `Orchestration \"${dag.name}\" started`,\n });\n\n const resolvedGates = new Set<string>();\n const running = new Map<string, Promise<void>>();\n\n // Helper: transition orchestration with callback\n async function transitionOrch(to: OrchestrationStatus, error?: string): Promise<void> {\n const from = state.status;\n state = transition(state, to, error);\n if (callbacks?.onPhaseTransition) {\n await callbacks.onPhaseTransition(from, to);\n }\n }\n\n // Helper: dispatch a single task\n function dispatchTask(nodeId: string): void {\n const node = dag.nodes.find((n) => n.id === nodeId)!;\n\n // pending -> ready -> running\n state = transitionTask(state, nodeId, \"ready\");\n state = transitionTask(state, nodeId, \"running\");\n\n const taskPromise = (async () => {\n // Fire onTaskStarted callback\n if (callbacks?.onTaskStarted) {\n await callbacks.onTaskStarted(nodeId, node.name);\n }\n\n recordAuditEvent(auditLog, {\n type: \"task_started\",\n message: `Task \"${node.name}\" started`,\n taskId: nodeId,\n });\n\n const startedAt = Date.now();\n const client = router.getClient(node.tier);\n\n // Build task description from name + description + context\n const taskDesc = [node.name, node.description, node.context]\n .filter(Boolean)\n .join(\": \");\n\n try {\n const delegationResult = await delegateTask(\n taskDesc,\n node.profile,\n client,\n mcpManager,\n { silent: true },\n );\n\n const completedAt = Date.now();\n\n if (delegationResult.success) {\n const taskResult: TaskResult = {\n nodeId,\n status: \"completed\",\n output: delegationResult.response,\n toolsUsed: delegationResult.toolsUsed,\n turns: delegationResult.turns,\n startedAt,\n completedAt,\n tier: node.tier,\n };\n\n state = transitionTask(state, nodeId, \"completed\");\n state.taskResults.set(nodeId, taskResult);\n\n recordAuditEvent(auditLog, {\n type: \"task_completed\",\n message: `Task \"${node.name}\" completed`,\n taskId: nodeId,\n });\n\n if (callbacks?.onTaskCompleted) {\n await callbacks.onTaskCompleted(nodeId, node.name, taskResult);\n }\n } else {\n const taskResult: TaskResult = {\n nodeId,\n status: \"failed\",\n error: delegationResult.error ?? \"Task failed\",\n toolsUsed: delegationResult.toolsUsed,\n turns: delegationResult.turns,\n startedAt,\n completedAt,\n tier: node.tier,\n };\n\n state = transitionTask(state, nodeId, \"failed\");\n state.taskResults.set(nodeId, taskResult);\n\n recordAuditEvent(auditLog, {\n type: \"task_failed\",\n message: `Task \"${node.name}\" failed: ${delegationResult.error}`,\n taskId: nodeId,\n });\n\n if (callbacks?.onTaskFailed) {\n await callbacks.onTaskFailed(nodeId, node.name, delegationResult.error ?? \"Task failed\");\n }\n }\n } catch (err) {\n const completedAt = Date.now();\n const errorMsg = err instanceof Error ? err.message : String(err);\n\n const taskResult: TaskResult = {\n nodeId,\n status: \"failed\",\n error: errorMsg,\n toolsUsed: [],\n turns: 0,\n startedAt,\n completedAt,\n tier: node.tier,\n };\n\n state = transitionTask(state, nodeId, \"failed\");\n state.taskResults.set(nodeId, taskResult);\n\n recordAuditEvent(auditLog, {\n type: \"task_failed\",\n message: `Task \"${node.name}\" threw: ${errorMsg}`,\n taskId: nodeId,\n });\n\n if (callbacks?.onTaskFailed) {\n await callbacks.onTaskFailed(nodeId, node.name, errorMsg);\n }\n }\n })();\n\n running.set(nodeId, taskPromise);\n\n // Remove from running map when done\n taskPromise.then(() => running.delete(nodeId));\n }\n\n // 4. Main loop\n try {\n while (true) {\n // Check for terminal state\n if ([\"completed\", \"failed\", \"cancelled\"].includes(state.status)) {\n break;\n }\n\n // a. Check if any task failed\n const hasFailed = [...state.taskStatuses.values()].some((s) => s === \"failed\");\n if (hasFailed) {\n await transitionOrch(\"failed\", \"A task failed\");\n recordAuditEvent(auditLog, {\n type: \"orchestration_failed\",\n message: \"Orchestration failed due to task failure\",\n });\n break;\n }\n\n // b. Check for pending gates\n let gateHandled = false;\n for (const gate of dag.gates) {\n if (resolvedGates.has(gate.id)) continue;\n\n const allAfterDone = gate.afterNodes.every(\n (id) => state.taskStatuses.get(id) === \"completed\",\n );\n if (!allAfterDone) continue;\n\n // Gate is active — need approval\n gateHandled = true;\n\n await transitionOrch(\"awaiting_approval\");\n recordAuditEvent(auditLog, {\n type: \"approval_requested\",\n message: `Gate \"${gate.name}\" requires approval`,\n gateId: gate.id,\n });\n\n let approved = false;\n if (callbacks?.onApprovalRequired) {\n approved = await callbacks.onApprovalRequired(gate.id, gate.name);\n }\n\n if (approved) {\n resolvedGates.add(gate.id);\n await transitionOrch(\"approved\");\n recordAuditEvent(auditLog, {\n type: \"approval_granted\",\n message: `Gate \"${gate.name}\" approved`,\n gateId: gate.id,\n });\n await transitionOrch(\"running\");\n recordAuditEvent(auditLog, {\n type: \"gate_resolved\",\n message: `Gate \"${gate.name}\" resolved, resuming`,\n gateId: gate.id,\n });\n } else {\n await transitionOrch(\"cancelled\");\n recordAuditEvent(auditLog, {\n type: \"approval_denied\",\n message: `Gate \"${gate.name}\" denied, cancelling`,\n gateId: gate.id,\n });\n break;\n }\n }\n\n if ([\"completed\", \"failed\", \"cancelled\"].includes(state.status)) {\n break;\n }\n\n // c. Get ready nodes\n const readyNodes = getReadyNodes(dag, state.taskStatuses, resolvedGates);\n\n if (readyNodes.length === 0 && running.size === 0) {\n // Check if all done\n const allCompleted = [...state.taskStatuses.values()].every(\n (s) => s === \"completed\" || s === \"skipped\",\n );\n if (allCompleted) {\n await transitionOrch(\"completed\");\n recordAuditEvent(auditLog, {\n type: \"orchestration_completed\",\n message: `Orchestration \"${dag.name}\" completed successfully`,\n });\n break;\n } else {\n // Stuck — nothing ready, nothing running, not all done\n await transitionOrch(\"failed\", \"Scheduler stuck: no ready or running tasks\");\n recordAuditEvent(auditLog, {\n type: \"orchestration_failed\",\n message: \"Orchestration stuck with no progress possible\",\n });\n break;\n }\n }\n\n // d. Dispatch ready tasks up to available slots\n const availableSlots = maxParallel - running.size;\n const toDispatch = readyNodes.slice(0, availableSlots);\n\n for (const nodeId of toDispatch) {\n dispatchTask(nodeId);\n }\n\n // e. Wait for at least one task to finish before re-looping\n if (running.size > 0) {\n await Promise.race(running.values());\n }\n }\n } catch (err) {\n const errorMsg = err instanceof Error ? err.message : String(err);\n if (![\"completed\", \"failed\", \"cancelled\"].includes(state.status)) {\n try {\n state = transition(state, \"failed\", errorMsg);\n } catch {\n // already terminal\n }\n }\n recordAuditEvent(auditLog, {\n type: \"orchestration_failed\",\n message: `Orchestration error: ${errorMsg}`,\n });\n }\n\n return {\n status: state.status,\n taskResults: state.taskResults,\n auditLog,\n error: state.error,\n durationMs: Date.now() - startTime,\n };\n}\n","import type { TaskDAG, TaskResult } from \"./types.js\";\nimport type { ModelRouter } from \"./model-router.js\";\nimport type { SchedulerCallbacks, SchedulerResult } from \"./scheduler.js\";\nimport { runScheduler } from \"./scheduler.js\";\n\n// ── Public interfaces ───────────────────────────────────────────────\n\nexport interface ReviewLoopOptions {\n /** Max review iterations before giving up (default: 3) */\n maxIterations?: number;\n /** Model router for the review agents */\n router: ModelRouter;\n /** Callbacks (passed through to scheduler) */\n callbacks?: SchedulerCallbacks;\n}\n\nexport interface ReviewResult {\n /** Whether the review loop passed */\n passed: boolean;\n /** Number of iterations it took */\n iterations: number;\n /** Results from the final review */\n reviewResult?: SchedulerResult;\n /** Reason for failure if !passed */\n reason?: string;\n}\n\n// ── buildReviewDAG ──────────────────────────────────────────────────\n\n/**\n * Build a review DAG that evaluates the output of a completed orchestration.\n * The review DAG has: code-review and test-review running in parallel.\n */\nexport function buildReviewDAG(\n originalDAG: TaskDAG,\n taskResults: Map<string, TaskResult>,\n): TaskDAG {\n // Build a formatted context summary from all task results\n let context = \"Review the following completed work:\\n\\n\";\n\n for (const node of originalDAG.nodes) {\n const result = taskResults.get(node.id);\n context += `## Task: ${node.name}\\n`;\n context += `Profile: ${node.profile}\\n`;\n context += `Output: ${result?.output ?? \"(no output)\"}\\n\\n`;\n }\n\n return {\n id: `review-${originalDAG.id}`,\n name: `Review: ${originalDAG.name}`,\n goal: `Review the completed work from \"${originalDAG.name}\"`,\n nodes: [\n {\n id: \"code-review\",\n name: \"Code Review\",\n profile: \"reviewer\",\n tier: \"standard\",\n dependencies: [],\n context,\n },\n {\n id: \"test-review\",\n name: \"Test Review\",\n profile: \"tester\",\n tier: \"standard\",\n dependencies: [],\n context,\n },\n ],\n gates: [],\n };\n}\n\n// ── runReviewLoop ───────────────────────────────────────────────────\n\n/**\n * Run a self-review loop on completed orchestration output.\n *\n * 1. Build a review DAG from the completed task results\n * 2. Run the review DAG via scheduler\n * 3. Check if review passed (all tasks succeed)\n * 4. If passed, return { passed: true }\n * 5. If failed, return { passed: false, reason }\n *\n * This is a single-pass review (not iterative fix-and-review).\n * The iterative pattern is: orchestrate → review → fix → review → ...\n * which is handled at a higher level.\n */\nexport async function runReviewLoop(\n originalDAG: TaskDAG,\n taskResults: Map<string, TaskResult>,\n options: ReviewLoopOptions,\n): Promise<ReviewResult> {\n const reviewDAG = buildReviewDAG(originalDAG, taskResults);\n\n const schedulerResult = await runScheduler(\n reviewDAG,\n options.router,\n {},\n options.callbacks,\n );\n\n if (schedulerResult.status === \"completed\") {\n return {\n passed: true,\n iterations: 1,\n reviewResult: schedulerResult,\n };\n }\n\n return {\n passed: false,\n iterations: 1,\n reason: schedulerResult.error,\n reviewResult: schedulerResult,\n };\n}\n","export type CircuitState = \"closed\" | \"open\" | \"half-open\";\n\nexport interface CircuitBreakerOptions {\n failureThreshold: number;\n resetTimeoutMs: number;\n halfOpenMaxAttempts: number;\n}\n\nconst DEFAULTS: CircuitBreakerOptions = {\n failureThreshold: 3,\n resetTimeoutMs: 60_000,\n halfOpenMaxAttempts: 1,\n};\n\nexport interface CircuitBreaker {\n readonly name: string;\n readonly state: CircuitState;\n readonly failures: number;\n readonly lastFailureAt: number | null;\n\n /** Check if a request can proceed. Returns false if circuit is open. */\n canExecute(): boolean;\n\n /** Record a successful execution. Resets to closed. */\n recordSuccess(): void;\n\n /** Record a failed execution. May trip the circuit to open. */\n recordFailure(): void;\n\n /** Force reset to closed state. */\n reset(): void;\n}\n\nexport function createCircuitBreaker(\n name: string,\n options?: Partial<CircuitBreakerOptions>,\n): CircuitBreaker {\n const opts: CircuitBreakerOptions = { ...DEFAULTS, ...options };\n\n let state: CircuitState = \"closed\";\n let failures = 0;\n let lastFailureAt: number | null = null;\n let openedAt: number | null = null;\n let halfOpenAttempts = 0;\n\n function checkHalfOpen(): void {\n if (\n state === \"open\" &&\n openedAt !== null &&\n Date.now() - openedAt >= opts.resetTimeoutMs\n ) {\n state = \"half-open\";\n halfOpenAttempts = 0;\n }\n }\n\n return {\n get name() {\n return name;\n },\n get state() {\n checkHalfOpen();\n return state;\n },\n get failures() {\n return failures;\n },\n get lastFailureAt() {\n return lastFailureAt;\n },\n\n canExecute(): boolean {\n checkHalfOpen();\n if (state === \"closed\") return true;\n if (state === \"open\") return false;\n // half-open: limited attempts\n if (halfOpenAttempts >= opts.halfOpenMaxAttempts) return false;\n halfOpenAttempts++;\n return true;\n },\n\n recordSuccess(): void {\n if (state === \"half-open\") {\n state = \"closed\";\n failures = 0;\n lastFailureAt = null;\n openedAt = null;\n halfOpenAttempts = 0;\n }\n },\n\n recordFailure(): void {\n failures++;\n lastFailureAt = Date.now();\n if (state === \"half-open\") {\n // back to open\n state = \"open\";\n openedAt = Date.now();\n halfOpenAttempts = 0;\n } else if (failures >= opts.failureThreshold) {\n state = \"open\";\n openedAt = Date.now();\n }\n },\n\n reset(): void {\n state = \"closed\";\n failures = 0;\n lastFailureAt = null;\n openedAt = null;\n halfOpenAttempts = 0;\n },\n };\n}\n\n/**\n * Registry of circuit breakers, one per agent profile.\n */\nexport interface CircuitBreakerRegistry {\n get(name: string): CircuitBreaker;\n getAll(): CircuitBreaker[];\n resetAll(): void;\n /** Get formatted status summary. */\n formatStatus(): string;\n}\n\nexport function createCircuitBreakerRegistry(\n options?: Partial<CircuitBreakerOptions>,\n): CircuitBreakerRegistry {\n const breakers = new Map<string, CircuitBreaker>();\n\n return {\n get(name: string): CircuitBreaker {\n let cb = breakers.get(name);\n if (!cb) {\n cb = createCircuitBreaker(name, options);\n breakers.set(name, cb);\n }\n return cb;\n },\n\n getAll(): CircuitBreaker[] {\n return [...breakers.values()];\n },\n\n resetAll(): void {\n for (const cb of breakers.values()) {\n cb.reset();\n }\n },\n\n formatStatus(): string {\n if (breakers.size === 0) {\n return \"No circuit breakers registered.\";\n }\n const lines = [...breakers.values()].map(\n (cb) =>\n ` ${cb.name}: state=${cb.state} failures=${cb.failures}`,\n );\n return `Circuit breakers (${breakers.size}):\\n${lines.join(\"\\n\")}`;\n },\n };\n}\n","import { readFile, writeFile, mkdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport type {\n TaskDAG,\n TaskResult,\n OrchestrationStatus,\n TaskStatus,\n} from \"./types.js\";\n\n// ── CheckpointData ──────────────────────────────────────────────────────\nexport interface CheckpointData {\n version: number;\n orchestrationId: string;\n dag: TaskDAG;\n status: OrchestrationStatus;\n taskStatuses: Record<string, TaskStatus>;\n taskResults: Record<string, TaskResult>;\n resolvedGates: string[];\n activeGate: string | null;\n startedAt: number;\n updatedAt: number;\n checkpointedAt: number;\n}\n\n/**\n * Serialize orchestration state to a checkpoint.\n */\nexport function createCheckpoint(\n orchestrationId: string,\n dag: TaskDAG,\n status: OrchestrationStatus,\n taskStatuses: Map<string, TaskStatus>,\n taskResults: Map<string, TaskResult>,\n resolvedGates: Set<string>,\n activeGate: string | null,\n startedAt: number,\n): CheckpointData {\n const now = Date.now();\n return {\n version: 1,\n orchestrationId,\n dag,\n status,\n taskStatuses: Object.fromEntries(taskStatuses),\n taskResults: Object.fromEntries(taskResults),\n resolvedGates: [...resolvedGates],\n activeGate,\n startedAt,\n updatedAt: now,\n checkpointedAt: now,\n };\n}\n\n/**\n * Serialize checkpoint to JSON string.\n */\nexport function serializeCheckpoint(checkpoint: CheckpointData): string {\n return JSON.stringify(checkpoint);\n}\n\n/**\n * Deserialize JSON string to checkpoint.\n */\nexport function deserializeCheckpoint(json: string): CheckpointData {\n return JSON.parse(json) as CheckpointData;\n}\n\n/**\n * Save checkpoint to a file.\n * Writes to dir/checkpoint-{orchestrationId}.json.\n * Returns the file path.\n */\nexport async function saveCheckpoint(\n checkpoint: CheckpointData,\n dir: string,\n): Promise<string> {\n await mkdir(dir, { recursive: true });\n const filePath = join(dir, `checkpoint-${checkpoint.orchestrationId}.json`);\n await writeFile(filePath, serializeCheckpoint(checkpoint), \"utf-8\");\n return filePath;\n}\n\n/**\n * Load checkpoint from a file.\n * Returns null if the file does not exist.\n */\nexport async function loadCheckpoint(\n orchestrationId: string,\n dir: string,\n): Promise<CheckpointData | null> {\n const filePath = join(dir, `checkpoint-${orchestrationId}.json`);\n try {\n const json = await readFile(filePath, \"utf-8\");\n return deserializeCheckpoint(json);\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n return null;\n }\n throw err;\n }\n}\n\n/**\n * Restore Maps and Sets from checkpoint data.\n */\nexport function restoreMaps(checkpoint: CheckpointData): {\n taskStatuses: Map<string, TaskStatus>;\n taskResults: Map<string, TaskResult>;\n resolvedGates: Set<string>;\n} {\n return {\n taskStatuses: new Map(Object.entries(checkpoint.taskStatuses)),\n taskResults: new Map(Object.entries(checkpoint.taskResults)),\n resolvedGates: new Set(checkpoint.resolvedGates),\n };\n}\n","import type { ModelTier } from \"./types.js\";\n\n// ── Interfaces ──────────────────────────────────────────────────────\n\nexport interface TierCost {\n inputTokensPerDollar: number;\n outputTokensPerDollar: number;\n}\n\nexport interface CostEntry {\n tier: ModelTier;\n taskId: string;\n inputTokens: number;\n outputTokens: number;\n estimatedCost: number;\n timestamp: number;\n}\n\nexport interface CostTracker {\n /** Record token usage for a task. */\n record(\n taskId: string,\n tier: ModelTier,\n inputTokens: number,\n outputTokens: number,\n ): void;\n\n /** Get total estimated cost. */\n totalCost(): number;\n\n /** Get cost breakdown by tier. */\n costByTier(): Record<ModelTier, number>;\n\n /** Get all entries. */\n entries(): CostEntry[];\n\n /** Check if budget is exceeded. */\n isOverBudget(): boolean;\n\n /** Get remaining budget (null if no budget set). */\n remainingBudget(): number | null;\n\n /** Format cost summary. */\n formatSummary(): string;\n}\n\nexport interface CostTrackerOptions {\n /** Budget limit in dollars (null = unlimited). */\n budgetLimit?: number | null;\n /** Cost rates per tier (defaults provided). */\n tierCosts?: Partial<Record<ModelTier, TierCost>>;\n}\n\n// ── Default rates (approximate Claude pricing) ──────────────────────\n\nexport const DEFAULT_TIER_COSTS: Record<ModelTier, TierCost> = {\n fast: {\n inputTokensPerDollar: 5_000_000,\n outputTokensPerDollar: 1_250_000,\n }, // ~$0.20/$0.80 per 1M\n standard: {\n inputTokensPerDollar: 333_333,\n outputTokensPerDollar: 66_667,\n }, // ~$3/$15 per 1M\n advanced: {\n inputTokensPerDollar: 66_667,\n outputTokensPerDollar: 13_333,\n }, // ~$15/$75 per 1M\n};\n\n// ── Factory ─────────────────────────────────────────────────────────\n\nexport function createCostTracker(options?: CostTrackerOptions): CostTracker {\n const budgetLimit = options?.budgetLimit ?? null;\n const tierCosts: Record<ModelTier, TierCost> = {\n ...DEFAULT_TIER_COSTS,\n ...options?.tierCosts,\n };\n\n const _entries: CostEntry[] = [];\n\n function estimateCost(\n tier: ModelTier,\n inputTokens: number,\n outputTokens: number,\n ): number {\n const rates = tierCosts[tier];\n return (\n inputTokens / rates.inputTokensPerDollar +\n outputTokens / rates.outputTokensPerDollar\n );\n }\n\n function record(\n taskId: string,\n tier: ModelTier,\n inputTokens: number,\n outputTokens: number,\n ): void {\n _entries.push({\n tier,\n taskId,\n inputTokens,\n outputTokens,\n estimatedCost: estimateCost(tier, inputTokens, outputTokens),\n timestamp: Date.now(),\n });\n }\n\n function totalCost(): number {\n return _entries.reduce((sum, e) => sum + e.estimatedCost, 0);\n }\n\n function costByTier(): Record<ModelTier, number> {\n const result: Record<ModelTier, number> = {\n fast: 0,\n standard: 0,\n advanced: 0,\n };\n for (const entry of _entries) {\n result[entry.tier] += entry.estimatedCost;\n }\n return result;\n }\n\n function entries(): CostEntry[] {\n return [..._entries];\n }\n\n function isOverBudget(): boolean {\n if (budgetLimit === null) return false;\n return totalCost() > budgetLimit;\n }\n\n function remainingBudget(): number | null {\n if (budgetLimit === null) return null;\n return budgetLimit - totalCost();\n }\n\n function formatSummary(): string {\n const total = totalCost();\n const byTier = costByTier();\n const lines: string[] = [];\n\n lines.push(`Total: $${total.toFixed(4)}`);\n\n for (const tier of [\"fast\", \"standard\", \"advanced\"] as ModelTier[]) {\n if (byTier[tier] > 0) {\n lines.push(` ${tier}: $${byTier[tier].toFixed(4)}`);\n }\n }\n\n if (budgetLimit !== null) {\n const remaining = remainingBudget()!;\n lines.push(\n `Budget: $${budgetLimit.toFixed(2)} | Remaining: $${remaining.toFixed(4)}`,\n );\n }\n\n lines.push(`Entries: ${_entries.length}`);\n\n return lines.join(\"\\n\");\n }\n\n return {\n record,\n totalCost,\n costByTier,\n entries,\n isOverBudget,\n remainingBudget,\n formatSummary,\n };\n}\n","import type { TaskDAG, TaskNode, ModelTier } from \"./types.js\";\n\n// ── Types ──────────────────────────────────────────────────────────\n\nexport type PolicySeverity = \"error\" | \"warning\" | \"info\";\n\nexport interface PolicyViolation {\n rule: string;\n severity: PolicySeverity;\n message: string;\n nodeId?: string;\n}\n\nexport interface PolicyResult {\n passed: boolean;\n violations: PolicyViolation[];\n}\n\nexport interface PolicyRule {\n name: string;\n description: string;\n severity: PolicySeverity;\n check: (dag: TaskDAG) => PolicyViolation[];\n}\n\n// ── Built-in policy rules ──────────────────────────────────────────\n\nconst maxTaskCount: PolicyRule = {\n name: \"max-task-count\",\n description: \"DAG has more than 20 tasks\",\n severity: \"warning\",\n check: (dag) => {\n if (dag.nodes.length > 20) {\n return [\n {\n rule: \"max-task-count\",\n severity: \"warning\",\n message: `DAG has ${dag.nodes.length} tasks (limit: 20)`,\n },\n ];\n }\n return [];\n },\n};\n\nconst requiresReview: PolicyRule = {\n name: \"requires-review\",\n description: 'No node with profile \"reviewer\" exists',\n severity: \"warning\",\n check: (dag) => {\n const hasReviewer = dag.nodes.some((n) => n.profile === \"reviewer\");\n if (!hasReviewer) {\n return [\n {\n rule: \"requires-review\",\n severity: \"warning\",\n message: \"DAG has no reviewer node — consider adding a code review step\",\n },\n ];\n }\n return [];\n },\n};\n\nconst requiresTesting: PolicyRule = {\n name: \"requires-testing\",\n description: 'No node with profile \"tester\" exists',\n severity: \"warning\",\n check: (dag) => {\n const hasTester = dag.nodes.some((n) => n.profile === \"tester\");\n if (!hasTester) {\n return [\n {\n rule: \"requires-testing\",\n severity: \"warning\",\n message: \"DAG has no tester node — consider adding a testing step\",\n },\n ];\n }\n return [];\n },\n};\n\nconst noOrphanNodes: PolicyRule = {\n name: \"no-orphan-nodes\",\n description: \"Every node is either a root or has valid dependencies\",\n severity: \"error\",\n check: (dag) => {\n const nodeIds = new Set(dag.nodes.map((n) => n.id));\n const violations: PolicyViolation[] = [];\n for (const node of dag.nodes) {\n for (const dep of node.dependencies) {\n if (!nodeIds.has(dep)) {\n violations.push({\n rule: \"no-orphan-nodes\",\n severity: \"error\",\n message: `Node \"${node.id}\" depends on \"${dep}\" which does not exist`,\n nodeId: node.id,\n });\n }\n }\n }\n return violations;\n },\n};\n\nconst approvalBeforeDeploy: PolicyRule = {\n name: \"approval-before-deploy\",\n description:\n \"If any node name contains 'deploy' or 'release', an approval gate should exist\",\n severity: \"warning\",\n check: (dag) => {\n const deployNodes = dag.nodes.filter((n) => {\n const lower = n.name.toLowerCase();\n return lower.includes(\"deploy\") || lower.includes(\"release\");\n });\n if (deployNodes.length === 0) return [];\n\n const hasApprovalGate = dag.gates.some((g) => g.type === \"approval\");\n if (hasApprovalGate) return [];\n\n return deployNodes.map((n) => ({\n rule: \"approval-before-deploy\",\n severity: \"warning\" as const,\n message: `Node \"${n.name}\" looks like a deploy/release step but no approval gate exists`,\n nodeId: n.id,\n }));\n },\n};\n\nconst noAdvancedWithoutJustification: PolicyRule = {\n name: \"no-advanced-without-justification\",\n description: 'Nodes with tier \"advanced\" flagged for cost awareness',\n severity: \"info\",\n check: (dag) =>\n dag.nodes\n .filter((n) => n.tier === \"advanced\")\n .map((n) => ({\n rule: \"no-advanced-without-justification\",\n severity: \"info\" as const,\n message: `Node \"${n.id}\" uses advanced tier — ensure this is justified for cost`,\n nodeId: n.id,\n })),\n};\n\nconst maxParallelDepth: PolicyRule = {\n name: \"max-parallel-depth\",\n description: \"DAG has more than 5 levels of depth\",\n severity: \"warning\",\n check: (dag) => {\n // Compute max depth via topological traversal\n const nodeIds = new Set(dag.nodes.map((n) => n.id));\n const depthMap = new Map<string, number>();\n\n // Build adjacency: for each node, depth = max(depth of deps) + 1\n // Handle missing deps gracefully (they are caught by no-orphan-nodes)\n function getDepth(node: TaskNode, visited: Set<string>): number {\n if (depthMap.has(node.id)) return depthMap.get(node.id)!;\n if (visited.has(node.id)) return 0; // cycle guard\n visited.add(node.id);\n\n let maxDep = 0;\n for (const depId of node.dependencies) {\n const depNode = dag.nodes.find((n) => n.id === depId);\n if (depNode) {\n maxDep = Math.max(maxDep, getDepth(depNode, visited) + 1);\n }\n }\n depthMap.set(node.id, maxDep);\n return maxDep;\n }\n\n for (const node of dag.nodes) {\n getDepth(node, new Set());\n }\n\n const maxDepth = Math.max(0, ...depthMap.values());\n if (maxDepth > 5) {\n return [\n {\n rule: \"max-parallel-depth\",\n severity: \"warning\",\n message: `DAG depth is ${maxDepth} (limit: 5)`,\n },\n ];\n }\n return [];\n },\n};\n\n// ── Public API ─────────────────────────────────────────────────────\n\n/**\n * Create built-in policy rules.\n */\nexport function getDefaultPolicies(): PolicyRule[] {\n return [\n maxTaskCount,\n requiresReview,\n requiresTesting,\n noOrphanNodes,\n approvalBeforeDeploy,\n noAdvancedWithoutJustification,\n maxParallelDepth,\n ];\n}\n\n/**\n * Evaluate a DAG against a set of policy rules.\n */\nexport function evaluatePolicy(\n dag: TaskDAG,\n rules?: PolicyRule[],\n): PolicyResult {\n const effectiveRules = rules ?? getDefaultPolicies();\n const violations: PolicyViolation[] = [];\n\n for (const rule of effectiveRules) {\n violations.push(...rule.check(dag));\n }\n\n const hasErrors = violations.some((v) => v.severity === \"error\");\n\n return {\n passed: !hasErrors,\n violations,\n };\n}\n\n/**\n * Format policy result for display.\n */\nexport function formatPolicyResult(result: PolicyResult): string {\n const lines: string[] = [];\n const status = result.passed ? \"PASS\" : \"FAIL\";\n lines.push(`Policy check: ${status}`);\n\n if (result.violations.length === 0) {\n lines.push(\" No violations found.\");\n return lines.join(\"\\n\");\n }\n\n for (const v of result.violations) {\n const nodeLabel = v.nodeId ? ` [${v.nodeId}]` : \"\";\n lines.push(` [${v.severity}] ${v.rule}${nodeLabel}: ${v.message}`);\n }\n\n return lines.join(\"\\n\");\n}\n","import type { TaskDAG, ModelTier } from \"./types.js\";\nimport type { ModelRouter } from \"./model-router.js\";\nimport type { SchedulerCallbacks, SchedulerResult } from \"./scheduler.js\";\nimport type { CircuitBreakerRegistry } from \"./circuit-breaker.js\";\nimport type { CostTracker } from \"./cost-tracker.js\";\nimport type { ReviewResult } from \"./review-loop.js\";\nimport type { PolicyResult } from \"./policy.js\";\n\nimport { runScheduler } from \"./scheduler.js\";\nimport { evaluatePolicy } from \"./policy.js\";\nimport { createCircuitBreakerRegistry } from \"./circuit-breaker.js\";\nimport { createCostTracker } from \"./cost-tracker.js\";\nimport { runReviewLoop } from \"./review-loop.js\";\nimport { createAuditLog } from \"./audit.js\";\n\n// ── Options ─────────────────────────────────────────────────────────\n\nexport interface FullOrchestrationOptions {\n router: ModelRouter;\n maxParallelTasks?: number;\n\n // Enterprise features (all optional — graceful degradation)\n enableCircuitBreaker?: boolean;\n enableCostTracking?: boolean;\n enableCheckpoints?: boolean;\n enablePolicyCheck?: boolean;\n enableSelfReview?: boolean;\n\n // Budget limit in dollars (null = unlimited)\n budgetLimit?: number | null;\n\n // Checkpoint directory\n checkpointDir?: string;\n\n // Callbacks\n callbacks?: SchedulerCallbacks;\n}\n\n// ── Result ──────────────────────────────────────────────────────────\n\nexport interface FullOrchestrationResult {\n // Core result\n scheduler: SchedulerResult;\n\n // Enterprise results (undefined if feature disabled)\n policy?: PolicyResult;\n review?: ReviewResult;\n costSummary?: string;\n circuitBreakerStatus?: string;\n checkpointPath?: string;\n\n // Summary\n success: boolean;\n durationMs: number;\n}\n\n// ── Runner ──────────────────────────────────────────────────────────\n\n/**\n * Run a full orchestration with all enterprise features wired in.\n *\n * Flow:\n * 1. Policy check — evaluate DAG against rules. If errors, abort.\n * 2. Initialize circuit breaker registry + cost tracker\n * 3. Run scheduler with wrapped callbacks that:\n * a. Check circuit breaker before each task\n * b. Record cost after each task\n * c. Record circuit breaker success/failure\n * d. Save checkpoint after each completed task\n * 4. If enableSelfReview and scheduler completed, run review loop\n * 5. Return consolidated result\n */\nexport async function runOrchestrationFull(\n dag: TaskDAG,\n options: FullOrchestrationOptions,\n): Promise<FullOrchestrationResult> {\n const startTime = Date.now();\n\n // 1. Policy check\n let policyResult: PolicyResult | undefined;\n if (options.enablePolicyCheck) {\n policyResult = evaluatePolicy(dag);\n if (!policyResult.passed) {\n const errorMessages = policyResult.violations\n .filter((v) => v.severity === \"error\")\n .map((v) => v.message)\n .join(\"; \");\n return {\n scheduler: {\n status: \"failed\",\n taskResults: new Map(),\n auditLog: createAuditLog(dag.id),\n error: `Policy check failed: ${errorMessages}`,\n durationMs: Date.now() - startTime,\n },\n policy: policyResult,\n success: false,\n durationMs: Date.now() - startTime,\n };\n }\n }\n\n // 2. Initialize enterprise features\n const circuitBreakers: CircuitBreakerRegistry | undefined =\n options.enableCircuitBreaker ? createCircuitBreakerRegistry() : undefined;\n const costTracker: CostTracker | undefined =\n options.enableCostTracking\n ? createCostTracker({ budgetLimit: options.budgetLimit })\n : undefined;\n\n // 3. Wrap callbacks\n const wrappedCallbacks: SchedulerCallbacks = {\n ...options.callbacks,\n\n onTaskStarted: async (nodeId: string, nodeName: string) => {\n // Check circuit breaker\n const node = dag.nodes.find((n) => n.id === nodeId);\n if (circuitBreakers && node) {\n circuitBreakers.get(node.profile).canExecute();\n }\n await options.callbacks?.onTaskStarted?.(nodeId, nodeName);\n },\n\n onTaskCompleted: async (nodeId: string, nodeName: string, result) => {\n const node = dag.nodes.find((n) => n.id === nodeId);\n if (node) {\n // Record circuit breaker success\n circuitBreakers?.get(node.profile).recordSuccess();\n // Record cost (estimate tokens from turns)\n costTracker?.record(nodeId, node.tier, result.turns * 500, result.turns * 200);\n }\n await options.callbacks?.onTaskCompleted?.(nodeId, nodeName, result);\n },\n\n onTaskFailed: async (nodeId: string, nodeName: string, error: string) => {\n const node = dag.nodes.find((n) => n.id === nodeId);\n if (node) {\n circuitBreakers?.get(node.profile).recordFailure();\n }\n await options.callbacks?.onTaskFailed?.(nodeId, nodeName, error);\n },\n };\n\n // 4. Run scheduler\n const schedulerResult = await runScheduler(dag, options.router, {\n maxParallelTasks: options.maxParallelTasks,\n }, wrappedCallbacks);\n\n // 5. Self-review (if enabled and scheduler completed)\n let reviewResult: ReviewResult | undefined;\n if (options.enableSelfReview && schedulerResult.status === \"completed\") {\n reviewResult = await runReviewLoop(dag, schedulerResult.taskResults, {\n router: options.router,\n });\n }\n\n // 6. Build result\n const success =\n schedulerResult.status === \"completed\" &&\n (reviewResult ? reviewResult.passed : true) &&\n (costTracker ? !costTracker.isOverBudget() : true);\n\n return {\n scheduler: schedulerResult,\n policy: policyResult,\n review: reviewResult,\n costSummary: costTracker?.formatSummary(),\n circuitBreakerStatus: circuitBreakers?.formatStatus(),\n success,\n durationMs: Date.now() - startTime,\n };\n}\n","import type { LLMClient } from \"../llm/types.js\";\nimport type { TaskDAG } from \"./types.js\";\nimport type { ModelRouter } from \"./model-router.js\";\nimport type { FullOrchestrationResult } from \"./runner.js\";\nimport type { SchedulerCallbacks } from \"./scheduler.js\";\n\nimport { decomposeRequirement } from \"./decompose.js\";\nimport { getTemplate } from \"./templates/index.js\";\nimport { runOrchestrationFull } from \"./runner.js\";\nimport { classifyProject } from \"../project/detector.js\";\nimport { scanStack } from \"../dev/stack-detector.js\";\nimport {\n ensureAllProfilesInstalled,\n getProfilesDir,\n} from \"../profiles/auto-install.js\";\n\n// ── DAG Display (inlined to avoid circular import with index.ts) ────\n\nfunction formatDAGForDisplay(dag: TaskDAG): string {\n const lines: string[] = [];\n lines.push(`## ${dag.name}`);\n lines.push(`**Goal:** ${dag.goal}`);\n lines.push(`**Tasks:** ${dag.nodes.length} | **Gates:** ${dag.gates.length}`);\n lines.push(\"\");\n for (const node of dag.nodes) {\n const depLabel =\n node.dependencies.length === 0\n ? \"(root)\"\n : `(after: ${node.dependencies.join(\", \")})`;\n lines.push(`- **${node.name}** \\u2192 ${node.profile} [${node.tier}] ${depLabel}`);\n }\n for (const gate of dag.gates) {\n lines.push(`- \\uD83D\\uDD12 **${gate.name}** [${gate.type}]`);\n }\n return lines.join(\"\\n\");\n}\n\n// ── Options ─────────────────────────────────────────────────────────\n\nexport interface SmartOrchestrationOptions {\n /** The requirement to orchestrate */\n requirement: string;\n /** LLM client for decomposition */\n client: LLMClient;\n /** Model router for task execution */\n router: ModelRouter;\n /** Optional: project path for auto-classification */\n projectPath?: string;\n /** Optional: force a specific template name */\n templateName?: string;\n /** Enable enterprise features */\n enablePolicyCheck?: boolean;\n enableSelfReview?: boolean;\n enableCostTracking?: boolean;\n budgetLimit?: number | null;\n /** Callbacks */\n callbacks?: SchedulerCallbacks;\n}\n\n// ── Result ──────────────────────────────────────────────────────────\n\nexport interface SmartOrchestrationResult {\n /** The DAG that was generated or selected */\n dag: TaskDAG;\n /** Project type detected (if projectPath provided) */\n projectType?: string;\n /** Template used (if any) */\n templateUsed?: string;\n /** Full orchestration result */\n orchestration: FullOrchestrationResult;\n /** Human-readable summary */\n summary: string;\n}\n\n// ── Smart Orchestration Pipeline ────────────────────────────────────\n\n/**\n * Smart orchestration pipeline:\n * 1. Ensure orchestrator profiles are installed\n * 2. If projectPath → classify project, get recommended template\n * 3. If templateName → use that template to build DAG\n * 4. Otherwise → decompose requirement via LLM\n * 5. Run full orchestration (policy + scheduler + circuit breakers + cost + review)\n * 6. Return consolidated result with summary\n */\nexport async function smartOrchestrate(\n options: SmartOrchestrationOptions,\n): Promise<SmartOrchestrationResult> {\n // 1. Auto-install profiles\n ensureAllProfilesInstalled(getProfilesDir());\n\n // 2. Detect project type if path given and no explicit template\n let projectType: string | undefined;\n let templateName = options.templateName;\n\n if (options.projectPath && !templateName) {\n const stack = scanStack(options.projectPath);\n const classification = classifyProject(stack);\n projectType = classification.type;\n templateName = classification.suggestedTemplate;\n }\n\n // 3. Build DAG — template if available, otherwise LLM decomposition\n let dag: TaskDAG;\n if (templateName) {\n const templateFn = getTemplate(templateName);\n if (templateFn) {\n dag = templateFn({ name: \"Orchestration\", goal: options.requirement });\n } else {\n // Template not found — fall back to LLM\n dag = await decomposeRequirement(options.requirement, options.client);\n templateName = undefined;\n }\n } else {\n dag = await decomposeRequirement(options.requirement, options.client);\n }\n\n // 4. Run full orchestration\n const orchestration = await runOrchestrationFull(dag, {\n router: options.router,\n enablePolicyCheck: options.enablePolicyCheck,\n enableSelfReview: options.enableSelfReview,\n enableCostTracking: options.enableCostTracking,\n budgetLimit: options.budgetLimit,\n callbacks: options.callbacks,\n });\n\n // 5. Build summary\n const summary = formatSmartResult({\n dag,\n projectType,\n templateUsed: templateName,\n orchestration,\n summary: \"\",\n });\n\n return { dag, projectType, templateUsed: templateName, orchestration, summary };\n}\n\n// ── Formatting ──────────────────────────────────────────────────────\n\n/**\n * Format a SmartOrchestrationResult for CLI display.\n */\nexport function formatSmartResult(result: SmartOrchestrationResult): string {\n const lines: string[] = [];\n\n if (result.projectType) {\n lines.push(`Project type: ${result.projectType}`);\n }\n if (result.templateUsed) {\n lines.push(`Template: ${result.templateUsed}`);\n }\n\n lines.push(\"\");\n lines.push(formatDAGForDisplay(result.dag));\n lines.push(\"\");\n\n const orch = result.orchestration;\n lines.push(\n `Status: ${orch.success ? \"completed\" : \"failed\"} (${orch.durationMs}ms)`,\n );\n\n if (orch.policy && !orch.policy.passed) {\n const errorCount = orch.policy.violations.filter(\n (v) => v.severity === \"error\",\n ).length;\n lines.push(\n `Policy: FAILED — ${errorCount} error${errorCount !== 1 ? \"s\" : \"\"}`,\n );\n }\n if (orch.review) {\n lines.push(`Review: ${orch.review.passed ? \"passed\" : \"failed\"}`);\n }\n if (orch.costSummary) {\n lines.push(`Cost: ${orch.costSummary}`);\n }\n\n return lines.join(\"\\n\");\n}\n","import type { TaskDAG, TaskNode, PhaseGate } from \"../types.js\";\nimport { validateDAG } from \"../dag.js\";\n\n// ── Template Options ───────────────────────────────────────────────\n\nexport interface TemplateOptions {\n /** Project/feature name */\n name: string;\n /** Goal description */\n goal: string;\n /** Include approval gate before final phase */\n requireApproval?: boolean;\n}\n\n// ── Helpers ────────────────────────────────────────────────────────\n\nfunction node(\n id: string,\n profile: string,\n tier: TaskNode[\"tier\"],\n deps: string[] = [],\n): TaskNode {\n return {\n id,\n name: id.charAt(0).toUpperCase() + id.slice(1),\n profile,\n tier,\n dependencies: deps,\n };\n}\n\nfunction approvalGate(\n id: string,\n afterNodes: string[],\n beforeNodes: string[],\n): PhaseGate {\n return {\n id,\n name: `Approval: ${id}`,\n type: \"approval\",\n afterNodes,\n beforeNodes,\n };\n}\n\n// ── Templates ──────────────────────────────────────────────────────\n\n/**\n * Full feature development: architect → parallel coders → review → test → merge\n *\n * design (architect, advanced) → implement (coder) → review + test (parallel) → finalize\n * Optional approval gate between [review, test] and [finalize].\n */\nexport function fullFeatureTemplate(options: TemplateOptions): TaskDAG {\n const gates: PhaseGate[] = [];\n\n if (options.requireApproval) {\n gates.push(approvalGate(\"approval\", [\"review\", \"test\"], [\"finalize\"]));\n }\n\n const dag: TaskDAG = {\n id: `full-feature-${options.name}`,\n name: `Full Feature: ${options.name}`,\n goal: options.goal,\n nodes: [\n node(\"design\", \"architect\", \"advanced\"),\n node(\"implement\", \"coder\", \"standard\", [\"design\"]),\n node(\"review\", \"reviewer\", \"standard\", [\"implement\"]),\n node(\"test\", \"tester\", \"standard\", [\"implement\"]),\n node(\"finalize\", \"coder\", \"standard\", [\"review\", \"test\"]),\n ],\n gates,\n };\n\n validateDAG(dag);\n return dag;\n}\n\n/**\n * Bug fix: reproduce → fix → test → review\n *\n * With approval: adds a verify step gated behind review.\n */\nexport function bugFixTemplate(options: TemplateOptions): TaskDAG {\n const nodes: TaskNode[] = [\n node(\"reproduce\", \"tester\", \"standard\"),\n node(\"fix\", \"coder\", \"standard\", [\"reproduce\"]),\n node(\"test\", \"tester\", \"standard\", [\"fix\"]),\n node(\"review\", \"reviewer\", \"standard\", [\"test\"]),\n ];\n\n const gates: PhaseGate[] = [];\n\n if (options.requireApproval) {\n nodes.push(node(\"verify\", \"tester\", \"standard\", [\"review\"]));\n gates.push(approvalGate(\"approval\", [\"review\"], [\"verify\"]));\n }\n\n const dag: TaskDAG = {\n id: `bug-fix-${options.name}`,\n name: `Bug Fix: ${options.name}`,\n goal: options.goal,\n nodes,\n gates,\n };\n\n validateDAG(dag);\n return dag;\n}\n\n/**\n * Security audit: scan → triage → fix → rescan → review\n *\n * With approval: gates the fix step behind triage approval.\n */\nexport function securityAuditTemplate(options: TemplateOptions): TaskDAG {\n const gates: PhaseGate[] = [];\n\n if (options.requireApproval) {\n gates.push(approvalGate(\"approval\", [\"triage\"], [\"fix\"]));\n }\n\n const dag: TaskDAG = {\n id: `security-audit-${options.name}`,\n name: `Security Audit: ${options.name}`,\n goal: options.goal,\n nodes: [\n node(\"scan\", \"security\", \"standard\"),\n node(\"triage\", \"security\", \"standard\", [\"scan\"]),\n node(\"fix\", \"coder\", \"standard\", [\"triage\"]),\n node(\"rescan\", \"security\", \"standard\", [\"fix\"]),\n node(\"review\", \"reviewer\", \"standard\", [\"rescan\"]),\n ],\n gates,\n };\n\n validateDAG(dag);\n return dag;\n}\n\n// ── Registry ───────────────────────────────────────────────────────\n\nconst TEMPLATES: Record<string, (options: TemplateOptions) => TaskDAG> = {\n \"full-feature\": fullFeatureTemplate,\n \"bug-fix\": bugFixTemplate,\n \"security-audit\": securityAuditTemplate,\n};\n\n/**\n * Get a template by name.\n */\nexport function getTemplate(\n name: string,\n): ((options: TemplateOptions) => TaskDAG) | undefined {\n return TEMPLATES[name];\n}\n\n/**\n * List available template names.\n */\nexport function listTemplates(): string[] {\n return Object.keys(TEMPLATES);\n}\n","import type { StackProfile } from \"../dev/stack-detector.js\";\n\nexport type ProjectType =\n | \"web-frontend\"\n | \"web-fullstack\"\n | \"api-backend\"\n | \"mobile\"\n | \"cli-tool\"\n | \"library\"\n | \"ml-data\"\n | \"monorepo\"\n | \"unknown\";\n\nexport interface ProjectClassification {\n type: ProjectType;\n confidence: number;\n suggestedTemplate: string;\n suggestedProfiles: string[];\n description: string;\n}\n\nconst FRONTEND_FRAMEWORKS = new Set([\"react\", \"vue\", \"svelte\"]);\nconst FULLSTACK_FRAMEWORKS = new Set([\"next\", \"nuxt\", \"remix\"]);\nconst BACKEND_FRAMEWORKS = new Set([\n \"express\", \"fastify\", \"hono\", \"nestjs\",\n \"fiber\", \"gin\", \"chi\", \"echo\",\n \"fastapi\", \"django\", \"flask\",\n]);\nconst ML_FRAMEWORKS = new Set([\"torch\", \"tensorflow\", \"sklearn\", \"pytorch\", \"pandas\", \"numpy\"]);\nconst WEB_FRAMEWORKS = new Set([\n ...FRONTEND_FRAMEWORKS, ...FULLSTACK_FRAMEWORKS, ...BACKEND_FRAMEWORKS,\n]);\n\nconst TEMPLATE_MAP: Record<ProjectType, string> = {\n \"web-frontend\": \"full-feature\",\n \"web-fullstack\": \"full-feature\",\n \"api-backend\": \"full-feature\",\n mobile: \"full-feature\",\n \"cli-tool\": \"bug-fix\",\n library: \"full-feature\",\n \"ml-data\": \"full-feature\",\n monorepo: \"full-feature\",\n unknown: \"full-feature\",\n};\n\nconst PROFILE_MAP: Record<ProjectType, string[]> = {\n \"web-frontend\": [\"architect\", \"coder\", \"tester\", \"reviewer\"],\n \"web-fullstack\": [\"architect\", \"coder\", \"security\", \"tester\", \"reviewer\"],\n \"api-backend\": [\"architect\", \"coder\", \"security\", \"tester\", \"reviewer\"],\n mobile: [\"architect\", \"coder\", \"tester\", \"reviewer\"],\n \"cli-tool\": [\"coder\", \"tester\", \"reviewer\"],\n library: [\"architect\", \"coder\", \"tester\", \"reviewer\"],\n \"ml-data\": [\"architect\", \"coder\", \"tester\"],\n monorepo: [\"architect\", \"coder\", \"security\", \"tester\", \"reviewer\"],\n unknown: [\"coder\", \"tester\", \"reviewer\"],\n};\n\nconst DESCRIPTION_MAP: Record<ProjectType, string> = {\n \"web-frontend\": \"Frontend web application\",\n \"web-fullstack\": \"Full-stack web application with database\",\n \"api-backend\": \"API/backend service\",\n mobile: \"Mobile application\",\n \"cli-tool\": \"Command-line tool\",\n library: \"Reusable library/package\",\n \"ml-data\": \"Machine learning / data science project\",\n monorepo: \"Monorepo with multiple packages\",\n unknown: \"Unknown project type\",\n};\n\nfunction hasAny(items: string[], set: Set<string>): boolean {\n return items.some((i) => set.has(i));\n}\n\nexport function classifyProject(stack: StackProfile): ProjectClassification {\n let type: ProjectType;\n let confidence: number;\n\n if (stack.isMonorepo) {\n type = \"monorepo\";\n confidence = 0.9;\n } else if (hasAny(stack.frameworks, new Set([\"flutter\"])) || stack.languages.includes(\"dart\")) {\n type = \"mobile\";\n confidence = 0.9;\n } else if (hasAny(stack.frameworks, FULLSTACK_FRAMEWORKS) && stack.databases.length > 0) {\n type = \"web-fullstack\";\n confidence = 0.9;\n } else if (hasAny(stack.frameworks, BACKEND_FRAMEWORKS)) {\n type = \"api-backend\";\n confidence = 0.9;\n } else if (hasAny(stack.frameworks, FRONTEND_FRAMEWORKS)) {\n type = \"web-frontend\";\n confidence = 0.85;\n } else if (stack.languages.includes(\"python\") && !hasAny(stack.frameworks, WEB_FRAMEWORKS)) {\n if (hasAny(stack.frameworks, ML_FRAMEWORKS)) {\n type = \"ml-data\";\n confidence = 0.8;\n } else {\n type = \"cli-tool\";\n confidence = 0.6;\n }\n } else if (stack.languages.length > 0 && stack.frameworks.length === 0) {\n type = \"library\";\n confidence = 0.6;\n } else if (stack.languages.length === 0 && stack.frameworks.length === 0) {\n type = \"unknown\";\n confidence = 0.3;\n } else {\n type = \"unknown\";\n confidence = 0.3;\n }\n\n return {\n type,\n confidence,\n suggestedTemplate: TEMPLATE_MAP[type],\n suggestedProfiles: PROFILE_MAP[type],\n description: DESCRIPTION_MAP[type],\n };\n}\n\nexport function getRecommendedTemplate(type: ProjectType): string {\n return TEMPLATE_MAP[type] ?? TEMPLATE_MAP.unknown;\n}\n\nexport function getRecommendedProfiles(type: ProjectType): string[] {\n return PROFILE_MAP[type] ?? PROFILE_MAP.unknown;\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport os from \"node:os\";\n\nimport { getOrchestratorProfile, ORCHESTRATOR_PROFILES } from \"./orchestrator-profiles.js\";\n\n/**\n * Check if an orchestrator profile is installed.\n * A profile is considered installed if {profilesDir}/{profileName}/core.md exists.\n */\nexport function isProfileInstalled(profileName: string, profilesDir: string): boolean {\n return fs.existsSync(path.join(profilesDir, profileName, \"core.md\"));\n}\n\n/**\n * Install a single orchestrator profile.\n * Gets the profile from getOrchestratorProfile(), creates the directory,\n * writes core.md and optionally rules.md.\n *\n * @returns true if installed, false if profile not found\n */\nexport function installProfile(profileName: string, profilesDir: string): boolean {\n const profile = getOrchestratorProfile(profileName);\n if (!profile) return false;\n\n const profileDir = path.join(profilesDir, profileName);\n fs.mkdirSync(profileDir, { recursive: true });\n\n fs.writeFileSync(path.join(profileDir, \"core.md\"), profile.core, \"utf-8\");\n\n if (profile.rules) {\n fs.writeFileSync(path.join(profileDir, \"rules.md\"), profile.rules, \"utf-8\");\n }\n\n return true;\n}\n\n/**\n * Ensure all orchestrator profiles are installed.\n * Skips profiles that already have core.md present.\n *\n * @returns summary of which profiles were installed vs skipped\n */\nexport function ensureAllProfilesInstalled(profilesDir: string): {\n installed: string[];\n skipped: string[];\n} {\n const installed: string[] = [];\n const skipped: string[] = [];\n\n for (const profile of ORCHESTRATOR_PROFILES) {\n if (isProfileInstalled(profile.name, profilesDir)) {\n skipped.push(profile.name);\n } else {\n installProfile(profile.name, profilesDir);\n installed.push(profile.name);\n }\n }\n\n return { installed, skipped };\n}\n\n/**\n * Auto-install a profile if it's an orchestrator profile and not yet installed.\n * Call this before delegation.\n *\n * @returns true if profile is now ready (already was or just installed)\n * @returns false if it's not a known orchestrator profile\n */\nexport function ensureProfileReady(profileName: string, profilesDir: string): boolean {\n const profile = getOrchestratorProfile(profileName);\n if (!profile) return false;\n\n if (!isProfileInstalled(profileName, profilesDir)) {\n installProfile(profileName, profilesDir);\n }\n\n return true;\n}\n\n/**\n * Get the default profiles directory.\n * Respects ACORE_HOME env var, otherwise uses ~/.acore/profiles.\n */\nexport function getProfilesDir(): string {\n const acoreHome = process.env.ACORE_HOME;\n if (acoreHome) {\n return path.join(acoreHome, \"profiles\");\n }\n return path.join(os.homedir(), \".acore\", \"profiles\");\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport os from \"node:os\";\nimport pc from \"picocolors\";\nimport type { LLMClient, ToolDefinition } from \"./llm/types.js\";\nimport type { McpManager } from \"./mcp/client.js\";\nimport { delegateTask, delegateParallel, delegatePipeline, type DelegationResult } from \"./delegate.js\";\nimport { listProfiles } from \"./prompt.js\";\nimport { log } from \"./logger.js\";\n\n// --- Types ---\n\nexport interface TeamMember {\n profile: string;\n role: string;\n}\n\nexport interface Team {\n name: string;\n goal: string;\n coordinator: string; // profile name or \"default\" for main agent\n members: TeamMember[];\n workflow: \"pipeline\" | \"parallel\" | \"coordinator\";\n}\n\nexport interface TeamRunResult {\n team: string;\n task: string;\n workflow: string;\n results: DelegationResult[];\n finalOutput: string;\n success: boolean;\n}\n\n// --- Storage ---\n\nfunction getTeamsDir(): string {\n return path.join(os.homedir(), \".acore\", \"teams\");\n}\n\nfunction ensureTeamsDir(): string {\n const dir = getTeamsDir();\n if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });\n return dir;\n}\n\nfunction teamPath(name: string): string {\n const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, \"-\");\n return path.join(ensureTeamsDir(), `${slug}.json`);\n}\n\n// --- CRUD ---\n\nexport function createTeam(team: Team): void {\n const fp = teamPath(team.name);\n fs.writeFileSync(fp, JSON.stringify(team, null, 2), \"utf-8\");\n}\n\nexport function loadTeam(name: string): Team | null {\n const fp = teamPath(name);\n if (!fs.existsSync(fp)) return null;\n try {\n return JSON.parse(fs.readFileSync(fp, \"utf-8\")) as Team;\n } catch {\n return null;\n }\n}\n\nexport function listTeams(): Team[] {\n const dir = getTeamsDir();\n if (!fs.existsSync(dir)) return [];\n\n const teams: Team[] = [];\n for (const file of fs.readdirSync(dir)) {\n if (!file.endsWith(\".json\")) continue;\n try {\n const content = fs.readFileSync(path.join(dir, file), \"utf-8\");\n teams.push(JSON.parse(content) as Team);\n } catch { /* skip malformed */ }\n }\n return teams;\n}\n\nexport function deleteTeam(name: string): boolean {\n const fp = teamPath(name);\n if (!fs.existsSync(fp)) return false;\n fs.unlinkSync(fp);\n return true;\n}\n\n// --- Team Execution ---\n\n/**\n * Run a task with a team. Routes to the appropriate execution mode.\n */\nexport async function runTeam(\n team: Team,\n task: string,\n client: LLMClient,\n mcpManager: McpManager,\n tools?: ToolDefinition[],\n): Promise<TeamRunResult> {\n process.stdout.write(pc.dim(`\\n Team: ${team.name} (${team.workflow} mode)\\n`));\n process.stdout.write(pc.dim(` Members: ${team.members.map((m) => m.profile).join(\", \")}\\n\\n`));\n\n switch (team.workflow) {\n case \"pipeline\":\n return runPipeline(team, task, client, mcpManager, tools);\n case \"parallel\":\n return runParallel(team, task, client, mcpManager, tools);\n case \"coordinator\":\n return runCoordinator(team, task, client, mcpManager, tools);\n default:\n return {\n team: team.name,\n task,\n workflow: team.workflow,\n results: [],\n finalOutput: `Unknown workflow mode: ${team.workflow}`,\n success: false,\n };\n }\n}\n\n/**\n * Pipeline mode: each member works sequentially, passing output to the next.\n */\nasync function runPipeline(\n team: Team,\n task: string,\n client: LLMClient,\n mcpManager: McpManager,\n tools?: ToolDefinition[],\n): Promise<TeamRunResult> {\n const steps = team.members.map((m, i) => ({\n profile: m.profile,\n taskTemplate: i === 0\n ? `${task}\\n\\nYour role: ${m.role}`\n : `${m.role}. Here is the previous agent's work:\\n\\n{{input}}`,\n }));\n\n for (const step of steps) {\n process.stdout.write(pc.dim(` [${step.profile}: ${team.members.find((m) => m.profile === step.profile)?.role}...]\\n`));\n }\n\n const results = await delegatePipeline(steps, task, client, mcpManager, {\n tools,\n silent: true,\n });\n\n const lastResult = results[results.length - 1];\n const success = results.every((r) => r.success);\n\n return {\n team: team.name,\n task,\n workflow: \"pipeline\",\n results,\n finalOutput: lastResult?.response || \"\",\n success,\n };\n}\n\n/**\n * Parallel mode: all members work concurrently, coordinator merges results.\n */\nasync function runParallel(\n team: Team,\n task: string,\n client: LLMClient,\n mcpManager: McpManager,\n tools?: ToolDefinition[],\n): Promise<TeamRunResult> {\n // Each member gets the task with their specific role\n const tasks = team.members.map((m) => ({\n profile: m.profile,\n task: `${task}\\n\\nYour specific role: ${m.role}. Focus only on your role.`,\n }));\n\n for (const m of team.members) {\n process.stdout.write(pc.dim(` [${m.profile}: ${m.role} (parallel)...]\\n`));\n }\n\n const results = await delegateParallel(tasks, client, mcpManager, { tools });\n\n // Merge results using coordinator (or main agent)\n const mergeInput = results\n .filter((r) => r.success)\n .map((r) => `[${r.profile} — ${team.members.find((m) => m.profile === r.profile)?.role}]:\\n${r.response}`)\n .join(\"\\n\\n---\\n\\n\");\n\n process.stdout.write(pc.dim(` [merging results...]\\n`));\n\n const mergeResult = await delegateTask(\n `You are the team coordinator. Multiple agents worked on this task in parallel. Merge their outputs into a single cohesive result. Keep the best parts from each.\\n\\nOriginal task: ${task}\\n\\n${mergeInput}`,\n team.coordinator === \"default\" ? team.members[0]?.profile || \"default\" : team.coordinator,\n client,\n mcpManager,\n { tools, silent: true },\n );\n\n return {\n team: team.name,\n task,\n workflow: \"parallel\",\n results: [...results, mergeResult],\n finalOutput: mergeResult.response,\n success: results.some((r) => r.success),\n };\n}\n\n/**\n * Coordinator mode: coordinator LLM decides how to route tasks to members.\n * Most flexible — coordinator analyzes the task and creates its own execution plan.\n */\nasync function runCoordinator(\n team: Team,\n task: string,\n client: LLMClient,\n mcpManager: McpManager,\n tools?: ToolDefinition[],\n): Promise<TeamRunResult> {\n const memberDescriptions = team.members\n .map((m) => `- ${m.profile}: ${m.role}`)\n .join(\"\\n\");\n\n // Step 1: Coordinator plans the work\n process.stdout.write(pc.dim(` [coordinator planning...]\\n`));\n\n const planResult = await delegateTask(\n `You are the coordinator of a team. Your job is to break down this task and decide which team members should handle each part.\n\nTeam members:\n${memberDescriptions}\n\nTask: ${task}\n\nRespond with a JSON array of assignments:\n[{\"profile\": \"member-name\", \"subtask\": \"what they should do\"}]\n\nOnly use the JSON array, no other text.`,\n team.coordinator === \"default\" ? team.members[0]?.profile || \"default\" : team.coordinator,\n client,\n mcpManager,\n { tools: undefined, silent: true, maxTurns: 0 },\n );\n\n if (!planResult.success) {\n return {\n team: team.name,\n task,\n workflow: \"coordinator\",\n results: [planResult],\n finalOutput: `Coordinator failed to plan: ${planResult.error}`,\n success: false,\n };\n }\n\n // Step 2: Parse assignments\n let assignments: Array<{ profile: string; subtask: string }>;\n try {\n let cleaned = planResult.response.trim();\n const codeBlockMatch = cleaned.match(/```(?:json)?\\s*\\n?([\\s\\S]*?)\\n?```/);\n if (codeBlockMatch) cleaned = codeBlockMatch[1].trim();\n assignments = JSON.parse(cleaned);\n } catch {\n // Fallback: run all members in parallel with the full task\n assignments = team.members.map((m) => ({ profile: m.profile, subtask: `${m.role}: ${task}` }));\n }\n\n // Step 3: Execute assignments in parallel\n for (const a of assignments) {\n process.stdout.write(pc.dim(` [${a.profile}: ${a.subtask.slice(0, 60)}...]\\n`));\n }\n\n const results = await delegateParallel(\n assignments.map((a) => ({ profile: a.profile, task: a.subtask })),\n client,\n mcpManager,\n { tools },\n );\n\n // Step 4: Coordinator merges\n const mergeInput = results\n .filter((r) => r.success)\n .map((r, i) => `[${assignments[i]?.profile} — ${assignments[i]?.subtask}]:\\n${r.response}`)\n .join(\"\\n\\n---\\n\\n\");\n\n process.stdout.write(pc.dim(` [coordinator merging...]\\n`));\n\n const mergeResult = await delegateTask(\n `You are the team coordinator. Your team members completed their assigned work. Combine their outputs into a single cohesive, polished result.\\n\\nOriginal task: ${task}\\n\\n${mergeInput}`,\n team.coordinator === \"default\" ? team.members[0]?.profile || \"default\" : team.coordinator,\n client,\n mcpManager,\n { tools, silent: true },\n );\n\n return {\n team: team.name,\n task,\n workflow: \"coordinator\",\n results: [...results, mergeResult],\n finalOutput: mergeResult.response,\n success: results.some((r) => r.success),\n };\n}\n\n// --- Formatting ---\n\nexport function formatTeam(team: Team): string {\n const lines: string[] = [];\n lines.push(`Team: ${pc.bold(team.name)}`);\n lines.push(`Goal: ${team.goal}`);\n lines.push(`Mode: ${team.workflow}`);\n lines.push(`Coordinator: ${team.coordinator}`);\n lines.push(\"\");\n lines.push(\"Members:\");\n for (const m of team.members) {\n lines.push(` ${pc.bold(m.profile)} — ${m.role}`);\n }\n return lines.join(\"\\n\");\n}\n\nexport function formatTeamResult(result: TeamRunResult): string {\n const lines: string[] = [];\n lines.push(`\\n${pc.bold(`Team: ${result.team}`)} (${result.workflow})`);\n\n for (const r of result.results) {\n const status = r.success ? pc.green(\"✓\") : pc.red(\"✗\");\n const tools = r.toolsUsed.length > 0 ? pc.dim(` (${r.toolsUsed.join(\", \")})`) : \"\";\n lines.push(` ${status} ${pc.bold(r.profile)}${tools}`);\n }\n\n lines.push(\"\");\n lines.push(result.finalOutput);\n\n return lines.join(\"\\n\");\n}\n\n// --- Built-in Team Templates ---\n\nexport const BUILT_IN_TEAMS: Team[] = [\n {\n name: \"content-team\",\n goal: \"Create and publish high-quality content\",\n coordinator: \"default\",\n members: [\n { profile: \"writer\", role: \"Draft compelling content with engaging narrative\" },\n { profile: \"researcher\", role: \"Fact-check claims and add citations\" },\n ],\n workflow: \"pipeline\",\n },\n {\n name: \"dev-team\",\n goal: \"Build and review code with quality assurance\",\n coordinator: \"default\",\n members: [\n { profile: \"coder\", role: \"Write clean, tested implementation code\" },\n { profile: \"researcher\", role: \"Review for security, performance, and best practices\" },\n ],\n workflow: \"pipeline\",\n },\n {\n name: \"research-team\",\n goal: \"Deep research with multiple perspectives\",\n coordinator: \"default\",\n members: [\n { profile: \"researcher\", role: \"Research the topic thoroughly with citations\" },\n { profile: \"writer\", role: \"Synthesize findings into clear, readable format\" },\n ],\n workflow: \"pipeline\",\n },\n];\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport os from \"node:os\";\nimport { log } from \"./logger.js\";\n\n// --- Types ---\n\nexport interface PlanStep {\n text: string;\n done: boolean;\n}\n\nexport interface Plan {\n name: string;\n goal: string;\n steps: PlanStep[];\n createdAt: string;\n updatedAt: string;\n active: boolean;\n}\n\n// --- Paths ---\n\nfunction getPlansDir(): string {\n // Project-local plans if .acore exists, otherwise global\n const localDir = path.join(process.cwd(), \".acore\", \"plans\");\n const localAcore = path.join(process.cwd(), \".acore\");\n if (fs.existsSync(localAcore)) return localDir;\n return path.join(os.homedir(), \".acore\", \"plans\");\n}\n\nfunction ensurePlansDir(): string {\n const dir = getPlansDir();\n if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });\n return dir;\n}\n\nfunction planPath(name: string): string {\n const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-|-$/g, \"\");\n return path.join(ensurePlansDir(), `${slug}.md`);\n}\n\n// --- Serialization ---\n\nfunction serializePlan(plan: Plan): string {\n const lines: string[] = [];\n lines.push(`# ${plan.name}`);\n lines.push(\"\");\n lines.push(`**Goal:** ${plan.goal}`);\n lines.push(`**Created:** ${plan.createdAt}`);\n lines.push(`**Updated:** ${plan.updatedAt}`);\n lines.push(`**Active:** ${plan.active}`);\n lines.push(\"\");\n lines.push(\"## Steps\");\n lines.push(\"\");\n for (const step of plan.steps) {\n lines.push(`- [${step.done ? \"x\" : \" \"}] ${step.text}`);\n }\n lines.push(\"\");\n return lines.join(\"\\n\");\n}\n\nfunction parsePlan(content: string, filePath: string): Plan | null {\n try {\n const nameMatch = content.match(/^# (.+)/m);\n const goalMatch = content.match(/\\*\\*Goal:\\*\\*\\s*(.+)/);\n const createdMatch = content.match(/\\*\\*Created:\\*\\*\\s*(.+)/);\n const updatedMatch = content.match(/\\*\\*Updated:\\*\\*\\s*(.+)/);\n const activeMatch = content.match(/\\*\\*Active:\\*\\*\\s*(.+)/);\n\n const name = nameMatch?.[1]?.trim() || path.basename(filePath, \".md\");\n const goal = goalMatch?.[1]?.trim() || \"\";\n const createdAt = createdMatch?.[1]?.trim() || \"\";\n const updatedAt = updatedMatch?.[1]?.trim() || \"\";\n const active = activeMatch?.[1]?.trim() === \"true\";\n\n // Parse checkbox steps\n const steps: PlanStep[] = [];\n const stepMatches = content.matchAll(/- \\[([ x])\\] (.+)/g);\n for (const match of stepMatches) {\n steps.push({\n done: match[1] === \"x\",\n text: match[2].trim(),\n });\n }\n\n return { name, goal, steps, createdAt, updatedAt, active };\n } catch (err) {\n log.debug(\"plans\", \"Failed to parse plan: \" + filePath, err);\n return null;\n }\n}\n\n// --- CRUD ---\n\nexport function createPlan(name: string, goal: string, steps: string[]): Plan {\n const now = new Date().toISOString().split(\"T\")[0];\n const plan: Plan = {\n name,\n goal,\n steps: steps.map((text) => ({ text, done: false })),\n createdAt: now,\n updatedAt: now,\n active: true,\n };\n\n // Deactivate any currently active plan\n const existing = listPlans();\n for (const p of existing) {\n if (p.active) {\n p.active = false;\n p.updatedAt = now;\n savePlan(p);\n }\n }\n\n savePlan(plan);\n return plan;\n}\n\nexport function savePlan(plan: Plan): void {\n const fp = planPath(plan.name);\n fs.writeFileSync(fp, serializePlan(plan), \"utf-8\");\n}\n\nexport function loadPlan(name: string): Plan | null {\n const fp = planPath(name);\n if (!fs.existsSync(fp)) return null;\n const content = fs.readFileSync(fp, \"utf-8\");\n return parsePlan(content, fp);\n}\n\nexport function listPlans(): Plan[] {\n const dir = getPlansDir();\n if (!fs.existsSync(dir)) return [];\n\n const plans: Plan[] = [];\n for (const file of fs.readdirSync(dir)) {\n if (!file.endsWith(\".md\")) continue;\n const fp = path.join(dir, file);\n const content = fs.readFileSync(fp, \"utf-8\");\n const plan = parsePlan(content, fp);\n if (plan) plans.push(plan);\n }\n\n return plans;\n}\n\nexport function getActivePlan(): Plan | null {\n const plans = listPlans();\n return plans.find((p) => p.active) || null;\n}\n\n// --- Operations ---\n\nexport function markStepDone(plan: Plan, stepIndex: number): boolean {\n if (stepIndex < 0 || stepIndex >= plan.steps.length) return false;\n plan.steps[stepIndex].done = true;\n plan.updatedAt = new Date().toISOString().split(\"T\")[0];\n savePlan(plan);\n return true;\n}\n\nexport function markStepUndone(plan: Plan, stepIndex: number): boolean {\n if (stepIndex < 0 || stepIndex >= plan.steps.length) return false;\n plan.steps[stepIndex].done = false;\n plan.updatedAt = new Date().toISOString().split(\"T\")[0];\n savePlan(plan);\n return true;\n}\n\nexport function setActivePlan(name: string): Plan | null {\n const now = new Date().toISOString().split(\"T\")[0];\n\n // Deactivate all\n const plans = listPlans();\n for (const p of plans) {\n if (p.active) {\n p.active = false;\n p.updatedAt = now;\n savePlan(p);\n }\n }\n\n // Activate target\n const target = loadPlan(name);\n if (!target) return null;\n target.active = true;\n target.updatedAt = now;\n savePlan(target);\n return target;\n}\n\n// --- Formatting ---\n\nexport function formatPlan(plan: Plan): string {\n const total = plan.steps.length;\n const done = plan.steps.filter((s) => s.done).length;\n const pct = total > 0 ? Math.round((done / total) * 100) : 0;\n const bar = progressBar(pct);\n\n const lines: string[] = [];\n lines.push(`Plan: ${plan.name} ${plan.active ? \"(active)\" : \"(inactive)\"}`);\n lines.push(`Goal: ${plan.goal}`);\n lines.push(`Progress: ${bar} ${done}/${total} (${pct}%)`);\n lines.push(\"\");\n\n for (let i = 0; i < plan.steps.length; i++) {\n const step = plan.steps[i];\n const marker = step.done ? \"✓\" : \" \";\n const num = String(i + 1).padStart(2, \" \");\n lines.push(` ${num}. [${marker}] ${step.text}`);\n }\n\n if (done === total && total > 0) {\n lines.push(\"\\n All steps complete!\");\n } else {\n const next = plan.steps.findIndex((s) => !s.done);\n if (next >= 0) {\n lines.push(`\\n Next: Step ${next + 1} — ${plan.steps[next].text}`);\n }\n }\n\n return lines.join(\"\\n\");\n}\n\nexport function formatPlanForPrompt(plan: Plan): string {\n const total = plan.steps.length;\n const done = plan.steps.filter((s) => s.done).length;\n\n const lines: string[] = [];\n lines.push(`<active-plan name=\"${plan.name}\" progress=\"${done}/${total}\">`);\n lines.push(`Goal: ${plan.goal}`);\n lines.push(\"\");\n\n for (let i = 0; i < plan.steps.length; i++) {\n const step = plan.steps[i];\n lines.push(`- [${step.done ? \"x\" : \" \"}] Step ${i + 1}: ${step.text}`);\n }\n\n const next = plan.steps.findIndex((s) => !s.done);\n if (next >= 0) {\n lines.push(\"\");\n lines.push(`Current focus: Step ${next + 1} — ${plan.steps[next].text}`);\n lines.push(\"After completing the current step, remind the user to mark it done with /plan done and suggest committing their work.\");\n }\n\n lines.push(\"</active-plan>\");\n return lines.join(\"\\n\");\n}\n\nfunction progressBar(pct: number): string {\n const filled = Math.round(pct / 5);\n const empty = 20 - filled;\n return `[${\"█\".repeat(filled)}${\"░\".repeat(empty)}]`;\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport os from \"node:os\";\nimport pc from \"picocolors\";\nimport type { McpManager } from \"./mcp/client.js\";\nimport { log } from \"./logger.js\";\n\nexport interface BackgroundTask {\n id: string;\n toolName: string;\n toolUseId: string;\n startedAt: number;\n promise: Promise<string>;\n result?: string;\n error?: string;\n done: boolean;\n}\n\n// Tools that are likely long-running and benefit from background execution\nconst BACKGROUND_ELIGIBLE = new Set([\n \"run_tests\", \"npm_test\", \"build\", \"npm_build\",\n \"file_search\", \"code_search\", \"grep_search\",\n \"git_clone\", \"docker_build\", \"docker_run\",\n]);\n\n// Tools that should NEVER run in background (need immediate results for tool loop)\nconst NEVER_BACKGROUND = new Set([\n \"memory_recall\", \"memory_store\", \"memory_log\", \"memory_context\", \"memory_detail\",\n \"identity_read\", \"identity_summary\", \"identity_update_session\", \"identity_update_dynamics\",\n \"rules_check\", \"rules_list\", \"workflow_list\", \"workflow_get\",\n \"skill_list\", \"skill_search\", \"eval_status\", \"eval_log\",\n \"reminder_check\", \"reminder_set\",\n \"file_read\", \"doc_convert\", \"file_list\",\n \"avatar_prompt\",\n]);\n\n// ── Persistent task log ────────────────────────────────────────────────────────\n\nexport interface TaskLogEntry {\n id: string;\n toolName: string;\n startedAt: number;\n completedAt?: number;\n status: \"running\" | \"completed\" | \"failed\" | \"interrupted\";\n resultPreview?: string;\n error?: string;\n}\n\nconst TASK_LOG_DIR = path.join(os.homedir(), \".aman-agent\");\nconst TASK_LOG_FILE = path.join(TASK_LOG_DIR, \"bg-tasks.json\");\nconst MAX_LOG_ENTRIES = 50;\n\nexport function loadTaskLog(): TaskLogEntry[] {\n try {\n if (!fs.existsSync(TASK_LOG_FILE)) return [];\n const raw = fs.readFileSync(TASK_LOG_FILE, \"utf-8\");\n return JSON.parse(raw) as TaskLogEntry[];\n } catch {\n return [];\n }\n}\n\nexport function saveTaskLog(entries: TaskLogEntry[]): void {\n try {\n if (!fs.existsSync(TASK_LOG_DIR)) fs.mkdirSync(TASK_LOG_DIR, { recursive: true });\n // Keep only recent entries\n const trimmed = entries.slice(-MAX_LOG_ENTRIES);\n fs.writeFileSync(TASK_LOG_FILE, JSON.stringify(trimmed, null, 2));\n } catch (err) {\n log.debug(\"background\", \"Failed to save task log\", err);\n }\n}\n\nfunction logTaskStart(task: BackgroundTask): void {\n const entries = loadTaskLog();\n // Mark any stale \"running\" entries as interrupted (from prior crash)\n for (const e of entries) {\n if (e.status === \"running\") e.status = \"interrupted\";\n }\n entries.push({\n id: task.id,\n toolName: task.toolName,\n startedAt: task.startedAt,\n status: \"running\",\n });\n saveTaskLog(entries);\n}\n\nfunction logTaskComplete(task: BackgroundTask): void {\n const entries = loadTaskLog();\n const entry = entries.find((e) => e.id === task.id);\n if (entry) {\n entry.completedAt = Date.now();\n entry.status = task.error ? \"failed\" : \"completed\";\n entry.resultPreview = (task.result || \"\").slice(0, 200);\n entry.error = task.error;\n }\n saveTaskLog(entries);\n}\nexport function shouldRunInBackground(toolName: string): boolean {\n if (NEVER_BACKGROUND.has(toolName)) return false;\n if (BACKGROUND_ELIGIBLE.has(toolName)) return true;\n return false;\n}\n\n/**\n * Background task manager.\n * Runs tool calls concurrently and reports results when ready.\n */\nexport class BackgroundTaskManager {\n private tasks: Map<string, BackgroundTask> = new Map();\n private taskCounter = 0;\n\n /**\n * Launch a tool call in the background.\n */\n launch(\n toolName: string,\n toolUseId: string,\n mcpManager: McpManager,\n toolInput: Record<string, unknown>,\n ): BackgroundTask {\n const id = `bg-${++this.taskCounter}`;\n const task: BackgroundTask = {\n id,\n toolName,\n toolUseId,\n startedAt: Date.now(),\n done: false,\n promise: mcpManager.callTool(toolName, toolInput).then(\n (result) => {\n task.result = result;\n task.done = true;\n logTaskComplete(task);\n return result;\n },\n (error) => {\n task.error = error instanceof Error ? error.message : String(error);\n task.done = true;\n logTaskComplete(task);\n return `Error: ${task.error}`;\n },\n ),\n };\n\n this.tasks.set(id, task);\n logTaskStart(task);\n process.stdout.write(pc.dim(` [${toolName} running in background (${id})...]\\n`));\n return task;\n }\n\n /**\n * Check for completed background tasks and return their results.\n */\n collectCompleted(): BackgroundTask[] {\n const completed: BackgroundTask[] = [];\n for (const [id, task] of this.tasks) {\n if (task.done) {\n completed.push(task);\n this.tasks.delete(id);\n }\n }\n return completed;\n }\n\n /**\n * Display completed background task results to the user.\n */\n displayCompleted(): string[] {\n const completed = this.collectCompleted();\n const outputs: string[] = [];\n\n for (const task of completed) {\n const elapsed = ((Date.now() - task.startedAt) / 1000).toFixed(1);\n if (task.error) {\n process.stdout.write(pc.yellow(`\\n [${task.id}] ${task.toolName} failed after ${elapsed}s: ${task.error}\\n`));\n outputs.push(`[Background task ${task.toolName} failed: ${task.error}]`);\n } else {\n process.stdout.write(pc.green(`\\n [${task.id}] ${task.toolName} completed in ${elapsed}s\\n`));\n const preview = (task.result || \"\").slice(0, 200);\n if (preview) {\n process.stdout.write(pc.dim(` ${preview}${(task.result || \"\").length > 200 ? \"...\" : \"\"}\\n`));\n }\n outputs.push(`[Background task ${task.toolName} completed: ${task.result}]`);\n }\n }\n\n return outputs;\n }\n\n /**\n * Wait for all pending background tasks to complete.\n */\n async waitAll(): Promise<void> {\n const pending = [...this.tasks.values()].filter((t) => !t.done);\n if (pending.length === 0) return;\n\n process.stdout.write(pc.dim(`\\n Waiting for ${pending.length} background task(s)...\\n`));\n await Promise.allSettled(pending.map((t) => t.promise));\n }\n\n /**\n * Number of currently running tasks.\n */\n get pendingCount(): number {\n return [...this.tasks.values()].filter((t) => !t.done).length;\n }\n\n /**\n * Check if any tasks have completed (non-blocking).\n */\n get hasCompleted(): boolean {\n return [...this.tasks.values()].some((t) => t.done);\n }\n}\n","import type { Message, LLMClient } from \"./llm/types.js\";\nimport { log } from \"./logger.js\";\n\n// Rough token estimation: ~1.3 tokens per word\nfunction estimateMessageTokens(msg: Message): number {\n if (typeof msg.content === \"string\") {\n return Math.round(msg.content.split(/\\s+/).filter(Boolean).length * 1.3);\n }\n // Content blocks — estimate from stringified content\n let text = \"\";\n let imageTokens = 0;\n for (const block of msg.content) {\n if (block.type === \"text\") text += block.text;\n else if (block.type === \"tool_result\") text += block.content;\n else if (block.type === \"tool_use\") text += JSON.stringify(block.input);\n else if (block.type === \"image\") imageTokens += 1600;\n }\n return Math.round(text.split(/\\s+/).filter(Boolean).length * 1.3) + imageTokens;\n}\n\nfunction estimateTotalTokens(messages: Message[]): number {\n let total = 0;\n for (const msg of messages) {\n total += estimateMessageTokens(msg);\n }\n return total;\n}\n\n// Maximum conversation tokens before trimming (leave room for system prompt + response)\nconst MAX_CONVERSATION_TOKENS = 80_000;\n// How many recent messages to always keep\nconst KEEP_RECENT = 10;\n// How many initial messages to always keep (session context injection)\nconst KEEP_INITIAL = 2;\n\n/**\n * Trims conversation history when it gets too long.\n * Keeps initial context messages and recent messages.\n * Replaces middle messages with a summary.\n * Mutates the messages array in place.\n */\nexport async function trimConversation(\n messages: Message[],\n client: LLMClient,\n): Promise<void> {\n const totalTokens = estimateTotalTokens(messages);\n\n if (totalTokens < MAX_CONVERSATION_TOKENS || messages.length <= KEEP_INITIAL + KEEP_RECENT) {\n return;\n }\n\n const initial = messages.slice(0, KEEP_INITIAL);\n const recent = messages.slice(-KEEP_RECENT);\n const middle = messages.slice(KEEP_INITIAL, messages.length - KEEP_RECENT);\n\n const middleText = middle\n .filter((m) => typeof m.content === \"string\" && m.content.length > 0)\n .map((m) => `[${m.role}]: ${(m.content as string).slice(0, 500)}`)\n .slice(0, 30)\n .join(\"\\n\");\n\n let summaryText: string;\n\n try {\n const summaryPrompt = \"Summarize the following conversation messages in 3-5 bullet points. Preserve: decisions made, user preferences expressed, action items, and key facts discussed. Be concise.\\n\\n\" + middleText;\n\n let fullText = \"\";\n await client.chat(\n \"You are a concise summarizer. Return only bullet points, no preamble.\",\n [{ role: \"user\", content: summaryPrompt }],\n (chunk) => {\n if (chunk.type === \"text\" && chunk.text) fullText += chunk.text;\n },\n );\n\n summaryText = `<conversation-summary>\\nSummary of ${middle.length} earlier messages:\\n\\n${fullText}\\n</conversation-summary>`;\n log.debug(\"context\", `Summarized ${middle.length} messages via LLM`);\n } catch (err) {\n log.warn(\"context\", \"LLM summarization failed, using fallback\", err);\n const summaryParts: string[] = [];\n for (const msg of middle) {\n if (typeof msg.content === \"string\" && msg.content.length > 0) {\n const preview = msg.content.slice(0, 150);\n summaryParts.push(`[${msg.role}]: ${preview}${msg.content.length > 150 ? \"...\" : \"\"}`);\n }\n }\n summaryText = `<conversation-summary>\\nSummary of ${middle.length} earlier messages:\\n\\n${summaryParts.slice(0, 20).join(\"\\n\")}\\n</conversation-summary>`;\n }\n\n messages.length = 0;\n messages.push(...initial);\n messages.push({ role: \"user\", content: summaryText });\n messages.push({ role: \"assistant\", content: \"I have the context from our earlier conversation. Let's continue.\" });\n messages.push(...recent);\n}\n","import type { LLMClient } from \"./llm/types.js\";\nimport { log } from \"./logger.js\";\nimport { matchPatternToSkill, enrichSkill } from \"./skill-engine.js\";\nimport { memoryRecall, memoryStore, getDb } from \"./memory.js\";\nimport { reflect, isReflectionDue, autoRelateMemory } from \"@aman_asmuei/amem-core\";\n\nexport interface ExtractionCandidate {\n content: string;\n type: \"preference\" | \"fact\" | \"pattern\" | \"decision\" | \"correction\" | \"topology\";\n tags: string[];\n confidence: number;\n scope: string;\n}\n\nconst VALID_TYPES = new Set([\"preference\", \"fact\", \"pattern\", \"topology\", \"decision\", \"correction\"]);\nconst MIN_RESPONSE_LENGTH = 50;\nconst MIN_TURNS_BETWEEN_EMPTY = 3;\n\nconst EXTRACTION_PROMPT = `Analyze this conversation turn. Extract any information worth remembering long-term, and assess the user's emotional tone.\n\nReturn a JSON object with two fields:\n{\n \"memories\": [{\n \"content\": \"what to remember — be specific and self-contained\",\n \"type\": \"preference|fact|pattern|decision|correction|topology\",\n \"tags\": [\"relevant\", \"tags\"],\n \"confidence\": 0.0-1.0,\n \"scope\": \"global\"\n }],\n \"sentiment\": {\n \"tone\": \"neutral|positive|frustrated|confused|excited|fatigued\",\n \"confidence\": 0.0-1.0,\n \"context\": \"brief reason for sentiment read\"\n }\n}\n\nType guide:\n- \"preference\" = user likes/dislikes/preferences\n- \"fact\" = objective information about systems, people, projects\n- \"pattern\" = recurring behavior, coding style, approach\n- \"topology\" = how systems/components connect to each other\n- \"decision\" = explicit choice between alternatives\n- \"correction\" = user correcting a prior wrong assumption\n\nRules:\n- Only extract genuinely useful LONG-TERM information\n- Skip ephemeral things (\"user asked about X\" is NOT useful)\n- Be conservative — 90% of turns produce nothing worth storing\n- Sentiment should reflect the USER's tone, not the assistant's\n- Return ONLY the JSON object, no other text`;\n\nexport function shouldExtract(\n assistantResponse: string,\n turnsSinceLastExtraction: number,\n lastExtractionCount: number,\n): boolean {\n // Always skip very short responses regardless of previous extraction results\n if (assistantResponse.length < MIN_RESPONSE_LENGTH) return false;\n // If previous turn found memories, extract again but respect min turns spacing\n if (lastExtractionCount > 0 && turnsSinceLastExtraction >= 1) return true;\n // Otherwise, wait for MIN_TURNS_BETWEEN_EMPTY turns between empty extractions\n if (turnsSinceLastExtraction < MIN_TURNS_BETWEEN_EMPTY) return false;\n return true;\n}\n\nexport interface ExtractionResult {\n memories: ExtractionCandidate[];\n sentiment?: LlmSentiment;\n}\n\nexport function parseExtractionResult(raw: string): ExtractionResult {\n try {\n let cleaned = raw.trim();\n const codeBlockMatch = cleaned.match(/```(?:json)?\\s*\\n?([\\s\\S]*?)\\n?```/);\n if (codeBlockMatch) {\n cleaned = codeBlockMatch[1].trim();\n }\n\n const parsed = JSON.parse(cleaned);\n\n // New format: { memories: [...], sentiment: {...} }\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed) && \"memories\" in parsed) {\n const memories = Array.isArray(parsed.memories)\n ? (parsed.memories as Record<string, unknown>[]).filter(\n (item) =>\n typeof item.content === \"string\" &&\n (item.content as string).length > 0 &&\n typeof item.type === \"string\" &&\n VALID_TYPES.has(item.type as string),\n ) as unknown as ExtractionCandidate[]\n : [];\n\n let sentiment: LlmSentiment | undefined;\n if (parsed.sentiment && typeof parsed.sentiment === \"object\") {\n const s = parsed.sentiment as Record<string, unknown>;\n if (typeof s.tone === \"string\" && typeof s.confidence === \"number\") {\n sentiment = {\n tone: s.tone,\n confidence: s.confidence,\n context: typeof s.context === \"string\" ? s.context : undefined,\n };\n }\n }\n\n return { memories, sentiment };\n }\n\n // Legacy format: plain array\n if (Array.isArray(parsed)) {\n const memories = parsed.filter(\n (item: Record<string, unknown>) =>\n typeof item.content === \"string\" &&\n item.content.length > 0 &&\n typeof item.type === \"string\" &&\n VALID_TYPES.has(item.type),\n ) as ExtractionCandidate[];\n return { memories };\n }\n\n return { memories: [] };\n } catch {\n return { memories: [] };\n }\n}\n\nexport interface LlmSentiment {\n tone: string;\n confidence: number;\n context?: string;\n}\n\nexport interface ExtractorState {\n turnsSinceLastExtraction: number;\n lastExtractionCount: number;\n lastLlmSentiment?: LlmSentiment;\n}\n\nexport async function extractMemories(\n userMessage: string,\n assistantResponse: string,\n client: LLMClient,\n state: ExtractorState,\n): Promise<number> {\n if (!shouldExtract(assistantResponse, state.turnsSinceLastExtraction, state.lastExtractionCount)) {\n state.turnsSinceLastExtraction++;\n return 0;\n }\n\n try {\n const conversationTurn = `User: ${userMessage.slice(0, 2000)}\\n\\nAssistant: ${assistantResponse.slice(0, 2000)}`;\n\n let fullText = \"\";\n await client.chat(\n EXTRACTION_PROMPT,\n [{ role: \"user\", content: conversationTurn }],\n (chunk) => {\n if (chunk.type === \"text\" && chunk.text) fullText += chunk.text;\n },\n );\n\n const result = parseExtractionResult(fullText);\n state.turnsSinceLastExtraction = 0;\n state.lastExtractionCount = result.memories.length;\n\n // Store LLM sentiment on state for personality system to read\n if (result.sentiment) {\n state.lastLlmSentiment = result.sentiment;\n log.debug(\"extractor\", `LLM sentiment: ${result.sentiment.tone} (${result.sentiment.confidence})`);\n }\n\n if (result.memories.length === 0) return 0;\n\n let stored = 0;\n\n for (const candidate of result.memories) {\n // Dedup check\n try {\n const existing = await memoryRecall(candidate.content, { limit: 1 });\n if (existing.total > 0 && existing.memories.length > 0) {\n const topScore = (existing.memories[0] as { score?: number })?.score;\n if (topScore && topScore > 0.85) {\n log.debug(\"extractor\", \"Skipping duplicate: \" + candidate.content);\n continue;\n }\n }\n } catch { /* Dedup failed, proceed */ }\n\n // Store\n try {\n const storeResult = await memoryStore({\n content: candidate.content,\n type: candidate.type,\n tags: candidate.tags,\n confidence: candidate.confidence,\n source: \"auto-extraction\",\n scope: candidate.scope,\n });\n if (storeResult.action !== \"private\") {\n stored++;\n log.debug(\"extractor\", \"Stored \" + candidate.type + \": \" + candidate.content);\n // Auto-relate: build knowledge graph edges to similar memories\n try {\n autoRelateMemory(getDb(), storeResult.id);\n } catch {\n // Best-effort — never block extraction\n }\n // Self-improving skills: enrich skills with learned patterns\n if (candidate.type === \"pattern\" || candidate.type === \"preference\") {\n const skillMatch = matchPatternToSkill(candidate.content, candidate.tags);\n if (skillMatch) {\n enrichSkill(skillMatch, candidate.content);\n }\n }\n }\n } catch (err) {\n log.warn(\"extractor\", \"Failed to store: \" + candidate.content, err);\n }\n }\n\n // Post-extraction: trigger reflection if enough memories have accumulated\n if (stored > 0 && isReflectionDue(getDb()).due) {\n try {\n reflect(getDb());\n } catch {\n // Reflection is best-effort — suppress errors so they never block extraction\n }\n }\n\n return stored;\n } catch (err) {\n log.debug(\"extractor\", \"extraction failed\", err);\n state.turnsSinceLastExtraction = 0;\n state.lastExtractionCount = 0;\n return 0;\n }\n}\n","import fs from \"node:fs\";\nimport fsp from \"node:fs/promises\";\nimport path from \"node:path\";\nimport os from \"node:os\";\nimport type { McpManager } from \"./mcp/client.js\";\nimport { log } from \"./logger.js\";\nimport { extractSkillsWithMarkers } from \"./crystallization.js\";\n\n// --- Skill Keyword Map for Auto-Triggering ---\n\nconst SKILL_TRIGGERS: Record<string, string[]> = {\n testing: [\"test\", \"spec\", \"coverage\", \"tdd\", \"jest\", \"vitest\", \"mocha\", \"assert\", \"mock\", \"stub\", \"fixture\", \"e2e\", \"integration test\", \"unit test\"],\n \"api-design\": [\"api\", \"endpoint\", \"rest\", \"graphql\", \"route\", \"controller\", \"middleware\", \"http\", \"request\", \"response\", \"status code\", \"pagination\"],\n security: [\"security\", \"auth\", \"csrf\", \"xss\", \"injection\", \"cors\", \"jwt\", \"token\", \"oauth\", \"password\", \"hash\", \"encrypt\", \"vulnerability\", \"owasp\", \"sanitize\"],\n performance: [\"performance\", \"slow\", \"latency\", \"cache\", \"optimize\", \"profil\", \"bundle size\", \"lazy load\", \"memory leak\", \"benchmark\", \"bottleneck\"],\n \"code-review\": [\"review\", \"pr review\", \"pull request\", \"code quality\", \"clean code\", \"best practice\"],\n documentation: [\"document\", \"readme\", \"jsdoc\", \"tsdoc\", \"changelog\", \"adr\", \"comment\"],\n \"git-workflow\": [\"git\", \"branch\", \"merge\", \"rebase\", \"cherry-pick\", \"bisect\", \"stash\", \"commit message\", \"pr\", \"pull request\"],\n debugging: [\"debug\", \"breakpoint\", \"stack trace\", \"error\", \"exception\", \"crash\", \"bug\", \"issue\", \"unexpected\", \"reproduce\"],\n refactoring: [\"refactor\", \"extract\", \"rename\", \"move\", \"split\", \"consolidate\", \"dry\", \"code smell\", \"technical debt\", \"legacy\"],\n database: [\"database\", \"schema\", \"migration\", \"index\", \"query\", \"sql\", \"postgres\", \"mysql\", \"sqlite\", \"mongo\", \"orm\", \"prisma\", \"drizzle\"],\n typescript: [\"typescript\", \"type\", \"interface\", \"generic\", \"infer\", \"utility type\", \"zod\", \"discriminated union\", \"type guard\", \"as const\"],\n accessibility: [\"accessibility\", \"a11y\", \"aria\", \"screen reader\", \"wcag\", \"semantic html\", \"tab order\", \"focus\", \"contrast\"],\n};\n\n// --- Runtime Triggers (crystallized skills) ---\n\n/**\n * Load runtime trigger keywords from crystallized skills in ~/.askill/skills.md.\n * These supplement the hardcoded SKILL_TRIGGERS map without modifying it.\n *\n * Returns a Map<skillName, triggers[]>. Returns empty map if file is missing or\n * unreadable — never throws.\n */\nexport async function loadRuntimeTriggers(\n skillsMdPath: string,\n): Promise<Map<string, string[]>> {\n try {\n const content = await fsp.readFile(skillsMdPath, \"utf-8\");\n const skills = extractSkillsWithMarkers(content);\n const result = new Map<string, string[]>();\n for (const [name, marker] of skills) {\n result.set(name, marker.triggers);\n }\n return result;\n } catch (err) {\n log.debug(\"skill-engine\", \"loadRuntimeTriggers failed\", err);\n return new Map();\n }\n}\n\n// --- Skill Level Tracking ---\n\nconst LEVEL_FILE = path.join(os.homedir(), \".aman-agent\", \"skill-levels.json\");\n\ninterface SkillLevel {\n name: string;\n activations: number;\n lastUsed: string;\n userPatterns: string[]; // user-specific patterns learned\n}\n\nfunction loadSkillLevels(): Record<string, SkillLevel> {\n try {\n if (fs.existsSync(LEVEL_FILE)) {\n return JSON.parse(fs.readFileSync(LEVEL_FILE, \"utf-8\")) as Record<string, SkillLevel>;\n }\n } catch { /* ignore */ }\n return {};\n}\n\nfunction saveSkillLevels(levels: Record<string, SkillLevel>): void {\n const dir = path.dirname(LEVEL_FILE);\n if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });\n fs.writeFileSync(LEVEL_FILE, JSON.stringify(levels, null, 2), \"utf-8\");\n}\n\n/**\n * Compute skill level from activation count.\n * Lv.1 = beginner guidance, Lv.5 = proactive expert suggestions\n */\nexport function computeLevel(activations: number): { level: number; label: string } {\n if (activations >= 50) return { level: 5, label: \"Expert\" };\n if (activations >= 25) return { level: 4, label: \"Advanced\" };\n if (activations >= 10) return { level: 3, label: \"Proficient\" };\n if (activations >= 3) return { level: 2, label: \"Familiar\" };\n return { level: 1, label: \"Learning\" };\n}\n\n/**\n * Record a skill activation and return updated level.\n */\nexport function recordActivation(skillName: string): { level: number; label: string } {\n const levels = loadSkillLevels();\n if (!levels[skillName]) {\n levels[skillName] = { name: skillName, activations: 0, lastUsed: \"\", userPatterns: [] };\n }\n levels[skillName].activations++;\n levels[skillName].lastUsed = new Date().toISOString().split(\"T\")[0];\n saveSkillLevels(levels);\n return computeLevel(levels[skillName].activations);\n}\n\n/**\n * Get current level for a skill.\n */\nexport function getSkillLevel(skillName: string): { level: number; label: string; activations: number } {\n const levels = loadSkillLevels();\n const data = levels[skillName];\n if (!data) return { level: 1, label: \"Learning\", activations: 0 };\n const { level, label } = computeLevel(data.activations);\n return { level, label, activations: data.activations };\n}\n\n// --- Auto-Triggered Skills ---\n\n/**\n * Match user input against installed skill triggers.\n * Returns skill names that should be activated for this turn.\n */\nexport function matchSkills(\n userInput: string,\n installedSkillNames: string[],\n runtimeTriggers: Map<string, string[]> = new Map(),\n): string[] {\n const input = userInput.toLowerCase();\n const matched = new Set<string>();\n\n // Hardcoded triggers — only fire for installed skills\n for (const skillName of installedSkillNames) {\n const triggers = SKILL_TRIGGERS[skillName];\n if (!triggers) continue;\n\n for (const trigger of triggers) {\n if (input.includes(trigger)) {\n matched.add(skillName);\n break;\n }\n }\n }\n\n // Runtime triggers — fire regardless of installedSkillNames since\n // crystallized skills may not appear in the aman-mcp skill_list\n for (const [skillName, triggers] of runtimeTriggers) {\n for (const trigger of triggers) {\n if (input.includes(trigger)) {\n matched.add(skillName);\n break;\n }\n }\n }\n\n return Array.from(matched);\n}\n\n// --- Semantic Trigger Matching (TF-IDF cosine similarity) ---\n\nconst SEMANTIC_STOPWORDS = new Set([\n \"the\", \"a\", \"an\", \"is\", \"are\", \"was\", \"were\", \"be\", \"been\", \"being\",\n \"have\", \"has\", \"had\", \"do\", \"does\", \"did\", \"will\", \"would\", \"shall\",\n \"should\", \"may\", \"might\", \"must\", \"can\", \"could\", \"to\", \"of\", \"in\",\n \"for\", \"on\", \"with\", \"at\", \"by\", \"from\", \"as\", \"into\", \"through\",\n \"during\", \"before\", \"after\", \"above\", \"below\", \"between\", \"and\",\n \"but\", \"or\", \"nor\", \"not\", \"so\", \"yet\", \"both\", \"either\", \"neither\",\n \"each\", \"every\", \"all\", \"any\", \"few\", \"more\", \"most\", \"other\",\n \"some\", \"such\", \"no\", \"only\", \"own\", \"same\", \"than\", \"too\", \"very\",\n \"just\", \"because\", \"if\", \"when\", \"while\", \"how\", \"what\", \"which\",\n \"who\", \"whom\", \"this\", \"that\", \"these\", \"those\", \"i\", \"me\", \"my\",\n \"we\", \"us\", \"our\", \"you\", \"your\", \"he\", \"him\", \"his\", \"she\", \"her\",\n \"it\", \"its\", \"they\", \"them\", \"their\",\n]);\n\n/**\n * Tokenize text into lowercased words, filtering stopwords and short tokens.\n */\nexport function tokenize(text: string): string[] {\n return text\n .toLowerCase()\n .replace(/[^a-z0-9\\s-]/g, \" \")\n .split(/\\s+/)\n .filter((w) => w.length > 2 && !SEMANTIC_STOPWORDS.has(w));\n}\n\n/**\n * Build a term frequency map for tokens.\n */\nfunction termFrequency(tokens: string[]): Map<string, number> {\n const tf = new Map<string, number>();\n for (const t of tokens) {\n tf.set(t, (tf.get(t) || 0) + 1);\n }\n // Normalize by document length\n for (const [k, v] of tf) {\n tf.set(k, v / tokens.length);\n }\n return tf;\n}\n\n/**\n * Compute cosine similarity between two term frequency maps.\n */\nfunction cosineSimilarity(a: Map<string, number>, b: Map<string, number>): number {\n let dot = 0;\n let normA = 0;\n let normB = 0;\n\n for (const [k, v] of a) {\n normA += v * v;\n const bv = b.get(k);\n if (bv !== undefined) dot += v * bv;\n }\n for (const [, v] of b) {\n normB += v * v;\n }\n\n if (normA === 0 || normB === 0) return 0;\n return dot / (Math.sqrt(normA) * Math.sqrt(normB));\n}\n\n/**\n * Check if user input semantically matches a set of trigger keywords.\n * Uses TF-IDF-like bag-of-words cosine similarity.\n * @returns similarity score (0-1)\n */\nexport function semanticSimilarity(userInput: string, triggers: string[]): number {\n const inputTokens = tokenize(userInput);\n if (inputTokens.length === 0) return 0;\n\n // Build trigger \"document\" from all trigger keywords\n const triggerTokens = triggers.flatMap((t) => tokenize(t));\n if (triggerTokens.length === 0) return 0;\n\n const inputTf = termFrequency(inputTokens);\n const triggerTf = termFrequency(triggerTokens);\n\n return cosineSimilarity(inputTf, triggerTf);\n}\n\nconst SEMANTIC_THRESHOLD = 0.15;\n\n/**\n * Enhanced matchSkills with semantic similarity fallback.\n */\nexport function matchSkillsSemantic(\n userInput: string,\n installedSkillNames: string[],\n runtimeTriggers: Map<string, string[]> = new Map(),\n): string[] {\n // First, get exact keyword matches\n const exact = matchSkills(userInput, installedSkillNames, runtimeTriggers);\n const matched = new Set(exact);\n\n // Then, check semantic similarity for skills not already matched\n for (const skillName of installedSkillNames) {\n if (matched.has(skillName)) continue;\n const triggers = SKILL_TRIGGERS[skillName];\n if (!triggers) continue;\n\n const sim = semanticSimilarity(userInput, triggers);\n if (sim >= SEMANTIC_THRESHOLD) {\n matched.add(skillName);\n }\n }\n\n for (const [skillName, triggers] of runtimeTriggers) {\n if (matched.has(skillName)) continue;\n const sim = semanticSimilarity(userInput, triggers);\n if (sim >= SEMANTIC_THRESHOLD) {\n matched.add(skillName);\n }\n }\n\n return Array.from(matched);\n}\n\n/**\n * Format skill context block for injection into system prompt.\n * Adapts detail level based on skill level.\n */\nexport function formatSkillContext(\n skillName: string,\n skillContent: string,\n level: { level: number; label: string },\n): string {\n let depthHint: string;\n if (level.level >= 4) {\n depthHint = \"User is advanced — skip basics, focus on edge cases and proactive optimization.\";\n } else if (level.level >= 3) {\n depthHint = \"User is proficient — brief reminders of principles, focus on the specific task.\";\n } else if (level.level >= 2) {\n depthHint = \"User is familiar — explain reasoning briefly, show patterns.\";\n } else {\n depthHint = \"User is learning — explain concepts clearly, show examples, be patient.\";\n }\n\n return `<active-skill name=\"${skillName}\" level=\"${level.level}\" label=\"${level.label}\">\n${depthHint}\n\n${skillContent}\n</active-skill>`;\n}\n\n/**\n * Auto-trigger skills based on user input.\n * Reads installed skills, matches keywords, injects context.\n * Returns formatted skill blocks to append to system prompt.\n */\nexport async function autoTriggerSkills(\n userInput: string,\n mcpManager: McpManager,\n): Promise<string> {\n try {\n // Get installed skills\n const result = await mcpManager.callTool(\"skill_list\", {});\n const skills = JSON.parse(result) as Array<{ name: string; description: string; installed: boolean }>;\n const installed = skills.filter((s) => s.installed).map((s) => s.name);\n\n // Load runtime (crystallized) triggers from ~/.askill/skills.md\n const skillsMdPath = path.join(os.homedir(), \".askill\", \"skills.md\");\n const runtimeTriggers = await loadRuntimeTriggers(skillsMdPath);\n\n if (installed.length === 0 && runtimeTriggers.size === 0) return \"\";\n\n // Match user input against skill triggers (keyword + semantic)\n const matched = matchSkillsSemantic(userInput, installed, runtimeTriggers);\n if (matched.length === 0) return \"\";\n\n // Load skill content and build context blocks\n const blocks: string[] = [];\n for (const skillName of matched.slice(0, 2)) { // max 2 skills per turn\n // Record activation and get level\n const level = recordActivation(skillName);\n\n // Read skill content from skills.md\n const skillsContent = await mcpManager.callTool(\"skill_search\", { query: skillName });\n const skillEntries = JSON.parse(skillsContent) as Array<{ name: string; description: string }>;\n const entry = skillEntries.find((s) => s.name.toLowerCase() === skillName.toLowerCase());\n\n if (entry) {\n blocks.push(formatSkillContext(skillName, entry.description, level));\n }\n\n log.debug(\"skill-engine\", `Auto-triggered: ${skillName} (Lv.${level.level} ${level.label})`);\n }\n\n return blocks.join(\"\\n\\n\");\n } catch (err) {\n log.debug(\"skill-engine\", \"autoTriggerSkills failed\", err);\n return \"\";\n }\n}\n\n// --- Self-Improving Skills ---\n\n/**\n * Enrich a skill with a user-specific pattern learned from conversation.\n * Called by memory-extractor when a \"pattern\" type extraction matches a skill domain.\n */\nexport function enrichSkill(skillName: string, pattern: string): void {\n const levels = loadSkillLevels();\n if (!levels[skillName]) {\n levels[skillName] = { name: skillName, activations: 0, lastUsed: \"\", userPatterns: [] };\n }\n\n // Deduplicate patterns\n const existing = levels[skillName].userPatterns;\n if (existing.length >= 20) return; // cap at 20 patterns per skill\n if (existing.some((p) => p.toLowerCase() === pattern.toLowerCase())) return;\n\n levels[skillName].userPatterns.push(pattern);\n saveSkillLevels(levels);\n log.debug(\"skill-engine\", `Enriched ${skillName} with pattern: ${pattern.slice(0, 80)}`);\n}\n\n/**\n * Get user-specific patterns for a skill (for injection into skill context).\n */\nexport function getSkillPatterns(skillName: string): string[] {\n const levels = loadSkillLevels();\n return levels[skillName]?.userPatterns || [];\n}\n\n/**\n * Match a memory extraction pattern to a skill domain.\n * Returns the skill name if the pattern is relevant, null otherwise.\n */\nexport function matchPatternToSkill(patternContent: string, tags: string[]): string | null {\n const combined = (patternContent + \" \" + tags.join(\" \")).toLowerCase();\n\n for (const [skillName, triggers] of Object.entries(SKILL_TRIGGERS)) {\n for (const trigger of triggers) {\n if (combined.includes(trigger)) {\n return skillName;\n }\n }\n }\n\n return null;\n}\n\n// --- Knowledge Library ---\n\nexport interface KnowledgeItem {\n name: string;\n category: string;\n description: string;\n content: string;\n}\n\nexport const KNOWLEDGE_LIBRARY: KnowledgeItem[] = [\n {\n name: \"security-headers\",\n category: \"security\",\n description: \"Essential HTTP security headers for web applications\",\n content: `Essential Security Headers:\n- Content-Security-Policy: default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'\n- X-Content-Type-Options: nosniff\n- X-Frame-Options: DENY\n- Strict-Transport-Security: max-age=31536000; includeSubDomains; preload\n- X-XSS-Protection: 0 (CSP replaces this)\n- Referrer-Policy: strict-origin-when-cross-origin\n- Permissions-Policy: camera=(), microphone=(), geolocation=()`,\n },\n {\n name: \"docker-node\",\n category: \"deployment\",\n description: \"Production Node.js Dockerfile template\",\n content: `FROM node:22-alpine AS builder\nWORKDIR /app\nCOPY package*.json ./\nRUN npm ci --production=false\nCOPY . .\nRUN npm run build\n\nFROM node:22-alpine\nWORKDIR /app\nRUN addgroup -g 1001 -S nodejs && adduser -S appuser -u 1001\nCOPY --from=builder /app/dist ./dist\nCOPY --from=builder /app/node_modules ./node_modules\nCOPY --from=builder /app/package.json ./\nUSER appuser\nEXPOSE 3000\nCMD [\"node\", \"dist/index.js\"]`,\n },\n {\n name: \"github-actions-node\",\n category: \"ci\",\n description: \"CI/CD pipeline for Node.js with GitHub Actions\",\n content: `name: CI\non: [push, pull_request]\njobs:\n build:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v5\n - uses: actions/setup-node@v5\n with: { node-version: 22 }\n - run: npm ci\n - run: npm test\n - run: npm run build`,\n },\n {\n name: \"env-config\",\n category: \"configuration\",\n description: \"Environment variable configuration pattern with validation\",\n content: `import { z } from \"zod\";\n\nconst envSchema = z.object({\n NODE_ENV: z.enum([\"development\", \"production\", \"test\"]).default(\"development\"),\n PORT: z.coerce.number().default(3000),\n DATABASE_URL: z.string().url(),\n API_KEY: z.string().min(1),\n});\n\nexport const env = envSchema.parse(process.env);`,\n },\n {\n name: \"error-handling\",\n category: \"patterns\",\n description: \"TypeScript error handling patterns with Result type\",\n content: `type Result<T, E = Error> = { ok: true; value: T } | { ok: false; error: E };\n\nfunction ok<T>(value: T): Result<T, never> { return { ok: true, value }; }\nfunction err<E>(error: E): Result<never, E> { return { ok: false, error }; }\n\n// Usage:\nasync function fetchUser(id: string): Promise<Result<User>> {\n try {\n const user = await db.users.findUnique({ where: { id } });\n if (!user) return err(new Error(\"User not found\"));\n return ok(user);\n } catch (e) {\n return err(e instanceof Error ? e : new Error(String(e)));\n }\n}`,\n },\n {\n name: \"rate-limiter\",\n category: \"security\",\n description: \"Token bucket rate limiter implementation\",\n content: `class RateLimiter {\n private tokens: Map<string, { count: number; resetAt: number }> = new Map();\n\n constructor(private maxRequests: number, private windowMs: number) {}\n\n allow(key: string): boolean {\n const now = Date.now();\n const entry = this.tokens.get(key);\n if (!entry || now > entry.resetAt) {\n this.tokens.set(key, { count: 1, resetAt: now + this.windowMs });\n return true;\n }\n if (entry.count >= this.maxRequests) return false;\n entry.count++;\n return true;\n }\n}`,\n },\n {\n name: \"prisma-setup\",\n category: \"database\",\n description: \"Prisma ORM setup with connection pooling\",\n content: `import { PrismaClient } from \"@prisma/client\";\n\nconst globalForPrisma = globalThis as unknown as { prisma: PrismaClient };\nexport const prisma = globalForPrisma.prisma ?? new PrismaClient({\n log: process.env.NODE_ENV === \"development\" ? [\"query\", \"error\", \"warn\"] : [\"error\"],\n});\nif (process.env.NODE_ENV !== \"production\") globalForPrisma.prisma = prisma;`,\n },\n {\n name: \"zod-validation\",\n category: \"validation\",\n description: \"Zod schema patterns for API input validation\",\n content: `import { z } from \"zod\";\n\nconst CreateUserSchema = z.object({\n email: z.string().email(),\n name: z.string().min(1).max(100),\n age: z.number().int().min(13).max(150).optional(),\n role: z.enum([\"user\", \"admin\"]).default(\"user\"),\n tags: z.array(z.string()).max(10).default([]),\n});\n\ntype CreateUser = z.infer<typeof CreateUserSchema>;\n\n// Express middleware:\nfunction validate<T>(schema: z.ZodSchema<T>) {\n return (req, res, next) => {\n const result = schema.safeParse(req.body);\n if (!result.success) return res.status(400).json({ errors: result.error.flatten() });\n req.body = result.data;\n next();\n };\n}`,\n },\n {\n name: \"testing-patterns\",\n category: \"testing\",\n description: \"Test organization and assertion patterns\",\n content: `// Arrange-Act-Assert pattern\ndescribe(\"UserService\", () => {\n it(\"creates user with valid email\", async () => {\n // Arrange\n const input = { email: \"test@example.com\", name: \"Test\" };\n\n // Act\n const user = await userService.create(input);\n\n // Assert\n expect(user.id).toBeDefined();\n expect(user.email).toBe(input.email);\n });\n\n it(\"rejects duplicate email\", async () => {\n await userService.create({ email: \"dup@test.com\", name: \"First\" });\n await expect(userService.create({ email: \"dup@test.com\", name: \"Second\" }))\n .rejects.toThrow(\"already exists\");\n });\n});`,\n },\n {\n name: \"git-hooks\",\n category: \"git\",\n description: \"Pre-commit and commit-msg hooks with lint-staged\",\n content: `// package.json\n{\n \"lint-staged\": {\n \"*.{ts,tsx}\": [\"eslint --fix\", \"prettier --write\"],\n \"*.{json,md}\": [\"prettier --write\"]\n }\n}\n\n// .husky/pre-commit\nnpx lint-staged\n\n// .husky/commit-msg\nnpx commitlint --edit $1\n\n// commitlint.config.js\nmodule.exports = { extends: [\"@commitlint/config-conventional\"] };`,\n },\n];\n\n/**\n * Search knowledge library by query.\n */\nexport function searchKnowledge(query: string): KnowledgeItem[] {\n const q = query.toLowerCase();\n return KNOWLEDGE_LIBRARY.filter(\n (item) =>\n item.name.includes(q) ||\n item.category.includes(q) ||\n item.description.toLowerCase().includes(q),\n );\n}\n\n/**\n * Auto-suggest knowledge items based on conversation context.\n * Returns formatted knowledge block if relevant item found.\n */\nexport function matchKnowledge(userInput: string): KnowledgeItem | null {\n const input = userInput.toLowerCase();\n\n // Direct keyword matches\n const keywordMap: Record<string, string> = {\n \"security header\": \"security-headers\",\n \"csp\": \"security-headers\",\n \"content-security\": \"security-headers\",\n \"dockerfile\": \"docker-node\",\n \"docker\": \"docker-node\",\n \"github action\": \"github-actions-node\",\n \"ci/cd\": \"github-actions-node\",\n \"ci pipeline\": \"github-actions-node\",\n \"env config\": \"env-config\",\n \"environment variable\": \"env-config\",\n \"error handling\": \"error-handling\",\n \"result type\": \"error-handling\",\n \"rate limit\": \"rate-limiter\",\n \"throttle\": \"rate-limiter\",\n \"prisma\": \"prisma-setup\",\n \"zod\": \"zod-validation\",\n \"validation\": \"zod-validation\",\n \"test pattern\": \"testing-patterns\",\n \"arrange act assert\": \"testing-patterns\",\n \"git hook\": \"git-hooks\",\n \"pre-commit\": \"git-hooks\",\n \"lint-staged\": \"git-hooks\",\n \"husky\": \"git-hooks\",\n };\n\n for (const [keyword, itemName] of Object.entries(keywordMap)) {\n if (input.includes(keyword)) {\n return KNOWLEDGE_LIBRARY.find((i) => i.name === itemName) || null;\n }\n }\n\n return null;\n}\n","interface ErrorMapping {\n pattern: RegExp;\n message: string;\n}\n\nconst ERROR_MAPPINGS: ErrorMapping[] = [\n { pattern: /rate.?limit|429/i, message: \"Rate limited. I'll retry automatically.\" },\n { pattern: /401|unauthorized/i, message: \"API key invalid. Run /reset config to fix.\" },\n { pattern: /403|forbidden/i, message: \"API key doesn't have access to this model. Try a different model with --model.\" },\n { pattern: /fetch failed|network/i, message: \"Network error. Check your internet connection.\" },\n { pattern: /ECONNREFUSED/i, message: \"Can't reach the API. Are you behind a proxy or firewall?\" },\n { pattern: /context.?length/i, message: \"Conversation too long. Use /clear to start fresh or I'll auto-trim.\" },\n { pattern: /overloaded/i, message: \"API is overloaded. Retrying in a moment...\" },\n { pattern: /ETIMEDOUT/i, message: \"Request timed out. Retrying...\" },\n];\n\nexport function humanizeError(message: string): string {\n for (const mapping of ERROR_MAPPINGS) {\n if (mapping.pattern.test(message)) {\n return mapping.message;\n }\n }\n return message;\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport os from \"node:os\";\n\nexport interface HintState {\n turnCount: number;\n shownHints: Set<string>;\n hintShownThisSession: boolean;\n}\n\ninterface HintContext {\n hasWorkflows: boolean;\n memoryCount: number;\n}\n\ninterface HintDef {\n id: string;\n minTurn: number;\n condition: (ctx: HintContext) => boolean;\n text: string;\n}\n\nconst HINTS: HintDef[] = [\n {\n id: \"eval\",\n minTurn: 15,\n condition: () => true,\n text: \"Tip: See how our relationship has evolved with /eval\",\n },\n {\n id: \"memory-search\",\n minTurn: 3,\n condition: (ctx) => ctx.memoryCount >= 10,\n text: \"Tip: Search everything I remember with /memory search <query>\",\n },\n {\n id: \"workflows\",\n minTurn: 5,\n condition: (ctx) => !ctx.hasWorkflows,\n text: \"Tip: Teach me multi-step processes with /workflows add\",\n },\n {\n id: \"rules\",\n minTurn: 8,\n condition: () => true,\n text: \"Tip: Set guardrails for what I should/shouldn't do with /rules\",\n },\n];\n\nexport function getHint(state: HintState, ctx: HintContext): string | null {\n if (state.hintShownThisSession) return null;\n\n for (const hint of HINTS) {\n if (state.turnCount >= hint.minTurn && !state.shownHints.has(hint.id) && hint.condition(ctx)) {\n state.shownHints.add(hint.id);\n state.hintShownThisSession = true;\n return hint.text;\n }\n }\n\n return null;\n}\n\nconst HINTS_FILE = path.join(os.homedir(), \".aman-agent\", \"hints-seen.json\");\n\nexport function loadShownHints(): Set<string> {\n try {\n if (fs.existsSync(HINTS_FILE)) {\n const data = JSON.parse(fs.readFileSync(HINTS_FILE, \"utf-8\"));\n return new Set(Array.isArray(data) ? data : []);\n }\n } catch { /* ignore */ }\n return new Set();\n}\n\nexport function saveShownHints(shown: Set<string>): void {\n try {\n const dir = path.dirname(HINTS_FILE);\n fs.mkdirSync(dir, { recursive: true });\n fs.writeFileSync(HINTS_FILE, JSON.stringify([...shown]), \"utf-8\");\n } catch { /* non-critical */ }\n}\n","export type PresetName = \"coding\" | \"creative\" | \"assistant\" | \"learning\" | \"minimal\";\n\ninterface PresetRule {\n category: string;\n rule: string;\n}\n\ninterface PresetWorkflow {\n name: string;\n description: string;\n steps: string[];\n}\n\ninterface Preset {\n identity: { personality: string; style: string };\n rules: PresetRule[];\n workflows: PresetWorkflow[];\n}\n\nexport const PRESETS: Record<PresetName, Preset> = {\n coding: {\n identity: {\n personality: \"Direct, technical, concise. Shows code over explanation.\",\n style: \"Use short answers. Lead with the solution, explain after.\",\n },\n rules: [\n { category: \"response\", rule: \"Always show code examples, not just descriptions\" },\n { category: \"safety\", rule: \"Never execute destructive commands without confirmation\" },\n { category: \"quality\", rule: \"Follow project conventions over personal preference\" },\n ],\n workflows: [\n { name: \"debug\", description: \"Systematic debugging process\", steps: [\"Reproduce the issue\", \"Identify root cause\", \"Propose fix\", \"Verify fix\"] },\n ],\n },\n creative: {\n identity: {\n personality: \"Warm, imaginative, encouraging. Explores multiple angles.\",\n style: \"Use metaphors and vivid language. Ask 'what if' questions.\",\n },\n rules: [\n { category: \"response\", rule: \"Always offer 2-3 alternative approaches\" },\n { category: \"tone\", rule: \"Encourage experimentation, never dismiss ideas\" },\n ],\n workflows: [\n { name: \"brainstorm\", description: \"Creative brainstorming process\", steps: [\"Explore the problem space\", \"Generate 5+ ideas\", \"Evaluate trade-offs\", \"Refine top 2\"] },\n ],\n },\n assistant: {\n identity: {\n personality: \"Organized, proactive, action-oriented.\",\n style: \"Use bullet points and checklists. Summarize key takeaways.\",\n },\n rules: [\n { category: \"response\", rule: \"End responses with clear next steps when applicable\" },\n { category: \"memory\", rule: \"Always track deadlines and commitments mentioned\" },\n ],\n workflows: [\n { name: \"plan\", description: \"Task planning process\", steps: [\"Clarify the goal\", \"Break into tasks\", \"Prioritize\", \"Set deadlines\"] },\n ],\n },\n learning: {\n identity: {\n personality: \"Patient, curious, Socratic. Builds understanding layer by layer.\",\n style: \"Use analogies. Check understanding before moving on.\",\n },\n rules: [\n { category: \"response\", rule: \"Explain concepts before showing solutions\" },\n { category: \"teaching\", rule: \"Ask a follow-up question to reinforce learning\" },\n ],\n workflows: [],\n },\n minimal: {\n identity: {\n personality: \"Helpful and adaptive. Matches the user's tone and needs.\",\n style: \"Clear and concise. Prioritizes usefulness over verbosity.\",\n },\n rules: [],\n workflows: [],\n },\n};\n\ninterface PresetResult {\n coreMd: string;\n rulesMd: string | null;\n flowMd: string | null;\n}\n\nexport function applyPreset(name: PresetName, companionName: string): PresetResult {\n const preset = PRESETS[name];\n\n const coreMd = [\n `# ${companionName}`,\n \"\",\n \"## Personality\",\n preset.identity.personality,\n \"\",\n \"## Style\",\n preset.identity.style,\n \"\",\n \"## Session\",\n \"_New companion — no prior sessions._\",\n ].join(\"\\n\");\n\n let rulesMd: string | null = null;\n if (preset.rules.length > 0) {\n const grouped = new Map<string, string[]>();\n for (const r of preset.rules) {\n if (!grouped.has(r.category)) grouped.set(r.category, []);\n grouped.get(r.category)!.push(r.rule);\n }\n const sections = [...grouped.entries()]\n .map(([cat, rules]) => `## ${cat}\\n${rules.map((r) => `- ${r}`).join(\"\\n\")}`)\n .join(\"\\n\\n\");\n rulesMd = `# Guardrails\\n\\n${sections}`;\n }\n\n let flowMd: string | null = null;\n if (preset.workflows.length > 0) {\n const wfSections = preset.workflows\n .map((wf) => {\n const steps = wf.steps.map((s, i) => `${i + 1}. ${s}`).join(\"\\n\");\n return `## ${wf.name}\\n${wf.description}\\n\\n${steps}`;\n })\n .join(\"\\n\\n\");\n flowMd = `# Workflows\\n\\n${wfSections}`;\n }\n\n return { coreMd, rulesMd, flowMd };\n}\n","import pc from \"picocolors\";\nimport * as p from \"@clack/prompts\";\nimport { startAgentServer, type RunningAgentServer } from \"./index.js\";\nimport { McpManager } from \"../mcp/client.js\";\nimport { pickLLMClient } from \"../llm/index.js\";\nimport { loadConfig, type AgentConfig, type HooksConfig } from \"../config.js\";\n\nexport interface ServeOptions {\n name: string;\n profile: string;\n}\n\n/**\n * Entry point for `aman-agent serve --name X --profile Y`.\n *\n * Process lifecycle:\n * 1. Load config + pick an LLM client (Task 0's factory honors\n * AMAN_AGENT_FAKE_LLM=1 and short-circuits to the fake client).\n * 2. Connect aman-mcp + any custom MCP servers from config. When\n * AMAN_AGENT_FAKE_LLM=1 we skip MCP entirely so Task 13's integration\n * test stays hermetic (no `npx -y @aman_asmuei/aman-mcp` fetch in CI).\n * 3. Start the A2A server (Task 7's `startAgentServer`).\n * 4. Install SIGINT/SIGTERM handlers, idempotent via `shuttingDown` guard,\n * which stop the server, disconnect MCP, then exit 0.\n * 5. Block forever on an unresolved promise so the event loop stays alive\n * until a signal fires.\n *\n * NOTE: `running.stop()` does not drain in-flight `agent.delegate` calls —\n * mid-flight delegations are cut off at shutdown. Acceptable for MVP.\n */\nexport async function runServe(opts: ServeOptions): Promise<void> {\n const config: AgentConfig | null = loadConfig();\n if (!config) {\n throw new Error(\n \"aman-agent is not configured. Run `aman-agent` once interactively to set up your provider before starting serve mode.\",\n );\n }\n const model = config.model ?? \"claude-sonnet-4-6\";\n\n p.intro(\n pc.bold(\"aman-agent serve\") +\n pc.dim(` — name=${opts.name} profile=${opts.profile}`),\n );\n\n // 1. LLM client (honors AMAN_AGENT_FAKE_LLM via the factory from Task 0)\n const client = pickLLMClient(config, model);\n\n // 2. MCP manager — matches the interactive baseline at src/index.ts:463–465:\n // ONLY aman-mcp is auto-connected (NOT amem). Custom mcpServers entries\n // are connected too, skipping the reserved names \"aman\" and \"amem\".\n // When AMAN_AGENT_FAKE_LLM=1 we skip MCP entirely so the A2A integration\n // test (Task 13) stays hermetic.\n const mcpManager = new McpManager();\n if (process.env.AMAN_AGENT_FAKE_LLM !== \"1\") {\n try {\n await mcpManager.connect(\"aman\", \"npx\", [\"-y\", \"@aman_asmuei/aman-mcp\"]);\n } catch (err) {\n p.log.warning(\n `aman-mcp unavailable — continuing without tools: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n if (config.mcpServers) {\n for (const [name, sc] of Object.entries(config.mcpServers)) {\n if (name === \"aman\" || name === \"amem\") continue;\n try {\n await mcpManager.connect(name, sc.command, sc.args, sc.env);\n } catch {\n /* connect() logs internally — warnings only, not fatal */\n }\n }\n }\n }\n\n // 3. Start the A2A server (wired by Task 7)\n const running: RunningAgentServer = await startAgentServer({\n name: opts.name,\n profile: opts.profile,\n client,\n mcpManager,\n hooksConfig: config.hooks as HooksConfig | undefined,\n });\n\n p.log.success(`registered as @${opts.name}`);\n p.log.info(\n `port ${running.entry.port} (127.0.0.1) — token is in ~/.aman-agent/registry.json (mode 0600)`,\n );\n\n // 4. Signal handlers. Guard against double-fire so SIGINT+SIGTERM in quick\n // succession doesn't call stop() twice — transport.close is not\n // guaranteed safe to call twice and an MCP SDK close on a torn-down\n // transport throws.\n let shuttingDown = false;\n const shutdown = async (signal: NodeJS.Signals) => {\n if (shuttingDown) return;\n shuttingDown = true;\n p.log.warning(`received ${signal}, unregistering @${opts.name}...`);\n try {\n await running.stop();\n } catch (err) {\n p.log.error(\n `stop failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n try {\n await mcpManager.disconnect();\n } catch {\n /* best effort — never block exit on MCP teardown */\n }\n p.outro(\"goodbye\");\n process.exit(0);\n };\n process.on(\"SIGINT\", shutdown);\n process.on(\"SIGTERM\", shutdown);\n\n // 5. Keep the event loop alive indefinitely — signal handlers call\n // process.exit(), so this promise never needs to resolve.\n await new Promise<never>(() => {\n /* never resolves */\n });\n}\n","import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport { createTransport, type ServerTransport } from \"./transport.js\";\nimport { registerAgent, unregisterAgent, type AgentEntry } from \"./registry.js\";\nimport { Inbox } from \"./inbox.js\";\nimport { infoHandler } from \"./tools/info.js\";\nimport { sendHandler } from \"./tools/send.js\";\nimport { delegateToolHandler, type DelegateContext } from \"./tools/delegate.js\";\nimport type { LLMClient } from \"../llm/types.js\";\nimport type { McpManager } from \"../mcp/client.js\";\nimport type { HooksConfig } from \"../config.js\";\nimport pkg from \"../../package.json\" with { type: \"json\" };\n\nexport interface StartAgentServerOptions {\n name: string;\n profile: string;\n client: LLMClient;\n mcpManager: McpManager;\n hooksConfig?: HooksConfig;\n}\n\nexport interface RunningAgentServer {\n entry: AgentEntry;\n inbox: Inbox;\n stop: () => Promise<void>;\n}\n\n/**\n * Assemble an `McpServer` exposing `agent.info`, `agent.delegate`, and\n * `agent.send`, bind it to a localhost HTTP transport with a bearer token,\n * and publish the resulting port/token to the shared registry for peers to\n * discover.\n *\n * Ordering is deliberate:\n *\n * 1. Transport bound and MCP server connected first — if anything in that\n * chain fails we throw before touching the registry, so there's no stale\n * entry to clean up.\n * 2. `registerAgent` runs only after a successful `mcp.connect`, meaning a\n * registry entry always points at a live, listening server.\n * 3. `stop()` unregisters BEFORE tearing down the transport, so remote\n * callers never see a registered entry pointing at a server that has\n * already begun shutting down.\n */\nexport async function startAgentServer(\n opts: StartAgentServerOptions,\n): Promise<RunningAgentServer> {\n const transport: ServerTransport = await createTransport();\n const inbox = new Inbox();\n const startedAt = Date.now();\n\n const delegateCtx: DelegateContext = {\n profile: opts.profile,\n client: opts.client,\n mcpManager: opts.mcpManager,\n hooksConfig: opts.hooksConfig,\n };\n\n const mcp = new McpServer({\n name: `aman-agent:${opts.name}`,\n version: pkg.version,\n });\n\n mcp.registerTool(\n \"agent.info\",\n {\n description: \"Return this agent's identity, profile, PID, and inbox depth.\",\n inputSchema: {},\n },\n async () => {\n const result = infoHandler({\n name: opts.name,\n profile: opts.profile,\n startedAt,\n inbox,\n });\n return { content: [{ type: \"text\", text: JSON.stringify(result) }] };\n },\n );\n\n mcp.registerTool(\n \"agent.delegate\",\n {\n description:\n \"Delegate a task to this agent. Returns the agent's final response text.\",\n inputSchema: {\n task: z.string().describe(\"The task to run against this agent's profile\"),\n context: z.string().optional().describe(\"Optional extra context\"),\n },\n },\n async (input) => {\n const result = await delegateToolHandler(delegateCtx, input);\n return { content: [{ type: \"text\", text: JSON.stringify(result) }] };\n },\n );\n\n mcp.registerTool(\n \"agent.send\",\n {\n description:\n \"Deliver a one-way message into this agent's inbox. Drained at next user turn.\",\n inputSchema: {\n from: z.string().optional(),\n topic: z.string().optional(),\n body: z.string(),\n },\n },\n async (input) => {\n const result = sendHandler(inbox, input);\n return { content: [{ type: \"text\", text: JSON.stringify(result) }] };\n },\n );\n\n try {\n await mcp.connect(transport.mcpTransport);\n } catch (err) {\n // Connect failed — tear down the transport we already bound so we don't\n // leak a listening port, then rethrow.\n await transport.close();\n throw err;\n }\n\n const entry: AgentEntry = {\n name: opts.name,\n profile: opts.profile,\n pid: process.pid,\n port: transport.port,\n token: transport.token,\n started_at: startedAt,\n version: pkg.version,\n };\n await registerAgent(entry);\n\n return {\n entry,\n inbox,\n stop: async () => {\n try {\n await unregisterAgent(opts.name);\n } catch {\n /* best effort — don't let a registry hiccup block teardown */\n }\n try {\n await mcp.close();\n } catch {\n /* best effort — don't let a flaky SDK close leak the transport */\n }\n await transport.close();\n },\n };\n}\n","import http from \"node:http\";\nimport crypto from \"node:crypto\";\nimport { StreamableHTTPServerTransport } from \"@modelcontextprotocol/sdk/server/streamableHttp.js\";\n\n/**\n * Handle for a running localhost MCP transport.\n *\n * Downstream code (Task 7 `startAgentServer`) hands `mcpTransport` to\n * `McpServer.connect(...)`. Task 12 (`/agents ping`) uses `port` + `token`\n * to hit the `/health` endpoint. Task 10 (`delegateRemote`) uses them to\n * dial `/mcp` via the MCP client transport.\n */\nexport interface ServerTransport {\n port: number;\n token: string;\n httpServer: http.Server;\n mcpTransport: StreamableHTTPServerTransport;\n close: () => Promise<void>;\n}\n\n/**\n * Check a request's `Authorization: Bearer <token>` header against the\n * expected token. Uses a constant-time comparison to avoid leaking token\n * bytes via response-timing side channels.\n */\nfunction authOk(req: http.IncomingMessage, token: string): boolean {\n const header = req.headers[\"authorization\"];\n if (!header || typeof header !== \"string\") return false;\n const m = header.match(/^Bearer\\s+(.+)$/);\n if (!m) return false;\n const a = Buffer.from(m[1]);\n const b = Buffer.from(token);\n if (a.length !== b.length) return false;\n return crypto.timingSafeEqual(a, b);\n}\n\n/**\n * Bind an HTTP server to `127.0.0.1` on an ephemeral port, protected by a\n * freshly generated 32-byte hex bearer token. Routes:\n *\n * - `GET /health` -> `{ ok: true }` (200)\n * - `/mcp*` -> `StreamableHTTPServerTransport.handleRequest`\n *\n * Every request (including `/health`) requires the bearer — this is\n * intentional; there are no anonymous endpoints.\n *\n * The caller is responsible for calling `close()` when the server is no\n * longer needed; `close()` tears down the MCP transport and frees the port.\n */\nexport async function createTransport(): Promise<ServerTransport> {\n const token = crypto.randomBytes(32).toString(\"hex\");\n const mcpTransport = new StreamableHTTPServerTransport({\n sessionIdGenerator: () => crypto.randomUUID(),\n });\n\n const httpServer = http.createServer(async (req, res) => {\n if (!authOk(req, token)) {\n res.statusCode = 401;\n res.setHeader(\"WWW-Authenticate\", \"Bearer\");\n res.setHeader(\"content-type\", \"application/json\");\n res.end(JSON.stringify({ error: \"unauthorized\" }));\n return;\n }\n\n if (req.url === \"/health\") {\n res.statusCode = 200;\n res.setHeader(\"content-type\", \"application/json\");\n res.end(JSON.stringify({ ok: true }));\n return;\n }\n\n if (req.url?.startsWith(\"/mcp\")) {\n await mcpTransport.handleRequest(req, res);\n return;\n }\n\n res.statusCode = 404;\n res.end();\n });\n\n await new Promise<void>((resolve, reject) => {\n const onError = (err: Error) => reject(err);\n httpServer.once(\"error\", onError);\n httpServer.listen(0, \"127.0.0.1\", () => {\n httpServer.off(\"error\", onError);\n resolve();\n });\n });\n\n const addr = httpServer.address();\n if (!addr || typeof addr === \"string\") {\n throw new Error(\"failed to bind localhost port\");\n }\n\n return {\n port: addr.port,\n token,\n httpServer,\n mcpTransport,\n close: async () => {\n try {\n await mcpTransport.close();\n } catch {\n /* ignore — best-effort teardown */\n }\n await new Promise<void>((resolve) => httpServer.close(() => resolve()));\n },\n };\n}\n","export interface InboxMessage {\n id: string;\n from: string; // sender agent name or \"user\"\n topic?: string;\n body: string;\n received_at: number;\n}\n\nexport class Inbox {\n private queue: InboxMessage[] = [];\n private counter = 0;\n\n enqueue(msg: Omit<InboxMessage, \"id\" | \"received_at\">): InboxMessage {\n const full: InboxMessage = {\n ...msg,\n id: `inbox-${++this.counter}`,\n received_at: Date.now(),\n };\n this.queue.push(full);\n return full;\n }\n\n peek(): readonly InboxMessage[] {\n return [...this.queue];\n }\n\n drain(): InboxMessage[] {\n const out = this.queue;\n this.queue = [];\n return out;\n }\n\n get count(): number {\n return this.queue.length;\n }\n}\n","{\n \"name\": \"@aman_asmuei/aman-agent\",\n \"version\": \"0.41.0\",\n \"description\": \"Your AI companion, running locally — powered by the aman ecosystem\",\n \"type\": \"module\",\n \"engines\": {\n \"node\": \">=18.0.0\"\n },\n \"bin\": {\n \"aman-agent\": \"./bin/aman-agent.js\"\n },\n \"main\": \"./dist/index.js\",\n \"files\": [\n \"dist\",\n \"bin\"\n ],\n \"scripts\": {\n \"build\": \"tsup\",\n \"dev\": \"tsup --watch\",\n \"lint\": \"tsc --noEmit\",\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\",\n \"prepublishOnly\": \"npm run build\"\n },\n \"dependencies\": {\n \"@aman_asmuei/aman-core\": \"^0.3.0\",\n \"@aman_asmuei/acore-core\": \"^0.2.0\",\n \"@aman_asmuei/arules-core\": \"^0.2.0\",\n \"@aman_asmuei/amem-core\": \"^0.5.0\",\n \"@anthropic-ai/sdk\": \"^0.39.0\",\n \"@clack/prompts\": \"^0.9.1\",\n \"@modelcontextprotocol/sdk\": \"^1.27.1\",\n \"commander\": \"^13.1.0\",\n \"log-update\": \"^7.2.0\",\n \"marked\": \"^15.0.12\",\n \"marked-terminal\": \"^7.3.0\",\n \"openai\": \"^4.80.0\",\n \"picocolors\": \"^1.1.1\",\n \"zod\": \"^3.25.0\"\n },\n \"devDependencies\": {\n \"@types/marked-terminal\": \"^6.1.1\",\n \"@types/node\": \"^22.0.0\",\n \"tsup\": \"^8.4.0\",\n \"typescript\": \"^5.7.0\",\n \"vitest\": \"^4.1.0\"\n },\n \"keywords\": [\n \"ai\",\n \"agent\",\n \"companion\",\n \"aman\",\n \"llm\",\n \"claude\",\n \"openai\"\n ],\n \"author\": \"Aman Asmuei\",\n \"license\": \"MIT\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/amanasmuei/aman-agent.git\"\n }\n}\n","import type { Inbox } from \"../inbox.js\";\nimport pkg from \"../../../package.json\" with { type: \"json\" };\n\nexport interface InfoContext {\n name: string;\n profile: string;\n startedAt: number;\n inbox: Inbox;\n}\n\nexport interface InfoResult {\n name: string;\n profile: string;\n pid: number;\n started_at: number;\n pending_inbox: number;\n version: string;\n}\n\n/**\n * Handler for the `agent.info` MCP tool. Returns the running agent's\n * identity, profile, PID, startup timestamp, inbox depth, and version.\n *\n * Pure function — has no side effects and reads no global state beyond\n * `process.pid` and the imported `package.json` version.\n */\nexport function infoHandler(ctx: InfoContext): InfoResult {\n return {\n name: ctx.name,\n profile: ctx.profile,\n pid: process.pid,\n started_at: ctx.startedAt,\n pending_inbox: ctx.inbox.count,\n version: pkg.version,\n };\n}\n","import type { Inbox } from \"../inbox.js\";\n\nexport interface SendInput {\n from?: string;\n topic?: string;\n body: string;\n}\n\nexport interface SendResult {\n ok: boolean;\n id?: string;\n error?: string;\n}\n\nconst MAX_BODY_BYTES = 8 * 1024;\n\n/**\n * Handler for the `agent.send` MCP tool. Validates a one-way message\n * and enqueues it on the target agent's inbox. Messages sit in-memory\n * until the agent drains them at the start of its next user turn.\n *\n * Not durable — if the agent crashes before drain, the message is lost.\n */\nexport function sendHandler(inbox: Inbox, input: SendInput): SendResult {\n if (!input.body || input.body.trim() === \"\") {\n return { ok: false, error: \"empty body\" };\n }\n if (Buffer.byteLength(input.body, \"utf8\") > MAX_BODY_BYTES) {\n return { ok: false, error: \"body too large\" };\n }\n const msg = inbox.enqueue({\n from: input.from ?? \"unknown\",\n topic: input.topic,\n body: input.body,\n });\n return { ok: true, id: msg.id };\n}\n","import type { LLMClient } from \"../../llm/types.js\";\nimport type { McpManager } from \"../../mcp/client.js\";\nimport type { HooksConfig } from \"../../config.js\";\nimport { delegateTask } from \"../../delegate.js\";\n\nexport interface DelegateContext {\n profile: string;\n client: LLMClient;\n mcpManager: McpManager;\n hooksConfig?: HooksConfig;\n}\n\nexport interface DelegateInput {\n task: string;\n context?: string;\n}\n\nexport interface DelegateToolResult {\n ok: boolean;\n text?: string;\n turns?: number;\n tools_used?: string[];\n error?: string;\n}\n\nconst MAX_TASK_BYTES = 64 * 1024;\n\n/**\n * Handler for the `agent.delegate` MCP tool. Wraps the existing local\n * `delegateTask` so a remote agent can run a full delegation loop\n * (LLM + tools) through this agent's profile and return the final text.\n *\n * Task 7 registers this as the `agent.delegate` tool on the MCP server.\n */\nexport async function delegateToolHandler(\n ctx: DelegateContext,\n input: DelegateInput,\n): Promise<DelegateToolResult> {\n if (!input.task || input.task.trim() === \"\") {\n return { ok: false, error: \"empty task\" };\n }\n if (Buffer.byteLength(input.task, \"utf8\") > MAX_TASK_BYTES) {\n return { ok: false, error: \"task too large\" };\n }\n\n const composed = input.context\n ? `${input.context}\\n\\n---\\n\\n${input.task}`\n : input.task;\n\n try {\n const result = await delegateTask(\n composed,\n ctx.profile,\n ctx.client,\n ctx.mcpManager,\n { silent: true, hooksConfig: ctx.hooksConfig },\n );\n if (!result.success) {\n return { ok: false, error: result.error ?? \"delegation failed\" };\n }\n return {\n ok: true,\n text: result.response,\n turns: result.turns,\n tools_used: result.toolsUsed,\n };\n } catch (err) {\n return {\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n };\n }\n}\n"],"mappings":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O,YAAY;AAClB,QAAMC,QAAO,QAAQ;AAErB,MAAI,CAAC,QAAQ,MAAM,OAAO;AACxB,IAAAN,KAAG,OAAOM,OAAM,EAAE,WAAW,MAAM,OAAO,KAAK,CAAC;AAChD,YAAQ,IAAI,oBAAeA,KAAI;AAC/B;AAAA,EACF;AAEA,QAAMC,WAAU,MAAQ,WAAQ;AAAA,IAC9B,SAAS,oBAAoBD,KAAI;AAAA,EACnC,CAAC;AACD,MAAI,CAACC,YAAa,YAASA,QAAO,GAAG;AACnC,YAAQ,IAAI,YAAY;AACxB;AAAA,EACF;AAEA,EAAAP,KAAG,OAAOM,OAAM,EAAE,WAAW,MAAM,OAAO,KAAK,CAAC;AAChD,UAAQ,IAAI,oBAAeA,KAAI;AAC/B,UAAQ,IAAI,EAAE;AACd,UAAQ,IAAI,qEAAqE;AACjF,UAAQ,IAAI,qDAAqD;AACnE,CAAC;AAEH,QAAQ,MAAM;","names":["text","fs","path","os","fs","path","os","p","fs","path","os","Client","text","node","text","fs","path","z","init_types","init_types","execFile","promisify","GhError","execFileAsync","init_types","init_types","init_types","fs","path","os","createDatabase","recall","acoreGetIdentity","arulesListCategories","buildContext","db","AGENT_SCOPE","text","p","fs","path","p","fs","path","ctx","buildContext","p","pc","p","fs","path","os","home","os","path","fs","fs","path","os","fs","path","path","fs","home","path","fs","os","text","text","spawn","execFileSync","extractText","formatConversation","text","parseToolUses","text","OpenAI","OpenAI","text","fs","path","os","pc","fs","path","os","execFileSync","pc","fs","path","os","loadConfig","saveConfig","path","os","fs","db","path","os","loadConfig","saveConfig","db","fs","path","os","p","path","os","fs","fs","path","os","home","fs","path","os","p","pc","pc","p","fs","path","os","text","p","fs","path","os","fs","path","os","path","os","defaultObservationsDir","text","p","fs","fs","path","timeContext","pc","path","fs","os","delegateRemote","recall","pc","node","log","node","node","readFile","node","node","fs","path","os","fs","path","path","os","node","StreamableHTTPClientTransport","Client","fs","path","os","pc","path","os","fs","pc","fs","path","os","text","p","fs","path","os","pc","fs","pc","model","p","home","os","path","content","text","result","configDir","execFileSync","members","task","profile","StreamableHTTPClientTransport","Client","text","fs","path","os","path","os","fs","text","cosineSimilarity","path","os","p","reflect","isReflectionDue","fs","path","os","p","isRetryable","pc","path","os","fs","recall","loadUserModel","computeProfile","model","hour","predictBurnout","input","result","fs","path","pc","p","z","z","pc","path","fs","pc","runDev","scanStack","EDITOR_TARGETS","execFileSync","home","confirm"]}
1
+ {"version":3,"sources":["../src/token-budget.ts","../src/logger.ts","../src/user-model.ts","../src/server/registry.ts","../src/delegate-remote.ts","../src/orchestrator/types.ts","../src/orchestrator/dag.ts","../src/orchestrator/decompose.ts","../src/dev/stack-detector.ts","../src/github/types.ts","../src/github/cli.ts","../src/github/issue-planner.ts","../src/github/pr-manager.ts","../src/github/ci-gate.ts","../src/github/index.ts","../src/dev/context-builder.ts","../src/dev/claude-md-writer.ts","../src/dev/dev-command.ts","../src/index.ts","../src/config.ts","../src/migrate.ts","../src/prompt.ts","../src/user-identity.ts","../src/llm/anthropic.ts","../src/llm/claude-code.ts","../src/llm/copilot.ts","../src/llm/ollama.ts","../src/llm/openai-compat.ts","../src/llm/openai.ts","../src/llm/index.ts","../src/mcp/client.ts","../src/retry.ts","../src/agent.ts","../src/commands.ts","../src/layers/parsers.ts","../src/memory.ts","../src/profile-templates.ts","../src/profiles/orchestrator-profiles.ts","../src/onboarding.ts","../src/showcase-bridge.ts","../src/files.ts","../src/delegate.ts","../src/hooks.ts","../src/personality.ts","../src/postmortem.ts","../src/observation.ts","../src/crystallization.ts","../src/orchestrator/index.ts","../src/orchestrator/state-machine.ts","../src/orchestrator/model-router.ts","../src/orchestrator/audit.ts","../src/orchestrator/scheduler.ts","../src/orchestrator/review-loop.ts","../src/orchestrator/circuit-breaker.ts","../src/orchestrator/checkpoint.ts","../src/orchestrator/cost-tracker.ts","../src/orchestrator/policy.ts","../src/orchestrator/runner.ts","../src/orchestrator/smart-orchestrate.ts","../src/orchestrator/templates/index.ts","../src/project/detector.ts","../src/profiles/auto-install.ts","../src/teams.ts","../src/plans.ts","../src/background.ts","../src/context-manager.ts","../src/memory-extractor.ts","../src/skill-engine.ts","../src/errors.ts","../src/hints.ts","../src/presets.ts","../src/server/serve-command.ts","../src/server/index.ts","../src/server/transport.ts","../src/server/inbox.ts","../package.json","../src/server/tools/info.ts","../src/server/tools/send.ts","../src/server/tools/delegate.ts"],"sourcesContent":["// Rough token estimation: ~1.3 tokens per word for English markdown\nexport function estimateTokens(text: string): number {\n return Math.round(text.split(/\\s+/).filter(Boolean).length * 1.3);\n}\n\n// Priority order for system prompt components (highest to lowest)\nconst PRIORITIES = [\n \"identity\", // core.md — always include\n \"user\", // user.md — user profile, always include\n \"guardrails\", // rules.md — safety critical\n \"workflows\", // flow.md — behavioral\n \"tools\", // kit.md — capabilities\n \"skills\", // skills.md — can be truncated\n];\n\nexport interface PromptComponent {\n name: string;\n content: string;\n tokens: number;\n}\n\nexport function buildBudgetedPrompt(\n components: PromptComponent[],\n maxTokens: number = 8000, // default budget for system prompt\n): { prompt: string; included: string[]; truncated: string[]; totalTokens: number } {\n const included: string[] = [];\n const truncated: string[] = [];\n const parts: string[] = [];\n let totalTokens = 0;\n\n // Sort by priority\n const sorted = [...components].sort((a, b) => {\n const aPri = PRIORITIES.indexOf(a.name);\n const bPri = PRIORITIES.indexOf(b.name);\n return (aPri === -1 ? 99 : aPri) - (bPri === -1 ? 99 : bPri);\n });\n\n for (const comp of sorted) {\n if (totalTokens + comp.tokens <= maxTokens) {\n parts.push(comp.content);\n included.push(comp.name);\n totalTokens += comp.tokens;\n } else {\n // Try to include a truncated version (first 50% of content)\n const halfContent = comp.content.slice(0, Math.floor(comp.content.length / 2));\n const halfTokens = estimateTokens(halfContent);\n if (totalTokens + halfTokens <= maxTokens) {\n parts.push(halfContent + \"\\n\\n[... truncated for context budget ...]\");\n included.push(comp.name + \" (partial)\");\n totalTokens += halfTokens;\n } else {\n truncated.push(comp.name);\n }\n }\n }\n\n return {\n prompt: parts.join(\"\\n\\n---\\n\\n\"),\n included,\n truncated,\n totalTokens,\n };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport os from \"node:os\";\n\nconst LOG_DIR = path.join(os.homedir(), \".aman-agent\");\nexport const LOG_PATH = path.join(LOG_DIR, \"debug.log\");\nconst MAX_LOG_SIZE = 1_048_576; // 1MB\n\ninterface LogEntry {\n timestamp: string;\n level: \"debug\" | \"warn\" | \"error\";\n module: string;\n message: string;\n data?: string;\n}\n\nfunction ensureDir(): void {\n if (!fs.existsSync(LOG_DIR)) {\n fs.mkdirSync(LOG_DIR, { recursive: true });\n }\n}\n\nfunction maybeRotate(): void {\n try {\n if (!fs.existsSync(LOG_PATH)) return;\n const stat = fs.statSync(LOG_PATH);\n if (stat.size >= MAX_LOG_SIZE) {\n const backupPath = LOG_PATH + \".1\";\n if (fs.existsSync(backupPath)) fs.unlinkSync(backupPath);\n fs.renameSync(LOG_PATH, backupPath);\n }\n } catch {\n // Rotation failure is non-critical\n }\n}\n\nfunction write(level: LogEntry[\"level\"], module: string, message: string, data?: unknown): void {\n try {\n ensureDir();\n maybeRotate();\n const entry: LogEntry = {\n timestamp: new Date().toISOString(),\n level,\n module,\n message,\n };\n if (data !== undefined) {\n entry.data = data instanceof Error ? data.message : String(data);\n }\n fs.appendFileSync(LOG_PATH, JSON.stringify(entry) + \"\\n\");\n } catch {\n // Logger must never throw\n }\n}\n\nexport const log = {\n debug: (module: string, message: string, data?: unknown) => write(\"debug\", module, message, data),\n warn: (module: string, message: string, data?: unknown) => write(\"warn\", module, message, data),\n error: (module: string, message: string, data?: unknown) => write(\"error\", module, message, data),\n};\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport os from \"node:os\";\nimport { log } from \"./logger.js\";\n\n// ── Types ──\n\nexport interface SessionSnapshot {\n sessionId: string;\n date: string;\n durationMinutes: number;\n turnCount: number;\n\n dominantSentiment: string;\n avgFrustration: number;\n avgExcitement: number;\n avgConfusion: number;\n avgFatigue: number;\n\n toolCalls: number;\n toolErrors: number;\n blockers: number;\n milestones: number;\n topicShifts: number;\n\n peakEnergy: string;\n primaryMode: string;\n timePeriod: string;\n\n rating?: string;\n hadPostmortem: boolean;\n wellbeingNudges: string[];\n}\n\nexport interface UserProfile {\n trustScore: number;\n trustTrajectory: \"ascending\" | \"stable\" | \"declining\";\n totalSessions: number;\n\n preferredTimePeriod: string;\n energyDistribution: Record<string, number>;\n avgSessionMinutes: number;\n\n baselineFrustration: number;\n baselineExcitement: number;\n sentimentTrend: \"improving\" | \"stable\" | \"worsening\";\n\n frustrationCorrelations: {\n toolErrors: number;\n longSessions: number;\n lateNight: number;\n };\n\n avgTurnsPerSession: number;\n engagementTrend: \"increasing\" | \"stable\" | \"decreasing\";\n\n nudgeStats: Record<string, { fired: number; sessionRatingAfter: number }>;\n}\n\nexport interface UserModel {\n version: 1;\n sessions: SessionSnapshot[];\n profile: UserProfile;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface PersonalityOverrides {\n energyOverride?: string;\n compactGreeting: boolean;\n frustrationNudgeThreshold: number;\n defaultToPersonalMode: boolean;\n}\n\n// ── Constants ──\n\nconst MAX_SESSIONS = 30;\nconst TRUST_ALPHA = 0.3;\nconst MIN_SESSIONS_FOR_FEED_FORWARD = 5;\nconst MIN_SESSIONS_FOR_CORRELATIONS = 10;\n\n// ── Default model path ──\n\nexport function defaultModelPath(): string {\n return path.join(os.homedir(), \".acore\", \"user-model.json\");\n}\n\n// ── Factory ──\n\nexport function createEmptyModel(): UserModel {\n const now = new Date().toISOString();\n return {\n version: 1,\n sessions: [],\n profile: emptyProfile(),\n createdAt: now,\n updatedAt: now,\n };\n}\n\nfunction emptyProfile(): UserProfile {\n return {\n trustScore: 0.5,\n trustTrajectory: \"stable\",\n totalSessions: 0,\n preferredTimePeriod: \"afternoon\",\n energyDistribution: {},\n avgSessionMinutes: 0,\n baselineFrustration: 0,\n baselineExcitement: 0,\n sentimentTrend: \"stable\",\n frustrationCorrelations: { toolErrors: 0, longSessions: 0, lateNight: 0 },\n avgTurnsPerSession: 0,\n engagementTrend: \"stable\",\n nudgeStats: {},\n };\n}\n\n// ── I/O ──\n\nexport async function loadUserModel(filePath?: string): Promise<UserModel | null> {\n const fp = filePath ?? defaultModelPath();\n try {\n const raw = await fs.readFile(fp, \"utf-8\");\n const parsed = JSON.parse(raw);\n if (parsed?.version !== 1) return null;\n return parsed as UserModel;\n } catch {\n return null;\n }\n}\n\nexport async function saveUserModel(model: UserModel, filePath?: string): Promise<void> {\n const fp = filePath ?? defaultModelPath();\n const dir = path.dirname(fp);\n await fs.mkdir(dir, { recursive: true });\n\n const tmp = fp + `.tmp-${Date.now()}`;\n await fs.writeFile(tmp, JSON.stringify(model, null, 2), \"utf-8\");\n await fs.rename(tmp, fp);\n}\n\n// ── Aggregation ──\n\nexport function aggregateSession(model: UserModel, snapshot: SessionSnapshot): UserModel {\n const sessions = [...model.sessions, snapshot];\n\n // Enforce rolling window\n while (sessions.length > MAX_SESSIONS) {\n sessions.shift();\n }\n\n const totalSessions = model.profile.totalSessions + 1;\n const profile = computeProfile(sessions, totalSessions);\n\n return {\n ...model,\n sessions,\n profile,\n updatedAt: new Date().toISOString(),\n };\n}\n\n// ── Profile Computation ──\n\nexport function computeProfile(sessions: SessionSnapshot[], totalSessions: number): UserProfile {\n if (sessions.length === 0) return { ...emptyProfile(), totalSessions };\n\n const n = sessions.length;\n\n // ── Trust Score (EMA) ──\n let trustScore = 0.5;\n for (const s of sessions) {\n trustScore = TRUST_ALPHA * ratingSignal(s) + (1 - TRUST_ALPHA) * trustScore;\n }\n\n // Trust trajectory: compare last 5 vs previous 5\n const trustTrajectory = computeTrustTrajectory(sessions);\n\n // ── Sentiment Baselines ──\n const baselineFrustration = avg(sessions.map((s) => s.avgFrustration));\n const baselineExcitement = avg(sessions.map((s) => s.avgExcitement));\n const sentimentTrend = computeSentimentTrend(sessions);\n\n // ── Energy Distribution ──\n const energyDistribution: Record<string, number> = {};\n for (const s of sessions) {\n energyDistribution[s.timePeriod] = (energyDistribution[s.timePeriod] || 0) + 1;\n }\n const preferredTimePeriod = Object.entries(energyDistribution).sort(\n (a, b) => b[1] - a[1],\n )[0]?.[0] ?? \"afternoon\";\n\n // ── Session Duration ──\n const avgSessionMinutes = avg(sessions.map((s) => s.durationMinutes));\n\n // ── Engagement ──\n const avgTurnsPerSession = avg(sessions.map((s) => s.turnCount));\n const engagementTrend = computeLinearTrend(sessions.map((s) => s.turnCount));\n\n // ── Frustration Correlations ──\n const frustrationCorrelations =\n n >= MIN_SESSIONS_FOR_CORRELATIONS\n ? {\n toolErrors: pearsonR(\n sessions.map((s) => s.avgFrustration),\n sessions.map((s) => s.toolErrors),\n ),\n longSessions: pearsonR(\n sessions.map((s) => s.avgFrustration),\n sessions.map((s) => s.durationMinutes),\n ),\n lateNight: pearsonR(\n sessions.map((s) => s.avgFrustration),\n sessions.map((s) => (s.timePeriod === \"late-night\" || s.timePeriod === \"night\" ? 1 : 0)),\n ),\n }\n : { toolErrors: 0, longSessions: 0, lateNight: 0 };\n\n // ── Nudge Stats ──\n const nudgeStats: Record<string, { fired: number; sessionRatingAfter: number }> = {};\n for (const s of sessions) {\n const ratingVal = ratingToNumber(s.rating);\n for (const nudge of s.wellbeingNudges) {\n if (!nudgeStats[nudge]) nudgeStats[nudge] = { fired: 0, sessionRatingAfter: 0 };\n nudgeStats[nudge].fired++;\n nudgeStats[nudge].sessionRatingAfter += ratingVal;\n }\n }\n for (const key of Object.keys(nudgeStats)) {\n if (nudgeStats[key].fired > 0) {\n nudgeStats[key].sessionRatingAfter /= nudgeStats[key].fired;\n }\n }\n\n return {\n trustScore,\n trustTrajectory,\n totalSessions,\n preferredTimePeriod,\n energyDistribution,\n avgSessionMinutes,\n baselineFrustration,\n baselineExcitement,\n sentimentTrend,\n frustrationCorrelations,\n avgTurnsPerSession,\n engagementTrend,\n nudgeStats,\n };\n}\n\n// ── Feed-Forward ──\n\nexport function feedForward(model: UserModel): PersonalityOverrides | null {\n if (model.profile.totalSessions < MIN_SESSIONS_FOR_FEED_FORWARD) return null;\n\n const p = model.profile;\n const overrides: PersonalityOverrides = {\n compactGreeting: false,\n frustrationNudgeThreshold: 0.6,\n defaultToPersonalMode: false,\n };\n\n // Night owl calibration: if 70%+ sessions are late-night/night with low frustration,\n // don't default to \"reflective\" — use \"steady\"\n const nightSessions =\n (p.energyDistribution[\"late-night\"] || 0) + (p.energyDistribution[\"night\"] || 0);\n const totalInWindow = model.sessions.length;\n if (totalInWindow > 0 && nightSessions / totalInWindow >= 0.7 && p.baselineFrustration < 0.3) {\n overrides.energyOverride = \"steady\";\n }\n\n // High trust → compact greeting\n if (p.trustScore > 0.8) {\n overrides.compactGreeting = true;\n }\n\n // Tool error frustration correlation → lower nudge threshold\n if (p.frustrationCorrelations.toolErrors > 0.4) {\n overrides.frustrationNudgeThreshold = 0.4;\n }\n\n // Worsening sentiment → default to Personal mode more readily\n if (p.sentimentTrend === \"worsening\") {\n overrides.defaultToPersonalMode = true;\n }\n\n return overrides;\n}\n\n// ── Burnout Predictor ──\n\nexport interface BurnoutPrediction {\n risk: number; // 0-1\n factors: string[];\n recommendation?: string;\n}\n\n/**\n * Predict burnout risk from session patterns.\n * Looks at recent 7 sessions for:\n * - Rising frustration trend\n * - Declining session ratings\n * - Long sessions without breaks\n * - Late-night clustering\n * - High blocker frequency\n */\nexport function predictBurnout(\n sessions: SessionSnapshot[],\n currentSession?: { minutes: number; frustration: number; timePeriod: string },\n): BurnoutPrediction {\n const recent = sessions.slice(-7);\n if (recent.length < 3) {\n return { risk: 0, factors: [] };\n }\n\n const factors: string[] = [];\n let risk = 0;\n\n // Factor 1: Rising frustration (compare first half vs second half)\n const mid = Math.floor(recent.length / 2);\n const firstHalf = recent.slice(0, mid);\n const secondHalf = recent.slice(mid);\n const avgFrustFirst = avg(firstHalf.map((s) => s.avgFrustration));\n const avgFrustSecond = avg(secondHalf.map((s) => s.avgFrustration));\n if (avgFrustSecond > avgFrustFirst + 0.1 && avgFrustSecond > 0.4) {\n risk += 0.25;\n factors.push(\"rising frustration trend\");\n }\n\n // Factor 2: Declining ratings\n const ratings = recent.filter((s) => s.rating).map((s) => ratingSignal(s));\n if (ratings.length >= 3) {\n const lastThree = ratings.slice(-3);\n const avgLast3 = avg(lastThree);\n if (avgLast3 < 0.5) {\n risk += 0.2;\n factors.push(\"low recent ratings\");\n }\n }\n\n // Factor 3: Long sessions (avg > 90 min)\n const avgMins = avg(recent.map((s) => s.durationMinutes));\n if (avgMins > 90) {\n risk += 0.15;\n factors.push(\"consistently long sessions\");\n }\n\n // Factor 4: Late-night clustering\n const lateNightCount = recent.filter((s) => s.timePeriod === \"late-night\" || s.timePeriod === \"night\").length;\n if (lateNightCount / recent.length > 0.5) {\n risk += 0.15;\n factors.push(\"frequent late-night sessions\");\n }\n\n // Factor 5: High blocker frequency\n const avgBlockers = avg(recent.map((s) => s.blockers));\n if (avgBlockers > 1) {\n risk += 0.15;\n factors.push(\"frequent blockers\");\n }\n\n // Current session amplifier\n if (currentSession) {\n if (currentSession.minutes > 120 && currentSession.frustration > 0.5) {\n risk += 0.1;\n factors.push(\"current session: long + frustrated\");\n }\n }\n\n risk = clamp(risk, 0, 1);\n\n let recommendation: string | undefined;\n if (risk > 0.7) {\n recommendation = \"Consider taking a longer break. You've been pushing hard — rest is productive too.\";\n } else if (risk > 0.5) {\n recommendation = \"Watch for signs of fatigue. A change of pace or shorter sessions might help.\";\n }\n\n return { risk, factors, recommendation };\n}\n\n// ── Math Utilities ──\n\nfunction clamp(val: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, val));\n}\n\nfunction avg(values: number[]): number {\n if (values.length === 0) return 0;\n return values.reduce((sum, v) => sum + v, 0) / values.length;\n}\n\nfunction ratingSignal(session: SessionSnapshot): number {\n if (session.rating === \"great\") return 1.0;\n if (session.rating === \"good\") return 0.75;\n if (session.rating === \"okay\") return 0.5;\n if (session.rating === \"frustrating\") return 0.25;\n\n // No explicit rating — infer from signals\n let implicit = 1.0;\n implicit -= session.avgFrustration * 0.4;\n implicit -= session.toolErrors > 3 ? 0.2 : 0;\n implicit -= session.blockers > 2 ? 0.2 : 0;\n implicit += session.milestones > 0 ? 0.1 : 0;\n return clamp(implicit, 0, 1);\n}\n\nfunction ratingToNumber(rating?: string): number {\n if (rating === \"great\") return 1.0;\n if (rating === \"good\") return 0.75;\n if (rating === \"okay\") return 0.5;\n if (rating === \"frustrating\") return 0.25;\n return 0.5;\n}\n\nfunction pearsonR(x: number[], y: number[]): number {\n const n = x.length;\n if (n < 3) return 0;\n\n const mx = avg(x);\n const my = avg(y);\n\n let num = 0;\n let dx2 = 0;\n let dy2 = 0;\n\n for (let i = 0; i < n; i++) {\n const dx = x[i] - mx;\n const dy = y[i] - my;\n num += dx * dy;\n dx2 += dx * dx;\n dy2 += dy * dy;\n }\n\n const denom = Math.sqrt(dx2 * dy2);\n if (denom === 0) return 0;\n return num / denom;\n}\n\nfunction computeTrustTrajectory(\n sessions: SessionSnapshot[],\n): \"ascending\" | \"stable\" | \"declining\" {\n if (sessions.length < 10) return \"stable\";\n\n const recent5 = sessions.slice(-5).map(ratingSignal);\n const prev5 = sessions.slice(-10, -5).map(ratingSignal);\n\n const recentAvg = avg(recent5);\n const prevAvg = avg(prev5);\n const delta = recentAvg - prevAvg;\n\n if (delta > 0.1) return \"ascending\";\n if (delta < -0.1) return \"declining\";\n return \"stable\";\n}\n\nfunction computeSentimentTrend(sessions: SessionSnapshot[]): \"improving\" | \"stable\" | \"worsening\" {\n if (sessions.length < 5) return \"stable\";\n\n const frustrations = sessions.slice(-10).map((s) => s.avgFrustration);\n const slope = linearSlope(frustrations);\n\n if (slope > 0.02) return \"worsening\"; // frustration increasing = worsening\n if (slope < -0.02) return \"improving\"; // frustration decreasing = improving\n return \"stable\";\n}\n\nfunction computeLinearTrend(values: number[]): \"increasing\" | \"stable\" | \"decreasing\" {\n if (values.length < 5) return \"stable\";\n\n const recent = values.slice(-10);\n const slope = linearSlope(recent);\n\n // Normalize slope relative to mean to detect meaningful changes\n const mean = avg(recent);\n const relativeSlope = mean > 0 ? slope / mean : slope;\n\n if (relativeSlope > 0.03) return \"increasing\";\n if (relativeSlope < -0.03) return \"decreasing\";\n return \"stable\";\n}\n\nfunction linearSlope(values: number[]): number {\n const n = values.length;\n if (n < 2) return 0;\n\n let sumX = 0;\n let sumY = 0;\n let sumXY = 0;\n let sumX2 = 0;\n\n for (let i = 0; i < n; i++) {\n sumX += i;\n sumY += values[i];\n sumXY += i * values[i];\n sumX2 += i * i;\n }\n\n const denom = n * sumX2 - sumX * sumX;\n if (denom === 0) return 0;\n return (n * sumXY - sumX * sumY) / denom;\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport os from \"node:os\";\nimport { log } from \"../logger.js\";\n\nexport interface AgentEntry {\n name: string; // unique handle, used as @name\n profile: string; // aman-agent profile this server loaded\n pid: number; // process id for liveness check\n port: number; // 127.0.0.1 port\n token: string; // 32-byte hex bearer\n started_at: number; // epoch ms\n version: string; // package version\n}\n\nexport interface ListOptions {\n prune?: boolean; // write the pruned registry back\n isAlive?: (pid: number) => boolean; // injectable for tests\n}\n\nfunction amanAgentHome(): string {\n return process.env.AMAN_AGENT_HOME || path.join(os.homedir(), \".aman-agent\");\n}\n\nfunction registryPath(): string {\n return path.join(amanAgentHome(), \"registry.json\");\n}\n\nasync function ensureHome(): Promise<void> {\n await fs.mkdir(amanAgentHome(), { recursive: true });\n}\n\nasync function readRaw(): Promise<AgentEntry[]> {\n try {\n const buf = await fs.readFile(registryPath(), \"utf-8\");\n const parsed = JSON.parse(buf);\n return Array.isArray(parsed) ? parsed : [];\n } catch (err: unknown) {\n const code = (err as { code?: string }).code;\n if (code === \"ENOENT\") return [];\n const message = err instanceof Error ? err.message : String(err);\n log.warn(\"registry\", `failed to read registry: ${message}`);\n return [];\n }\n}\n\nasync function writeAtomic(entries: AgentEntry[]): Promise<void> {\n await ensureHome();\n const tmp = registryPath() + \".tmp\";\n await fs.writeFile(tmp, JSON.stringify(entries, null, 2), { mode: 0o600 });\n await fs.rename(tmp, registryPath());\n // Ensure mode even if file already existed (chmod is idempotent).\n try {\n await fs.chmod(registryPath(), 0o600);\n } catch {\n // best effort\n }\n}\n\nfunction defaultIsAlive(pid: number): boolean {\n try {\n // Signal 0 probes existence without sending anything.\n process.kill(pid, 0);\n return true;\n } catch {\n return false;\n }\n}\n\nexport async function registerAgent(entry: AgentEntry): Promise<void> {\n const current = await readRaw();\n const filtered = current.filter((e) => e.name !== entry.name);\n if (filtered.length !== current.length) {\n log.warn(\"registry\", `replacing existing entry for name=\"${entry.name}\"`);\n }\n filtered.push(entry);\n await writeAtomic(filtered);\n}\n\nexport async function unregisterAgent(name: string): Promise<void> {\n const current = await readRaw();\n const next = current.filter((e) => e.name !== name);\n if (next.length !== current.length) {\n await writeAtomic(next);\n }\n}\n\nexport async function listAgents(opts: ListOptions = {}): Promise<AgentEntry[]> {\n const isAlive = opts.isAlive ?? defaultIsAlive;\n const raw = await readRaw();\n const alive = raw.filter((e) => isAlive(e.pid));\n if (opts.prune && alive.length !== raw.length) {\n await writeAtomic(alive);\n }\n return alive;\n}\n\nexport async function findAgent(name: string): Promise<AgentEntry | null> {\n const all = await listAgents();\n return all.find((e) => e.name === name) ?? null;\n}\n","import { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { StreamableHTTPClientTransport } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport { findAgent } from \"./server/registry.js\";\nimport type { DelegationResult } from \"./delegate.js\";\nimport { log } from \"./logger.js\";\n\nexport interface RemoteDelegateOptions {\n context?: string;\n timeoutMs?: number;\n}\n\nconst DEFAULT_TIMEOUT_MS = 120_000;\n\n/**\n * Dial another aman-agent running as an A2A server on the same machine\n * and run a task through its `agent.delegate` MCP tool. Returns a\n * DelegationResult matching the shape of the local `delegateTask` so\n * callers can treat local and remote delegation uniformly.\n *\n * Trust model: same user, same machine — bearer comes from the local\n * registry file (mode 0600). See plan docs for the broader discussion.\n */\nexport async function delegateRemote(\n task: string,\n agentName: string,\n options: RemoteDelegateOptions = {},\n): Promise<DelegationResult> {\n const entry = await findAgent(agentName);\n if (!entry) {\n return {\n profile: `@${agentName}`,\n task,\n response: \"\",\n toolsUsed: [],\n turns: 0,\n success: false,\n error: `agent not found: ${agentName}`,\n };\n }\n\n const url = new URL(`http://127.0.0.1:${entry.port}/mcp`);\n const transport = new StreamableHTTPClientTransport(url, {\n requestInit: {\n headers: { Authorization: `Bearer ${entry.token}` },\n },\n // Disable SSE reconnection scheduling. On close(), the SDK aborts\n // the controller; without this override, the SSE stream's error\n // handler races to schedule a new _reconnectionTimeout AFTER close()\n // cleared the old one, and the timer (plus its referenced socket)\n // pins Node's event loop until the undici keepalive times out. A\n // delegateRemote caller then can't exit cleanly. maxRetries: 0\n // drops the schedule-on-error path entirely; we're doing a single\n // RPC, not a persistent stream, so reconnection has no value here.\n reconnectionOptions: {\n maxRetries: 0,\n initialReconnectionDelay: 1,\n maxReconnectionDelay: 1,\n reconnectionDelayGrowFactor: 1,\n },\n });\n const client = new Client({ name: \"aman-agent-a2a-caller\", version: \"0.1.0\" });\n\n try {\n await client.connect(transport);\n\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const call = client.callTool({\n name: \"agent.delegate\",\n arguments: {\n task,\n ...(options.context ? { context: options.context } : {}),\n },\n });\n\n // Promise.race picks a winner but does NOT cancel the losing promise's\n // resources. Capturing the timer id lets us clear it after the call\n // resolves — otherwise the setTimeout keeps a Timeout handle alive for\n // the full timeoutMs (120 s default) and pins Node's event loop long\n // after the caller thinks the RPC is done. Equivalent effect to using\n // AbortSignal.timeout() but keeps the existing error message.\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<never>((_, rej) => {\n timeoutId = setTimeout(\n () => rej(new Error(`remote delegate timed out after ${timeoutMs}ms`)),\n timeoutMs,\n );\n });\n let result;\n try {\n result = await Promise.race([call, timeout]);\n } finally {\n if (timeoutId !== undefined) clearTimeout(timeoutId);\n }\n\n const text = Array.isArray(result.content)\n ? (result.content as Array<{ type: string; text?: string }>)\n .filter((c) => c.type === \"text\")\n .map((c) => c.text ?? \"\")\n .join(\"\")\n : \"\";\n\n // MCP tool-level errors arrive as { isError: true, content: [{text: \"...\"}] }.\n // Surface them distinctly from JSON.parse failures and from empty responses.\n if ((result as { isError?: boolean }).isError) {\n return {\n profile: `@${agentName}`,\n task,\n response: \"\",\n toolsUsed: [],\n turns: 0,\n success: false,\n error: `remote tool error: ${text || \"(no details)\"}`,\n };\n }\n\n const parsed = text ? JSON.parse(text) : { ok: false, error: \"empty response\" };\n\n log.debug(\"delegate-remote\", `@${agentName} ok=${parsed.ok}`);\n\n if (!parsed.ok) {\n return {\n profile: `@${agentName}`,\n task,\n response: \"\",\n toolsUsed: [],\n turns: 0,\n success: false,\n error: parsed.error ?? \"unknown remote error\",\n };\n }\n\n return {\n profile: `@${agentName}`,\n task,\n response: parsed.text ?? \"\",\n toolsUsed: parsed.tools_used ?? [],\n turns: parsed.turns ?? 0,\n success: true,\n };\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n const lower = msg.toLowerCase();\n const normalized =\n lower.includes(\"401\") || lower.includes(\"unauthor\")\n ? `unauthorized: ${msg}`\n : msg;\n return {\n profile: `@${agentName}`,\n task,\n response: \"\",\n toolsUsed: [],\n turns: 0,\n success: false,\n error: normalized,\n };\n } finally {\n // Teardown order matters:\n // 1. terminateSession() sends an MCP DELETE to drop the server-side\n // session. This needs the transport's abort controller to still\n // be alive, so it MUST run BEFORE client.close() (which aborts\n // the controller). Earlier order threw DOMException[AbortError].\n // 2. client.close() then releases SDK-side state and aborts the\n // transport. Combined with reconnectionOptions: { maxRetries: 0 }\n // on construction, this leaves zero handles pinning the event\n // loop — verified via process.getActiveResourcesInfo() === [].\n // 3. transport.close() is a no-op after client.close() (which\n // transitively closes the transport) but kept for symmetry.\n // All three are best-effort: any throw here is swallowed so a\n // teardown failure never masks a real result from the caller.\n try { await transport.terminateSession(); } catch { /* best effort */ }\n try { await client.close(); } catch { /* best effort */ }\n try { await transport.close(); } catch { /* best effort */ }\n }\n}\n","import { z } from \"zod\";\n\n// ── Model Tiers ──────────────────────────────────────────────────────\nexport const ModelTierEnum = z.enum([\"fast\", \"standard\", \"advanced\"]);\nexport type ModelTier = z.infer<typeof ModelTierEnum>;\n\n// ── TaskNode — a single unit of work in the DAG ─────────────────────\nexport const TaskNodeSchema = z.object({\n id: z.string().min(1),\n name: z.string().min(1),\n description: z.string().optional(),\n profile: z.string().min(1),\n tier: ModelTierEnum,\n dependencies: z.array(z.string()).default([]),\n phase: z.string().optional(),\n context: z.string().optional(),\n metadata: z.record(z.unknown()).optional(),\n});\nexport type TaskNode = z.infer<typeof TaskNodeSchema>;\n\n// ── PhaseGate — a gate between phases ────────────────────────────────\nexport const PhaseGateTypeEnum = z.enum([\n \"approval\",\n \"ci_pass\",\n \"test_pass\",\n \"custom\",\n]);\nexport type PhaseGateType = z.infer<typeof PhaseGateTypeEnum>;\n\nexport const PhaseGateSchema = z.object({\n id: z.string().min(1),\n name: z.string().min(1),\n type: PhaseGateTypeEnum,\n afterNodes: z.array(z.string()),\n beforeNodes: z.array(z.string()),\n metadata: z.record(z.unknown()).optional(),\n});\nexport type PhaseGate = z.infer<typeof PhaseGateSchema>;\n\n// ── TaskDAG — the complete directed acyclic graph ────────────────────\nexport const TaskDAGSchema = z.object({\n id: z.string().min(1),\n name: z.string().min(1),\n goal: z.string().min(1),\n nodes: z.array(TaskNodeSchema).min(1),\n gates: z.array(PhaseGateSchema).default([]),\n metadata: z.record(z.unknown()).optional(),\n});\nexport type TaskDAG = z.infer<typeof TaskDAGSchema>;\n\n// ── OrchestrationStatus ──────────────────────────────────────────────\nexport const OrchestrationStatusEnum = z.enum([\n \"pending\",\n \"running\",\n \"awaiting_approval\",\n \"approved\",\n \"paused\",\n \"completed\",\n \"failed\",\n \"cancelled\",\n]);\nexport type OrchestrationStatus = z.infer<typeof OrchestrationStatusEnum>;\n\n// ── TaskStatus ───────────────────────────────────────────────────────\nexport const TaskStatusEnum = z.enum([\n \"pending\",\n \"ready\",\n \"running\",\n \"completed\",\n \"failed\",\n \"skipped\",\n \"blocked\",\n]);\nexport type TaskStatus = z.infer<typeof TaskStatusEnum>;\n\n// ── TaskResult (plain TS — no Zod) ──────────────────────────────────\nexport interface TaskResult {\n nodeId: string;\n status: TaskStatus;\n output?: string;\n error?: string;\n toolsUsed: string[];\n turns: number;\n startedAt: number;\n completedAt?: number;\n tier: ModelTier;\n}\n\n// ── OrchestrationState (plain TS — uses Maps) ───────────────────────\nexport interface OrchestrationState {\n dag: TaskDAG;\n status: OrchestrationStatus;\n taskStatuses: Map<string, TaskStatus>;\n taskResults: Map<string, TaskResult>;\n activeGate: string | null;\n startedAt: number;\n updatedAt: number;\n completedAt?: number;\n error?: string;\n}\n\n// ── OrchestrationConfig ──────────────────────────────────────────────\nexport const OrchestrationConfigSchema = z.object({\n maxParallelTasks: z.number().int().positive().default(4),\n defaultTier: ModelTierEnum.default(\"standard\"),\n requireApprovalForPhaseTransition: z.boolean().default(true),\n taskTimeoutMs: z.number().int().positive().default(300_000),\n orchestrationTimeoutMs: z.number().int().positive().default(3_600_000),\n});\nexport type OrchestrationConfig = z.infer<typeof OrchestrationConfigSchema>;\n","import type { TaskDAG, TaskStatus } from \"./types.js\";\n\n// ── Error ───────────────────────────────────────────────────────────\n\nexport class DAGValidationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"DAGValidationError\";\n }\n}\n\n// ── Validation ──────────────────────────────────────────────────────\n\nexport function validateDAG(dag: TaskDAG): void {\n const nodeIds = new Set<string>();\n\n // Check for duplicate ids\n for (const node of dag.nodes) {\n if (nodeIds.has(node.id)) {\n throw new DAGValidationError(`Duplicate node id: \"${node.id}\"`);\n }\n nodeIds.add(node.id);\n }\n\n // Check that all dependencies reference existing nodes\n for (const node of dag.nodes) {\n for (const dep of node.dependencies) {\n if (!nodeIds.has(dep)) {\n throw new DAGValidationError(\n `Node \"${node.id}\" depends on nonexistent node \"${dep}\"`,\n );\n }\n }\n }\n\n // Validate gate references\n for (const gate of dag.gates) {\n for (const id of gate.afterNodes) {\n if (!nodeIds.has(id)) {\n throw new DAGValidationError(\n `Gate \"${gate.id}\" references nonexistent afterNode \"${id}\"`,\n );\n }\n }\n for (const id of gate.beforeNodes) {\n if (!nodeIds.has(id)) {\n throw new DAGValidationError(\n `Gate \"${gate.id}\" references nonexistent beforeNode \"${id}\"`,\n );\n }\n }\n }\n\n // Cycle detection via Kahn's algorithm\n const inDegree = new Map<string, number>();\n const adj = new Map<string, string[]>();\n\n for (const node of dag.nodes) {\n inDegree.set(node.id, 0);\n adj.set(node.id, []);\n }\n\n for (const node of dag.nodes) {\n for (const dep of node.dependencies) {\n adj.get(dep)!.push(node.id);\n inDegree.set(node.id, inDegree.get(node.id)! + 1);\n }\n }\n\n const queue: string[] = [];\n for (const [id, deg] of inDegree) {\n if (deg === 0) queue.push(id);\n }\n\n let visited = 0;\n while (queue.length > 0) {\n const current = queue.shift()!;\n visited++;\n for (const neighbor of adj.get(current)!) {\n const newDeg = inDegree.get(neighbor)! - 1;\n inDegree.set(neighbor, newDeg);\n if (newDeg === 0) queue.push(neighbor);\n }\n }\n\n if (visited !== dag.nodes.length) {\n throw new DAGValidationError(\n \"DAG contains a cycle — not all nodes were reachable via topological ordering\",\n );\n }\n}\n\n// ── Topological Sort (Kahn's) ───────────────────────────────────────\n\nexport function topologicalSort(dag: TaskDAG): string[] {\n const inDegree = new Map<string, number>();\n const adj = new Map<string, string[]>();\n\n for (const node of dag.nodes) {\n inDegree.set(node.id, 0);\n adj.set(node.id, []);\n }\n\n for (const node of dag.nodes) {\n for (const dep of node.dependencies) {\n adj.get(dep)!.push(node.id);\n inDegree.set(node.id, inDegree.get(node.id)! + 1);\n }\n }\n\n const queue: string[] = [];\n for (const [id, deg] of inDegree) {\n if (deg === 0) queue.push(id);\n }\n\n const result: string[] = [];\n while (queue.length > 0) {\n const current = queue.shift()!;\n result.push(current);\n for (const neighbor of adj.get(current)!) {\n const newDeg = inDegree.get(neighbor)! - 1;\n inDegree.set(neighbor, newDeg);\n if (newDeg === 0) queue.push(neighbor);\n }\n }\n\n return result;\n}\n\n// ── Ready-Node Resolution ───────────────────────────────────────────\n\nexport function getReadyNodes(\n dag: TaskDAG,\n taskStatuses: Map<string, TaskStatus>,\n resolvedGates?: Set<string>,\n): string[] {\n // Build set of nodes blocked by unresolved gates\n const gateBlocked = new Set<string>();\n for (const gate of dag.gates) {\n if (resolvedGates?.has(gate.id)) continue;\n // If all afterNodes are completed, the gate is active but unresolved => block beforeNodes\n const allAfterDone = gate.afterNodes.every(\n (id) => taskStatuses.get(id) === \"completed\",\n );\n if (allAfterDone) {\n for (const id of gate.beforeNodes) {\n gateBlocked.add(id);\n }\n }\n }\n\n const ready: string[] = [];\n\n for (const node of dag.nodes) {\n if (taskStatuses.get(node.id) !== \"pending\") continue;\n if (gateBlocked.has(node.id)) continue;\n\n const allDepsCompleted = node.dependencies.every(\n (dep) => taskStatuses.get(dep) === \"completed\",\n );\n if (allDepsCompleted) {\n ready.push(node.id);\n }\n }\n\n return ready;\n}\n\n// ── Dependents ──────────────────────────────────────────────────────\n\nexport function getDependents(dag: TaskDAG, nodeId: string): string[] {\n return dag.nodes\n .filter((n) => n.dependencies.includes(nodeId))\n .map((n) => n.id);\n}\n","import { TaskDAGSchema, type TaskDAG } from \"./types.js\";\nimport { validateDAG } from \"./dag.js\";\nimport type { LLMClient } from \"../llm/types.js\";\n\n// ── System prompt for decomposition ────────────────────────────────\n\nexport const DECOMPOSITION_SYSTEM_PROMPT = `You are a software project decomposer. Given a requirement, break it into a task DAG for parallel agent execution.\n\nReturn ONLY valid JSON matching this schema:\n{\n \"id\": \"orch-<short-id>\",\n \"name\": \"<short name>\",\n \"goal\": \"<one-line goal>\",\n \"nodes\": [\n {\n \"id\": \"<unique-id>\",\n \"name\": \"<task name>\",\n \"description\": \"<what to do>\",\n \"profile\": \"<architect|coder|tester|reviewer|security>\",\n \"tier\": \"<fast|standard|advanced>\",\n \"dependencies\": [\"<prerequisite task ids>\"]\n }\n ],\n \"gates\": [\n {\n \"id\": \"<gate-id>\",\n \"name\": \"<gate description>\",\n \"type\": \"approval\",\n \"afterNodes\": [\"<completed before gate>\"],\n \"beforeNodes\": [\"<blocked until gate resolves>\"]\n }\n ]\n}\n\nRules:\n- architect profile = tier advanced\n- coder/tester/reviewer = tier standard\n- Maximize parallelism\n- Add approval gate before destructive actions\n- 3-12 tasks for most features`;\n\n// ── Parse + validate an LLM response into a TaskDAG ────────────────\n\nexport function parseDecompositionResponse(response: string): TaskDAG {\n let jsonStr: string;\n\n // 1. Try to extract JSON from markdown code block\n const codeBlockMatch = response.match(/```(?:json)?\\s*\\n([\\s\\S]*?)\\n```/);\n if (codeBlockMatch) {\n jsonStr = codeBlockMatch[1];\n } else {\n // 2. Try the whole response as JSON\n jsonStr = response;\n }\n\n // 3. Parse JSON\n let raw: unknown;\n try {\n raw = JSON.parse(jsonStr);\n } catch {\n throw new Error(\n `Failed to parse decomposition response as JSON: ${jsonStr.slice(0, 200)}`,\n );\n }\n\n // 4. Validate through Zod schema\n const parsed = TaskDAGSchema.parse(raw);\n\n // 5. Validate DAG structure (cycles, refs)\n validateDAG(parsed);\n\n return parsed;\n}\n\n// ── LLM-driven requirement decomposition ───────────────────────────\n\nexport async function decomposeRequirement(\n requirement: string,\n client: LLMClient,\n): Promise<TaskDAG> {\n const response = await client.chat(\n DECOMPOSITION_SYSTEM_PROMPT,\n [{ role: \"user\", content: requirement }],\n () => {}, // stream chunks are unused; we read the final message\n );\n\n // Extract text from response\n const text =\n typeof response.message.content === \"string\"\n ? response.message.content\n : response.message.content\n .filter((b) => b.type === \"text\")\n .map((b) => (b as { type: \"text\"; text: string }).text)\n .join(\"\");\n\n return parseDecompositionResponse(text);\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\n\nexport interface StackProfile {\n projectName: string;\n languages: string[];\n frameworks: string[];\n databases: string[];\n infra: string[];\n isMonorepo: boolean;\n detectedAt: number;\n}\n\nconst FRAMEWORK_MAP: Record<string, string> = {\n next: \"next\", react: \"react\", remix: \"remix\", express: \"express\",\n fastify: \"fastify\", hono: \"hono\", \"@nestjs/core\": \"nestjs\",\n vue: \"vue\", svelte: \"svelte\", nuxt: \"nuxt\",\n};\n\nconst DB_IMAGE_MAP: Record<string, string> = {\n postgres: \"postgresql\", mysql: \"mysql\", mariadb: \"mariadb\",\n mongo: \"mongodb\", redis: \"redis\", timescaledb: \"timescaledb\",\n};\n\nexport function scanStack(projectPath: string): StackProfile {\n const languages: string[] = [];\n const frameworks: string[] = [];\n const databases: string[] = [];\n const infra: string[] = [];\n let isMonorepo = false;\n let projectName = path.basename(projectPath);\n\n // --- Go ---\n const goModPath = path.join(projectPath, \"go.mod\");\n if (fs.existsSync(goModPath)) {\n languages.push(\"go\");\n const content = fs.readFileSync(goModPath, \"utf-8\");\n const moduleMatch = content.match(/^module\\s+(.+)$/m);\n if (moduleMatch) {\n const parts = moduleMatch[1].trim().split(\"/\");\n projectName = parts[parts.length - 1];\n }\n if (content.includes(\"gofiber/fiber\")) frameworks.push(\"fiber\");\n if (content.includes(\"gin-gonic/gin\")) frameworks.push(\"gin\");\n if (content.includes(\"go-chi/chi\")) frameworks.push(\"chi\");\n if (content.includes(\"labstack/echo\")) frameworks.push(\"echo\");\n }\n\n // --- Node/TypeScript ---\n const pkgPath = path.join(projectPath, \"package.json\");\n const hasTsConfig = fs.existsSync(path.join(projectPath, \"tsconfig.json\"));\n if (fs.existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(fs.readFileSync(pkgPath, \"utf-8\"));\n if (pkg.name) projectName = pkg.name;\n if (hasTsConfig) {\n languages.push(\"typescript\");\n } else {\n languages.push(\"javascript\");\n }\n const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };\n for (const [dep, fwName] of Object.entries(FRAMEWORK_MAP)) {\n if (allDeps?.[dep]) frameworks.push(fwName);\n }\n if (pkg.workspaces) isMonorepo = true;\n } catch {\n if (hasTsConfig) languages.push(\"typescript\");\n }\n } else if (hasTsConfig) {\n languages.push(\"typescript\");\n }\n\n // --- Rust ---\n const cargoPath = path.join(projectPath, \"Cargo.toml\");\n if (fs.existsSync(cargoPath)) {\n languages.push(\"rust\");\n const content = fs.readFileSync(cargoPath, \"utf-8\");\n if (content.includes(\"[workspace]\")) isMonorepo = true;\n const nameMatch = content.match(/^\\s*name\\s*=\\s*\"([^\"]+)\"/m);\n if (nameMatch && !isMonorepo) projectName = nameMatch[1];\n }\n\n // --- Python ---\n const pyprojectPath = path.join(projectPath, \"pyproject.toml\");\n if (fs.existsSync(pyprojectPath)) {\n languages.push(\"python\");\n const content = fs.readFileSync(pyprojectPath, \"utf-8\");\n if (content.includes(\"django\")) frameworks.push(\"django\");\n if (content.includes(\"fastapi\")) frameworks.push(\"fastapi\");\n if (content.includes(\"flask\")) frameworks.push(\"flask\");\n }\n\n // --- Flutter/Dart ---\n if (fs.existsSync(path.join(projectPath, \"pubspec.yaml\"))) {\n languages.push(\"dart\");\n frameworks.push(\"flutter\");\n }\n\n // --- Docker ---\n if (fs.existsSync(path.join(projectPath, \"Dockerfile\"))) {\n infra.push(\"docker\");\n }\n\n // --- Docker Compose (databases) ---\n const composeNames = [\"docker-compose.yml\", \"docker-compose.yaml\", \"compose.yml\", \"compose.yaml\"];\n for (const name of composeNames) {\n const composePath = path.join(projectPath, name);\n if (fs.existsSync(composePath)) {\n if (!infra.includes(\"docker\")) infra.push(\"docker\");\n const content = fs.readFileSync(composePath, \"utf-8\");\n for (const [pattern, dbName] of Object.entries(DB_IMAGE_MAP)) {\n if (content.includes(pattern) && !databases.includes(dbName)) {\n databases.push(dbName);\n }\n }\n break;\n }\n }\n\n // --- CI/CD ---\n if (fs.existsSync(path.join(projectPath, \".github\", \"workflows\"))) {\n infra.push(\"github-actions\");\n }\n\n // --- Kubernetes ---\n for (const dir of [\"k3s\", \"k8s\", \"deploy\"]) {\n if (fs.existsSync(path.join(projectPath, dir))) {\n infra.push(\"kubernetes\");\n break;\n }\n }\n\n // --- Makefile ---\n if (fs.existsSync(path.join(projectPath, \"Makefile\"))) {\n infra.push(\"make\");\n }\n\n return {\n projectName,\n languages,\n frameworks,\n databases,\n infra,\n isMonorepo,\n detectedAt: Date.now(),\n };\n}\n","import { z } from \"zod\";\n\n// ---------- Issue ----------\nexport const GitHubIssueSchema = z.object({\n number: z.number().int().positive(),\n title: z.string().min(1),\n body: z.string().nullable().default(null),\n state: z.enum([\"OPEN\", \"CLOSED\"]),\n url: z.string().url(),\n labels: z.array(z.object({ name: z.string() })).default([]),\n assignees: z.array(z.object({ login: z.string() })).default([]),\n author: z.object({ login: z.string() }).optional(),\n createdAt: z.string(),\n updatedAt: z.string(),\n});\nexport type GitHubIssue = z.infer<typeof GitHubIssueSchema>;\n\n// ---------- Pull Request ----------\nexport const GitHubPRSchema = z.object({\n number: z.number().int().positive(),\n title: z.string().min(1),\n body: z.string().nullable().default(null),\n state: z.enum([\"OPEN\", \"CLOSED\", \"MERGED\"]),\n url: z.string().url(),\n headRefName: z.string(),\n baseRefName: z.string(),\n isDraft: z.boolean().default(false),\n mergeable: z\n .enum([\"MERGEABLE\", \"CONFLICTING\", \"UNKNOWN\"])\n .default(\"UNKNOWN\"),\n labels: z.array(z.object({ name: z.string() })).default([]),\n author: z.object({ login: z.string() }).optional(),\n createdAt: z.string(),\n updatedAt: z.string(),\n});\nexport type GitHubPR = z.infer<typeof GitHubPRSchema>;\n\n// ---------- Workflow Run (CI) ----------\nexport const WorkflowRunSchema = z.object({\n databaseId: z.number().int().positive(),\n name: z.string(),\n workflowName: z.string().optional(),\n status: z.enum([\n \"queued\",\n \"in_progress\",\n \"completed\",\n \"waiting\",\n \"requested\",\n \"pending\",\n ]),\n conclusion: z\n .enum([\n \"success\",\n \"failure\",\n \"cancelled\",\n \"skipped\",\n \"timed_out\",\n \"action_required\",\n \"neutral\",\n \"stale\",\n \"\",\n ])\n .nullable()\n .default(null),\n url: z.string().url(),\n headBranch: z.string(),\n event: z.string(),\n createdAt: z.string(),\n updatedAt: z.string(),\n});\nexport type WorkflowRun = z.infer<typeof WorkflowRunSchema>;\n\n// ---------- Check Status (simplified) ----------\nexport const CheckStatusSchema = z.object({\n passed: z.boolean(),\n pending: z.boolean(),\n failing: z.boolean(),\n total: z.number().int().nonnegative(),\n details: z\n .array(\n z.object({\n name: z.string(),\n status: z.string(),\n conclusion: z.string().nullable(),\n }),\n )\n .default([]),\n});\nexport type CheckStatus = z.infer<typeof CheckStatusSchema>;\n\n// ---------- gh CLI result wrapper ----------\nexport const GhResultSchema = z.object({\n success: z.boolean(),\n stdout: z.string(),\n stderr: z.string(),\n exitCode: z.number().int(),\n});\nexport type GhResult = z.infer<typeof GhResultSchema>;\n","import { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport type { GhResult } from \"./types.js\";\n\nconst execFileAsync = promisify(execFile);\n\nexport interface GhOptions {\n /** Working directory for the command */\n cwd?: string;\n /** Timeout in ms (default: 30_000) */\n timeoutMs?: number;\n /** Additional environment variables */\n env?: Record<string, string>;\n}\n\nexport class GhError extends Error {\n constructor(\n message: string,\n public readonly exitCode: number,\n public readonly stderr: string,\n ) {\n super(message);\n this.name = \"GhError\";\n }\n}\n\n/**\n * Run a gh CLI command safely via execFile (no shell).\n * Returns structured GhResult with stdout, stderr, exitCode.\n * Does NOT throw on non-zero exit — returns { success: false, exitCode, stderr }.\n */\nexport async function gh(\n args: string[],\n options?: GhOptions,\n): Promise<GhResult> {\n const ghBin = options?.env?.GH_PATH ?? process.env.GH_PATH ?? \"gh\";\n const timeout = options?.timeoutMs ?? 30_000;\n\n const execOpts: Record<string, unknown> = {\n timeout,\n ...(options?.cwd ? { cwd: options.cwd } : {}),\n ...(options?.env\n ? { env: { ...process.env, ...options.env } }\n : {}),\n };\n\n try {\n const { stdout, stderr } = await execFileAsync(ghBin, args, execOpts);\n return { success: true, stdout, stderr, exitCode: 0 };\n } catch (err: unknown) {\n const e = err as {\n code?: number;\n stdout?: string;\n stderr?: string;\n };\n const exitCode = typeof e.code === \"number\" ? e.code : 1;\n return {\n success: false,\n stdout: e.stdout ?? \"\",\n stderr: e.stderr ?? \"\",\n exitCode,\n };\n }\n}\n\n/**\n * Run gh and parse JSON output. Throws if gh fails or output isn't valid JSON.\n */\nexport async function ghJson<T>(\n args: string[],\n options?: GhOptions,\n): Promise<T> {\n const result = await gh(args, options);\n\n if (!result.success) {\n throw new GhError(\n `gh command failed: ${result.stderr}`,\n result.exitCode,\n result.stderr,\n );\n }\n\n try {\n return JSON.parse(result.stdout) as T;\n } catch {\n throw new GhError(\n `Failed to parse JSON from gh output: ${result.stdout.slice(0, 200)}`,\n 0,\n result.stderr,\n );\n }\n}\n\n/**\n * Check if gh CLI is available and authenticated.\n */\nexport async function ghAvailable(): Promise<boolean> {\n const result = await gh([\"auth\", \"status\"]);\n return result.success;\n}\n\n/**\n * Get the current repo owner/name from gh CLI.\n */\nexport async function ghCurrentRepo(): Promise<{\n owner: string;\n name: string;\n} | null> {\n try {\n const data = await ghJson<{ owner: { login: string }; name: string }>(\n [\"repo\", \"view\", \"--json\", \"owner,name\"],\n );\n return { owner: data.owner.login, name: data.name };\n } catch {\n return null;\n }\n}\n","import type { LLMClient } from \"../llm/types.js\";\nimport type { TaskDAG } from \"../orchestrator/types.js\";\nimport type { GitHubIssue } from \"./types.js\";\nimport { ghJson } from \"./cli.js\";\nimport { GitHubIssueSchema } from \"./types.js\";\nimport { decomposeRequirement } from \"../orchestrator/decompose.js\";\n\nconst ISSUE_JSON_FIELDS =\n \"number,title,body,state,url,labels,assignees,author,createdAt,updatedAt\";\n\n/**\n * Fetch a GitHub issue by number.\n */\nexport async function fetchIssue(\n issueNumber: number,\n options?: { repo?: string; cwd?: string },\n): Promise<GitHubIssue> {\n const args = [\n \"issue\",\n \"view\",\n String(issueNumber),\n \"--json\",\n ISSUE_JSON_FIELDS,\n ];\n\n if (options?.repo) {\n args.push(\"--repo\", options.repo);\n }\n\n const raw = await ghJson<unknown>(args, { cwd: options?.cwd });\n return GitHubIssueSchema.parse(raw);\n}\n\n/**\n * Format an issue into a requirement string for the decomposer.\n */\nexport function formatIssueAsRequirement(issue: GitHubIssue): string {\n const parts: string[] = [`# ${issue.title}`];\n\n if (issue.body) {\n parts.push(\"\", issue.body);\n }\n\n const extras: string[] = [];\n\n if (issue.labels.length > 0) {\n extras.push(`Labels: ${issue.labels.map((l) => l.name).join(\", \")}`);\n }\n\n if (issue.assignees.length > 0) {\n extras.push(\n `Assignees: ${issue.assignees.map((a) => a.login).join(\", \")}`,\n );\n }\n\n if (extras.length > 0) {\n parts.push(\"\", ...extras);\n }\n\n return parts.join(\"\\n\");\n}\n\n/**\n * Fetch a GitHub issue and decompose it into a TaskDAG.\n */\nexport async function planFromIssue(\n issueNumber: number,\n client: LLMClient,\n options?: { repo?: string; cwd?: string },\n): Promise<{ issue: GitHubIssue; dag: TaskDAG }> {\n const issue = await fetchIssue(issueNumber, options);\n const requirement = formatIssueAsRequirement(issue);\n const dag = await decomposeRequirement(requirement, client);\n return { issue, dag };\n}\n","import { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { gh, ghJson } from \"./cli.js\";\nimport { GitHubPRSchema } from \"./types.js\";\nimport type { GitHubPR } from \"./types.js\";\n\nconst execFileAsync = promisify(execFile);\n\n/** JSON fields requested from gh for PR objects. */\nconst PR_JSON_FIELDS =\n \"number,title,body,state,url,headRefName,baseRefName,isDraft,mergeable,labels,author,createdAt,updatedAt\";\n\n// ---------- types ----------\n\nexport interface CreatePROptions {\n title: string;\n body: string;\n head: string;\n base?: string;\n draft?: boolean;\n labels?: string[];\n repo?: string;\n cwd?: string;\n}\n\n// ---------- createPR ----------\n\n/**\n * Create a pull request via gh CLI.\n */\nexport async function createPR(options: CreatePROptions): Promise<GitHubPR> {\n const args: string[] = [\n \"pr\",\n \"create\",\n \"--title\",\n options.title,\n \"--body\",\n options.body,\n \"--head\",\n options.head,\n ];\n\n if (options.base) {\n args.push(\"--base\", options.base);\n }\n if (options.draft) {\n args.push(\"--draft\");\n }\n if (options.labels) {\n for (const label of options.labels) {\n args.push(\"--label\", label);\n }\n }\n if (options.repo) {\n args.push(\"--repo\", options.repo);\n }\n\n const ghOpts = options.cwd ? { cwd: options.cwd } : undefined;\n\n // Create the PR — gh prints the URL on success\n const result = await gh(args, ghOpts);\n if (!result.success) {\n const { GhError } = await import(\"./cli.js\");\n throw new GhError(\n `Failed to create PR: ${result.stderr}`,\n result.exitCode,\n result.stderr,\n );\n }\n\n // Extract PR number from the URL (last path segment)\n const url = result.stdout.trim();\n const prNumber = parseInt(url.split(\"/\").pop()!, 10);\n\n // Fetch full PR data\n return getPR(prNumber, { repo: options.repo, cwd: options.cwd });\n}\n\n// ---------- listPRs ----------\n\n/**\n * List open PRs, optionally filtered.\n */\nexport async function listPRs(options?: {\n state?: \"open\" | \"closed\" | \"merged\" | \"all\";\n head?: string;\n limit?: number;\n repo?: string;\n cwd?: string;\n}): Promise<GitHubPR[]> {\n const args: string[] = [\"pr\", \"list\", \"--json\", PR_JSON_FIELDS];\n\n if (options?.state) {\n args.push(\"--state\", options.state);\n }\n if (options?.head) {\n args.push(\"--head\", options.head);\n }\n if (options?.limit != null) {\n args.push(\"--limit\", String(options.limit));\n }\n if (options?.repo) {\n args.push(\"--repo\", options.repo);\n }\n\n const ghOpts = options?.cwd ? { cwd: options.cwd } : undefined;\n const raw = await ghJson<unknown[]>(args, ghOpts);\n\n return raw.map((item) => GitHubPRSchema.parse(item));\n}\n\n// ---------- getPR ----------\n\n/**\n * Get a specific PR by number.\n */\nexport async function getPR(\n prNumber: number,\n options?: { repo?: string; cwd?: string },\n): Promise<GitHubPR> {\n const args: string[] = [\n \"pr\",\n \"view\",\n String(prNumber),\n \"--json\",\n PR_JSON_FIELDS,\n ];\n\n if (options?.repo) {\n args.push(\"--repo\", options.repo);\n }\n\n const ghOpts = options?.cwd ? { cwd: options.cwd } : undefined;\n const raw = await ghJson<unknown>(args, ghOpts);\n\n return GitHubPRSchema.parse(raw);\n}\n\n// ---------- commentOnPR ----------\n\n/**\n * Post a review comment on a PR.\n */\nexport async function commentOnPR(\n prNumber: number,\n body: string,\n options?: { repo?: string; cwd?: string },\n): Promise<void> {\n const args: string[] = [\"pr\", \"comment\", String(prNumber), \"--body\", body];\n\n if (options?.repo) {\n args.push(\"--repo\", options.repo);\n }\n\n const ghOpts = options?.cwd ? { cwd: options.cwd } : undefined;\n const result = await gh(args, ghOpts);\n\n if (!result.success) {\n const { GhError } = await import(\"./cli.js\");\n throw new GhError(\n `Failed to comment on PR #${prNumber}: ${result.stderr}`,\n result.exitCode,\n result.stderr,\n );\n }\n}\n\n// ---------- createBranch ----------\n\n/**\n * Create a git branch (via git, not gh).\n */\nexport async function createBranch(\n branchName: string,\n options?: { baseBranch?: string; cwd?: string },\n): Promise<void> {\n const args = [\"checkout\", \"-b\", branchName];\n\n if (options?.baseBranch) {\n args.push(options.baseBranch);\n }\n\n const execOpts: Record<string, unknown> = {};\n if (options?.cwd) {\n execOpts.cwd = options.cwd;\n }\n\n await execFileAsync(\"git\", args, execOpts);\n}\n","import { ghJson } from \"./cli.js\";\nimport { WorkflowRunSchema, CheckStatusSchema } from \"./types.js\";\nimport type { WorkflowRun, CheckStatus } from \"./types.js\";\n\nconst RUN_JSON_FIELDS =\n \"databaseId,name,workflowName,status,conclusion,url,headBranch,event,createdAt,updatedAt\";\n\n/**\n * Get the latest workflow run for a branch.\n */\nexport async function getLatestRun(\n branch: string,\n options?: { workflow?: string; repo?: string; cwd?: string },\n): Promise<WorkflowRun | null> {\n const args = [\n \"run\",\n \"list\",\n \"--branch\",\n branch,\n \"--limit\",\n \"1\",\n \"--json\",\n RUN_JSON_FIELDS,\n ];\n\n if (options?.workflow) {\n args.push(\"--workflow\", options.workflow);\n }\n if (options?.repo) {\n args.push(\"--repo\", options.repo);\n }\n\n const runs = await ghJson<unknown[]>(args, { cwd: options?.cwd });\n\n if (!runs.length) return null;\n\n return WorkflowRunSchema.parse(runs[0]);\n}\n\n/**\n * Get check status for a specific commit or PR.\n */\nexport async function getCheckStatus(\n ref: string,\n options?: { repo?: string; cwd?: string },\n): Promise<CheckStatus> {\n // If ref looks like a PR number, use `gh pr checks`\n const isPRNumber = /^\\d+$/.test(ref);\n\n if (isPRNumber) {\n const args = [\"pr\", \"checks\", ref, \"--json\", \"name,status,conclusion\"];\n if (options?.repo) args.push(\"--repo\", options.repo);\n\n const checks = await ghJson<\n Array<{ name: string; status: string; conclusion: string | null }>\n >(args, { cwd: options?.cwd });\n\n const details = checks.map((c) => ({\n name: c.name,\n status: c.status,\n conclusion: c.conclusion,\n }));\n\n const passed = details.every(\n (d) => d.status === \"completed\" && d.conclusion === \"success\",\n );\n const pending = details.some((d) => d.status !== \"completed\");\n const failing = details.some(\n (d) =>\n d.status === \"completed\" &&\n d.conclusion !== \"success\" &&\n d.conclusion !== \"skipped\" &&\n d.conclusion !== \"neutral\",\n );\n\n return CheckStatusSchema.parse({\n passed: passed && details.length > 0,\n pending,\n failing,\n total: details.length,\n details,\n });\n }\n\n // For commit SHAs, fall back to run list\n const run = await getLatestRun(ref, options);\n\n if (!run) {\n return CheckStatusSchema.parse({\n passed: false,\n pending: false,\n failing: false,\n total: 0,\n details: [],\n });\n }\n\n return CheckStatusSchema.parse({\n passed: run.status === \"completed\" && run.conclusion === \"success\",\n pending: run.status !== \"completed\",\n failing:\n run.status === \"completed\" &&\n run.conclusion !== \"success\" &&\n run.conclusion !== \"skipped\" &&\n run.conclusion !== \"neutral\",\n total: 1,\n details: [\n { name: run.name, status: run.status, conclusion: run.conclusion },\n ],\n });\n}\n\n/**\n * Wait for CI to complete on a branch. Polls at interval.\n */\nexport async function waitForCI(\n branch: string,\n options?: {\n workflow?: string;\n repo?: string;\n cwd?: string;\n pollIntervalMs?: number;\n timeoutMs?: number;\n },\n): Promise<{ passed: boolean; run: WorkflowRun | null }> {\n const pollInterval = options?.pollIntervalMs ?? 10_000;\n const timeout = options?.timeoutMs ?? 600_000;\n const deadline = Date.now() + timeout;\n\n while (Date.now() < deadline) {\n const run = await getLatestRun(branch, options);\n\n if (run && run.status === \"completed\") {\n return { passed: run.conclusion === \"success\", run };\n }\n\n // Check if we'd exceed deadline after sleeping\n if (Date.now() + pollInterval >= deadline) break;\n\n await new Promise((resolve) => setTimeout(resolve, pollInterval));\n }\n\n return { passed: false, run: null };\n}\n\n/**\n * Check if CI is passing for a branch (non-blocking snapshot).\n */\nexport async function isCIPassing(\n branch: string,\n options?: { workflow?: string; repo?: string; cwd?: string },\n): Promise<boolean> {\n const run = await getLatestRun(branch, options);\n return run !== null && run.status === \"completed\" && run.conclusion === \"success\";\n}\n","// Types\nexport {\n type GitHubIssue, type GitHubPR, type WorkflowRun, type CheckStatus, type GhResult,\n GitHubIssueSchema, GitHubPRSchema, WorkflowRunSchema, CheckStatusSchema, GhResultSchema,\n} from \"./types.js\";\n\n// CLI\nexport { gh, ghJson, ghAvailable, ghCurrentRepo, GhError } from \"./cli.js\";\n\n// Issue Planner\nexport { fetchIssue, formatIssueAsRequirement, planFromIssue } from \"./issue-planner.js\";\n\n// PR Manager\nexport { createPR, listPRs, getPR, commentOnPR, createBranch, type CreatePROptions } from \"./pr-manager.js\";\n\n// CI Gate\nexport { getLatestRun, getCheckStatus, waitForCI, isCIPassing } from \"./ci-gate.js\";\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport os from \"node:os\";\nimport { createDatabase, recall } from \"@aman_asmuei/amem-core\";\nimport {\n getIdentity as acoreGetIdentity,\n} from \"@aman_asmuei/acore-core\";\nimport {\n listRuleCategories as arulesListCategories,\n} from \"@aman_asmuei/arules-core\";\nimport type { StackProfile } from \"./stack-detector.js\";\nimport type { ProjectContext } from \"./claude-md-writer.js\";\nimport { estimateTokens } from \"../token-budget.js\";\n\nconst AGENT_SCOPE = process.env.AMAN_AGENT_SCOPE ?? \"dev:agent\";\n\nconst TOKEN_LIMITS: Record<string, number> = {\n conventions: 1500,\n decisions: 1200,\n corrections: 800,\n preferences: 500,\n rules: 800,\n};\n\nfunction trimToTokenBudget(items: string[], maxTokens: number): string[] {\n const result: string[] = [];\n let total = 0;\n for (const item of items) {\n if (typeof item !== \"string\" || !item) continue;\n const tokens = estimateTokens(item);\n if (total + tokens > maxTokens) break;\n result.push(item);\n total += tokens;\n }\n return result;\n}\n\nexport interface BuildOptions {\n smart?: boolean;\n llmClient?: unknown;\n}\n\nexport async function buildContext(\n stack: StackProfile,\n opts?: BuildOptions,\n): Promise<ProjectContext> {\n const conventions: string[] = [];\n const decisions: string[] = [];\n const corrections: string[] = [];\n const preferences: string[] = [];\n const rules: string[] = [];\n let memoriesUsed = 0;\n\n // --- Query amem ---\n try {\n const amemDir = process.env.AMEM_DIR ?? path.join(os.homedir(), \".amem\");\n const dbPath = process.env.AMEM_DB ?? path.join(amemDir, \"memory.db\");\n\n // Skip if database doesn't exist — avoids loading HuggingFace models for nothing\n // But allow override via AMEM_DB env var (also needed for tests with mocked createDatabase)\n if (!process.env.AMEM_DB && !fs.existsSync(dbPath)) throw new Error(\"no db\");\n\n const db = createDatabase(dbPath);\n\n // Build a project-focused query\n const queryParts = [stack.projectName, ...stack.languages, ...stack.frameworks];\n const query = queryParts.join(\" \");\n\n // Build relevance keywords for post-recall filtering\n // Only keep memories that mention the project name, stack languages, or frameworks\n const relevanceKeywords = queryParts\n .map((k) => k.toLowerCase())\n .filter(Boolean);\n\n // rerank: false skips the cross-encoder model — much faster startup\n // Fetch more candidates so we have enough after filtering\n const result = await recall(db, { query, limit: 40, compact: false, rerank: false });\n\n // Max content length per memory entry (prevents one huge memory from filling the budget)\n const MAX_CONTENT_LENGTH = 500;\n\n for (const mem of result.memories) {\n let content = (mem as any).content;\n if (typeof content !== \"string\" || !content) continue;\n\n // Project relevance filter: memory must mention at least one keyword\n // from the project name, language, or framework\n const contentLower = content.toLowerCase();\n const isRelevant = relevanceKeywords.length === 0 ||\n relevanceKeywords.some((kw) => {\n // Short keywords (e.g. \"go\") use word boundary match to avoid false positives\n if (kw.length <= 3) {\n return new RegExp(`\\\\b${kw}\\\\b`, \"i\").test(contentLower);\n }\n return contentLower.includes(kw);\n });\n if (!isRelevant) continue;\n\n // Truncate very long memories to keep CLAUDE.md focused\n if (content.length > MAX_CONTENT_LENGTH) {\n content = content.slice(0, MAX_CONTENT_LENGTH).trimEnd() + \"...\";\n }\n\n switch ((mem as any).type) {\n case \"pattern\":\n if (!conventions.includes(content)) conventions.push(content);\n break;\n case \"decision\":\n if (!decisions.includes(content)) decisions.push(content);\n break;\n case \"correction\":\n if (!corrections.includes(content)) corrections.push(content);\n break;\n case \"preference\":\n if (!preferences.includes(content)) preferences.push(content);\n break;\n }\n memoriesUsed++;\n }\n } catch {\n // amem not available — continue without memories\n }\n\n // --- Query acore for identity/preferences ---\n try {\n const identity = await acoreGetIdentity(AGENT_SCOPE);\n if (identity?.content) {\n const lines = identity.content.split(\"\\n\").filter((l: string) =>\n l.startsWith(\"- \") && (\n l.toLowerCase().includes(\"prefer\") ||\n l.toLowerCase().includes(\"style\") ||\n l.toLowerCase().includes(\"convention\")\n ),\n );\n for (const line of lines) {\n const text = line.replace(/^-\\s*/, \"\").trim();\n if (text && !preferences.includes(text)) preferences.push(text);\n }\n }\n } catch {\n // acore not available\n }\n\n // --- Query arules ---\n try {\n const categories = await arulesListCategories(AGENT_SCOPE);\n // arules-core returns { name: string; rules: string[] } — rules are already filtered to active-only\n for (const cat of categories) {\n for (const ruleText of cat.rules) {\n if (typeof ruleText === \"string\" && ruleText && !rules.includes(ruleText)) {\n rules.push(ruleText);\n }\n }\n }\n } catch {\n // arules not available\n }\n\n // --- Smart mode: LLM synthesis ---\n if (opts?.smart && opts.llmClient) {\n try {\n const client = opts.llmClient as { chat: (system: string, msgs: { role: string; content: string }[], onChunk: () => void) => Promise<{ message: { content: string | { text?: string }[] } }> };\n const rawData = [\n `Project: ${stack.projectName}`,\n `Stack: ${stack.languages.join(\", \")} + ${stack.frameworks.join(\", \")}`,\n `Databases: ${stack.databases.join(\", \") || \"none detected\"}`,\n \"\",\n conventions.length > 0 ? `Conventions:\\n${conventions.map((c) => `- ${c}`).join(\"\\n\")}` : \"\",\n decisions.length > 0 ? `Decisions:\\n${decisions.map((d) => `- ${d}`).join(\"\\n\")}` : \"\",\n corrections.length > 0 ? `Corrections:\\n${corrections.map((c) => `- ${c}`).join(\"\\n\")}` : \"\",\n preferences.length > 0 ? `Preferences:\\n${preferences.map((p) => `- ${p}`).join(\"\\n\")}` : \"\",\n rules.length > 0 ? `Rules:\\n${rules.map((r) => `- ${r}`).join(\"\\n\")}` : \"\",\n ].filter(Boolean).join(\"\\n\\n\");\n\n const response = await client.chat(\n \"You are a developer context assembler. Given raw developer history, output a merged, deduplicated set of conventions and decisions as markdown bullet lists. Group by: Conventions, Decisions, Corrections, Preferences, Rules. Be specific, not generic. Max 3000 tokens.\",\n [{ role: \"user\", content: rawData }],\n () => {},\n );\n\n // Parse LLM response to extract synthesized sections\n const text = typeof response.message.content === \"string\"\n ? response.message.content\n : response.message.content.map((b: { text?: string }) => b.text ?? \"\").join(\"\");\n\n // Extract bullet points from each section the LLM generated\n const extractSection = (sectionName: string): string[] => {\n const regex = new RegExp(`##?\\\\s*${sectionName}[\\\\s\\\\S]*?(?=##|$)`, \"i\");\n const match = text.match(regex);\n if (!match) return [];\n return match[0].split(\"\\n\").filter((l) => l.startsWith(\"- \")).map((l) => l.replace(/^-\\s*/, \"\").trim());\n };\n\n const smartConventions = extractSection(\"Conventions\");\n const smartDecisions = extractSection(\"Decisions\");\n const smartCorrections = extractSection(\"Corrections\");\n const smartPreferences = extractSection(\"Preferences\");\n const smartRules = extractSection(\"Rules\");\n\n return {\n stack,\n conventions: trimToTokenBudget(smartConventions.length > 0 ? smartConventions : conventions, TOKEN_LIMITS.conventions),\n decisions: trimToTokenBudget(smartDecisions.length > 0 ? smartDecisions : decisions, TOKEN_LIMITS.decisions),\n corrections: trimToTokenBudget(smartCorrections.length > 0 ? smartCorrections : corrections, TOKEN_LIMITS.corrections),\n preferences: trimToTokenBudget(smartPreferences.length > 0 ? smartPreferences : preferences, TOKEN_LIMITS.preferences),\n rules: trimToTokenBudget(smartRules.length > 0 ? smartRules : rules, TOKEN_LIMITS.rules),\n metadata: {\n generatedAt: Date.now(),\n mode: \"smart\" as const,\n memoriesUsed,\n },\n };\n } catch {\n // LLM failed — fall through to template mode\n }\n }\n\n // --- Apply token budgets ---\n return {\n stack,\n conventions: trimToTokenBudget(conventions, TOKEN_LIMITS.conventions),\n decisions: trimToTokenBudget(decisions, TOKEN_LIMITS.decisions),\n corrections: trimToTokenBudget(corrections, TOKEN_LIMITS.corrections),\n preferences: trimToTokenBudget(preferences, TOKEN_LIMITS.preferences),\n rules: trimToTokenBudget(rules, TOKEN_LIMITS.rules),\n metadata: {\n generatedAt: Date.now(),\n mode: \"template\" as const,\n memoriesUsed,\n },\n };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { StackProfile } from \"./stack-detector.js\";\n\nexport interface ProjectContext {\n stack: StackProfile;\n conventions: string[];\n decisions: string[];\n corrections: string[];\n preferences: string[];\n rules: string[];\n metadata: {\n generatedAt: number;\n mode: \"template\" | \"smart\";\n memoriesUsed: number;\n };\n}\n\nexport interface MarkerInfo {\n generatedAt: Date;\n memories: number;\n mode: string;\n}\n\nexport interface WriteResult {\n written: boolean;\n backedUp: boolean;\n path: string;\n}\n\nexport interface StalenessResult {\n status: \"missing\" | \"no-marker\" | \"fresh\" | \"stale\";\n generatedAt?: Date;\n}\n\nfunction formatStack(stack: StackProfile): string {\n const parts: string[] = [];\n const goFrameworks = [\"fiber\", \"gin\", \"chi\", \"echo\"];\n const jsFrameworks = [\"next\", \"react\", \"remix\", \"express\", \"fastify\", \"hono\", \"nestjs\", \"vue\", \"svelte\", \"nuxt\"];\n const pyFrameworks = [\"django\", \"fastapi\", \"flask\"];\n\n for (const lang of stack.languages) {\n const fw = stack.frameworks.filter((f) => {\n if (lang === \"go\" && goFrameworks.includes(f)) return true;\n if ((lang === \"typescript\" || lang === \"javascript\") && jsFrameworks.includes(f)) return true;\n if (lang === \"python\" && pyFrameworks.includes(f)) return true;\n if (lang === \"dart\" && f === \"flutter\") return true;\n return false;\n });\n const name = lang.charAt(0).toUpperCase() + lang.slice(1);\n if (fw.length > 0) {\n parts.push(`${name} (${fw.map((f) => f.charAt(0).toUpperCase() + f.slice(1)).join(\", \")})`);\n } else {\n parts.push(name);\n }\n }\n if (stack.databases.length > 0) {\n parts.push(...stack.databases.map((d) => d.charAt(0).toUpperCase() + d.slice(1)));\n }\n return parts.join(\" + \");\n}\n\nexport function renderToString(ctx: ProjectContext): string {\n const lines: string[] = [];\n const ts = new Date(ctx.metadata.generatedAt).toISOString();\n\n lines.push(`# Project: ${ctx.stack.projectName}`);\n lines.push(`<!-- aman-agent:dev generated=${ts} memories=${ctx.metadata.memoriesUsed} mode=${ctx.metadata.mode} -->`);\n lines.push(\"\");\n\n const stackLine = formatStack(ctx.stack);\n if (stackLine || ctx.stack.infra.length > 0) {\n lines.push(\"## Stack\");\n if (stackLine) lines.push(`- ${stackLine}`);\n if (ctx.stack.infra.length > 0) {\n lines.push(`- Infra: ${ctx.stack.infra.join(\", \")}`);\n }\n if (ctx.stack.isMonorepo) {\n lines.push(\"- Monorepo\");\n }\n lines.push(\"\");\n }\n\n if (ctx.conventions.length > 0) {\n lines.push(\"## Conventions\");\n for (const c of ctx.conventions) lines.push(`- ${c}`);\n lines.push(\"\");\n }\n\n if (ctx.decisions.length > 0) {\n lines.push(\"## Past Decisions\");\n for (const d of ctx.decisions) lines.push(`- ${d}`);\n lines.push(\"\");\n }\n\n if (ctx.corrections.length > 0) {\n lines.push(\"## Corrections\");\n for (const c of ctx.corrections) lines.push(`- ${c}`);\n lines.push(\"\");\n }\n\n if (ctx.preferences.length > 0) {\n lines.push(\"## Developer Preferences\");\n for (const p of ctx.preferences) lines.push(`- ${p}`);\n lines.push(\"\");\n }\n\n if (ctx.rules.length > 0) {\n lines.push(\"## Rules\");\n for (const r of ctx.rules) lines.push(`- ${r}`);\n lines.push(\"\");\n }\n\n return lines.join(\"\\n\");\n}\n\nexport function parseMarker(content: string): MarkerInfo | null {\n const match = content.match(\n /<!--\\s*aman-agent:dev\\s+generated=(\\S+)\\s+memories=(\\d+)\\s+mode=(\\S+)\\s*-->/,\n );\n if (!match) return null;\n return {\n generatedAt: new Date(match[1]),\n memories: parseInt(match[2], 10),\n mode: match[3],\n };\n}\n\n// --- Editor target definitions ---\n\nexport type EditorName = \"claude\" | \"copilot\" | \"cursor\";\n\nexport interface EditorTarget {\n name: EditorName;\n contextFile: string; // relative path from project root\n launchCmd: string; // binary to launch\n launchArgs: string[]; // default args\n yoloArgs?: string[]; // extra args for --yolo mode\n gitignoreEntry: string; // what to add to .gitignore\n displayName: string; // for terminal output\n}\n\nexport const EDITOR_TARGETS: Record<EditorName, EditorTarget> = {\n claude: {\n name: \"claude\",\n contextFile: \"CLAUDE.md\",\n launchCmd: \"claude\",\n launchArgs: [],\n yoloArgs: [\"--dangerously-skip-permissions\"],\n gitignoreEntry: \"CLAUDE.md\",\n displayName: \"Claude Code\",\n },\n copilot: {\n name: \"copilot\",\n contextFile: \".github/copilot-instructions.md\",\n launchCmd: \"code\",\n launchArgs: [\".\"],\n gitignoreEntry: \".github/copilot-instructions.md\",\n displayName: \"VS Code (Copilot)\",\n },\n cursor: {\n name: \"cursor\",\n contextFile: \".cursorrules\",\n launchCmd: \"cursor\",\n launchArgs: [\".\"],\n gitignoreEntry: \".cursorrules\",\n displayName: \"Cursor\",\n },\n};\n\nexport function checkStaleness(projectPath: string, editor: EditorName = \"claude\"): StalenessResult {\n const target = EDITOR_TARGETS[editor];\n const filePath = path.join(projectPath, target.contextFile);\n if (!fs.existsSync(filePath)) {\n return { status: \"missing\" };\n }\n const content = fs.readFileSync(filePath, \"utf-8\");\n const marker = parseMarker(content);\n if (!marker) {\n return { status: \"no-marker\" };\n }\n return { status: \"fresh\", generatedAt: marker.generatedAt };\n}\n\nexport function writeContextFile(ctx: ProjectContext, projectPath: string, editor: EditorName = \"claude\"): WriteResult {\n const target = EDITOR_TARGETS[editor];\n const filePath = path.join(projectPath, target.contextFile);\n let backedUp = false;\n\n // Ensure parent directory exists (e.g. .github/ for copilot)\n const parentDir = path.dirname(filePath);\n if (!fs.existsSync(parentDir)) {\n fs.mkdirSync(parentDir, { recursive: true });\n }\n\n if (fs.existsSync(filePath)) {\n const content = fs.readFileSync(filePath, \"utf-8\");\n const marker = parseMarker(content);\n if (!marker) {\n fs.copyFileSync(filePath, `${filePath}.bak`);\n backedUp = true;\n }\n }\n\n const md = renderToString(ctx);\n fs.writeFileSync(filePath, md, \"utf-8\");\n\n return { written: true, backedUp, path: filePath };\n}\n\n// Backward compat alias\nexport const writeClaudeMd = writeContextFile;\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { scanStack, type StackProfile } from \"./stack-detector.js\";\nimport { buildContext } from \"./context-builder.js\";\nimport {\n renderToString,\n writeContextFile,\n checkStaleness,\n EDITOR_TARGETS,\n type EditorName,\n} from \"./claude-md-writer.js\";\nimport type { ProjectContext } from \"./claude-md-writer.js\";\n\nexport interface DevFlags {\n smart?: boolean;\n noLaunch?: boolean;\n force?: boolean;\n diff?: boolean;\n editor?: EditorName;\n}\n\nexport interface DevResult {\n success: boolean;\n generated: boolean;\n skippedReason?: string;\n diff?: string;\n context?: ProjectContext;\n error?: string;\n}\n\nfunction ensureGitignore(projectPath: string, editor: EditorName): void {\n const gitignorePath = path.join(projectPath, \".gitignore\");\n if (!fs.existsSync(gitignorePath)) return;\n const content = fs.readFileSync(gitignorePath, \"utf-8\");\n const target = EDITOR_TARGETS[editor];\n if (content.includes(target.gitignoreEntry)) return;\n fs.appendFileSync(gitignorePath, `\\n# Generated by aman-agent dev\\n${target.gitignoreEntry}\\n`);\n}\n\nexport async function runDev(\n projectPath: string,\n flags: DevFlags = {},\n precomputedStack?: StackProfile,\n): Promise<DevResult> {\n const resolved = path.resolve(projectPath);\n const editor = flags.editor ?? \"claude\";\n\n if (!fs.existsSync(resolved)) {\n return { success: false, generated: false, error: `Directory not found: ${resolved}` };\n }\n\n const stack = precomputedStack ?? scanStack(resolved);\n\n // Handle --diff\n if (flags.diff) {\n const ctx = await buildContext(stack, { smart: flags.smart });\n const newContent = renderToString(ctx);\n const target = EDITOR_TARGETS[editor];\n const existingPath = path.join(resolved, target.contextFile);\n const existing = fs.existsSync(existingPath)\n ? fs.readFileSync(existingPath, \"utf-8\")\n : \"\";\n return {\n success: true,\n generated: false,\n diff: existing === newContent ? \"(no changes)\" : newContent,\n context: ctx,\n };\n }\n\n // Check staleness\n // --smart always regenerates (user explicitly wants LLM synthesis)\n if (!flags.force && !flags.smart) {\n const staleness = checkStaleness(resolved, editor);\n if (staleness.status === \"fresh\") {\n // Check if context file is older than 1 hour — if so, regenerate\n if (staleness.generatedAt) {\n const ageMs = Date.now() - staleness.generatedAt.getTime();\n const ONE_HOUR = 60 * 60 * 1000;\n if (ageMs < ONE_HOUR) {\n return { success: true, generated: false, skippedReason: \"fresh\" };\n }\n } else {\n return { success: true, generated: false, skippedReason: \"fresh\" };\n }\n }\n }\n\n // Build context and write\n const ctx = await buildContext(stack, { smart: flags.smart });\n writeContextFile(ctx, resolved, editor);\n\n ensureGitignore(resolved, editor);\n\n return {\n success: true,\n generated: true,\n context: ctx,\n };\n}\n","import { Command } from \"commander\";\nimport * as p from \"@clack/prompts\";\nimport pc from \"picocolors\";\nimport { loadConfig, saveConfig, identityDir, rulesDir, workflowsDir, skillsDir, memoryDir, homeDir } from \"./config.js\";\nimport { migrateIfNeeded } from \"./migrate.js\";\nimport { assembleSystemPrompt, getProfileAiName } from \"./prompt.js\";\nimport { pickLLMClient } from \"./llm/index.js\";\nimport { isClaudeCliInstalled } from \"./llm/claude-code.js\";\nimport { isCopilotCliInstalled, isCopilotCliAuthenticated } from \"./llm/copilot.js\";\nimport { McpManager } from \"./mcp/client.js\";\nimport { runAgent } from \"./agent.js\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { applyPreset, PRESETS, type PresetName } from \"./presets.js\";\nimport { initMemory, memoryConsolidate, isMemoryInitialized, setMemoryConfig, startupAutoSync } from \"./memory.js\";\nimport { hasUserIdentity, loadUserIdentity } from \"./user-identity.js\";\nimport { runOnboarding } from \"./onboarding.js\";\nimport { runServe } from \"./server/serve-command.js\";\n\ndeclare const __VERSION__: string;\n\ninterface AutoDetectedConfig {\n provider: \"anthropic\" | \"openai\" | \"ollama\" | \"claude-code\" | \"copilot\";\n apiKey: string;\n model: string;\n}\n\nasync function autoDetectConfig(): Promise<AutoDetectedConfig | null> {\n // Skip auto-detect if user just ran /reset config\n const reconfigMarker = path.join(homeDir(), \".reconfig\");\n if (fs.existsSync(reconfigMarker)) {\n fs.unlinkSync(reconfigMarker);\n return null; // Force interactive prompt\n }\n\n const anthropicKey = process.env.ANTHROPIC_API_KEY;\n if (anthropicKey) {\n return { provider: \"anthropic\", apiKey: anthropicKey, model: \"claude-sonnet-4-6\" };\n }\n const openaiKey = process.env.OPENAI_API_KEY;\n if (openaiKey) {\n return { provider: \"openai\", apiKey: openaiKey, model: \"gpt-4o\" };\n }\n // Check Ollama — verify it's running AND has at least one model\n try {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), 2000);\n const res = await fetch(\"http://localhost:11434/api/tags\", { signal: controller.signal });\n clearTimeout(timeout);\n if (res.ok) {\n const data = await res.json() as { models?: Array<{ name: string }> };\n const models = data.models || [];\n if (models.length > 0) {\n // Pick the first available model\n const modelName = models[0].name.replace(/:latest$/, \"\");\n return { provider: \"ollama\", apiKey: \"ollama\", model: modelName };\n }\n // Ollama running but no models downloaded — skip\n }\n } catch { /* Ollama not available */ }\n return null;\n}\n\nfunction bootstrapEcosystem(): boolean {\n const corePath = path.join(identityDir(), \"core.md\");\n if (fs.existsSync(corePath)) return false;\n\n fs.mkdirSync(identityDir(), { recursive: true });\n fs.writeFileSync(corePath, [\n \"# Aman\",\n \"\",\n \"## Personality\",\n \"Helpful, adaptive, and thoughtful. Matches the user's tone and needs.\",\n \"\",\n \"## Style\",\n \"Clear and concise. Prioritizes usefulness over verbosity.\",\n \"\",\n \"## Session\",\n \"_New companion — no prior sessions._\",\n ].join(\"\\n\"), \"utf-8\");\n\n const rulesPath = path.join(rulesDir(), \"rules.md\");\n if (!fs.existsSync(rulesPath)) {\n fs.mkdirSync(rulesDir(), { recursive: true });\n fs.writeFileSync(rulesPath, [\n \"# Guardrails\",\n \"\",\n \"## safety\",\n \"- Never execute destructive commands without explicit confirmation\",\n \"- Never expose API keys, passwords, or secrets in responses\",\n \"\",\n \"## behavior\",\n '- Be honest when uncertain — say \"I\\'m not sure\" rather than guessing',\n \"- Respect the user's preferences stored in memory\",\n ].join(\"\\n\"), \"utf-8\");\n }\n\n const flowPath = path.join(workflowsDir(), \"flow.md\");\n if (!fs.existsSync(flowPath)) {\n fs.mkdirSync(workflowsDir(), { recursive: true });\n fs.writeFileSync(flowPath, \"# Workflows\\n\\n_No workflows defined yet. Use /workflows add to create one._\\n\", \"utf-8\");\n }\n\n const skillPath = path.join(skillsDir(), \"skills.md\");\n if (!fs.existsSync(skillPath)) {\n fs.mkdirSync(skillsDir(), { recursive: true });\n fs.writeFileSync(skillPath, \"# Skills\\n\\n_No skills installed yet. Use /skills install to add domain expertise._\\n\", \"utf-8\");\n }\n\n return true;\n}\n\nconst program = new Command();\n\nprogram\n .name(\"aman-agent\")\n .description(\"Your AI companion, running locally\")\n .version(__VERSION__)\n .option(\"--model <model>\", \"Override LLM model\")\n .option(\"--budget <tokens>\", \"Token budget for system prompt (default: 8000)\", parseInt)\n .option(\"--profile <name>\", \"Use a specific agent profile (e.g., coder, writer, researcher)\")\n .action(async (options) => {\n p.intro(pc.bold(\"aman agent\") + pc.dim(\" — your AI companion\"));\n\n // Setup config if needed\n let config = loadConfig();\n if (!config) {\n const detected = await autoDetectConfig();\n if (detected) {\n config = detected;\n const providerLabel =\n detected.provider === \"anthropic\" ? \"Anthropic API key\" :\n detected.provider === \"openai\" ? \"OpenAI API key\" : \"Ollama\";\n p.log.success(`Auto-detected ${providerLabel}. Using ${pc.bold(detected.model)}.`);\n p.log.info(pc.dim(\"Change anytime with /reset config\"));\n saveConfig(config);\n } else {\n // Non-interactive (systemd, Docker without -it, CI) — fail clearly\n if (!process.stdin.isTTY) {\n console.error(\"Error: No LLM provider configured.\");\n console.error(\"Set ANTHROPIC_API_KEY or OPENAI_API_KEY, or run interactively: aman-agent\");\n process.exit(1);\n }\n\n p.log.info(\"First-time setup — configure your LLM connection.\");\n\n const provider = (await p.select({\n message: \"LLM provider\",\n options: [\n {\n value: \"claude-code\",\n label: \"Claude (Anthropic)\",\n hint: \"recommended\",\n },\n {\n value: \"copilot\",\n label: \"GitHub Copilot\",\n hint: \"uses GitHub Models\",\n },\n { value: \"openai\", label: \"GPT (OpenAI)\" },\n { value: \"ollama\", label: \"Ollama (local)\", hint: \"free, runs offline\" },\n ],\n initialValue: \"claude-code\",\n })) as \"openai\" | \"ollama\" | \"claude-code\" | \"copilot\";\n if (p.isCancel(provider)) process.exit(0);\n\n let apiKey = \"\";\n let defaultModel = \"\";\n\n if (provider === \"ollama\") {\n apiKey = \"ollama\";\n const modelInput = (await p.text({\n message: \"Ollama model name\",\n placeholder: \"llama3.2\",\n defaultValue: \"llama3.2\",\n })) as string;\n if (p.isCancel(modelInput)) process.exit(0);\n defaultModel = modelInput || \"llama3.2\";\n } else if (provider === \"claude-code\") {\n // Claude via Claude Code CLI — handles subscription, API, and 3rd-party auth\n p.note(\n [\n `${pc.bold(\"Claude Plans:\")}`,\n \"\",\n ` ${pc.cyan(\"Free\")} $0/mo Basic access`,\n ` ${pc.cyan(\"Pro\")} $20/mo Full models + Claude Code`,\n ` ${pc.cyan(\"Max 5x\")} $100/mo 5× usage + Claude Code`,\n ` ${pc.cyan(\"Max 20x\")} $200/mo 20× usage + Opus 4.6 + 1M context`,\n ` ${pc.cyan(\"Team\")} $25+/seat Collaborative workspace`,\n ` ${pc.cyan(\"Enterprise\")} Custom SSO, admin, dedicated support`,\n \"\",\n `${pc.dim(\"Authentication is handled by Claude Code CLI.\")}`,\n `${pc.dim(\"Supports: subscription, API billing, Bedrock, Vertex AI.\")}`,\n ].join(\"\\n\"),\n \"Claude Plans\",\n );\n\n // Check if claude CLI is installed\n if (!isClaudeCliInstalled()) {\n p.log.error(\"Claude Code CLI is not installed.\");\n p.log.info(\"Install it with:\");\n p.log.step(pc.bold(\"npm install -g @anthropic-ai/claude-code\"));\n p.log.info(pc.dim(\"Then re-run aman-agent to continue setup.\"));\n process.exit(1);\n }\n\n p.log.success(\"Claude Code CLI detected.\");\n\n // Check auth / offer login\n const authAction = (await p.select({\n message: \"Authentication\",\n options: [\n { value: \"logged-in\", label: \"Already logged in to Claude Code\" },\n { value: \"login\", label: \"Log in now\", hint: \"runs: claude login\" },\n ],\n })) as string;\n if (p.isCancel(authAction)) process.exit(0);\n\n if (authAction === \"login\") {\n p.log.step(\"Launching Claude Code login...\");\n const { spawnSync } = await import(\"node:child_process\");\n const loginResult = spawnSync(\"claude\", [\"login\"], {\n stdio: \"inherit\",\n });\n if (loginResult.status !== 0) {\n p.log.error(\"Login failed or was cancelled. Please try again.\");\n process.exit(1);\n }\n p.log.success(\"Login successful.\");\n }\n\n apiKey = \"claude-code\"; // Sentinel — auth handled by CLI\n\n const modelChoice = (await p.select({\n message: \"Claude model\",\n options: [\n { value: \"claude-sonnet-4-6\", label: \"Claude Sonnet 4.6\", hint: \"fast, recommended\" },\n { value: \"claude-opus-4-6\", label: \"Claude Opus 4.6\", hint: \"most capable\" },\n { value: \"claude-haiku-4-5-20251001\", label: \"Claude Haiku 4.5\", hint: \"fastest\" },\n { value: \"custom\", label: \"Custom model ID\" },\n ],\n initialValue: \"claude-sonnet-4-6\",\n })) as string;\n if (p.isCancel(modelChoice)) process.exit(0);\n\n if (modelChoice === \"custom\") {\n const customModel = (await p.text({\n message: \"Model ID\",\n placeholder: \"claude-sonnet-4-6\",\n validate: (v) => v.length === 0 ? \"Model ID is required\" : undefined,\n })) as string;\n if (p.isCancel(customModel)) process.exit(0);\n defaultModel = customModel;\n } else {\n defaultModel = modelChoice;\n }\n } else if (provider === \"copilot\") {\n // GitHub Copilot via Copilot CLI\n p.note(\n [\n `${pc.bold(\"GitHub Copilot Plans:\")}`,\n \"\",\n ` ${pc.cyan(\"Free\")} $0/mo 2,000 code completions + 50 chat msgs`,\n ` ${pc.cyan(\"Pro\")} $10/mo Unlimited completions + chat`,\n ` ${pc.cyan(\"Pro+\")} $39/mo Unlimited + Opus/o1 + agent mode`,\n ` ${pc.cyan(\"Business\")} $19/user/mo Team admin + policy controls`,\n ` ${pc.cyan(\"Enterprise\")} $39/user/mo SSO, audit logs, IP indemnity`,\n \"\",\n `${pc.dim(\"Authentication is handled by the Copilot CLI.\")}`,\n `${pc.dim(\"Subscribe at: https://github.com/features/copilot\")}`,\n ].join(\"\\n\"),\n \"Copilot Plans\",\n );\n\n // Check if copilot CLI is installed\n if (!isCopilotCliInstalled()) {\n p.log.error(\"Copilot CLI is not installed.\");\n p.log.info(\"Install it from:\");\n p.log.step(pc.bold(\"https://docs.github.com/copilot/how-tos/copilot-cli\"));\n p.log.info(pc.dim(\"Then re-run aman-agent to continue setup.\"));\n process.exit(1);\n }\n\n p.log.success(\"Copilot CLI detected.\");\n\n // Check auth / offer login\n const copilotAuth = isCopilotCliAuthenticated();\n if (copilotAuth) {\n p.log.success(\"Copilot authentication found.\");\n } else {\n p.log.warn(\"Not logged in to Copilot.\");\n const authAction = (await p.select({\n message: \"Authentication\",\n options: [\n { value: \"login\", label: \"Log in now\", hint: \"runs: copilot login\" },\n { value: \"skip\", label: \"Skip (I'll log in later)\" },\n ],\n })) as string;\n if (p.isCancel(authAction)) process.exit(0);\n\n if (authAction === \"login\") {\n p.log.step(\"Launching Copilot login...\");\n const { spawnSync } = await import(\"node:child_process\");\n const loginResult = spawnSync(\"copilot\", [\"login\"], {\n stdio: \"inherit\",\n });\n if (loginResult.status !== 0) {\n p.log.error(\"Login failed or was cancelled.\");\n process.exit(1);\n }\n p.log.success(\"Copilot login successful.\");\n }\n }\n\n apiKey = \"copilot\"; // Sentinel — auth handled by CLI\n\n const modelChoice = (await p.select({\n message: \"Model\",\n options: [\n { value: \"default\", label: \"Default\", hint: \"Copilot's default model\" },\n { value: \"gpt-4o\", label: \"GPT-4o\", hint: \"fast\" },\n { value: \"gpt-5.2\", label: \"GPT-5.2\", hint: \"most capable\" },\n { value: \"o3-mini\", label: \"o3-mini\", hint: \"reasoning\" },\n { value: \"custom\", label: \"Custom model ID\" },\n ],\n initialValue: \"default\",\n })) as string;\n if (p.isCancel(modelChoice)) process.exit(0);\n\n if (modelChoice === \"custom\") {\n const customModel = (await p.text({\n message: \"Model ID (run copilot --help for available models)\",\n placeholder: \"gpt-4o\",\n validate: (v) => v.length === 0 ? \"Model ID is required\" : undefined,\n })) as string;\n if (p.isCancel(customModel)) process.exit(0);\n defaultModel = customModel;\n } else if (modelChoice === \"default\") {\n defaultModel = \"\";\n } else {\n defaultModel = modelChoice;\n }\n } else {\n // OpenAI\n apiKey = (await p.text({\n message: \"API key\",\n validate: (v) => v.length === 0 ? \"API key is required\" : undefined,\n })) as string;\n if (p.isCancel(apiKey)) process.exit(0);\n\n const modelChoice = (await p.select({\n message: \"OpenAI model\",\n options: [\n { value: \"gpt-4o\", label: \"GPT-4o\", hint: \"recommended\" },\n { value: \"gpt-4o-mini\", label: \"GPT-4o Mini\", hint: \"faster, cheaper\" },\n { value: \"o3\", label: \"o3\", hint: \"reasoning model\" },\n { value: \"custom\", label: \"Custom model ID\" },\n ],\n initialValue: \"gpt-4o\",\n })) as string;\n if (p.isCancel(modelChoice)) process.exit(0);\n\n if (modelChoice === \"custom\") {\n const customModel = (await p.text({\n message: \"Model ID\",\n placeholder: \"gpt-4o\",\n validate: (v) => v.length === 0 ? \"Model ID is required\" : undefined,\n })) as string;\n if (p.isCancel(customModel)) process.exit(0);\n defaultModel = customModel;\n } else {\n defaultModel = modelChoice;\n }\n }\n\n config = { provider, apiKey, model: defaultModel };\n saveConfig(config);\n p.log.success(\"Config saved to ~/.aman-agent/config.json\");\n }\n }\n\n // Override model if specified\n const model = options.model || config.model;\n\n // Spinner: bootstrap ecosystem + load system prompt\n const s = p.spinner();\n s.start(\"Loading ecosystem\");\n\n // Migrate old scattered directories to consolidated layout\n const migration = migrateIfNeeded();\n if (migration.migrated.length > 0) {\n for (const dir of migration.migrated) {\n p.log.info(`Migrated → ~/.aman-agent/${dir}/`);\n }\n }\n\n // Point ecosystem libs at consolidated layout\n process.env.ACORE_HOME = identityDir();\n process.env.ARULES_HOME = rulesDir();\n process.env.AMEM_DIR = memoryDir();\n\n const isFirstRun = bootstrapEcosystem();\n\n // User onboarding — runs once on first launch\n if (!hasUserIdentity()) {\n s.stop(\"Ecosystem loaded\");\n const user = await runOnboarding();\n if (!user) {\n p.log.info(\"Skipped profile setup. You can set it up later with /profile edit\");\n }\n s.start(\"Loading ecosystem\");\n }\n\n // Resolve profile\n const profile = options.profile || process.env.AMAN_PROFILE || undefined;\n if (profile) {\n p.log.info(`Profile: ${pc.bold(profile)}`);\n }\n\n // Assemble system prompt from ecosystem with token budget\n const budget = options.budget || undefined;\n const { prompt: systemPrompt, layers, truncated, totalTokens } = assembleSystemPrompt(budget, profile);\n\n s.stop(\"Ecosystem loaded\");\n\n if (layers.length === 0) {\n p.log.warning(\n \"No ecosystem configured. Run \" +\n pc.bold(\"npx @aman_asmuei/aman\") +\n \" first.\",\n );\n p.log.info(\"Starting with empty system prompt.\");\n } else {\n p.log.success(\n `Loaded: ${layers.join(\", \")} ${pc.dim(`(${totalTokens.toLocaleString()} tokens)`)}`,\n );\n if (truncated.length > 0) {\n p.log.warning(`Truncated: ${truncated.join(\", \")} ${pc.dim(\"(over budget)\")}`);\n }\n }\n\n // Extract AI name from core.md\n const aiName = getProfileAiName(profile);\n\n // Initialize memory (in-process, replaces amem MCP)\n if (config.memory) setMemoryConfig(config.memory);\n try {\n await initMemory();\n } catch (err) {\n p.log.warning(`Memory initialization failed: ${err instanceof Error ? err.message : String(err)}`);\n }\n\n // Auto-sync mirror dir → DB (Task 2.4). Closes the multi-device loop:\n // edits made on machine A's mirror dir (Dropbox/iCloud/git) land in\n // machine B's DB on next launch. Awaited so the REPL does not accept\n // user input before synced memories are queryable. startupAutoSync\n // swallows its own errors — any throw here is a defensive net.\n //\n // Wrapped in a spinner because with a fresh Dropbox mirror each file\n // triggers generateEmbedding() (~50-200ms + 3-5s cold start). Without\n // feedback the REPL looks frozen for 10-40s on first launch.\n if (isMemoryInitialized()) {\n const mirrorSpinner = p.spinner();\n mirrorSpinner.start(\"Checking mirror dir for updates\");\n try {\n const syncResult = await startupAutoSync();\n mirrorSpinner.stop(\n syncResult && syncResult.imported > 0\n ? `[mirror] synced ${syncResult.imported} new`\n : \"\",\n );\n } catch (err) {\n mirrorSpinner.stop(\n pc.dim(\n `[mirror] auto-sync skipped: ${err instanceof Error ? err.message : String(err)}`,\n ),\n );\n }\n }\n\n // Memory consolidation (in-process via amem-core)\n if (isMemoryInitialized()) {\n const memSpinner = p.spinner();\n memSpinner.start(\"Consolidating memory\");\n try {\n const report = memoryConsolidate();\n memSpinner.stop(\"Memory consolidated\");\n if (report.merged > 0 || report.pruned > 0 || report.promoted > 0) {\n p.log.info(\n `Memory health: ${report.healthScore ?? \"?\"}% ` +\n pc.dim(`(merged ${report.merged}, pruned ${report.pruned}, promoted ${report.promoted})`),\n );\n }\n } catch {\n memSpinner.stop(\"Memory consolidation skipped\");\n }\n }\n\n // Start MCP servers\n const mcpManager = new McpManager();\n\n const mcpSpinner = p.spinner();\n mcpSpinner.start(\"Connecting to MCP servers\");\n\n // Core MCP servers (always connect) + custom servers — all in parallel\n const connections: Promise<void>[] = [\n mcpManager.connect(\"aman\", \"npx\", [\"-y\", \"@aman_asmuei/aman-mcp\"]),\n ];\n if (config.mcpServers) {\n for (const [name, serverConfig] of Object.entries(config.mcpServers)) {\n if (name === \"aman\" || name === \"amem\") continue;\n connections.push(mcpManager.connect(name, serverConfig.command, serverConfig.args, serverConfig.env));\n }\n }\n await Promise.all(connections);\n\n const mcpTools = mcpManager.getTools();\n\n mcpSpinner.stop(\"MCP connected\");\n\n if (mcpTools.length > 0) {\n p.log.success(`${mcpTools.length} MCP tools available`);\n } else {\n p.log.info(\n \"No MCP tools connected (install aman-mcp for tool support)\",\n );\n }\n\n // Convert ToolDef[] to ToolDefinition[] for the LLM\n const toolDefs = mcpTools.map((t) => ({\n name: t.name,\n description: t.description,\n input_schema: t.input_schema,\n }));\n\n // Create LLM client\n const client = pickLLMClient(config, model);\n\n const userIdentity = loadUserIdentity();\n if (userIdentity) {\n p.log.success(`${pc.bold(aiName)} is ready for ${pc.bold(userIdentity.name)}. Model: ${pc.dim(model)}`);\n } else {\n p.log.success(`${pc.bold(aiName)} is ready. Model: ${pc.dim(model)}`);\n }\n\n // Run the agent\n await runAgent(\n client,\n systemPrompt,\n aiName,\n model,\n toolDefs.length > 0 ? toolDefs : undefined,\n toolDefs.length > 0 ? mcpManager : undefined,\n config.hooks,\n );\n\n // Cleanup on exit\n await mcpManager.disconnect();\n });\n\nprogram\n .command(\"init\")\n .description(\"Set up your AI companion with a guided wizard\")\n .action(async () => {\n p.intro(pc.bold(\"aman agent init\") + pc.dim(\" — set up your companion\"));\n\n const name = (await p.text({\n message: \"What should your companion be called?\",\n placeholder: \"Aman\",\n defaultValue: \"Aman\",\n })) as string;\n if (p.isCancel(name)) process.exit(0);\n\n const preset = (await p.select({\n message: \"What kind of companion do you need?\",\n options: [\n { value: \"coding\", label: \"Coding Partner\", hint: \"direct, technical, concise\" },\n { value: \"creative\", label: \"Creative Collaborator\", hint: \"warm, imaginative\" },\n { value: \"assistant\", label: \"Personal Assistant\", hint: \"organized, action-oriented\" },\n { value: \"learning\", label: \"Learning Buddy\", hint: \"patient, Socratic\" },\n { value: \"minimal\", label: \"Minimal\", hint: \"just chat, I'll customize later\" },\n ],\n initialValue: \"coding\",\n })) as PresetName;\n if (p.isCancel(preset)) process.exit(0);\n\n const result = applyPreset(preset, name || \"Aman\");\n\n fs.mkdirSync(identityDir(), { recursive: true });\n fs.writeFileSync(path.join(identityDir(), \"core.md\"), result.coreMd, \"utf-8\");\n p.log.success(`Identity created — ${PRESETS[preset].identity.personality.split(\".\")[0].toLowerCase()}`);\n\n if (result.rulesMd) {\n fs.mkdirSync(rulesDir(), { recursive: true });\n fs.writeFileSync(path.join(rulesDir(), \"rules.md\"), result.rulesMd, \"utf-8\");\n const ruleCount = (result.rulesMd.match(/^- /gm) || []).length;\n p.log.success(`${ruleCount} rules set`);\n }\n\n if (result.flowMd) {\n fs.mkdirSync(workflowsDir(), { recursive: true });\n fs.writeFileSync(path.join(workflowsDir(), \"flow.md\"), result.flowMd, \"utf-8\");\n const wfCount = (result.flowMd.match(/^## /gm) || []).length;\n p.log.success(`${wfCount} workflow${wfCount > 1 ? \"s\" : \"\"} added`);\n }\n\n // Detect if running via npx (temp install)\n const isNpx = process.argv[1]?.includes(\"_npx\") || !process.argv[1]?.includes(\"node_modules/.bin\");\n\n p.outro(\"Your companion is ready.\");\n\n console.log(\"\");\n if (isNpx) {\n console.log(` ${pc.bold(\"Start chatting:\")} npx @aman_asmuei/aman-agent`);\n console.log(\"\");\n console.log(` ${pc.dim(\"Tip: Install globally to use\")} ${pc.bold(\"aman-agent\")} ${pc.dim(\"directly:\")}`);\n console.log(` ${pc.dim(\" npm install -g @aman_asmuei/aman-agent\")}`);\n } else {\n console.log(` ${pc.bold(\"Start chatting:\")} aman-agent`);\n }\n console.log(\"\");\n console.log(` ${pc.dim(\"Add tools:\")} npx @aman_asmuei/akit add github`);\n console.log(` ${pc.dim(\"Browse:\")} npx @aman_asmuei/akit search <query>`);\n console.log(\"\");\n });\n\nprogram\n .command(\"serve\")\n .description(\"Run aman-agent as a local MCP server other agents can delegate to\")\n .requiredOption(\"--name <name>\", \"Unique handle for @-mention (e.g. 'coder')\")\n .option(\"--profile <profile>\", \"Which profile to load\", \"default\")\n .action(async (opts) => {\n try {\n await runServe({ name: opts.name, profile: opts.profile });\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.error(pc.red(`aman-agent serve failed: ${msg}`));\n process.exit(1);\n }\n });\n\nprogram\n .command(\"dev [path]\")\n .description(\"Set up project context and launch your editor (Claude Code, Copilot, or Cursor)\")\n .option(\"--smart\", \"Use LLM to synthesize context file\")\n .option(\"--no-launch\", \"Generate context file only, don't launch editor\")\n .option(\"--force\", \"Regenerate even if context file is fresh\")\n .option(\"--diff\", \"Show what would change without writing\")\n .option(\"--yolo\", \"Launch with skip-permissions (Claude Code only)\")\n .option(\"--copilot\", \"Target GitHub Copilot (writes .github/copilot-instructions.md, opens VS Code)\")\n .option(\"--cursor\", \"Target Cursor editor (writes .cursorrules, opens Cursor)\")\n .action(async (projectPath: string | undefined, opts: Record<string, boolean>) => {\n const { runDev } = await import(\"./dev/dev-command.js\");\n const { scanStack } = await import(\"./dev/stack-detector.js\");\n const { EDITOR_TARGETS } = await import(\"./dev/claude-md-writer.js\");\n\n // Determine editor target\n const editorName = opts.copilot ? \"copilot\" as const : opts.cursor ? \"cursor\" as const : \"claude\" as const;\n const target = EDITOR_TARGETS[editorName];\n\n const targetPath = projectPath ?? process.cwd();\n const stack = scanStack(targetPath);\n\n // Print detection\n const stackParts = stack.languages.map((l: string) => l.charAt(0).toUpperCase() + l.slice(1));\n if (stack.frameworks.length > 0) {\n stackParts.push(`(${stack.frameworks.map((f: string) => f.charAt(0).toUpperCase() + f.slice(1)).join(\", \")})`);\n }\n if (stack.databases.length > 0) {\n stackParts.push(...stack.databases.map((d: string) => d.charAt(0).toUpperCase() + d.slice(1)));\n }\n if (stack.infra.length > 0) {\n stackParts.push(...stack.infra.map((i: string) => i.charAt(0).toUpperCase() + i.slice(1)));\n }\n\n if (stack.languages.length > 0) {\n console.log(`\\n ${pc.cyan(\"Detected:\")} ${stackParts.join(\" + \")}`);\n } else {\n console.log(`\\n ${pc.dim(\"No stack detected — generating minimal context\")}`);\n }\n\n const result = await runDev(targetPath, {\n smart: opts.smart,\n noLaunch: opts.launch === false,\n force: opts.force,\n diff: opts.diff,\n editor: editorName,\n }, stack);\n\n if (!result.success) {\n console.error(` ${pc.red(\"Error:\")} ${result.error}`);\n process.exit(1);\n }\n\n if (result.diff) {\n console.log(`\\n${result.diff}`);\n return;\n }\n\n if (result.generated) {\n const mode = opts.smart ? \"smart\" : \"template\";\n const memCount = result.context?.metadata.memoriesUsed ?? 0;\n console.log(` ${pc.cyan(\"Recalled:\")} ${memCount} memories`);\n console.log(` ${pc.green(\"✓\")} ${target.contextFile} written (${mode} mode)\\n`);\n } else if (result.skippedReason === \"fresh\") {\n console.log(` ${pc.green(\"✓\")} ${target.contextFile} is up to date\\n`);\n }\n\n // Launch editor\n if (opts.launch !== false && !opts.diff) {\n const { execFileSync } = await import(\"node:child_process\");\n try {\n execFileSync(\"which\", [target.launchCmd], { stdio: \"ignore\" });\n } catch {\n console.log(` ${pc.yellow(`${target.displayName} not found.`)} Ensure '${target.launchCmd}' is in your PATH.`);\n process.exit(1);\n }\n const launchArgs = [...target.launchArgs];\n if (opts.yolo && target.yoloArgs) {\n launchArgs.push(...target.yoloArgs);\n console.log(` ${pc.cyan(`Launching ${target.displayName}`)} ${pc.yellow(\"(skip-permissions)\")}...\\n`);\n } else {\n console.log(` ${pc.cyan(`Launching ${target.displayName}...`)}\\n`);\n }\n execFileSync(target.launchCmd, launchArgs, { cwd: targetPath, stdio: \"inherit\" });\n }\n });\n\nprogram\n .command(\"setup\")\n .description(\"Run the full configuration wizard (provider, identity, presets)\")\n .action(async () => {\n p.intro(pc.bold(\"aman agent setup\") + pc.dim(\" — full configuration wizard\"));\n\n // Create .reconfig marker to force interactive provider selection on next run\n const reconfigPath = path.join(homeDir(), \".reconfig\");\n fs.mkdirSync(homeDir(), { recursive: true });\n fs.writeFileSync(reconfigPath, \"\", \"utf-8\");\n\n p.log.info(\"Configuration reset. Restart aman-agent to complete setup.\");\n });\n\nprogram\n .command(\"update\")\n .description(\"Update aman-agent to the latest version\")\n .action(async () => {\n const { execFileSync } = await import(\"node:child_process\");\n const isVendored = process.execPath.includes(path.join(\".aman-agent\", \"node\"));\n\n if (isVendored) {\n const npmPath = path.join(homeDir(), \"node\", \"bin\", \"npm\");\n console.log(\"Updating aman-agent...\");\n try {\n execFileSync(npmPath, [\"install\", \"-g\", \"@aman_asmuei/aman-agent@latest\"], {\n stdio: \"inherit\",\n env: { ...process.env, PREFIX: homeDir() },\n });\n console.log(\"✓ Updated successfully.\");\n } catch {\n console.error(\"Update failed. Try manually: npm install -g @aman_asmuei/aman-agent@latest\");\n process.exit(1);\n }\n } else {\n console.log(\"Updating via npm...\");\n try {\n execFileSync(\"npm\", [\"install\", \"-g\", \"@aman_asmuei/aman-agent@latest\"], {\n stdio: \"inherit\",\n });\n console.log(\"✓ Updated successfully.\");\n } catch {\n console.error(\"Update failed. Try manually: npm install -g @aman_asmuei/aman-agent@latest\");\n process.exit(1);\n }\n }\n });\n\nprogram\n .command(\"uninstall\")\n .description(\"Remove aman-agent and all its data\")\n .action(async () => {\n const home = homeDir();\n\n if (!process.stdin.isTTY) {\n fs.rmSync(home, { recursive: true, force: true });\n console.log(\"✓ Removed \" + home);\n return;\n }\n\n const confirm = await p.confirm({\n message: `This will delete ${home} and all your data (memory, identity, config). Continue?`,\n });\n if (!confirm || p.isCancel(confirm)) {\n console.log(\"Cancelled.\");\n return;\n }\n\n fs.rmSync(home, { recursive: true, force: true });\n console.log(\"✓ Removed \" + home);\n console.log(\"\");\n console.log(\"To complete uninstall, remove the PATH line from your shell config:\");\n console.log(' Remove: export PATH=\"$HOME/.aman-agent/bin:$PATH\"');\n });\n\nprogram.parse();\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport os from \"node:os\";\n\nexport interface HooksConfig {\n memoryRecall?: boolean;\n sessionResume?: boolean;\n rulesCheck?: boolean;\n workflowSuggest?: boolean;\n evalPrompt?: boolean;\n autoSessionSave?: boolean;\n extractMemories?: boolean;\n featureHints?: boolean;\n personalityAdapt?: boolean;\n recordObservations?: boolean;\n autoPostmortem?: boolean;\n}\n\nconst DEFAULT_HOOKS: HooksConfig = {\n memoryRecall: true,\n sessionResume: true,\n rulesCheck: true,\n workflowSuggest: true,\n evalPrompt: true,\n autoSessionSave: true,\n extractMemories: true,\n featureHints: true,\n personalityAdapt: true,\n};\n\nexport interface MirrorConfig {\n enabled?: boolean;\n dir?: string;\n tiers?: Array<\"core\" | \"working\" | \"archival\">;\n autoSyncOnStartup?: boolean;\n}\n\nconst DEFAULT_MIRROR: Required<MirrorConfig> = {\n enabled: true,\n dir: \"\", // populated in loadConfig via homeDir() — empty string is a sentinel\n tiers: [\"core\", \"working\", \"archival\"],\n autoSyncOnStartup: true,\n};\n\n/**\n * Expand a leading `~/` or bare `~` in a path to the user's home directory.\n * Narrow contract: only expands `~` or `~/...`; `~alice/...` is returned as-is.\n */\nexport function expandHome(p: string): string {\n if (p.startsWith(\"~/\") || p === \"~\") {\n return path.join(os.homedir(), p.slice(1));\n }\n return p;\n}\n\nexport interface McpServerEntry {\n command: string;\n args: string[];\n env?: Record<string, string>;\n}\n\nexport interface MemoryConfig {\n maxStaleDays?: number;\n minConfidence?: number;\n minAccessCount?: number;\n maxRecallTokens?: number;\n}\n\nexport interface AgentConfig {\n provider: \"anthropic\" | \"openai\" | \"ollama\" | \"claude-code\" | \"copilot\";\n apiKey: string;\n model: string;\n ollamaUrl?: string;\n maxOutputTokens?: number;\n hooks?: HooksConfig;\n mcpServers?: Record<string, McpServerEntry>;\n memory?: MemoryConfig;\n mirror?: MirrorConfig;\n orchestrator?: {\n maxParallelTasks?: number;\n defaultTier?: \"fast\" | \"standard\" | \"advanced\";\n requireApprovalForPhaseTransition?: boolean;\n taskTimeoutMs?: number;\n orchestrationTimeoutMs?: number;\n };\n github?: {\n defaultRepo?: string; // owner/repo format\n defaultBranch?: string; // default: \"main\"\n autoCreatePR?: boolean; // auto-create PR after orchestration\n ciGateEnabled?: boolean; // wait for CI before merging\n };\n}\n\n/**\n * Resolve the aman-agent home directory.\n * Priority: $AMAN_HOME > $AMAN_AGENT_HOME > ~/.aman-agent\n *\n * Previously `configDir()` was the sole entry point and only checked\n * `AMAN_AGENT_HOME`. Now `homeDir()` is canonical, and `configDir()`\n * delegates to it. Recorded as feedback memory\n * `feedback_aman_agent_hermetic_tests.md`.\n */\nexport function homeDir(): string {\n return process.env.AMAN_HOME || process.env.AMAN_AGENT_HOME || path.join(os.homedir(), \".aman-agent\");\n}\n\nexport function identityDir(): string { return path.join(homeDir(), \"identity\"); }\nexport function rulesDir(): string { return path.join(homeDir(), \"rules\"); }\nexport function memoryDir(): string { return path.join(homeDir(), \"memory\"); }\nexport function workflowsDir(): string { return path.join(homeDir(), \"workflows\"); }\nexport function skillsDir(): string { return path.join(homeDir(), \"skills\"); }\nexport function evalDir(): string { return path.join(homeDir(), \"eval\"); }\n\nfunction configDir(): string {\n return homeDir();\n}\n\nfunction configPath(): string {\n return path.join(configDir(), \"config.json\");\n}\n\nexport function loadConfig(): AgentConfig | null {\n const p = configPath();\n if (!fs.existsSync(p)) return null;\n try {\n const raw = JSON.parse(fs.readFileSync(p, \"utf-8\")) as AgentConfig;\n raw.hooks = { ...DEFAULT_HOOKS, ...raw.hooks };\n raw.mirror = {\n ...DEFAULT_MIRROR,\n dir: path.join(homeDir(), \"memories\"),\n ...(raw.mirror ?? {}),\n };\n raw.mirror.dir = expandHome(raw.mirror.dir as string);\n return raw;\n } catch {\n return null;\n }\n}\n\nexport function saveConfig(config: AgentConfig): void {\n fs.mkdirSync(configDir(), { recursive: true });\n fs.writeFileSync(\n configPath(),\n JSON.stringify(config, null, 2) + \"\\n\",\n \"utf-8\",\n );\n}\n\nexport function configExists(): boolean {\n return fs.existsSync(configPath());\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport os from \"node:os\";\nimport { homeDir } from \"./config.js\";\n\ninterface MigrationResult {\n migrated: string[];\n}\n\nconst MIGRATION_MAP: Array<{ oldName: string; newSubdir: string }> = [\n { oldName: \".acore\", newSubdir: \"identity\" },\n { oldName: \".arules\", newSubdir: \"rules\" },\n { oldName: \".aflow\", newSubdir: \"workflows\" },\n { oldName: \".askill\", newSubdir: \"skills\" },\n { oldName: \".amem\", newSubdir: \"memory\" },\n { oldName: \".aeval\", newSubdir: \"eval\" },\n];\n\n/**\n * Migrate old scattered dot-directories into the consolidated ~/.aman-agent/ layout.\n * Safe: skips if new directory already has content, idempotent.\n */\nexport function migrateIfNeeded(): MigrationResult {\n const home = os.homedir();\n const target = homeDir();\n const migrated: string[] = [];\n\n for (const { oldName, newSubdir } of MIGRATION_MAP) {\n const oldDir = path.join(home, oldName);\n const newDir = path.join(target, newSubdir);\n\n if (!fs.existsSync(oldDir)) continue;\n if (fs.existsSync(newDir) && fs.readdirSync(newDir).length > 0) continue;\n\n fs.mkdirSync(newDir, { recursive: true });\n for (const entry of fs.readdirSync(oldDir)) {\n fs.renameSync(path.join(oldDir, entry), path.join(newDir, entry));\n }\n\n fs.rmSync(oldDir, { recursive: true, force: true });\n migrated.push(newSubdir);\n }\n\n return { migrated };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport os from \"node:os\";\nimport { estimateTokens, buildBudgetedPrompt } from \"./token-budget.js\";\nimport type { PromptComponent } from \"./token-budget.js\";\nimport { loadUserIdentity, formatUserContext } from \"./user-identity.js\";\n\ninterface EcosystemFile {\n name: string;\n dir: string;\n file: string;\n profileOverridable?: boolean; // can be overridden by profile-specific file\n}\n\nconst ECOSYSTEM_FILES: EcosystemFile[] = [\n { name: \"identity\", dir: \".acore\", file: \"core.md\", profileOverridable: true },\n { name: \"tools\", dir: \".akit\", file: \"kit.md\" },\n { name: \"workflows\", dir: \".aflow\", file: \"flow.md\" },\n { name: \"guardrails\", dir: \".arules\", file: \"rules.md\", profileOverridable: true },\n { name: \"skills\", dir: \".askill\", file: \"skills.md\", profileOverridable: true },\n];\n\n/**\n * Resolve the file path for an ecosystem layer, checking profile override first.\n */\nfunction resolveLayerPath(entry: EcosystemFile, home: string, profile?: string): string | null {\n // Check profile-specific override first\n if (profile && entry.profileOverridable) {\n const profilePath = path.join(home, \".acore\", \"profiles\", profile, entry.file);\n if (fs.existsSync(profilePath)) return profilePath;\n\n // For rules/skills, also check profile dir with original filename\n if (entry.name === \"guardrails\") {\n const altPath = path.join(home, \".acore\", \"profiles\", profile, \"rules.md\");\n if (fs.existsSync(altPath)) return altPath;\n }\n if (entry.name === \"skills\") {\n const altPath = path.join(home, \".acore\", \"profiles\", profile, \"skills.md\");\n if (fs.existsSync(altPath)) return altPath;\n }\n }\n\n // Fall back to global path\n const globalPath = path.join(home, entry.dir, entry.file);\n if (fs.existsSync(globalPath)) return globalPath;\n\n return null;\n}\n\nexport function assembleSystemPrompt(\n maxTokens?: number,\n profile?: string,\n): {\n prompt: string;\n layers: string[];\n truncated: string[];\n totalTokens: number;\n profile?: string;\n} {\n const home = os.homedir();\n const components: PromptComponent[] = [];\n\n for (const entry of ECOSYSTEM_FILES) {\n const filePath = resolveLayerPath(entry, home, profile);\n if (filePath) {\n const content = fs.readFileSync(filePath, \"utf-8\").trim();\n components.push({\n name: entry.name,\n content,\n tokens: estimateTokens(content),\n });\n }\n }\n\n // Project context (not prioritized — appended as extra)\n const contextPath = path.join(process.cwd(), \".acore\", \"context.md\");\n if (fs.existsSync(contextPath)) {\n const content = fs.readFileSync(contextPath, \"utf-8\").trim();\n components.push({\n name: \"context\",\n content,\n tokens: estimateTokens(content),\n });\n }\n\n // User identity — always included if available (high priority, low token cost)\n const userIdentity = loadUserIdentity();\n if (userIdentity) {\n const userContent = formatUserContext(userIdentity);\n components.push({\n name: \"user\",\n content: userContent,\n tokens: estimateTokens(userContent),\n });\n }\n\n const budgeted = buildBudgetedPrompt(components, maxTokens);\n\n return {\n prompt: budgeted.prompt,\n layers: budgeted.included,\n truncated: budgeted.truncated,\n totalTokens: budgeted.totalTokens,\n profile,\n };\n}\n\n/**\n * List available profiles.\n */\nexport function listProfiles(): Array<{ name: string; aiName: string; personality: string }> {\n const profilesDir = path.join(os.homedir(), \".acore\", \"profiles\");\n if (!fs.existsSync(profilesDir)) return [];\n\n const profiles: Array<{ name: string; aiName: string; personality: string }> = [];\n for (const entry of fs.readdirSync(profilesDir, { withFileTypes: true })) {\n if (!entry.isDirectory()) continue;\n const corePath = path.join(profilesDir, entry.name, \"core.md\");\n if (!fs.existsSync(corePath)) continue;\n\n const content = fs.readFileSync(corePath, \"utf-8\");\n const nameMatch = content.match(/^# (.+)/m);\n const personalityMatch = content.match(/- Personality:\\s*(.+)/);\n\n profiles.push({\n name: entry.name,\n aiName: nameMatch?.[1]?.trim() || entry.name,\n personality: personalityMatch?.[1]?.trim() || \"default\",\n });\n }\n\n return profiles;\n}\n\n/**\n * Get the AI name for a profile (or default).\n */\nexport function getProfileAiName(profile?: string): string {\n const home = os.homedir();\n let corePath: string;\n\n if (profile) {\n const profileCorePath = path.join(home, \".acore\", \"profiles\", profile, \"core.md\");\n corePath = fs.existsSync(profileCorePath) ? profileCorePath : path.join(home, \".acore\", \"core.md\");\n } else {\n corePath = path.join(home, \".acore\", \"core.md\");\n }\n\n if (!fs.existsSync(corePath)) return \"Assistant\";\n const content = fs.readFileSync(corePath, \"utf-8\");\n const match = content.match(/^# (.+)$/m);\n return match?.[1]?.trim() || \"Assistant\";\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { identityDir } from \"./config.js\";\n\nexport interface UserIdentity {\n name: string;\n role: \"developer\" | \"designer\" | \"student\" | \"manager\" | \"generalist\";\n roleLabel: string;\n expertise: \"beginner\" | \"intermediate\" | \"advanced\" | \"expert\";\n expertiseLabel: string;\n style: \"concise\" | \"balanced\" | \"thorough\" | \"socratic\";\n styleLabel: string;\n workingOn?: string;\n notes?: string;\n createdAt: string;\n updatedAt: string;\n}\n\nconst USER_FILE = path.join(identityDir(), \"user.md\");\n\n/**\n * Check if user identity exists.\n */\nexport function hasUserIdentity(): boolean {\n return fs.existsSync(USER_FILE);\n}\n\n/**\n * Load user identity from ~/.acore/user.md.\n * Returns null if file doesn't exist or is malformed.\n */\nexport function loadUserIdentity(): UserIdentity | null {\n if (!fs.existsSync(USER_FILE)) return null;\n\n try {\n const content = fs.readFileSync(USER_FILE, \"utf-8\");\n\n const get = (key: string): string => {\n const match = content.match(new RegExp(`^- ${key}:\\\\s*(.+)$`, \"m\"));\n return match?.[1]?.trim() ?? \"\";\n };\n\n const getSection = (heading: string): string => {\n const pattern = new RegExp(`## ${heading}\\\\n([\\\\s\\\\S]*?)(?=\\\\n## |$)`);\n const match = content.match(pattern);\n if (!match) return \"\";\n // Strip leading \"- Key: value\" lines, return freeform text\n return match[1]\n .split(\"\\n\")\n .filter((line) => !line.startsWith(\"- \") && line.trim().length > 0)\n .join(\"\\n\")\n .trim();\n };\n\n const name = get(\"Name\");\n if (!name) return null;\n\n return {\n name,\n role: (get(\"Role\") || \"generalist\") as UserIdentity[\"role\"],\n roleLabel: get(\"Role Label\") || get(\"Role\") || \"Generalist\",\n expertise: (get(\"Expertise\") || \"intermediate\") as UserIdentity[\"expertise\"],\n expertiseLabel: get(\"Expertise Label\") || get(\"Expertise\") || \"Intermediate\",\n style: (get(\"Style\") || \"balanced\") as UserIdentity[\"style\"],\n styleLabel: get(\"Style Label\") || get(\"Style\") || \"Balanced\",\n workingOn: getSection(\"Working On\") || undefined,\n notes: getSection(\"Notes\") || undefined,\n createdAt: get(\"Created\") || new Date().toISOString().split(\"T\")[0],\n updatedAt: get(\"Updated\") || new Date().toISOString().split(\"T\")[0],\n };\n } catch {\n return null;\n }\n}\n\n/**\n * Save user identity to ~/.acore/user.md.\n */\nexport function saveUserIdentity(user: UserIdentity): void {\n const dir = path.dirname(USER_FILE);\n if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });\n\n const lines: string[] = [\n \"# User Profile\",\n \"\",\n \"## About\",\n `- Name: ${user.name}`,\n `- Role: ${user.role}`,\n `- Role Label: ${user.roleLabel}`,\n `- Expertise: ${user.expertise}`,\n `- Expertise Label: ${user.expertiseLabel}`,\n `- Style: ${user.style}`,\n `- Style Label: ${user.styleLabel}`,\n ];\n\n if (user.workingOn) {\n lines.push(\"\", \"## Working On\", user.workingOn);\n }\n\n if (user.notes) {\n lines.push(\"\", \"## Notes\", user.notes);\n }\n\n lines.push(\n \"\",\n \"## Meta\",\n `- Created: ${user.createdAt}`,\n `- Updated: ${user.updatedAt}`,\n );\n\n fs.writeFileSync(USER_FILE, lines.join(\"\\n\") + \"\\n\", \"utf-8\");\n}\n\n/**\n * Format user identity for injection into system prompt.\n */\nexport function formatUserContext(user: UserIdentity): string {\n const parts: string[] = [\n `<user-profile>`,\n `The person you're talking to:`,\n `- Name: ${user.name}`,\n `- Role: ${user.roleLabel}`,\n `- Expertise: ${user.expertiseLabel}`,\n ];\n\n // Style instructions\n switch (user.style) {\n case \"concise\":\n parts.push(\"- Prefers: short, direct answers. Code first, explain after. No fluff.\");\n break;\n case \"balanced\":\n parts.push(\"- Prefers: explain the reasoning briefly, then show the solution.\");\n break;\n case \"thorough\":\n parts.push(\"- Prefers: detailed explanations with context. Help them understand deeply.\");\n break;\n case \"socratic\":\n parts.push(\"- Prefers: ask guiding questions. Help them figure it out themselves.\");\n break;\n }\n\n // Expertise calibration\n switch (user.expertise) {\n case \"beginner\":\n parts.push(\"- Calibration: explain concepts clearly, define terms, show examples. Be patient.\");\n break;\n case \"intermediate\":\n parts.push(\"- Calibration: skip basic explanations, focus on the task. Explain non-obvious things.\");\n break;\n case \"advanced\":\n parts.push(\"- Calibration: be direct. Skip explanations unless asked. Focus on edge cases and trade-offs.\");\n break;\n case \"expert\":\n parts.push(\"- Calibration: peer-level discussion. Challenge assumptions. Focus on architecture and nuance.\");\n break;\n }\n\n if (user.workingOn) {\n parts.push(`- Currently working on: ${user.workingOn}`);\n }\n\n if (user.notes) {\n parts.push(`- Notes: ${user.notes}`);\n }\n\n parts.push(\n \"\",\n `Use their name naturally (not every message). Adapt to their level and style.`,\n `</user-profile>`,\n );\n\n return parts.join(\"\\n\");\n}\n","import Anthropic from \"@anthropic-ai/sdk\";\nimport type {\n LLMClient,\n Message,\n StreamChunk,\n ToolDefinition,\n ChatResponse,\n ChatOptions,\n ContentBlock,\n} from \"./types.js\";\n\nfunction toAnthropicMessages(\n messages: Message[],\n): Anthropic.Messages.MessageParam[] {\n return messages.map((m) => {\n if (typeof m.content === \"string\") {\n return { role: m.role, content: m.content };\n }\n // Complex content blocks (text, image, tool_use, tool_result)\n return {\n role: m.role,\n content: m.content.map((block) => {\n if (block.type === \"text\") {\n return { type: \"text\" as const, text: block.text };\n }\n if (block.type === \"image\") {\n return {\n type: \"image\" as const,\n source: {\n type: \"base64\" as const,\n media_type: block.source.media_type,\n data: block.source.data,\n },\n };\n }\n if (block.type === \"tool_use\") {\n return {\n type: \"tool_use\" as const,\n id: block.id,\n name: block.name,\n input: block.input,\n };\n }\n if (block.type === \"tool_result\") {\n return {\n type: \"tool_result\" as const,\n tool_use_id: block.tool_use_id,\n content: block.content,\n };\n }\n return { type: \"text\" as const, text: \"\" };\n }),\n };\n });\n}\n\nexport function createAnthropicClient(\n apiKey: string,\n model: string,\n): LLMClient {\n const client = new Anthropic({ apiKey });\n\n return {\n async chat(\n systemPrompt: string,\n messages: Message[],\n onChunk: (chunk: StreamChunk) => void,\n tools?: ToolDefinition[],\n options?: ChatOptions,\n ): Promise<ChatResponse> {\n const anthropicMessages = toAnthropicMessages(messages);\n const hasTools = tools && tools.length > 0;\n\n try {\n let fullText = \"\";\n const toolUseBlocks: Array<{\n id: string;\n name: string;\n inputJson: string;\n }> = [];\n let currentBlockType: \"text\" | \"tool_use\" | null = null;\n let currentBlockIndex = -1;\n\n const createParams: Record<string, unknown> = {\n model,\n max_tokens: options?.maxOutputTokens ?? 8192,\n system: systemPrompt,\n messages: anthropicMessages,\n stream: true,\n };\n\n if (hasTools) {\n createParams.tools = tools.map((t) => ({\n name: t.name,\n description: t.description,\n input_schema:\n t.input_schema as Anthropic.Messages.Tool[\"input_schema\"],\n }));\n }\n\n const stream = await client.messages.create(\n createParams as unknown as Anthropic.Messages.MessageCreateParamsStreaming,\n );\n\n for await (const event of stream) {\n if (event.type === \"content_block_start\") {\n currentBlockIndex = event.index;\n if (event.content_block.type === \"text\") {\n currentBlockType = \"text\";\n } else if (event.content_block.type === \"tool_use\") {\n currentBlockType = \"tool_use\";\n toolUseBlocks.push({\n id: event.content_block.id,\n name: event.content_block.name,\n inputJson: \"\",\n });\n }\n } else if (event.type === \"content_block_delta\") {\n if (\n currentBlockType === \"text\" &&\n event.delta.type === \"text_delta\"\n ) {\n const text = event.delta.text;\n fullText += text;\n onChunk({ type: \"text\", text });\n } else if (\n currentBlockType === \"tool_use\" &&\n event.delta.type === \"input_json_delta\"\n ) {\n const lastTool = toolUseBlocks[toolUseBlocks.length - 1];\n if (lastTool) {\n lastTool.inputJson += event.delta.partial_json;\n }\n }\n } else if (event.type === \"content_block_stop\") {\n currentBlockType = null;\n }\n }\n\n // Parse tool inputs from accumulated JSON\n const toolUses = toolUseBlocks.map((block) => ({\n id: block.id,\n name: block.name,\n input: (block.inputJson\n ? JSON.parse(block.inputJson)\n : {}) as Record<string, unknown>,\n }));\n\n // Signal done\n onChunk({ type: \"done\" });\n\n // Build content blocks for the message\n if (toolUses.length > 0) {\n const contentBlocks: ContentBlock[] = [];\n if (fullText) {\n contentBlocks.push({ type: \"text\" as const, text: fullText });\n }\n for (const tu of toolUses) {\n contentBlocks.push({\n type: \"tool_use\" as const,\n id: tu.id,\n name: tu.name,\n input: tu.input,\n });\n }\n return {\n message: { role: \"assistant\", content: contentBlocks },\n toolUses,\n };\n }\n\n return {\n message: { role: \"assistant\", content: fullText },\n toolUses: [],\n };\n } catch (error) {\n if (error instanceof Anthropic.AuthenticationError) {\n throw new Error(\n \"Invalid API key. Run with --model flag or delete ~/.aman-agent/config.json to reconfigure.\",\n );\n }\n if (error instanceof Anthropic.RateLimitError) {\n throw new Error(\"Rate limited by Anthropic. Please wait and retry.\");\n }\n throw error;\n }\n },\n };\n}\n","import { spawn, execFileSync } from \"node:child_process\";\nimport type {\n LLMClient,\n Message,\n StreamChunk,\n ToolDefinition,\n ChatResponse,\n ChatOptions,\n ContentBlock,\n} from \"./types.js\";\n\n/**\n * Check if the `claude` CLI is installed and accessible.\n */\nexport function isClaudeCliInstalled(): boolean {\n try {\n execFileSync(\"which\", [\"claude\"], { stdio: \"ignore\" });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Check if the `claude` CLI is authenticated (has an active session).\n */\nexport function isClaudeCliAuthenticated(): boolean {\n try {\n const result = execFileSync(\"claude\", [\"--version\"], {\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n timeout: 5000,\n });\n return result.toString().trim().length > 0;\n } catch {\n return false;\n }\n}\n\nfunction extractText(content: string | ContentBlock[]): string {\n if (typeof content === \"string\") return content;\n return content\n .map((block) => {\n if (block.type === \"text\") return block.text;\n if (block.type === \"tool_result\")\n return `[Tool result for ${block.tool_use_id}]: ${block.content}`;\n if (block.type === \"tool_use\") return `[Used tool: ${block.name}]`;\n return \"\";\n })\n .filter(Boolean)\n .join(\"\\n\");\n}\n\n/**\n * Format conversation history into a single prompt for the CLI.\n * The claude CLI in print mode is single-turn, so we flatten the\n * multi-turn conversation into context.\n */\nfunction formatConversation(\n systemPrompt: string,\n messages: Message[],\n tools?: ToolDefinition[],\n): { prompt: string; systemPrompt: string } {\n const parts: string[] = [];\n\n // Include tool definitions in context if present\n let fullSystem = systemPrompt;\n if (tools && tools.length > 0) {\n fullSystem += \"\\n\\n## Available Tools\\n\";\n fullSystem +=\n \"You have access to the following tools. To use a tool, respond with a JSON block in this exact format:\\n\";\n fullSystem +=\n '```json\\n{\"tool_use\": {\"id\": \"call_1\", \"name\": \"tool_name\", \"input\": {…}}}\\n```\\n\\n';\n for (const tool of tools) {\n fullSystem += `### ${tool.name}\\n${tool.description}\\nParameters: ${JSON.stringify(tool.input_schema)}\\n\\n`;\n }\n fullSystem +=\n \"You may include multiple tool_use blocks. After each tool use, you will receive the result and can continue.\\n\";\n }\n\n // Build conversation history (skip system, it goes via --system-prompt)\n if (messages.length > 1) {\n parts.push(\"<conversation_history>\");\n for (let i = 0; i < messages.length - 1; i++) {\n const msg = messages[i];\n const role = msg.role === \"user\" ? \"User\" : \"Assistant\";\n const text = extractText(msg.content);\n parts.push(`[${role}]: ${text}`);\n }\n parts.push(\"</conversation_history>\\n\");\n }\n\n // Last message is the current user prompt\n const lastMsg = messages[messages.length - 1];\n if (lastMsg) {\n parts.push(extractText(lastMsg.content));\n }\n\n return { prompt: parts.join(\"\\n\"), systemPrompt: fullSystem };\n}\n\n/**\n * Parse tool_use JSON blocks from the assistant's text response.\n */\nfunction parseToolUses(\n text: string,\n): Array<{ id: string; name: string; input: Record<string, unknown> }> {\n const toolUses: Array<{\n id: string;\n name: string;\n input: Record<string, unknown>;\n }> = [];\n\n // Match ```json blocks containing tool_use\n const codeBlockRegex = /```json\\s*\\n?([\\s\\S]*?)```/g;\n let match;\n while ((match = codeBlockRegex.exec(text)) !== null) {\n try {\n const parsed = JSON.parse(match[1].trim());\n if (parsed.tool_use) {\n toolUses.push({\n id: parsed.tool_use.id || `call_${toolUses.length + 1}`,\n name: parsed.tool_use.name,\n input: parsed.tool_use.input || {},\n });\n }\n } catch {\n // Not valid JSON, skip\n }\n }\n\n // Also match inline {\"tool_use\": ...} patterns\n if (toolUses.length === 0) {\n const inlineRegex =\n /\\{\"tool_use\"\\s*:\\s*\\{[^}]*\"name\"\\s*:\\s*\"[^\"]+?\"[^}]*\\}\\s*\\}/g;\n while ((match = inlineRegex.exec(text)) !== null) {\n try {\n const parsed = JSON.parse(match[0]);\n if (parsed.tool_use) {\n toolUses.push({\n id: parsed.tool_use.id || `call_${toolUses.length + 1}`,\n name: parsed.tool_use.name,\n input: parsed.tool_use.input || {},\n });\n }\n } catch {\n // Not valid JSON, skip\n }\n }\n }\n\n return toolUses;\n}\n\nexport function createClaudeCodeClient(model?: string): LLMClient {\n return {\n async chat(\n systemPrompt: string,\n messages: Message[],\n onChunk: (chunk: StreamChunk) => void,\n tools?: ToolDefinition[],\n options?: ChatOptions,\n ): Promise<ChatResponse> {\n const { prompt, systemPrompt: fullSystem } = formatConversation(\n systemPrompt,\n messages,\n tools,\n );\n\n return new Promise((resolve, reject) => {\n const args = [\n \"--print\",\n \"--output-format\",\n \"stream-json\",\n \"--system-prompt\",\n fullSystem,\n ];\n\n if (model) {\n args.push(\"--model\", model);\n }\n\n if (options?.maxOutputTokens) {\n args.push(\"--max-tokens\", String(options.maxOutputTokens));\n }\n\n // Pass prompt via stdin to avoid shell escaping issues\n const proc = spawn(\"claude\", args, {\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n });\n\n let fullText = \"\";\n let buffer = \"\";\n let stderrOutput = \"\";\n\n proc.stdin.write(prompt);\n proc.stdin.end();\n\n proc.stdout.on(\"data\", (data: Buffer) => {\n buffer += data.toString();\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n if (!line.trim()) continue;\n try {\n const event = JSON.parse(line);\n\n // Handle different stream-json event formats\n if (event.type === \"assistant\") {\n if (event.subtype === \"text\" && event.content) {\n fullText += event.content;\n onChunk({ type: \"text\", text: event.content });\n }\n } else if (event.type === \"content_block_delta\") {\n if (event.delta?.type === \"text_delta\" && event.delta.text) {\n fullText += event.delta.text;\n onChunk({ type: \"text\", text: event.delta.text });\n }\n } else if (event.type === \"message\" && event.message?.content) {\n for (const block of event.message.content) {\n if (block.type === \"text\" && block.text) {\n fullText += block.text;\n onChunk({ type: \"text\", text: block.text });\n }\n }\n }\n // \"result\" type is final summary — skip to avoid duplication\n } catch {\n // Not JSON, treat as raw text\n if (line.trim()) {\n fullText += line;\n onChunk({ type: \"text\", text: line });\n }\n }\n }\n });\n\n proc.stderr.on(\"data\", (data: Buffer) => {\n stderrOutput += data.toString();\n });\n\n proc.on(\"close\", (code) => {\n // Process remaining buffer\n if (buffer.trim()) {\n try {\n const event = JSON.parse(buffer);\n if (\n event.type === \"assistant\" &&\n event.subtype === \"text\" &&\n event.content\n ) {\n fullText += event.content;\n onChunk({ type: \"text\", text: event.content });\n }\n } catch {\n if (buffer.trim()) {\n fullText += buffer;\n onChunk({ type: \"text\", text: buffer });\n }\n }\n }\n\n onChunk({ type: \"done\" });\n\n if (code !== 0 && !fullText) {\n reject(\n new Error(\n `Claude CLI exited with code ${code}${stderrOutput ? `: ${stderrOutput.trim()}` : \"\"}`,\n ),\n );\n return;\n }\n\n // Check for tool use in the response\n const hasTools = tools && tools.length > 0;\n if (hasTools) {\n const toolUses = parseToolUses(fullText);\n if (toolUses.length > 0) {\n // Strip the JSON tool_use blocks from the visible text\n let cleanText = fullText;\n const stripRegex =\n /```json\\s*\\n?\\s*\\{\"tool_use\"[\\s\\S]*?```/g;\n cleanText = cleanText.replace(stripRegex, \"\").trim();\n\n const contentBlocks: ContentBlock[] = [];\n if (cleanText) {\n contentBlocks.push({ type: \"text\", text: cleanText });\n }\n for (const tu of toolUses) {\n contentBlocks.push({\n type: \"tool_use\",\n id: tu.id,\n name: tu.name,\n input: tu.input,\n });\n }\n\n resolve({\n message: { role: \"assistant\", content: contentBlocks },\n toolUses,\n });\n return;\n }\n }\n\n resolve({\n message: { role: \"assistant\", content: fullText },\n toolUses: [],\n });\n });\n\n proc.on(\"error\", (err) => {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n reject(\n new Error(\n \"Claude CLI not found. Install it with: npm install -g @anthropic-ai/claude-code\",\n ),\n );\n } else {\n reject(err);\n }\n });\n });\n },\n };\n}\n","import { spawn, execFileSync } from \"node:child_process\";\nimport type {\n LLMClient,\n Message,\n StreamChunk,\n ToolDefinition,\n ChatResponse,\n ChatOptions,\n ContentBlock,\n} from \"./types.js\";\n\n/**\n * Check if the `copilot` CLI is installed.\n */\nexport function isCopilotCliInstalled(): boolean {\n try {\n execFileSync(\"which\", [\"copilot\"], { stdio: \"ignore\" });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Check if the `copilot` CLI is authenticated.\n */\nexport function isCopilotCliAuthenticated(): boolean {\n try {\n const result = execFileSync(\"copilot\", [\"--version\"], {\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n timeout: 5000,\n });\n return result.toString().trim().length > 0;\n } catch {\n return false;\n }\n}\n\nfunction extractText(content: string | ContentBlock[]): string {\n if (typeof content === \"string\") return content;\n return content\n .map((block) => {\n if (block.type === \"text\") return block.text;\n if (block.type === \"tool_result\")\n return `[Tool result for ${block.tool_use_id}]: ${block.content}`;\n if (block.type === \"tool_use\") return `[Used tool: ${block.name}]`;\n return \"\";\n })\n .filter(Boolean)\n .join(\"\\n\");\n}\n\n/**\n * Format conversation history into a single prompt for the CLI.\n * The copilot CLI in print mode is single-turn, so we flatten the\n * multi-turn conversation into context.\n */\nfunction formatConversation(\n systemPrompt: string,\n messages: Message[],\n tools?: ToolDefinition[],\n): { prompt: string; systemPrompt: string } {\n const parts: string[] = [];\n\n let fullSystem = systemPrompt;\n if (tools && tools.length > 0) {\n fullSystem += \"\\n\\n## Available Tools\\n\";\n fullSystem +=\n \"You have access to the following tools. To use a tool, respond with a JSON block in this exact format:\\n\";\n fullSystem +=\n '```json\\n{\"tool_use\": {\"id\": \"call_1\", \"name\": \"tool_name\", \"input\": {…}}}\\n```\\n\\n';\n for (const tool of tools) {\n fullSystem += `### ${tool.name}\\n${tool.description}\\nParameters: ${JSON.stringify(tool.input_schema)}\\n\\n`;\n }\n fullSystem +=\n \"You may include multiple tool_use blocks. After each tool use, you will receive the result and can continue.\\n\";\n }\n\n if (messages.length > 1) {\n parts.push(\"<conversation_history>\");\n for (let i = 0; i < messages.length - 1; i++) {\n const msg = messages[i];\n const role = msg.role === \"user\" ? \"User\" : \"Assistant\";\n const text = extractText(msg.content);\n parts.push(`[${role}]: ${text}`);\n }\n parts.push(\"</conversation_history>\\n\");\n }\n\n const lastMsg = messages[messages.length - 1];\n if (lastMsg) {\n parts.push(extractText(lastMsg.content));\n }\n\n return { prompt: parts.join(\"\\n\"), systemPrompt: fullSystem };\n}\n\n/**\n * Parse tool_use JSON blocks from the assistant's text response.\n */\nfunction parseToolUses(\n text: string,\n): Array<{ id: string; name: string; input: Record<string, unknown> }> {\n const toolUses: Array<{\n id: string;\n name: string;\n input: Record<string, unknown>;\n }> = [];\n\n const codeBlockRegex = /```json\\s*\\n?([\\s\\S]*?)```/g;\n let match;\n while ((match = codeBlockRegex.exec(text)) !== null) {\n try {\n const parsed = JSON.parse(match[1].trim());\n if (parsed.tool_use) {\n toolUses.push({\n id: parsed.tool_use.id || `call_${toolUses.length + 1}`,\n name: parsed.tool_use.name,\n input: parsed.tool_use.input || {},\n });\n }\n } catch {\n // Not valid JSON\n }\n }\n\n if (toolUses.length === 0) {\n const inlineRegex =\n /\\{\"tool_use\"\\s*:\\s*\\{[^}]*\"name\"\\s*:\\s*\"[^\"]+?\"[^}]*\\}\\s*\\}/g;\n while ((match = inlineRegex.exec(text)) !== null) {\n try {\n const parsed = JSON.parse(match[0]);\n if (parsed.tool_use) {\n toolUses.push({\n id: parsed.tool_use.id || `call_${toolUses.length + 1}`,\n name: parsed.tool_use.name,\n input: parsed.tool_use.input || {},\n });\n }\n } catch {\n // Not valid JSON\n }\n }\n }\n\n return toolUses;\n}\n\nexport function createCopilotClient(model?: string): LLMClient {\n return {\n async chat(\n systemPrompt: string,\n messages: Message[],\n onChunk: (chunk: StreamChunk) => void,\n tools?: ToolDefinition[],\n options?: ChatOptions,\n ): Promise<ChatResponse> {\n const { prompt, systemPrompt: fullSystem } = formatConversation(\n systemPrompt,\n messages,\n tools,\n );\n\n return new Promise((resolve, reject) => {\n // The GitHub Copilot CLI renamed its non-interactive flag from\n // --print (positional prompt) to --prompt <text>. The old form\n // was silently broken in v0.30 and earlier once Copilot shipped\n // the rename. Surfaced by an A2A round-trip smoke test on\n // 2026-04-11: `copilot --print` now errors with \"unknown option\n // '--print' (Did you mean --prompt?)\".\n const args = [\n \"--prompt\", prompt,\n \"--output-format\", \"json\",\n \"--silent\",\n \"--no-custom-instructions\",\n ];\n\n if (model) {\n args.push(\"--model\", model);\n }\n\n const proc = spawn(\"copilot\", args, {\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n env: {\n ...process.env,\n COPILOT_SYSTEM_PROMPT: fullSystem,\n },\n });\n\n let fullText = \"\";\n let buffer = \"\";\n let stderrOutput = \"\";\n\n proc.stdout.on(\"data\", (data: Buffer) => {\n buffer += data.toString();\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n if (!line.trim()) continue;\n try {\n const event = JSON.parse(line);\n\n // Handle JSONL output from copilot CLI\n if (event.type === \"assistant\" && event.content) {\n fullText += event.content;\n onChunk({ type: \"text\", text: event.content });\n } else if (event.type === \"message\" && event.message?.content) {\n for (const block of event.message.content) {\n if (block.type === \"text\" && block.text) {\n fullText += block.text;\n onChunk({ type: \"text\", text: block.text });\n }\n }\n } else if (event.type === \"content_block_delta\") {\n if (event.delta?.type === \"text_delta\" && event.delta.text) {\n fullText += event.delta.text;\n onChunk({ type: \"text\", text: event.delta.text });\n }\n } else if (event.role === \"assistant\" && event.content) {\n // Some formats return {role, content} directly\n const text =\n typeof event.content === \"string\"\n ? event.content\n : event.content\n .map((b: { text?: string }) => b.text || \"\")\n .join(\"\");\n if (text) {\n fullText += text;\n onChunk({ type: \"text\", text });\n }\n }\n // Skip \"result\" type to avoid duplication\n } catch {\n // Not JSON — treat as raw text\n if (line.trim()) {\n fullText += line;\n onChunk({ type: \"text\", text: line });\n }\n }\n }\n });\n\n proc.stderr.on(\"data\", (data: Buffer) => {\n stderrOutput += data.toString();\n });\n\n proc.on(\"close\", (code) => {\n // Process remaining buffer\n if (buffer.trim()) {\n try {\n const event = JSON.parse(buffer);\n if (event.type === \"assistant\" && event.content) {\n fullText += event.content;\n onChunk({ type: \"text\", text: event.content });\n } else if (\n event.role === \"assistant\" &&\n typeof event.content === \"string\"\n ) {\n fullText += event.content;\n onChunk({ type: \"text\", text: event.content });\n }\n } catch {\n if (buffer.trim()) {\n fullText += buffer;\n onChunk({ type: \"text\", text: buffer });\n }\n }\n }\n\n onChunk({ type: \"done\" });\n\n if (code !== 0 && !fullText) {\n reject(\n new Error(\n `Copilot CLI exited with code ${code}${stderrOutput ? `: ${stderrOutput.trim()}` : \"\"}`,\n ),\n );\n return;\n }\n\n // Check for tool use in the response\n const hasTools = tools && tools.length > 0;\n if (hasTools) {\n const toolUses = parseToolUses(fullText);\n if (toolUses.length > 0) {\n let cleanText = fullText;\n const stripRegex = /```json\\s*\\n?\\s*\\{\"tool_use\"[\\s\\S]*?```/g;\n cleanText = cleanText.replace(stripRegex, \"\").trim();\n\n const contentBlocks: ContentBlock[] = [];\n if (cleanText) {\n contentBlocks.push({ type: \"text\", text: cleanText });\n }\n for (const tu of toolUses) {\n contentBlocks.push({\n type: \"tool_use\",\n id: tu.id,\n name: tu.name,\n input: tu.input,\n });\n }\n\n resolve({\n message: { role: \"assistant\", content: contentBlocks },\n toolUses,\n });\n return;\n }\n }\n\n resolve({\n message: { role: \"assistant\", content: fullText },\n toolUses: [],\n });\n });\n\n proc.on(\"error\", (err) => {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n reject(\n new Error(\n \"Copilot CLI not found. Install it from: https://docs.github.com/copilot/how-tos/copilot-cli\",\n ),\n );\n } else {\n reject(err);\n }\n });\n });\n },\n };\n}\n","import OpenAI from \"openai\";\nimport type {\n LLMClient,\n Message,\n StreamChunk,\n ToolDefinition,\n ChatResponse,\n ChatOptions,\n} from \"./types.js\";\nimport { toOpenAICompatibleMessages } from \"./openai-compat.js\";\n\nexport function createOllamaClient(\n model: string,\n baseURL?: string,\n): LLMClient {\n const client = new OpenAI({\n baseURL: baseURL || \"http://localhost:11434/v1\",\n apiKey: \"ollama\", // Ollama doesn't require a real key\n });\n\n return {\n async chat(\n systemPrompt: string,\n messages: Message[],\n onChunk: (chunk: StreamChunk) => void,\n tools?: ToolDefinition[],\n options?: ChatOptions,\n ): Promise<ChatResponse> {\n const ollamaMessages = toOpenAICompatibleMessages(systemPrompt, messages);\n const hasTools = tools && tools.length > 0;\n\n try {\n let fullText = \"\";\n const toolCallAccumulators: Map<\n number,\n { id: string; name: string; arguments: string }\n > = new Map();\n\n const createParams: Record<string, unknown> = {\n model,\n max_tokens: options?.maxOutputTokens ?? 4096,\n messages: ollamaMessages,\n stream: true,\n };\n\n if (hasTools) {\n createParams.tools = tools.map((t) => ({\n type: \"function\" as const,\n function: {\n name: t.name,\n description: t.description,\n parameters: t.input_schema,\n },\n }));\n }\n\n const stream = await client.chat.completions.create(\n createParams as unknown as OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming,\n );\n\n for await (const chunk of stream) {\n const delta = chunk.choices[0]?.delta;\n if (!delta) continue;\n\n // Stream text content\n if (delta.content) {\n fullText += delta.content;\n onChunk({ type: \"text\", text: delta.content });\n }\n\n // Accumulate tool calls\n if (delta.tool_calls) {\n for (const tc of delta.tool_calls) {\n const idx = tc.index;\n let acc = toolCallAccumulators.get(idx);\n if (!acc) {\n acc = { id: \"\", name: \"\", arguments: \"\" };\n toolCallAccumulators.set(idx, acc);\n }\n if (tc.id) {\n acc.id = tc.id;\n }\n if (tc.function?.name) {\n acc.name = tc.function.name;\n }\n if (tc.function?.arguments) {\n acc.arguments += tc.function.arguments;\n }\n }\n }\n }\n\n // Parse accumulated tool calls\n const toolUses = Array.from(toolCallAccumulators.entries())\n .sort(([a], [b]) => a - b)\n .map(([, acc]) => ({\n id: acc.id,\n name: acc.name,\n input: JSON.parse(acc.arguments || \"{}\") as Record<\n string,\n unknown\n >,\n }));\n\n // Signal done\n onChunk({ type: \"done\" });\n\n // Build response\n if (toolUses.length > 0) {\n const contentBlocks = [\n ...(fullText\n ? [{ type: \"text\" as const, text: fullText }]\n : []),\n ...toolUses.map((tu) => ({\n type: \"tool_use\" as const,\n id: tu.id,\n name: tu.name,\n input: tu.input,\n })),\n ];\n return {\n message: { role: \"assistant\", content: contentBlocks },\n toolUses,\n };\n }\n\n return {\n message: { role: \"assistant\", content: fullText },\n toolUses: [],\n };\n } catch (error) {\n if (\n error instanceof Error &&\n error.message.includes(\"ECONNREFUSED\")\n ) {\n throw new Error(\n \"Cannot connect to Ollama. Make sure it's running: ollama serve\",\n );\n }\n throw error;\n }\n },\n };\n}\n","import type OpenAI from \"openai\";\nimport type { Message } from \"./types.js\";\n\n/**\n * Converts internal Message[] to OpenAI-compatible chat completion messages.\n * Shared by both the OpenAI and Ollama clients since they use the same format.\n */\nexport function toOpenAICompatibleMessages(\n systemPrompt: string,\n messages: Message[],\n): OpenAI.Chat.Completions.ChatCompletionMessageParam[] {\n const result: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [\n { role: \"system\", content: systemPrompt },\n ];\n\n for (const m of messages) {\n if (typeof m.content === \"string\") {\n result.push({\n role: m.role as \"user\" | \"assistant\",\n content: m.content,\n });\n } else if (m.role === \"assistant\") {\n // Assistant message with tool calls\n const textParts = m.content.filter((b) => b.type === \"text\");\n const toolUseParts = m.content.filter((b) => b.type === \"tool_use\");\n const text = textParts.map((b) => (\"text\" in b ? b.text : \"\")).join(\"\");\n\n if (toolUseParts.length > 0) {\n result.push({\n role: \"assistant\",\n content: text || null,\n tool_calls: toolUseParts.map((b) => ({\n id: \"id\" in b ? b.id : \"\",\n type: \"function\" as const,\n function: {\n name: \"name\" in b ? b.name : \"\",\n arguments: JSON.stringify(\"input\" in b ? b.input : {}),\n },\n })),\n });\n } else {\n result.push({ role: \"assistant\", content: text });\n }\n } else if (m.role === \"user\") {\n // Check if it contains tool results\n const toolResults = m.content.filter((b) => b.type === \"tool_result\");\n if (toolResults.length > 0) {\n for (const tr of toolResults) {\n if (tr.type === \"tool_result\") {\n result.push({\n role: \"tool\",\n tool_call_id: tr.tool_use_id,\n content: tr.content,\n });\n }\n }\n } else {\n // User message — may contain text + images\n const hasImages = m.content.some((b) => b.type === \"image\");\n if (hasImages) {\n const parts: Array<Record<string, unknown>> = [];\n for (const b of m.content) {\n if (b.type === \"text\") {\n parts.push({ type: \"text\", text: b.text });\n } else if (b.type === \"image\") {\n parts.push({\n type: \"image_url\",\n image_url: {\n url: `data:${b.source.media_type};base64,${b.source.data}`,\n },\n });\n }\n }\n result.push({ role: \"user\", content: parts as never });\n } else {\n const text = m.content\n .map((b) => (\"text\" in b ? b.text : \"\"))\n .join(\"\");\n result.push({ role: \"user\", content: text });\n }\n }\n }\n }\n\n return result;\n}\n","import OpenAI from \"openai\";\nimport type {\n LLMClient,\n Message,\n StreamChunk,\n ToolDefinition,\n ChatResponse,\n ChatOptions,\n} from \"./types.js\";\nimport { toOpenAICompatibleMessages } from \"./openai-compat.js\";\n\nexport function createOpenAIClient(apiKey: string, model: string): LLMClient {\n const client = new OpenAI({ apiKey });\n\n return {\n async chat(\n systemPrompt: string,\n messages: Message[],\n onChunk: (chunk: StreamChunk) => void,\n tools?: ToolDefinition[],\n options?: ChatOptions,\n ): Promise<ChatResponse> {\n const openaiMessages = toOpenAICompatibleMessages(systemPrompt, messages);\n const hasTools = tools && tools.length > 0;\n\n try {\n let fullText = \"\";\n const toolCallAccumulators: Map<\n number,\n { id: string; name: string; arguments: string }\n > = new Map();\n\n const createParams: Record<string, unknown> = {\n model,\n max_tokens: options?.maxOutputTokens ?? 8192,\n messages: openaiMessages,\n stream: true,\n };\n\n if (hasTools) {\n createParams.tools = tools.map((t) => ({\n type: \"function\" as const,\n function: {\n name: t.name,\n description: t.description,\n parameters: t.input_schema,\n },\n }));\n }\n\n const stream = await client.chat.completions.create(\n createParams as unknown as OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming,\n );\n\n for await (const chunk of stream) {\n const delta = chunk.choices[0]?.delta;\n if (!delta) continue;\n\n // Stream text content\n if (delta.content) {\n fullText += delta.content;\n onChunk({ type: \"text\", text: delta.content });\n }\n\n // Accumulate tool calls\n if (delta.tool_calls) {\n for (const tc of delta.tool_calls) {\n const idx = tc.index;\n let acc = toolCallAccumulators.get(idx);\n if (!acc) {\n acc = { id: \"\", name: \"\", arguments: \"\" };\n toolCallAccumulators.set(idx, acc);\n }\n if (tc.id) {\n acc.id = tc.id;\n }\n if (tc.function?.name) {\n acc.name = tc.function.name;\n }\n if (tc.function?.arguments) {\n acc.arguments += tc.function.arguments;\n }\n }\n }\n }\n\n // Parse accumulated tool calls\n const toolUses = Array.from(toolCallAccumulators.entries())\n .sort(([a], [b]) => a - b)\n .map(([, acc]) => ({\n id: acc.id,\n name: acc.name,\n input: JSON.parse(acc.arguments || \"{}\") as Record<\n string,\n unknown\n >,\n }));\n\n // Signal done\n onChunk({ type: \"done\" });\n\n // Build response\n if (toolUses.length > 0) {\n const contentBlocks = [\n ...(fullText\n ? [{ type: \"text\" as const, text: fullText }]\n : []),\n ...toolUses.map((tu) => ({\n type: \"tool_use\" as const,\n id: tu.id,\n name: tu.name,\n input: tu.input,\n })),\n ];\n return {\n message: { role: \"assistant\", content: contentBlocks },\n toolUses,\n };\n }\n\n return {\n message: { role: \"assistant\", content: fullText },\n toolUses: [],\n };\n } catch (error) {\n if (error instanceof OpenAI.AuthenticationError) {\n throw new Error(\n \"Invalid API key. Run with --model flag or delete ~/.aman-agent/config.json to reconfigure.\",\n );\n }\n if (error instanceof OpenAI.RateLimitError) {\n throw new Error(\"Rate limited by OpenAI. Please wait and retry.\");\n }\n throw error;\n }\n },\n };\n}\n","import type {\n ChatOptions,\n ChatResponse,\n LLMClient,\n Message,\n StreamChunk,\n ToolDefinition,\n} from \"./types.js\";\nimport { createAnthropicClient } from \"./anthropic.js\";\nimport { createClaudeCodeClient } from \"./claude-code.js\";\nimport { createCopilotClient } from \"./copilot.js\";\nimport { createOllamaClient } from \"./ollama.js\";\nimport { createOpenAIClient } from \"./openai.js\";\nimport type { AgentConfig } from \"../config.js\";\n\nexport type { LLMClient };\n\n/**\n * Factory for constructing an LLM client from the user's config.\n *\n * When `AMAN_AGENT_FAKE_LLM=1` is set, returns a deterministic stub client\n * that echoes the last user message and never calls tools. Used exclusively\n * by the A2A integration test so it can run in a hermetic CI environment\n * without network, real API keys, or spawning aman-mcp.\n */\nexport function pickLLMClient(config: AgentConfig, model: string): LLMClient {\n if (process.env.AMAN_AGENT_FAKE_LLM === \"1\") {\n return createFakeClient();\n }\n if (config.provider === \"claude-code\") return createClaudeCodeClient(model);\n if (config.provider === \"copilot\") return createCopilotClient(model);\n if (config.provider === \"anthropic\")\n return createAnthropicClient(config.apiKey, model);\n if (config.provider === \"ollama\") return createOllamaClient(model);\n return createOpenAIClient(config.apiKey, model);\n}\n\n/**\n * Deterministic stub LLM client for the A2A integration test.\n *\n * Echoes the last user message as plain text and never emits tool calls.\n * Must satisfy `LLMClient` exactly so `serve-command.ts` compiles against\n * the real type — do not loosen.\n */\nfunction createFakeClient(): LLMClient {\n return {\n async chat(\n _systemPrompt: string,\n messages: Message[],\n onChunk: (chunk: StreamChunk) => void,\n _tools?: ToolDefinition[],\n _options?: ChatOptions,\n ): Promise<ChatResponse> {\n const last = messages[messages.length - 1];\n const text =\n typeof last?.content === \"string\"\n ? last.content\n : \"[fake-llm] ok\";\n const reply = `[fake-llm] received: ${text}`;\n onChunk({ type: \"text\", text: reply });\n onChunk({ type: \"done\" });\n return {\n message: { role: \"assistant\", content: reply },\n toolUses: [],\n };\n },\n };\n}\n","import { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { StdioClientTransport } from \"@modelcontextprotocol/sdk/client/stdio.js\";\nimport { log } from \"../logger.js\";\nimport { withRetry } from \"../retry.js\";\n\ninterface McpConnection {\n name: string;\n client: Client;\n transport: StdioClientTransport;\n /** Original params stored for reconnect */\n connectParams: { command: string; args: string[]; env?: Record<string, string> };\n}\n\nexport interface ToolDef {\n name: string;\n description: string;\n input_schema: Record<string, unknown>;\n serverName: string;\n}\n\nconst TOOL_CALL_TIMEOUT_MS = 30_000;\n\nexport class McpManager {\n private connections: McpConnection[] = [];\n private tools: ToolDef[] = [];\n\n async connect(\n name: string,\n command: string,\n args: string[],\n env?: Record<string, string>,\n ): Promise<void> {\n try {\n const transport = new StdioClientTransport({\n command,\n args,\n stderr: \"pipe\",\n env: env ? env : undefined,\n });\n const client = new Client({\n name: `aman-agent-${name}`,\n version: \"0.1.0\",\n });\n await client.connect(transport);\n\n // Redirect stderr to debug log instead of terminal\n if (transport.stderr) {\n transport.stderr.on(\"data\", (chunk: Buffer) => {\n log.debug(\"mcp\", `[${name} stderr] ${chunk.toString().trim()}`);\n });\n }\n\n this.connections.push({ name, client, transport, connectParams: { command, args, env } });\n\n // List tools from this server\n const toolsResult = await client.listTools();\n for (const tool of toolsResult.tools) {\n // Fix 4: Warn on tool name collisions\n const existing = this.tools.find((t) => t.name === tool.name);\n if (existing) {\n log.warn(\n \"mcp\",\n `Warning: tool \"${tool.name}\" from server \"${name}\" shadows existing tool from \"${existing.serverName}\"`,\n );\n }\n\n this.tools.push({\n name: tool.name,\n description: tool.description || \"\",\n input_schema: tool.inputSchema as Record<string, unknown>,\n serverName: name,\n });\n }\n } catch (err) {\n log.error(\"mcp\", \"Failed to connect to \" + name + \" MCP server\", err);\n console.error(` Warning: Could not connect to ${name} MCP server`);\n }\n }\n\n getTools(): ToolDef[] {\n return this.tools;\n }\n\n async callTool(\n toolName: string,\n args: Record<string, unknown>,\n ): Promise<string> {\n const tool = this.tools.find((t) => t.name === toolName);\n if (!tool) return `Error: tool ${toolName} not found`;\n\n const conn = this.connections.find((c) => c.name === tool.serverName);\n if (!conn) return `Error: server ${tool.serverName} not connected`;\n\n const executeTool = async () => {\n const currentConn = this.connections.find((c) => c.name === tool.serverName);\n if (!currentConn) throw new Error(`Server ${tool.serverName} disconnected`);\n\n const result = await Promise.race([\n currentConn.client.callTool({ name: toolName, arguments: args }),\n new Promise<never>((_, reject) =>\n setTimeout(\n () => reject(new Error(`Tool ${toolName} timed out after 30s`)),\n TOOL_CALL_TIMEOUT_MS,\n ),\n ),\n ]);\n\n if (result.content && Array.isArray(result.content)) {\n return (result.content as Array<{ type: string; text?: string }>)\n .filter((c) => c.type === \"text\")\n .map((c) => c.text ?? \"\")\n .join(\"\\n\");\n }\n return JSON.stringify(result);\n };\n\n try {\n return await withRetry(executeTool, {\n maxAttempts: 2,\n baseDelay: 500,\n retryable: (err) => err.message.includes(\"ETIMEDOUT\") || err.message.includes(\"timeout\"),\n });\n } catch (error) {\n const errMsg = error instanceof Error ? error.message : String(error);\n // Detect connection failures and auto-reconnect once\n const isConnectionError = errMsg.includes(\"EPIPE\") || errMsg.includes(\"ECONNRESET\") ||\n errMsg.includes(\"channel closed\") || errMsg.includes(\"disconnected\") ||\n errMsg.includes(\"not connected\") || errMsg.includes(\"write after end\") ||\n errMsg.includes(\"socket hang up\") || errMsg.includes(\"spawn\");\n if (isConnectionError) {\n log.warn(\"mcp\", `Connection error for ${tool.serverName}, attempting reconnect: ${errMsg}`);\n try {\n await this.reconnect(tool.serverName);\n return await executeTool();\n } catch (reconnectErr) {\n return `Error calling ${toolName}: reconnect failed — ${reconnectErr instanceof Error ? reconnectErr.message : String(reconnectErr)}`;\n }\n }\n return `Error calling ${toolName}: ${errMsg}`;\n }\n }\n\n async reconnect(name: string): Promise<void> {\n const connIndex = this.connections.findIndex((c) => c.name === name);\n if (connIndex === -1) {\n log.error(\"mcp\", `Cannot reconnect: no connection found for \"${name}\"`);\n return;\n }\n\n const conn = this.connections[connIndex];\n const { command, args, env } = conn.connectParams;\n\n // Kill old connection\n try {\n await conn.client.close();\n } catch (err) {\n log.debug(\"mcp\", `Error closing old connection for ${name}`, err);\n }\n\n // Remove old connection and its tools\n this.connections.splice(connIndex, 1);\n this.tools = this.tools.filter((t) => t.serverName !== name);\n\n // Re-connect with same params\n await this.connect(name, command, args, env);\n }\n\n async disconnect(): Promise<void> {\n for (const conn of this.connections) {\n try {\n await conn.client.close();\n } catch (err) {\n log.debug(\"mcp\", \"Cleanup error disconnecting \" + conn.name, err);\n }\n }\n this.connections = [];\n this.tools = [];\n }\n}\n","export interface RetryOptions {\n maxAttempts: number;\n baseDelay: number;\n retryable: (err: Error) => boolean;\n}\n\nexport async function withRetry<T>(\n fn: () => Promise<T>,\n options: RetryOptions,\n): Promise<T> {\n const { maxAttempts, baseDelay, retryable } = options;\n let lastError: Error | undefined;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n try {\n return await fn();\n } catch (err) {\n lastError = err instanceof Error ? err : new Error(String(err));\n if (!retryable(lastError) || attempt === maxAttempts) {\n throw lastError;\n }\n const delay = baseDelay * Math.pow(2, attempt - 1) * (0.5 + Math.random() * 0.5);\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n }\n\n throw lastError;\n}\n","import * as readline from \"node:readline\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport os from \"node:os\";\nimport pc from \"picocolors\";\nimport { marked } from \"marked\";\nimport { markedTerminal } from \"marked-terminal\";\nimport logUpdate from \"log-update\";\nimport type {\n LLMClient,\n Message,\n ContentBlock,\n ToolDefinition,\n ToolResultBlock,\n ImageBlock,\n StreamChunk,\n} from \"./llm/types.js\";\nimport { handleCommand } from \"./commands.js\";\nimport type { McpManager } from \"./mcp/client.js\";\nimport {\n onSessionStart,\n onBeforeToolExec,\n onWorkflowMatch,\n onSessionEnd,\n getSessionStartTime,\n type HookContext,\n} from \"./hooks.js\";\nimport {\n computePersonality,\n syncPersonalityToCore,\n formatWellbeingNudge,\n shouldFireNudge,\n} from \"./personality.js\";\nimport type { HooksConfig } from \"./config.js\";\nimport { trimConversation } from \"./context-manager.js\";\nimport { log } from \"./logger.js\";\nimport { withRetry } from \"./retry.js\";\nimport { extractMemories as runExtraction, type ExtractorState } from \"./memory-extractor.js\";\nimport { memoryRecall, memoryLog, getMaxRecallTokens } from \"./memory.js\";\nimport { autoTriggerSkills, matchKnowledge } from \"./skill-engine.js\";\nimport { BackgroundTaskManager, shouldRunInBackground } from \"./background.js\";\nimport { getActivePlan, formatPlanForPrompt } from \"./plans.js\";\nimport { estimateTokens } from \"./token-budget.js\";\nimport { delegateTask } from \"./delegate.js\";\nimport { listProfiles } from \"./prompt.js\";\nimport { listTeams, loadTeam, runTeam, formatTeamResult } from \"./teams.js\";\nimport { humanizeError } from \"./errors.js\";\nimport { getHint, loadShownHints, saveShownHints, type HintState } from \"./hints.js\";\nimport {\n createObservationSession,\n recordEvent,\n flushEvents,\n detectTopicShift,\n cleanupOldObservations,\n type ObservationSession,\n} from \"./observation.js\";\n\n// markedTerminal() returns a MarkedExtension — types lag behind, cast is safe\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nmarked.use(markedTerminal() as any);\n\ninterface AgentRecallResult {\n text: string;\n tokenEstimate: number;\n}\n\nasync function recallForMessage(\n input: string,\n): Promise<AgentRecallResult | null> {\n try {\n const result = await memoryRecall(input, { limit: 5, compact: true });\n if (result.total === 0) {\n return null;\n }\n const tokenEstimate = result.tokenEstimate ?? Math.round(result.text.split(/\\s+/).filter(Boolean).length * 1.3);\n const MAX_MEMORY_TOKENS = getMaxRecallTokens();\n let memoryText = result.text;\n if (tokenEstimate > MAX_MEMORY_TOKENS) {\n // Truncate to fit within the token ceiling (rough char estimate: 1 token ≈ 4 chars)\n const maxChars = MAX_MEMORY_TOKENS * 4;\n memoryText = memoryText.slice(0, maxChars) + \"\\n[... memory truncated to fit token budget]\";\n log.debug(\"agent\", `memory recall truncated from ~${tokenEstimate} to ~${MAX_MEMORY_TOKENS} tokens`);\n }\n return {\n text: `\\n\\n<relevant-memories>\\n${memoryText}\\n</relevant-memories>`,\n tokenEstimate: Math.min(tokenEstimate, MAX_MEMORY_TOKENS),\n };\n } catch (err) {\n log.debug(\"agent\", \"memory recall failed\", err);\n return null;\n }\n}\n\n// Generate a session ID for conversation logging\nfunction generateSessionId(): string {\n const now = new Date();\n const pad = (n: number) => n.toString().padStart(2, \"0\");\n return `session-${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}`;\n}\n\nexport async function runAgent(\n client: LLMClient,\n systemPrompt: string,\n aiName: string,\n model: string,\n tools?: ToolDefinition[],\n mcpManager?: McpManager,\n hooksConfig?: HooksConfig,\n): Promise<void> {\n const messages: Message[] = [];\n const sessionId = generateSessionId();\n const extractorState: ExtractorState = { turnsSinceLastExtraction: 0, lastExtractionCount: 0 };\n const bgTasks = new BackgroundTaskManager();\n let abortController: AbortController | null = null;\n let isStreaming = false;\n let lastCheckpointTurn = 0;\n const CHECKPOINT_INTERVAL = 10; // auto-save every N user turns\n\n // Add virtual tools for delegation and teams\n const profiles = listProfiles();\n const teams = listTeams();\n if (tools && (profiles.length > 0 || teams.length > 0)) {\n const virtualTools: ToolDefinition[] = [];\n\n if (profiles.length > 0) {\n virtualTools.push({\n name: \"delegate_task\",\n description: `Delegate a task to a specialist sub-agent with a different profile. Available profiles: ${profiles.map((p) => `${p.name} (${p.personality})`).join(\", \")}. IMPORTANT: Always ask the user for permission before delegating.`,\n input_schema: {\n type: \"object\",\n properties: {\n profile: { type: \"string\", description: \"Profile name to delegate to\" },\n task: { type: \"string\", description: \"The task description for the sub-agent\" },\n },\n required: [\"profile\", \"task\"],\n },\n });\n }\n\n if (teams.length > 0) {\n virtualTools.push({\n name: \"team_run\",\n description: `Run a task with a named agent team. Available teams: ${teams.map((t) => `${t.name} (${t.workflow}: ${t.members.map((m) => m.profile).join(\"→\")})`).join(\", \")}. IMPORTANT: Always ask the user for permission before running a team.`,\n input_schema: {\n type: \"object\",\n properties: {\n team: { type: \"string\", description: \"Team name\" },\n task: { type: \"string\", description: \"The task for the team\" },\n },\n required: [\"team\", \"task\"],\n },\n });\n }\n\n tools = [...tools, ...virtualTools];\n }\n const hintState: HintState = {\n turnCount: 0,\n shownHints: loadShownHints(),\n hintShownThisSession: false,\n };\n\n const isRetryable = (err: Error) =>\n err.message.includes(\"Rate limit\") ||\n err.message.includes(\"rate limit\") ||\n err.message.includes(\"ECONNRESET\") ||\n err.message.includes(\"ETIMEDOUT\") ||\n err.message.includes(\"fetch failed\") ||\n err.message.includes(\"socket hang up\") ||\n err.message.includes(\"network socket disconnected\") ||\n err.message.includes(\"ENOTFOUND\") ||\n err.message.includes(\"EAI_AGAIN\");\n\n let responseBuffer = \"\";\n\n const onChunkHandler = (chunk: StreamChunk) => {\n if (chunk.type === \"text\" && chunk.text) {\n responseBuffer += chunk.text;\n if (process.stdout.isTTY) {\n logUpdate(responseBuffer);\n } else {\n process.stdout.write(chunk.text);\n }\n }\n if (chunk.type === \"done\") {\n if (process.stdout.isTTY && responseBuffer.trim()) {\n try {\n const rendered = marked(responseBuffer.trim()) as string;\n logUpdate(rendered);\n logUpdate.done();\n } catch {\n logUpdate.done();\n }\n } else {\n process.stdout.write(\"\\n\");\n }\n responseBuffer = \"\";\n }\n };\n\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n // Handle Ctrl+C gracefully — abort current stream or exit\n let sigintCount = 0;\n rl.on(\"SIGINT\", async () => {\n // If streaming, abort the current response instead of exiting\n if (isStreaming && abortController) {\n abortController.abort();\n sigintCount = 0;\n process.stdout.write(pc.yellow(\"\\n [response cancelled]\\n\"));\n return;\n }\n\n sigintCount++;\n // Double Ctrl+C to exit\n if (sigintCount < 2) {\n process.stdout.write(pc.dim(\"\\n Press Ctrl+C again to exit.\\n\"));\n setTimeout(() => { sigintCount = 0; }, 2000);\n return;\n }\n\n // Wait for background tasks before exiting\n if (bgTasks.pendingCount > 0) {\n await bgTasks.waitAll();\n bgTasks.displayCompleted();\n }\n if (observationSession) {\n await flushEvents(observationSession).catch(() => {});\n }\n if (mcpManager && hooksConfig) {\n try {\n const hookCtx: HookContext = { mcpManager, config: hooksConfig, llmClient: client };\n await onSessionEnd(hookCtx, messages, sessionId, observationSession);\n } catch (err) { log.debug(\"agent\", \"session end hook failed on SIGINT\", err); }\n }\n console.log(pc.dim(\"\\nGoodbye.\\n\"));\n rl.close();\n process.exit(0);\n });\n\n const prompt = (): Promise<string> => {\n return new Promise<string>((resolve) => {\n rl.question(pc.green(\"\\nYou > \"), (answer) => {\n resolve(answer);\n });\n });\n };\n\n console.log(\n `\\nType a message, ${pc.dim(\"/help\")} for commands, or ${pc.dim(\"/quit\")} to exit.\\n`,\n );\n\n if (mcpManager && hooksConfig) {\n const hookCtx: HookContext = { mcpManager, config: hooksConfig };\n try {\n const session = await onSessionStart(hookCtx);\n\n if (!session.firstRun) {\n if (session.resumeTopic) {\n console.log(pc.dim(` Welcome back. Last time we talked about ${session.resumeTopic}`));\n } else {\n console.log(pc.dim(\" Welcome back.\"));\n }\n }\n\n if (session.visibleReminders && session.visibleReminders.length > 0) {\n for (const reminder of session.visibleReminders) {\n console.log(pc.yellow(` Reminder: ${reminder}`));\n }\n }\n\n if (session.contextInjection) {\n messages.push({ role: \"user\", content: session.contextInjection });\n if (session.firstRun) {\n messages.push({ role: \"assistant\", content: \"acknowledged\" });\n } else {\n messages.push({ role: \"assistant\", content: \"I have context from our previous sessions. How can I help?\" });\n }\n }\n } catch (err) { log.warn(\"agent\", \"session start hook failed\", err); }\n }\n\n // Initialize observation session (passive session telemetry)\n let observationSession: ObservationSession | undefined;\n let prevSentiment: string | undefined;\n if (hooksConfig?.recordObservations !== false) {\n observationSession = createObservationSession(sessionId);\n // Cleanup old observation files (non-blocking, fire-and-forget)\n cleanupOldObservations().catch(() => {});\n }\n\n while (true) {\n // Check for completed background tasks — inject as proper tool results\n if (bgTasks.hasCompleted) {\n const completed = bgTasks.collectCompleted();\n const bgToolResults: ToolResultBlock[] = [];\n for (const task of completed) {\n const elapsed = ((Date.now() - task.startedAt) / 1000).toFixed(1);\n if (task.error) {\n process.stdout.write(pc.yellow(`\\n [${task.id}] ${task.toolName} failed after ${elapsed}s: ${task.error}\\n`));\n bgToolResults.push({\n type: \"tool_result\" as const,\n tool_use_id: task.toolUseId,\n content: `[Background] ${task.toolName} failed: ${task.error}`,\n is_error: true,\n });\n } else {\n process.stdout.write(pc.green(`\\n [${task.id}] ${task.toolName} completed in ${elapsed}s\\n`));\n const preview = (task.result || \"\").slice(0, 200);\n if (preview) {\n process.stdout.write(pc.dim(` ${preview}${(task.result || \"\").length > 200 ? \"...\" : \"\"}\\n`));\n }\n bgToolResults.push({\n type: \"tool_result\" as const,\n tool_use_id: task.toolUseId,\n content: `[Background] ${task.toolName} completed:\\n${task.result}`,\n });\n }\n }\n if (bgToolResults.length > 0) {\n messages.push({ role: \"user\", content: bgToolResults });\n }\n }\n\n const input = await prompt();\n if (!input.trim()) continue;\n\n // Handle slash commands\n const cmdResult = await handleCommand(input, {\n model,\n mcpManager,\n llmClient: client,\n tools,\n observationSession,\n messages,\n });\n if (cmdResult.handled) {\n if (cmdResult.quit) {\n if (observationSession) {\n await flushEvents(observationSession).catch(() => {});\n }\n if (mcpManager && hooksConfig) {\n try {\n const hookCtx: HookContext = { mcpManager, config: hooksConfig, llmClient: client };\n await onSessionEnd(hookCtx, messages, sessionId, observationSession);\n } catch (err) { log.debug(\"agent\", \"session end hook failed on quit\", err); }\n }\n console.log(pc.dim(\"\\nGoodbye.\\n\"));\n rl.close();\n return;\n }\n if (cmdResult.exportConversation) {\n try {\n const exportDir = path.join(os.homedir(), \".aman-agent\", \"exports\");\n fs.mkdirSync(exportDir, { recursive: true });\n const exportPath = path.join(exportDir, `${sessionId}.md`);\n\n const lines: string[] = [\n `# Conversation — ${new Date().toLocaleString()}`,\n `**Model:** ${model}`,\n \"\",\n \"---\",\n \"\",\n ];\n\n for (const msg of messages) {\n if (typeof msg.content === \"string\") {\n const label = msg.role === \"user\" ? \"**You:**\" : `**${aiName}:**`;\n lines.push(`${label} ${msg.content}`, \"\");\n }\n }\n\n fs.writeFileSync(exportPath, lines.join(\"\\n\"), \"utf-8\");\n console.log(pc.green(`Exported to ${exportPath}`));\n } catch {\n console.log(pc.red(\"Failed to export conversation.\"));\n }\n continue;\n }\n if (cmdResult.saveConversation) {\n try {\n await saveConversationToMemory(messages, sessionId);\n console.log(pc.green(\"Conversation saved to memory.\"));\n } catch {\n console.log(pc.red(\"Failed to save conversation.\"));\n }\n continue;\n }\n if (cmdResult.output) {\n console.log(cmdResult.output);\n }\n if (cmdResult.clearHistory) {\n messages.length = 0;\n }\n continue;\n }\n\n // Check for workflow match\n let activeSystemPrompt = systemPrompt;\n if (mcpManager && hooksConfig) {\n try {\n const hookCtx: HookContext = { mcpManager, config: hooksConfig };\n const wfMatch = await onWorkflowMatch(input, hookCtx);\n if (wfMatch) {\n const useIt = await new Promise<boolean>((resolve) => {\n rl.question(pc.dim(` Workflow \"${wfMatch.name}\" matches. Use it? (y/N) `), (answer) => resolve(answer.toLowerCase() === \"y\"));\n });\n if (useIt) {\n activeSystemPrompt = systemPrompt + `\\n\\n<active-workflow>\\n${wfMatch.steps}\\n</active-workflow>`;\n console.log(pc.dim(` Using \"${wfMatch.name}\" workflow.`));\n }\n }\n } catch (err) { log.debug(\"agent\", \"workflow match failed\", err); }\n }\n\n // Inject active plan into context\n const activePlan = getActivePlan();\n if (activePlan) {\n activeSystemPrompt += \"\\n\\n\" + formatPlanForPrompt(activePlan);\n }\n\n // Auto-trigger skills based on conversation context\n if (mcpManager) {\n try {\n const skillContext = await autoTriggerSkills(input, mcpManager);\n if (skillContext) {\n activeSystemPrompt += \"\\n\\n\" + skillContext;\n }\n } catch (err) { log.debug(\"agent\", \"skill auto-trigger failed\", err); }\n\n // Auto-suggest knowledge library items\n const knowledgeItem = matchKnowledge(input);\n if (knowledgeItem) {\n activeSystemPrompt += `\\n\\n<knowledge name=\"${knowledgeItem.name}\" category=\"${knowledgeItem.category}\">\n${knowledgeItem.description}\n\n${knowledgeItem.content}\n</knowledge>`;\n }\n }\n\n // Auto-trim conversation if approaching token limits\n await trimConversation(messages, client);\n\n // Detect and process file paths + image URLs in user input\n const textExts = new Set([\n \".txt\", \".md\", \".json\", \".js\", \".ts\", \".jsx\", \".tsx\", \".py\",\n \".html\", \".css\", \".yml\", \".yaml\", \".toml\", \".xml\", \".csv\",\n \".sh\", \".bash\", \".zsh\", \".env\", \".cfg\", \".ini\", \".log\",\n \".sql\", \".graphql\", \".rs\", \".go\", \".java\", \".rb\", \".php\",\n \".c\", \".cpp\", \".h\", \".swift\", \".kt\", \".r\", \".lua\",\n ]);\n const imageExts = new Set([\".png\", \".jpg\", \".jpeg\", \".gif\", \".webp\", \".bmp\"]);\n const docExts = new Set([\".docx\", \".doc\", \".pdf\", \".pptx\", \".ppt\", \".xlsx\", \".xls\", \".odt\", \".rtf\", \".epub\"]);\n const mimeMap: Record<string, ImageBlock[\"source\"][\"media_type\"]> = {\n \".png\": \"image/png\", \".jpg\": \"image/jpeg\", \".jpeg\": \"image/jpeg\",\n \".gif\": \"image/gif\", \".webp\": \"image/webp\", \".bmp\": \"image/png\",\n };\n const maxImageBytes = 20 * 1024 * 1024; // 20MB\n\n let textContent = input;\n const imageBlocks: ImageBlock[] = [];\n\n // Detect all local file paths\n const filePathMatches = [...input.matchAll(/(\\/[\\w./-]+|~\\/[\\w./-]+)/g)];\n for (const match of filePathMatches) {\n let filePath = match[1];\n if (filePath.startsWith(\"~/\")) {\n filePath = path.join(os.homedir(), filePath.slice(2));\n }\n if (!fs.existsSync(filePath) || !fs.statSync(filePath).isFile()) continue;\n\n const ext = path.extname(filePath).toLowerCase();\n\n if (imageExts.has(ext)) {\n // Image file — base64 encode\n try {\n const stat = fs.statSync(filePath);\n if (stat.size > maxImageBytes) {\n process.stdout.write(pc.yellow(` [skipped: ${path.basename(filePath)} — exceeds 20MB limit]\\n`));\n continue;\n }\n const data = fs.readFileSync(filePath).toString(\"base64\");\n const mediaType = mimeMap[ext] || \"image/png\";\n imageBlocks.push({\n type: \"image\",\n source: { type: \"base64\", media_type: mediaType, data },\n });\n process.stdout.write(pc.dim(` [attached image: ${path.basename(filePath)} (${(stat.size / 1024).toFixed(1)}KB)]\\n`));\n } catch {\n process.stdout.write(pc.dim(` [could not read image: ${filePath}]\\n`));\n }\n } else if (textExts.has(ext) || ext === \"\") {\n // Text file — inline as XML\n try {\n const content = fs.readFileSync(filePath, \"utf-8\");\n const maxChars = 50000;\n const trimmed = content.length > maxChars\n ? content.slice(0, maxChars) + `\\n\\n[... truncated, ${content.length - maxChars} chars remaining]`\n : content;\n textContent += `\\n\\n<file path=\"${filePath}\" size=\"${content.length} chars\">\\n${trimmed}\\n</file>`;\n process.stdout.write(pc.dim(` [attached: ${path.basename(filePath)} (${(content.length / 1024).toFixed(1)}KB)]\\n`));\n } catch {\n process.stdout.write(pc.dim(` [could not read: ${filePath}]\\n`));\n }\n } else if (docExts.has(ext)) {\n // Binary document — convert via MCP\n if (mcpManager) {\n try {\n process.stdout.write(pc.dim(` [converting: ${path.basename(filePath)}...]\\n`));\n const converted = await mcpManager.callTool(\"doc_convert\", { path: filePath });\n if (converted && !converted.startsWith(\"Error\") && !converted.includes(\"Could not convert\")) {\n textContent += `\\n\\n<file path=\"${filePath}\" format=\"${ext}\">\\n${converted.slice(0, 50000)}\\n</file>`;\n process.stdout.write(pc.dim(` [attached: ${path.basename(filePath)} (converted from ${ext})]\\n`));\n } else {\n textContent += `\\n\\n<file-error path=\"${filePath}\">\\n${converted}\\n</file-error>`;\n process.stdout.write(pc.yellow(` [conversion note: ${converted.split(\"\\n\")[0]}]\\n`));\n }\n } catch {\n process.stdout.write(pc.dim(` [could not convert: ${path.basename(filePath)}]\\n`));\n }\n } else {\n process.stdout.write(pc.yellow(` Binary file (${ext}) — install Docling for document support: pip install docling\\n`));\n }\n }\n }\n\n // Detect image URLs in user input\n const urlImageMatches = [...input.matchAll(/https?:\\/\\/\\S+\\.(?:png|jpg|jpeg|gif|webp)(?:\\?\\S*)?/gi)];\n for (const match of urlImageMatches) {\n const url = match[0];\n try {\n process.stdout.write(pc.dim(` [fetching image: ${url.slice(0, 60)}...]\\n`));\n const response = await fetch(url);\n if (!response.ok) {\n process.stdout.write(pc.yellow(` [could not fetch: HTTP ${response.status}]\\n`));\n continue;\n }\n const buffer = Buffer.from(await response.arrayBuffer());\n if (buffer.length > maxImageBytes) {\n process.stdout.write(pc.yellow(` [skipped: image URL exceeds 20MB limit]\\n`));\n continue;\n }\n const contentType = response.headers.get(\"content-type\") || \"\";\n let mediaType: ImageBlock[\"source\"][\"media_type\"] = \"image/png\";\n if (contentType.includes(\"jpeg\") || contentType.includes(\"jpg\")) mediaType = \"image/jpeg\";\n else if (contentType.includes(\"gif\")) mediaType = \"image/gif\";\n else if (contentType.includes(\"webp\")) mediaType = \"image/webp\";\n else if (contentType.includes(\"png\")) mediaType = \"image/png\";\n\n imageBlocks.push({\n type: \"image\",\n source: { type: \"base64\", media_type: mediaType, data: buffer.toString(\"base64\") },\n });\n process.stdout.write(pc.dim(` [attached image URL: (${(buffer.length / 1024).toFixed(1)}KB)]\\n`));\n } catch {\n process.stdout.write(pc.dim(` [could not fetch image: ${url}]\\n`));\n }\n }\n\n // Build user message: structured ContentBlock[] if images present, string otherwise\n if (imageBlocks.length > 0) {\n const blocks: ContentBlock[] = [\n { type: \"text\", text: textContent },\n ...imageBlocks,\n ];\n messages.push({ role: \"user\", content: blocks });\n } else {\n messages.push({ role: \"user\", content: textContent });\n }\n\n // Per-message memory recall\n let augmentedSystemPrompt = activeSystemPrompt;\n let memoryTokens = 0;\n {\n const recall = await recallForMessage(input);\n if (recall) {\n augmentedSystemPrompt = activeSystemPrompt + recall.text;\n memoryTokens = recall.tokenEstimate;\n }\n }\n\n // Personality refresh with sentiment (every 5 turns)\n const userTurnCount = messages.filter((m) => m.role === \"user\").length;\n if (mcpManager && hooksConfig?.personalityAdapt !== false && userTurnCount > 0 && userTurnCount % 5 === 0) {\n const hour = new Date().getHours();\n let period: string;\n if (hour < 6) period = \"late-night\";\n else if (hour < 12) period = \"morning\";\n else if (hour < 17) period = \"afternoon\";\n else if (hour < 21) period = \"evening\";\n else period = \"night\";\n\n // Collect recent user messages for sentiment analysis\n const recentUserMsgs = messages\n .filter((m) => m.role === \"user\" && typeof m.content === \"string\")\n .slice(-5)\n .map((m) => m.content as string);\n\n const sessionMinutes = Math.round((Date.now() - getSessionStartTime()) / 60000);\n const state = computePersonality({\n timePeriod: period,\n sessionMinutes,\n turnCount: userTurnCount,\n recentMessages: recentUserMsgs,\n });\n\n syncPersonalityToCore(state, mcpManager).catch(() => {});\n\n // Record sentiment shift observation\n if (observationSession && prevSentiment !== state.sentiment.dominant) {\n recordEvent(observationSession, {\n type: \"sentiment_shift\",\n summary: `${prevSentiment ?? \"neutral\"} → ${state.sentiment.dominant}`,\n data: { from: prevSentiment ?? \"neutral\", to: state.sentiment.dominant },\n });\n prevSentiment = state.sentiment.dominant;\n }\n\n // Record blocker observation on sustained frustration\n if (observationSession && state.sentiment.frustration > 0.6) {\n recordEvent(observationSession, {\n type: \"blocker\",\n summary: \"User expressing frustration\",\n data: { frustrationLevel: state.sentiment.frustration },\n });\n }\n\n // Detect topic shift based on recent vs prior user messages\n if (observationSession && recentUserMsgs.length >= 6) {\n const recent = recentUserMsgs.slice(-3);\n const previous = recentUserMsgs.slice(-6, -3);\n const shift = detectTopicShift(recent, previous);\n if (shift.shifted) {\n recordEvent(observationSession, {\n type: \"topic_shift\",\n summary: `Topics: ${shift.newTopics.join(\", \")}`,\n data: { newTopics: shift.newTopics },\n });\n }\n }\n\n const nudge = formatWellbeingNudge(state);\n if (nudge && state.wellbeingNudge) {\n // Adaptive nudge: check user model stats before firing\n let fireNudge = true;\n try {\n const { loadUserModel, computeProfile } = await import(\"./user-model.js\");\n const model = await loadUserModel();\n if (model && model.sessions.length >= 5) {\n const profile = computeProfile(model.sessions, model.sessions.length);\n fireNudge = shouldFireNudge(state.wellbeingNudge, profile);\n }\n } catch {\n // No model yet — always fire\n }\n if (fireNudge) {\n augmentedSystemPrompt += \"\\n\" + nudge;\n }\n }\n\n // Feed-forward v2: preemptive context from frustration correlations\n try {\n const { loadUserModel, computeProfile } = await import(\"./user-model.js\");\n const model = await loadUserModel();\n if (model && model.sessions.length >= 10) {\n const profile = computeProfile(model.sessions, model.sessions.length);\n const preemptive: string[] = [];\n\n // Late night + high correlation → extra gentle mode\n const hour = new Date().getHours();\n const isLate = hour >= 21 || hour < 6;\n if (isLate && profile.frustrationCorrelations.lateNight > 0.4) {\n preemptive.push(\n \"Based on past patterns, late-night sessions tend to increase frustration for this user. \" +\n \"Be extra concise, proactive about blockers, and gently suggest wrapping up if frustration rises.\"\n );\n }\n\n // Long session + high correlation → preemptive break suggestion\n const sessionMins = Math.round((Date.now() - getSessionStartTime()) / 60000);\n if (sessionMins > 60 && profile.frustrationCorrelations.longSessions > 0.4) {\n preemptive.push(\n \"This session is getting long and past patterns show long sessions correlate with frustration. \" +\n \"Proactively suggest natural breakpoints.\"\n );\n }\n\n if (preemptive.length > 0) {\n augmentedSystemPrompt += `\\n<feed-forward-v2>\\n${preemptive.join(\"\\n\")}\\n</feed-forward-v2>`;\n }\n }\n } catch {\n // No model — skip feed-forward v2\n }\n\n // Burnout predictor\n try {\n const { loadUserModel, predictBurnout } = await import(\"./user-model.js\");\n const model = await loadUserModel();\n if (model && model.sessions.length >= 5) {\n const sessionMins = Math.round((Date.now() - getSessionStartTime()) / 60000);\n const burnout = predictBurnout(model.sessions, {\n minutes: sessionMins,\n frustration: state.sentiment.frustration,\n timePeriod: period,\n });\n if (burnout.risk > 0.7) {\n const burnoutState = { ...state, wellbeingNudge: \"burnout-warning\" };\n const burnoutNudge = formatWellbeingNudge(burnoutState);\n if (burnoutNudge) {\n augmentedSystemPrompt += \"\\n\" + burnoutNudge;\n }\n }\n }\n } catch {\n // No model — skip\n }\n }\n\n // Cap augmented system prompt to prevent unbounded growth\n const MAX_SYSTEM_TOKENS = 16_000;\n const systemTokens = estimateTokens(augmentedSystemPrompt);\n if (systemTokens > MAX_SYSTEM_TOKENS) {\n // Trim from the end (memories, knowledge, skills are appended last)\n const maxChars = MAX_SYSTEM_TOKENS * 4; // ~4 chars per token\n augmentedSystemPrompt = augmentedSystemPrompt.slice(0, maxChars) + \"\\n[... system context truncated to fit token budget]\";\n log.debug(\"agent\", `system prompt trimmed from ~${systemTokens} to ~${MAX_SYSTEM_TOKENS} tokens`);\n }\n\n const divider = \"─\".repeat(Math.min(process.stdout.columns || 60, 60) - aiName.length - 2);\n process.stdout.write(`\\n ${pc.cyan(pc.bold(aiName))} ${pc.dim(divider)}\\n\\n`);\n\n try {\n abortController = new AbortController();\n isStreaming = true;\n let response = await withRetry(\n () => client.chat(augmentedSystemPrompt, messages, onChunkHandler, tools),\n { maxAttempts: 3, baseDelay: 1000, retryable: isRetryable },\n );\n isStreaming = false;\n\n // Add assistant message to history\n messages.push(response.message);\n\n // Agentic tool loop: execute tools until LLM stops requesting them\n const MAX_TOOL_TURNS = 20;\n let toolTurnCount = 0;\n while (response.toolUses.length > 0 && mcpManager) {\n toolTurnCount++;\n if (toolTurnCount > MAX_TOOL_TURNS) {\n messages.push({\n role: \"assistant\",\n content: \"Tool execution limit reached (20). Breaking to prevent infinite loop.\",\n });\n console.log(pc.yellow(\"\\n Tool execution limit reached (20). Breaking to prevent infinite loop.\"));\n break;\n }\n const toolResults: ToolResultBlock[] = await Promise.all(\n response.toolUses.map(async (toolUse) => {\n if (hooksConfig) {\n const hookCtx: HookContext = { mcpManager: mcpManager!, config: hooksConfig };\n const check = await onBeforeToolExec(toolUse.name, toolUse.input, hookCtx);\n if (!check.allow) {\n process.stdout.write(pc.red(` [BLOCKED: ${check.reason}]\\n`));\n return {\n type: \"tool_result\" as const,\n tool_use_id: toolUse.id,\n content: `BLOCKED by guardrail: ${check.reason}`,\n is_error: true,\n };\n }\n }\n\n // Handle delegate_task virtual tool\n if (toolUse.name === \"delegate_task\" && mcpManager) {\n const input = toolUse.input as { profile: string; task: string };\n // Confirmation: ask user before delegating\n const confirmed = await new Promise<boolean>((resolve) => {\n rl.question(\n pc.cyan(` Delegate to ${pc.bold(input.profile)}? `) + pc.dim(`\"${input.task.slice(0, 80)}${input.task.length > 80 ? \"...\" : \"\"}\" (y/N) `),\n (answer) => resolve(answer.toLowerCase() === \"y\"),\n );\n });\n if (!confirmed) {\n return {\n type: \"tool_result\" as const,\n tool_use_id: toolUse.id,\n content: \"User declined delegation.\",\n is_error: true,\n };\n }\n process.stdout.write(pc.dim(`\\n [delegating to ${input.profile}...]\\n\\n`));\n const result = await delegateTask(input.task, input.profile, client, mcpManager, { tools, hooksConfig });\n const output = result.success\n ? `[${input.profile}] completed:\\n\\n${result.response}`\n : `[${input.profile}] failed: ${result.error}`;\n return {\n type: \"tool_result\" as const,\n tool_use_id: toolUse.id,\n content: output,\n };\n }\n\n // Handle team_run virtual tool\n if (toolUse.name === \"team_run\" && mcpManager) {\n const input = toolUse.input as { team: string; task: string };\n // Confirmation: ask user before launching team\n const confirmed = await new Promise<boolean>((resolve) => {\n rl.question(\n pc.cyan(` Run team ${pc.bold(input.team)}? `) + pc.dim(`\"${input.task.slice(0, 80)}${input.task.length > 80 ? \"...\" : \"\"}\" (y/N) `),\n (answer) => resolve(answer.toLowerCase() === \"y\"),\n );\n });\n if (!confirmed) {\n return {\n type: \"tool_result\" as const,\n tool_use_id: toolUse.id,\n content: \"User declined team execution.\",\n is_error: true,\n };\n }\n const team = loadTeam(input.team);\n if (!team) {\n return {\n type: \"tool_result\" as const,\n tool_use_id: toolUse.id,\n content: `Team not found: ${input.team}`,\n is_error: true,\n };\n }\n const result = await runTeam(team, input.task, client, mcpManager, tools);\n return {\n type: \"tool_result\" as const,\n tool_use_id: toolUse.id,\n content: result.success\n ? formatTeamResult(result)\n : `Team execution failed: ${result.finalOutput}`,\n };\n }\n\n // Check if tool should run in background\n if (shouldRunInBackground(toolUse.name)) {\n const task = bgTasks.launch(toolUse.name, toolUse.id, mcpManager, toolUse.input);\n return {\n type: \"tool_result\" as const,\n tool_use_id: toolUse.id,\n content: `[${toolUse.name} launched in background (${task.id}). Results will appear when ready. Continue with other work.]`,\n };\n }\n\n process.stdout.write(pc.dim(` [using ${toolUse.name}...]\\n`));\n const toolStartMs = Date.now();\n let result: string;\n try {\n result = await mcpManager.callTool(toolUse.name, toolUse.input);\n } catch (toolErr) {\n const errMsg = toolErr instanceof Error ? toolErr.message : String(toolErr);\n if (observationSession) {\n recordEvent(observationSession, {\n type: \"tool_error\",\n summary: `${toolUse.name}: ${errMsg}`,\n data: { tool: toolUse.name, error: errMsg },\n });\n }\n throw toolErr;\n }\n\n // Record successful tool call observation\n if (observationSession) {\n const durationMs = Date.now() - toolStartMs;\n recordEvent(observationSession, {\n type: \"tool_call\",\n summary: `${toolUse.name} (${durationMs}ms)`,\n data: { tool: toolUse.name, durationMs, success: true },\n });\n\n // Detect file-modifying tools and record file_change events\n const FILE_TOOLS = new Set([\"file_write\", \"file_edit\", \"file_create\", \"file_delete\"]);\n if (FILE_TOOLS.has(toolUse.name)) {\n const filePath = (toolUse.input as Record<string, unknown>)?.path ?? \"unknown\";\n recordEvent(observationSession, {\n type: \"file_change\",\n summary: `${toolUse.name}: ${String(filePath)}`,\n data: { tool: toolUse.name, path: filePath },\n });\n }\n }\n\n // Log tool observation to memory (passive capture, fire-and-forget)\n const skipLogging = [\"memory_log\", \"memory_recall\", \"memory_context\", \"memory_detail\", \"reminder_check\"].includes(toolUse.name);\n if (!skipLogging) {\n try {\n memoryLog(sessionId, \"system\", `[tool:${toolUse.name}] input=${JSON.stringify(toolUse.input).slice(0, 500)} result=${result.slice(0, 500)}`);\n } catch {}\n }\n\n return {\n type: \"tool_result\" as const,\n tool_use_id: toolUse.id,\n content: result,\n };\n }),\n );\n\n // Add tool results as a user message\n messages.push({\n role: \"user\",\n content: toolResults,\n });\n\n // Trim conversation if tool results pushed us over token limits\n await trimConversation(messages, client);\n\n // Call LLM again with tool results\n abortController = new AbortController();\n isStreaming = true;\n response = await withRetry(\n () => client.chat(augmentedSystemPrompt, messages, onChunkHandler, tools),\n { maxAttempts: 3, baseDelay: 1000, retryable: isRetryable },\n );\n isStreaming = false;\n\n // Add assistant response to history\n messages.push(response.message);\n }\n\n // Response footer\n const footerParts: string[] = [];\n if (memoryTokens > 0) footerParts.push(`memories: ~${memoryTokens} tokens`);\n const footer = footerParts.length > 0 ? ` ${footerParts.join(\" | \")}` : \"\";\n const footerDivider = \"─\".repeat(Math.min(process.stdout.columns || 60, 60) - footer.length - 1);\n process.stdout.write(pc.dim(` ${footerDivider}${footer}\\n`));\n\n // Periodic session checkpoint (fire-and-forget — prevents data loss on crash)\n const currentTurn = messages.filter((m) => m.role === \"user\").length;\n if (hooksConfig?.autoSessionSave && currentTurn - lastCheckpointTurn >= CHECKPOINT_INTERVAL) {\n lastCheckpointTurn = currentTurn;\n saveConversationToMemory(messages, sessionId).catch(() => {});\n log.debug(\"agent\", `checkpoint saved at turn ${currentTurn}`);\n }\n\n // Periodic flush of buffered observation events (fire-and-forget)\n if (observationSession && observationSession.events.length >= 5) {\n flushEvents(observationSession).catch(() => {});\n }\n\n // Memory extraction (fire-and-forget — never blocks the prompt)\n if (hooksConfig?.extractMemories) {\n const assistantText = typeof response.message.content === \"string\"\n ? response.message.content\n : response.message.content\n .filter((b) => b.type === \"text\")\n .map((b) => (\"text\" in b ? b.text : \"\"))\n .join(\"\");\n\n if (assistantText) {\n runExtraction(\n input, assistantText, client, extractorState,\n ).then((count) => {\n if (count > 0) {\n process.stdout.write(pc.dim(` [${count} memory${count > 1 ? \"ies\" : \"\"} stored]\\n`));\n }\n }).catch(() => {});\n }\n } else {\n extractorState.turnsSinceLastExtraction++;\n }\n\n // Progressive hints\n if (hooksConfig?.featureHints) {\n hintState.turnCount++;\n const hasWorkflows = fs.existsSync(path.join(os.homedir(), \".aflow\", \"flow.md\"));\n const memoryCount = memoryTokens > 0 ? Math.floor(memoryTokens / 5) : 0;\n const hint = getHint(hintState, { hasWorkflows, memoryCount });\n if (hint) {\n process.stdout.write(pc.dim(` ${hint}\\n`));\n saveShownHints(hintState.shownHints);\n }\n }\n } catch (error) {\n isStreaming = false;\n // If aborted by user (Ctrl+C), just add partial response and continue\n if (abortController?.signal.aborted) {\n if (responseBuffer.trim()) {\n messages.push({ role: \"assistant\", content: responseBuffer.trim() });\n if (process.stdout.isTTY) {\n try { logUpdate(marked(responseBuffer.trim()) as string); logUpdate.done(); } catch { logUpdate.done(); }\n }\n responseBuffer = \"\";\n }\n continue;\n }\n const rawMessage = error instanceof Error ? error.message : \"Unknown error occurred\";\n const friendly = humanizeError(rawMessage);\n console.error(pc.red(`\\n ${friendly}`));\n // Don't remove the user message — keep for retry\n }\n }\n}\n\n// Save conversation messages to memory log\nasync function saveConversationToMemory(\n messages: Message[],\n sessionId: string,\n): Promise<void> {\n // Save last 50 messages\n const recentMessages = messages.slice(-50);\n\n for (const msg of recentMessages) {\n if (typeof msg.content !== \"string\") continue;\n try {\n memoryLog(sessionId, msg.role, msg.content.slice(0, 5000));\n } catch (err) {\n log.debug(\"agent\", \"memory_log write failed\", err);\n }\n }\n}\n","declare const __VERSION__: string;\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport os from \"node:os\";\nimport { execFileSync } from \"node:child_process\";\nimport pc from \"picocolors\";\nimport type { McpManager } from \"./mcp/client.js\";\nimport { getEcosystemStatus } from \"./layers/parsers.js\";\nimport { memoryContext, memoryRecall, memoryMultiRecall, memoryForget, memoryStats, memoryExport, memorySince, memorySearch, isMemoryInitialized, reminderSet, reminderList, reminderCheck, reminderComplete, memoryDoctor, memoryRepair, memoryConfig, memoryReflect, memoryConsolidate, memoryTier, memoryDetail, memoryRelate, memoryExpire, memoryVersions, memorySync, getMirrorEngine, syncFromMirrorDir } from \"./memory.js\";\nimport { expandHome } from \"./config.js\";\nimport { listProfiles } from \"./prompt.js\";\nimport { BUILT_IN_PROFILES, installProfileTemplate } from \"./profile-templates.js\";\nimport { loadUserIdentity, hasUserIdentity } from \"./user-identity.js\";\nimport { runOnboarding, editProfile } from \"./onboarding.js\";\nimport { loadShowcaseManifest, installShowcaseTemplate } from \"./showcase-bridge.js\";\nimport { readFile, listFiles } from \"./files.js\";\nimport { delegateTask, delegatePipeline } from \"./delegate.js\";\nimport { smartOrchestrate, createModelRouter } from \"./orchestrator/index.js\";\nimport { listAgents, findAgent } from \"./server/registry.js\";\nimport { StreamableHTTPClientTransport } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport {\n createTeam,\n loadTeam,\n listTeams,\n deleteTeam,\n runTeam,\n formatTeam,\n formatTeamResult,\n BUILT_IN_TEAMS,\n type Team,\n} from \"./teams.js\";\nimport {\n createPlan,\n getActivePlan,\n listPlans,\n loadPlan,\n markStepDone,\n markStepUndone,\n setActivePlan,\n formatPlan,\n} from \"./plans.js\";\nimport {\n type ObservationSession,\n recordEvent,\n getSessionStats,\n pauseObservation,\n resumeObservation,\n} from \"./observation.js\";\nimport {\n generatePostmortemReport,\n savePostmortem,\n listPostmortems,\n readPostmortem,\n analyzePostmortemRange,\n formatPostmortemMarkdown,\n} from \"./postmortem.js\";\nimport {\n ghAvailable,\n ghCurrentRepo,\n listPRs,\n fetchIssue,\n formatIssueAsRequirement,\n isCIPassing,\n} from \"./github/index.js\";\nimport {\n validateCandidate,\n writeSkillToFile,\n appendCrystallizationLog,\n loadSuggestionCounts,\n} from \"./crystallization.js\";\nimport {\n loadUserModel,\n defaultModelPath,\n computeProfile,\n predictBurnout,\n} from \"./user-model.js\";\nimport { loadTaskLog } from \"./background.js\";\n\n// ── aman engine layers (Phase 5: replace file IO + mcpWrite for identity/rules) ──\nimport {\n getIdentity as acoreGetIdentity,\n updateSection as acoreUpdateSection,\n updateDynamics as acoreUpdateDynamics,\n} from \"@aman_asmuei/acore-core\";\nimport {\n listRuleCategories as arulesListCategories,\n addRule as arulesAddRule,\n removeRule as arulesRemoveRule,\n toggleRuleAt as arulesToggleRule,\n checkAction as arulesCheckAction,\n} from \"@aman_asmuei/arules-core\";\n\n/**\n * Canonical scope for aman-agent's slash commands. The CLI runtime is\n * the dev's `dev:agent` surface — distinct from `dev:plugin` (Claude Code)\n * and `dev:default` (the legacy single-tenant catch-all).\n *\n * Override at runtime with $AMAN_AGENT_SCOPE if you want a different\n * default (e.g. `dev:work` vs `dev:personal`).\n */\nconst AGENT_SCOPE: string =\n process.env.AMAN_AGENT_SCOPE ?? \"dev:agent\";\n\nexport interface CommandResult {\n handled: boolean;\n output?: string;\n quit?: boolean;\n clearHistory?: boolean;\n saveConversation?: boolean;\n exportConversation?: boolean;\n}\n\nexport interface CommandContext {\n model?: string;\n mcpManager?: McpManager;\n llmClient?: import(\"./llm/types.js\").LLMClient;\n tools?: import(\"./llm/types.js\").ToolDefinition[];\n observationSession?: ObservationSession;\n messages?: import(\"./llm/types.js\").Message[];\n}\n\nfunction readEcosystemFile(filePath: string, label: string): string {\n if (!fs.existsSync(filePath)) {\n return pc.dim(`No ${label} file found at ${filePath}`);\n }\n return fs.readFileSync(filePath, \"utf-8\").trim();\n}\n\nfunction parseCommand(input: string): { base: string; action?: string; args: string[] } {\n const trimmed = input.trim();\n const parts = trimmed.split(/\\s+/);\n const base = parts[0].toLowerCase().replace(/^\\//, \"\");\n let action = parts.length > 1 ? parts[1].toLowerCase() : undefined;\n if (action === \"--help\" || action === \"-h\") action = \"help\";\n const args = parts.slice(2);\n return { base, action, args };\n}\n\n/**\n * Parse dot-notation key (e.g. \"consolidation.maxStaleDays\") into nested object.\n * Returns { consolidation: { maxStaleDays: val } } instead of { \"consolidation.maxStaleDays\": val }\n */\nfunction buildNestedUpdate(key: string, val: unknown): Record<string, unknown> {\n const parts = key.split(\".\");\n if (parts.length === 1) return { [key]: val };\n const result: Record<string, unknown> = {};\n let curr = result;\n for (let i = 0; i < parts.length - 1; i++) {\n curr[parts[i]] = {};\n curr = curr[parts[i]] as Record<string, unknown>;\n }\n curr[parts[parts.length - 1]] = val;\n return result;\n}\n\nasync function mcpWrite(\n ctx: CommandContext,\n layer: string,\n tool: string,\n args: Record<string, unknown>,\n): Promise<string> {\n if (!ctx.mcpManager) {\n return pc.red(`Cannot modify ${layer}: aman-mcp not connected. Start it with: npx @aman_asmuei/aman-mcp`);\n }\n const result = await ctx.mcpManager.callTool(tool, args);\n if (result.startsWith(\"Error\")) {\n return pc.red(result);\n }\n return pc.green(result);\n}\n\n// --- Layer Handlers ---\n\nasync function handleIdentityCommand(\n action: string | undefined,\n args: string[],\n _ctx: CommandContext,\n): Promise<CommandResult> {\n if (!action) {\n const identity = await acoreGetIdentity(AGENT_SCOPE);\n if (!identity) {\n return {\n handled: true,\n output: pc.dim(\n `No identity configured for ${AGENT_SCOPE}. Run: npx @aman_asmuei/acore`,\n ),\n };\n }\n return { handled: true, output: identity.content.trim() };\n }\n if (action === \"update\") {\n if (args.length === 0) {\n return {\n handled: true,\n output: pc.yellow(\n \"Usage: /identity update <section>\\nTip: describe changes in natural language and the AI will update via acore-core.\",\n ),\n };\n }\n const section = args[0];\n const content = args.slice(1).join(\" \");\n if (!content) {\n return {\n handled: true,\n output: pc.yellow(\n \"Usage: /identity update <section> <new content...>\\nExample: /identity update Personality Warm, curious, and direct.\",\n ),\n };\n }\n try {\n await acoreUpdateSection(section, content, AGENT_SCOPE);\n return { handled: true, output: pc.green(`Updated section: ${section}`) };\n } catch (err) {\n return {\n handled: true,\n output: pc.red(\n `Failed to update ${section}: ${\n err instanceof Error ? err.message : String(err)\n }`,\n ),\n };\n }\n }\n if (action === \"dynamics\") {\n // --json flag: raw JSON output\n if (args.includes(\"--json\")) {\n const model = await loadUserModel();\n if (!model) return { handled: true, output: pc.dim(\"No user model yet. Complete a few sessions first.\") };\n return { handled: true, output: JSON.stringify(model, null, 2) };\n }\n\n // --reset flag: delete model\n if (args.includes(\"--reset\")) {\n const modelPath = defaultModelPath();\n if (fs.existsSync(modelPath)) {\n fs.unlinkSync(modelPath);\n return { handled: true, output: pc.green(\"User model reset. Starting fresh.\") };\n }\n return { handled: true, output: pc.dim(\"No user model to reset.\") };\n }\n\n // key=val args: manual dynamics override (existing behavior)\n const updates: Record<string, string> = {};\n for (const arg of args) {\n const eq = arg.indexOf(\"=\");\n if (eq > 0) updates[arg.slice(0, eq)] = arg.slice(eq + 1);\n }\n if (Object.keys(updates).length > 0) {\n try {\n await acoreUpdateDynamics({\n energy: updates.energy,\n activeMode: updates.mode,\n currentRead: updates.read,\n }, AGENT_SCOPE);\n return { handled: true, output: `Dynamics updated: ${Object.entries(updates).map(([k, v]) => `${k}=${v}`).join(\", \")}` };\n } catch (err) {\n return { handled: true, output: pc.red(`Dynamics error: ${err instanceof Error ? err.message : String(err)}`) };\n }\n }\n\n // No args: show user model summary\n const model = await loadUserModel();\n if (!model) {\n return { handled: true, output: pc.dim(\"No user model yet. Complete a few sessions to start building your profile.\") };\n }\n\n const p = model.profile;\n const trustBar = \"█\".repeat(Math.round(p.trustScore * 10)) + \"░\".repeat(10 - Math.round(p.trustScore * 10));\n const frustBar = \"█\".repeat(Math.round(p.baselineFrustration * 10)) + \"░\".repeat(10 - Math.round(p.baselineFrustration * 10));\n\n const lines = [\n pc.bold(\" Dynamic User Model\"),\n \"\",\n ` ${pc.cyan(\"Trust\")} ${trustBar} ${(p.trustScore * 100).toFixed(0)}% ${p.trustTrajectory === \"ascending\" ? pc.green(\"↑\") : p.trustTrajectory === \"declining\" ? pc.red(\"↓\") : \"→\"}`,\n ` ${pc.cyan(\"Sessions\")} ${p.totalSessions} total (${model.sessions.length} in window)`,\n ` ${pc.cyan(\"Sentiment\")} ${frustBar} frustration baseline ${p.sentimentTrend === \"improving\" ? pc.green(\"improving\") : p.sentimentTrend === \"worsening\" ? pc.red(\"worsening\") : \"stable\"}`,\n \"\",\n ` ${pc.cyan(\"Preferred\")} ${p.preferredTimePeriod} (${Object.entries(p.energyDistribution).map(([k, v]) => `${k}: ${v}`).join(\", \")})`,\n ` ${pc.cyan(\"Avg session\")} ${p.avgSessionMinutes.toFixed(0)} min, ${p.avgTurnsPerSession.toFixed(0)} turns ${p.engagementTrend === \"increasing\" ? pc.green(\"↑\") : p.engagementTrend === \"decreasing\" ? pc.red(\"↓\") : \"→\"}`,\n ];\n\n // Frustration correlations (only show if enough data)\n if (p.totalSessions >= 10) {\n const corrs: string[] = [];\n if (Math.abs(p.frustrationCorrelations.toolErrors) > 0.3) {\n corrs.push(`tool errors (${p.frustrationCorrelations.toolErrors.toFixed(2)})`);\n }\n if (Math.abs(p.frustrationCorrelations.longSessions) > 0.3) {\n corrs.push(`long sessions (${p.frustrationCorrelations.longSessions.toFixed(2)})`);\n }\n if (Math.abs(p.frustrationCorrelations.lateNight) > 0.3) {\n corrs.push(`late night (${p.frustrationCorrelations.lateNight.toFixed(2)})`);\n }\n if (corrs.length > 0) {\n lines.push(` ${pc.cyan(\"Frustration\")} correlates with: ${corrs.join(\", \")}`);\n }\n }\n\n // Nudge stats\n const nudgeKeys = Object.keys(p.nudgeStats);\n if (nudgeKeys.length > 0) {\n lines.push(\"\");\n lines.push(` ${pc.cyan(\"Nudges\")} ${nudgeKeys.map(k => `${k}: ${p.nudgeStats[k].fired}×`).join(\", \")}`);\n }\n\n lines.push(\"\");\n lines.push(pc.dim(` Use --json for raw data, --reset to start fresh`));\n\n return { handled: true, output: lines.join(\"\\n\") };\n }\n if (action === \"summary\") {\n try {\n const identity = await acoreGetIdentity(AGENT_SCOPE);\n if (!identity) return { handled: true, output: pc.yellow(\"No identity configured.\") };\n const nameMatch = identity.content.match(/\\*\\*Name:\\*\\*\\s*(.+)/);\n const lines = [\n `**Identity Summary**`,\n nameMatch ? `Name: ${nameMatch[1].trim()}` : \"\",\n `Scope: ${AGENT_SCOPE}`,\n ].filter(Boolean);\n return { handled: true, output: lines.join(\"\\n\") };\n } catch (err) {\n return { handled: true, output: pc.red(`Summary error: ${err instanceof Error ? err.message : String(err)}`) };\n }\n }\n if (action === \"help\") {\n return {\n handled: true,\n output: [\n pc.bold(\"Identity commands:\"),\n ` ${pc.cyan(\"/identity\")} View current identity`,\n ` ${pc.cyan(\"/identity update\")} <section> Update a section`,\n ` ${pc.cyan(\"/identity dynamics\")} View user model (trust, sentiment, patterns)`,\n ` ${pc.cyan(\"/identity dynamics\")} key=val Update dynamic fields (energy, mode, read)`,\n ` ${pc.cyan(\"/identity dynamics\")} --json Raw JSON user model`,\n ` ${pc.cyan(\"/identity dynamics\")} --reset Reset user model`,\n ` ${pc.cyan(\"/identity summary\")} Show structured identity summary`,\n ].join(\"\\n\"),\n };\n }\n return {\n handled: true,\n output: pc.yellow(\n `Unknown action: /identity ${action}. Try /identity --help`,\n ),\n };\n}\n\nasync function handleRulesCommand(\n action: string | undefined,\n args: string[],\n _ctx: CommandContext,\n): Promise<CommandResult> {\n if (!action) {\n const cats = await arulesListCategories(AGENT_SCOPE);\n if (cats.length === 0) {\n return {\n handled: true,\n output: pc.dim(\n `No rules configured for ${AGENT_SCOPE}. Run: npx @aman_asmuei/arules`,\n ),\n };\n }\n const lines: string[] = [];\n for (const cat of cats) {\n lines.push(pc.bold(`## ${cat.name}`));\n for (const rule of cat.rules) {\n lines.push(` - ${rule}`);\n }\n lines.push(\"\");\n }\n return { handled: true, output: lines.join(\"\\n\").trim() };\n }\n if (action === \"add\") {\n if (args.length < 2) {\n return {\n handled: true,\n output: pc.yellow(\"Usage: /rules add <category> <rule text...>\"),\n };\n }\n const category = args[0];\n const rule = args.slice(1).join(\" \");\n try {\n await arulesAddRule(category, rule, AGENT_SCOPE);\n return {\n handled: true,\n output: pc.green(`Added rule to \"${category}\": ${rule}`),\n };\n } catch (err) {\n return {\n handled: true,\n output: pc.red(\n `Failed: ${err instanceof Error ? err.message : String(err)}`,\n ),\n };\n }\n }\n if (action === \"remove\") {\n if (args.length < 2) {\n return {\n handled: true,\n output: pc.yellow(\"Usage: /rules remove <category> <index>\"),\n };\n }\n const category = args[0];\n const idx = parseInt(args[1], 10);\n if (isNaN(idx) || idx < 1) {\n return {\n handled: true,\n output: pc.yellow(\"Index must be a positive integer.\"),\n };\n }\n try {\n await arulesRemoveRule(category, idx, AGENT_SCOPE);\n return {\n handled: true,\n output: pc.green(`Removed rule ${idx} from \"${category}\"`),\n };\n } catch (err) {\n return {\n handled: true,\n output: pc.red(\n `Failed: ${err instanceof Error ? err.message : String(err)}`,\n ),\n };\n }\n }\n if (action === \"toggle\") {\n if (args.length < 2) {\n return {\n handled: true,\n output: pc.yellow(\"Usage: /rules toggle <category> <index>\"),\n };\n }\n const category = args[0];\n const idx = parseInt(args[1], 10);\n if (isNaN(idx) || idx < 1) {\n return {\n handled: true,\n output: pc.yellow(\"Index must be a positive integer.\"),\n };\n }\n try {\n await arulesToggleRule(category, idx, AGENT_SCOPE);\n return {\n handled: true,\n output: pc.green(`Toggled rule ${idx} in \"${category}\"`),\n };\n } catch (err) {\n return {\n handled: true,\n output: pc.red(\n `Failed: ${err instanceof Error ? err.message : String(err)}`,\n ),\n };\n }\n }\n if (action === \"check\") {\n if (args.length === 0) {\n return { handled: true, output: pc.yellow(\"Usage: /rules check <action description...>\") };\n }\n const description = args.join(\" \");\n try {\n const result = await arulesCheckAction(description, AGENT_SCOPE);\n if (result.safe) {\n return { handled: true, output: pc.green(`Action is allowed: \"${description}\"`) };\n }\n return {\n handled: true,\n output: pc.red(`Action blocked: \"${description}\"\\nViolations:\\n${result.violations.map(v => ` - ${v}`).join(\"\\n\")}`),\n };\n } catch (err) {\n return { handled: true, output: pc.red(`Check error: ${err instanceof Error ? err.message : String(err)}`) };\n }\n }\n if (action === \"help\") {\n return {\n handled: true,\n output: [\n pc.bold(\"Rules commands:\"),\n ` ${pc.cyan(\"/rules\")} View current rules`,\n ` ${pc.cyan(\"/rules add\")} <category> <text> Add a rule`,\n ` ${pc.cyan(\"/rules remove\")} <category> <idx> Remove a rule`,\n ` ${pc.cyan(\"/rules toggle\")} <category> <idx> Toggle a rule`,\n ` ${pc.cyan(\"/rules check\")} <action...> Check if an action is allowed`,\n ].join(\"\\n\"),\n };\n }\n return {\n handled: true,\n output: pc.yellow(`Unknown action: /rules ${action}. Try /rules --help`),\n };\n}\n\nasync function handleWorkflowsCommand(\n action: string | undefined,\n args: string[],\n ctx: CommandContext,\n): Promise<CommandResult> {\n const home = os.homedir();\n if (!action) {\n const content = readEcosystemFile(path.join(home, \".aflow\", \"flow.md\"), \"workflows (aflow)\");\n return { handled: true, output: content };\n }\n if (action === \"add\") {\n if (args.length < 1) {\n return { handled: true, output: pc.yellow(\"Usage: /workflows add <name>\") };\n }\n const output = await mcpWrite(ctx, \"workflows\", \"workflow_add\", { name: args.join(\" \") });\n return { handled: true, output };\n }\n if (action === \"remove\") {\n if (args.length < 1) {\n return { handled: true, output: pc.yellow(\"Usage: /workflows remove <name>\") };\n }\n const output = await mcpWrite(ctx, \"workflows\", \"workflow_remove\", { name: args.join(\" \") });\n return { handled: true, output };\n }\n if (action === \"get\") {\n if (args.length === 0) {\n return { handled: true, output: pc.yellow(\"Usage: /workflows get <name>\") };\n }\n const name = args.join(\" \").toLowerCase();\n const raw = readEcosystemFile(path.join(home, \".aflow\", \"flow.md\"), \"workflows (aflow)\");\n if (raw.startsWith(\"No \")) {\n return { handled: true, output: raw };\n }\n // Parse sections: ## WorkflowName\\n<steps>\n const sections = raw.split(/^## /m).slice(1);\n const match = sections.find(s => s.split(\"\\n\")[0].trim().toLowerCase() === name);\n if (!match) {\n return { handled: true, output: pc.yellow(`No workflow found: \"${args.join(\" \")}\"`) };\n }\n const title = match.split(\"\\n\")[0].trim();\n const body = match.split(\"\\n\").slice(1).join(\"\\n\").trim();\n return { handled: true, output: `## ${title}\\n\\n${body}` };\n }\n if (action === \"help\") {\n return { handled: true, output: [\n pc.bold(\"Workflow commands:\"),\n ` ${pc.cyan(\"/workflows\")} View current workflows`,\n ` ${pc.cyan(\"/workflows add\")} <name> Add a workflow`,\n ` ${pc.cyan(\"/workflows remove\")} <name> Remove a workflow`,\n ` ${pc.cyan(\"/workflows get\")} <name> Show a specific workflow`,\n ].join(\"\\n\") };\n }\n return { handled: true, output: pc.yellow(`Unknown action: /workflows ${action}. Try /workflows --help`) };\n}\n\n// ── /akit slash command — Phase 5 cleanup ───────────────────────────────────\n//\n// The hardcoded AKIT_REGISTRY (17 entries kept \"in sync\" with akit's own\n// registry by hand), the AkitTool/InstalledTool interfaces, and the\n// loadAkitInstalled / saveAkitInstalled / addToAmanAgentConfig /\n// removeFromAmanAgentConfig helpers all lived here in commands.ts. They were\n// a parallel implementation of `akit/src/lib/registry.ts` and `lib/kit.ts`,\n// flagged by the Phase 0 audit as the worst duplication site in aman-agent.\n//\n// Per engine v1 D4: akit is reclassified as DORMANT — it stays as the\n// standalone CLI tool installer, and aman-agent no longer reimplements its\n// registry. This /akit slash command becomes informational, pointing the\n// user at the canonical CLI.\n\nfunction handleAkitCommand(\n _action: string | undefined,\n _args: string[],\n): CommandResult {\n return {\n handled: true,\n output: [\n pc.bold(\"akit — Tool Management\"),\n \"\",\n pc.dim(\n \"Tool management is now handled by the standalone akit CLI rather than\",\n ),\n pc.dim(\n \"duplicated inside aman-agent. The akit slash command is informational only.\",\n ),\n \"\",\n ` ${pc.cyan(\"npx @aman_asmuei/akit list\")} List installed tools`,\n ` ${pc.cyan(\"npx @aman_asmuei/akit search <query>\")} Search the tool registry`,\n ` ${pc.cyan(\"npx @aman_asmuei/akit add <tool>\")} Install a tool`,\n ` ${pc.cyan(\"npx @aman_asmuei/akit remove <tool>\")} Uninstall a tool`,\n \"\",\n pc.dim(\n \"Restart aman-agent after installing/removing tools to pick up changes.\",\n ),\n ].join(\"\\n\"),\n };\n}\n\nasync function handleToolsCommand(\n action: string | undefined,\n args: string[],\n _ctx: CommandContext,\n): Promise<CommandResult> {\n if (!action || action === \"list\") {\n // Informational stub — actual tool management is via akit CLI\n return handleAkitCommand(action, args);\n }\n if (action === \"search\") {\n if (args.length === 0) {\n return { handled: true, output: pc.yellow(\"Usage: /tools search <query...>\") };\n }\n const query = args.join(\" \").toLowerCase();\n const home = os.homedir();\n const toolsFile = path.join(home, \".akit\", \"tools.md\");\n if (!fs.existsSync(toolsFile)) {\n return { handled: true, output: pc.dim(`No tools file found. Use 'npx @aman_asmuei/akit search ${args.join(\" \")}' to search the registry.`) };\n }\n const raw = fs.readFileSync(toolsFile, \"utf-8\").trim();\n const lines = raw.split(\"\\n\");\n const matches = lines.filter(l => l.toLowerCase().includes(query));\n if (matches.length === 0) {\n return { handled: true, output: pc.dim(`No tools matching \"${query}\".`) };\n }\n return { handled: true, output: [pc.bold(`Tools matching \"${query}\":`), ...matches].join(\"\\n\") };\n }\n return handleAkitCommand(action, args);\n}\n\nasync function handleSkillsCommand(\n action: string | undefined,\n args: string[],\n ctx: CommandContext,\n): Promise<CommandResult> {\n const home = os.homedir();\n if (!action) {\n const content = readEcosystemFile(path.join(home, \".askill\", \"skills.md\"), \"skills (askill)\");\n return { handled: true, output: content };\n }\n if (action === \"install\") {\n if (args.length < 1) {\n return { handled: true, output: pc.yellow(\"Usage: /skills install <name>\") };\n }\n const output = await mcpWrite(ctx, \"skills\", \"skill_install\", { name: args.join(\" \") });\n return { handled: true, output };\n }\n if (action === \"uninstall\") {\n if (args.length < 1) {\n return { handled: true, output: pc.yellow(\"Usage: /skills uninstall <name>\") };\n }\n const output = await mcpWrite(ctx, \"skills\", \"skill_uninstall\", { name: args.join(\" \") });\n return { handled: true, output };\n }\n if (action === \"search\") {\n if (args.length === 0) {\n return { handled: true, output: pc.yellow(\"Usage: /skills search <query...>\") };\n }\n const query = args.join(\" \").toLowerCase();\n const home = os.homedir();\n const raw = readEcosystemFile(path.join(home, \".askill\", \"skills.md\"), \"skills (askill)\");\n if (raw.startsWith(\"No \")) {\n return { handled: true, output: raw };\n }\n const lines = raw.split(\"\\n\");\n const matches = lines.filter(l => l.toLowerCase().includes(query));\n if (matches.length === 0) {\n return { handled: true, output: pc.dim(`No skills matching \"${query}\".`) };\n }\n return { handled: true, output: [pc.bold(`Skills matching \"${query}\":`), ...matches].join(\"\\n\") };\n }\n if (action === \"list\") {\n const autoOnly = args.includes(\"--auto\");\n if (autoOnly) {\n const logPath = path.join(os.homedir(), \".aman-agent\", \"crystallization-log.json\");\n try {\n const content = fs.readFileSync(logPath, \"utf-8\");\n const entries = JSON.parse(content) as Array<{\n name: string;\n createdAt: string;\n fromPostmortem: string;\n confidence: number;\n triggers: string[];\n }>;\n if (entries.length === 0) {\n return { handled: true, output: pc.dim(\"No crystallized skills yet.\") };\n }\n const suggestionsPath = path.join(os.homedir(), \".aman-agent\", \"crystallization-suggestions.json\");\n let sugCounts: Record<string, number> = {};\n try {\n const sc = fs.readFileSync(suggestionsPath, \"utf-8\");\n sugCounts = JSON.parse(sc);\n } catch { /* noop */ }\n\n // Count archived versions per skill from skills.md\n let versionCounts: Record<string, number> = {};\n try {\n const skillsContent = fs.readFileSync(path.join(os.homedir(), \".askill\", \"skills.md\"), \"utf-8\");\n const versionRe = /^# (.+)\\.v(\\d+)$/gm;\n let vMatch;\n while ((vMatch = versionRe.exec(skillsContent)) !== null) {\n const skillHeading = vMatch[1].toLowerCase().replace(/ /g, \"-\");\n const ver = parseInt(vMatch[2], 10);\n versionCounts[skillHeading] = Math.max(versionCounts[skillHeading] || 0, ver);\n }\n } catch { /* noop */ }\n\n const lines = [pc.bold(`Crystallized skills (${entries.length}):`)];\n for (const entry of entries) {\n const date = entry.createdAt.slice(0, 10);\n const count = sugCounts[entry.name];\n const reinforced = count && count >= 3 ? pc.green(` ★ reinforced (${count}×)`) : \"\";\n const versions = versionCounts[entry.name];\n const versionLabel = versions ? pc.dim(` [v${versions + 1}]`) : \"\";\n lines.push(` ${pc.cyan(entry.name)} (${date}, conf ${entry.confidence})${reinforced}${versionLabel}`);\n lines.push(pc.dim(` triggers: ${entry.triggers.join(\", \")}`));\n }\n return { handled: true, output: lines.join(\"\\n\") };\n } catch {\n return { handled: true, output: pc.dim(\"No crystallized skills yet.\") };\n }\n }\n const content = readEcosystemFile(path.join(home, \".askill\", \"skills.md\"), \"skills (askill)\");\n return { handled: true, output: content };\n }\n if (action === \"crystallize\") {\n const pmDir = path.join(os.homedir(), \".acore\", \"postmortems\");\n try {\n const files = fs.readdirSync(pmDir);\n const jsonFiles = files.filter((f) => f.endsWith(\".json\")).sort().reverse();\n if (jsonFiles.length === 0) {\n return {\n handled: true,\n output: pc.dim(\"No post-mortems found. Run a session that triggers a post-mortem first.\"),\n };\n }\n const latest = jsonFiles[0];\n const content = fs.readFileSync(path.join(pmDir, latest), \"utf-8\");\n const report = JSON.parse(content);\n if (\n !report.crystallizationCandidates ||\n report.crystallizationCandidates.length === 0\n ) {\n return {\n handled: true,\n output: pc.dim(`No crystallization candidates in the most recent post-mortem (${latest}). Run a longer session or wait for the next auto-postmortem.`),\n };\n }\n\n const skillsMdPath = path.join(os.homedir(), \".askill\", \"skills.md\");\n const logPath = path.join(os.homedir(), \".aman-agent\", \"crystallization-log.json\");\n const postmortemFilename = latest.replace(/\\.json$/, \".md\");\n\n const lines: string[] = [\n pc.bold(`Found ${report.crystallizationCandidates.length} candidate(s) in ${latest}:`),\n ];\n let written = 0;\n for (const raw of report.crystallizationCandidates) {\n const candidate = validateCandidate(raw);\n if (!candidate) {\n const rawName = (raw as { name?: string }).name ?? \"unknown\";\n lines.push(pc.dim(` ⊘ ${rawName} — failed validation`));\n continue;\n }\n const result = await writeSkillToFile(candidate, skillsMdPath, postmortemFilename);\n if (result.written) {\n written++;\n lines.push(pc.green(` ✓ Crystallized: ${candidate.name}`));\n await appendCrystallizationLog(\n {\n name: candidate.name,\n createdAt: new Date().toISOString(),\n fromPostmortem: postmortemFilename,\n confidence: candidate.confidence,\n triggers: candidate.triggers,\n },\n logPath,\n );\n } else {\n lines.push(pc.yellow(` ⊘ ${candidate.name} — ${result.reason}`));\n }\n }\n\n if (written > 0) {\n lines.push(\"\");\n lines.push(pc.dim(`Crystallized skills will auto-activate in your next session.`));\n }\n\n return { handled: true, output: lines.join(\"\\n\") };\n } catch (err) {\n return {\n handled: true,\n output: pc.red(`Failed to load post-mortems: ${err instanceof Error ? err.message : String(err)}`),\n };\n }\n }\n if (action === \"help\") {\n return { handled: true, output: [\n pc.bold(\"Skills commands:\"),\n ` ${pc.cyan(\"/skills\")} View installed skills`,\n ` ${pc.cyan(\"/skills install\")} <name> Install a skill`,\n ` ${pc.cyan(\"/skills uninstall\")} <name> Uninstall a skill`,\n ` ${pc.cyan(\"/skills search\")} <query> Search skills by name/description`,\n ` ${pc.cyan(\"/skills crystallize\")} Crystallize skills from most recent post-mortem`,\n ` ${pc.cyan(\"/skills list --auto\")} List crystallized (auto-created) skills`,\n ].join(\"\\n\") };\n }\n return { handled: true, output: pc.yellow(`Unknown action: /skills ${action}. Try /skills --help`) };\n}\n\nasync function handleEvalCommand(\n action: string | undefined,\n args: string[],\n ctx: CommandContext,\n): Promise<CommandResult> {\n const home = os.homedir();\n if (!action) {\n const content = readEcosystemFile(path.join(home, \".aeval\", \"eval.md\"), \"evaluation (aeval)\");\n return { handled: true, output: content };\n }\n if (action === \"milestone\") {\n if (args.length < 1) {\n return { handled: true, output: pc.yellow(\"Usage: /eval milestone <text...>\") };\n }\n const text = args.join(\" \");\n const output = await mcpWrite(ctx, \"eval\", \"eval_milestone\", { text });\n return { handled: true, output };\n }\n if (action === \"report\") {\n const evalFile = path.join(home, \".aeval\", \"eval.md\");\n const lines: string[] = [pc.bold(\"📊 Eval Report\")];\n\n // Raw eval log\n if (fs.existsSync(evalFile)) {\n lines.push(\"\", fs.readFileSync(evalFile, \"utf-8\").trim());\n } else {\n lines.push(\"\", pc.dim(\"No eval log yet. Use /eval milestone <text> to start.\"));\n }\n\n // Analytics from user model\n try {\n const model = await loadUserModel();\n if (model && model.sessions.length >= 3) {\n const profile = computeProfile(model.sessions, model.profile.totalSessions);\n const burnout = predictBurnout(model.sessions);\n lines.push(\"\", pc.bold(\"── Analytics ──\"));\n lines.push(` Sessions tracked: ${pc.cyan(String(profile.totalSessions))}`);\n lines.push(` Trust score: ${pc.cyan(profile.trustScore.toFixed(2))}`);\n lines.push(` Sentiment trend: ${pc.cyan(profile.sentimentTrend)}`);\n\n // Energy distribution\n const topEnergy = Object.entries(profile.energyDistribution)\n .sort((a, b) => b[1] - a[1])\n .slice(0, 2)\n .map(([k, v]) => `${k} ${(v * 100).toFixed(0)}%`);\n lines.push(` Top energy: ${pc.cyan(topEnergy.join(\", \"))}`);\n\n // Burnout\n const riskColor = burnout.risk > 0.7 ? pc.red : burnout.risk > 0.4 ? pc.yellow : pc.green;\n lines.push(` Burnout risk: ${riskColor((burnout.risk * 100).toFixed(0) + \"%\")} ${burnout.factors.length > 0 ? pc.dim(\"(\" + burnout.factors.join(\", \") + \")\") : \"\"}`);\n\n // Frustration correlations\n const cors = Object.entries(profile.frustrationCorrelations)\n .filter(([, v]) => Math.abs(v) > 0.3)\n .sort((a, b) => Math.abs(b[1]) - Math.abs(a[1]))\n .slice(0, 3);\n if (cors.length > 0) {\n lines.push(` Frustration corr: ${cors.map(([k, v]) => `${k} ${v > 0 ? \"↑\" : \"↓\"}${Math.abs(v).toFixed(2)}`).join(\", \")}`);\n }\n }\n } catch {\n // User model unavailable — skip analytics silently\n }\n\n // Background task history\n try {\n const taskLog = loadTaskLog();\n if (taskLog.length > 0) {\n const completed = taskLog.filter((t) => t.status === \"completed\").length;\n const failed = taskLog.filter((t) => t.status === \"failed\").length;\n const interrupted = taskLog.filter((t) => t.status === \"interrupted\").length;\n lines.push(\"\", pc.bold(\"── Background Tasks ──\"));\n lines.push(` Total: ${taskLog.length} ✅ ${completed} ❌ ${failed} ⚠️ ${interrupted}`);\n }\n } catch {\n // Task log unavailable — skip\n }\n\n return { handled: true, output: lines.join(\"\\n\") };\n }\n return { handled: true, output: pc.yellow(`Unknown action: /eval ${action}. Use /eval, /eval report, or /eval milestone <text>.`) };\n}\n\nasync function handleMemoryCommand(\n action: string | undefined,\n args: string[],\n ctx: CommandContext,\n): Promise<CommandResult> {\n if (!action) {\n // Default: show recent memory context\n try {\n const result = await memoryContext(\"recent context\");\n if (result.memoriesUsed === 0) {\n return { handled: true, output: pc.dim(\"No memories yet. Start chatting and I'll remember what matters.\") };\n }\n return { handled: true, output: result.text };\n } catch (err) {\n return { handled: true, output: pc.red(`Memory error: ${err instanceof Error ? err.message : String(err)}`) };\n }\n }\n // /memory <topic> — shortcut for context on a specific topic\n if (action && ![\"search\", \"clear\", \"timeline\", \"stats\", \"export\", \"since\", \"fts\", \"help\", \"doctor\", \"repair\", \"config\", \"reflect\", \"consolidate\", \"tier\", \"detail\", \"relate\", \"expire\", \"versions\", \"sync\", \"mirror\"].includes(action)) {\n try {\n const topic = [action, ...args].join(\" \");\n const result = await memoryContext(topic);\n if (result.memoriesUsed === 0) {\n return { handled: true, output: pc.dim(`No memories found for: \"${topic}\".`) };\n }\n return { handled: true, output: result.text };\n } catch (err) {\n return { handled: true, output: pc.red(`Memory error: ${err instanceof Error ? err.message : String(err)}`) };\n }\n }\n if (action === \"search\") {\n if (args.length < 1) {\n return { handled: true, output: pc.yellow(\"Usage: /memory search <query...>\") };\n }\n const query = args.join(\" \");\n try {\n const result = await memoryMultiRecall(query, { limit: 10 });\n if (result.total === 0) {\n return { handled: true, output: pc.dim(\"No memories found.\") };\n }\n const header = `Search results for \"${query}\" (${result.total}):`;\n const lines: string[] = [pc.bold(header), \"\"];\n for (const m of result.memories) {\n const tags = m.tags?.length > 0\n ? ` ${pc.dim(m.tags.map((t: string) => `#${t}`).join(\" \"))}`\n : \"\";\n lines.push(` [${m.type}] ${m.content}${tags}`);\n }\n return { handled: true, output: lines.join(\"\\n\") };\n } catch (err) {\n return { handled: true, output: pc.red(`Memory error: ${err instanceof Error ? err.message : String(err)}`) };\n }\n }\n if (action === \"clear\") {\n if (args.length < 1) {\n return { handled: true, output: pc.yellow(\"Usage: /memory clear <query> — delete memories matching a search query\\n /memory clear --type <type> — delete all memories of a type (correction|decision|pattern|preference|topology|fact)\") };\n }\n try {\n // Support --type <type> for category-based delete\n if (args[0] === \"--type\" && args[1]) {\n const result = await memoryForget({ type: args[1] });\n return { handled: true, output: result.deleted > 0 ? pc.green(result.message) : pc.dim(result.message) };\n }\n const result = await memoryForget({ query: args.join(\" \") });\n return { handled: true, output: result.deleted > 0 ? pc.green(result.message) : pc.dim(result.message) };\n } catch (err) {\n return { handled: true, output: pc.red(`Memory error: ${err instanceof Error ? err.message : String(err)}`) };\n }\n }\n if (action === \"timeline\") {\n try {\n const result = await memoryRecall(\"*\", { limit: 500, compact: false });\n if (result.total === 0) {\n return { handled: true, output: pc.dim(\"No memories yet. Start chatting and I'll remember what matters.\") };\n }\n const memories = result.memories;\n if (memories.length > 0) {\n const byDate = new Map<string, number>();\n for (const mem of memories) {\n const createdAt = (mem as { created_at?: number }).created_at;\n const date = createdAt\n ? new Date(createdAt).toLocaleDateString(\"en-US\", { month: \"short\", day: \"numeric\" })\n : \"Unknown\";\n byDate.set(date, (byDate.get(date) || 0) + 1);\n }\n const maxCount = Math.max(...byDate.values());\n const barWidth = 10;\n const lines: string[] = [pc.bold(\"Memory Timeline:\"), \"\"];\n for (const [date, count] of byDate) {\n const filled = Math.round((count / maxCount) * barWidth);\n const bar = \"█\".repeat(filled) + \"░\".repeat(barWidth - filled);\n lines.push(` ${date.padEnd(8)} ${bar} ${count} memories`);\n }\n const tags = new Map<string, number>();\n for (const mem of memories) {\n const memTags = (mem as { tags?: string[] }).tags;\n if (Array.isArray(memTags)) {\n for (const tag of memTags) {\n tags.set(tag, (tags.get(tag) || 0) + 1);\n }\n }\n }\n lines.push(\"\");\n lines.push(` Total: ${result.total} memories`);\n if (tags.size > 0) {\n const topTags = [...tags.entries()]\n .sort((a, b) => b[1] - a[1])\n .slice(0, 5)\n .map(([tag, count]) => `#${tag} (${count})`)\n .join(\", \");\n lines.push(` Top tags: ${topTags}`);\n }\n return { handled: true, output: lines.join(\"\\n\") };\n }\n return { handled: true, output: `Total memories: ${result.total} entries.` };\n } catch {\n return { handled: true, output: pc.red(\"Failed to retrieve memory timeline.\") };\n }\n }\n if (action === \"stats\") {\n try {\n const stats = memoryStats();\n const lines: string[] = [pc.bold(\"Memory Statistics:\"), \"\"];\n lines.push(` Total memories: ${pc.bold(String(stats.total))}`);\n if (Object.keys(stats.byType).length > 0) {\n lines.push(\"\");\n lines.push(` ${pc.dim(\"By type:\")}`);\n for (const [type, count] of Object.entries(stats.byType)) {\n lines.push(` ${type.padEnd(16)} ${count}`);\n }\n }\n return { handled: true, output: lines.join(\"\\n\") };\n } catch (err) {\n return { handled: true, output: pc.red(`Memory error: ${err instanceof Error ? err.message : String(err)}`) };\n }\n }\n if (action === \"export\") {\n try {\n // `--to <dir>` / `--to=<dir>` → one-shot snapshot via MirrorEngine.\n // Left of any legacy stdout-dump behaviour unchanged so existing\n // callers of `/memory export [json]` keep working.\n const toDir = parseFlagValue(args, \"--to\");\n if (toDir !== undefined) {\n const engine = getMirrorEngine();\n if (!engine) {\n return { handled: true, output: pc.yellow(\"Mirror is disabled — enable via config.mirror.enabled in config.json.\") };\n }\n const resolved = expandHome(toDir);\n const res = await engine.exportSnapshot(resolved);\n const lines = [\n `Wrote ${res.written} files to ${resolved} (${res.skipped} skipped, ${res.errors.length} errors).`,\n ];\n if (res.errors.length > 0) {\n lines.push(\"\");\n for (const e of res.errors.slice(0, 5)) lines.push(` - ${e}`);\n if (res.errors.length > 5) lines.push(` ...and ${res.errors.length - 5} more`);\n }\n return { handled: true, output: lines.join(\"\\n\") };\n }\n const format = args[0] === \"json\" ? \"json\" : \"markdown\";\n const memories = memoryExport();\n if (memories.length === 0) {\n return { handled: true, output: pc.dim(\"No memories to export.\") };\n }\n if (format === \"json\") {\n const jsonOut = memories.map(m => ({ id: m.id, type: m.type, content: m.content, tags: m.tags, confidence: m.confidence, createdAt: m.createdAt, tier: m.tier }));\n return { handled: true, output: JSON.stringify(jsonOut, null, 2) };\n }\n const lines: string[] = [`# Memory Export (${memories.length} memories)`, \"\"];\n for (const m of memories) {\n const date = new Date(m.createdAt).toLocaleDateString();\n const tags = m.tags.length > 0 ? ` [${m.tags.map(t => `#${t}`).join(\", \")}]` : \"\";\n lines.push(`- **[${m.type}]** ${m.content}${tags} ${pc.dim(`(${date}, ${Math.round(m.confidence * 100)}%)`)}`);\n }\n return { handled: true, output: lines.join(\"\\n\") };\n } catch (err) {\n return { handled: true, output: pc.red(`Memory error: ${err instanceof Error ? err.message : String(err)}`) };\n }\n }\n if (action === \"since\") {\n try {\n let hours = 24;\n if (args[0]) {\n const match = args[0].match(/^(\\d+)(h|d|w)$/);\n if (match) {\n const value = parseInt(match[1], 10);\n const unit = match[2];\n if (unit === \"h\") hours = value;\n else if (unit === \"d\") hours = value * 24;\n else if (unit === \"w\") hours = value * 24 * 7;\n } else {\n return { handled: true, output: pc.yellow(\"Usage: /memory since <Nh|Nd|Nw> (e.g., 24h, 7d, 1w)\") };\n }\n }\n const memories = memorySince(hours);\n if (memories.length === 0) {\n return { handled: true, output: pc.dim(`No memories in the last ${args[0] || \"24h\"}.`) };\n }\n const lines: string[] = [pc.bold(`Memories since ${args[0] || \"24h\"} (${memories.length}):`), \"\"];\n for (const m of memories) {\n const age = Math.round((Date.now() - m.createdAt) / 3600000);\n const ageStr = age < 1 ? \"<1h ago\" : `${age}h ago`;\n lines.push(` ${pc.dim(ageStr.padEnd(10))} [${m.type}] ${m.content}`);\n }\n return { handled: true, output: lines.join(\"\\n\") };\n } catch (err) {\n return { handled: true, output: pc.red(`Memory error: ${err instanceof Error ? err.message : String(err)}`) };\n }\n }\n if (action === \"fts\") {\n if (args.length < 1) {\n return { handled: true, output: pc.yellow(\"Usage: /memory fts <query...> — full-text search\") };\n }\n try {\n const query = args.join(\" \");\n const results = memorySearch(query, 20);\n if (results.length === 0) {\n return { handled: true, output: pc.dim(`No results for full-text search: \"${query}\".`) };\n }\n const lines: string[] = [pc.bold(`FTS results for \"${query}\" (${results.length}):`), \"\"];\n for (const m of results) {\n const tags = m.tags.length > 0 ? ` ${pc.dim(m.tags.map(t => `#${t}`).join(\" \"))}` : \"\";\n lines.push(` [${m.type}] ${m.content}${tags}`);\n }\n return { handled: true, output: lines.join(\"\\n\") };\n } catch (err) {\n return { handled: true, output: pc.red(`Memory error: ${err instanceof Error ? err.message : String(err)}`) };\n }\n }\n if (action === \"help\") {\n return { handled: true, output: [\n pc.bold(\"Memory commands:\"),\n ` ${pc.cyan(\"/memory\")} View recent context`,\n ` ${pc.cyan(\"/memory\")} <topic> Context for a topic`,\n ` ${pc.cyan(\"/memory search\")} <query> Search memories (semantic)`,\n ` ${pc.cyan(\"/memory fts\")} <query> Full-text search (FTS5)`,\n ` ${pc.cyan(\"/memory since\")} <Nh|Nd|Nw> Memories from time window`,\n ` ${pc.cyan(\"/memory stats\")} Show memory statistics`,\n ` ${pc.cyan(\"/memory export\")} [json] Export all memories`,\n ` ${pc.cyan(\"/memory export --to\")} <dir> Snapshot mirror-format files to <dir>`,\n ` ${pc.cyan(\"/memory timeline\")} View memory timeline`,\n ` ${pc.cyan(\"/memory clear\")} <query> Delete matching memories`,\n ` ${pc.cyan(\"/memory clear --type\")} <type> Delete all of a type`,\n ` ${pc.cyan(\"/memory doctor\")} Run memory diagnostics`,\n ` ${pc.cyan(\"/memory repair\")} Dry-run repair (safe)`,\n ` ${pc.cyan(\"/memory config\")} [key=value] View or update config (e.g. consolidation.maxStaleDays=60)`,\n ` ${pc.cyan(\"/memory mirror status\")} Show mirror dir, file count, health`,\n ` ${pc.cyan(\"/memory mirror rebuild\")} Rebuild the mirror from the DB`,\n ` ${pc.cyan(\"/memory sync --from\")} <dir> Import edits from a mirror-format dir`,\n ].join(\"\\n\") };\n }\n if (action === \"doctor\") {\n try {\n const diag = await memoryDoctor();\n const statusIcon = diag.status === \"healthy\" ? \"✅\" : \"⚠️\";\n const lines: string[] = [\n `**Memory Diagnostics**`,\n `Status: ${statusIcon} ${diag.status}`,\n ];\n if (diag.issues?.length) {\n lines.push(\"\", \"**Issues:**\");\n for (const issue of diag.issues) {\n lines.push(`- ${typeof issue === \"string\" ? issue : (issue as { message?: string }).message ?? String(issue)}`);\n }\n lines.push(\"\", \"_Run `/memory repair` (dry-run) or `/memory repair --apply` to fix._\");\n }\n return { handled: true, output: lines.join(\"\\n\") };\n } catch (err) {\n return { handled: true, output: pc.red(`Memory doctor error: ${err instanceof Error ? err.message : String(err)}`) };\n }\n }\n if (action === \"repair\") {\n try {\n const dryRun = !args.includes(\"--apply\");\n const result = await memoryRepair({ dryRun });\n const prefix = dryRun ? \"[DRY RUN] \" : \"\";\n const lines: string[] = [`**${prefix}Memory Repair**`];\n if (result.actions?.length) {\n lines.push(\"\", \"**Actions:**\");\n for (const act of result.actions) {\n lines.push(`- ${act}`);\n }\n } else {\n lines.push(\"No actions needed.\");\n }\n if (dryRun) {\n lines.push(\"\", \"_Run `/memory repair --apply` to execute._\");\n }\n return { handled: true, output: lines.join(\"\\n\") };\n } catch (err) {\n return { handled: true, output: pc.red(`Memory repair error: ${err instanceof Error ? err.message : String(err)}`) };\n }\n }\n if (action === \"config\") {\n try {\n const kvArg = args.find((a: string) => a.includes(\"=\") && !a.startsWith(\"-\"));\n if (kvArg) {\n const eqIdx = kvArg.indexOf(\"=\");\n const key = kvArg.slice(0, eqIdx);\n const rawVal = kvArg.slice(eqIdx + 1);\n if (!rawVal) {\n return { handled: true, output: pc.yellow(`Usage: /memory config <key>=<value>`) };\n }\n const val = isNaN(Number(rawVal)) ? rawVal : Number(rawVal);\n const update = buildNestedUpdate(key, val);\n await memoryConfig(update);\n return { handled: true, output: `✅ Set \\`${key}\\` → \\`${val}\\`` };\n }\n const config = await memoryConfig();\n const lines = [\"**Memory Config**\", \"```\"];\n for (const [k, v] of Object.entries(config as Record<string, unknown>)) {\n if (typeof v === \"object\" && v !== null) {\n for (const [sk, sv] of Object.entries(v as Record<string, unknown>)) {\n lines.push(`${k}.${sk}: ${sv}`);\n }\n } else {\n lines.push(`${k}: ${v}`);\n }\n }\n lines.push(\"```\", \"\", \"_Use `/memory config key=value` to change a setting._\");\n return { handled: true, output: lines.join(\"\\n\") };\n } catch (err) {\n return { handled: true, output: pc.red(`Memory config error: ${err instanceof Error ? err.message : String(err)}`) };\n }\n }\n if (action === \"reflect\") {\n try {\n const report = await memoryReflect();\n const lines = [\n pc.bold(\"Reflection complete\"),\n `Clusters: ${report.clusters.length}`,\n `Contradictions: ${report.contradictions.length}`,\n `Synthesis candidates: ${report.synthesisCandidates.length}`,\n `Knowledge gaps: ${report.knowledgeGaps.length}`,\n `Health score: ${(report.stats.healthScore * 100).toFixed(0)}%`,\n `Duration: ${report.durationMs}ms`,\n ];\n return { handled: true, output: lines.join(\"\\n\") };\n } catch (err) {\n return { handled: true, output: pc.red(`Reflect error: ${err instanceof Error ? err.message : String(err)}`) };\n }\n }\n if (action === \"consolidate\") {\n const apply = args.includes(\"--apply\");\n try {\n const report = memoryConsolidate(!apply);\n const lines = [\n apply ? pc.bold(\"Consolidation applied\") : pc.bold(\"Consolidation dry-run\"),\n `Merged: ${report.merged}`,\n `Pruned: ${report.pruned}`,\n `Promoted: ${report.promoted}`,\n `Decayed: ${report.decayed}`,\n `Health score: ${(report.healthScore * 100).toFixed(0)}%`,\n `Before: ${report.before.total} → After: ${report.after.total}`,\n ];\n if (!apply) lines.push(pc.dim(\"Run with --apply to execute.\"));\n return { handled: true, output: lines.join(\"\\n\") };\n } catch (err) {\n return { handled: true, output: pc.red(`Consolidate error: ${err instanceof Error ? err.message : String(err)}`) };\n }\n }\n if (action === \"tier\") {\n const id = args[0];\n const tier = args[1];\n if (!id || !tier) {\n return { handled: true, output: pc.yellow(\"Usage: /memory tier <id> <core|working|archival>\") };\n }\n const tierResult = memoryTier(id, tier);\n if (!tierResult.ok) {\n return { handled: true, output: pc.red(`Tier error: ${tierResult.error}`) };\n }\n return { handled: true, output: `✅ Memory ${tierResult.id} moved to tier: ${tierResult.tier}` };\n }\n if (action === \"detail\") {\n const id = args[0];\n if (!id) {\n return { handled: true, output: pc.yellow(\"Usage: /memory detail <id>\") };\n }\n const memory = memoryDetail(id);\n if (!memory) {\n return { handled: true, output: pc.dim(`Memory not found: ${id}`) };\n }\n const lines = [\n pc.bold(`Memory: ${memory.id}`),\n `Content: ${memory.content}`,\n `Type: ${memory.type}`,\n `Confidence: ${memory.confidence}`,\n `Tier: ${(memory as any).tier ?? \"working\"}`,\n `Access count: ${memory.accessCount}`,\n `Created: ${new Date(memory.createdAt).toISOString()}`,\n memory.tags?.length ? `Tags: ${memory.tags.join(\", \")}` : \"\",\n ].filter(Boolean);\n return { handled: true, output: lines.join(\"\\n\") };\n }\n if (action === \"relate\") {\n const [fromId, toId, relType, strengthStr] = args;\n if (!fromId || !toId || !relType) {\n return { handled: true, output: pc.yellow(\"Usage: /memory relate <fromId> <toId> <type> [strength]\") };\n }\n const strength = strengthStr !== undefined ? parseFloat(strengthStr) : undefined;\n const relResult = memoryRelate(fromId, toId, relType, strength);\n if (!relResult.ok) {\n return { handled: true, output: pc.red(`Relate error: ${relResult.error}`) };\n }\n return { handled: true, output: `✅ Relation created: ${fromId} --[${relType}]--> ${toId} (id: ${relResult.relationId})` };\n }\n if (action === \"expire\") {\n const id = args[0];\n if (!id) {\n return { handled: true, output: pc.yellow(\"Usage: /memory expire <id> [reason]\") };\n }\n const reason = args.slice(1).join(\" \") || undefined;\n const expireResult = memoryExpire(id, reason);\n if (!expireResult.ok) {\n return { handled: true, output: pc.red(`Expire error: ${expireResult.error}`) };\n }\n return { handled: true, output: `✅ Memory ${expireResult.id} expired${reason ? `: ${reason}` : \"\"}` };\n }\n if (action === \"versions\") {\n const id = args[0];\n if (!id) {\n return { handled: true, output: pc.yellow(\"Usage: /memory versions <id>\") };\n }\n const versions = memoryVersions(id);\n if (!versions.length) {\n return { handled: true, output: pc.dim(`No version history for: ${id}`) };\n }\n const lines = [pc.bold(`Version history for ${id}:`)];\n for (const v of versions) {\n lines.push(` [${new Date(v.editedAt).toISOString()}] ${v.content.slice(0, 80)}${v.content.length > 80 ? \"\\u2026\" : \"\"}`);\n }\n return { handled: true, output: lines.join(\"\\n\") };\n }\n if (action === \"mirror\") {\n const sub = args[0];\n try {\n if (sub === \"status\") {\n const engine = getMirrorEngine();\n if (!engine) return { handled: true, output: pc.yellow(\"Mirror is disabled — enable via config.mirror.enabled in config.json.\") };\n const s = engine.status();\n const last = s.lastWriteAt\n ? `${new Date(s.lastWriteAt).toISOString()} (${relativeTimeFromNow(s.lastWriteAt)})`\n : \"never\";\n const lines = [\n pc.bold(\"Mirror:\"),\n ` Dir: ${s.dir}`,\n ` File count: ${s.fileCount}`,\n ` Last write: ${last}`,\n ` Health: ${s.healthy ? \"healthy\" : \"drifted\"}`,\n ];\n return { handled: true, output: lines.join(\"\\n\") };\n }\n if (sub === \"rebuild\") {\n const engine = getMirrorEngine();\n if (!engine) return { handled: true, output: pc.yellow(\"Mirror is disabled — enable via config.mirror.enabled in config.json.\") };\n const res = await engine.fullMirror();\n return {\n handled: true,\n output: `Rebuilt mirror: ${res.written} files written, ${res.skipped} skipped, ${res.errors.length} errors.`,\n };\n }\n return { handled: true, output: pc.yellow(\"Unknown mirror subcommand; try 'status' or 'rebuild'.\") };\n } catch (err) {\n return { handled: true, output: pc.red(`Mirror error: ${err instanceof Error ? err.message : String(err)}`) };\n }\n }\n if (action === \"sync\") {\n // `--from <dir>` / `--from=<dir>` → import mirror-format files into the DB.\n // This is the recovery path for the multi-device sync loop: a machine\n // that lost its DB but kept the markdown mirror can reconstruct state.\n const fromDir = parseFlagValue(args, \"--from\");\n if (fromDir !== undefined) {\n try {\n const resolved = expandHome(fromDir);\n const res = await syncFromMirrorDir(resolved);\n return {\n handled: true,\n output: `Synced ${res.imported} memories from ${resolved} (${res.skipped} skipped, ${res.updated} updated).`,\n };\n } catch (err) {\n return { handled: true, output: pc.red(`Sync error: ${err instanceof Error ? err.message : String(err)}`) };\n }\n }\n const syncAction = args[0] as \"import-claude\" | \"export-team\" | \"import-team\" | \"sync-copilot\" | undefined;\n if (!syncAction) {\n return { handled: true, output: pc.yellow(\"Usage: /memory sync <import-claude|export-team|import-team|sync-copilot>\") };\n }\n try {\n const opts: Record<string, string | boolean | undefined> = {};\n for (const arg of args.slice(1)) {\n if (arg.startsWith(\"--\")) {\n const [k, v] = arg.slice(2).split(\"=\");\n opts[k] = v ?? true;\n }\n }\n const result = await memorySync(syncAction, opts as any);\n return { handled: true, output: `✅ Sync [${syncAction}] complete:\\n${JSON.stringify(result, null, 2)}` };\n } catch (err) {\n return { handled: true, output: pc.red(`Sync error: ${err instanceof Error ? err.message : String(err)}`) };\n }\n }\n return { handled: true, output: pc.yellow(`Unknown action: /memory ${action}. Try /memory --help`) };\n}\n\n/**\n * Parse `--flag <value>` and `--flag=<value>` forms from an argv-like list.\n * Returns `undefined` when the flag isn't present so callers can distinguish\n * \"flag absent\" from \"flag with empty value\". Shared by `/memory export --to`\n * and `/memory sync --from` to keep their arg-parsing consistent.\n */\nfunction parseFlagValue(args: string[], flag: string): string | undefined {\n for (let i = 0; i < args.length; i++) {\n const a = args[i];\n if (a === flag) {\n return args[i + 1];\n }\n if (a.startsWith(`${flag}=`)) {\n return a.slice(flag.length + 1);\n }\n }\n return undefined;\n}\n\n/**\n * Tiny relative-time formatter for mirror status. Stays local to commands.ts\n * because mirror status is its only caller — no need to add a helper module.\n */\nfunction relativeTimeFromNow(ts: number): string {\n const delta = Date.now() - ts;\n if (delta < 60_000) return \"just now\";\n if (delta < 3_600_000) return `${Math.round(delta / 60_000)}m ago`;\n if (delta < 86_400_000) return `${Math.round(delta / 3_600_000)}h ago`;\n return `${Math.round(delta / 86_400_000)}d ago`;\n}\n\nfunction handleStatusCommand(ctx: CommandContext): CommandResult {\n const mcpToolCount = ctx.mcpManager ? ctx.mcpManager.getTools().length : 0;\n const amemConnected = isMemoryInitialized();\n const status = getEcosystemStatus(mcpToolCount, amemConnected);\n\n const lines: string[] = [pc.bold(\"Aman Ecosystem Dashboard\"), \"\"];\n\n for (const layer of status.layers) {\n const icon = layer.exists ? pc.green(\"●\") : pc.dim(\"○\");\n const name = pc.bold(layer.name.padEnd(12));\n const summary = layer.exists ? layer.summary : pc.dim(\"not configured\");\n lines.push(` ${icon} ${name} ${summary}`);\n }\n\n lines.push(\"\");\n lines.push(` ${status.mcpConnected ? pc.green(\"●\") : pc.dim(\"○\")} ${pc.bold(\"MCP\".padEnd(12))} ${status.mcpConnected ? `${status.mcpToolCount} tools available` : pc.dim(\"not connected\")}`);\n lines.push(` ${status.amemConnected ? pc.green(\"●\") : pc.dim(\"○\")} ${pc.bold(\"Memory\".padEnd(12))} ${status.amemConnected ? \"connected\" : pc.dim(\"not connected\")}`);\n\n return { handled: true, output: lines.join(\"\\n\") };\n}\n\nfunction handleDoctorCommand(ctx: CommandContext): CommandResult {\n const mcpToolCount = ctx.mcpManager ? ctx.mcpManager.getTools().length : 0;\n const amemConnected = isMemoryInitialized();\n const status = getEcosystemStatus(mcpToolCount, amemConnected);\n\n const lines: string[] = [pc.bold(\"Aman Health Check\"), \"\"];\n let healthy = 0;\n let fixes = 0;\n let suggestions = 0;\n\n for (const layer of status.layers) {\n if (layer.exists) {\n lines.push(` ${pc.green(\"✓\")} ${layer.name.padEnd(12)} ${pc.green(layer.summary)}`);\n healthy++;\n } else {\n const isRequired = [\"identity\", \"rules\"].includes(layer.name.toLowerCase());\n if (isRequired) {\n lines.push(` ${pc.red(\"✗\")} ${layer.name.padEnd(12)} ${pc.red(\"missing\")}`);\n lines.push(` ${pc.dim(\"→ Fix: aman-agent init\")}`);\n fixes++;\n } else {\n lines.push(` ${pc.yellow(\"⚠\")} ${layer.name.padEnd(12)} ${pc.yellow(\"empty\")}`);\n const cmd = layer.name.toLowerCase() === \"workflows\" ? \"/workflows add <name>\"\n : layer.name.toLowerCase() === \"tools\" ? \"/tools add <name> <type> <desc>\"\n : layer.name.toLowerCase() === \"skills\" ? \"/skills install <name>\"\n : \"\";\n if (cmd) lines.push(` ${pc.dim(`→ Add with ${cmd}`)}`);\n suggestions++;\n }\n }\n }\n\n lines.push(\"\");\n lines.push(` ${status.mcpConnected ? pc.green(\"✓\") : pc.red(\"✗\")} ${\"MCP\".padEnd(12)} ${status.mcpConnected ? pc.green(`${status.mcpToolCount} tools`) : pc.red(\"not connected\")}`);\n if (!status.mcpConnected) {\n lines.push(` ${pc.dim(\"→ Fix: ensure npx is available and network is connected\")}`);\n fixes++;\n } else {\n healthy++;\n }\n\n lines.push(` ${status.amemConnected ? pc.green(\"✓\") : pc.red(\"✗\")} ${\"Memory\".padEnd(12)} ${status.amemConnected ? pc.green(\"connected\") : pc.red(\"not connected\")}`);\n if (!status.amemConnected) {\n lines.push(` ${pc.dim(\"→ Fix: restart aman-agent (memory initializes automatically)\")}`);\n fixes++;\n } else {\n healthy++;\n }\n\n const total = healthy + fixes + suggestions;\n lines.push(\"\");\n lines.push(` Overall: ${healthy}/${total} healthy.${fixes > 0 ? ` ${fixes} fix${fixes > 1 ? \"es\" : \"\"} needed.` : \"\"}${suggestions > 0 ? ` ${suggestions} suggestion${suggestions > 1 ? \"s\" : \"\"}.` : \"\"}`);\n\n return { handled: true, output: lines.join(\"\\n\") };\n}\n\nfunction handleHelp(): CommandResult {\n return {\n handled: true,\n output: [\n pc.bold(\"Commands:\"),\n ` ${pc.cyan(\"/help\")} Show this help`,\n ` ${pc.cyan(\"/identity\")} View identity [update <section>]`,\n ` ${pc.cyan(\"/rules\")} View rules [add|remove|toggle ...]`,\n ` ${pc.cyan(\"/workflows\")} View workflows [add|remove ...]`,\n ` ${pc.cyan(\"/akit\")} Manage tools [add|remove <tool>]`,\n ` ${pc.cyan(\"/skills\")} View skills [install|uninstall|crystallize|list --auto]`,\n ` ${pc.cyan(\"/eval\")} View evaluation [milestone ...]`,\n ` ${pc.cyan(\"/memory\")} View recent memories [search|fts|since|stats|export|clear|timeline]`,\n ` ${pc.cyan(\"/reminder\")} Manage reminders [set|check|done]`,\n ` ${pc.cyan(\"/status\")} Ecosystem dashboard`,\n ` ${pc.cyan(\"/doctor\")} Health check all layers`,\n ` ${pc.cyan(\"/decisions\")} View decision log [<project>]`,\n ` ${pc.cyan(\"/export\")} Export conversation to markdown`,\n ` ${pc.cyan(\"/debug\")} Show debug log`,\n ` ${pc.cyan(\"/save\")} Save conversation to memory`,\n ` ${pc.cyan(\"/model\")} Show current LLM model`,\n ` ${pc.cyan(\"/plan\")} Manage multi-step plans`,\n ` ${pc.cyan(\"/profile me\")} View your profile`,\n ` ${pc.cyan(\"/profile edit\")} Edit your profile`,\n ` ${pc.cyan(\"/profile\")} List agent profiles`,\n ` ${pc.cyan(\"/showcase\")} Browse & switch companion templates`,\n ` ${pc.cyan(\"/delegate\")} Delegate tasks to sub-agents`,\n ` ${pc.cyan(\"/team\")} Manage agent teams`,\n ` ${pc.cyan(\"/observe\")} Session observation dashboard [pause|resume]`,\n ` ${pc.cyan(\"/postmortem\")} Generate post-mortem [last|list|--since 7d]`,\n ` ${pc.cyan(\"/update\")} Check for updates`,\n ` ${pc.cyan(\"/reset\")} Full reset [all|memory|config|identity|rules]`,\n ` ${pc.cyan(\"/clear\")} Clear conversation history`,\n ` ${pc.cyan(\"/quit\")} Exit`,\n ].join(\"\\n\"),\n };\n}\n\nfunction handleSave(): CommandResult {\n return { handled: true, saveConversation: true };\n}\n\nfunction handleReset(action: string | undefined): CommandResult {\n const dirs = {\n config: path.join(os.homedir(), \".aman-agent\"),\n memory: path.join(os.homedir(), \".amem\"),\n identity: path.join(os.homedir(), \".acore\"),\n rules: path.join(os.homedir(), \".arules\"),\n };\n\n if (action === \"help\" || !action) {\n return {\n handled: true,\n output: [\n pc.bold(\"Reset options:\"),\n ` ${pc.cyan(\"/reset all\")} Full reset — config, memory, identity, rules`,\n ` ${pc.cyan(\"/reset memory\")} Clear all memories only`,\n ` ${pc.cyan(\"/reset config\")} Reset LLM config only`,\n ` ${pc.cyan(\"/reset identity\")} Reset persona/identity only`,\n ` ${pc.cyan(\"/reset rules\")} Reset guardrails only`,\n \"\",\n pc.dim(\"Directories:\"),\n ...Object.entries(dirs).map(([k, v]) => ` ${k}: ${pc.dim(v)}`),\n ].join(\"\\n\"),\n };\n }\n\n const targets: Array<keyof typeof dirs> =\n action === \"all\" ? [\"config\", \"memory\", \"identity\", \"rules\"] : [action as keyof typeof dirs];\n\n if (!targets.every((t) => t in dirs)) {\n return { handled: true, output: pc.red(`Unknown target: ${action}. Use /reset help`) };\n }\n\n const removed: string[] = [];\n for (const target of targets) {\n const dir = dirs[target];\n if (fs.existsSync(dir)) {\n fs.rmSync(dir, { recursive: true, force: true });\n removed.push(target);\n }\n }\n\n // Write .reconfig marker so next run forces interactive LLM prompt\n if (targets.includes(\"config\")) {\n const configDir = dirs.config;\n fs.mkdirSync(configDir, { recursive: true });\n fs.writeFileSync(path.join(configDir, \".reconfig\"), \"\", \"utf-8\");\n }\n\n if (removed.length === 0) {\n return { handled: true, output: pc.dim(\"Nothing to reset — directories don't exist.\") };\n }\n\n return {\n handled: true,\n quit: true,\n output: [\n pc.green(`Reset complete: ${removed.join(\", \")}`),\n \"Restart aman-agent to begin fresh.\",\n ].join(\"\\n\"),\n };\n}\n\nfunction handleUpdate(): CommandResult {\n try {\n const current = execFileSync(\"npm\", [\"view\", \"@aman_asmuei/aman-agent\", \"version\"], { encoding: \"utf-8\" }).trim();\n const local = typeof __VERSION__ !== \"undefined\" ? __VERSION__ : \"unknown\";\n if (current === local) {\n return { handled: true, output: `${pc.green(\"Up to date\")} — v${local}` };\n }\n // Detect vendored install (node lives inside ~/.aman-agent/node/)\n const isVendored = process.execPath.includes(path.join(\".aman-agent\", \"node\"));\n const updateCmd = isVendored\n ? \"aman-agent update\"\n : \"npm install -g @aman_asmuei/aman-agent@latest\";\n\n return {\n handled: true,\n output: [\n `${pc.yellow(\"Update available:\")} v${local} → v${current}`,\n \"\",\n `Run this in your terminal:`,\n ` ${pc.bold(updateCmd)}`,\n ].join(\"\\n\"),\n };\n } catch {\n return {\n handled: true,\n output: [\n `To update, run in your terminal:`,\n ` ${pc.bold(\"npm install -g @aman_asmuei/aman-agent@latest\")}`,\n ].join(\"\\n\"),\n };\n }\n}\n\nasync function handleDecisionsCommand(\n action: string | undefined,\n _args: string[],\n _ctx: CommandContext,\n): Promise<CommandResult> {\n try {\n const result = await memoryRecall(\"decision\", { type: \"decision\", limit: 20 });\n if (result.total === 0) {\n return { handled: true, output: pc.dim(\"No decisions recorded yet.\") };\n }\n return { handled: true, output: pc.bold(\"Decision Log:\\n\") + result.text };\n } catch (err) {\n return { handled: true, output: pc.red(`Memory error: ${err instanceof Error ? err.message : String(err)}`) };\n }\n}\n\nfunction handleExportCommand(): CommandResult {\n return { handled: true, exportConversation: true };\n}\n\nfunction handleDebugCommand(): CommandResult {\n const logPath = path.join(os.homedir(), \".aman-agent\", \"debug.log\");\n if (!fs.existsSync(logPath)) {\n return { handled: true, output: pc.dim(\"No debug log found.\") };\n }\n const content = fs.readFileSync(logPath, \"utf-8\");\n const lines = content.trim().split(\"\\n\");\n const last20 = lines.slice(-20).join(\"\\n\");\n return { handled: true, output: pc.bold(\"Debug Log (last 20 entries):\\n\") + pc.dim(last20) };\n}\n\n// --- Main Router ---\n\n// --- Teams ---\n\nasync function handleTeamCommand(action: string | undefined, args: string[], ctx: CommandContext): Promise<CommandResult> {\n if (!action || action === \"list\") {\n const teams = listTeams();\n if (teams.length === 0) {\n return {\n handled: true,\n output: pc.dim(\"No teams yet. Create one:\") +\n \"\\n /team create <name> Create from built-in template\" +\n \"\\n /team create Show available templates\",\n };\n }\n const lines = teams.map((t) => {\n const members = t.members.map((m) => m.profile).join(\", \");\n return ` ${pc.bold(t.name)} (${t.workflow}) — ${members}`;\n });\n return { handled: true, output: \"Teams:\\n\" + lines.join(\"\\n\") };\n }\n\n switch (action) {\n case \"create\": {\n const name = args[0];\n if (!name) {\n const lines = BUILT_IN_TEAMS.map((t) => {\n const members = t.members.map((m) => m.profile).join(\" → \");\n return ` ${pc.bold(t.name)} (${t.workflow}) — ${members}\\n ${pc.dim(t.goal)}`;\n });\n return {\n handled: true,\n output: \"Built-in teams:\\n\" + lines.join(\"\\n\\n\") +\n \"\\n\\nUsage:\\n /team create content-team Install built-in\" +\n \"\\n /team create <name> <mode> <profile1:role>,<profile2:role> Custom\",\n };\n }\n\n // Check if it's a built-in template\n const builtIn = BUILT_IN_TEAMS.find((t) => t.name === name);\n if (builtIn) {\n createTeam(builtIn);\n return { handled: true, output: pc.green(`Team installed: ${builtIn.name}`) + \"\\n\\n\" + formatTeam(builtIn) };\n }\n\n // Custom team: /team create <name> <mode> <profile:role>,<profile:role>\n const mode = args[1] as Team[\"workflow\"];\n const membersStr = args[2];\n if (!mode || !membersStr) {\n return { handled: true, output: pc.yellow(\"Usage: /team create <name> <pipeline|parallel|coordinator> <profile1:role>,<profile2:role>\") };\n }\n if (![\"pipeline\", \"parallel\", \"coordinator\"].includes(mode)) {\n return { handled: true, output: pc.yellow(\"Mode must be: pipeline, parallel, or coordinator\") };\n }\n\n const members = membersStr.split(\",\").map((m) => {\n const [profile, ...roleParts] = m.trim().split(\":\");\n return { profile: profile.trim(), role: roleParts.join(\":\").trim() || profile.trim() };\n });\n\n const team: Team = {\n name,\n goal: `Team: ${name}`,\n coordinator: \"default\",\n members,\n workflow: mode,\n };\n createTeam(team);\n return { handled: true, output: pc.green(`Team created!`) + \"\\n\\n\" + formatTeam(team) };\n }\n\n case \"run\": {\n const teamName = args[0];\n const task = args.slice(1).join(\" \");\n if (!teamName || !task) {\n return { handled: true, output: pc.yellow(\"Usage: /team run <team-name> <task description>\") };\n }\n\n const team = loadTeam(teamName);\n if (!team) return { handled: true, output: pc.red(`Team not found: ${teamName}`) };\n\n if (!ctx.llmClient || !ctx.mcpManager) {\n return { handled: true, output: pc.red(\"Team execution requires LLM client and MCP.\") };\n }\n\n const result = await runTeam(team, task, ctx.llmClient, ctx.mcpManager, ctx.tools);\n return { handled: true, output: formatTeamResult(result) };\n }\n\n case \"show\": {\n const name = args[0];\n if (!name) return { handled: true, output: pc.yellow(\"Usage: /team show <name>\") };\n const team = loadTeam(name);\n if (!team) return { handled: true, output: pc.red(`Team not found: ${name}`) };\n return { handled: true, output: formatTeam(team) };\n }\n\n case \"delete\": {\n const name = args[0];\n if (!name) return { handled: true, output: pc.yellow(\"Usage: /team delete <name>\") };\n if (!deleteTeam(name)) return { handled: true, output: pc.red(`Team not found: ${name}`) };\n return { handled: true, output: pc.dim(`Team deleted: ${name}`) };\n }\n\n case \"help\":\n return { handled: true, output: `Team commands:\n /team List all teams\n /team create Show built-in templates\n /team create <name> Install built-in team\n /team create <n> <mode> <m> Custom team (mode: pipeline|parallel|coordinator)\n /team run <name> <task> Run a task with a team\n /team show <name> Show team details\n /team delete <name> Delete a team\n\nModes:\n pipeline Sequential: agent1 → agent2 → agent3\n parallel All agents work concurrently, coordinator merges\n coordinator Coordinator LLM decides how to split the task\n\nExamples:\n /team create content-team\n /team run content-team Write a blog post about AI companions\n /team create review-squad pipeline coder:implement,researcher:review\n /team run review-squad Build a rate limiter in TypeScript` };\n\n default:\n return { handled: true, output: pc.yellow(`Unknown team action: ${action}. Try /team help`) };\n }\n}\n\n// --- Delegation ---\n\nasync function handleDelegateCommand(action: string | undefined, args: string[], ctx: CommandContext): Promise<CommandResult> {\n if (!action) {\n return { handled: true, output: `Delegate commands:\n /delegate <profile> <task> Delegate a task to a local profile\n /delegate @<name> <task> Delegate to another running aman-agent (A2A)\n /delegate pipeline <p1> <p2> ... Run a sequential pipeline\n /delegate help Show help\n\nExamples:\n /delegate writer Write a blog post about AI companions\n /delegate coder Review this code for security issues\n /delegate @reviewer Review PR #42 for security issues\n /delegate pipeline writer,researcher Write and fact-check an article about quantum computing` };\n }\n\n if (action === \"help\") {\n return { handled: true, output: `Delegate a task to a sub-agent with a specific profile.\n\nThe sub-agent runs with its own identity, rules, and skills but shares\nyour memory and tools. Results come back to you.\n\nUsage:\n /delegate <profile> <task> Local sub-agent with named profile\n /delegate @<name> <task> Remote aman-agent (A2A via MCP)\n /delegate pipeline <profile1>,<profile2> <task>\n\nUse /agents list to see which remote agents are running.\n\nThe pipeline mode passes each agent's output to the next:\n writer drafts → researcher reviews → writer polishes` };\n }\n\n if (!ctx.llmClient || !ctx.mcpManager) {\n return { handled: true, output: pc.red(\"Delegation requires LLM client and MCP. Not available.\") };\n }\n\n if (action === \"pipeline\") {\n // /delegate pipeline writer,researcher,writer Write an article about AI\n const profileList = args[0];\n const task = args.slice(1).join(\" \");\n if (!profileList || !task) {\n return { handled: true, output: pc.yellow(\"Usage: /delegate pipeline <profile1>,<profile2> <task>\") };\n }\n\n const profiles = profileList.split(\",\").map((p) => p.trim());\n const steps = profiles.map((profile, i) => {\n if (i === 0) {\n return { profile, taskTemplate: task };\n }\n return { profile, taskTemplate: `Review and improve the following:\\n\\n{{input}}` };\n });\n\n process.stdout.write(pc.dim(`\\n Pipeline: ${profiles.join(\" → \")}\\n`));\n\n const results = await delegatePipeline(steps, task, ctx.llmClient, ctx.mcpManager, { tools: ctx.tools });\n\n const output: string[] = [];\n for (const r of results) {\n if (r.success) {\n output.push(`\\n${pc.bold(`[${r.profile}]`)} ${pc.green(\"✓\")} (${r.turns} tool turns)`);\n output.push(r.response.slice(0, 2000));\n if (r.toolsUsed.length > 0) output.push(pc.dim(` Tools: ${r.toolsUsed.join(\", \")}`));\n } else {\n output.push(`\\n${pc.bold(`[${r.profile}]`)} ${pc.red(\"✗\")} ${r.error}`);\n }\n }\n\n return { handled: true, output: output.join(\"\\n\") };\n }\n\n // /delegate <profile> <task>\n const profile = action;\n const task = args.join(\" \");\n if (!task) {\n return { handled: true, output: pc.yellow(`Usage: /delegate ${profile} <task description>`) };\n }\n\n process.stdout.write(pc.dim(`\\n [delegating to ${profile}...]\\n\\n`));\n\n const result = await delegateTask(task, profile, ctx.llmClient, ctx.mcpManager, { tools: ctx.tools });\n\n if (!result.success) {\n return { handled: true, output: pc.red(`Delegation failed: ${result.error}`) };\n }\n\n const meta: string[] = [];\n if (result.toolsUsed.length > 0) meta.push(`Tools: ${result.toolsUsed.join(\", \")}`);\n if (result.turns > 0) meta.push(`${result.turns} tool turns`);\n\n return {\n handled: true,\n output: `\\n${pc.bold(`[${profile}]`)} ${pc.green(\"✓\")}${meta.length > 0 ? \" \" + pc.dim(`(${meta.join(\", \")})`) : \"\"}\\n\\n${result.response}`,\n };\n}\n\n// --- Agents (A2A discovery + health) ---\n\nasync function handleAgentsCommand(\n action: string | undefined,\n args: string[],\n): Promise<CommandResult> {\n const sub = action ?? \"list\";\n\n if (sub === \"list\") {\n const all = await listAgents();\n if (all.length === 0) {\n return { handled: true, output: \"No agents running.\" };\n }\n const rows = all.map((a) => {\n const uptime = Math.round((Date.now() - a.started_at) / 1000);\n return ` @${a.name.padEnd(12)} ${a.profile.padEnd(12)} pid=${String(a.pid).padEnd(6)} port=${a.port} up ${uptime}s`;\n });\n return { handled: true, output: [\"Running agents:\", ...rows].join(\"\\n\") };\n }\n\n if (sub === \"info\") {\n const name = args[0];\n if (!name) {\n return { handled: true, output: pc.yellow(\"Usage: /agents info <name>\") };\n }\n const entry = await findAgent(name);\n if (!entry) {\n return { handled: true, output: `No such agent: ${name}` };\n }\n const url = new URL(`http://127.0.0.1:${entry.port}/mcp`);\n const transport = new StreamableHTTPClientTransport(url, {\n requestInit: { headers: { Authorization: `Bearer ${entry.token}` } },\n });\n const client = new Client({ name: \"aman-agent-cli\", version: \"0.1.0\" });\n try {\n await client.connect(transport);\n const res = await client.callTool({ name: \"agent.info\", arguments: {} });\n const text = Array.isArray(res.content)\n ? (res.content as Array<{ type: string; text?: string }>)\n .filter((c) => c.type === \"text\")\n .map((c) => c.text ?? \"\")\n .join(\"\")\n : \"\";\n return { handled: true, output: `@${entry.name}:\\n${text}` };\n } catch (err) {\n return {\n handled: true,\n output: pc.red(\n `Error calling @${name}: ${err instanceof Error ? err.message : String(err)}`,\n ),\n };\n } finally {\n try {\n await client.close();\n } catch {\n /* best effort */\n }\n }\n }\n\n if (sub === \"ping\") {\n const name = args[0];\n if (!name) {\n return { handled: true, output: pc.yellow(\"Usage: /agents ping <name>\") };\n }\n const entry = await findAgent(name);\n if (!entry) {\n return { handled: true, output: `No such agent: ${name}` };\n }\n const t0 = Date.now();\n try {\n const res = await fetch(`http://127.0.0.1:${entry.port}/health`, {\n headers: { Authorization: `Bearer ${entry.token}` },\n });\n if (!res.ok) {\n return { handled: true, output: `@${name}: HTTP ${res.status}` };\n }\n return { handled: true, output: `@${name}: ok (${Date.now() - t0}ms)` };\n } catch (err) {\n return {\n handled: true,\n output: `@${name}: ${err instanceof Error ? err.message : String(err)}`,\n };\n }\n }\n\n return {\n handled: true,\n output: pc.yellow(\"Usage: /agents [list|info <name>|ping <name>]\"),\n };\n}\n\n// --- Profile management ---\n\nfunction handleProfileCommand(action: string | undefined, args: string[]): CommandResult {\n const profilesDir = path.join(os.homedir(), \".acore\", \"profiles\");\n\n // User identity commands (separate from AI agent profiles)\n if (action === \"me\") {\n const user = loadUserIdentity();\n if (!user) {\n return { handled: true, output: pc.dim(\"No user profile yet. Run /profile edit to set one up.\") };\n }\n const lines = [\n ` ${pc.bold(\"Name:\")} ${user.name}`,\n ` ${pc.bold(\"Role:\")} ${user.roleLabel}`,\n ` ${pc.bold(\"Expertise:\")} ${user.expertiseLabel}`,\n ` ${pc.bold(\"Style:\")} ${user.styleLabel}`,\n ];\n if (user.workingOn) lines.push(` ${pc.bold(\"Working on:\")} ${user.workingOn}`);\n if (user.notes) lines.push(` ${pc.bold(\"Notes:\")} ${user.notes}`);\n lines.push(` ${pc.dim(`Updated: ${user.updatedAt}`)}`);\n return { handled: true, output: `Your profile:\\n${lines.join(\"\\n\")}\\n\\n${pc.dim(\"Edit with: /profile edit\")}` };\n }\n\n if (action === \"edit\") {\n const current = loadUserIdentity();\n if (!current) {\n // No profile yet — run full onboarding\n runOnboarding().then(() => {}).catch(() => {});\n return { handled: true, output: \"\" }; // onboarding handles its own output\n }\n // Edit existing profile\n editProfile(current).then(() => {}).catch(() => {});\n return { handled: true, output: \"\" }; // editProfile handles its own output\n }\n\n if (action === \"setup\") {\n // Force re-run full onboarding\n runOnboarding().then(() => {}).catch(() => {});\n return { handled: true, output: \"\" };\n }\n\n if (!action || action === \"list\") {\n const profiles = listProfiles();\n const user = loadUserIdentity();\n const userLine = user\n ? `${pc.bold(\"You:\")} ${user.name} (${user.roleLabel}, ${user.expertiseLabel})\\n\\n`\n : `${pc.dim(\"No user profile. Set up with: /profile edit\")}\\n\\n`;\n\n if (profiles.length === 0) {\n return { handled: true, output: userLine + pc.dim(\"No agent profiles yet. Create one with: /profile create <name>\") };\n }\n const lines = profiles.map((p) =>\n ` ${pc.bold(p.name)} — ${p.aiName} (${pc.dim(p.personality)})`\n );\n return { handled: true, output: userLine + \"Agent profiles:\\n\" + lines.join(\"\\n\") + \"\\n\\n\" + pc.dim(\"Switch with: aman-agent --profile <name>\") };\n }\n\n switch (action) {\n case \"create\": {\n const name = args[0];\n if (!name) {\n // Show available templates\n const lines = BUILT_IN_PROFILES.map((t) =>\n ` ${pc.bold(t.name)} — ${t.label}: ${pc.dim(t.description)}`\n );\n return {\n handled: true,\n output: \"Built-in profiles:\\n\" + lines.join(\"\\n\") +\n \"\\n\\nUsage:\\n /profile create coder Install built-in template\" +\n \"\\n /profile create <custom> Create blank profile\",\n };\n }\n\n const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, \"-\");\n const profileDir = path.join(profilesDir, slug);\n\n if (fs.existsSync(profileDir)) {\n return { handled: true, output: pc.yellow(`Profile already exists: ${slug}`) };\n }\n\n // Check if it's a built-in template\n const builtIn = BUILT_IN_PROFILES.find((t) => t.name === slug);\n if (builtIn) {\n const err = installProfileTemplate(slug);\n if (err) return { handled: true, output: pc.red(err) };\n return {\n handled: true,\n output: pc.green(`Profile installed: ${builtIn.label}`) +\n `\\n AI name: ${builtIn.core.match(/^# (.+)/m)?.[1] || slug}` +\n `\\n ${pc.dim(builtIn.description)}` +\n `\\n\\n Use: aman-agent --profile ${slug}`,\n };\n }\n\n // Custom profile — create from default\n fs.mkdirSync(profileDir, { recursive: true });\n const globalCore = path.join(os.homedir(), \".acore\", \"core.md\");\n if (fs.existsSync(globalCore)) {\n let content = fs.readFileSync(globalCore, \"utf-8\");\n const aiName = name.charAt(0).toUpperCase() + name.slice(1);\n content = content.replace(/^# .+$/m, `# ${aiName}`);\n fs.writeFileSync(path.join(profileDir, \"core.md\"), content, \"utf-8\");\n } else {\n const aiName = name.charAt(0).toUpperCase() + name.slice(1);\n fs.writeFileSync(path.join(profileDir, \"core.md\"), `# ${aiName}\\n\\n## Identity\\n- Role: ${aiName} is your AI companion\\n- Personality: helpful, adaptive\\n- Communication: clear and concise\\n- Values: honesty, simplicity\\n- Boundaries: won't pretend to be human\\n`, \"utf-8\");\n }\n\n return {\n handled: true,\n output: pc.green(`Profile created: ${slug}`) +\n `\\n Edit: ${path.join(profileDir, \"core.md\")}` +\n `\\n Use: aman-agent --profile ${slug}` +\n `\\n\\n ${pc.dim(\"Add rules.md or skills.md for profile-specific overrides.\")}`,\n };\n }\n\n case \"show\": {\n const name = args[0];\n if (!name) return { handled: true, output: pc.yellow(\"Usage: /profile show <name>\") };\n const profileDir = path.join(profilesDir, name);\n if (!fs.existsSync(profileDir)) return { handled: true, output: pc.red(`Profile not found: ${name}`) };\n\n const files = fs.readdirSync(profileDir).filter((f) => f.endsWith(\".md\"));\n const lines = files.map((f) => ` ${f}`);\n return { handled: true, output: `Profile: ${pc.bold(name)}\\nFiles:\\n${lines.join(\"\\n\")}` };\n }\n\n case \"delete\": {\n const name = args[0];\n if (!name) return { handled: true, output: pc.yellow(\"Usage: /profile delete <name>\") };\n const profileDir = path.join(profilesDir, name);\n if (!fs.existsSync(profileDir)) return { handled: true, output: pc.red(`Profile not found: ${name}`) };\n\n fs.rmSync(profileDir, { recursive: true });\n return { handled: true, output: pc.dim(`Profile deleted: ${name}`) };\n }\n\n case \"help\":\n return { handled: true, output: `Profile commands:\n\n ${pc.bold(\"Your profile:\")}\n /profile me View your profile\n /profile edit Edit your profile\n /profile setup Re-run full profile setup\n\n ${pc.bold(\"Agent profiles:\")}\n /profile List all profiles\n /profile create <n> Create new agent profile\n /profile show <n> Show agent profile files\n /profile delete <n> Delete an agent profile\n\n ${pc.bold(\"Use agent profiles:\")}\n aman-agent --profile <name>\n AMAN_PROFILE=<name> aman-agent` };\n\n default:\n return { handled: true, output: pc.yellow(`Unknown profile action: ${action}. Try /profile help`) };\n }\n}\n\n// --- Plan management ---\n\nfunction handlePlanCommand(action: string | undefined, args: string[], ctx?: CommandContext): CommandResult {\n if (!action) {\n // /plan — show active plan\n const active = getActivePlan();\n if (!active) {\n return { handled: true, output: pc.dim(\"No active plan. Create one with: /plan create <name> | <goal> | <step1>, <step2>, ...\") };\n }\n return { handled: true, output: formatPlan(active) };\n }\n\n switch (action) {\n case \"create\": {\n // /plan create <name> | <goal> | <step1>, <step2>, ...\n const fullArgs = args.join(\" \");\n const parts = fullArgs.split(\"|\").map((p) => p.trim());\n if (parts.length < 3) {\n return { handled: true, output: pc.yellow(\"Usage: /plan create <name> | <goal> | <step1>, <step2>, ...\") };\n }\n const name = parts[0];\n const goal = parts[1];\n const steps = parts[2].split(\",\").map((s) => s.trim()).filter(Boolean);\n if (steps.length === 0) {\n return { handled: true, output: pc.yellow(\"Need at least one step. Separate steps with commas.\") };\n }\n const plan = createPlan(name, goal, steps);\n return { handled: true, output: pc.green(`Plan created!\\n\\n`) + formatPlan(plan) };\n }\n\n case \"done\": {\n // /plan done [step number]\n const active = getActivePlan();\n if (!active) return { handled: true, output: pc.yellow(\"No active plan.\") };\n\n const recordPlanMilestone = (stepIndex: number) => {\n if (ctx?.observationSession) {\n const step = active.steps[stepIndex];\n recordEvent(ctx.observationSession, {\n type: \"milestone\",\n summary: `Plan step done: ${step.text}`,\n data: { plan: active.name, stepIndex, stepText: step.text },\n });\n }\n };\n\n if (args.length > 0) {\n const stepNum = parseInt(args[0], 10);\n if (isNaN(stepNum) || stepNum < 1 || stepNum > active.steps.length) {\n return { handled: true, output: pc.yellow(`Invalid step number. Range: 1-${active.steps.length}`) };\n }\n markStepDone(active, stepNum - 1);\n recordPlanMilestone(stepNum - 1);\n return { handled: true, output: pc.green(`Step ${stepNum} done!`) + \"\\n\\n\" + formatPlan(active) };\n }\n\n // No step specified — mark next incomplete step\n const next = active.steps.findIndex((s) => !s.done);\n if (next < 0) return { handled: true, output: pc.green(\"All steps already complete!\") };\n markStepDone(active, next);\n recordPlanMilestone(next);\n return { handled: true, output: pc.green(`Step ${next + 1} done!`) + \"\\n\\n\" + formatPlan(active) };\n }\n\n case \"undo\": {\n // /plan undo <step number>\n const active = getActivePlan();\n if (!active) return { handled: true, output: pc.yellow(\"No active plan.\") };\n const stepNum = parseInt(args[0], 10);\n if (isNaN(stepNum) || stepNum < 1 || stepNum > active.steps.length) {\n return { handled: true, output: pc.yellow(`Invalid step number. Range: 1-${active.steps.length}`) };\n }\n markStepUndone(active, stepNum - 1);\n return { handled: true, output: pc.dim(`Step ${stepNum} unmarked.`) + \"\\n\\n\" + formatPlan(active) };\n }\n\n case \"list\": {\n // /plan list — show all plans\n const plans = listPlans();\n if (plans.length === 0) return { handled: true, output: pc.dim(\"No plans yet.\") };\n const lines = plans.map((p) => {\n const done = p.steps.filter((s) => s.done).length;\n const total = p.steps.length;\n const status = p.active ? pc.green(\"active\") : pc.dim(\"inactive\");\n return ` ${p.name} — ${done}/${total} steps (${status})`;\n });\n return { handled: true, output: \"Plans:\\n\" + lines.join(\"\\n\") };\n }\n\n case \"switch\": {\n // /plan switch <name>\n const name = args.join(\" \");\n if (!name) return { handled: true, output: pc.yellow(\"Usage: /plan switch <name>\") };\n const plan = setActivePlan(name);\n if (!plan) return { handled: true, output: pc.red(`Plan not found: ${name}`) };\n return { handled: true, output: pc.green(`Switched to: ${plan.name}`) + \"\\n\\n\" + formatPlan(plan) };\n }\n\n case \"show\": {\n // /plan show <name>\n const name = args.join(\" \");\n if (!name) return { handled: true, output: pc.yellow(\"Usage: /plan show <name>\") };\n const plan = loadPlan(name);\n if (!plan) return { handled: true, output: pc.red(`Plan not found: ${name}`) };\n return { handled: true, output: formatPlan(plan) };\n }\n\n case \"help\":\n return { handled: true, output: `Plan commands:\n /plan Show active plan\n /plan create <name> | <goal> | <step1>, <step2>, ...\n /plan done [step#] Mark step complete (next if no number)\n /plan undo <step#> Unmark a step\n /plan list List all plans\n /plan switch <name> Switch active plan\n /plan show <name> Show a specific plan` };\n\n default:\n return { handled: true, output: pc.yellow(`Unknown plan action: ${action}. Try /plan help`) };\n }\n}\n\nasync function handleReminderCommand(\n action: string | undefined,\n args: string[],\n): Promise<CommandResult> {\n if (!action || action === \"list\") {\n try {\n const reminders = reminderList();\n if (reminders.length === 0) return { handled: true, output: pc.dim(\"No reminders.\") };\n const lines: string[] = [pc.bold(`Reminders (${reminders.length}):`), \"\"];\n for (const r of reminders) {\n const status = r.completed ? pc.green(\"[done]\") : pc.yellow(\"[todo]\");\n const due = r.dueAt ? ` ${pc.dim(`due: ${new Date(r.dueAt).toLocaleString()}`)}` : \"\";\n lines.push(` ${status} ${r.content}${due} ${pc.dim(`(${r.id.slice(0, 8)})`)}`);\n }\n return { handled: true, output: lines.join(\"\\n\") };\n } catch (err) {\n return { handled: true, output: pc.red(`Reminder error: ${err instanceof Error ? err.message : String(err)}`) };\n }\n }\n\n if (action === \"set\" || action === \"add\") {\n if (args.length === 0) return { handled: true, output: pc.yellow(\"Usage: /reminder set <text> [--due <time>]\\n Time formats: 1h, 2d, 1w, or ISO date (2026-04-10)\") };\n // Parse --due flag\n let dueAt: number | undefined;\n const dueIdx = args.indexOf(\"--due\");\n let contentArgs = args;\n if (dueIdx >= 0 && args[dueIdx + 1]) {\n const dueStr = args[dueIdx + 1];\n contentArgs = [...args.slice(0, dueIdx), ...args.slice(dueIdx + 2)];\n // Parse relative time: 1h, 2d, 1w\n const relMatch = dueStr.match(/^(\\d+)(h|d|w)$/);\n if (relMatch) {\n const num = parseInt(relMatch[1], 10);\n const unit = relMatch[2];\n const ms = unit === \"h\" ? num * 3600000 : unit === \"d\" ? num * 86400000 : num * 604800000;\n dueAt = Date.now() + ms;\n } else {\n // Try ISO date\n const parsed = Date.parse(dueStr);\n if (!isNaN(parsed)) dueAt = parsed;\n }\n }\n const content = contentArgs.join(\" \");\n if (!content) return { handled: true, output: pc.yellow(\"Usage: /reminder set <text> [--due <time>]\") };\n try {\n const id = reminderSet(content, dueAt);\n const dueInfo = dueAt ? ` (due: ${new Date(dueAt).toLocaleDateString()})` : \"\";\n return { handled: true, output: pc.green(`Reminder set: \"${content}\"${dueInfo} (ID: ${id.slice(0, 8)})`) };\n } catch (err) {\n return { handled: true, output: pc.red(`Reminder error: ${err instanceof Error ? err.message : String(err)}`) };\n }\n }\n\n if (action === \"done\" || action === \"complete\") {\n if (!args[0]) return { handled: true, output: pc.yellow(\"Usage: /reminder done <id>\") };\n try {\n const result = reminderComplete(args[0]);\n return { handled: true, output: result ? pc.green(\"Reminder completed.\") : pc.yellow(\"Reminder not found.\") };\n } catch (err) {\n return { handled: true, output: pc.red(`Reminder error: ${err instanceof Error ? err.message : String(err)}`) };\n }\n }\n\n if (action === \"check\") {\n try {\n const reminders = reminderCheck();\n if (reminders.length === 0) return { handled: true, output: pc.dim(\"No pending reminders.\") };\n const lines: string[] = [pc.bold(\"Pending Reminders:\"), \"\"];\n for (const r of reminders) {\n const icon = r.status === \"overdue\" ? pc.red(\"!!!\") : r.status === \"today\" ? pc.yellow(\"(!)\") : pc.dim(\"( )\");\n const due = r.dueAt ? ` ${pc.dim(`due: ${new Date(r.dueAt).toLocaleString()}`)}` : \"\";\n lines.push(` ${icon} ${r.content}${due} ${pc.dim(`[${r.status}]`)}`);\n }\n return { handled: true, output: lines.join(\"\\n\") };\n } catch (err) {\n return { handled: true, output: pc.red(`Reminder error: ${err instanceof Error ? err.message : String(err)}`) };\n }\n }\n\n if (action === \"help\") {\n return { handled: true, output: [\n pc.bold(\"Reminder commands:\"),\n ` ${pc.cyan(\"/reminder\")} List all reminders`,\n ` ${pc.cyan(\"/reminder set\")} <text> Create a reminder [--due 1h|2d|1w|date]`,\n ` ${pc.cyan(\"/reminder check\")} Show overdue/upcoming`,\n ` ${pc.cyan(\"/reminder done\")} <id> Mark as completed`,\n ].join(\"\\n\") };\n }\n\n return { handled: true, output: pc.yellow(`Unknown action: /reminder ${action}. Try /reminder --help`) };\n}\n\n// --- Showcase templates ---\n\nfunction handleShowcaseCommand(action: string | undefined, args: string[]): CommandResult {\n const showcases = loadShowcaseManifest();\n\n if (showcases.length === 0) {\n return {\n handled: true,\n output: pc.dim(\"No showcase templates found.\") +\n \"\\n\\n Install aman-showcase to get 13 pre-built companion personalities:\" +\n `\\n ${pc.bold(\"npm install -g @aman_asmuei/aman-showcase\")}` +\n \"\\n Or place it as a sibling directory to aman-agent.\",\n };\n }\n\n // Detect current showcase from core.md\n const corePath = path.join(os.homedir(), \".acore\", \"core.md\");\n let currentShowcase: string | null = null;\n if (fs.existsSync(corePath)) {\n const content = fs.readFileSync(corePath, \"utf-8\");\n const nameMatch = content.match(/^# (.+)/m);\n if (nameMatch) {\n const coreName = nameMatch[1].trim().toLowerCase();\n const match = showcases.find((s) => coreName.includes(s.name) || coreName.includes(s.title.split(\"—\")[0].trim().toLowerCase()));\n if (match) currentShowcase = match.name;\n }\n }\n\n if (!action || action === \"list\") {\n const lines = showcases.map((s) => {\n const active = s.name === currentShowcase ? pc.green(\" ← active\") : \"\";\n const langBadge = s.language === \"ms\" ? \" [BM]\" : s.language === \"en+ms\" ? \" [EN/BM]\" : \"\";\n return ` ${pc.bold(s.name.padEnd(12))} ${s.title}${langBadge}${active}`;\n });\n const currentLine = currentShowcase\n ? `\\nCurrent: ${pc.bold(currentShowcase)}\\n`\n : `\\nNo showcase active (using default personality)\\n`;\n return {\n handled: true,\n output: `Showcase templates (${showcases.length}):\\n\\n${lines.join(\"\\n\")}\\n${currentLine}\\n${pc.dim(\"Switch with: /showcase install <name>\")}`,\n };\n }\n\n if (action === \"install\" || action === \"switch\" || action === \"use\") {\n const name = args[0];\n if (!name) {\n return { handled: true, output: pc.yellow(\"Usage: /showcase install <name>\\n\\nRun /showcase list to see available templates.\") };\n }\n\n const entry = showcases.find((s) => s.name === name);\n if (!entry) {\n return { handled: true, output: pc.red(`Showcase not found: ${name}`) + `\\n\\nAvailable: ${showcases.map((s) => s.name).join(\", \")}` };\n }\n\n if (name === currentShowcase) {\n return { handled: true, output: pc.dim(`${entry.title} is already active.`) };\n }\n\n try {\n const result = installShowcaseTemplate(name);\n const lines = [pc.green(`Installed ${pc.bold(entry.title)}`)];\n for (const f of result.installed) {\n lines.push(pc.dim(` ${f}`));\n }\n if (result.backed_up.length > 0) {\n lines.push(pc.dim(`\\n Backed up ${result.backed_up.length} existing file(s) (.bak)`));\n }\n lines.push(\"\");\n lines.push(pc.yellow(\"Restart aman-agent to use the new personality.\"));\n lines.push(pc.dim(\"Your user profile (/profile me) is unchanged — only the AI personality switched.\"));\n return { handled: true, output: lines.join(\"\\n\") };\n } catch (err) {\n return { handled: true, output: pc.red(`Failed to install: ${err instanceof Error ? err.message : String(err)}`) };\n }\n }\n\n if (action === \"current\") {\n if (currentShowcase) {\n const entry = showcases.find((s) => s.name === currentShowcase);\n return { handled: true, output: `Active showcase: ${pc.bold(entry?.title || currentShowcase)}\\n${pc.dim(entry?.description || \"\")}` };\n }\n return { handled: true, output: pc.dim(\"No showcase active — using default personality.\") + `\\n${pc.dim(\"Install one with: /showcase install <name>\")}` };\n }\n\n if (action === \"help\") {\n return { handled: true, output: `Showcase commands:\n\n /showcase List all available templates\n /showcase install <n> Install/switch to a template\n /showcase current Show active template\n\n${pc.dim(\"Showcase templates replace your AI's personality, workflows, rules, and skills.\")}\n${pc.dim(\"Your user profile (/profile me) stays unchanged — only the AI personality switches.\")}\n${pc.dim(\"Existing files are backed up (.bak) before overwriting.\")}` };\n }\n\n return { handled: true, output: pc.yellow(`Unknown action: /showcase ${action}. Try /showcase help`) };\n}\n\nasync function handleFileCommand(\n action: string | undefined,\n args: string[],\n): Promise<CommandResult> {\n if (!action) {\n return {\n handled: true,\n output: [\n pc.bold(\"File commands:\"),\n ` ${pc.cyan(\"/file read\")} <path> Read a text file (max 50 KB)`,\n ` ${pc.cyan(\"/file convert\")} <path> Attempt to read binary file as text`,\n ` ${pc.cyan(\"/file list\")} <path> [--recursive] List directory contents`,\n ].join(\"\\n\"),\n };\n }\n\n if (action === \"read\" || action === \"convert\") {\n const filePath = args[0];\n if (!filePath) {\n return { handled: true, output: pc.yellow(`Usage: /file ${action} <path>`) };\n }\n try {\n const result = await readFile(filePath);\n const lines: string[] = [\n pc.bold(`📄 ${result.path}`) + pc.dim(` (${(result.size / 1024).toFixed(1)} KB)`),\n \"\",\n result.content,\n ];\n if (result.truncated) {\n lines.push(\"\", pc.yellow(`⚠ File truncated at 50 KB. Use a text editor for the full file.`));\n }\n return { handled: true, output: lines.join(\"\\n\") };\n } catch (err) {\n return { handled: true, output: pc.red(`File error: ${err instanceof Error ? err.message : String(err)}`) };\n }\n }\n\n if (action === \"list\") {\n const dirPath = args.find((a) => !a.startsWith(\"-\"));\n if (!dirPath) {\n return { handled: true, output: pc.yellow(`Usage: /file list <path> [--recursive]`) };\n }\n const recursive = args.includes(\"--recursive\") || args.includes(\"-r\");\n try {\n const result = await listFiles(dirPath, { recursive });\n const lines: string[] = [\n pc.bold(`📁 ${result.path}`) + pc.dim(` (${result.total} items)`),\n \"\",\n ];\n for (const entry of result.entries) {\n if (entry.type === \"dir\") {\n lines.push(` ${pc.cyan(entry.name + \"/\")}`);\n } else {\n const kb = entry.size > 0 ? pc.dim(` ${(entry.size / 1024).toFixed(1)} KB`) : \"\";\n lines.push(` ${entry.name}${kb}`);\n }\n }\n return { handled: true, output: lines.join(\"\\n\") };\n } catch (err) {\n return { handled: true, output: pc.red(`File error: ${err instanceof Error ? err.message : String(err)}`) };\n }\n }\n\n return { handled: true, output: pc.yellow(`Unknown /file subcommand: ${action}. Try /file for help.`) };\n}\n\nasync function handleOrchestrateCommand(\n action: string | undefined,\n args: string[],\n ctx: CommandContext,\n): Promise<CommandResult> {\n if (!action) {\n return {\n handled: true,\n output: [\n \"Usage: /orchestrate <requirement>\",\n \"\",\n \"Decomposes a requirement into a task DAG and executes it with parallel agents.\",\n \"Auto-detects project type, selects template, runs policy check, and tracks cost.\",\n \"\",\n \"Options (pass as first arg):\",\n \" --template <name> Force a template (full-feature, bug-fix, security-audit)\",\n \" --no-review Skip self-review loop\",\n \" --no-policy Skip policy check\",\n \"\",\n \"Alias: /orch\",\n ].join(\"\\n\"),\n };\n }\n\n if (!ctx.llmClient) {\n return { handled: true, output: pc.red(\"Orchestration requires an LLM client. Not available.\") };\n }\n\n // Parse flags\n let templateName: string | undefined;\n let enableSelfReview = true;\n let enablePolicyCheck = true;\n const filtered: string[] = [];\n\n const allArgs = [action, ...args];\n for (let i = 0; i < allArgs.length; i++) {\n if (allArgs[i] === \"--template\" && allArgs[i + 1]) {\n templateName = allArgs[++i];\n } else if (allArgs[i] === \"--no-review\") {\n enableSelfReview = false;\n } else if (allArgs[i] === \"--no-policy\") {\n enablePolicyCheck = false;\n } else {\n filtered.push(allArgs[i]);\n }\n }\n\n const requirement = filtered.join(\" \");\n if (!requirement.trim()) {\n return { handled: true, output: pc.red(\"Please provide a requirement to orchestrate.\") };\n }\n\n try {\n const router = createModelRouter({ standard: ctx.llmClient });\n const result = await smartOrchestrate({\n requirement,\n client: ctx.llmClient,\n router,\n projectPath: process.cwd(),\n templateName,\n enablePolicyCheck,\n enableSelfReview,\n enableCostTracking: true,\n });\n\n return { handled: true, output: result.summary };\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n return { handled: true, output: pc.red(`Orchestration failed: ${msg}`) };\n }\n}\n\nasync function handleGitHubCommand(\n action: string | undefined,\n args: string[],\n ctx: CommandContext,\n): Promise<CommandResult> {\n // No subcommand → show repo info\n if (!action) {\n const available = await ghAvailable();\n if (!available) {\n return { handled: true, output: pc.red(\"GitHub CLI (gh) is not available or not authenticated. Run: gh auth login\") };\n }\n const repo = await ghCurrentRepo();\n if (!repo) {\n return { handled: true, output: pc.yellow(\"Not inside a GitHub repository.\") };\n }\n return { handled: true, output: `GitHub repo: ${pc.bold(`${repo.owner}/${repo.name}`)}` };\n }\n\n switch (action) {\n case \"issues\": {\n // Quick issue list via gh CLI\n const { gh: ghExec } = await import(\"./github/index.js\");\n const repoArgs = args.length > 0 ? [\"--repo\", args[0]] : [];\n const result = await ghExec([\"issue\", \"list\", \"--limit\", \"10\", ...repoArgs]);\n if (!result.success) {\n return { handled: true, output: pc.red(`Failed to list issues: ${result.stderr}`) };\n }\n return { handled: true, output: result.stdout.trim() || pc.dim(\"No open issues.\") };\n }\n\n case \"prs\": {\n const repoArgs: { repo?: string } = args.length > 0 ? { repo: args[0] } : {};\n try {\n const prs = await listPRs({ state: \"open\", limit: 10, ...repoArgs });\n if (prs.length === 0) {\n return { handled: true, output: pc.dim(\"No open PRs.\") };\n }\n const lines = prs.map(\n (pr) => `#${pr.number} ${pr.title} (${pr.headRefName} → ${pr.baseRefName})${pr.isDraft ? \" [draft]\" : \"\"}`,\n );\n return { handled: true, output: lines.join(\"\\n\") };\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n return { handled: true, output: pc.red(`Failed to list PRs: ${msg}`) };\n }\n }\n\n case \"plan\": {\n const issueNum = parseInt(args[0], 10);\n if (!issueNum || isNaN(issueNum)) {\n return { handled: true, output: pc.red(\"Usage: /github plan <issue-number>\") };\n }\n if (!ctx.llmClient) {\n return { handled: true, output: pc.red(\"Planning requires an LLM client. Not available.\") };\n }\n try {\n const issue = await fetchIssue(issueNum);\n const requirement = formatIssueAsRequirement(issue);\n const router = createModelRouter({ standard: ctx.llmClient });\n const result = await smartOrchestrate({\n requirement,\n client: ctx.llmClient,\n router,\n projectPath: process.cwd(),\n enablePolicyCheck: true,\n enableSelfReview: false,\n enableCostTracking: true,\n });\n return {\n handled: true,\n output: `${pc.bold(`Plan for #${issue.number}: ${issue.title}`)}\\n\\n${result.summary}`,\n };\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n return { handled: true, output: pc.red(`Failed to plan issue #${issueNum}: ${msg}`) };\n }\n }\n\n case \"ci\": {\n const branch = args[0];\n if (!branch) {\n return { handled: true, output: pc.red(\"Usage: /github ci <branch>\") };\n }\n try {\n const passing = await isCIPassing(branch);\n return {\n handled: true,\n output: passing\n ? pc.green(`CI is passing on ${branch}`)\n : pc.yellow(`CI is NOT passing on ${branch}`),\n };\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n return { handled: true, output: pc.red(`Failed to check CI: ${msg}`) };\n }\n }\n\n default:\n return {\n handled: true,\n output: [\n `Usage: /github [subcommand]`,\n ``,\n `Subcommands:`,\n ` (none) Show current repo info`,\n ` issues [repo] List open issues`,\n ` prs [repo] List open PRs`,\n ` plan <number> Plan from a GitHub issue`,\n ` ci <branch> Check CI status for a branch`,\n ].join(\"\\n\"),\n };\n }\n}\n\nconst KNOWN_COMMANDS = new Set([\n \"quit\", \"exit\", \"q\", \"help\", \"clear\", \"model\", \"identity\", \"rules\",\n \"workflows\", \"tools\", \"akit\", \"skills\", \"eval\", \"memory\", \"status\", \"doctor\",\n \"save\", \"decisions\", \"export\", \"debug\", \"reset\", \"reminder\",\n \"update\", \"upgrade\", \"plan\", \"profile\", \"delegate\", \"team\", \"agents\", \"showcase\", \"file\",\n \"observe\", \"postmortem\", \"orchestrate\", \"orch\", \"github\",\n]);\n\nasync function handleObserveCommand(\n action: string | undefined,\n ctx: CommandContext,\n): Promise<CommandResult> {\n if (!ctx.observationSession) {\n return {\n handled: true,\n output: pc.dim(\"Observation is disabled. Enable with recordObservations: true in config.\"),\n };\n }\n\n switch (action) {\n case \"pause\":\n pauseObservation(ctx.observationSession);\n return { handled: true, output: pc.dim(\"Observation paused. Use /observe resume to continue.\") };\n\n case \"resume\":\n resumeObservation(ctx.observationSession);\n return { handled: true, output: pc.dim(\"Observation resumed.\") };\n\n default:\n return { handled: true, output: getSessionStats(ctx.observationSession) };\n }\n}\n\nasync function handlePostmortemCommand(\n action: string | undefined,\n args: string[],\n ctx: CommandContext,\n): Promise<CommandResult> {\n switch (action) {\n case \"last\": {\n const files = await listPostmortems();\n if (files.length === 0) return { handled: true, output: pc.dim(\"No post-mortems found.\") };\n const content = await readPostmortem(files[0]);\n return { handled: true, output: content ?? pc.red(\"Could not read post-mortem.\") };\n }\n\n case \"list\": {\n const files = await listPostmortems();\n if (files.length === 0) return { handled: true, output: pc.dim(\"No post-mortems found.\") };\n return { handled: true, output: \"Post-mortems:\\n\" + files.map((f) => ` ${f}`).join(\"\\n\") };\n }\n\n default: {\n // Check for --since flag (in either action or args position)\n const allArgs = action ? [action, ...args] : args;\n const sinceIdx = allArgs.indexOf(\"--since\");\n if (sinceIdx !== -1 && allArgs[sinceIdx + 1]) {\n const daysStr = allArgs[sinceIdx + 1];\n const days = parseInt(daysStr.replace(\"d\", \"\"), 10) || 7;\n if (!ctx.llmClient) {\n return { handled: true, output: pc.red(\"LLM client not available for analysis.\") };\n }\n const analysis = await analyzePostmortemRange(days, ctx.llmClient);\n return { handled: true, output: analysis ?? pc.red(\"Could not analyze post-mortems.\") };\n }\n\n // Generate post-mortem for current session\n if (!ctx.observationSession || !ctx.llmClient || !ctx.messages) {\n return {\n handled: true,\n output: pc.dim(\"Cannot generate post-mortem: missing session context.\"),\n };\n }\n const report = await generatePostmortemReport(\n ctx.observationSession.sessionId,\n ctx.messages,\n ctx.observationSession,\n ctx.llmClient,\n );\n if (!report) return { handled: true, output: pc.red(\"Could not generate post-mortem.\") };\n const filePath = await savePostmortem(report);\n return {\n handled: true,\n output: formatPostmortemMarkdown(report) + `\\n\\n${pc.dim(`Saved → ${filePath}`)}`,\n };\n }\n }\n}\n\nexport async function handleCommand(input: string, ctx: CommandContext): Promise<CommandResult> {\n const trimmed = input.trim();\n if (!trimmed.startsWith(\"/\")) return { handled: false };\n\n const { base, action, args } = parseCommand(trimmed);\n\n // Don't treat file paths (e.g., /Users/...) as commands\n if (!KNOWN_COMMANDS.has(base)) return { handled: false };\n\n switch (base) {\n case \"quit\":\n case \"exit\":\n case \"q\":\n return { handled: true, quit: true };\n case \"help\":\n return handleHelp();\n case \"clear\":\n return { handled: true, output: pc.dim(\"Conversation cleared.\"), clearHistory: true };\n case \"model\":\n return { handled: true, output: ctx.model ? `Model: ${pc.bold(ctx.model)}` : \"Model: unknown\" };\n case \"identity\":\n return handleIdentityCommand(action, args, ctx);\n case \"rules\":\n return handleRulesCommand(action, args, ctx);\n case \"workflows\":\n return handleWorkflowsCommand(action, args, ctx);\n case \"tools\":\n return handleToolsCommand(action, args, ctx);\n case \"akit\":\n return handleAkitCommand(action, args);\n case \"skills\":\n return handleSkillsCommand(action, args, ctx);\n case \"eval\":\n return handleEvalCommand(action, args, ctx);\n case \"memory\":\n return handleMemoryCommand(action, args, ctx);\n case \"status\":\n return handleStatusCommand(ctx);\n case \"doctor\":\n return handleDoctorCommand(ctx);\n case \"save\":\n return handleSave();\n case \"decisions\":\n return handleDecisionsCommand(action, args, ctx);\n case \"export\":\n return handleExportCommand();\n case \"debug\":\n return handleDebugCommand();\n case \"reset\":\n return handleReset(action);\n case \"plan\":\n return handlePlanCommand(action, args, ctx);\n case \"profile\":\n return handleProfileCommand(action, args);\n case \"delegate\":\n return handleDelegateCommand(action, args, ctx);\n case \"team\":\n return handleTeamCommand(action, args, ctx);\n case \"agents\":\n return handleAgentsCommand(action, args);\n case \"reminder\":\n return handleReminderCommand(action, args);\n case \"showcase\":\n return handleShowcaseCommand(action, args);\n case \"file\":\n return handleFileCommand(action, args);\n case \"update\":\n case \"upgrade\":\n return handleUpdate();\n case \"observe\":\n return handleObserveCommand(action, ctx);\n case \"postmortem\":\n return handlePostmortemCommand(action, args, ctx);\n case \"orchestrate\":\n case \"orch\":\n return handleOrchestrateCommand(action, args, ctx);\n case \"github\":\n return handleGitHubCommand(action, args, ctx);\n default:\n return { handled: false }; // Pass to LLM if not matched\n }\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport os from \"node:os\";\n\nconst home = os.homedir();\n\ninterface LayerStatus {\n name: string;\n exists: boolean;\n path: string;\n summary: string;\n}\n\nexport interface EcosystemStatus {\n layers: LayerStatus[];\n mcpConnected: boolean;\n mcpToolCount: number;\n amemConnected: boolean;\n}\n\nconst LAYER_FILES = [\n { name: \"identity\", dir: \".acore\", file: \"core.md\" },\n { name: \"rules\", dir: \".arules\", file: \"rules.md\" },\n { name: \"workflows\", dir: \".aflow\", file: \"flow.md\" },\n { name: \"tools\", dir: \".akit\", file: \"kit.md\" },\n { name: \"skills\", dir: \".askill\", file: \"skills.md\" },\n { name: \"eval\", dir: \".aeval\", file: \"eval.md\" },\n] as const;\n\nfunction countLines(content: string, pattern: RegExp): number {\n return (content.match(pattern) || []).length;\n}\n\nfunction getLayerSummary(name: string, content: string): string {\n switch (name) {\n case \"identity\": {\n const nameMatch = content.match(/^# (.+)/m);\n return nameMatch ? nameMatch[1] : \"configured\";\n }\n case \"rules\":\n return `${countLines(content, /^- /gm)} rules`;\n case \"workflows\":\n return `${countLines(content, /^## /gm)} workflows`;\n case \"tools\":\n return `${countLines(content, /^- \\*\\*/gm)} tools`;\n case \"skills\":\n return `${countLines(content, /^### /gm)} skills`;\n case \"eval\": {\n const sessions = countLines(content, /^### Session/gm);\n return `${sessions} sessions logged`;\n }\n default:\n return \"unknown\";\n }\n}\n\nexport function getEcosystemStatus(\n mcpToolCount: number,\n amemConnected: boolean,\n): EcosystemStatus {\n const layers: LayerStatus[] = LAYER_FILES.map((entry) => {\n const filePath = path.join(home, entry.dir, entry.file);\n const exists = fs.existsSync(filePath);\n let summary = \"not configured\";\n\n if (exists) {\n const content = fs.readFileSync(filePath, \"utf-8\");\n summary = getLayerSummary(entry.name, content);\n }\n\n return { name: entry.name, exists, path: filePath, summary };\n });\n\n return {\n layers,\n mcpConnected: mcpToolCount > 0,\n mcpToolCount,\n amemConnected,\n };\n}\n\nexport function readLayerFile(name: string): string | null {\n const entry = LAYER_FILES.find((l) => l.name === name);\n if (!entry) return null;\n const filePath = path.join(home, entry.dir, entry.file);\n if (!fs.existsSync(filePath)) return null;\n return fs.readFileSync(filePath, \"utf-8\").trim();\n}\n","import {\n createDatabase,\n recall,\n buildContext,\n storeMemory,\n consolidateMemories,\n cosineSimilarity,\n preloadEmbeddings,\n buildVectorIndex,\n recallMemories,\n generateEmbedding,\n getVectorIndex,\n runDiagnostics,\n repairDatabase,\n loadConfig,\n saveConfig,\n multiStrategyRecall,\n reflect,\n isReflectionDue,\n syncFromClaude,\n exportForTeam,\n importFromTeam,\n syncToCopilot,\n MirrorEngine,\n parseFrontmatter,\n type AmemDatabase,\n type RecallResult,\n type ContextResult,\n type StoreResult,\n type StoreOptions,\n type ConsolidationReport,\n type MemoryStats,\n type Memory,\n type MemoryVersion,\n type MemoryRelation,\n type DiagnosticReport,\n type ReflectionReport,\n type ReflectionConfig,\n type AmemConfig,\n type SyncResult,\n type TeamExportOptions,\n type TeamImportOptions,\n type TeamImportResult,\n type CopilotSyncOptions,\n type CopilotSyncResult,\n} from \"@aman_asmuei/amem-core\";\nimport { loadConfig as loadAgentConfig, homeDir, expandHome } from \"./config.js\";\n\ntype DeepPartial<T> = { [K in keyof T]?: T[K] extends object ? DeepPartial<T[K]> : T[K] };\nimport path from \"node:path\";\nimport os from \"node:os\";\nimport fs from \"node:fs\";\n\nlet db: AmemDatabase | null = null;\nlet mirrorEngine: MirrorEngine | null = null;\nlet currentProject = \"global\";\n\n/**\n * Test-only hook: reset the memory module's cached singletons so a\n * subsequent `initMemory()` call picks up a fresh DB and mirror engine.\n * Integration tests use this to exercise different configs within one file.\n */\nexport function _resetMemoryForTesting(): void {\n db = null;\n mirrorEngine = null;\n currentProject = \"global\";\n}\n\nexport async function initMemory(project?: string): Promise<AmemDatabase> {\n if (db) return db;\n\n const amemDir = process.env.AMEM_DIR ?? path.join(os.homedir(), \".amem\");\n if (!fs.existsSync(amemDir)) fs.mkdirSync(amemDir, { recursive: true });\n\n const dbPath = process.env.AMEM_DB ?? path.join(amemDir, \"memory.db\");\n\n try {\n db = createDatabase(dbPath);\n } catch (err) {\n // Attempt recovery: if DB is corrupted, back it up and create fresh\n const backupPath = `${dbPath}.corrupt.${Date.now()}`;\n try {\n if (fs.existsSync(dbPath)) {\n fs.renameSync(dbPath, backupPath);\n // Remove WAL/SHM files too\n if (fs.existsSync(`${dbPath}-wal`)) fs.unlinkSync(`${dbPath}-wal`);\n if (fs.existsSync(`${dbPath}-shm`)) fs.unlinkSync(`${dbPath}-shm`);\n console.error(`[amem] Database corrupted — backed up to ${backupPath}`);\n console.error(\"[amem] Creating fresh database. Previous memories are in the backup file.\");\n db = createDatabase(dbPath);\n } else {\n throw err;\n }\n } catch {\n console.error(`[amem] Failed to initialize memory: ${err instanceof Error ? err.message : String(err)}`);\n console.error(`[amem] Try deleting ${amemDir} to reset: rm -rf ${amemDir}`);\n throw err;\n }\n }\n\n currentProject = project ?? \"global\";\n\n // Construct the Markdown mirror engine (Task 2.2).\n // Config contract:\n // - no config file on disk -> mirror enabled with defaults\n // - config file with mirror.enabled=false -> mirror disabled (null engine)\n // - config file with partial mirror block -> Task 2.1's loadConfig merges defaults\n try {\n const agentCfg = loadAgentConfig();\n const mirrorCfg = agentCfg?.mirror;\n const enabled = mirrorCfg?.enabled ?? true;\n if (enabled) {\n const dir = expandHome(mirrorCfg?.dir ?? path.join(homeDir(), \"memories\"));\n const tiers = mirrorCfg?.tiers ?? [\"core\", \"working\", \"archival\"];\n mirrorEngine = new MirrorEngine(db, {\n dir,\n tiers,\n includeIndex: true,\n });\n }\n } catch (err) {\n // Mirror construction must never break memory init.\n console.warn(`[amem-mirror] construction failed: ${err instanceof Error ? err.message : String(err)}`);\n mirrorEngine = null;\n }\n\n preloadEmbeddings();\n\n setTimeout(() => {\n try { buildVectorIndex(db!); } catch {}\n }, 1000);\n\n return db;\n}\n\nexport function getDb(): AmemDatabase {\n if (!db) throw new Error(\"Memory not initialized — call initMemory() first\");\n return db;\n}\n\nexport function getProject(): string {\n return currentProject;\n}\n\nexport async function memoryRecall(query: string, opts?: {\n limit?: number;\n compact?: boolean;\n type?: string;\n tag?: string;\n minConfidence?: number;\n explain?: boolean;\n}): Promise<RecallResult> {\n return recall(getDb(), {\n query,\n limit: opts?.limit ?? 10,\n compact: opts?.compact ?? true,\n type: opts?.type,\n tag: opts?.tag,\n minConfidence: opts?.minConfidence,\n explain: opts?.explain,\n scope: currentProject,\n });\n}\n\nexport async function memoryContext(topic: string, maxTokens?: number): Promise<ContextResult> {\n return buildContext(getDb(), topic, { maxTokens, scope: currentProject });\n}\n\nexport async function memoryStore(opts: StoreOptions): Promise<StoreResult> {\n const result = await storeMemory(getDb(), opts);\n // Fire-and-forget mirror write. Null-safe via optional chaining; the\n // engine's internal onError swallows all I/O failures so mirror errors\n // cannot break a memory save. `private` action from the sanitizer means\n // no memory was written, so skip the mirror call in that case.\n if (result.action !== \"private\" && mirrorEngine) {\n const saved = getDb().getById(result.id);\n if (saved) void mirrorEngine.onSave(saved);\n }\n return result;\n}\n\nexport function memoryLog(sessionId: string, role: string, content: string): string {\n return getDb().appendLog({\n sessionId,\n role: role as \"user\" | \"assistant\" | \"system\",\n content,\n project: currentProject,\n metadata: {},\n });\n}\n\nexport function reminderCheck(): Array<{ id: string; content: string; dueAt: number | null; status: \"overdue\" | \"today\" | \"upcoming\"; scope: string }> {\n const all = getDb().checkReminders();\n return all.filter((r) => r.scope === \"global\" || r.scope === currentProject);\n}\n\nexport async function memoryForget(opts: { id?: string; query?: string; type?: string }): Promise<{ deleted: number; message: string }> {\n const db = getDb();\n if (opts.id) {\n const fullId = db.resolveId(opts.id) ?? opts.id;\n const memory = db.getById(fullId);\n if (!memory) return { deleted: 0, message: `Memory ${opts.id} not found.` };\n db.deleteMemory(fullId);\n const vecIdx = getVectorIndex();\n if (vecIdx) vecIdx.remove(fullId);\n void mirrorEngine?.onDelete(fullId, memory.type);\n return { deleted: 1, message: `Deleted: \"${memory.content}\" (${memory.type})` };\n }\n // Type-based delete: delete all memories of a given type\n if (opts.type) {\n const all = db.getAllForProject(currentProject);\n const matches = all.filter((m) => m.type === opts.type);\n if (matches.length === 0) return { deleted: 0, message: `No memories of type \"${opts.type}\" found.` };\n const vecIdx = getVectorIndex();\n for (const m of matches) {\n db.deleteMemory(m.id);\n if (vecIdx) vecIdx.remove(m.id);\n void mirrorEngine?.onDelete(m.id, m.type);\n }\n return { deleted: matches.length, message: `Deleted ${matches.length} \"${opts.type}\" memories.` };\n }\n if (opts.query) {\n const queryEmbedding = await generateEmbedding(opts.query);\n const matches = recallMemories(db, { query: opts.query, queryEmbedding, limit: 50, minConfidence: 0, scope: currentProject });\n if (matches.length === 0) return { deleted: 0, message: `No memories found matching \"${opts.query}\".` };\n const vecIdx = getVectorIndex();\n for (const m of matches) {\n db.deleteMemory(m.id);\n if (vecIdx) vecIdx.remove(m.id);\n void mirrorEngine?.onDelete(m.id, m.type);\n }\n return { deleted: matches.length, message: `Deleted ${matches.length} memories matching \"${opts.query}\".` };\n }\n return { deleted: 0, message: \"Provide an id, type, or query to forget.\" };\n}\n\nlet _localMemoryConfig: { maxStaleDays?: number; minConfidence?: number; minAccessCount?: number; maxRecallTokens?: number } = {};\n\nexport function setMemoryConfig(config: typeof _localMemoryConfig): void {\n _localMemoryConfig = config;\n}\n\nexport function getMaxRecallTokens(): number {\n return _localMemoryConfig.maxRecallTokens ?? 1500;\n}\n\nexport function memoryConsolidate(dryRun = false): ConsolidationReport {\n return consolidateMemories(getDb(), cosineSimilarity, {\n dryRun,\n maxStaleDays: _localMemoryConfig.maxStaleDays ?? 90,\n minConfidence: _localMemoryConfig.minConfidence ?? 0.3,\n minAccessCount: _localMemoryConfig.minAccessCount ?? 0,\n });\n}\n\nexport function isMemoryInitialized(): boolean {\n return db !== null;\n}\n\nexport function memoryStats(): MemoryStats {\n return getDb().getStats();\n}\n\nexport function memoryExport(): Memory[] {\n return getDb().getAllForProject(currentProject);\n}\n\nexport function memorySince(hours: number): Memory[] {\n const since = Date.now() - hours * 60 * 60 * 1000;\n const all = getDb().getMemoriesSince(since);\n return all.filter((m) => m.scope === \"global\" || m.scope === currentProject);\n}\n\nexport function memorySearch(query: string, limit?: number): Memory[] {\n return getDb().fullTextSearch(query, limit, currentProject);\n}\n\nexport function reminderSet(content: string, dueAt?: number): string {\n return getDb().insertReminder(content, dueAt ?? null, currentProject);\n}\n\nexport function reminderList(includeCompleted?: boolean): Array<{ id: string; content: string; dueAt: number | null; completed: boolean; createdAt: number; scope: string }> {\n return getDb().listReminders(includeCompleted, currentProject);\n}\n\nexport function reminderComplete(id: string): boolean {\n const fullId = getDb().resolveReminderId(id) ?? id;\n return getDb().completeReminder(fullId);\n}\n\nexport { type RecallResult, type ContextResult, type StoreResult, type StoreOptions, type ConsolidationReport, type MemoryStats, type Memory };\n\n// ─── Admin: Doctor ───────────────────────────────────────────────────────────\n\n/**\n * Run read-only health diagnostics on the amem database.\n * Returns a structured report with status, stats, and a list of issues.\n */\nexport async function memoryDoctor(): Promise<DiagnosticReport> {\n return runDiagnostics(getDb());\n}\n\n// ─── Admin: Repair ───────────────────────────────────────────────────────────\n\nexport interface MemoryRepairResult {\n dryRun: boolean;\n status: \"healthy\" | \"warning\" | \"critical\";\n issues: string[];\n actions: string[];\n}\n\n/**\n * Diagnose and optionally repair the memory database.\n * By default runs in dry-run mode — set dryRun:false to apply fixes.\n */\nexport async function memoryRepair(\n opts: { dryRun?: boolean } = {}\n): Promise<MemoryRepairResult> {\n const dryRun = opts.dryRun ?? true;\n if (dryRun) {\n // Dry-run: run diagnostics and surface what would be repaired\n const diag = runDiagnostics(getDb());\n return {\n dryRun: true,\n status: diag.status,\n issues: diag.issues.map((issue) => issue.message),\n actions: diag.issues.map((issue) => `Would fix: ${issue.suggestion}`),\n };\n }\n // Actual repair: call repairDatabase with the DB path\n const dbPath = process.env.AMEM_DB ?? path.join(os.homedir(), \".amem\", \"memory.db\");\n const result = repairDatabase(dbPath);\n return {\n dryRun: false,\n status: result.status === \"repaired\" ? \"warning\" : result.status === \"failed\" ? \"critical\" : \"healthy\",\n issues: [],\n actions: result.memoriesRecovered > 0 ? [`Recovered ${result.memoriesRecovered} memories`] : [],\n };\n}\n\n// ─── Admin: Config ───────────────────────────────────────────────────────────\n\n/**\n * Read or update the amem configuration.\n * With no args, returns the current config.\n * With updates, deep-merges and saves the new config, then returns authoritative post-save state.\n */\nexport async function memoryConfig(\n updates?: DeepPartial<AmemConfig>\n): Promise<AmemConfig> {\n const current = loadConfig();\n if (updates && Object.keys(updates).length > 0) {\n saveConfig(updates as Partial<AmemConfig>);\n return loadConfig(); // read back authoritative merged state\n }\n return current;\n}\n\n// ─── Advanced Recall ─────────────────────────────────────────────────────────\n\n/**\n * Multi-strategy recall: combines semantic, FTS5, knowledge graph, and\n * temporal scoring into a unified ranked result.\n */\nexport async function memoryMultiRecall(\n query: string,\n opts: { limit?: number; scope?: string } = {}\n): Promise<{ memories: Awaited<ReturnType<typeof multiStrategyRecall>>; total: number }> {\n const queryEmbedding = await generateEmbedding(query);\n const memories = await multiStrategyRecall(getDb(), {\n query,\n queryEmbedding,\n limit: opts.limit ?? 10,\n scope: opts.scope ?? currentProject ?? undefined,\n });\n return { memories, total: memories.length };\n}\n\n// ─── Reflection ──────────────────────────────────────────────────────────────\n\n/**\n * Run the self-evolving memory reflection engine.\n * Returns clusters, contradictions, and synthesis candidates.\n */\nexport async function memoryReflect(\n config?: Partial<ReflectionConfig>\n): Promise<ReflectionReport> {\n return reflect(getDb(), config);\n}\n\n/**\n * Check whether a reflection run is due based on last-run metadata.\n */\nexport function checkReflectionDue(): { due: boolean; reason: string } {\n return isReflectionDue(getDb());\n}\n\n// ─── Tier ────────────────────────────────────────────────────────────────────\n\n/**\n * Move a memory between tiers: \"core\" | \"working\" | \"archival\".\n */\nexport function memoryTier(\n id: string,\n tier: string,\n): { id: string; tier: string; ok: true } | { ok: false; error: string } {\n try {\n const db = getDb();\n const fullId = db.resolveId(id) ?? id;\n db.updateTier(fullId, tier);\n return { id: fullId, tier, ok: true };\n } catch (err) {\n return { ok: false, error: err instanceof Error ? err.message : String(err) };\n }\n}\n\n// ─── Detail ──────────────────────────────────────────────────────────────────\n\n/**\n * Get the full Memory object for a given id. Returns null if not found.\n */\nexport function memoryDetail(id: string): Memory | null {\n const db = getDb();\n const fullId = db.resolveId(id) ?? id;\n return db.getById(fullId);\n}\n\n// ─── Relate ──────────────────────────────────────────────────────────────────\n\n/**\n * Add a knowledge-graph relation between two memories.\n */\nexport function memoryRelate(\n fromId: string,\n toId: string,\n type: string,\n strength?: number,\n): { ok: true; relationId: string } | { ok: false; error: string } {\n try {\n const relationId = getDb().addRelation(fromId, toId, type, strength);\n return { ok: true, relationId };\n } catch (err) {\n return { ok: false, error: err instanceof Error ? err.message : String(err) };\n }\n}\n\n// ─── Expire ──────────────────────────────────────────────────────────────────\n\n/**\n * Mark a memory as expired (sets valid_until to now).\n * The optional `reason` string is for caller-side logging only — the db\n * itself stores the timestamp rather than a reason field.\n */\nexport function memoryExpire(\n id: string,\n reason?: string,\n): { ok: true; id: string; reason?: string } | { ok: false; error: string } {\n try {\n const db = getDb();\n const fullId = db.resolveId(id) ?? id;\n db.expireMemory(fullId);\n return { ok: true, id: fullId, ...(reason !== undefined ? { reason } : {}) };\n } catch (err) {\n return { ok: false, error: err instanceof Error ? err.message : String(err) };\n }\n}\n\n// ─── Versions ────────────────────────────────────────────────────────────────\n\n/**\n * Return the full version history for a memory.\n */\nexport function memoryVersions(id: string): MemoryVersion[] {\n const db = getDb();\n const fullId = db.resolveId(id) ?? id;\n return db.getVersionHistory(fullId);\n}\n\n// ─── Sync ────────────────────────────────────────────────────────────────────\n\nexport type MemorySyncAction = \"import-claude\" | \"export-team\" | \"import-team\" | \"sync-copilot\";\n\nexport interface MemorySyncOptions {\n /** For import-claude: filter to a specific project path */\n projectFilter?: string;\n /** For import-claude / export-team: skip actual writes */\n dryRun?: boolean;\n /** For export-team: output directory */\n outputDir?: string;\n /** For export-team: userId identifier in the export manifest */\n userId?: string;\n /** For import-team: path to the JSON export file */\n filePath?: string;\n /** For sync-copilot: options forwarded to syncToCopilot */\n copilotOptions?: CopilotSyncOptions;\n /** For import-team: options forwarded to importFromTeam */\n importOptions?: TeamImportOptions;\n}\n\n/**\n * Sync memories with Claude Code auto-memory or team members.\n *\n * Actions:\n * - \"import-claude\" — read Claude Code memory files and import into amem\n * - \"export-team\" — write a shareable JSON export for teammates\n * - \"import-team\" — merge a teammate's JSON export into amem\n * - \"sync-copilot\" — update the Copilot instructions file from amem memories\n */\nexport async function memorySync(\n action: MemorySyncAction,\n opts: MemorySyncOptions = {},\n): Promise<SyncResult | TeamImportResult | { file: string; count: number } | CopilotSyncResult | { ok: false; error: string }> {\n const db = getDb();\n try {\n switch (action) {\n case \"import-claude\":\n return await syncFromClaude(db, opts.projectFilter, opts.dryRun ?? false);\n\n case \"export-team\": {\n const exportOptions: TeamExportOptions = {\n userId: opts.userId ?? currentProject,\n };\n return await exportForTeam(db, opts.outputDir ?? process.cwd(), exportOptions);\n }\n\n case \"import-team\":\n if (!opts.filePath) {\n return { ok: false, error: \"filePath is required for import-team\" };\n }\n return await importFromTeam(db, opts.filePath, opts.importOptions);\n\n case \"sync-copilot\":\n return syncToCopilot(db, opts.copilotOptions);\n\n default:\n return { ok: false, error: `Unknown sync action: ${action as string}` };\n }\n } catch (err) {\n return { ok: false, error: err instanceof Error ? err.message : String(err) };\n }\n}\n\nexport type { MemoryVersion, MemoryRelation, SyncResult, TeamImportResult, CopilotSyncResult };\n\n// ─── Mirror (Task 2.3) ───────────────────────────────────────────────────────\n\n/**\n * Expose the process-wide MirrorEngine so slash commands can call\n * `fullMirror()` / `exportSnapshot()` / `status()` directly. Returns\n * `null` when the mirror is disabled in config — callers should\n * surface that to the user instead of crashing.\n */\nexport function getMirrorEngine(): MirrorEngine | null {\n return mirrorEngine;\n}\n\n/**\n * Mirror-specific fields we recognise in a mirror-format markdown file's\n * YAML frontmatter. Parsed in addition to the legacy Claude fields so the\n * round trip (MirrorEngine.serialize → syncFromMirrorDir) is lossless for\n * memory type, confidence, tags, and id.\n */\ninterface MirrorFrontmatter {\n amemId?: string;\n amemType?: string;\n amemConfidence?: number;\n amemTags?: string[];\n amemCreated?: number;\n amemTier?: string;\n}\n\n/**\n * Extract `amem_*` fields from raw frontmatter text. amem-core's\n * `parseFrontmatter` only surfaces Claude-vocab fields (name/description/\n * type/body) — we need a second pass for the lossless fields that\n * MirrorEngine.serializeMemoryFile writes. Tolerant of missing fields;\n * absent values leave the corresponding property undefined.\n */\nfunction extractAmemFields(raw: string): MirrorFrontmatter {\n const out: MirrorFrontmatter = {};\n const block = raw.match(/^---\\s*\\n([\\s\\S]*?)\\n---/);\n if (!block) return out;\n for (const line of block[1].split(\"\\n\")) {\n const kv = line.match(/^(amem_\\w+)\\s*:\\s*(.+)$/);\n if (!kv) continue;\n const key = kv[1];\n const val = kv[2].trim();\n switch (key) {\n case \"amem_id\": out.amemId = val; break;\n case \"amem_type\": out.amemType = val; break;\n case \"amem_tier\": out.amemTier = val; break;\n case \"amem_confidence\": {\n const n = Number(val);\n if (Number.isFinite(n)) out.amemConfidence = n;\n break;\n }\n case \"amem_tags\":\n out.amemTags = val\n .split(\",\")\n .map((t) => t.trim())\n .filter((t) => t.length > 0);\n break;\n case \"amem_created\": {\n const t = Date.parse(val);\n if (!Number.isNaN(t)) out.amemCreated = t;\n break;\n }\n }\n }\n return out;\n}\n\n// Claude-vocab → amem type map, mirrored from amem-core/sync.ts. Used as a\n// fallback when a `.md` file lacks `amem_type` (e.g. a hand-authored note\n// or a file imported from Claude's auto-memory tree). Kept inline here\n// instead of importing because amem-core does not export it.\nconst CLAUDE_TO_AMEM_TYPE: Record<string, \"correction\" | \"decision\" | \"preference\" | \"topology\"> = {\n feedback: \"correction\",\n project: \"decision\",\n user: \"preference\",\n reference: \"topology\",\n};\n\n/**\n * Auto-sync the mirror dir into the DB on agent startup (Task 2.4).\n *\n * Closes the multi-device loop: edits made on machine A's mirror dir\n * (via Dropbox/iCloud/git) land in machine B's DB on next launch.\n *\n * Contract:\n * - Fast no-op when `config.mirror.enabled=false` OR `autoSyncOnStartup=false`:\n * no fs scan, no engine lookup; returns `null`.\n * - Errors are swallowed and surfaced as `null` — a failed sync MUST NOT\n * block startup. Callers can log/ignore.\n * - Returns the SyncResult on success so the caller (index.ts) can emit\n * a subtle log line. Keeping logging in the caller avoids pulling\n * picocolors into memory.ts and keeps the function pure for tests.\n *\n * Must be awaited by the caller so the REPL doesn't accept user input\n * before synced memories are in the DB (otherwise /recall could miss\n * just-synced entries).\n */\nexport async function startupAutoSync(): Promise<SyncResult | null> {\n // Config first — a disabled auto-sync is a genuine no-op, not a\n // cheap-scan-then-bail.\n const cfg = loadAgentConfig();\n const autoSync = cfg?.mirror?.autoSyncOnStartup ?? true;\n const enabled = cfg?.mirror?.enabled ?? true;\n if (!enabled || !autoSync) return null;\n\n const engine = mirrorEngine;\n if (!engine) return null; // construction failed silently earlier\n\n const dir = engine.status().dir;\n try {\n return await syncFromMirrorDir(dir);\n } catch {\n // Swallow — mirror ops are best-effort. Caller may log.\n return null;\n }\n}\n\n/**\n * Import memories from an arbitrary mirror-format directory into the DB.\n *\n * Unlike amem-core's `syncFromClaude` — which scans the Claude auto-memory\n * tree under `~/.claude/projects/<escaped>/memory/` — this helper takes a\n * single directory and walks all `.md` files beneath it (including one\n * level of type-subdirectories, which is MirrorEngine's on-disk layout).\n *\n * The parser is lossless when the file carries `amem_*` frontmatter (the\n * mirror round-trip case). When those fields are missing we fall back to\n * the Claude-vocab type map so files authored elsewhere still import.\n *\n * Dedup: skipped by content hash and by name-FTS match, matching\n * `syncFromClaude`'s behaviour. Scope defaults to `currentProject` for\n * memories that look project-local, `global` for user/preference ones —\n * the same policy syncFromClaude applies.\n */\nexport async function syncFromMirrorDir(dir: string): Promise<SyncResult> {\n const db = getDb();\n const result: SyncResult = {\n imported: 0,\n skipped: 0,\n updated: 0,\n details: [],\n projectsScanned: 1,\n };\n if (!fs.existsSync(dir)) return result;\n\n // Collect .md files one level deep (type-subdirs) plus any at the root.\n const targets: string[] = [];\n const walk = (d: string): void => {\n for (const name of fs.readdirSync(d)) {\n if (name === \"INDEX.md\") continue;\n const full = path.join(d, name);\n const stat = fs.statSync(full);\n if (stat.isDirectory()) walk(full);\n else if (name.endsWith(\".md\")) targets.push(full);\n }\n };\n try { walk(dir); } catch { return result; }\n\n for (const filePath of targets) {\n const raw = fs.readFileSync(filePath, \"utf-8\");\n const parsed = parseFrontmatter(raw, filePath);\n if (!parsed) {\n result.skipped++;\n result.details.push({ action: \"skipped\", name: filePath, type: \"unknown\", reason: \"invalid frontmatter\" });\n continue;\n }\n const amem = extractAmemFields(raw);\n\n // Prefer amem_* fields when present; fall back to the Claude-vocab\n // type map for hand-authored / Claude-sourced files.\n const resolvedType = (amem.amemType as \"correction\" | \"decision\" | \"pattern\" | \"preference\" | \"topology\" | \"fact\" | undefined)\n ?? CLAUDE_TO_AMEM_TYPE[parsed.type];\n if (!resolvedType) {\n result.skipped++;\n result.details.push({ action: \"skipped\", name: parsed.name, type: parsed.type, reason: `Unknown type: ${parsed.type}` });\n continue;\n }\n\n const content = parsed.body;\n if (!content.trim()) {\n result.skipped++;\n result.details.push({ action: \"skipped\", name: parsed.name, type: resolvedType, reason: \"empty body\" });\n continue;\n }\n\n // Dedup by content hash (source of truth) — cheap and deterministic.\n const existing = db.findByContentHash(content);\n if (existing) {\n result.skipped++;\n result.details.push({ action: \"skipped\", name: parsed.name, type: resolvedType, reason: \"duplicate content\" });\n continue;\n }\n\n const embedding = await generateEmbedding(content);\n const confidence = amem.amemConfidence ?? 0.8;\n const isGlobal = resolvedType === \"preference\" || resolvedType === \"correction\";\n const scope = isGlobal ? \"global\" : currentProject;\n const tags = amem.amemTags ?? [\"mirror-sync\"];\n db.insertMemory({\n content,\n type: resolvedType,\n tags,\n confidence,\n source: \"mirror-sync\",\n embedding,\n scope,\n ...(amem.amemTier ? { tier: amem.amemTier } : {}),\n // Preserve original creation time when the mirror file carries it,\n // so round-tripped memories keep their chronology for recency decay.\n ...(amem.amemCreated ? { validFrom: amem.amemCreated } : {}),\n });\n result.imported++;\n result.details.push({ action: \"imported\", name: parsed.name, type: resolvedType });\n }\n\n return result;\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport os from \"node:os\";\n\nimport { ORCHESTRATOR_PROFILES } from \"./profiles/orchestrator-profiles.js\";\n\nexport interface ProfileTemplate {\n name: string;\n label: string;\n description: string;\n core: string;\n rules?: string;\n skills?: string;\n}\n\nexport const BUILT_IN_PROFILES: ProfileTemplate[] = [\n {\n name: \"coder\",\n label: \"Coder\",\n description: \"Direct, technical, code-first. Skips pleasantries, shows code.\",\n core: `# Coder\n\n## Identity\n- Role: Coder is your technical pair programmer\n- Personality: direct, precise, efficient — code speaks louder than words\n- Communication: lead with code, explain after. No fluff.\n- Values: simplicity over cleverness, working code over perfect code, tests over trust\n- Boundaries: won't pretend to be human, flags when out of depth\n\n### Appearance\n- Base: focused developer, dark hoodie, terminal glow\n- Style: minimal\n- Palette: green on black`,\n rules: `# Coder Rules\n\n## Always\n- Show code before explaining\n- Include error handling\n- Suggest tests for new code\n\n## Never\n- Write code without understanding the requirement\n- Push to main without tests\n- Ignore security implications`,\n },\n {\n name: \"writer\",\n label: \"Writer\",\n description: \"Creative, eloquent, story-driven. Focuses on narrative and engagement.\",\n core: `# Muse\n\n## Identity\n- Role: Muse is your creative writing partner\n- Personality: eloquent, imaginative, encouraging — finds the story in everything\n- Communication: explore ideas together, offer alternatives, celebrate good writing\n- Values: authenticity over formulas, voice over grammar, emotion over information\n- Boundaries: won't write without understanding the audience, flags when content is sensitive\n\n### Appearance\n- Base: warm expression, creative energy, pen in hand\n- Style: illustrated\n- Palette: warm amber and cream`,\n rules: `# Writer Rules\n\n## Always\n- Ask about the target audience\n- Offer 2-3 angle options before drafting\n- Read drafts aloud mentally for rhythm\n\n## Never\n- Use cliches without subverting them\n- Write without a clear hook\n- Ignore tone consistency`,\n },\n {\n name: \"researcher\",\n label: \"Researcher\",\n description: \"Analytical, thorough, citation-focused. Digs deep, verifies claims.\",\n core: `# Scholar\n\n## Identity\n- Role: Scholar is your research analyst\n- Personality: analytical, thorough, intellectually curious — never takes claims at face value\n- Communication: present findings with evidence, flag uncertainty, compare perspectives\n- Values: accuracy over speed, nuance over simplification, primary sources over summaries\n- Boundaries: clearly marks speculation vs fact, flags when evidence is insufficient\n\n### Appearance\n- Base: thoughtful expression, glasses, surrounded by notes\n- Style: minimal\n- Palette: navy and white`,\n rules: `# Researcher Rules\n\n## Always\n- Cite sources when making factual claims\n- Flag confidence level (high/medium/low)\n- Present multiple perspectives on contested topics\n\n## Never\n- Present speculation as fact\n- Ignore contradicting evidence\n- Oversimplify complex topics`,\n },\n ...ORCHESTRATOR_PROFILES,\n];\n\n/**\n * Install a built-in profile template.\n */\nexport function installProfileTemplate(templateName: string, userName?: string): string | null {\n const template = BUILT_IN_PROFILES.find((t) => t.name === templateName);\n if (!template) return null;\n\n const profileDir = path.join(os.homedir(), \".acore\", \"profiles\", template.name);\n if (fs.existsSync(profileDir)) return `Profile already exists: ${template.name}`;\n\n fs.mkdirSync(profileDir, { recursive: true });\n\n // Write core.md\n let core = template.core;\n if (userName) {\n core += `\\n\\n---\\n\\n## Relationship\\n- Name: ${userName}\\n- Nicknames: []\\n- Communication: [updated over time]\\n- Detail level: balanced\\n`;\n }\n fs.writeFileSync(path.join(profileDir, \"core.md\"), core, \"utf-8\");\n\n // Write rules.md if template has one\n if (template.rules) {\n fs.writeFileSync(path.join(profileDir, \"rules.md\"), template.rules, \"utf-8\");\n }\n\n // Write skills.md if template has one\n if (template.skills) {\n fs.writeFileSync(path.join(profileDir, \"skills.md\"), template.skills, \"utf-8\");\n }\n\n return null; // success\n}\n","import type { ProfileTemplate } from \"../profile-templates.js\";\n\nexport const architectProfile: ProfileTemplate = {\n name: \"architect\",\n label: \"System Architect\",\n description: \"Designs system architecture, decomposes features into modules, plans file structure and interfaces\",\n core: `# System Architect\n\nYou are a system architect. Your job is to:\n- Analyze requirements and design the overall system structure\n- Define module boundaries, interfaces, and data flows\n- Plan file structure and naming conventions\n- Identify dependencies and integration points\n- Choose appropriate patterns and abstractions\n- Consider scalability, maintainability, and testability\n\n## Output Format\nProduce a clear, structured design document with:\n1. **Architecture overview** — high-level components and their relationships\n2. **File structure** — exact paths for new/modified files\n3. **Interfaces** — key types, function signatures, and data contracts\n4. **Dependencies** — what depends on what, build order\n5. **Risks** — potential issues and mitigation strategies\n\nBe precise with file paths and interface definitions. The implementation agents will follow your design exactly.`,\n rules: `- Never write implementation code — design only\n- Always specify exact file paths\n- Consider existing codebase patterns before proposing new ones\n- Flag breaking changes explicitly`,\n};\n\nexport const securityProfile: ProfileTemplate = {\n name: \"security\",\n label: \"Security Analyst\",\n description: \"Reviews code for security vulnerabilities, runs SAST checks, audits dependencies\",\n core: `# Security Analyst\n\nYou are a security analyst. Your job is to:\n- Review code for OWASP Top 10 vulnerabilities\n- Check for injection flaws (SQL, command, XSS)\n- Verify authentication and authorization patterns\n- Audit dependency versions for known CVEs\n- Check for secrets/credentials in code\n- Validate input sanitization and output encoding\n- Review error handling for information leakage\n\n## Output Format\nProduce a security report with:\n1. **Critical** — must fix before merge (injection, auth bypass, secrets)\n2. **High** — should fix (missing validation, weak crypto)\n3. **Medium** — recommended (verbose errors, missing rate limiting)\n4. **Low** — informational (best practice suggestions)\n\nFor each finding: file path, line number, description, remediation.`,\n rules: `- Never approve code with Critical findings\n- Always check for hardcoded secrets\n- Flag any use of eval, exec, or shell string concatenation\n- Verify all user input is validated at system boundaries`,\n};\n\nexport const testerProfile: ProfileTemplate = {\n name: \"tester\",\n label: \"Test Engineer\",\n description: \"Writes comprehensive tests, identifies edge cases, ensures coverage\",\n core: `# Test Engineer\n\nYou are a test engineer. Your job is to:\n- Write comprehensive unit and integration tests\n- Identify edge cases and boundary conditions\n- Test error paths and failure modes\n- Verify behavior against specifications\n- Ensure tests are deterministic and fast\n- Follow existing test patterns in the codebase\n\n## Testing Principles\n- Test behavior, not implementation details\n- Each test should verify one specific thing\n- Use descriptive test names that explain the expected behavior\n- Arrange-Act-Assert pattern\n- Mock external dependencies, test internal logic directly\n- Prefer integration tests for complex interactions\n\n## Output Format\nProduce test files following the project's existing patterns (Vitest, Jest, pytest, etc.).\nInclude: happy path, error cases, edge cases, boundary values.`,\n rules: `- Never skip error path testing\n- Always test boundary conditions\n- Tests must be deterministic (no timing dependencies, no random values)\n- Follow the project's existing test framework and patterns`,\n};\n\nexport const reviewerProfile: ProfileTemplate = {\n name: \"reviewer\",\n label: \"Code Reviewer\",\n description: \"Reviews code for quality, correctness, and adherence to patterns\",\n core: `# Code Reviewer\n\nYou are a code reviewer. Your job is to:\n- Check code correctness and logic errors\n- Verify adherence to project conventions and patterns\n- Identify potential performance issues\n- Assess readability and maintainability\n- Check error handling completeness\n- Verify tests adequately cover the changes\n\n## Review Approach\n- Focus on correctness first, style second\n- Flag bugs and logic errors as Critical\n- Flag missing error handling as High\n- Flag style and convention issues as Medium\n- Acknowledge good patterns and clean code\n\n## Output Format\nProduce a review with confidence-scored findings:\n- **CRITICAL** (confidence > 0.9) — definite bugs or security issues\n- **IMPORTANT** (confidence > 0.7) — likely problems or missing handling\n- **SUGGESTION** (confidence > 0.5) — improvements worth considering\n- **PRAISE** — highlight good patterns\n\nInclude file path, line range, and specific explanation for each finding.`,\n rules: `- Never rubber-stamp — always provide substantive review\n- Focus on what matters: correctness > performance > style\n- Be specific: cite exact lines and explain why something is wrong\n- Distinguish between \"must fix\" and \"nice to have\"`,\n};\n\nexport const ORCHESTRATOR_PROFILES: ProfileTemplate[] = [\n architectProfile,\n securityProfile,\n testerProfile,\n reviewerProfile,\n];\n\n/** Get a profile by name */\nexport function getOrchestratorProfile(name: string): ProfileTemplate | undefined {\n return ORCHESTRATOR_PROFILES.find((p) => p.name === name);\n}\n\n/** Get all profile names */\nexport function getOrchestratorProfileNames(): string[] {\n return ORCHESTRATOR_PROFILES.map((p) => p.name);\n}\n","import * as p from \"@clack/prompts\";\nimport pc from \"picocolors\";\nimport type { UserIdentity } from \"./user-identity.js\";\nimport { saveUserIdentity } from \"./user-identity.js\";\nimport { loadShowcaseManifest, installShowcaseTemplate, type ShowcaseOption } from \"./showcase-bridge.js\";\n\n/**\n * Run the interactive onboarding flow for first-time users.\n * Captures user identity with personality-driven questions.\n * Returns the saved UserIdentity.\n */\nexport async function runOnboarding(): Promise<UserIdentity | null> {\n console.log(\"\");\n p.intro(pc.bold(\"Let's get to know each other\"));\n p.log.info(pc.dim(\"Quick setup so I can be actually useful to you. Takes ~30 seconds.\"));\n\n // --- Name ---\n const name = await p.text({\n message: \"What should I call you?\",\n placeholder: \"Your name or nickname\",\n validate: (v) => (v.trim().length === 0 ? \"I need something to call you!\" : undefined),\n });\n if (p.isCancel(name)) return null;\n\n // --- Role ---\n const role = await p.select({\n message: `Nice to meet you, ${pc.bold(name)}! What's your main thing?`,\n options: [\n { value: \"developer\", label: \"Building things\", hint: \"developer, engineer, maker\" },\n { value: \"designer\", label: \"Designing things\", hint: \"UI/UX, creative, visual\" },\n { value: \"student\", label: \"Learning things\", hint: \"student, researcher, exploring\" },\n { value: \"manager\", label: \"Running things\", hint: \"lead, PM, coordinator\" },\n { value: \"generalist\", label: \"A bit of everything\", hint: \"jack of all trades\" },\n ],\n initialValue: \"developer\",\n });\n if (p.isCancel(role)) return null;\n\n const ROLE_LABELS: Record<string, string> = {\n developer: \"Developer / Engineer\",\n designer: \"Designer / Creative\",\n student: \"Student / Researcher\",\n manager: \"Lead / Manager\",\n generalist: \"Generalist\",\n };\n\n // --- Expertise ---\n const expertise = await p.select({\n message: \"How deep in the game are you?\",\n options: [\n { value: \"beginner\", label: \"Just getting started\", hint: \"explain everything, I'm here to learn\" },\n { value: \"intermediate\", label: \"Know my way around\", hint: \"skip the basics, get to the point\" },\n { value: \"advanced\", label: \"Been at it for years\", hint: \"show me the advanced stuff\" },\n { value: \"expert\", label: \"I wrote the book\", hint: \"challenge me, peer-level talk\" },\n ],\n initialValue: \"intermediate\",\n });\n if (p.isCancel(expertise)) return null;\n\n const EXPERTISE_LABELS: Record<string, string> = {\n beginner: \"Getting Started\",\n intermediate: \"Intermediate\",\n advanced: \"Advanced\",\n expert: \"Expert\",\n };\n\n // --- Communication Style ---\n const style = await p.select({\n message: \"How do you like your answers?\",\n options: [\n { value: \"concise\", label: \"Short and sharp\", hint: \"code first, talk later\" },\n { value: \"balanced\", label: \"Balanced\", hint: \"explain the why, show the how\" },\n { value: \"thorough\", label: \"Deep and detailed\", hint: \"I want to understand everything\" },\n { value: \"socratic\", label: \"Make me think\", hint: \"ask questions, guide me there\" },\n ],\n initialValue: \"balanced\",\n });\n if (p.isCancel(style)) return null;\n\n const STYLE_LABELS: Record<string, string> = {\n concise: \"Concise — code first, talk later\",\n balanced: \"Balanced — explain and show\",\n thorough: \"Thorough — deep explanations\",\n socratic: \"Socratic — guide with questions\",\n };\n\n // --- Working On (optional) ---\n const workingOn = await p.text({\n message: \"What are you working on right now? \" + pc.dim(\"(optional, press Enter to skip)\"),\n placeholder: \"e.g. a React app, a CLI tool, learning Python...\",\n defaultValue: \"\",\n });\n if (p.isCancel(workingOn)) return null;\n\n // --- Notes (optional) ---\n const notes = await p.text({\n message: \"Anything else I should know about you? \" + pc.dim(\"(optional)\"),\n placeholder: \"e.g. I prefer TypeScript, I work on a Mac, I'm in GMT+8...\",\n defaultValue: \"\",\n });\n if (p.isCancel(notes)) return null;\n\n // --- Build and save ---\n const today = new Date().toISOString().split(\"T\")[0];\n\n const user: UserIdentity = {\n name: (name as string).trim(),\n role: role as UserIdentity[\"role\"],\n roleLabel: ROLE_LABELS[role as string] || \"Generalist\",\n expertise: expertise as UserIdentity[\"expertise\"],\n expertiseLabel: EXPERTISE_LABELS[expertise as string] || \"Intermediate\",\n style: style as UserIdentity[\"style\"],\n styleLabel: STYLE_LABELS[style as string] || \"Balanced\",\n workingOn: (workingOn as string).trim() || undefined,\n notes: (notes as string).trim() || undefined,\n createdAt: today,\n updatedAt: today,\n };\n\n saveUserIdentity(user);\n\n // --- Showcase Template (optional) ---\n let showcaseInstalled: string | null = null;\n const showcases = loadShowcaseManifest();\n if (showcases.length > 0) {\n console.log(\"\");\n const wantShowcase = await p.confirm({\n message: \"Want to give your companion a specialty? \" + pc.dim(\"(pre-built personalities with workflows)\"),\n initialValue: false,\n });\n\n if (!p.isCancel(wantShowcase) && wantShowcase) {\n // Group by category for nicer display\n const categories = new Map<string, ShowcaseOption[]>();\n for (const s of showcases) {\n if (!categories.has(s.category)) categories.set(s.category, []);\n categories.get(s.category)!.push(s);\n }\n\n const options: Array<{ value: string; label: string; hint: string }> = [];\n for (const [category, items] of categories) {\n for (const item of items) {\n const langBadge = item.language === \"ms\" ? \" [BM]\" : item.language === \"en+ms\" ? \" [EN/BM]\" : \"\";\n options.push({\n value: item.name,\n label: `${item.title}${langBadge}`,\n hint: item.description.slice(0, 70) + (item.description.length > 70 ? \"...\" : \"\"),\n });\n }\n }\n\n const chosen = await p.select({\n message: \"Pick a companion specialty\",\n options,\n });\n\n if (!p.isCancel(chosen)) {\n const chosenName = chosen as string;\n try {\n const result = installShowcaseTemplate(chosenName);\n if (result.installed.length > 0) {\n showcaseInstalled = chosenName;\n const entry = showcases.find((s) => s.name === chosenName);\n p.log.success(`Installed ${pc.bold(entry?.title || chosenName)}`);\n for (const f of result.installed) {\n process.stdout.write(pc.dim(` ${f}\\n`));\n }\n if (result.backed_up.length > 0) {\n p.log.info(pc.dim(`Backed up ${result.backed_up.length} existing file(s) (.bak)`));\n }\n }\n } catch (err) {\n p.log.warning(`Could not install showcase: ${err instanceof Error ? err.message : String(err)}`);\n }\n }\n }\n }\n\n // --- Confirmation ---\n console.log(\"\");\n p.log.success(`Profile saved for ${pc.bold(user.name)}`);\n\n const summary = [\n ` ${pc.dim(\"Role:\")} ${user.roleLabel}`,\n ` ${pc.dim(\"Level:\")} ${user.expertiseLabel}`,\n ` ${pc.dim(\"Style:\")} ${user.styleLabel}`,\n ];\n if (user.workingOn) {\n summary.push(` ${pc.dim(\"Working on:\")} ${user.workingOn}`);\n }\n if (showcaseInstalled) {\n const entry = showcases.find((s) => s.name === showcaseInstalled);\n summary.push(` ${pc.dim(\"Specialty:\")} ${entry?.title || showcaseInstalled}`);\n }\n console.log(summary.join(\"\\n\"));\n console.log(\"\");\n\n p.log.info(pc.dim(\"Update anytime with /profile edit\"));\n\n return user;\n}\n\n/**\n * Quick profile update — edit specific fields.\n * Returns updated identity or null if cancelled.\n */\nexport async function editProfile(current: UserIdentity): Promise<UserIdentity | null> {\n const field = await p.select({\n message: \"What do you want to update?\",\n options: [\n { value: \"name\", label: \"Name\", hint: `currently: ${current.name}` },\n { value: \"role\", label: \"Role\", hint: `currently: ${current.roleLabel}` },\n { value: \"expertise\", label: \"Expertise level\", hint: `currently: ${current.expertiseLabel}` },\n { value: \"style\", label: \"Communication style\", hint: `currently: ${current.styleLabel}` },\n { value: \"workingOn\", label: \"What you're working on\", hint: current.workingOn || \"not set\" },\n { value: \"notes\", label: \"Notes\", hint: current.notes ? current.notes.slice(0, 40) : \"not set\" },\n ],\n });\n if (p.isCancel(field)) return null;\n\n const updated = { ...current, updatedAt: new Date().toISOString().split(\"T\")[0] };\n\n switch (field) {\n case \"name\": {\n const val = await p.text({ message: \"New name\", defaultValue: current.name });\n if (p.isCancel(val)) return null;\n updated.name = (val as string).trim();\n break;\n }\n case \"role\": {\n const val = await p.select({\n message: \"New role\",\n options: [\n { value: \"developer\", label: \"Building things\" },\n { value: \"designer\", label: \"Designing things\" },\n { value: \"student\", label: \"Learning things\" },\n { value: \"manager\", label: \"Running things\" },\n { value: \"generalist\", label: \"A bit of everything\" },\n ],\n initialValue: current.role,\n });\n if (p.isCancel(val)) return null;\n updated.role = val as UserIdentity[\"role\"];\n const labels: Record<string, string> = { developer: \"Developer / Engineer\", designer: \"Designer / Creative\", student: \"Student / Researcher\", manager: \"Lead / Manager\", generalist: \"Generalist\" };\n updated.roleLabel = labels[val as string] || \"Generalist\";\n break;\n }\n case \"expertise\": {\n const val = await p.select({\n message: \"New expertise level\",\n options: [\n { value: \"beginner\", label: \"Just getting started\" },\n { value: \"intermediate\", label: \"Know my way around\" },\n { value: \"advanced\", label: \"Been at it for years\" },\n { value: \"expert\", label: \"I wrote the book\" },\n ],\n initialValue: current.expertise,\n });\n if (p.isCancel(val)) return null;\n updated.expertise = val as UserIdentity[\"expertise\"];\n const labels: Record<string, string> = { beginner: \"Getting Started\", intermediate: \"Intermediate\", advanced: \"Advanced\", expert: \"Expert\" };\n updated.expertiseLabel = labels[val as string] || \"Intermediate\";\n break;\n }\n case \"style\": {\n const val = await p.select({\n message: \"New communication style\",\n options: [\n { value: \"concise\", label: \"Short and sharp\" },\n { value: \"balanced\", label: \"Balanced\" },\n { value: \"thorough\", label: \"Deep and detailed\" },\n { value: \"socratic\", label: \"Make me think\" },\n ],\n initialValue: current.style,\n });\n if (p.isCancel(val)) return null;\n updated.style = val as UserIdentity[\"style\"];\n const labels: Record<string, string> = { concise: \"Concise — code first, talk later\", balanced: \"Balanced — explain and show\", thorough: \"Thorough — deep explanations\", socratic: \"Socratic — guide with questions\" };\n updated.styleLabel = labels[val as string] || \"Balanced\";\n break;\n }\n case \"workingOn\": {\n const val = await p.text({ message: \"What are you working on?\", defaultValue: current.workingOn || \"\" });\n if (p.isCancel(val)) return null;\n updated.workingOn = (val as string).trim() || undefined;\n break;\n }\n case \"notes\": {\n const val = await p.text({ message: \"Notes about you\", defaultValue: current.notes || \"\" });\n if (p.isCancel(val)) return null;\n updated.notes = (val as string).trim() || undefined;\n break;\n }\n }\n\n saveUserIdentity(updated);\n p.log.success(\"Profile updated!\");\n return updated;\n}\n","/**\n * Bridge to @aman_asmuei/aman-showcase.\n * Safely handles the case where the showcase package isn't installed.\n * All imports are dynamic to avoid hard dependency.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport os from \"node:os\";\nimport { log } from \"./logger.js\";\n\nexport interface ShowcaseOption {\n name: string;\n title: string;\n description: string;\n category: string;\n language: string;\n tags: string[];\n}\n\nexport interface ShowcaseInstallResult {\n installed: string[];\n backed_up: string[];\n env_example: string;\n}\n\nlet cachedManifest: ShowcaseOption[] | null = null;\nlet cachedShowcaseRoot: string | null = null;\n\n/**\n * Find the aman-showcase package root directory.\n */\nfunction findShowcaseRoot(): string | null {\n const candidates = [\n // Sibling in monorepo\n path.join(os.homedir(), \"project-aman\", \"aman-showcase\"),\n path.join(process.cwd(), \"..\", \"aman-showcase\"),\n // npm global install\n path.join(process.cwd(), \"node_modules\", \"@aman_asmuei\", \"aman-showcase\"),\n ];\n\n for (const candidate of candidates) {\n if (fs.existsSync(path.join(candidate, \"src\", \"manifest.ts\")) ||\n fs.existsSync(path.join(candidate, \"dist\", \"index.js\"))) {\n return candidate;\n }\n }\n\n return null;\n}\n\n/**\n * Parse showcase entries from manifest.ts source (works without building).\n */\nfunction parseManifestSource(source: string): ShowcaseOption[] {\n const entries: ShowcaseOption[] = [];\n // Match each showcase entry object\n const regex = /\\{\\s*name:\\s*\"([^\"]+)\"[\\s\\S]*?title:\\s*\"([^\"]+)\"[\\s\\S]*?description:\\s*\"([^\"]+)\"[\\s\\S]*?category:\\s*\"([^\"]+)\"[\\s\\S]*?language:\\s*\"([^\"]+)\"[\\s\\S]*?tags:\\s*\\[([^\\]]*)\\]/g;\n\n let match;\n while ((match = regex.exec(source)) !== null) {\n entries.push({\n name: match[1],\n title: match[2],\n description: match[3],\n category: match[4],\n language: match[5],\n tags: match[6].split(\",\").map((t) => t.trim().replace(/\"/g, \"\")).filter(Boolean),\n });\n }\n\n return entries;\n}\n\n/**\n * Load showcase manifest from @aman_asmuei/aman-showcase.\n * Returns empty array if the package isn't available.\n */\nexport function loadShowcaseManifest(): ShowcaseOption[] {\n if (cachedManifest !== null) return cachedManifest;\n\n const root = findShowcaseRoot();\n if (!root) {\n cachedManifest = [];\n return cachedManifest;\n }\n\n cachedShowcaseRoot = root;\n\n // Try reading manifest source directly (works without dist build)\n const manifestSrc = path.join(root, \"src\", \"manifest.ts\");\n if (fs.existsSync(manifestSrc)) {\n try {\n const content = fs.readFileSync(manifestSrc, \"utf-8\");\n const parsed = parseManifestSource(content);\n if (parsed.length > 0) {\n cachedManifest = parsed;\n return cachedManifest;\n }\n } catch {\n log.debug(\"showcase\", \"Failed to parse manifest.ts\");\n }\n }\n\n // Fallback: scan directories for showcases\n try {\n const dirs = fs.readdirSync(root, { withFileTypes: true })\n .filter((d) => d.isDirectory() && !d.name.startsWith(\".\") &&\n ![\"node_modules\", \"dist\", \"src\", \"bin\", \"docs\"].includes(d.name))\n .filter((d) => fs.existsSync(path.join(root, d.name, \"identity\")));\n\n cachedManifest = dirs.map((d) => ({\n name: d.name,\n title: d.name.charAt(0).toUpperCase() + d.name.slice(1),\n description: \"\",\n category: \"other\",\n language: \"en\",\n tags: [],\n }));\n } catch {\n cachedManifest = [];\n }\n\n return cachedManifest;\n}\n\n/**\n * Install a showcase template by name.\n * Copies identity, rules, workflows, and skills from the showcase package.\n */\nexport function installShowcaseTemplate(name: string): ShowcaseInstallResult {\n const root = cachedShowcaseRoot || findShowcaseRoot();\n if (!root) {\n throw new Error(\"aman-showcase package not found. Install it or check the path.\");\n }\n\n const showcaseDir = path.join(root, name);\n if (!fs.existsSync(showcaseDir) || !fs.existsSync(path.join(showcaseDir, \"identity\"))) {\n throw new Error(`Showcase \"${name}\" not found in ${root}`);\n }\n\n const result: ShowcaseInstallResult = { installed: [], backed_up: [], env_example: \"\" };\n const home = os.homedir();\n\n const copies: Array<{ src: string; dest: string; label: string }> = [\n {\n src: path.join(showcaseDir, \"identity\", \"core.md\"),\n dest: path.join(home, \".acore\", \"core.md\"),\n label: \"~/.acore/core.md (identity)\",\n },\n {\n src: path.join(showcaseDir, \"workflows\", \"flow.md\"),\n dest: path.join(home, \".aflow\", \"flow.md\"),\n label: \"~/.aflow/flow.md (workflows)\",\n },\n {\n src: path.join(showcaseDir, \"rules\", \"rules.md\"),\n dest: path.join(home, \".arules\", \"rules.md\"),\n label: \"~/.arules/rules.md (guardrails)\",\n },\n ];\n\n // Skills — consolidate individual skill files into ~/.askill/skills.md\n const skillsSrc = path.join(showcaseDir, \"skills\");\n if (fs.existsSync(skillsSrc)) {\n const skillFiles = fs.readdirSync(skillsSrc).filter((f: string) => f.endsWith(\".md\"));\n if (skillFiles.length > 0) {\n // Read all skill files and merge into a single skills.md\n const skillParts: string[] = [];\n for (const skillFile of skillFiles) {\n const content = fs.readFileSync(path.join(skillsSrc, skillFile), \"utf-8\").trim();\n if (content) skillParts.push(content);\n }\n\n if (skillParts.length > 0) {\n const skillsDest = path.join(home, \".askill\", \"skills.md\");\n const consolidated = `# Skills\\n\\n${skillParts.join(\"\\n\\n---\\n\\n\")}\\n`;\n\n // Backup existing\n if (fs.existsSync(skillsDest)) {\n fs.copyFileSync(skillsDest, `${skillsDest}.bak`);\n result.backed_up.push(\"~/.askill/skills.md (skills)\");\n }\n\n fs.mkdirSync(path.dirname(skillsDest), { recursive: true });\n fs.writeFileSync(skillsDest, consolidated, \"utf-8\");\n result.installed.push(`~/.askill/skills.md (${skillFiles.length} skill${skillFiles.length > 1 ? \"s\" : \"\"} consolidated)`);\n }\n }\n }\n\n for (const { src, dest, label } of copies) {\n if (!fs.existsSync(src)) continue;\n\n // Backup existing files\n if (fs.existsSync(dest)) {\n const backup = `${dest}.bak`;\n fs.copyFileSync(dest, backup);\n result.backed_up.push(label);\n }\n\n fs.mkdirSync(path.dirname(dest), { recursive: true });\n fs.copyFileSync(src, dest);\n result.installed.push(label);\n }\n\n // Copy env example if present\n const envExample = path.join(showcaseDir, \"config\", \"telegram.env.example\");\n if (fs.existsSync(envExample)) {\n const destEnv = path.join(process.cwd(), \".env.example\");\n fs.copyFileSync(envExample, destEnv);\n result.env_example = destEnv;\n }\n\n log.debug(\"showcase\", `Installed showcase: ${name} (${result.installed.length} files)`);\n return result;\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport os from \"node:os\";\n\nconst MAX_READ_BYTES = 50_000;\nconst HOME = fs.realpathSync(os.homedir());\nconst TMPDIR = fs.realpathSync(os.tmpdir());\nconst CWD = fs.realpathSync(process.cwd());\n\nfunction realOrBest(p: string): string {\n // Walk up the path until we find an existing ancestor, then append the rest.\n // This handles non-existent files under symlinked directories (e.g. macOS /var → /private/var).\n const parts = p.split(path.sep);\n for (let i = parts.length; i > 0; i--) {\n const candidate = parts.slice(0, i).join(path.sep) || path.sep;\n try {\n const real = fs.realpathSync(candidate);\n const remainder = parts.slice(i).join(path.sep);\n return remainder ? `${real}${path.sep}${remainder}` : real;\n } catch {\n // keep walking up\n }\n }\n return p;\n}\n\nfunction isUnderDir(real: string, dir: string): boolean {\n return real === dir || real.startsWith(dir + path.sep);\n}\n\nfunction assertSafePath(filePath: string): string {\n const resolved = path.resolve(filePath);\n const real = realOrBest(resolved);\n if (!isUnderDir(real, HOME) && !isUnderDir(real, CWD) && !isUnderDir(real, TMPDIR)) {\n throw new Error(`Path is outside allowed directories (home or cwd): ${real}`);\n }\n return resolved;\n}\n\nexport interface ReadFileResult {\n path: string;\n content: string;\n size: number;\n truncated: boolean;\n encoding: \"utf-8\";\n}\n\nexport async function readFile(filePath: string): Promise<ReadFileResult> {\n const resolved = assertSafePath(filePath);\n if (!fs.existsSync(resolved)) {\n throw new Error(`File not found: ${resolved}`);\n }\n const stat = fs.statSync(resolved);\n if (stat.isDirectory()) {\n throw new Error(`Path is a directory, not a file: ${resolved}. Use /file list instead.`);\n }\n const size = stat.size;\n const buf = Buffer.alloc(Math.min(size, MAX_READ_BYTES));\n const fd = fs.openSync(resolved, \"r\");\n try {\n fs.readSync(fd, buf, 0, buf.length, 0);\n } finally {\n fs.closeSync(fd);\n }\n return {\n path: resolved,\n content: buf.toString(\"utf-8\"),\n size,\n truncated: size > MAX_READ_BYTES,\n encoding: \"utf-8\",\n };\n}\n\nexport interface FileEntry {\n name: string;\n type: \"file\" | \"dir\";\n size: number;\n}\n\nexport interface ListFilesResult {\n path: string;\n entries: FileEntry[];\n total: number;\n}\n\nexport async function listFiles(\n dirPath: string,\n opts: { recursive?: boolean } = {}\n): Promise<ListFilesResult> {\n const resolved = assertSafePath(dirPath);\n if (!fs.existsSync(resolved)) {\n throw new Error(`Directory not found: ${resolved}`);\n }\n const stat = fs.statSync(resolved);\n if (!stat.isDirectory()) {\n throw new Error(`Path is a file, not a directory: ${resolved}. Use /file read instead.`);\n }\n\n const entries: FileEntry[] = [];\n\n function walk(dir: string, prefix: string) {\n const items = fs.readdirSync(dir, { withFileTypes: true });\n for (const item of items) {\n const rel = prefix ? `${prefix}/${item.name}` : item.name;\n if (item.isDirectory()) {\n entries.push({ name: rel, type: \"dir\", size: 0 });\n if (opts.recursive) walk(path.join(dir, item.name), rel);\n } else {\n const s = fs.statSync(path.join(dir, item.name));\n entries.push({ name: rel, type: \"file\", size: s.size });\n }\n }\n }\n\n walk(resolved, \"\");\n return { path: resolved, entries, total: entries.length };\n}\n","import pc from \"picocolors\";\nimport type {\n LLMClient,\n Message,\n ToolDefinition,\n ToolResultBlock,\n StreamChunk,\n} from \"./llm/types.js\";\nimport type { McpManager } from \"./mcp/client.js\";\nimport { assembleSystemPrompt } from \"./prompt.js\";\nimport { withRetry } from \"./retry.js\";\nimport { log } from \"./logger.js\";\nimport { onBeforeToolExec, type HookContext } from \"./hooks.js\";\nimport { memoryRecall } from \"./memory.js\";\nimport type { HooksConfig } from \"./config.js\";\n\nexport interface DelegationResult {\n profile: string;\n task: string;\n response: string;\n toolsUsed: string[];\n turns: number;\n success: boolean;\n error?: string;\n}\n\nexport interface DelegateOptions {\n maxTurns?: number; // max tool loop iterations (default: 10)\n silent?: boolean; // suppress output (default: false)\n tools?: ToolDefinition[]; // tools available to sub-agent\n hooksConfig?: HooksConfig; // guardrail config for tool execution\n}\n\nconst isRetryable = (err: unknown): boolean => {\n if (err instanceof Error) {\n const msg = err.message.toLowerCase();\n return msg.includes(\"rate\") || msg.includes(\"timeout\") || msg.includes(\"econnreset\");\n }\n return false;\n};\n\n/**\n * Run a task with a specific profile as a non-interactive sub-agent.\n * The sub-agent gets its own system prompt (from profile), runs a mini agent loop\n * (LLM → tools → LLM → ...), and returns the final text response.\n *\n * Reuses the parent's LLM client and MCP connections.\n */\nexport async function delegateTask(\n task: string,\n profile: string,\n client: LLMClient,\n mcpManager: McpManager,\n options: DelegateOptions = {},\n): Promise<DelegationResult> {\n // Route @name profiles to remote delegation via MCP server mode.\n if (profile.startsWith(\"@\")) {\n const remoteName = profile.slice(1).trim();\n if (!remoteName) {\n return {\n profile,\n task,\n response: \"\",\n toolsUsed: [],\n turns: 0,\n success: false,\n error: \"empty remote agent name\",\n };\n }\n // Lazy import to insulate against future cycles between delegate.ts\n // and delegate-remote.ts → server/*. The static graph is acyclic today\n // but this is cheap insurance.\n const { delegateRemote } = await import(\"./delegate-remote.js\");\n return delegateRemote(task, remoteName, {});\n }\n\n const maxTurns = options.maxTurns ?? 10;\n const silent = options.silent ?? false;\n const tools = options.tools;\n\n try {\n // Load profile-specific system prompt\n const { prompt: systemPrompt } = assembleSystemPrompt(undefined, profile);\n\n // Build the delegation prompt\n const delegationPrompt = `${systemPrompt}\n\n<delegation>\nYou are being delegated a specific task by the primary agent. Complete this task thoroughly and return your result. You have access to tools if needed. Focus on the task — do not ask follow-up questions, just do your best with what you have.\n</delegation>`;\n\n // Inject relevant memories into delegation prompt\n let finalDelegationPrompt = delegationPrompt;\n try {\n const recall = await memoryRecall(task, { limit: 3, compact: true });\n if (recall.total > 0) {\n finalDelegationPrompt += `\\n\\n<relevant-memories>\\n${recall.text}\\n</relevant-memories>`;\n }\n } catch { /* memory unavailable, proceed without */ }\n\n const messages: Message[] = [\n { role: \"user\", content: task },\n ];\n\n const toolsUsed: string[] = [];\n let turns = 0;\n\n // Collect streamed text\n const onChunk: (chunk: StreamChunk) => void = silent\n ? () => {}\n : (chunk) => {\n if (chunk.type === \"text\" && chunk.text) {\n process.stdout.write(chunk.text);\n }\n };\n\n // Initial LLM call\n let response = await withRetry(\n () => client.chat(finalDelegationPrompt, messages, onChunk, tools),\n { maxAttempts: 2, baseDelay: 1000, retryable: isRetryable },\n );\n\n messages.push(response.message);\n\n // Tool loop (same pattern as agent.ts)\n while (response.toolUses.length > 0 && turns < maxTurns) {\n turns++;\n\n const toolResults: ToolResultBlock[] = await Promise.all(\n response.toolUses.map(async (toolUse) => {\n if (!silent) {\n process.stdout.write(pc.dim(` [${profile}:${toolUse.name}...]\\n`));\n }\n toolsUsed.push(toolUse.name);\n\n // Guardrail check (same as main agent)\n if (options.hooksConfig?.rulesCheck) {\n try {\n const hookCtx: HookContext = { mcpManager, config: options.hooksConfig };\n const check = await onBeforeToolExec(toolUse.name, toolUse.input, hookCtx);\n if (!check.allow) {\n return {\n type: \"tool_result\" as const,\n tool_use_id: toolUse.id,\n content: `BLOCKED by guardrail: ${check.reason}`,\n is_error: true,\n };\n }\n } catch { /* guardrail check failed, allow */ }\n }\n\n try {\n const result = await mcpManager.callTool(toolUse.name, toolUse.input);\n return {\n type: \"tool_result\" as const,\n tool_use_id: toolUse.id,\n content: result,\n };\n } catch (err) {\n return {\n type: \"tool_result\" as const,\n tool_use_id: toolUse.id,\n content: `Error: ${err instanceof Error ? err.message : String(err)}`,\n is_error: true,\n };\n }\n }),\n );\n\n messages.push({ role: \"user\", content: toolResults });\n\n response = await withRetry(\n () => client.chat(finalDelegationPrompt, messages, onChunk, tools),\n { maxAttempts: 2, baseDelay: 1000, retryable: isRetryable },\n );\n\n messages.push(response.message);\n }\n\n // Extract final text response\n const finalMessage = response.message;\n const responseText = typeof finalMessage.content === \"string\"\n ? finalMessage.content\n : finalMessage.content\n .filter((b) => b.type === \"text\")\n .map((b) => (\"text\" in b ? b.text : \"\"))\n .join(\"\");\n\n return {\n profile,\n task,\n response: responseText,\n toolsUsed: [...new Set(toolsUsed)],\n turns,\n success: true,\n };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n log.warn(\"delegate\", `Delegation to ${profile} failed: ${error}`);\n return {\n profile,\n task,\n response: \"\",\n toolsUsed: [],\n turns: 0,\n success: false,\n error,\n };\n }\n}\n\n/**\n * Delegate a task to multiple profiles in parallel.\n * Useful for: write + review, research + summarize, etc.\n */\nexport async function delegateParallel(\n tasks: Array<{ task: string; profile: string }>,\n client: LLMClient,\n mcpManager: McpManager,\n options: DelegateOptions = {},\n): Promise<DelegationResult[]> {\n return Promise.all(\n tasks.map(({ task, profile }) =>\n delegateTask(task, profile, client, mcpManager, { ...options, silent: true }),\n ),\n );\n}\n\n/**\n * Delegate a pipeline of tasks sequentially — each task receives the previous result.\n * Useful for: draft → review → polish pipelines.\n */\nexport async function delegatePipeline(\n steps: Array<{ profile: string; taskTemplate: string }>,\n initialInput: string,\n client: LLMClient,\n mcpManager: McpManager,\n options: DelegateOptions = {},\n): Promise<DelegationResult[]> {\n const results: DelegationResult[] = [];\n let previousResult = initialInput;\n\n for (const step of steps) {\n const task = step.taskTemplate.replace(\"{{input}}\", previousResult);\n\n if (!options.silent) {\n process.stdout.write(pc.dim(`\\n [delegating to ${step.profile}...]\\n`));\n }\n\n const result = await delegateTask(task, step.profile, client, mcpManager, {\n ...options,\n silent: true,\n });\n results.push(result);\n\n if (!result.success) break;\n previousResult = result.response;\n }\n\n return results;\n}\n","import pc from \"picocolors\";\nimport * as p from \"@clack/prompts\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport os from \"node:os\";\nimport type { McpManager } from \"./mcp/client.js\";\nimport type { LLMClient, Message } from \"./llm/types.js\";\nimport type { HooksConfig } from \"./config.js\";\nimport { log } from \"./logger.js\";\nimport {\n computePersonality,\n syncPersonalityToCore,\n formatWellbeingNudge,\n shouldFireNudge,\n} from \"./personality.js\";\nimport { memoryRecall, memoryContext, reminderCheck, memoryLog, isMemoryInitialized, memoryStore } from \"./memory.js\";\nimport { loadUserIdentity } from \"./user-identity.js\";\nimport { shouldAutoPostmortem, generatePostmortemReport, savePostmortem } from \"./postmortem.js\";\nimport {\n validateCandidate,\n writeSkillToFile,\n mergeSkillInFile,\n appendCrystallizationLog,\n appendRejection,\n loadRejectedNames,\n incrementSuggestionCount,\n loadSuggestionCounts,\n} from \"./crystallization.js\";\nimport type { ObservationSession } from \"./observation.js\";\nimport {\n loadUserModel,\n saveUserModel,\n createEmptyModel,\n aggregateSession,\n computeProfile,\n feedForward,\n type SessionSnapshot,\n type PersonalityOverrides,\n} from \"./user-model.js\";\n\nfunction getTimeContext(): string {\n const now = new Date();\n const hour = now.getHours();\n const days = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"];\n const day = days[now.getDay()];\n\n let period: string;\n if (hour < 6) period = \"late-night\";\n else if (hour < 12) period = \"morning\";\n else if (hour < 17) period = \"afternoon\";\n else if (hour < 21) period = \"evening\";\n else period = \"night\";\n\n const timeStr = now.toLocaleTimeString([], { hour: \"2-digit\", minute: \"2-digit\" });\n const dateStr = now.toLocaleDateString();\n\n return `<time-context>\\nCurrent time: ${dateStr} ${timeStr} (${period}, ${day})\\nAdapt your tone naturally — don't announce the time, just be contextually appropriate.\\n</time-context>`;\n}\n\nexport interface HookContext {\n mcpManager: McpManager;\n config: HooksConfig;\n llmClient?: LLMClient; // needed for auto-postmortem generation\n}\n\nlet isHookCall = false;\nlet sessionStartTime: number = Date.now();\n\nexport function getSessionStartTime(): number {\n return sessionStartTime;\n}\n\nexport async function onSessionStart(\n ctx: HookContext,\n): Promise<{ greeting?: string; contextInjection?: string; firstRun?: boolean; visibleReminders?: string[]; resumeTopic?: string }> {\n let greeting = \"\";\n let contextInjection = \"\";\n let firstRun = false;\n let resumeTopic: string | undefined;\n const visibleReminders: string[] = [];\n\n // Detect first run via memory_recall\n if (!isMemoryInitialized()) {\n // Memory system failed to init — skip memory operations but don't treat as first run\n firstRun = false;\n } else {\n try {\n isHookCall = true;\n const recallResult = await memoryRecall(\"*\", { limit: 1 });\n firstRun = recallResult.total === 0;\n } catch {\n firstRun = true;\n } finally {\n isHookCall = false;\n }\n }\n\n if (firstRun) {\n const userIdentity = loadUserIdentity();\n\n if (userIdentity) {\n // First run WITH user profile — personalized introduction\n contextInjection = `<first-session>\nThis is your FIRST conversation with ${userIdentity.name}. They just set up their profile:\n- Role: ${userIdentity.roleLabel}\n- Expertise: ${userIdentity.expertiseLabel}\n- Style preference: ${userIdentity.styleLabel}\n${userIdentity.workingOn ? `- Working on: ${userIdentity.workingOn}` : \"\"}\n${userIdentity.notes ? `- Notes: ${userIdentity.notes}` : \"\"}\n\nIntroduce yourself warmly:\n- Greet them by name\n- Acknowledge what they do and what they're working on (if provided)\n- Show you understand their style preference (e.g., if they want concise answers, keep it tight)\n- Mention you'll remember what matters across conversations\n- Keep it to 3-5 sentences, natural tone — make them feel like you GET them\n</first-session>`;\n } else {\n // First run WITHOUT user profile — generic introduction\n contextInjection = `<first-session>\nThis is your FIRST conversation with this user. Introduce yourself warmly:\n- Share your name and that you're their personal AI companion\n- Mention you'll remember what matters across conversations\n- Ask what they'd like to be called\n- Mention they can set up their profile with /profile edit for a more personalized experience\n- Keep it to 3-4 sentences, natural tone\n</first-session>`;\n }\n\n // Still add time context\n const timeContext = getTimeContext();\n contextInjection = `<session-context>\\n${timeContext}\\n</session-context>\\n${contextInjection}`;\n\n return {\n greeting: undefined,\n contextInjection,\n firstRun,\n visibleReminders,\n resumeTopic: undefined,\n };\n }\n\n // Returning user flow\n if (ctx.config.memoryRecall) {\n try {\n isHookCall = true;\n const contextResult = await memoryContext(\"session context\");\n if (contextResult.memoriesUsed > 0) {\n greeting += contextResult.text;\n }\n } catch (err) {\n log.warn(\"hooks\", \"memory_context recall failed\", err);\n } finally {\n isHookCall = false;\n }\n }\n\n if (ctx.config.sessionResume) {\n try {\n isHookCall = true;\n const result = await ctx.mcpManager.callTool(\"identity_summary\", {});\n if (result && !result.startsWith(\"Error\")) {\n if (greeting) greeting += \"\\n\";\n greeting += result;\n\n // Extract resume topic\n const topicMatch = result.match(/(?:resume|last|topic)[:\\s]*(.+?)(?:\\n|$)/i);\n if (topicMatch) {\n resumeTopic = topicMatch[1].trim();\n }\n }\n } catch (err) {\n log.warn(\"hooks\", \"identity_summary failed\", err);\n } finally {\n isHookCall = false;\n }\n }\n\n // Time context\n const timeContext = getTimeContext();\n if (greeting) greeting += \"\\n\" + timeContext;\n else greeting = timeContext;\n\n // Check reminders\n try {\n isHookCall = true;\n const reminders = reminderCheck();\n if (reminders.length > 0) {\n const reminderText = reminders.map(r => r.content).join(\"\\n\");\n greeting += \"\\n\\n<pending-reminders>\\n\" + reminderText + \"\\n</pending-reminders>\";\n for (const r of reminders) {\n visibleReminders.push(r.content);\n }\n }\n } catch (err) {\n log.debug(\"hooks\", \"reminder_check failed\", err);\n } finally {\n isHookCall = false;\n }\n\n // Compute initial personality state (with feed-forward from user model)\n if (ctx.config.personalityAdapt !== false) {\n sessionStartTime = Date.now();\n const hour = new Date().getHours();\n let period: string;\n if (hour < 6) period = \"late-night\";\n else if (hour < 12) period = \"morning\";\n else if (hour < 17) period = \"afternoon\";\n else if (hour < 21) period = \"evening\";\n else period = \"night\";\n\n const state = computePersonality({\n timePeriod: period,\n sessionMinutes: 0,\n turnCount: 0,\n });\n\n // Load user model for feed-forward overrides\n try {\n const model = await loadUserModel();\n if (model) {\n const overrides = feedForward(model);\n if (overrides) {\n log.debug(\"hooks\", `Feed-forward active (trust=${model.profile.trustScore.toFixed(2)}, sessions=${model.profile.totalSessions})`);\n\n // Apply energy override (e.g., night owls stay \"steady\" instead of \"reflective\")\n if (overrides.energyOverride && (period === \"late-night\" || period === \"night\")) {\n (state as { energy: string }).energy = overrides.energyOverride as typeof state.energy;\n }\n\n // Apply default-to-Personal-mode when sentiment is worsening\n if (overrides.defaultToPersonalMode && state.activeMode === \"Default\") {\n (state as { activeMode: string }).activeMode = \"Personal\";\n }\n\n // Inject trust context into greeting\n if (overrides.compactGreeting) {\n greeting += \"\\n<user-model-context>High trust user (score: \" +\n model.profile.trustScore.toFixed(2) +\n \", \" + model.profile.totalSessions +\n \" sessions). Keep greeting compact — they know you well.</user-model-context>\";\n }\n\n // Surface sentiment trend if concerning\n if (model.profile.sentimentTrend === \"worsening\") {\n greeting += \"\\n<user-model-context>Sentiment trend is worsening across recent sessions. Be more attentive and patient.</user-model-context>\";\n }\n }\n }\n } catch (err) {\n log.debug(\"hooks\", \"user model feed-forward failed\", err);\n }\n\n // Sync to acore (fire-and-forget)\n syncPersonalityToCore(state, ctx.mcpManager).catch(() => {});\n\n // Add wellbeing nudge to context if applicable (with adaptive filtering)\n const nudge = formatWellbeingNudge(state);\n if (nudge && state.wellbeingNudge) {\n let fireNudge = true;\n try {\n const model = await loadUserModel();\n if (model && model.sessions.length >= 5) {\n const profile = computeProfile(model.sessions, model.sessions.length);\n fireNudge = shouldFireNudge(state.wellbeingNudge, profile);\n }\n } catch {\n // No model yet — always fire\n }\n if (fireNudge) {\n greeting += \"\\n\" + nudge;\n }\n }\n }\n\n if (greeting) {\n contextInjection = `<session-context>\\n${greeting}\\n</session-context>`;\n }\n\n return {\n greeting: greeting || undefined,\n contextInjection: contextInjection || undefined,\n firstRun,\n visibleReminders,\n resumeTopic,\n };\n}\n\nexport async function onBeforeToolExec(\n toolName: string,\n toolArgs: Record<string, unknown>,\n ctx: HookContext,\n): Promise<{ allow: boolean; reason?: string }> {\n if (!ctx.config.rulesCheck || isHookCall) {\n return { allow: true };\n }\n\n if (toolName === \"rules_check\") {\n return { allow: true };\n }\n\n try {\n isHookCall = true;\n const description = `${toolName}(${JSON.stringify(toolArgs)})`;\n const result = await ctx.mcpManager.callTool(\"rules_check\", {\n action: description,\n });\n\n try {\n const parsed = JSON.parse(result) as {\n violations?: string[];\n };\n if (parsed.violations && parsed.violations.length > 0) {\n return {\n allow: false,\n reason: parsed.violations.join(\"; \"),\n };\n }\n } catch (err) {\n log.debug(\"hooks\", \"rules_check parse failed\", err);\n }\n\n return { allow: true };\n } catch (err) {\n log.warn(\"hooks\", \"rules_check call failed\", err);\n return { allow: true };\n } finally {\n isHookCall = false;\n }\n}\n\nexport async function onWorkflowMatch(\n userInput: string,\n ctx: HookContext,\n): Promise<{ name: string; steps: string } | null> {\n if (!ctx.config.workflowSuggest) {\n return null;\n }\n\n try {\n isHookCall = true;\n const result = await ctx.mcpManager.callTool(\"workflow_list\", {});\n\n const workflows = JSON.parse(result) as Array<{\n name: string;\n description?: string;\n steps?: string[];\n }>;\n\n const inputLower = userInput.toLowerCase();\n\n for (const wf of workflows) {\n const nameLower = wf.name.toLowerCase();\n\n // Check if user input contains workflow name\n if (inputLower.includes(nameLower)) {\n const steps = (wf.steps || [])\n .map((s, i) => `${i + 1}. ${s}`)\n .join(\"\\n\");\n return { name: wf.name, steps };\n }\n\n // Check significant words from description\n if (wf.description) {\n const words = wf.description\n .split(/\\s+/)\n .filter((w) => w.length > 4)\n .map((w) => w.toLowerCase());\n\n for (const word of words) {\n if (inputLower.includes(word)) {\n const steps = (wf.steps || [])\n .map((s, i) => `${i + 1}. ${s}`)\n .join(\"\\n\");\n return { name: wf.name, steps };\n }\n }\n }\n }\n\n return null;\n } catch (err) {\n log.debug(\"hooks\", \"workflow_list failed\", err);\n return null;\n } finally {\n isHookCall = false;\n }\n}\n\nexport async function onSessionEnd(\n ctx: HookContext,\n messages: Message[],\n sessionId: string,\n observationSession?: ObservationSession,\n): Promise<void> {\n try {\n // Auto-save conversation to amem memory_log\n if (ctx.config.autoSessionSave && messages.length > 2) {\n console.log(pc.dim(\"\\n Saving conversation to memory...\"));\n\n // Save last 50 text messages to memory_log\n const textMessages = messages\n .filter((m) => typeof m.content === \"string\")\n .slice(-50);\n\n for (const msg of textMessages) {\n try {\n isHookCall = true;\n memoryLog(sessionId, msg.role, (msg.content as string).slice(0, 5000));\n } catch (err) {\n log.debug(\"hooks\", \"memory_log write failed for \" + sessionId, err);\n } finally {\n isHookCall = false;\n }\n }\n\n // Update session resume in identity\n let lastUserMsg = \"\";\n for (let i = messages.length - 1; i >= 0; i--) {\n if (\n messages[i].role === \"user\" &&\n typeof messages[i].content === \"string\"\n ) {\n lastUserMsg = messages[i].content as string;\n break;\n }\n }\n\n if (lastUserMsg) {\n try {\n isHookCall = true;\n await ctx.mcpManager.callTool(\"identity_update_session\", {\n resume: lastUserMsg.slice(0, 200),\n topics: \"See conversation history\",\n decisions: \"See conversation history\",\n });\n } finally {\n isHookCall = false;\n }\n }\n\n console.log(pc.dim(` Saved ${textMessages.length} messages (session: ${sessionId})`));\n }\n\n // Update per-project .acore/context.md if it exists\n const projectContextPath = path.join(process.cwd(), \".acore\", \"context.md\");\n if (fs.existsSync(projectContextPath) && messages.length > 2) {\n try {\n let contextContent = fs.readFileSync(projectContextPath, \"utf-8\");\n const now = new Date().toISOString().split(\"T\")[0];\n\n // Extract last user message for resume\n let lastUserMsg = \"\";\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i].role === \"user\" && typeof messages[i].content === \"string\") {\n lastUserMsg = (messages[i].content as string).slice(0, 200);\n break;\n }\n }\n\n // Update Session section in context.md\n const sessionPattern = /## Session\\n[\\s\\S]*?(?=\\n## |$)/;\n if (sessionPattern.test(contextContent)) {\n const newSession = `## Session\\n- Last updated: ${now}\\n- Resume: ${lastUserMsg || \"See conversation history\"}\\n- Active topics: [see memory]\\n- Recent decisions: [see memory]\\n- Temp notes: [cleared]`;\n contextContent = contextContent.replace(sessionPattern, newSession);\n fs.writeFileSync(projectContextPath, contextContent, \"utf-8\");\n log.debug(\"hooks\", `Updated project context: ${projectContextPath}`);\n }\n } catch (err) {\n log.debug(\"hooks\", \"project context update failed\", err);\n }\n }\n\n // Persist final personality state\n const sessionMinutes = Math.round((Date.now() - sessionStartTime) / 60000);\n const hour = new Date().getHours();\n let period: string;\n if (hour < 6) period = \"late-night\";\n else if (hour < 12) period = \"morning\";\n else if (hour < 17) period = \"afternoon\";\n else if (hour < 21) period = \"evening\";\n else period = \"night\";\n\n const turnCount = messages.filter((m) => m.role === \"user\").length;\n const finalState = computePersonality({\n timePeriod: period,\n sessionMinutes,\n turnCount,\n });\n\n if (ctx.config.personalityAdapt !== false) {\n try {\n isHookCall = true;\n await syncPersonalityToCore(finalState, ctx.mcpManager);\n } finally {\n isHookCall = false;\n }\n }\n\n // Session rating prompt\n let sessionRating: string | undefined;\n if (ctx.config.evalPrompt) {\n const rating = await p.select({\n message: \"Quick rating for this session?\",\n options: [\n { value: \"great\", label: \"Great\" },\n { value: \"good\", label: \"Good\" },\n { value: \"okay\", label: \"Okay\" },\n { value: \"skip\", label: \"Skip\" },\n ],\n initialValue: \"skip\",\n });\n\n if (!p.isCancel(rating) && rating !== \"skip\") {\n sessionRating = rating as string;\n try {\n isHookCall = true;\n await ctx.mcpManager.callTool(\"eval_log\", {\n rating: sessionRating,\n highlights: \"Quick session rating\",\n improvements: \"\",\n });\n } finally {\n isHookCall = false;\n }\n }\n }\n\n // Aggregate session into user model (v0.27)\n if (turnCount >= 2 && sessionMinutes >= 1) {\n try {\n const snapshot: SessionSnapshot = {\n sessionId,\n date: new Date().toISOString().split(\"T\")[0],\n durationMinutes: sessionMinutes,\n turnCount,\n dominantSentiment: finalState.sentiment.dominant,\n avgFrustration: finalState.sentiment.frustration,\n avgExcitement: finalState.sentiment.excitement,\n avgConfusion: finalState.sentiment.confusion,\n avgFatigue: finalState.sentiment.fatigue,\n toolCalls: observationSession?.stats.toolCalls ?? 0,\n toolErrors: observationSession?.stats.toolErrors ?? 0,\n blockers: observationSession?.stats.blockers ?? 0,\n milestones: observationSession?.stats.milestones ?? 0,\n topicShifts: observationSession?.stats.topicShifts ?? 0,\n peakEnergy: finalState.energy,\n primaryMode: finalState.activeMode,\n timePeriod: period,\n rating: sessionRating,\n hadPostmortem: false, // updated below if postmortem is generated\n wellbeingNudges: finalState.wellbeingNudge ? [finalState.wellbeingNudge] : [],\n };\n\n const model = (await loadUserModel()) ?? createEmptyModel();\n const updated = aggregateSession(model, snapshot);\n await saveUserModel(updated);\n log.debug(\"hooks\", `User model updated (session ${updated.profile.totalSessions})`);\n\n // Sync model metrics to acore dynamics section\n if (ctx.config.personalityAdapt !== false) {\n try {\n isHookCall = true;\n await syncPersonalityToCore(finalState, ctx.mcpManager, {\n trustScore: updated.profile.trustScore,\n totalSessions: updated.profile.totalSessions,\n sentimentTrend: updated.profile.sentimentTrend,\n });\n } finally {\n isHookCall = false;\n }\n }\n } catch (err) {\n log.debug(\"hooks\", \"user model aggregation failed\", err);\n }\n }\n\n // Auto post-mortem (smart trigger)\n if (\n ctx.config.autoPostmortem !== false &&\n observationSession &&\n shouldAutoPostmortem(observationSession, messages)\n ) {\n try {\n const client = ctx.llmClient;\n if (client) {\n // Load rejected skill names for feedback loop\n const rejectionsPath = path.join(\n os.homedir(),\n \".aman-agent\",\n \"crystallization-rejections.json\",\n );\n const rejectedNames = await loadRejectedNames(rejectionsPath);\n\n const report = await generatePostmortemReport(\n sessionId,\n messages,\n observationSession,\n client,\n undefined,\n rejectedNames,\n );\n if (report) {\n const filePath = await savePostmortem(report);\n console.log(pc.dim(`\\n Post-mortem saved → ${filePath}`));\n\n // Store actionable patterns as memories\n for (const pattern of report.patterns) {\n try {\n await memoryStore({\n content: pattern,\n type: \"pattern\",\n tags: [\"postmortem\", \"auto\"],\n confidence: 0.7,\n });\n } catch {\n // Silent — don't block exit\n }\n }\n\n // Crystallization prompt loop (v0.26 + v0.28 reinforcement)\n if (\n report.crystallizationCandidates &&\n report.crystallizationCandidates.length > 0\n ) {\n const skillsMdPath = path.join(os.homedir(), \".askill\", \"skills.md\");\n const logPath = path.join(\n os.homedir(),\n \".aman-agent\",\n \"crystallization-log.json\",\n );\n const rejectionsPath2 = path.join(\n os.homedir(),\n \".aman-agent\",\n \"crystallization-rejections.json\",\n );\n const suggestionsPath = path.join(\n os.homedir(),\n \".aman-agent\",\n \"crystallization-suggestions.json\",\n );\n const postmortemFilename = `${report.date}-${report.sessionId.slice(0, 4)}.md`;\n\n console.log(\n pc.dim(`\\n Crystallization candidates: ${report.crystallizationCandidates.length}`),\n );\n\n let skipAll = false;\n for (const rawCandidate of report.crystallizationCandidates) {\n if (skipAll) break;\n const candidate = validateCandidate(rawCandidate);\n if (!candidate) {\n log.debug(\"hooks\", \"candidate failed validation\");\n continue;\n }\n\n // Track suggestion count for reinforcement\n const suggestCount = await incrementSuggestionCount(candidate.name, suggestionsPath);\n const reinforced = suggestCount >= 3;\n\n const message = reinforced\n ? `Crystallize \"${candidate.name}\"? (suggested ${suggestCount}× across sessions — high confidence)`\n : `Crystallize \"${candidate.name}\" as a reusable skill?`;\n\n const choice = await p.select({\n message,\n options: [\n { value: \"accept\", label: reinforced ? \"Yes — recommended (seen multiple times)\" : \"Yes — write to ~/.askill/skills.md\" },\n { value: \"reject\", label: \"No — skip this one\" },\n { value: \"skip-all\", label: \"Skip all crystallization for this session\" },\n ],\n initialValue: reinforced ? \"accept\" : \"reject\",\n });\n\n if (p.isCancel(choice) || choice === \"skip-all\") {\n skipAll = true;\n break;\n }\n\n if (choice === \"accept\") {\n const result = await writeSkillToFile(\n candidate,\n skillsMdPath,\n postmortemFilename,\n );\n if (result.written) {\n console.log(\n pc.green(` ✓ Crystallized: ${candidate.name} → ${result.filePath}`),\n );\n console.log(pc.dim(` Triggers: ${candidate.triggers.join(\", \")}`));\n console.log(pc.dim(` Will auto-activate next session.`));\n await appendCrystallizationLog(\n {\n name: candidate.name,\n createdAt: new Date().toISOString(),\n fromPostmortem: postmortemFilename,\n confidence: candidate.confidence,\n triggers: candidate.triggers,\n },\n logPath,\n );\n } else if (result.collidesWith) {\n // Collision detected — offer merge\n const mergeChoice = await p.select({\n message: `\"${candidate.name}\" collides with existing \"${result.collidesWith}\". Merge?`,\n options: [\n { value: \"merge\", label: `Yes — replace \"${result.collidesWith}\" with updated version` },\n { value: \"skip\", label: \"No — keep existing\" },\n ],\n initialValue: \"merge\",\n });\n\n if (!p.isCancel(mergeChoice) && mergeChoice === \"merge\") {\n const mergeResult = await mergeSkillInFile(\n candidate,\n result.collidesWith,\n skillsMdPath,\n postmortemFilename,\n );\n if (mergeResult.written) {\n console.log(pc.green(` ✓ Merged: ${candidate.name} (replaced \"${result.collidesWith}\")`));\n await appendCrystallizationLog(\n {\n name: candidate.name,\n createdAt: new Date().toISOString(),\n fromPostmortem: postmortemFilename,\n confidence: candidate.confidence,\n triggers: candidate.triggers,\n },\n logPath,\n );\n } else {\n console.log(pc.yellow(` ⊘ Merge failed: ${mergeResult.reason}`));\n }\n } else {\n console.log(pc.dim(` Kept existing: ${result.collidesWith}`));\n }\n } else {\n console.log(pc.yellow(` ⊘ Could not crystallize: ${result.reason}`));\n }\n } else {\n console.log(pc.dim(` Skipped: ${candidate.name}`));\n await appendRejection(candidate, postmortemFilename, rejectionsPath2);\n }\n }\n }\n }\n }\n } catch (err) {\n log.debug(\"hooks\", \"auto post-mortem failed\", err);\n }\n }\n } catch (err) {\n log.warn(\"hooks\", \"session end hook failed\", err);\n }\n}\n","import type { McpManager } from \"./mcp/client.js\";\nimport type { UserProfile } from \"./user-model.js\";\nimport { log } from \"./logger.js\";\n\nexport interface PersonalityState {\n currentRead: string;\n energy: \"high-drive\" | \"steady\" | \"reflective\";\n activeMode: \"Default\" | \"Focused Work\" | \"Creative\" | \"Personal\";\n sleepReminder: boolean;\n wellbeingNudge: string | null;\n sentiment: SentimentRead;\n}\n\nexport interface SentimentRead {\n frustration: number; // 0-1\n excitement: number; // 0-1\n confusion: number; // 0-1\n fatigue: number; // 0-1\n dominant: \"neutral\" | \"frustrated\" | \"excited\" | \"confused\" | \"fatigued\";\n}\n\nexport interface PersonalitySignals {\n timePeriod: string;\n sessionMinutes: number;\n turnCount: number;\n recentMessages?: string[]; // last N user messages for sentiment analysis\n}\n\n// --- Sentiment Detection (keyword-based, zero latency) ---\n\nconst FRUSTRATION_SIGNALS = [\n /\\b(ugh|argh|damn|dammit|wtf|ffs|shit|fuck|crap|hate this|stupid|broken|still not|doesn't work|not working|won't work|keeps failing|again\\?!|what the hell|for the love of|give up|giving up|fed up)\\b/i,\n /\\b(why (is|does|won't|can't|isn't)|same (error|issue|problem|bug)|tried everything|nothing works|no idea|lost|stuck|frustrated|annoying|impossible)\\b/i,\n /!{2,}/, // multiple exclamation marks\n /\\?{2,}/, // multiple question marks (exasperation)\n];\n\nconst EXCITEMENT_SIGNALS = [\n /\\b(amazing|awesome|perfect|brilliant|love it|yes!|nice!|great!|finally|it works|nailed it|beautiful|incredible|exactly|that's it|hell yeah|wow|woah|let's go)\\b/i,\n /\\b(excited|pumped|stoked|can't wait|this is great|so cool|love this)\\b/i,\n /!{1,}.*(!|🎉|🚀|✨|💪|🔥)/,\n];\n\nconst CONFUSION_SIGNALS = [\n /\\b(confused|don't understand|what do you mean|huh\\??|makes no sense|i'm lost|unclear|what\\?|how does that|wait what|can you explain|i don't get)\\b/i,\n /\\b(which one|what's the difference|should i|not sure (if|what|how|why|whether))\\b/i,\n];\n\nconst FATIGUE_SIGNALS = [\n /\\b(tired|exhausted|long day|need (a )?break|calling it|wrapping up|done for (now|today)|heading (to bed|off)|good night|gn|signing off|one more thing then|last one)\\b/i,\n /\\b(brain (is )?fried|can't think|eyes (are )?heavy|running on fumes|barely awake)\\b/i,\n];\n\nfunction scorePatterns(text: string, patterns: RegExp[]): number {\n let hits = 0;\n for (const p of patterns) {\n if (p.test(text)) hits++;\n }\n return Math.min(hits / patterns.length, 1);\n}\n\n/**\n * Detect sentiment from recent user messages.\n * Lightweight keyword-based analysis — no LLM calls.\n */\nexport function detectSentiment(recentMessages: string[]): SentimentRead {\n if (recentMessages.length === 0) {\n return { frustration: 0, excitement: 0, confusion: 0, fatigue: 0, dominant: \"neutral\" };\n }\n\n // Weight recent messages more heavily (last message = 1.0, second-last = 0.6, third = 0.3)\n const weights = [1.0, 0.6, 0.3, 0.2, 0.1];\n let frustration = 0, excitement = 0, confusion = 0, fatigue = 0;\n let totalWeight = 0;\n\n for (let i = 0; i < Math.min(recentMessages.length, weights.length); i++) {\n const msg = recentMessages[recentMessages.length - 1 - i];\n const w = weights[i];\n totalWeight += w;\n\n frustration += scorePatterns(msg, FRUSTRATION_SIGNALS) * w;\n excitement += scorePatterns(msg, EXCITEMENT_SIGNALS) * w;\n confusion += scorePatterns(msg, CONFUSION_SIGNALS) * w;\n fatigue += scorePatterns(msg, FATIGUE_SIGNALS) * w;\n }\n\n if (totalWeight > 0) {\n frustration /= totalWeight;\n excitement /= totalWeight;\n confusion /= totalWeight;\n fatigue /= totalWeight;\n }\n\n // Determine dominant sentiment\n const scores = { frustrated: frustration, excited: excitement, confused: confusion, fatigued: fatigue };\n const maxKey = Object.entries(scores).reduce((a, b) => a[1] > b[1] ? a : b);\n const dominant = maxKey[1] > 0.15 ? maxKey[0] as SentimentRead[\"dominant\"] : \"neutral\";\n\n return { frustration, excitement, confusion, fatigue, dominant };\n}\n\n// --- Personality Computation ---\n\n/**\n * Compute personality state from current signals including sentiment.\n * Pure function — no side effects.\n */\nexport function computePersonality(signals: PersonalitySignals): PersonalityState {\n const { timePeriod, sessionMinutes, turnCount, recentMessages } = signals;\n\n // Detect sentiment from recent messages\n const sentiment = detectSentiment(recentMessages || []);\n\n // Energy curve: time + session + sentiment\n let energy: PersonalityState[\"energy\"] = \"steady\";\n if (timePeriod === \"morning\" && sentiment.dominant !== \"fatigued\") {\n energy = \"high-drive\";\n } else if (timePeriod === \"late-night\" || (timePeriod === \"night\" && sessionMinutes > 45)) {\n energy = \"reflective\";\n } else if (sentiment.dominant === \"fatigued\") {\n energy = \"reflective\";\n } else if (sentiment.dominant === \"excited\") {\n energy = \"high-drive\"; // match their energy\n } else if (timePeriod === \"afternoon\" && turnCount > 20) {\n energy = \"reflective\";\n }\n\n // Active mode: time + sentiment\n let activeMode: PersonalityState[\"activeMode\"] = \"Default\";\n if (timePeriod === \"late-night\") {\n activeMode = \"Personal\";\n } else if (sentiment.dominant === \"frustrated\" || sentiment.dominant === \"fatigued\") {\n activeMode = \"Personal\"; // warm, patient when they're struggling\n }\n\n // Current read: combines time context + sentiment\n const readParts: string[] = [];\n\n // Time-based read\n switch (timePeriod) {\n case \"late-night\":\n readParts.push(\"late night session\");\n if (sessionMinutes > 60) readParts.push(\"been going a while\");\n else readParts.push(\"quiet hours\");\n break;\n case \"morning\":\n readParts.push(\"morning session\");\n if (turnCount <= 3) readParts.push(\"just getting started\");\n else readParts.push(\"building momentum\");\n break;\n case \"afternoon\":\n readParts.push(\"afternoon session\");\n if (turnCount > 15) readParts.push(\"deep in flow\");\n else readParts.push(\"steady pace\");\n break;\n case \"evening\":\n readParts.push(\"evening session\");\n if (sessionMinutes > 60) readParts.push(\"long session\");\n break;\n case \"night\":\n readParts.push(\"night session\");\n if (sessionMinutes > 45) readParts.push(\"getting late\");\n break;\n }\n\n // Sentiment-based read\n switch (sentiment.dominant) {\n case \"frustrated\":\n readParts.push(\"user seems stuck or frustrated\");\n break;\n case \"excited\":\n readParts.push(\"user is energized and making progress\");\n break;\n case \"confused\":\n readParts.push(\"user may need clearer explanations\");\n break;\n case \"fatigued\":\n readParts.push(\"user seems tired\");\n break;\n }\n\n const currentRead = readParts.join(\", \");\n\n // Sleep guardian\n const sleepReminder =\n (timePeriod === \"late-night\" && sessionMinutes > 60) ||\n (timePeriod === \"night\" && sessionMinutes > 90);\n\n // Wellbeing nudges (beyond sleep)\n let wellbeingNudge: string | null = null;\n\n if (sleepReminder && sentiment.dominant === \"frustrated\") {\n wellbeingNudge = \"sleep-frustrated\";\n } else if (sleepReminder) {\n wellbeingNudge = \"sleep\";\n } else if (sentiment.dominant === \"frustrated\" && sessionMinutes > 90) {\n wellbeingNudge = \"break-frustrated\";\n } else if (sentiment.dominant === \"frustrated\" && turnCount > 15) {\n wellbeingNudge = \"step-back\";\n } else if (sentiment.dominant === \"fatigued\") {\n wellbeingNudge = \"rest\";\n } else if (sessionMinutes > 120) {\n wellbeingNudge = \"break-long-session\";\n }\n\n return { currentRead, energy, activeMode, sleepReminder, wellbeingNudge, sentiment };\n}\n\n// --- Wellbeing Nudge Formatting ---\n\nconst WELLBEING_NUDGES: Record<string, string> = {\n \"sleep\": `<wellbeing>\nIt's late and this session has been running a while. When there's a natural pause, gently mention they might want to wrap up soon. One brief mention is enough — don't be pushy.\n</wellbeing>`,\n\n \"sleep-frustrated\": `<wellbeing>\nIt's late, the session has been long, and the user seems frustrated. This is a tough combination. Acknowledge what they're dealing with is hard, suggest they sleep on it — fresh eyes in the morning often solve what hours of late-night debugging can't. Be warm, not condescending.\n</wellbeing>`,\n\n \"break-frustrated\": `<wellbeing>\nThe user has been at this for over 90 minutes and seems frustrated. If the conversation allows, gently suggest stepping away for a few minutes — a short break often unblocks what persistence can't. Frame it as a strategy, not giving up.\n</wellbeing>`,\n\n \"step-back\": `<wellbeing>\nThe user seems stuck or frustrated. Consider: offer to re-approach the problem from a different angle, break it into smaller pieces, or explain the underlying concept. Match their directness — don't over-soothe, just help them find a way forward.\n</wellbeing>`,\n\n \"rest\": `<wellbeing>\nThe user seems tired. Keep responses concise and to the point. If they mention wrapping up, support that. Don't add extra complexity or tangents.\n</wellbeing>`,\n\n \"break-long-session\": `<wellbeing>\nThis session has been running for over 2 hours. If there's a natural moment, a brief mention that a short break might help maintain focus is fine. Once is enough.\n</wellbeing>`,\n\n \"burnout-warning\": `<wellbeing>\nRecent patterns suggest the user may be approaching burnout — rising frustration, declining satisfaction, long or late sessions. Be extra mindful: keep responses concise, celebrate small wins, gently suggest breaks or scope reduction. Don't mention burnout directly unless they bring it up.\n</wellbeing>`,\n};\n\n/**\n * Format the appropriate wellbeing nudge for the current state.\n */\nexport function formatWellbeingNudge(state: PersonalityState): string | null {\n if (!state.wellbeingNudge) return null;\n return WELLBEING_NUDGES[state.wellbeingNudge] || null;\n}\n\n/**\n * Check whether a nudge should fire based on user model nudge stats.\n * If a nudge type has been fired 5+ times with avg rating below 0.4 (on 0-1 scale),\n * suppress it (return false). Otherwise allow (return true).\n * If no profile provided, always allows.\n */\nexport function shouldFireNudge(nudgeType: string, profile?: UserProfile): boolean {\n if (!profile) return true;\n\n const stats = profile.nudgeStats[nudgeType];\n if (!stats || stats.fired < 5) return true;\n\n // sessionRatingAfter is avg on 0-1 scale (0=frustrating, 1=great)\n // If avg rating after nudge is < 0.4, this nudge is hurting more than helping\n if (stats.sessionRatingAfter < 0.4) {\n log.debug(\"personality\", `suppressing nudge \"${nudgeType}\" — low avg rating ${stats.sessionRatingAfter.toFixed(2)} after ${stats.fired} fires`);\n return false;\n }\n\n return true;\n}\n\n/**\n * Push current personality state to acore via identity_update_dynamics.\n * Optionally includes user model metrics (trust, sessions, sentiment trend).\n * Fire-and-forget — failures are logged but don't block.\n */\nexport async function syncPersonalityToCore(\n state: PersonalityState,\n mcpManager: McpManager,\n modelMetrics?: { trustScore: number; totalSessions: number; sentimentTrend: string },\n): Promise<void> {\n try {\n const payload: Record<string, unknown> = {\n currentRead: state.currentRead,\n energy: state.energy,\n activeMode: state.activeMode,\n };\n if (modelMetrics) {\n payload.trust = `${(modelMetrics.trustScore * 100).toFixed(0)}%`;\n payload.sessions = modelMetrics.totalSessions;\n payload.sentimentTrend = modelMetrics.sentimentTrend;\n }\n await mcpManager.callTool(\"identity_update_dynamics\", payload);\n } catch (err) {\n log.debug(\"personality\", \"identity_update_dynamics failed\", err);\n }\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport os from \"node:os\";\nimport { readObservationEvents, type ObservationSession } from \"./observation.js\";\nimport type { LLMClient, Message } from \"./llm/types.js\";\nimport { log } from \"./logger.js\";\nimport type { SkillCandidate } from \"./crystallization.js\";\n\n// ── Types ──\n\nexport interface PostmortemReport {\n sessionId: string;\n date: string;\n duration: number;\n turnCount: number;\n summary: string;\n goals: string[];\n completed: string[];\n blockers: string[];\n decisions: string[];\n toolUsage: { name: string; count: number; errorRate: number }[];\n fileChanges: string[];\n topicProgression: string[];\n sentimentArc: string;\n patterns: string[];\n recommendations: string[];\n crystallizationCandidates?: SkillCandidate[];\n}\n\n// ── Default directories ──\n\nexport function defaultPostmortemsDir(): string {\n return path.join(os.homedir(), \".acore\", \"postmortems\");\n}\n\nfunction defaultObservationsDir(): string {\n return path.join(os.homedir(), \".acore\", \"observations\");\n}\n\n// ── Smart trigger ──\n\nexport function shouldAutoPostmortem(\n session: ObservationSession,\n messages: Message[],\n): boolean {\n if (messages.length < 6) return false;\n\n const durationMs = Date.now() - session.startedAt;\n return (\n session.stats.toolErrors >= 3 ||\n session.stats.blockers >= 2 ||\n durationMs > 60 * 60_000 ||\n hasAbandonedPlanSteps(messages) ||\n hasSustainedFrustration(session, 5)\n );\n}\n\nfunction hasAbandonedPlanSteps(messages: Message[]): boolean {\n // Check if any message mentions incomplete plan steps (e.g., /plan output with unchecked items)\n const text = messages\n .map((m) => (typeof m.content === \"string\" ? m.content : \"\"))\n .join(\"\\n\");\n const unchecked = (text.match(/- \\[ \\]/g) ?? []).length;\n const checked = (text.match(/- \\[x\\]/g) ?? []).length;\n // If there are plan steps and some are unchecked, the plan was abandoned\n return checked > 0 && unchecked > 0 && unchecked >= checked;\n}\n\nfunction hasSustainedFrustration(session: ObservationSession, threshold: number): boolean {\n // Use stats counter — events may have been flushed to disk\n return session.stats.blockers >= threshold;\n}\n\n// ── Helper: extract text from message content ──\n\nfunction messageContentToText(content: Message[\"content\"]): string {\n if (typeof content === \"string\") return content;\n return content\n .filter((b) => b.type === \"text\")\n .map((b) => (\"text\" in b ? b.text : \"\"))\n .join(\"\");\n}\n\n// ── Report generation ──\n\nconst POSTMORTEM_PROMPT = `Analyze this session and generate a structured post-mortem report.\nReturn ONLY valid JSON matching this schema (no markdown, no explanation):\n\n{\n \"summary\": \"2-3 sentence overview\",\n \"goals\": [\"what the user tried to accomplish\"],\n \"completed\": [\"what actually got done\"],\n \"blockers\": [\"what caused friction\"],\n \"decisions\": [\"key choices made with rationale\"],\n \"sentimentArc\": \"how mood evolved during session\",\n \"patterns\": [\"recurring behaviors worth remembering for future sessions\"],\n \"recommendations\": [\"actionable suggestions for next session\"],\n \"crystallizationCandidates\": [\n {\n \"name\": \"lowercase-kebab-name\",\n \"description\": \"1-sentence description of when this would be useful\",\n \"triggers\": [\"3-8\", \"trigger\", \"keywords\"],\n \"approach\": \"1-paragraph context: when and why to use this procedure\",\n \"steps\": [\"ordered step 1\", \"ordered step 2\"],\n \"gotchas\": [\"common mistake 1\"],\n \"confidence\": 0.0\n }\n ]\n}\n\nCRYSTALLIZATION RULES:\n- Only suggest 0-2 candidates per session — if nothing qualifies, return an empty array\n- Only suggest REUSABLE procedures (not one-off tasks specific to today's work)\n- The user must have demonstrated the procedure in this session\n- Confidence < 0.6 → don't suggest at all\n- Skip vague things like \"use library X\" — that's not procedural knowledge\n- Prefer narrow specific procedures over broad generalizations\n- Trigger keywords should be highly specific (avoid generic words like \"code\", \"fix\", \"the\")`;\n\nexport async function generatePostmortemReport(\n sessionId: string,\n messages: Message[],\n session: ObservationSession,\n client: LLMClient,\n obsDir?: string,\n rejectedSkillNames?: string[],\n): Promise<PostmortemReport | null> {\n try {\n const events = await readObservationEvents(sessionId, obsDir ?? defaultObservationsDir());\n\n // Compute tool usage from events\n const toolMap = new Map<string, { calls: number; errors: number }>();\n const fileChanges: string[] = [];\n const topicProgression: string[] = [];\n\n for (const event of events) {\n if (event.type === \"tool_call\") {\n const name = (event.data.tool as string) ?? \"unknown\";\n const entry = toolMap.get(name) ?? { calls: 0, errors: 0 };\n entry.calls++;\n toolMap.set(name, entry);\n } else if (event.type === \"tool_error\") {\n const name = (event.data.tool as string) ?? \"unknown\";\n const entry = toolMap.get(name) ?? { calls: 0, errors: 0 };\n entry.errors++;\n toolMap.set(name, entry);\n } else if (event.type === \"file_change\") {\n const p = (event.data.path as string) ?? \"unknown\";\n if (!fileChanges.includes(p)) fileChanges.push(p);\n } else if (event.type === \"topic_shift\") {\n const topics = (event.data.newTopics as string[]) ?? [];\n topicProgression.push(...topics);\n }\n }\n\n const toolUsage = [...toolMap.entries()].map(([name, { calls, errors }]) => ({\n name,\n count: calls,\n errorRate: calls > 0 ? Math.round((errors / calls) * 100) / 100 : 0,\n }));\n\n // Build LLM prompt with capped context\n const recentMessages = messages.slice(-20).map((m) => {\n const text = messageContentToText(m.content);\n return `${m.role}: ${text.slice(0, 200)}`;\n });\n const obsSnapshot = events.slice(-30).map((e) => `[${e.type}] ${e.summary}`);\n\n const durationMin = Math.round((Date.now() - session.startedAt) / 60_000);\n\n const prompt = `${POSTMORTEM_PROMPT}${\n rejectedSkillNames && rejectedSkillNames.length > 0\n ? `\\n\\nPREVIOUSLY REJECTED SKILLS (do NOT suggest these again):\\n${rejectedSkillNames.map((n) => `- ${n}`).join(\"\\n\")}`\n : \"\"\n }\n\nSession ID: ${sessionId}\nDuration: ${durationMin} minutes\nTurns: ${messages.length}\nTool calls: ${session.stats.toolCalls} (${session.stats.toolErrors} errors)\nBlockers: ${session.stats.blockers}\nMilestones: ${session.stats.milestones}\n\nRecent messages:\n${recentMessages.join(\"\\n\")}\n\nObservations:\n${obsSnapshot.join(\"\\n\")}`;\n\n const response = await client.chat(\n \"You are a session analyst. Output only valid JSON.\",\n [{ role: \"user\", content: prompt }],\n () => {}, // no-op onChunk — postmortem runs silently\n );\n\n const text = messageContentToText(response.message.content);\n const jsonMatch = text.match(/\\{[\\s\\S]*\\}/);\n if (!jsonMatch) {\n log.debug(\"postmortem\", \"LLM returned non-JSON response\");\n return null;\n }\n\n const parsed = JSON.parse(jsonMatch[0]);\n\n return {\n sessionId,\n date: new Date().toISOString().slice(0, 10),\n duration: durationMin,\n turnCount: messages.length,\n summary: parsed.summary ?? \"\",\n goals: parsed.goals ?? [],\n completed: parsed.completed ?? [],\n blockers: parsed.blockers ?? [],\n decisions: parsed.decisions ?? [],\n toolUsage,\n fileChanges,\n topicProgression: [...new Set(topicProgression)],\n sentimentArc: parsed.sentimentArc ?? \"\",\n patterns: parsed.patterns ?? [],\n recommendations: parsed.recommendations ?? [],\n crystallizationCandidates: Array.isArray(parsed.crystallizationCandidates)\n ? parsed.crystallizationCandidates\n : undefined,\n };\n } catch (err) {\n log.debug(\"postmortem\", \"Failed to generate post-mortem\", err);\n return null;\n }\n}\n\n// ── Markdown formatting ──\n\nexport function formatPostmortemMarkdown(report: PostmortemReport): string {\n const lines: string[] = [\n `# Post-Mortem: ${report.date}`,\n \"\",\n `**Session:** ${report.sessionId} | **Duration:** ${report.duration} min | **Turns:** ${report.turnCount}`,\n \"\",\n \"## Summary\",\n report.summary,\n \"\",\n ];\n\n if (report.goals.length > 0) {\n lines.push(\"## Goals\");\n report.goals.forEach((g) => lines.push(`- ${g}`));\n lines.push(\"\");\n }\n\n if (report.completed.length > 0) {\n lines.push(\"## Completed\");\n report.completed.forEach((c) => lines.push(`- [x] ${c}`));\n lines.push(\"\");\n }\n\n if (report.blockers.length > 0) {\n lines.push(\"## Blockers\");\n report.blockers.forEach((b) => lines.push(`- ${b}`));\n lines.push(\"\");\n }\n\n if (report.decisions.length > 0) {\n lines.push(\"## Decisions\");\n report.decisions.forEach((d) => lines.push(`- ${d}`));\n lines.push(\"\");\n }\n\n if (report.toolUsage.length > 0) {\n lines.push(\"## Tool Usage\");\n lines.push(\"| Tool | Calls | Error Rate |\");\n lines.push(\"|------|-------|------------|\");\n report.toolUsage.forEach((t) =>\n lines.push(`| ${t.name} | ${t.count} | ${Math.round(t.errorRate * 100)}% |`),\n );\n lines.push(\"\");\n }\n\n if (report.fileChanges.length > 0) {\n lines.push(\"## Files Changed\");\n report.fileChanges.forEach((f) => lines.push(`- \\`${f}\\``));\n lines.push(\"\");\n }\n\n if (report.topicProgression.length > 0) {\n lines.push(`## Topics`);\n lines.push(report.topicProgression.join(\" → \"));\n lines.push(\"\");\n }\n\n if (report.sentimentArc) {\n lines.push(\"## Sentiment Arc\");\n lines.push(report.sentimentArc);\n lines.push(\"\");\n }\n\n if (report.patterns.length > 0) {\n lines.push(\"## Patterns\");\n report.patterns.forEach((p) => lines.push(`- ${p}`));\n lines.push(\"\");\n }\n\n if (report.recommendations.length > 0) {\n lines.push(\"## Recommendations\");\n report.recommendations.forEach((r) => lines.push(`- ${r}`));\n lines.push(\"\");\n }\n\n if (\n report.crystallizationCandidates &&\n report.crystallizationCandidates.length > 0\n ) {\n lines.push(\"## Crystallization Candidates\");\n report.crystallizationCandidates.forEach((c) => {\n lines.push(`- **${c.name}** (confidence ${c.confidence})`);\n lines.push(` ${c.description}`);\n });\n lines.push(\"\");\n }\n\n return lines.join(\"\\n\");\n}\n\n// ── Save & read post-mortems ──\n\nexport async function savePostmortem(\n report: PostmortemReport,\n dir?: string,\n): Promise<string> {\n const pmDir = dir ?? defaultPostmortemsDir();\n await fs.mkdir(pmDir, { recursive: true });\n\n const shortId = report.sessionId.slice(0, 4);\n const fileName = `${report.date}-${shortId}.md`;\n const filePath = path.join(pmDir, fileName);\n\n const markdown = formatPostmortemMarkdown(report);\n await fs.writeFile(filePath, markdown, \"utf-8\");\n\n // Also write a JSON sidecar for lossless re-parsing\n const jsonPath = filePath.replace(/\\.md$/, \".json\");\n try {\n await fs.writeFile(jsonPath, JSON.stringify(report, null, 2), \"utf-8\");\n } catch (err) {\n log.debug(\"postmortem\", \"JSON sidecar write failed\", err);\n }\n\n return filePath;\n}\n\nexport async function listPostmortems(dir?: string): Promise<string[]> {\n const pmDir = dir ?? defaultPostmortemsDir();\n try {\n const files = await fs.readdir(pmDir);\n return files\n .filter((f) => f.endsWith(\".md\"))\n .sort()\n .reverse();\n } catch {\n return [];\n }\n}\n\nexport async function readPostmortem(\n name: string,\n dir?: string,\n): Promise<string | null> {\n const pmDir = dir ?? defaultPostmortemsDir();\n const fileName = name.endsWith(\".md\") ? name : `${name}.md`;\n try {\n return await fs.readFile(path.join(pmDir, fileName), \"utf-8\");\n } catch {\n return null;\n }\n}\n\nexport async function analyzePostmortemRange(\n sinceDays: number,\n client: LLMClient,\n dir?: string,\n): Promise<string | null> {\n const pmDir = dir ?? defaultPostmortemsDir();\n try {\n const files = await listPostmortems(pmDir);\n const cutoffDate = new Date(Date.now() - sinceDays * 24 * 60 * 60 * 1000)\n .toISOString()\n .slice(0, 10);\n\n const recentFiles = files.filter((f) => f >= cutoffDate);\n if (recentFiles.length === 0) return \"No post-mortems found in the specified range.\";\n\n const contents: string[] = [];\n for (const f of recentFiles.slice(0, 10)) {\n const content = await readPostmortem(f, pmDir);\n if (content) contents.push(content);\n }\n\n const response = await client.chat(\n \"You are a session analyst. Analyze these post-mortems and identify trends.\",\n [\n {\n role: \"user\",\n content: `Analyze these ${contents.length} post-mortem reports from the last ${sinceDays} days. Identify:\n1. Recurring blockers\n2. Productivity patterns\n3. Tool reliability issues\n4. Topic continuity across sessions\n5. Actionable recommendations\n\nReports:\n${contents.join(\"\\n\\n---\\n\\n\")}`,\n },\n ],\n () => {}, // no-op onChunk\n );\n\n const text = messageContentToText(response.message.content);\n return text || null;\n } catch (err) {\n log.debug(\"postmortem\", \"Failed to analyze range\", err);\n return null;\n }\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport os from \"node:os\";\n\n// ── Types ──\n\nexport type ObservationEventType =\n | \"tool_call\"\n | \"tool_error\"\n | \"topic_shift\"\n | \"decision\"\n | \"blocker\"\n | \"milestone\"\n | \"file_change\"\n | \"sentiment_shift\"\n | \"error\"\n | \"phase_start\"\n | \"phase_complete\"\n | \"approval_gate\"\n | \"task_delegated\";\n\nexport interface ObservationEvent {\n timestamp: number;\n type: ObservationEventType;\n summary: string;\n data: Record<string, unknown>;\n}\n\nexport interface ObservationSession {\n sessionId: string;\n startedAt: number;\n events: ObservationEvent[];\n paused: boolean;\n stats: {\n toolCalls: number;\n toolErrors: number;\n topicShifts: number;\n blockers: number;\n milestones: number;\n fileChanges: number;\n };\n}\n\n// ── Stat counters by event type ──\n\nconst STAT_MAP: Partial<Record<ObservationEventType, keyof ObservationSession[\"stats\"]>> = {\n tool_call: \"toolCalls\",\n tool_error: \"toolErrors\",\n topic_shift: \"topicShifts\",\n blocker: \"blockers\",\n milestone: \"milestones\",\n file_change: \"fileChanges\",\n};\n\n// ── Default observations directory ──\n\nexport function defaultObservationsDir(): string {\n return path.join(os.homedir(), \".acore\", \"observations\");\n}\n\n// ── Core functions ──\n\nexport function createObservationSession(sessionId: string): ObservationSession {\n return {\n sessionId,\n startedAt: Date.now(),\n events: [],\n paused: false,\n stats: {\n toolCalls: 0,\n toolErrors: 0,\n topicShifts: 0,\n blockers: 0,\n milestones: 0,\n fileChanges: 0,\n },\n };\n}\n\nexport function recordEvent(\n session: ObservationSession,\n event: Omit<ObservationEvent, \"timestamp\">,\n): void {\n if (session.paused) return;\n\n const full: ObservationEvent = { ...event, timestamp: Date.now() };\n session.events.push(full);\n\n const statKey = STAT_MAP[event.type];\n if (statKey) {\n session.stats[statKey]++;\n }\n}\n\nexport function pauseObservation(session: ObservationSession): void {\n session.paused = true;\n}\n\nexport function resumeObservation(session: ObservationSession): void {\n session.paused = false;\n}\n\nexport async function flushEvents(\n session: ObservationSession,\n dir?: string,\n): Promise<void> {\n if (session.events.length === 0) return;\n\n const obsDir = dir ?? defaultObservationsDir();\n await fs.mkdir(obsDir, { recursive: true });\n\n const filePath = path.join(obsDir, `${session.sessionId}.jsonl`);\n const lines = session.events.map((e) => JSON.stringify(e)).join(\"\\n\") + \"\\n\";\n await fs.appendFile(filePath, lines, \"utf-8\");\n\n session.events.length = 0;\n}\n\nexport async function readObservationEvents(\n sessionId: string,\n dir?: string,\n): Promise<ObservationEvent[]> {\n const obsDir = dir ?? defaultObservationsDir();\n const filePath = path.join(obsDir, `${sessionId}.jsonl`);\n\n try {\n const content = await fs.readFile(filePath, \"utf-8\");\n return content\n .trim()\n .split(\"\\n\")\n .filter((line) => line.length > 0)\n .map((line) => JSON.parse(line) as ObservationEvent);\n } catch {\n return [];\n }\n}\n\nexport function getSessionStats(session: ObservationSession): string {\n const elapsed = Math.round((Date.now() - session.startedAt) / 60_000);\n const s = session.stats;\n const parts = [\n `Session: ${elapsed} min`,\n `Tools: ${s.toolCalls} calls (${s.toolErrors} error${s.toolErrors !== 1 ? \"s\" : \"\"})`,\n `Files: ${s.fileChanges} changed`,\n `Blockers: ${s.blockers}`,\n `Milestones: ${s.milestones}`,\n ];\n if (s.topicShifts > 0) parts.push(`Topic shifts: ${s.topicShifts}`);\n if (session.paused) parts.push(\"(paused)\");\n return parts.join(\" | \");\n}\n\nexport async function cleanupOldObservations(\n dir?: string,\n maxAgeDays = 30,\n): Promise<void> {\n const obsDir = dir ?? defaultObservationsDir();\n try {\n const files = await fs.readdir(obsDir);\n const cutoff = Date.now() - maxAgeDays * 24 * 60 * 60 * 1000;\n\n for (const file of files) {\n if (!file.endsWith(\".jsonl\")) continue;\n const filePath = path.join(obsDir, file);\n const stat = await fs.stat(filePath);\n if (stat.mtimeMs < cutoff) {\n await fs.unlink(filePath);\n }\n }\n } catch {\n // Directory may not exist yet — that's fine\n }\n}\n\n// ── Topic shift detection ──\n\nexport function detectTopicShift(\n recentMessages: string[],\n previousMessages: string[],\n): { shifted: boolean; newTopics: string[] } {\n const extractKeywords = (msgs: string[]): Set<string> => {\n const words = msgs\n .join(\" \")\n .toLowerCase()\n .split(/\\W+/)\n .filter((w) => w.length > 3);\n return new Set(words);\n };\n\n const recent = extractKeywords(recentMessages);\n const previous = extractKeywords(previousMessages);\n\n if (previous.size === 0) return { shifted: false, newTopics: [] };\n\n let overlap = 0;\n for (const word of recent) {\n if (previous.has(word)) overlap++;\n }\n\n const overlapRatio = previous.size > 0 ? overlap / previous.size : 1;\n const shifted = overlapRatio < 0.3;\n\n const newTopics = shifted\n ? [...recent].filter((w) => !previous.has(w)).slice(0, 5)\n : [];\n\n return { shifted, newTopics };\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { log } from \"./logger.js\";\n\n// ── Types ──\n\nexport interface SkillCandidate {\n name: string;\n description: string;\n triggers: string[];\n approach: string;\n steps: string[];\n gotchas: string[];\n confidence: number;\n}\n\nexport interface CrystallizationResult {\n written: boolean;\n filePath: string;\n skillName: string;\n reason?: string;\n collidesWith?: string;\n}\n\nexport interface MarkerData {\n source: string;\n date: string;\n confidence: number;\n triggers: string[];\n}\n\nexport interface CrystallizationLogEntry {\n name: string;\n createdAt: string;\n fromPostmortem: string;\n confidence: number;\n triggers: string[];\n}\n\nexport interface RejectionLogEntry {\n name: string;\n rejectedAt: string;\n fromPostmortem: string;\n triggers: string[];\n}\n\nexport interface CollisionResult {\n collides: boolean;\n collidesWith?: string;\n reason?: string;\n}\n\n// ── Constants ──\n\nconst STOPWORDS = new Set([\n \"the\", \"and\", \"is\", \"to\", \"of\", \"a\", \"in\", \"for\", \"on\", \"with\",\n \"this\", \"that\", \"it\", \"as\", \"be\", \"by\", \"or\", \"at\", \"an\", \"from\",\n \"code\", \"fix\", \"do\", \"use\", \"make\", \"get\", \"set\", \"run\", \"we\", \"i\",\n]);\n\nconst MAX_REJECTIONS = 100;\nconst MARKER_RE = /<!--\\s*aman-auto\\s+([^>]+?)\\s*-->/;\n\n// ── sanitizeName ──\n\nexport function sanitizeName(input: string): string {\n const cleaned = input\n .toLowerCase()\n .trim()\n .replace(/[^a-z0-9\\s-]/g, \" \")\n .replace(/\\s+/g, \"-\")\n .replace(/-+/g, \"-\")\n .replace(/^-|-$/g, \"\");\n\n if (cleaned.length === 0) {\n throw new Error(`Cannot sanitize name: \"${input}\" produced empty result`);\n }\n return cleaned;\n}\n\n// ── validateCandidate ──\n\nexport function validateCandidate(raw: unknown): SkillCandidate | null {\n if (!raw || typeof raw !== \"object\") return null;\n const c = raw as Record<string, unknown>;\n\n if (typeof c.name !== \"string\" || c.name.trim() === \"\") return null;\n if (typeof c.description !== \"string\") return null;\n if (typeof c.approach !== \"string\") return null;\n if (!Array.isArray(c.triggers) || c.triggers.length === 0) return null;\n if (c.triggers.length > 10) return null;\n if (!Array.isArray(c.steps)) return null;\n if (typeof c.confidence !== \"number\") return null;\n if (!Number.isFinite(c.confidence)) return null;\n\n if (c.confidence < 0.6) return null;\n\n const triggers = Array.from(\n new Set(\n c.triggers\n .filter((t): t is string => typeof t === \"string\")\n .map((t) => t.toLowerCase().trim())\n .filter((t) => t.length > 0 && !STOPWORDS.has(t))\n )\n );\n\n if (triggers.length === 0) return null;\n\n let name: string;\n try {\n name = sanitizeName(c.name);\n } catch {\n return null;\n }\n\n return {\n name,\n description: c.description,\n triggers,\n approach: c.approach,\n steps: c.steps.filter((s): s is string => typeof s === \"string\"),\n gotchas: Array.isArray(c.gotchas)\n ? c.gotchas.filter((g): g is string => typeof g === \"string\")\n : [],\n confidence: Math.min(1, Math.max(0, c.confidence)),\n };\n}\n\n// ── formatSkillMarkdown ──\n\nfunction toTitleCase(kebab: string): string {\n return kebab\n .split(\"-\")\n .map((w) => w.charAt(0).toUpperCase() + w.slice(1))\n .join(\" \");\n}\n\nexport function formatSkillMarkdown(\n candidate: SkillCandidate,\n postmortemFilename: string,\n): string {\n const date = new Date().toISOString().slice(0, 10);\n const heading = toTitleCase(candidate.name);\n const triggerStr = candidate.triggers.join(\",\");\n\n const lines: string[] = [\n `# ${heading}`,\n `<!-- aman-auto source=postmortem date=${date} confidence=${candidate.confidence} triggers=\"${triggerStr}\" -->`,\n \"\",\n \"## When to use\",\n candidate.approach,\n \"\",\n \"## Steps\",\n ...candidate.steps.map((s, i) => `${i + 1}. ${s}`),\n \"\",\n ];\n\n if (candidate.gotchas.length > 0) {\n lines.push(\"## Gotchas\");\n lines.push(...candidate.gotchas.map((g) => `- ${g}`));\n lines.push(\"\");\n }\n\n lines.push(`<!-- generated from ${postmortemFilename} -->`);\n lines.push(\"\");\n\n return lines.join(\"\\n\");\n}\n\n// ── parseMarkerComment ──\n\nexport function parseMarkerComment(line: string): MarkerData | null {\n const match = line.match(MARKER_RE);\n if (!match) return null;\n\n const attrs: Record<string, string> = {};\n const attrRe = /(\\w+)=(?:\"([^\"]*)\"|(\\S+))/g;\n let m: RegExpExecArray | null;\n while ((m = attrRe.exec(match[1])) !== null) {\n attrs[m[1]] = m[2] ?? m[3] ?? \"\";\n }\n\n if (!attrs.triggers) return null;\n\n const triggers = attrs.triggers\n .split(\",\")\n .map((t) => t.trim())\n .filter((t) => t.length > 0);\n\n if (triggers.length === 0) return null;\n\n return {\n source: attrs.source ?? \"unknown\",\n date: attrs.date ?? \"\",\n confidence: attrs.confidence ? Number(attrs.confidence) : 0,\n triggers,\n };\n}\n\n// ── extractSkillsWithMarkers ──\n\nexport function extractSkillsWithMarkers(\n skillsMdContent: string,\n): Map<string, MarkerData> {\n const result = new Map<string, MarkerData>();\n const lines = skillsMdContent.split(\"\\n\");\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n if (line.startsWith(\"# \") && i + 1 < lines.length) {\n const headingText = line.slice(2).trim();\n const nextLine = lines[i + 1];\n const marker = parseMarkerComment(nextLine);\n if (marker) {\n try {\n const skillName = sanitizeName(headingText);\n result.set(skillName, marker);\n } catch {\n log.debug(\"crystallization\", `cannot sanitize heading: ${headingText}`);\n }\n }\n }\n }\n\n return result;\n}\n\n// ── findCollision ──\n\nexport function findCollision(\n name: string,\n triggers: string[],\n existing: Map<string, MarkerData>,\n): CollisionResult {\n if (existing.has(name)) {\n return { collides: true, collidesWith: name, reason: \"exact name match\" };\n }\n\n const triggerSet = new Set(triggers);\n for (const [otherName, otherData] of existing) {\n const otherTriggers = new Set(otherData.triggers);\n const intersection = [...triggerSet].filter((t) => otherTriggers.has(t)).length;\n const union = new Set([...triggerSet, ...otherTriggers]).size;\n const overlap = union > 0 ? intersection / union : 0;\n if (overlap >= 0.8) {\n return {\n collides: true,\n collidesWith: otherName,\n reason: `${Math.round(overlap * 100)}% trigger overlap`,\n };\n }\n }\n\n return { collides: false };\n}\n\n// ── writeSkillToFile ──\n\nexport async function writeSkillToFile(\n candidate: SkillCandidate,\n skillsMdPath: string,\n postmortemFilename: string,\n): Promise<CrystallizationResult> {\n try {\n await fs.mkdir(path.dirname(skillsMdPath), { recursive: true });\n\n let existingContent = \"\";\n try {\n existingContent = await fs.readFile(skillsMdPath, \"utf-8\");\n } catch {\n existingContent = \"# Skills\\n\\n\";\n }\n\n if (existingContent.trim() === \"\") {\n existingContent = \"# Skills\\n\\n\";\n }\n\n const existingSkills = extractSkillsWithMarkers(existingContent);\n const collision = findCollision(candidate.name, candidate.triggers, existingSkills);\n if (collision.collides) {\n log.debug(\"crystallization\", `collision detected: ${collision.reason}`);\n return {\n written: false,\n filePath: skillsMdPath,\n skillName: candidate.name,\n reason: `collision with \"${collision.collidesWith}\" (${collision.reason})`,\n collidesWith: collision.collidesWith,\n };\n }\n\n const skillMarkdown = formatSkillMarkdown(candidate, postmortemFilename);\n const separator = existingContent.endsWith(\"\\n\\n\")\n ? \"\"\n : existingContent.endsWith(\"\\n\")\n ? \"\\n\"\n : \"\\n\\n\";\n await fs.writeFile(\n skillsMdPath,\n existingContent + separator + skillMarkdown,\n \"utf-8\",\n );\n\n return {\n written: true,\n filePath: skillsMdPath,\n skillName: candidate.name,\n };\n } catch (err) {\n log.warn(\"crystallization\", \"writeSkillToFile failed\", err);\n return {\n written: false,\n filePath: skillsMdPath,\n skillName: candidate.name,\n reason: err instanceof Error ? err.message : String(err),\n };\n }\n}\n\n// ── mergeSkillInFile ──\n\n/**\n * Replace an existing skill block in skills.md with a new candidate.\n * Finds the heading for `existingName`, removes everything up to the next heading or EOF,\n * and writes the new candidate in its place.\n */\nexport async function mergeSkillInFile(\n candidate: SkillCandidate,\n existingName: string,\n skillsMdPath: string,\n postmortemFilename: string,\n): Promise<CrystallizationResult> {\n try {\n const content = await fs.readFile(skillsMdPath, \"utf-8\");\n const lines = content.split(\"\\n\");\n\n // Find the heading line for the existing skill\n const heading = toTitleCase(existingName);\n let startIdx = -1;\n for (let i = 0; i < lines.length; i++) {\n if (lines[i].startsWith(\"# \") && lines[i].slice(2).trim() === heading) {\n startIdx = i;\n break;\n }\n }\n\n if (startIdx === -1) {\n return writeSkillToFile(candidate, skillsMdPath, postmortemFilename);\n }\n\n // Find the end of this skill block (next heading or EOF)\n let endIdx = lines.length;\n for (let i = startIdx + 1; i < lines.length; i++) {\n if (lines[i].startsWith(\"# \") && !lines[i].startsWith(\"## \")) {\n endIdx = i;\n break;\n }\n }\n\n // Determine version number — count existing archived versions\n const versionPattern = new RegExp(`^# ${heading.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}\\\\.v\\\\d+`);\n let maxVersion = 0;\n for (const line of lines) {\n if (versionPattern.test(line)) {\n const vMatch = line.match(/\\.v(\\d+)/);\n if (vMatch) maxVersion = Math.max(maxVersion, parseInt(vMatch[1], 10));\n }\n }\n const archiveVersion = maxVersion + 1;\n\n // Archive the old version by renaming its heading\n const oldBlock = lines.slice(startIdx, endIdx);\n oldBlock[0] = `# ${heading}.v${archiveVersion}`;\n // Add archive marker\n const archiveMarker = `<!-- aman-archived version=${archiveVersion} archived-at=${new Date().toISOString().slice(0, 10)} -->`;\n if (oldBlock.length > 1 && oldBlock[1].includes(\"aman-auto\")) {\n oldBlock.splice(2, 0, archiveMarker);\n } else {\n oldBlock.splice(1, 0, archiveMarker);\n }\n\n // Write: archived old block + new candidate\n const newSkillMarkdown = formatSkillMarkdown(candidate, postmortemFilename);\n const before = lines.slice(0, startIdx);\n const after = lines.slice(endIdx);\n const merged = [...before, ...oldBlock, \"\", newSkillMarkdown, ...after].join(\"\\n\");\n\n await fs.writeFile(skillsMdPath, merged, \"utf-8\");\n\n return {\n written: true,\n filePath: skillsMdPath,\n skillName: candidate.name,\n reason: `merged with \"${existingName}\" (archived as .v${archiveVersion})`,\n };\n } catch (err) {\n log.warn(\"crystallization\", \"mergeSkillInFile failed\", err);\n return {\n written: false,\n filePath: skillsMdPath,\n skillName: candidate.name,\n reason: err instanceof Error ? err.message : String(err),\n };\n }\n}\n\n// ── Logs ──\n\nexport async function appendCrystallizationLog(\n entry: CrystallizationLogEntry,\n logPath: string,\n): Promise<void> {\n try {\n await fs.mkdir(path.dirname(logPath), { recursive: true });\n let existing: CrystallizationLogEntry[] = [];\n try {\n const content = await fs.readFile(logPath, \"utf-8\");\n existing = JSON.parse(content);\n if (!Array.isArray(existing)) existing = [];\n } catch {\n existing = [];\n }\n existing.push(entry);\n await fs.writeFile(logPath, JSON.stringify(existing, null, 2), \"utf-8\");\n } catch (err) {\n log.debug(\"crystallization\", \"appendCrystallizationLog failed\", err);\n }\n}\n\nexport async function appendRejection(\n candidate: SkillCandidate,\n postmortemFilename: string,\n rejectionsPath: string,\n): Promise<void> {\n try {\n await fs.mkdir(path.dirname(rejectionsPath), { recursive: true });\n let existing: RejectionLogEntry[] = [];\n try {\n const content = await fs.readFile(rejectionsPath, \"utf-8\");\n existing = JSON.parse(content);\n if (!Array.isArray(existing)) existing = [];\n } catch {\n existing = [];\n }\n\n existing.push({\n name: candidate.name,\n rejectedAt: new Date().toISOString(),\n fromPostmortem: postmortemFilename,\n triggers: candidate.triggers,\n });\n\n while (existing.length > MAX_REJECTIONS) {\n existing.shift();\n }\n\n await fs.writeFile(rejectionsPath, JSON.stringify(existing, null, 2), \"utf-8\");\n } catch (err) {\n log.debug(\"crystallization\", \"appendRejection failed\", err);\n }\n}\n\n/**\n * Load rejected skill names from the rejections log.\n * Returns unique names. Never throws.\n */\nexport async function loadRejectedNames(rejectionsPath: string): Promise<string[]> {\n try {\n const content = await fs.readFile(rejectionsPath, \"utf-8\");\n const entries: RejectionLogEntry[] = JSON.parse(content);\n if (!Array.isArray(entries)) return [];\n return [...new Set(entries.map((e) => e.name))];\n } catch {\n return [];\n }\n}\n\n// ── Suggestion tracking (cross-session reinforcement) ──\n\nexport interface SuggestionCounts {\n [name: string]: number;\n}\n\n/**\n * Load suggestion counts. Never throws.\n */\nexport async function loadSuggestionCounts(suggestionsPath: string): Promise<SuggestionCounts> {\n try {\n const content = await fs.readFile(suggestionsPath, \"utf-8\");\n const parsed = JSON.parse(content);\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) return {};\n return parsed as SuggestionCounts;\n } catch {\n return {};\n }\n}\n\n/**\n * Increment suggestion count for a candidate name. Returns the new count.\n */\nexport async function incrementSuggestionCount(\n name: string,\n suggestionsPath: string,\n): Promise<number> {\n try {\n await fs.mkdir(path.dirname(suggestionsPath), { recursive: true });\n const counts = await loadSuggestionCounts(suggestionsPath);\n counts[name] = (counts[name] || 0) + 1;\n await fs.writeFile(suggestionsPath, JSON.stringify(counts, null, 2), \"utf-8\");\n return counts[name];\n } catch (err) {\n log.debug(\"crystallization\", \"incrementSuggestionCount failed\", err);\n return 0;\n }\n}\n","// ── Public API for the orchestrator module ──────────────────────────\n\n// Re-exports: types\nexport {\n type TaskNode,\n type TaskDAG,\n type PhaseGate,\n type OrchestrationState,\n type OrchestrationConfig,\n type TaskResult,\n type ModelTier,\n TaskNodeSchema,\n TaskDAGSchema,\n PhaseGateSchema,\n OrchestrationConfigSchema,\n OrchestrationStatusEnum,\n TaskStatusEnum,\n ModelTierEnum,\n PhaseGateTypeEnum,\n} from \"./types.js\";\n\n// Re-exports: state machine\nexport {\n createOrchestrationState,\n transition,\n canTransition,\n getValidTransitions,\n transitionTask,\n InvalidTransitionError,\n} from \"./state-machine.js\";\n\n// Re-exports: DAG\nexport {\n validateDAG,\n topologicalSort,\n getReadyNodes,\n getDependents,\n DAGValidationError,\n} from \"./dag.js\";\n\n// Re-exports: model router\nexport {\n createModelRouter,\n suggestTier,\n type ModelRouter,\n} from \"./model-router.js\";\n\n// Re-exports: audit\nexport {\n createAuditLog,\n recordAuditEvent,\n getAuditTrail,\n formatAuditTrail,\n type AuditLog,\n type AuditEvent,\n type AuditEventType,\n} from \"./audit.js\";\n\n// Re-exports: decompose\nexport {\n decomposeRequirement,\n parseDecompositionResponse,\n} from \"./decompose.js\";\n\n// Re-exports: scheduler\nexport {\n runScheduler,\n type SchedulerCallbacks,\n type SchedulerResult,\n} from \"./scheduler.js\";\n\n// Re-exports: review loop\nexport {\n buildReviewDAG,\n runReviewLoop,\n type ReviewLoopOptions,\n type ReviewResult,\n} from \"./review-loop.js\";\n\n// Re-exports: circuit breaker\nexport {\n createCircuitBreaker,\n createCircuitBreakerRegistry,\n type CircuitState,\n type CircuitBreaker,\n type CircuitBreakerOptions,\n type CircuitBreakerRegistry,\n} from \"./circuit-breaker.js\";\n\n// Re-exports: checkpoint\nexport {\n createCheckpoint,\n serializeCheckpoint,\n deserializeCheckpoint,\n saveCheckpoint,\n loadCheckpoint,\n restoreMaps,\n type CheckpointData,\n} from \"./checkpoint.js\";\n\n// Re-exports: cost tracker\nexport {\n createCostTracker,\n DEFAULT_TIER_COSTS,\n type CostTracker,\n type CostTrackerOptions,\n type CostEntry,\n type TierCost,\n} from \"./cost-tracker.js\";\n\n// Re-exports: policy\nexport {\n evaluatePolicy,\n getDefaultPolicies,\n formatPolicyResult,\n type PolicySeverity,\n type PolicyViolation,\n type PolicyResult,\n type PolicyRule,\n} from \"./policy.js\";\n\n// Re-exports: runner (unified orchestration)\nexport {\n runOrchestrationFull,\n type FullOrchestrationOptions,\n type FullOrchestrationResult,\n} from \"./runner.js\";\n\n// Re-exports: smart orchestrate\nexport {\n smartOrchestrate,\n formatSmartResult,\n type SmartOrchestrationOptions,\n type SmartOrchestrationResult,\n} from \"./smart-orchestrate.js\";\n\n// Re-exports: templates\nexport {\n fullFeatureTemplate,\n bugFixTemplate,\n securityAuditTemplate,\n getTemplate,\n listTemplates,\n type TemplateOptions,\n} from \"./templates/index.js\";\n\n// ── Convenience functions ───────────────────────────────────────────\n\nimport type { TaskDAG, TaskNode, PhaseGate, OrchestrationState } from \"./types.js\";\nimport type { ModelRouter } from \"./model-router.js\";\nimport type { SchedulerCallbacks, SchedulerResult } from \"./scheduler.js\";\nimport { validateDAG } from \"./dag.js\";\nimport { createOrchestrationState } from \"./state-machine.js\";\nimport { runScheduler } from \"./scheduler.js\";\n\n/**\n * Formats a TaskDAG for human-readable CLI display.\n */\nexport function formatDAGForDisplay(dag: TaskDAG): string {\n const lines: string[] = [];\n lines.push(`## ${dag.name}`);\n lines.push(`**Goal:** ${dag.goal}`);\n lines.push(`**Tasks:** ${dag.nodes.length} | **Gates:** ${dag.gates.length}`);\n lines.push(\"\");\n\n for (const node of dag.nodes) {\n const depLabel =\n node.dependencies.length === 0\n ? \"(root)\"\n : `(after: ${node.dependencies.join(\", \")})`;\n lines.push(`- **${node.name}** \\u2192 ${node.profile} [${node.tier}] ${depLabel}`);\n }\n\n for (const gate of dag.gates) {\n lines.push(`- \\uD83D\\uDD12 **${gate.name}** [${gate.type}]`);\n }\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Validates DAG (throws DAGValidationError if invalid), then creates\n * initial orchestration state.\n */\nexport function createOrchestration(dag: TaskDAG): OrchestrationState {\n validateDAG(dag);\n return createOrchestrationState(dag);\n}\n\n/**\n * Convenience wrapper: validates DAG and runs the scheduler end-to-end.\n */\nexport async function runOrchestration(\n dag: TaskDAG,\n router: ModelRouter,\n options?: { maxParallelTasks?: number; taskTimeoutMs?: number },\n callbacks?: SchedulerCallbacks,\n): Promise<SchedulerResult> {\n return runScheduler(dag, router, options, callbacks);\n}\n","import type {\n TaskDAG,\n OrchestrationState,\n OrchestrationStatus,\n TaskStatus,\n} from \"./types.js\";\n\n// ── Transition tables ───────────────────────────────────────────────\n\nconst ORCHESTRATION_TRANSITIONS: Record<OrchestrationStatus, OrchestrationStatus[]> = {\n pending: [\"running\", \"cancelled\"],\n running: [\"awaiting_approval\", \"paused\", \"completed\", \"failed\", \"cancelled\"],\n awaiting_approval: [\"approved\", \"cancelled\", \"failed\"],\n approved: [\"running\", \"cancelled\"],\n paused: [\"running\", \"cancelled\", \"failed\"],\n completed: [],\n failed: [],\n cancelled: [],\n};\n\nconst TASK_TRANSITIONS: Record<TaskStatus, TaskStatus[]> = {\n pending: [\"ready\", \"skipped\", \"blocked\"],\n ready: [\"running\", \"skipped\", \"blocked\"],\n running: [\"completed\", \"failed\"],\n completed: [],\n failed: [\"ready\"],\n skipped: [],\n blocked: [\"ready\", \"skipped\"],\n};\n\nconst TERMINAL_ORCHESTRATION: Set<OrchestrationStatus> = new Set([\n \"completed\",\n \"failed\",\n \"cancelled\",\n]);\n\n// ── InvalidTransitionError ──────────────────────────────────────────\n\nexport class InvalidTransitionError extends Error {\n constructor(\n public readonly from: string,\n public readonly to: string,\n public readonly entity: string = \"orchestration\",\n ) {\n super(\n `Invalid ${entity} transition: ${from} → ${to}`,\n );\n this.name = \"InvalidTransitionError\";\n }\n}\n\n// ── Factory ─────────────────────────────────────────────────────────\n\nexport function createOrchestrationState(dag: TaskDAG): OrchestrationState {\n const now = Date.now();\n const taskStatuses = new Map<string, TaskStatus>();\n for (const node of dag.nodes) {\n taskStatuses.set(node.id, \"pending\");\n }\n return {\n dag,\n status: \"pending\",\n taskStatuses,\n taskResults: new Map(),\n activeGate: null,\n startedAt: now,\n updatedAt: now,\n };\n}\n\n// ── Query helpers ───────────────────────────────────────────────────\n\nexport function canTransition(\n state: OrchestrationState,\n to: OrchestrationStatus,\n): boolean {\n return ORCHESTRATION_TRANSITIONS[state.status].includes(to);\n}\n\nexport function getValidTransitions(\n state: OrchestrationState,\n): OrchestrationStatus[] {\n return [...ORCHESTRATION_TRANSITIONS[state.status]];\n}\n\n// ── Orchestration transition ────────────────────────────────────────\n\nfunction cloneState(state: OrchestrationState): OrchestrationState {\n return {\n ...state,\n taskStatuses: new Map(state.taskStatuses),\n taskResults: new Map(state.taskResults),\n updatedAt: Date.now(),\n };\n}\n\nexport function transition(\n state: OrchestrationState,\n to: OrchestrationStatus,\n error?: string,\n): OrchestrationState {\n if (!canTransition(state, to)) {\n throw new InvalidTransitionError(state.status, to);\n }\n\n const next = cloneState(state);\n next.status = to;\n\n if (TERMINAL_ORCHESTRATION.has(to)) {\n next.completedAt = next.updatedAt;\n }\n\n if (error !== undefined) {\n next.error = error;\n }\n\n return next;\n}\n\n// ── Task transition ─────────────────────────────────────────────────\n\nexport function transitionTask(\n state: OrchestrationState,\n taskId: string,\n to: TaskStatus,\n): OrchestrationState {\n const current = state.taskStatuses.get(taskId);\n if (current === undefined) {\n throw new Error(`Unknown task id: ${taskId}`);\n }\n\n if (!TASK_TRANSITIONS[current].includes(to)) {\n throw new InvalidTransitionError(current, to, \"task\");\n }\n\n const next = cloneState(state);\n next.taskStatuses.set(taskId, to);\n return next;\n}\n","import type { LLMClient } from \"../llm/types.js\";\nimport type { ModelTier, TaskNode } from \"./types.js\";\n\n// ── Profile → tier mapping sets ─────────────────────────────────────\nexport const ADVANCED_PROFILES = new Set([\"architect\", \"planner\", \"designer\"]);\nexport const FAST_PROFILES = new Set([\"linter\", \"formatter\", \"validator\"]);\n\n// ── ModelRouter interface ───────────────────────────────────────────\nexport interface ModelRouter {\n getClient(tier: ModelTier): LLMClient;\n}\n\nexport interface ModelRouterClients {\n fast?: LLMClient;\n standard: LLMClient; // required, used as fallback\n advanced?: LLMClient;\n}\n\n// ── Factory ─────────────────────────────────────────────────────────\nexport function createModelRouter(clients: ModelRouterClients): ModelRouter {\n return {\n getClient(tier: ModelTier): LLMClient {\n if (tier === \"fast\") return clients.fast ?? clients.standard;\n if (tier === \"advanced\") return clients.advanced ?? clients.standard;\n return clients.standard;\n },\n };\n}\n\n// ── Tier suggestion based on task profile ───────────────────────────\nexport function suggestTier(node: TaskNode): ModelTier {\n if (ADVANCED_PROFILES.has(node.profile)) return \"advanced\";\n if (FAST_PROFILES.has(node.profile)) return \"fast\";\n return \"standard\";\n}\n","// ── Audit Logging ───────────────────────────────────────────────────\n\nexport type AuditEventType =\n | \"orchestration_started\"\n | \"orchestration_completed\"\n | \"orchestration_failed\"\n | \"orchestration_cancelled\"\n | \"task_started\"\n | \"task_completed\"\n | \"task_failed\"\n | \"task_skipped\"\n | \"approval_requested\"\n | \"approval_granted\"\n | \"approval_denied\"\n | \"gate_resolved\"\n | \"phase_transition\"\n | \"state_transition\";\n\nexport interface AuditEvent {\n timestamp: number;\n type: AuditEventType;\n message: string;\n taskId?: string;\n gateId?: string;\n data?: Record<string, unknown>;\n}\n\nexport interface AuditLog {\n orchestrationId: string;\n events: AuditEvent[];\n}\n\n/** Create an empty audit log for the given orchestration. */\nexport function createAuditLog(orchestrationId: string): AuditLog {\n return { orchestrationId, events: [] };\n}\n\n/** Append an event with a Date.now() timestamp. Mutates the log. */\nexport function recordAuditEvent(\n log: AuditLog,\n event: Omit<AuditEvent, \"timestamp\">,\n): void {\n log.events.push({ ...event, timestamp: Date.now() });\n}\n\n/** Return all events, optionally filtered by type. */\nexport function getAuditTrail(\n log: AuditLog,\n type?: AuditEventType,\n): AuditEvent[] {\n if (type === undefined) return [...log.events];\n return log.events.filter((e) => e.type === type);\n}\n\n/** Return a human-readable formatted string of the audit trail. */\nexport function formatAuditTrail(log: AuditLog): string {\n return log.events\n .map((e) => {\n const iso = new Date(e.timestamp).toISOString();\n const taskPart = e.taskId ? ` [${e.taskId}]` : \"\";\n const gatePart = e.gateId ? ` [gate:${e.gateId}]` : \"\";\n return `${iso} ${e.type}${taskPart}${gatePart} — ${e.message}`;\n })\n .join(\"\\n\");\n}\n","import type {\n TaskDAG,\n TaskResult,\n OrchestrationStatus,\n OrchestrationState,\n ModelTier,\n} from \"./types.js\";\nimport type { ModelRouter } from \"./model-router.js\";\nimport type { McpManager } from \"../mcp/client.js\";\nimport type { AuditLog } from \"./audit.js\";\n\nimport { validateDAG, getReadyNodes } from \"./dag.js\";\nimport {\n createOrchestrationState,\n transition,\n transitionTask,\n} from \"./state-machine.js\";\nimport { createAuditLog, recordAuditEvent } from \"./audit.js\";\nimport { delegateTask } from \"../delegate.js\";\n\n// ── Public interfaces ───────────────────────────────────────────────\n\nexport interface SchedulerCallbacks {\n onTaskStarted?: (nodeId: string, nodeName: string) => Promise<void>;\n onTaskCompleted?: (nodeId: string, nodeName: string, result: TaskResult) => Promise<void>;\n onTaskFailed?: (nodeId: string, nodeName: string, error: string) => Promise<void>;\n onApprovalRequired?: (gateId: string, gateName: string) => Promise<boolean>;\n onPhaseTransition?: (from: OrchestrationStatus, to: OrchestrationStatus) => Promise<void>;\n}\n\nexport interface SchedulerOptions {\n maxParallelTasks?: number; // default 4\n taskTimeoutMs?: number; // default 300_000\n mcpManager?: McpManager;\n}\n\nexport interface SchedulerResult {\n status: OrchestrationStatus;\n taskResults: Map<string, TaskResult>;\n auditLog: AuditLog;\n error?: string;\n durationMs: number;\n}\n\n// ── Scheduler ───────────────────────────────────────────────────────\n\nexport async function runScheduler(\n dag: TaskDAG,\n router: ModelRouter,\n options?: SchedulerOptions,\n callbacks?: SchedulerCallbacks,\n): Promise<SchedulerResult> {\n const startTime = Date.now();\n const maxParallel = options?.maxParallelTasks ?? 4;\n const mcpManager = options?.mcpManager ?? (null as unknown as McpManager);\n\n // 1. Validate DAG\n validateDAG(dag);\n\n // 2. Create initial state and audit log\n let state = createOrchestrationState(dag);\n const auditLog = createAuditLog(dag.id);\n\n // 3. Transition to running\n state = transition(state, \"running\");\n recordAuditEvent(auditLog, {\n type: \"orchestration_started\",\n message: `Orchestration \"${dag.name}\" started`,\n });\n\n const resolvedGates = new Set<string>();\n const running = new Map<string, Promise<void>>();\n\n // Helper: transition orchestration with callback\n async function transitionOrch(to: OrchestrationStatus, error?: string): Promise<void> {\n const from = state.status;\n state = transition(state, to, error);\n if (callbacks?.onPhaseTransition) {\n await callbacks.onPhaseTransition(from, to);\n }\n }\n\n // Helper: dispatch a single task\n function dispatchTask(nodeId: string): void {\n const node = dag.nodes.find((n) => n.id === nodeId)!;\n\n // pending -> ready -> running\n state = transitionTask(state, nodeId, \"ready\");\n state = transitionTask(state, nodeId, \"running\");\n\n const taskPromise = (async () => {\n // Fire onTaskStarted callback\n if (callbacks?.onTaskStarted) {\n await callbacks.onTaskStarted(nodeId, node.name);\n }\n\n recordAuditEvent(auditLog, {\n type: \"task_started\",\n message: `Task \"${node.name}\" started`,\n taskId: nodeId,\n });\n\n const startedAt = Date.now();\n const client = router.getClient(node.tier);\n\n // Build task description from name + description + context\n const taskDesc = [node.name, node.description, node.context]\n .filter(Boolean)\n .join(\": \");\n\n try {\n const delegationResult = await delegateTask(\n taskDesc,\n node.profile,\n client,\n mcpManager,\n { silent: true },\n );\n\n const completedAt = Date.now();\n\n if (delegationResult.success) {\n const taskResult: TaskResult = {\n nodeId,\n status: \"completed\",\n output: delegationResult.response,\n toolsUsed: delegationResult.toolsUsed,\n turns: delegationResult.turns,\n startedAt,\n completedAt,\n tier: node.tier,\n };\n\n state = transitionTask(state, nodeId, \"completed\");\n state.taskResults.set(nodeId, taskResult);\n\n recordAuditEvent(auditLog, {\n type: \"task_completed\",\n message: `Task \"${node.name}\" completed`,\n taskId: nodeId,\n });\n\n if (callbacks?.onTaskCompleted) {\n await callbacks.onTaskCompleted(nodeId, node.name, taskResult);\n }\n } else {\n const taskResult: TaskResult = {\n nodeId,\n status: \"failed\",\n error: delegationResult.error ?? \"Task failed\",\n toolsUsed: delegationResult.toolsUsed,\n turns: delegationResult.turns,\n startedAt,\n completedAt,\n tier: node.tier,\n };\n\n state = transitionTask(state, nodeId, \"failed\");\n state.taskResults.set(nodeId, taskResult);\n\n recordAuditEvent(auditLog, {\n type: \"task_failed\",\n message: `Task \"${node.name}\" failed: ${delegationResult.error}`,\n taskId: nodeId,\n });\n\n if (callbacks?.onTaskFailed) {\n await callbacks.onTaskFailed(nodeId, node.name, delegationResult.error ?? \"Task failed\");\n }\n }\n } catch (err) {\n const completedAt = Date.now();\n const errorMsg = err instanceof Error ? err.message : String(err);\n\n const taskResult: TaskResult = {\n nodeId,\n status: \"failed\",\n error: errorMsg,\n toolsUsed: [],\n turns: 0,\n startedAt,\n completedAt,\n tier: node.tier,\n };\n\n state = transitionTask(state, nodeId, \"failed\");\n state.taskResults.set(nodeId, taskResult);\n\n recordAuditEvent(auditLog, {\n type: \"task_failed\",\n message: `Task \"${node.name}\" threw: ${errorMsg}`,\n taskId: nodeId,\n });\n\n if (callbacks?.onTaskFailed) {\n await callbacks.onTaskFailed(nodeId, node.name, errorMsg);\n }\n }\n })();\n\n running.set(nodeId, taskPromise);\n\n // Remove from running map when done\n taskPromise.then(() => running.delete(nodeId));\n }\n\n // 4. Main loop\n try {\n while (true) {\n // Check for terminal state\n if ([\"completed\", \"failed\", \"cancelled\"].includes(state.status)) {\n break;\n }\n\n // a. Check if any task failed\n const hasFailed = [...state.taskStatuses.values()].some((s) => s === \"failed\");\n if (hasFailed) {\n await transitionOrch(\"failed\", \"A task failed\");\n recordAuditEvent(auditLog, {\n type: \"orchestration_failed\",\n message: \"Orchestration failed due to task failure\",\n });\n break;\n }\n\n // b. Check for pending gates\n let gateHandled = false;\n for (const gate of dag.gates) {\n if (resolvedGates.has(gate.id)) continue;\n\n const allAfterDone = gate.afterNodes.every(\n (id) => state.taskStatuses.get(id) === \"completed\",\n );\n if (!allAfterDone) continue;\n\n // Gate is active — need approval\n gateHandled = true;\n\n await transitionOrch(\"awaiting_approval\");\n recordAuditEvent(auditLog, {\n type: \"approval_requested\",\n message: `Gate \"${gate.name}\" requires approval`,\n gateId: gate.id,\n });\n\n let approved = false;\n if (callbacks?.onApprovalRequired) {\n approved = await callbacks.onApprovalRequired(gate.id, gate.name);\n }\n\n if (approved) {\n resolvedGates.add(gate.id);\n await transitionOrch(\"approved\");\n recordAuditEvent(auditLog, {\n type: \"approval_granted\",\n message: `Gate \"${gate.name}\" approved`,\n gateId: gate.id,\n });\n await transitionOrch(\"running\");\n recordAuditEvent(auditLog, {\n type: \"gate_resolved\",\n message: `Gate \"${gate.name}\" resolved, resuming`,\n gateId: gate.id,\n });\n } else {\n await transitionOrch(\"cancelled\");\n recordAuditEvent(auditLog, {\n type: \"approval_denied\",\n message: `Gate \"${gate.name}\" denied, cancelling`,\n gateId: gate.id,\n });\n break;\n }\n }\n\n if ([\"completed\", \"failed\", \"cancelled\"].includes(state.status)) {\n break;\n }\n\n // c. Get ready nodes\n const readyNodes = getReadyNodes(dag, state.taskStatuses, resolvedGates);\n\n if (readyNodes.length === 0 && running.size === 0) {\n // Check if all done\n const allCompleted = [...state.taskStatuses.values()].every(\n (s) => s === \"completed\" || s === \"skipped\",\n );\n if (allCompleted) {\n await transitionOrch(\"completed\");\n recordAuditEvent(auditLog, {\n type: \"orchestration_completed\",\n message: `Orchestration \"${dag.name}\" completed successfully`,\n });\n break;\n } else {\n // Stuck — nothing ready, nothing running, not all done\n await transitionOrch(\"failed\", \"Scheduler stuck: no ready or running tasks\");\n recordAuditEvent(auditLog, {\n type: \"orchestration_failed\",\n message: \"Orchestration stuck with no progress possible\",\n });\n break;\n }\n }\n\n // d. Dispatch ready tasks up to available slots\n const availableSlots = maxParallel - running.size;\n const toDispatch = readyNodes.slice(0, availableSlots);\n\n for (const nodeId of toDispatch) {\n dispatchTask(nodeId);\n }\n\n // e. Wait for at least one task to finish before re-looping\n if (running.size > 0) {\n await Promise.race(running.values());\n }\n }\n } catch (err) {\n const errorMsg = err instanceof Error ? err.message : String(err);\n if (![\"completed\", \"failed\", \"cancelled\"].includes(state.status)) {\n try {\n state = transition(state, \"failed\", errorMsg);\n } catch {\n // already terminal\n }\n }\n recordAuditEvent(auditLog, {\n type: \"orchestration_failed\",\n message: `Orchestration error: ${errorMsg}`,\n });\n }\n\n return {\n status: state.status,\n taskResults: state.taskResults,\n auditLog,\n error: state.error,\n durationMs: Date.now() - startTime,\n };\n}\n","import type { TaskDAG, TaskResult } from \"./types.js\";\nimport type { ModelRouter } from \"./model-router.js\";\nimport type { SchedulerCallbacks, SchedulerResult } from \"./scheduler.js\";\nimport { runScheduler } from \"./scheduler.js\";\n\n// ── Public interfaces ───────────────────────────────────────────────\n\nexport interface ReviewLoopOptions {\n /** Max review iterations before giving up (default: 3) */\n maxIterations?: number;\n /** Model router for the review agents */\n router: ModelRouter;\n /** Callbacks (passed through to scheduler) */\n callbacks?: SchedulerCallbacks;\n}\n\nexport interface ReviewResult {\n /** Whether the review loop passed */\n passed: boolean;\n /** Number of iterations it took */\n iterations: number;\n /** Results from the final review */\n reviewResult?: SchedulerResult;\n /** Reason for failure if !passed */\n reason?: string;\n}\n\n// ── buildReviewDAG ──────────────────────────────────────────────────\n\n/**\n * Build a review DAG that evaluates the output of a completed orchestration.\n * The review DAG has: code-review and test-review running in parallel.\n */\nexport function buildReviewDAG(\n originalDAG: TaskDAG,\n taskResults: Map<string, TaskResult>,\n): TaskDAG {\n // Build a formatted context summary from all task results\n let context = \"Review the following completed work:\\n\\n\";\n\n for (const node of originalDAG.nodes) {\n const result = taskResults.get(node.id);\n context += `## Task: ${node.name}\\n`;\n context += `Profile: ${node.profile}\\n`;\n context += `Output: ${result?.output ?? \"(no output)\"}\\n\\n`;\n }\n\n return {\n id: `review-${originalDAG.id}`,\n name: `Review: ${originalDAG.name}`,\n goal: `Review the completed work from \"${originalDAG.name}\"`,\n nodes: [\n {\n id: \"code-review\",\n name: \"Code Review\",\n profile: \"reviewer\",\n tier: \"standard\",\n dependencies: [],\n context,\n },\n {\n id: \"test-review\",\n name: \"Test Review\",\n profile: \"tester\",\n tier: \"standard\",\n dependencies: [],\n context,\n },\n ],\n gates: [],\n };\n}\n\n// ── runReviewLoop ───────────────────────────────────────────────────\n\n/**\n * Run a self-review loop on completed orchestration output.\n *\n * 1. Build a review DAG from the completed task results\n * 2. Run the review DAG via scheduler\n * 3. Check if review passed (all tasks succeed)\n * 4. If passed, return { passed: true }\n * 5. If failed, return { passed: false, reason }\n *\n * This is a single-pass review (not iterative fix-and-review).\n * The iterative pattern is: orchestrate → review → fix → review → ...\n * which is handled at a higher level.\n */\nexport async function runReviewLoop(\n originalDAG: TaskDAG,\n taskResults: Map<string, TaskResult>,\n options: ReviewLoopOptions,\n): Promise<ReviewResult> {\n const reviewDAG = buildReviewDAG(originalDAG, taskResults);\n\n const schedulerResult = await runScheduler(\n reviewDAG,\n options.router,\n {},\n options.callbacks,\n );\n\n if (schedulerResult.status === \"completed\") {\n return {\n passed: true,\n iterations: 1,\n reviewResult: schedulerResult,\n };\n }\n\n return {\n passed: false,\n iterations: 1,\n reason: schedulerResult.error,\n reviewResult: schedulerResult,\n };\n}\n","export type CircuitState = \"closed\" | \"open\" | \"half-open\";\n\nexport interface CircuitBreakerOptions {\n failureThreshold: number;\n resetTimeoutMs: number;\n halfOpenMaxAttempts: number;\n}\n\nconst DEFAULTS: CircuitBreakerOptions = {\n failureThreshold: 3,\n resetTimeoutMs: 60_000,\n halfOpenMaxAttempts: 1,\n};\n\nexport interface CircuitBreaker {\n readonly name: string;\n readonly state: CircuitState;\n readonly failures: number;\n readonly lastFailureAt: number | null;\n\n /** Check if a request can proceed. Returns false if circuit is open. */\n canExecute(): boolean;\n\n /** Record a successful execution. Resets to closed. */\n recordSuccess(): void;\n\n /** Record a failed execution. May trip the circuit to open. */\n recordFailure(): void;\n\n /** Force reset to closed state. */\n reset(): void;\n}\n\nexport function createCircuitBreaker(\n name: string,\n options?: Partial<CircuitBreakerOptions>,\n): CircuitBreaker {\n const opts: CircuitBreakerOptions = { ...DEFAULTS, ...options };\n\n let state: CircuitState = \"closed\";\n let failures = 0;\n let lastFailureAt: number | null = null;\n let openedAt: number | null = null;\n let halfOpenAttempts = 0;\n\n function checkHalfOpen(): void {\n if (\n state === \"open\" &&\n openedAt !== null &&\n Date.now() - openedAt >= opts.resetTimeoutMs\n ) {\n state = \"half-open\";\n halfOpenAttempts = 0;\n }\n }\n\n return {\n get name() {\n return name;\n },\n get state() {\n checkHalfOpen();\n return state;\n },\n get failures() {\n return failures;\n },\n get lastFailureAt() {\n return lastFailureAt;\n },\n\n canExecute(): boolean {\n checkHalfOpen();\n if (state === \"closed\") return true;\n if (state === \"open\") return false;\n // half-open: limited attempts\n if (halfOpenAttempts >= opts.halfOpenMaxAttempts) return false;\n halfOpenAttempts++;\n return true;\n },\n\n recordSuccess(): void {\n if (state === \"half-open\") {\n state = \"closed\";\n failures = 0;\n lastFailureAt = null;\n openedAt = null;\n halfOpenAttempts = 0;\n }\n },\n\n recordFailure(): void {\n failures++;\n lastFailureAt = Date.now();\n if (state === \"half-open\") {\n // back to open\n state = \"open\";\n openedAt = Date.now();\n halfOpenAttempts = 0;\n } else if (failures >= opts.failureThreshold) {\n state = \"open\";\n openedAt = Date.now();\n }\n },\n\n reset(): void {\n state = \"closed\";\n failures = 0;\n lastFailureAt = null;\n openedAt = null;\n halfOpenAttempts = 0;\n },\n };\n}\n\n/**\n * Registry of circuit breakers, one per agent profile.\n */\nexport interface CircuitBreakerRegistry {\n get(name: string): CircuitBreaker;\n getAll(): CircuitBreaker[];\n resetAll(): void;\n /** Get formatted status summary. */\n formatStatus(): string;\n}\n\nexport function createCircuitBreakerRegistry(\n options?: Partial<CircuitBreakerOptions>,\n): CircuitBreakerRegistry {\n const breakers = new Map<string, CircuitBreaker>();\n\n return {\n get(name: string): CircuitBreaker {\n let cb = breakers.get(name);\n if (!cb) {\n cb = createCircuitBreaker(name, options);\n breakers.set(name, cb);\n }\n return cb;\n },\n\n getAll(): CircuitBreaker[] {\n return [...breakers.values()];\n },\n\n resetAll(): void {\n for (const cb of breakers.values()) {\n cb.reset();\n }\n },\n\n formatStatus(): string {\n if (breakers.size === 0) {\n return \"No circuit breakers registered.\";\n }\n const lines = [...breakers.values()].map(\n (cb) =>\n ` ${cb.name}: state=${cb.state} failures=${cb.failures}`,\n );\n return `Circuit breakers (${breakers.size}):\\n${lines.join(\"\\n\")}`;\n },\n };\n}\n","import { readFile, writeFile, mkdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport type {\n TaskDAG,\n TaskResult,\n OrchestrationStatus,\n TaskStatus,\n} from \"./types.js\";\n\n// ── CheckpointData ──────────────────────────────────────────────────────\nexport interface CheckpointData {\n version: number;\n orchestrationId: string;\n dag: TaskDAG;\n status: OrchestrationStatus;\n taskStatuses: Record<string, TaskStatus>;\n taskResults: Record<string, TaskResult>;\n resolvedGates: string[];\n activeGate: string | null;\n startedAt: number;\n updatedAt: number;\n checkpointedAt: number;\n}\n\n/**\n * Serialize orchestration state to a checkpoint.\n */\nexport function createCheckpoint(\n orchestrationId: string,\n dag: TaskDAG,\n status: OrchestrationStatus,\n taskStatuses: Map<string, TaskStatus>,\n taskResults: Map<string, TaskResult>,\n resolvedGates: Set<string>,\n activeGate: string | null,\n startedAt: number,\n): CheckpointData {\n const now = Date.now();\n return {\n version: 1,\n orchestrationId,\n dag,\n status,\n taskStatuses: Object.fromEntries(taskStatuses),\n taskResults: Object.fromEntries(taskResults),\n resolvedGates: [...resolvedGates],\n activeGate,\n startedAt,\n updatedAt: now,\n checkpointedAt: now,\n };\n}\n\n/**\n * Serialize checkpoint to JSON string.\n */\nexport function serializeCheckpoint(checkpoint: CheckpointData): string {\n return JSON.stringify(checkpoint);\n}\n\n/**\n * Deserialize JSON string to checkpoint.\n */\nexport function deserializeCheckpoint(json: string): CheckpointData {\n return JSON.parse(json) as CheckpointData;\n}\n\n/**\n * Save checkpoint to a file.\n * Writes to dir/checkpoint-{orchestrationId}.json.\n * Returns the file path.\n */\nexport async function saveCheckpoint(\n checkpoint: CheckpointData,\n dir: string,\n): Promise<string> {\n await mkdir(dir, { recursive: true });\n const filePath = join(dir, `checkpoint-${checkpoint.orchestrationId}.json`);\n await writeFile(filePath, serializeCheckpoint(checkpoint), \"utf-8\");\n return filePath;\n}\n\n/**\n * Load checkpoint from a file.\n * Returns null if the file does not exist.\n */\nexport async function loadCheckpoint(\n orchestrationId: string,\n dir: string,\n): Promise<CheckpointData | null> {\n const filePath = join(dir, `checkpoint-${orchestrationId}.json`);\n try {\n const json = await readFile(filePath, \"utf-8\");\n return deserializeCheckpoint(json);\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n return null;\n }\n throw err;\n }\n}\n\n/**\n * Restore Maps and Sets from checkpoint data.\n */\nexport function restoreMaps(checkpoint: CheckpointData): {\n taskStatuses: Map<string, TaskStatus>;\n taskResults: Map<string, TaskResult>;\n resolvedGates: Set<string>;\n} {\n return {\n taskStatuses: new Map(Object.entries(checkpoint.taskStatuses)),\n taskResults: new Map(Object.entries(checkpoint.taskResults)),\n resolvedGates: new Set(checkpoint.resolvedGates),\n };\n}\n","import type { ModelTier } from \"./types.js\";\n\n// ── Interfaces ──────────────────────────────────────────────────────\n\nexport interface TierCost {\n inputTokensPerDollar: number;\n outputTokensPerDollar: number;\n}\n\nexport interface CostEntry {\n tier: ModelTier;\n taskId: string;\n inputTokens: number;\n outputTokens: number;\n estimatedCost: number;\n timestamp: number;\n}\n\nexport interface CostTracker {\n /** Record token usage for a task. */\n record(\n taskId: string,\n tier: ModelTier,\n inputTokens: number,\n outputTokens: number,\n ): void;\n\n /** Get total estimated cost. */\n totalCost(): number;\n\n /** Get cost breakdown by tier. */\n costByTier(): Record<ModelTier, number>;\n\n /** Get all entries. */\n entries(): CostEntry[];\n\n /** Check if budget is exceeded. */\n isOverBudget(): boolean;\n\n /** Get remaining budget (null if no budget set). */\n remainingBudget(): number | null;\n\n /** Format cost summary. */\n formatSummary(): string;\n}\n\nexport interface CostTrackerOptions {\n /** Budget limit in dollars (null = unlimited). */\n budgetLimit?: number | null;\n /** Cost rates per tier (defaults provided). */\n tierCosts?: Partial<Record<ModelTier, TierCost>>;\n}\n\n// ── Default rates (approximate Claude pricing) ──────────────────────\n\nexport const DEFAULT_TIER_COSTS: Record<ModelTier, TierCost> = {\n fast: {\n inputTokensPerDollar: 5_000_000,\n outputTokensPerDollar: 1_250_000,\n }, // ~$0.20/$0.80 per 1M\n standard: {\n inputTokensPerDollar: 333_333,\n outputTokensPerDollar: 66_667,\n }, // ~$3/$15 per 1M\n advanced: {\n inputTokensPerDollar: 66_667,\n outputTokensPerDollar: 13_333,\n }, // ~$15/$75 per 1M\n};\n\n// ── Factory ─────────────────────────────────────────────────────────\n\nexport function createCostTracker(options?: CostTrackerOptions): CostTracker {\n const budgetLimit = options?.budgetLimit ?? null;\n const tierCosts: Record<ModelTier, TierCost> = {\n ...DEFAULT_TIER_COSTS,\n ...options?.tierCosts,\n };\n\n const _entries: CostEntry[] = [];\n\n function estimateCost(\n tier: ModelTier,\n inputTokens: number,\n outputTokens: number,\n ): number {\n const rates = tierCosts[tier];\n return (\n inputTokens / rates.inputTokensPerDollar +\n outputTokens / rates.outputTokensPerDollar\n );\n }\n\n function record(\n taskId: string,\n tier: ModelTier,\n inputTokens: number,\n outputTokens: number,\n ): void {\n _entries.push({\n tier,\n taskId,\n inputTokens,\n outputTokens,\n estimatedCost: estimateCost(tier, inputTokens, outputTokens),\n timestamp: Date.now(),\n });\n }\n\n function totalCost(): number {\n return _entries.reduce((sum, e) => sum + e.estimatedCost, 0);\n }\n\n function costByTier(): Record<ModelTier, number> {\n const result: Record<ModelTier, number> = {\n fast: 0,\n standard: 0,\n advanced: 0,\n };\n for (const entry of _entries) {\n result[entry.tier] += entry.estimatedCost;\n }\n return result;\n }\n\n function entries(): CostEntry[] {\n return [..._entries];\n }\n\n function isOverBudget(): boolean {\n if (budgetLimit === null) return false;\n return totalCost() > budgetLimit;\n }\n\n function remainingBudget(): number | null {\n if (budgetLimit === null) return null;\n return budgetLimit - totalCost();\n }\n\n function formatSummary(): string {\n const total = totalCost();\n const byTier = costByTier();\n const lines: string[] = [];\n\n lines.push(`Total: $${total.toFixed(4)}`);\n\n for (const tier of [\"fast\", \"standard\", \"advanced\"] as ModelTier[]) {\n if (byTier[tier] > 0) {\n lines.push(` ${tier}: $${byTier[tier].toFixed(4)}`);\n }\n }\n\n if (budgetLimit !== null) {\n const remaining = remainingBudget()!;\n lines.push(\n `Budget: $${budgetLimit.toFixed(2)} | Remaining: $${remaining.toFixed(4)}`,\n );\n }\n\n lines.push(`Entries: ${_entries.length}`);\n\n return lines.join(\"\\n\");\n }\n\n return {\n record,\n totalCost,\n costByTier,\n entries,\n isOverBudget,\n remainingBudget,\n formatSummary,\n };\n}\n","import type { TaskDAG, TaskNode, ModelTier } from \"./types.js\";\n\n// ── Types ──────────────────────────────────────────────────────────\n\nexport type PolicySeverity = \"error\" | \"warning\" | \"info\";\n\nexport interface PolicyViolation {\n rule: string;\n severity: PolicySeverity;\n message: string;\n nodeId?: string;\n}\n\nexport interface PolicyResult {\n passed: boolean;\n violations: PolicyViolation[];\n}\n\nexport interface PolicyRule {\n name: string;\n description: string;\n severity: PolicySeverity;\n check: (dag: TaskDAG) => PolicyViolation[];\n}\n\n// ── Built-in policy rules ──────────────────────────────────────────\n\nconst maxTaskCount: PolicyRule = {\n name: \"max-task-count\",\n description: \"DAG has more than 20 tasks\",\n severity: \"warning\",\n check: (dag) => {\n if (dag.nodes.length > 20) {\n return [\n {\n rule: \"max-task-count\",\n severity: \"warning\",\n message: `DAG has ${dag.nodes.length} tasks (limit: 20)`,\n },\n ];\n }\n return [];\n },\n};\n\nconst requiresReview: PolicyRule = {\n name: \"requires-review\",\n description: 'No node with profile \"reviewer\" exists',\n severity: \"warning\",\n check: (dag) => {\n const hasReviewer = dag.nodes.some((n) => n.profile === \"reviewer\");\n if (!hasReviewer) {\n return [\n {\n rule: \"requires-review\",\n severity: \"warning\",\n message: \"DAG has no reviewer node — consider adding a code review step\",\n },\n ];\n }\n return [];\n },\n};\n\nconst requiresTesting: PolicyRule = {\n name: \"requires-testing\",\n description: 'No node with profile \"tester\" exists',\n severity: \"warning\",\n check: (dag) => {\n const hasTester = dag.nodes.some((n) => n.profile === \"tester\");\n if (!hasTester) {\n return [\n {\n rule: \"requires-testing\",\n severity: \"warning\",\n message: \"DAG has no tester node — consider adding a testing step\",\n },\n ];\n }\n return [];\n },\n};\n\nconst noOrphanNodes: PolicyRule = {\n name: \"no-orphan-nodes\",\n description: \"Every node is either a root or has valid dependencies\",\n severity: \"error\",\n check: (dag) => {\n const nodeIds = new Set(dag.nodes.map((n) => n.id));\n const violations: PolicyViolation[] = [];\n for (const node of dag.nodes) {\n for (const dep of node.dependencies) {\n if (!nodeIds.has(dep)) {\n violations.push({\n rule: \"no-orphan-nodes\",\n severity: \"error\",\n message: `Node \"${node.id}\" depends on \"${dep}\" which does not exist`,\n nodeId: node.id,\n });\n }\n }\n }\n return violations;\n },\n};\n\nconst approvalBeforeDeploy: PolicyRule = {\n name: \"approval-before-deploy\",\n description:\n \"If any node name contains 'deploy' or 'release', an approval gate should exist\",\n severity: \"warning\",\n check: (dag) => {\n const deployNodes = dag.nodes.filter((n) => {\n const lower = n.name.toLowerCase();\n return lower.includes(\"deploy\") || lower.includes(\"release\");\n });\n if (deployNodes.length === 0) return [];\n\n const hasApprovalGate = dag.gates.some((g) => g.type === \"approval\");\n if (hasApprovalGate) return [];\n\n return deployNodes.map((n) => ({\n rule: \"approval-before-deploy\",\n severity: \"warning\" as const,\n message: `Node \"${n.name}\" looks like a deploy/release step but no approval gate exists`,\n nodeId: n.id,\n }));\n },\n};\n\nconst noAdvancedWithoutJustification: PolicyRule = {\n name: \"no-advanced-without-justification\",\n description: 'Nodes with tier \"advanced\" flagged for cost awareness',\n severity: \"info\",\n check: (dag) =>\n dag.nodes\n .filter((n) => n.tier === \"advanced\")\n .map((n) => ({\n rule: \"no-advanced-without-justification\",\n severity: \"info\" as const,\n message: `Node \"${n.id}\" uses advanced tier — ensure this is justified for cost`,\n nodeId: n.id,\n })),\n};\n\nconst maxParallelDepth: PolicyRule = {\n name: \"max-parallel-depth\",\n description: \"DAG has more than 5 levels of depth\",\n severity: \"warning\",\n check: (dag) => {\n // Compute max depth via topological traversal\n const nodeIds = new Set(dag.nodes.map((n) => n.id));\n const depthMap = new Map<string, number>();\n\n // Build adjacency: for each node, depth = max(depth of deps) + 1\n // Handle missing deps gracefully (they are caught by no-orphan-nodes)\n function getDepth(node: TaskNode, visited: Set<string>): number {\n if (depthMap.has(node.id)) return depthMap.get(node.id)!;\n if (visited.has(node.id)) return 0; // cycle guard\n visited.add(node.id);\n\n let maxDep = 0;\n for (const depId of node.dependencies) {\n const depNode = dag.nodes.find((n) => n.id === depId);\n if (depNode) {\n maxDep = Math.max(maxDep, getDepth(depNode, visited) + 1);\n }\n }\n depthMap.set(node.id, maxDep);\n return maxDep;\n }\n\n for (const node of dag.nodes) {\n getDepth(node, new Set());\n }\n\n const maxDepth = Math.max(0, ...depthMap.values());\n if (maxDepth > 5) {\n return [\n {\n rule: \"max-parallel-depth\",\n severity: \"warning\",\n message: `DAG depth is ${maxDepth} (limit: 5)`,\n },\n ];\n }\n return [];\n },\n};\n\n// ── Public API ─────────────────────────────────────────────────────\n\n/**\n * Create built-in policy rules.\n */\nexport function getDefaultPolicies(): PolicyRule[] {\n return [\n maxTaskCount,\n requiresReview,\n requiresTesting,\n noOrphanNodes,\n approvalBeforeDeploy,\n noAdvancedWithoutJustification,\n maxParallelDepth,\n ];\n}\n\n/**\n * Evaluate a DAG against a set of policy rules.\n */\nexport function evaluatePolicy(\n dag: TaskDAG,\n rules?: PolicyRule[],\n): PolicyResult {\n const effectiveRules = rules ?? getDefaultPolicies();\n const violations: PolicyViolation[] = [];\n\n for (const rule of effectiveRules) {\n violations.push(...rule.check(dag));\n }\n\n const hasErrors = violations.some((v) => v.severity === \"error\");\n\n return {\n passed: !hasErrors,\n violations,\n };\n}\n\n/**\n * Format policy result for display.\n */\nexport function formatPolicyResult(result: PolicyResult): string {\n const lines: string[] = [];\n const status = result.passed ? \"PASS\" : \"FAIL\";\n lines.push(`Policy check: ${status}`);\n\n if (result.violations.length === 0) {\n lines.push(\" No violations found.\");\n return lines.join(\"\\n\");\n }\n\n for (const v of result.violations) {\n const nodeLabel = v.nodeId ? ` [${v.nodeId}]` : \"\";\n lines.push(` [${v.severity}] ${v.rule}${nodeLabel}: ${v.message}`);\n }\n\n return lines.join(\"\\n\");\n}\n","import type { TaskDAG, ModelTier } from \"./types.js\";\nimport type { ModelRouter } from \"./model-router.js\";\nimport type { SchedulerCallbacks, SchedulerResult } from \"./scheduler.js\";\nimport type { CircuitBreakerRegistry } from \"./circuit-breaker.js\";\nimport type { CostTracker } from \"./cost-tracker.js\";\nimport type { ReviewResult } from \"./review-loop.js\";\nimport type { PolicyResult } from \"./policy.js\";\n\nimport { runScheduler } from \"./scheduler.js\";\nimport { evaluatePolicy } from \"./policy.js\";\nimport { createCircuitBreakerRegistry } from \"./circuit-breaker.js\";\nimport { createCostTracker } from \"./cost-tracker.js\";\nimport { runReviewLoop } from \"./review-loop.js\";\nimport { createAuditLog } from \"./audit.js\";\n\n// ── Options ─────────────────────────────────────────────────────────\n\nexport interface FullOrchestrationOptions {\n router: ModelRouter;\n maxParallelTasks?: number;\n\n // Enterprise features (all optional — graceful degradation)\n enableCircuitBreaker?: boolean;\n enableCostTracking?: boolean;\n enableCheckpoints?: boolean;\n enablePolicyCheck?: boolean;\n enableSelfReview?: boolean;\n\n // Budget limit in dollars (null = unlimited)\n budgetLimit?: number | null;\n\n // Checkpoint directory\n checkpointDir?: string;\n\n // Callbacks\n callbacks?: SchedulerCallbacks;\n}\n\n// ── Result ──────────────────────────────────────────────────────────\n\nexport interface FullOrchestrationResult {\n // Core result\n scheduler: SchedulerResult;\n\n // Enterprise results (undefined if feature disabled)\n policy?: PolicyResult;\n review?: ReviewResult;\n costSummary?: string;\n circuitBreakerStatus?: string;\n checkpointPath?: string;\n\n // Summary\n success: boolean;\n durationMs: number;\n}\n\n// ── Runner ──────────────────────────────────────────────────────────\n\n/**\n * Run a full orchestration with all enterprise features wired in.\n *\n * Flow:\n * 1. Policy check — evaluate DAG against rules. If errors, abort.\n * 2. Initialize circuit breaker registry + cost tracker\n * 3. Run scheduler with wrapped callbacks that:\n * a. Check circuit breaker before each task\n * b. Record cost after each task\n * c. Record circuit breaker success/failure\n * d. Save checkpoint after each completed task\n * 4. If enableSelfReview and scheduler completed, run review loop\n * 5. Return consolidated result\n */\nexport async function runOrchestrationFull(\n dag: TaskDAG,\n options: FullOrchestrationOptions,\n): Promise<FullOrchestrationResult> {\n const startTime = Date.now();\n\n // 1. Policy check\n let policyResult: PolicyResult | undefined;\n if (options.enablePolicyCheck) {\n policyResult = evaluatePolicy(dag);\n if (!policyResult.passed) {\n const errorMessages = policyResult.violations\n .filter((v) => v.severity === \"error\")\n .map((v) => v.message)\n .join(\"; \");\n return {\n scheduler: {\n status: \"failed\",\n taskResults: new Map(),\n auditLog: createAuditLog(dag.id),\n error: `Policy check failed: ${errorMessages}`,\n durationMs: Date.now() - startTime,\n },\n policy: policyResult,\n success: false,\n durationMs: Date.now() - startTime,\n };\n }\n }\n\n // 2. Initialize enterprise features\n const circuitBreakers: CircuitBreakerRegistry | undefined =\n options.enableCircuitBreaker ? createCircuitBreakerRegistry() : undefined;\n const costTracker: CostTracker | undefined =\n options.enableCostTracking\n ? createCostTracker({ budgetLimit: options.budgetLimit })\n : undefined;\n\n // 3. Wrap callbacks\n const wrappedCallbacks: SchedulerCallbacks = {\n ...options.callbacks,\n\n onTaskStarted: async (nodeId: string, nodeName: string) => {\n // Check circuit breaker\n const node = dag.nodes.find((n) => n.id === nodeId);\n if (circuitBreakers && node) {\n circuitBreakers.get(node.profile).canExecute();\n }\n await options.callbacks?.onTaskStarted?.(nodeId, nodeName);\n },\n\n onTaskCompleted: async (nodeId: string, nodeName: string, result) => {\n const node = dag.nodes.find((n) => n.id === nodeId);\n if (node) {\n // Record circuit breaker success\n circuitBreakers?.get(node.profile).recordSuccess();\n // Record cost (estimate tokens from turns)\n costTracker?.record(nodeId, node.tier, result.turns * 500, result.turns * 200);\n }\n await options.callbacks?.onTaskCompleted?.(nodeId, nodeName, result);\n },\n\n onTaskFailed: async (nodeId: string, nodeName: string, error: string) => {\n const node = dag.nodes.find((n) => n.id === nodeId);\n if (node) {\n circuitBreakers?.get(node.profile).recordFailure();\n }\n await options.callbacks?.onTaskFailed?.(nodeId, nodeName, error);\n },\n };\n\n // 4. Run scheduler\n const schedulerResult = await runScheduler(dag, options.router, {\n maxParallelTasks: options.maxParallelTasks,\n }, wrappedCallbacks);\n\n // 5. Self-review (if enabled and scheduler completed)\n let reviewResult: ReviewResult | undefined;\n if (options.enableSelfReview && schedulerResult.status === \"completed\") {\n reviewResult = await runReviewLoop(dag, schedulerResult.taskResults, {\n router: options.router,\n });\n }\n\n // 6. Build result\n const success =\n schedulerResult.status === \"completed\" &&\n (reviewResult ? reviewResult.passed : true) &&\n (costTracker ? !costTracker.isOverBudget() : true);\n\n return {\n scheduler: schedulerResult,\n policy: policyResult,\n review: reviewResult,\n costSummary: costTracker?.formatSummary(),\n circuitBreakerStatus: circuitBreakers?.formatStatus(),\n success,\n durationMs: Date.now() - startTime,\n };\n}\n","import type { LLMClient } from \"../llm/types.js\";\nimport type { TaskDAG } from \"./types.js\";\nimport type { ModelRouter } from \"./model-router.js\";\nimport type { FullOrchestrationResult } from \"./runner.js\";\nimport type { SchedulerCallbacks } from \"./scheduler.js\";\n\nimport { decomposeRequirement } from \"./decompose.js\";\nimport { getTemplate } from \"./templates/index.js\";\nimport { runOrchestrationFull } from \"./runner.js\";\nimport { classifyProject } from \"../project/detector.js\";\nimport { scanStack } from \"../dev/stack-detector.js\";\nimport {\n ensureAllProfilesInstalled,\n getProfilesDir,\n} from \"../profiles/auto-install.js\";\n\n// ── DAG Display (inlined to avoid circular import with index.ts) ────\n\nfunction formatDAGForDisplay(dag: TaskDAG): string {\n const lines: string[] = [];\n lines.push(`## ${dag.name}`);\n lines.push(`**Goal:** ${dag.goal}`);\n lines.push(`**Tasks:** ${dag.nodes.length} | **Gates:** ${dag.gates.length}`);\n lines.push(\"\");\n for (const node of dag.nodes) {\n const depLabel =\n node.dependencies.length === 0\n ? \"(root)\"\n : `(after: ${node.dependencies.join(\", \")})`;\n lines.push(`- **${node.name}** \\u2192 ${node.profile} [${node.tier}] ${depLabel}`);\n }\n for (const gate of dag.gates) {\n lines.push(`- \\uD83D\\uDD12 **${gate.name}** [${gate.type}]`);\n }\n return lines.join(\"\\n\");\n}\n\n// ── Options ─────────────────────────────────────────────────────────\n\nexport interface SmartOrchestrationOptions {\n /** The requirement to orchestrate */\n requirement: string;\n /** LLM client for decomposition */\n client: LLMClient;\n /** Model router for task execution */\n router: ModelRouter;\n /** Optional: project path for auto-classification */\n projectPath?: string;\n /** Optional: force a specific template name */\n templateName?: string;\n /** Enable enterprise features */\n enablePolicyCheck?: boolean;\n enableSelfReview?: boolean;\n enableCostTracking?: boolean;\n budgetLimit?: number | null;\n /** Callbacks */\n callbacks?: SchedulerCallbacks;\n}\n\n// ── Result ──────────────────────────────────────────────────────────\n\nexport interface SmartOrchestrationResult {\n /** The DAG that was generated or selected */\n dag: TaskDAG;\n /** Project type detected (if projectPath provided) */\n projectType?: string;\n /** Template used (if any) */\n templateUsed?: string;\n /** Full orchestration result */\n orchestration: FullOrchestrationResult;\n /** Human-readable summary */\n summary: string;\n}\n\n// ── Smart Orchestration Pipeline ────────────────────────────────────\n\n/**\n * Smart orchestration pipeline:\n * 1. Ensure orchestrator profiles are installed\n * 2. If projectPath → classify project, get recommended template\n * 3. If templateName → use that template to build DAG\n * 4. Otherwise → decompose requirement via LLM\n * 5. Run full orchestration (policy + scheduler + circuit breakers + cost + review)\n * 6. Return consolidated result with summary\n */\nexport async function smartOrchestrate(\n options: SmartOrchestrationOptions,\n): Promise<SmartOrchestrationResult> {\n // 1. Auto-install profiles\n ensureAllProfilesInstalled(getProfilesDir());\n\n // 2. Detect project type if path given and no explicit template\n let projectType: string | undefined;\n let templateName = options.templateName;\n\n if (options.projectPath && !templateName) {\n const stack = scanStack(options.projectPath);\n const classification = classifyProject(stack);\n projectType = classification.type;\n templateName = classification.suggestedTemplate;\n }\n\n // 3. Build DAG — template if available, otherwise LLM decomposition\n let dag: TaskDAG;\n if (templateName) {\n const templateFn = getTemplate(templateName);\n if (templateFn) {\n dag = templateFn({ name: \"Orchestration\", goal: options.requirement });\n } else {\n // Template not found — fall back to LLM\n dag = await decomposeRequirement(options.requirement, options.client);\n templateName = undefined;\n }\n } else {\n dag = await decomposeRequirement(options.requirement, options.client);\n }\n\n // 4. Run full orchestration\n const orchestration = await runOrchestrationFull(dag, {\n router: options.router,\n enablePolicyCheck: options.enablePolicyCheck,\n enableSelfReview: options.enableSelfReview,\n enableCostTracking: options.enableCostTracking,\n budgetLimit: options.budgetLimit,\n callbacks: options.callbacks,\n });\n\n // 5. Build summary\n const summary = formatSmartResult({\n dag,\n projectType,\n templateUsed: templateName,\n orchestration,\n summary: \"\",\n });\n\n return { dag, projectType, templateUsed: templateName, orchestration, summary };\n}\n\n// ── Formatting ──────────────────────────────────────────────────────\n\n/**\n * Format a SmartOrchestrationResult for CLI display.\n */\nexport function formatSmartResult(result: SmartOrchestrationResult): string {\n const lines: string[] = [];\n\n if (result.projectType) {\n lines.push(`Project type: ${result.projectType}`);\n }\n if (result.templateUsed) {\n lines.push(`Template: ${result.templateUsed}`);\n }\n\n lines.push(\"\");\n lines.push(formatDAGForDisplay(result.dag));\n lines.push(\"\");\n\n const orch = result.orchestration;\n lines.push(\n `Status: ${orch.success ? \"completed\" : \"failed\"} (${orch.durationMs}ms)`,\n );\n\n if (orch.policy && !orch.policy.passed) {\n const errorCount = orch.policy.violations.filter(\n (v) => v.severity === \"error\",\n ).length;\n lines.push(\n `Policy: FAILED — ${errorCount} error${errorCount !== 1 ? \"s\" : \"\"}`,\n );\n }\n if (orch.review) {\n lines.push(`Review: ${orch.review.passed ? \"passed\" : \"failed\"}`);\n }\n if (orch.costSummary) {\n lines.push(`Cost: ${orch.costSummary}`);\n }\n\n return lines.join(\"\\n\");\n}\n","import type { TaskDAG, TaskNode, PhaseGate } from \"../types.js\";\nimport { validateDAG } from \"../dag.js\";\n\n// ── Template Options ───────────────────────────────────────────────\n\nexport interface TemplateOptions {\n /** Project/feature name */\n name: string;\n /** Goal description */\n goal: string;\n /** Include approval gate before final phase */\n requireApproval?: boolean;\n}\n\n// ── Helpers ────────────────────────────────────────────────────────\n\nfunction node(\n id: string,\n profile: string,\n tier: TaskNode[\"tier\"],\n deps: string[] = [],\n): TaskNode {\n return {\n id,\n name: id.charAt(0).toUpperCase() + id.slice(1),\n profile,\n tier,\n dependencies: deps,\n };\n}\n\nfunction approvalGate(\n id: string,\n afterNodes: string[],\n beforeNodes: string[],\n): PhaseGate {\n return {\n id,\n name: `Approval: ${id}`,\n type: \"approval\",\n afterNodes,\n beforeNodes,\n };\n}\n\n// ── Templates ──────────────────────────────────────────────────────\n\n/**\n * Full feature development: architect → parallel coders → review → test → merge\n *\n * design (architect, advanced) → implement (coder) → review + test (parallel) → finalize\n * Optional approval gate between [review, test] and [finalize].\n */\nexport function fullFeatureTemplate(options: TemplateOptions): TaskDAG {\n const gates: PhaseGate[] = [];\n\n if (options.requireApproval) {\n gates.push(approvalGate(\"approval\", [\"review\", \"test\"], [\"finalize\"]));\n }\n\n const dag: TaskDAG = {\n id: `full-feature-${options.name}`,\n name: `Full Feature: ${options.name}`,\n goal: options.goal,\n nodes: [\n node(\"design\", \"architect\", \"advanced\"),\n node(\"implement\", \"coder\", \"standard\", [\"design\"]),\n node(\"review\", \"reviewer\", \"standard\", [\"implement\"]),\n node(\"test\", \"tester\", \"standard\", [\"implement\"]),\n node(\"finalize\", \"coder\", \"standard\", [\"review\", \"test\"]),\n ],\n gates,\n };\n\n validateDAG(dag);\n return dag;\n}\n\n/**\n * Bug fix: reproduce → fix → test → review\n *\n * With approval: adds a verify step gated behind review.\n */\nexport function bugFixTemplate(options: TemplateOptions): TaskDAG {\n const nodes: TaskNode[] = [\n node(\"reproduce\", \"tester\", \"standard\"),\n node(\"fix\", \"coder\", \"standard\", [\"reproduce\"]),\n node(\"test\", \"tester\", \"standard\", [\"fix\"]),\n node(\"review\", \"reviewer\", \"standard\", [\"test\"]),\n ];\n\n const gates: PhaseGate[] = [];\n\n if (options.requireApproval) {\n nodes.push(node(\"verify\", \"tester\", \"standard\", [\"review\"]));\n gates.push(approvalGate(\"approval\", [\"review\"], [\"verify\"]));\n }\n\n const dag: TaskDAG = {\n id: `bug-fix-${options.name}`,\n name: `Bug Fix: ${options.name}`,\n goal: options.goal,\n nodes,\n gates,\n };\n\n validateDAG(dag);\n return dag;\n}\n\n/**\n * Security audit: scan → triage → fix → rescan → review\n *\n * With approval: gates the fix step behind triage approval.\n */\nexport function securityAuditTemplate(options: TemplateOptions): TaskDAG {\n const gates: PhaseGate[] = [];\n\n if (options.requireApproval) {\n gates.push(approvalGate(\"approval\", [\"triage\"], [\"fix\"]));\n }\n\n const dag: TaskDAG = {\n id: `security-audit-${options.name}`,\n name: `Security Audit: ${options.name}`,\n goal: options.goal,\n nodes: [\n node(\"scan\", \"security\", \"standard\"),\n node(\"triage\", \"security\", \"standard\", [\"scan\"]),\n node(\"fix\", \"coder\", \"standard\", [\"triage\"]),\n node(\"rescan\", \"security\", \"standard\", [\"fix\"]),\n node(\"review\", \"reviewer\", \"standard\", [\"rescan\"]),\n ],\n gates,\n };\n\n validateDAG(dag);\n return dag;\n}\n\n// ── Registry ───────────────────────────────────────────────────────\n\nconst TEMPLATES: Record<string, (options: TemplateOptions) => TaskDAG> = {\n \"full-feature\": fullFeatureTemplate,\n \"bug-fix\": bugFixTemplate,\n \"security-audit\": securityAuditTemplate,\n};\n\n/**\n * Get a template by name.\n */\nexport function getTemplate(\n name: string,\n): ((options: TemplateOptions) => TaskDAG) | undefined {\n return TEMPLATES[name];\n}\n\n/**\n * List available template names.\n */\nexport function listTemplates(): string[] {\n return Object.keys(TEMPLATES);\n}\n","import type { StackProfile } from \"../dev/stack-detector.js\";\n\nexport type ProjectType =\n | \"web-frontend\"\n | \"web-fullstack\"\n | \"api-backend\"\n | \"mobile\"\n | \"cli-tool\"\n | \"library\"\n | \"ml-data\"\n | \"monorepo\"\n | \"unknown\";\n\nexport interface ProjectClassification {\n type: ProjectType;\n confidence: number;\n suggestedTemplate: string;\n suggestedProfiles: string[];\n description: string;\n}\n\nconst FRONTEND_FRAMEWORKS = new Set([\"react\", \"vue\", \"svelte\"]);\nconst FULLSTACK_FRAMEWORKS = new Set([\"next\", \"nuxt\", \"remix\"]);\nconst BACKEND_FRAMEWORKS = new Set([\n \"express\", \"fastify\", \"hono\", \"nestjs\",\n \"fiber\", \"gin\", \"chi\", \"echo\",\n \"fastapi\", \"django\", \"flask\",\n]);\nconst ML_FRAMEWORKS = new Set([\"torch\", \"tensorflow\", \"sklearn\", \"pytorch\", \"pandas\", \"numpy\"]);\nconst WEB_FRAMEWORKS = new Set([\n ...FRONTEND_FRAMEWORKS, ...FULLSTACK_FRAMEWORKS, ...BACKEND_FRAMEWORKS,\n]);\n\nconst TEMPLATE_MAP: Record<ProjectType, string> = {\n \"web-frontend\": \"full-feature\",\n \"web-fullstack\": \"full-feature\",\n \"api-backend\": \"full-feature\",\n mobile: \"full-feature\",\n \"cli-tool\": \"bug-fix\",\n library: \"full-feature\",\n \"ml-data\": \"full-feature\",\n monorepo: \"full-feature\",\n unknown: \"full-feature\",\n};\n\nconst PROFILE_MAP: Record<ProjectType, string[]> = {\n \"web-frontend\": [\"architect\", \"coder\", \"tester\", \"reviewer\"],\n \"web-fullstack\": [\"architect\", \"coder\", \"security\", \"tester\", \"reviewer\"],\n \"api-backend\": [\"architect\", \"coder\", \"security\", \"tester\", \"reviewer\"],\n mobile: [\"architect\", \"coder\", \"tester\", \"reviewer\"],\n \"cli-tool\": [\"coder\", \"tester\", \"reviewer\"],\n library: [\"architect\", \"coder\", \"tester\", \"reviewer\"],\n \"ml-data\": [\"architect\", \"coder\", \"tester\"],\n monorepo: [\"architect\", \"coder\", \"security\", \"tester\", \"reviewer\"],\n unknown: [\"coder\", \"tester\", \"reviewer\"],\n};\n\nconst DESCRIPTION_MAP: Record<ProjectType, string> = {\n \"web-frontend\": \"Frontend web application\",\n \"web-fullstack\": \"Full-stack web application with database\",\n \"api-backend\": \"API/backend service\",\n mobile: \"Mobile application\",\n \"cli-tool\": \"Command-line tool\",\n library: \"Reusable library/package\",\n \"ml-data\": \"Machine learning / data science project\",\n monorepo: \"Monorepo with multiple packages\",\n unknown: \"Unknown project type\",\n};\n\nfunction hasAny(items: string[], set: Set<string>): boolean {\n return items.some((i) => set.has(i));\n}\n\nexport function classifyProject(stack: StackProfile): ProjectClassification {\n let type: ProjectType;\n let confidence: number;\n\n if (stack.isMonorepo) {\n type = \"monorepo\";\n confidence = 0.9;\n } else if (hasAny(stack.frameworks, new Set([\"flutter\"])) || stack.languages.includes(\"dart\")) {\n type = \"mobile\";\n confidence = 0.9;\n } else if (hasAny(stack.frameworks, FULLSTACK_FRAMEWORKS) && stack.databases.length > 0) {\n type = \"web-fullstack\";\n confidence = 0.9;\n } else if (hasAny(stack.frameworks, BACKEND_FRAMEWORKS)) {\n type = \"api-backend\";\n confidence = 0.9;\n } else if (hasAny(stack.frameworks, FRONTEND_FRAMEWORKS)) {\n type = \"web-frontend\";\n confidence = 0.85;\n } else if (stack.languages.includes(\"python\") && !hasAny(stack.frameworks, WEB_FRAMEWORKS)) {\n if (hasAny(stack.frameworks, ML_FRAMEWORKS)) {\n type = \"ml-data\";\n confidence = 0.8;\n } else {\n type = \"cli-tool\";\n confidence = 0.6;\n }\n } else if (stack.languages.length > 0 && stack.frameworks.length === 0) {\n type = \"library\";\n confidence = 0.6;\n } else if (stack.languages.length === 0 && stack.frameworks.length === 0) {\n type = \"unknown\";\n confidence = 0.3;\n } else {\n type = \"unknown\";\n confidence = 0.3;\n }\n\n return {\n type,\n confidence,\n suggestedTemplate: TEMPLATE_MAP[type],\n suggestedProfiles: PROFILE_MAP[type],\n description: DESCRIPTION_MAP[type],\n };\n}\n\nexport function getRecommendedTemplate(type: ProjectType): string {\n return TEMPLATE_MAP[type] ?? TEMPLATE_MAP.unknown;\n}\n\nexport function getRecommendedProfiles(type: ProjectType): string[] {\n return PROFILE_MAP[type] ?? PROFILE_MAP.unknown;\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport os from \"node:os\";\n\nimport { getOrchestratorProfile, ORCHESTRATOR_PROFILES } from \"./orchestrator-profiles.js\";\n\n/**\n * Check if an orchestrator profile is installed.\n * A profile is considered installed if {profilesDir}/{profileName}/core.md exists.\n */\nexport function isProfileInstalled(profileName: string, profilesDir: string): boolean {\n return fs.existsSync(path.join(profilesDir, profileName, \"core.md\"));\n}\n\n/**\n * Install a single orchestrator profile.\n * Gets the profile from getOrchestratorProfile(), creates the directory,\n * writes core.md and optionally rules.md.\n *\n * @returns true if installed, false if profile not found\n */\nexport function installProfile(profileName: string, profilesDir: string): boolean {\n const profile = getOrchestratorProfile(profileName);\n if (!profile) return false;\n\n const profileDir = path.join(profilesDir, profileName);\n fs.mkdirSync(profileDir, { recursive: true });\n\n fs.writeFileSync(path.join(profileDir, \"core.md\"), profile.core, \"utf-8\");\n\n if (profile.rules) {\n fs.writeFileSync(path.join(profileDir, \"rules.md\"), profile.rules, \"utf-8\");\n }\n\n return true;\n}\n\n/**\n * Ensure all orchestrator profiles are installed.\n * Skips profiles that already have core.md present.\n *\n * @returns summary of which profiles were installed vs skipped\n */\nexport function ensureAllProfilesInstalled(profilesDir: string): {\n installed: string[];\n skipped: string[];\n} {\n const installed: string[] = [];\n const skipped: string[] = [];\n\n for (const profile of ORCHESTRATOR_PROFILES) {\n if (isProfileInstalled(profile.name, profilesDir)) {\n skipped.push(profile.name);\n } else {\n installProfile(profile.name, profilesDir);\n installed.push(profile.name);\n }\n }\n\n return { installed, skipped };\n}\n\n/**\n * Auto-install a profile if it's an orchestrator profile and not yet installed.\n * Call this before delegation.\n *\n * @returns true if profile is now ready (already was or just installed)\n * @returns false if it's not a known orchestrator profile\n */\nexport function ensureProfileReady(profileName: string, profilesDir: string): boolean {\n const profile = getOrchestratorProfile(profileName);\n if (!profile) return false;\n\n if (!isProfileInstalled(profileName, profilesDir)) {\n installProfile(profileName, profilesDir);\n }\n\n return true;\n}\n\n/**\n * Get the default profiles directory.\n * Respects ACORE_HOME env var, otherwise uses ~/.acore/profiles.\n */\nexport function getProfilesDir(): string {\n const acoreHome = process.env.ACORE_HOME;\n if (acoreHome) {\n return path.join(acoreHome, \"profiles\");\n }\n return path.join(os.homedir(), \".acore\", \"profiles\");\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport os from \"node:os\";\nimport pc from \"picocolors\";\nimport type { LLMClient, ToolDefinition } from \"./llm/types.js\";\nimport type { McpManager } from \"./mcp/client.js\";\nimport { delegateTask, delegateParallel, delegatePipeline, type DelegationResult } from \"./delegate.js\";\nimport { listProfiles } from \"./prompt.js\";\nimport { log } from \"./logger.js\";\n\n// --- Types ---\n\nexport interface TeamMember {\n profile: string;\n role: string;\n}\n\nexport interface Team {\n name: string;\n goal: string;\n coordinator: string; // profile name or \"default\" for main agent\n members: TeamMember[];\n workflow: \"pipeline\" | \"parallel\" | \"coordinator\";\n}\n\nexport interface TeamRunResult {\n team: string;\n task: string;\n workflow: string;\n results: DelegationResult[];\n finalOutput: string;\n success: boolean;\n}\n\n// --- Storage ---\n\nfunction getTeamsDir(): string {\n return path.join(os.homedir(), \".acore\", \"teams\");\n}\n\nfunction ensureTeamsDir(): string {\n const dir = getTeamsDir();\n if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });\n return dir;\n}\n\nfunction teamPath(name: string): string {\n const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, \"-\");\n return path.join(ensureTeamsDir(), `${slug}.json`);\n}\n\n// --- CRUD ---\n\nexport function createTeam(team: Team): void {\n const fp = teamPath(team.name);\n fs.writeFileSync(fp, JSON.stringify(team, null, 2), \"utf-8\");\n}\n\nexport function loadTeam(name: string): Team | null {\n const fp = teamPath(name);\n if (!fs.existsSync(fp)) return null;\n try {\n return JSON.parse(fs.readFileSync(fp, \"utf-8\")) as Team;\n } catch {\n return null;\n }\n}\n\nexport function listTeams(): Team[] {\n const dir = getTeamsDir();\n if (!fs.existsSync(dir)) return [];\n\n const teams: Team[] = [];\n for (const file of fs.readdirSync(dir)) {\n if (!file.endsWith(\".json\")) continue;\n try {\n const content = fs.readFileSync(path.join(dir, file), \"utf-8\");\n teams.push(JSON.parse(content) as Team);\n } catch { /* skip malformed */ }\n }\n return teams;\n}\n\nexport function deleteTeam(name: string): boolean {\n const fp = teamPath(name);\n if (!fs.existsSync(fp)) return false;\n fs.unlinkSync(fp);\n return true;\n}\n\n// --- Team Execution ---\n\n/**\n * Run a task with a team. Routes to the appropriate execution mode.\n */\nexport async function runTeam(\n team: Team,\n task: string,\n client: LLMClient,\n mcpManager: McpManager,\n tools?: ToolDefinition[],\n): Promise<TeamRunResult> {\n process.stdout.write(pc.dim(`\\n Team: ${team.name} (${team.workflow} mode)\\n`));\n process.stdout.write(pc.dim(` Members: ${team.members.map((m) => m.profile).join(\", \")}\\n\\n`));\n\n switch (team.workflow) {\n case \"pipeline\":\n return runPipeline(team, task, client, mcpManager, tools);\n case \"parallel\":\n return runParallel(team, task, client, mcpManager, tools);\n case \"coordinator\":\n return runCoordinator(team, task, client, mcpManager, tools);\n default:\n return {\n team: team.name,\n task,\n workflow: team.workflow,\n results: [],\n finalOutput: `Unknown workflow mode: ${team.workflow}`,\n success: false,\n };\n }\n}\n\n/**\n * Pipeline mode: each member works sequentially, passing output to the next.\n */\nasync function runPipeline(\n team: Team,\n task: string,\n client: LLMClient,\n mcpManager: McpManager,\n tools?: ToolDefinition[],\n): Promise<TeamRunResult> {\n const steps = team.members.map((m, i) => ({\n profile: m.profile,\n taskTemplate: i === 0\n ? `${task}\\n\\nYour role: ${m.role}`\n : `${m.role}. Here is the previous agent's work:\\n\\n{{input}}`,\n }));\n\n for (const step of steps) {\n process.stdout.write(pc.dim(` [${step.profile}: ${team.members.find((m) => m.profile === step.profile)?.role}...]\\n`));\n }\n\n const results = await delegatePipeline(steps, task, client, mcpManager, {\n tools,\n silent: true,\n });\n\n const lastResult = results[results.length - 1];\n const success = results.every((r) => r.success);\n\n return {\n team: team.name,\n task,\n workflow: \"pipeline\",\n results,\n finalOutput: lastResult?.response || \"\",\n success,\n };\n}\n\n/**\n * Parallel mode: all members work concurrently, coordinator merges results.\n */\nasync function runParallel(\n team: Team,\n task: string,\n client: LLMClient,\n mcpManager: McpManager,\n tools?: ToolDefinition[],\n): Promise<TeamRunResult> {\n // Each member gets the task with their specific role\n const tasks = team.members.map((m) => ({\n profile: m.profile,\n task: `${task}\\n\\nYour specific role: ${m.role}. Focus only on your role.`,\n }));\n\n for (const m of team.members) {\n process.stdout.write(pc.dim(` [${m.profile}: ${m.role} (parallel)...]\\n`));\n }\n\n const results = await delegateParallel(tasks, client, mcpManager, { tools });\n\n // Merge results using coordinator (or main agent)\n const mergeInput = results\n .filter((r) => r.success)\n .map((r) => `[${r.profile} — ${team.members.find((m) => m.profile === r.profile)?.role}]:\\n${r.response}`)\n .join(\"\\n\\n---\\n\\n\");\n\n process.stdout.write(pc.dim(` [merging results...]\\n`));\n\n const mergeResult = await delegateTask(\n `You are the team coordinator. Multiple agents worked on this task in parallel. Merge their outputs into a single cohesive result. Keep the best parts from each.\\n\\nOriginal task: ${task}\\n\\n${mergeInput}`,\n team.coordinator === \"default\" ? team.members[0]?.profile || \"default\" : team.coordinator,\n client,\n mcpManager,\n { tools, silent: true },\n );\n\n return {\n team: team.name,\n task,\n workflow: \"parallel\",\n results: [...results, mergeResult],\n finalOutput: mergeResult.response,\n success: results.some((r) => r.success),\n };\n}\n\n/**\n * Coordinator mode: coordinator LLM decides how to route tasks to members.\n * Most flexible — coordinator analyzes the task and creates its own execution plan.\n */\nasync function runCoordinator(\n team: Team,\n task: string,\n client: LLMClient,\n mcpManager: McpManager,\n tools?: ToolDefinition[],\n): Promise<TeamRunResult> {\n const memberDescriptions = team.members\n .map((m) => `- ${m.profile}: ${m.role}`)\n .join(\"\\n\");\n\n // Step 1: Coordinator plans the work\n process.stdout.write(pc.dim(` [coordinator planning...]\\n`));\n\n const planResult = await delegateTask(\n `You are the coordinator of a team. Your job is to break down this task and decide which team members should handle each part.\n\nTeam members:\n${memberDescriptions}\n\nTask: ${task}\n\nRespond with a JSON array of assignments:\n[{\"profile\": \"member-name\", \"subtask\": \"what they should do\"}]\n\nOnly use the JSON array, no other text.`,\n team.coordinator === \"default\" ? team.members[0]?.profile || \"default\" : team.coordinator,\n client,\n mcpManager,\n { tools: undefined, silent: true, maxTurns: 0 },\n );\n\n if (!planResult.success) {\n return {\n team: team.name,\n task,\n workflow: \"coordinator\",\n results: [planResult],\n finalOutput: `Coordinator failed to plan: ${planResult.error}`,\n success: false,\n };\n }\n\n // Step 2: Parse assignments\n let assignments: Array<{ profile: string; subtask: string }>;\n try {\n let cleaned = planResult.response.trim();\n const codeBlockMatch = cleaned.match(/```(?:json)?\\s*\\n?([\\s\\S]*?)\\n?```/);\n if (codeBlockMatch) cleaned = codeBlockMatch[1].trim();\n assignments = JSON.parse(cleaned);\n } catch {\n // Fallback: run all members in parallel with the full task\n assignments = team.members.map((m) => ({ profile: m.profile, subtask: `${m.role}: ${task}` }));\n }\n\n // Step 3: Execute assignments in parallel\n for (const a of assignments) {\n process.stdout.write(pc.dim(` [${a.profile}: ${a.subtask.slice(0, 60)}...]\\n`));\n }\n\n const results = await delegateParallel(\n assignments.map((a) => ({ profile: a.profile, task: a.subtask })),\n client,\n mcpManager,\n { tools },\n );\n\n // Step 4: Coordinator merges\n const mergeInput = results\n .filter((r) => r.success)\n .map((r, i) => `[${assignments[i]?.profile} — ${assignments[i]?.subtask}]:\\n${r.response}`)\n .join(\"\\n\\n---\\n\\n\");\n\n process.stdout.write(pc.dim(` [coordinator merging...]\\n`));\n\n const mergeResult = await delegateTask(\n `You are the team coordinator. Your team members completed their assigned work. Combine their outputs into a single cohesive, polished result.\\n\\nOriginal task: ${task}\\n\\n${mergeInput}`,\n team.coordinator === \"default\" ? team.members[0]?.profile || \"default\" : team.coordinator,\n client,\n mcpManager,\n { tools, silent: true },\n );\n\n return {\n team: team.name,\n task,\n workflow: \"coordinator\",\n results: [...results, mergeResult],\n finalOutput: mergeResult.response,\n success: results.some((r) => r.success),\n };\n}\n\n// --- Formatting ---\n\nexport function formatTeam(team: Team): string {\n const lines: string[] = [];\n lines.push(`Team: ${pc.bold(team.name)}`);\n lines.push(`Goal: ${team.goal}`);\n lines.push(`Mode: ${team.workflow}`);\n lines.push(`Coordinator: ${team.coordinator}`);\n lines.push(\"\");\n lines.push(\"Members:\");\n for (const m of team.members) {\n lines.push(` ${pc.bold(m.profile)} — ${m.role}`);\n }\n return lines.join(\"\\n\");\n}\n\nexport function formatTeamResult(result: TeamRunResult): string {\n const lines: string[] = [];\n lines.push(`\\n${pc.bold(`Team: ${result.team}`)} (${result.workflow})`);\n\n for (const r of result.results) {\n const status = r.success ? pc.green(\"✓\") : pc.red(\"✗\");\n const tools = r.toolsUsed.length > 0 ? pc.dim(` (${r.toolsUsed.join(\", \")})`) : \"\";\n lines.push(` ${status} ${pc.bold(r.profile)}${tools}`);\n }\n\n lines.push(\"\");\n lines.push(result.finalOutput);\n\n return lines.join(\"\\n\");\n}\n\n// --- Built-in Team Templates ---\n\nexport const BUILT_IN_TEAMS: Team[] = [\n {\n name: \"content-team\",\n goal: \"Create and publish high-quality content\",\n coordinator: \"default\",\n members: [\n { profile: \"writer\", role: \"Draft compelling content with engaging narrative\" },\n { profile: \"researcher\", role: \"Fact-check claims and add citations\" },\n ],\n workflow: \"pipeline\",\n },\n {\n name: \"dev-team\",\n goal: \"Build and review code with quality assurance\",\n coordinator: \"default\",\n members: [\n { profile: \"coder\", role: \"Write clean, tested implementation code\" },\n { profile: \"researcher\", role: \"Review for security, performance, and best practices\" },\n ],\n workflow: \"pipeline\",\n },\n {\n name: \"research-team\",\n goal: \"Deep research with multiple perspectives\",\n coordinator: \"default\",\n members: [\n { profile: \"researcher\", role: \"Research the topic thoroughly with citations\" },\n { profile: \"writer\", role: \"Synthesize findings into clear, readable format\" },\n ],\n workflow: \"pipeline\",\n },\n];\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport os from \"node:os\";\nimport { log } from \"./logger.js\";\n\n// --- Types ---\n\nexport interface PlanStep {\n text: string;\n done: boolean;\n}\n\nexport interface Plan {\n name: string;\n goal: string;\n steps: PlanStep[];\n createdAt: string;\n updatedAt: string;\n active: boolean;\n}\n\n// --- Paths ---\n\nfunction getPlansDir(): string {\n // Project-local plans if .acore exists, otherwise global\n const localDir = path.join(process.cwd(), \".acore\", \"plans\");\n const localAcore = path.join(process.cwd(), \".acore\");\n if (fs.existsSync(localAcore)) return localDir;\n return path.join(os.homedir(), \".acore\", \"plans\");\n}\n\nfunction ensurePlansDir(): string {\n const dir = getPlansDir();\n if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });\n return dir;\n}\n\nfunction planPath(name: string): string {\n const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-|-$/g, \"\");\n return path.join(ensurePlansDir(), `${slug}.md`);\n}\n\n// --- Serialization ---\n\nfunction serializePlan(plan: Plan): string {\n const lines: string[] = [];\n lines.push(`# ${plan.name}`);\n lines.push(\"\");\n lines.push(`**Goal:** ${plan.goal}`);\n lines.push(`**Created:** ${plan.createdAt}`);\n lines.push(`**Updated:** ${plan.updatedAt}`);\n lines.push(`**Active:** ${plan.active}`);\n lines.push(\"\");\n lines.push(\"## Steps\");\n lines.push(\"\");\n for (const step of plan.steps) {\n lines.push(`- [${step.done ? \"x\" : \" \"}] ${step.text}`);\n }\n lines.push(\"\");\n return lines.join(\"\\n\");\n}\n\nfunction parsePlan(content: string, filePath: string): Plan | null {\n try {\n const nameMatch = content.match(/^# (.+)/m);\n const goalMatch = content.match(/\\*\\*Goal:\\*\\*\\s*(.+)/);\n const createdMatch = content.match(/\\*\\*Created:\\*\\*\\s*(.+)/);\n const updatedMatch = content.match(/\\*\\*Updated:\\*\\*\\s*(.+)/);\n const activeMatch = content.match(/\\*\\*Active:\\*\\*\\s*(.+)/);\n\n const name = nameMatch?.[1]?.trim() || path.basename(filePath, \".md\");\n const goal = goalMatch?.[1]?.trim() || \"\";\n const createdAt = createdMatch?.[1]?.trim() || \"\";\n const updatedAt = updatedMatch?.[1]?.trim() || \"\";\n const active = activeMatch?.[1]?.trim() === \"true\";\n\n // Parse checkbox steps\n const steps: PlanStep[] = [];\n const stepMatches = content.matchAll(/- \\[([ x])\\] (.+)/g);\n for (const match of stepMatches) {\n steps.push({\n done: match[1] === \"x\",\n text: match[2].trim(),\n });\n }\n\n return { name, goal, steps, createdAt, updatedAt, active };\n } catch (err) {\n log.debug(\"plans\", \"Failed to parse plan: \" + filePath, err);\n return null;\n }\n}\n\n// --- CRUD ---\n\nexport function createPlan(name: string, goal: string, steps: string[]): Plan {\n const now = new Date().toISOString().split(\"T\")[0];\n const plan: Plan = {\n name,\n goal,\n steps: steps.map((text) => ({ text, done: false })),\n createdAt: now,\n updatedAt: now,\n active: true,\n };\n\n // Deactivate any currently active plan\n const existing = listPlans();\n for (const p of existing) {\n if (p.active) {\n p.active = false;\n p.updatedAt = now;\n savePlan(p);\n }\n }\n\n savePlan(plan);\n return plan;\n}\n\nexport function savePlan(plan: Plan): void {\n const fp = planPath(plan.name);\n fs.writeFileSync(fp, serializePlan(plan), \"utf-8\");\n}\n\nexport function loadPlan(name: string): Plan | null {\n const fp = planPath(name);\n if (!fs.existsSync(fp)) return null;\n const content = fs.readFileSync(fp, \"utf-8\");\n return parsePlan(content, fp);\n}\n\nexport function listPlans(): Plan[] {\n const dir = getPlansDir();\n if (!fs.existsSync(dir)) return [];\n\n const plans: Plan[] = [];\n for (const file of fs.readdirSync(dir)) {\n if (!file.endsWith(\".md\")) continue;\n const fp = path.join(dir, file);\n const content = fs.readFileSync(fp, \"utf-8\");\n const plan = parsePlan(content, fp);\n if (plan) plans.push(plan);\n }\n\n return plans;\n}\n\nexport function getActivePlan(): Plan | null {\n const plans = listPlans();\n return plans.find((p) => p.active) || null;\n}\n\n// --- Operations ---\n\nexport function markStepDone(plan: Plan, stepIndex: number): boolean {\n if (stepIndex < 0 || stepIndex >= plan.steps.length) return false;\n plan.steps[stepIndex].done = true;\n plan.updatedAt = new Date().toISOString().split(\"T\")[0];\n savePlan(plan);\n return true;\n}\n\nexport function markStepUndone(plan: Plan, stepIndex: number): boolean {\n if (stepIndex < 0 || stepIndex >= plan.steps.length) return false;\n plan.steps[stepIndex].done = false;\n plan.updatedAt = new Date().toISOString().split(\"T\")[0];\n savePlan(plan);\n return true;\n}\n\nexport function setActivePlan(name: string): Plan | null {\n const now = new Date().toISOString().split(\"T\")[0];\n\n // Deactivate all\n const plans = listPlans();\n for (const p of plans) {\n if (p.active) {\n p.active = false;\n p.updatedAt = now;\n savePlan(p);\n }\n }\n\n // Activate target\n const target = loadPlan(name);\n if (!target) return null;\n target.active = true;\n target.updatedAt = now;\n savePlan(target);\n return target;\n}\n\n// --- Formatting ---\n\nexport function formatPlan(plan: Plan): string {\n const total = plan.steps.length;\n const done = plan.steps.filter((s) => s.done).length;\n const pct = total > 0 ? Math.round((done / total) * 100) : 0;\n const bar = progressBar(pct);\n\n const lines: string[] = [];\n lines.push(`Plan: ${plan.name} ${plan.active ? \"(active)\" : \"(inactive)\"}`);\n lines.push(`Goal: ${plan.goal}`);\n lines.push(`Progress: ${bar} ${done}/${total} (${pct}%)`);\n lines.push(\"\");\n\n for (let i = 0; i < plan.steps.length; i++) {\n const step = plan.steps[i];\n const marker = step.done ? \"✓\" : \" \";\n const num = String(i + 1).padStart(2, \" \");\n lines.push(` ${num}. [${marker}] ${step.text}`);\n }\n\n if (done === total && total > 0) {\n lines.push(\"\\n All steps complete!\");\n } else {\n const next = plan.steps.findIndex((s) => !s.done);\n if (next >= 0) {\n lines.push(`\\n Next: Step ${next + 1} — ${plan.steps[next].text}`);\n }\n }\n\n return lines.join(\"\\n\");\n}\n\nexport function formatPlanForPrompt(plan: Plan): string {\n const total = plan.steps.length;\n const done = plan.steps.filter((s) => s.done).length;\n\n const lines: string[] = [];\n lines.push(`<active-plan name=\"${plan.name}\" progress=\"${done}/${total}\">`);\n lines.push(`Goal: ${plan.goal}`);\n lines.push(\"\");\n\n for (let i = 0; i < plan.steps.length; i++) {\n const step = plan.steps[i];\n lines.push(`- [${step.done ? \"x\" : \" \"}] Step ${i + 1}: ${step.text}`);\n }\n\n const next = plan.steps.findIndex((s) => !s.done);\n if (next >= 0) {\n lines.push(\"\");\n lines.push(`Current focus: Step ${next + 1} — ${plan.steps[next].text}`);\n lines.push(\"After completing the current step, remind the user to mark it done with /plan done and suggest committing their work.\");\n }\n\n lines.push(\"</active-plan>\");\n return lines.join(\"\\n\");\n}\n\nfunction progressBar(pct: number): string {\n const filled = Math.round(pct / 5);\n const empty = 20 - filled;\n return `[${\"█\".repeat(filled)}${\"░\".repeat(empty)}]`;\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport os from \"node:os\";\nimport pc from \"picocolors\";\nimport type { McpManager } from \"./mcp/client.js\";\nimport { log } from \"./logger.js\";\n\nexport interface BackgroundTask {\n id: string;\n toolName: string;\n toolUseId: string;\n startedAt: number;\n promise: Promise<string>;\n result?: string;\n error?: string;\n done: boolean;\n}\n\n// Tools that are likely long-running and benefit from background execution\nconst BACKGROUND_ELIGIBLE = new Set([\n \"run_tests\", \"npm_test\", \"build\", \"npm_build\",\n \"file_search\", \"code_search\", \"grep_search\",\n \"git_clone\", \"docker_build\", \"docker_run\",\n]);\n\n// Tools that should NEVER run in background (need immediate results for tool loop)\nconst NEVER_BACKGROUND = new Set([\n \"memory_recall\", \"memory_store\", \"memory_log\", \"memory_context\", \"memory_detail\",\n \"identity_read\", \"identity_summary\", \"identity_update_session\", \"identity_update_dynamics\",\n \"rules_check\", \"rules_list\", \"workflow_list\", \"workflow_get\",\n \"skill_list\", \"skill_search\", \"eval_status\", \"eval_log\",\n \"reminder_check\", \"reminder_set\",\n \"file_read\", \"doc_convert\", \"file_list\",\n \"avatar_prompt\",\n]);\n\n// ── Persistent task log ────────────────────────────────────────────────────────\n\nexport interface TaskLogEntry {\n id: string;\n toolName: string;\n startedAt: number;\n completedAt?: number;\n status: \"running\" | \"completed\" | \"failed\" | \"interrupted\";\n resultPreview?: string;\n error?: string;\n}\n\nconst TASK_LOG_DIR = path.join(os.homedir(), \".aman-agent\");\nconst TASK_LOG_FILE = path.join(TASK_LOG_DIR, \"bg-tasks.json\");\nconst MAX_LOG_ENTRIES = 50;\n\nexport function loadTaskLog(): TaskLogEntry[] {\n try {\n if (!fs.existsSync(TASK_LOG_FILE)) return [];\n const raw = fs.readFileSync(TASK_LOG_FILE, \"utf-8\");\n return JSON.parse(raw) as TaskLogEntry[];\n } catch {\n return [];\n }\n}\n\nexport function saveTaskLog(entries: TaskLogEntry[]): void {\n try {\n if (!fs.existsSync(TASK_LOG_DIR)) fs.mkdirSync(TASK_LOG_DIR, { recursive: true });\n // Keep only recent entries\n const trimmed = entries.slice(-MAX_LOG_ENTRIES);\n fs.writeFileSync(TASK_LOG_FILE, JSON.stringify(trimmed, null, 2));\n } catch (err) {\n log.debug(\"background\", \"Failed to save task log\", err);\n }\n}\n\nfunction logTaskStart(task: BackgroundTask): void {\n const entries = loadTaskLog();\n // Mark any stale \"running\" entries as interrupted (from prior crash)\n for (const e of entries) {\n if (e.status === \"running\") e.status = \"interrupted\";\n }\n entries.push({\n id: task.id,\n toolName: task.toolName,\n startedAt: task.startedAt,\n status: \"running\",\n });\n saveTaskLog(entries);\n}\n\nfunction logTaskComplete(task: BackgroundTask): void {\n const entries = loadTaskLog();\n const entry = entries.find((e) => e.id === task.id);\n if (entry) {\n entry.completedAt = Date.now();\n entry.status = task.error ? \"failed\" : \"completed\";\n entry.resultPreview = (task.result || \"\").slice(0, 200);\n entry.error = task.error;\n }\n saveTaskLog(entries);\n}\nexport function shouldRunInBackground(toolName: string): boolean {\n if (NEVER_BACKGROUND.has(toolName)) return false;\n if (BACKGROUND_ELIGIBLE.has(toolName)) return true;\n return false;\n}\n\n/**\n * Background task manager.\n * Runs tool calls concurrently and reports results when ready.\n */\nexport class BackgroundTaskManager {\n private tasks: Map<string, BackgroundTask> = new Map();\n private taskCounter = 0;\n\n /**\n * Launch a tool call in the background.\n */\n launch(\n toolName: string,\n toolUseId: string,\n mcpManager: McpManager,\n toolInput: Record<string, unknown>,\n ): BackgroundTask {\n const id = `bg-${++this.taskCounter}`;\n const task: BackgroundTask = {\n id,\n toolName,\n toolUseId,\n startedAt: Date.now(),\n done: false,\n promise: mcpManager.callTool(toolName, toolInput).then(\n (result) => {\n task.result = result;\n task.done = true;\n logTaskComplete(task);\n return result;\n },\n (error) => {\n task.error = error instanceof Error ? error.message : String(error);\n task.done = true;\n logTaskComplete(task);\n return `Error: ${task.error}`;\n },\n ),\n };\n\n this.tasks.set(id, task);\n logTaskStart(task);\n process.stdout.write(pc.dim(` [${toolName} running in background (${id})...]\\n`));\n return task;\n }\n\n /**\n * Check for completed background tasks and return their results.\n */\n collectCompleted(): BackgroundTask[] {\n const completed: BackgroundTask[] = [];\n for (const [id, task] of this.tasks) {\n if (task.done) {\n completed.push(task);\n this.tasks.delete(id);\n }\n }\n return completed;\n }\n\n /**\n * Display completed background task results to the user.\n */\n displayCompleted(): string[] {\n const completed = this.collectCompleted();\n const outputs: string[] = [];\n\n for (const task of completed) {\n const elapsed = ((Date.now() - task.startedAt) / 1000).toFixed(1);\n if (task.error) {\n process.stdout.write(pc.yellow(`\\n [${task.id}] ${task.toolName} failed after ${elapsed}s: ${task.error}\\n`));\n outputs.push(`[Background task ${task.toolName} failed: ${task.error}]`);\n } else {\n process.stdout.write(pc.green(`\\n [${task.id}] ${task.toolName} completed in ${elapsed}s\\n`));\n const preview = (task.result || \"\").slice(0, 200);\n if (preview) {\n process.stdout.write(pc.dim(` ${preview}${(task.result || \"\").length > 200 ? \"...\" : \"\"}\\n`));\n }\n outputs.push(`[Background task ${task.toolName} completed: ${task.result}]`);\n }\n }\n\n return outputs;\n }\n\n /**\n * Wait for all pending background tasks to complete.\n */\n async waitAll(): Promise<void> {\n const pending = [...this.tasks.values()].filter((t) => !t.done);\n if (pending.length === 0) return;\n\n process.stdout.write(pc.dim(`\\n Waiting for ${pending.length} background task(s)...\\n`));\n await Promise.allSettled(pending.map((t) => t.promise));\n }\n\n /**\n * Number of currently running tasks.\n */\n get pendingCount(): number {\n return [...this.tasks.values()].filter((t) => !t.done).length;\n }\n\n /**\n * Check if any tasks have completed (non-blocking).\n */\n get hasCompleted(): boolean {\n return [...this.tasks.values()].some((t) => t.done);\n }\n}\n","import type { Message, LLMClient } from \"./llm/types.js\";\nimport { log } from \"./logger.js\";\n\n// Rough token estimation: ~1.3 tokens per word\nfunction estimateMessageTokens(msg: Message): number {\n if (typeof msg.content === \"string\") {\n return Math.round(msg.content.split(/\\s+/).filter(Boolean).length * 1.3);\n }\n // Content blocks — estimate from stringified content\n let text = \"\";\n let imageTokens = 0;\n for (const block of msg.content) {\n if (block.type === \"text\") text += block.text;\n else if (block.type === \"tool_result\") text += block.content;\n else if (block.type === \"tool_use\") text += JSON.stringify(block.input);\n else if (block.type === \"image\") imageTokens += 1600;\n }\n return Math.round(text.split(/\\s+/).filter(Boolean).length * 1.3) + imageTokens;\n}\n\nfunction estimateTotalTokens(messages: Message[]): number {\n let total = 0;\n for (const msg of messages) {\n total += estimateMessageTokens(msg);\n }\n return total;\n}\n\n// Maximum conversation tokens before trimming (leave room for system prompt + response)\nconst MAX_CONVERSATION_TOKENS = 80_000;\n// How many recent messages to always keep\nconst KEEP_RECENT = 10;\n// How many initial messages to always keep (session context injection)\nconst KEEP_INITIAL = 2;\n\n/**\n * Trims conversation history when it gets too long.\n * Keeps initial context messages and recent messages.\n * Replaces middle messages with a summary.\n * Mutates the messages array in place.\n */\nexport async function trimConversation(\n messages: Message[],\n client: LLMClient,\n): Promise<void> {\n const totalTokens = estimateTotalTokens(messages);\n\n if (totalTokens < MAX_CONVERSATION_TOKENS || messages.length <= KEEP_INITIAL + KEEP_RECENT) {\n return;\n }\n\n const initial = messages.slice(0, KEEP_INITIAL);\n const recent = messages.slice(-KEEP_RECENT);\n const middle = messages.slice(KEEP_INITIAL, messages.length - KEEP_RECENT);\n\n const middleText = middle\n .filter((m) => typeof m.content === \"string\" && m.content.length > 0)\n .map((m) => `[${m.role}]: ${(m.content as string).slice(0, 500)}`)\n .slice(0, 30)\n .join(\"\\n\");\n\n let summaryText: string;\n\n try {\n const summaryPrompt = \"Summarize the following conversation messages in 3-5 bullet points. Preserve: decisions made, user preferences expressed, action items, and key facts discussed. Be concise.\\n\\n\" + middleText;\n\n let fullText = \"\";\n await client.chat(\n \"You are a concise summarizer. Return only bullet points, no preamble.\",\n [{ role: \"user\", content: summaryPrompt }],\n (chunk) => {\n if (chunk.type === \"text\" && chunk.text) fullText += chunk.text;\n },\n );\n\n summaryText = `<conversation-summary>\\nSummary of ${middle.length} earlier messages:\\n\\n${fullText}\\n</conversation-summary>`;\n log.debug(\"context\", `Summarized ${middle.length} messages via LLM`);\n } catch (err) {\n log.warn(\"context\", \"LLM summarization failed, using fallback\", err);\n const summaryParts: string[] = [];\n for (const msg of middle) {\n if (typeof msg.content === \"string\" && msg.content.length > 0) {\n const preview = msg.content.slice(0, 150);\n summaryParts.push(`[${msg.role}]: ${preview}${msg.content.length > 150 ? \"...\" : \"\"}`);\n }\n }\n summaryText = `<conversation-summary>\\nSummary of ${middle.length} earlier messages:\\n\\n${summaryParts.slice(0, 20).join(\"\\n\")}\\n</conversation-summary>`;\n }\n\n messages.length = 0;\n messages.push(...initial);\n messages.push({ role: \"user\", content: summaryText });\n messages.push({ role: \"assistant\", content: \"I have the context from our earlier conversation. Let's continue.\" });\n messages.push(...recent);\n}\n","import type { LLMClient } from \"./llm/types.js\";\nimport { log } from \"./logger.js\";\nimport { matchPatternToSkill, enrichSkill } from \"./skill-engine.js\";\nimport { memoryRecall, memoryStore, getDb } from \"./memory.js\";\nimport { reflect, isReflectionDue, autoRelateMemory } from \"@aman_asmuei/amem-core\";\n\nexport interface ExtractionCandidate {\n content: string;\n type: \"preference\" | \"fact\" | \"pattern\" | \"decision\" | \"correction\" | \"topology\";\n tags: string[];\n confidence: number;\n scope: string;\n}\n\nconst VALID_TYPES = new Set([\"preference\", \"fact\", \"pattern\", \"topology\", \"decision\", \"correction\"]);\nconst MIN_RESPONSE_LENGTH = 50;\nconst MIN_TURNS_BETWEEN_EMPTY = 3;\n\nconst EXTRACTION_PROMPT = `Analyze this conversation turn. Extract any information worth remembering long-term, and assess the user's emotional tone.\n\nReturn a JSON object with two fields:\n{\n \"memories\": [{\n \"content\": \"what to remember — be specific and self-contained\",\n \"type\": \"preference|fact|pattern|decision|correction|topology\",\n \"tags\": [\"relevant\", \"tags\"],\n \"confidence\": 0.0-1.0,\n \"scope\": \"global\"\n }],\n \"sentiment\": {\n \"tone\": \"neutral|positive|frustrated|confused|excited|fatigued\",\n \"confidence\": 0.0-1.0,\n \"context\": \"brief reason for sentiment read\"\n }\n}\n\nType guide:\n- \"preference\" = user likes/dislikes/preferences\n- \"fact\" = objective information about systems, people, projects\n- \"pattern\" = recurring behavior, coding style, approach\n- \"topology\" = how systems/components connect to each other\n- \"decision\" = explicit choice between alternatives\n- \"correction\" = user correcting a prior wrong assumption\n\nRules:\n- Only extract genuinely useful LONG-TERM information\n- Skip ephemeral things (\"user asked about X\" is NOT useful)\n- Be conservative — 90% of turns produce nothing worth storing\n- Sentiment should reflect the USER's tone, not the assistant's\n- Return ONLY the JSON object, no other text`;\n\nexport function shouldExtract(\n assistantResponse: string,\n turnsSinceLastExtraction: number,\n lastExtractionCount: number,\n): boolean {\n // Always skip very short responses regardless of previous extraction results\n if (assistantResponse.length < MIN_RESPONSE_LENGTH) return false;\n // If previous turn found memories, extract again but respect min turns spacing\n if (lastExtractionCount > 0 && turnsSinceLastExtraction >= 1) return true;\n // Otherwise, wait for MIN_TURNS_BETWEEN_EMPTY turns between empty extractions\n if (turnsSinceLastExtraction < MIN_TURNS_BETWEEN_EMPTY) return false;\n return true;\n}\n\nexport interface ExtractionResult {\n memories: ExtractionCandidate[];\n sentiment?: LlmSentiment;\n}\n\nexport function parseExtractionResult(raw: string): ExtractionResult {\n try {\n let cleaned = raw.trim();\n const codeBlockMatch = cleaned.match(/```(?:json)?\\s*\\n?([\\s\\S]*?)\\n?```/);\n if (codeBlockMatch) {\n cleaned = codeBlockMatch[1].trim();\n }\n\n const parsed = JSON.parse(cleaned);\n\n // New format: { memories: [...], sentiment: {...} }\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed) && \"memories\" in parsed) {\n const memories = Array.isArray(parsed.memories)\n ? (parsed.memories as Record<string, unknown>[]).filter(\n (item) =>\n typeof item.content === \"string\" &&\n (item.content as string).length > 0 &&\n typeof item.type === \"string\" &&\n VALID_TYPES.has(item.type as string),\n ) as unknown as ExtractionCandidate[]\n : [];\n\n let sentiment: LlmSentiment | undefined;\n if (parsed.sentiment && typeof parsed.sentiment === \"object\") {\n const s = parsed.sentiment as Record<string, unknown>;\n if (typeof s.tone === \"string\" && typeof s.confidence === \"number\") {\n sentiment = {\n tone: s.tone,\n confidence: s.confidence,\n context: typeof s.context === \"string\" ? s.context : undefined,\n };\n }\n }\n\n return { memories, sentiment };\n }\n\n // Legacy format: plain array\n if (Array.isArray(parsed)) {\n const memories = parsed.filter(\n (item: Record<string, unknown>) =>\n typeof item.content === \"string\" &&\n item.content.length > 0 &&\n typeof item.type === \"string\" &&\n VALID_TYPES.has(item.type),\n ) as ExtractionCandidate[];\n return { memories };\n }\n\n return { memories: [] };\n } catch {\n return { memories: [] };\n }\n}\n\nexport interface LlmSentiment {\n tone: string;\n confidence: number;\n context?: string;\n}\n\nexport interface ExtractorState {\n turnsSinceLastExtraction: number;\n lastExtractionCount: number;\n lastLlmSentiment?: LlmSentiment;\n}\n\nexport async function extractMemories(\n userMessage: string,\n assistantResponse: string,\n client: LLMClient,\n state: ExtractorState,\n): Promise<number> {\n if (!shouldExtract(assistantResponse, state.turnsSinceLastExtraction, state.lastExtractionCount)) {\n state.turnsSinceLastExtraction++;\n return 0;\n }\n\n try {\n const conversationTurn = `User: ${userMessage.slice(0, 2000)}\\n\\nAssistant: ${assistantResponse.slice(0, 2000)}`;\n\n let fullText = \"\";\n await client.chat(\n EXTRACTION_PROMPT,\n [{ role: \"user\", content: conversationTurn }],\n (chunk) => {\n if (chunk.type === \"text\" && chunk.text) fullText += chunk.text;\n },\n );\n\n const result = parseExtractionResult(fullText);\n state.turnsSinceLastExtraction = 0;\n state.lastExtractionCount = result.memories.length;\n\n // Store LLM sentiment on state for personality system to read\n if (result.sentiment) {\n state.lastLlmSentiment = result.sentiment;\n log.debug(\"extractor\", `LLM sentiment: ${result.sentiment.tone} (${result.sentiment.confidence})`);\n }\n\n if (result.memories.length === 0) return 0;\n\n let stored = 0;\n\n for (const candidate of result.memories) {\n // Dedup check\n try {\n const existing = await memoryRecall(candidate.content, { limit: 1 });\n if (existing.total > 0 && existing.memories.length > 0) {\n const topScore = (existing.memories[0] as { score?: number })?.score;\n if (topScore && topScore > 0.85) {\n log.debug(\"extractor\", \"Skipping duplicate: \" + candidate.content);\n continue;\n }\n }\n } catch { /* Dedup failed, proceed */ }\n\n // Store\n try {\n const storeResult = await memoryStore({\n content: candidate.content,\n type: candidate.type,\n tags: candidate.tags,\n confidence: candidate.confidence,\n source: \"auto-extraction\",\n scope: candidate.scope,\n });\n if (storeResult.action !== \"private\") {\n stored++;\n log.debug(\"extractor\", \"Stored \" + candidate.type + \": \" + candidate.content);\n // Auto-relate: build knowledge graph edges to similar memories\n try {\n autoRelateMemory(getDb(), storeResult.id);\n } catch {\n // Best-effort — never block extraction\n }\n // Self-improving skills: enrich skills with learned patterns\n if (candidate.type === \"pattern\" || candidate.type === \"preference\") {\n const skillMatch = matchPatternToSkill(candidate.content, candidate.tags);\n if (skillMatch) {\n enrichSkill(skillMatch, candidate.content);\n }\n }\n }\n } catch (err) {\n log.warn(\"extractor\", \"Failed to store: \" + candidate.content, err);\n }\n }\n\n // Post-extraction: trigger reflection if enough memories have accumulated\n if (stored > 0 && isReflectionDue(getDb()).due) {\n try {\n reflect(getDb());\n } catch {\n // Reflection is best-effort — suppress errors so they never block extraction\n }\n }\n\n return stored;\n } catch (err) {\n log.debug(\"extractor\", \"extraction failed\", err);\n state.turnsSinceLastExtraction = 0;\n state.lastExtractionCount = 0;\n return 0;\n }\n}\n","import fs from \"node:fs\";\nimport fsp from \"node:fs/promises\";\nimport path from \"node:path\";\nimport os from \"node:os\";\nimport type { McpManager } from \"./mcp/client.js\";\nimport { log } from \"./logger.js\";\nimport { extractSkillsWithMarkers } from \"./crystallization.js\";\n\n// --- Skill Keyword Map for Auto-Triggering ---\n\nconst SKILL_TRIGGERS: Record<string, string[]> = {\n testing: [\"test\", \"spec\", \"coverage\", \"tdd\", \"jest\", \"vitest\", \"mocha\", \"assert\", \"mock\", \"stub\", \"fixture\", \"e2e\", \"integration test\", \"unit test\"],\n \"api-design\": [\"api\", \"endpoint\", \"rest\", \"graphql\", \"route\", \"controller\", \"middleware\", \"http\", \"request\", \"response\", \"status code\", \"pagination\"],\n security: [\"security\", \"auth\", \"csrf\", \"xss\", \"injection\", \"cors\", \"jwt\", \"token\", \"oauth\", \"password\", \"hash\", \"encrypt\", \"vulnerability\", \"owasp\", \"sanitize\"],\n performance: [\"performance\", \"slow\", \"latency\", \"cache\", \"optimize\", \"profil\", \"bundle size\", \"lazy load\", \"memory leak\", \"benchmark\", \"bottleneck\"],\n \"code-review\": [\"review\", \"pr review\", \"pull request\", \"code quality\", \"clean code\", \"best practice\"],\n documentation: [\"document\", \"readme\", \"jsdoc\", \"tsdoc\", \"changelog\", \"adr\", \"comment\"],\n \"git-workflow\": [\"git\", \"branch\", \"merge\", \"rebase\", \"cherry-pick\", \"bisect\", \"stash\", \"commit message\", \"pr\", \"pull request\"],\n debugging: [\"debug\", \"breakpoint\", \"stack trace\", \"error\", \"exception\", \"crash\", \"bug\", \"issue\", \"unexpected\", \"reproduce\"],\n refactoring: [\"refactor\", \"extract\", \"rename\", \"move\", \"split\", \"consolidate\", \"dry\", \"code smell\", \"technical debt\", \"legacy\"],\n database: [\"database\", \"schema\", \"migration\", \"index\", \"query\", \"sql\", \"postgres\", \"mysql\", \"sqlite\", \"mongo\", \"orm\", \"prisma\", \"drizzle\"],\n typescript: [\"typescript\", \"type\", \"interface\", \"generic\", \"infer\", \"utility type\", \"zod\", \"discriminated union\", \"type guard\", \"as const\"],\n accessibility: [\"accessibility\", \"a11y\", \"aria\", \"screen reader\", \"wcag\", \"semantic html\", \"tab order\", \"focus\", \"contrast\"],\n};\n\n// --- Runtime Triggers (crystallized skills) ---\n\n/**\n * Load runtime trigger keywords from crystallized skills in ~/.askill/skills.md.\n * These supplement the hardcoded SKILL_TRIGGERS map without modifying it.\n *\n * Returns a Map<skillName, triggers[]>. Returns empty map if file is missing or\n * unreadable — never throws.\n */\nexport async function loadRuntimeTriggers(\n skillsMdPath: string,\n): Promise<Map<string, string[]>> {\n try {\n const content = await fsp.readFile(skillsMdPath, \"utf-8\");\n const skills = extractSkillsWithMarkers(content);\n const result = new Map<string, string[]>();\n for (const [name, marker] of skills) {\n result.set(name, marker.triggers);\n }\n return result;\n } catch (err) {\n log.debug(\"skill-engine\", \"loadRuntimeTriggers failed\", err);\n return new Map();\n }\n}\n\n// --- Skill Level Tracking ---\n\nconst LEVEL_FILE = path.join(os.homedir(), \".aman-agent\", \"skill-levels.json\");\n\ninterface SkillLevel {\n name: string;\n activations: number;\n lastUsed: string;\n userPatterns: string[]; // user-specific patterns learned\n}\n\nfunction loadSkillLevels(): Record<string, SkillLevel> {\n try {\n if (fs.existsSync(LEVEL_FILE)) {\n return JSON.parse(fs.readFileSync(LEVEL_FILE, \"utf-8\")) as Record<string, SkillLevel>;\n }\n } catch { /* ignore */ }\n return {};\n}\n\nfunction saveSkillLevels(levels: Record<string, SkillLevel>): void {\n const dir = path.dirname(LEVEL_FILE);\n if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });\n fs.writeFileSync(LEVEL_FILE, JSON.stringify(levels, null, 2), \"utf-8\");\n}\n\n/**\n * Compute skill level from activation count.\n * Lv.1 = beginner guidance, Lv.5 = proactive expert suggestions\n */\nexport function computeLevel(activations: number): { level: number; label: string } {\n if (activations >= 50) return { level: 5, label: \"Expert\" };\n if (activations >= 25) return { level: 4, label: \"Advanced\" };\n if (activations >= 10) return { level: 3, label: \"Proficient\" };\n if (activations >= 3) return { level: 2, label: \"Familiar\" };\n return { level: 1, label: \"Learning\" };\n}\n\n/**\n * Record a skill activation and return updated level.\n */\nexport function recordActivation(skillName: string): { level: number; label: string } {\n const levels = loadSkillLevels();\n if (!levels[skillName]) {\n levels[skillName] = { name: skillName, activations: 0, lastUsed: \"\", userPatterns: [] };\n }\n levels[skillName].activations++;\n levels[skillName].lastUsed = new Date().toISOString().split(\"T\")[0];\n saveSkillLevels(levels);\n return computeLevel(levels[skillName].activations);\n}\n\n/**\n * Get current level for a skill.\n */\nexport function getSkillLevel(skillName: string): { level: number; label: string; activations: number } {\n const levels = loadSkillLevels();\n const data = levels[skillName];\n if (!data) return { level: 1, label: \"Learning\", activations: 0 };\n const { level, label } = computeLevel(data.activations);\n return { level, label, activations: data.activations };\n}\n\n// --- Auto-Triggered Skills ---\n\n/**\n * Match user input against installed skill triggers.\n * Returns skill names that should be activated for this turn.\n */\nexport function matchSkills(\n userInput: string,\n installedSkillNames: string[],\n runtimeTriggers: Map<string, string[]> = new Map(),\n): string[] {\n const input = userInput.toLowerCase();\n const matched = new Set<string>();\n\n // Hardcoded triggers — only fire for installed skills\n for (const skillName of installedSkillNames) {\n const triggers = SKILL_TRIGGERS[skillName];\n if (!triggers) continue;\n\n for (const trigger of triggers) {\n if (input.includes(trigger)) {\n matched.add(skillName);\n break;\n }\n }\n }\n\n // Runtime triggers — fire regardless of installedSkillNames since\n // crystallized skills may not appear in the aman-mcp skill_list\n for (const [skillName, triggers] of runtimeTriggers) {\n for (const trigger of triggers) {\n if (input.includes(trigger)) {\n matched.add(skillName);\n break;\n }\n }\n }\n\n return Array.from(matched);\n}\n\n// --- Semantic Trigger Matching (TF-IDF cosine similarity) ---\n\nconst SEMANTIC_STOPWORDS = new Set([\n \"the\", \"a\", \"an\", \"is\", \"are\", \"was\", \"were\", \"be\", \"been\", \"being\",\n \"have\", \"has\", \"had\", \"do\", \"does\", \"did\", \"will\", \"would\", \"shall\",\n \"should\", \"may\", \"might\", \"must\", \"can\", \"could\", \"to\", \"of\", \"in\",\n \"for\", \"on\", \"with\", \"at\", \"by\", \"from\", \"as\", \"into\", \"through\",\n \"during\", \"before\", \"after\", \"above\", \"below\", \"between\", \"and\",\n \"but\", \"or\", \"nor\", \"not\", \"so\", \"yet\", \"both\", \"either\", \"neither\",\n \"each\", \"every\", \"all\", \"any\", \"few\", \"more\", \"most\", \"other\",\n \"some\", \"such\", \"no\", \"only\", \"own\", \"same\", \"than\", \"too\", \"very\",\n \"just\", \"because\", \"if\", \"when\", \"while\", \"how\", \"what\", \"which\",\n \"who\", \"whom\", \"this\", \"that\", \"these\", \"those\", \"i\", \"me\", \"my\",\n \"we\", \"us\", \"our\", \"you\", \"your\", \"he\", \"him\", \"his\", \"she\", \"her\",\n \"it\", \"its\", \"they\", \"them\", \"their\",\n]);\n\n/**\n * Tokenize text into lowercased words, filtering stopwords and short tokens.\n */\nexport function tokenize(text: string): string[] {\n return text\n .toLowerCase()\n .replace(/[^a-z0-9\\s-]/g, \" \")\n .split(/\\s+/)\n .filter((w) => w.length > 2 && !SEMANTIC_STOPWORDS.has(w));\n}\n\n/**\n * Build a term frequency map for tokens.\n */\nfunction termFrequency(tokens: string[]): Map<string, number> {\n const tf = new Map<string, number>();\n for (const t of tokens) {\n tf.set(t, (tf.get(t) || 0) + 1);\n }\n // Normalize by document length\n for (const [k, v] of tf) {\n tf.set(k, v / tokens.length);\n }\n return tf;\n}\n\n/**\n * Compute cosine similarity between two term frequency maps.\n */\nfunction cosineSimilarity(a: Map<string, number>, b: Map<string, number>): number {\n let dot = 0;\n let normA = 0;\n let normB = 0;\n\n for (const [k, v] of a) {\n normA += v * v;\n const bv = b.get(k);\n if (bv !== undefined) dot += v * bv;\n }\n for (const [, v] of b) {\n normB += v * v;\n }\n\n if (normA === 0 || normB === 0) return 0;\n return dot / (Math.sqrt(normA) * Math.sqrt(normB));\n}\n\n/**\n * Check if user input semantically matches a set of trigger keywords.\n * Uses TF-IDF-like bag-of-words cosine similarity.\n * @returns similarity score (0-1)\n */\nexport function semanticSimilarity(userInput: string, triggers: string[]): number {\n const inputTokens = tokenize(userInput);\n if (inputTokens.length === 0) return 0;\n\n // Build trigger \"document\" from all trigger keywords\n const triggerTokens = triggers.flatMap((t) => tokenize(t));\n if (triggerTokens.length === 0) return 0;\n\n const inputTf = termFrequency(inputTokens);\n const triggerTf = termFrequency(triggerTokens);\n\n return cosineSimilarity(inputTf, triggerTf);\n}\n\nconst SEMANTIC_THRESHOLD = 0.15;\n\n/**\n * Enhanced matchSkills with semantic similarity fallback.\n */\nexport function matchSkillsSemantic(\n userInput: string,\n installedSkillNames: string[],\n runtimeTriggers: Map<string, string[]> = new Map(),\n): string[] {\n // First, get exact keyword matches\n const exact = matchSkills(userInput, installedSkillNames, runtimeTriggers);\n const matched = new Set(exact);\n\n // Then, check semantic similarity for skills not already matched\n for (const skillName of installedSkillNames) {\n if (matched.has(skillName)) continue;\n const triggers = SKILL_TRIGGERS[skillName];\n if (!triggers) continue;\n\n const sim = semanticSimilarity(userInput, triggers);\n if (sim >= SEMANTIC_THRESHOLD) {\n matched.add(skillName);\n }\n }\n\n for (const [skillName, triggers] of runtimeTriggers) {\n if (matched.has(skillName)) continue;\n const sim = semanticSimilarity(userInput, triggers);\n if (sim >= SEMANTIC_THRESHOLD) {\n matched.add(skillName);\n }\n }\n\n return Array.from(matched);\n}\n\n/**\n * Format skill context block for injection into system prompt.\n * Adapts detail level based on skill level.\n */\nexport function formatSkillContext(\n skillName: string,\n skillContent: string,\n level: { level: number; label: string },\n): string {\n let depthHint: string;\n if (level.level >= 4) {\n depthHint = \"User is advanced — skip basics, focus on edge cases and proactive optimization.\";\n } else if (level.level >= 3) {\n depthHint = \"User is proficient — brief reminders of principles, focus on the specific task.\";\n } else if (level.level >= 2) {\n depthHint = \"User is familiar — explain reasoning briefly, show patterns.\";\n } else {\n depthHint = \"User is learning — explain concepts clearly, show examples, be patient.\";\n }\n\n return `<active-skill name=\"${skillName}\" level=\"${level.level}\" label=\"${level.label}\">\n${depthHint}\n\n${skillContent}\n</active-skill>`;\n}\n\n/**\n * Auto-trigger skills based on user input.\n * Reads installed skills, matches keywords, injects context.\n * Returns formatted skill blocks to append to system prompt.\n */\nexport async function autoTriggerSkills(\n userInput: string,\n mcpManager: McpManager,\n): Promise<string> {\n try {\n // Get installed skills\n const result = await mcpManager.callTool(\"skill_list\", {});\n const skills = JSON.parse(result) as Array<{ name: string; description: string; installed: boolean }>;\n const installed = skills.filter((s) => s.installed).map((s) => s.name);\n\n // Load runtime (crystallized) triggers from ~/.askill/skills.md\n const skillsMdPath = path.join(os.homedir(), \".askill\", \"skills.md\");\n const runtimeTriggers = await loadRuntimeTriggers(skillsMdPath);\n\n if (installed.length === 0 && runtimeTriggers.size === 0) return \"\";\n\n // Match user input against skill triggers (keyword + semantic)\n const matched = matchSkillsSemantic(userInput, installed, runtimeTriggers);\n if (matched.length === 0) return \"\";\n\n // Load skill content and build context blocks\n const blocks: string[] = [];\n for (const skillName of matched.slice(0, 2)) { // max 2 skills per turn\n // Record activation and get level\n const level = recordActivation(skillName);\n\n // Read skill content from skills.md\n const skillsContent = await mcpManager.callTool(\"skill_search\", { query: skillName });\n const skillEntries = JSON.parse(skillsContent) as Array<{ name: string; description: string }>;\n const entry = skillEntries.find((s) => s.name.toLowerCase() === skillName.toLowerCase());\n\n if (entry) {\n blocks.push(formatSkillContext(skillName, entry.description, level));\n }\n\n log.debug(\"skill-engine\", `Auto-triggered: ${skillName} (Lv.${level.level} ${level.label})`);\n }\n\n return blocks.join(\"\\n\\n\");\n } catch (err) {\n log.debug(\"skill-engine\", \"autoTriggerSkills failed\", err);\n return \"\";\n }\n}\n\n// --- Self-Improving Skills ---\n\n/**\n * Enrich a skill with a user-specific pattern learned from conversation.\n * Called by memory-extractor when a \"pattern\" type extraction matches a skill domain.\n */\nexport function enrichSkill(skillName: string, pattern: string): void {\n const levels = loadSkillLevels();\n if (!levels[skillName]) {\n levels[skillName] = { name: skillName, activations: 0, lastUsed: \"\", userPatterns: [] };\n }\n\n // Deduplicate patterns\n const existing = levels[skillName].userPatterns;\n if (existing.length >= 20) return; // cap at 20 patterns per skill\n if (existing.some((p) => p.toLowerCase() === pattern.toLowerCase())) return;\n\n levels[skillName].userPatterns.push(pattern);\n saveSkillLevels(levels);\n log.debug(\"skill-engine\", `Enriched ${skillName} with pattern: ${pattern.slice(0, 80)}`);\n}\n\n/**\n * Get user-specific patterns for a skill (for injection into skill context).\n */\nexport function getSkillPatterns(skillName: string): string[] {\n const levels = loadSkillLevels();\n return levels[skillName]?.userPatterns || [];\n}\n\n/**\n * Match a memory extraction pattern to a skill domain.\n * Returns the skill name if the pattern is relevant, null otherwise.\n */\nexport function matchPatternToSkill(patternContent: string, tags: string[]): string | null {\n const combined = (patternContent + \" \" + tags.join(\" \")).toLowerCase();\n\n for (const [skillName, triggers] of Object.entries(SKILL_TRIGGERS)) {\n for (const trigger of triggers) {\n if (combined.includes(trigger)) {\n return skillName;\n }\n }\n }\n\n return null;\n}\n\n// --- Knowledge Library ---\n\nexport interface KnowledgeItem {\n name: string;\n category: string;\n description: string;\n content: string;\n}\n\nexport const KNOWLEDGE_LIBRARY: KnowledgeItem[] = [\n {\n name: \"security-headers\",\n category: \"security\",\n description: \"Essential HTTP security headers for web applications\",\n content: `Essential Security Headers:\n- Content-Security-Policy: default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'\n- X-Content-Type-Options: nosniff\n- X-Frame-Options: DENY\n- Strict-Transport-Security: max-age=31536000; includeSubDomains; preload\n- X-XSS-Protection: 0 (CSP replaces this)\n- Referrer-Policy: strict-origin-when-cross-origin\n- Permissions-Policy: camera=(), microphone=(), geolocation=()`,\n },\n {\n name: \"docker-node\",\n category: \"deployment\",\n description: \"Production Node.js Dockerfile template\",\n content: `FROM node:22-alpine AS builder\nWORKDIR /app\nCOPY package*.json ./\nRUN npm ci --production=false\nCOPY . .\nRUN npm run build\n\nFROM node:22-alpine\nWORKDIR /app\nRUN addgroup -g 1001 -S nodejs && adduser -S appuser -u 1001\nCOPY --from=builder /app/dist ./dist\nCOPY --from=builder /app/node_modules ./node_modules\nCOPY --from=builder /app/package.json ./\nUSER appuser\nEXPOSE 3000\nCMD [\"node\", \"dist/index.js\"]`,\n },\n {\n name: \"github-actions-node\",\n category: \"ci\",\n description: \"CI/CD pipeline for Node.js with GitHub Actions\",\n content: `name: CI\non: [push, pull_request]\njobs:\n build:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v5\n - uses: actions/setup-node@v5\n with: { node-version: 22 }\n - run: npm ci\n - run: npm test\n - run: npm run build`,\n },\n {\n name: \"env-config\",\n category: \"configuration\",\n description: \"Environment variable configuration pattern with validation\",\n content: `import { z } from \"zod\";\n\nconst envSchema = z.object({\n NODE_ENV: z.enum([\"development\", \"production\", \"test\"]).default(\"development\"),\n PORT: z.coerce.number().default(3000),\n DATABASE_URL: z.string().url(),\n API_KEY: z.string().min(1),\n});\n\nexport const env = envSchema.parse(process.env);`,\n },\n {\n name: \"error-handling\",\n category: \"patterns\",\n description: \"TypeScript error handling patterns with Result type\",\n content: `type Result<T, E = Error> = { ok: true; value: T } | { ok: false; error: E };\n\nfunction ok<T>(value: T): Result<T, never> { return { ok: true, value }; }\nfunction err<E>(error: E): Result<never, E> { return { ok: false, error }; }\n\n// Usage:\nasync function fetchUser(id: string): Promise<Result<User>> {\n try {\n const user = await db.users.findUnique({ where: { id } });\n if (!user) return err(new Error(\"User not found\"));\n return ok(user);\n } catch (e) {\n return err(e instanceof Error ? e : new Error(String(e)));\n }\n}`,\n },\n {\n name: \"rate-limiter\",\n category: \"security\",\n description: \"Token bucket rate limiter implementation\",\n content: `class RateLimiter {\n private tokens: Map<string, { count: number; resetAt: number }> = new Map();\n\n constructor(private maxRequests: number, private windowMs: number) {}\n\n allow(key: string): boolean {\n const now = Date.now();\n const entry = this.tokens.get(key);\n if (!entry || now > entry.resetAt) {\n this.tokens.set(key, { count: 1, resetAt: now + this.windowMs });\n return true;\n }\n if (entry.count >= this.maxRequests) return false;\n entry.count++;\n return true;\n }\n}`,\n },\n {\n name: \"prisma-setup\",\n category: \"database\",\n description: \"Prisma ORM setup with connection pooling\",\n content: `import { PrismaClient } from \"@prisma/client\";\n\nconst globalForPrisma = globalThis as unknown as { prisma: PrismaClient };\nexport const prisma = globalForPrisma.prisma ?? new PrismaClient({\n log: process.env.NODE_ENV === \"development\" ? [\"query\", \"error\", \"warn\"] : [\"error\"],\n});\nif (process.env.NODE_ENV !== \"production\") globalForPrisma.prisma = prisma;`,\n },\n {\n name: \"zod-validation\",\n category: \"validation\",\n description: \"Zod schema patterns for API input validation\",\n content: `import { z } from \"zod\";\n\nconst CreateUserSchema = z.object({\n email: z.string().email(),\n name: z.string().min(1).max(100),\n age: z.number().int().min(13).max(150).optional(),\n role: z.enum([\"user\", \"admin\"]).default(\"user\"),\n tags: z.array(z.string()).max(10).default([]),\n});\n\ntype CreateUser = z.infer<typeof CreateUserSchema>;\n\n// Express middleware:\nfunction validate<T>(schema: z.ZodSchema<T>) {\n return (req, res, next) => {\n const result = schema.safeParse(req.body);\n if (!result.success) return res.status(400).json({ errors: result.error.flatten() });\n req.body = result.data;\n next();\n };\n}`,\n },\n {\n name: \"testing-patterns\",\n category: \"testing\",\n description: \"Test organization and assertion patterns\",\n content: `// Arrange-Act-Assert pattern\ndescribe(\"UserService\", () => {\n it(\"creates user with valid email\", async () => {\n // Arrange\n const input = { email: \"test@example.com\", name: \"Test\" };\n\n // Act\n const user = await userService.create(input);\n\n // Assert\n expect(user.id).toBeDefined();\n expect(user.email).toBe(input.email);\n });\n\n it(\"rejects duplicate email\", async () => {\n await userService.create({ email: \"dup@test.com\", name: \"First\" });\n await expect(userService.create({ email: \"dup@test.com\", name: \"Second\" }))\n .rejects.toThrow(\"already exists\");\n });\n});`,\n },\n {\n name: \"git-hooks\",\n category: \"git\",\n description: \"Pre-commit and commit-msg hooks with lint-staged\",\n content: `// package.json\n{\n \"lint-staged\": {\n \"*.{ts,tsx}\": [\"eslint --fix\", \"prettier --write\"],\n \"*.{json,md}\": [\"prettier --write\"]\n }\n}\n\n// .husky/pre-commit\nnpx lint-staged\n\n// .husky/commit-msg\nnpx commitlint --edit $1\n\n// commitlint.config.js\nmodule.exports = { extends: [\"@commitlint/config-conventional\"] };`,\n },\n];\n\n/**\n * Search knowledge library by query.\n */\nexport function searchKnowledge(query: string): KnowledgeItem[] {\n const q = query.toLowerCase();\n return KNOWLEDGE_LIBRARY.filter(\n (item) =>\n item.name.includes(q) ||\n item.category.includes(q) ||\n item.description.toLowerCase().includes(q),\n );\n}\n\n/**\n * Auto-suggest knowledge items based on conversation context.\n * Returns formatted knowledge block if relevant item found.\n */\nexport function matchKnowledge(userInput: string): KnowledgeItem | null {\n const input = userInput.toLowerCase();\n\n // Direct keyword matches\n const keywordMap: Record<string, string> = {\n \"security header\": \"security-headers\",\n \"csp\": \"security-headers\",\n \"content-security\": \"security-headers\",\n \"dockerfile\": \"docker-node\",\n \"docker\": \"docker-node\",\n \"github action\": \"github-actions-node\",\n \"ci/cd\": \"github-actions-node\",\n \"ci pipeline\": \"github-actions-node\",\n \"env config\": \"env-config\",\n \"environment variable\": \"env-config\",\n \"error handling\": \"error-handling\",\n \"result type\": \"error-handling\",\n \"rate limit\": \"rate-limiter\",\n \"throttle\": \"rate-limiter\",\n \"prisma\": \"prisma-setup\",\n \"zod\": \"zod-validation\",\n \"validation\": \"zod-validation\",\n \"test pattern\": \"testing-patterns\",\n \"arrange act assert\": \"testing-patterns\",\n \"git hook\": \"git-hooks\",\n \"pre-commit\": \"git-hooks\",\n \"lint-staged\": \"git-hooks\",\n \"husky\": \"git-hooks\",\n };\n\n for (const [keyword, itemName] of Object.entries(keywordMap)) {\n if (input.includes(keyword)) {\n return KNOWLEDGE_LIBRARY.find((i) => i.name === itemName) || null;\n }\n }\n\n return null;\n}\n","interface ErrorMapping {\n pattern: RegExp;\n message: string;\n}\n\nconst ERROR_MAPPINGS: ErrorMapping[] = [\n { pattern: /rate.?limit|429/i, message: \"Rate limited. I'll retry automatically.\" },\n { pattern: /401|unauthorized/i, message: \"API key invalid. Run /reset config to fix.\" },\n { pattern: /403|forbidden/i, message: \"API key doesn't have access to this model. Try a different model with --model.\" },\n { pattern: /fetch failed|network/i, message: \"Network error. Check your internet connection.\" },\n { pattern: /ECONNREFUSED/i, message: \"Can't reach the API. Are you behind a proxy or firewall?\" },\n { pattern: /context.?length/i, message: \"Conversation too long. Use /clear to start fresh or I'll auto-trim.\" },\n { pattern: /overloaded/i, message: \"API is overloaded. Retrying in a moment...\" },\n { pattern: /ETIMEDOUT/i, message: \"Request timed out. Retrying...\" },\n];\n\nexport function humanizeError(message: string): string {\n for (const mapping of ERROR_MAPPINGS) {\n if (mapping.pattern.test(message)) {\n return mapping.message;\n }\n }\n return message;\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport os from \"node:os\";\n\nexport interface HintState {\n turnCount: number;\n shownHints: Set<string>;\n hintShownThisSession: boolean;\n}\n\ninterface HintContext {\n hasWorkflows: boolean;\n memoryCount: number;\n}\n\ninterface HintDef {\n id: string;\n minTurn: number;\n condition: (ctx: HintContext) => boolean;\n text: string;\n}\n\nconst HINTS: HintDef[] = [\n {\n id: \"eval\",\n minTurn: 15,\n condition: () => true,\n text: \"Tip: See how our relationship has evolved with /eval\",\n },\n {\n id: \"memory-search\",\n minTurn: 3,\n condition: (ctx) => ctx.memoryCount >= 10,\n text: \"Tip: Search everything I remember with /memory search <query>\",\n },\n {\n id: \"workflows\",\n minTurn: 5,\n condition: (ctx) => !ctx.hasWorkflows,\n text: \"Tip: Teach me multi-step processes with /workflows add\",\n },\n {\n id: \"rules\",\n minTurn: 8,\n condition: () => true,\n text: \"Tip: Set guardrails for what I should/shouldn't do with /rules\",\n },\n];\n\nexport function getHint(state: HintState, ctx: HintContext): string | null {\n if (state.hintShownThisSession) return null;\n\n for (const hint of HINTS) {\n if (state.turnCount >= hint.minTurn && !state.shownHints.has(hint.id) && hint.condition(ctx)) {\n state.shownHints.add(hint.id);\n state.hintShownThisSession = true;\n return hint.text;\n }\n }\n\n return null;\n}\n\nconst HINTS_FILE = path.join(os.homedir(), \".aman-agent\", \"hints-seen.json\");\n\nexport function loadShownHints(): Set<string> {\n try {\n if (fs.existsSync(HINTS_FILE)) {\n const data = JSON.parse(fs.readFileSync(HINTS_FILE, \"utf-8\"));\n return new Set(Array.isArray(data) ? data : []);\n }\n } catch { /* ignore */ }\n return new Set();\n}\n\nexport function saveShownHints(shown: Set<string>): void {\n try {\n const dir = path.dirname(HINTS_FILE);\n fs.mkdirSync(dir, { recursive: true });\n fs.writeFileSync(HINTS_FILE, JSON.stringify([...shown]), \"utf-8\");\n } catch { /* non-critical */ }\n}\n","export type PresetName = \"coding\" | \"creative\" | \"assistant\" | \"learning\" | \"minimal\";\n\ninterface PresetRule {\n category: string;\n rule: string;\n}\n\ninterface PresetWorkflow {\n name: string;\n description: string;\n steps: string[];\n}\n\ninterface Preset {\n identity: { personality: string; style: string };\n rules: PresetRule[];\n workflows: PresetWorkflow[];\n}\n\nexport const PRESETS: Record<PresetName, Preset> = {\n coding: {\n identity: {\n personality: \"Direct, technical, concise. Shows code over explanation.\",\n style: \"Use short answers. Lead with the solution, explain after.\",\n },\n rules: [\n { category: \"response\", rule: \"Always show code examples, not just descriptions\" },\n { category: \"safety\", rule: \"Never execute destructive commands without confirmation\" },\n { category: \"quality\", rule: \"Follow project conventions over personal preference\" },\n ],\n workflows: [\n { name: \"debug\", description: \"Systematic debugging process\", steps: [\"Reproduce the issue\", \"Identify root cause\", \"Propose fix\", \"Verify fix\"] },\n ],\n },\n creative: {\n identity: {\n personality: \"Warm, imaginative, encouraging. Explores multiple angles.\",\n style: \"Use metaphors and vivid language. Ask 'what if' questions.\",\n },\n rules: [\n { category: \"response\", rule: \"Always offer 2-3 alternative approaches\" },\n { category: \"tone\", rule: \"Encourage experimentation, never dismiss ideas\" },\n ],\n workflows: [\n { name: \"brainstorm\", description: \"Creative brainstorming process\", steps: [\"Explore the problem space\", \"Generate 5+ ideas\", \"Evaluate trade-offs\", \"Refine top 2\"] },\n ],\n },\n assistant: {\n identity: {\n personality: \"Organized, proactive, action-oriented.\",\n style: \"Use bullet points and checklists. Summarize key takeaways.\",\n },\n rules: [\n { category: \"response\", rule: \"End responses with clear next steps when applicable\" },\n { category: \"memory\", rule: \"Always track deadlines and commitments mentioned\" },\n ],\n workflows: [\n { name: \"plan\", description: \"Task planning process\", steps: [\"Clarify the goal\", \"Break into tasks\", \"Prioritize\", \"Set deadlines\"] },\n ],\n },\n learning: {\n identity: {\n personality: \"Patient, curious, Socratic. Builds understanding layer by layer.\",\n style: \"Use analogies. Check understanding before moving on.\",\n },\n rules: [\n { category: \"response\", rule: \"Explain concepts before showing solutions\" },\n { category: \"teaching\", rule: \"Ask a follow-up question to reinforce learning\" },\n ],\n workflows: [],\n },\n minimal: {\n identity: {\n personality: \"Helpful and adaptive. Matches the user's tone and needs.\",\n style: \"Clear and concise. Prioritizes usefulness over verbosity.\",\n },\n rules: [],\n workflows: [],\n },\n};\n\ninterface PresetResult {\n coreMd: string;\n rulesMd: string | null;\n flowMd: string | null;\n}\n\nexport function applyPreset(name: PresetName, companionName: string): PresetResult {\n const preset = PRESETS[name];\n\n const coreMd = [\n `# ${companionName}`,\n \"\",\n \"## Personality\",\n preset.identity.personality,\n \"\",\n \"## Style\",\n preset.identity.style,\n \"\",\n \"## Session\",\n \"_New companion — no prior sessions._\",\n ].join(\"\\n\");\n\n let rulesMd: string | null = null;\n if (preset.rules.length > 0) {\n const grouped = new Map<string, string[]>();\n for (const r of preset.rules) {\n if (!grouped.has(r.category)) grouped.set(r.category, []);\n grouped.get(r.category)!.push(r.rule);\n }\n const sections = [...grouped.entries()]\n .map(([cat, rules]) => `## ${cat}\\n${rules.map((r) => `- ${r}`).join(\"\\n\")}`)\n .join(\"\\n\\n\");\n rulesMd = `# Guardrails\\n\\n${sections}`;\n }\n\n let flowMd: string | null = null;\n if (preset.workflows.length > 0) {\n const wfSections = preset.workflows\n .map((wf) => {\n const steps = wf.steps.map((s, i) => `${i + 1}. ${s}`).join(\"\\n\");\n return `## ${wf.name}\\n${wf.description}\\n\\n${steps}`;\n })\n .join(\"\\n\\n\");\n flowMd = `# Workflows\\n\\n${wfSections}`;\n }\n\n return { coreMd, rulesMd, flowMd };\n}\n","import pc from \"picocolors\";\nimport * as p from \"@clack/prompts\";\nimport { startAgentServer, type RunningAgentServer } from \"./index.js\";\nimport { McpManager } from \"../mcp/client.js\";\nimport { pickLLMClient } from \"../llm/index.js\";\nimport { loadConfig, type AgentConfig, type HooksConfig } from \"../config.js\";\n\nexport interface ServeOptions {\n name: string;\n profile: string;\n}\n\n/**\n * Entry point for `aman-agent serve --name X --profile Y`.\n *\n * Process lifecycle:\n * 1. Load config + pick an LLM client (Task 0's factory honors\n * AMAN_AGENT_FAKE_LLM=1 and short-circuits to the fake client).\n * 2. Connect aman-mcp + any custom MCP servers from config. When\n * AMAN_AGENT_FAKE_LLM=1 we skip MCP entirely so Task 13's integration\n * test stays hermetic (no `npx -y @aman_asmuei/aman-mcp` fetch in CI).\n * 3. Start the A2A server (Task 7's `startAgentServer`).\n * 4. Install SIGINT/SIGTERM handlers, idempotent via `shuttingDown` guard,\n * which stop the server, disconnect MCP, then exit 0.\n * 5. Block forever on an unresolved promise so the event loop stays alive\n * until a signal fires.\n *\n * NOTE: `running.stop()` does not drain in-flight `agent.delegate` calls —\n * mid-flight delegations are cut off at shutdown. Acceptable for MVP.\n */\nexport async function runServe(opts: ServeOptions): Promise<void> {\n const config: AgentConfig | null = loadConfig();\n if (!config) {\n throw new Error(\n \"aman-agent is not configured. Run `aman-agent` once interactively to set up your provider before starting serve mode.\",\n );\n }\n const model = config.model ?? \"claude-sonnet-4-6\";\n\n p.intro(\n pc.bold(\"aman-agent serve\") +\n pc.dim(` — name=${opts.name} profile=${opts.profile}`),\n );\n\n // 1. LLM client (honors AMAN_AGENT_FAKE_LLM via the factory from Task 0)\n const client = pickLLMClient(config, model);\n\n // 2. MCP manager — matches the interactive baseline at src/index.ts:463–465:\n // ONLY aman-mcp is auto-connected (NOT amem). Custom mcpServers entries\n // are connected too, skipping the reserved names \"aman\" and \"amem\".\n // When AMAN_AGENT_FAKE_LLM=1 we skip MCP entirely so the A2A integration\n // test (Task 13) stays hermetic.\n const mcpManager = new McpManager();\n if (process.env.AMAN_AGENT_FAKE_LLM !== \"1\") {\n try {\n await mcpManager.connect(\"aman\", \"npx\", [\"-y\", \"@aman_asmuei/aman-mcp\"]);\n } catch (err) {\n p.log.warning(\n `aman-mcp unavailable — continuing without tools: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n if (config.mcpServers) {\n for (const [name, sc] of Object.entries(config.mcpServers)) {\n if (name === \"aman\" || name === \"amem\") continue;\n try {\n await mcpManager.connect(name, sc.command, sc.args, sc.env);\n } catch {\n /* connect() logs internally — warnings only, not fatal */\n }\n }\n }\n }\n\n // 3. Start the A2A server (wired by Task 7)\n const running: RunningAgentServer = await startAgentServer({\n name: opts.name,\n profile: opts.profile,\n client,\n mcpManager,\n hooksConfig: config.hooks as HooksConfig | undefined,\n });\n\n p.log.success(`registered as @${opts.name}`);\n p.log.info(\n `port ${running.entry.port} (127.0.0.1) — token is in ~/.aman-agent/registry.json (mode 0600)`,\n );\n\n // 4. Signal handlers. Guard against double-fire so SIGINT+SIGTERM in quick\n // succession doesn't call stop() twice — transport.close is not\n // guaranteed safe to call twice and an MCP SDK close on a torn-down\n // transport throws.\n let shuttingDown = false;\n const shutdown = async (signal: NodeJS.Signals) => {\n if (shuttingDown) return;\n shuttingDown = true;\n p.log.warning(`received ${signal}, unregistering @${opts.name}...`);\n try {\n await running.stop();\n } catch (err) {\n p.log.error(\n `stop failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n try {\n await mcpManager.disconnect();\n } catch {\n /* best effort — never block exit on MCP teardown */\n }\n p.outro(\"goodbye\");\n process.exit(0);\n };\n process.on(\"SIGINT\", shutdown);\n process.on(\"SIGTERM\", shutdown);\n\n // 5. Keep the event loop alive indefinitely — signal handlers call\n // process.exit(), so this promise never needs to resolve.\n await new Promise<never>(() => {\n /* never resolves */\n });\n}\n","import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport { createTransport, type ServerTransport } from \"./transport.js\";\nimport { registerAgent, unregisterAgent, type AgentEntry } from \"./registry.js\";\nimport { Inbox } from \"./inbox.js\";\nimport { infoHandler } from \"./tools/info.js\";\nimport { sendHandler } from \"./tools/send.js\";\nimport { delegateToolHandler, type DelegateContext } from \"./tools/delegate.js\";\nimport type { LLMClient } from \"../llm/types.js\";\nimport type { McpManager } from \"../mcp/client.js\";\nimport type { HooksConfig } from \"../config.js\";\nimport pkg from \"../../package.json\" with { type: \"json\" };\n\nexport interface StartAgentServerOptions {\n name: string;\n profile: string;\n client: LLMClient;\n mcpManager: McpManager;\n hooksConfig?: HooksConfig;\n}\n\nexport interface RunningAgentServer {\n entry: AgentEntry;\n inbox: Inbox;\n stop: () => Promise<void>;\n}\n\n/**\n * Assemble an `McpServer` exposing `agent.info`, `agent.delegate`, and\n * `agent.send`, bind it to a localhost HTTP transport with a bearer token,\n * and publish the resulting port/token to the shared registry for peers to\n * discover.\n *\n * Ordering is deliberate:\n *\n * 1. Transport bound and MCP server connected first — if anything in that\n * chain fails we throw before touching the registry, so there's no stale\n * entry to clean up.\n * 2. `registerAgent` runs only after a successful `mcp.connect`, meaning a\n * registry entry always points at a live, listening server.\n * 3. `stop()` unregisters BEFORE tearing down the transport, so remote\n * callers never see a registered entry pointing at a server that has\n * already begun shutting down.\n */\nexport async function startAgentServer(\n opts: StartAgentServerOptions,\n): Promise<RunningAgentServer> {\n const transport: ServerTransport = await createTransport();\n const inbox = new Inbox();\n const startedAt = Date.now();\n\n const delegateCtx: DelegateContext = {\n profile: opts.profile,\n client: opts.client,\n mcpManager: opts.mcpManager,\n hooksConfig: opts.hooksConfig,\n };\n\n const mcp = new McpServer({\n name: `aman-agent:${opts.name}`,\n version: pkg.version,\n });\n\n mcp.registerTool(\n \"agent.info\",\n {\n description: \"Return this agent's identity, profile, PID, and inbox depth.\",\n inputSchema: {},\n },\n async () => {\n const result = infoHandler({\n name: opts.name,\n profile: opts.profile,\n startedAt,\n inbox,\n });\n return { content: [{ type: \"text\", text: JSON.stringify(result) }] };\n },\n );\n\n mcp.registerTool(\n \"agent.delegate\",\n {\n description:\n \"Delegate a task to this agent. Returns the agent's final response text.\",\n inputSchema: {\n task: z.string().describe(\"The task to run against this agent's profile\"),\n context: z.string().optional().describe(\"Optional extra context\"),\n },\n },\n async (input) => {\n const result = await delegateToolHandler(delegateCtx, input);\n return { content: [{ type: \"text\", text: JSON.stringify(result) }] };\n },\n );\n\n mcp.registerTool(\n \"agent.send\",\n {\n description:\n \"Deliver a one-way message into this agent's inbox. Drained at next user turn.\",\n inputSchema: {\n from: z.string().optional(),\n topic: z.string().optional(),\n body: z.string(),\n },\n },\n async (input) => {\n const result = sendHandler(inbox, input);\n return { content: [{ type: \"text\", text: JSON.stringify(result) }] };\n },\n );\n\n try {\n await mcp.connect(transport.mcpTransport);\n } catch (err) {\n // Connect failed — tear down the transport we already bound so we don't\n // leak a listening port, then rethrow.\n await transport.close();\n throw err;\n }\n\n const entry: AgentEntry = {\n name: opts.name,\n profile: opts.profile,\n pid: process.pid,\n port: transport.port,\n token: transport.token,\n started_at: startedAt,\n version: pkg.version,\n };\n await registerAgent(entry);\n\n return {\n entry,\n inbox,\n stop: async () => {\n try {\n await unregisterAgent(opts.name);\n } catch {\n /* best effort — don't let a registry hiccup block teardown */\n }\n try {\n await mcp.close();\n } catch {\n /* best effort — don't let a flaky SDK close leak the transport */\n }\n await transport.close();\n },\n };\n}\n","import http from \"node:http\";\nimport crypto from \"node:crypto\";\nimport { StreamableHTTPServerTransport } from \"@modelcontextprotocol/sdk/server/streamableHttp.js\";\n\n/**\n * Handle for a running localhost MCP transport.\n *\n * Downstream code (Task 7 `startAgentServer`) hands `mcpTransport` to\n * `McpServer.connect(...)`. Task 12 (`/agents ping`) uses `port` + `token`\n * to hit the `/health` endpoint. Task 10 (`delegateRemote`) uses them to\n * dial `/mcp` via the MCP client transport.\n */\nexport interface ServerTransport {\n port: number;\n token: string;\n httpServer: http.Server;\n mcpTransport: StreamableHTTPServerTransport;\n close: () => Promise<void>;\n}\n\n/**\n * Check a request's `Authorization: Bearer <token>` header against the\n * expected token. Uses a constant-time comparison to avoid leaking token\n * bytes via response-timing side channels.\n */\nfunction authOk(req: http.IncomingMessage, token: string): boolean {\n const header = req.headers[\"authorization\"];\n if (!header || typeof header !== \"string\") return false;\n const m = header.match(/^Bearer\\s+(.+)$/);\n if (!m) return false;\n const a = Buffer.from(m[1]);\n const b = Buffer.from(token);\n if (a.length !== b.length) return false;\n return crypto.timingSafeEqual(a, b);\n}\n\n/**\n * Bind an HTTP server to `127.0.0.1` on an ephemeral port, protected by a\n * freshly generated 32-byte hex bearer token. Routes:\n *\n * - `GET /health` -> `{ ok: true }` (200)\n * - `/mcp*` -> `StreamableHTTPServerTransport.handleRequest`\n *\n * Every request (including `/health`) requires the bearer — this is\n * intentional; there are no anonymous endpoints.\n *\n * The caller is responsible for calling `close()` when the server is no\n * longer needed; `close()` tears down the MCP transport and frees the port.\n */\nexport async function createTransport(): Promise<ServerTransport> {\n const token = crypto.randomBytes(32).toString(\"hex\");\n const mcpTransport = new StreamableHTTPServerTransport({\n sessionIdGenerator: () => crypto.randomUUID(),\n });\n\n const httpServer = http.createServer(async (req, res) => {\n if (!authOk(req, token)) {\n res.statusCode = 401;\n res.setHeader(\"WWW-Authenticate\", \"Bearer\");\n res.setHeader(\"content-type\", \"application/json\");\n res.end(JSON.stringify({ error: \"unauthorized\" }));\n return;\n }\n\n if (req.url === \"/health\") {\n res.statusCode = 200;\n res.setHeader(\"content-type\", \"application/json\");\n res.end(JSON.stringify({ ok: true }));\n return;\n }\n\n if (req.url?.startsWith(\"/mcp\")) {\n await mcpTransport.handleRequest(req, res);\n return;\n }\n\n res.statusCode = 404;\n res.end();\n });\n\n await new Promise<void>((resolve, reject) => {\n const onError = (err: Error) => reject(err);\n httpServer.once(\"error\", onError);\n httpServer.listen(0, \"127.0.0.1\", () => {\n httpServer.off(\"error\", onError);\n resolve();\n });\n });\n\n const addr = httpServer.address();\n if (!addr || typeof addr === \"string\") {\n throw new Error(\"failed to bind localhost port\");\n }\n\n return {\n port: addr.port,\n token,\n httpServer,\n mcpTransport,\n close: async () => {\n try {\n await mcpTransport.close();\n } catch {\n /* ignore — best-effort teardown */\n }\n await new Promise<void>((resolve) => httpServer.close(() => resolve()));\n },\n };\n}\n","export interface InboxMessage {\n id: string;\n from: string; // sender agent name or \"user\"\n topic?: string;\n body: string;\n received_at: number;\n}\n\nexport class Inbox {\n private queue: InboxMessage[] = [];\n private counter = 0;\n\n enqueue(msg: Omit<InboxMessage, \"id\" | \"received_at\">): InboxMessage {\n const full: InboxMessage = {\n ...msg,\n id: `inbox-${++this.counter}`,\n received_at: Date.now(),\n };\n this.queue.push(full);\n return full;\n }\n\n peek(): readonly InboxMessage[] {\n return [...this.queue];\n }\n\n drain(): InboxMessage[] {\n const out = this.queue;\n this.queue = [];\n return out;\n }\n\n get count(): number {\n return this.queue.length;\n }\n}\n","{\n \"name\": \"@aman_asmuei/aman-agent\",\n \"version\": \"0.42.0\",\n \"description\": \"Your AI companion, running locally — powered by the aman ecosystem\",\n \"type\": \"module\",\n \"engines\": {\n \"node\": \">=18.0.0\"\n },\n \"bin\": {\n \"aman-agent\": \"./bin/aman-agent.js\"\n },\n \"main\": \"./dist/index.js\",\n \"files\": [\n \"dist\",\n \"bin\"\n ],\n \"scripts\": {\n \"build\": \"tsup\",\n \"dev\": \"tsup --watch\",\n \"lint\": \"tsc --noEmit\",\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\",\n \"prepublishOnly\": \"npm run build\"\n },\n \"dependencies\": {\n \"@aman_asmuei/acore-core\": \"^0.2.0\",\n \"@aman_asmuei/aman-core\": \"^0.3.0\",\n \"@aman_asmuei/amem-core\": \"^0.6.0\",\n \"@aman_asmuei/arules-core\": \"^0.2.0\",\n \"@anthropic-ai/sdk\": \"^0.39.0\",\n \"@clack/prompts\": \"^0.9.1\",\n \"@modelcontextprotocol/sdk\": \"^1.27.1\",\n \"commander\": \"^13.1.0\",\n \"log-update\": \"^7.2.0\",\n \"marked\": \"^15.0.12\",\n \"marked-terminal\": \"^7.3.0\",\n \"openai\": \"^4.80.0\",\n \"picocolors\": \"^1.1.1\",\n \"zod\": \"^3.25.0\"\n },\n \"devDependencies\": {\n \"@types/marked-terminal\": \"^6.1.1\",\n \"@types/node\": \"^22.0.0\",\n \"tsup\": \"^8.4.0\",\n \"typescript\": \"^5.7.0\",\n \"vitest\": \"^4.1.0\"\n },\n \"keywords\": [\n \"ai\",\n \"agent\",\n \"companion\",\n \"aman\",\n \"llm\",\n \"claude\",\n \"openai\"\n ],\n \"author\": \"Aman Asmuei\",\n \"license\": \"MIT\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/amanasmuei/aman-agent.git\"\n }\n}\n","import type { Inbox } from \"../inbox.js\";\nimport pkg from \"../../../package.json\" with { type: \"json\" };\n\nexport interface InfoContext {\n name: string;\n profile: string;\n startedAt: number;\n inbox: Inbox;\n}\n\nexport interface InfoResult {\n name: string;\n profile: string;\n pid: number;\n started_at: number;\n pending_inbox: number;\n version: string;\n}\n\n/**\n * Handler for the `agent.info` MCP tool. Returns the running agent's\n * identity, profile, PID, startup timestamp, inbox depth, and version.\n *\n * Pure function — has no side effects and reads no global state beyond\n * `process.pid` and the imported `package.json` version.\n */\nexport function infoHandler(ctx: InfoContext): InfoResult {\n return {\n name: ctx.name,\n profile: ctx.profile,\n pid: process.pid,\n started_at: ctx.startedAt,\n pending_inbox: ctx.inbox.count,\n version: pkg.version,\n };\n}\n","import type { Inbox } from \"../inbox.js\";\n\nexport interface SendInput {\n from?: string;\n topic?: string;\n body: string;\n}\n\nexport interface SendResult {\n ok: boolean;\n id?: string;\n error?: string;\n}\n\nconst MAX_BODY_BYTES = 8 * 1024;\n\n/**\n * Handler for the `agent.send` MCP tool. Validates a one-way message\n * and enqueues it on the target agent's inbox. Messages sit in-memory\n * until the agent drains them at the start of its next user turn.\n *\n * Not durable — if the agent crashes before drain, the message is lost.\n */\nexport function sendHandler(inbox: Inbox, input: SendInput): SendResult {\n if (!input.body || input.body.trim() === \"\") {\n return { ok: false, error: \"empty body\" };\n }\n if (Buffer.byteLength(input.body, \"utf8\") > MAX_BODY_BYTES) {\n return { ok: false, error: \"body too large\" };\n }\n const msg = inbox.enqueue({\n from: input.from ?? \"unknown\",\n topic: input.topic,\n body: input.body,\n });\n return { ok: true, id: msg.id };\n}\n","import type { LLMClient } from \"../../llm/types.js\";\nimport type { McpManager } from \"../../mcp/client.js\";\nimport type { HooksConfig } from \"../../config.js\";\nimport { delegateTask } from \"../../delegate.js\";\n\nexport interface DelegateContext {\n profile: string;\n client: LLMClient;\n mcpManager: McpManager;\n hooksConfig?: HooksConfig;\n}\n\nexport interface DelegateInput {\n task: string;\n context?: string;\n}\n\nexport interface DelegateToolResult {\n ok: boolean;\n text?: string;\n turns?: number;\n tools_used?: string[];\n error?: string;\n}\n\nconst MAX_TASK_BYTES = 64 * 1024;\n\n/**\n * Handler for the `agent.delegate` MCP tool. Wraps the existing local\n * `delegateTask` so a remote agent can run a full delegation loop\n * (LLM + tools) through this agent's profile and return the final text.\n *\n * Task 7 registers this as the `agent.delegate` tool on the MCP server.\n */\nexport async function delegateToolHandler(\n ctx: DelegateContext,\n input: DelegateInput,\n): Promise<DelegateToolResult> {\n if (!input.task || input.task.trim() === \"\") {\n return { ok: false, error: \"empty task\" };\n }\n if (Buffer.byteLength(input.task, \"utf8\") > MAX_TASK_BYTES) {\n return { ok: false, error: \"task too large\" };\n }\n\n const composed = input.context\n ? `${input.context}\\n\\n---\\n\\n${input.task}`\n : input.task;\n\n try {\n const result = await delegateTask(\n composed,\n ctx.profile,\n ctx.client,\n ctx.mcpManager,\n { silent: true, hooksConfig: ctx.hooksConfig },\n );\n if (!result.success) {\n return { ok: false, error: result.error ?? \"delegation failed\" };\n }\n return {\n ok: true,\n text: result.response,\n turns: result.turns,\n tools_used: result.toolsUsed,\n };\n } catch (err) {\n return {\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n };\n }\n}\n"],"mappings":";;;;;;;;;;;AACO,SAAS,eAAeA,OAAsB;AACnD,SAAO,KAAK,MAAMA,MAAK,MAAM,KAAK,EAAE,OAAO,OAAO,EAAE,SAAS,GAAG;AAClE;AAkBO,SAAS,oBACd,YACA,YAAoB,KAC8D;AAClF,QAAM,WAAqB,CAAC;AAC5B,QAAM,YAAsB,CAAC;AAC7B,QAAM,QAAkB,CAAC;AACzB,MAAI,cAAc;AAGlB,QAAM,SAAS,CAAC,GAAG,UAAU,EAAE,KAAK,CAAC,GAAG,MAAM;AAC5C,UAAM,OAAO,WAAW,QAAQ,EAAE,IAAI;AACtC,UAAM,OAAO,WAAW,QAAQ,EAAE,IAAI;AACtC,YAAQ,SAAS,KAAK,KAAK,SAAS,SAAS,KAAK,KAAK;AAAA,EACzD,CAAC;AAED,aAAW,QAAQ,QAAQ;AACzB,QAAI,cAAc,KAAK,UAAU,WAAW;AAC1C,YAAM,KAAK,KAAK,OAAO;AACvB,eAAS,KAAK,KAAK,IAAI;AACvB,qBAAe,KAAK;AAAA,IACtB,OAAO;AAEL,YAAM,cAAc,KAAK,QAAQ,MAAM,GAAG,KAAK,MAAM,KAAK,QAAQ,SAAS,CAAC,CAAC;AAC7E,YAAM,aAAa,eAAe,WAAW;AAC7C,UAAI,cAAc,cAAc,WAAW;AACzC,cAAM,KAAK,cAAc,4CAA4C;AACrE,iBAAS,KAAK,KAAK,OAAO,YAAY;AACtC,uBAAe;AAAA,MACjB,OAAO;AACL,kBAAU,KAAK,KAAK,IAAI;AAAA,MAC1B;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AAAA,IACL,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D,YAAQ,IAAI,oBAAeA,KAAI;AAC/B;AAAA,EACF;AAEA,QAAMC,WAAU,MAAQ,WAAQ;AAAA,IAC9B,SAAS,oBAAoBD,KAAI;AAAA,EACnC,CAAC;AACD,MAAI,CAACC,YAAa,YAASA,QAAO,GAAG;AACnC,YAAQ,IAAI,YAAY;AACxB;AAAA,EACF;AAEA,EAAAP,KAAG,OAAOM,OAAM,EAAE,WAAW,MAAM,OAAO,KAAK,CAAC;AAChD,UAAQ,IAAI,oBAAeA,KAAI;AAC/B,UAAQ,IAAI,EAAE;AACd,UAAQ,IAAI,qEAAqE;AACjF,UAAQ,IAAI,qDAAqD;AACnE,CAAC;AAEH,QAAQ,MAAM;","names":["text","fs","path","os","fs","path","os","p","fs","path","os","Client","text","node","text","fs","path","z","init_types","init_types","execFile","promisify","GhError","execFileAsync","init_types","init_types","init_types","fs","path","os","createDatabase","recall","acoreGetIdentity","arulesListCategories","buildContext","db","AGENT_SCOPE","text","p","fs","path","p","fs","path","ctx","buildContext","p","pc","p","p","fs","path","os","home","os","path","fs","fs","path","os","fs","path","path","fs","home","path","fs","os","text","text","spawn","execFileSync","extractText","formatConversation","text","parseToolUses","text","OpenAI","OpenAI","text","fs","path","os","pc","fs","path","os","execFileSync","pc","fs","path","os","loadConfig","saveConfig","path","os","fs","path","os","fs","db","path","os","loadConfig","saveConfig","db","fs","path","fs","path","os","p","path","os","fs","fs","path","os","home","fs","path","os","p","pc","pc","p","fs","path","os","text","p","fs","path","os","fs","path","os","path","os","defaultObservationsDir","text","p","fs","fs","path","timeContext","pc","path","fs","os","delegateRemote","recall","pc","node","log","node","node","readFile","node","node","fs","path","os","fs","path","path","os","node","StreamableHTTPClientTransport","Client","fs","path","os","pc","path","os","fs","pc","fs","path","os","text","p","fs","path","os","pc","fs","pc","model","p","home","os","path","content","text","result","lines","configDir","execFileSync","members","task","profile","StreamableHTTPClientTransport","Client","text","fs","path","os","path","os","fs","text","cosineSimilarity","path","os","p","reflect","isReflectionDue","fs","path","os","p","isRetryable","pc","path","os","fs","recall","loadUserModel","computeProfile","model","hour","predictBurnout","input","result","fs","path","pc","p","z","z","pc","path","fs","pc","runDev","scanStack","EDITOR_TARGETS","execFileSync","home","confirm"]}