/** * Subcommand dispatcher. Lives in its own module so tests can drive it * without going through argv parsing or process.exit. */ import { runRecallContext, renderRecallResult } from './commands/recall-context.js'; import { runSaveSession } from './commands/save-session.js'; import { runHarvestLocal, type HarvestSource } from './commands/harvest-local.js'; import { runCognify } from './commands/cognify.js'; import { runCompileWiki } from './commands/compile-wiki.js'; import { runMaintenance } from './commands/maintenance.js'; import { runInit, renderInitResult } from './commands/init.js'; import { runStatus, renderStatusResult } from './commands/status.js'; import { runMcpStart } from './commands/mcp-start.js'; import { runMcpCall, renderMcpCallResult } from './commands/mcp-call.js'; import { runDoctor, renderDoctorResult } from './commands/doctor.js'; import { renderDanceReceive, renderDanceSend, runDanceReceive, runDanceSend, type DanceMessageSubtype, type DanceMessageType, } from './commands/dance.js'; import type { CliEnv } from './setup.js'; import type { Importance } from '@waggle/hive-mind-core'; export interface DispatchArgs { subcommand: string; values: Record; positionals: string[]; /** Optional env override for tests — bypasses openPersonalMind(). */ env?: CliEnv; } type OutputFormat = 'plain' | 'json'; function intArg(values: Record, key: string): number | undefined { const v = values[key]; if (v === undefined) return undefined; const n = Number(v); return Number.isFinite(n) ? n : undefined; } function suppliedNumberArg(values: Record, key: string): number | undefined { const value = values[key]; return value === undefined ? undefined : Number(value); } function formatOf(values: Record): OutputFormat { return values['json'] ? 'json' : 'plain'; } function json(obj: unknown): string { return JSON.stringify(obj, null, 2); } export async function dispatch(args: DispatchArgs): Promise { const { subcommand, values, positionals, env } = args; const fmt = formatOf(values); switch (subcommand) { case 'recall-context': { const query = (values['query'] as string) ?? positionals[0]; if (!query) throw new Error('recall-context requires a query (positional or --query)'); const result = await runRecallContext({ query, limit: intArg(values, 'limit'), scope: (values['scope'] as 'personal' | 'all' | undefined) ?? 'personal', profile: (values['profile'] as 'balanced' | 'recent' | 'important' | 'connected' | undefined), env, }); return fmt === 'json' ? json(result) : renderRecallResult(result, 'plain'); } case 'save-session': { const result = await runSaveSession({ file: values['file'] as string | undefined, importance: values['importance'] as Importance | undefined, sessionLabel: values['session-label'] as string | undefined, env, }); return fmt === 'json' ? json(result) : ( result.saved ? `Saved session summary as frame #${result.frameId} (${result.characters} chars)` : `Nothing saved: ${result.reason ?? 'empty input'}` ); } case 'harvest-local': { const source = values['source'] as HarvestSource | undefined; const pth = values['path'] as string | undefined; if (!source) throw new Error('harvest-local requires --source (chatgpt|claude|claude-code|gemini|universal)'); if (!pth) throw new Error('harvest-local requires --path'); const result = await runHarvestLocal({ source, path: pth, env }); return fmt === 'json' ? json(result) : ( `Harvested ${result.itemsFound} items from ${result.source} ` + `(${result.framesCreated} new, ${result.duplicatesSkipped} duplicates` + (result.suppressedSkipped ? `, ${result.suppressedSkipped} erased-suppressed` : '') + (result.errors.length ? `, ${result.errors.length} errors` : '') + `)` ); } case 'cognify': { const result = await runCognify({ since: suppliedNumberArg(values, 'since'), limit: suppliedNumberArg(values, 'limit'), env, }); return fmt === 'json' ? json(result) : ( `Scanned ${result.framesScanned} frames — ${result.entitiesCreated} new entities, ` + `${result.entitiesUpdated} updated (lastFrameId=${result.lastFrameId})` ); } case 'compile-wiki': { const result = await runCompileWiki({ mode: (values['mode'] as 'incremental' | 'full' | undefined) ?? 'incremental', concepts: values['concept'] as string[] | undefined, env, }); return fmt === 'json' ? json(result) : ( `Wiki compiled via ${result.provider} — ${result.pagesCreated} created, ` + `${result.pagesUpdated} updated, ${result.pagesUnchanged} unchanged, ` + `${result.healthIssues} health issues (${result.durationMs}ms)` ); } case 'maintenance': { const result = await runMaintenance({ compact: Boolean(values['compact']), wipeImports: Boolean(values['wipe-imports']), reconcile: Boolean(values['reconcile']), reembedAll: Boolean(values['reembed-all']), rechunkAll: Boolean(values['rechunk-all']), dedupeEntities: Boolean(values['dedupe-entities']), consolidate: Boolean(values['consolidate']), consolidateModel: typeof values['consolidate-model'] === 'string' ? values['consolidate-model'] : undefined, consolidateLimit: suppliedNumberArg(values, 'consolidate-limit'), cognify: Boolean(values['cognify']), wiki: Boolean(values['wiki']), maxTempAgeDays: intArg(values, 'max-temp-age-days'), maxDeprecatedAgeDays: intArg(values, 'max-deprecated-age-days'), workspace: typeof values['workspace'] === 'string' ? values['workspace'] : undefined, allWorkspaces: Boolean(values['all-workspaces']), env, }); if (fmt === 'json') return json(result); const lines: string[] = [`Maintenance run complete (${result.durationMs}ms)`]; if (result.compact) lines.push(` compact: temp=${result.compact.temporaryPruned} deprecated=${result.compact.deprecatedPruned} pframes=${result.compact.pframesMerged}`); if (result.wipeImports) lines.push(` wipeImports: ${result.wipeImports.framesDeleted} frames`); if (result.reconcile) lines.push(` reconcile: fts=${result.reconcile.ftsFixed} vec=${result.reconcile.vecFixed}`); if (result.reembedAll) lines.push(` reembed-all: ${result.reembedAll.framesEmbedded} frames via ${result.reembedAll.activeProvider}/${result.reembedAll.modelName} in ${(result.reembedAll.durationMs / 1000).toFixed(1)}s`); if (result.rechunkAll) lines.push(` rechunk-all: ${result.rechunkAll.framesProcessed} frames → ${result.rechunkAll.chunksCreated} chunks via ${result.rechunkAll.activeProvider}/${result.rechunkAll.modelName} in ${(result.rechunkAll.durationMs / 1000).toFixed(1)}s`); if (result.dedupeEntities) lines.push(` dedupe-entities: merged ${result.dedupeEntities.merged} dup(s) across ${result.dedupeEntities.groups} group(s)`); if (result.consolidate) lines.push(` consolidate: ${result.consolidate.chains} chain(s) → ${result.consolidate.pframes} P-frame(s) (${result.consolidate.deprecated} deprecated), ${result.consolidate.groups} group(s) → ${result.consolidate.bframes} B-frame(s)`); if (result.cognify) lines.push(` cognify: ${result.cognify.framesScanned} frames, ${result.cognify.entitiesCreated} new, ${result.cognify.entitiesUpdated} updated`); if (result.wiki) lines.push(` wiki: ${result.wiki.pagesCreated} created, ${result.wiki.pagesUpdated} updated, provider=${result.wiki.provider}`); return lines.join('\n'); } case 'init': { const result = await runInit({ env }); return fmt === 'json' ? json(result) : renderInitResult(result, 'plain'); } case 'status': { const result = await runStatus({ env }); return fmt === 'json' ? json(result) : renderStatusResult(result, 'plain'); } case 'mcp-start': { // Long-running. Exits with the child's exit code; this branch only // returns once the MCP server child has stopped. const code = await runMcpStart(); process.exit(code); // `process.exit` returns `never`, so this is unreachable — but ESLint's // no-fallthrough rule does no type analysis, so make the terminator explicit. break; } case 'mcp-call': { const tool = (values['tool'] as string | undefined) ?? positionals[0]; if (!tool) throw new Error('mcp call requires a tool name (e.g. `mcp call recall_memory`)'); let parsedArgs: Record = {}; const argsRaw = values['args'] as string | undefined; if (argsRaw) { try { parsedArgs = JSON.parse(argsRaw) as Record; } catch (err) { const msg = err instanceof Error ? err.message : String(err); throw new Error(`--args is not valid JSON: ${msg}`); } } const result = await runMcpCall({ tool, args: parsedArgs, timeoutMs: intArg(values, 'timeout-ms'), }); return fmt === 'json' ? json(result) : renderMcpCallResult(result, 'plain'); } case 'dance-send': { const message = (values['message'] as string | undefined) ?? positionals.join(' '); if (!message) throw new Error('dance send requires --message or positional text'); const result = await runDanceSend({ type: (values['type'] as DanceMessageType | undefined) ?? 'broadcast', subtype: (values['subtype'] as DanceMessageSubtype | undefined) ?? 'discovery', message, referenceId: values['reference-id'] as string | undefined, timeoutMs: intArg(values, 'timeout-ms'), }); return fmt === 'json' ? json(result) : renderDanceSend(result); } case 'dance-receive': { const result = await runDanceReceive({ since: values['since'] as string | undefined, limit: intArg(values, 'limit'), subtype: values['subtype'] as DanceMessageSubtype | undefined, timeoutMs: intArg(values, 'timeout-ms'), }); return fmt === 'json' ? json(result) : renderDanceReceive(result); } case 'doctor': { // Wave 1 cleanup — self-diagnostic smoke test independent of upstream hook. // Spawn probe (Windows .cmd shim) → save+recall frame → cache cleanup. // Lazy-opens env if not provided (matches status command pattern). const result = await runDoctor({ env }); // Doctor command sets process exit code via dispatch's caller (index.ts) // by checking result.ok in the json/plain return shape. We surface a non-zero // exit through throwing on fail to match the existing dispatch convention. if (fmt === 'json') { return json(result); } const rendered = renderDoctorResult(result); if (!result.ok) { // Throw here so index.ts's top-level catch sets exit code 1. throw new Error(rendered); } return rendered; } default: throw new Error(`Unknown subcommand: "${subcommand}". Try: init, status, doctor, recall-context, save-session, harvest-local, cognify, compile-wiki, maintenance, mcp start, mcp call , dance send, dance receive`); } }